code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
package main import ( "fmt" "math" "math/rand" "time" ) // number of points to search for closest pair const n = 1e6 // size of bounding box for points. // x and y will be random with uniform distribution in the range [0,scale). const scale = 100. // point struct type xy struct { x, y float64 // coordinates key int64 // an annotation used in the algorithm } func d(p1, p2 xy) float64 { return math.Hypot(p2.x-p1.x, p2.y-p1.y) } func main() { rand.Seed(time.Now().Unix()) points := make([]xy, n) for i := range points { points[i] = xy{rand.Float64() * scale, rand.Float64() * scale, 0} } p1, p2 := closestPair(points) fmt.Println(p1, p2) fmt.Println("distance:", d(p1, p2)) } func closestPair(s []xy) (p1, p2 xy) { if len(s) < 2 { panic("2 points required") } var dxi float64 // step 0 for s1, i := s, 1; ; i++ { // step 1: compute min distance to a random point // (for the case of random data, it's enough to just try // to pick a different point) rp := i % len(s1) xi := s1[rp] dxi = 2 * scale for p, xn := range s1 { if p != rp { if dq := d(xi, xn); dq < dxi { dxi = dq } } } // step 2: filter invB := 3 / dxi // b is size of a mesh cell mx := int64(scale*invB) + 1 // mx is number of cells along a side // construct map as a histogram: // key is index into mesh. value is count of points in cell hm := map[int64]int{} for ip, p := range s1 { key := int64(p.x*invB)*mx + int64(p.y*invB) s1[ip].key = key hm[key]++ } // construct s2 = s1 less the points without neighbors s2 := make([]xy, 0, len(s1)) nx := []int64{-mx - 1, -mx, -mx + 1, -1, 0, 1, mx - 1, mx, mx + 1} for i, p := range s1 { nn := 0 for _, ofs := range nx { nn += hm[p.key+ofs] if nn > 1 { s2 = append(s2, s1[i]) break } } } // step 3: done? if len(s2) == 0 { break } s1 = s2 } // step 4: compute answer from approximation invB := 1 / dxi mx := int64(scale*invB) + 1 hm := map[int64][]int{} for i, p := range s { key := int64(p.x*invB)*mx + int64(p.y*invB) s[i].key = key hm[key] = append(hm[key], i) } nx := []int64{-mx - 1, -mx, -mx + 1, -1, 0, 1, mx - 1, mx, mx + 1} var min = scale * 2 for ip, p := range s { for _, ofs := range nx { for _, iq := range hm[p.key+ofs] { if ip != iq { if d1 := d(p, s[iq]); d1 < min { min = d1 p1, p2 = p, s[iq] } } } } } return p1, p2 } //\Closest-pair-problem\closest-pair-problem-2.go
tasks/Closest-pair-problem/closest-pair-problem-2.go
0.614163
0.572962
closest-pair-problem-2.go
starcoder
package pixelpusher import ( "encoding/binary" "image/color" "github.com/xyproto/pf" ) // Pixel draws a pixel to the pixel buffer func Pixel(pixels []uint32, x, y int32, c color.RGBA, pitch int32) { pixels[y*pitch+x] = binary.BigEndian.Uint32([]uint8{c.A, c.R, c.G, c.B}) } // PixelRGB draws an opaque pixel to the pixel buffer, given red, green and blue func PixelRGB(pixels []uint32, x, y int32, r, g, b uint8, pitch int32) { pixels[y*pitch+x] = binary.BigEndian.Uint32([]uint8{0xff, r, g, b}) } // FastPixel draws a pixel to the pixel buffer, given a uint32 ARGB value func FastPixel(pixels []uint32, x, y int32, colorValue uint32, pitch int32) { pixels[y*pitch+x] = colorValue } // RGBAToColorValue converts from four bytes to an ARGB uint32 color value func RGBAToColorValue(r, g, b, a uint8) uint32 { return binary.BigEndian.Uint32([]uint8{a, r, g, b}) } // ColorValueToRGBA converts from an ARGB uint32 color value to four bytes func ColorValueToRGBA(cv uint32) (uint8, uint8, uint8, uint8) { bs := make([]uint8, 4) binary.LittleEndian.PutUint32(bs, cv) // r, g, b, a return bs[2], bs[1], bs[0], bs[3] } // ColorToColorValue converts from color.RGBA to an ARGB uint32 color value func ColorToColorValue(c color.RGBA) uint32 { return binary.BigEndian.Uint32([]uint8{c.A, c.R, c.G, c.B}) } // Extract the alpha component from a ARGB uint32 color value func Alpha(cv uint32) uint8 { return uint8((cv & 0xff000000) >> 24) } // Extract the red component from a ARGB uint32 color value func Red(cv uint32) uint8 { return uint8((cv & 0xff0000) >> 16) } // Extract the green component from a ARGB uint32 color value func Green(cv uint32) uint8 { return uint8((cv & 0xff00) >> 8) } // Extract the blue component from a ARGB uint32 color value func Blue(cv uint32) uint8 { return uint8(cv & 0xff) } // Extract the color value / intensity from a ARGB uint32 color value func ValueWithAlpha(cv uint32) uint8 { // TODO: This can be optimized bs := make([]uint8, 4) binary.LittleEndian.PutUint32(bs, cv) grayscaleColor := float32(bs[2]+bs[1]+bs[0]) / float32(3) alpha := float32(bs[3]) / float32(255) return uint8(grayscaleColor * alpha) } // Extract the color value / intensity from a ARGB uint32 color value. // Ignores alpha. func Value(cv uint32) uint8 { // TODO: This can be optimized bs := make([]uint8, 4) binary.LittleEndian.PutUint32(bs, cv) grayscaleColor := float32(bs[2]+bs[1]+bs[0]) / float32(3) return uint8(grayscaleColor) } // RemoveRed removes all red color. func RemoveRed(cores int, pixels []uint32) { pf.Map(cores, pf.RemoveRed, pixels) } // RemoveGreen removes all green color. func RemoveGreen(cores int, pixels []uint32) { pf.Map(cores, pf.RemoveGreen, pixels) } // RemoveBlue removes all blue color. func RemoveBlue(cores int, pixels []uint32) { pf.Map(cores, pf.RemoveBlue, pixels) } // Turn on all the red bits func SetRedBits(cores int, pixels []uint32) { pf.Map(cores, pf.SetRedBits, pixels) } // Turn on all the green bits func SetGreenBits(cores int, pixels []uint32) { pf.Map(cores, pf.SetGreenBits, pixels) } // Turn on all the blue bits func SetBlueBits(cores int, pixels []uint32) { pf.Map(cores, pf.SetBlueBits, pixels) } // Turn on all the alpha bits func OrAlpha(cores int, pixels []uint32) { pf.Map(cores, pf.OrAlpha, pixels) } // Return a pixel, with position wraparound instead of overflow func GetXYWrap(pixels []uint32, x, y, w, h, pitch int32) uint32 { if x >= w { x -= w } else if x < 0 { x += w } if y >= h { y -= h } else if y < 0 { y += h } return pixels[y*pitch+x] } // Set a pixel, with position wraparound instead of overflow func SetXYWrap(pixels []uint32, x, y, w, h int32, colorValue uint32, pitch int32) { if x >= w { x -= w } else if x < 0 { x += w } if y >= h { y -= h } else if y < 0 { y += h } pixels[y*pitch+x] = colorValue } // Return a pixel, with position wraparound instead of overflow func GetWrap(pixels []uint32, pos, size int32) uint32 { i := pos if i >= size { i -= size } if i < 0 { i += size } return pixels[i] } // Set a pixel, with position wraparound instead of overflow func SetWrap(pixels []uint32, pos, size int32, colorValue uint32) { i := pos if i >= size { i -= size } if i < 0 { i += size } pixels[i] = colorValue } // Blend blends two color values, based on the alpha value func Blend(c1, c2 uint32) uint32 { mf := float32(255.0) a1 := float32(Alpha(c1)) / mf a2 := float32(Alpha(c2)) / mf // Weight the color values by alpha, then take the average r := uint8((float32(Red(c1))*a1 + float32(Red(c2))*a2) / 2.0) g := uint8((float32(Green(c1))*a1 + float32(Green(c2))*a2) / 2.0) b := uint8((float32(Blue(c1))*a1 + float32(Blue(c2))*a2) / 2.0) // Let the new alpha value be the product of the two given alpha values //a := uint8(a1 * a2 * mf) // Let the new alpha value be the average of the two given alpha values a := uint8(((a1 + a2) / 2) * mf) // Combine the new values to an uint32 (ARGB), and return that return RGBAToColorValue(r, g, b, a) } // Add adds one color value on top of another. // Only considers the alpha value of the second color value. // Returns an opaque color. func Add(c1, c2 uint32) uint32 { mf := float32(255.0) a2 := float32(Alpha(c2)) / mf // Let the second color be affected by the alpha value, but not the first one r := uint8((float32(Red(c1)) + float32(Red(c2))*a2) / 2.0) g := uint8((float32(Green(c1)) + float32(Green(c2))*a2) / 2.0) b := uint8((float32(Blue(c1)) + float32(Blue(c2))*a2) / 2.0) // Combine the new values to an uint32 (ARGB), and return that return RGBAToColorValue(r, g, b, 255) }
pixel.go
0.802594
0.550607
pixel.go
starcoder
// Package cputemp implements an i3bar module that shows the CPU temperature. package cputemp import ( "fmt" "math" "strconv" "strings" "time" "github.com/spf13/afero" "github.com/soumya92/barista/bar" "github.com/soumya92/barista/base" "github.com/soumya92/barista/outputs" ) // Temperature represents the current CPU temperature. type Temperature float64 // C returns the temperature in degrees celcius. func (t Temperature) C() int { return int(math.Floor(float64(t) + .5)) } // K returns the temperature in kelvin. func (t Temperature) K() int { return int(math.Floor(float64(t) + 273.15 + .5)) } // F returns the temperature in degrees fahrenheit. func (t Temperature) F() int { return int(math.Floor(float64(t)*1.8 + 32 + .5)) } // Module represents a cputemp bar module. It supports setting the output // format, click handler, update frequency, and urgency/colour functions. type Module interface { base.WithClickHandler // RefreshInterval configures the polling frequency for cpu temperatures. // Note: updates might still be less frequent if the temperature does not change. RefreshInterval(time.Duration) Module // OutputFunc configures a module to display the output of a user-defined function. OutputFunc(func(Temperature) bar.Output) Module // OutputTemplate configures a module to display the output of a template. OutputTemplate(func(interface{}) bar.Output) Module // OutputColor configures a module to change the colour of its output based on a // user-defined function. This allows you to set up color thresholds, or even // blend between two colours based on the current temperature. OutputColor(func(Temperature) bar.Color) Module // UrgentWhen configures a module to mark its output as urgent based on a // user-defined function. UrgentWhen(func(Temperature) bool) Module } type module struct { *base.Base thermalFile string outputFunc func(Temperature) bar.Output colorFunc func(Temperature) bar.Color urgentFunc func(Temperature) bool } // Zone constructs an instance of the cputemp module for the specified zone. // The file /sys/class/thermal/<zone>/temp should return cpu temp in 1/1000 deg C. func Zone(thermalZone string) Module { m := &module{ Base: base.New(), thermalFile: fmt.Sprintf("/sys/class/thermal/%s/temp", thermalZone), } // Default is to refresh every 3s, matching the behaviour of top. m.RefreshInterval(3 * time.Second) // Default output template, if no template/function was specified. m.OutputTemplate(outputs.TextTemplate(`{{.C}}℃`)) // Update temperature when asked. m.OnUpdate(m.update) return m } // DefaultZone constructs an instance of the cputemp module for the default zone. func DefaultZone() Module { return Zone("thermal_zone0") } func (m *module) OutputFunc(outputFunc func(Temperature) bar.Output) Module { m.Lock() defer m.UnlockAndUpdate() m.outputFunc = outputFunc return m } func (m *module) OutputTemplate(template func(interface{}) bar.Output) Module { return m.OutputFunc(func(t Temperature) bar.Output { return template(t) }) } func (m *module) RefreshInterval(interval time.Duration) Module { m.Schedule().Every(interval) return m } func (m *module) OutputColor(colorFunc func(Temperature) bar.Color) Module { m.Lock() defer m.UnlockAndUpdate() m.colorFunc = colorFunc return m } func (m *module) UrgentWhen(urgentFunc func(Temperature) bool) Module { m.Lock() defer m.UnlockAndUpdate() m.urgentFunc = urgentFunc return m } var fs = afero.NewOsFs() func (m *module) update() { bytes, err := afero.ReadFile(fs, m.thermalFile) if m.Error(err) { return } value := strings.TrimSpace(string(bytes)) milliC, err := strconv.Atoi(value) if m.Error(err) { return } temp := Temperature(float64(milliC) / 1000.0) m.Lock() out := m.outputFunc(temp) if m.urgentFunc != nil { out.Urgent(m.urgentFunc(temp)) } if m.colorFunc != nil { out.Color(m.colorFunc(temp)) } m.Unlock() m.Output(out) }
modules/cputemp/cputemp.go
0.753013
0.417865
cputemp.go
starcoder
package filter import ( "math" ) // DoubleFilter matches against double values. type DoubleFilter interface { // Match returns true if the given value is considered a match. Match(v float64) bool } const ( // doubleEps is used to determine whether two floating point numbers are considered equal. doubleEps = 1e-10 ) type doubleToDoubleFilterFn func(float64) doubleFilterFn type intToDoubleFilterFn func(int) doubleFilterFn type doubleFilterFn func(v float64) bool func (fn doubleFilterFn) Match(v float64) bool { return fn(v) } func equalsDoubleDouble(rhs float64) doubleFilterFn { return func(lhs float64) bool { return math.Abs(lhs-rhs) < doubleEps } } func notEqualsDoubleDouble(rhs float64) doubleFilterFn { return func(lhs float64) bool { return math.Abs(lhs-rhs) >= doubleEps } } func largerThanDoubleDouble(rhs float64) doubleFilterFn { return func(lhs float64) bool { return lhs > rhs } } func largerThanOrEqualDoubleDouble(rhs float64) doubleFilterFn { return func(lhs float64) bool { return lhs >= rhs } } func smallerThanDoubleDouble(rhs float64) doubleFilterFn { return func(lhs float64) bool { return lhs < rhs } } func smallerThanOrEqualDoubleDouble(rhs float64) doubleFilterFn { return func(lhs float64) bool { return lhs <= rhs } } func equalsDoubleInt(rhs int) doubleFilterFn { rf := float64(rhs) return func(lhs float64) bool { return math.Abs(lhs-rf) < doubleEps } } func notEqualsDoubleInt(rhs int) doubleFilterFn { rf := float64(rhs) return func(lhs float64) bool { return math.Abs(lhs-rf) >= doubleEps } } func largerThanDoubleInt(rhs int) doubleFilterFn { rf := float64(rhs) return func(lhs float64) bool { return lhs > rf } } func largerThanOrEqualDoubleInt(rhs int) doubleFilterFn { rf := float64(rhs) return func(lhs float64) bool { return lhs >= rf } } func smallerThanDoubleInt(rhs int) doubleFilterFn { rf := float64(rhs) return func(lhs float64) bool { return lhs < rf } } func smallerThanOrEqualDoubleInt(rhs int) doubleFilterFn { rf := float64(rhs) return func(lhs float64) bool { return lhs <= rf } }
filter/double_filter.go
0.865181
0.663737
double_filter.go
starcoder
package datadog import ( "encoding/json" "time" ) // UsageAuditLogsHour Audit logs usage for a given organization for a given hour. type UsageAuditLogsHour struct { // The hour for the usage. Hour *time.Time `json:"hour,omitempty"` // The total number of audit logs lines indexed during a given hour. LinesIndexed *int64 `json:"lines_indexed,omitempty"` // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct UnparsedObject map[string]interface{} `json:-` } // NewUsageAuditLogsHour instantiates a new UsageAuditLogsHour 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 NewUsageAuditLogsHour() *UsageAuditLogsHour { this := UsageAuditLogsHour{} return &this } // NewUsageAuditLogsHourWithDefaults instantiates a new UsageAuditLogsHour 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 NewUsageAuditLogsHourWithDefaults() *UsageAuditLogsHour { this := UsageAuditLogsHour{} return &this } // GetHour returns the Hour field value if set, zero value otherwise. func (o *UsageAuditLogsHour) GetHour() time.Time { if o == nil || o.Hour == nil { var ret time.Time return ret } return *o.Hour } // GetHourOk returns a tuple with the Hour field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *UsageAuditLogsHour) GetHourOk() (*time.Time, bool) { if o == nil || o.Hour == nil { return nil, false } return o.Hour, true } // HasHour returns a boolean if a field has been set. func (o *UsageAuditLogsHour) HasHour() bool { if o != nil && o.Hour != nil { return true } return false } // SetHour gets a reference to the given time.Time and assigns it to the Hour field. func (o *UsageAuditLogsHour) SetHour(v time.Time) { o.Hour = &v } // GetLinesIndexed returns the LinesIndexed field value if set, zero value otherwise. func (o *UsageAuditLogsHour) GetLinesIndexed() int64 { if o == nil || o.LinesIndexed == nil { var ret int64 return ret } return *o.LinesIndexed } // GetLinesIndexedOk returns a tuple with the LinesIndexed field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *UsageAuditLogsHour) GetLinesIndexedOk() (*int64, bool) { if o == nil || o.LinesIndexed == nil { return nil, false } return o.LinesIndexed, true } // HasLinesIndexed returns a boolean if a field has been set. func (o *UsageAuditLogsHour) HasLinesIndexed() bool { if o != nil && o.LinesIndexed != nil { return true } return false } // SetLinesIndexed gets a reference to the given int64 and assigns it to the LinesIndexed field. func (o *UsageAuditLogsHour) SetLinesIndexed(v int64) { o.LinesIndexed = &v } func (o UsageAuditLogsHour) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.UnparsedObject != nil { return json.Marshal(o.UnparsedObject) } if o.Hour != nil { toSerialize["hour"] = o.Hour } if o.LinesIndexed != nil { toSerialize["lines_indexed"] = o.LinesIndexed } return json.Marshal(toSerialize) } func (o *UsageAuditLogsHour) UnmarshalJSON(bytes []byte) (err error) { raw := map[string]interface{}{} all := struct { Hour *time.Time `json:"hour,omitempty"` LinesIndexed *int64 `json:"lines_indexed,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.Hour = all.Hour o.LinesIndexed = all.LinesIndexed return nil } type NullableUsageAuditLogsHour struct { value *UsageAuditLogsHour isSet bool } func (v NullableUsageAuditLogsHour) Get() *UsageAuditLogsHour { return v.value } func (v *NullableUsageAuditLogsHour) Set(val *UsageAuditLogsHour) { v.value = val v.isSet = true } func (v NullableUsageAuditLogsHour) IsSet() bool { return v.isSet } func (v *NullableUsageAuditLogsHour) Unset() { v.value = nil v.isSet = false } func NewNullableUsageAuditLogsHour(val *UsageAuditLogsHour) *NullableUsageAuditLogsHour { return &NullableUsageAuditLogsHour{value: val, isSet: true} } func (v NullableUsageAuditLogsHour) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUsageAuditLogsHour) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/v1/datadog/model_usage_audit_logs_hour.go
0.73307
0.414721
model_usage_audit_logs_hour.go
starcoder
package suggest import ( "github.com/suggest-go/suggest/pkg/index" "github.com/suggest-go/suggest/pkg/merger" ) // Candidate is an item of Collector type Candidate struct { // Key is a position (docId) in posting list Key index.Position // Score is a float64 number that represents a score of a document Score float64 } // Less tells is the given candidate is less that the provided func (c Candidate) Less(o Candidate) bool { if c.Score == o.Score { return c.Key > o.Key } return c.Score < o.Score } // Collector collects the doc stream satisfied to a search criteria type Collector interface { merger.Collector // SetScorer sets a scorer before collection starts SetScorer(scorer Scorer) // GetCandidates returns the list of collected candidates GetCandidates() []Candidate } // CollectorManager is responsible for creating collectors and reducing them into the result set type CollectorManager interface { // Create creates a new collector that will be used for a search segment Create() (Collector, error) // Reduce reduces the result from the given list of collectors Reduce(collectors []Collector) []Candidate } type firstKCollector struct { limit int items []merger.MergeCandidate } // Collect collects the given merge candidate func (c *firstKCollector) Collect(item merger.MergeCandidate) error { if c.limit == len(c.items) { return merger.ErrCollectionTerminated } c.items = append(c.items, item) return nil } // SetScorer sets a scorer before collection starts func (c *firstKCollector) SetScorer(scorer Scorer) { return } // GetCandidates returns the list of collected candidates func (c *firstKCollector) GetCandidates() []Candidate { result := make([]Candidate, 0, len(c.items)) for _, item := range c.items { result = append(result, Candidate{ Key: item.Position(), }) } return result } // NewFirstKCollectorManager creates a new instance of CollectorManager with firstK collectors func NewFirstKCollectorManager(limit int) CollectorManager { return &firstKCollectorManager{ limit: limit, } } type firstKCollectorManager struct { limit int } // Create creates a new collector that will be used for a search segment func (m *firstKCollectorManager) Create() (Collector, error) { return &firstKCollector{ limit: m.limit, }, nil } // Reduce reduces the result from the given list of collectors func (m *firstKCollectorManager) Reduce(collectors []Collector) []Candidate { topKQueue := NewTopKQueue(m.limit) for _, c := range collectors { if collector, ok := c.(*firstKCollector); ok { for _, item := range collector.items { topKQueue.Add(item.Position(), -float64(item.Position())) } } } return topKQueue.GetCandidates() } type fuzzyCollector struct { topKQueue TopKQueue scorer Scorer } // Collect collects the given merge candidate // calculates the distance, and tries to add this document with it's score to the collector func (c *fuzzyCollector) Collect(item merger.MergeCandidate) error { c.topKQueue.Add(item.Position(), c.scorer.Score(item)) return nil } // GetCandidates returns `top k items` func (c *fuzzyCollector) GetCandidates() []Candidate { return c.topKQueue.GetCandidates() } // Score returns the score of the given position func (c *fuzzyCollector) SetScorer(scorer Scorer) { }
pkg/suggest/collector.go
0.762336
0.415907
collector.go
starcoder
package binrpc import ( "bytes" "encoding/binary" "fmt" "io" "log" "math/rand" ) /* Kamailio's binrpc protocol consists of a variable-byte header with an attached payload. HEADER: | 4 bits | 4 bits | 4 bits | 2b | 2b | variable | variable | | BinRpcMagic | BinRpcVersion | Flags | LL | CL | data length | cookie | BinRpcMagic and BinRpcVersion are constants Flags ??? LL = (size in bytes of the data length) - 1 CL = (size in bytes of the cookie ) - 1 data length = total number of bytes of the payload (excluding this header) cookie = arbitrary identifier PAYLOAD: | 1 bit | 3 bits | 4 bits | variable | variable | | Size flag | Size | Type | optional value length | optional value | Size flag: 0 = Size is the direct size, in bytes of the value 1 = Size is the size (in bytes) of the "optional value length" (hence, if the size in bytes of the payload is larger than 2^3 bytes, you must use size flag = 1) Type: the type code of the data 0 = Integer 1 = String (null-terminated) 2 = Double 3 = Struct 4 = Array 5 = AVP 6 = Byte array (not null-terminated) */ const ( BinRpcMagic uint = 0xA BinRpcVersion uint = 0x1 BinRpcMagicVersion uint = BinRpcMagic<<4 + BinRpcVersion BinRpcTypeInt uint = 0x0 BinRpcTypeString uint = 0x1 // Null-terminated string BinRpcTypeDouble uint = 0x2 BinRpcTypeStruct uint = 0x3 BinRpcTypeArray uint = 0x4 BinRpcTypeAVP uint = 0x5 BinRpcTypeBytes uint = 0x6 // Byte array without null terminator BinRpcTypeAll uint = 0xF // Wildcard; matches any record ) type BinRpcEncoder interface { Encode(io.Writer) error } type BinRpcInt int32 func (s BinRpcInt) Encode(w io.Writer) error { return WritePacket(w, BinRpcTypeInt, s) } type BinRpcString string func (s BinRpcString) Encode(w io.Writer) error { // Strings must be NUL-terminated in binrpc val := append([]byte(s), 0x0) return WritePacket(w, BinRpcTypeString, val) } // ConstructHeader takes the payload length and cookie // and returns a byte array header func ConstructHeader(header *bytes.Buffer, payloadLength uint64, cookie uint32) error { // Add the Magic/Version err := header.WriteByte(byte(BinRpcMagicVersion)) if err != nil { return fmt.Errorf("Failed to write magic/version to header: %s", err.Error()) } // Find the size (in bytes) of the payload length plSize := uint8(payloadLength / 256) if payloadLength%256 > 0 { plSize += 1 } //log.Printf("Payload length is %d, and the length of that value in bytes is %d", payloadLength, plSize) // Find the size of the cookie cookieSize := binary.Size(cookie) if cookieSize < 0 { return fmt.Errorf("failed to determine byte length of cookie") } // Write the Flags/LL/CL byte (flags hard-coded to 0x0 for now) err = header.WriteByte(byte(0x0<<4 | uint(plSize-1)<<2 | uint(cookieSize-1))) if err != nil { return fmt.Errorf("failed to write flags byte: %w", err) } // Write the payload length err = binary.Write(header, binary.BigEndian, uint8(payloadLength)) if err != nil { return fmt.Errorf("failed to append payload length: %w", err) } // Write the cookie err = binary.Write(header, binary.BigEndian, cookie) if err != nil { return fmt.Errorf("failed to append cookie: %w", err) } return nil } // ConstructPayload takes a value and encodes it // into a BinRpc payload func ConstructPayload(payload *bytes.Buffer, valType uint, val interface{}) error { // Calculate the minimum byte-size of the value valueLength := int8(binary.Size(val)) if valueLength < 0 { return fmt.Errorf("failed to determine byte-size of value") } // If the minimum byte-size is larger than will // fit in three bits, set the size flag = 1 var sflag uint var size uint if valueLength > 8 { // 2^3 = 8 sflag = 1 // If sflag = 1, size now describes the byte size // of the _length_ of the value instead of the value itself if temp_size := binary.Size(valueLength); temp_size < 0 { log.Println("binary size of", valueLength, "is", temp_size) return fmt.Errorf("failed to determine byte-size of value length") } else { size = uint(temp_size) } } else { // Otherwise, the size is (directly) the byte-length of the value size = uint(valueLength) } // Write the payload header err := payload.WriteByte(byte(sflag<<7 | size<<4 | valType)) if err != nil { return fmt.Errorf("failed to write payload header: %w", err) } // Write the optional value length if our size is too large // to fit in `size` if sflag == 1 { err = binary.Write(payload, binary.BigEndian, uint8(valueLength)) if err != nil { return fmt.Errorf("failed to append optional value length: %w", err) } } // Append the value itself err = binary.Write(payload, binary.BigEndian, val) if err != nil { return fmt.Errorf("failed to append payload value: %w", err) } return nil } func WritePacket(w io.Writer, valType uint, val interface{}) error { buf := new(bytes.Buffer) // Construct the payload payload := new(bytes.Buffer) err := ConstructPayload(payload, valType, val) if err != nil { return fmt.Errorf("failed to construct payload: %w", err) } // Generate a cookie cookie := uint32(rand.Int63()) // Add the header err = ConstructHeader(buf, uint64(payload.Len()), cookie) if err != nil { return fmt.Errorf("failed to construct header: %w", err) } // Add the payload _, err = payload.WriteTo(buf) if err != nil { return fmt.Errorf("failed to append payload: %w", err) } // Write the buffer to the io.Writer _, err = buf.WriteTo(w) return err }
binrpc/binrpc.go
0.598782
0.424949
binrpc.go
starcoder
package ring // NumberTheoreticTransformer is an interface to provide // flexibility on what type of NTT is used by the struct Ring. type NumberTheoreticTransformer interface { Forward(r *Ring, p1, p2 *Poly) ForwardLvl(r *Ring, level int, p1, p2 *Poly) ForwardLazy(r *Ring, p1, p2 *Poly) ForwardLazyLvl(r *Ring, level int, p1, p2 *Poly) Backward(r *Ring, p1, p2 *Poly) BackwardLvl(r *Ring, level int, p1, p2 *Poly) BackwardLazy(r *Ring, p1, p2 *Poly) BackwardLazyLvl(r *Ring, level int, p1, p2 *Poly) ForwardVec(r *Ring, level int, p1, p2 []uint64) ForwardLazyVec(r *Ring, level int, p1, p2 []uint64) BackwardVec(r *Ring, level int, p1, p2 []uint64) BackwardLazyVec(r *Ring, level int, p1, p2 []uint64) } // NumberTheoreticTransformerStandard computes the standard nega-cyclic NTT in the ring Z[X]/(X^N+1). type NumberTheoreticTransformerStandard struct { } // Forward writes the forward NTT in Z[X]/(X^N+1) of p1 on p2. func (rntt NumberTheoreticTransformerStandard) Forward(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { NTT(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // ForwardLvl writes the forward NTT in Z[X]/(X^N+1) of p1 on p2. // Only computes the NTT for the first level+1 moduli. func (rntt NumberTheoreticTransformerStandard) ForwardLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { NTT(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // ForwardLazy writes the forward NTT in Z[X]/(X^N+1) of p1 on p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerStandard) ForwardLazy(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { NTTLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // ForwardLazyLvl writes the forward NTT in Z[X]/(X^N+1) of p1 on p2. // Only computes the NTT for the first level+1 moduli and returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerStandard) ForwardLazyLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { NTTLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // Backward writes the backward NTT in Z[X]/(X^N+1) on p2. func (rntt NumberTheoreticTransformerStandard) Backward(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { InvNTT(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // BackwardLvl writes the backward NTT in Z[X]/(X^N+1) on p2. // Only computes the NTT for the first level+1 moduli. func (rntt NumberTheoreticTransformerStandard) BackwardLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { InvNTT(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // BackwardLazy writes the backward NTT in Z[X]/(X^N+1) on p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerStandard) BackwardLazy(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { InvNTTLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // BackwardLazyLvl writes the backward NTT in Z[X]/(X^N+1) on p2. // Only computes the NTT for the first level+1 moduli and returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerStandard) BackwardLazyLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { InvNTTLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // ForwardVec writes the forward NTT in Z[X]/(X^N+1) of the i-th level of p1 on the i-th level of p2. func (rntt NumberTheoreticTransformerStandard) ForwardVec(r *Ring, level int, p1, p2 []uint64) { NTT(p1, p2, r.N, r.NttPsi[level], r.Modulus[level], r.MredParams[level], r.BredParams[level]) } // ForwardLazyVec writes the forward NTT in Z[X]/(X^N+1) of the i-th level of p1 on the i-th level of p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerStandard) ForwardLazyVec(r *Ring, level int, p1, p2 []uint64) { NTTLazy(p1, p2, r.N, r.NttPsi[level], r.Modulus[level], r.MredParams[level], r.BredParams[level]) } // BackwardVec writes the backward NTT in Z[X]/(X^N+1) of the i-th level of p1 on the i-th level of p2. func (rntt NumberTheoreticTransformerStandard) BackwardVec(r *Ring, level int, p1, p2 []uint64) { InvNTT(p1, p2, r.N, r.NttPsiInv[level], r.NttNInv[level], r.Modulus[level], r.MredParams[level]) } // BackwardLazyVec writes the backward NTT in Z[X]/(X^N+1) of the i-th level of p1 on the i-th level of p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerStandard) BackwardLazyVec(r *Ring, level int, p1, p2 []uint64) { InvNTTLazy(p1, p2, r.N, r.NttPsiInv[level], r.NttNInv[level], r.Modulus[level], r.MredParams[level]) } // NumberTheoreticTransformerConjugateInvariant computes the NTT in the ring Z[X+X^-1]/(X^2N+1). // Z[X+X^-1]/(X^2N+1) is a closed sub-ring of Z[X]/(X^2N+1). Note that the input polynomial only needs to be size N // since the right half does not provide any additional information. // See "Approximate Homomorphic Encryption over the Conjugate-invariant Ring", https://eprint.iacr.org/2018/952. // The implemented approach is more efficient than the one proposed in the referenced work. // It avoids the linear map Z[X + X^-1]/(X^2N + 1) <-> Z[X]/(X^N - 1) by instead directly computing the left // half of the NTT of Z[X + X^-1]/(X^2N + 1) since the right half provides no additional information, which // allows to (re)use nega-cyclic NTT. type NumberTheoreticTransformerConjugateInvariant struct { } // Forward writes the forward NTT in Z[X+X^-1]/(X^2N+1) on p2. func (rntt NumberTheoreticTransformerConjugateInvariant) Forward(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { NTTConjugateInvariant(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // ForwardLvl writes the forward NTT in Z[X+X^-1]/(X^2N+1) on p2. // Only computes the NTT for the first level+1 moduli. func (rntt NumberTheoreticTransformerConjugateInvariant) ForwardLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { NTTConjugateInvariant(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // ForwardLazy writes the forward NTT in Z[X+X^-1]/(X^2N+1) on p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerConjugateInvariant) ForwardLazy(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { NTTConjugateInvariantLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // ForwardLazyLvl writes the forward NTT in Z[X+X^-1]/(X^2N+1) on p2. // Only computes the NTT for the first level+1 moduli and returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerConjugateInvariant) ForwardLazyLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { NTTConjugateInvariantLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsi[x], r.Modulus[x], r.MredParams[x], r.BredParams[x]) } } // Backward writes the backward NTT in Z[X+X^-1]/(X^2N+1) on p2. func (rntt NumberTheoreticTransformerConjugateInvariant) Backward(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { InvNTTConjugateInvariant(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // BackwardLvl writes the backward NTT in Z[X+X^-1]/(X^2N+1) on p2. // Only computes the NTT for the first level+1 moduli. func (rntt NumberTheoreticTransformerConjugateInvariant) BackwardLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { InvNTTConjugateInvariant(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // BackwardLazy writes the backward NTT in Z[X+X^-1]/(X^2N+1) on p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerConjugateInvariant) BackwardLazy(r *Ring, p1, p2 *Poly) { for x := range r.Modulus { InvNTTConjugateInvariantLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // BackwardLazyLvl writes the backward NTT in Z[X+X^-1]/(X^2N+1) on p2. // Only computes the NTT for the first level+1 moduli and returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerConjugateInvariant) BackwardLazyLvl(r *Ring, level int, p1, p2 *Poly) { for x := 0; x < level+1; x++ { InvNTTConjugateInvariantLazy(p1.Coeffs[x], p2.Coeffs[x], r.N, r.NttPsiInv[x], r.NttNInv[x], r.Modulus[x], r.MredParams[x]) } } // ForwardVec writes the forward NTT in Z[X+X^-1]/(X^2N+1) of the i-th level of p1 on the i-th level of p2. func (rntt NumberTheoreticTransformerConjugateInvariant) ForwardVec(r *Ring, level int, p1, p2 []uint64) { NTTConjugateInvariant(p1, p2, r.N, r.NttPsi[level], r.Modulus[level], r.MredParams[level], r.BredParams[level]) } // ForwardLazyVec writes the forward NTT in Z[X+X^-1]/(X^2N+1) of the i-th level of p1 on the i-th level of p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerConjugateInvariant) ForwardLazyVec(r *Ring, level int, p1, p2 []uint64) { NTTConjugateInvariantLazy(p1, p2, r.N, r.NttPsi[level], r.Modulus[level], r.MredParams[level], r.BredParams[level]) } // BackwardVec writes the backward NTT in Z[X+X^-1]/(X^2N+1) of the i-th level of p1 on the i-th level of p2. func (rntt NumberTheoreticTransformerConjugateInvariant) BackwardVec(r *Ring, level int, p1, p2 []uint64) { InvNTTConjugateInvariant(p1, p2, r.N, r.NttPsiInv[level], r.NttNInv[level], r.Modulus[level], r.MredParams[level]) } // BackwardLazyVec writes the backward NTT in Z[X+X^-1]/(X^2N+1) of the i-th level of p1 on the i-th level of p2. // Returns values in the range [0, 2q-1]. func (rntt NumberTheoreticTransformerConjugateInvariant) BackwardLazyVec(r *Ring, level int, p1, p2 []uint64) { InvNTTConjugateInvariantLazy(p1, p2, r.N, r.NttPsiInv[level], r.NttNInv[level], r.Modulus[level], r.MredParams[level]) }
ring/ring_ntt_interface.go
0.798698
0.475484
ring_ntt_interface.go
starcoder
package main import ( "math" . "github.com/jakecoffman/cp" "github.com/jakecoffman/cp/examples" ) var dollyBody *Body // Constraint used as a servo motor to move the dolly back and forth. var dollyServo *PivotJoint // Constraint used as a winch motor to lift the load. var winchServo *SlideJoint // Temporary joint used to hold the hook to the load. var hookJoint *Constraint func main() { space := NewSpace() space.Iterations = 30 space.SetGravity(Vector{0, -100}) space.SetDamping(0.8) shape := space.AddShape(NewSegment(space.StaticBody, Vector{-320, -240}, Vector{320, -240}, 0)) shape.SetElasticity(1) shape.SetFriction(1) shape.SetFilter(examples.NotGrabbableFilter) dollyBody = space.AddBody(NewBody(10, INFINITY)) dollyBody.SetPosition(Vector{0, 100}) space.AddShape(NewBox(dollyBody, 30, 30, 0)) // Add a groove joint for it to move back and forth on. space.AddConstraint(NewGrooveJoint(space.StaticBody, dollyBody, Vector{-250, 100}, Vector{250, 100}, Vector{})) // Add a pivot joint to act as a servo motor controlling it's position // By updating the anchor points of the pivot joint, you can move the dolly. dollyServo = space.AddConstraint(NewPivotJoint(space.StaticBody, dollyBody, dollyBody.Position())).Class.(*PivotJoint) // Max force the dolly servo can generate. dollyServo.SetMaxForce(10000) // Max speed of the dolly servo dollyServo.SetMaxBias(100) // You can also change the error bias to control how it slows down. //dollyServo.SetErrorBias(0.2) hookBody := space.AddBody(NewBody(1, INFINITY)) hookBody.SetPosition(Vector{0, 50}) // This will be used to figure out when the hook touches a box. shape = space.AddShape(NewCircle(hookBody, 10, Vector{})) shape.SetSensor(true) shape.SetCollisionType(COLLISION_HOOK) // By updating the max length of the joint you can make it pull up the load. winchServo = space.AddConstraint(NewSlideJoint(dollyBody, hookBody, Vector{}, Vector{}, 0, INFINITY)).Class.(*SlideJoint) winchServo.SetMaxForce(30000) winchServo.SetMaxBias(60) boxBody := space.AddBody(NewBody(30, MomentForBox(30, 50, 0))) boxBody.SetPosition(Vector{200, -200}) shape = space.AddShape(NewBox(boxBody,50, 50, 0)) shape.SetFriction(0.7) shape.SetCollisionType(COLLISION_CRATE) handler := space.NewCollisionHandler(COLLISION_HOOK, COLLISION_CRATE) handler.BeginFunc = hookCrate examples.Main(space, 1.0/60.0, update, examples.DefaultDraw) } func update(space *Space, dt float64) { // Set the first anchor point (the one attached to the static body) of the dolly servo to the mouse's x position. dollyServo.AnchorA = Vector{examples.Mouse.X, 100} // Set the max length of the winch servo to match the mouse's height. winchServo.Max = math.Max(100.0-examples.Mouse.Y, 50) if hookJoint != nil && examples.RightClick { space.RemoveConstraint(hookJoint) hookJoint = nil } examples.DrawString(Vector{-200, -200}, "Control the crane by moving the mouse. Right click to release.") space.Step(dt) } const ( COLLISION_HOOK = 1 COLLISION_CRATE = 2 ) func attachHook(space *Space, b1, b2 interface{}) { hook := b1.(*Body) crate := b2.(*Body) hookJoint = space.AddConstraint(NewPivotJoint(hook, crate, hook.Position())) } func hookCrate(arb *Arbiter, space *Space, data interface{}) bool { if hookJoint == nil { // Get pointers to the two bodies in the collision pair and define local variables for them. // Their order matches the order of the collision types passed // to the collision handler this function was defined for hook, crate := arb.Bodies() // additions and removals can't be done in a normal callback. // Schedule a post step callback to do it. // Use the hook as the key and pass along the arbiter. space.AddPostStepCallback(attachHook, hook, crate) } return true }
examples/crane/crane.go
0.637821
0.484136
crane.go
starcoder
package css import ( "strings" "golang.org/x/net/html" ) // Represents a callback function that will be invoked when the default // matching machinery couldn't match the given SimpleSelector and HTML node. // If the callback function returns true it means that the node matches. type SimpleSelectorMatchFunc func(SimpleSelector, *html.Node) bool // Matches the given SelectorGroup s against the HTML node n using the callback function // f if the default matching machinery didn't find a match. func MatchesSelectors(s SelectorsGroup, n *html.Node, f SimpleSelectorMatchFunc) bool { for _, x := range s { if MatchesSelector(x, n, f) { return true } } return false } // Matches the given Selector s against the HTML node n using the callback function // f if the default matching machinery didn't find a match. func MatchesSelector(s *Selector, n *html.Node, f SimpleSelectorMatchFunc) bool { return s.PseudoElement == nil && matchesCompoundSelector(s.CompoundSelector, n, f) == matched } // Matches the given SimpleSelector s against the HTML node n using the callback function // f if the default matching machinery didn't find a match. func MatchesSimpleSelector(s SimpleSelector, n *html.Node, f SimpleSelectorMatchFunc) bool { if n.Type == html.DocumentNode { for n = n.FirstChild; n != nil; n = n.NextSibling { if n.Type == html.ElementNode { break } } } if n.Type != html.ElementNode { return false } switch x := s.(type) { case *LocalNameSelector: return strings.EqualFold(n.Data, x.Name) case *AttributeSelector: return matchesAttributeSelector(x, n) case *PseudoNegationSelector: return !MatchesSimpleSelector(x.Selector, n, f) case *PseudoClassSelector: if matchesPseudoClassSelector(x, n) { return true } case *PseudoNthSelector: if matchesPseudoNthSelector(x, n) { return true } } if f != nil { return f(s, n) } return false } type matchingResult int const ( matched matchingResult = iota notMatched restartFromClosestDescendant restartFromClosestLaterSibling ) func matchesCompoundSelector(s *CompoundSelector, n *html.Node, f SimpleSelectorMatchFunc) matchingResult { for _, ss := range s.SimpleSelectors { if !MatchesSimpleSelector(ss, n, f) { return restartFromClosestLaterSibling } } if s.Prev == nil { return matched } siblings := false candidateNotFound := notMatched switch s.Prev.Combinator { case NextSibling, LaterSibling: siblings = true candidateNotFound = restartFromClosestDescendant } for { var nextNode *html.Node if siblings { nextNode = n.PrevSibling } else { nextNode = n.Parent } if nextNode == nil { return candidateNotFound } else { n = nextNode } if n.Type == html.ElementNode { r := matchesCompoundSelector(s.Prev.CompoundSelector, n, f) if r == matched || r == notMatched { return r } switch s.Prev.Combinator { case Child: return restartFromClosestDescendant case NextSibling: return r case LaterSibling: if r == restartFromClosestDescendant { return r } } } } } func matchesAttributeSelector(s *AttributeSelector, n *html.Node) bool { for _, a := range n.Attr { if a.Key != s.Name { continue } switch s.Match { case Exists: return true case Equals: return a.Val == s.Value case Includes: for _, x := range strings.FieldsFunc(a.Val, IsSpace) { if x == s.Value { return true } } case Begins: return strings.HasPrefix(a.Val, s.Value) case Ends: return strings.HasSuffix(a.Val, s.Value) case Contains: return strings.Contains(a.Val, s.Value) case Hyphens: return a.Val == s.Value || strings.HasPrefix(a.Val, s.Value+"-") } return false } return false } func matchesPseudoClassSelector(s *PseudoClassSelector, n *html.Node) bool { switch s.Value { case "first-child": return matchesFirstOrLastChild(n, true) case "last-child": return matchesFirstOrLastChild(n, false) case "only-child": return matchesFirstOrLastChild(n, true) && matchesFirstOrLastChild(n, false) case "first-of-type": return matchesNthChild(n, 0, 1, true, false) case "last-of-type": return matchesNthChild(n, 0, 1, true, true) case "only-of-type": return matchesNthChild(n, 0, 1, true, false) && matchesNthChild(n, 0, 1, true, true) case "root": return n.Parent != nil && n.Parent.Type == html.DocumentNode case "empty": for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type == html.ElementNode { return false } if c.Type == html.TextNode && len(c.Data) > 0 { return false } } return true default: return false } } func matchesPseudoNthSelector(s *PseudoNthSelector, n *html.Node) bool { switch s.Name { case "nth-child": return matchesNthChild(n, s.A, s.B, false, false) case "nth-last-child": return matchesNthChild(n, s.A, s.B, false, true) case "nth-of-type": return matchesNthChild(n, s.A, s.B, true, false) case "nth-last-of-type": return matchesNthChild(n, s.A, s.B, true, true) default: return false } } func matchesFirstOrLastChild(n *html.Node, first bool) bool { for { var x *html.Node if first { x = n.PrevSibling } else { x = n.NextSibling } if x == nil { x = n.Parent return x != nil && x.Type != html.DocumentNode } else { if x.Type == html.ElementNode { return false } n = x } } } func matchesNthChild(n *html.Node, a, b int, isOfType, fromEnd bool) bool { if n.Parent == nil || n.Parent.Type == html.DocumentNode { return false } x := n i := 1 for { if fromEnd { s := x.NextSibling if s == nil { break } else { x = s } } else { s := x.PrevSibling if s == nil { break } else { x = s } } if x.Type == html.ElementNode { if isOfType { if n.Data == x.Data { i += 1 } } else { i += 1 } } } if a == 0 { return b == i } return ((i-b)/a) >= 0 && ((i-b)%a) == 0 }
css/selector_matching.go
0.701815
0.443781
selector_matching.go
starcoder
package aipreflect import "google.golang.org/protobuf/reflect/protoreflect" // MethodType is an AIP method type. type MethodType int //go:generate stringer -type MethodType -trimprefix MethodType const ( // MethodTypeNone represents no method type. MethodTypeNone MethodType = iota // MethodTypeGet is the method type of the AIP standard Get method. // See: https://google.aip.dev/131 (Standard methods: Get). MethodTypeGet // MethodTypeList is the method type of the AIP standard List method. // See: https://google.aip.dev/132 (Standard methods: List). MethodTypeList // MethodTypeCreate is the method type of the AIP standard Create method. // See: https://google.aip.dev/133 (Standard methods: Create). MethodTypeCreate // MethodTypeUpdate is the method type of the AIP standard Update method. // See: https://google.aip.dev/133 (Standard methods: Update). MethodTypeUpdate // MethodTypeDelete is the method type of the AIP standard Delete method. // See: https://google.aip.dev/135 (Standard methods: Delete). MethodTypeDelete // MethodTypeUndelete is the method type of the AIP Undelete method for soft delete. // See: https://google.aip.dev/164 (Soft delete). MethodTypeUndelete // MethodTypeBatchGet is the method type of the AIP standard BatchGet method. // See: https://google.aip.dev/231 (Batch methods: Get). MethodTypeBatchGet // MethodTypeBatchCreate is the method type of the AIP standard BatchCreate method. // See: https://google.aip.dev/233 (Batch methods: Create). MethodTypeBatchCreate // MethodTypeBatchUpdate is the method type of the AIP standard BatchUpdate method. // See: https://google.aip.dev/234 (Batch methods: Update). MethodTypeBatchUpdate // MethodTypeBatchDelete is the method type of the AIP standard BatchDelete method. // See: https://google.aip.dev/235 (Batch methods: Delete). MethodTypeBatchDelete // MethodTypeSearch is the method type of the custom AIP method for searching a resource collection. // See: https://google.aip.dev/136 (Custom methods). MethodTypeSearch ) // NamePrefix returns the method type's method name prefix. func (s MethodType) NamePrefix() protoreflect.Name { return protoreflect.Name(s.String()) } // IsPlural returns true if the method type relates to a plurality of resources. func (s MethodType) IsPlural() bool { switch s { case MethodTypeList, MethodTypeSearch, MethodTypeBatchGet, MethodTypeBatchCreate, MethodTypeBatchUpdate, MethodTypeBatchDelete: return true case MethodTypeNone, MethodTypeGet, MethodTypeCreate, MethodTypeUpdate, MethodTypeDelete, MethodTypeUndelete: return false } return false }
reflect/aipreflect/methodtype.go
0.645902
0.472562
methodtype.go
starcoder
package math3d import "math" // Matrix struct holds a 4x4 matrix type Matrix struct { X Vector Y Vector Z Vector W Vector } // ToArray converts the matrix to its array representation func (m Matrix) ToArray() []float64 { ret := append(m.X.ToArray(), m.Y.ToArray()...) ret = append(ret, m.Z.ToArray()...) return append(ret, m.W.ToArray()...) } // FromArray converts an array to a matrix func (m *Matrix) FromArray(a []float64) { m.X.FromArray(a[0:4]) m.Y.FromArray(a[4:8]) m.Z.FromArray(a[8:12]) m.W.FromArray(a[12:16]) } // LoadIdentity loads the identity matrix func (m *Matrix) LoadIdentity() { *m = IdentityMatrix() } // Transpose mirrors the content of the matrix diagonally func (m *Matrix) Transpose() { m.X.Y, m.Y.X = m.Y.X, m.X.Y m.X.Z, m.Y.Y, m.Z.X, m.Z.Y = m.Z.X, m.Z.Y, m.X.Z, m.Y.Y m.X.W, m.Y.W, m.Z.W, m.W.X, m.W.Y, m.W.Z = m.W.X, m.W.Y, m.W.Z, m.X.W, m.Y.W, m.Z.W } // Multiply returns the product of: m * n func Multiply(m, n Matrix) Matrix { return Matrix{ X: Vector{ X: m.X.X*n.X.X + m.Y.X*n.X.Y + m.Z.X*n.X.Z + m.W.X*n.X.W, Y: m.X.Y*n.X.X + m.Y.Y*n.X.Y + m.Z.Y*n.X.Z + m.W.Y*n.X.W, Z: m.X.Z*n.X.X + m.Y.Z*n.X.Y + m.Z.Z*n.X.Z + m.W.Z*n.X.W, W: m.X.W*n.X.X + m.Y.W*n.X.Y + m.Z.W*n.X.Z + m.W.W*n.X.W, }, Y: Vector{ X: m.X.X*n.Y.X + m.Y.X*n.Y.Y + m.Z.X*n.Y.Z + m.W.X*n.Y.W, Y: m.X.Y*n.Y.X + m.Y.Y*n.Y.Y + m.Z.Y*n.Y.Z + m.W.Y*n.Y.W, Z: m.X.Z*n.Y.X + m.Y.Z*n.Y.Y + m.Z.Z*n.Y.Z + m.W.Z*n.Y.W, W: m.X.W*n.Y.X + m.Y.W*n.Y.Y + m.Z.W*n.Y.Z + m.W.W*n.Y.W, }, Z: Vector{ X: m.X.X*n.Z.X + m.Y.X*n.Z.Y + m.Z.X*n.Z.Z + m.W.X*n.Z.W, Y: m.X.Y*n.Z.X + m.Y.Y*n.Z.Y + m.Z.Y*n.Z.Z + m.W.Y*n.Z.W, Z: m.X.Z*n.Z.X + m.Y.Z*n.Z.Y + m.Z.Z*n.Z.Z + m.W.Z*n.Z.W, W: m.X.W*n.Z.X + m.Y.W*n.Z.Y + m.Z.W*n.Z.Z + m.W.W*n.Z.W, }, W: Vector{ X: m.X.X*n.W.X + m.Y.X*n.W.Y + m.Z.X*n.W.Z + m.W.X*n.W.W, Y: m.X.Y*n.W.X + m.Y.Y*n.W.Y + m.Z.Y*n.W.Z + m.W.Y*n.W.W, Z: m.X.Z*n.W.X + m.Y.Z*n.W.Y + m.Z.Z*n.W.Z + m.W.Z*n.W.W, W: m.X.W*n.W.X + m.Y.W*n.W.Y + m.Z.W*n.W.Z + m.W.W*n.W.W, }, } } // Transform returns a transformed vector, which is m * v func Transform(m Matrix, v Vector, isNormalVec bool) Vector { if !isNormalVec { return Vector{ X: m.X.X*v.X + m.Y.X*v.Y + m.Z.X*v.Z + m.W.X*v.W, Y: m.X.Y*v.X + m.Y.Y*v.Y + m.Z.Y*v.Z + m.W.Y*v.W, Z: m.X.Z*v.X + m.Y.Z*v.Y + m.Z.Z*v.Z + m.W.Z*v.W, W: m.X.W*v.X + m.Y.W*v.Y + m.Z.W*v.Z + m.W.W*v.W, } } return Vector{ X: m.X.X*v.X + m.Y.X*v.Y + m.Z.X*v.Z, Y: m.X.Y*v.X + m.Y.Y*v.Y + m.Z.Y*v.Z, Z: m.X.Z*v.X + m.Y.Z*v.Y + m.Z.Z*v.Z, W: 0, } } // Translate returns the matrix translated by x, y, z func Translate(m Matrix, x, y, z float64) Matrix { translationMat := IdentityMatrix() translationMat.W = Vector{x, y, z, 1} return Multiply(m, translationMat) } // Scale returns the matrix scaled by x, y, z func Scale(m Matrix, x, y, z float64) Matrix { translationMat := IdentityMatrix() translationMat.X.X = x translationMat.Y.Y = y translationMat.Z.Z = z translationMat.W.W = 1 return Multiply(m, translationMat) } // Rotate rottes the matrix on one axis func Rotate(m Matrix, radians, x, y, z float64) Matrix { s := math.Sin(radians) c := math.Cos(radians) rotationMat := IdentityMatrix() rotationMat.X = Vector{x*x*(1-c) + c, y*x*(1-c) - z*s, z*x*(1-c) + y*s, 0} rotationMat.Y = Vector{x*y*(1-c) + z*s, y*y*(1-c) + c, z*y*(1-c) - x*s, 0} rotationMat.Z = Vector{x*z*(1-c) - y*s, y*z*(1-c) + x*s, z*z*(1-c) + c, 0} return Multiply(m, rotationMat) } // IdentityMatrix returns the identity matrix func IdentityMatrix() Matrix { return Matrix{ X: Vector{1, 0, 0, 0}, Y: Vector{0, 1, 0, 0}, Z: Vector{0, 0, 1, 0}, W: Vector{0, 0, 0, 1}, } } // ProjectionMatrix creates a projection matrix with the given arguments func ProjectionMatrix(fov, aspectRatio, zNear, zFar float64) Matrix { t := math.Tan(fov*math.Pi/360.) * zNear r := t * aspectRatio return Matrix{ X: Vector{zNear / r, 0, 0, 0}, Y: Vector{0, zNear / t, 0, 0}, Z: Vector{0, 0, (-zFar - zNear) / (zFar - zNear), -1}, W: Vector{0, 0, -2. * zNear * zFar / (zFar - zNear), 0}, } } // Viewport creates a viewport matrix for a window func Viewport(x, y, w, h float64) Matrix { vp := IdentityMatrix() vp = Translate(vp, x, y, 0) vp = Scale(vp, w/2., -h/2., 1./2.) vp = Translate(vp, 1, -1, 1) return vp }
math3d/matrix.go
0.910743
0.752126
matrix.go
starcoder
package builder import "encoding/json" // A metric contains measurements or data points. Each data point has a time // stamp of when the measurement occurred and a value that is either a long or // double and optionally contains tags. Tags are labels that can be added to // better identify the metric. For example, if the measurement was done on server1 // then you might add a tag named "host" with a value of "server1". Note that a // metric must have at least one tag. // An interface that represents an instance of a metric. type Metric interface { // Adds a TTL, expressed in seconds, to the metric. AddTTL(ttl int64) Metric // Adds a custom type of value stored in datapoint. AddType(t string) Metric // Adds a tag to the datapoint. AddTag(name, val string) Metric // Add a map of tags. This narrows the query to only show data points // associated with the tags' values. AddTags(tags map[string]string) Metric // Adds a datapoint to the metric. The value is of int64 type. AddDataPoint(timestamp int64, value interface{}) Metric // Returns the TLL associated with the metric. GetTTL() int64 // Returns the name of the metric. GetName() string // Returns the custom type name. GetType() string // Returns all the tags/values as a map. GetTags() map[string]string // Returns an array of all the datapoints of this metric. GetDataPoints() []DataPoint // Validates the contents of the metric struct. validate() error // Encodes the Metric instance as a JSON array. Build() ([]byte, error) } // Type that implements the Metric interface. type metricType struct { Name string `json:"name,omitempty"` // Name of the metric. Type string `json:"type,omitempty"` // Type of the metric being stored. Tags map[string]string `json:"tags,omitempty"` // Map of tag names and the values associated. DataPoints []DataPoint `json:"datapoints,omitempty"` // List of DataPoints. TTL int64 `json:"ttl,omitempty"` // TTL associated with the metric. } func NewMetric(name string) Metric { return &metricType{ Name: name, Tags: make(map[string]string), } } func (m *metricType) AddTTL(ttl int64) Metric { m.TTL = ttl return m } func (m *metricType) AddType(t string) Metric { m.Type = t return m } func (m *metricType) AddTags(tags map[string]string) Metric { for k, v := range tags { m.Tags[k] = v } return m } func (m *metricType) AddTag(name, val string) Metric { m.Tags[name] = val return m } func (m *metricType) AddDataPoint(timestamp int64, value interface{}) Metric { m.DataPoints = append(m.DataPoints, DataPoint{timestamp: timestamp, value: value}) return m } func (m *metricType) GetName() string { return m.Name } func (m *metricType) GetType() string { return m.Type } func (m *metricType) GetTTL() int64 { return m.TTL } func (m *metricType) GetTags() map[string]string { return m.Tags } func (m *metricType) GetDataPoints() []DataPoint { return m.DataPoints } func (m *metricType) validate() error { // Check if the metric name set is valid. if m.Name == "" { return ErrorMetricNameInvalid } // Check if the tag names & vaues are valid. for k, v := range m.Tags { if k == "" { return ErrorTagNameInvalid } else if v == "" { return ErrorTagValueInvalid } } // Check if TTL is greater than 0. if m.TTL < 0 { return ErrorTTLInvalid } return nil } func (m *metricType) Build() ([]byte, error) { err := m.validate() if err != nil { return nil, err } // Encode the struct into JSON object. b, err := json.Marshal(m) return b, err }
vendor/github.com/ArthurHlt/go-kairosdb/builder/metric.go
0.896518
0.591723
metric.go
starcoder
package genfuncs import ( "fmt" "golang.org/x/exp/constraints" ) var ( // Orderings LessThan = -1 EqualTo = 0 GreaterThan = 1 // Predicates IsBlank = OrderedEqualTo("") IsNotBlank = Not(IsBlank) F32IsZero = OrderedEqualTo(float32(0.0)) F64IsZero = OrderedEqualTo(0.0) IIsZero = OrderedEqualTo(0) ) // OrderedEqual returns true jf a is ordered equal to b. func OrderedEqual[O constraints.Ordered](a, b O) (orderedEqualTo bool) { orderedEqualTo = Ordered(a, b) == EqualTo return orderedEqualTo } // OrderedEqualTo return a function that returns true if its argument is ordered equal to a. func OrderedEqualTo[O constraints.Ordered](a O) (fn Function[O, bool]) { fn = Curried[O, bool](OrderedEqual[O], a) return fn } // OrderedGreater returns true if a is ordered greater than b. func OrderedGreater[O constraints.Ordered](a, b O) (orderedGreaterThan bool) { orderedGreaterThan = Ordered(a, b) == GreaterThan return orderedGreaterThan } // OrderedGreaterThan returns a function that returns true if its argument is ordered greater than a. func OrderedGreaterThan[O constraints.Ordered](a O) (fn Function[O, bool]) { fn = Curried[O, bool](OrderedGreater[O], a) return fn } // OrderedLess returns true if a is ordered less than b. func OrderedLess[O constraints.Ordered](a, b O) (orderedLess bool) { orderedLess = Ordered(a, b) == LessThan return orderedLess } // OrderedLessThan returns a function that returns true if its argument is ordered less than a. func OrderedLessThan[O constraints.Ordered](a O) (fn Function[O, bool]) { fn = Curried[O, bool](OrderedLess[O], a) return fn } // Max returns max value one or more constraints.Ordered values, func Max[T constraints.Ordered](v ...T) (max T) { if len(v) == 0 { panic(fmt.Errorf("%w: at leat one value required", IllegalArguments)) } max = v[0] for _, val := range v { if val > max { max = val } } return max } // Min returns min value of one or more constraints.Ordered values, func Min[T constraints.Ordered](v ...T) (min T) { if len(v) == 0 { panic(fmt.Errorf("%w: at leat one value required", IllegalArguments)) } min = v[0] for _, val := range v { if val < min { min = val } } return min } // StringerToString creates a ToString for any type that implements fmt.Stringer. func StringerToString[T fmt.Stringer]() (fn ToString[T]) { fn = func(t T) string { return t.String() } return fn } // TransformArgs uses the function to transform the arguments to be passed to the operation. func TransformArgs[T1, T2, R any](transform Function[T1, T2], operation BiFunction[T2, T2, R]) (fn BiFunction[T1, T1, R]) { fn = func(a, b T1) R { return operation(transform(a), transform(b)) } return fn } // Curried takes a BiFunction and one argument, and Curries the function to return a single argument Function. func Curried[A, R any](operation BiFunction[A, A, R], a A) (fn Function[A, R]) { fn = func(b A) R { return operation(b, a) } return fn } // Not takes a predicate returning and inverts the result. func Not[T any](predicate Function[T, bool]) (fn Function[T, bool]) { fn = func(a T) bool { return !predicate(a) } return fn } // Ordered performs old school -1/0/1 comparison of constraints.Ordered arguments. func Ordered[T constraints.Ordered](a, b T) (order int) { switch { case a < b: order = LessThan case a > b: order = GreaterThan default: order = EqualTo } return order }
dry.go
0.778186
0.673819
dry.go
starcoder
package main import ( . "github.com/9d77v/leetcode/pkg/algorithm/math" . "github.com/9d77v/leetcode/pkg/algorithm/unionfind" ) /* 题目:岛屿的最大面积 给定一个包含了一些 0 和 1 的非空二维数组 grid 。 一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。 找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。) 注意: 给定的矩阵grid 的长度和宽度都不超过 50。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/max-area-of-island */ /* 方法一:并查集(数组) 时间复杂度:О(nmlognm) 空间复杂度:О(nm) 运行时间:8 ms 内存消耗:5.6 MB */ func maxAreaOfIsland(grid [][]int) (result int) { n := len(grid) if n == 0 { return 0 } m := len(grid[0]) if m == 0 { return 0 } uf := NewUnionFind(m * n) for i := 0; i < n; i++ { for j := 0; j < m; j++ { if grid[i][j] == 1 { current, right, down := index(i, j, m), index(i, j+1, m), index(i+1, j, m) if j+1 < m && grid[i][j+1] == 1 { uf.Union(current, right) } if i+1 < n && grid[i+1][j] == 1 { uf.Union(current, down) } result = Max(result, uf.Rank(uf.Find(current))) } } } return } func index(i, j, m int) int { return i*m + j } /* 方法二:深度优先遍历 时间复杂度:О(nm) 空间复杂度:О(nm) 运行时间:8 ms 内存消耗:5.4 MB */ func maxAreaOfIslandFunc2(grid [][]int) (ans int) { n, m := len(grid), len(grid[0]) d := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} visited := make([][]bool, n) for i := range visited { visited[i] = make([]bool, m) } var dfs func(i, j int) (cnt int) dfs = func(i, j int) (cnt int) { visited[i][j] = true for _, v := range d { x, y := i+v[0], j+v[1] if x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == 1 && !visited[x][y] { cnt += dfs(x, y) } } return 1 + cnt } for i := range grid { for j := range grid[i] { if grid[i][j] == 1 && !visited[i][j] { ans = Max(ans, dfs(i, j)) } } } return } /* 方法二:深度优先遍历 时间复杂度:О(nm) 空间复杂度:О(nm) 运行时间:8 ms 内存消耗:5.4 MB */ func maxAreaOfIslandFunc2_1(grid [][]int) (ans int) { n, m := len(grid), len(grid[0]) d := [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}} var dfs func(i, j int) int dfs = func(i, j int) (cnt int) { if !(i >= 0 && i < n && j >= 0 && j < m) || grid[i][j] != 1 { return 0 } grid[i][j] = 2 for _, v := range d { cnt += dfs(i+v[0], j+v[1]) } return 1 + cnt } for i := range grid { for j := range grid[i] { if grid[i][j] == 1 { ans = Max(ans, dfs(i, j)) } } } return } /* 方法三:广度优先遍历 时间复杂度:О(nm) 空间复杂度:О(nm) 运行时间:12 ms 内存消耗:6.8 MB */ func maxAreaOfIslandFunc3(grid [][]int) (result int) { n := len(grid) if n == 0 { return 0 } m := len(grid[0]) if m == 0 { return 0 } var bfs func(i, j int) int bfs = func(i, j int) (count int) { arr := [][2]int{{i, j}} for len(arr) != 0 { a, b := arr[0][0], arr[0][1] arr = arr[1:] if a >= 0 && a < n && b >= 0 && b < m && grid[a][b] == 1 { count++ grid[a][b] = 0 arr = append(arr, [][2]int{{a - 1, b}, {a, b - 1}, {a + 1, b}, {a, b + 1}}...) } } return } for i := range grid { for j := range grid[0] { result = Max(result, bfs(i, j)) } } return }
internal/leetcode/695.max-area-of-island/main.go
0.536313
0.434881
main.go
starcoder
package gost import ( "errors" "net" ) var ( // ErrEmptyChain is an error that implies the chain is empty. ErrEmptyChain = errors.New("empty chain") ) // Chain is a proxy chain that holds a list of proxy nodes. type Chain struct { nodes []Node } // NewChain creates a proxy chain with proxy nodes nodes. func NewChain(nodes ...Node) *Chain { return &Chain{ nodes: nodes, } } // Nodes returns the proxy nodes that the chain holds. func (c *Chain) Nodes() []Node { return c.nodes } // LastNode returns the last node of the node list. // If the chain is empty, an empty node is returns. func (c *Chain) LastNode() Node { if c.IsEmpty() { return Node{} } return c.nodes[len(c.nodes)-1] } // AddNode appends the node(s) to the chain. func (c *Chain) AddNode(nodes ...Node) { if c == nil { return } c.nodes = append(c.nodes, nodes...) } // IsEmpty checks if the chain is empty. // An empty chain means that there is no proxy node in the chain. func (c *Chain) IsEmpty() bool { return c == nil || len(c.nodes) == 0 } // Dial connects to the target address addr through the chain. // If the chain is empty, it will use the net.Dial directly. func (c *Chain) Dial(addr string) (net.Conn, error) { if c.IsEmpty() { return net.Dial("tcp", addr) } conn, err := c.Conn() if err != nil { return nil, err } cc, err := c.LastNode().Client.Connect(conn, addr) if err != nil { conn.Close() return nil, err } return cc, nil } // Conn obtains a handshaked connection to the last node of the chain. // If the chain is empty, it returns an ErrEmptyChain error. func (c *Chain) Conn() (net.Conn, error) { if c.IsEmpty() { return nil, ErrEmptyChain } nodes := c.nodes conn, err := nodes[0].Client.Dial(nodes[0].Addr, nodes[0].DialOptions...) if err != nil { return nil, err } conn, err = nodes[0].Client.Handshake(conn, nodes[0].HandshakeOptions...) if err != nil { return nil, err } for i, node := range nodes { if i == len(nodes)-1 { break } next := nodes[i+1] cc, err := node.Client.Connect(conn, next.Addr) if err != nil { conn.Close() return nil, err } cc, err = next.Client.Handshake(cc, next.HandshakeOptions...) if err != nil { conn.Close() return nil, err } conn = cc } return conn, nil }
chain.go
0.643441
0.419767
chain.go
starcoder
package dmr // Data Type information element definitions, DMR Air Interface (AI) protocol, Table 6.1 const ( PrivacyIndicator uint8 = iota // Privacy Indicator information in a standalone burst VoiceLC // Indicates the beginning of voice transmission, carries addressing information TerminatorWithLC // Indicates the end of transmission, carries LC information CSBK // Carries a control block MultiBlockControl // Header for multi-block control MultiBlockControlContinuation // Follow-on blocks for multi-block control Data // Carries addressing and numbering of packet data blocks Rate12Data // Payload for rate 1/2 packet data Rate34Data // Payload for rate 3⁄4 packet data Idle // Fills channel when no info to transmit VoiceBurstA // Burst A marks the start of a superframe and always contains a voice SYNC pattern VoiceBurstB // Bursts B to F carry embedded signalling in place of the SYNC pattern VoiceBurstC // Bursts B to F carry embedded signalling in place of the SYNC pattern VoiceBurstD // Bursts B to F carry embedded signalling in place of the SYNC pattern VoiceBurstE // Bursts B to F carry embedded signalling in place of the SYNC pattern VoiceBurstF // Bursts B to F carry embedded signalling in place of the SYNC pattern IPSCSync UnknownSlotType ) var DataTypeName = map[uint8]string{ PrivacyIndicator: "privacy indicator", VoiceLC: "voice LC", TerminatorWithLC: "terminator with LC", CSBK: "control block", MultiBlockControl: "multi-block control", MultiBlockControlContinuation: "multi-block control follow-on", Data: "data", Rate12Data: "rate ½ packet data", Rate34Data: "rate ¾ packet data", Idle: "idle", VoiceBurstA: "voice (burst A)", VoiceBurstB: "voice (burst B)", VoiceBurstC: "voice (burst C)", VoiceBurstD: "voice (burst D)", VoiceBurstE: "voice (burst E)", VoiceBurstF: "voice (burst F)", IPSCSync: "IPSC sync", UnknownSlotType: "uknown", } // Call Type const ( CallTypeGroup uint8 = iota CallTypePrivate ) var CallTypeName = map[uint8]string{ CallTypeGroup: "group", CallTypePrivate: "private", } var CallTypeShortName = map[uint8]string{ CallTypeGroup: "TG", CallTypePrivate: "", } // Packet represents a frame transported by the Air Interface type Packet struct { // 0 for slot 1, 1 for slot 2 Timeslot uint8 // Starts at zero for each incoming transmission, wraps back to zero when 256 is reached Sequence uint8 // Source and destination DMR ID SrcID uint32 DstID uint32 // 3 bytes registered DMR-ID for public repeaters, 4 bytes for private repeaters RepeaterID uint32 // Random or incremented number which stays the same from PTT-press to PTT-release which identifies a stream StreamID uint32 // Data Type or Slot type DataType uint8 // 0 for group call, 1 for unit to unit CallType uint8 // BER ratio BER uint8 // RSSI level RSSI uint8 // The on-air DMR data with possible FEC fixes to the AMBE data and/or Slot Type and/or EMB, etc Data []byte // 34 bytes Bits []byte // 264 bits } // EMBBits returns the frame EMB bits from the SYNC bits func (p *Packet) EMBBits() []byte { var ( b = make([]byte, EMBBits) o = EMBHalfBits + EMBSignallingLCFragmentBits sync = p.SyncBits() ) copy(b[:EMBHalfBits], sync[:EMBHalfBits]) copy(b[EMBHalfBits:], sync[o:o+EMBHalfBits]) return b } // InfoBits returns the frame Info bits func (p *Packet) InfoBits() []byte { var b = make([]byte, InfoBits) copy(b[0:InfoHalfBits], p.Bits[0:InfoHalfBits]) copy(b[InfoHalfBits:], p.Bits[InfoHalfBits+SlotTypeBits+SignalBits:]) return b } // SyncBits returns the frame SYNC bits func (p *Packet) SyncBits() []byte { return p.Bits[SyncOffsetBits : SyncOffsetBits+SyncBits] } // SlotType returns the frame Slot Type parsed from the Slot Type bits func (p *Packet) SlotType() []byte { return BitsToBytes(p.SlotTypeBits()) } // SlotTypeBits returns the SloT Type bits func (p *Packet) SlotTypeBits() []byte { var o = InfoHalfBits + SlotTypeHalfBits + SyncBits return append(p.Bits[InfoHalfBits:InfoHalfBits+SlotTypeHalfBits], p.Bits[o:o+SlotTypeHalfBits]...) } // VoiceBits returns the bits containing voice data func (p *Packet) VoiceBits() []byte { var b = make([]byte, VoiceBits) copy(b[:VoiceHalfBits], p.Bits[:VoiceHalfBits]) copy(b[VoiceHalfBits:], p.Bits[VoiceHalfBits+SignalBits:]) return b } func (p *Packet) SetData(data []byte) { p.Data = data p.Bits = BytesToBits(data) } // PacketFunc is a callback function that handles DMR packets type PacketFunc func(Repeater, *Packet) error
packet.go
0.611846
0.54056
packet.go
starcoder
package geo import ( "math" "github.com/golang/geo/s1" "github.com/golang/geo/s2" ) const ( // According to Wikipedia, the Earth's radius is about 6,371km EARTH_RADIUS = 6371 ) // Geometry is a geometric shape that can be used to // verify whether Geo point is contained in there or not. type Geometry interface { Contains(latlng LatLng) bool CircleBound() (LatLng, float64) } type LatLng struct { Lat float64 Lng float64 } // GreatCircleDistance: Calculates the Haversine distance between two points in kilometers. // Original Implementation from: http://www.movable-type.co.uk/scripts/latlong.html func (p *LatLng) GreatCircleDistance(p2 *LatLng) float64 { dLat := (p2.Lat - p.Lat) * (math.Pi / 180.0) dLon := (p2.Lng - p.Lng) * (math.Pi / 180.0) lat1 := p.Lat * (math.Pi / 180.0) lat2 := p2.Lat * (math.Pi / 180.0) a1 := math.Sin(dLat/2) * math.Sin(dLat/2) a2 := math.Sin(dLon/2) * math.Sin(dLon/2) * math.Cos(lat1) * math.Cos(lat2) a := a1 + a2 c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) return EARTH_RADIUS * c } type Point struct { Type string Coordinates []float64 } func (p *Point) Contains(latlng LatLng) bool { return latlng.Lng == p.Coordinates[0] && latlng.Lat == p.Coordinates[1] } func (p *Point) CircleBound() (LatLng, float64) { return LatLng{Lng: p.Coordinates[0], Lat: p.Coordinates[1]}, 0 } // Polygon is representing a polygon // line structure. type Polygon struct { Type string coordinates [][][]float64 loop *s2.Loop } // NewPolygon creates a new polygon for the provided // coordinates. func NewPolygon(coordinates [][][]float64) *Polygon { points := make([]s2.Point, len(coordinates[0])) for i, coordinate := range coordinates[0] { points[len(coordinates[0])-1-i] = s2.PointFromLatLng(s2.LatLngFromDegrees(coordinate[1], coordinate[0])) } loop := s2.LoopFromPoints(points) return &Polygon{coordinates: coordinates, loop: loop} } // Contains checks whether the LatLng is contained in the // polygon. It returns true if the LatLng is contained in // the polygon and false otherwise. func (p *Polygon) Contains(latlng LatLng) bool { return p.loop.ContainsPoint(s2.PointFromLatLng(s2.LatLngFromDegrees(latlng.Lat, latlng.Lng))) } func (p *Polygon) CircleBound() (LatLng, float64) { points := make([]s2.Point, len(p.coordinates[0])) for i, coordinate := range p.coordinates[0] { points[len(p.coordinates[0])-1-i] = s2.PointFromLatLng(s2.LatLngFromDegrees(coordinate[1], coordinate[0])) } cap := s2.LoopFromPoints(points).CapBound() latlng := s2.LatLngFromPoint(cap.Center()) return LatLng{ Lng: latlng.Lng.Degrees(), Lat: latlng.Lat.Degrees(), }, float64(cap.Radius() * 6371000) } type Circle struct { Type string Radius float64 Coordinates []float64 } func (c *Circle) Contains(latlng LatLng) bool { earthRadius := float64(6371000) radiusAngle := s1.Angle(c.Radius / earthRadius) a := s2.PointFromLatLng(s2.LatLngFromDegrees(c.Coordinates[1], c.Coordinates[0])) b := s2.PointFromLatLng(s2.LatLngFromDegrees(latlng.Lat, latlng.Lng)) rd := s1.ChordAngleFromAngle(radiusAngle) cp := s2.CapFromCenterChordAngle(a, rd) return cp.ContainsPoint(b) } func (c *Circle) CircleBound() (LatLng, float64) { return LatLng{Lng: c.Coordinates[0], Lat: c.Coordinates[1]}, c.Radius } type Rectangle struct { Type string Coordinates [][]float64 } func (r *Rectangle) Contains(latlng LatLng) bool { rect := s2.RectFromLatLng(s2.LatLngFromDegrees(r.Coordinates[0][1], r.Coordinates[0][0])) for i := 1; i < len(r.Coordinates[0]); i++ { rect = rect.AddPoint(s2.LatLngFromDegrees(r.Coordinates[i][1], r.Coordinates[i][0])) } return rect.ContainsLatLng(s2.LatLngFromDegrees(latlng.Lat, latlng.Lng)) } func (r *Rectangle) CircleBound() (LatLng, float64) { rect := s2.RectFromLatLng(s2.LatLngFromDegrees(r.Coordinates[0][1], r.Coordinates[0][0])) for i := 1; i < len(r.Coordinates[0]); i++ { rect = rect.AddPoint(s2.LatLngFromDegrees(r.Coordinates[i][1], r.Coordinates[i][0])) } cap := rect.CapBound() latlng := s2.LatLngFromPoint(cap.Center()) return LatLng{ Lat: latlng.Lat.Degrees(), Lng: latlng.Lng.Degrees(), }, float64(cap.Radius() * 6371000) }
geo/geometry.go
0.885693
0.62641
geometry.go
starcoder
package filter import ( "gonum.org/v1/gonum/mat" ) // Filter is a dynamical system filter. type Filter interface { // Predict returns a prediction of which will be // next internal state Predict(x, u mat.Vector) (Estimate, error) // Update returns estimated system state based on external measurement ym. Update(x, u, ym mat.Vector) (Estimate, error) } // Propagator propagates internal state of the system to the next step type Propagator interface { // Propagate propagates internal state of the system to the next step. // x is starting state, u is input vector, and z is disturbance input Propagate(x, u, z mat.Vector) (mat.Vector, error) } // Observer observes external state (output) of the system type Observer interface { // Observe observes external state of the system. // Result for a linear system would be y=C*x+D*u+wn (last term is measurement noise) Observe(x, u, wn mat.Vector) (y mat.Vector, err error) } // Model is a model of a dynamical system type Model interface { // Propagator is system propagator Propagator // Observer is system observer Observer // SystemDims returns the dimension of state vector, input vector, // output (measurements, written as y) vector and disturbance vector (only dynamical systems). // Below are dimension of matrices as returned by SystemDims() (row,column) // nx, nx = A.SystemDims() // nx, nu = B.SystemDims() // ny, nx = C.SystemDims() // ny, nu = D.SystemDims() // nx, nz = E.SystemDims() SystemDims() (nx, nu, ny, nz int) } // Smoother is a filter smoother type Smoother interface { // Smooth implements filter smoothing and returns new estimates Smooth([]Estimate, []mat.Vector) ([]Estimate, error) } // DiscreteModel is a dynamical system whose state is driven by // static propagation and observation dynamics matrices type DiscreteModel interface { // Model is a model of a dynamical system Model // SystemMatrix returns state propagation matrix SystemMatrix() (A mat.Matrix) // ControlMatrix returns state propagation control matrix ControlMatrix() (B mat.Matrix) // OutputMatrix returns observation matrix OutputMatrix() (C mat.Matrix) // FeedForwardMatrix returns observation control matrix FeedForwardMatrix() (D mat.Matrix) // TODO DisturbanceMatrix } // InitCond is initial state condition of the filter type InitCond interface { // State returns initial filter state State() mat.Vector // Cov returns initial state covariance Cov() mat.Symmetric } // Estimate is dynamical system filter estimate type Estimate interface { // Val returns estimate value Val() mat.Vector // Cov returns estimate covariance Cov() mat.Symmetric } // Noise is dynamical system noise type Noise interface { // Mean returns noise mean Mean() []float64 // Cov returns covariance matrix of the noise Cov() mat.Symmetric // Sample returns a sample of the noise Sample() mat.Vector // Reset resets the noise Reset() }
filter.go
0.568536
0.587115
filter.go
starcoder
package math import "math" type Vector3 struct { X float64 Y float64 Z float64 } func (v *Vector3) Set( x, y, z float64) *Vector3{ v.X = x v.Y = y v.Z = z return v } func (v *Vector3) SetScalar( scalar float64 ) *Vector3 { v.X = scalar v.Y = scalar v.Z = scalar return v } func (v *Vector3) SetX( x float64 ) *Vector3 { v.X = x return v } func (v *Vector3) SetY( y float64 ) *Vector3 { v.Y = y return v } func (v *Vector3) SetZ( z float64 ) *Vector3 { v.Z = z return v } func (v *Vector3) SetComponent( index int, value float64 ) { switch index { case 0: v.X = value case 1: v.Y = value case 2: v.Z = value } } func (v *Vector3) GetComponent( index int ) float64 { switch index { case 0: return v.X case 1: return v.Y case 2: return v.Z } return 0.0 } func (v *Vector3) Clone() *Vector3 { v2 := &Vector3{ X:v.X, Y:v.Y, Z:v.Z } return v2 } func (v *Vector3) Copy( other *Vector3 ) *Vector3 { v.X = other.X v.Y = other.Y v.Z = other.Z return v } func (v *Vector3) Add( other *Vector3) *Vector3 { v.X += other.X v.Y += other.Y v.Z += other.Z return v } func (v *Vector3) AddScalar( scalar float64 ) *Vector3{ v.X += scalar v.Y += scalar v.Z += scalar return v } func (v *Vector3) AddVectors( a, b *Vector3 ) *Vector3 { v.X = a.X + b.X v.Y = a.Y + b.Y v.Z = a.Z + b.Z return v } func (v *Vector3) AddScaledVector( other *Vector3, scalar float64 ) *Vector3 { v.X += v.X * scalar v.Y += v.Y * scalar v.Z += v.Z * scalar return v } func (v *Vector3) Sub( other *Vector3) *Vector3 { v.X -= other.X v.Y -= other.Y v.Z -= other.Z return v } func (v *Vector3) SubScalar( scalar float64 ) *Vector3 { v.X -= scalar v.Y -= scalar v.Z -= scalar return v } func (v *Vector3) SubVectors( a, b *Vector3) *Vector3 { v.X = a.X - b.X v.Y = a.Y - b.Y v.Z = a.Z - b.Z return v } func (v *Vector3) Multiply( other *Vector3 ) *Vector3 { v.X *= other.X v.Y *= other.Y v.Z *= other.Z return v } func (v *Vector3) MultiplyScalar( scalar float64 ) *Vector3 { v.X *= scalar v.Y *= scalar v.Z *= scalar return v } func (v *Vector3) MultiplyVectors( a, b *Vector3 ) *Vector3 { v.X = a.X * b.X v.Y = a.Y * b.Y v.Z = a.Z * b.Z return v } func (v *Vector3) ApplyEuler() { // TODO After Quaternion } func (v *Vector3) ApplyAxisAngle() { // TODO After Quaternion } func (v *Vector3) ApplyMatrix3(m *Matrix3) *Vector3 { x := v.X y := v.Y z := v.Z e := m.Elements v.X = e[0] * x + e[3] * y + e[6] * z v.Y = e[1] * x + e[4] * y + e[7] * z v.Z = e[2] * x + e[5] * y + e[8] * z return v } func (v *Vector3) ApplyMatrix4() { // TODO After Matrix4 } func (v *Vector3) ApplyProjection() { // TODO After Matrix4 } func (v *Vector3) ApplyQuaternion() { // TODO After Quaternion } func (v *Vector3) Project() { // TODO After Matrix } func (v *Vector3) Unproject() { // TODO After Matrix } func (v *Vector3) TransformDirection() { // TODO After Matrix4 } func (v *Vector3) Divide( other *Vector3) *Vector3 { v.X /= other.X v.Y /= other.Y v.Z /= other.Z return v } func (v *Vector3) DivideScalar( scalar float64 ) *Vector3 { v.X /= scalar v.Y /= scalar v.Z /= scalar return v } func (v *Vector3) Min( other *Vector3 ) *Vector3 { v.X = math.Min( v.X, other.X ) v.Y = math.Min( v.Y, other.Y ) v.Z = math.Min( v.Z, other.Z ) return v } func (v *Vector3) Max( other *Vector3 ) *Vector3 { v.X = math.Max( v.X, other.X ) v.Y = math.Max( v.Y, other.Y ) v.Z = math.Max( v.Z, other.Z ) return v } func (v *Vector3) Clamp( min, max *Vector3 ) *Vector3 { v.X = math.Max( min.X, math.Min( max.X, v.X )) v.Y = math.Max( min.Y, math.Min( max.Y, v.Y )) v.Z = math.Max( min.Z, math.Min( max.Z, v.Z )) return v } func (v *Vector3) ClampLength( min, max float64 ) *Vector3 { length := v.Length() return v.MultiplyScalar( math.Max( min, math.Min( max, length ) ) / length ) } func (v *Vector3) Floor() *Vector3 { v.X = math.Floor( v.X ) v.Y = math.Floor( v.Y ) v.Z = math.Floor( v.Z ) return v } func (v *Vector3) Ceil() *Vector3 { v.X = math.Ceil( v.X ) v.Y = math.Ceil( v.Y ) v.Z = math.Ceil( v.Z ) return v } func (v *Vector3) Round() *Vector3 { v.X = math.Floor( v.X + .5 ) v.Y = math.Floor( v.Y + .5 ) v.Z = math.Floor( v.Z + .5 ) return v } func (v *Vector3) RoundToZero() *Vector3 { if v.X < 0 { v.X = math.Ceil( v.X ) } else { v.X = math.Floor( v.X ) } if v.Y < 0 { v.Y = math.Ceil( v.Y ) } else { v.Y = math.Floor( v.Y ) } if v.Z < 0 { v.Z = math.Ceil( v.Z ) } else { v.Z = math.Floor( v.Z ) } return v } func (v *Vector3) Negate() *Vector3 { v.X = - v.X v.Y = - v.Y v.Z = - v.Z return v } func (v *Vector3) Dot( other *Vector3) float64 { return v.X * other.X + v.Y * other.Y + v.Z * other.Z } func (v *Vector3) LengthSq() float64 { return v.X * v.X + v.Y * v.Y + v.Z * v.Z } func (v *Vector3) Length() float64 { return math.Sqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z) } func (v *Vector3) LengthManhattan() float64 { return math.Abs( v.X ) + math.Abs( v.Y ) + math.Abs( v.Z ) } func (v *Vector3) Normalize() *Vector3 { return v.DivideScalar( v.Length() ) } func (v *Vector3) SetLength( length float64 ) *Vector3 { orgLength := v.Length(); v.MultiplyScalar( length ) v.DivideScalar( orgLength ) return v } func (v *Vector3) Lerp( other *Vector3, alpha float64 ) *Vector3 { v.X += ( other.X - v.X ) * alpha v.Y += ( other.Y - v.Y ) * alpha v.Z += ( other.Z - v.Z ) * alpha return v } func (v *Vector3) LerpVectors( v1, v2 *Vector3, alpha float64 ) *Vector3 { return v.SubVectors( v2, v1).MultiplyScalar( alpha ).Add( v1 ) } func (v *Vector3) Cross( other *Vector3 ) *Vector3 { x := v.X y := v.Y z := v.Z v.X = y * v.Z - z * v.Y v.Y = z * v.X - x * v.Z v.Z = x * v.Y - y * v.X return v } func (v *Vector3) CrossVectors( a, b *Vector3 ) *Vector3 { ax := a.X ay := a.Y az := a.Z bx := b.X by := b.Y bz := b.Z v.X = ay * bz - az * by v.Y = az * bx - ax * bz v.Z = ax * by - ay * bx return v } func (v *Vector3) ProjectOnVector( vector *Vector3) *Vector3 { scalar := vector.Dot(v) / vector.LengthSq() return v.Copy(vector).MultiplyScalar(scalar) } func (v *Vector3) ProjectOnPlane( planeNormal *Vector3) *Vector3 { v1 := &Vector3{} v1.Copy( v ).ProjectOnVector( planeNormal ) return v.Sub( v1 ) } func (v *Vector3) Reflect( normal *Vector3 ) *Vector3 { v1 := &Vector3{} return v.Sub( v1.Copy( normal ).MultiplyScalar( 2 * v.Dot( normal) ) ) } func (v *Vector3) AngleTo( other *Vector3) float64 { theta := v.Dot(other) / ( math.Sqrt( v.LengthSq() * other.LengthSq() ) ) return math.Acos( Clamp( theta, -1, 1 ) ) } func (v *Vector3) DistanceTo( other *Vector3 ) float64 { return math.Sqrt( v.DistanceToSquared(other) ) } func (v *Vector3) DistanceToSquared( other *Vector3 ) float64 { dx := v.X - other.X dy := v.Y - other.Y dz := v.Z - other.Z return dx * dx + dy * dy + dz * dz } func (v *Vector3) SetFromSpherical() { // TODO After Spherical } func (v *Vector3) SetFromMatrixPosition() { // TODO After Matrix } func (v *Vector3) SetFromMatrixScale() { // TODO After Matrix } func (v *Vector3) SetFromMatrixColumn() { } func (v *Vector3) Equals( other *Vector3 ) bool { return ( ( v.X == other.X ) && ( v.Y == other.Y ) && ( v.Z == other.Z ) ) } func (v *Vector3) FromArray( array []float64 ) *Vector3 { v.X = array[0] v.Y = array[1] v.X = array[2] return v } func (v *Vector3) ToArray( array []float64 ) []float64 { array[0] = v.X array[1] = v.Y array[2] = v.Z return array } func (v *Vector3) FromAttribute() { // TODO After Attribute }
math/vector3.go
0.703244
0.725065
vector3.go
starcoder
package model import ( "fmt" "strings" "time" "k8s.io/heapster/store/daystore" "k8s.io/heapster/store/statstore" ) // latestTimestamp returns its largest time.Time argument func latestTimestamp(first time.Time, second time.Time) time.Time { if first.After(second) { return first } return second } // newInfoType is an InfoType Constructor, which returns a new InfoType. // Initial fields for the new InfoType can be provided as arguments. // A nil argument results in a newly-allocated map for that field. func newInfoType(metrics map[string]*daystore.DayStore, labels map[string]string, context map[string]*statstore.TimePoint) InfoType { if metrics == nil { metrics = make(map[string]*daystore.DayStore) } if labels == nil { labels = make(map[string]string) } if context == nil { context = make(map[string]*statstore.TimePoint) } return InfoType{ Creation: time.Time{}, Metrics: metrics, Labels: labels, Context: context, } } // addContainerToMap creates or finds a ContainerInfo element under a map[string]*ContainerInfo func addContainerToMap(container_name string, dict map[string]*ContainerInfo) *ContainerInfo { var container_ptr *ContainerInfo if val, ok := dict[container_name]; ok { // A container already exists under that name, return the address container_ptr = val } else { container_ptr = &ContainerInfo{ InfoType: newInfoType(nil, nil, nil), } dict[container_name] = container_ptr } return container_ptr } // addTimePoints adds the values of two TimePoints as uint64. // addTimePoints returns a new TimePoint with the added Value fields // and the Timestamp of the first TimePoint. func addTimePoints(tp1 statstore.TimePoint, tp2 statstore.TimePoint) statstore.TimePoint { maxTS := tp1.Timestamp if maxTS.Before(tp2.Timestamp) { maxTS = tp2.Timestamp } return statstore.TimePoint{ Timestamp: maxTS, Value: tp1.Value + tp2.Value, } } // popTPSlice pops the first element of a TimePoint Slice, removing it from the slice. // popTPSlice receives a *[]TimePoint and returns its first element. func popTPSlice(tps_ptr *[]statstore.TimePoint) *statstore.TimePoint { if tps_ptr == nil { return nil } tps := *tps_ptr if len(tps) == 0 { return nil } res := tps[0] if len(tps) == 1 { (*tps_ptr) = tps[0:0] } (*tps_ptr) = tps[1:] return &res } // addMatchingTimeseries performs addition over two timeseries with unique timestamps. // addMatchingTimeseries returns a []TimePoint of the resulting aggregated timeseries. // Assumes time-descending order of both []TimePoint parameters and the return slice. func addMatchingTimeseries(left []statstore.TimePoint, right []statstore.TimePoint) []statstore.TimePoint { var cur_left *statstore.TimePoint var cur_right *statstore.TimePoint result := []statstore.TimePoint{} // Merge timeseries into result until either one is empty cur_left = popTPSlice(&left) cur_right = popTPSlice(&right) for cur_left != nil && cur_right != nil { result = append(result, addTimePoints(*cur_left, *cur_right)) if cur_left.Timestamp.Equal(cur_right.Timestamp) { cur_left = popTPSlice(&left) cur_right = popTPSlice(&right) } else if cur_left.Timestamp.After(cur_right.Timestamp) { cur_left = popTPSlice(&left) } else { cur_right = popTPSlice(&right) } } if cur_left == nil && cur_right != nil { result = append(result, *cur_right) } else if cur_left != nil && cur_right == nil { result = append(result, *cur_left) } // Append leftover elements from non-empty timeseries if len(left) > 0 { result = append(result, left...) } else if len(right) > 0 { result = append(result, right...) } return result } // instantFromCumulativeMetric calculates the value of an instantaneous metric from two // points of a cumulative metric, such as cpu/usage. // The inputs are the value and timestamp of the newer cumulative datapoint, // and a pointer to a TimePoint holding the previous cumulative datapoint. func instantFromCumulativeMetric(value uint64, stamp time.Time, prev *statstore.TimePoint) (uint64, error) { if prev == nil { return uint64(0), fmt.Errorf("unable to calculate instant metric with nil previous TimePoint") } if !stamp.After(prev.Timestamp) { return uint64(0), fmt.Errorf("the previous TimePoint is not earlier in time than the newer one") } tdelta := uint64(stamp.Sub(prev.Timestamp).Nanoseconds()) // Divide metric by nanoseconds that have elapsed, multiply by 1000 to get an unsigned metric if value < prev.Value { return uint64(0), fmt.Errorf("the provided value %d is less than the previous one %d", value, prev.Value) } // Divide metric by nanoseconds that have elapsed, multiply by 1000 to get an unsigned metric vdelta := (value - prev.Value) * 1000 instaVal := vdelta / tdelta prev.Value = value prev.Timestamp = stamp return instaVal, nil } // getStats extracts derived stats from an InfoType and their timestamp. func getStats(info InfoType) (map[string]StatBundle, time.Time) { res := make(map[string]StatBundle) var timestamp time.Time for key, ds := range info.Metrics { last, lastMax, _ := ds.Hour.Last() timestamp = last.Timestamp minAvg := last.Value minPct := lastMax minMax := lastMax hourAvg, _ := ds.Hour.Average() hourPct, _ := ds.Hour.Percentile(0.95) hourMax, _ := ds.Hour.Max() dayAvg, _ := ds.Average() dayPct, _ := ds.NinetyFifth() dayMax, _ := ds.Max() res[key] = StatBundle{ Minute: Stats{ Average: minAvg, NinetyFifth: minPct, Max: minMax, }, Hour: Stats{ Average: hourAvg, NinetyFifth: hourPct, Max: hourMax, }, Day: Stats{ Average: dayAvg, NinetyFifth: dayPct, Max: dayMax, }, } } return res, timestamp } func epsilonFromMetric(metric string) uint64 { switch metric { case cpuLimit: return cpuLimitEpsilon case cpuUsage: return cpuUsageEpsilon case memLimit: return memLimitEpsilon case memUsage: return memUsageEpsilon case memWorking: return memWorkingEpsilon default: if strings.Contains(metric, fsLimit) { return fsLimitEpsilon } if strings.Contains(metric, fsUsage) { return fsUsageEpsilon } return defaultEpsilon } }
vendor/k8s.io/heapster/model/util.go
0.784195
0.416322
util.go
starcoder
package timing import ( "github.com/knieriem/can" ) const ( tq = 1 minPhSeg2 = 2 * tq maxPhSeg2 = 8 * tq maxPhSeg1 = 8 * tq maxTSeg1 = maxProp + maxPhSeg1 maxProp = 8 * tq syncSeg = 1 * tq ) // Calculate a CANopen bit timing for a given oscillator frequency // and the desired bitrate. func CanOpen(fOsc, bitRate uint32) (*BitTiming, error) { return FitSamplePoint(fOsc, bitRate, .875, 1) } // Calculate a bit timing with a desired location of the // sample point for the given oscillator frequency and bitrate. func FitSamplePoint(fOsc, bitRate uint32, spLoc float32, maxSJW uint) (t *BitTiming, err error) { var minErrLoc = 1 << 16 var bestTiming BitTiming for preSc := uint32(1); preSc < 64; preSc++ { nq := int(fOsc / bitRate / preSc) if fOsc/bitRate%preSc != 0 { continue } if nq <= 0 { break } if nq > 25 { continue } ps2 := calcPhSeg2BySampleLoc(nq, spLoc) again: // compute a tseg1 tseg1 := nq - ps2 - syncSeg if tseg1 > maxTSeg1 { if ps2 >= maxPhSeg2 { continue } ps2++ goto again } // we need at least 1tq for each of propSeg and phSeg1 if tseg1 < 2 { break } // split tseg1, start with phSeg1 one less than phSeg2 prop, ps1 := splitTSeg1(tseg1, ps2-1) if ps1 > maxPhSeg1 { // should never be true continue } errLoc := abs((1+int(tseg1))*1000/int(nq) - int(spLoc*1000)) if errLoc > minErrLoc { continue } minErrLoc = errLoc bestTiming = BitTiming{ Prescaler: uint(preSc), PhaseSeg1: uint(ps1), PhaseSeg2: uint(ps2), PropSeg: uint(prop), } } if bestTiming.PhaseSeg2 == 0 { err = can.Error("unable to calculate a bit timing") } else { t = &bestTiming sjw := t.PhaseSeg1 if sjw > 4 { sjw = 4 } if sjw > maxSJW { sjw = maxSJW } t.SJW = sjw t.Clock = fOsc } return } func abs(v int) int { if v < 0 { return -v } return v } func splitTSeg1(tseg1, ps1start int) (prop, ps1 int) { ps1 = ps1start // propSeg gets the remaining tqs prop = tseg1 - ps1 // adjust prop, if it is negative or zero for prop <= 0 { ps1-- prop++ } // adjust prop, if it is too large to be programmable for prop > maxProp { prop-- ps1++ } return } func calcPhSeg2BySampleLoc(nq int, spLoc float32) (ps2 int) { ps2 = int((1-spLoc)*float32(nq) + .5) if ps2 < minPhSeg2 { ps2 = minPhSeg2 } if ps2 > maxPhSeg2 { ps2 = maxPhSeg2 } return } func oscTol(sjw, prop, ps1, ps2 int) int { minPh := ps1 if ps2 < ps1 { minPh = ps2 } nq := 1 + prop + ps1 + ps2 cond1 := 1e6 * minPh / 2 / (13*nq - ps2) cond2 := 1e6 * sjw / (20 * nq) if cond1 < cond2 { return cond1 } return cond2 }
timing/calc.go
0.623033
0.426979
calc.go
starcoder
package download_tracker import ( "container/list" "time" "github.com/patrickmn/go-cache" "github.com/turt2live/matrix-media-repo/util" ) /* * The download tracker works by keeping a limited number of buckets for each media record * in an expiring cache. The number of buckets is the equal to the number of minutes to track * downloads for (max age). The entire download history expires after the max age so long * as it is not added to. * * The underlying data structure is a linked list of buckets (which are just a timestamp and * number of downloads). A linked list was chosen for it's capability to easily append and * remove items without having to do array slicing. Buckets were chosen to limit the number * of entries in the list because the total downloads are calculated through iteration. If * each calculation had to iterate over thousands of items, the execution would be slow. A * smaller number, like 30, is a lot more manageable. */ type DownloadTracker struct { cache *cache.Cache maxAge int64 } type mediaRecord struct { buckets *list.List downloads int } type bucket struct { ts int64 downloads int } func New(maxAgeMinutes int) (*DownloadTracker) { maxAge := time.Duration(maxAgeMinutes) * time.Minute return &DownloadTracker{ cache: cache.New(maxAge, maxAge*2), maxAge: int64(maxAgeMinutes), } } func (d *DownloadTracker) Reset() { d.cache.Flush() } func (d *DownloadTracker) NumDownloads(recordId string) (int) { item, found := d.cache.Get(recordId) if !found { return 0 } return d.recountDownloads(item.(*mediaRecord), recordId) } func (d *DownloadTracker) Increment(recordId string) (int) { item, found := d.cache.Get(recordId) var record *mediaRecord if !found { record = &mediaRecord{buckets: list.New()} } else { record = item.(*mediaRecord) } bucketTs := util.NowMillis() / 60000 // minutes if record.buckets.Len() <= 0 { // First bucket record.buckets.PushFront(&bucket{ ts: bucketTs, downloads: 1, }) } else { firstRecord := record.buckets.Front().Value.(*bucket) if firstRecord.ts != bucketTs { record.buckets.PushFront(&bucket{ ts: bucketTs, downloads: 1, }) } else { firstRecord.downloads++ } } return d.recountDownloads(record, recordId) } func (d *DownloadTracker) recountDownloads(record *mediaRecord, recordId string) int { currentBucketTs := util.NowMillis() / 60000 // minutes changed := false // Trim off anything that is too old for e := record.buckets.Back(); e != nil; e = record.buckets.Back() { b := e.Value.(*bucket) if (currentBucketTs - b.ts) > d.maxAge { changed = true record.buckets.Remove(e) } else { break // count is still relevant } } // Count the number of downloads downloads := 0 for e := record.buckets.Front(); e != nil; e = e.Next() { b := e.Value.(*bucket) downloads += b.downloads } if changed || downloads != record.downloads { record.downloads = downloads d.cache.Set(recordId, record, cache.DefaultExpiration) } return downloads }
src/github.com/turt2live/matrix-media-repo/util/download_tracker/tracker.go
0.658966
0.415373
tracker.go
starcoder
package v1alpha1 import ( "strings" "golang.org/x/xerrors" ) // Node represents a Task in a pipeline. type Node struct { // Task represent the PipelineTask in Pipeline Task PipelineTask // Prev represent all the Previous task Nodes for the current Task Prev []*Node // Next represent all the Next task Nodes for the current Task Next []*Node } // DAG represents the Pipeline DAG type DAG struct { //Nodes represent map of PipelineTask name to Node in Pipeline DAG Nodes map[string]*Node } // Returns an empty Pipeline DAG func newDAG() *DAG { return &DAG{Nodes: map[string]*Node{}} } func (g *DAG) addPipelineTask(t PipelineTask) (*Node, error) { if _, ok := g.Nodes[t.Name]; ok { return nil, xerrors.New("duplicate pipeline task") } newNode := &Node{ Task: t, } g.Nodes[t.Name] = newNode return newNode, nil } func linkPipelineTasks(prev *Node, next *Node) error { // Check for self cycle if prev.Task.Name == next.Task.Name { return xerrors.Errorf("cycle detected; task %q depends on itself", next.Task.Name) } // Check if we are adding cycles. visited := map[string]bool{prev.Task.Name: true, next.Task.Name: true} path := []string{next.Task.Name, prev.Task.Name} if err := visit(next.Task.Name, prev.Prev, path, visited); err != nil { return xerrors.Errorf("cycle detected: %w", err) } next.Prev = append(next.Prev, prev) prev.Next = append(prev.Next, next) return nil } func visit(currentName string, nodes []*Node, path []string, visited map[string]bool) error { for _, n := range nodes { path = append(path, n.Task.Name) if _, ok := visited[n.Task.Name]; ok { return xerrors.New(getVisitedPath(path)) } visited[currentName+"."+n.Task.Name] = true if err := visit(n.Task.Name, n.Prev, path, visited); err != nil { return err } } return nil } func getVisitedPath(path []string) string { // Reverse the path since we traversed the DAG using prev pointers. for i := len(path)/2 - 1; i >= 0; i-- { opp := len(path) - 1 - i path[i], path[opp] = path[opp], path[i] } return strings.Join(path, " -> ") } func addLink(pt PipelineTask, previousTask string, nodes map[string]*Node) error { prev, ok := nodes[previousTask] if !ok { return xerrors.Errorf("Task %s depends on %s but %s wasn't present in Pipeline", pt.Name, previousTask, previousTask) } next := nodes[pt.Name] if err := linkPipelineTasks(prev, next); err != nil { return xerrors.Errorf("Couldn't create link from %s to %s: %w", prev.Task.Name, next.Task.Name, err) } return nil } // BuildDAG returns a valid pipeline DAG. Returns error if the pipeline is invalid func BuildDAG(tasks []PipelineTask) (*DAG, error) { d := newDAG() // Add all Tasks mentioned in the `PipelineSpec` for _, pt := range tasks { if _, err := d.addPipelineTask(pt); err != nil { return nil, xerrors.Errorf("task %s is already present in DAG, can't add it again: %w", pt.Name, err) } } // Process all from and runAfter constraints to add task dependency for _, pt := range tasks { for _, previousTask := range pt.RunAfter { if err := addLink(pt, previousTask, d.Nodes); err != nil { return nil, xerrors.Errorf("couldn't add link between %s and %s: %w", pt.Name, previousTask, err) } } if pt.Resources != nil { for _, rd := range pt.Resources.Inputs { for _, previousTask := range rd.From { if err := addLink(pt, previousTask, d.Nodes); err != nil { return nil, xerrors.Errorf("couldn't add link between %s and %s: %w", pt.Name, previousTask, err) } } } } } return d, nil }
vendor/github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1/dag.go
0.610802
0.40031
dag.go
starcoder
package example // Adapted from: tour.golang.org import ( "fmt" ) func printSlice(action string, s []int) { // len() is the number of elements in the slice while cap() is the max size of the underlying array fmt.Printf("len=%d cap=%d %v - %s\n", len(s), cap(s), s, action) } func ranges() { // Dropping the elements of an array from the start of the array via the slice will mean those values are garbage collected from the array but if you reduce a slice from the end while they won't be in that current slice they will still be in the underlying array for later use. Meaning the below is shrinking the overall capacity of the underlying array by "dropping" elements from the beginning of the array via a slice but not from the end of the array/slice. s := []int{2, 3, 5, 7, 11, 13} printSlice("All values", s) s = s[:0] printSlice("Slice the slice to give it zero length", s) s = s[:4] printSlice("Extend its length", s) s = s[2:] printSlice("Drop its first two values reducing the capacity of the array", s) s = s[:] printSlice("Simply means all elements in the current slice", s) s = s[0:4] printSlice("Extends it length", s) s = s[:2] printSlice("Reduces the length by 2", s) s = s[1 : len(s)-1] printSlice("Drops the first element and reduces the last element", s) s = s[:3] printSlice("Extends it's length to all remaining items in the array", s) } func arrays() { // This is an array literal. The type of this array is [3]bool meaning the size is apart of this arrays type. array := [3]bool{true, true, false} fmt.Printf("type=%T value=%v\n", array, array[2]) // And this creates the same array as above and then builds a slice that references it. // The underlying array will be like the above, the same type, but the slice on top means the size doesn't have to be defined. slice := []bool{true, true, false} fmt.Printf("type=%T value=%v\n", slice, slice[2]) } func appending() { a := [6]struct { i int b bool }{ {2, true}, {3, false}, {5, true}, {7, true}, {11, false}, {13, true}, } fmt.Println(a) // This will append the elements 0-1 and 3-5 together into a slice, i.e. skipping the second element. s := append(a[:2], a[2+1:]...) fmt.Println(s) } func structs() { // Creates a struct and sets it at the same time. This is good for when the struct only needs to be used in the one place. s := []struct { i int b bool }{ {2, true}, {3, false}, {5, true}, {7, true}, {11, false}, {13, true}, } fmt.Println(s) s = s[1:] fmt.Println(s) s = s[:2] fmt.Println(s) } func init() { examples := runs{ {"Appending with slices", appending}, {"Arrays", arrays}, {"Arrays & slices with custom types", structs}, {"Ranges with slices ", ranges}, } GetMyExamples().Add("arrays", examples.runExamples) }
chase/internal/pkg/example/arrays_slices.go
0.656218
0.644952
arrays_slices.go
starcoder
package clocks import ( "bytes" "image/color" "log" "math" "time" "github.com/fogleman/gg" "github.com/golang/freetype/truetype" "golang.org/x/image/bmp" "golang.org/x/image/font/gofont/goregular" ) var ( colorTicks color.Color = color.RGBA{R: 0x80, G: 0x80, B: 0x80, A: 0xFF} colorArHour color.Color = color.RGBA{R: 0x40, G: 0x40, B: 0x80, A: 0xFF} colorArMinute color.Color = color.RGBA{R: 0x40, G: 0x40, B: 0x80, A: 0xFF} colorArSecond color.Color = color.RGBA{R: 0xff, G: 0x00, B: 0x00, A: 0xFF} tickLength float64 = 15 ) // GenerateAnalog generates a nice clock bmp func GenerateAnalog(timeToRender time.Time, width int, height int, showseconds bool, showDate bool, fontsize int, dateformat string) []byte { edgeSize := height if width < height { edgeSize = width } dc := gg.NewContext(edgeSize, edgeSize) halfWidth := float64(edgeSize / 2) halfHeight := float64(edgeSize / 2) floatEdgeSize := float64(edgeSize) myTicklength := tickLength * floatEdgeSize / float64(ClockImageHeight) smallClock := edgeSize < 100 if showDate { font, err := truetype.Parse(goregular.TTF) if err != nil { log.Fatal(err) } face := truetype.NewFace(font, &truetype.Options{Size: float64(fontsize)}) dc.SetFontFace(face) dc.SetColor(colorArSecond) dc.SetLineWidth(2.0) dateStr := timeToRender.Format(dateformat) dc.DrawStringAnchored(dateStr, halfWidth, halfHeight/2.0, 0.5, 0.5) dc.Stroke() } dc.SetColor(colorTicks) dc.InvertY() // Stundenticks dc.SetLineWidth(1) if !smallClock { dc.DrawCircle(halfWidth, halfHeight, halfHeight-1) } dc.MoveTo(halfWidth-1, floatEdgeSize) dc.LineTo(halfWidth-1, floatEdgeSize-myTicklength) for i := 0; i < 12; i++ { deg := float64(30.0 * i) dc.MoveTo(halfWidth+(math.Sin(deg2Rad(deg))*(halfWidth-myTicklength)), halfHeight+(math.Cos(deg2Rad(deg))*(halfHeight-myTicklength))) dc.LineTo(halfWidth+(math.Sin(deg2Rad(deg))*(halfWidth-1)), halfHeight+(math.Cos(deg2Rad(deg))*(halfHeight-1))) } dc.Stroke() // Viertelstunden ticks if smallClock { dc.SetLineWidth(2.0) } else { dc.SetLineWidth(4.0) } // dc.MoveTo(halfWidth-1, floatEdgeSize) dc.LineTo(halfWidth-1, floatEdgeSize-myTicklength) dc.MoveTo(halfWidth-1, 0) dc.LineTo(halfWidth-1, myTicklength) dc.MoveTo(0, halfHeight-1) dc.LineTo(myTicklength, halfHeight-1) dc.MoveTo(floatEdgeSize-myTicklength, halfHeight-1) dc.LineTo(floatEdgeSize, halfHeight-1) dc.Stroke() // Sekundezeiger if showseconds { dc.SetColor(colorArSecond) if smallClock { dc.SetLineWidth(0.2) } else { dc.SetLineWidth(1.0) } seconds := timeToRender.Second() deg := float64(6.0 * seconds) dc.MoveTo(halfWidth-(math.Sin(deg2Rad(deg))*10), halfHeight-(math.Cos(deg2Rad(deg))*10)) dc.LineTo(halfWidth+(math.Sin(deg2Rad(deg))*(halfWidth-2)), halfHeight+(math.Cos(deg2Rad(deg))*(halfHeight-2))) dc.Stroke() } // Minutenzeiger dc.SetColor(colorArMinute) if smallClock { dc.SetLineWidth(0.8) } else { dc.SetLineWidth(3.0) } minute := timeToRender.Minute() deg := float64(6.0 * minute) dc.MoveTo(halfWidth-(math.Sin(deg2Rad(deg))*2), halfHeight-(math.Cos(deg2Rad(deg))*2)) dc.LineTo(halfWidth+(math.Sin(deg2Rad(deg))*(halfWidth-10)), halfHeight+(math.Cos(deg2Rad(deg))*(halfHeight-10))) dc.Stroke() // StundenZeiger dc.SetColor(colorArHour) if smallClock { dc.SetLineWidth(3.0) } else { dc.SetLineWidth(6.0) } hour := timeToRender.Hour() deg = float64(30.0*hour + (minute / 2)) dc.MoveTo(halfWidth-(math.Sin(deg2Rad(deg))*2), halfHeight-(math.Cos(deg2Rad(deg))*2)) dc.LineTo(halfWidth+(math.Sin(deg2Rad(deg))*(halfWidth*1/2)), halfHeight+(math.Cos(deg2Rad(deg))*(halfHeight*1/2))) dc.Stroke() myImage := dc.Image() var buff bytes.Buffer // The Buffer satisfies the Writer interface so we can use it with Encode // In previous example we encoded to a file, this time to a temp buffer //png.Encode(&buff, myImage) bmp.Encode(&buff, myImage) return buff.Bytes() } func deg2Rad(deg float64) float64 { return deg * (math.Pi / 180.0) } func rad2Deg(rad float64) float64 { return rad * (180.0 / math.Pi) }
service/pac/clocks/analog.go
0.614047
0.403773
analog.go
starcoder
package reflect import "unsafe" // Len returns v's length. func (v MapValue) Len() int { return maplen(v.pointer()) } // MapIndex returns the value associated with key in the map v. // It returns the zero Value if key is not found in the map or if v represents a nil map. // As in Go, the key's value must be assignable to the map's key type. func (v MapValue) MapIndex(key Value) Value { mapType := v.Type.ConvToMap() // Do not require key to be exported, so that DeepEqual and other programs can use all the keys returned by MapKeys as arguments to MapIndex. If either the map or the key is unexported, though, the result will be considered unexported. // This is consistent with the behavior for structs, which allow read but not write of unexported fields. key = key.assignTo(mapType.KeyType, nil) var keyPtr unsafe.Pointer if key.isPointer() { keyPtr = key.Ptr } else { keyPtr = unsafe.Pointer(&key.Ptr) } elemPtr := mapaccess(v.Type, v.pointer(), keyPtr) if elemPtr == nil { // we could return nil, but deep equal will panic return Value{} } mapElemType := mapType.ElemType fl := v.ro() | key.ro() fl |= Flag(mapElemType.Kind()) if !mapElemType.isDirectIface() { return Value{Type: mapElemType, Ptr: convPtr(elemPtr), Flag: fl} } // Copy result so future changes to the map won't change the underlying value. mapElemValue := unsafeNew(mapElemType) typedmemmove(mapElemType, mapElemValue, elemPtr) return Value{Type: mapElemType, Ptr: mapElemValue, Flag: fl | pointerFlag} } // MapKeys returns a slice containing all the keys present in the map, in unspecified order. // It returns an empty slice if v represents a nil map. func (v MapValue) MapKeys() []Value { mapType := v.Type.ConvToMap() keyType := mapType.KeyType fl := v.ro() | Flag(keyType.Kind()) mapPtr := v.pointer() mapLen := int(0) if mapPtr != nil { mapLen = maplen(mapPtr) } it := mapiterinit(v.Type, mapPtr) result := make([]Value, mapLen) var i int for i = 0; i < len(result); i++ { key := mapiterkey(it) if key == nil { // Someone deleted an entry from the map since we called maplen above. It's a data race, but nothing we can do about it. break } if keyType.isDirectIface() { // Copy result so future changes to the map won't change the underlying value. keyValue := unsafeNew(keyType) typedmemmove(keyType, keyValue, key) result[i] = Value{Type: keyType, Ptr: keyValue, Flag: fl | pointerFlag} } else { result[i] = Value{Type: keyType, Ptr: convPtr(key), Flag: fl} } mapiternext(it) } return result[:i] } // SetMapIndex sets the value associated with key in the map v to val. // If val is the zero Value, SetMapIndex deletes the key from the map. // Otherwise if v holds a nil map, SetMapIndex will panic. // As in Go, key's value must be assignable to the map's key type, and val's value must be assignable to the map's value type. func (v MapValue) SetMapIndex(key, value Value) { if !v.IsValid() || !v.isExported() { if willPrintDebug { println("reflect.MapValue.SetMapIndex: map must be exported") } return } if !key.IsValid() || !key.isExported() { if willPrintDebug { println("reflect.MapValue.SetMapIndex: key must be exported") } return } mapType := v.Type.ConvToMap() key = key.assignTo(mapType.KeyType, nil) var keyPtr unsafe.Pointer if key.isPointer() { keyPtr = key.Ptr } else { keyPtr = unsafe.Pointer(&key.Ptr) } if value.Type == nil { // this allows us to delete from map, when setting key to nil value mapdelete(v.Type, v.pointer(), keyPtr) return } // now we check the value too - we don't check this earlier, because delete operations if !value.IsValid() || !value.isExported() { return } value = value.assignTo(mapType.ElemType, nil) var elemPtr unsafe.Pointer if value.isPointer() { elemPtr = value.Ptr } else { elemPtr = unsafe.Pointer(&value.Ptr) } mapassign(v.Type, v.pointer(), keyPtr, elemPtr) }
reflect_map_value.go
0.734881
0.459501
reflect_map_value.go
starcoder
package main import ( "github.com/gen2brain/raylib-go/physics" "github.com/gen2brain/raylib-go/raylib" ) const ( velocity = 0.5 ) func main() { screenWidth := float32(800) screenHeight := float32(450) raylib.SetConfigFlags(raylib.FlagMsaa4xHint) raylib.InitWindow(int32(screenWidth), int32(screenHeight), "Physac [raylib] - body shatter") // Physac logo drawing position logoX := int32(screenWidth) - raylib.MeasureText("Physac", 30) - 10 logoY := int32(15) // Initialize physics and default physics bodies physics.Init() physics.SetGravity(0, 0) // Create random polygon physics body to shatter physics.NewBodyPolygon(raylib.NewVector2(screenWidth/2, screenHeight/2), float32(raylib.GetRandomValue(80, 200)), int(raylib.GetRandomValue(3, 8)), 10) raylib.SetTargetFPS(60) for !raylib.WindowShouldClose() { // Update created physics objects physics.Update() if raylib.IsKeyPressed(raylib.KeyR) { // Reset physics input physics.Reset() // Create random polygon physics body to shatter physics.NewBodyPolygon(raylib.NewVector2(screenWidth/2, screenHeight/2), float32(raylib.GetRandomValue(80, 200)), int(raylib.GetRandomValue(3, 8)), 10) } if raylib.IsMouseButtonPressed(raylib.MouseLeftButton) { for _, b := range physics.GetBodies() { b.Shatter(raylib.GetMousePosition(), 10/b.InverseMass) } } raylib.BeginDrawing() raylib.ClearBackground(raylib.Black) // Draw created physics bodies for i, body := range physics.GetBodies() { vertexCount := physics.GetShapeVerticesCount(i) for j := 0; j < vertexCount; j++ { // Get physics bodies shape vertices to draw lines // NOTE: GetShapeVertex() already calculates rotation transformations vertexA := body.GetShapeVertex(j) jj := 0 if j+1 < vertexCount { // Get next vertex or first to close the shape jj = j + 1 } vertexB := body.GetShapeVertex(jj) raylib.DrawLineV(vertexA, vertexB, raylib.Green) // Draw a line between two vertex positions } } raylib.DrawText("Left mouse button in polygon area to shatter body\nPress 'R' to reset example", 10, 10, 10, raylib.White) raylib.DrawText("Physac", logoX, logoY, 30, raylib.White) raylib.DrawText("Powered by", logoX+50, logoY-7, 10, raylib.White) raylib.EndDrawing() } physics.Close() // Unitialize physics raylib.CloseWindow() }
examples/physics/physac/shatter/main.go
0.629661
0.403537
main.go
starcoder
package darts import ( "fmt" "github.com/sbinet/npyio/npz" "gonum.org/v1/gonum/mat" "math" ) type actFunc func(i, j int, v float64) float64 //DenseNet is a dense net type DenseNet struct { w mat.Matrix b mat.Vector active actFunc } //Sigmoid a active function func Sigmoid(r, c int, z float64) float64 { return 1.0 / (1 + math.Exp(-1*z)) } //Tanh active func func Tanh(r, c int, z float64) float64 { return math.Tanh(z) } func applyCopy(fn actFunc, m mat.Matrix) mat.Matrix { r, c := m.Dims() o := mat.NewDense(r, c, nil) o.Apply(fn, m) return o } func liner(input, w mat.Matrix, b mat.Vector) *mat.Dense { var c mat.Dense c.Mul(input, w) if b != nil { //add blas r, _ := c.Dims() var x mat.VecDense for i := 0; i < r; i++ { x.AddVec(c.RowView(i), b) c.SetRow(i, x.RawVector().Data) } } return &c } //Forward do net work func (dense *DenseNet) Forward(input mat.Matrix) mat.Matrix { c := liner(input, dense.w, dense.b) if dense.active != nil { c.Apply(dense.active, c) } return c } //SetAct set the active func (dense *DenseNet) SetAct(act actFunc) { dense.active = act } //RNNCell is rnn cell type RNNCell interface { //the state size use for the rnn stateDim() (int, int) //the state forward(input, state mat.Matrix) (mat.Matrix, mat.Matrix) } //GRUCell is a RNN network,this used for type GRUCell struct { hh, ih mat.Matrix hb, ib mat.Vector } //readMatFromNpz read a matrix from numpy npz file func readMatFromNpz(rz npz.Reader, name string) (mat.Matrix, error) { key := fmt.Sprintf("%s.npy", name) header := rz.Header(key) if header == nil { return nil, nil } shape := header.Descr.Shape if len(shape) > 2 { return nil, fmt.Errorf("only support 2d or 1d matrix,but %s id %dd", name, len(header.Descr.Shape)) } size := shape[0] if len(shape) == 2 { size *= shape[1] } data := make([]float64, 0, size) err := rz.Read(key, &data) if err != nil { return nil, err } if len(shape) == 2 { return mat.NewDense(shape[0], shape[1], data), nil } return mat.NewVecDense(shape[0], data), nil } //NewGRU make a gru cell func NewGRU(rz npz.Reader, base string) *GRUCell { cell := new(GRUCell) if len(base) > 0 { base = fmt.Sprintf("%s.", base) } m, err := readMatFromNpz(rz, fmt.Sprintf("%s%s", base, "rnn_hh_weight")) if err != nil { panic(err) } m, err = readMatFromNpz(rz, fmt.Sprintf("%s%s", base, "rnn_ih_weight")) if err != nil { panic(err) } cell.ih = m m, err = readMatFromNpz(rz, fmt.Sprintf("%s%s", base, "rnn_hh_blas")) if err != nil { panic(err) } cell.hb = m.(mat.Vector) m, err = readMatFromNpz(rz, fmt.Sprintf("%s%s", base, "rnn_ih_blas")) if err != nil { panic(err) } cell.ib = m.(mat.Vector) return cell } //NewDenseNet make a dense func NewDenseNet(rz npz.Reader, base string) *DenseNet { net := new(DenseNet) if len(base) > 0 { base = fmt.Sprintf("%s.", base) } m, err := readMatFromNpz(rz, fmt.Sprintf("%s%s", base, "weight")) if err != nil { panic(err) } net.w = m m, err = readMatFromNpz(rz, fmt.Sprintf("%s%s", base, "blas")) if err != nil { panic(err) } net.b = m.(mat.Vector) return net }
src/darts/netmodel.go
0.594434
0.422207
netmodel.go
starcoder
package sort // BubbleSort sorts slice by using bubble sort. func BubbleSort(a []int) { n := len(a) if n <= 1 { return } var flag bool for i := 0; i < n; i++ { flag = false for j := 0; j < n-i-1; j++ { if a[j] > a[j+1] { a[j], a[j+1] = a[j+1], a[j] flag = true } } if !flag { break } } } // InsertionSort sorts slice by using insertion sort. func InsertionSort(a []int) { n := len(a) if n <= 1 { return } for i := 1; i < n; i++ { elem := a[i] j := i - 1 for ; j >= 0; j-- { if a[j] > elem { a[j+1] = a[j] } else { break } } a[j+1] = elem } } // SelectionSort sorts slice by using selection sort. func SelectionSort(a []int) { n := len(a) if n <= 1 { return } for i := 0; i < n-1; i++ { minIndex := i for j := i + 1; j < n; j++ { if a[j] < a[minIndex] { minIndex = j } } a[i], a[minIndex] = a[minIndex], a[i] } } // merge array func merge(a []int, start, mid, end int) { temp := make([]int, len(a)) i := start j := mid + 1 copy(temp, a) for k := start; k <= end; k++ { if i > mid { a[k] = temp[j] j++ } else if j > end { a[k] = temp[i] i++ } else if temp[i] < temp[j] { a[k] = temp[i] i++ } else { a[k] = temp[j] j++ } } } func mergeSort(a []int, start int, end int) { if start >= end { return } mid := (start + end) / 2 mergeSort(a, start, mid) mergeSort(a, mid+1, end) merge(a, start, mid, end) } func MergeSort(a []int) { mergeSort(a, 0, len(a)-1) } func partition(a []int, lo, hi int) int { pivot := a[hi] i := lo for j := lo; j < hi; j++ { if a[j] < pivot { a[i], a[j] = a[j], a[i] i++ } } a[i], a[hi] = a[hi], a[i] return i } func quickSort(a []int, start, end int) { if start >= end { return } pivot := partition(a, start, end) quickSort(a, start, pivot-1) quickSort(a, pivot+1, end) } // QuickSort sorts the slice by using quick sort. func QuickSort(a []int) { quickSort(a, 0, len(a)-1) } // CountingSort sorts the slice by using counting sort. // Element in slice should be nonnegative integer. func CountingSort(a []int) { n := len(a) if n <= 1 { return } var max = a[0] for _, i := range a { if i > max { max = i } } c := make([]int, max+1) for _, i := range a { c[i]++ } for i := 1; i <= max; i++ { c[i] = c[i-1] + c[i] } r := make([]int, n) for i := n - 1; i >= 0; i-- { index := c[a[i]] - 1 r[index] = a[i] c[a[i]]-- } copy(a, r) }
sort/sort.go
0.615897
0.438785
sort.go
starcoder
package elliptic import "math/big" // CurveParams contains the parameters of an elliptic curve and also provides // a generic, non-constant time implementation of Curve. type CurveParams struct { P *big.Int // the order of the underlying field N *big.Int // the order of the base point B *big.Int // the constant of the curve equation Gx, Gy *big.Int // (x,y) of the base point BitSize int // the size of the underlying field Name string // the canonical name of the curve } func (curve *CurveParams) Params() *CurveParams { return curve } // CurveParams operates, internally, on Jacobian coordinates. For a given // (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1) // where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole // calculation can be performed within the transform (as in ScalarMult and // ScalarBaseMult). But even for Add and Double, it's faster to apply and // reverse the transform than to operate in affine coordinates. // polynomial returns x³ - 3x + b. func (curve *CurveParams) polynomial(x *big.Int) *big.Int { x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) threeX := new(big.Int).Lsh(x, 1) threeX.Add(threeX, x) x3.Sub(x3, threeX) x3.Add(x3, curve.B) x3.Mod(x3, curve.P) return x3 } func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool { // If there is a dedicated constant-time implementation for this curve operation, // use that instead of the generic one. if specific, ok := matchesSpecificCurve(curve); ok { return specific.IsOnCurve(x, y) } if x.Sign() < 0 || x.Cmp(curve.P) >= 0 || y.Sign() < 0 || y.Cmp(curve.P) >= 0 { return false } // y² = x³ - 3x + b y2 := new(big.Int).Mul(y, y) y2.Mod(y2, curve.P) return curve.polynomial(x).Cmp(y2) == 0 } // zForAffine returns a Jacobian Z value for the affine point (x, y). If x and // y are zero, it assumes that they represent the point at infinity because (0, // 0) is not on the any of the curves handled here. func zForAffine(x, y *big.Int) *big.Int { z := new(big.Int) if x.Sign() != 0 || y.Sign() != 0 { z.SetInt64(1) } return z } // affineFromJacobian reverses the Jacobian transform. See the comment at the // top of the file. If the point is ∞ it returns 0, 0. func (curve *CurveParams) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { if z.Sign() == 0 { return new(big.Int), new(big.Int) } zinv := new(big.Int).ModInverse(z, curve.P) zinvsq := new(big.Int).Mul(zinv, zinv) xOut = new(big.Int).Mul(x, zinvsq) xOut.Mod(xOut, curve.P) zinvsq.Mul(zinvsq, zinv) yOut = new(big.Int).Mul(y, zinvsq) yOut.Mod(yOut, curve.P) return } func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { // If there is a dedicated constant-time implementation for this curve operation, // use that instead of the generic one. if specific, ok := matchesSpecificCurve(curve); ok { return specific.Add(x1, y1, x2, y2) } panicIfNotOnCurve(curve, x1, y1) panicIfNotOnCurve(curve, x2, y2) z1 := zForAffine(x1, y1) z2 := zForAffine(x2, y2) return curve.affineFromJacobian(curve.addJacobian(x1, y1, z1, x2, y2, z2)) } // addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and // (x2, y2, z2) and returns their sum, also in Jacobian form. func (curve *CurveParams) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { // See https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl x3, y3, z3 := new(big.Int), new(big.Int), new(big.Int) if z1.Sign() == 0 { x3.Set(x2) y3.Set(y2) z3.Set(z2) return x3, y3, z3 } if z2.Sign() == 0 { x3.Set(x1) y3.Set(y1) z3.Set(z1) return x3, y3, z3 } z1z1 := new(big.Int).Mul(z1, z1) z1z1.Mod(z1z1, curve.P) z2z2 := new(big.Int).Mul(z2, z2) z2z2.Mod(z2z2, curve.P) u1 := new(big.Int).Mul(x1, z2z2) u1.Mod(u1, curve.P) u2 := new(big.Int).Mul(x2, z1z1) u2.Mod(u2, curve.P) h := new(big.Int).Sub(u2, u1) xEqual := h.Sign() == 0 if h.Sign() == -1 { h.Add(h, curve.P) } i := new(big.Int).Lsh(h, 1) i.Mul(i, i) j := new(big.Int).Mul(h, i) s1 := new(big.Int).Mul(y1, z2) s1.Mul(s1, z2z2) s1.Mod(s1, curve.P) s2 := new(big.Int).Mul(y2, z1) s2.Mul(s2, z1z1) s2.Mod(s2, curve.P) r := new(big.Int).Sub(s2, s1) if r.Sign() == -1 { r.Add(r, curve.P) } yEqual := r.Sign() == 0 if xEqual && yEqual { return curve.doubleJacobian(x1, y1, z1) } r.Lsh(r, 1) v := new(big.Int).Mul(u1, i) x3.Set(r) x3.Mul(x3, x3) x3.Sub(x3, j) x3.Sub(x3, v) x3.Sub(x3, v) x3.Mod(x3, curve.P) y3.Set(r) v.Sub(v, x3) y3.Mul(y3, v) s1.Mul(s1, j) s1.Lsh(s1, 1) y3.Sub(y3, s1) y3.Mod(y3, curve.P) z3.Add(z1, z2) z3.Mul(z3, z3) z3.Sub(z3, z1z1) z3.Sub(z3, z2z2) z3.Mul(z3, h) z3.Mod(z3, curve.P) return x3, y3, z3 } func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { // If there is a dedicated constant-time implementation for this curve operation, // use that instead of the generic one. if specific, ok := matchesSpecificCurve(curve); ok { return specific.Double(x1, y1) } panicIfNotOnCurve(curve, x1, y1) z1 := zForAffine(x1, y1) return curve.affineFromJacobian(curve.doubleJacobian(x1, y1, z1)) } // doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and // returns its double, also in Jacobian form. func (curve *CurveParams) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b delta := new(big.Int).Mul(z, z) delta.Mod(delta, curve.P) gamma := new(big.Int).Mul(y, y) gamma.Mod(gamma, curve.P) alpha := new(big.Int).Sub(x, delta) if alpha.Sign() == -1 { alpha.Add(alpha, curve.P) } alpha2 := new(big.Int).Add(x, delta) alpha.Mul(alpha, alpha2) alpha2.Set(alpha) alpha.Lsh(alpha, 1) alpha.Add(alpha, alpha2) beta := alpha2.Mul(x, gamma) x3 := new(big.Int).Mul(alpha, alpha) beta8 := new(big.Int).Lsh(beta, 3) beta8.Mod(beta8, curve.P) x3.Sub(x3, beta8) if x3.Sign() == -1 { x3.Add(x3, curve.P) } x3.Mod(x3, curve.P) z3 := new(big.Int).Add(y, z) z3.Mul(z3, z3) z3.Sub(z3, gamma) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Sub(z3, delta) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Mod(z3, curve.P) beta.Lsh(beta, 2) beta.Sub(beta, x3) if beta.Sign() == -1 { beta.Add(beta, curve.P) } y3 := alpha.Mul(alpha, beta) gamma.Mul(gamma, gamma) gamma.Lsh(gamma, 3) gamma.Mod(gamma, curve.P) y3.Sub(y3, gamma) if y3.Sign() == -1 { y3.Add(y3, curve.P) } y3.Mod(y3, curve.P) return x3, y3, z3 } func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { // If there is a dedicated constant-time implementation for this curve operation, // use that instead of the generic one. if specific, ok := matchesSpecificCurve(curve); ok { return specific.ScalarMult(Bx, By, k) } panicIfNotOnCurve(curve, Bx, By) Bz := new(big.Int).SetInt64(1) x, y, z := new(big.Int), new(big.Int), new(big.Int) for _, byte := range k { for bitNum := 0; bitNum < 8; bitNum++ { x, y, z = curve.doubleJacobian(x, y, z) if byte&0x80 == 0x80 { x, y, z = curve.addJacobian(Bx, By, Bz, x, y, z) } byte <<= 1 } } return curve.affineFromJacobian(x, y, z) } func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { // If there is a dedicated constant-time implementation for this curve operation, // use that instead of the generic one. if specific, ok := matchesSpecificCurve(curve); ok { return specific.ScalarBaseMult(k) } return curve.ScalarMult(curve.Gx, curve.Gy, k) } func matchesSpecificCurve(params *CurveParams) (Curve, bool) { for _, c := range []Curve{p224, p256, p384, p521} { if params == c.Params() { return c, true } } return nil, false }
src/crypto/elliptic/params.go
0.903959
0.727516
params.go
starcoder
package heartbeat import ( "time" "github.com/garyburd/redigo/redis" ) // Heartbeater serves as a factory-type, in essence, to create both Hearts and // Detectors. It maintains information about the ID used to heartbeat with, the // Location in which to store ticks, the interval at which to update that // location, the pool in which to maintain and recycle Redis connections to, and // the strategy to use to tick and recover items in Redis. type Heartbeater struct { // ID is a unique identifier used by the Heart to tick with. ID string // Location is the absolute path of the keyspace in Redis in which to // store all of the heartbeat updates. Location string // interval is the Interval at which to tell the Heart to tick itself. interval time.Duration // pool is the *redis.Pool that connections are derived from. pool *redis.Pool // Strategy is the strategy to use both to tick the items in Redis, but // also to determine which ones are still alive. Strategy Strategy } // New allocates and returns a pointer to a new instance of a Heartbeater. It // takes in the id, location, interval and pool with which to use to create // Hearts and Detectors. func New(id, location string, interval time.Duration, pool *redis.Pool) *Heartbeater { h := &Heartbeater{ ID: id, Location: location, interval: interval, pool: pool, } h.Strategy = HashExpireyStrategy{h.MaxAge()} return h } // Interval returns the interval at which the heart should tick itself. func (h *Heartbeater) Interval() time.Duration { return h.interval } // Heart creates and returns a new instance of the Heart type with the // parameters used by the Heartbeater for consistency. func (h *Heartbeater) Heart() Heart { // TODO: missing strategy field here return NewSimpleHeart(h.ID, h.Location, h.interval, h.pool, h.Strategy) } // Detectors creates and returns a new instance of the Detector type with the // parameters used by the Heartbeater for consistency. func (h *Heartbeater) Detector() Detector { return NewDetector(h.Location, h.pool, h.Strategy) } // MaxAge returns the maximum amount of time that can pass from the last tick of // an item before that item may be considered dead. By default, it is three // halves of the Interval() time, but is only one second if the interval time is // less than five seconds. func (h *Heartbeater) MaxAge() time.Duration { if h.Interval() < 5*time.Second { return h.Interval() + time.Second } return h.Interval() * 3 / 2 } // SetStrategy changes the strategy used by all future Heart and Detector // instantiations. func (h *Heartbeater) SetStrategy(strategy Strategy) *Heartbeater { h.Strategy = strategy return h }
heartbeat/heartbeater.go
0.639286
0.512083
heartbeater.go
starcoder
package smd import ( "math" "github.com/gonum/matrix/mat64" ) const ( // EarthRotationRate is the average Earth rotation rate in radians per second. EarthRotationRate = 7.292115900231276e-5 // EarthRotationRate2 is another value (project of StatOD). EarthRotationRate2 = 7.29211585275553e-5 ) // Rot313Vec converts a given vector from PQW frame to ECI frame. func Rot313Vec(θ1, θ2, θ3 float64, vI []float64) []float64 { return MxV33(R3R1R3(θ1, θ2, θ3), vI) } // R3R1R3 performs a 3-1-3 Euler parameter rotation. // From Schaub and Junkins (the one in Vallado is wrong... surprinsingly, right? =/) func R3R1R3(θ1, θ2, θ3 float64) *mat64.Dense { sθ1, cθ1 := math.Sincos(θ1) sθ2, cθ2 := math.Sincos(θ2) sθ3, cθ3 := math.Sincos(θ3) return mat64.NewDense(3, 3, []float64{cθ3*cθ1 - sθ3*cθ2*sθ1, cθ3*sθ1 + sθ3*cθ2*cθ1, sθ3 * sθ2, -sθ3*cθ1 - cθ3*cθ2*sθ1, -sθ3*sθ1 + cθ3*cθ2*cθ1, cθ3 * sθ2, sθ2 * sθ1, -sθ2 * cθ1, cθ2}) } // R1 rotation about the 1st axis. func R1(x float64) *mat64.Dense { s, c := math.Sincos(x) return mat64.NewDense(3, 3, []float64{1, 0, 0, 0, c, s, 0, -s, c}) } // R2 rotation about the 2nd axis. func R2(x float64) *mat64.Dense { s, c := math.Sincos(x) return mat64.NewDense(3, 3, []float64{c, 0, -s, 0, 1, 0, s, 0, c}) } // R3 rotation about the 3rd axis. func R3(x float64) *mat64.Dense { s, c := math.Sincos(x) return mat64.NewDense(3, 3, []float64{c, s, 0, -s, c, 0, 0, 0, 1}) } // MxV33 multiplies a matrix with a vector. Note that there is no dimension check! func MxV33(m mat64.Matrix, v []float64) (o []float64) { vVec := mat64.NewVector(len(v), v) var rVec mat64.Vector rVec.MulVec(m, vVec) return []float64{rVec.At(0, 0), rVec.At(1, 0), rVec.At(2, 0)} } // GEO2ECEF converts the provided parameters (in km and radians) to the ECEF vector. // Note that the first parameter is the altitude, not the radius from the center of the body! func GEO2ECEF(altitude, latitude, longitude float64) []float64 { sLong, cLong := math.Sincos(longitude) sLat, cLat := math.Sincos(latitude) r := altitude + Earth.Radius return []float64{r * cLat * cLong, r * cLat * sLong, r * sLat} } // ECI2ECEF converts the provided ECI vector to ECEF for the θgst given in degrees. func ECI2ECEF(R []float64, θgst float64) []float64 { return MxV33(R3(θgst), R) } // ECEF2ECI converts the provided ECEF vector to ECI for the θgst given in degrees. func ECEF2ECI(R []float64, θgst float64) []float64 { return ECI2ECEF(R, -θgst) }
rotation.go
0.845369
0.726741
rotation.go
starcoder
package view import ( "github.com/viant/sqlx/io" "github.com/viant/xunsafe" "reflect" "sync" "unsafe" ) //Visitor represents visitor function type Visitor func(value interface{}) error //Collector collects and build result from view fetched from Database //If View or any of the View.With MatchStrategy support Parallel fetching, it is important to call MergeData //when all needed view was fetched type Collector struct { mutex sync.Mutex parent *Collector dest interface{} appender *xunsafe.Appender valuePosition map[string]map[interface{}][]int //stores positions in main slice, based on _field name, indexed by _field value. types map[string]*xunsafe.Type relation *Relation values map[string]*[]interface{} //acts like a buffer. Value resolved with Resolve method can't be put to the value position map // because value fetched from database was not scanned into yet. Putting value to the map as a key, would create key as a pointer to the zero value. slice *xunsafe.Slice view *View relations []*Collector wg *sync.WaitGroup supportParallel bool wgDelta int indexCounter int manyCounter int } func (r *Collector) Lock() *sync.Mutex { if r.parent == nil { return &r.mutex } return &r.parent.mutex } //Resolve resolved unmapped column func (r *Collector) Resolve(column io.Column) func(ptr unsafe.Pointer) interface{} { buffer, ok := r.values[column.Name()] if !ok { localSlice := make([]interface{}, 0) buffer = &localSlice r.values[column.Name()] = buffer } scanType := column.ScanType() scanType = remapScanType(scanType, column.DatabaseTypeName()) kind := scanType.Kind() switch kind { case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Int32, reflect.Uint16, reflect.Int16, reflect.Uint8, reflect.Int8: scanType = reflect.TypeOf(0) } r.types[column.Name()] = xunsafe.NewType(scanType) return func(ptr unsafe.Pointer) interface{} { var valuePtr interface{} switch kind { case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Int32, reflect.Uint16, reflect.Int16, reflect.Uint8, reflect.Int8: value := 0 valuePtr = &value case reflect.Float64, reflect.Float32: value := 0.0 valuePtr = &value case reflect.Bool: value := false valuePtr = &value case reflect.String: value := "" valuePtr = &value default: valuePtr = reflect.New(scanType).Interface() } *buffer = append(*buffer, valuePtr) return valuePtr } } //parentValuesPositions returns positions in the parent main slice by given column name //After first use, it is not possible to index new resolved column indexes by Resolve method func (r *Collector) parentValuesPositions(columnName string) map[interface{}][]int { result, ok := r.parent.valuePosition[columnName] if !ok { r.indexParentPositions(columnName) result = r.parent.valuePosition[columnName] } return result } //NewCollector creates a collector func NewCollector(slice *xunsafe.Slice, view *View, dest interface{}, supportParallel bool) *Collector { ensuredDest := ensureDest(dest, view) wg := sync.WaitGroup{} wgDelta := 0 if !supportParallel { wgDelta = 1 } wg.Add(wgDelta) return &Collector{ dest: ensuredDest, valuePosition: make(map[string]map[interface{}][]int), appender: slice.Appender(xunsafe.AsPointer(ensuredDest)), slice: slice, view: view, types: make(map[string]*xunsafe.Type), values: make(map[string]*[]interface{}), supportParallel: supportParallel, wg: &wg, wgDelta: wgDelta, } } func ensureDest(dest interface{}, view *View) interface{} { if _, ok := dest.(*interface{}); ok { return reflect.MakeSlice(view.Schema.SliceType(), 0, 1).Interface() } return dest } //Visitor creates visitor function func (r *Collector) Visitor() Visitor { relation := r.relation visitorRelations := RelationsSlice(r.view.With).PopulateWithVisitor() for _, rel := range visitorRelations { r.valuePosition[rel.Column] = map[interface{}][]int{} } visitors := make([]Visitor, 1) visitors[0] = r.valueIndexer(visitorRelations) if relation != nil && (r.parent == nil || !r.parent.SupportsParallel()) { switch relation.Cardinality { case "One": visitors = append(visitors, r.visitorOne(relation)) case "Many": visitors = append(visitors, r.visitorMany(relation)) } } return func(value interface{}) error { var err error for _, visitor := range visitors { if err = visitor(value); err != nil { return err } } return nil } } func (r *Collector) valueIndexer(visitorRelations []*Relation) func(value interface{}) error { distinctRelations := make([]*Relation, 0) presenceMap := map[string]bool{} for i := range visitorRelations { if _, ok := presenceMap[visitorRelations[i].Column]; ok { continue } distinctRelations = append(distinctRelations, visitorRelations[i]) presenceMap[visitorRelations[i].Column] = true } return func(value interface{}) error { ptr := xunsafe.AsPointer(value) for _, rel := range distinctRelations { fieldValue := rel.columnField.Value(ptr) r.indexValueByRel(fieldValue, rel, r.indexCounter) } r.indexCounter++ return nil } } func (r *Collector) indexValueByRel(fieldValue interface{}, rel *Relation, counter int) { switch actual := fieldValue.(type) { case []int: for _, v := range actual { r.indexValueToPosition(rel, v, counter) } case []*int64: for _, v := range actual { r.indexValueToPosition(rel, int(*v), counter) } case []int64: for _, v := range actual { r.indexValueToPosition(rel, int(v), counter) } case int32: r.indexValueToPosition(rel, int(actual), counter) case *int64: r.indexValueToPosition(rel, int(*actual), counter) case []string: for _, v := range actual { r.indexValueToPosition(rel, v, counter) } default: r.indexValueToPosition(rel, normalizeKey(fieldValue), counter) } } func (r *Collector) indexValueToPosition(rel *Relation, fieldValue interface{}, counter int) { _, ok := r.valuePosition[rel.Column][fieldValue] if !ok { r.valuePosition[rel.Column][fieldValue] = []int{counter} } else { r.valuePosition[rel.Column][fieldValue] = append(r.valuePosition[rel.Column][fieldValue], counter) } } func (r *Collector) visitorOne(relation *Relation) func(value interface{}) error { keyField := relation.Of._field holderField := relation.holderField dest := r.parent.Dest() destPtr := xunsafe.AsPointer(dest) var key interface{} return func(owner interface{}) error { key = keyField.Interface(xunsafe.AsPointer(owner)) key = normalizeKey(key) valuePosition := r.parentValuesPositions(relation.Column) positions, ok := valuePosition[key] if !ok { return nil } for _, index := range positions { item := r.parent.slice.ValuePointerAt(destPtr, index) holderField.SetValue(xunsafe.AsPointer(item), owner) } return nil } } func (r *Collector) visitorMany(relation *Relation) func(value interface{}) error { keyField := relation.Of._field holderField := relation.holderField var xType *xunsafe.Type var values *[]interface{} var key interface{} dest := r.parent.Dest() destPtr := xunsafe.AsPointer(dest) return func(owner interface{}) error { if keyField == nil && xType == nil { xType = r.types[relation.Of.Column] values = r.values[relation.Of.Column] } if keyField != nil { key = keyField.Interface(xunsafe.AsPointer(owner)) } else { key = xType.Deref((*values)[r.manyCounter]) r.manyCounter++ } valuePosition := r.parentValuesPositions(relation.Column) key = normalizeKey(key) positions, ok := valuePosition[key] if !ok { return nil } for _, index := range positions { parentItem := r.parent.slice.ValuePointerAt(destPtr, index) r.Lock().Lock() sliceAddPtr := holderField.Pointer(xunsafe.AsPointer(parentItem)) slice := relation.Of.Schema.Slice() appender := slice.Appender(sliceAddPtr) appender.Append(owner) r.Lock().Unlock() r.view.Logger.ObjectReconciling(dest, owner, parentItem, index) } return nil } } //NewItem creates and return item provider //Each produced item is automatically appended to the dest func (r *Collector) NewItem() func() interface{} { return func() interface{} { return r.appender.Add() } } func (r *Collector) indexParentPositions(name string) { if r.parent == nil { return } values := r.parent.values[name] if values == nil { return } xType := r.parent.types[name] r.parent.valuePosition[name] = map[interface{}][]int{} for position, v := range *values { if v == nil { continue } val := xType.Deref(v) val = normalizeKey(val) _, ok := r.parent.valuePosition[name][val] if !ok { r.parent.valuePosition[name][val] = make([]int, 0) } r.parent.valuePosition[name][val] = append(r.parent.valuePosition[name][val], position) } } //Relations creates and register new Collector for each Relation present in the Selector.Columns if View allows use Selector.Columns func (r *Collector) Relations(selector *Selector) []*Collector { result := make([]*Collector, len(r.view.With)) counter := 0 for i := range r.view.With { if selector != nil && len(selector.Columns) > 0 && !selector.Has(r.view.With[i].Holder) { continue } dest := reflect.MakeSlice(r.view.With[i].Of.View.Schema.SliceType(), 0, 1).Interface() slice := r.view.With[i].Of.View.Schema.Slice() wg := sync.WaitGroup{} delta := 0 if !r.SupportsParallel() { delta = 1 } wg.Add(delta) result[counter] = &Collector{ parent: r, dest: dest, appender: slice.Appender(xunsafe.AsPointer(dest)), valuePosition: make(map[string]map[interface{}][]int), types: make(map[string]*xunsafe.Type), values: make(map[string]*[]interface{}), slice: slice, view: &r.view.With[i].Of.View, relation: r.view.With[i], supportParallel: r.view.With[i].Of.MatchStrategy.SupportsParallel(), wg: &wg, wgDelta: delta, } counter++ } r.relations = result[:counter] return result[:counter] } //View returns View assigned to the Collector func (r *Collector) View() *View { return r.view } //Dest returns collector slice func (r *Collector) Dest() interface{} { return r.dest } //SupportsParallel if Collector supports parallelism, it means that his Relations can fetch view in the same time //Later on it will be merged with the parent Collector func (r *Collector) SupportsParallel() bool { return r.supportParallel } //MergeData merges view with Collectors produced via Relations //It is sufficient to call it on the most Parent Collector to produce result func (r *Collector) MergeData() { for i := range r.relations { r.relations[i].MergeData() } if r.parent == nil || !r.parent.SupportsParallel() { return } r.mergeToParent() } func (r *Collector) mergeToParent() { valuePositions := r.parentValuesPositions(r.relation.Column) destPtr := xunsafe.AsPointer(r.dest) field := r.relation.Of._field holderField := r.relation.holderField parentSlice := r.parent.slice parentDestPtr := xunsafe.AsPointer(r.parent.dest) for i := 0; i < r.slice.Len(destPtr); i++ { value := r.slice.ValuePointerAt(destPtr, i) key := normalizeKey(field.Value(xunsafe.AsPointer(value))) positions, ok := valuePositions[key] if !ok { continue } for _, position := range positions { parentValue := parentSlice.ValuePointerAt(parentDestPtr, position) if r.relation.Cardinality == One { at := r.slice.ValuePointerAt(destPtr, i) holderField.SetValue(xunsafe.AsPointer(parentValue), at) } else if r.relation.Cardinality == Many { r.Lock().Lock() appender := r.slice.Appender(holderField.ValuePointer(xunsafe.AsPointer(parentValue))) appender.Append(value) r.Lock().Unlock() r.view.Logger.ObjectReconciling(r.dest, value, parentValue, position) } } } } //ParentPlaceholders if Collector doesn't support parallel fetching and has a Parent, it will return a parent _field values and column name //that the relation was created from, otherwise empty slice and empty string //i.e. if Parent Collector collects Employee{AccountId: int}, Column.Name is account_id and Collector collects Account //it will extract and return all the AccountId that were accumulated and account_id func (r *Collector) ParentPlaceholders() ([]interface{}, string) { if r.parent == nil || r.parent.SupportsParallel() { return []interface{}{}, "" } column := r.relation.Of.Column if r.relation.columnField != nil { destPtr := xunsafe.AsPointer(r.parent.dest) sliceLen := r.parent.slice.Len(destPtr) result := make([]interface{}, 0) for i := 0; i < sliceLen; i++ { parent := r.parent.slice.ValuePointerAt(destPtr, i) fieldValue := r.relation.columnField.Value(xunsafe.AsPointer(parent)) switch actual := fieldValue.(type) { case []*int64: for j := range actual { result = append(result, int(*actual[j])) } case []int64: for j := range actual { result = append(result, int(actual[j])) } case []int: for j := range actual { result = append(result, actual[j]) } case []string: for j := range actual { result = append(result, actual[j]) } default: result = append(result, fieldValue) } } return result, column } else { positions := r.parentValuesPositions(r.relation.Column) result := make([]interface{}, len(positions)) counter := 0 for key := range positions { result[counter] = key counter++ } return result, column } } func (r *Collector) WaitIfNeeded() { if r.parent != nil { r.parent.wg.Wait() } } func (r *Collector) Fetched() { if r.wgDelta > 0 { r.wg.Done() r.wgDelta-- } } func (r *Collector) Slice() (unsafe.Pointer, *xunsafe.Slice) { return xunsafe.AsPointer(r.dest), r.slice } func (r *Collector) Relation() *Relation { return r.relation }
view/collector.go
0.569613
0.45423
collector.go
starcoder
// Package counterpair is an example using go-frp modeled after the Elm example found at: // https://github.com/evancz/elm-architecture-tutorial/blob/master/examples/inception/CounterPair.elm package counterpair import ( "github.com/gmlewis/go-frp/v2/examples/inception/counter" h "github.com/gmlewis/go-frp/v2/html" ) // MODEL type Model struct { top counter.Model bottom counter.Model } func Init(top, bottom int) Model { return Model{ top: counter.Init(top), bottom: counter.Init(bottom), } } func (m Model) Top() int { return int(m.top) } func (m Model) Bottom() int { return int(m.bottom) } // UPDATE type Action func(Model) Model func Updater(model Model) func(action Action) Model { return func(action Action) Model { return model.Update(action) } } func (m Model) Update(action Action) Model { return action(m) } func IncrementTop(model Model) Model { return Top(model)(counter.Increment) } func IncrementBottom(model Model) Model { return Bottom(model)(counter.Increment) } func DecrementTop(model Model) Model { return Top(model)(counter.Decrement) } func DecrementBottom(model Model) Model { return Bottom(model)(counter.Decrement) } func Reset(model Model) Model { return Init(0, 0) } type CounterAction func(counter.Action) Model func Top(model Model) CounterAction { return func(action counter.Action) Model { return Model{ top: model.top.Update(action), bottom: model.bottom, } } } func Bottom(model Model) CounterAction { return func(action counter.Action) Model { return Model{ top: model.top, bottom: model.bottom.Update(action), } } } func AdjustBy(top, bottom int) func(model Model) Model { return func(model Model) Model { return Model{ top: counter.Init(int(model.top) + top), bottom: counter.Init(int(model.bottom) + bottom), } } } type WrapFunc func(model Model) interface{} func wrapper(model Model, wrapFunc WrapFunc) func(action Action) interface{} { return func(action Action) interface{} { newModel := model.Update(action) return wrapFunc(newModel) } } func topWrapper(model Model, wrapFunc WrapFunc) counter.WrapFunc { return func(cm counter.Model) interface{} { newModel := Model{ top: cm, bottom: model.bottom, } return wrapFunc(newModel) } } func bottomWrapper(model Model, wrapFunc WrapFunc) counter.WrapFunc { return func(cm counter.Model) interface{} { newModel := Model{ top: model.top, bottom: cm, } return wrapFunc(newModel) } } // VIEW func (m Model) View(rootUpdateFunc interface{}, wrapFunc WrapFunc) h.HTML { return h.Div( m.top.View(rootUpdateFunc, topWrapper(m, wrapFunc)), m.bottom.View(rootUpdateFunc, bottomWrapper(m, wrapFunc)), h.Button(h.Text("Reset")).OnClick(rootUpdateFunc, wrapper(m, wrapFunc), Reset), ) }
examples/inception/counterpair/counterpair.go
0.821331
0.44553
counterpair.go
starcoder
package planar import ( "log" "math/big" "github.com/go-spatial/geom" ) const ( // Experimental testing produced this result. // For finding the intersect we need higher precision. // Then geom.PrecisionLevelBigFloat PrecisionLevelBigFloat = 110 ) func AreLinesColinear(l1, l2 geom.Line) bool { x1, y1 := l1.Point1().X(), l1.Point1().Y() x2, y2 := l1.Point2().X(), l1.Point2().Y() x3, y3 := l2.Point1().X(), l2.Point1().Y() x4, y4 := l2.Point2().X(), l2.Point2().Y() denom := ((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)) // The lines are parallel or they overlap fi denom is 0. if denom != 0 { return false } // now we just need to see if one of the end points is on the other one. xmin, xmax := x1, x2 if x1 > x2 { xmin, xmax = x2, x1 } ymin, ymax := y1, y2 if y1 > y2 { ymin, ymax = y2, y1 } fn := func(x, y float64) bool { return xmin <= x && x <= xmax && ymin <= y && y <= ymax } return fn(x3, y3) || fn(x4, y4) } // LineIntersect find the intersection point (x,y) between two lines if there is one. Ok will be true if it found an interseciton point. // ok being false, means there isn't just one intersection point, there could be zero, or more then one. // ref: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line func LineIntersect(l1, l2 geom.Line) (pt [2]float64, ok bool) { x1, y1 := l1.Point1().X(), l1.Point1().Y() x2, y2 := l1.Point2().X(), l1.Point2().Y() x3, y3 := l2.Point1().X(), l2.Point1().Y() x4, y4 := l2.Point2().X(), l2.Point2().Y() denom := ((x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)) // The lines are parallel or they overlap. No single point. if denom == 0 { return pt, false } xnom := (((x1 * y2) - (y1 * x2)) * (x3 - x4)) - ((x1 - x2) * ((x3 * y4) - (y3 * x4))) ynom := (((x1 * y2) - (y1 * x2)) * (y3 - y4)) - ((y1 - y2) * ((x3 * y4) - (y3 * x4))) return [2]float64{xnom / denom, ynom / denom}, true } func bigFloat(f float64) *big.Float { return big.NewFloat(f).SetPrec(PrecisionLevelBigFloat) } // LineIntersectBigFloat find the intersection point (x,y) between two lines if there is one. Ok will be true if it found an interseciton point. Internally uses math/big // ok being false, means there isn't just one intersection point, there could be zero, or more then one. // ref: https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line func LineIntersectBigFloat(l1, l2 geom.Line) (pt [2]*big.Float, ok bool) { x1, y1 := bigFloat(l1.Point1().X()), bigFloat(l1.Point1().Y()) x2, y2 := bigFloat(l1.Point2().X()), bigFloat(l1.Point2().Y()) x3, y3 := bigFloat(l2.Point1().X()), bigFloat(l2.Point1().Y()) x4, y4 := bigFloat(l2.Point2().X()), bigFloat(l2.Point2().Y()) deltaX12 := bigFloat(0).Sub(x1, x2) deltaX34 := bigFloat(0).Sub(x3, x4) deltaY12 := bigFloat(0).Sub(y1, y2) deltaY34 := bigFloat(0).Sub(y3, y4) denom := bigFloat(0).Sub( bigFloat(0).Mul(deltaX12, deltaY34), bigFloat(0).Mul(deltaY12, deltaX34), ) // The lines are parallel or they overlap. No single point. if d, _ := denom.Float64(); d == 0 { return pt, false } xnom := bigFloat(0).Sub( bigFloat(0).Mul( bigFloat(0).Sub( bigFloat(0).Mul(x1, y2), bigFloat(0).Mul(y1, x2), ), deltaX34, ), bigFloat(0).Mul( deltaX12, bigFloat(0).Sub( bigFloat(0).Mul(x3, y4), bigFloat(0).Mul(y3, x4), ), ), ) ynom := bigFloat(0).Sub( bigFloat(0).Mul( bigFloat(0).Sub( bigFloat(0).Mul(x1, y2), bigFloat(0).Mul(y1, x2), ), deltaY34, ), bigFloat(0).Mul( deltaY12, bigFloat(0).Sub( bigFloat(0).Mul(x3, y4), bigFloat(0).Mul(y3, x4), ), ), ) bx := bigFloat(0).Quo(xnom, denom) by := bigFloat(0).Quo(ynom, denom) return [2]*big.Float{bx, by}, true } // SegmentIntersect finds the intersection point (x,y) between two lines if there is one. Ok will be true if it found a point that is on both line segments, otherwise it will be false. func SegmentIntersect(l1, l2 geom.Line) (pt [2]float64, ok bool) { bpt, ok := LineIntersectBigFloat(l1, l2) if !ok { if debug { log.Printf("Lines don't intersect: %v %v", l1, l2) } return pt, false } l1c, l2c := l1.ContainsPointBigFloat(bpt), l2.ContainsPointBigFloat(bpt) if debug { log.Printf("LineIntersect returns %v %v", bpt, ok) log.Printf("line (%v) contains point(%v) :%v ", l1, bpt, l1c) log.Printf("line (%v) contains point(%v) :%v ", l2, bpt, l2c) } x, _ := bpt[0].Float64() y, _ := bpt[1].Float64() if y == -0 { y = 0 } if x == -0 { x = 0 } // Check to see if the pt is on both line segments. return [2]float64{x, y}, l1c && l2c }
planar/line_intersect.go
0.68784
0.610889
line_intersect.go
starcoder
package syntax import ( "regexp/syntax" "unicode" ) type charNodeMatcher interface { Match(rune, syntax.Flags) bool } type reverseMatcher struct { M charNodeMatcher } func (m reverseMatcher) Match(r rune, flags syntax.Flags) bool { return !m.M.Match(r, flags) } type unicodeMatcher struct { R *unicode.RangeTable } func (m unicodeMatcher) Match(r rune, flags syntax.Flags) bool { return unicode.Is(m.R, r) } type digitsMatcher struct{} func (m digitsMatcher) Match(r rune, flags syntax.Flags) bool { return '0' <= r && r <= '9' } type whitespaceMatcher struct{} func (m whitespaceMatcher) Match(r rune, flags syntax.Flags) bool { switch r { case '\t', '\n', '\f', '\r', ' ': return true default: return false } } func isASCIIWord(r rune) bool { return ('0' <= r && r <= '9') || ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') || r == '_' } type wordMatcher struct{} func (m wordMatcher) Match(r rune, flags syntax.Flags) bool { return isASCIIWord(r) } type alphanumericMatcher struct { } func (m alphanumericMatcher) Match(r rune, flags syntax.Flags) bool { return ('0' <= r && r <= '9') || ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') } type alphabeticMatcher struct { } func (m alphabeticMatcher) Match(r rune, flags syntax.Flags) bool { return ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') } type asciiMatcher struct { } func (m asciiMatcher) Match(r rune, flags syntax.Flags) bool { return 0 <= r && r <= 0x7F } type blankMatcher struct { } func (m blankMatcher) Match(r rune, flags syntax.Flags) bool { return r == '\t' || r == ' ' } type controlMatcher struct { } func (m controlMatcher) Match(r rune, flags syntax.Flags) bool { return (0 <= r && r <= 0x1F) || r == 0x7F } type graphicalMatcher struct { } func (m graphicalMatcher) Match(r rune, flags syntax.Flags) bool { return '!' <= r && r <= '~' } type lowerMatcher struct { } func (m lowerMatcher) Match(r rune, flags syntax.Flags) bool { return 'a' <= r && r <= 'z' } type printableMatcher struct { } func (m printableMatcher) Match(r rune, flags syntax.Flags) bool { return ' ' <= r && r <= '~' } func isASCIIPunct(r rune) bool { return ('!' <= r && r <= '/') || (':' <= r && r <= '@') || ('[' <= r && r <= '`') || ('{' <= r && r <= '~') } type punctuationMatcher struct { } func (m punctuationMatcher) Match(r rune, flags syntax.Flags) bool { return isASCIIPunct(r) } type upperMatcher struct { } func (m upperMatcher) Match(r rune, flags syntax.Flags) bool { return 'A' <= r && r <= 'Z' } func isASCIIXdigit(r rune) bool { return ('0' <= r && r <= '9') || ('a' <= r && r <= 'f') || ('A' <= r && r <= 'F') } type xdigitMatcher struct { } func (m xdigitMatcher) Match(r rune, flags syntax.Flags) bool { return isASCIIXdigit(r) }
syntax/matcher.go
0.707607
0.450843
matcher.go
starcoder
package orm import ( "bytes" "context" "github.com/goradd/goradd/web/examples/gen/goradd/model" "github.com/goradd/goradd/web/examples/gen/goradd/model/node" ) func (ctrl *ManyManyPanel) DrawTemplate(ctx context.Context, buf *bytes.Buffer) (err error) { buf.WriteString(` <h1>Many-to-Many Relationships</h1> <p> Many-to-many relationships link records where each side of the relationship sees multiple records on the other side. In the Golang ORM, each side of the relationship will see a slice of records on the other side. </p> <p> Many-to-many relationships are modeled in SQL databases with an intermediate table, called an Association table. The association table is a table with just two fields, each field being a foreign key pointing to one side of the relationship. To identify a table as being an association table in SQL, append "_assn" to the end of the name of the table. </p> <p> NoSQL databases store Many-to-many relationships in special fields on each side that is an array of record ids that point to the records on the other side. </p> <p> In either case, the ORM abstracts out the means of creating the relationship so that you do not have to worry about what is happening in the database. Simply treat each side as a slice of objects pointing to the other table, and the Goradd ORM will take care of the rest. </p> <p> In the example below, we are using the team member - project association. Any person can be a team member of many projects, and any project can have multiple team members. `) project := model.LoadProject(ctx, "1", node.Project().TeamMembers()) person := model.LoadPerson(ctx, "1", node.Person().ProjectsAsTeamMember()) buf.WriteString(`</p> <p> Project `) buf.WriteString(project.Name()) buf.WriteString(` has team members: `) for _, t := range project.TeamMembers() { buf.WriteString(t.FirstName()) buf.WriteString(` `) buf.WriteString(t.LastName()) buf.WriteString(`, `) } buf.Truncate(buf.Len() - 2) buf.WriteString(` `) buf.WriteString(` </p> <p> Person `) buf.WriteString(person.FirstName()) buf.WriteString(` `) buf.WriteString(person.LastName()) buf.WriteString(` is a member of these projects: `) for _, p := range person.ProjectsAsTeamMember() { buf.WriteString(p.Name()) buf.WriteString(`, `) } buf.Truncate(buf.Len() - 2) buf.WriteString(`</p> <h2>Creating Many-Many Linked Records</h2> <p> Creating many-many linked records is similar to creating linked records in a one-to-many situation. You simply call the appropriate Set* function to set the slice of items, and then call Save. </p> `) project2 := model.NewProject() project2.SetName("NewProject") project2.SetNum(100) project2.SetProjectStatusType(model.ProjectStatusTypeOpen) p1 := model.NewPerson() p1.SetFirstName("Me") p1.SetLastName("You") p2 := model.NewPerson() p2.SetFirstName("Him") p2.SetLastName("Her") project2.SetTeamMembers([]*model.Person{p1, p2}) project2.Save(ctx) project3 := model.LoadProject(ctx, project2.ID(), node.Project().TeamMembers()) buf.WriteString(` <p> Project `) buf.WriteString(project3.Name()) buf.WriteString(` has team members: `) for _, t := range project3.TeamMembers() { buf.WriteString(t.FirstName()) buf.WriteString(` `) buf.WriteString(t.LastName()) buf.WriteString(`, `) } buf.Truncate(buf.Len() - 2) buf.WriteString(`</p> <h2>Deleting Many-Many Linked Records</h2> <p> Deleting a record will also delete the link between two many-many linked records. However, it will not delete the record on the other side of the link. </p> `) // Delete the records we created above. project3.Delete(ctx) p1.Delete(ctx) p2.Delete(ctx) buf.WriteString(` `) buf.WriteString(` `) return }
web/examples/tutorial/orm/8-manymany.tpl.go
0.575827
0.436022
8-manymany.tpl.go
starcoder
package engine import "math" // Entity is a basic game entity. type Entity interface { Tick() SetCollider(*Collider) Position() Vec2 AddImage(...Image) Images() []Image Class() string Dispose() IsDisposed() bool } // CoreEntity is a default Entity implementation. type CoreEntity struct { Vec2 prevPos Vec2 // Direction is the current cardinal direction // the entity is facing. Direction CardinalDirection images []Image collider *Collider disposed bool lastAngle float64 } // Tick updates the CoreEntity's position. func (e *CoreEntity) Tick() { if e.collider != nil { e.Vec2 = e.collider.Resolve(e.prevPos, e.Vec2) } e.prevPos = e.Vec2 for _, img := range e.images { img.Translate(e.X, e.Y) } } // SetCollider sets the CoreEntity's Collider. func (e *CoreEntity) SetCollider(collider *Collider) { e.collider = collider } // Position gets the CoreEntity's current position. func (e *CoreEntity) Position() Vec2 { return e.Vec2 } // AddImage adds an Image to the CoreEntity. func (e *CoreEntity) AddImage(image ...Image) { for _, img := range image { img.Translate(e.X, e.Y) } e.images = append(e.images, image...) } // Images gets the CoreEntity's Images. func (e *CoreEntity) Images() []Image { return e.images } // Dispose marks the CoreEntity as disposed, and disposes its Images. func (e *CoreEntity) Dispose() { e.disposed = true for _, img := range e.images { img.Dispose() } } // IsDisposed checks if the CoreEntity has been disposed. func (e *CoreEntity) IsDisposed() bool { return e.disposed } // MoveTowards moves the CoreEntity in the direction of angle // by distance dist. The change in angle between MoveTowards // calls is limited to a delta of the interval argument. // An interval of 0 can be provided for no delta limit. // The Direction field is updated with the // current closest cardinal direction. func (e *CoreEntity) MoveTowards(angle, dist, interval float64) { if interval != 0 { interval := math.Pi / 32 delta := math.Atan2( math.Sin(angle-e.lastAngle), math.Cos(e.lastAngle-angle), ) op := math.Min if delta < 0 { interval = -interval op = math.Max } e.lastAngle += op( interval, delta, ) } else { e.lastAngle = angle } if e.lastAngle < 0 { e.lastAngle += math.Pi * 2 } else if e.lastAngle > math.Pi*2 { e.lastAngle -= math.Pi * 2 } e.Direction = AngleToCardinal(e.lastAngle) e.Vec2 = e.Translate(e.lastAngle, dist) }
engine/entity.go
0.823612
0.438665
entity.go
starcoder
package main import ( "bayesiannetwork" "bufio" "encoding/csv" "fmt" "io" "math" "math/rand" "os" "strconv" ) func loadData(fname string) [][]float64 { // Load a TXT file. f, _ := os.Open(fname) // Create a new reader. r := csv.NewReader(bufio.NewReader(f)) data := make([][]float64, 0) for { record, err := r.Read() // Stop at EOF. if err == io.EOF { break } row := make([]float64, 0) for _, value := range record { v, _ := strconv.ParseFloat(value, 64) row = append(row, v) } data = append(data, row) } return data } func main() { data := loadData("iris.data") // bin the data -- bayesiannetwork requires discrete statesw nCols := len(data[0]) max := make([]float64, nCols) min := make([]float64, nCols) for c := 0; c < nCols; c++ { min[c] = math.MaxFloat64 } for _, row := range data { for i, v := range row { if max[i] < v { max[i] = v } if min[i] > v { min[i] = v } } } // discritize the features nBins := 3.0 discritized := make([][]int, 0) for i := 0; i < len(data); i++ { discritized = append(discritized, make([]int, nCols)) } for c := 0; c < nCols; c++ { for i, row := range data { bin := math.Floor(nBins * (row[c] - min[c]) / (max[c] - min[c])) bin = math.Min(nBins-1, bin) discritized[i][c] = int(bin) } } featureNames := []string{ "sepal_length", "sepal_width", "petal_length", "petal_width", "species"} // make the data set into a []map[*node]int converted := bayesiannetwork.ConvertDataset(discritized, featureNames) // Typically, we would split this data set into a test and train set but // this is such a small data set that not all states would be observed in // the BN and we wouldn't be able to make inferences. // split the data into a training and test set order := rand.Perm(len(data)) train := make([]map[*bayesiannetwork.Node]int, 0) test := make([]map[*bayesiannetwork.Node]int, 0) for i, index := range order { // NOTE: all instances are in the training set if i < 150 { train = append(train, converted[index]) } else { test = append(test, converted[index]) } } inferred := bayesiannetwork.InferBayesianNetwork(train, 1000) fmt.Println("Inferred topology:") for _, n := range inferred.Nodes { fmt.Println(n.Name) for _, c := range n.Children { fmt.Println("\t", c.Name) } } fmt.Println() mn := math.MaxFloat64 for _, v := range inferred.Likelihood(train) { if v < mn { mn = v } } modelLL := inferred.ModelLikelihood(train) fmt.Println("Model log likelihood", modelLL) // get the decision matrix source := rand.NewSource(1) r := rand.New(source) // get the class node var classNode *bayesiannetwork.Node for n, _ := range train[0] { if n.Name == featureNames[len(featureNames)-1] { classNode = n break } } //initialize decision matrix confusionMatrix := make([][]int, int(nBins)) for i := 0; i < int(nBins); i++ { confusionMatrix[i] = make([]int, int(nBins)) } // classify the instances (first removing the class feature) for _, instance := range train { // copy the instance except the class feature classless := make(map[*bayesiannetwork.Node]int) for k, v := range instance { if k.Name != featureNames[len(featureNames)-1] { classless[k] = v } } dist := inferred.PosteriorDistribution( r, []*bayesiannetwork.Node{classNode}, classless) // argmax of dist / update decision matrix actual := instance[classNode] mx := 0.0 mxState := 0 for k, v := range dist[classNode].StateMap { if v > mx { mx = v mxState = k } } predicted := mxState confusionMatrix[actual][predicted] += 1 } // print the confusion matrix fmt.Println("confusionMatrix:") for _, row := range confusionMatrix { fmt.Println(row) } // calculate the precision per class precision := make([]float64, int(nBins)) for ci := 0; ci < len(confusionMatrix); ci++ { tp := float64(confusionMatrix[ci][ci]) tpfp := 0.0 for ri := 0; ri < len(confusionMatrix); ri++ { tpfp += float64(confusionMatrix[ci][ri]) } precision[ci] = tp / tpfp } fmt.Println("precision: ", precision) } // Discussion: // For a classification problem like this, it would be better to replace the InferBayesianNetwork function with a function that evaluates the model based on how well the class is predicted instead of general model likelihood. You would also typically use a separate train and testing set. // There are tradeoffs in using a discrete bayesian network such as this. On the one hand, the model can approximate arbitrary distributions with multinomials with increasing numbers of buckets. On the other hand, as the number of buckets increases, the number of observations necessary to support the increased complexity grows very quickly. A continuous bayesian network might reduce the number of necessary observations by offloading some of the intelligence into the distribution types used.
example.go
0.671794
0.410402
example.go
starcoder
package registration import ( "context" "testing" "github.com/ory/kratos/ui/node" "github.com/ory/x/assertx" "github.com/bxcodec/faker/v3" "github.com/gofrs/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/ory/kratos/x" ) type FlowPersister interface { UpdateRegistrationFlow(context.Context, *Flow) error CreateRegistrationFlow(context.Context, *Flow) error GetRegistrationFlow(context.Context, uuid.UUID) (*Flow, error) } type FlowPersistenceProvider interface { RegistrationFlowPersister() FlowPersister } func TestFlowPersister(ctx context.Context, p FlowPersister) func(t *testing.T) { var clearids = func(r *Flow) { r.ID = uuid.UUID{} } return func(t *testing.T) { t.Run("case=should error when the registration flow does not exist", func(t *testing.T) { _, err := p.GetRegistrationFlow(ctx, x.NewUUID()) require.Error(t, err) }) var newFlow = func(t *testing.T) *Flow { var r Flow require.NoError(t, faker.FakeData(&r)) clearids(&r) return &r } t.Run("case=should create a new registration flow and properly set IDs", func(t *testing.T) { r := newFlow(t) err := p.CreateRegistrationFlow(ctx, r) require.NoError(t, err, "%#v", err) assert.NotEqual(t, uuid.Nil, r.ID) }) t.Run("case=should create with set ids", func(t *testing.T) { var r Flow require.NoError(t, faker.FakeData(&r)) require.NoError(t, p.CreateRegistrationFlow(ctx, &r)) }) t.Run("case=should create and fetch a registration flow", func(t *testing.T) { expected := newFlow(t) err := p.CreateRegistrationFlow(ctx, expected) require.NoError(t, err) actual, err := p.GetRegistrationFlow(ctx, expected.ID) require.NoError(t, err) assert.EqualValues(t, expected.ID, actual.ID) x.AssertEqualTime(t, expected.IssuedAt, actual.IssuedAt) x.AssertEqualTime(t, expected.ExpiresAt, actual.ExpiresAt) assert.EqualValues(t, expected.RequestURL, actual.RequestURL) assert.EqualValues(t, expected.Active, actual.Active) assertx.EqualAsJSON(t, expected.UI, actual.UI, "expected:\t%s\nactual:\t%s", expected.UI, actual.UI) }) t.Run("case=should not cause data loss when updating a request without changes", func(t *testing.T) { expected := newFlow(t) expected.UI.Nodes = node.Nodes{} expected.UI.Nodes.Append(node.NewInputField("zab", nil, node.DefaultGroup, "bar", node.WithInputAttributes(func(a *node.InputAttributes) { a.Pattern = "baz" }))) expected.UI.Nodes.Append(node.NewInputField("foo", nil, node.DefaultGroup, "bar", node.WithInputAttributes(func(a *node.InputAttributes) { a.Pattern = "baz" }))) err := p.CreateRegistrationFlow(ctx, expected) require.NoError(t, err) expected.UI.Action = "/new-action" expected.UI.Nodes.Append( node.NewInputField("zab", nil, node.DefaultGroup, "zab", node.WithInputAttributes(func(a *node.InputAttributes) { a.Pattern = "zab" }))) expected.RequestURL = "/new-request-url" require.NoError(t, p.UpdateRegistrationFlow(ctx, expected)) actual, err := p.GetRegistrationFlow(ctx, expected.ID) require.NoError(t, err) assert.Equal(t, "/new-action", actual.UI.Action) assert.Equal(t, "/new-request-url", actual.RequestURL) assertx.EqualAsJSON(t, node.Nodes{ // v0.5: {Name: "zab", Type: "zab", Pattern: "zab"}, node.NewInputField("zab", nil, node.DefaultGroup, "bar", node.WithInputAttributes(func(a *node.InputAttributes) { a.Pattern = "baz" })), node.NewInputField("foo", nil, node.DefaultGroup, "bar", node.WithInputAttributes(func(a *node.InputAttributes) { a.Pattern = "baz" })), // v0.5: {Name: "zab", Type: "bar", Pattern: "baz"}, node.NewInputField("zab", nil, node.DefaultGroup, "zab", node.WithInputAttributes(func(a *node.InputAttributes) { a.Pattern = "zab" })), }, actual.UI.Nodes) }) } }
selfservice/flow/registration/persistence.go
0.598077
0.593109
persistence.go
starcoder
package diff import ( "github.com/liquidata-inc/dolt/go/libraries/doltcore/schema" ) type SchemaChangeType int const ( // SchDiffNone is the SchemaChangeType for two columns with the same tag that are identical SchDiffNone SchemaChangeType = iota // SchDiffAdded is the SchemaChangeType when a column is in the new schema but not the old SchDiffColAdded // SchDiffRemoved is the SchemaChangeType when a column is in the old schema but not the new SchDiffColRemoved // SchDiffModified is the SchemaChangeType for two columns with the same tag that are different SchDiffColModified ) // SchemaDifference is the result of comparing two columns from two schemas. type SchemaDifference struct { DiffType SchemaChangeType Tag uint64 Old *schema.Column New *schema.Column } // DiffSchemas compares two schemas by looking at columns with the same tag. func DiffSchemas(sch1, sch2 schema.Schema) (map[uint64]SchemaDifference, error) { colPairMap, err := pairColumns(sch1, sch2) if err != nil { return nil, err } diffs := make(map[uint64]SchemaDifference) for tag, colPair := range colPairMap { if colPair[0] == nil { diffs[tag] = SchemaDifference{SchDiffColAdded, tag, nil, colPair[1]} } else if colPair[1] == nil { diffs[tag] = SchemaDifference{SchDiffColRemoved, tag, colPair[0], nil} } else if !colPair[0].Equals(*colPair[1]) { diffs[tag] = SchemaDifference{SchDiffColModified, tag, colPair[0], colPair[1]} } else { diffs[tag] = SchemaDifference{SchDiffNone, tag, colPair[0], colPair[1]} } } return diffs, nil } // pairColumns loops over both sets of columns pairing columns with the same tag. func pairColumns(sch1, sch2 schema.Schema) (map[uint64][2]*schema.Column, error) { colPairMap := make(map[uint64][2]*schema.Column) err := sch1.GetAllCols().Iter(func(tag uint64, col schema.Column) (stop bool, err error) { colPairMap[tag] = [2]*schema.Column{&col, nil} return false, nil }) if err != nil { return nil, err } err = sch2.GetAllCols().Iter(func(tag uint64, col schema.Column) (stop bool, err error) { if pair, ok := colPairMap[tag]; ok { pair[1] = &col colPairMap[tag] = pair } else { colPairMap[tag] = [2]*schema.Column{nil, &col} } return false, nil }) return colPairMap, nil }
go/libraries/doltcore/diff/schema_diff.go
0.562898
0.593668
schema_diff.go
starcoder
package fuzzydice import ( "errors" "fmt" "reflect" "sort" "strings" ) // FuzzyDice describes a FuzzyDice instance with loaded objects. A single FuzzyDice instance can contain structures of // varying types, as long as they share common fields for searching. type FuzzyDice struct { objects []object } // Load will load searchable data into the instance. Searchable data can either be a singular Struct, or a Slice of // Structs. Not all objects fed into the search need to be of the same type, however, they must share common field names // that can be searched on. func (f *FuzzyDice) Load(source interface{}, fields ...string) error { value := reflect.ValueOf(source) switch value.Kind() { case reflect.Struct: for _, field := range fields { if !value.FieldByName(field).IsValid() { panic("Field doesn't exist " + field) } } f.objects = append(f.objects, object{ source: source, fields: fields, }) case reflect.Slice: for i := 0; i < value.Len(); i++ { item := value.Index(i) if item.Kind() == reflect.Struct { f.Load(item.Interface(), fields...) } } default: return errors.New("Unsupported type provided.") } return nil } // BestMatch will find the top ranked match for a given query. It will return the matching interface{} and a float32 // similarity value. If there are no matches available, the match will return nil as the interface{}. func (f *FuzzyDice) BestMatch(query string) (interface{}, float32) { results := f.Rank(query) if len(results) > 0 { return results[0].Source, results[0].Rank } return nil, 0 } // Matches will return all matches for a given query. The resulting interface{} will contain each of the matching // objects that were loaded in that were matched. func (f *FuzzyDice) Matches(query string) []interface{} { ranks := f.Rank(query) results := make([]interface{}, len(ranks)) for i, r := range ranks { results[i] = r.Source } return results } // Rank will perform the search for a given query. It will return a []RankedObject that contains a reference to the // source object that matched, as well as the similarity coefficient of the match to the query. func (f *FuzzyDice) Rank(query string) []RankedObject { ranks := []RankedObject{} for _, o := range f.objects { distance := o.rank(normalize(query)) if distance <= 0 { continue } ranks = append(ranks, RankedObject{ Source: o.source, Rank: distance, }) } if len(ranks) == 0 { return []RankedObject{} } sort.Slice(ranks, func(i, j int) bool { return ranks[i].Rank > ranks[j].Rank }) return ranks } type object struct { source interface{} fields []string } // RankedObject is a return structure containing found source matches, and their similarity coefficient ranking. type RankedObject struct { Source interface{} Rank float32 } func (o object) rank(query string) float32 { var highestRank float32 highestRank = -1 for _, field := range o.fields { for _, value := range valuesForField(o, field) { rank := calcCoefficient(query, value) if rank > highestRank { highestRank = rank } } } return highestRank } func calcCoefficient(source, target string) float32 { if value := returnEarlyIfPossible(source, target); value >= 0 { return value } bigrams := make(map[string]int) for i := 0; i < len(source)-1; i++ { var count int bigram := makeBigram(source, i) if value, ok := bigrams[bigram]; ok { count = value + 1 } else { count = 1 } bigrams[bigram] = count } var intersectionSize float32 intersectionSize = 0 for i := 0; i < len(target)-1; i++ { var count int bigram := makeBigram(target, i) if value, ok := bigrams[bigram]; ok { count = value } else { count = 0 } if count > 0 { bigrams[bigram] = count - 1 intersectionSize = intersectionSize + 1 } } return (2.0 * intersectionSize) / (float32(len(source)) + float32(len(target)) - 2) } func makeBigram(source string, index int) string { a := fmt.Sprintf("%c", source[index]) b := fmt.Sprintf("%c", source[index+1]) return a + b } func normalize(s string) string { return strings.Replace(strings.ToLower(s), " ", "", -1) } func returnEarlyIfPossible(source, target string) float32 { if len(source) == 0 && len(target) == 0 { return 1 } if len(source) == 0 || len(target) == 0 { return 0 } if source == target { return 1 } if len(source) == 1 && len(target) == 1 { return 0 } if len(source) < 2 || len(target) < 2 { return 0 } return -1 } func valuesForField(o object, fieldName string) []string { field := reflect.ValueOf(o.source).FieldByName(fieldName) if strSlice, isStrSlice := field.Interface().([]string); isStrSlice { lc := make([]string, len(strSlice)) for i, s := range strSlice { lc[i] = normalize(s) } return lc } return []string{normalize(field.String())} }
fuzzydice.go
0.784319
0.504639
fuzzydice.go
starcoder
package frenyard // Constants // SizeUnlimited is equal to the maximum value an int32 can have, represents an infinite value. Note that 0x80000000 is reserved; -0x7FFFFFFF is considered the definitive 'negative unlimited' value for simplicity's sake. const SizeUnlimited int32 = 0x7FFFFFFF // Vec2iUnlimited returns a Vec2i of unlimited size. func Vec2iUnlimited() Vec2i { return Vec2i{SizeUnlimited, SizeUnlimited} } // AddCU performs an addition with consideration for unlimited values. func AddCU(a int32, b int32) int32 { if a == SizeUnlimited { if b == -SizeUnlimited { return 0 } return SizeUnlimited } else if b == SizeUnlimited { if a == -SizeUnlimited { return 0 } return SizeUnlimited } else if a == -SizeUnlimited { return -SizeUnlimited } else if b == -SizeUnlimited { return -SizeUnlimited } return a + b } // Part I: Basic maths // Max returns the higher of two int32 values. func Max(a int32, b int32) int32 { if a > b { return a } return b } // Min returns the smaller of two int32 values. func Min(a int32, b int32) int32 { if a < b { return a } return b } // Part II: Point Type // Vec2i is the basic 2-dimensional vector type. type Vec2i struct { X, Y int32 } // Add adds two Vec2is. func (a Vec2i) Add(b Vec2i) Vec2i { return Vec2i{AddCU(a.X, b.X), AddCU(a.Y, b.Y)} } // Min returns a Vec2i with each axis value being the minimum of the two input Vec2i values on that axis. func (a Vec2i) Min(b Vec2i) Vec2i { return Vec2i{Min(a.X, b.X), Min(a.Y, b.Y)} } // Max is similar to Min, but uses maximum, not minimum. func (a Vec2i) Max(b Vec2i) Vec2i { return Vec2i{Max(a.X, b.X), Max(a.Y, b.Y)} } // Eq compares two Vec2is and returns true for equal. func (a Vec2i) Eq(b Vec2i) bool { return a.X == b.X && a.Y == b.Y } // These two are framed in the sense of 'an area of size A could contain an area of size B'. // Gt checks if an area of size A could hold an area of size B with room to spare. func (a Vec2i) Gt(b Vec2i) bool { return a.X > b.X && a.Y > b.Y } // Ge checks if an area of size A could hold an area of size B (with or without spare room). func (a Vec2i) Ge(b Vec2i) bool { return a.X >= b.X && a.Y >= b.Y } // Negate returns the vector multiplied by -1. func (a Vec2i) Negate() Vec2i { return Vec2i{-a.X, -a.Y} } // ConditionalTranspose conditionally swaps X/Y, which is useful when the coordinate system is variable. func (a Vec2i) ConditionalTranspose(yes bool) Vec2i { if yes { return Vec2i{a.Y, a.X} } return Vec2i{a.X, a.Y} } // Part III: Area Types (AABBs) // Area1i is a 1-dimensional axis-aligned area, which is a useful primitive for N-dimensional areas. Please note that Area1i, and by extension Area2i, may malfunction if given infinite values. type Area1i struct { Pos int32 Size int32 } // Area1iOfSize returns an Area1i of the given size (covering range inclusive 0 to exclusive size) func Area1iOfSize(a int32) Area1i { return Area1i{0, a} } // Area1iMargin is a quick idiom for a margin of a given size. func Area1iMargin(l int32, r int32) Area1i { return Area1i{-l, l + r} } // Empty returns Size <= 0 func (a Area1i) Empty() bool { return a.Size <= 0 } // Normalized replaces empty areas with zeroed areas. func (a Area1i) Normalized() Area1i { if a.Empty() { return Area1i{} } return a } // Union unions two areas. func (a Area1i) Union(b Area1i) Area1i { pos := Min(a.Pos, b.Pos) end := Max(a.Pos+a.Size, b.Pos+b.Size) return Area1i{ pos, end - pos, } } // Intersect intersects two areas. Always returns a normalized area. func (a Area1i) Intersect(b Area1i) Area1i { pos := Max(a.Pos, b.Pos) end := Min(a.Pos+a.Size, b.Pos+b.Size) return Area1i{ pos, end - pos, }.Normalized() } // Translate translates an area by an offset. func (a Area1i) Translate(i int32) Area1i { return Area1i{a.Pos + i, a.Size} } // Expand expands an area by a margin, expressed as the area around as if this had zero size. func (a Area1i) Expand(n Area1i) Area1i { return Area1i{a.Pos + n.Pos, a.Size + n.Size} } // Contract contracts an area by a margin; the reverse of Expand. func (a Area1i) Contract(n Area1i) Area1i { return Area1i{a.Pos - n.Pos, a.Size - n.Size} } // Contains checks if a point is within the area. func (a Area1i) Contains(i int32) bool { return (i >= a.Pos) && (i < a.Pos+a.Size) } // Align aligns an area within another. func (a Area1i) Align(content int32, x Alignment1i) Area1i { if x == AlignStart { return Area1i{ a.Pos, content, } } else if x == AlignEnd { return Area1i{ a.Size - content, content, } } else { return Area1i{ ((a.Size - content) / 2) + a.Pos, content, } } } // UnionArea1i gets an area containing all areas in the given slice func UnionArea1i(areas []Area1i) Area1i { base := Area1i{} for _, area := range areas { base = base.Union(area) } return base } // Area2i is the basic rectangle type. Please note that Area2i may malfunction if given infinite values. type Area2i struct { X Area1i Y Area1i } // Pos returns a 'position' vector for the area. (see Area2iFromVecs) func (a Area2i) Pos() Vec2i { return Vec2i{a.X.Pos, a.Y.Pos} } // Size returns a 'size' vector for the area (see Area2iFromVecs) func (a Area2i) Size() Vec2i { return Vec2i{a.X.Size, a.Y.Size} } // Area2iFromVecs returns an Area2i made from a position/size vector pair. func Area2iFromVecs(pos Vec2i, size Vec2i) Area2i { return Area2i{ Area1i{pos.X, size.X}, Area1i{pos.Y, size.Y}, } } // Area2iOfSize returns an Area2i of the given size. func Area2iOfSize(a Vec2i) Area2i { return Area2i{Area1iOfSize(a.X), Area1iOfSize(a.Y)} } // Area2iMargin is a quick idiom for a margin of a given size. func Area2iMargin(l int32, u int32, r int32, d int32) Area2i { return Area2i{Area1iMargin(l, r), Area1iMargin(u, d)} } // Empty returns Size <= 0 func (a Area2i) Empty() bool { return a.X.Empty() || a.Y.Empty() } // Normalized replaces empty areas with zeroed areas. func (a Area2i) Normalized() Area2i { if a.Empty() { return Area2i{} } return a } // Union unions two areas. func (a Area2i) Union(b Area2i) Area2i { return Area2i{a.X.Union(b.X), a.Y.Union(b.Y)} } // Intersect intersects two areas. Always returns a normalized area. func (a Area2i) Intersect(b Area2i) Area2i { return Area2i{a.X.Intersect(b.X), a.Y.Intersect(b.Y)}.Normalized() } // Translate translates an area by an offset. func (a Area2i) Translate(v Vec2i) Area2i { return Area2i{a.X.Translate(v.X), a.Y.Translate(v.Y)} } // Expand expands an area by a margin, expressed as the area around as if this had zero size. func (a Area2i) Expand(b Area2i) Area2i { return Area2i{a.X.Expand(b.X), a.Y.Expand(b.Y)} } // Contract contracts an area by a margin; the reverse of Expand. func (a Area2i) Contract(b Area2i) Area2i { return Area2i{a.X.Contract(b.X), a.Y.Contract(b.Y)} } // Contains checks if a point is within the area. func (a Area2i) Contains(v Vec2i) bool { return a.X.Contains(v.X) && a.Y.Contains(v.Y) } // Align aligns an area within another. func (a Area2i) Align(content Vec2i, align Alignment2i) Area2i { return Area2i{ a.X.Align(content.X, align.X), a.Y.Align(content.Y, align.Y), } } // UnionArea2i gets an area containing all areas in the given slice func UnionArea2i(areas []Area2i) Area2i { base := Area2i{} for _, area := range areas { base = base.Union(area) } return base } // Part IV: Alignment Structures (see Align methods of areas) // Alignment1i specifies an alignment preference along an axis. type Alignment1i int8 // AlignStart aligns the element at the start (left/top). const AlignStart Alignment1i = -1 // AlignMiddle aligns the element at the centre. const AlignMiddle Alignment1i = 0 // AlignEnd aligns the element at the end (right/bottom). const AlignEnd Alignment1i = 1 // Alignment2i contains two Alignment1is (one for each axis). type Alignment2i struct { X Alignment1i Y Alignment1i } // Part V: Even More Utilities // Area1iGrid3 is an Area1i split into a left area, the original 'inner' area, and the right area. type Area1iGrid3 struct { A Area1i B Area1i C Area1i } // SplitArea1iGrid3 splits an Area1i into 3 sections using the bounds of an inner Area1i. func SplitArea1iGrid3(outer Area1i, inner Area1i) Area1iGrid3 { return Area1iGrid3{ Area1i{outer.Pos, inner.Pos - outer.Pos}, inner, Area1i{inner.Pos + inner.Size, (outer.Pos + outer.Size) - (inner.Pos + inner.Size)}, } } // AsMargin returns a margin around the centre Area1i for Expand. func (a Area1iGrid3) AsMargin() Area1i { return Area1i{-a.A.Size, a.C.Size + a.A.Size} } // Area2iGrid3x3 is Area1iGrid3 in two dimensions. type Area2iGrid3x3 struct { A Area2i B Area2i C Area2i D Area2i E Area2i F Area2i G Area2i H Area2i I Area2i } // SplitArea2iGrid3x3 splits an Area2i into 9 sections using the bounds of an inner Area2i. func SplitArea2iGrid3x3(outer Area2i, inner Area2i) Area2iGrid3x3 { xSplit := SplitArea1iGrid3(outer.X, inner.X) ySplit := SplitArea1iGrid3(outer.Y, inner.Y) return Area2iGrid3x3{ Area2i{xSplit.A, ySplit.A}, Area2i{xSplit.B, ySplit.A}, Area2i{xSplit.C, ySplit.A}, Area2i{xSplit.A, ySplit.B}, Area2i{xSplit.B, ySplit.B}, Area2i{xSplit.C, ySplit.B}, Area2i{xSplit.A, ySplit.C}, Area2i{xSplit.B, ySplit.C}, Area2i{xSplit.C, ySplit.C}, } } // AsMargin returns a margin around the centre Area2i for Expand. func (a Area2iGrid3x3) AsMargin() Area2i { return Area2iFromVecs(a.A.Size().Negate(), a.I.Size().Add(a.A.Size())) } // Part VI: Easings // EasingQuadraticIn is a quadratic ease-in function, which in practice means it just squares the input value. func EasingQuadraticIn(point float64) float64 { return point * point } // EasingInOut currys a function. Given an ease-in function, returns an ease in-out function. func EasingInOut(easeIn func (float64) float64) func(float64) float64 { return func (point float64) float64 { if point < 0.5 { return easeIn(point * 2.0) / 2.0 } return 1.0 - (easeIn(2.0 - (point * 2.0)) / 2.0) } }
frenyard/coreMaths.go
0.900677
0.563738
coreMaths.go
starcoder
package el import ( g "github.com/maragudk/gomponents" ) // Address returns an element with name "address" and the given children. func Address(children ...g.Node) g.NodeFunc { return g.El("address", children...) } // Article returns an element with name "article" and the given children. func Article(children ...g.Node) g.NodeFunc { return g.El("article", children...) } // Aside returns an element with name "aside" and the given children. func Aside(children ...g.Node) g.NodeFunc { return g.El("aside", children...) } // Footer returns an element with name "footer" and the given children. func Footer(children ...g.Node) g.NodeFunc { return g.El("footer", children...) } // Header returns an element with name "header" and the given children. func Header(children ...g.Node) g.NodeFunc { return g.El("header", children...) } // H1 returns an element with name "h1", the given text content, and the given children. func H1(text string, children ...g.Node) g.NodeFunc { return g.El("h1", g.Text(text), g.Group(children)) } // H2 returns an element with name "h2", the given text content, and the given children. func H2(text string, children ...g.Node) g.NodeFunc { return g.El("h2", g.Text(text), g.Group(children)) } // H3 returns an element with name "h3", the given text content, and the given children. func H3(text string, children ...g.Node) g.NodeFunc { return g.El("h3", g.Text(text), g.Group(children)) } // H4 returns an element with name "h4", the given text content, and the given children. func H4(text string, children ...g.Node) g.NodeFunc { return g.El("h4", g.Text(text), g.Group(children)) } // H5 returns an element with name "h5", the given text content, and the given children. func H5(text string, children ...g.Node) g.NodeFunc { return g.El("h5", g.Text(text), g.Group(children)) } // H6 returns an element with name "h6", the given text content, and the given children. func H6(text string, children ...g.Node) g.NodeFunc { return g.El("h6", g.Text(text), g.Group(children)) } // HGroup returns an element with name "hgroup" and the given children. func HGroup(children ...g.Node) g.NodeFunc { return g.El("hgroup", children...) } // Main returns an element with name "main" and the given children. func Main(children ...g.Node) g.NodeFunc { return g.El("main", children...) } // Nav returns an element with name "nav" and the given children. func Nav(children ...g.Node) g.NodeFunc { return g.El("nav", children...) } // Section returns an element with name "section" and the given children. func Section(children ...g.Node) g.NodeFunc { return g.El("section", children...) }
el/section.go
0.86267
0.449816
section.go
starcoder
package main import ( "math" "github.com/ByteArena/box2d" "github.com/wdevore/Ranger-Go-IGE/api" "github.com/wdevore/Ranger-Go-IGE/extras/particles" "github.com/wdevore/Ranger-Go-IGE/extras/shapes" ) // Lava particle type triPhysicsComponent struct { particles.Particle physicsComponent categoryBits uint16 // I am a... maskBits uint16 // I can collide with a... initialPosition api.IPoint direction float64 angularVel float64 force float64 debug int } func newTriPhysicsComponent() *triPhysicsComponent { o := new(triPhysicsComponent) return o } func (p *triPhysicsComponent) Configure( phyWorld *box2d.B2World, parent api.INode, id int, scale float32, color api.IPalette, position api.IPoint) error { var err error p.initialPosition = position // fmt.Sprintf("::Lava%d", id) p.phyNode, err = shapes.NewMonoTriangleNode("::Lava", api.FILLED, parent.World(), parent) if err != nil { return err } p.phyNode.SetScale(scale) p.phyNode.SetPosition(position.X(), position.Y()) p.phyNode.SetVisible(false) gt := p.phyNode.(*shapes.MonoTriangleNode) gt.SetFilledColor(color) return nil } func (p *triPhysicsComponent) Build(phyWorld *box2d.B2World, position api.IPoint) { // A body def used to create bodies bDef := box2d.MakeB2BodyDef() bDef.Type = box2d.B2BodyType.B2_dynamicBody // Set the initial position of the Body px := p.phyNode.Position().X() py := p.phyNode.Position().Y() bDef.Position.Set( float64(px), float64(py), ) // An instance of a body to contain Fixtures p.b2Body = phyWorld.CreateBody(&bDef) tcc := p.phyNode.(*shapes.MonoTriangleNode) // Box2D expects polygon edges to be defined at full length, not // half-side scale := tcc.SideLength() verts := tcc.Vertices() vertices := []box2d.B2Vec2{} for i := 0; i < len(*verts); i += api.XYZComponentCount { vertices = append(vertices, box2d.B2Vec2{X: float64((*verts)[i] * scale), Y: float64((*verts)[i+1] * scale)}) } // Every Fixture has a shape b2Shape := box2d.MakeB2PolygonShape() b2Shape.Set(vertices, len(vertices)) fd := box2d.MakeB2FixtureDef() fd.Shape = &b2Shape fd.Density = 1.0 fd.Filter.CategoryBits = p.categoryBits fd.Filter.MaskBits = p.maskBits fd.Friction = 0.1 fd.Restitution = 0.4 p.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body } func (p *triPhysicsComponent) ConfigureFilter(categoryBits, maskBits uint16) { p.categoryBits = categoryBits p.maskBits = maskBits } // EnableGravity enables/disables gravity for this component func (p *triPhysicsComponent) EnableGravity(enable bool) { if enable { p.b2Body.SetGravityScale(1.0) } else { p.b2Body.SetGravityScale(0.0) } } func (p *triPhysicsComponent) Update() { if p.b2Body.IsActive() { pos := p.b2Body.GetPosition() p.phyNode.SetPosition(float32(pos.X), float32(pos.Y)) rot := p.b2Body.GetAngle() p.phyNode.SetRotation(rot) } } //----------------------------------------------------------------- // Particles //----------------------------------------------------------------- // SetLifespan sets how long the Particle lives func (p *triPhysicsComponent) SetLifespan(duration float32) { p.Particle.SetLifespan(duration) } // Activate changes the Particle's state func (p *triPhysicsComponent) Activate(active bool) { p.Particle.Activate(active) // Note: All physic properties must be reset otherwise they // carry over into the next activation causing compounding effects. // So even though only an Angular velocity was applied, during the // simulation linear velocities manifest during collisions, we need // to clear any linear effects too. p.b2Body.SetLinearVelocity(box2d.MakeB2Vec2(0.0, 0.0)) p.b2Body.SetTransform( box2d.MakeB2Vec2(float64(p.initialPosition.X()), float64(p.initialPosition.Y())), 0.0) if !active { return } p.b2Body.SetAngularVelocity(p.angularVel) // Apply force upwards p.b2Body.ApplyLinearImpulse( box2d.B2Vec2{X: math.Cos(p.direction) * p.force, Y: math.Sin(p.direction) * p.force}, p.b2Body.GetWorldCenter(), true) } // IsActive indicates if the Particle is alive func (p *triPhysicsComponent) IsActive() bool { return p.Particle.IsActive() } // Update changes the Particle's state based on time func (p *triPhysicsComponent) Evaluate(dt float32) { p.Particle.Evaluate(dt) // Update Particle's position as long as the Particle is active. p.phyNode.SetVisible(p.Particle.IsActive()) } // Reset resets the Particle func (p *triPhysicsComponent) Reset() { p.Particle.Reset() p.phyNode.SetVisible(false) } // ParticleConfigure configures a particle prior to activation. func (p *triPhysicsComponent) ParticleConfigure(direction, angularVel, force float64) { p.direction = direction p.angularVel = angularVel p.force = force }
examples/complex/physics/complex/c4_lava/tri_physics_component.go
0.744285
0.480296
tri_physics_component.go
starcoder
package main import ( "image/color" "math" "github.com/hajimehoshi/ebiten" "github.com/hajimehoshi/ebiten/text" "github.com/hajimehoshi/ebiten/vector" "golang.org/x/image/font" "golang.org/x/image/math/fixed" ) // Draws a block color polygon. func drawPolygon(screen *ebiten.Image, clr color.Color, coordinates []vertex) { path := vector.Path{} path.MoveTo(float32(coordinates[0][0]), float32(coordinates[0][1])) for i := 1; i < len(coordinates); i++ { path.LineTo(float32(coordinates[i][0]), float32(coordinates[i][1])) } path.MoveTo(float32(coordinates[0][0]), float32(coordinates[0][1])) path.Fill(screen, &vector.FillOptions{ Color: clr, }) } // Draws an outlined polygon. // Note that to account for the function not being able to properly stroke // asymmetrical polygons, if width is less than 1 the stroke will proportional // to the shape. So a width of ".8" would the stroke is 20% wide. This was // added last minute and would ideally be removed so triangles could be evenly // stroked. func drawPolygonLine(screen *ebiten.Image, width float64, borderColor color.Color, fillColor color.Color, coordinates []vertex) { drawPolygon(screen, borderColor, coordinates) centerX := 0 centerY := 0 for i := range coordinates { centerX += coordinates[i][0] centerY += coordinates[i][1] } centerX = centerX / len(coordinates) centerY = centerY / len(coordinates) for i := range coordinates { if width < 1 { coordinates[i][0] = centerX + int(float64(coordinates[i][0]-centerX)*width) coordinates[i][1] = centerY + int(float64(coordinates[i][1]-centerY)*width) continue } offsetX := width offsetY := width if coordinates[i][0] > centerX { offsetX = offsetX * -1 } if coordinates[i][1] > centerY { offsetY = offsetY * -1 } coordinates[i][0] = centerX + int(float64(coordinates[i][0]-centerX)+offsetX) coordinates[i][1] = centerY + int(float64(coordinates[i][1]-centerY)+offsetY) } drawPolygon(screen, fillColor, coordinates) } // Calculates the distance between two vertexes. func distance(p1, p2 vertex) float64 { first := math.Pow(float64(p2[0]-p1[0]), 2) second := math.Pow(float64(p2[1]-p1[1]), 2) return math.Sqrt(first + second) } // Used to calculate the match chart's points. func getHexPoints(x, y int) []vertex { return []vertex{ {50 + x, 0 + y}, {100 + x, 25 + y}, {100 + x, 75 + y}, {50 + x, 100 + y}, {0 + x, 75 + y}, {0 + x, 25 + y}, } } // Gets the boundary points of the match chart. These are used to draw the // triangle on the match chart and handle drag and drop. func getHexBoundaryPoints(hexPoints []vertex) []vertex { points := make([]vertex, 0) for i := 0; i < len(hexPoints); i++ { nextIndex := i + 1 if nextIndex >= len(hexPoints) { nextIndex = 0 } xDelta := float64(hexPoints[nextIndex][0]-hexPoints[i][0]) / 17 yDelta := float64(hexPoints[nextIndex][1]-hexPoints[i][1]) / 17 for j := 0.0; j < 17; j++ { points = append(points, vertex{ hexPoints[i][0] + int(j*xDelta), hexPoints[i][1] + int(j*yDelta), }) } } return points } // Checks if the mouse is colliding with a collision box. func isMouseColliding(x, y, width, height int) bool { mouseX, mouseY := ebiten.CursorPosition() return mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height } // Gets the vertexes used to draw a button. func getButtonBounds(buttonText string, x, y int) []vertex { width := getTextWidth(buttonText, defaultFont) return []vertex{{x, y}, {x + width + 20, y}, {x + width + 20, y + 40}, {x, y + 40}} } // Checks if the mouse is colliding with a button. func isButtonColliding(buttonText string, x, y int) bool { bounds := getButtonBounds(buttonText, x, y) return isMouseColliding(x, y, bounds[2][0]-x, bounds[2][1]-y) } // Draws a button with the given text. func drawButton(screen *ebiten.Image, buttonText string, x, y int) { drawPolygonLine(screen, 2, defaultColors["darkPink"], defaultColors["white"], getButtonBounds(buttonText, x, y)) clr := defaultColors["purple"] if isButtonColliding(buttonText, x, y) { clr = defaultColors["darkPink"] } text.Draw(screen, buttonText, defaultFont, x+10, y+25, clr) } // Calculates text width - very useful for centering text. func getTextWidth(text string, face font.Face) int { width := fixed.I(0) prevR := rune(-1) largestWidth := fixed.I(0) for _, r := range []rune(text) { if r == '\n' { width = 0 prevR = rune(-1) continue } if prevR >= 0 { width += face.Kern(prevR, r) } a, ok := face.GlyphAdvance(r) if !ok { panic("Unable to determine glyph width") } width += a prevR = r if width > largestWidth { largestWidth = width } } return largestWidth.Round() }
shared.go
0.727298
0.459864
shared.go
starcoder
package day5 import ( "adventofcode/utils" "fmt" "strconv" "strings" ) func orderedPath(a int, b int) (int, int) { if a < b { return a, b } else { return b, a } } func ParseWindMatrix(winds []string, parseDiagonal bool) [][]uint8 { matrixDim := 1000 matrix := make([][]uint8, matrixDim) for i := range matrix { matrix[i] = make([]uint8, matrixDim) } for _, wind := range winds { windSplits := strings.Split(wind, " -> ") startSplits := strings.Split(windSplits[0], ",") endSplits := strings.Split(windSplits[1], ",") startX, _ := strconv.Atoi(startSplits[0]) startY, _ := strconv.Atoi(startSplits[1]) endX, _ := strconv.Atoi(endSplits[0]) endY, _ := strconv.Atoi(endSplits[1]) // vertical if startX == endX { minY, maxY := orderedPath(startY, endY) for y := minY; y <= maxY; y++ { matrix[startX][y] = matrix[startX][y] + 1 } } // horizontal if startY == endY { minX, maxX := orderedPath(startX, endX) for x := minX; x <= maxX; x++ { matrix[x][startY] = matrix[x][startY] + 1 } } // diagonal if parseDiagonal { minY, maxY := orderedPath(startY, endY) minX, maxX := orderedPath(startX, endX) if maxY-minY == maxX-minX { for d := 0; d <= maxX-minX; d++ { if startX < endX && startY < endY { matrix[startX+d][startY+d] = matrix[startX+d][startY+d] + 1 } else if startX < endX && startY > endY { matrix[startX+d][startY-d] = matrix[startX+d][startY-d] + 1 } else if startX > endX && startY < endY { matrix[startX-d][startY+d] = matrix[startX-d][startY+d] + 1 } else { matrix[startX-d][startY-d] = matrix[startX-d][startY-d] + 1 } } } } } return matrix } func CountTresholdValues(matrix [][]uint8, treshold uint8) int { thresholdCounter := 0 for i := 0; i < len(matrix); i++ { for j := 0; j < len(matrix[i]); j++ { if matrix[i][j] >= treshold { thresholdCounter++ } } } return thresholdCounter } func PrintSolution() { wind := utils.ParseLines("./inputs/day5.txt") windMatrix := ParseWindMatrix(wind, false) counter := CountTresholdValues(windMatrix, 2) fmt.Println("Wind Counter (Part 1)", counter) windMatrixDiagonal := ParseWindMatrix(wind, true) counterDiagonal := CountTresholdValues(windMatrixDiagonal, 2) fmt.Println("Wind Counter with Diagonal (Part 2)", counterDiagonal) }
day5/day5.go
0.680454
0.446857
day5.go
starcoder
package parser import ( "os" "github.com/goccy/go-graphviz/cgraph" ) type Parser struct { Data string Index int File *os.File Graph *Graph } func (p *Parser) Block() { block := p.Graph.AddNode("block") if p.Data[p.Index] != LBRACE { panic("Left brace '{' expected") } p.apply("") lbrace := p.Graph.AddNode(string(LBRACE)) opList := p.Graph.AddNode("operatorList") p.operatorList(opList) if p.Data[p.Index] != RBRACE { panic("Right brace '}' expected") } p.apply("") rbrace := p.Graph.AddNode(string(RBRACE)) if p.Index < len(p.Data) { panic("Something odd in the end") } p.Graph.AddEdges(block, lbrace, opList, rbrace) } func (p *Parser) operatorList(begin *cgraph.Node) { operator := p.Graph.AddNode("operator") p.operator(operator) tail := p.Graph.AddNode("tail") p.tail(tail) p.Graph.AddEdges(begin, operator, tail) } func (p *Parser) operator(begin *cgraph.Node) { id := p.Graph.AddNode("identifier") p.identifier(id) if p.Data[p.Index] != EQ { panic("Equal sign '=' expected") } p.apply("") eq := p.Graph.AddNode(string(EQ)) expr := p.Graph.AddNode("expression") p.Expression(expr) p.Graph.AddEdges(begin, id, eq, expr) } func (p *Parser) tail(begin *cgraph.Node) { if p.Data[p.Index] == SEP { p.apply("") sep := p.Graph.AddNode(string(SEP)) operator := p.Graph.AddNode("operator") p.operator(operator) tail := p.Graph.AddNode("tail") p.tail(tail) p.Graph.AddEdges(begin, sep, operator, tail) return } eps := p.Graph.AddNode(EPS) p.Graph.AddEdges(begin, eps) } func (p *Parser) Expression(begin *cgraph.Node) { me1 := p.Graph.AddNode("mathExpr") p.mathExpr(me1) rs := p.Graph.AddNode("relationSign") p.relationSign(rs) me2 := p.Graph.AddNode("mathExpr") p.mathExpr(me2) p.Graph.AddEdges(begin, me1, rs, me2) } func (p *Parser) mathExpr(begin *cgraph.Node) { nodes, edges := len(p.Graph.Nodes), len(p.Graph.Edges) defer func() { if msg := recover(); msg != nil { p.Graph.DeleteNodes(p.Graph.Nodes[nodes:]) p.Graph.DeleteEdges(p.Graph.Edges[edges:]) p.Graph.Nodes = p.Graph.Nodes[:nodes] p.Graph.Edges = p.Graph.Edges[:edges] as := p.Graph.AddNode("addSign") p.addSign(as) t := p.Graph.AddNode("term") p.term(t) m := p.Graph.AddNode("math") p.math(m) p.Graph.AddEdges(begin, as, t, m) } }() t := p.Graph.AddNode("term") p.term(t) m := p.Graph.AddNode("math") p.math(m) p.Graph.AddEdges(begin, t, m) } func (p *Parser) math(begin *cgraph.Node) { nodes, edges := len(p.Graph.Nodes), len(p.Graph.Edges) defer func() { if msg := recover(); msg != nil { p.Graph.DeleteNodes(p.Graph.Nodes[nodes:]) p.Graph.DeleteEdges(p.Graph.Edges[edges:]) p.Graph.Nodes = p.Graph.Nodes[:nodes] p.Graph.Edges = p.Graph.Edges[:edges] eps := p.Graph.AddNode(EPS) p.Graph.AddEdges(begin, eps) } }() as := p.Graph.AddNode("addSign") p.addSign(as) t := p.Graph.AddNode("term") p.term(t) m := p.Graph.AddNode("math") p.math(m) p.Graph.AddEdges(begin, as, t, m) } func (p *Parser) term(begin *cgraph.Node) { f := p.Graph.AddNode("factor") p.factor(f) t := p.Graph.AddNode("term_") p.term_(t) p.Graph.AddEdges(begin, f, t) } func (p *Parser) term_(begin *cgraph.Node) { nodes, edges := len(p.Graph.Nodes), len(p.Graph.Edges) defer func() { if msg := recover(); msg != nil { p.Graph.DeleteNodes(p.Graph.Nodes[nodes:]) p.Graph.DeleteEdges(p.Graph.Edges[edges:]) p.Graph.Nodes = p.Graph.Nodes[:nodes] p.Graph.Edges = p.Graph.Edges[:edges] eps := p.Graph.AddNode(EPS) p.Graph.AddEdges(begin, eps) } }() ms := p.Graph.AddNode("mulSign") p.mulSign(ms) f := p.Graph.AddNode("factor") p.factor(f) t := p.Graph.AddNode("term_") p.term_(t) p.Graph.AddEdges(begin, ms, f, t) } func (p *Parser) factor(begin *cgraph.Node) { pe := p.Graph.AddNode("primaryExpr") p.primaryExpr(pe) f := p.Graph.AddNode("factor_") p.factor_(f) p.Graph.AddEdges(begin, pe, f) } func (p *Parser) factor_(begin *cgraph.Node) { if p.Data[p.Index] == CIRKUM { p.apply("") c := p.Graph.AddNode(string(CIRKUM)) pe := p.Graph.AddNode("primaryExpr") p.primaryExpr(pe) f := p.Graph.AddNode("factor_") p.factor_(f) p.Graph.AddEdges(begin, c, pe, f) return } eps := p.Graph.AddNode(EPS) p.Graph.AddEdges(begin, eps) } func (p *Parser) primaryExpr(begin *cgraph.Node) { nodes, edges := len(p.Graph.Nodes), len(p.Graph.Edges) defer func() { if msg := recover(); msg != nil { p.Graph.DeleteNodes(p.Graph.Nodes[nodes:]) p.Graph.DeleteEdges(p.Graph.Edges[edges:]) p.Graph.Nodes = p.Graph.Nodes[:nodes] p.Graph.Edges = p.Graph.Edges[:edges] n := p.Graph.AddNode("number") p.number(n) p.Graph.AddEdges(begin, n) } }() defer func() { if msg := recover(); msg != nil { p.Graph.DeleteNodes(p.Graph.Nodes[nodes:]) p.Graph.DeleteEdges(p.Graph.Edges[edges:]) p.Graph.Nodes = p.Graph.Nodes[:nodes] p.Graph.Edges = p.Graph.Edges[:edges] id := p.Graph.AddNode("identifier") p.identifier(id) p.Graph.AddEdges(begin, id) } }() if p.Data[p.Index] != LBRACKET { panic("Left bracket '(' expected") } p.apply("") lb := p.Graph.AddNode(string(LBRACKET)) me := p.Graph.AddNode("mathExpr") p.mathExpr(me) if p.Data[p.Index] != RBRACKET { panic("Right bracket ')' expected") } p.apply("") rb := p.Graph.AddNode(string(RBRACKET)) p.Graph.AddEdges(begin, lb, me, rb) }
rd_parser/parser/parser.go
0.512937
0.48499
parser.go
starcoder
package ridge import ( "github.com/gonum/matrix" "github.com/gonum/matrix/mat64" "fmt" "math" ) const BasicallyZero = 1.0e-15 func fmtMat(mat mat64.Matrix) fmt.Formatter { return mat64.Formatted(mat, mat64.Excerpt(2), mat64.Squeeze()) } type RidgeRegression struct { X *mat64.Dense XSVD *mat64.SVD U *mat64.Dense D *mat64.Dense V *mat64.Dense XScaled *mat64.Dense Y *mat64.Vector Scales *mat64.Vector L2Penalty float64 Coefficients *mat64.Vector Fitted []float64 Residuals []float64 StdErrs []float64 } // New returns a new ridge regression. func New(x *mat64.Dense, y *mat64.Vector, l2Penalty float64) *RidgeRegression { return &RidgeRegression{ X: x, Y: y, L2Penalty: l2Penalty, Fitted: make([]float64, y.Len()), Residuals: make([]float64, y.Len()), } } // Regress runs the ridge regression to calculate coefficients. func (r *RidgeRegression) Regress() { r.scaleX() r.solveSVD() xr, _ := r.X.Dims() fitted := mat64.NewVector(xr, nil) fitted.MulVec(r.X, r.Coefficients) r.Fitted = fitted.RawVector().Data for i := range r.Residuals { r.Residuals[i] = r.Y.At(i, 0) - r.Fitted[i] } r.calcStdErr() } func (r *RidgeRegression) scaleX() { xr, xc := r.X.Dims() scaleData := make([]float64, xr) scalar := 1.0 / float64(xr) for i := range scaleData { scaleData[i] = scalar } scaleMat := mat64.NewDense(1, xr, scaleData) sqX := mat64.NewDense(xr, xc, nil) sqX.MulElem(r.X, r.X) scales := mat64.NewDense(1, xc, nil) scales.Mul(scaleMat, sqX) sqrtElem := func(i, j int, v float64) float64 { return math.Sqrt(v) } scales.Apply(sqrtElem, scales) r.Scales = mat64.NewVector(xc, scales.RawRowView(0)) r.XScaled = mat64.NewDense(xr, xc, nil) scale := func(i, j int, v float64) float64 { return v / r.Scales.At(j, 0) } r.XScaled.Apply(scale, r.X) } func (r *RidgeRegression) solveSVD() { if r.XSVD == nil || r.XSVD.Kind() == 0 { r.XSVD = new(mat64.SVD) r.XSVD.Factorize(r.XScaled, matrix.SVDThin) } xr, xc := r.XScaled.Dims() xMinDim := int(math.Min(float64(xr), float64(xc))) u := mat64.NewDense(xr, xMinDim, nil) u.UFromSVD(r.XSVD) r.U = u s := r.XSVD.Values(nil) for i := 0; i < len(s); i++ { if s[i] < BasicallyZero { s[i] = 0 } else { s[i] = s[i] / (s[i]*s[i] + r.L2Penalty) } } d := mat64.NewDense(len(s), len(s), nil) setDiag(d, s) r.D = d v := mat64.NewDense(xc, xMinDim, nil) v.VFromSVD(r.XSVD) r.V = v uty := mat64.NewVector(xMinDim, nil) uty.MulVec(u.T(), r.Y) duty := mat64.NewVector(len(s), nil) duty.MulVec(d, uty) coef := mat64.NewVector(xc, nil) coef.MulVec(v, duty) r.Coefficients = mat64.NewVector(xc, nil) r.Coefficients.DivElemVec(coef, r.Scales) } // http://stats.stackexchange.com/a/2126 // http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3228544/ func (r *RidgeRegression) calcStdErr() { xr, xc := r.X.Dims() xMinDim := int(math.Min(float64(xr), float64(xc))) errVari := 0.0 for _, v := range r.Residuals { errVari += v * v } errVari /= float64(xr - xc) errVariMat := mat64.NewDense(xr, xr, nil) for i := 0; i < xr; i++ { errVariMat.Set(i, i, errVari) } // V D UT Z // xc x xMinDim * xMinDim x xMinDim * xMinDim x xr = xc x xr vd := mat64.NewDense(xc, xMinDim, nil) vd.Mul(r.V, r.D) z := mat64.NewDense(xc, xr, nil) z.Mul(vd, r.U.T()) // Z ErrVar ZT // xc x xr * xr x xr * xr x xc zerr := mat64.NewDense(xc, xr, nil) zerr.Mul(z, errVariMat) coefCovarMat := mat64.NewDense(xc, xc, nil) coefCovarMat.Mul(zerr, z.T()) r.StdErrs = getDiag(coefCovarMat) } func getDiag(mat mat64.Matrix) []float64 { r, _ := mat.Dims() diag := make([]float64, r) for i := range diag { diag[i] = mat.At(i, i) } return diag } func setDiag(mat mat64.Mutable, d []float64) { for i, v := range d { mat.Set(i, i, v) } }
vendor/github.com/berkmancenter/ridge/ridge.go
0.799677
0.621139
ridge.go
starcoder
package flownetwork import ( "bufio" "fmt" "io" "github.com/wangyoucao577/algorithms_practice/graph" ) // EdgeFlowUnit represent unit of capacity/flow of one edge type EdgeFlowUnit int // CapacityStorage represent capacities/residualCapacities on a flow network type CapacityStorage map[graph.EdgeID]EdgeFlowUnit //FlowNetwork represent graph for network flow problem (maximum flow problem) type FlowNetwork struct { graph.Graph capacities CapacityStorage // source, target will represent the maximum flow problem on the flow network // so we define them with the flow network source graph.NodeID target graph.NodeID } //ConstructFlowNetwork try to construct a adjacency list based graph with edge capacity, // nodeCount and edgeCount will define V and E // then from r to read contents for adjacency list relationship and edge attr func ConstructFlowNetwork(nodeCount, edgeCount int, r io.Reader) (*FlowNetwork, error) { flowGraph := &FlowNetwork{ Graph: graph.NewAdjacencyListGraph(nodeCount, true), capacities: CapacityStorage{}, source: graph.InvalidNodeID, target: graph.InvalidNodeID} scanner := bufio.NewScanner(r) scanner.Split(bufio.ScanLines) var count int for scanner.Scan() { count++ var fromNode, toNode, edgeCapacity int fmt.Sscanf(scanner.Text(), "%d%d%d", &fromNode, &toNode, &edgeCapacity) //NOTE: input nodeID will start from 1, but in code we prefer start from 0 fromNode-- toNode-- if fromNode < 0 || fromNode >= nodeCount { return nil, fmt.Errorf("invalid fromNode %d, nodeCount %d", fromNode, nodeCount) } if toNode < 0 || toNode >= nodeCount { return nil, fmt.Errorf("invalid toNode %d, nodeCount %d", toNode, nodeCount) } if edgeCapacity <= 0 { return nil, fmt.Errorf("invalid edgeCapacity %d", edgeCapacity) } flowGraph.AddEdge(graph.NodeID(fromNode), graph.NodeID(toNode)) edge := graph.EdgeID{From: graph.NodeID(fromNode), To: graph.NodeID(toNode)} flowGraph.capacities[edge] = EdgeFlowUnit(edgeCapacity) if count >= edgeCount { // got enough edges break } } if err := scanner.Err(); err != nil { return nil, err } flowGraph.source = graph.NodeID(0) flowGraph.target = graph.NodeID(nodeCount - 1) return flowGraph, nil } // Capacity return capacity for an edge func (f *FlowNetwork) Capacity(e graph.EdgeID) EdgeFlowUnit { c, ok := f.capacities[e] if !ok { return 0 } return c } // Source represent the start point of the maximum flow problem on current flow network func (f *FlowNetwork) Source() graph.NodeID { return f.source } // Target represent the end point of the maximum flow problem on current flow network func (f *FlowNetwork) Target() graph.NodeID { return f.target }
flownetwork/flownetwork.go
0.806624
0.560553
flownetwork.go
starcoder
package losses import ( "github.com/nlpodyssey/spago/ag" "github.com/nlpodyssey/spago/mat" ) // MAE measures the mean absolute error (a.k.a. L1 Loss) between each element in the input x and target y. func MAE(x ag.Node, y ag.Node, reduceMean bool) ag.Node { loss := ag.Abs(ag.Sub(x, y)) if reduceMean { return ag.ReduceMean(loss) } return ag.ReduceSum(loss) } // MSE measures the mean squared error (squared L2 norm) between each element in the input x and target y. func MSE(x ag.Node, y ag.Node, reduceMean bool) ag.Node { loss := ag.ProdScalar(ag.Square(ag.Sub(x, y)), ag.Var(x.Value().NewScalar(0.5))) if reduceMean { return ag.ReduceMean(loss) } return ag.ReduceSum(loss) } // NLL returns the loss of the input x respect to the target y. // The target is expected to be a one-hot vector. func NLL(x ag.Node, y ag.Node) ag.Node { return ag.Neg(ag.ReduceSum(ag.Prod(y, ag.Log(x)))) } // CrossEntropy implements a cross-entropy loss function. // x is the raw scores for each class (logits). // c is the index of the gold class. func CrossEntropy(x ag.Node, c int) ag.Node { return ag.Add(ag.Neg(ag.AtVec(x, c)), ag.LogSumExp(x)) } // WeightedCrossEntropy implements a weighted cross-entropy loss function. // x is the raw scores for each class (logits). // c is the index of the gold class. // This function is scaled by a weighting factor weights[class] ∈ [0,1] func WeightedCrossEntropy(weights mat.Matrix) func(x ag.Node, c int) ag.Node { return func(x ag.Node, c int) ag.Node { return ag.ProdScalar(CrossEntropy(x, c), ag.Var(weights.AtVec(c))) } } // FocalLoss implements a variant of the CrossEntropy loss that reduces // the loss contribution from "easy" examples and increases the importance // of correcting misclassified examples. // x is the raw scores for each class (logits). // c is the index of the gold class. // gamma is the focusing parameter (gamma ≥ 0). func FocalLoss(x ag.Node, c int, gamma float64) ag.Node { ce := CrossEntropy(x, c) p := ag.Exp(ag.Neg(ce)) sub := ag.ReverseSub(p, ag.Var(x.Value().NewScalar(1))) a := ag.Pow(sub, gamma) return ag.Prod(a, ce) } // WeightedFocalLoss implements a variant of the CrossEntropy loss that reduces // the loss contribution from "easy" examples and increases the importance // of correcting misclassified examples. // x is the raw scores for each class (logits). // c is the index of the gold class. // gamma is the focusing parameter (gamma ≥ 0). // This function is scaled by a weighting factor weights[class] ∈ [0,1]. func WeightedFocalLoss(weights mat.Matrix) func(x ag.Node, c int, gamma float64) ag.Node { return func(x ag.Node, c int, gamma float64) ag.Node { ce := CrossEntropy(x, c) p := ag.Exp(ag.Neg(ce)) sub := ag.ReverseSub(p, ag.Var(x.Value().NewScalar(1.0))) b := ag.Pow(sub, gamma) fl := ag.Prod(b, ce) return ag.ProdScalar(fl, ag.Var(weights.AtVec(c))) } } // Perplexity computes the perplexity, implemented as exp over the cross-entropy. func Perplexity(x ag.Node, c int) ag.Node { return ag.Exp(CrossEntropy(x, c)) } // ZeroOneQuantization is a loss function that is minimized when each component // of x satisfies x(i) ≡ [x]i ∈ {0, 1}. func ZeroOneQuantization(x ag.Node) ag.Node { return ag.ReduceSum(ag.Prod(ag.Square(x), ag.Square(ag.ReverseSub(x, ag.Var(x.Value().NewScalar(1.0)))))) } // Norm2Quantization is a loss function that is minimized when norm2(x) = 1. func Norm2Quantization(x ag.Node) ag.Node { return ag.Square(ag.SubScalar(ag.ReduceSum(ag.Square(x)), ag.Var(x.Value().NewScalar(1.0)))) } // OneHotQuantization is a loss function that pushes towards the x vector to be 1-hot. // q is the quantization regularizer weight (suggested 0.00001). func OneHotQuantization(x ag.Node, q float64) ag.Node { return ag.ProdScalar(ag.Add(ZeroOneQuantization(x), Norm2Quantization(x)), ag.Var(x.Value().NewScalar(q))) } // Distance is a loss function that calculates the distance between target and x. func Distance(x ag.Node, target float64) ag.Node { return ag.Abs(ag.Sub(ag.Var(x.Value().NewScalar(target)), x)) } // MSESeq calculates the MSE loss on the given sequence. func MSESeq(predicted []ag.Node, target []ag.Node, reduceMean bool) ag.Node { loss := MSE(predicted[0], target[0], false) for i := 1; i < len(predicted); i++ { loss = ag.Add(loss, MSE(predicted[i], target[i], false)) } if reduceMean { return ag.DivScalar(loss, ag.Var(loss.Value().NewScalar(float64(len(predicted))))) } return loss } // MAESeq calculates the MAE loss on the given sequence. func MAESeq(predicted []ag.Node, target []ag.Node, reduceMean bool) ag.Node { loss := MAE(predicted[0], target[0], false) for i := 1; i < len(predicted); i++ { loss = ag.Add(loss, MAE(predicted[i], target[i], false)) } if reduceMean { return ag.DivScalar(loss, ag.Var(loss.Value().NewScalar(float64(len(predicted))))) } return loss } // CrossEntropySeq calculates the CrossEntropy loss on the given sequence. func CrossEntropySeq(predicted []ag.Node, target []int, reduceMean bool) ag.Node { loss := CrossEntropy(predicted[0], target[0]) for i := 1; i < len(predicted); i++ { loss = ag.Add(loss, CrossEntropy(predicted[i], target[i])) } if reduceMean { return ag.DivScalar(loss, ag.Var(loss.Value().NewScalar(float64(len(predicted))))) } return loss } // SPG (Softmax Policy Gradient) is a Gradient Policy used in Reinforcement Learning. // logPropActions are the log-probability of the chosen action by the Agent at each time; // logProbTargets are results of the reward function i.e. the predicted log-likelihood of the ground truth at each time; func SPG(logPropActions []ag.Node, logProbTargets []ag.Node) ag.Node { var loss ag.Node for t := 0; t < len(logPropActions); t++ { loss = ag.Add(loss, ag.Prod(logPropActions[t], logProbTargets[t])) } return ag.Neg(loss) }
losses/losses.go
0.909802
0.703575
losses.go
starcoder
package solver import ( "fmt" "github.com/erikbryant/magnets/board" "github.com/erikbryant/magnets/common" "github.com/erikbryant/magnets/magnets" ) // justOne iterates through all empty cells. For any that have just one // possibility left in the cbs, it sets that frame. func (cbs CBS) justOne(game magnets.Game) { for cell := range game.Guess.Cells(common.Empty) { row, col := cell.Unpack() if len(cbs[row][col]) == 1 { cbs.setFrame(game, row, col, cbs.getOnlyPossibility(row, col)) } } } // satisfied looks at each row/col to see if there are exactly as many spaces // to put a given polarity as there are needed. func (cbs CBS) satisfied(game magnets.Game) { for _, category := range []rune{common.Positive, common.Negative, common.Neutral} { // Row is satisfied in this category? Set those frames. Clear this // possibility elsewhere. for row := 0; row < game.Guess.Height(); row++ { if rowNeeds(game, row, category) == cbs.rowHasSpaceForTotal(game, row, category) { for col := 0; col < game.Guess.Width(); col++ { if cbs[row][col][category] { if category == common.Neutral { cbs.setFrame(game, row, col, category) } else { direction := game.GetFrame(row, col) switch direction { case common.Up: cbs[row][col] = map[rune]bool{category: true} case common.Down: cbs[row][col] = map[rune]bool{category: true} case common.Left: cbs.unsetPossibility(game, row, col, common.Neutral) case common.Right: cbs.unsetPossibility(game, row, col, common.Neutral) } } } } } } // Col is satisfied in this category? Set those frames. Clear this // possibility elsewhere. for col := 0; col < game.Guess.Width(); col++ { if colNeeds(game, col, category) == cbs.colHasSpaceForTotal(game, col, category) { for row := 0; row < game.Guess.Height(); row++ { if cbs[row][col][category] { if category == common.Neutral { cbs.setFrame(game, row, col, category) } else { direction := game.GetFrame(row, col) switch direction { case common.Up: cbs[row][col] = map[rune]bool{category: true} case common.Down: cbs[row][col] = map[rune]bool{category: true} case common.Left: cbs.unsetPossibility(game, row, col, common.Neutral) case common.Right: cbs.unsetPossibility(game, row, col, common.Neutral) } } } } } } } return } // needAll checks to see if the number of pos+neg needed is equal to the number // of frames that are still undecided. If so, none of those frames can be neutral. // NOTE: Once doubleSingle() is written this function will no longer be needed. func (cbs CBS) needAll(game magnets.Game) { // If there are any that we know what they must be, but have not set them // yet, do that now. Otherwise, the count will be off. cbs.justOne(game) for _, category := range []rune{common.Positive, common.Negative} { // Row (#frames remaining that can be category) == (#squares needed). for row := 0; row < game.Guess.Height(); row++ { needs := rowNeeds(game, row, category) if needs == 0 { continue } provides := cbs.rowHasSpaceForTotal(game, row, category) if needs == provides { // All that remain undecided are needed for signs. None can be neutral. cbs.unsetPossibilityRow(game, row, common.Neutral) } } // Col (#frames remaining that can be category) == (#squares needed). for col := 0; col < game.Guess.Width(); col++ { needs := colNeeds(game, col, category) if needs == 0 { continue } provides := cbs.colHasSpaceForTotal(game, col, category) if needs == provides { // All that remain undecided are needed for signs. None can be neutral. cbs.unsetPossibilityCol(game, col, common.Neutral) } } } } // oddRowAllMagnets checks to see if the entire row is full of magnets. If it // is, and if the row length is odd, then we know the pattern of the magnets. func (cbs CBS) oddRowAllMagnets(game magnets.Game) { // If the length is not odd then there is nothing we can determine. if game.Guess.Width()%2 == 0 { return } for row := 0; row < game.Guess.Height(); row++ { if game.CountRow(row, common.Positive)+game.CountRow(row, common.Negative) == game.Guess.Width() { // There is only one way the magnets can be arranged. // The polarity with the larger count goes first. var polarity rune if game.CountRow(row, common.Positive) > game.CountRow(row, common.Negative) { polarity = common.Positive } else { polarity = common.Negative } for col := 0; col < game.Guess.Width(); col++ { game.Guess.Set(row, col, polarity, false) polarity = common.Negate(polarity) cbs.unsetPossibility(game, row, col, polarity) cbs.unsetPossibility(game, row, col, common.Neutral) } dirty = true } } } // oddColAllMagnets checks to see if the entire col is full of magnets. If it // is, and if the col length is odd, then we know the pattern of the magnets. func (cbs CBS) oddColAllMagnets(game magnets.Game) { // If the length is not odd then there is nothing we can determine. if game.Guess.Height()%2 == 0 { return } for col := 0; col < game.Guess.Width(); col++ { if game.CountCol(col, common.Positive)+game.CountCol(col, common.Negative) == game.Guess.Height() { // There is only one way the magnets can be arranged. // The polarity with the larger count goes first. var polarity rune if game.CountCol(col, common.Positive) > game.CountCol(col, common.Negative) { polarity = common.Positive } else { polarity = common.Negative } for row := 0; row < game.Guess.Height(); row++ { game.Guess.Set(row, col, polarity, false) polarity = common.Negate(polarity) cbs.unsetPossibility(game, row, col, polarity) cbs.unsetPossibility(game, row, col, common.Neutral) } dirty = true } } } // doubleSingle() looks for cases where, based on the length of the frame // (1 or 2 cells in this row/col) we know the frame can/cannot be a magnet. // For instance if we need 2 polarities (1 plus and 1 minus) and there is // 1 horizontal and 1 vertical frame we know the vertical frame cannot have // a polarity. func (cbs CBS) doubleSingle(game magnets.Game) { // Enumerate each of the combinations of frames (that are undecided) in the // row/col that will satisfy the pos+neg count conditions. If there is a // frame that is not in any of those combinations then that frame must not // be a magnet (and therefore is neutral). Once we mark it as neutral (and the // remaining frames as !neutral) the rest of the CBS will figure out whether // we now know the other frames, so we do not need to also do that here. // ALSO: If there is a frame that is in *every* one of those combinations then // it must be non-neutral. // If all of the frames are needed to make the solution, then none of them // can be neutral. This doesn't find us a solution directly, but might be // enough info to let the CBS tease out a solution. // NOTE: This turned out to be true. For small boards it works fine. // See the needAll() function. But, it will no longer be needed once this // function is complete. } // resolveNeighbors() propagates any constraint a cell has (like it can only be // negative) to its neighbor (which can then only be positive). func (cbs CBS) resolveNeighbors(game magnets.Game) { // If a cell borders one whose polarity is already identified, update the cbs. for cell := range game.Guess.Cells() { row, col := cell.Unpack() rowEnd, colEnd := game.GetFrameEnd(row, col) if rowEnd == -1 || colEnd == -1 { continue } for _, adj := range board.Adjacents { r, c := adj.Unpack() switch game.Guess.Get(row+r, col+c, false) { case common.Positive: cbs.unsetPossibility(game, row, col, common.Positive) cbs.unsetPossibility(game, rowEnd, colEnd, common.Negative) case common.Negative: cbs.unsetPossibility(game, row, col, common.Negative) cbs.unsetPossibility(game, rowEnd, colEnd, common.Positive) } } } } // zeroInRow looks for rows that have no positives or that have no negatives // and removes those possibilities from the cbs. func (cbs CBS) zeroInRow(game magnets.Game) { for _, category := range []rune{common.Positive, common.Negative} { for row := 0; row < game.Guess.Height(); row++ { if game.CountRow(row, category) == 0 { // Remove all instances of 'category' from the row in the cbs cbs.unsetPossibilityRow(game, row, category) } } } } // zeroInCol looks for columns that have no positives or that have no negatives // and removes those possibilities from the cbs. func (cbs CBS) zeroInCol(game magnets.Game) { for _, category := range []rune{common.Positive, common.Negative} { for col := 0; col < game.Guess.Width(); col++ { if game.CountCol(col, category) == 0 { // Remove all instances of 'category' from the column in the cbs cbs.unsetPossibilityCol(game, col, category) } } } } func (cbs CBS) checker(game magnets.Game, msg string) { // fmt.Printf("\n\n\n") // fmt.Println("----> State coming out of", msg, "<-----") // game.Print() // cbs.print() err := cbs.validate(game) if err != nil { game.Print() cbs.print() panic(err) } } // Solve attempts to find a solution for the game, or gives up if it cannot. func Solve(game magnets.Game) { cbs := new(game) cbs.zeroInRow(game) cbs.checker(game, "zeroInRow") cbs.zeroInCol(game) cbs.checker(game, "zeroInCol") cbs.oddRowAllMagnets(game) cbs.checker(game, "oddRowAllMagnets") cbs.oddColAllMagnets(game) cbs.checker(game, "oddColAllMagnets") attempts := 0 for { dirty = false // cbs.satisfied(game) // This is definitely buggy cbs.checker(game, "satisfied") cbs.resolveNeighbors(game) cbs.checker(game, "resolveNeighbors") cbs.doubleSingle(game) cbs.checker(game, "doubleSingle") // cbs.needAll(game) // This appears to be buggy cbs.checker(game, "needAll") cbs.justOne(game) cbs.checker(game, "justOne") if !dirty { break } attempts++ if attempts > 500 { fmt.Println("WARNING: unable to solve game after >500 attempts") game.Print() break } } }
solver/solver.go
0.647687
0.406921
solver.go
starcoder
package rgb16 // Conversion of different RGB colorspaces with their native illuminators (reference whites) to CIE XYZ scaled to [0, 1e9] and back. // RGB values MUST BE LINEAR and in the nominal range [0, 2^16]. // XYZ values are usually in [0, 1e9] but may be slightly outside this interval. // To get quick and dirty XYZ [0.0, 1.0] approximations, divide by 1e9, otherwise use the float64 version of these functions. // Ref.: [24] // AdobeToXYZ converts from Adobe RGB 1998 with D65 illuminator to CIE XYZ. func AdobeToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((88003494315*rr + 28313725490*gg + 28715220873*bb) / 1e7) y = int((45376806286*rr + 95727336537*gg + 11486091400*bb) / 1e7) z = int((4125169756*rr + 10786175325*gg + 151233463034*bb) / 1e7) return } // XYZToAdobe converts from CIE XYZ to Adobe RGB 1998 with D65 illuminator. func XYZToAdobe(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((20414001*xx - 5649464*yy - 3446944*zz) / 152587890625) gg := int((-9692660*xx + 18760394*yy + 415566*zz) / 152587890625) bb := int((134476*xx - 1183897*yy + 10154250*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // AppleToXYZ converts from Apple RGB with D65 illuminator to CIE XYZ. func AppleToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((68624216067*rr + 48256443121*gg + 28151766230*bb) / 1e7) y = int((37331578545*rr + 102544945448*gg + 12713694971*bb) / 1e7) z = int((3842954145*rr + 21543053329*gg + 140758800640*bb) / 1e7) return } // XYZToApple converts from CIE XYZ to Apple RGB with D65 illuminator. func XYZToApple(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((29515823*xx - 12894116*yy - 4738445*zz) / 152587890625) gg := int((-10851093*xx + 19908869*yy + 372031*zz) / 152587890625) bb := int((854947*xx - 2694965*yy + 10913141*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // BestToXYZ converts from Best RGB with D50 illuminator to CIE XYZ. func BestToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((96539192797*rr + 31213214312*gg + 19378133820*bb) / 1e7) y = int((34860288394*rr + 112512748912*gg + 5217181657*bb) / 1e7) z = int((0*rr + 1451773860*gg + 124467200731*bb) / 1e7) return } // XYZToBest converts from CIE XYZ to Best RGB with D50 illuminator. func XYZToBest(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((17552866*xx - 4836786*yy - 2530000*zz) / 152587890625) gg := int((-5441336*xx + 15069018*yy + 215531*zz) / 152587890625) bb := int((63467*xx - 175761*yy + 12257146*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // BetaToXYZ converts from Beta RGB with D50 illuminator to CIE XYZ. func BetaToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((102426749065*rr + 26639719233*gg + 18064072632*bb) / 1e7) y = int((46276432440*rr + 101287266346*gg + 5026520179*bb) / 1e7) z = int((0*rr + 6210574501*gg + 119708400091*bb) / 1e7) return } // XYZToBeta converts from CIE XYZ to Beta RGB with D50 illuminator. func XYZToBeta(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((16832526*xx - 4282363*yy - 2360185*zz) / 152587890625) gg := int((-7710229*xx + 17065831*yy + 446906*zz) / 152587890625) bb := int((400018*xx - 885376*yy + 12723834*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // BruceToXYZ converts from Bruce RGB with D65 illuminator to CIE XYZ. func BruceToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((71323140305*rr + 44930373083*gg + 28778912031*bb) / 1e7) y = int((36775997558*rr + 104302662698*gg + 11511558708*bb) / 1e7) z = int((3343266956*rr + 11232593270*gg + 151568947889*bb) / 1e7) return } // XYZToBruce converts from CIE XYZ to Bruce RGB with D65 illuminator. func XYZToBruce(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((27455087*xx - 11358136*yy - 4350269*zz) / 152587890625) gg := int((-9692660*xx + 18760394*yy + 415566*zz) / 152587890625) bb := int((112724*xx - 1139754*yy + 10132695*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // CIEToXYZ converts from CIE RGB with E illuminator to CIE XYZ. func CIEToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((74573586632*rr + 47406775004*gg + 30609857327*bb) / 1e7) y = int((26887067978*rr + 124053513389*gg + 1649637597*bb) / 1e7) z = int((0*rr + 1557152666*gg + 151033066299*bb) / 1e7) return } // XYZToCIE converts from CIE XYZ to CIE RGB with E illuminator. func XYZToCIE(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((23707104*xx - 9000405*yy - 4706338*zz) / 152587890625) gg := int((-5138850*xx + 14253252*yy + 885827*zz) / 152587890625) bb := int((52982*xx - 146949*yy + 10094122*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // ColorMatchToXYZ converts from ColorMatch RGB with D50 illuminator to CIE XYZ. func ColorMatchToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((77720897229*rr + 48967284656*gg + 20442374302*bb) / 1e7) y = int((41944609749*rr + 100424429693*gg + 10221179521*bb) / 1e7) z = int((3700999465*rr + 16599084457*gg + 105618905927*bb) / 1e7) return } // XYZToColorMatch converts from CIE XYZ to ColorMatch RGB with D50 illuminator. func XYZToColorMatch(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((26423277*xx - 12234270*yy - 3930143*zz) / 152587890625) gg := int((-11119763*xx + 20590497*yy + 159616*zz) / 152587890625) bb := int((821711*xx - 2807254*yy + 14560099*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } //DonToXYZ converts from Don RGB-4 with D50 illuminator to CIE XYZ. func DonToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((98538353550*rr + 29503486686*gg + 19088700693*bb) / 1e7) y = int((42473426413*rr + 104977523459*gg + 5139269092*bb) / 1e7) z = int((566308079*rr + 2744502936*gg + 122608148316*bb) / 1e7) return } // XYZToDon converts from CIE XYZ to Don RGB-4 with D50 illuminator. func XYZToDon(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((17604170*xx - 4881198*yy - 2536126*zz) / 152587890625) gg := int((-7126288*xx + 16527684*yy + 416721*zz) / 152587890625) bb := int((78208*xx - 347411*yy + 12447932*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // ECIToXYZ converts from ECI RGB with D50 illuminator to CIE XYZ. func ECIToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((99214816509*rr + 27172869458*gg + 20742870221*bb) / 1e7) y = int((48867002364*rr + 91870160982*gg + 11853070877*bb) / 1e7) z = int((0*rr + 10351567864*gg + 115567406728*bb) / 1e7) return } // XYZToECI converts from CIE XYZ to ECI RGB with D50 illuminator. func XYZToECI(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((17827890*xx - 4969847*yy - 2690101*zz) / 152587890625) gg := int((-9593623*xx + 19478259*yy - 275807*zz) / 152587890625) bb := int((859330*xx - 1744674*yy + 13228474*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // EktaSpaceToXYZ converts from Ekta Space PS5 with D50 illuminator to CIE XYZ. func EktaSpaceToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((90622018768*rr + 41654093232*gg + 14854428930*bb) / 1e7) y = int((39769375142*rr + 112145647363*gg + 675196459*bb) / 1e7) z = int((0*rr + 6408316166*gg + 119510658425*bb) / 1e7) return } // XYZToEktaSpace converts from CIE XYZ to Ekta Space PS5 with D50 illuminator. func XYZToEktaSpace(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((20044124*xx - 7304844*yy - 2450052*zz) / 152587890625) gg := int((-7110285*xx + 16202372*yy + 792238*zz) / 152587890625) bb := int((381268*xx - 868780*yy + 12725632*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // NTSCToXYZ converts from NTSC RGB with D50 illuminator to CIE XYZ. func NTSCToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((92605615319*rr + 26474570839*gg + 30571145188*bb) / 1e7) y = int((45611718928*rr + 89509269855*gg + 17469214923*bb) / 1e7) z = int((0*rr + 10085557335*gg + 170324910352*bb) / 1e7) return } // XYZToNTSC converts from CIE XYZ to NTSC RGB with D50 illuminator. func XYZToNTSC(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((19100252*xx - 5324542*yy - 2882091*zz) / 152587890625) gg := int((-9846663*xx + 19992015*yy - 283082*zz) / 152587890625) bb := int((583064*xx - 1183781*yy + 8975671*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // PALToXYZ converts from PAL/SECAM RGB with D65 illuminator to CIE XYZ. func PALToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((65708247501*rr + 52115953307*gg + 27208224612*bb) / 1e7) y = int((33880811779*rr + 107826108185*gg + 10883283740*bb) / 1e7) z = int((3080079346*rr + 19768123902*gg + 143296620125*bb) / 1e7) return } // XYZToPAL converts from CIE XYZ to PAL/SECAM RGB with D65 illuminator. func XYZToPAL(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((30629438*xx - 13931791*yy - 4757517*zz) / 152587890625) gg := int((-9692660*xx + 18760394*yy + 415566*zz) / 152587890625) bb := int((678784*xx - 2288548*yy + 10693653*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // ProPhotoToXYZ converts from ProPhoto RGB with D50 illuminator to CIE XYZ. func ProPhotoToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((121717387654*rr + 20628931105*gg + 4784222170*bb) / 1e7) y = int((43952117189*rr + 108625024795*gg + 13076981*bb) / 1e7) z = int((0*rr + 0*gg + 125918974593*bb) / 1e7) return } // XYZToProPhoto converts from CIE XYZ to ProPhoto RGB with D50 illuminator. func XYZToProPhoto(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((13459638*xx - 2556075*yy - 511118*zz) / 152587890625) gg := int((-5445989*xx + 15081903*yy + 205354*zz) / 152587890625) bb := int((0*xx + 0*yy + 12118312*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // SMPTE_CToXYZ converts from SMPTE-C RGB with D65 illuminator to CIE XYZ. func SMPTE_CToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((60057846951*rr + 55733531700*gg + 29241062027*bb) / 1e7) y = int((32412176698*rr + 106972411687*gg + 13205645837*bb) / 1e7) z = int((2859891660*rr + 17079621575*gg + 146205279621*bb) / 1e7) return } // XYZToSMPTE_C converts from CIE XYZ to SMPTE-C RGB with D65 illuminator. func XYZToSMPTE_C(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((35054494*xx - 17394894*yy - 5439640*zz) / 152587890625) gg := int((-10690722*xx + 19778546*yy + 351727*zz) / 152587890625) bb := int((563208*xx - 1970226*yy + 10502186*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // SRGBToXYZ converts from sRGB with D65 illuminator to CIE XYZ. func SRGBToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((62936812389*rr + 54562615395*gg + 27532997634*bb) / 1e7) y = int((32451804379*rr + 109125230791*gg + 11013199053*bb) / 1e7) z = int((2950164033*rr + 18187533378*gg + 145007110703*bb) / 1e7) return } // XYZToSRGB converts from CIE XYZ to sRGB with D65 illuminator. func XYZToSRGB(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((32405036*xx - 15371385*yy - 4985314*zz) / 152587890625) gg := int((-9692660*xx + 18760394*yy + 415566*zz) / 152587890625) bb := int((556442*xx - 2040259*yy + 10572413*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return } // WGamutToXYZ converts from Wide Gamut RGB with D50 illuminator to CIE XYZ. func WGamutToXYZ(r, g, b uint16) (x, y, z int) { rr := int64(r) gg := int64(g) bb := int64(b) x = int((109270557716*rr + 15400869763*gg + 22459113449*bb) / 1e7) y = int((39396871899*rr + 110618417639*gg + 2574929426*bb) / 1e7) z = int((0*rr + 7901319904*gg + 118017654687*bb) / 1e7) return } // XYZToWGamut converts from CIE XYZ to Wide Gamut RGB with D50 illuminator. func XYZToWGamut(x, y, z int) (r, g, b uint16) { xx, yy, zz := int64(x), int64(y), int64(z) rr := int((14628290*xx - 1840624*yy - 2743606*zz) / 152587890625) gg := int((-5217933*xx + 14472601*yy + 677237*zz) / 152587890625) bb := int((349347*xx - 968931*yy + 12884295*zz) / 152587890625) if rr < 0 { rr = 0 } else if rr > 65535 { rr = 65535 } if gg < 0 { gg = 0 } else if gg > 65535 { gg = 65535 } if bb < 0 { bb = 0 } else if bb > 65535 { bb = 65535 } r, g, b = uint16(rr), uint16(gg), uint16(bb) return }
i16/rgb16/rgb.go
0.717111
0.533276
rgb.go
starcoder
package bsc import ( "github.com/jesand/stats" "github.com/jesand/stats/channel" "github.com/jesand/stats/dist" "github.com/jesand/stats/factor" "github.com/jesand/stats/variable" "math/rand" ) // Create a new binary symmetric channel with the specified noise rate. func NewBSC(noiseRate float64) *BSC { if noiseRate < 0 || noiseRate > 1 { panic(stats.ErrfInvalidProb(noiseRate)) } ch := &BSC{ NoiseRate: variable.NewContinuousRV(noiseRate, dist.UnitIntervalSpace), } ch.DefChannelSampleN.Channel = ch return ch } // A binary symmetric channel. Given a Bernoulli random variable X, it emits // a Bernoulli random variable Y such that with probability `NoiseRate` // Y = !X, and Y = X otherwise. In other words, the channel has fixed // probability `NoiseRate` of outputting Y with the opposite value of X. type BSC struct { // The probability of flipping the input NoiseRate *variable.ContinuousRV channel.DefChannelSampleN } // Send an input to the channel and sample an output func (ch BSC) Sample(input variable.RandomVariable) variable.RandomVariable { var ( rv = input.(*variable.DiscreteRV) space = dist.BooleanSpace x = space.BoolValue(rv.Outcome()) ) if rand.Float64() <= ch.NoiseRate.Val() { return variable.NewDiscreteRV(space.BoolOutcome(!x), space) } else { return variable.NewDiscreteRV(rv.Outcome(), space) } } // Build a factor relating an input variable to an output variable func (ch BSC) Factor(input variable.RandomVariable, output variable.RandomVariable) factor.Factor { return &BSCFactor{ Input: input.(*variable.DiscreteRV), Output: output.(*variable.DiscreteRV), NoiseRate: ch.NoiseRate, } } // Build factors relating an input variable to a sequence of output variables func (ch BSC) Factors(input variable.RandomVariable, outputs []variable.RandomVariable) []factor.Factor { var fs []factor.Factor for _, rv := range outputs { fs = append(fs, ch.Factor(input, rv)) } return fs } // A factor connecting an input variable to its output, as perturbed by a constant // Bernoulli noise rate. type BSCFactor struct { Input, Output *variable.DiscreteRV NoiseRate *variable.ContinuousRV } // Do the input and output currently match? func (factor BSCFactor) OutputMatchesInput() bool { return factor.Input.Equals(factor.Output) } // The adjacent random variables func (factor BSCFactor) Adjacent() []variable.RandomVariable { return []variable.RandomVariable{factor.Output, factor.Input, factor.NoiseRate} } // The factor's current score, based on the values of adjacent variables func (factor BSCFactor) Score() float64 { if factor.OutputMatchesInput() { return 1 - factor.NoiseRate.Val() } else { return factor.NoiseRate.Val() } }
channel/bsc/bsc.go
0.794624
0.566258
bsc.go
starcoder
package ump import ( "math" ) type grid struct { cellSize float32 rows map[int]map[int]*cell } func newGrid(cellSize int) *grid { return &grid{ cellSize: float32(cellSize), rows: make(map[int]map[int]*cell), } } func (g *grid) update(body *Body) { for _, c := range body.cells { c.leave(body) } body.cells = []*cell{} cl, ct, cw, ch := g.toCellRect(body.x, body.y, body.w, body.h) for cy := ct; cy <= ct+ch-1; cy++ { for cx := cl; cx <= cl+cw-1; cx++ { g.cellAt(float32(cx), float32(cy), true).enter(body) } } } func (g *grid) cellsInRect(l, t, w, h float32) []*cell { cl, ct, cw, ch := g.toCellRect(l, t, w, h) cells := []*cell{} for cy := ct; cy <= ct+ch-1; cy++ { row, ok := g.rows[cy] if ok { for cx := cl; cx <= cl+cw-1; cx++ { c, ok := row[cx] if ok { cells = append(cells, c) } } } } return cells } func (g *grid) toCellRect(x, y, w, h float32) (cx, cy, cw, ch int) { cx, cy = g.cellCoordsAt(x, y) cr, cb := int(math.Ceil(float64((x+w)/g.cellSize))), int(math.Ceil(float64((y+h)/g.cellSize))) return cx, cy, cr - cx, cb - cy } func (g *grid) cellCoordsAt(x, y float32) (cx, cy int) { return int(math.Floor(float64(x / g.cellSize))), int(math.Floor(float64(y / g.cellSize))) } func (g *grid) cellAt(x, y float32, cellCoords bool) *cell { var cx, cy int if cellCoords == true { cx, cy = int(x), int(y) } else { cx, cy = g.cellCoordsAt(x, y) } row, ok := g.rows[cy] if !ok { g.rows[cy] = make(map[int]*cell) row = g.rows[cy] } c, ok := row[cx] if !ok { row[cx] = &cell{bodies: make(map[uint32]*Body)} c = row[cx] } return c } func (g *grid) getCellsTouchedBySegment(x1, y1, x2, y2 float32) []*cell { cells := []*cell{} visited := map[*cell]bool{} g.traceRay(x1, y1, x2, y2, func(cx, cy int) { c := g.cellAt(float32(cx), float32(cy), true) if _, found := visited[c]; found { return } visited[c] = true cells = append(cells, c) }) return cells } // traceRay* functions are based on "A Fast Voxel Traversal Algorithm for Ray Tracing", // by <NAME> and <NAME> - http://www.cse.yorku.ca/~amana/research/grid.pdf // It has been modified to include both cells when the ray "touches a grid corner", // and with a different exit condition func (g *grid) rayStep(ct, t1, t2 float32) (int, float32, float32) { v := t2 - t1 delta := g.cellSize / v if v > 0 { return 1, delta, delta * (1.0 - frac(t1/g.cellSize)) } else if v < 0 { return -1, -delta, -delta * frac(t1/g.cellSize) } else { return 0, inf, inf } } func (g *grid) traceRay(x1, y1, x2, y2 float32, f func(cx, cy int)) { cx1, cy1 := g.cellCoordsAt(x1, y1) cx2, cy2 := g.cellCoordsAt(x2, y2) stepX, dx, tx := g.rayStep(float32(cx1), x1, x2) stepY, dy, ty := g.rayStep(float32(cy1), y1, y2) cx, cy := cx1, cy1 f(cx, cy) // The default implementation had an infinite loop problem when // approaching the last cell in some occassions. We finish iterating // when we are *next* to the last cell for abs(float32(cx-cx2))+abs(float32(cy-cy2)) > 1 { if tx < ty { tx += dx cx += stepX } else { // Addition: include both cells when going through corners if tx == ty { f(cx+stepX, cy) } ty += dy cy += stepY } f(cx, cy) } // If we have not arrived to the last cell, use it if cx != cx2 || cy != cy2 { f(cx2, cy2) } }
grid.go
0.642993
0.405684
grid.go
starcoder
package fit import ( "math" ) func ConstantError1D( x, y []float64, p0 []Parameter, f Func1D, ) (p, err []float64, cov [][]float64) { pdf := ConstantError1DPDF(x, y, f) sampler := NewSampler() sampler.Run(pdf, p0, Steps(20000)) chains := sampler.Chains() return chainStats(chains) } func Error1D( x, y, yerr []float64, p0 []Parameter, f Func1D, ) (p, err []float64, cov [][]float64) { pdf := Error1DPDF(x, y, yerr, f) sampler := NewSampler() sampler.Run(pdf, p0, Steps(20000)) return chainStats(sampler.Chains()) } func ScatterError1D( x, y, yerr []float64, p0 []Parameter, f Func1D, ) (p, err []float64, cov [][]float64) { pdf := ScatterError1DPDF(x, y, yerr, f) sampler := NewSampler() sampler.Run(pdf, p0, Steps(20000)) return chainStats(sampler.Chains()) } func chainStats(chains [][]float64) (mean, err []float64, cov [][]float64) { dim := len(chains) mean = chainMean(chains) cov = chainCovariance(chains, mean) err = make([]float64, dim) for i := range err { err[i] = math.Sqrt(cov[i][i]) } return mean, err, cov } func chainMean(chains [][]float64) []float64 { dim := len(chains) n := float64(len(chains[0])) means := make([]float64, dim) for c := range chains { offset := 0.0 for i := range chains[c] { offset += chains[c][i] } offset /= n for i := range chains[c] { means[c] += chains[c][i] - offset } means[c] /= n means[c] += offset } return means } // TODO: rewrite to not run into floating point cancellation bugs in the wings // of the covariance matrix. func chainCovariance(chains [][]float64, mean []float64) [][]float64 { dim := len(chains) n := float64(len(chains[0])) cov := make([][]float64, dim) for i := range cov { cov[i] = make([]float64, dim) } for c1 := range chains { for c2 := c1 + 1; c2 < len(chains); c2++ { for i := range chains[0] { dx1 := chains[c1][i] - mean[c1] dx2 := chains[c2][i] - mean[c2] cov[c1][c2] += dx1*dx2 } cov[c1][c2] /= n } } for c1 := range chains { for c2 := 0; c2 < c1; c2++ { cov[c1][c2] = cov[c2][c1] } } for c := range chains { for i := range chains[c] { dx := chains[c][i] - mean[c] cov[c][c] += dx*dx } cov[c][c] /= n } return cov }
fit.go
0.540924
0.403655
fit.go
starcoder
package main import ( "math" "github.com/lucasb-eyer/go-colorful" ) const ( colorPointRed = 0 colorPointGreen = 1 colorPointBlue = 2 ) // XY is a colour represented using the CIE colour space. type XY struct { X float64 Y float64 } // colourPointsForModel returns the XY bounds for the specified lightbulb model. // The returned array always has the red, then green, then blue points in that order. func colorPointsForModel(model string) (points []XY) { points = make([]XY, 3) switch model { case "LCT001", "LCT002", "LCT003": points[colorPointRed].X = 0.674 points[colorPointRed].Y = 0.322 points[colorPointGreen].X = 0.408 points[colorPointGreen].Y = 0.517 points[colorPointBlue].X = 0.168 points[colorPointBlue].Y = 0.041 return case "LLC001", "LLC005", "LLC006", "LLC007", "LLC011", "LLC012", "LLC013", "LST001": points[colorPointRed].X = 0.703 points[colorPointRed].Y = 0.296 points[colorPointGreen].X = 0.214 points[colorPointGreen].Y = 0.709 points[colorPointBlue].X = 0.139 points[colorPointBlue].Y = 0.081 return } points[colorPointRed].X = 1.0 points[colorPointRed].Y = 0.0 points[colorPointGreen].X = 0.0 points[colorPointGreen].Y = 1.0 points[colorPointBlue].X = 0.0 points[colorPointBlue].Y = 0.0 return } func crossProduct(p1, p2 XY) float64 { return p1.X*p2.Y - p1.Y*p2.X } func getClosestPointToPoints(a, b, p XY) XY { ap := XY{X: p.X - a.X, Y: p.Y - a.Y} ab := XY{X: b.X - a.X, Y: b.Y - a.Y} ab2 := ab.X*ab.X + ab.Y*ab.Y ap_ab := ap.X*ab.X + ap.Y*ab.Y t := ap_ab / ab2 if t < 0.0 { t = 0.0 } else if t > 1.0 { t = 1.0 } return XY{X: a.X + ab.X*t, Y: a.Y + ab.Y*t} } func getDistanceBetweenTwoPoints(p1, p2 XY) float64 { dx := p1.X - p2.X dy := p1.Y - p2.Y return math.Sqrt(dx*dx + dy*dy) } func checkPointInColorPointsReach(p XY, colorPoints []XY) bool { if len(colorPoints) != 3 { return false } red := colorPoints[colorPointRed] green := colorPoints[colorPointGreen] blue := colorPoints[colorPointBlue] v1 := XY{X: green.X - red.X, Y: green.Y - red.Y} v2 := XY{X: blue.X - red.X, Y: blue.Y - red.Y} q := XY{X: p.X - red.X, Y: p.Y - red.Y} s := crossProduct(q, v2) / crossProduct(v1, v2) t := crossProduct(v1, q) / crossProduct(v1, v2) if s >= 0.0 && t >= 0.0 && s+t <= 1.0 { return true } return false } func getHueXYBrightnessFromColor(c colorful.Color, model string) (float64, float64, float64) { X, Y, Z := c.Xyz() cx := X / (X + Y + Z) cy := Y / (X + Y + Z) xy := XY{X: cx, Y: cy} colorPoints := colorPointsForModel(model) if !checkPointInColorPointsReach(xy, colorPoints) { // Find the closest color we can reach and send this instead pAB := getClosestPointToPoints(colorPoints[colorPointRed], colorPoints[colorPointGreen], xy) pAC := getClosestPointToPoints(colorPoints[colorPointBlue], colorPoints[colorPointRed], xy) pBC := getClosestPointToPoints(colorPoints[colorPointGreen], colorPoints[colorPointBlue], xy) dAB := getDistanceBetweenTwoPoints(xy, pAB) dAC := getDistanceBetweenTwoPoints(xy, pAC) dBC := getDistanceBetweenTwoPoints(xy, pBC) lowest := dAB closestPoint := pAB if dAC < lowest { lowest = dAC closestPoint = pAC } if dBC < lowest { lowest = dBC closestPoint = pBC } cx = closestPoint.X cy = closestPoint.Y } return cx, cy, Y }
services/domotics/bridge/cmd/deconzd/color.go
0.824638
0.497131
color.go
starcoder
package bitree import ( "errors" ) type BiTreeNode struct { data interface{} left *BiTreeNode right *BiTreeNode } type BiTree struct { size int root *BiTreeNode compare func(a, b interface{}) int } func NewBiTree() *BiTree { return &BiTree{ size: 0, root: nil, } } var ErrByLogical = errors.New("logical error") func (b *BiTree) InsertLeft(n *BiTreeNode, data interface{}) { var pos **BiTreeNode if n == nil { if b.size > 0 { panic(ErrByLogical) } pos = &(b.root) } else { if n.left != nil { panic(ErrByLogical) } pos = &(n.left) } *pos = &BiTreeNode{ data: data, } b.size++ } func (b *BiTree) InsertRight(n *BiTreeNode, data interface{}) { var pos **BiTreeNode if n == nil { if b.size > 0 { panic(ErrByLogical) } pos = &(b.root) } else { if n.right != nil { panic(ErrByLogical) } pos = &(n.right) } *pos = &BiTreeNode{ data: data, } b.size++ } func (b *BiTree) RemoveLeft(n *BiTreeNode) { if b.size == 0 { return } var pos **BiTreeNode if n == nil { pos = &(b.root) } else { pos = &(n.left) } if *pos != nil { b.RemoveLeft(*pos) b.RemoveRight(*pos) (*pos).data = nil *pos = nil b.size-- } } func (b *BiTree) RemoveRight(n *BiTreeNode) { if b.size == 0 { return } var pos **BiTreeNode if n == nil { pos = &(b.root) } else { pos = &(n.right) } if *pos != nil { b.RemoveLeft(*pos) b.RemoveRight(*pos) (*pos).data = nil *pos = nil b.size-- } } func (b *BiTree) Root() *BiTreeNode { return b.root } func (b *BiTree) Size() int { return b.size } func (b *BiTreeNode) Data() interface{} { return b.data } func (b *BiTreeNode) Left() *BiTreeNode { return b.left } func (b *BiTreeNode) Right() *BiTreeNode { return b.right } func BiTreeMerge(left, right *BiTree, data interface{}) *BiTree { n := NewBiTree() n.InsertLeft(nil, data) if left == nil { panic(ErrByLogical) } if right == nil { panic(ErrByLogical) } n.root.left = left.root n.root.right = right.root n.size = n.size + left.size + right.size return n }
golang/t_bitree/bitree/bitree.go
0.590543
0.453746
bitree.go
starcoder
// Package washout provides washout filters // to approximately display the sensation of vehicle motions. package washout import ( "math" "github.com/shoarai/washout/internal/integral" ) // A Washout is a washout filter. type Washout struct { TranslationScale, RotationScale float64 translationHighPassFilters *[3]Filter translationLowPassFilters *[2]Filter rotationHighPassFilters *[3]Filter translationDoubleIntegrals *[3]integral.Integral rotationIntegrals *[3]integral.Integral simulatorGravity Vector } // A Filter is a filter returns an output from an input. type Filter interface { Filter(input float64) (output float64) } // A Position is a position of simulator. type Position struct { X, Y, Z, AngleX, AngleY, AngleZ float64 } // gravity is the acceleration of gravity. const gravity = 9.80665 * 1000 // NewWashout creates a new washout filter. // interval is the interval of proccessing in milliseconds. func NewWashout( translationHighPassFilters *[3]Filter, translationLowPassFilters *[2]Filter, rotationHighPassFilters *[3]Filter, interval uint) *Washout { translationDoubleIntegrals := newThreeDoubleIntegrals(interval) rotationIntegrals := newThreeIntegrals(interval) return &Washout{ TranslationScale: 1, RotationScale: 1, translationHighPassFilters: translationHighPassFilters, translationLowPassFilters: translationLowPassFilters, rotationHighPassFilters: rotationHighPassFilters, translationDoubleIntegrals: &translationDoubleIntegrals, rotationIntegrals: &rotationIntegrals} } func newThreeDoubleIntegrals(interval uint) [3]integral.Integral { const integralNumber = 2 return [3]integral.Integral{ *integral.NewMulti(interval, integralNumber), *integral.NewMulti(interval, integralNumber), *integral.NewMulti(interval, integralNumber)} } func newThreeIntegrals(interval uint) [3]integral.Integral { return [3]integral.Integral{ *integral.New(interval), *integral.New(interval), *integral.New(interval)} } // Filter processes vehicle motions to produce simulator positions to simulate the motion. // The filter receives vehicle's accelerations in meters per square second, // and vehicle's angular velocities in radians per second. // Then the filter returns simulator's displacements in X, Y, Z-axis in meters // and simulator's angles in X, Y, Z-axis in radians. func (w *Washout) Filter( accelerationX, accelerationY, accelerationZ, angularVelocityX, angularVelocityY, angularVelocityZ float64) Position { acceleration := Vector{ X: accelerationX, Y: accelerationY, Z: accelerationZ, } angularVelocity := Vector{ X: angularVelocityX, Y: angularVelocityY, Z: angularVelocityZ, } scaledAcceleration, scaledAngVel := w.scaleMotion(&acceleration, &angularVelocity) return w.filter(&scaledAcceleration, &scaledAngVel) } func (w *Washout) scaleMotion(acceleration *Vector, angularVelocity *Vector) (Vector, Vector) { scaledAcceleration := Vector{ X: acceleration.X, Y: acceleration.Y, Z: acceleration.Z, }.Multi(w.TranslationScale) scaledAngVel := Vector{ X: angularVelocity.X, Y: angularVelocity.Y, Z: angularVelocity.Z, }.Multi(w.RotationScale) return scaledAcceleration, scaledAngVel } func (w *Washout) filter(scaledAcceleration *Vector, scaledAngularVelocity *Vector) Position { displacement := w.toSimulatorDisplacement(scaledAcceleration) tiltAngle := w.toSimulatorTilt(scaledAcceleration) rotationAngle := w.toSimulatorRotation(scaledAngularVelocity) angle := tiltAngle.Plus(rotationAngle) w.simulatorGravity = w.calculateGravity(&angle) return Position{ displacement.X, displacement.Y, displacement.Z, angle.X, angle.Y, angle.Z} } func (w *Washout) toSimulatorDisplacement(acceleration *Vector) Vector { acce := acceleration.Plus(w.simulatorGravity) acce.Z -= gravity acce = w.filterVector(w.translationHighPassFilters, &acce) return w.integrateVector(w.translationDoubleIntegrals, &acce) } func (w *Washout) toSimulatorTilt(acceleration *Vector) Vector { filteredAx := w.translationLowPassFilters[0].Filter(acceleration.X) filteredAy := w.translationLowPassFilters[1].Filter(acceleration.Y) // TODO: Check if asin returns NaN. // math.IsNaN(math.Asin(x) // Convert low pass filtered accelerations to tilt angles. return Vector{ X: math.Asin(filteredAy / gravity), Y: -math.Asin(filteredAx / gravity), Z: 0} } // toSimulatorRotation returns the simulator angle to simulate. func (w *Washout) toSimulatorRotation(angVel *Vector) Vector { filteredAngVel := w.filterVector(w.rotationHighPassFilters, angVel) return w.integrateVector(w.rotationIntegrals, &filteredAngVel) } // calculateGravity calculates gravity in the simulator coordinate. func (w *Washout) calculateGravity(angle *Vector) Vector { sinAngleX := math.Sin(angle.X) cosAngleX := math.Cos(angle.X) sinAngleY := math.Sin(angle.Y) cosAngleY := math.Cos(angle.Y) return Vector{ X: -sinAngleY, Y: sinAngleX * cosAngleY, Z: cosAngleX * cosAngleY, }.Multi(gravity) } func (w *Washout) filterVector(filter *[3]Filter, vector *Vector) Vector { return Vector{ X: filter[0].Filter(vector.X), Y: filter[1].Filter(vector.Y), Z: filter[2].Filter(vector.Z)} } func (w *Washout) integrateVector(integ *[3]integral.Integral, vector *Vector) Vector { return Vector{ X: integ[0].Integrate(vector.X), Y: integ[1].Integrate(vector.Y), Z: integ[2].Integrate(vector.Z)} }
washout.go
0.840684
0.595051
washout.go
starcoder
package values import ( "encoding/csv" "github.com/iancoleman/strcase" "reflect" "strings" ) // NewImmutable creates a new immutable Values object func NewImmutable(values map[string]interface{}) *ImmutableValues { return &ImmutableValues{ values: values, } } // New creates a new Values object func New(values ...map[string]interface{}) *Values { if len(values) > 1 { panic("too many values") } if len(values) == 1 { return &Values{ values: values[0], } } return &Values{ values: make(map[string]interface{}), } } // ImmutableValues is a helper for reading values type ImmutableValues struct { values map[string]interface{} } func (v *ImmutableValues) Get(path string) interface{} { keys := splitKeys(path) parentKeys, childKey := keys[:len(keys)-1], keys[len(keys)-1] parent := getParent(v.values, parentKeys) return copyValue(parent[childKey]) } func (v *ImmutableValues) Values() map[string]interface{} { return copy(v.values) } // Values is a utility for managing values type Values struct { values map[string]interface{} } func (v *Values) Values() map[string]interface{} { return copy(v.values) } func (v *Values) Set(path string, value interface{}) *Values { keys := splitKeys(path) parentKeys, childKey := keys[:len(keys)-1], keys[len(keys)-1] parent := getParent(v.values, parentKeys) parent[childKey] = value return v } func (v *Values) Get(path string) interface{} { keys := splitKeys(path) parentKeys, childKey := keys[:len(keys)-1], keys[len(keys)-1] parent := getParent(v.values, parentKeys) return parent[childKey] } func (v *Values) Normalize() *Values { v.values = normalize(v.values) return v } func (v *Values) Override(overrides *Values) *Values { v.values = override(v.values, overrides.values) return v } func (v *Values) Immutable() *ImmutableValues { return NewImmutable(copy(v.values)) } func splitKeys(path string) []string { r := csv.NewReader(strings.NewReader(path)) r.Comma = '.' names, err := r.Read() if err != nil { panic(err) } return names } func getParent(parent map[string]interface{}, path []string) map[string]interface{} { if len(path) == 0 { return parent } child, ok := parent[path[0]] if !ok { child = make(map[string]interface{}) parent[path[0]] = child } return getParent(child.(map[string]interface{}), path[1:]) } // override recursively merges values 'b' into values 'a', returning a new merged values map func override(values, overrides map[string]interface{}) map[string]interface{} { out := make(map[string]interface{}, len(overrides)) for k, v := range overrides { out[k] = v } for k, v := range values { if v, ok := v.(map[string]interface{}); ok { if bv, ok := out[k]; ok { if bv, ok := bv.(map[string]interface{}); ok { out[k] = override(bv, v) continue } } } out[k] = v } return out } // normalize normalizes the given values map, converting structs into maps func normalize(values map[string]interface{}) map[string]interface{} { return copy(values) } // copy copies the given values map func copy(values map[string]interface{}) map[string]interface{} { return copyValue(values).(map[string]interface{}) } // copyValue copies the given value func copyValue(value interface{}) interface{} { kind := reflect.ValueOf(value).Kind() if kind == reflect.Struct { return copyStruct(value.(struct{})) } else if kind == reflect.Map { return copyMap(value.(map[string]interface{})) } else if kind == reflect.Slice { return copySlice(value.([]interface{})) } return value } // copyStruct copies the given struct func copyStruct(value struct{}) map[string]interface{} { elem := reflect.ValueOf(value).Elem() elemType := elem.Type() normalized := make(map[string]interface{}) for i := 0; i < elem.NumField(); i++ { key := getFieldKey(elemType.Field(i)) value := copyValue(elem.Field(i).Interface()) normalized[key] = value } return normalized } // copyMap copies the given map func copyMap(values map[string]interface{}) map[string]interface{} { normalized := make(map[string]interface{}) for key, value := range values { normalized[key] = copyValue(value) } return normalized } // copySlice copies the given slice func copySlice(values []interface{}) interface{} { normalized := make([]interface{}, len(values)) for i, value := range values { normalized[i] = copyValue(value) } return normalized } // getFieldKey returns the map key name for the given struct field func getFieldKey(field reflect.StructField) string { tag := field.Tag.Get("yaml") if tag != "" { return strings.Split(tag, ",")[0] } return strcase.ToLowerCamel(field.Name) }
pkg/helm/values/values.go
0.680772
0.507202
values.go
starcoder
package mat import ( "fmt" "strings" ) // Mat4 represents 4x4 matrix stored by (column * 4 + row) index. // (Column is stored first to optimize memory access when transforming vector.) type Mat4 [16]float32 func (m Mat4) Floats() [16]float32 { return m } func (m Mat4) Mul(a Mat4) Mat4 { var out Mat4 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { var sum float32 for k := 0; k < 4; k++ { sum += m[4*k+i] * a[4*j+k] } out[4*j+i] = sum } } return out } func (m Mat4) Factor(f float32) Mat4 { var out Mat4 for i := range m { out[i] = m[i] * f } return out } func (m Mat4) Add(a Mat4) Mat4 { var out Mat4 for i := range m { out[i] = m[i] + a[i] } return out } func (m Mat4) MulAffine(a Mat4) Mat4 { var out Mat4 out[4*0+0] = m[4*0+0]*a[4*0+0] + m[4*1+0]*a[4*0+1] + m[4*2+0]*a[4*0+2] out[4*1+0] = m[4*0+0]*a[4*1+0] + m[4*1+0]*a[4*1+1] + m[4*2+0]*a[4*1+2] out[4*2+0] = m[4*0+0]*a[4*2+0] + m[4*1+0]*a[4*2+1] + m[4*2+0]*a[4*2+2] out[4*3+0] = m[4*0+0]*a[4*3+0] + m[4*1+0]*a[4*3+1] + m[4*2+0]*a[4*3+2] + m[4*3+0] out[4*0+1] = m[4*0+1]*a[4*0+0] + m[4*1+1]*a[4*0+1] + m[4*2+1]*a[4*0+2] out[4*1+1] = m[4*0+1]*a[4*1+0] + m[4*1+1]*a[4*1+1] + m[4*2+1]*a[4*1+2] out[4*2+1] = m[4*0+1]*a[4*2+0] + m[4*1+1]*a[4*2+1] + m[4*2+1]*a[4*2+2] out[4*3+1] = m[4*0+1]*a[4*3+0] + m[4*1+1]*a[4*3+1] + m[4*2+1]*a[4*3+2] + m[4*3+1] out[4*0+2] = m[4*0+2]*a[4*0+0] + m[4*1+2]*a[4*0+1] + m[4*2+2]*a[4*0+2] out[4*1+2] = m[4*0+2]*a[4*1+0] + m[4*1+2]*a[4*1+1] + m[4*2+2]*a[4*1+2] out[4*2+2] = m[4*0+2]*a[4*2+0] + m[4*1+2]*a[4*2+1] + m[4*2+2]*a[4*2+2] out[4*3+2] = m[4*0+2]*a[4*3+0] + m[4*1+2]*a[4*3+1] + m[4*2+2]*a[4*3+2] + m[4*3+2] out[4*3+3] = 1 return out } func (m Mat4) InvAffine() Mat4 { var out Mat4 normInv := 1 / (m[4*0+0]*m[4*1+1]*m[4*2+2] + m[4*0+1]*m[4*1+2]*m[4*2+0] + m[4*0+2]*m[4*1+0]*m[4*2+1] - m[4*0+2]*m[4*1+1]*m[4*2+0] - m[4*0+1]*m[4*1+0]*m[4*2+2] - m[4*0+0]*m[4*1+2]*m[4*2+1]) out[4*0+0] = (m[4*1+1]*m[4*2+2] - m[4*1+2]*m[4*2+1]) * normInv out[4*0+1] = -(m[4*0+1]*m[4*2+2] - m[4*0+2]*m[4*2+1]) * normInv out[4*0+2] = (m[4*0+1]*m[4*1+2] - m[4*0+2]*m[4*1+1]) * normInv out[4*1+0] = -(m[4*1+0]*m[4*2+2] - m[4*1+2]*m[4*2+0]) * normInv out[4*1+1] = (m[4*0+0]*m[4*2+2] - m[4*0+2]*m[4*2+0]) * normInv out[4*1+2] = -(m[4*0+0]*m[4*1+2] - m[4*0+2]*m[4*1+0]) * normInv out[4*2+0] = (m[4*1+0]*m[4*2+1] - m[4*1+1]*m[4*2+0]) * normInv out[4*2+1] = -(m[4*0+0]*m[4*2+1] - m[4*0+1]*m[4*2+0]) * normInv out[4*2+2] = (m[4*0+0]*m[4*1+1] - m[4*0+1]*m[4*1+0]) * normInv out[4*3+3] = 1 b2 := out.Transform(NewVec3(m[4*3+0], m[4*3+1], m[4*3+2])) out[4*3+0] = -b2[0] out[4*3+1] = -b2[1] out[4*3+2] = -b2[2] return out } func (m Mat4) TransformAffine(a Vec3) Vec3 { return Vec3{ m[4*0+0]*a[0] + m[4*1+0]*a[1] + m[4*2+0]*a[2] + m[4*3+0], m[4*0+1]*a[0] + m[4*1+1]*a[1] + m[4*2+1]*a[2] + m[4*3+1], m[4*0+2]*a[0] + m[4*1+2]*a[1] + m[4*2+2]*a[2] + m[4*3+2], } } func (m Mat4) Transform(a Vec3) Vec3 { w := 1 / (m[4*0+3]*a[0] + m[4*1+3]*a[1] + m[4*2+3]*a[2] + m[4*3+3]) return Vec3{ (m[4*0+0]*a[0] + m[4*1+0]*a[1] + m[4*2+0]*a[2] + m[4*3+0]) * w, (m[4*0+1]*a[0] + m[4*1+1]*a[1] + m[4*2+1]*a[2] + m[4*3+1]) * w, (m[4*0+2]*a[0] + m[4*1+2]*a[1] + m[4*2+2]*a[2] + m[4*3+2]) * w, } } func (m Mat4) TransformAffineX(a Vec3) float32 { return m[4*0+0]*a[0] + m[4*1+0]*a[1] + m[4*2+0]*a[2] + m[4*3+0] } func (m Mat4) TransformAffineY(a Vec3) float32 { return m[4*0+1]*a[0] + m[4*1+1]*a[1] + m[4*2+1]*a[2] + m[4*3+1] } func (m Mat4) TransformAffineZ(a Vec3) float32 { return m[4*0+2]*a[0] + m[4*1+2]*a[1] + m[4*2+2]*a[2] + m[4*3+2] } func (m Mat4) Det() float32 { a11, a12, a13, a14 := m[4*0+0], m[4*0+1], m[4*0+2], m[4*0+3] a21, a22, a23, a24 := m[4*1+0], m[4*1+1], m[4*1+2], m[4*1+3] a31, a32, a33, a34 := m[4*2+0], m[4*2+1], m[4*2+2], m[4*2+3] a41, a42, a43, a44 := m[4*3+0], m[4*3+1], m[4*3+2], m[4*3+3] return a11*a22*a33*a44 + a11*a23*a34*a42 + a11*a24*a32*a43 - a11*a24*a33*a42 - a11*a23*a32*a44 - a11*a22*a34*a43 - a12*a21*a33*a44 - a13*a21*a34*a42 - a14*a21*a32*a43 + a14*a21*a33*a42 + a13*a21*a32*a44 + a12*a21*a34*a43 + a12*a23*a31*a44 + a13*a24*a31*a42 + a14*a22*a31*a43 - a14*a23*a31*a42 - a13*a22*a31*a44 - a12*a24*a31*a43 - a12*a23*a34*a41 - a13*a24*a32*a41 - a14*a22*a33*a41 + a14*a23*a32*a41 + a13*a22*a34*a41 + a12*a24*a33*a41 } func (m Mat4) Inv() Mat4 { a11, a12, a13, a14 := m[4*0+0], m[4*0+1], m[4*0+2], m[4*0+3] a21, a22, a23, a24 := m[4*1+0], m[4*1+1], m[4*1+2], m[4*1+3] a31, a32, a33, a34 := m[4*2+0], m[4*2+1], m[4*2+2], m[4*2+3] a41, a42, a43, a44 := m[4*3+0], m[4*3+1], m[4*3+2], m[4*3+3] var out Mat4 out[4*0+0] = a22*a33*a44 + a23*a34*a42 + a24*a32*a43 - a24*a33*a42 - a23*a32*a44 - a22*a34*a43 out[4*0+1] = -a12*a33*a44 - a13*a34*a42 - a14*a32*a43 + a14*a33*a42 + a13*a32*a44 + a12*a34*a43 out[4*0+2] = a12*a23*a44 + a13*a24*a42 + a14*a22*a43 - a14*a23*a42 - a13*a22*a44 - a12*a24*a43 out[4*0+3] = -a12*a23*a34 - a13*a24*a32 - a14*a22*a33 + a14*a23*a32 + a13*a22*a34 + a12*a24*a33 out[4*1+0] = -a21*a33*a44 - a23*a34*a41 - a24*a31*a43 + a24*a33*a41 + a23*a31*a44 + a21*a34*a43 out[4*1+1] = a11*a33*a44 + a13*a34*a41 + a14*a31*a43 - a14*a33*a41 - a13*a31*a44 - a11*a34*a43 out[4*1+2] = -a11*a23*a44 - a13*a24*a41 - a14*a21*a43 + a14*a23*a41 + a13*a21*a44 + a11*a24*a43 out[4*1+3] = a11*a23*a34 + a13*a24*a31 + a14*a21*a33 - a14*a23*a31 - a13*a21*a34 - a11*a24*a33 out[4*2+0] = a21*a32*a44 + a22*a34*a41 + a24*a31*a42 - a24*a32*a41 - a22*a31*a44 - a21*a34*a42 out[4*2+1] = -a11*a32*a44 - a12*a34*a41 - a14*a31*a42 + a14*a32*a41 + a12*a31*a44 + a11*a34*a42 out[4*2+2] = a11*a22*a44 + a12*a24*a41 + a14*a21*a42 - a14*a22*a41 - a12*a21*a44 - a11*a24*a42 out[4*2+3] = -a11*a22*a34 - a12*a24*a31 - a14*a21*a32 + a14*a22*a31 + a12*a21*a34 + a11*a24*a32 out[4*3+0] = -a21*a32*a43 - a22*a33*a41 - a23*a31*a42 + a23*a32*a41 + a22*a31*a43 + a21*a33*a42 out[4*3+1] = a11*a32*a43 + a12*a33*a41 + a13*a31*a42 - a13*a32*a41 - a12*a31*a43 - a11*a33*a42 out[4*3+2] = -a11*a22*a43 - a12*a23*a41 - a13*a21*a42 + a13*a22*a41 + a12*a21*a43 + a11*a23*a42 out[4*3+3] = a11*a22*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31 - a12*a21*a33 - a11*a23*a32 dinv := 1 / m.Det() for i := range out { out[i] *= dinv } return out } func (m Mat4) Transpose() Mat4 { return Mat4{ m[4*0+0], m[4*1+0], m[4*2+0], m[4*3+0], m[4*0+1], m[4*1+1], m[4*2+1], m[4*3+1], m[4*0+2], m[4*1+2], m[4*2+2], m[4*3+2], m[4*0+3], m[4*1+3], m[4*2+3], m[4*3+3], } } func (m Mat4) String() string { out := make([]string, 4) for j := 0; j < 4; j++ { out[j] = fmt.Sprintf("[%0.3f %0.3f %0.3f %0.3f]", m[j*4+0], m[j*4+1], m[j*4+2], m[j*4+3], ) } return "[" + strings.Join(out, " ") + "]" }
mat/mat4.go
0.561095
0.546738
mat4.go
starcoder
package payouts // AdditionalData3DSecure struct for AdditionalData3DSecure type AdditionalData3DSecure struct { // This parameter indicates that you are able to process 3D Secure 2 transactions natively on your payment page. Send this field when you are using `/payments` endpoint with any of our [native 3D Secure 2 solutions](https://docs.adyen.com/checkout/3d-secure/native-3ds2), such as Components or Drop-in. Possible values: * **true** - Ready to support native 3D Secure 2 authentication. Setting this to true does not mean always applying 3D Secure 2. Adyen still selects the version of 3D Secure based on configuration to optimize authorisation rates and improve the shopper's experience. * **false** – Not ready to support native 3D Secure 2 authentication. Adyen will not offer 3D Secure 2 to your shopper regardless of your configuration. > This parameter only indicates your readiness to support 3D Secure 2 natively on Drop-in or Components. To specify that you want to perform 3D Secure on a transaction, use Dynamic 3D Secure or send the executeThreeD parameter. Allow3DS2 string `json:"allow3DS2,omitempty"` // This parameter indicates if you want to perform 3D Secure authentication on a transaction or not. Allowed values: * **true** – Perform 3D Secure authentication. * **false** – Don't perform 3D Secure authentication. > Alternatively, you can also use Dynamic 3D Secure to configure rules for applying 3D Secure. ExecuteThreeD string `json:"executeThreeD,omitempty"` // In case of Secure+, this field must be set to **CUPSecurePlus**. MpiImplementationType string `json:"mpiImplementationType,omitempty"` // Indicates the [exemption type](https://docs-admin.is.adyen.com/payments-fundamentals/psd2-sca-compliance-and-implementation-guide#specifypreferenceinyourapirequest) that you want to request for the transaction. Possible values: * **lowValue** * **secureCorporate** * **trustedBeneficiary** * **transactionRiskAnalysis** ScaExemption string `json:"scaExemption,omitempty"` }
src/payouts/model_additional_data3_d_secure.go
0.826151
0.550909
model_additional_data3_d_secure.go
starcoder
package imageblk import ( "fmt" "math" "strconv" "sync" "github.com/janelia-flyem/dvid/dvid" "github.com/janelia-flyem/dvid/server" "github.com/janelia-flyem/dvid/storage" ) // ArbSlice is a 2d rectangle that can be positioned arbitrarily in 3D. type ArbSlice struct { topLeft dvid.Vector3d topRight dvid.Vector3d bottomLeft dvid.Vector3d res float64 // Calculated from above size dvid.Point2d incrX dvid.Vector3d incrY dvid.Vector3d // The image buffer. We don't worry about strides and byte order for now because // we only GET and don't PUT arbitrary images, where we have to worry about receiving // external data. bytesPerVoxel int32 data []byte } // NewArbSliceFromStrings returns an image with arbitrary 3D orientation given string parameters. // The 3d points are in real world space definited by resolution, e.g., nanometer space. func (d *Data) NewArbSliceFromStrings(tlStr, trStr, blStr, resStr, sep string) (*ArbSlice, error) { topLeft, err := dvid.StringToVector3d(tlStr, sep) if err != nil { return nil, err } topRight, err := dvid.StringToVector3d(trStr, sep) if err != nil { return nil, err } bottomLeft, err := dvid.StringToVector3d(blStr, sep) if err != nil { return nil, err } res, err := strconv.ParseFloat(resStr, 64) if err != nil { return nil, err } return d.NewArbSlice(topLeft, topRight, bottomLeft, res) } // NewArbSlice returns an image with arbitrary 3D orientation. // The 3d points are in real world space definited by resolution, e.g., nanometer space. func (d *Data) NewArbSlice(topLeft, topRight, bottomLeft dvid.Vector3d, res float64) (*ArbSlice, error) { // Compute the increments in x,y and number of pixes in each direction. dx := topRight.Distance(topLeft) dy := bottomLeft.Distance(topLeft) nxFloat := math.Floor(dx / res) nyFloat := math.Floor(dy / res) incrX := topRight.Subtract(topLeft).DivideScalar(nxFloat) incrY := bottomLeft.Subtract(topLeft).DivideScalar(nyFloat) size := dvid.Point2d{int32(nxFloat) + 1, int32(nyFloat) + 1} bytesPerVoxel := d.Properties.Values.BytesPerElement() arb := &ArbSlice{topLeft, topRight, bottomLeft, res, size, incrX, incrY, bytesPerVoxel, nil} // Allocate the image buffer numVoxels := size[0] * size[1] if numVoxels <= 0 { return nil, fmt.Errorf("Bad arbitrary image size requested: %s", arb) } requestSize := int64(bytesPerVoxel) * int64(numVoxels) if requestSize > server.MaxDataRequest { return nil, fmt.Errorf("Requested payload (%d bytes) exceeds this DVID server's set limit (%d)", requestSize, server.MaxDataRequest) } arb.data = make([]byte, requestSize) return arb, nil } func (s ArbSlice) String() string { return fmt.Sprintf("Arbitrary %d x %d image: top left %q, top right %q, bottom left %q, res %f", s.size[0], s.size[1], s.topLeft, s.topRight, s.bottomLeft, s.res) } func (d *Data) GetArbitraryImage(ctx storage.Context, tlStr, trStr, blStr, resStr string) (*dvid.Image, error) { // Setup the image buffer arb, err := d.NewArbSliceFromStrings(tlStr, trStr, blStr, resStr, "_") if err != nil { return nil, err } // Iterate across arbitrary image using res increments, retrieving trilinear interpolation // at each point. cache := NewValueCache(100) keyF := func(pt dvid.Point3d) []byte { chunkPt := pt.Chunk(d.BlockSize()).(dvid.ChunkPoint3d) idx := dvid.IndexZYX(chunkPt) return NewTKey(&idx) } // TODO: Add concurrency. leftPt := arb.topLeft var i int32 var wg sync.WaitGroup for y := int32(0); y < arb.size[1]; y++ { <-server.HandlerToken wg.Add(1) go func(curPt dvid.Vector3d, dstI int32) { defer func() { server.HandlerToken <- 1 wg.Done() }() for x := int32(0); x < arb.size[0]; x++ { value, err := d.computeValue(curPt, ctx, KeyFunc(keyF), cache) if err != nil { dvid.Errorf("Error in concurrent arbitrary image calc: %v", err) return } copy(arb.data[dstI:dstI+arb.bytesPerVoxel], value) curPt.Increment(arb.incrX) dstI += arb.bytesPerVoxel } }(leftPt, i) leftPt.Increment(arb.incrY) i += arb.size[0] * arb.bytesPerVoxel } wg.Wait() return dvid.ImageFromData(arb.size[0], arb.size[1], arb.data, d.Properties.Values, d.Properties.Interpolable) } type neighbors struct { xd, yd, zd float64 coords [8]dvid.Point3d values []byte } func (d *Data) neighborhood(pt dvid.Vector3d) neighbors { res32 := d.Properties.Resolution res := dvid.Vector3d{float64(res32.VoxelSize[0]), float64(res32.VoxelSize[1]), float64(res32.VoxelSize[2])} // Calculate voxel lattice points voxelCoord := dvid.Vector3d{pt[0] / res[0], pt[1] / res[1], pt[2] / res[2]} x0 := math.Floor(voxelCoord[0]) x1 := math.Ceil(voxelCoord[0]) y0 := math.Floor(voxelCoord[1]) y1 := math.Ceil(voxelCoord[1]) z0 := math.Floor(voxelCoord[2]) z1 := math.Ceil(voxelCoord[2]) ix0 := int32(x0) ix1 := int32(x1) iy0 := int32(y0) iy1 := int32(y1) iz0 := int32(z0) iz1 := int32(z1) // Calculate real-world lattice points in given resolution rx0 := x0 * res[0] rx1 := x1 * res[0] ry0 := y0 * res[1] ry1 := y1 * res[1] rz0 := z0 * res[2] rz1 := z1 * res[2] var n neighbors if ix0 != ix1 { n.xd = (pt[0] - rx0) / (rx1 - rx0) } if iy0 != iy1 { n.yd = (pt[1] - ry0) / (ry1 - ry0) } if iz0 != iz1 { n.zd = (pt[2] - rz0) / (rz1 - rz0) } n.coords[0] = dvid.Point3d{ix0, iy0, iz0} n.coords[1] = dvid.Point3d{ix1, iy0, iz0} n.coords[2] = dvid.Point3d{ix0, iy1, iz0} n.coords[3] = dvid.Point3d{ix1, iy1, iz0} n.coords[4] = dvid.Point3d{ix0, iy0, iz1} n.coords[5] = dvid.Point3d{ix1, iy0, iz1} n.coords[6] = dvid.Point3d{ix0, iy1, iz1} n.coords[7] = dvid.Point3d{ix1, iy1, iz1} // Allocate the values slice buffer based on bytes/voxel. bufSize := 8 * d.Properties.Values.BytesPerElement() n.values = make([]byte, bufSize, bufSize) return n } type KeyFunc func(dvid.Point3d) []byte type PopulateFunc func([]byte) ([]byte, error) // ValueCache is a concurrency-friendly cache type ValueCache struct { sync.Mutex deserializedBlocks map[string]([]byte) keyQueue []string size int } func NewValueCache(size int) *ValueCache { var vc ValueCache vc.deserializedBlocks = make(map[string]([]byte), size) vc.keyQueue = make([]string, size) vc.size = size return &vc } // Get returns the cached value of a key. On a miss, it uses the passed PopulateFunc // to retrieve the key and stores it in the cache. If nil is passed for the PopulateFunc, // the function just returns a "false" with no value. func (vc *ValueCache) Get(key []byte, pf PopulateFunc) ([]byte, bool, error) { vc.Lock() data, found := vc.deserializedBlocks[string(key)] if !found { // If no populate function provided, just say it's not found. if pf == nil { vc.Unlock() return nil, false, nil } // Populate the cache var err error data, err = pf(key) if err != nil { vc.Unlock() return nil, false, err } vc.add(key, data) } vc.Unlock() return data, found, nil } func (vc *ValueCache) add(key []byte, data []byte) { stringKey := string(key) if len(vc.keyQueue) >= vc.size { delete(vc.deserializedBlocks, vc.keyQueue[0]) vc.keyQueue = append(vc.keyQueue[1:], stringKey) } else { vc.keyQueue = append(vc.keyQueue, stringKey) } vc.deserializedBlocks[stringKey] = data } // Clear clears the cache. func (vc *ValueCache) Clear() { vc.Lock() vc.deserializedBlocks = make(map[string]([]byte), vc.size) vc.keyQueue = make([]string, vc.size) vc.Unlock() } // Calculates value of a 3d real world point in space defined by underlying data resolution. func (d *Data) computeValue(pt dvid.Vector3d, ctx storage.Context, keyF KeyFunc, cache *ValueCache) ([]byte, error) { db, err := d.GetOrderedKeyValueDB() if err != nil { return nil, err } valuesPerElement := d.Properties.Values.ValuesPerElement() bytesPerValue, err := d.Properties.Values.BytesPerValue() if err != nil { return nil, err } bytesPerVoxel := valuesPerElement * bytesPerValue // Allocate an empty block. blockSize, ok := d.BlockSize().(dvid.Point3d) if !ok { return nil, fmt.Errorf("Data %q does not have a 3d block size", d.DataName()) } nx := blockSize[0] nxy := nx * blockSize[1] emptyBlock := d.BackgroundBlock() populateF := func(key []byte) ([]byte, error) { serializedData, err := db.Get(ctx, key) if err != nil { return nil, err } var deserializedData []byte if serializedData == nil || len(serializedData) == 0 { deserializedData = emptyBlock } else { deserializedData, _, err = dvid.DeserializeData(serializedData, true) if err != nil { return nil, fmt.Errorf("Unable to deserialize block: %v", err) } } return deserializedData, nil } // For the given point, compute surrounding lattice points and retrieve values. neighbors := d.neighborhood(pt) var valuesI int32 for _, voxelCoord := range neighbors.coords { deserializedData, _, err := cache.Get(keyF(voxelCoord), populateF) if err != nil { return nil, err } blockPt := voxelCoord.PointInChunk(blockSize).(dvid.Point3d) blockI := blockPt[2]*nxy + blockPt[1]*nx + blockPt[0] //fmt.Printf("Block %s (%d) len %d -> Neighbor %s (buffer %d, len %d)\n", // blockPt, blockI, len(blockData), voxelCoord, valuesI, len(neighbors.values)) copy(neighbors.values[valuesI:valuesI+bytesPerVoxel], deserializedData[blockI:blockI+bytesPerVoxel]) valuesI += bytesPerVoxel } // Perform trilinear interpolation on the underlying data values. unsupported := func() error { return fmt.Errorf("DVID cannot retrieve images with arbitrary orientation using %d channels and %d bytes/channel", valuesPerElement, bytesPerValue) } var value []byte switch valuesPerElement { case 1: switch bytesPerValue { case 1: if d.Interpolable { interpValue := trilinearInterpUint8(neighbors.xd, neighbors.yd, neighbors.zd, []uint8(neighbors.values)) value = []byte{byte(interpValue)} } else { value = []byte{nearestNeighborUint8(neighbors.xd, neighbors.yd, neighbors.zd, []uint8(neighbors.values))} } case 2: fallthrough case 4: fallthrough case 8: fallthrough default: return nil, unsupported() } case 4: switch bytesPerValue { case 1: value = make([]byte, 4, 4) for c := 0; c < 4; c++ { channelValues := make([]uint8, 8, 8) for i := 0; i < 8; i++ { channelValues[i] = uint8(neighbors.values[i*4+c]) } if d.Interpolable { interpValue := trilinearInterpUint8(neighbors.xd, neighbors.yd, neighbors.zd, channelValues) value[c] = byte(interpValue) } else { value[c] = byte(nearestNeighborUint8(neighbors.xd, neighbors.yd, neighbors.zd, channelValues)) } } case 2: fallthrough default: return nil, unsupported() } default: } return value, nil } // Returns value of nearest neighbor to point. func nearestNeighborUint8(xd, yd, zd float64, values []uint8) uint8 { var x, y, z int if xd > 0.5 { x = 1 } if yd > 0.5 { y = 1 } if zd > 0.5 { z = 1 } return values[z*4+y*2+x] } // Returns the trilinear interpolation of a point 'pt' where 'pt0' is the lattice point below and // 'pt1' is the lattice point above. The values c000...c111 are at lattice points surrounding // the interpolated point. This can be used for interpolation of anisotropic space. Formulation // follows Wikipedia trilinear interpolation page although direction of y axes is flipped, which // shouldn't matter for formulae. func trilinearInterpUint8(xd, yd, zd float64, values []uint8) uint8 { c000 := float64(values[0]) c100 := float64(values[1]) c010 := float64(values[2]) c110 := float64(values[3]) c001 := float64(values[4]) c101 := float64(values[5]) c011 := float64(values[6]) c111 := float64(values[7]) c00 := c000*(1.0-xd) + c100*xd c10 := c010*(1.0-xd) + c110*xd c01 := c001*(1.0-xd) + c101*xd c11 := c011*(1.0-xd) + c111*xd c0 := c00*(1.0-yd) + c10*yd c1 := c01*(1.0-yd) + c11*yd c := math.Floor(c0*(1-zd) + c1*zd + 0.5) if c > 255 { return 255 } return uint8(c) }
datatype/imageblk/arb_image.go
0.676834
0.494507
arb_image.go
starcoder
package bild import ( "fmt" "image" "math" ) // ConvolutionMatrix interface. // At returns the matrix value at position x, y. // Normalized returns a new matrix with normalized values. // SideLength returns the matrix side length. type ConvolutionMatrix interface { At(x, y int) float64 Normalized() ConvolutionMatrix SideLength() int } // NewKernel returns a kernel of the provided length. func NewKernel(length int) *Kernel { return &Kernel{make([]float64, length*length), length} } // Kernel to be used as a convolution matrix. type Kernel struct { Matrix []float64 Stride int } // Normalized returns a new Kernel with normalized values. func (k *Kernel) Normalized() ConvolutionMatrix { sum := absum(k) stride := k.Stride nk := NewKernel(stride) // avoid division by 0 if sum == 0 { sum = 1 } for i := 0; i < stride*stride; i++ { nk.Matrix[i] = k.Matrix[i] / sum } return nk } // SideLength returns the matrix side length. func (k *Kernel) SideLength() int { return k.Stride } // At returns the matrix value at position x, y. func (k *Kernel) At(x, y int) float64 { return k.Matrix[y*k.Stride+x] } // String returns the string representation of the matrix. func (k *Kernel) String() string { result := "" stride := k.Stride for x := 0; x < stride; x++ { result += fmt.Sprintf("\n") for y := 0; y < stride; y++ { result += fmt.Sprintf("%-8.4f", k.At(x, y)) } } return result } // ConvolutionOptions are the Convolve function parameters. // Bias is added to each RGB channel after convoluting. Range is -255 to 255. // Wrap sets if indices outside of image dimensions should be taken from the opposite side. // CarryAlpha sets if the alpha should be taken from the source image without convoluting type ConvolutionOptions struct { Bias float64 Wrap bool CarryAlpha bool } // Convolve applies a convolution matrix (kernel) to an image with the supplied options. func Convolve(img image.Image, k ConvolutionMatrix, o *ConvolutionOptions) *image.RGBA { bounds := img.Bounds() src := CloneAsRGBA(img) dst := image.NewRGBA(bounds) w, h := bounds.Max.X, bounds.Max.Y kernelLength := k.SideLength() bias := 0.0 wrap := false carryAlpha := true if o != nil { bias = o.Bias wrap = o.Wrap carryAlpha = o.CarryAlpha } parallelize(h, func(start, end int) { for x := 0; x < w; x++ { for y := start; y < end; y++ { var r, g, b, a float64 for kx := 0; kx < kernelLength; kx++ { for ky := 0; ky < kernelLength; ky++ { var ix, iy int if wrap { ix = (x - kernelLength/2 + kx + w) % w iy = (y - kernelLength/2 + ky + h) % h } else { ix = x - kernelLength/2 + kx iy = y - kernelLength/2 + ky if ix < 0 || ix >= w || iy < 0 || iy >= h { continue } } ipos := iy*dst.Stride + ix*4 kvalue := k.At(kx, ky) r += float64(src.Pix[ipos+0]) * kvalue g += float64(src.Pix[ipos+1]) * kvalue b += float64(src.Pix[ipos+2]) * kvalue if !carryAlpha { a += float64(src.Pix[ipos+3]) * kvalue } } } pos := y*dst.Stride + x*4 dst.Pix[pos+0] = uint8(math.Max(math.Min(r+bias, 255), 0)) dst.Pix[pos+1] = uint8(math.Max(math.Min(g+bias, 255), 0)) dst.Pix[pos+2] = uint8(math.Max(math.Min(b+bias, 255), 0)) if !carryAlpha { dst.Pix[pos+3] = uint8(math.Max(math.Min(a, 255), 0)) } else { dst.Pix[pos+3] = src.Pix[pos+3] } } } }) return dst } // absum returns the absolute cumulative value of the matrix. func absum(k *Kernel) float64 { var sum float64 for _, v := range k.Matrix { sum += math.Abs(v) } return sum }
convolution.go
0.895791
0.62498
convolution.go
starcoder
// Package frames describes the Frame interface. // A set of standard frames are also defined in this package. These are: Fixed, Window, Wild and WildMin. package frames import ( "errors" "strconv" "github.com/sniperkit/xfilter/internal/bytematcher/patterns" "github.com/sniperkit/xfilter/internal/persist" ) // Frame encapsulates a pattern with offset information, mediating between the pattern and the bytestream. type Frame interface { Match([]byte) (bool, []int) // Match the enclosed pattern against the byte slice in a L-R direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. MatchN([]byte, int) (bool, int) MatchR([]byte) (bool, []int) // Match the enclosed pattern against the byte slice in a reverse (R-L) direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. MatchNR([]byte, int) (bool, int) Equals(Frame) bool // Equals tests equality of two frames. String() string Min() int // Min returns the minimum offset a frame can appear at Max() int // Max returns the maximum offset a frame can appear at. Returns -1 for no limit (wildcard, *) Linked(Frame, int, int) (bool, int, int) // Linked tests whether a frame is linked to a preceding frame (by a preceding or succeding relationship) with an offset and range that is less than the supplied ints Pat() patterns.Pattern // Pat exposes the enclosed pattern Save(*persist.LoadSaver) // Save a frame to a LoadSaver. The first byte written should be the identifying byte provided to Register(). // The following methods are inherited from the enclosed OffType Orientation() OffType SwitchOff() OffType // The following methods are inherited from the enclosed pattern Length() (int, int) // min and max lengths of the enclosed pattern NumSequences() int // // the number of simple sequences that the enclosed pattern can be represented by. Return 0 if the pattern cannot be represented by a defined number of simple sequence (e.g. for an indirect offset pattern) or, if in your opinion, the number of sequences is unreasonably large. Sequences() []patterns.Sequence } // Loader is any function that accepts a persist.LoadSaver and returns a Frame. type Loader func(*persist.LoadSaver) Frame const ( fixedLoader byte = iota windowLoader wildLoader wildMinLoader ) var loaders = [8]Loader{loadFixed, loadWindow, loadWild, loadWildMin, nil, nil, nil, nil} // Register an additional Loader. // Must provide an integer between 4 and 7 (the first four loaders are taken by the standard four frames). func Register(id byte, l Loader) { loaders[int(id)] = l } // Load a frame from a persist.LoadSaver func Load(ls *persist.LoadSaver) Frame { id := ls.LoadByte() l := loaders[int(id)] if l == nil { if ls.Err == nil { ls.Err = errors.New("bad frame loader") } return nil } return l(ls) } // OffType is the type of offset type OffType uint8 // Four offset types are supported const ( BOF OffType = iota // beginning of file offset PREV // offset from previous frame SUCC // offset from successive frame EOF // end of file offset ) // OffString is an exported array of strings representing each of the four offset types var OffString = [...]string{"B", "P", "S", "E"} // Orientation returns the offset type of the frame which must be either BOF, PREV, SUCC or EOF func (o OffType) Orientation() OffType { return o } // SwitchOff returns a new offset type according to a given set of rules. These are: // - PREV -> SUCC // - SUCC and EOF -> PREV // This is helpful when changing the orientation of a frame (for example to allow right-left searching). func (o OffType) SwitchOff() OffType { switch o { case PREV: return SUCC case SUCC, EOF: return PREV default: return o } } // NewFrame generates Fixed, Window, Wild and WildMin frames. The offsets argument controls what type of frame is created: // - for a Wild frame, give no offsets or give a max offset of < 0 and a min of < 1 // - for a WildMin frame, give one offset, or give a max offset of < 0 and a min of > 0 // - for a Fixed frame, give two offsets that are both >= 0 and that are equal to each other // - for a Window frame, give two offsets that are both >= 0 and that are not equal to each other. func NewFrame(typ OffType, pat patterns.Pattern, offsets ...int) Frame { switch len(offsets) { case 0: return Frame(Wild{typ, pat}) case 1: if offsets[0] > 0 { return Frame(WildMin{typ, offsets[0], pat}) } return Frame(Wild{typ, pat}) } if offsets[1] < 0 { if offsets[0] > 0 { return Frame(WildMin{typ, offsets[0], pat}) } return Frame(Wild{typ, pat}) } if offsets[0] < 0 { offsets[0] = 0 } if offsets[0] == offsets[1] { return Frame(Fixed{typ, offsets[0], pat}) } return Frame(Window{typ, offsets[0], offsets[1], pat}) } // SwitchFrame returns a new frame with a different orientation (for example to allow right-left searching). func SwitchFrame(f Frame, p patterns.Pattern) Frame { return NewFrame(f.SwitchOff(), p, f.Min(), f.Max()) } // BMHConvert converts the patterns within a slice of frames to BMH sequences if possible. func BMHConvert(fs []Frame, rev bool) []Frame { nfs := make([]Frame, len(fs)) for i, f := range fs { nfs[i] = NewFrame(f.Orientation(), patterns.BMH(f.Pat(), rev), f.Min(), f.Max()) } return nfs } // NonZero checks whether, when converted to simple byte sequences, this frame's pattern is all 0 bytes. func NonZero(f Frame) bool { for _, seq := range f.Sequences() { allzeros := true for _, b := range seq { if b != 0 { allzeros = false } } if allzeros { return false } } return true } // TotalLength is sum of the maximum length of the enclosed pattern and the maximum offset. func TotalLength(f Frame) int { _, l := f.Length() return l + f.Max() } // Fixed frames are at a fixed offset e.g. 0 or 10 from the BOF, EOF or a preceding or succeeding frame. type Fixed struct { OffType Off int patterns.Pattern } // Match the enclosed pattern against the byte slice in a L-R direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (f Fixed) Match(b []byte) (bool, []int) { if m, l := f.MatchN(b, 0); m { return true, []int{l} } return false, nil } func (f Fixed) MatchN(b []byte, n int) (bool, int) { if n > 0 || f.Off >= len(b) { return false, -1 } if success, length := f.Test(b[f.Off:]); success { return true, f.Off + length } return false, -1 } // MatchR matches the enclosed pattern against the byte slice in a reverse (R-L) direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (f Fixed) MatchR(b []byte) (bool, []int) { if m, l := f.MatchNR(b, 0); m { return true, []int{l} } return false, nil } func (f Fixed) MatchNR(b []byte, n int) (bool, int) { if n > 0 || f.Off >= len(b) { return false, -1 } if success, length := f.TestR(b[:len(b)-f.Off]); success { return true, f.Off + length } return false, -1 } // Equals tests equality of two frames func (f Fixed) Equals(frame Frame) bool { f1, ok := frame.(Fixed) if ok { if f.OffType == f1.OffType && f.Off == f1.Off { return f.Pattern.Equals(f1.Pattern) } } return false } func (f Fixed) String() string { return "F " + OffString[f.OffType] + ":" + strconv.Itoa(f.Off) + " " + f.Pattern.String() } // Min returns the minimum offset a frame can appear at. func (f Fixed) Min() int { return f.Off } // Max returns the maximum offset a frame can appear at. Returns -1 for no limit (wildcard, *). func (f Fixed) Max() int { return f.Off } // Linked tests whether a frame is linked to a preceding frame (by a preceding or succeding relationship) with an offset and range that is less than the supplied ints. func (f Fixed) Linked(prev Frame, maxDistance, maxRange int) (bool, int, int) { switch f.OffType { case PREV: if f.Off > maxDistance { return false, 0, 0 } return true, maxDistance - f.Off, maxRange case SUCC, EOF: if prev.Orientation() != SUCC || prev.Max() < 0 || prev.Max() > maxDistance || prev.Max()-prev.Min() > maxRange { return false, 0, 0 } return true, maxDistance - prev.Max(), maxRange - (prev.Max() - prev.Min()) default: return false, 0, 0 } } // Pat exposes the enclosed pattern. func (f Fixed) Pat() patterns.Pattern { return f.Pattern } // Save frame to a LoadSaver. func (f Fixed) Save(ls *persist.LoadSaver) { ls.SaveByte(fixedLoader) ls.SaveByte(byte(f.OffType)) ls.SaveInt(f.Off) f.Pattern.Save(ls) } func loadFixed(ls *persist.LoadSaver) Frame { return Fixed{ OffType(ls.LoadByte()), ls.LoadInt(), patterns.Load(ls), } } // Window frames are at a range of offsets e.g. e.g. 1-1500 from the BOF, EOF or a preceding or succeeding frame. type Window struct { OffType MinOff int MaxOff int patterns.Pattern } // Match the enclosed pattern against the byte slice in a L-R direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (w Window) Match(b []byte) (bool, []int) { ret := make([]int, 0, 1) min, max := w.MinOff, w.MaxOff _, m := w.Length() max += m if max > len(b) { max = len(b) } for min < max { success, length := w.Test(b[min:max]) if success { ret = append(ret, min+length) min++ } else { if length == 0 { break } min += length } } if len(ret) > 0 { return true, ret } return false, nil } func (w Window) MatchN(b []byte, n int) (bool, int) { var i int min, max := w.MinOff, w.MaxOff _, m := w.Length() max += m if max > len(b) { max = len(b) } for min < max { success, length := w.Test(b[min:max]) if success { if i == n { return true, min + length } i++ min++ } else { if length == 0 { break } min += length } } return false, -1 } // MatchR matches the enclosed pattern against the byte slice in a reverse (R-L) direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (w Window) MatchR(b []byte) (bool, []int) { ret := make([]int, 0, 1) min, max := w.MinOff, w.MaxOff _, m := w.Length() max += m if max > len(b) { max = len(b) } for min < max { success, length := w.TestR(b[len(b)-max : len(b)-min]) if success { ret = append(ret, min+length) min++ } else { if length == 0 { break } min += length } } if len(ret) > 0 { return true, ret } return false, nil } func (w Window) MatchNR(b []byte, n int) (bool, int) { var i int min, max := w.MinOff, w.MaxOff _, m := w.Length() max += m if max > len(b) { max = len(b) } for min < max { success, length := w.TestR(b[len(b)-max : len(b)-min]) if success { if i == n { return true, min + length } i++ min++ } else { if length == 0 { break } min += length } } return false, -1 } // Equals tests equality of two frames func (w Window) Equals(frame Frame) bool { w1, ok := frame.(Window) if ok { if w.OffType == w1.OffType && w.MinOff == w1.MinOff && w.MaxOff == w1.MaxOff { return w.Pattern.Equals(w1.Pattern) } } return false } func (w Window) String() string { return "WW " + OffString[w.OffType] + ":" + strconv.Itoa(w.MinOff) + "-" + strconv.Itoa(w.MaxOff) + " " + w.Pattern.String() } // Min returns the minimum offset a frame can appear at. func (w Window) Min() int { return w.MinOff } // Max returns the maximum offset a frame can appear at. Returns -1 for no limit (wildcard, *). func (w Window) Max() int { return w.MaxOff } // Linked tests whether a frame is linked to a preceding frame (by a preceding or succeding relationship) with an offset and range that is less than the supplied ints. func (w Window) Linked(prev Frame, maxDistance, maxRange int) (bool, int, int) { switch w.OffType { case PREV: if w.MaxOff > maxDistance || w.MaxOff-w.MinOff > maxRange { return false, 0, 0 } return true, maxDistance - w.MaxOff, maxRange - (w.MaxOff - w.MinOff) case SUCC, EOF: if prev.Orientation() != SUCC || prev.Max() < 0 || prev.Max() > maxDistance || prev.Max()-prev.Min() > maxRange { return false, 0, 0 } return true, maxDistance - prev.Max(), maxRange - (prev.Max() - prev.Min()) default: return false, 0, 0 } } // Pat exposes the enclosed pattern. func (w Window) Pat() patterns.Pattern { return w.Pattern } // Save frame to a LoadSaver. func (w Window) Save(ls *persist.LoadSaver) { ls.SaveByte(windowLoader) ls.SaveByte(byte(w.OffType)) ls.SaveInt(w.MinOff) ls.SaveInt(w.MaxOff) w.Pattern.Save(ls) } func loadWindow(ls *persist.LoadSaver) Frame { return Window{ OffType(ls.LoadByte()), ls.LoadInt(), ls.LoadInt(), patterns.Load(ls), } } // Wild frames can be at any offset (i.e. 0 to the end of the file) relative to the BOF, EOF or a preceding or succeeding frame. type Wild struct { OffType patterns.Pattern } // Match the enclosed pattern against the byte slice in a L-R direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (w Wild) Match(b []byte) (bool, []int) { ret := make([]int, 0, 1) min, max := 0, len(b) for min < max { success, length := w.Test(b[min:]) if success { ret = append(ret, min+length) min++ } else { if length == 0 { break } min += length } } if len(ret) > 0 { return true, ret } return false, nil } func (w Wild) MatchN(b []byte, n int) (bool, int) { var i int min, max := 0, len(b) for min < max { success, length := w.Test(b[min:]) if success { if i == n { return true, min + length } i++ min++ } else { if length == 0 { break } min += length } } return false, -1 } // MatchR matches the enclosed pattern against the byte slice in a reverse (R-L) direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (w Wild) MatchR(b []byte) (bool, []int) { ret := make([]int, 0, 1) min, max := 0, len(b) for min < max { success, length := w.TestR(b[:len(b)-min]) if success { ret = append(ret, min+length) min++ } else { if length == 0 { break } min += length } } if len(ret) > 0 { return true, ret } return false, nil } func (w Wild) MatchNR(b []byte, n int) (bool, int) { var i int min, max := 0, len(b) for min < max { success, length := w.TestR(b[:len(b)-min]) if success { if i == n { return true, min + length } i++ min++ } else { if length == 0 { break } min += length } } return false, -1 } // Equals tests equality of two frames. func (w Wild) Equals(frame Frame) bool { w1, ok := frame.(Wild) if ok { if w.OffType == w1.OffType { return w.Pattern.Equals(w1.Pattern) } } return false } func (w Wild) String() string { return "WL " + OffString[w.OffType] + " " + w.Pattern.String() } // Min returns the minimum offset a frame can appear at. func (w Wild) Min() int { return 0 } // Max returns the maximum offset a frame can appear at. Returns -1 for no limit (wildcard, *). func (w Wild) Max() int { return -1 } // Linked tests whether a frame is linked to a preceding frame (by a preceding or succeding relationship) with an offset and range that is less than the supplied ints. func (w Wild) Linked(prev Frame, maxDistance, maxRange int) (bool, int, int) { switch w.OffType { case SUCC, EOF: if prev.Orientation() != SUCC || prev.Max() < 0 || prev.Max() > maxDistance || prev.Max()-prev.Min() > maxRange { return false, 0, 0 } return true, maxDistance - prev.Max(), maxRange - (prev.Max() - prev.Min()) default: return false, 0, 0 } } // Pat exposes the enclosed pattern. func (w Wild) Pat() patterns.Pattern { return w.Pattern } // Save frame to a LoadSaver. func (w Wild) Save(ls *persist.LoadSaver) { ls.SaveByte(wildLoader) ls.SaveByte(byte(w.OffType)) w.Pattern.Save(ls) } func loadWild(ls *persist.LoadSaver) Frame { return Wild{ OffType(ls.LoadByte()), patterns.Load(ls), } } // WildMin frames have a minimum but no maximum offset (e.g. 200-*) relative to the BOF, EOF or a preceding or succeeding frame. type WildMin struct { OffType MinOff int patterns.Pattern } // Match the enclosed pattern against the byte slice in a L-R direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (w WildMin) Match(b []byte) (bool, []int) { ret := make([]int, 0, 1) min, max := w.MinOff, len(b) for min < max { success, length := w.Test(b[min:]) if success { ret = append(ret, min+length) min++ } else { if length == 0 { break } min += length } } if len(ret) > 0 { return true, ret } return false, nil } func (w WildMin) MatchN(b []byte, n int) (bool, int) { var i int min, max := w.MinOff, len(b) for min < max { success, length := w.Test(b[min:]) if success { if i == n { return true, min + length } i++ min++ } else { if length == 0 { break } min += length } } return false, -1 } // MatchR matches the enclosed pattern against the byte slice in a reverse (R-L) direction. Return a boolean to indicate success. If true, return an offset for where a successive match by a related frame should begin. func (w WildMin) MatchR(b []byte) (bool, []int) { ret := make([]int, 0, 1) min, max := w.MinOff, len(b) for min < max { success, length := w.TestR(b[:len(b)-min]) if success { ret = append(ret, min+length) min++ } else { if length == 0 { break } min += length } } if len(ret) > 0 { return true, ret } return false, nil } func (w WildMin) MatchNR(b []byte, n int) (bool, int) { var i int min, max := w.MinOff, len(b) for min < max { success, length := w.TestR(b[:len(b)-min]) if success { if i == n { return true, min + length } i++ min++ } else { if length == 0 { break } min += length } } return false, -1 } // Equals tests equality of two frames. func (w WildMin) Equals(frame Frame) bool { w1, ok := frame.(WildMin) if ok { if w.OffType == w1.OffType && w.MinOff == w1.MinOff { return w.Pattern.Equals(w1.Pattern) } } return false } func (w WildMin) String() string { return "WM " + OffString[w.OffType] + ":" + strconv.Itoa(w.MinOff) + " " + w.Pattern.String() } // Min returns the minimum offset a frame can appear at. func (w WildMin) Min() int { return w.MinOff } // Max returns the maximum offset a frame can appear at. Returns -1 for no limit (wildcard, *). func (w WildMin) Max() int { return -1 } // Linked tests whether a frame is linked to a preceding frame (by a preceding or succeding relationship) with an offset and range that is less than the supplied ints. func (w WildMin) Linked(prev Frame, maxDistance, maxRange int) (bool, int, int) { switch w.OffType { case SUCC, EOF: if prev.Orientation() != SUCC || prev.Max() < 0 || prev.Max() > maxDistance || prev.Max()-prev.Min() > maxRange { return false, 0, 0 } return true, maxDistance - prev.Max(), maxRange - (prev.Max() - prev.Min()) default: return false, 0, 0 } } // Pat exposes the enclosed pattern. func (w WildMin) Pat() patterns.Pattern { return w.Pattern } // Save frame to a LoadSaver. func (w WildMin) Save(ls *persist.LoadSaver) { ls.SaveByte(wildMinLoader) ls.SaveByte(byte(w.OffType)) ls.SaveInt(w.MinOff) w.Pattern.Save(ls) } func loadWildMin(ls *persist.LoadSaver) Frame { return WildMin{ OffType(ls.LoadByte()), ls.LoadInt(), patterns.Load(ls), } }
internal/bytematcher/frames/frames.go
0.836721
0.561696
frames.go
starcoder
package kclosestnumbers import ( "container/heap" "sort" ) /* Given a sorted number array and two integers ‘K’ and ‘X’, find ‘K’ closest numbers to ‘X’ in the array. Return the numbers in the sorted order. ‘X’ is not necessarily present in the array. Input: [5, 6, 7, 8, 9], K = 3, X = 7 Output: [6, 7, 8] Input: [2, 4, 5, 6, 9], K = 3, X = 6 Output: [4, 5, 6] Input: [2, 4, 5, 6, 9], K = 3, X = 10 Output: [5, 6, 9] ref: https://leetcode-cn.com/problems/find-k-closest-elements/ */ func findClosestElements(arr []int, k int, x int) []int { index := binarySearch(arr, x) low, high := index-k, index+k if low < 0 { low = 0 } if high > len(arr)-1 { high = len(arr) - 1 } var h IntHeap heap.Init(&h) for i := low; i <= high; i++ { heap.Push(&h, Integer{Value: arr[i], Distance: abs(arr[i] - x)}) } res := make([]int, 0, k) for i := 0; i < k; i++ { res = append(res, heap.Pop(&h).(Integer).Value) } sort.Ints(res) return res } func binarySearch(arr []int, x int) int { var ( start = 0 end = len(arr) - 1 ) for start <= end { mid := start + (end-start)/2 if arr[mid] == x { return mid } if x < arr[mid] { end = mid - 1 } else { start = mid + 1 } } if start > 0 { return start - 1 } else { return start } } func abs(x int) int { if x < 0 { return -x } return x } type Integer struct { Value int Distance int } type IntHeap []Integer func (h IntHeap) Len() int { return len(h) } func (h IntHeap) Less(i, j int) bool { if h[i].Distance != h[j].Distance { return h[i].Distance < h[j].Distance } else { return h[i].Value < h[j].Value } } func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(Integer)) } func (h *IntHeap) Pop() interface{} { old := *h n := len(old) x := old[n-1] *h = old[:n-1] return x } func findClosestElementsByTwoPointer(arr []int, k int, x int) []int { index := binarySearch(arr, x) left, right := index, index+1 res := make([]int, 0, k) for i := 0; i < k; i++ { if left >= 0 && right < len(arr) { diff1 := abs(arr[left] - x) diff2 := abs(arr[right] - x) if diff1 <= diff2 { res = append([]int{arr[left]}, res...) left-- } else { res = append(res, arr[right]) right++ } } else if left >= 0 { res = append([]int{arr[left]}, res...) left-- } else if right < len(arr) { res = append(res, arr[right]) right++ } } return res }
Pattern13 - Top K Elements/K_Closest_Numbers/solution.go
0.829008
0.586641
solution.go
starcoder
package alteryx_formulas import ( "math" "math/rand" "sort" "strconv" ) func (calc *calculator) addNumbers() { add := func(left interface{}, right interface{}) interface{} { return left.(float64) + right.(float64) } calc.ifNonNullLeftRight(add) } func (calc *calculator) subtractNumbers() { subtract := func(left interface{}, right interface{}) interface{} { return left.(float64) - right.(float64) } calc.ifNonNullLeftRight(subtract) } func (calc *calculator) multiplyNumbers() { multiply := func(left interface{}, right interface{}) interface{} { return left.(float64) * right.(float64) } calc.ifNonNullLeftRight(multiply) } func (calc *calculator) divideNumbers() { divide := func(left interface{}, right interface{}) interface{} { if right.(float64) == 0 { return nil } return left.(float64) / right.(float64) } calc.ifNonNullLeftRight(divide) } func (calc *calculator) pow() { value := calc.popValue() power := calc.popValue() if value == nil || power == nil { calc.pushValue(nil) return } calc.pushValue(math.Pow(value.(float64), power.(float64))) } func (calc *calculator) abs() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Abs(expr.(float64))) } func (calc *calculator) acos() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Acos(expr.(float64))) } func (calc *calculator) asin() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Asin(expr.(float64))) } func (calc *calculator) atan() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Atan(expr.(float64))) } func (calc *calculator) atan2() { expr1 := calc.popValue() expr2 := calc.popValue() if expr1 == nil { calc.pushValue(nil) return } if expr2 == nil { expr2 = 0.0 } calc.pushValue(math.Atan2(expr1.(float64), expr2.(float64))) } func (calc *calculator) average() { exprCount := calc.popValue().(int) sum := 0.0 for i := 0; i < exprCount; i++ { value := calc.popValue() if value == nil { continue } sum += value.(float64) } calc.pushValue(sum / float64(exprCount)) } func (calc *calculator) ceil() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Ceil(expr.(float64))) } func (calc *calculator) cos() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Cos(expr.(float64))) } func (calc *calculator) cosh() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Cosh(expr.(float64))) } func (calc *calculator) distance() { values := make([]float64, 4) for i := 0; i < 4; i++ { poppedValue := calc.popValue() if poppedValue == nil { values[i] = 0.0 } else { values[i] = poppedValue.(float64) } } distance, _ := calc.geo.To(values[0], values[1], values[2], values[3]) calc.pushValue(distance) } func (calc *calculator) exp() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Exp(expr.(float64))) } func (calc *calculator) floor() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Floor(expr.(float64))) } func (calc *calculator) log() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Log(expr.(float64))) } func (calc *calculator) log10() { expr := calc.popValue() if expr == nil { calc.pushValue(nil) return } calc.pushValue(math.Log10(expr.(float64))) } func (calc *calculator) median() { exprCount := calc.popValue().(int) exprs := make([]float64, exprCount) for i := 0; i < exprCount; i++ { popped := calc.popValue() if popped == nil { exprs[i] = 0.0 } else { exprs[i] = popped.(float64) } } sort.Float64s(exprs) var value float64 if exprCount%2 > 0 { valueIndex := int(math.Floor(float64(exprCount) / 2)) value = exprs[valueIndex] } else { valueIndex := exprCount / 2 value = (exprs[valueIndex] + exprs[valueIndex-1]) / 2 } calc.pushValue(value) } func (calc *calculator) mod() { expr1 := calc.popValue() expr2 := calc.popValue() if expr1 == nil || expr2 == nil { calc.pushValue(nil) return } dividend := int(expr1.(float64)) divisor := int(expr2.(float64)) if divisor == 0 { calc.pushValue(nil) return } remainder := dividend % divisor calc.pushValue(float64(remainder)) } func (calc *calculator) pi() { calc.pushValue(math.Pi) } func (calc *calculator) rand() { calc.pushValue(rand.Float64()) } func (calc *calculator) randInt() { // adding 1 to the ceiling and using Floor() gives each integer the same probability. If we use the ceiling // as-is and then round the final result, 0 and the ceiling both have half the probability of the other integers // and will, over time, have half the number of hits. expr := calc.popValue() if expr == nil { calc.pushValue(0.0) return } ceiling := expr.(float64) + 1 value := rand.Float64() * ceiling calc.pushValue(math.Floor(value)) } func (calc *calculator) round() { expr1 := calc.popValue() expr2 := calc.popValue() if expr1 == nil || expr2 == nil { calc.pushValue(nil) return } value := expr1.(float64) multiple := expr2.(float64) if multiple == 0 { calc.pushValue(nil) return } floor, _ := math.Modf(value / multiple) floor = floor * multiple var ceiling float64 if value >= 0 { ceiling = floor + multiple } else { ceiling = floor - multiple } if math.Abs(value-floor) < math.Abs(value-ceiling) { calc.pushValue(floor) } else { calc.pushValue(ceiling) } } func (calc *calculator) sin() { radians := calc.popValue() if radians == nil { calc.pushValue(nil) return } calc.pushValue(math.Sin(radians.(float64))) } func (calc *calculator) sinh() { radians := calc.popValue() if radians == nil { calc.pushValue(nil) return } calc.pushValue(math.Sinh(radians.(float64))) } func (calc *calculator) sqrt() { value := calc.popValue() if value == nil { calc.pushValue(nil) return } calc.pushValue(math.Sqrt(value.(float64))) } func (calc *calculator) tan() { radians := calc.popValue() if radians == nil { calc.pushValue(nil) return } calc.pushValue(math.Tan(radians.(float64))) } func (calc *calculator) tanh() { radians := calc.popValue() if radians == nil { calc.pushValue(nil) return } calc.pushValue(math.Tanh(radians.(float64))) } func (calc *calculator) hexToNumber() { hexCode := calc.popValue() if hexCode == nil { calc.pushValue(nil) return } result, err := strconv.ParseInt(hexCode.(string), 16, 64) if err != nil { calc.pushValue(nil) return } calc.pushValue(float64(result)) }
calculator_numbers.go
0.620622
0.412767
calculator_numbers.go
starcoder
package onshape import ( "encoding/json" ) // BTPExpressionOperator244 struct for BTPExpressionOperator244 type BTPExpressionOperator244 struct { BTPExpression9 BtType *string `json:"btType,omitempty"` ForExport *bool `json:"forExport,omitempty"` GlobalNamespace *bool `json:"globalNamespace,omitempty"` ImportMicroversion *string `json:"importMicroversion,omitempty"` Namespace *[]BTPIdentifier8 `json:"namespace,omitempty"` Operand1 *BTPExpression9 `json:"operand1,omitempty"` Operand2 *BTPExpression9 `json:"operand2,omitempty"` Operand3 *BTPExpression9 `json:"operand3,omitempty"` Operator *string `json:"operator,omitempty"` SpaceAfterNamespace *BTPSpace10 `json:"spaceAfterNamespace,omitempty"` SpaceAfterOperator *BTPSpace10 `json:"spaceAfterOperator,omitempty"` SpaceBeforeOperator *BTPSpace10 `json:"spaceBeforeOperator,omitempty"` WrittenAsFunctionCall *bool `json:"writtenAsFunctionCall,omitempty"` } // NewBTPExpressionOperator244 instantiates a new BTPExpressionOperator244 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 NewBTPExpressionOperator244() *BTPExpressionOperator244 { this := BTPExpressionOperator244{} return &this } // NewBTPExpressionOperator244WithDefaults instantiates a new BTPExpressionOperator244 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 NewBTPExpressionOperator244WithDefaults() *BTPExpressionOperator244 { this := BTPExpressionOperator244{} return &this } // GetBtType returns the BtType field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetBtType() string { if o == nil || o.BtType == nil { var ret string return ret } return *o.BtType } // GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetBtTypeOk() (*string, bool) { if o == nil || o.BtType == nil { return nil, false } return o.BtType, true } // HasBtType returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasBtType() bool { if o != nil && o.BtType != nil { return true } return false } // SetBtType gets a reference to the given string and assigns it to the BtType field. func (o *BTPExpressionOperator244) SetBtType(v string) { o.BtType = &v } // GetForExport returns the ForExport field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetForExport() bool { if o == nil || o.ForExport == nil { var ret bool return ret } return *o.ForExport } // GetForExportOk returns a tuple with the ForExport field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetForExportOk() (*bool, bool) { if o == nil || o.ForExport == nil { return nil, false } return o.ForExport, true } // HasForExport returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasForExport() bool { if o != nil && o.ForExport != nil { return true } return false } // SetForExport gets a reference to the given bool and assigns it to the ForExport field. func (o *BTPExpressionOperator244) SetForExport(v bool) { o.ForExport = &v } // GetGlobalNamespace returns the GlobalNamespace field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetGlobalNamespace() bool { if o == nil || o.GlobalNamespace == nil { var ret bool return ret } return *o.GlobalNamespace } // GetGlobalNamespaceOk returns a tuple with the GlobalNamespace field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetGlobalNamespaceOk() (*bool, bool) { if o == nil || o.GlobalNamespace == nil { return nil, false } return o.GlobalNamespace, true } // HasGlobalNamespace returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasGlobalNamespace() bool { if o != nil && o.GlobalNamespace != nil { return true } return false } // SetGlobalNamespace gets a reference to the given bool and assigns it to the GlobalNamespace field. func (o *BTPExpressionOperator244) SetGlobalNamespace(v bool) { o.GlobalNamespace = &v } // GetImportMicroversion returns the ImportMicroversion field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetImportMicroversion() string { if o == nil || o.ImportMicroversion == nil { var ret string return ret } return *o.ImportMicroversion } // GetImportMicroversionOk returns a tuple with the ImportMicroversion field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetImportMicroversionOk() (*string, bool) { if o == nil || o.ImportMicroversion == nil { return nil, false } return o.ImportMicroversion, true } // HasImportMicroversion returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasImportMicroversion() bool { if o != nil && o.ImportMicroversion != nil { return true } return false } // SetImportMicroversion gets a reference to the given string and assigns it to the ImportMicroversion field. func (o *BTPExpressionOperator244) SetImportMicroversion(v string) { o.ImportMicroversion = &v } // GetNamespace returns the Namespace field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetNamespace() []BTPIdentifier8 { if o == nil || o.Namespace == nil { var ret []BTPIdentifier8 return ret } return *o.Namespace } // GetNamespaceOk returns a tuple with the Namespace field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetNamespaceOk() (*[]BTPIdentifier8, bool) { if o == nil || o.Namespace == nil { return nil, false } return o.Namespace, true } // HasNamespace returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasNamespace() bool { if o != nil && o.Namespace != nil { return true } return false } // SetNamespace gets a reference to the given []BTPIdentifier8 and assigns it to the Namespace field. func (o *BTPExpressionOperator244) SetNamespace(v []BTPIdentifier8) { o.Namespace = &v } // GetOperand1 returns the Operand1 field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetOperand1() BTPExpression9 { if o == nil || o.Operand1 == nil { var ret BTPExpression9 return ret } return *o.Operand1 } // GetOperand1Ok returns a tuple with the Operand1 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetOperand1Ok() (*BTPExpression9, bool) { if o == nil || o.Operand1 == nil { return nil, false } return o.Operand1, true } // HasOperand1 returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasOperand1() bool { if o != nil && o.Operand1 != nil { return true } return false } // SetOperand1 gets a reference to the given BTPExpression9 and assigns it to the Operand1 field. func (o *BTPExpressionOperator244) SetOperand1(v BTPExpression9) { o.Operand1 = &v } // GetOperand2 returns the Operand2 field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetOperand2() BTPExpression9 { if o == nil || o.Operand2 == nil { var ret BTPExpression9 return ret } return *o.Operand2 } // GetOperand2Ok returns a tuple with the Operand2 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetOperand2Ok() (*BTPExpression9, bool) { if o == nil || o.Operand2 == nil { return nil, false } return o.Operand2, true } // HasOperand2 returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasOperand2() bool { if o != nil && o.Operand2 != nil { return true } return false } // SetOperand2 gets a reference to the given BTPExpression9 and assigns it to the Operand2 field. func (o *BTPExpressionOperator244) SetOperand2(v BTPExpression9) { o.Operand2 = &v } // GetOperand3 returns the Operand3 field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetOperand3() BTPExpression9 { if o == nil || o.Operand3 == nil { var ret BTPExpression9 return ret } return *o.Operand3 } // GetOperand3Ok returns a tuple with the Operand3 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetOperand3Ok() (*BTPExpression9, bool) { if o == nil || o.Operand3 == nil { return nil, false } return o.Operand3, true } // HasOperand3 returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasOperand3() bool { if o != nil && o.Operand3 != nil { return true } return false } // SetOperand3 gets a reference to the given BTPExpression9 and assigns it to the Operand3 field. func (o *BTPExpressionOperator244) SetOperand3(v BTPExpression9) { o.Operand3 = &v } // GetOperator returns the Operator field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetOperator() string { if o == nil || o.Operator == nil { var ret string return ret } return *o.Operator } // GetOperatorOk returns a tuple with the Operator field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetOperatorOk() (*string, bool) { if o == nil || o.Operator == nil { return nil, false } return o.Operator, true } // HasOperator returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasOperator() bool { if o != nil && o.Operator != nil { return true } return false } // SetOperator gets a reference to the given string and assigns it to the Operator field. func (o *BTPExpressionOperator244) SetOperator(v string) { o.Operator = &v } // GetSpaceAfterNamespace returns the SpaceAfterNamespace field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetSpaceAfterNamespace() BTPSpace10 { if o == nil || o.SpaceAfterNamespace == nil { var ret BTPSpace10 return ret } return *o.SpaceAfterNamespace } // GetSpaceAfterNamespaceOk returns a tuple with the SpaceAfterNamespace field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetSpaceAfterNamespaceOk() (*BTPSpace10, bool) { if o == nil || o.SpaceAfterNamespace == nil { return nil, false } return o.SpaceAfterNamespace, true } // HasSpaceAfterNamespace returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasSpaceAfterNamespace() bool { if o != nil && o.SpaceAfterNamespace != nil { return true } return false } // SetSpaceAfterNamespace gets a reference to the given BTPSpace10 and assigns it to the SpaceAfterNamespace field. func (o *BTPExpressionOperator244) SetSpaceAfterNamespace(v BTPSpace10) { o.SpaceAfterNamespace = &v } // GetSpaceAfterOperator returns the SpaceAfterOperator field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetSpaceAfterOperator() BTPSpace10 { if o == nil || o.SpaceAfterOperator == nil { var ret BTPSpace10 return ret } return *o.SpaceAfterOperator } // GetSpaceAfterOperatorOk returns a tuple with the SpaceAfterOperator field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetSpaceAfterOperatorOk() (*BTPSpace10, bool) { if o == nil || o.SpaceAfterOperator == nil { return nil, false } return o.SpaceAfterOperator, true } // HasSpaceAfterOperator returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasSpaceAfterOperator() bool { if o != nil && o.SpaceAfterOperator != nil { return true } return false } // SetSpaceAfterOperator gets a reference to the given BTPSpace10 and assigns it to the SpaceAfterOperator field. func (o *BTPExpressionOperator244) SetSpaceAfterOperator(v BTPSpace10) { o.SpaceAfterOperator = &v } // GetSpaceBeforeOperator returns the SpaceBeforeOperator field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetSpaceBeforeOperator() BTPSpace10 { if o == nil || o.SpaceBeforeOperator == nil { var ret BTPSpace10 return ret } return *o.SpaceBeforeOperator } // GetSpaceBeforeOperatorOk returns a tuple with the SpaceBeforeOperator field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetSpaceBeforeOperatorOk() (*BTPSpace10, bool) { if o == nil || o.SpaceBeforeOperator == nil { return nil, false } return o.SpaceBeforeOperator, true } // HasSpaceBeforeOperator returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasSpaceBeforeOperator() bool { if o != nil && o.SpaceBeforeOperator != nil { return true } return false } // SetSpaceBeforeOperator gets a reference to the given BTPSpace10 and assigns it to the SpaceBeforeOperator field. func (o *BTPExpressionOperator244) SetSpaceBeforeOperator(v BTPSpace10) { o.SpaceBeforeOperator = &v } // GetWrittenAsFunctionCall returns the WrittenAsFunctionCall field value if set, zero value otherwise. func (o *BTPExpressionOperator244) GetWrittenAsFunctionCall() bool { if o == nil || o.WrittenAsFunctionCall == nil { var ret bool return ret } return *o.WrittenAsFunctionCall } // GetWrittenAsFunctionCallOk returns a tuple with the WrittenAsFunctionCall field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPExpressionOperator244) GetWrittenAsFunctionCallOk() (*bool, bool) { if o == nil || o.WrittenAsFunctionCall == nil { return nil, false } return o.WrittenAsFunctionCall, true } // HasWrittenAsFunctionCall returns a boolean if a field has been set. func (o *BTPExpressionOperator244) HasWrittenAsFunctionCall() bool { if o != nil && o.WrittenAsFunctionCall != nil { return true } return false } // SetWrittenAsFunctionCall gets a reference to the given bool and assigns it to the WrittenAsFunctionCall field. func (o *BTPExpressionOperator244) SetWrittenAsFunctionCall(v bool) { o.WrittenAsFunctionCall = &v } func (o BTPExpressionOperator244) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} serializedBTPExpression9, errBTPExpression9 := json.Marshal(o.BTPExpression9) if errBTPExpression9 != nil { return []byte{}, errBTPExpression9 } errBTPExpression9 = json.Unmarshal([]byte(serializedBTPExpression9), &toSerialize) if errBTPExpression9 != nil { return []byte{}, errBTPExpression9 } if o.BtType != nil { toSerialize["btType"] = o.BtType } if o.ForExport != nil { toSerialize["forExport"] = o.ForExport } if o.GlobalNamespace != nil { toSerialize["globalNamespace"] = o.GlobalNamespace } if o.ImportMicroversion != nil { toSerialize["importMicroversion"] = o.ImportMicroversion } if o.Namespace != nil { toSerialize["namespace"] = o.Namespace } if o.Operand1 != nil { toSerialize["operand1"] = o.Operand1 } if o.Operand2 != nil { toSerialize["operand2"] = o.Operand2 } if o.Operand3 != nil { toSerialize["operand3"] = o.Operand3 } if o.Operator != nil { toSerialize["operator"] = o.Operator } if o.SpaceAfterNamespace != nil { toSerialize["spaceAfterNamespace"] = o.SpaceAfterNamespace } if o.SpaceAfterOperator != nil { toSerialize["spaceAfterOperator"] = o.SpaceAfterOperator } if o.SpaceBeforeOperator != nil { toSerialize["spaceBeforeOperator"] = o.SpaceBeforeOperator } if o.WrittenAsFunctionCall != nil { toSerialize["writtenAsFunctionCall"] = o.WrittenAsFunctionCall } return json.Marshal(toSerialize) } type NullableBTPExpressionOperator244 struct { value *BTPExpressionOperator244 isSet bool } func (v NullableBTPExpressionOperator244) Get() *BTPExpressionOperator244 { return v.value } func (v *NullableBTPExpressionOperator244) Set(val *BTPExpressionOperator244) { v.value = val v.isSet = true } func (v NullableBTPExpressionOperator244) IsSet() bool { return v.isSet } func (v *NullableBTPExpressionOperator244) Unset() { v.value = nil v.isSet = false } func NewNullableBTPExpressionOperator244(val *BTPExpressionOperator244) *NullableBTPExpressionOperator244 { return &NullableBTPExpressionOperator244{value: val, isSet: true} } func (v NullableBTPExpressionOperator244) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBTPExpressionOperator244) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
onshape/model_btp_expression_operator_244.go
0.717804
0.456228
model_btp_expression_operator_244.go
starcoder
package camt import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02600105 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.026.001.05 Document"` Message *UnableToApplyV05 `xml:"UblToApply"` } func (d *Document02600105) AddMessage() *UnableToApplyV05 { d.Message = new(UnableToApplyV05) return d.Message } // Scope // The Unable To Apply message is sent by a case creator or a case assigner to a case assignee. This message is used to initiate an investigation of a payment instruction that cannot be executed or reconciled. // Usage // The Unable To Apply case occurs in two situations: // - an agent cannot execute the payment instruction due to missing or incorrect information // - a creditor cannot reconcile the payment entry as it is received unexpectedly, or missing or incorrect information prevents reconciliation // The Unable To Apply message // - always follows the reverse route of the original payment instruction // - must be forwarded to the preceding agents in the payment processing chain, where appropriate // - covers one and only one payment instruction (or payment entry) at a time; if several payment instructions cannot be executed or several payment entries cannot be reconciled, then multiple Unable To Apply messages must be sent. // Depending on what stage the payment is and what has been done to it, for example incorrect routing, errors/omissions when processing the instruction or even the absence of any error, the unable to apply case may lead to a: // - Additional Payment Information message, sent to the case creator/case assigner, if a truncation or omission in a payment instruction prevented reconciliation. // - Request To Cancel Payment message, sent to the subsequent agent in the payment processing chain, if the original payment instruction has been incorrectly routed through the chain of agents (this also entails a new corrected payment instruction being issued). Prior to sending the payment cancellation request, the agent should first send a resolution indicating that a cancellation will follow (CWFW). // - Request To Modify Payment message, sent to the subsequent agent in the payment processing chain, if a truncation or omission has occurred during the processing of the original payment instruction. Prior to sending the modify payment request, the agent should first send a resolution indicating that a modification will follow (MWFW). // - Debit Authorisation Request message, sent to the case creator/case assigner, if the payment instruction has reached an incorrect creditor. // The UnableToApply message has the following main characteristics: // The case creator (the instructed party/creditor of a payment instruction) assigns a unique case identification and optionally the reason code for the Unable To Apply message. This information will be passed unchanged to all subsequent case assignees. // The case creator specifies the identification of the underlying payment instruction. This identification needs to be updated by the subsequent case assigner(s) in order to match the one used with their case assignee(s). // The Unable To Apply Justification element allows the assigner to indicate whether a specific element causes the unable to apply situation (incorrect element and/or mismatched element can be listed) or whether any supplementary information needs to be forwarded. type UnableToApplyV05 struct { // Identifies the assignment of an investigation case from an assigner to an assignee. // Usage: The Assigner must be the sender of this confirmation and the Assignee must be the receiver. Assignment *iso20022.CaseAssignment3 `xml:"Assgnmt"` // Identifies the investigation case. Case *iso20022.Case3 `xml:"Case"` // References the payment instruction or statement entry that a party is unable to execute or unable to reconcile. Underlying *iso20022.UnderlyingTransaction3Choice `xml:"Undrlyg"` // Explains the reason why the case creator is unable to apply the instruction. Justification *iso20022.UnableToApplyJustification3Choice `xml:"Justfn"` // Additional information that cannot be captured in the structured elements and/or any other specific block. SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (u *UnableToApplyV05) AddAssignment() *iso20022.CaseAssignment3 { u.Assignment = new(iso20022.CaseAssignment3) return u.Assignment } func (u *UnableToApplyV05) AddCase() *iso20022.Case3 { u.Case = new(iso20022.Case3) return u.Case } func (u *UnableToApplyV05) AddUnderlying() *iso20022.UnderlyingTransaction3Choice { u.Underlying = new(iso20022.UnderlyingTransaction3Choice) return u.Underlying } func (u *UnableToApplyV05) AddJustification() *iso20022.UnableToApplyJustification3Choice { u.Justification = new(iso20022.UnableToApplyJustification3Choice) return u.Justification } func (u *UnableToApplyV05) AddSupplementaryData() *iso20022.SupplementaryData1 { newValue := new(iso20022.SupplementaryData1) u.SupplementaryData = append(u.SupplementaryData, newValue) return newValue }
iso20022/camt/UnableToApplyV05.go
0.722037
0.472623
UnableToApplyV05.go
starcoder
package core import ( "context" "github.com/jhump/golang-x-tools/internal/event/keys" "github.com/jhump/golang-x-tools/internal/event/label" ) // Log1 takes a message and one label delivers a log event to the exporter. // It is a customized version of Print that is faster and does no allocation. func Log1(ctx context.Context, message string, t1 label.Label) { Export(ctx, MakeEvent([3]label.Label{ keys.Msg.Of(message), t1, }, nil)) } // Log2 takes a message and two labels and delivers a log event to the exporter. // It is a customized version of Print that is faster and does no allocation. func Log2(ctx context.Context, message string, t1 label.Label, t2 label.Label) { Export(ctx, MakeEvent([3]label.Label{ keys.Msg.Of(message), t1, t2, }, nil)) } // Metric1 sends a label event to the exporter with the supplied labels. func Metric1(ctx context.Context, t1 label.Label) context.Context { return Export(ctx, MakeEvent([3]label.Label{ keys.Metric.New(), t1, }, nil)) } // Metric2 sends a label event to the exporter with the supplied labels. func Metric2(ctx context.Context, t1, t2 label.Label) context.Context { return Export(ctx, MakeEvent([3]label.Label{ keys.Metric.New(), t1, t2, }, nil)) } // Start1 sends a span start event with the supplied label list to the exporter. // It also returns a function that will end the span, which should normally be // deferred. func Start1(ctx context.Context, name string, t1 label.Label) (context.Context, func()) { return ExportPair(ctx, MakeEvent([3]label.Label{ keys.Start.Of(name), t1, }, nil), MakeEvent([3]label.Label{ keys.End.New(), }, nil)) } // Start2 sends a span start event with the supplied label list to the exporter. // It also returns a function that will end the span, which should normally be // deferred. func Start2(ctx context.Context, name string, t1, t2 label.Label) (context.Context, func()) { return ExportPair(ctx, MakeEvent([3]label.Label{ keys.Start.Of(name), t1, t2, }, nil), MakeEvent([3]label.Label{ keys.End.New(), }, nil)) }
internal/event/core/fast.go
0.656768
0.423577
fast.go
starcoder
package ring import ( "context" "sort" "time" ) // ReplicationSet describes the ingesters to talk to for a given key, and how // many errors to tolerate. type ReplicationSet struct { Ingesters []InstanceDesc // Maximum number of tolerated failing instances. Max errors and max unavailable zones are // mutually exclusive. MaxErrors int // Maximum number of different zones in which instances can fail. Max unavailable zones and // max errors are mutually exclusive. MaxUnavailableZones int } // Do function f in parallel for all replicas in the set, erroring is we exceed // MaxErrors and returning early otherwise. func (r ReplicationSet) Do(ctx context.Context, delay time.Duration, f func(context.Context, *InstanceDesc) (interface{}, error)) ([]interface{}, error) { type instanceResult struct { res interface{} err error instance *InstanceDesc } // Initialise the result tracker, which is use to keep track of successes and failures. var tracker replicationSetResultTracker if r.MaxUnavailableZones > 0 { tracker = newZoneAwareResultTracker(r.Ingesters, r.MaxUnavailableZones) } else { tracker = newDefaultResultTracker(r.Ingesters, r.MaxErrors) } var ( ch = make(chan instanceResult, len(r.Ingesters)) forceStart = make(chan struct{}, r.MaxErrors) ) ctx, cancel := context.WithCancel(ctx) defer cancel() // Spawn a goroutine for each instance. for i := range r.Ingesters { go func(i int, ing *InstanceDesc) { // Wait to send extra requests. Works only when zone-awareness is disabled. if delay > 0 && r.MaxUnavailableZones == 0 && i >= len(r.Ingesters)-r.MaxErrors { after := time.NewTimer(delay) defer after.Stop() select { case <-ctx.Done(): return case <-forceStart: case <-after.C: } } result, err := f(ctx, ing) ch <- instanceResult{ res: result, err: err, instance: ing, } }(i, &r.Ingesters[i]) } results := make([]interface{}, 0, len(r.Ingesters)) for !tracker.succeeded() { select { case res := <-ch: tracker.done(res.instance, res.err) if res.err != nil { if tracker.failed() { return nil, res.err } // force one of the delayed requests to start if delay > 0 && r.MaxUnavailableZones == 0 { forceStart <- struct{}{} } } else { results = append(results, res.res) } case <-ctx.Done(): return nil, ctx.Err() } } return results, nil } // Includes returns whether the replication set includes the replica with the provided addr. func (r ReplicationSet) Includes(addr string) bool { for _, instance := range r.Ingesters { if instance.GetAddr() == addr { return true } } return false } // GetAddresses returns the addresses of all instances within the replication set. Returned slice // order is not guaranteed. func (r ReplicationSet) GetAddresses() []string { addrs := make([]string, 0, len(r.Ingesters)) for _, desc := range r.Ingesters { addrs = append(addrs, desc.Addr) } return addrs } // HasReplicationSetChanged returns true if two replications sets are the same (with possibly different timestamps), // false if they differ in any way (number of instances, instance states, tokens, zones, ...). func HasReplicationSetChanged(before, after ReplicationSet) bool { beforeInstances := before.Ingesters afterInstances := after.Ingesters if len(beforeInstances) != len(afterInstances) { return true } sort.Sort(ByAddr(beforeInstances)) sort.Sort(ByAddr(afterInstances)) for i := 0; i < len(beforeInstances); i++ { b := beforeInstances[i] a := afterInstances[i] // Exclude the heartbeat timestamp from the comparison. b.Timestamp = 0 a.Timestamp = 0 if !b.Equal(a) { return true } } return false }
vendor/github.com/cortexproject/cortex/pkg/ring/replication_set.go
0.635109
0.40486
replication_set.go
starcoder
package trie import ( "fmt" "sort" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric/core/util" ) type trieNode struct { trieKey *trieKey value []byte childrenCryptoHashes map[int][]byte valueUpdated bool childrenCryptoHashesUpdated map[int]bool markedForDeletion bool } func newTrieNode(key *trieKey, value []byte, updated bool) *trieNode { return &trieNode{ trieKey: key, value: value, childrenCryptoHashes: make(map[int][]byte), valueUpdated: updated, childrenCryptoHashesUpdated: make(map[int]bool), } } func (trieNode *trieNode) getLevel() int { return trieNode.trieKey.getLevel() } func (trieNode *trieNode) isRootNode() bool { return trieNode.trieKey.isRootKey() } func (trieNode *trieNode) setChildCryptoHash(index int, childCryptoHash []byte) { if index >= trieKeyEncoderImpl.getMaxTrieWidth() { panic(fmt.Errorf("Index for child crypto-hash cannot be greater than [%d]. Tried to access index value [%d]", trieKeyEncoderImpl.getMaxTrieWidth(), index)) } if childCryptoHash != nil { trieNode.childrenCryptoHashes[index] = childCryptoHash } trieNode.childrenCryptoHashesUpdated[index] = true } func (trieNode *trieNode) getParentTrieKey() *trieKey { return trieNode.trieKey.getParentTrieKey() } func (trieNode *trieNode) getParentLevel() int { return trieNode.trieKey.getParentLevel() } func (trieNode *trieNode) getIndexInParent() int { return trieNode.trieKey.getIndexInParent() } func (trieNode *trieNode) mergeMissingAttributesFrom(dbTrieNode *trieNode) { stateTrieLogger.Debugf("Enter mergeMissingAttributesFrom() baseNode=[%s], mergeNode=[%s]", trieNode, dbTrieNode) if !trieNode.valueUpdated { trieNode.value = dbTrieNode.value } for k, v := range dbTrieNode.childrenCryptoHashes { if !trieNode.childrenCryptoHashesUpdated[k] { trieNode.childrenCryptoHashes[k] = v } } stateTrieLogger.Debugf("Exit mergeMissingAttributesFrom() mergedNode=[%s]", trieNode) } func (trieNode *trieNode) computeCryptoHash() []byte { stateTrieLogger.Debugf("Enter computeCryptoHash() for trieNode [%s]", trieNode) var cryptoHashContent []byte if trieNode.containsValue() { stateTrieLogger.Debugf("Adding value to hash computation for trieNode [%s]", trieNode) key := trieNode.trieKey.getEncodedBytes() cryptoHashContent = append(cryptoHashContent, proto.EncodeVarint(uint64(len(key)))...) cryptoHashContent = append(cryptoHashContent, key...) cryptoHashContent = append(cryptoHashContent, trieNode.value...) } sortedChildrenIndexes := trieNode.getSortedChildrenIndex() for _, index := range sortedChildrenIndexes { childCryptoHash := trieNode.childrenCryptoHashes[index] stateTrieLogger.Debugf("Adding hash [%#v] for child number [%d] to hash computation for trieNode [%s]", childCryptoHash, index, trieNode) cryptoHashContent = append(cryptoHashContent, childCryptoHash...) } if cryptoHashContent == nil { // node has no associated value and no associated children. stateTrieLogger.Debugf("Returning nil as hash for trieNode = [%s]. Also, marking this key for deletion.", trieNode) trieNode.markedForDeletion = true return nil } if !trieNode.containsValue() && trieNode.getNumChildren() == 1 { // node has no associated value and has a single child. Propagate the child hash up stateTrieLogger.Debugf("Returning hash as of a single child for trieKey = [%s]", trieNode.trieKey) return cryptoHashContent } stateTrieLogger.Debugf("Recomputing hash for trieKey = [%s]", trieNode) return util.ComputeCryptoHash(cryptoHashContent) } func (trieNode *trieNode) containsValue() bool { if trieNode.isRootNode() { return false } return trieNode.value != nil } func (trieNode *trieNode) marshal() ([]byte, error) { buffer := proto.NewBuffer([]byte{}) // write value marker explicitly because rocksdb apis convertes a nil into an empty array and protobuf does it other-way around var valueMarker uint64 = 0 // ignore golint warning. Dropping '= 0' makes assignment less clear if trieNode.value != nil { valueMarker = 1 } err := buffer.EncodeVarint(valueMarker) if err != nil { return nil, err } if trieNode.value != nil { // write value err = buffer.EncodeRawBytes(trieNode.value) if err != nil { return nil, err } } //write number of crypto-hashes numCryptoHashes := trieNode.getNumChildren() err = buffer.EncodeVarint(uint64(numCryptoHashes)) if err != nil { return nil, err } if numCryptoHashes == 0 { return buffer.Bytes(), nil } for i, cryptoHash := range trieNode.childrenCryptoHashes { //write crypto-hash Index err = buffer.EncodeVarint(uint64(i)) if err != nil { return nil, err } // write crypto-hash err = buffer.EncodeRawBytes(cryptoHash) if err != nil { return nil, err } } serializedBytes := buffer.Bytes() stateTrieLogger.Debugf("Marshalled trieNode [%s]. Serialized bytes size = %d", trieNode.trieKey, len(serializedBytes)) return serializedBytes, nil } func unmarshalTrieNode(key *trieKey, serializedContent []byte) (*trieNode, error) { stateTrieLogger.Debugf("key = [%s], len(serializedContent) = %d", key, len(serializedContent)) trieNode := newTrieNode(key, nil, false) buffer := proto.NewBuffer(serializedContent) trieNode.value = unmarshalTrieNodeValueFromBuffer(buffer) numCryptoHashes, err := buffer.DecodeVarint() stateTrieLogger.Debugf("numCryptoHashes = [%d]", numCryptoHashes) if err != nil { return nil, err } for i := uint64(0); i < numCryptoHashes; i++ { index, err := buffer.DecodeVarint() if err != nil { return nil, err } cryptoHash, err := buffer.DecodeRawBytes(false) if err != nil { return nil, err } trieNode.childrenCryptoHashes[int(index)] = cryptoHash } stateTrieLogger.Debugf("unmarshalled trieNode = [%s]", trieNode) return trieNode, nil } func unmarshalTrieNodeValue(serializedContent []byte) []byte { return unmarshalTrieNodeValueFromBuffer(proto.NewBuffer(serializedContent)) } func unmarshalTrieNodeValueFromBuffer(buffer *proto.Buffer) []byte { valueMarker, err := buffer.DecodeVarint() if err != nil { panic(fmt.Errorf("This error is not excpected: %s", err)) } if valueMarker == 0 { return nil } value, err := buffer.DecodeRawBytes(false) if err != nil { panic(fmt.Errorf("This error is not excpected: %s", err)) } return value } func (trieNode *trieNode) String() string { return fmt.Sprintf("trieKey=[%s], value=[%#v], Num children hashes=[%#v]", trieNode.trieKey, trieNode.value, trieNode.getNumChildren()) } func (trieNode *trieNode) getNumChildren() int { return len(trieNode.childrenCryptoHashes) } func (trieNode *trieNode) getSortedChildrenIndex() []int { keys := make([]int, trieNode.getNumChildren()) i := 0 for k := range trieNode.childrenCryptoHashes { keys[i] = k i++ } sort.Ints(keys) return keys }
core/ledger/statemgmt/trie/trie_node.go
0.606032
0.430806
trie_node.go
starcoder
package labCode /* NetworkResponse create response messages for network. All of the RPC are sent using these message functions. The functions will create a Response object with the data it has to send. Then the MessageHandler function will send and retreive the response from the other contact. */ // Will create a simple ping RPC response object func (network *Network) CreatePingResponse(res Response) Response { responseMessage := Response{ RPC: "ping", ID: res.ID, SendingContact: &network.Node.Me, } return responseMessage } // Creates a find_node RPC response containing the nodes k closest contacts to a given ID func (network *Network) CreateFindNodeResponse(res Response) Response { contacts := network.Node.Routingtable.FindClosestContacts(res.Body.KadID, bucketSize) resBody := Msgbody{ Nodes: contacts, } responseMessage := Response{ RPC: "find_node", ID: res.ID, SendingContact: &network.Node.Me, Body: resBody, } return responseMessage } // Creates a find_data RPC response containing only the data requested if it is stored in the node // Or will return the 20 closest contacts to the hashed value ID func (network *Network) CreateFindDataResponse(res Response) Response { // Gets the data object from the map if the hash matches a key var value []byte var containsHash bool value, containsHash = network.Node.getDataFromStore(res.Body.Hash) if containsHash { resBody := Msgbody{ Data: value, } responseMessage := Response{ RPC: "find_data", SendingContact: &network.Node.Me, ID: res.ID, Body: resBody, } return responseMessage } contacts := network.Node.Routingtable.FindClosestContacts(NewKademliaID(res.Body.Hash), 20) resBody := Msgbody{ Nodes: contacts, } responseMessage := Response{ RPC: "find_data", SendingContact: &network.Node.Me, ID: res.ID, Body: resBody, } return responseMessage } // Creates a simple store_data RPC response to confirm that the data has been stored on the node func (network *Network) CreateStoreResponse(res Response) Response { //Stores data in the node and set the expiration time (TTL) network.Node.storeData(res.Body.Data) responseMessage := Response{ RPC: "store_data", SendingContact: &network.Node.Me, ID: res.ID, } return responseMessage }
labCode/networkResponse.go
0.733165
0.433921
networkResponse.go
starcoder
package condition import ( "fmt" "github.com/Jeffail/benthos/v3/internal/bloblang/mapping" "github.com/Jeffail/benthos/v3/internal/bloblang/parser" "github.com/Jeffail/benthos/v3/internal/bloblang/query" "github.com/Jeffail/benthos/v3/internal/interop" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeBloblang] = TypeSpec{ constructor: NewBloblang, Summary: ` Executes a [Bloblang](/docs/guides/bloblang/about) query on messages, expecting a boolean result. If the result of the query is true then the condition passes, otherwise it does not.`, Footnotes: ` ## Examples With the following config: ` + "``` yaml" + ` bloblang: a == "foo" ` + "```" + ` A message ` + "`" + `{"a":"foo"}` + "`" + ` would pass, but ` + "`" + `{"a":"bar"}` + "`" + ` would not.`, } } //------------------------------------------------------------------------------ // BloblangConfig is a configuration struct containing fields for the bloblang // condition. type BloblangConfig string // NewBloblangConfig returns a BloblangConfig with default values. func NewBloblangConfig() BloblangConfig { return "" } //------------------------------------------------------------------------------ // Bloblang is a condition that checks message against a Bloblang query. type Bloblang struct { fn *mapping.Executor log log.Modular mCount metrics.StatCounter mTrue metrics.StatCounter mFalse metrics.StatCounter mErr metrics.StatCounter } // NewBloblang returns a Bloblang condition. func NewBloblang( conf Config, mgr types.Manager, log log.Modular, stats metrics.Type, ) (Type, error) { fn, err := interop.NewBloblangMapping(mgr, string(conf.Bloblang)) if err != nil { if perr, ok := err.(*parser.Error); ok { return nil, fmt.Errorf("%v", perr.ErrorAtPosition([]rune(conf.Bloblang))) } return nil, err } return &Bloblang{ fn: fn, log: log, mCount: stats.GetCounter("count"), mTrue: stats.GetCounter("true"), mFalse: stats.GetCounter("false"), mErr: stats.GetCounter("error"), }, nil } //------------------------------------------------------------------------------ // Check attempts to check a message part against a configured condition. func (c *Bloblang) Check(msg types.Message) bool { c.mCount.Incr(1) var valuePtr *interface{} var parseErr error lazyValue := func() *interface{} { if valuePtr == nil && parseErr == nil { if jObj, err := msg.Get(0).JSON(); err == nil { valuePtr = &jObj } else { parseErr = err } } return valuePtr } result, err := c.fn.Exec(query.FunctionContext{ Maps: map[string]query.Function{}, Vars: map[string]interface{}{}, MsgBatch: msg, }.WithValueFunc(lazyValue)) if err != nil { c.log.Errorf("Failed to check query: %v\n", err) c.mErr.Incr(1) c.mFalse.Incr(1) return false } resultBool, _ := result.(bool) if resultBool { c.mTrue.Incr(1) } else { c.mFalse.Incr(1) } return resultBool } //------------------------------------------------------------------------------
lib/condition/bloblang.go
0.766075
0.672338
bloblang.go
starcoder
package command import ( "strings" "awesome-dragon.science/go/goGoGameBot/internal/interfaces" ) // Data represents all the data available for a command call type Data struct { FromTerminal bool Args []string OriginalArgs string Source string Target string Manager *Manager util DataUtil } // DataUtil provides methods for Data to use when returning messages or checking admin levels type DataUtil interface { interfaces.AdminLeveller interfaces.Messager } const notAllowed = "You are not permitted to use this command" // CheckPerms verifies that the admin level of the source user is at or above the requiredLevel func (d *Data) CheckPerms(requiredLevel int) bool { if d.FromTerminal || d.util.AdminLevel(d.Source) >= requiredLevel { return true } d.ReturnNotice(notAllowed) return false } // SendNotice sends an IRC notice to the given target with the given message func (d *Data) SendNotice(target, msg string) { d.util.SendNotice(target, msg) } // SendTargetNotice is a shortcut to SendNotice that sets the target of the notice to the target of the Data object func (d *Data) SendTargetNotice(msg string) { d.SendNotice(d.Target, msg) } // SendSourceNotice is a shortcut to SendNotice that sets the target of the notice to the nick of the source of the data // object func (d *Data) SendSourceNotice(msg string) { d.SendNotice(d.Source, msg) } // SendMessage sends an IRC privmsg to the given target func (d *Data) SendMessage(target, msg string) { d.util.SendMessage(target, msg) } // SendTargetMessage is a shortcut to SendMessage that sets the target for the privmsg to the target of the Data object func (d *Data) SendTargetMessage(msg string) { d.SendMessage(d.Target, msg) } // SendSourceMessage is a shortcut to SendMessage that sets the target for the privmsg to the nick of the source on the // data object func (d *Data) SendSourceMessage(msg string) { d.SendMessage(d.Source, msg) } // ReturnNotice either sends a notice to the caller of a command func (d *Data) ReturnNotice(msg string) { d.SendSourceNotice(msg) } // ReturnMessage either sends a notice to the caller of a command func (d *Data) ReturnMessage(msg string) { d.SendTargetMessage(msg) } // String implements the stringer interface func (d *Data) String() string { return strings.Join(d.Args, " ") }
internal/command/data.go
0.716219
0.408159
data.go
starcoder
package iso20022 // Specifies corporate action dates. type CorporateActionDate2 struct { // Date on which positions are struck at the end of the day to note which parties will receive the relevant amount of entitlement, due to be distributed on payment date. RecordDate *DateFormat4Choice `xml:"RcrdDt,omitempty"` // Date on which a process is to be completed or becomes effective. EffectiveDate *DateFormat4Choice `xml:"FctvDt,omitempty"` // Last day a holder can deliver the securities that it had previously protected. CoverExpirationDate *DateFormat4Choice `xml:"CoverXprtnDt,omitempty"` // Date on which all or part of any holding bought in a unit trust is subject to being treated as capital rather than income. This is normally one day after the previous distribution's ex date. EqualisationDate *DateFormat4Choice `xml:"EqulstnDt,omitempty"` // Date/time at which the margin rate will be determined . MarginFixingDate *DateFormat4Choice `xml:"MrgnFxgDt,omitempty"` // Date on which the lottery is run and applied to the holder's positions. This is also applicable to partial calls. LotteryDate *DateFormat4Choice `xml:"LtryDt,omitempty"` // Last date a holder can request to defer delivery of securities pursuant to a notice of guaranteed delivery or other required documentation. ProtectDate *DateFormat4Choice `xml:"PrtctDt,omitempty"` // Date upon which the terms of the take-over become unconditional as to acceptances. UnconditionalDate *DateFormat4Choice `xml:"UcondlDt,omitempty"` // Date on which all conditions, including regulatory, legal etc. pertaining to the take-over, have been met. WhollyUnconditionalDate *DateFormat4Choice `xml:"WhlyUcondlDt,omitempty"` // Date on which results are published, eg, results of an offer. ResultsPublicationDate *DateFormat4Choice `xml:"RsltsPblctnDt,omitempty"` // Date/time upon which the High Court provided approval. CourtApprovalDate *DateFormat4Choice `xml:"CrtApprvlDt,omitempty"` // First possible early closing date of an offer if different from the expiry date. EarlyClosingDate *DateFormat4Choice `xml:"EarlyClsgDt,omitempty"` // Date/time as from which trading (including exchange and OTC trading) occurs on the underlying security without the benefit. ExDividendDate *DateFormat4Choice `xml:"ExDvddDt,omitempty"` // Date/time at which an index rate will be determined . IndexFixingDate *DateFormat4Choice `xml:"IndxFxgDt,omitempty"` // Date on which an interest bearing financial instrument becomes due and principal is repaid by the issuer to the investor. MaturityDate *DateFormat4Choice `xml:"MtrtyDt,omitempty"` // Date on which trading of a security is suspended as the result of an event. TradingSuspendedDate *DateFormat4Choice `xml:"TradgSspdDt,omitempty"` // Deadline by which the beneficial ownership of securities must be declared. CertificationDeadline *DateFormat4Choice `xml:"CertfctnDdln,omitempty"` // Date/time at which the securities will be redeemed (early) for payment of principal. RedemptionDate *DateFormat4Choice `xml:"RedDt,omitempty"` // Date on which instructions to register or registration details will be accepted. RegistrationDeadline *DateFormat4Choice `xml:"RegnDdln,omitempty"` // Date (and time) at which an issuer will determine the proration amount/quantity of an offer. ProrationDate *DateFormat4Choice `xml:"PrratnDt,omitempty"` // Date on until which tax breakdown instructions will be accepted. DeadlineForTaxBreakdownInstruction *DateFormat4Choice `xml:"DdlnForTaxBrkdwnInstr,omitempty"` // Date/time at which an event/offer is terminated or lapsed. LapsedDate *DateFormat4Choice `xml:"LpsdDt,omitempty"` // Last date/time by which a buying counterparty to a trade can be sure that it will have the right to participate in an event. GuaranteedParticipationDate *DateFormat4Choice `xml:"GrntedPrtcptnDt,omitempty"` // Deadline by which an entitled holder needs to advise their counterparty to a transaction of their election for a corporate action event. ElectionToCounterpartyDeadline *DateFormat4Choice `xml:"ElctnToCtrPtyDdln,omitempty"` // Date/time as from which 'special processing' can start to be used by participants for that event. Special processing is a means of marking a transaction, that would normally be traded ex or cum, as being traded cum or ex respectively, eg, a transaction dealt 'special' after the ex date would result in the buyer being eligible for the entitlement. This is typically used in the UK and Irish markets. SpecialExDate *DateFormat4Choice `xml:"SpclExDt,omitempty"` } func (c *CorporateActionDate2) AddRecordDate() *DateFormat4Choice { c.RecordDate = new(DateFormat4Choice) return c.RecordDate } func (c *CorporateActionDate2) AddEffectiveDate() *DateFormat4Choice { c.EffectiveDate = new(DateFormat4Choice) return c.EffectiveDate } func (c *CorporateActionDate2) AddCoverExpirationDate() *DateFormat4Choice { c.CoverExpirationDate = new(DateFormat4Choice) return c.CoverExpirationDate } func (c *CorporateActionDate2) AddEqualisationDate() *DateFormat4Choice { c.EqualisationDate = new(DateFormat4Choice) return c.EqualisationDate } func (c *CorporateActionDate2) AddMarginFixingDate() *DateFormat4Choice { c.MarginFixingDate = new(DateFormat4Choice) return c.MarginFixingDate } func (c *CorporateActionDate2) AddLotteryDate() *DateFormat4Choice { c.LotteryDate = new(DateFormat4Choice) return c.LotteryDate } func (c *CorporateActionDate2) AddProtectDate() *DateFormat4Choice { c.ProtectDate = new(DateFormat4Choice) return c.ProtectDate } func (c *CorporateActionDate2) AddUnconditionalDate() *DateFormat4Choice { c.UnconditionalDate = new(DateFormat4Choice) return c.UnconditionalDate } func (c *CorporateActionDate2) AddWhollyUnconditionalDate() *DateFormat4Choice { c.WhollyUnconditionalDate = new(DateFormat4Choice) return c.WhollyUnconditionalDate } func (c *CorporateActionDate2) AddResultsPublicationDate() *DateFormat4Choice { c.ResultsPublicationDate = new(DateFormat4Choice) return c.ResultsPublicationDate } func (c *CorporateActionDate2) AddCourtApprovalDate() *DateFormat4Choice { c.CourtApprovalDate = new(DateFormat4Choice) return c.CourtApprovalDate } func (c *CorporateActionDate2) AddEarlyClosingDate() *DateFormat4Choice { c.EarlyClosingDate = new(DateFormat4Choice) return c.EarlyClosingDate } func (c *CorporateActionDate2) AddExDividendDate() *DateFormat4Choice { c.ExDividendDate = new(DateFormat4Choice) return c.ExDividendDate } func (c *CorporateActionDate2) AddIndexFixingDate() *DateFormat4Choice { c.IndexFixingDate = new(DateFormat4Choice) return c.IndexFixingDate } func (c *CorporateActionDate2) AddMaturityDate() *DateFormat4Choice { c.MaturityDate = new(DateFormat4Choice) return c.MaturityDate } func (c *CorporateActionDate2) AddTradingSuspendedDate() *DateFormat4Choice { c.TradingSuspendedDate = new(DateFormat4Choice) return c.TradingSuspendedDate } func (c *CorporateActionDate2) AddCertificationDeadline() *DateFormat4Choice { c.CertificationDeadline = new(DateFormat4Choice) return c.CertificationDeadline } func (c *CorporateActionDate2) AddRedemptionDate() *DateFormat4Choice { c.RedemptionDate = new(DateFormat4Choice) return c.RedemptionDate } func (c *CorporateActionDate2) AddRegistrationDeadline() *DateFormat4Choice { c.RegistrationDeadline = new(DateFormat4Choice) return c.RegistrationDeadline } func (c *CorporateActionDate2) AddProrationDate() *DateFormat4Choice { c.ProrationDate = new(DateFormat4Choice) return c.ProrationDate } func (c *CorporateActionDate2) AddDeadlineForTaxBreakdownInstruction() *DateFormat4Choice { c.DeadlineForTaxBreakdownInstruction = new(DateFormat4Choice) return c.DeadlineForTaxBreakdownInstruction } func (c *CorporateActionDate2) AddLapsedDate() *DateFormat4Choice { c.LapsedDate = new(DateFormat4Choice) return c.LapsedDate } func (c *CorporateActionDate2) AddGuaranteedParticipationDate() *DateFormat4Choice { c.GuaranteedParticipationDate = new(DateFormat4Choice) return c.GuaranteedParticipationDate } func (c *CorporateActionDate2) AddElectionToCounterpartyDeadline() *DateFormat4Choice { c.ElectionToCounterpartyDeadline = new(DateFormat4Choice) return c.ElectionToCounterpartyDeadline } func (c *CorporateActionDate2) AddSpecialExDate() *DateFormat4Choice { c.SpecialExDate = new(DateFormat4Choice) return c.SpecialExDate }
CorporateActionDate2.go
0.791459
0.594669
CorporateActionDate2.go
starcoder
package app // Window is the interface that describes a window. type Window interface { Navigator Closer // Position returns the window position. Position() (x, y float64) // Move moves the window to the position (x, y). Move(x, y float64) // Center moves the window to the center of the screen. Center() // Size returns the window size. Size() (width, height float64) // Resize resizes the window to width * height. Resize(width, height float64) // Focus gives the focus to the window. // The window will be put in front, above the other elements. Focus() // FullScreen takes the window into fullscreen mode. FullScreen() // ExitFullScreen takes the window out of fullscreen mode. ExitFullScreen() // Minimize takes the window into minimized mode Minimize() // Deminimize takes the window out of minimized mode Deminimize() } // WindowConfig is a struct that describes a window. type WindowConfig struct { // The title. Title string // The default position on x axis. X float64 // The default position on y axis. Y float64 // The default width. Width float64 // The minimum width. MinWidth float64 // The maximum width. MaxWidth float64 // The default height. Height float64 // The minimum height. MinHeight float64 // The maximum height. MaxHeight float64 // The background color (#rrggbb). BackgroundColor string // Reports whether the window is resizable. FixedSize bool // Reports whether the close button is hidden. CloseHidden bool // Reports whether the minimize button is hidden. MinimizeHidden bool // Reports whether the title bar is hidden. TitlebarHidden bool // The URL of the component to load when the window is created. URL string // The MacOS window specific configuration. Mac MacWindowConfig // The function that is called when the window is moved. OnMove func(x, y float64) `json:"-"` // The function that is called when the window is resized. OnResize func(width float64, height float64) `json:"-"` // The function that is called when the window get focus. OnFocus func() `json:"-"` // The function that is called when the window lose focus. OnBlur func() `json:"-"` // The function that is called when the window goes full screen. OnFullScreen func() `json:"-"` // The function that is called when the window exit full screen. OnExitFullScreen func() `json:"-"` // The function that is called when the window is minimized. OnMinimize func() `json:"-"` // The function that is called when the window is deminimized. OnDeminimize func() `json:"-"` // The function that is called when the window is closed. // Returning bool prevents the window to be closed. OnClose func() bool `json:"-"` } // MacWindowConfig is a struct that describes window fields specific to MacOS. type MacWindowConfig struct { BackgroundVibrancy Vibrancy } // Vibrancy represents a constant that define Apple's frost glass effects. type Vibrancy uint8 // Constants to specify vibrancy effects to use in Apple application elements. const ( VibeNone Vibrancy = iota VibeLight VibeDark VibeTitlebar VibeSelection VibeMenu VibePopover VibeSidebar VibeMediumLight VibeUltraDark )
window.go
0.817574
0.41941
window.go
starcoder
package draw import ( "image" ) // String draws the string in the specified font, placing the upper left corner at p. // It draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) String(pt image.Point, src *Image, sp image.Point, f *Font, s string) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, s, nil, nil, dst.Clipr, nil, image.ZP, SoverD) } // StringOp draws the string in the specified font, placing the upper left corner at p. // It draws the text using src, with sp aligned to pt, using the specified operation onto dst. func (dst *Image) StringOp(pt image.Point, src *Image, sp image.Point, f *Font, s string, op Op) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, s, nil, nil, dst.Clipr, nil, image.ZP, op) } // StringBg draws the string in the specified font, placing the upper left corner at p. // It first draws the background bg, with bgp aligned to pt, using operation SoverD onto dst. // It then draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) StringBg(pt image.Point, src *Image, sp image.Point, f *Font, s string, bg *Image, bgp image.Point) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, s, nil, nil, dst.Clipr, bg, bgp, SoverD) } // StringBgOp draws the string in the specified font, placing the upper left corner at p. // It first draws the background bg, with bgp aligned to pt, using operation SoverD onto dst. // It then draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) StringBgOp(pt image.Point, src *Image, sp image.Point, f *Font, s string, bg *Image, bgp image.Point, op Op) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, s, nil, nil, dst.Clipr, bg, bgp, op) } // Runes draws the rune slice in the specified font, placing the upper left corner at p. // It draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) Runes(pt image.Point, src *Image, sp image.Point, f *Font, r []rune) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", nil, r, dst.Clipr, nil, image.ZP, SoverD) } // RunesOp draws the rune slice in the specified font, placing the upper left corner at p. // It draws the text using src, with sp aligned to pt, using the specified operation onto dst. func (dst *Image) RunesOp(pt image.Point, src *Image, sp image.Point, f *Font, r []rune, op Op) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", nil, r, dst.Clipr, nil, image.ZP, op) } // RunesBg draws the rune slice in the specified font, placing the upper left corner at p. // It first draws the background bg, with bgp aligned to pt, using operation SoverD onto dst. // It then draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) RunesBg(pt image.Point, src *Image, sp image.Point, f *Font, r []rune, bg *Image, bgp image.Point) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", nil, r, dst.Clipr, bg, bgp, SoverD) } // RunesBgOp draws the rune slice in the specified font, placing the upper left corner at p. // It first draws the background bg, with bgp aligned to pt, using operation SoverD onto dst. // It then draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) RunesBgOp(pt image.Point, src *Image, sp image.Point, f *Font, r []rune, bg *Image, bgp image.Point, op Op) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", nil, r, dst.Clipr, bg, bgp, op) } // Bytes draws the byte slice in the specified font, placing the upper left corner at p. // It draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) Bytes(pt image.Point, src *Image, sp image.Point, f *Font, b []byte) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", b, nil, dst.Clipr, nil, image.ZP, SoverD) } // BytesOp draws the byte slice in the specified font, placing the upper left corner at p. // It draws the text using src, with sp aligned to pt, using the specified operation onto dst. func (dst *Image) BytesOp(pt image.Point, src *Image, sp image.Point, f *Font, b []byte, op Op) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", b, nil, dst.Clipr, nil, image.ZP, op) } // BytesBg draws the rune slice in the specified font, placing the upper left corner at p. // It first draws the background bg, with bgp aligned to pt, using operation SoverD onto dst. // It then draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) BytesBg(pt image.Point, src *Image, sp image.Point, f *Font, b []byte, bg *Image, bgp image.Point) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", b, nil, dst.Clipr, bg, bgp, SoverD) } // BytesBgOp draws the rune slice in the specified font, placing the upper left corner at p. // It first draws the background bg, with bgp aligned to pt, using operation SoverD onto dst. // It then draws the text using src, with sp aligned to pt, using operation SoverD onto dst. func (dst *Image) BytesBgOp(pt image.Point, src *Image, sp image.Point, f *Font, b []byte, bg *Image, bgp image.Point, op Op) image.Point { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() return _string(dst, pt, src, sp, f, "", b, nil, dst.Clipr, bg, bgp, op) } func _string(dst *Image, pt image.Point, src *Image, sp image.Point, f *Font, s string, b []byte, r []rune, clipr image.Rectangle, bg *Image, bgp image.Point, op Op) image.Point { var in input in.init(s, b, r) const Max = 100 cbuf := make([]uint16, Max) var sf *Subfont for !in.done { max := Max n, wid, subfontname := cachechars(f, &in, cbuf, max) if n > 0 { setdrawop(dst.Display, op) m := 47 + 2*n if bg != nil { m += 4 + 2*4 } b := dst.Display.bufimage(m) if bg != nil { b[0] = 'x' } else { b[0] = 's' } bplong(b[1:], uint32(dst.id)) bplong(b[5:], uint32(src.id)) bplong(b[9:], uint32(f.cacheimage.id)) bplong(b[13:], uint32(pt.X)) bplong(b[17:], uint32(pt.Y+f.Ascent)) bplong(b[21:], uint32(clipr.Min.X)) bplong(b[25:], uint32(clipr.Min.Y)) bplong(b[29:], uint32(clipr.Max.X)) bplong(b[33:], uint32(clipr.Max.Y)) bplong(b[37:], uint32(sp.X)) bplong(b[41:], uint32(sp.Y)) bpshort(b[45:], uint16(n)) b = b[47:] if bg != nil { bplong(b, uint32(bg.id)) bplong(b[4:], uint32(bgp.X)) bplong(b[8:], uint32(bgp.Y)) b = b[12:] } for i, c := range cbuf[:n] { bpshort(b[2*i:], c) } pt.X += wid bgp.X += wid agefont(f) } if subfontname != "" { sf.free() var err error sf, err = getsubfont(f.Display, subfontname) if err != nil { if f.Display != nil && f != f.Display.DefaultFont { f = f.Display.DefaultFont continue } break } /* * must not free sf until cachechars has found it in the cache * and picked up its own reference. */ } } return pt }
vendor/9fans.net/go/draw/string.go
0.833663
0.638723
string.go
starcoder
package evaluator func (e *Evaluator) snapStartOfSecond() { e.current = BeginningOfSecond(e.current) } func (e *Evaluator) snapStartOfMinute() { e.current = BeginningOfMinute(e.current) } func (e *Evaluator) snapStartOfHour() { e.current = BeginningOfHour(e.current) } func (e *Evaluator) snapStartOfDay() { e.current = BeginningOfDay(e.current) } func (e *Evaluator) snapStartOfWeek() { e.current = BeginningOfWeek(e.current, e.weekStartDay) } func (e *Evaluator) snapStartOfBusinessWeek() { e.snapStartOfWeek() } func (e *Evaluator) snapStartOfMonth() { e.current = BeginningOfMonth(e.current) } func (e *Evaluator) snapStartOfYear() { e.current = BeginningOfYear(e.current) } func (e *Evaluator) snapStartOfCurrentQuarter() { e.current = BeginningOfCurrentQuarter(e.current) } func (e *Evaluator) snapStartOfQuarter(q int) { e.current = BeginningOfQuarter(e.current, q) } func (e *Evaluator) snapEndOfCurrentQuarter() { e.current = EndOfCurrentQuarter(e.current) } func (e *Evaluator) snapEndOfQuarter(q int) { e.current = EndOfQuarter(e.current, q) } func (e *Evaluator) snapEndOfMinute() { e.current = EndOfMinute(e.current) } func (e *Evaluator) snapEndOfHour() { e.current = EndOfHour(e.current) } func (e *Evaluator) snapEndOfDay() { e.current = EndOfDay(e.current) } func (e *Evaluator) snapEndOfWeek() { e.current = EndOfWeek(e.current, e.weekStartDay) } func (e *Evaluator) snapEndOfBusinessWeek() { e.current = EndOfBusinessWeek(e.current, e.weekStartDay) } func (e *Evaluator) snapEndOfMonth() { e.current = EndOfMonth(e.current) } func (e *Evaluator) snapEndOfYear() { e.current = EndOfYear(e.current) } func (e *Evaluator) addSeconds(amount int) { e.current = AddSeconds(e.current, amount) } func (e *Evaluator) addMinutes(amount int) { e.current = AddMinutes(e.current, amount) } func (e *Evaluator) addHours(amount int) { e.current = AddHours(e.current, amount) } func (e *Evaluator) addDays(amount int) { e.current = AddDays(e.current, amount) } func (e *Evaluator) addWeeks(amount int) { e.current = AddWeeks(e.current, amount) } func (e *Evaluator) addMonths(amount int) { e.current = AddMonths(e.current, amount) } func (e *Evaluator) addYears(amount int) { e.current = AddYears(e.current, amount) } func (e *Evaluator) previousMonday() { e.current = PreviousMonday(e.current) } func (e *Evaluator) previousTuesday() { e.current = PreviousTuesday(e.current) } func (e *Evaluator) previousWednesday() { e.current = PreviousWednesday(e.current) } func (e *Evaluator) previousThursday() { e.current = PreviousThursday(e.current) } func (e *Evaluator) previousFriday() { e.current = PreviousFriday(e.current) } func (e *Evaluator) previousSaturday() { e.current = PreviousSaturday(e.current) } func (e *Evaluator) previousSunday() { e.current = PreviousSunday(e.current) } func (e *Evaluator) nextMonday() { e.current = NextMonday(e.current) } func (e *Evaluator) nextTuesday() { e.current = NextTuesday(e.current) } func (e *Evaluator) nextWednesday() { e.current = NextWednesday(e.current) } func (e *Evaluator) nextThursday() { e.current = NextThursday(e.current) } func (e *Evaluator) nextFriday() { e.current = NextFriday(e.current) } func (e *Evaluator) nextSaturday() { e.current = NextSaturday(e.current) } func (e *Evaluator) nextSunday() { e.current = NextSunday(e.current) }
evaluator/evaluator_dates.go
0.624408
0.592873
evaluator_dates.go
starcoder
package carbon import ( "bytes" "strconv" "strings" ) // ToTimestamp outputs a timestamp with second(will be removed from v2.0, only keep Timestamp). // 输出秒级时间戳(将在v2.0版本移除,只保留 Timestamp) func (c Carbon) ToTimestamp() int64 { if c.IsInvalid() { return 0 } return c.Timestamp() } // ToTimestampWithSecond outputs a timestamp with second(will be removed from v2.0, only keep TimestampWithSecond). // 输出秒级时间戳(将在v2.0版本移除,只保留 TimestampWithSecond) func (c Carbon) ToTimestampWithSecond() int64 { if c.IsInvalid() { return 0 } return c.TimestampWithSecond() } // ToTimestampWithMillisecond outputs a timestamp with millisecond(will be removed from v2.0, only keep TimestampWithMillisecond). // 输出毫秒级时间戳(将在v2.0版本移除,只保留 TimestampWithMillisecond) func (c Carbon) ToTimestampWithMillisecond() int64 { if c.IsInvalid() { return 0 } return c.TimestampWithMillisecond() } // ToTimestampWithMicrosecond outputs a timestamp with microsecond(will be removed from v2.0, only keep TimestampWithMicrosecond). // 输出微秒级时间戳(将在v2.0版本移除,只保留 TimestampWithMicrosecond) func (c Carbon) ToTimestampWithMicrosecond() int64 { if c.IsInvalid() { return 0 } return c.TimestampWithMicrosecond() } // ToTimestampWithNanosecond outputs a timestamp with nanosecond(will be removed from v2.0, only keep TimestampWithNanosecond). // 输出纳秒级时间戳(将在v2.0版本移除,只保留 TimestampWithNanosecond) func (c Carbon) ToTimestampWithNanosecond() int64 { if c.IsInvalid() { return 0 } return c.TimestampWithNanosecond() } // String outputs a string in date and time format, implement Stringer interface. // 实现 Stringer 接口 func (c Carbon) String() string { if c.IsInvalid() { return "" } return c.ToDateTimeString() } // ToString outputs a string in "2006-01-02 15:04:05.999999999 -0700 MST" format. // 输出"2006-01-02 15:04:05.999999999 -0700 MST"格式字符串 func (c Carbon) ToString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).String() } // ToMonthString outputs a string in month format, i18n is supported. // 输出完整月份字符串,支持i18n func (c Carbon) ToMonthString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } if len(c.lang.resources) == 0 { c.lang.SetLocale(defaultLocale) } if months, ok := c.lang.resources["months"]; ok { slice := strings.Split(months, "|") if len(slice) == 12 { return slice[c.Month()-1] } } return "" } // ToShortMonthString outputs a string in short month format, i18n is supported. // 输出缩写月份字符串,支持i18n func (c Carbon) ToShortMonthString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } if len(c.lang.resources) == 0 { c.lang.SetLocale(defaultLocale) } if months, ok := c.lang.resources["short_months"]; ok { slice := strings.Split(months, "|") if len(slice) == 12 { return slice[c.Month()-1] } } return "" } // ToWeekString outputs a string in week format, i18n is supported. // 输出完整星期字符串,支持i18n func (c Carbon) ToWeekString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } if len(c.lang.resources) == 0 { c.lang.SetLocale(defaultLocale) } if months, ok := c.lang.resources["weeks"]; ok { slice := strings.Split(months, "|") if len(slice) == 7 { return slice[c.Week()] } } return "" } // ToShortWeekString outputs a string in short week format, i18n is supported. // 输出缩写星期字符串,支持i18n func (c Carbon) ToShortWeekString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } if len(c.lang.resources) == 0 { c.lang.SetLocale(defaultLocale) } if months, ok := c.lang.resources["short_weeks"]; ok { slice := strings.Split(months, "|") if len(slice) == 7 { return slice[c.Week()] } } return "" } // ToDayDateTimeString outputs a string in day, date and time format. // 输出天数日期时间字符串 func (c Carbon) ToDayDateTimeString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(DayDateTimeFormat) } // ToDateTimeString outputs a string in date and time format. // 输出日期时间字符串 func (c Carbon) ToDateTimeString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(DateTimeFormat) } // ToShortDateTimeString outputs a string in short date and time format. // 输出简写日期时间字符串 func (c Carbon) ToShortDateTimeString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(ShortDateTimeFormat) } // ToDateString outputs a string in date format. // 输出日期字符串 func (c Carbon) ToDateString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(DateFormat) } // ToShortDateString outputs a string in short date format. // 输出简写日期字符串 func (c Carbon) ToShortDateString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(ShortDateFormat) } // ToTimeString outputs a string in time format. // 输出时间字符串 func (c Carbon) ToTimeString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(TimeFormat) } // ToShortTimeString outputs a string in short time format. // 输出简写时间字符串 func (c Carbon) ToShortTimeString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(ShortTimeFormat) } // ToAtomString outputs a string in ATOM format. // 输出 ATOM 格式字符串 func (c Carbon) ToAtomString(timezone ...string) string { if c.IsInvalid() { return "" } return c.ToRfc3339String(timezone...) } // ToAnsicString outputs a string in ANSIC format. // 输出 ANSIC 格式字符串 func (c Carbon) ToAnsicString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(AnsicFormat) } // ToCookieString outputs a string in COOKIE format. // 输出 COOKIE 格式字符串 func (c Carbon) ToCookieString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(CookieFormat) } // ToRssString outputs a string in RSS format. // 输出 RSS 格式字符串 func (c Carbon) ToRssString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RssFormat) } // ToW3cString outputs a string in W3C format. // 输出 W3C 格式字符串 func (c Carbon) ToW3cString(timezone ...string) string { if c.IsInvalid() { return "" } return c.ToRfc3339String(timezone...) } // ToUnixDateString outputs a string in unix date format. // 输出 UnixDate 格式字符串 func (c Carbon) ToUnixDateString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(UnixDateFormat) } // ToRubyDateString outputs a string in ruby date format. // 输出 RubyDate 格式字符串 func (c Carbon) ToRubyDateString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RubyDateFormat) } // ToKitchenString outputs a string in KITCHEN format. // 输出 KITCHEN 格式字符串 func (c Carbon) ToKitchenString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(KitchenFormat) } // ToIso8601String outputs a string in ISO8601 format. // 输出 ISO8601 格式字符串 func (c Carbon) ToIso8601String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(Iso8601Format) } // ToRfc822String outputs a string in RFC822 format. // 输出 RFC822 格式字符串 func (c Carbon) ToRfc822String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC822Format) } // ToRfc822zString outputs a string in RFC822Z format. // 输出 RFC822Z 格式字符串 func (c Carbon) ToRfc822zString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC822ZFormat) } // ToRfc850String outputs a string in RFC850 format. // 输出 RFC850 格式字符串 func (c Carbon) ToRfc850String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC850Format) } // ToRfc1036String outputs a string in RFC1036 format. // 输出 RFC1036 格式字符串 func (c Carbon) ToRfc1036String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC1036Format) } // ToRfc1123String outputs a string in RFC1123 format. // 输出 RFC1123 格式字符串 func (c Carbon) ToRfc1123String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC1123Format) } // ToRfc1123zString outputs a string in RFC1123z format. // 输出 RFC1123z 格式字符串 func (c Carbon) ToRfc1123zString(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC1123ZFormat) } // ToRfc2822String outputs a string in RFC2822 format. // 输出 RFC2822 格式字符串 func (c Carbon) ToRfc2822String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC2822Format) } // ToRfc3339String outputs a string in RFC3339 format. // 输出 RFC3339 格式字符串 func (c Carbon) ToRfc3339String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC3339Format) } // ToRfc7231String outputs a string in RFC7231 format. // 输出 RFC7231 格式字符串 func (c Carbon) ToRfc7231String(timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(RFC7231Format) } // ToLayoutString outputs a string by layout. // 输出指定布局的时间字符串 func (c Carbon) ToLayoutString(layout string, timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } return c.Time.In(c.loc).Format(layout) } // Layout outputs a string by layout, it is short for ToLayoutString. // 输出指定布局的时间字符串, 是 ToLayoutString 的简写 func (c Carbon) Layout(layout string, timezone ...string) string { if c.IsInvalid() { return "" } return c.ToLayoutString(layout, timezone...) } // ToFormatString outputs a string by format. // 输出指定格式的时间字符串 func (c Carbon) ToFormatString(format string, timezone ...string) string { if len(timezone) > 0 { c.loc, c.Error = getLocationByTimezone(timezone[len(timezone)-1]) } if c.IsInvalid() { return "" } buffer := bytes.NewBuffer(nil) for i := 0; i < len(format); i++ { if layout, ok := formats[byte(format[i])]; ok { buffer.WriteString(c.Time.In(c.loc).Format(layout)) } else { switch format[i] { case '\\': // 原样输出,不解析 buffer.WriteByte(format[i+1]) i++ continue case 'W': // ISO-8601 格式数字表示的年份中的第几周,取值范围 1-52 buffer.WriteString(strconv.Itoa(c.WeekOfYear())) case 'N': // ISO-8601 格式数字表示的星期中的第几天,取值范围 1-7 buffer.WriteString(strconv.Itoa(c.DayOfWeek())) case 'S': // 月份中第几天的英文缩写后缀,如st, nd, rd, th suffix := "th" switch c.Day() { case 1, 21, 31: suffix = "st" case 2, 22: suffix = "nd" case 3, 23: suffix = "rd" } buffer.WriteString(suffix) case 'L': // 是否为闰年,如果是闰年为 1,否则为 0 if c.IsLeapYear() { buffer.WriteString("1") } else { buffer.WriteString("0") } case 'G': // 数字表示的小时,24 小时格式,没有前导零,取值范围 0-23 buffer.WriteString(strconv.Itoa(c.Hour())) case 'U': // 秒级时间戳,如 1611818268 buffer.WriteString(strconv.FormatInt(c.Timestamp(), 10)) case 'u': // 数字表示的毫秒,如 999 buffer.WriteString(strconv.Itoa(c.Millisecond())) case 'w': // 数字表示的星期中的第几天,取值范围 0-6 buffer.WriteString(strconv.Itoa(c.DayOfWeek() - 1)) case 't': // 指定的月份有几天,取值范围 28-31 buffer.WriteString(strconv.Itoa(c.DaysInMonth())) case 'z': // 年份中的第几天,取值范围 0-365 buffer.WriteString(strconv.Itoa(c.DayOfYear() - 1)) case 'e': // 当前位置,如 UTC,GMT,Atlantic/Azores buffer.WriteString(c.Location()) case 'Q': // 当前季度,取值范围 1-4 buffer.WriteString(strconv.Itoa(c.Quarter())) case 'C': // 当前世纪数,取值范围 0-99 buffer.WriteString(strconv.Itoa(c.Century())) default: buffer.WriteByte(format[i]) } } } return buffer.String() } // Format outputs a string by format, it is short for ToFormatString. // 输出指定格式的时间字符串, 是 ToFormatString 的简写 func (c Carbon) Format(format string, timezone ...string) string { if c.IsInvalid() { return "" } return c.ToFormatString(format, timezone...) }
outputer.go
0.535827
0.434161
outputer.go
starcoder
// download contains a library for downloading data from logs. package download import ( "fmt" "time" backoff "github.com/cenkalti/backoff/v4" "github.com/golang/glog" ) // BatchFetch should be implemented to provide a mechanism to fetch a range of leaves. // Enough leaves should be fetched to fully fill `leaves`, or an error should be returned. type BatchFetch func(start uint64, leaves [][]byte) error // Bulk keeps downloading leaves starting from `first`, using the given leaf fetcher. // The number of workers and the batch size to use for each of the fetch requests are also specified. // The resulting leaves are returned in order over `leafChan`, and any terminal errors are returned via `errc`. // Internally this uses exponential backoff on the workers to download as fast as possible, but no faster. // TODO(mhutchinson): Pass in a context and check for termination so we can gracefully exit. func Bulk(first uint64, batchFetch BatchFetch, workers, batchSize uint, leafChan chan<- []byte, errc chan<- error) { // Each worker gets its own unbuffered channel to make sure it can only be at most one ahead. // This prevents lots of wasted work happening if one shard gets stuck. rangeChans := make([]chan leafRange, workers) increment := workers * batchSize for i := uint(0); i < workers; i++ { rangeChans[i] = make(chan leafRange) start := first + uint64(i*batchSize) go fetchWorker{ label: fmt.Sprintf("worker %d", i), start: start, count: batchSize, increment: uint64(increment), out: rangeChans[i], errc: errc, batchFetch: batchFetch, }.run() } // Perpetually round-robin through the sharded ranges. for i := 0; ; i = (i + 1) % int(workers) { r := <-rangeChans[i] for _, l := range r.leaves { leafChan <- l } } } type leafRange struct { start uint64 leaves [][]byte } type fetchWorker struct { label string start, increment uint64 count uint out chan<- leafRange errc chan<- error batchFetch BatchFetch } func (w fetchWorker) run() { // TODO(mhutchinson): Consider some way to reset this after intermittent connectivity issue. // If this is pushed in the loop then it fixes this issue, but at the cost that the worker // will never reach a stable rate if it is asked to back off. This is optimized for being // gentle to the logs, which is a reasonable default for a happy ecosystem. bo := backoff.NewExponentialBackOff() for { leaves := make([][]byte, w.count) var c leafRange operation := func() error { err := w.batchFetch(w.start, leaves) if err != nil { return fmt.Errorf("LeafFetcher.Batch(%d, %d): %w", w.start, w.count, err) } c = leafRange{ start: w.start, leaves: leaves, } return nil } err := backoff.RetryNotify(operation, bo, func(e error, _ time.Duration) { glog.V(1).Infof("%s: Retryable error getting data: %q", w.label, e) }) if err != nil { w.errc <- err } else { w.out <- c } w.start += w.increment } }
clone/internal/download/batch.go
0.563258
0.434761
batch.go
starcoder
package entity import ( "errors" "fmt" "regexp" "strconv" // "agenda/loghelper" ) // Date : class with y, m, d, h and m type Date struct { Year, Month, Day, Hour, Minute int } func (mDate Date) init(tYear, tMonth, tDay, tHour, tMinute int) { mDate.Year = tYear mDate.Month = tMonth mDate.Day = tDay mDate.Hour = tHour mDate.Minute = tMinute } // GetYear : getter of year func (mDate Date) GetYear() int { return mDate.Year } // SetYear : setter of year func (mDate Date) SetYear(tYear int) { mDate.Year = tYear } // GetMonth : getter of month func (mDate Date) GetMonth() int { return mDate.Month } // SetMonth : setter of month func (mDate Date) SetMonth(tMonth int) { mDate.Month = tMonth } // GetDay : getter of day func (mDate Date) GetDay() int { return mDate.Day } // SetDay : setter of day func (mDate Date) SetDay(tDay int) { mDate.Day = tDay } // GetHour : getter of Hour func (mDate Date) GetHour() int { return mDate.Hour } // SetHour : setter of Hour func (mDate Date) SetHour(tHour int) { mDate.Hour = tHour } // GetMinute : getter of minute func (mDate Date) GetMinute() int { return mDate.Minute } // SetMinute : setter of minute func (mDate Date) SetMinute(tMinute int) { mDate.Minute = tMinute } /** * @brief check whether the date is valid or not * @return the bool indicate valid or not */ func IsValid(tDate Date) bool { var dayOfMonths = [12]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} var currentYear = tDate.GetYear() var currentMonth = tDate.GetMonth() var currentDay = tDate.GetDay() //Check if date in normal range if currentYear < 1000 || currentYear > 9999 || currentMonth < 1 || currentMonth > 12 || currentDay < 1 || tDate.GetHour() < 0 || tDate.GetHour() >= 24 || tDate.GetMinute() < 0 || tDate.GetMinute() >= 60 { return false } if currentMonth != 2 && currentDay > dayOfMonths[currentMonth-1] { return false } else { //Check if leap year. if (currentYear%4 == 0 && currentYear%100 != 0) || (currentYear%400 == 0) { if currentDay > 29 { return false } } else { if currentDay > 28 { return false } } } return true } /** * @brief convert string to int */ func String2Int(s string) int { result, err := strconv.Atoi(s) if err != nil { fmt.Println(err) } return result } /** * @brief convert a string to date, if the format is not correct return * 0000-00-00/00:00 * @return a date */ func StringToDate(tDateString string) (Date, error) { var datePattern = `[\d]{4}-[\d]{2}-[\d]{2}\/[\d]{2}:[\d]{2}` var resultDate Date //Use regexp to check if parttern matched isValid, _ := regexp.Match(datePattern, []byte(tDateString)) if isValid != true { return resultDate, errors.New("Invalid string format") } resultDate.Year = String2Int(tDateString[0:4]) resultDate.Month = String2Int(tDateString[5:7]) resultDate.Day = String2Int(tDateString[8:10]) resultDate.Hour = String2Int(tDateString[11:13]) resultDate.Minute = String2Int(tDateString[14:]) return resultDate, nil } /** * @brief convert the date to string, if result length is 1, add padding 0 */ func Int2String(a int) string { var resultString string resultString = strconv.Itoa(a) return resultString } /** * @brief convert a date to string, if the format is not correct return * 0000-00-00/00:00 */ func DateToString(tDate Date) (string, error) { var dateString = "" var wString = "" var initTime = "0000-00-00/00:00" if !IsValid(tDate) { dateString = initTime return dateString, nil } // dateString = Int2String(tDate.GetYear()) + "-" + Int2String(tDate.GetMonth()) + // "-" + Int2String(tDate.GetDay()) + "/" + Int2String(tDate.GetHour()) + // ":" + Int2String(tDate.GetMinute()) dateStringWithZero := fmt.Sprintf("%04d", tDate.GetYear()) + "-" + fmt.Sprintf("%02d", tDate.GetMonth()) + "-" + fmt.Sprintf("%02d", tDate.GetDay()) + "/" + fmt.Sprintf("%02d", tDate.GetHour()) + ":" + fmt.Sprintf("%02d", tDate.GetMinute()) if dateStringWithZero != wString { return dateStringWithZero, nil } return dateStringWithZero, errors.New("wrong") } /** * @brief overload the assign operator */ func (mDate Date) CopyDate(tDate Date) Date { mDate.SetYear(tDate.GetYear()) mDate.SetMonth(tDate.GetMonth()) mDate.SetDay(tDate.GetDay()) mDate.SetHour(tDate.GetHour()) mDate.SetMinute(tDate.GetMinute()) return mDate } /** * @brief check whether the CurrentDate is equal to the tDate */ func (mDate Date) IsSameDate(tDate Date) bool { return (tDate.GetYear() == mDate.GetYear() && tDate.GetMonth() == mDate.GetMonth() && tDate.GetDay() == mDate.GetDay() && tDate.GetHour() == mDate.GetHour() && tDate.GetMinute() == mDate.GetMinute()) } /** * @brief check whether the CurrentDate is greater than the tDate */ func (mDate Date) MoreThan(tDate Date) bool { if mDate.Year > tDate.GetYear() { return true } if mDate.Year < tDate.GetYear() { return false } if mDate.Month > tDate.GetMonth() { return true } if mDate.Month < tDate.GetMonth() { return false } if mDate.Day > tDate.GetDay() { return true } if mDate.Day < tDate.GetDay() { return false } if mDate.Hour > tDate.GetHour() { return true } if mDate.Hour < tDate.GetHour() { return false } if mDate.Minute > tDate.GetMinute() { return true } if mDate.Minute < tDate.GetMinute() { return false } return false } // LessThan : ommited. func (mDate Date) LessThan(tDate Date) bool { if mDate.IsSameDate(tDate) == false && mDate.MoreThan(tDate) == false { return true } return false } /** * @brief check whether the CurrentDate is greater or equal than the * tDate */ func (mDate Date) GreateOrEqual(tDate Date) bool { return mDate.IsSameDate(tDate) || mDate.MoreThan(tDate) } /** * @brief check whether the CurrentDate is less than or equal to the * tDate */ func (mDate Date) LessOrEqual(tDate Date) bool { return !mDate.MoreThan(tDate) }
entity/date.go
0.570571
0.511168
date.go
starcoder
package miscmodule import ( "math/rand" "sort" "strconv" "strings" bot "../sweetiebot" "github.com/erikmcclure/discordgo" ) const maxShowDice int64 = 250 type showrollCommand struct { } func (c *showrollCommand) Info() *bot.CommandInfo { return &bot.CommandInfo{ Name: "ShowRoll", Usage: "Evaluates a dice expression, returning individual dice results.", ServerIndependent: true, } } func (c *showrollCommand) value(args []string, index *int, prefix string) string { *index++ s := "Rolling " + args[*index-1] + ": " errmsg := "I can't figure out your dice expression... Try " + prefix + "help showroll for more information." if diceregex.MatchString(args[*index-1]) { dice := strings.SplitN(args[*index-1], "d", 2) show := 0 var multiplier, num, threshold, fail int64 = 1, 1, 0, 0 if len(dice) > 1 { if len(dice[0]) > 0 { multiplier, _ = strconv.ParseInt(dice[0], 10, 64) } if strings.Contains(dice[1], "t") { tdice := strings.SplitN(dice[1], "t", 2) dice[1] = tdice[0] if strings.Contains(tdice[1], "f") { fdice := strings.SplitN(tdice[1], "f", 2) threshold, _ = strconv.ParseInt(fdice[0], 10, 64) fail, _ = strconv.ParseInt(fdice[1], 10, 64) } else { threshold, _ = strconv.ParseInt(tdice[1], 10, 64) } if threshold == 0 { return s + errmsg } } if strings.Contains(dice[1], "f") { fdice := strings.SplitN(dice[1], "f", 2) dice[1] = fdice[0] fail, _ = strconv.ParseInt(fdice[1], 10, 64) if fail == 0 { return s + errmsg } } if strings.Contains(dice[1], "h") { fdice := strings.SplitN(dice[1], "h", 2) dice[1] = fdice[0] parseshow, _ := strconv.ParseInt(fdice[1], 10, 32) show = int(parseshow) if show == 0 { return s + errmsg } } num, _ = strconv.ParseInt(dice[1], 10, 64) } else { num, _ = strconv.ParseInt(dice[0], 10, 64) } if fail < 0 || fail > num { return s + "That's a silly fail threshold, filly!" } if threshold < 0 || threshold > num { return s + "That's a silly success threshold, filly!" } if multiplier < 1 || num < 1 { return s + errmsg } if multiplier > maxShowDice { return s + "I don't have that many dice..." } var n int64 var t int var f int var results = make([]int64, 0, multiplier) for ; multiplier > 0; multiplier-- { n = rand.Int63n(num) + 1 results = append(results, n) if threshold > 0 { if n >= threshold { t++ } } if fail > 0 { if n <= fail { f++ } } } if show > 0 { sort.Slice(results, func(i, j int) bool { return results[i] > results[j] }) if len(results) < show { show = len(results) } } else { show = len(results) } if show > 0 { s += strconv.FormatInt(results[0], 10) for i := 1; i < show; i++ { s += " + " s += strconv.FormatInt(results[i], 10) } } if t > 0 { s += "\n" + strconv.Itoa(t) + " successes!" } if f > 0 { s += "\n" + strconv.Itoa(f) + " failures!" } return s } return s + errmsg } func (c *showrollCommand) Process(args []string, msg *discordgo.Message, indices []int, info *bot.GuildInfo) (retval string, b bool, embed *discordgo.MessageEmbed) { if len(args) < 1 { return "```\nNothing to roll...```", false, nil } index := 0 var s string for index < len(args) { s += c.value(args, &index, info.Config.Basic.CommandPrefix) + "\n" } return "```\n" + s + "```", false, nil } func (c *showrollCommand) Usage(info *bot.GuildInfo) *bot.CommandUsage { return &bot.CommandUsage{ Desc: `Evaluates a dice roll expression, returning the individual die results. Can also optionally report hit counting for success and fail thresholds. Acceptable expressions are defined as [**N**]d**X**[t**Y**][f**Z**][h**W**] where: N: number of dice to roll (postive integer < 250; optional, defaults to 1) dX: the type of dice to roll, where X is the number of sides (required) tY: the threshold to use for hit counting, (Y is a positive integer; optional) fZ: the fail threshold to use for hit counting, (Z is a positive integer; optional) hW: Only shows the highest W dice, (W is a positive integer; optional) Examples: d6: Rolls a single 6-sided die 4d20: Rolls 4 20-sided dice 12d6t5: Rolls 12 6-sided dice, and counts the number that score 5 or higher 17d10t8f2: Rolls 17 10-sided dice, counts number that roll 8 or higher (successes) and 2 or lower (fails) 12d6h5: Rolls 12 6-sided dice, and only shows the highest 5 results`, Params: []bot.CommandUsageParam{ {Name: "expression", Desc: "The dice expression to parse (e.g. `12d6t5f1`).", Optional: false}, }, } }
miscmodule/ShowRollCommand.go
0.595728
0.498535
ShowRollCommand.go
starcoder
package cron import "time" // Now returns a new timestamp. func Now() time.Time { return time.Now().UTC() } // Since returns the duration since another timestamp. func Since(t time.Time) time.Duration { return Now().Sub(t) } // Min returns the minimum of two times. func Min(t1, t2 time.Time) time.Time { if t1.IsZero() && t2.IsZero() { return time.Time{} } if t1.IsZero() { return t2 } if t2.IsZero() { return t1 } if t1.Before(t2) { return t1 } return t2 } // Max returns the maximum of two times. func Max(t1, t2 time.Time) time.Time { if t1.Before(t2) { return t2 } return t1 } // FormatTime returns a string for a time. func FormatTime(t time.Time) string { return t.Format(time.RFC3339) } // NOTE: time.Zero()? what's that? var ( // DaysOfWeek are all the time.Weekday in an array for utility purposes. DaysOfWeek = []time.Weekday{ time.Sunday, time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday, time.Saturday, } // WeekDays are the business time.Weekday in an array. WeekDays = []time.Weekday{ time.Monday, time.Tuesday, time.Wednesday, time.Thursday, time.Friday, } // WeekWeekEndDaysDays are the weekend time.Weekday in an array. WeekendDays = []time.Weekday{ time.Sunday, time.Saturday, } // Epoch is unix epoch saved for utility purposes. Epoch = time.Unix(0, 0) // Zero is basically epoch but if you want to be super duper sure. Zero = time.Time{} ) // NOTE: we have to use shifts here because in their infinite wisdom google didn't make these values powers of two for masking const ( // AllDaysMask is a bitmask of all the days of the week. AllDaysMask = 1<<uint(time.Sunday) | 1<<uint(time.Monday) | 1<<uint(time.Tuesday) | 1<<uint(time.Wednesday) | 1<<uint(time.Thursday) | 1<<uint(time.Friday) | 1<<uint(time.Saturday) // WeekDaysMask is a bitmask of all the weekdays of the week. WeekDaysMask = 1<<uint(time.Monday) | 1<<uint(time.Tuesday) | 1<<uint(time.Wednesday) | 1<<uint(time.Thursday) | 1<<uint(time.Friday) //WeekendDaysMask is a bitmask of the weekend days of the week. WeekendDaysMask = 1<<uint(time.Sunday) | 1<<uint(time.Saturday) ) // IsWeekDay returns if the day is a monday->friday. func IsWeekDay(day time.Weekday) bool { return !IsWeekendDay(day) } // IsWeekendDay returns if the day is a monday->friday. func IsWeekendDay(day time.Weekday) bool { return day == time.Saturday || day == time.Sunday } // ConstBool returns a value provider for a constant. func ConstBool(value bool) func() bool { return func() bool { return value } } // ConstInt returns a value provider for a constant. func ConstInt(value int) func() int { return func() int { return value } } // ConstDuration returns a value provider for a constant. func ConstDuration(value time.Duration) func() time.Duration { return func() time.Duration { return value } } // ConstLabels returns a value provider for a constant. func ConstLabels(labels map[string]string) func() map[string]string { return func() map[string]string { return labels } }
cron/util.go
0.837753
0.557725
util.go
starcoder
package captcha import ( "image" "image/color" "image/draw" "math" "github.com/golang/freetype" "github.com/golang/freetype/truetype" ) // Image 图片 type Image struct { *image.RGBA } // NewImage 创建一个新的图片 func NewImage(w, h int) *Image { img := &Image{image.NewRGBA(image.Rect(0, 0, w, h))} return img } func sign(x int) int { if x > 0 { return 1 } return -1 } // DrawLine 画直线 // Bresenham算法(https://zh.wikipedia.org/zh-cn/布雷森漢姆直線演算法) // x1,y1 起点 x2,y2终点 func (img *Image) DrawLine(x1, y1, x2, y2 int, c color.Color) { dx, dy, flag := int(math.Abs(float64(x2-x1))), int(math.Abs(float64(y2-y1))), false if dy > dx { flag = true x1, y1 = y1, x1 x2, y2 = y2, x2 dx, dy = dy, dx } ix, iy := sign(x2-x1), sign(y2-y1) n2dy := dy * 2 n2dydx := (dy - dx) * 2 d := n2dy - dx for x1 != x2 { if d < 0 { d += n2dy } else { y1 += iy d += n2dydx } if flag { img.Set(y1, x1, c) } else { img.Set(x1, y1, c) } x1 += ix } } func (img *Image) drawCircle8(xc, yc, x, y int, c color.Color) { img.Set(xc+x, yc+y, c) img.Set(xc-x, yc+y, c) img.Set(xc+x, yc-y, c) img.Set(xc-x, yc-y, c) img.Set(xc+y, yc+x, c) img.Set(xc-y, yc+x, c) img.Set(xc+y, yc-x, c) img.Set(xc-y, yc-x, c) } // DrawCircle 画圆 // xc,yc 圆心坐标 r 半径 fill是否填充颜色 func (img *Image) DrawCircle(xc, yc, r int, fill bool, c color.Color) { size := img.Bounds().Size() // 如果圆在图片可见区域外,直接退出 if xc+r < 0 || xc-r >= size.X || yc+r < 0 || yc-r >= size.Y { return } x, y, d := 0, r, 3-2*r for x <= y { if fill { for yi := x; yi <= y; yi++ { img.drawCircle8(xc, yc, x, yi, c) } } else { img.drawCircle8(xc, yc, x, y, c) } if d < 0 { d = d + 4*x + 6 } else { d = d + 4*(x-y) + 10 y-- } x++ } } // DrawString 写字 func (img *Image) DrawString(font *truetype.Font, c color.Color, str string, fontsize float64) { ctx := freetype.NewContext() // default 72dpi ctx.SetDst(img) ctx.SetClip(img.Bounds()) ctx.SetSrc(image.NewUniform(c)) ctx.SetFontSize(fontsize) ctx.SetFont(font) // 写入文字的位置 pt := freetype.Pt(0, int(-fontsize/6)+ctx.PointToFixed(fontsize).Ceil()) ctx.DrawString(str, pt) } // Rotate 旋转 func (img *Image) Rotate(angle float64) image.Image { return new(rotate).Rotate(angle, img.RGBA).transformRGBA() } // 填充背景 func (img *Image) FillBkg(c image.Image) { draw.Draw(img, img.Bounds(), c, image.ZP, draw.Over) } // 水波纹, amplude=振幅, period=周期 // copy from https://github.com/dchest/captcha/blob/master/image.go func (img *Image) distortTo(amplude float64, period float64) { w := img.Bounds().Max.X h := img.Bounds().Max.Y oldm := img.RGBA dx := 1.4 * math.Pi / period for x := 0; x < w; x++ { for y := 0; y < h; y++ { xo := amplude * math.Sin(float64(y)*dx) yo := amplude * math.Cos(float64(x)*dx) rgba := oldm.RGBAAt(x+int(xo), y+int(yo)) if rgba.A > 0 { oldm.SetRGBA(x, y, rgba) } } } } func inBounds(b image.Rectangle, x, y float64) bool { if x < float64(b.Min.X) || x >= float64(b.Max.X) { return false } if y < float64(b.Min.Y) || y >= float64(b.Max.Y) { return false } return true } type rotate struct { dx float64 dy float64 sin float64 cos float64 neww float64 newh float64 src *image.RGBA } func radian(angle float64) float64 { return angle * math.Pi / 180.0 } func (r *rotate) Rotate(angle float64, src *image.RGBA) *rotate { r.src = src srsize := src.Bounds().Size() width, height := srsize.X, srsize.Y // 源图四个角的坐标(以图像中心为坐标系原点) // 左下角,右下角,左上角,右上角 srcwp, srchp := float64(width)*0.5, float64(height)*0.5 srcx1, srcy1 := -srcwp, srchp srcx2, srcy2 := srcwp, srchp srcx3, srcy3 := -srcwp, -srchp srcx4, srcy4 := srcwp, -srchp r.sin, r.cos = math.Sincos(radian(angle)) // 旋转后的四角坐标 desx1, desy1 := r.cos*srcx1+r.sin*srcy1, -r.sin*srcx1+r.cos*srcy1 desx2, desy2 := r.cos*srcx2+r.sin*srcy2, -r.sin*srcx2+r.cos*srcy2 desx3, desy3 := r.cos*srcx3+r.sin*srcy3, -r.sin*srcx3+r.cos*srcy3 desx4, desy4 := r.cos*srcx4+r.sin*srcy4, -r.sin*srcx4+r.cos*srcy4 // 新的高度很宽度 r.neww = math.Max(math.Abs(desx4-desx1), math.Abs(desx3-desx2)) + 0.5 r.newh = math.Max(math.Abs(desy4-desy1), math.Abs(desy3-desy2)) + 0.5 r.dx = -0.5*r.neww*r.cos - 0.5*r.newh*r.sin + srcwp r.dy = 0.5*r.neww*r.sin - 0.5*r.newh*r.cos + srchp return r } func (r *rotate) pt(x, y int) (float64, float64) { return float64(-y)*r.sin + float64(x)*r.cos + r.dy, float64(y)*r.cos + float64(x)*r.sin + r.dx } func (r *rotate) transformRGBA() image.Image { srcb := r.src.Bounds() b := image.Rect(0, 0, int(r.neww), int(r.newh)) dst := image.NewRGBA(b) for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { sx, sy := r.pt(x, y) if inBounds(srcb, sx, sy) { // 消除锯齿填色 c := bili.RGBA(r.src, sx, sy) off := (y-dst.Rect.Min.Y)*dst.Stride + (x-dst.Rect.Min.X)*4 dst.Pix[off+0] = c.R dst.Pix[off+1] = c.G dst.Pix[off+2] = c.B dst.Pix[off+3] = c.A } } } return dst }
vendor/github.com/afocus/captcha/draw.go
0.52829
0.425367
draw.go
starcoder
package sudoku import ( "math" "math/rand" ) //ProbabilityDistribution represents a distribution of probabilities over //indexes. type ProbabilityDistribution []float64 //Normalized returns true if the distribution is normalized: that is, the //distribution sums to 1.0 func (d ProbabilityDistribution) normalized() bool { var sum float64 for _, weight := range d { if weight < 0 { return false } sum += weight } return sum == 1.0 } //Normalize returns a new probability distribution based on this one that is //normalized. func (d ProbabilityDistribution) normalize() ProbabilityDistribution { if d.normalized() { return d } var sum float64 fixedWeights := d.denegativize() for _, weight := range fixedWeights { sum += weight } result := make(ProbabilityDistribution, len(d)) for i, weight := range fixedWeights { result[i] = weight / sum } return result } //Denegativize returns a new probability distribution like this one, but with //no negatives. If a negative is found, the entire distribution is shifted up //by that amount. func (d ProbabilityDistribution) denegativize() ProbabilityDistribution { var lowestNegative float64 //Check for a negative. for _, weight := range d { if weight < 0 { if weight < lowestNegative { lowestNegative = weight } } } fixedWeights := make(ProbabilityDistribution, len(d)) copy(fixedWeights, d) if lowestNegative != 0 { //Found a negative. Need to fix up all weights. for i := 0; i < len(d); i++ { fixedWeights[i] = d[i] - lowestNegative } } return fixedWeights } //invert returns a new probability distribution like this one, but "flipped" //so low values have a high chance of occurring and high values have a low //chance. The curve used to invert is expoential. func (d ProbabilityDistribution) invert() ProbabilityDistribution { //TODO: this function means that the worst weighted item will have a weight of 0.0. Isn't that wrong? Maybe it should be +1 to everythign? weights := make(ProbabilityDistribution, len(d)) invertedWeights := d.denegativize() //This inversion isn't really an inversion, and it's tied closely to the shape of the weightings we expect to be given in the sudoku problem domain. //In sudoku, the weights for different techniques go up exponentially. So when we invert, we want to see a similar exponential shape of the //flipped values. //We flip with 1/x, and the bottom is an exponent, but softened some. //I don't know if this math makes any sense, but in the test distributions the outputs FEEL right. allInfinite := true for _, weight := range d { if !math.IsInf(weight, 0) { allInfinite = false break } } //If all of the items are infinite then we want to special case to spread //probability evenly by putting all numbers to lowest possible numbers. //However if there is a mix of some infinite and some non-infinite we want //to basically ignore the infinite ones. if allInfinite { for i, _ := range weights { weights[i] = math.SmallestNonzeroFloat64 } } else { //Invert for i, weight := range invertedWeights { weights[i] = invertWeight(weight) } } //But now you need to renormalize since they won't sum to 1. return weights.normalize() } //invertWeight is the primary logic used to invert a positive weight. func invertWeight(inverted float64) float64 { if math.IsInf(inverted, 0) { //This will only happen if there's a mix of Inf and non-Inf in the //input distribution--in which case the expected beahvior is that //Inf's are basically ignore.d return 0.0 } result := 1 / math.Exp(inverted/10) if math.IsInf(result, 0) { result = math.SmallestNonzeroFloat64 } else if result == 0.0 { //Some very large numbers will come out as 0.0, but that's wrong. result = math.SmallestNonzeroFloat64 } return result } //RandomIndex returns a random index based on the probability distribution. func (d ProbabilityDistribution) RandomIndex() int { weightsToUse := d if !d.normalized() { weightsToUse = d.normalize() } sample := rand.Float64() var counter float64 for i, weight := range weightsToUse { counter += weight if sample <= counter { return i } } //This shouldn't happen if the weights are properly normalized. return len(weightsToUse) - 1 }
probability_distribution.go
0.745584
0.604399
probability_distribution.go
starcoder
package iso20022 // Provides information related to the collateral position, that is, the identification of the exposed party, the total exposure amount and the total collateral amount held by the taker. It also contains the valuation dates and the requested settlement date of collateral if there is a shortage of collateral. type Summary1 struct { // Sum of the exposures of all transactions which are in the favour of party A. That is, all transactions which would have an amount payable by party B to party A if they were being terminated. ExposedAmountPartyA *ActiveCurrencyAndAmount `xml:"XpsdAmtPtyA,omitempty"` // Sum of the exposures of all transactions which are in the favour of party B. That is, all transactions which would have an amount payable by party A to party B if they were being terminated. ExposedAmountPartyB *ActiveCurrencyAndAmount `xml:"XpsdAmtPtyB,omitempty"` // Specifies the underlying business area/type of trade that triggered the posting of collateral. ExposureType *ExposureType1Code `xml:"XpsrTp"` // Total value of the collateral (post-haircut) held by the exposed party TotalValueOfCollateral *ActiveCurrencyAndAmount `xml:"TtlValOfColl"` // Specifies the amount of collateral in excess or deficit compared to the exposure. NetExcessDeficit *ActiveCurrencyAndAmount `xml:"NetXcssDfcit,omitempty"` // Indicates whether the collateral actually posted is a long or a short position. NetExcessDeficitIndicator *ShortLong1Code `xml:"NetXcssDfcitInd,omitempty"` // Date/time at which the collateral was valued. ValuationDateTime *ISODateTime `xml:"ValtnDtTm"` // Date on which the instructing party requests settlement of the collateral to take place. RequestedSettlementDate *ISODate `xml:"ReqdSttlmDt,omitempty"` // Provides the more details on the valuation of the collateral that is posted. SummaryDetails *SummaryAmounts1 `xml:"SummryDtls,omitempty"` } func (s *Summary1) SetExposedAmountPartyA(value, currency string) { s.ExposedAmountPartyA = NewActiveCurrencyAndAmount(value, currency) } func (s *Summary1) SetExposedAmountPartyB(value, currency string) { s.ExposedAmountPartyB = NewActiveCurrencyAndAmount(value, currency) } func (s *Summary1) SetExposureType(value string) { s.ExposureType = (*ExposureType1Code)(&value) } func (s *Summary1) SetTotalValueOfCollateral(value, currency string) { s.TotalValueOfCollateral = NewActiveCurrencyAndAmount(value, currency) } func (s *Summary1) SetNetExcessDeficit(value, currency string) { s.NetExcessDeficit = NewActiveCurrencyAndAmount(value, currency) } func (s *Summary1) SetNetExcessDeficitIndicator(value string) { s.NetExcessDeficitIndicator = (*ShortLong1Code)(&value) } func (s *Summary1) SetValuationDateTime(value string) { s.ValuationDateTime = (*ISODateTime)(&value) } func (s *Summary1) SetRequestedSettlementDate(value string) { s.RequestedSettlementDate = (*ISODate)(&value) } func (s *Summary1) AddSummaryDetails() *SummaryAmounts1 { s.SummaryDetails = new(SummaryAmounts1) return s.SummaryDetails }
Summary1.go
0.813609
0.542742
Summary1.go
starcoder
package goslice import "golang.org/x/exp/constraints" // SumSlice returns the sum of all the elements in the given slice. // No attempt is made to detect overflow. func SumSlice[T constraints.Ordered](elems []T) T { var sum T for _, elem := range elems { sum += elem } return sum } // ProdSlice returns the product of all the elemenst in the given slice. // No attempt is made to detect overflow. func ProdSlice[T constraints.Integer | constraints.Float](elems []T) T { var prod T = 1 for _, elem := range elems { prod *= elem } return prod } // AllOf returns true if and only if all of the elements in the slice satisfy the given predicate. func AllOf[T any](elems []T, pred func(elem T) bool) bool { var all bool = true for _, elem := range elems { all = all && pred(elem) } return all } // AnyOf returns true if and only if at least one of the elements in the slice satisfy the given predicate. func AnyOf[T any](elems []T, pred func(elem T) bool) bool { var anyOf bool = false for _, elem := range elems { anyOf = anyOf || pred(elem) } return anyOf } // NoneOf returns true if and only if none of the elements in the slice satisfy the given predicate. func NoneOf[T any](elems []T, pred func(elem T) bool) bool { return !AnyOf(elems, pred) } // CountIf returns the number of elements in the slice that satisfy the given predicate. func CountIf[T any](elems []T, pred func(elem T) bool) (count int) { for _, elem := range elems { if pred(elem) { count++ } } return } // FindIf returns the index to the first element in the slice that satisfies the given predicate. // If no such element exists, -1 is returned. func FindIf[T any](elems []T, pred func(elem T) bool) int { for i, elem := range elems { if pred(elem) { return i } } return -1 } // Merge merges the two provided sorted slices into a single sorted slice. func Merge[T constraints.Ordered](left, right []T) (sorted []T) { sorted = make([]T, len(left)+len(right)) i := 0 j := 0 k := 0 for i < len(left) && j < len(right) { if left[i] < right[j] { sorted[k] = left[i] i++ k++ } else { sorted[k] = right[j] j++ k++ } } for i < len(left) { sorted[k] = left[i] k++ i++ } for j < len(right) { sorted[k] = right[j] k++ j++ } return } // BinarySearch returns the index of the given target in the provided sorted elems slice. // If the target is not in the sorted slice, -1 is returned. func BinarySearch[T constraints.Ordered](elems []T, target T) (index int) { lower, upper := 0, len(elems)-1 for lower <= upper { mid := lower + (upper-1)/2 if elems[mid] == target { return mid } else if elems[mid] < target { lower = mid + 1 } else { upper = mid - 1 } } return -1 }
alg.go
0.837819
0.549278
alg.go
starcoder
package ach import ( "strings" "unicode/utf8" ) // ADVFileControl record contains entry counts, dollar totals and hash // totals accumulated from each batchADV control record in the file. type ADVFileControl struct { // ID is a client defined string used as a reference to this record. ID string `json:"id"` // RecordType defines the type of record in the block. fileControlPos 9 recordType string // BatchCount total number of batches (i.e., ‘5’ records) in the file BatchCount int `json:"batchCount"` // BlockCount total number of records in the file (include all headers and trailer) divided // by 10 (This number must be evenly divisible by 10. If not, additional records consisting of all 9’s are added to the file after the initial ‘9’ record to fill out the block 10.) BlockCount int `json:"blockCount,omitempty"` // EntryAddendaCount total detail and addenda records in the file EntryAddendaCount int `json:"entryAddendaCount"` // EntryHash calculated in the same manner as the batch has total but includes total from entire file EntryHash int `json:"entryHash"` // TotalDebitEntryDollarAmountInFile contains accumulated Batch debit totals within the file. TotalDebitEntryDollarAmountInFile int `json:"totalDebit"` // TotalCreditEntryDollarAmountInFile contains accumulated Batch credit totals within the file. TotalCreditEntryDollarAmountInFile int `json:"totalCredit"` // Reserved should be blank. reserved string // validator is composed for data validation validator // converters is composed for ACH to golang Converters converters } // Parse takes the input record string and parses the FileControl values // Parse provides no guarantee about all fields being filled in. Callers should make a Validate() call to confirm // successful parsing and data validity. func (fc *ADVFileControl) Parse(record string) { if utf8.RuneCountInString(record) < 71 { return } // 1-1 Always "9" fc.recordType = "9" // 2-7 The total number of Batch Header Record in the file. For example: "000003 fc.BatchCount = fc.parseNumField(record[1:7]) // 8-13 e total number of blocks on the file, including the File Header and File Control records. One block is 10 lines, so it's effectively the number of lines in the file divided by 10. fc.BlockCount = fc.parseNumField(record[7:13]) // 14-21 Total number of Entry Detail Record in the file fc.EntryAddendaCount = fc.parseNumField(record[13:21]) // 22-31 Total of all positions 4-11 on each Entry Detail Record in the file. This is essentially the sum of all the RDFI routing numbers in the file. // If the sum exceeds 10 digits (because you have lots of Entry Detail Records), lop off the most significant digits of the sum until there are only 10 fc.EntryHash = fc.parseNumField(record[21:31]) // 32-51 Number of cents of debit entries within the file fc.TotalDebitEntryDollarAmountInFile = fc.parseNumField(record[31:51]) // 52-71 Number of cents of credit entries within the file fc.TotalCreditEntryDollarAmountInFile = fc.parseNumField(record[51:71]) // 72-94 Reserved Always blank (just fill with spaces) fc.reserved = " " } // NewADVFileControl returns a new ADVFileControl with default values for none exported fields func NewADVFileControl() ADVFileControl { return ADVFileControl{ recordType: "9", reserved: " ", } } // String writes the ADVFileControl struct to a 94 character string. func (fc *ADVFileControl) String() string { var buf strings.Builder buf.Grow(94) buf.WriteString(fc.recordType) buf.WriteString(fc.BatchCountField()) buf.WriteString(fc.BlockCountField()) buf.WriteString(fc.EntryAddendaCountField()) buf.WriteString(fc.EntryHashField()) buf.WriteString(fc.TotalDebitEntryDollarAmountInFileField()) buf.WriteString(fc.TotalCreditEntryDollarAmountInFileField()) buf.WriteString(fc.reserved) return buf.String() } // Validate performs NACHA format rule checks on the record and returns an error if not Validated // The first error encountered is returned and stops that parsing. func (fc *ADVFileControl) Validate() error { if err := fc.fieldInclusion(); err != nil { return err } if fc.recordType != "9" { return fieldError("recordType", NewErrRecordType(9), fc.recordType) } return nil } // fieldInclusion validate mandatory fields are not default values. If fields are // invalid the ACH transfer will be returned. func (fc *ADVFileControl) fieldInclusion() error { if fc.recordType == "" { return fieldError("recordType", ErrConstructor, fc.recordType) } if fc.BatchCount == 0 { return fieldError("BatchCount", ErrConstructor, fc.BatchCountField()) } if fc.BlockCount == 0 { return fieldError("BlockCount", ErrConstructor, fc.BlockCountField()) } if fc.EntryAddendaCount == 0 { return fieldError("EntryAddendaCount", ErrConstructor, fc.EntryAddendaCountField()) } if fc.EntryHash == 0 { return fieldError("EntryHash", ErrConstructor, fc.EntryAddendaCountField()) } return nil } // BatchCountField gets a string of the batch count zero padded func (fc *ADVFileControl) BatchCountField() string { return fc.numericField(fc.BatchCount, 6) } // BlockCountField gets a string of the block count zero padded func (fc *ADVFileControl) BlockCountField() string { return fc.numericField(fc.BlockCount, 6) } // EntryAddendaCountField gets a string of entry addenda batch count zero padded func (fc *ADVFileControl) EntryAddendaCountField() string { return fc.numericField(fc.EntryAddendaCount, 8) } // EntryHashField gets a string of entry hash zero padded func (fc *ADVFileControl) EntryHashField() string { return fc.numericField(fc.EntryHash, 10) } // TotalDebitEntryDollarAmountInFileField get a zero padded Total debit Entry Amount func (fc *ADVFileControl) TotalDebitEntryDollarAmountInFileField() string { return fc.numericField(fc.TotalDebitEntryDollarAmountInFile, 20) } // TotalCreditEntryDollarAmountInFileField get a zero padded Total credit Entry Amount func (fc *ADVFileControl) TotalCreditEntryDollarAmountInFileField() string { return fc.numericField(fc.TotalCreditEntryDollarAmountInFile, 20) }
advFileControl.go
0.618435
0.483831
advFileControl.go
starcoder
package eml // A Solution describes an event sourced system // It will contain bounded contexts and meta information about what environment to deploy it to. // It can also contain references to other bounded contexts from the 'PlayStore' (Context Store? Microservice Store? type Solution struct { EmlVersion string `yaml:"EmlVersion"` Name string `yaml:"Solution"` Contexts []BoundedContext `yaml:"Contexts"` Errors []ValidationError `yaml:"Errors"` // The presence of errors means that no API can be generated for the Solution. } // A BoundedContext is a context in which a ubiquitous language applies. type BoundedContext struct { Name string `yaml:"Name"` Streams []Stream `yaml:"Streams"` Readmodels []Readmodel `yaml:"Readmodels"` } // A Stream is a stream of events representing a transactional scope. // In Domain Driven Design, this is known as an "aggregate". // In comp sci, it can be represented as a state machine. type Stream struct { Name string `yaml:"Stream"` Commands []Command `yaml:"Commands"` Events []Event `yaml:"Events"` } // An Event represents a fact that occurred as a result of a state change. type Event struct { Event struct { Name string `yaml:"Name"` Properties []Property `yaml:"Properties"` } `yaml:"Event"` } // A Property of an event. type Property struct { Name string `yaml:"Name"` Type string `yaml:"Type"` IsHashed bool `yaml:"IsHashed,omitempty"` } // A Command in a bounded context type Command struct { Command struct { Name string `yaml:"Name"` Parameters []Parameter `yaml:"Parameters"` Preconditions []string `yaml:"Preconditions"` Postconditions []string `yaml:"Postconditions"` } `yaml:"Command"` } // A Parameter for a command. type Parameter struct { Name string `yaml:"Name"` Type string `yaml:"Type"` Rules []string `yaml:"Rules"` } // A Readmodel which subscribes to events type Readmodel struct { Readmodel struct { Name string `yaml:"Name"` Key string `yaml:"Key"` SubscribesTo []string `yaml:"SubscribesTo"` } `yaml:"Readmodel"` } // A ValidationError means that the eml structure cannot be used to generate an API. type ValidationError struct { ErrorID string Context string Stream string Command string Event string Readmodel string Message string }
pkg/eml/eml_specification.go
0.760473
0.426799
eml_specification.go
starcoder
package spy import ( "reflect" ) type Matcher interface { //Match matches provided value against conditions and returns true or false // this method should not panic Match(actual interface{}) bool } type stringMatcher struct { value string } func (m stringMatcher) Match(a interface{}) bool { v, ok := a.(string) return ok && m.value == v } //String returns a matcher which match against provided string value func String(s string) Matcher { return stringMatcher{s} } type boolMatcher struct { value bool } func (m boolMatcher) Match(a interface{}) bool { v, ok := a.(bool) return ok && m.value == v } //Bool returns a matcher which can match against provided bool value func Bool(b bool) Matcher { return boolMatcher{b} } type anythingMatcher struct{} func (m anythingMatcher) Match(a interface{}) bool { return true } //Anything returns a matcher which matches anything func Anything() Matcher { return anythingMatcher{} } type nilMatcher struct{} func (m nilMatcher) Match(a interface{}) bool { return a == nil } //Nil returns a matcher which matches nil func Nil() Matcher { return nilMatcher{} } type notNilMatcher struct{} func (m notNilMatcher) Match(a interface{}) bool { return a != nil } //NotNil returns a matcher which matches anything not nil func NotNil() Matcher { return notNilMatcher{} } type intMatcher struct { value int } func (m intMatcher) Match(v interface{}) bool { v, ok := v.(int) return ok && m.value == v } //Int returns a matcher which can match against provided int value func Int(i int) Matcher { return intMatcher{i} } type int64Matcher struct { value int64 } func (m int64Matcher) Match(v interface{}) bool { v, ok := v.(int64) return ok && m.value == v } //Int64 returns a matcher which can match against provided int64 value func Int64(i int64) Matcher { return int64Matcher{i} } type uint64Matcher struct { value uint64 } func (m uint64Matcher) Match(v interface{}) bool { v, ok := v.(uint64) return ok && m.value == v } //Uint64 returns a matcher which can match against provided uint64 value func Uint64(i uint64) Matcher { return uint64Matcher{i} } type typeMatcher struct { value string } //Type returns a Matcher which matches the type against the string argument. // Example Type("*int") // Will match a pointer to int func (m typeMatcher) Match(v interface{}) bool { if v == nil { return false } return reflect.TypeOf(v).String() == m.value } func Type(t string) Matcher { return typeMatcher{t} } type customMatcher struct { value func(v interface{}) bool } func (m customMatcher) Match(v interface{}) bool { return m.value(v) } //Custom wrapps a custom func with Matcher interface func Custom(f func(v interface{}) bool) Matcher { return customMatcher{f} } type exactMatcher struct { value interface{} } func (m exactMatcher) Match(v interface{}) bool { if v == nil { return m.value == v } return reflect.DeepEqual(m.value, v) } //Exact only matches the same value. Uses reflect.DeepEqual func Exact(v interface{}) Matcher { return exactMatcher{v} }
matchers.go
0.855911
0.410047
matchers.go
starcoder
package chessboard type PieceInterface interface { Movements() []PieceMovement Symbol() string } // Piece is a generic piece type Piece struct { Board *Board XPos int YPos int PieceInterface } func (p *Piece) GetIndex() (BoardIndex, error) { return p.Board.CoordinatesToIndex(Coordinates{p.XPos, p.YPos}) } func (p *Piece) GetTerritory() (BoardBoolVector, error) { vector := p.Board.NewBoolVector() index, err := p.GetIndex() if err != nil { return nil, err } vector[index] = true for _, movement := range p.PieceInterface.Movements() { index, err = p.Board.CoordinatesToIndex(Coordinates{p.XPos + movement.Horizontal, p.YPos + movement.Vertical}) if err == nil { vector[index] = true } } return vector, nil } func (p *Piece) HorizontalMovements() []PieceMovement { movements := []PieceMovement{} for x := -p.LeftDistance(); x < p.RightDistance()+1; x++ { if x != 0 { movements = append(movements, PieceMovement{x, 0}) } } return movements } func (p *Piece) VerticalMovements() []PieceMovement { movements := []PieceMovement{} for y := -p.TopDistance(); y < p.BottomDistance()+1; y++ { if y != 0 { movements = append(movements, PieceMovement{0, y}) } } return movements } func (p *Piece) DiagonalMovements() []PieceMovement { movements := []PieceMovement{} leftDistance := p.LeftDistance() topDistance := p.TopDistance() rightDistance := p.RightDistance() bottomDistance := p.BottomDistance() leftTopMinDistance := min(leftDistance, topDistance) for i := 0; i < leftTopMinDistance; i++ { movements = append(movements, PieceMovement{-(i + 1), -(i + 1)}) } rightTopMinDistance := min(rightDistance, topDistance) for i := 0; i < rightTopMinDistance; i++ { movements = append(movements, PieceMovement{+(i + 1), -(i + 1)}) } rightBottomMinDistance := min(rightDistance, bottomDistance) for i := 0; i < rightBottomMinDistance; i++ { movements = append(movements, PieceMovement{+(i + 1), +(i + 1)}) } leftBottomMinDistance := min(leftDistance, bottomDistance) for i := 0; i < leftBottomMinDistance; i++ { movements = append(movements, PieceMovement{-(i + 1), +(i + 1)}) } return movements } func (p *Piece) LeftDistance() int { return p.XPos } func (p *Piece) TopDistance() int { return p.YPos } func (p *Piece) RightDistance() int { return p.Board.Length - p.XPos - 1 } func (p *Piece) BottomDistance() int { return p.Board.Height - p.YPos } type PieceMovement struct { Horizontal int Vertical int }
piece.go
0.818229
0.425904
piece.go
starcoder
package main import ( "bufio" "log" "math" "os" "sort" ) const ( Empty = '.' Asteroid = '#' ) func angle(x, y, xi, yi int) float64 { dx, dy := xi-x, yi-y deg := (math.Atan2(float64(dy), float64(dx)) * 180) / math.Pi if deg < 0 { deg += 360 } // munge to match coordinate system of grid deg += 90 if deg >= 360 { deg -= 360 } return deg } func abs(x int) int { if x < 0 { return -x } return x } type Point struct { X int Y int } func distance(x, y, xi, yi int) float64 { a, b := abs(x-xi), abs(y-yi) return math.Sqrt(float64((a * a) + (b * b))) } func detect(grid [][]byte, x, y int) map[float64]Point { detected := map[float64]Point{} for yi := 0; yi < len(grid); yi++ { for xi := 0; xi < len(grid[yi]); xi++ { if (xi == x && yi == y) || grid[yi][xi] == Empty { continue } a := angle(x, y, xi, yi) d := distance(x, y, xi, yi) if p, ok := detected[a]; !ok || d < distance(x, y, p.X, p.Y) { detected[a] = Point{X: xi, Y: yi} } } } return detected } func PartOne(grid [][]byte) (int, Point) { var most int var point Point for y := 0; y < len(grid); y++ { for x := 0; x < len(grid[y]); x++ { if grid[y][x] == Empty { continue } if c := len(detect(grid, x, y)); c > most { point = Point{X: x, Y: y} most = c } } } return most, point } func PartTwo(grid [][]byte, point Point) Point { var i int for { points := detect(grid, point.X, point.Y) keys := make([]float64, 0, len(points)) for k := range points { keys = append(keys, k) } sort.Float64s(keys) for _, k := range keys { p := points[k] grid[p.Y][p.X] = Empty i++ if i == 200 { return p } } } } func main() { f, err := os.Open("input.txt") if err != nil { log.Printf("opening file: %v", err) return } defer f.Close() var grid [][]byte s := bufio.NewScanner(bufio.NewReader(f)) for s.Scan() { line := []byte(s.Text()) grid = append(grid, line) } if s.Err() != nil { log.Printf("error scanning: %v", s.Err()) return } most, point := PartOne(grid) log.Printf("pt(1) (%v, %v): %v", point.X, point.Y, most) point2 := PartTwo(grid, point) log.Printf("pt(2) (%v, %v): %v", point2.X, point2.Y, (point2.X*100)+point2.Y) }
2019/10/main.go
0.68784
0.461684
main.go
starcoder
package curve import "github.com/oasisprotocol/curve25519-voi/internal/field" const ( // CompressedPointSize is the size of a compressed point in bytes. CompressedPointSize = 32 // MontgomeryPointSize is the size of the u-coordinate of a point on // the Montgomery form in bytes. MontgomeryPointSize = 32 // RistrettoUniformSize is the size of the uniformly random bytes // required to construct a random Ristretto point. RistrettoUniformSize = 64 ) var ( // ED25519_BASEPOINT_COMPRESSED is the Ed25519 basepoint, in // CompressedEdwardsY format. ED25519_BASEPOINT_COMPRESSED = &CompressedEdwardsY{ 0x58, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, } // X25519_BASEPOINT is the X25519 basepoint, in MontgomeryPoint // format. X25519_BASEPOINT = &MontgomeryPoint{ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, } // RISTRETTO_BASEPOINT_COMPRESED is the Ristretto basepoint, in // CompressedRistretto format. RISTRETTO_BASEPOINT_COMPRESSED = &CompressedRistretto{ 0xe2, 0xf2, 0xae, 0x0a, 0x6a, 0xbc, 0x4e, 0x71, 0xa8, 0x84, 0xa9, 0x61, 0xc5, 0x00, 0x51, 0x5f, 0x58, 0xe3, 0x0b, 0x6a, 0xa5, 0x82, 0xdd, 0x8d, 0xb6, 0xa6, 0x59, 0x45, 0xe0, 0x8d, 0x2d, 0x76, } // RISTRETTO_BASEPOINT_POINT is the Ristretto basepoint, in // RistrettoPoint format. RISTRETTO_BASEPOINT_POINT = &RistrettoPoint{ inner: *ED25519_BASEPOINT_POINT, } // RISTRETTO_BASEPOINT_TABLE is the Ristretto basepoint, as a // RistrettoBasepointTable for scalar multiplication. RISTRETTO_BASEPOINT_TABLE = &RistrettoBasepointTable{ inner: *ED25519_BASEPOINT_TABLE, } ) func newEdwardsPoint(X, Y, Z, T field.Element) *EdwardsPoint { return &EdwardsPoint{ edwardsPointInner{ X: X, Y: Y, Z: Z, T: T, }, } }
curve/constants.go
0.549399
0.54583
constants.go
starcoder
package main import astar "github.com/beefsack/go-astar" type tile struct { x int y int visual rune area area creature *creature } func newTile(x, y int, a area) *tile { return &tile{ x: x, y: y, visual: ' ', area: a, } } func (t *tile) getNeighbour(direction int) *tile { switch direction { case north: return t.area.get(t.x, t.y-1) case south: return t.area.get(t.x, t.y+1) case west: return t.area.get(t.x-1, t.y) case east: return t.area.get(t.x+1, t.y) } panic("unsupported direction") } func (t *tile) getNeighbours(filter tileFilter) []*tile { neighbours := []*tile{} for i := 0; i < 4; i++ { neighbour := t.getNeighbour(i) if neighbour != nil && neighbour.visual == '.' && filter(neighbour) { neighbours = append(neighbours, neighbour) } } return neighbours } func (t *tile) PathNeighbors() []astar.Pather { neighbours := t.getNeighbours(tilesWithoutCreature) pathers := make([]astar.Pather, len(neighbours)) for i, neighbour := range neighbours { pathers[i] = neighbour } return pathers } func (t *tile) PathNeighborCost(to astar.Pather) float64 { return 1 } func (t *tile) PathEstimatedCost(to astar.Pather) float64 { toT := to.(*tile) absX := toT.x - t.x if absX < 0 { absX = -absX } absY := toT.y - t.y if absY < 0 { absY = -absY } return float64(absX + absY) } /* func (t *tile) allowNeighbours(indexes ...int) { for _, index := range indexes { t.neighbours[index] = true } } func (t *tile) isTrackTo(directions ...int) bool { for _, direction := range directions { if !t.neighbours[direction] { return false } } return true } func (t *tile) isIntersection() bool { sum := 0 for _, value := range t.neighbours { if value { sum++ } } return sum > 2 } func (t *tile) isNeighbourOut(direction int) bool { switch direction { case north: if t.area.isOut(t.x, t.y-1) { return true } case south: if t.area.isOut(t.x, t.y+1) { return true } case west: if t.area.isOut(t.x-1, t.y) { return true } case east: if t.area.isOut(t.x+1, t.y) { return true } } return false } func (t *tile) getNeighbour(direction int) *tile { if t.isNeighbourOut(direction) { return nil } switch direction { case north: return t.area.get(t.x, t.y-1) case south: return t.area.get(t.x, t.y+1) case west: return t.area.get(t.x-1, t.y) case east: return t.area.get(t.x+1, t.y) default: return nil } } func (t *tile) isAccessibleFrom(directions ...int) bool { for _, direction := range directions { neighbour := t.getNeighbour(direction) if neighbour == nil { return false } if !neighbour.isTrackTo(oppositDirection(direction)) { return false } } return true } */
day15b/tile.go
0.60288
0.498169
tile.go
starcoder
package sandbox import ( "encoding/json" ) // SandboxInsertBeamStatsRequestBeamStatsMap struct for SandboxInsertBeamStatsRequestBeamStatsMap type SandboxInsertBeamStatsRequestBeamStatsMap struct { InHttp *SandboxBeamCounts `json:"inHttp,omitempty"` InMqtt *SandboxBeamCounts `json:"inMqtt,omitempty"` InTcp *SandboxBeamCounts `json:"inTcp,omitempty"` InUdp *SandboxBeamCounts `json:"inUdp,omitempty"` OutHttp *SandboxBeamCounts `json:"outHttp,omitempty"` OutHttps *SandboxBeamCounts `json:"outHttps,omitempty"` OutMqtt *SandboxBeamCounts `json:"outMqtt,omitempty"` OutMqtts *SandboxBeamCounts `json:"outMqtts,omitempty"` OutTcp *SandboxBeamCounts `json:"outTcp,omitempty"` OutTcps *SandboxBeamCounts `json:"outTcps,omitempty"` OutUdp *SandboxBeamCounts `json:"outUdp,omitempty"` } // NewSandboxInsertBeamStatsRequestBeamStatsMap instantiates a new SandboxInsertBeamStatsRequestBeamStatsMap 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 NewSandboxInsertBeamStatsRequestBeamStatsMap() *SandboxInsertBeamStatsRequestBeamStatsMap { this := SandboxInsertBeamStatsRequestBeamStatsMap{} return &this } // NewSandboxInsertBeamStatsRequestBeamStatsMapWithDefaults instantiates a new SandboxInsertBeamStatsRequestBeamStatsMap 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 NewSandboxInsertBeamStatsRequestBeamStatsMapWithDefaults() *SandboxInsertBeamStatsRequestBeamStatsMap { this := SandboxInsertBeamStatsRequestBeamStatsMap{} return &this } // GetInHttp returns the InHttp field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInHttp() SandboxBeamCounts { if o == nil || o.InHttp == nil { var ret SandboxBeamCounts return ret } return *o.InHttp } // GetInHttpOk returns a tuple with the InHttp field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInHttpOk() (*SandboxBeamCounts, bool) { if o == nil || o.InHttp == nil { return nil, false } return o.InHttp, true } // HasInHttp returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasInHttp() bool { if o != nil && o.InHttp != nil { return true } return false } // SetInHttp gets a reference to the given SandboxBeamCounts and assigns it to the InHttp field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetInHttp(v SandboxBeamCounts) { o.InHttp = &v } // GetInMqtt returns the InMqtt field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInMqtt() SandboxBeamCounts { if o == nil || o.InMqtt == nil { var ret SandboxBeamCounts return ret } return *o.InMqtt } // GetInMqttOk returns a tuple with the InMqtt field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInMqttOk() (*SandboxBeamCounts, bool) { if o == nil || o.InMqtt == nil { return nil, false } return o.InMqtt, true } // HasInMqtt returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasInMqtt() bool { if o != nil && o.InMqtt != nil { return true } return false } // SetInMqtt gets a reference to the given SandboxBeamCounts and assigns it to the InMqtt field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetInMqtt(v SandboxBeamCounts) { o.InMqtt = &v } // GetInTcp returns the InTcp field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInTcp() SandboxBeamCounts { if o == nil || o.InTcp == nil { var ret SandboxBeamCounts return ret } return *o.InTcp } // GetInTcpOk returns a tuple with the InTcp field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInTcpOk() (*SandboxBeamCounts, bool) { if o == nil || o.InTcp == nil { return nil, false } return o.InTcp, true } // HasInTcp returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasInTcp() bool { if o != nil && o.InTcp != nil { return true } return false } // SetInTcp gets a reference to the given SandboxBeamCounts and assigns it to the InTcp field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetInTcp(v SandboxBeamCounts) { o.InTcp = &v } // GetInUdp returns the InUdp field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInUdp() SandboxBeamCounts { if o == nil || o.InUdp == nil { var ret SandboxBeamCounts return ret } return *o.InUdp } // GetInUdpOk returns a tuple with the InUdp field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetInUdpOk() (*SandboxBeamCounts, bool) { if o == nil || o.InUdp == nil { return nil, false } return o.InUdp, true } // HasInUdp returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasInUdp() bool { if o != nil && o.InUdp != nil { return true } return false } // SetInUdp gets a reference to the given SandboxBeamCounts and assigns it to the InUdp field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetInUdp(v SandboxBeamCounts) { o.InUdp = &v } // GetOutHttp returns the OutHttp field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutHttp() SandboxBeamCounts { if o == nil || o.OutHttp == nil { var ret SandboxBeamCounts return ret } return *o.OutHttp } // GetOutHttpOk returns a tuple with the OutHttp field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutHttpOk() (*SandboxBeamCounts, bool) { if o == nil || o.OutHttp == nil { return nil, false } return o.OutHttp, true } // HasOutHttp returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasOutHttp() bool { if o != nil && o.OutHttp != nil { return true } return false } // SetOutHttp gets a reference to the given SandboxBeamCounts and assigns it to the OutHttp field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetOutHttp(v SandboxBeamCounts) { o.OutHttp = &v } // GetOutHttps returns the OutHttps field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutHttps() SandboxBeamCounts { if o == nil || o.OutHttps == nil { var ret SandboxBeamCounts return ret } return *o.OutHttps } // GetOutHttpsOk returns a tuple with the OutHttps field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutHttpsOk() (*SandboxBeamCounts, bool) { if o == nil || o.OutHttps == nil { return nil, false } return o.OutHttps, true } // HasOutHttps returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasOutHttps() bool { if o != nil && o.OutHttps != nil { return true } return false } // SetOutHttps gets a reference to the given SandboxBeamCounts and assigns it to the OutHttps field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetOutHttps(v SandboxBeamCounts) { o.OutHttps = &v } // GetOutMqtt returns the OutMqtt field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutMqtt() SandboxBeamCounts { if o == nil || o.OutMqtt == nil { var ret SandboxBeamCounts return ret } return *o.OutMqtt } // GetOutMqttOk returns a tuple with the OutMqtt field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutMqttOk() (*SandboxBeamCounts, bool) { if o == nil || o.OutMqtt == nil { return nil, false } return o.OutMqtt, true } // HasOutMqtt returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasOutMqtt() bool { if o != nil && o.OutMqtt != nil { return true } return false } // SetOutMqtt gets a reference to the given SandboxBeamCounts and assigns it to the OutMqtt field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetOutMqtt(v SandboxBeamCounts) { o.OutMqtt = &v } // GetOutMqtts returns the OutMqtts field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutMqtts() SandboxBeamCounts { if o == nil || o.OutMqtts == nil { var ret SandboxBeamCounts return ret } return *o.OutMqtts } // GetOutMqttsOk returns a tuple with the OutMqtts field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutMqttsOk() (*SandboxBeamCounts, bool) { if o == nil || o.OutMqtts == nil { return nil, false } return o.OutMqtts, true } // HasOutMqtts returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasOutMqtts() bool { if o != nil && o.OutMqtts != nil { return true } return false } // SetOutMqtts gets a reference to the given SandboxBeamCounts and assigns it to the OutMqtts field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetOutMqtts(v SandboxBeamCounts) { o.OutMqtts = &v } // GetOutTcp returns the OutTcp field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutTcp() SandboxBeamCounts { if o == nil || o.OutTcp == nil { var ret SandboxBeamCounts return ret } return *o.OutTcp } // GetOutTcpOk returns a tuple with the OutTcp field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutTcpOk() (*SandboxBeamCounts, bool) { if o == nil || o.OutTcp == nil { return nil, false } return o.OutTcp, true } // HasOutTcp returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasOutTcp() bool { if o != nil && o.OutTcp != nil { return true } return false } // SetOutTcp gets a reference to the given SandboxBeamCounts and assigns it to the OutTcp field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetOutTcp(v SandboxBeamCounts) { o.OutTcp = &v } // GetOutTcps returns the OutTcps field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutTcps() SandboxBeamCounts { if o == nil || o.OutTcps == nil { var ret SandboxBeamCounts return ret } return *o.OutTcps } // GetOutTcpsOk returns a tuple with the OutTcps field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutTcpsOk() (*SandboxBeamCounts, bool) { if o == nil || o.OutTcps == nil { return nil, false } return o.OutTcps, true } // HasOutTcps returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasOutTcps() bool { if o != nil && o.OutTcps != nil { return true } return false } // SetOutTcps gets a reference to the given SandboxBeamCounts and assigns it to the OutTcps field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetOutTcps(v SandboxBeamCounts) { o.OutTcps = &v } // GetOutUdp returns the OutUdp field value if set, zero value otherwise. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutUdp() SandboxBeamCounts { if o == nil || o.OutUdp == nil { var ret SandboxBeamCounts return ret } return *o.OutUdp } // GetOutUdpOk returns a tuple with the OutUdp field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) GetOutUdpOk() (*SandboxBeamCounts, bool) { if o == nil || o.OutUdp == nil { return nil, false } return o.OutUdp, true } // HasOutUdp returns a boolean if a field has been set. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) HasOutUdp() bool { if o != nil && o.OutUdp != nil { return true } return false } // SetOutUdp gets a reference to the given SandboxBeamCounts and assigns it to the OutUdp field. func (o *SandboxInsertBeamStatsRequestBeamStatsMap) SetOutUdp(v SandboxBeamCounts) { o.OutUdp = &v } func (o SandboxInsertBeamStatsRequestBeamStatsMap) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.InHttp != nil { toSerialize["inHttp"] = o.InHttp } if o.InMqtt != nil { toSerialize["inMqtt"] = o.InMqtt } if o.InTcp != nil { toSerialize["inTcp"] = o.InTcp } if o.InUdp != nil { toSerialize["inUdp"] = o.InUdp } if o.OutHttp != nil { toSerialize["outHttp"] = o.OutHttp } if o.OutHttps != nil { toSerialize["outHttps"] = o.OutHttps } if o.OutMqtt != nil { toSerialize["outMqtt"] = o.OutMqtt } if o.OutMqtts != nil { toSerialize["outMqtts"] = o.OutMqtts } if o.OutTcp != nil { toSerialize["outTcp"] = o.OutTcp } if o.OutTcps != nil { toSerialize["outTcps"] = o.OutTcps } if o.OutUdp != nil { toSerialize["outUdp"] = o.OutUdp } return json.Marshal(toSerialize) } type NullableSandboxInsertBeamStatsRequestBeamStatsMap struct { value *SandboxInsertBeamStatsRequestBeamStatsMap isSet bool } func (v NullableSandboxInsertBeamStatsRequestBeamStatsMap) Get() *SandboxInsertBeamStatsRequestBeamStatsMap { return v.value } func (v *NullableSandboxInsertBeamStatsRequestBeamStatsMap) Set(val *SandboxInsertBeamStatsRequestBeamStatsMap) { v.value = val v.isSet = true } func (v NullableSandboxInsertBeamStatsRequestBeamStatsMap) IsSet() bool { return v.isSet } func (v *NullableSandboxInsertBeamStatsRequestBeamStatsMap) Unset() { v.value = nil v.isSet = false } func NewNullableSandboxInsertBeamStatsRequestBeamStatsMap(val *SandboxInsertBeamStatsRequestBeamStatsMap) *NullableSandboxInsertBeamStatsRequestBeamStatsMap { return &NullableSandboxInsertBeamStatsRequestBeamStatsMap{value: val, isSet: true} } func (v NullableSandboxInsertBeamStatsRequestBeamStatsMap) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableSandboxInsertBeamStatsRequestBeamStatsMap) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
openapi/sandbox/model_sandbox_insert_beam_stats_request_beam_stats_map.go
0.696371
0.58261
model_sandbox_insert_beam_stats_request_beam_stats_map.go
starcoder
package main import ( "github.com/ByteArena/box2d" "github.com/wdevore/Ranger-Go-IGE/api" "github.com/wdevore/Ranger-Go-IGE/engine/rendering/color" "github.com/wdevore/Ranger-Go-IGE/extras/shapes" ) type fencePhysicsComponent struct { physicsComponent bottomLineNode api.INode rightLineNode api.INode topLineNode api.INode leftLineNode api.INode categoryBits uint16 // I am a... maskBits uint16 // I can collide with a... } func newFencePhysicsComponent() *fencePhysicsComponent { o := new(fencePhysicsComponent) return o } func (p *fencePhysicsComponent) Build(world api.IWorld, parent api.INode, phyWorld *box2d.B2World, position api.IPoint) { p.buildNodes(world, parent) p.buildPhysics(phyWorld, position) } func (p *fencePhysicsComponent) buildPhysics(phyWorld *box2d.B2World, position api.IPoint) { p.position = position // ------------------------------------------- // A body def used to create bodies bDef := box2d.MakeB2BodyDef() bDef.Type = box2d.B2BodyType.B2_staticBody // Set the position of the Body px := position.X() py := position.Y() bDef.Position.Set( float64(px), float64(py), ) // An instance of a body to contain Fixtures. // This body represents the entire fence (i.e. all four sides) p.b2Body = phyWorld.CreateBody(&bDef) fd := box2d.MakeB2FixtureDef() fd.Filter.CategoryBits = p.categoryBits fd.Filter.MaskBits = p.maskBits // ------------------------------------------------------------ // Bottom fixture px = p.bottomLineNode.Position().X() py = p.bottomLineNode.Position().Y() tln := p.bottomLineNode.(*shapes.MonoHLineNode) halfLength := float64(tln.HalfLength()) b2Shape := box2d.MakeB2EdgeShape() // Positioning and size relative to the body b2Shape.Set( box2d.MakeB2Vec2(-halfLength, float64(py)), box2d.MakeB2Vec2(halfLength, float64(py))) fd.Shape = &b2Shape p.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body // ------------------------------------------------------------ // Right fixture px = p.rightLineNode.Position().X() py = p.rightLineNode.Position().Y() b2Shape = box2d.MakeB2EdgeShape() // Positioning and size relative to the body b2Shape.Set( box2d.MakeB2Vec2(float64(px), -halfLength), box2d.MakeB2Vec2(float64(px), halfLength)) fd.Shape = &b2Shape p.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body // ------------------------------------------------------------ // Top fixture px = p.topLineNode.Position().X() py = p.topLineNode.Position().Y() b2Shape = box2d.MakeB2EdgeShape() b2Shape.Set( box2d.MakeB2Vec2(-halfLength, float64(py)), box2d.MakeB2Vec2(halfLength, float64(py))) fd.Shape = &b2Shape p.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body // ------------------------------------------------------------ // Left fixture px = p.leftLineNode.Position().X() py = p.leftLineNode.Position().Y() b2Shape = box2d.MakeB2EdgeShape() b2Shape.Set( box2d.MakeB2Vec2(float64(px), -halfLength), box2d.MakeB2Vec2(float64(px), halfLength)) fd.Shape = &b2Shape p.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body } func (p *fencePhysicsComponent) buildNodes(world api.IWorld, parent api.INode) error { var err error scaleX := float32(130.0) scaleY := float32(75.0) p.bottomLineNode, err = shapes.NewMonoHLineNode("Bottom", world, parent) if err != nil { return err } p.bottomLineNode.SetScale(scaleX) p.bottomLineNode.SetPosition(0.0, -scaleY/2) ghl := p.bottomLineNode.(*shapes.MonoHLineNode) ghl.SetColor(color.NewPaletteInt64(color.Yellow)) p.rightLineNode, err = shapes.NewMonoVLineNode("Right", world, parent) if err != nil { return err } p.rightLineNode.SetScale(scaleY) p.rightLineNode.SetPosition(scaleX/2, 0.0) ghv := p.rightLineNode.(*shapes.MonoVLineNode) ghv.SetColor(color.NewPaletteInt64(color.Yellow)) p.topLineNode, err = shapes.NewMonoHLineNode("Top", world, parent) if err != nil { return err } p.topLineNode.SetScale(scaleX) p.topLineNode.SetPosition(0.0, scaleY/2) ghl = p.topLineNode.(*shapes.MonoHLineNode) ghl.SetColor(color.NewPaletteInt64(color.Yellow)) p.leftLineNode, err = shapes.NewMonoVLineNode("Left", world, parent) if err != nil { return err } p.leftLineNode.SetScale(scaleY) p.leftLineNode.SetPosition(-scaleX/2, 0.0) ghv = p.leftLineNode.(*shapes.MonoVLineNode) ghv.SetColor(color.NewPaletteInt64(color.Yellow)) return nil } func (p *fencePhysicsComponent) ConfigureFilter(categoryBits, maskBits uint16) { p.categoryBits = categoryBits p.maskBits = maskBits }
examples/complex/physics/complex/c2_zones/fence_physics_component.go
0.681409
0.463991
fence_physics_component.go
starcoder
package integration import ( "errors" "testing" "time" "github.com/devhossamali/ari" "github.com/devhossamali/ari/rid" tmock "github.com/stretchr/testify/mock" ) var _ = tmock.Anything var nonEmpty = tmock.MatchedBy(func(s string) bool { return s != "" }) func TestChannelData(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { var expected ari.ChannelData expected.ID = "c1" expected.Name = "channe1" expected.State = "Up" m.Channel.On("Data", key).Return(&expected, nil) cd, err := cl.Channel().Data(key) if err != nil { t.Errorf("Unexpected error in remote Data call %s", err) } if cd == nil || cd.ID != expected.ID || cd.Name != expected.Name || cd.State != expected.State { t.Errorf("Expected channel data %v, got %v", expected, cd) } m.Shutdown() m.Channel.AssertCalled(t, "Data", key) }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("Unknown error") m.Channel.On("Data", key).Return(nil, expected) cd, err := cl.Channel().Data(key) if err == nil { t.Errorf("Expected error in remote Data call") } if cd != nil { t.Errorf("Expected channel data %v, got %v", nil, cd) } m.Shutdown() m.Channel.AssertCalled(t, "Data", key) }) } func TestChannelAnswer(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Answer", key).Return(nil) err := cl.Channel().Answer(key) if err != nil { t.Errorf("Unexpected error in remote Data call %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Answer", key) }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("Unknown error") m.Channel.On("Answer", key).Return(expected) err := cl.Channel().Answer(key) if err == nil { t.Errorf("Expected error in remote Answer call") } m.Shutdown() m.Channel.AssertCalled(t, "Answer", key) }) } func TestChannelBusy(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Busy", key).Return(nil) err := cl.Channel().Busy(key) if err != nil { t.Errorf("Unexpected error in remote Busy call %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Busy", key) }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("Unknown error") m.Channel.On("Busy", key).Return(expected) err := cl.Channel().Busy(key) if err == nil { t.Errorf("Expected error in remote Busy call") } m.Shutdown() m.Channel.AssertCalled(t, "Busy", key) }) } func TestChannelCongestion(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Congestion", key).Return(nil) err := cl.Channel().Congestion(key) if err != nil { t.Errorf("Unexpected error in remote Congestion call %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Congestion", key) }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("Unknown error") m.Channel.On("Congestion", key).Return(expected) err := cl.Channel().Congestion(key) if err == nil { t.Errorf("Expected error in remote Congestion call") } m.Shutdown() m.Channel.AssertCalled(t, "Congestion", key) }) } func TestChannelHangup(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("noReason", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Hangup", key, "").Return(nil) err := cl.Channel().Hangup(key, "") if err != nil { t.Errorf("Unexpected error in remote Hangup call %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Hangup", key, "") }) runTest("aReason", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Hangup", key, "busy").Return(nil) err := cl.Channel().Hangup(key, "busy") if err != nil { t.Errorf("Unexpected error in remote Hangup call %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Hangup", key, "busy") }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("Unknown error") m.Channel.On("Hangup", key, "busy").Return(expected) err := cl.Channel().Hangup(key, "busy") if err == nil { t.Errorf("Expected error in remote Hangup call") } m.Shutdown() m.Channel.AssertCalled(t, "Hangup", key, "busy") }) } func TestChannelList(t *testing.T, s Server) { runTest("empty", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("List", (*ari.Key)(nil)).Return([]*ari.Key{}, nil) ret, err := cl.Channel().List(nil) if err != nil { t.Errorf("Unexpected error in remote List call: %s", err) } if len(ret) != 0 { t.Errorf("Expected return length to be 0, got %d", len(ret)) } m.Shutdown() m.Channel.AssertCalled(t, "List", (*ari.Key)(nil)) }) runTest("nonEmpty", t, s, func(t *testing.T, m *mock, cl ari.Client) { h1 := ari.NewKey(ari.ChannelKey, "h1") h2 := ari.NewKey(ari.ChannelKey, "h2") m.Channel.On("List", (*ari.Key)(nil)).Return([]*ari.Key{h1, h2}, nil) ret, err := cl.Channel().List(nil) if err != nil { t.Errorf("Unexpected error in remote List call: %s", err) } if len(ret) != 2 { t.Errorf("Expected return length to be 2, got %d", len(ret)) } m.Shutdown() m.Channel.AssertCalled(t, "List", (*ari.Key)(nil)) }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("List", (*ari.Key)(nil)).Return(nil, errors.New("unknown error")) ret, err := cl.Channel().List(nil) if err == nil { t.Errorf("Expected error in remote List call") } if len(ret) != 0 { t.Errorf("Expected return length to be 0, got %d", len(ret)) } m.Shutdown() m.Channel.AssertCalled(t, "List", (*ari.Key)(nil)) }) } func TestChannelMute(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("both-ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Mute", key, ari.DirectionBoth).Return(nil) err := cl.Channel().Mute(key, ari.DirectionBoth) if err != nil { t.Errorf("Unexpected error in remote Mute call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Mute", key, ari.DirectionBoth) }) runTest("both-err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Mute", key, ari.DirectionBoth).Return(errors.New("error")) err := cl.Channel().Mute(key, ari.DirectionBoth) if err == nil { t.Errorf("Expected error in remote Mute call") } m.Shutdown() m.Channel.AssertCalled(t, "Mute", key, ari.DirectionBoth) }) runTest("none-ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Mute", key, ari.DirectionNone).Return(nil) err := cl.Channel().Mute(key, ari.DirectionNone) if err != nil { t.Errorf("Unexpected error in remote Mute call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Mute", key, ari.DirectionNone) }) runTest("none-err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Mute", key, ari.DirectionNone).Return(errors.New("error")) err := cl.Channel().Mute(key, ari.DirectionNone) if err == nil { t.Errorf("Expected error in remote Mute call") } m.Shutdown() m.Channel.AssertCalled(t, "Mute", key, ari.DirectionNone) }) } func TestChannelUnmute(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("both-ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Unmute", key, ari.DirectionBoth).Return(nil) err := cl.Channel().Unmute(key, ari.DirectionBoth) if err != nil { t.Errorf("Unexpected error in remote Unmute call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Unmute", key, ari.DirectionBoth) }) runTest("both-err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Unmute", key, ari.DirectionBoth).Return(errors.New("error")) err := cl.Channel().Unmute(key, ari.DirectionBoth) if err == nil { t.Errorf("Expected error in remote Unmute call") } m.Shutdown() m.Channel.AssertCalled(t, "Unmute", key, ari.DirectionBoth) }) runTest("none-ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Unmute", key, ari.DirectionNone).Return(nil) err := cl.Channel().Unmute(key, ari.DirectionNone) if err != nil { t.Errorf("Unexpected error in remote Unmute call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Unmute", key, ari.DirectionNone) }) runTest("none-err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Unmute", key, ari.DirectionNone).Return(errors.New("error")) err := cl.Channel().Unmute(key, ari.DirectionNone) if err == nil { t.Errorf("Expected error in remote Unmute call") } m.Shutdown() m.Channel.AssertCalled(t, "Unmute", key, ari.DirectionNone) }) } func TestChannelMOH(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("MOH", key, "music").Return(nil) err := cl.Channel().MOH(key, "music") if err != nil { t.Errorf("Unexpected error in remote MOH call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "MOH", key, "music") }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("MOH", key, "music").Return(errors.New("error")) err := cl.Channel().MOH(key, "music") if err == nil { t.Errorf("Expected error in remote Mute call") } m.Shutdown() m.Channel.AssertCalled(t, "MOH", key, "music") }) } func TestChannelStopMOH(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopMOH", key).Return(nil) err := cl.Channel().StopMOH(key) if err != nil { t.Errorf("Unexpected error in remote StopMOH call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "StopMOH", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopMOH", key).Return(errors.New("error")) err := cl.Channel().StopMOH(key) if err == nil { t.Errorf("Expected error in remote StopMOH call") } m.Shutdown() m.Channel.AssertCalled(t, "StopMOH", key) }) } func TestChannelCreate(t *testing.T, s Server) { runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { req := ari.ChannelCreateRequest{} req.App = "App" req.ChannelID = "1234" chkey := ari.NewKey(ari.ChannelKey, "ch2") expected := ari.NewChannelHandle(chkey, m.Channel, nil) m.Channel.On("Create", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, req).Return(expected, nil) h, err := cl.Channel().Create(nil, req) if err != nil { t.Errorf("Unexpected error in remote Create call: %s", err) } if h == nil { t.Errorf("Expected non-nil channel handle") } else if h.ID() != req.ChannelID { t.Errorf("Expected handle id '%s', got '%s'", h.ID(), req.ChannelID) } m.Shutdown() m.Channel.AssertCalled(t, "Create", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, ari.ChannelCreateRequest{App: "App", ChannelID: "1234"}) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { req := ari.ChannelCreateRequest{} req.App = "App" req.ChannelID = "1234" m.Channel.On("Create", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, req).Return(nil, errors.New("error")) h, err := cl.Channel().Create(nil, req) if err == nil { t.Errorf("Expected error in remote Create call") } if h != nil { t.Errorf("Expected nil channel handle") } m.Shutdown() m.Channel.AssertCalled(t, "Create", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, ari.ChannelCreateRequest{App: "App", ChannelID: "1234"}) }) } func TestChannelContinue(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Continue", key, "ctx1", "ext1", 0).Return(nil) err := cl.Channel().Continue(key, "ctx1", "ext1", 0) if err != nil { t.Errorf("Unexpected error in remote Continue call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Continue", key, "ctx1", "ext1", 0) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Continue", key, "ctx1", "ext1", 0).Return(errors.New("error")) err := cl.Channel().Continue(key, "ctx1", "ext1", 0) if err == nil { t.Errorf("Expected error in remote Continue call") } m.Shutdown() m.Channel.AssertCalled(t, "Continue", key, "ctx1", "ext1", 0) }) } func TestChannelDial(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Dial", key, "caller", 5*time.Second).Return(nil) err := cl.Channel().Dial(key, "caller", 5*time.Second) if err != nil { t.Errorf("Unexpected error in remote Dial call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Dial", key, "caller", 5*time.Second) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Dial", key, "caller", 5*time.Second).Return(errors.New("error")) err := cl.Channel().Dial(key, "caller", 5*time.Second) if err == nil { t.Errorf("Expected error in remote Dial call") } m.Shutdown() m.Channel.AssertCalled(t, "Dial", key, "caller", 5*time.Second) }) } func TestChannelHold(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Hold", key).Return(nil) err := cl.Channel().Hold(key) if err != nil { t.Errorf("Unexpected error in remote Hold call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Hold", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Hold", key).Return(errors.New("error")) err := cl.Channel().Hold(key) if err == nil { t.Errorf("Expected error in remote Hold call") } m.Shutdown() m.Channel.AssertCalled(t, "Hold", key) }) } func TestChannelStopHold(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopHold", key).Return(nil) err := cl.Channel().StopHold(key) if err != nil { t.Errorf("Unexpected error in remote StopHold call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "StopHold", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopHold", key).Return(errors.New("error")) err := cl.Channel().StopHold(key) if err == nil { t.Errorf("Expected error in remote StopHold call") } m.Shutdown() m.Channel.AssertCalled(t, "StopHold", key) }) } func TestChannelRing(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Ring", key).Return(nil) err := cl.Channel().Ring(key) if err != nil { t.Errorf("Unexpected error in remote Ring call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Ring", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Ring", key).Return(errors.New("error")) err := cl.Channel().Ring(key) if err == nil { t.Errorf("Expected error in remote Ring call") } m.Shutdown() m.Channel.AssertCalled(t, "Ring", key) }) } func TestChannelSilence(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Silence", key).Return(nil) err := cl.Channel().Silence(key) if err != nil { t.Errorf("Unexpected error in remote Silence call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "Silence", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Silence", key).Return(errors.New("error")) err := cl.Channel().Silence(key) if err == nil { t.Errorf("Expected error in remote Silence call") } m.Shutdown() m.Channel.AssertCalled(t, "Silence", key) }) } func TestChannelStopSilence(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopSilence", key).Return(nil) err := cl.Channel().StopSilence(key) if err != nil { t.Errorf("Unexpected error in remote StopSilence call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "StopSilence", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopSilence", key).Return(errors.New("error")) err := cl.Channel().StopSilence(key) if err == nil { t.Errorf("Expected error in remote StopSilence call") } m.Shutdown() m.Channel.AssertCalled(t, "StopSilence", key) }) } func TestChannelStopRing(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopRing", key).Return(nil) err := cl.Channel().StopRing(key) if err != nil { t.Errorf("Unexpected error in remote StopRing call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "StopRing", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("StopRing", key).Return(errors.New("error")) err := cl.Channel().StopRing(key) if err == nil { t.Errorf("Expected error in remote StopRing call") } m.Shutdown() m.Channel.AssertCalled(t, "StopRing", key) }) } func TestChannelOriginate(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := ari.NewChannelHandle(key, m.Channel, nil) var req ari.OriginateRequest req.App = "App" req.ChannelID = "1234" m.Channel.On("Originate", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, req).Return(expected, nil) h, err := cl.Channel().Originate(nil, req) if err != nil { t.Errorf("Unexpected error in remote Originate call: %s", err) } if h == nil { t.Error("Expected non-nil handle") } else if h.ID() != req.ChannelID { t.Errorf("Expected handle id '%s', got '%s'", h.ID(), req.ChannelID) } m.Shutdown() m.Channel.AssertCalled(t, "Originate", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, req) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { var req ari.OriginateRequest req.App = "App" req.ChannelID = "1234" m.Channel.On("Originate", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, req).Return(nil, errors.New("error")) h, err := cl.Channel().Originate(nil, req) if err == nil { t.Errorf("Expected error in remote Originate call") } if h != nil { t.Error("Expected nil handle") } m.Shutdown() m.Channel.AssertCalled(t, "Originate", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, req) }) } func TestChannelPlay(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") var cd ari.ChannelData cd.ID = "c1" cd.Name = "channe1" cd.State = "Up" runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { pbkey := ari.NewKey(ari.PlaybackKey, "pb1") expected := ari.NewPlaybackHandle(pbkey, m.Playback, nil) m.Channel.On("Data", key).Return(&cd, nil) m.Channel.On("Play", key, "playbackID", "sound:hello").Return(expected, nil) h, err := cl.Channel().Play(key, "playbackID", "sound:hello") if err != nil { t.Errorf("Unexpected error in remote Play call: %s", err) } if h == nil { t.Error("Expected non-nil handle") } else if h.ID() != "playbackID" { t.Errorf("Expected handle id '%s', got '%s'", h.ID(), "playbackID") } m.Shutdown() m.Channel.AssertCalled(t, "Play", key, "playbackID", "sound:hello") }) runTest("no-id", t, s, func(t *testing.T, m *mock, cl ari.Client) { pbkey := ari.NewKey(ari.PlaybackKey, "pb1") expected := ari.NewPlaybackHandle(pbkey, m.Playback, nil) m.Channel.On("Data", key).Return(&cd, nil) m.Channel.On("Play", key, nonEmpty, "sound:hello").Return(expected, nil) h, err := cl.Channel().Play(key, "", "sound:hello") if err != nil { t.Errorf("Unexpected error in remote Play call: %s", err) } if h == nil { t.Error("Expected non-nil handle") } m.Shutdown() m.Channel.AssertCalled(t, "Play", key, nonEmpty, "sound:hello") }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("Data", key).Return(&cd, nil) m.Channel.On("Play", key, "playbackID", "sound:hello").Return(nil, errors.New("error")) h, err := cl.Channel().Play(key, "playbackID", "sound:hello") if err == nil { t.Errorf("Expected error in remote Play call") } if h != nil { t.Error("Expected nil handle") } m.Shutdown() m.Channel.AssertCalled(t, "Play", key, "playbackID", "sound:hello") }) } func TestChannelRecord(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { var opts *ari.RecordingOptions lrkey := ari.NewKey(ari.LiveRecordingKey, "lrh1") expected := ari.NewLiveRecordingHandle(lrkey, m.LiveRecording, nil) m.Channel.On("Record", key, "recordid", opts).Return(expected, nil) h, err := cl.Channel().Record(key, "recordid", nil) if err != nil { t.Errorf("Unexpected error in remote Record call: %s", err) } if h == nil { t.Error("Expected non-nil handle") } else if h.ID() != "recordid" { t.Errorf("Expected handle id '%s', got '%s'", "recordid", h.ID()) } m.Shutdown() m.Channel.AssertCalled(t, "Record", key, "recordid", opts) }) runTest("no-id", t, s, func(t *testing.T, m *mock, cl ari.Client) { var opts *ari.RecordingOptions lrkey := ari.NewKey(ari.LiveRecordingKey, "lrh1") expected := ari.NewLiveRecordingHandle(lrkey, m.LiveRecording, nil) m.Channel.On("Record", key, nonEmpty, opts).Return(expected, nil) h, err := cl.Channel().Record(key, "", nil) if err != nil { t.Errorf("Unexpected error in remote Record call: %s", err) } if h == nil { t.Error("Expected non-nil handle") } m.Shutdown() m.Channel.AssertCalled(t, "Record", key, nonEmpty, opts) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { var opts *ari.RecordingOptions m.Channel.On("Record", key, "recordid", opts).Return(nil, errors.New("error")) h, err := cl.Channel().Record(key, "recordid", nil) if err == nil { t.Errorf("Expected error in remote Record call") } if h != nil { t.Error("Expected nil handle") } m.Shutdown() m.Channel.AssertCalled(t, "Record", key, "recordid", opts) }) } func TestChannelSnoop(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { var opts *ari.SnoopOptions chkey := ari.NewKey(ari.ChannelKey, "ch2") expected := ari.NewChannelHandle(chkey, m.Channel, nil) m.Channel.On("Snoop", key, "snoopID", opts).Return(expected, nil) h, err := cl.Channel().Snoop(key, "snoopID", nil) if err != nil { t.Errorf("Unexpected error in remote Snoop call: %s", err) } if h == nil { t.Error("Expected non-nil handle") } else if h.ID() != "snoopID" { t.Errorf("Expected handle id '%s', got '%s'", "snoopID", h.ID()) } m.Shutdown() m.Channel.AssertCalled(t, "Snoop", key, "snoopID", opts) }) runTest("no-id", t, s, func(t *testing.T, m *mock, cl ari.Client) { var opts *ari.SnoopOptions chkey := ari.NewKey(ari.ChannelKey, "ch2") expected := ari.NewChannelHandle(chkey, m.Channel, nil) m.Channel.On("Snoop", key, tmock.Anything, opts).Return(expected, nil) h, err := cl.Channel().Snoop(key, "", nil) if err != nil { t.Errorf("Unexpected error in remote Snoop call: %s", err) } if h == nil { t.Error("Expected non-nil handle") } m.Shutdown() m.Channel.AssertCalled(t, "Snoop", key, tmock.Anything, opts) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { var opts *ari.SnoopOptions m.Channel.On("Snoop", key, "ch2", opts).Return(nil, errors.New("error")) h, err := cl.Channel().Snoop(key, "ch2", nil) if err == nil { t.Errorf("Expected error in remote Snoop call") } if h != nil { t.Error("Expected nil handle") } m.Shutdown() m.Channel.AssertCalled(t, "Snoop", key, "ch2", opts) }) } func TestChannelExternalMedia(t *testing.T, s Server) { runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { key := ari.NewKey(ari.ChannelKey, rid.New(rid.Channel)) opts := ari.ExternalMediaOptions{ ChannelID: key.ID, App: cl.ApplicationName(), ExternalHost: "localhost:1234", Format: "slin16", } m.Channel.On("ExternalMedia", nil, opts).Return(nil, errors.New("error")) h, err := cl.Channel().ExternalMedia(nil, opts) if err != nil { t.Errorf("error calling ExternalMedia: %v", err) } else if h.ID() != key.ID { t.Errorf("expected handle id '%s', got '%s'", key.ID, h.ID()) } m.Shutdown() m.Channel.AssertCalled(t, "ExternalMedia", nil, opts) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { key := ari.NewKey(ari.ChannelKey, rid.New(rid.Channel)) opts := ari.ExternalMediaOptions{ ChannelID: key.ID, App: cl.ApplicationName(), ExternalHost: "localhost:1234", // Format: "slin16", // Format is required } m.Channel.On("ExternalMedia", nil, opts).Return(nil, errors.New("error")) h, err := cl.Channel().ExternalMedia(nil, opts) if err == nil { t.Error("expected error in ExternalMedia call, but got nil") } if h != nil { t.Errorf("expected nil channel handle, but got key with ID: %s", h.ID()) } m.Shutdown() m.Channel.AssertCalled(t, "ExternalMedia", nil, opts) }) } func TestChannelSendDTMF(t *testing.T, s Server) { key := ari.NewKey(ari.ChannelKey, "c1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("SendDTMF", key, "1", &ari.DTMFOptions{}).Return(nil) err := cl.Channel().SendDTMF(key, "1", nil) if err != nil { t.Errorf("Unexpected error in remote SendDTMF call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "SendDTMF", key, "1", &ari.DTMFOptions{}) }) runTest("with-options", t, s, func(t *testing.T, m *mock, cl ari.Client) { opts := &ari.DTMFOptions{ After: 4 * time.Second, } m.Channel.On("SendDTMF", key, "1", opts).Return(nil) err := cl.Channel().SendDTMF(key, "1", opts) if err != nil { t.Errorf("Unexpected error in remote SendDTMF call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "SendDTMF", key, "1", opts) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("SendDTMF", key, "1", &ari.DTMFOptions{}).Return(errors.New("err")) err := cl.Channel().SendDTMF(key, "1", nil) if err == nil { t.Errorf("Expected error in remote SendDTMF call") } m.Shutdown() m.Channel.AssertCalled(t, "SendDTMF", key, "1", &ari.DTMFOptions{}) }) } func TestChannelVariableGet(t *testing.T, s Server) { runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("GetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1").Return("value", nil) val, err := cl.Channel().GetVariable(nil, "v1") if err != nil { t.Errorf("Unexpected error in remote Variables Get call: %s", err) } if val != "value" { t.Errorf("Expected channel variable to be 'value', got '%s'", val) } m.Shutdown() m.Channel.AssertCalled(t, "GetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1") }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("GetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1").Return("", errors.New("1")) val, err := cl.Channel().GetVariable(nil, "v1") if err == nil { t.Errorf("Expected error in remote Variables Get call") } if val != "" { t.Errorf("Expected empty value, got '%s'", val) } m.Shutdown() m.Channel.AssertCalled(t, "GetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1") }) } func TestChannelVariableSet(t *testing.T, s Server) { runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("SetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1", "value").Return(nil) err := cl.Channel().SetVariable(nil, "v1", "value") if err != nil { t.Errorf("Unexpected error in remote Variables Set call: %s", err) } m.Shutdown() m.Channel.AssertCalled(t, "SetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1", "value") }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Channel.On("SetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1", "value").Return(errors.New("error")) err := cl.Channel().SetVariable(nil, "v1", "value") if err == nil { t.Errorf("Expected error in remote Variables Set call") } m.Shutdown() m.Channel.AssertCalled(t, "SetVariable", &ari.Key{Kind: "", ID: "", Node: "", Dialog: "", App: ""}, "v1", "value") }) }
internal/integration/channel.go
0.553505
0.466481
channel.go
starcoder
package solidserver import ( "encoding/json" "fmt" "github.com/hashicorp/terraform/helper/schema" "log" "net/url" "regexp" "strconv" "strings" ) func dataSourcednsview() *schema.Resource { return &schema.Resource{ Read: dataSourcednsviewRead, Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Description: "The name of the DNS view.", Required: true, }, "dnsserver": { Type: schema.TypeString, Description: "The name of DNS server or DNS SMART hosting the DNS view to create.", Required: true, }, "order": { Type: schema.TypeString, Description: "The level of the DNS view, where 0 represents the highest level in the views hierarchy.", Computed: true, }, "recursion": { Type: schema.TypeBool, Description: "The recursion status of the DNS view.", Computed: true, }, "forward": { Type: schema.TypeString, Description: "The forwarding mode of the DNS view (disabled if empty).", Computed: true, }, "forwarders": { Type: schema.TypeList, Description: "The IP address list of the forwarder(s) configured on the DNS view.", Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, "allow_transfer": { Type: schema.TypeList, Description: "A list of network prefixes allowed to query the DNS view for zone transfert (named ACL(s) are not supported using this provider).", Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, "allow_query": { Type: schema.TypeList, Description: "A list of network prefixes allowed to query the DNS view (named ACL(s) are not supported using this provider).", Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, "allow_recursion": { Type: schema.TypeList, Description: "A list of network prefixes allowed to query the DNS view for recursion (named ACL(s) are not supported using this provider).", Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, "match_clients": { Type: schema.TypeList, Description: "A list of network prefixes used to match the clients of the view (named ACL(s) are not supported using this provider).", Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, "match_to": { Type: schema.TypeList, Description: "A list of network prefixes used to match the traffic to the view (named ACL(s) are not supported using this provider).", Computed: true, Elem: &schema.Schema{ Type: schema.TypeString, }, }, "class": { Type: schema.TypeString, Description: "The class associated to the DNS view.", Computed: true, }, "class_parameters": { Type: schema.TypeMap, Description: "The class parameters associated to the DNS view.", Computed: true, }, }, } } func dataSourcednsviewRead(d *schema.ResourceData, meta interface{}) error { s := meta.(*SOLIDserver) d.SetId("") // Building parameters parameters := url.Values{} parameters.Add("WHERE", "dns_name='"+d.Get("dnsserver").(string)+"' AND dnsview_name='"+d.Get("name").(string)+"'") // Sending the read request resp, body, err := s.Request("get", "rest/dns_view_list", &parameters) if err == nil { var buf [](map[string]interface{}) json.Unmarshal([]byte(body), &buf) // Checking the answer if resp.StatusCode == 200 && len(buf) > 0 { d.SetId(buf[0]["dnsview_id"].(string)) d.Set("name", strings.ToLower(buf[0]["dnsview_name"].(string))) d.Set("dnsserver", buf[0]["dns_name"].(string)) viewOrder, _ := strconv.Atoi(buf[0]["dnsview_order"].(string)) d.Set("order", viewOrder) // Updating recursion mode if buf[0]["dnsview_recursion"].(string) == "yes" { d.Set("recursion", true) } else { d.Set("recursion", false) } // Updating forward mode forward, forwardErr := dnsparamget(buf[0]["dns_name"].(string), d.Id(), "forward", meta) if forwardErr == nil { if forward == "" { d.Set("forward", "none") } else { d.Set("forward", strings.ToLower(forward)) } } else { log.Printf("[DEBUG] SOLIDServer - Unable to DNS view's forward mode (oid): %s\n", d.Id()) d.Set("forward", "none") } // Updating forwarder information forwarders, forwardersErr := dnsparamget(buf[0]["dns_name"].(string), d.Id(), "forwarders", meta) if forwardersErr == nil { if forwarders != "" { d.Set("forwarders", toStringArrayInterface(strings.Split(strings.TrimSuffix(forwarders, ";"), ";"))) } } else { log.Printf("[DEBUG] SOLIDServer - Unable to DNS view's forwarders list (oid): %s\n", d.Id()) d.Set("forwarders", make([]string, 0)) } // Only look for network prefixes, acl(s) names will be ignored during the sync process with SOLIDserver // Building allow_transfer ACL if buf[0]["dnsview_allow_transfer"].(string) != "" { allowTransfers := []string{} for _, allowTransfer := range toStringArrayInterface(strings.Split(strings.TrimSuffix(buf[0]["dnsview_allow_transfer"].(string), ";"), ";")) { if match, _ := regexp.MatchString(regexpNetworkAcl, allowTransfer.(string)); match == true { allowTransfers = append(allowTransfers, allowTransfer.(string)) } } d.Set("allow_transfer", allowTransfers) } // Building allow_query ACL if buf[0]["dnsview_allow_query"].(string) != "" { allowQueries := []string{} for _, allowQuery := range toStringArrayInterface(strings.Split(strings.TrimSuffix(buf[0]["dnsview_allow_query"].(string), ";"), ";")) { if match, _ := regexp.MatchString(regexpNetworkAcl, allowQuery.(string)); match == true { allowQueries = append(allowQueries, allowQuery.(string)) } } d.Set("allow_query", allowQueries) } // Building allow_recursion ACL if buf[0]["dnsview_allow_recursion"].(string) != "" { allowRecursions := []string{} for _, allowRecursion := range toStringArrayInterface(strings.Split(strings.TrimSuffix(buf[0]["dnsview_allow_recursion"].(string), ";"), ";")) { if match, _ := regexp.MatchString(regexpNetworkAcl, allowRecursion.(string)); match == true { allowRecursions = append(allowRecursions, allowRecursion.(string)) } } d.Set("allow_recursion", allowRecursions) } // Updating ACL information if buf[0]["dnsview_match_clients"].(string) != "" { matchClients := []string{} for _, matchClient := range toStringArrayInterface(strings.Split(strings.TrimSuffix(buf[0]["dnsview_match_clients"].(string), ";"), ";")) { if match, _ := regexp.MatchString(regexpNetworkAcl, matchClient.(string)); match == true { matchClients = append(matchClients, matchClient.(string)) } } d.Set("match_clients", matchClients) } if buf[0]["dnsview_match_to"].(string) != "" { matchTos := []string{} for _, matchTo := range toStringArrayInterface(strings.Split(strings.TrimSuffix(buf[0]["dnsview_match_to"].(string), ";"), ";")) { if match, _ := regexp.MatchString(regexpNetworkAcl, matchTo.(string)); match == true { matchTos = append(matchTos, matchTo.(string)) } } d.Set("match_to", matchTos) } d.Set("class", buf[0]["dnsview_class_name"].(string)) // Setting local class_parameters retrievedClassParameters, _ := url.ParseQuery(buf[0]["dnsview_class_parameters"].(string)) computedClassParameters := map[string]string{} for ck := range retrievedClassParameters { computedClassParameters[ck] = retrievedClassParameters[ck][0] } d.Set("class_parameters", computedClassParameters) return nil } if len(buf) > 0 { if errMsg, errExist := buf[0]["errmsg"].(string); errExist { log.Printf("[DEBUG] SOLIDServer - Unable read information from DNS view: %s (%s)\n", d.Get("name"), errMsg) } } else { // Log the error log.Printf("[DEBUG] SOLIDServer - Unable to read information from DNS view: %s\n", d.Get("name")) } // Reporting a failure return fmt.Errorf("SOLIDServer - Unable to find DNS view: %s\n", d.Get("name")) } // Reporting a failure return err }
solidserver/data_source_dns_view.go
0.529263
0.410579
data_source_dns_view.go
starcoder