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 xtime import ( "fmt" "strconv" "strings" "time" ) // The xtime package contains types and functions that provide supplementary functionality to the // built in standard library 'time' package. It also provides some additional time-related // functionality and types that help things like output. // DurationFormat is an "enum" of the different display time formats. A DurationFormat can be used in // conjunction with FormatDuration to control how some output duration is displayed. type DurationFormat int // All possible duration formats. const ( FormatDecimal DurationFormat = iota FormatText ) var formats = map[string]DurationFormat{ "decimal": FormatDecimal, "text": FormatText, } // UnmarshalTOML takes a raw TOML time format value and attempts to parse the value as a // DurationFormat. The value passed to this method should be a byte array of a quoted string (i.e. // the raw TOML value), the method will remove the quotes. func (f *DurationFormat) UnmarshalTOML(bytes []byte) error { text, err := strconv.Unquote(string(bytes)) if err != nil { return err } text = strings.ToLower(text) format, ok := formats[text] if !ok { return fmt.Errorf("xtime: Invalid DurationFormat '%s'", text) } *f = format return nil } // Weekday is a type used to extend the built-in 'time.Weekday' type to add new methods to help with // things like parsing weekday strings into a stricter type. type Weekday time.Weekday // All possible Weekday values. const ( Sunday Weekday = iota Monday Tuesday Wednesday Thursday Friday Saturday ) var weekdays = map[string]Weekday{ "sunday": Sunday, "monday": Monday, "tuesday": Tuesday, "wednesday": Wednesday, "thursday": Thursday, "friday": Friday, "saturday": Saturday, } // TimeWeekday converts this Weekday to a standard library time.Weekday. func (w Weekday) TimeWeekday() time.Weekday { return time.Weekday(w) } // UnmarshalTOML takes a raw TOML weekday string value and attempts to parse the value as a Weekday. // The value passed to this method should be a byte array of a quoted string (i.e. the raw TOML // value), the method will remove the quotes. func (w *Weekday) UnmarshalTOML(bytes []byte) error { text, err := strconv.Unquote(string(bytes)) if err != nil { return err } text = strings.ToLower(text) weekday, ok := weekdays[text] if !ok { return fmt.Errorf("xtime: Invalid Weekday '%s'", text) } *w = weekday return nil } // DateFmt is a fairly standard, date-only format for times. const DateFmt = "2006-01-02" // Date returns a given time, without any time on it. Only the date. func Date(datetime time.Time) time.Time { date, err := time.Parse(DateFmt, datetime.Format(DateFmt)) if err != nil { // This should only happen if something really crazy happens... panic(err) } return date } // LastWeekday finds the date of the most recent occurrence of a given weekday in the past. func LastWeekday(weekday time.Weekday) time.Time { date := Date(time.Now()) for date.Weekday() != weekday { date = date.AddDate(0, 0, -1) } return date } // FormatDuration returns the given time.Duration as a string in the given DurationFormat. func FormatDuration(duration time.Duration, timeFormat DurationFormat) string { switch timeFormat { case FormatDecimal: return strconv.FormatFloat(duration.Hours(), 'f', 2, 64) case FormatText: fallthrough default: return duration.String() } }
pkg/xtime/xtime.go
0.666822
0.505981
xtime.go
starcoder
package ws281x import ( "bytes" ) // FBU can be used to implement a frame buffer for UART based WS281x driver. FBU // encoding uses one byte of memory to encode three WS281x bits (8 bytes/pixel). type FBU struct { data []byte } // MakeFBU allocates memory for string of n pixels. func MakeFBU(n int) FBU { return FBU{make([]byte, n*8)} } // AsFBU returns FBU using b as data storage. For n pixels n*8 bytes are need. func AsFBU(b []byte) FBU { return FBU{b} } // PixelSize returns pixel size in bytes (always 8). func (_ FBU) PixelSize() int { return 8 } // Len returns FBU length as number of pixels. func (s FBU) Len() int { return len(s.data) / 8 } // At returns slice of p that contains p.Len()-n pixels starting from n. func (s FBU) At(n int) FBU { return FBU{s.data[n*8:]} } // Head returns slice of p that contains n pixels starting from 0. func (s FBU) Head(n int) FBU { return FBU{s.data[:n*8]} } const zeroUART = (6>>1 + 6<<2 + 6<<5) // EncodeRGB encodes c to one pixel at begining of s in WS2811 RGB order. func (s FBU) EncodeRGB(c Color) { r, g, b := c.Red(), c.Green(), c.Blue() s.data[0] = byte(zeroUART &^ (r>>7&1 | r>>3&8 | r<<1&0x40)) s.data[1] = byte(zeroUART &^ (r>>4&1 | r>>0&8 | r<<4&0x40)) s.data[2] = byte(zeroUART &^ (r>>1&1 | r<<3&8 | g>>1&0x40)) s.data[3] = byte(zeroUART &^ (g>>6&1 | g>>2&8 | g<<2&0x40)) s.data[4] = byte(zeroUART &^ (g>>3&1 | g<<1&8 | g<<5&0x40)) s.data[5] = byte(zeroUART &^ (g>>0&1 | b>>4&8 | b>>0&0x40)) s.data[6] = byte(zeroUART &^ (b>>5&1 | b>>1&8 | b<<3&0x40)) s.data[7] = byte(zeroUART &^ (b>>2&1 | b<<2&8 | b<<6&0x40)) } // EncodeGRB encodes c to one pixel at begining of s in WS2812 GRB order. func (s FBU) EncodeGRB(c Color) { r, g, b := c.Red(), c.Green(), c.Blue() s.data[0] = byte(zeroUART &^ (g>>7&1 | g>>3&8 | g<<1&0x40)) s.data[1] = byte(zeroUART &^ (g>>4&1 | g>>0&8 | g<<4&0x40)) s.data[2] = byte(zeroUART &^ (g>>1&1 | g<<3&8 | r>>1&0x40)) s.data[3] = byte(zeroUART &^ (r>>6&1 | r>>2&8 | r<<2&0x40)) s.data[4] = byte(zeroUART &^ (r>>3&1 | r<<1&8 | r<<5&0x40)) s.data[5] = byte(zeroUART &^ (r>>0&1 | b>>4&8 | b>>0&0x40)) s.data[6] = byte(zeroUART &^ (b>>5&1 | b>>1&8 | b<<3&0x40)) s.data[7] = byte(zeroUART &^ (b>>2&1 | b<<2&8 | b<<6&0x40)) } // Bytes returns p's internal storage. func (s FBU) Bytes() []byte { return s.data } // Write writes src to beginning of s. func (s FBU) Write(src FBU) { copy(s.Bytes(), src.Bytes()) } // Fill fills whole s using pattern p. func (s FBU) Fill(p FBU) { sb := s.Bytes() pb := p.Bytes() for i := 0; i < len(sb); i += copy(sb[i:], pb) { } } // Clear clears whole s to black color. func (s FBU) Clear() { bytes.Fill(s.data, zeroUART) }
egpath/src/ws281x/fbu.go
0.68637
0.502869
fbu.go
starcoder
package json import ( "fmt" "io" "strconv" . "gx/ipfs/QmdBzoMxsBpojBfN1cv5GnKtB7sfYBMoLH7p9qSyEVYXcu/refmt/tok" ) func NewEncoder(wr io.Writer, cfg EncodeOptions) *Encoder { return &Encoder{ wr: wr, cfg: cfg, stack: make([]phase, 0, 10), } } func (d *Encoder) Reset() { d.stack = d.stack[0:0] d.current = phase_anyExpectValue d.some = false } /* A json.Encoder is a TokenSink implementation that emits json bytes. */ type Encoder struct { wr io.Writer cfg EncodeOptions // Stack, tracking how many array and map opens are outstanding. // (Values are only 'phase_mapExpectKeyOrEnd' and 'phase_arrExpectValueOrEnd'.) stack []phase current phase // shortcut to value at end of stack some bool // set to true after first value in any context; use to append commas. // Spare memory, for use in operations on leaf nodes (e.g. temp space for an int serialization). scratch [64]byte } type phase int const ( phase_anyExpectValue phase = iota phase_mapExpectKeyOrEnd phase_mapExpectValue phase_arrExpectValueOrEnd ) func (d *Encoder) Step(tok *Token) (done bool, err error) { switch d.current { case phase_anyExpectValue: switch tok.Type { case TMapOpen: d.pushPhase(phase_mapExpectKeyOrEnd) d.wr.Write(wordMapOpen) return false, nil case TArrOpen: d.pushPhase(phase_arrExpectValueOrEnd) d.wr.Write(wordArrOpen) return false, nil case TMapClose: return true, fmt.Errorf("unexpected mapClose; expected start of value") case TArrClose: return true, fmt.Errorf("unexpected arrClose; expected start of value") default: // It's a value; handle it. d.flushValue(tok) return true, nil } case phase_mapExpectKeyOrEnd: switch tok.Type { case TMapOpen: return true, fmt.Errorf("unexpected mapOpen; expected start of key or end of map") case TArrOpen: return true, fmt.Errorf("unexpected arrOpen; expected start of key or end of map") case TMapClose: if d.some { d.wr.Write(d.cfg.Line) for i := 1; i < len(d.stack); i++ { d.wr.Write(d.cfg.Indent) } } d.wr.Write(wordMapClose) return d.popPhase() case TArrClose: return true, fmt.Errorf("unexpected arrClose; expected start of key or end of map") default: // It's a key. It'd better be a string. switch tok.Type { case TString: d.entrySep() d.emitString(tok.Str) d.wr.Write(wordColon) if d.cfg.Line != nil { d.wr.Write(wordSpace) } d.current = phase_mapExpectValue return false, nil default: return true, fmt.Errorf("unexpected token of type %T; expected map key", *tok) } } case phase_mapExpectValue: switch tok.Type { case TMapOpen: d.pushPhase(phase_mapExpectKeyOrEnd) d.wr.Write(wordMapOpen) return false, nil case TArrOpen: d.pushPhase(phase_arrExpectValueOrEnd) d.wr.Write(wordArrOpen) return false, nil case TMapClose: return true, fmt.Errorf("unexpected mapClose; expected start of value") case TArrClose: return true, fmt.Errorf("unexpected arrClose; expected start of value") default: // It's a value; handle it. d.flushValue(tok) d.current = phase_mapExpectKeyOrEnd return false, nil } case phase_arrExpectValueOrEnd: switch tok.Type { case TMapOpen: d.entrySep() d.pushPhase(phase_mapExpectKeyOrEnd) d.wr.Write(wordMapOpen) return false, nil case TArrOpen: d.entrySep() d.pushPhase(phase_arrExpectValueOrEnd) d.wr.Write(wordArrOpen) return false, nil case TMapClose: return true, fmt.Errorf("unexpected mapClose; expected start of value or end of array") case TArrClose: if d.some { d.wr.Write(d.cfg.Line) for i := 1; i < len(d.stack); i++ { d.wr.Write(d.cfg.Indent) } } d.wr.Write(wordArrClose) return d.popPhase() default: // It's a value; handle it. d.entrySep() d.flushValue(tok) return false, nil } default: panic("Unreachable") } } func (d *Encoder) pushPhase(p phase) { d.current = p d.stack = append(d.stack, d.current) d.some = false } // Pop a phase from the stack; return 'true' if stack now empty. func (d *Encoder) popPhase() (bool, error) { n := len(d.stack) - 1 if n == 0 { d.wr.Write(d.cfg.Line) return true, nil } if n < 0 { // the state machines are supposed to have already errored better panic("jsonEncoder stack overpopped") } d.current = d.stack[n-1] d.stack = d.stack[0:n] d.some = true return false, nil } // Emit an entry separater (comma), unless we're at the start of an object. // Mark that we *do* have some content, regardless, so next time will need a sep. func (d *Encoder) entrySep() { if d.some { d.wr.Write(wordComma) } d.some = true d.wr.Write(d.cfg.Line) for i := 0; i < len(d.stack); i++ { d.wr.Write(d.cfg.Indent) } } func (d *Encoder) flushValue(tok *Token) { switch tok.Type { case TString: d.emitString(tok.Str) case TBool: switch tok.Bool { case true: d.wr.Write(wordTrue) case false: d.wr.Write(wordFalse) } case TInt: b := strconv.AppendInt(d.scratch[:0], tok.Int, 10) d.wr.Write(b) case TNull: d.wr.Write(wordNull) default: panic(fmt.Errorf("TODO finish more jsonEncoder primitives support: unhandled token %s", tok)) } } func (d *Encoder) writeByte(b byte) { d.scratch[0] = b d.wr.Write(d.scratch[0:1]) }
vendor/gx/ipfs/QmdBzoMxsBpojBfN1cv5GnKtB7sfYBMoLH7p9qSyEVYXcu/refmt/json/jsonEncoder.go
0.500488
0.442335
jsonEncoder.go
starcoder
package imagick /* #include <wand/MagickWand.h> */ import "C" import ( "runtime" "sync" "sync/atomic" "unsafe" ) type PixelWand struct { pw *C.PixelWand init sync.Once } // Returns a new pixel wand func newPixelWand(cpw *C.PixelWand) *PixelWand { pw := &PixelWand{pw: cpw} runtime.SetFinalizer(pw, Destroy) pw.IncreaseCount() return pw } // Returns a new pixel wand func NewPixelWand() *PixelWand { return newPixelWand(C.NewPixelWand()) } // Clears resources associated with the wand func (pw *PixelWand) Clear() { C.ClearPixelWand(pw.pw) runtime.KeepAlive(pw) } // Makes an exact copy of the wand func (pw *PixelWand) Clone() *PixelWand { ret := newPixelWand(C.ClonePixelWand(pw.pw)) runtime.KeepAlive(pw) return ret } // Deallocates resources associated with a pixel wand func (pw *PixelWand) Destroy() { if pw.pw == nil { return } pw.init.Do(func() { pw.pw = C.DestroyPixelWand(pw.pw) relinquishMemory(unsafe.Pointer(pw.pw)) pw.pw = nil pw.DecreaseCount() }) } // Returns true if the distance between two colors is less than the specified distance func (pw *PixelWand) IsSimilar(pixelWand *PixelWand, fuzz float64) bool { ret := 1 == C.int(C.IsPixelWandSimilar(pw.pw, pixelWand.pw, C.double(fuzz))) runtime.KeepAlive(pw) runtime.KeepAlive(pixelWand) return ret } // Returns true if the wand is verified as a pixel wand func (pw *PixelWand) IsVerified() bool { if pw.pw != nil { return 1 == C.int(C.IsPixelWand(pw.pw)) } runtime.KeepAlive(pw) return false } // Increase PixelWand ref counter and set according "can`t be terminated status" func (pw *PixelWand) IncreaseCount() { atomic.AddInt64(&pixelWandCounter, int64(1)) unsetCanTerminate() } // Decrease PixelWand ref counter and set according "can be terminated status" func (pw *PixelWand) DecreaseCount() { atomic.AddInt64(&pixelWandCounter, int64(-1)) setCanTerminate() } // Returns the normalized alpha color of the pixel wand func (pw *PixelWand) GetAlpha() float64 { ret := float64(C.PixelGetAlpha(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the alpha value of the pixel wand func (pw *PixelWand) GetAlphaQuantum() Quantum { ret := Quantum(C.PixelGetAlphaQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the normalized black color of the pixel wand func (pw *PixelWand) GetBlack() float64 { ret := float64(C.PixelGetBlack(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the black color of the pixel wand func (pw *PixelWand) GetBlackQuantum() Quantum { ret := Quantum(C.PixelGetBlackQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the normalized blue color of the pixel wand func (pw *PixelWand) GetBlue() float64 { ret := float64(C.PixelGetBlue(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the blue color of the pixel wand func (pw *PixelWand) GetBlueQuantum() Quantum { ret := Quantum(C.PixelGetBlueQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the color of the pixel wand as a string func (pw *PixelWand) GetColorAsString() string { p := C.PixelGetColorAsString(pw.pw) runtime.KeepAlive(pw) defer relinquishMemory(unsafe.Pointer(p)) return C.GoString(p) } // Returns the normalized color of the pixel wand as string func (pw *PixelWand) GetColorAsNormalizedString() string { p := C.PixelGetColorAsNormalizedString(pw.pw) runtime.KeepAlive(pw) defer relinquishMemory(unsafe.Pointer(p)) return C.GoString(p) } // Returns the color count associated with this color func (pw *PixelWand) GetColorCount() uint { ret := uint(C.PixelGetColorCount(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the normalized cyan color of the pixel wand func (pw *PixelWand) GetCyan() float64 { ret := float64(C.PixelGetCyan(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the cyan color of the pixel wand func (pw *PixelWand) GetCyanQuantum() Quantum { ret := Quantum(C.PixelGetCyanQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the normalized fuzz value of the pixel wand func (pw *PixelWand) GetFuzz() float64 { ret := float64(C.PixelGetFuzz(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the normalized green color of the pixel wand func (pw *PixelWand) GetGreen() float64 { ret := float64(C.PixelGetGreen(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the green color of the pixel wand func (pw *PixelWand) GetGreenQuantum() Quantum { ret := Quantum(C.PixelGetGreenQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the normalized HSL color of the pixel wand func (pw *PixelWand) GetHSL() (hue, saturation, brightness float64) { var cdhue, cdsaturation, cdbrightness C.double C.PixelGetHSL(pw.pw, &cdhue, &cdsaturation, &cdbrightness) runtime.KeepAlive(pw) hue, saturation, brightness = float64(cdhue), float64(cdsaturation), float64(cdbrightness) return } // Returns the colormap index from the pixel wand func (pw *PixelWand) GetIndex() IndexPacket { cip := C.PixelGetIndex(pw.pw) runtime.KeepAlive(pw) return IndexPacket(cip) } // Returns the normalized magenta color of the pixel wand func (pw *PixelWand) GetMagenta() float64 { ret := float64(C.PixelGetMagenta(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the magenta color of the pixel wand func (pw *PixelWand) GetMagentaQuantum() Quantum { ret := Quantum(C.PixelGetMagentaQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Gets the magick color of the pixel wand func (pw *PixelWand) GetMagickColor() *MagickPixelPacket { var mpp C.MagickPixelPacket C.PixelGetMagickColor(pw.pw, &mpp) runtime.KeepAlive(pw) return newMagickPixelPacketFromCAPI(&mpp) } // Returns the normalized opacity color of the pixel wand func (pw *PixelWand) GetOpacity() float64 { return float64(C.PixelGetOpacity(pw.pw)) } // Returns the opacity color of the pixel wand func (pw *PixelWand) GetOpacityQuantum() Quantum { return Quantum(C.PixelGetOpacityQuantum(pw.pw)) } // Gets the color of the pixel wand as a PixelPacket func (pw *PixelWand) GetQuantumColor() *PixelPacket { var pp C.PixelPacket C.PixelGetQuantumColor(pw.pw, &pp) runtime.KeepAlive(pw) return newPixelPacketFromCAPI(&pp) } // Returns the normalized red color of the pixel wand func (pw *PixelWand) GetRed() float64 { ret := float64(C.PixelGetRed(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the red color of the pixel wand func (pw *PixelWand) GetRedQuantum() Quantum { ret := Quantum(C.PixelGetRedQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the normalized yellow color of the pixel wand func (pw *PixelWand) GetYellow() float64 { ret := float64(C.PixelGetYellow(pw.pw)) runtime.KeepAlive(pw) return ret } // Returns the yellow color of the pixel wand func (pw *PixelWand) GetYellowQuantum() Quantum { ret := Quantum(C.PixelGetYellowQuantum(pw.pw)) runtime.KeepAlive(pw) return ret } // Sets the normalized alpha color of the pixel wand. // 1.0 is fully opaque and 0.0 is fully transparent. func (pw *PixelWand) SetAlpha(alpha float64) { C.PixelSetAlpha(pw.pw, C.double(alpha)) runtime.KeepAlive(pw) } // Sets the alpha color of the pixel wand func (pw *PixelWand) SetAlphaQuantum(opacity Quantum) { C.PixelSetAlphaQuantum(pw.pw, C.Quantum(opacity)) runtime.KeepAlive(pw) } // Sets the normalized black color of the pixel wand func (pw *PixelWand) SetBlack(black float64) { C.PixelSetBlack(pw.pw, C.double(black)) runtime.KeepAlive(pw) } // Sets the black color of the pixel wand func (pw *PixelWand) SetBlackQuantum(black Quantum) { C.PixelSetBlackQuantum(pw.pw, C.Quantum(black)) runtime.KeepAlive(pw) } // Sets the normalized blue color of the pixel wand func (pw *PixelWand) SetBlue(blue float64) { C.PixelSetBlue(pw.pw, C.double(blue)) runtime.KeepAlive(pw) } // Sets the blue color of the pixel wand func (pw *PixelWand) SetBlueQuantum(blue Quantum) { C.PixelSetBlueQuantum(pw.pw, C.Quantum(blue)) runtime.KeepAlive(pw) } // Sets the color of the pixel wand with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.) func (pw *PixelWand) SetColor(color string) bool { cscolor := C.CString(color) defer C.free(unsafe.Pointer(cscolor)) ret := 1 == int(C.PixelSetColor(pw.pw, cscolor)) runtime.KeepAlive(pw) return ret } // Sets the color count of the pixel wand func (pw *PixelWand) SetColorCount(count uint) { C.PixelSetColorCount(pw.pw, C.size_t(count)) runtime.KeepAlive(pw) } // Sets the color of the pixel wand from another one func (pw *PixelWand) SetColorFromWand(pixelWand *PixelWand) { C.PixelSetColorFromWand(pw.pw, pixelWand.pw) runtime.KeepAlive(pw) } // Sets the normalized cyan color of the pixel wand func (pw *PixelWand) SetCyan(cyan float64) { C.PixelSetCyan(pw.pw, C.double(cyan)) runtime.KeepAlive(pw) } // Sets the cyan color of the pixel wand func (pw *PixelWand) SetCyanQuantum(cyan Quantum) { C.PixelSetCyanQuantum(pw.pw, C.Quantum(cyan)) runtime.KeepAlive(pw) } // Sets the fuzz value of the pixel wand func (pw *PixelWand) SetFuzz(fuzz float64) { C.PixelSetFuzz(pw.pw, C.double(fuzz)) runtime.KeepAlive(pw) } // Sets the normalized green color of the pixel wand func (pw *PixelWand) SetGreen(green float64) { C.PixelSetGreen(pw.pw, C.double(green)) runtime.KeepAlive(pw) } // Sets the green color of the pixel wand func (pw *PixelWand) SetGreenQuantum(green Quantum) { C.PixelSetGreenQuantum(pw.pw, C.Quantum(green)) runtime.KeepAlive(pw) } // Sets the normalized HSL color of the pixel wand func (pw *PixelWand) SetHSL(hue, saturation, brightness float64) { C.PixelSetHSL(pw.pw, C.double(hue), C.double(saturation), C.double(brightness)) runtime.KeepAlive(pw) } // Sets the colormap index of the pixel wand func (pw *PixelWand) SetIndex(index *IndexPacket) { C.PixelSetIndex(pw.pw, C.IndexPacket(*index)) runtime.KeepAlive(pw) } // Sets the normalized magenta color of the pixel wand func (pw *PixelWand) SetMagenta(magenta float64) { C.PixelSetMagenta(pw.pw, C.double(magenta)) runtime.KeepAlive(pw) } // Sets the magenta color of the pixel wand func (pw *PixelWand) SetMagentaQuantum(magenta Quantum) { C.PixelSetMagentaQuantum(pw.pw, C.Quantum(magenta)) runtime.KeepAlive(pw) } // Sets the color of the pixel wand func (pw *PixelWand) SetMagickColor(color *MagickPixelPacket) { C.PixelSetMagickColor(pw.pw, color.mpp) } // Sets the normalized opacity color of the pixel wand func (pw *PixelWand) SetOpacity(opacity float64) { C.PixelSetOpacity(pw.pw, C.double(opacity)) runtime.KeepAlive(pw) } // Sets the opacity color of the pixel wand func (pw *PixelWand) SetOpacityQuantum(opacity Quantum) { C.PixelSetOpacityQuantum(pw.pw, C.Quantum(opacity)) runtime.KeepAlive(pw) } // Sets the color of the pixel wand func (pw *PixelWand) SetQuantumColor(color *PixelPacket) { C.PixelSetQuantumColor(pw.pw, color.pp) runtime.KeepAlive(pw) } // Sets the normalized red color of the pixel wand func (pw *PixelWand) SetRed(red float64) { C.PixelSetRed(pw.pw, C.double(red)) runtime.KeepAlive(pw) } // Sets the red color of the pixel wand func (pw *PixelWand) SetRedQuantum(red Quantum) { C.PixelSetRedQuantum(pw.pw, C.Quantum(red)) runtime.KeepAlive(pw) } // Sets the normalized yellow color of the pixel wand func (pw *PixelWand) SetYellow(yellow float64) { C.PixelSetYellow(pw.pw, C.double(yellow)) runtime.KeepAlive(pw) } // Sets the yellow color of the pixel wand func (pw *PixelWand) SetYellowQuantum(yellow Quantum) { C.PixelSetYellowQuantum(pw.pw, C.Quantum(yellow)) runtime.KeepAlive(pw) }
imagick/pixel_wand.go
0.813609
0.518424
pixel_wand.go
starcoder
package script import ( "time" "github.com/transmutate-io/atomicswap/cryptos" ) // Engine represents a scripting engine type Engine struct { b []byte Generator Generator } // NewEngine returns a scripting engine for the given crypto func NewEngine(c *cryptos.Crypto) (*Engine, error) { gen, ok := generators[c.Name] if !ok { return nil, cryptos.InvalidCryptoError(c.Name) } return newEngine(gen), nil } func newEngine(gen Generator) *Engine { return &Engine{ b: make([]byte, 0, 1024), Generator: gen, } } // If adds an if-else to the script func (eng *Engine) If(i, e []byte) *Engine { eng.b = append(eng.b, eng.Generator.If(i, e)...) return eng } // Data adds b as data the script func (eng *Engine) Data(b []byte) *Engine { eng.b = append(eng.b, eng.Generator.Data(b)...) return eng } // Int64 adds n as data to the script func (eng *Engine) Int64(n int64) *Engine { eng.b = append(eng.b, eng.Generator.Int64(n)...) return eng } // P2PKHHash adds a p2pkh contract to the script using the key hash func (eng *Engine) P2PKHHash(hash []byte) *Engine { eng.b = append(eng.b, eng.Generator.P2PKHHash(hash)...) return eng } // P2PKHPublic adds a p2pkh contract to the script using the public key func (eng *Engine) P2PKHPublic(pub []byte) *Engine { eng.b = append(eng.b, eng.Generator.P2PKHPublic(pub)...) return eng } // P2PKPublic adds a p2pk contract to the script using the public key func (eng *Engine) P2PKPublic(pub []byte) *Engine { eng.b = append(eng.b, eng.Generator.P2PKPublic(pub)...) return eng } // P2SHHash adds a p2sh contract to the script using the script hash func (eng *Engine) P2SHHash(h []byte) *Engine { eng.b = append(eng.b, eng.Generator.P2SHHash(h)...) return eng } // P2SHScript adds a p2sh contract to the script using the script s func (eng *Engine) P2SHScript(s []byte) *Engine { eng.b = append(eng.b, eng.Generator.P2SHScript(s)...) return eng } // P2MS adds a p2ms contract to the script func (eng *Engine) P2MS(verify bool, nRequired int64, pubKeys ...[]byte) *Engine { eng.b = append(eng.b, eng.Generator.P2MS(verify, nRequired, pubKeys...)...) return eng } // LockTime adds a timelock to the script using a fixed int func (eng *Engine) LockTime(lock int64) *Engine { eng.b = append(eng.b, eng.Generator.LockTime(lock)...) return eng } // LockTimeTime adds a timelock to the script using an absolute time func (eng *Engine) LockTimeTime(t time.Time) *Engine { eng.b = append(eng.b, eng.Generator.LockTimeTime(t)...) return eng } // Sequence adds a sequence check to the script func (eng *Engine) Sequence(lock int64) *Engine { eng.b = append(eng.b, eng.Generator.Sequence(lock)...) return eng } // HashLock adds an hashlock to the script func (eng *Engine) HashLock(h []byte, verify bool) *Engine { eng.b = append(eng.b, eng.Generator.HashLock(h, verify)...) return eng } // HTLC adds an hash-time-locked contract to the script func (eng *Engine) HTLC(lockScript, tokenHash, timeLockedScript, hashLockedScript []byte) *Engine { eng.b = append(eng.b, eng.Generator.HTLC(lockScript, tokenHash, timeLockedScript, hashLockedScript)...) return eng } // HTLCRedeem redeems an htlc to the script func (eng *Engine) HTLCRedeem(sig, key, token, locksScript []byte) *Engine { eng.b = append(eng.b, eng.Generator.HTLCRedeem(sig, key, token, locksScript)...) return eng } // HTLCRecover recovers an htlc to the script func (eng *Engine) HTLCRecover(sig, key, locksScript []byte) *Engine { eng.b = append(eng.b, eng.Generator.HTLCRecover(sig, key, locksScript)...) return eng } // MSTLC adds a multisig-time-lock contract to the script func (eng *Engine) MSTLC(lockScript, timeLockedScript []byte, nRequired int64, pubKeys ...[]byte) *Engine { eng.b = append(eng.b, eng.Generator.MSTLC(lockScript, timeLockedScript, nRequired, pubKeys...)...) return eng } // Bytes returns the script bytes func (eng *Engine) Bytes() []byte { return eng.b } // SetBytes sets the script bytes func (eng *Engine) SetBytes(b []byte) { eng.b = b }
script/engine.go
0.816772
0.424531
engine.go
starcoder
package ahrsweb const Port = 8000 type AHRSData struct { // Kalman state variables U1, U2, U3 float64 // Vector for airspeed, aircraft frame, kt Z1, Z2, Z3 float64 // Vector for rate of change of airspeed, aircraft frame, G E0, E1, E2, E3 float64 // Quaternion rotating earth frame to aircraft frame H1, H2, H3 float64 // Vector for gyro rates, earth frame, °/s N1, N2, N3 float64 // Vector for earth's magnetic field, earth (inertial) frame, µT V1, V2, V3 float64 // (Bias) Vector for windspeed, earth frame, kt C1, C2, C3 float64 // Bias vector for accelerometer, sensor frame, G F0, F1, F2, F3 float64 // (Bias) quaternion rotating sensor frame to aircraft frame D1, D2, D3 float64 // Bias vector for gyro rates, sensor frame, °/s L1, L2, L3 float64 // Bias vector for magnetometer direction, sensor frame, µT // Kalman state uncertainties DU1, DU2, DU3 float64 // Vector for airspeed, aircraft frame, kt DZ1, DZ2, DZ3 float64 // Vector for rate of change of airspeed, aircraft frame, G DE0, DE1, DE2, DE3 float64 // Quaternion rotating earth frame to aircraft frame DH1, DH2, DH3 float64 // Vector for gyro rates, earth frame, °/s DN1, DN2, DN3 float64 // Vector for earth's magnetic field, earth (inertial) frame, µT DV1, DV2, DV3 float64 // (Bias) Vector for windspeed, earth frame, kt DC1, DC2, DC3 float64 // Bias vector for accelerometer, sensor frame, G DF0, DF1, DF2, DF3 float64 // (Bias) quaternion rotating sensor frame to aircraft frame DD1, DD2, DD3 float64 // Bias vector for gyro rates, sensor frame, °/s DL1, DL2, DL3 float64 // Bias vector for magnetometer direction, sensor frame, µT // Measurement variables UValid, WValid, SValid, MValid bool // Do we have valid airspeed, GPS, accel/gyro, and magnetometer readings? S1, S2, S3 float64 // Vector of airspeeds W1, W2, W3 float64 // Vector of GPS speed in N/S, E/W and U/D directions, kt, latlong axes, earth (inertial) frame A1, A2, A3 float64 // Vector holding accelerometer readings, G, aircraft (accelerated) frame B1, B2, B3 float64 // Vector of gyro rates in roll, pitch, heading axes, °/s, aircraft (accelerated) frame M1, M2, M3 float64 // Vector of magnetometer readings, µT, aircraft (accelerated) frame T float64 // Timestamp of GPS, airspeed and magnetometer readings // Final output Pitch, Roll, Heading float64 }
ahrsweb/ahrs_data.go
0.581065
0.671721
ahrs_data.go
starcoder
package process import ( "fmt" "reflect" ) // Code from Go STL - template/funcs.go var ( errorType = reflect.TypeOf((*error)(nil)).Elem() ) // goodFunc checks that the function or method has the right result signature. func goodFunc(typ reflect.Type) bool { // We allow functions with 1 result or 2 results where the second is an error. switch { case typ.NumOut() == 1: return true case typ.NumOut() == 2 && typ.Out(1) == errorType: return true } return false } // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero. func canBeNil(typ reflect.Type) bool { switch typ.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return true } return false } // call returns the result of evaluating the first argument as a function. // The function must return 1 result, or 2 results, the second of which is an error. func call(fn interface{}, args []interface{}) (interface{}, error) { v := reflect.ValueOf(fn) typ := v.Type() if typ.Kind() != reflect.Func { return nil, fmt.Errorf("non-function of type %s", typ) } if !goodFunc(typ) { return nil, fmt.Errorf("function called with %d args; should be 1 or 2", typ.NumOut()) } numIn := typ.NumIn() var dddType reflect.Type if typ.IsVariadic() { if len(args) < numIn-1 { return nil, fmt.Errorf("wrong number of args: got %d want at least %d", len(args), numIn-1) } dddType = typ.In(numIn - 1).Elem() } else { if len(args) != numIn { return nil, fmt.Errorf("wrong number of args: got %d want %d", len(args), numIn) } } argv := make([]reflect.Value, len(args)) for i, arg := range args { value := reflect.ValueOf(arg) // Compute the expected type. Clumsy because of variadics. var argType reflect.Type if !typ.IsVariadic() || i < numIn-1 { argType = typ.In(i) } else { argType = dddType } if !value.IsValid() && canBeNil(argType) { value = reflect.Zero(argType) } if !value.Type().AssignableTo(argType) { return nil, fmt.Errorf("arg %d has type %s; should be %s", i, value.Type(), argType) } argv[i] = value } result := v.Call(argv) if len(result) == 2 && !result[1].IsNil() { return result[0].Interface(), result[1].Interface().(error) } return result[0].Interface(), nil }
src/process/func_utils.go
0.581065
0.426859
func_utils.go
starcoder
package mathexp import ( "fmt" "sort" "time" "github.com/grafana/gel-app/pkg/mathexp/parse" "github.com/grafana/grafana-plugin-sdk-go/data" ) // Series has time.Time and ...? *float64 fields. type Series struct { Frame *data.Frame TimeIsNullable bool TimeIdx int ValueIsNullabe bool ValueIdx int // TODO: // - Multiple Value Fields // - Value can be different number types } // SeriesFromFrame validates that the dataframe can be considered a Series type // and populate meta information on Series about the frame. func SeriesFromFrame(frame *data.Frame) (s Series, err error) { if len(frame.Fields) != 2 { return s, fmt.Errorf("frame must have exactly two fields to be a series, has %v", len(frame.Fields)) } foundTime := false foundValue := false for i, field := range frame.Fields { //[0].Vector.PrimitiveType() { switch field.Type() { case data.FieldTypeTime: s.TimeIdx = i foundTime = true case data.FieldTypeNullableTime: s.TimeIsNullable = true foundTime = true s.TimeIdx = i case data.FieldTypeFloat64: foundValue = true s.ValueIdx = i case data.FieldTypeNullableFloat64: s.ValueIsNullabe = true foundValue = true s.ValueIdx = i } } if !foundTime { return s, fmt.Errorf("no time column found in frame %v", frame.Name) } if !foundValue { return s, fmt.Errorf("no float64 value column found in frame %v", frame.Name) } s.Frame = frame return } // NewSeries returns a dataframe of type Series. func NewSeries(name string, labels data.Labels, timeIdx int, nullableTime bool, valueIdx int, nullableValue bool, size int) Series { fields := make([]*data.Field, 2) if nullableValue { fields[valueIdx] = data.NewField(name, labels, make([]*float64, size)) } else { fields[valueIdx] = data.NewField(name, labels, make([]float64, size)) } if nullableTime { fields[timeIdx] = data.NewField("Time", nil, make([]*time.Time, size)) } else { fields[timeIdx] = data.NewField("Time", nil, make([]time.Time, size)) } return Series{ Frame: data.NewFrame("", fields...), TimeIsNullable: nullableTime, TimeIdx: timeIdx, ValueIsNullabe: nullableValue, ValueIdx: valueIdx, } } // Type returns the Value type and allows it to fulfill the Value interface. func (s Series) Type() parse.ReturnType { return parse.TypeSeriesSet } // Value returns the actual value allows it to fulfill the Value interface. func (s Series) Value() interface{} { return &s } func (s Series) GetLabels() data.Labels { return s.Frame.Fields[s.ValueIdx].Labels } func (s Series) SetLabels(ls data.Labels) { s.Frame.Fields[s.ValueIdx].Labels = ls } func (s Series) GetName() string { return s.Frame.Name } // AsDataFrame returns the underlying *data.Frame. func (s Series) AsDataFrame() *data.Frame { return s.Frame } // GetPoint returns the time and value at the specified index. func (s Series) GetPoint(pointIdx int) (*time.Time, *float64) { return s.GetTime(pointIdx), s.GetValue(pointIdx) } // SetPoint sets the time and value on the corresponding vectors at the specified index. func (s Series) SetPoint(pointIdx int, t *time.Time, f *float64) (err error) { if s.TimeIsNullable { s.Frame.Fields[s.TimeIdx].Set(pointIdx, t) } else { if t == nil { return fmt.Errorf("can not set null time value on non-nullable time field for series name %v", s.Frame.Name) } s.Frame.Fields[s.TimeIdx].Set(pointIdx, *t) } if s.ValueIsNullabe { s.Frame.Fields[s.ValueIdx].Set(pointIdx, f) } else { if f == nil { return fmt.Errorf("can not set null float value on non-nullable float field for series name %v", s.Frame.Name) } s.Frame.Fields[s.ValueIdx].Set(pointIdx, *f) } return } // AppendPoint appends a point (time/value). func (s Series) AppendPoint(pointIdx int, t *time.Time, f *float64) (err error) { if s.TimeIsNullable { s.Frame.Fields[s.TimeIdx].Append(t) } else { if t == nil { return fmt.Errorf("can not append null time value on non-nullable time field for series name %v", s.Frame.Name) } s.Frame.Fields[s.TimeIdx].Append(*t) } if s.ValueIsNullabe { s.Frame.Fields[s.ValueIdx].Append(f) } else { if f == nil { return fmt.Errorf("can not append null float value on non-nullable float field for series name %v", s.Frame.Name) } s.Frame.Fields[s.ValueIdx].Append(*f) } return } // Len returns the length of the series. func (s Series) Len() int { return s.Frame.Fields[0].Len() } // GetTime returns the time at the specified index. func (s Series) GetTime(pointIdx int) *time.Time { if s.TimeIsNullable { return s.Frame.Fields[s.TimeIdx].At(pointIdx).(*time.Time) } t := s.Frame.Fields[s.TimeIdx].At(pointIdx).(time.Time) return &t } // GetValue returns the float value at the specified index. func (s Series) GetValue(pointIdx int) *float64 { if s.ValueIsNullabe { return s.Frame.Fields[s.ValueIdx].At(pointIdx).(*float64) } f := s.Frame.Fields[s.ValueIdx].At(pointIdx).(float64) return &f } // SortByTime sorts the series by the time from oldest to newest. // If desc is true, it will sort from newest to oldest. // If any time values are nil, it will panic. func (s Series) SortByTime(desc bool) { if desc { sort.Sort(sort.Reverse(SortSeriesByTime(s))) return } sort.Sort(SortSeriesByTime(s)) } // SortSeriesByTime allows a Series to be sorted by time // the sort interface will panic if any timestamps are null type SortSeriesByTime Series func (ss SortSeriesByTime) Len() int { return Series(ss).Len() } func (ss SortSeriesByTime) Swap(i, j int) { iTimeVal, iFVal := Series(ss).GetPoint(i) jTimeVal, jFVal := Series(ss).GetPoint(j) Series(ss).SetPoint(j, iTimeVal, iFVal) Series(ss).SetPoint(i, jTimeVal, jFVal) } func (ss SortSeriesByTime) Less(i, j int) bool { iTimeVal := Series(ss).GetTime(i) jTimeVal := Series(ss).GetTime(j) return iTimeVal.Before(*jTimeVal) }
pkg/mathexp/type_series.go
0.558809
0.509093
type_series.go
starcoder
// CMAC message authentication code, defined in // NIST Special Publication SP 800-38B. package cmac import ( "crypto/cipher" "hash" "github.com/miscreant/miscreant/go/block" ) type cmac struct { // c is the block cipher we're using (i.e. AES-128 or AES-256) c cipher.Block // k1 and k2 are CMAC subkeys (for finishing the tag) k1, k2 block.Block // digest contains the PMAC tag-in-progress digest block.Block // buffer contains a part of the input message, processed a block-at-a-time buf block.Block // pos marks the end of plaintext in the buffer pos uint } // New returns a new instance of a CMAC message authentication code // digest using the given cipher.Block. func New(c cipher.Block) hash.Hash { if c.BlockSize() != block.Size { panic("pmac: invalid cipher block size") } d := new(cmac) d.c = c // Subkey generation, p. 7 d.k1.Encrypt(c) d.k1.Dbl() copy(d.k2[:], d.k1[:]) d.k2.Dbl() return d } // Reset clears the digest state, starting a new digest. func (d *cmac) Reset() { d.digest.Clear() d.buf.Clear() d.pos = 0 } // Write adds the given data to the digest state. func (d *cmac) Write(p []byte) (nn int, err error) { nn = len(p) left := block.Size - d.pos if uint(len(p)) > left { xor(d.buf[d.pos:], p[:left]) p = p[left:] d.buf.Encrypt(d.c) d.pos = 0 } for uint(len(p)) > block.Size { xor(d.buf[:], p[:block.Size]) p = p[block.Size:] d.buf.Encrypt(d.c) } if len(p) > 0 { xor(d.buf[d.pos:], p) d.pos += uint(len(p)) } return } // Sum returns the CMAC digest, one cipher block in length, // of the data written with Write. func (d *cmac) Sum(in []byte) []byte { // Finish last block, mix in key, encrypt. // Don't edit ci, in case caller wants // to keep digesting after call to Sum. k := d.k1 if d.pos < uint(len(d.digest)) { k = d.k2 } for i := 0; i < len(d.buf); i++ { d.digest[i] = d.buf[i] ^ k[i] } if d.pos < uint(len(d.digest)) { d.digest[d.pos] ^= 0x80 } d.digest.Encrypt(d.c) return append(in, d.digest[:]...) } func (d *cmac) Size() int { return len(d.digest) } func (d *cmac) BlockSize() int { return d.c.BlockSize() } func xor(a, b []byte) { for i, v := range b { a[i] ^= v } }
vendor/github.com/miscreant/miscreant/go/cmac/cmac.go
0.687945
0.443781
cmac.go
starcoder
package clock // Forked from github.com/andres-erbsen/clock to isolate a missing nap. import ( "container/heap" "sync" "time" ) // Mock represents a mock clock that only moves forward programmically. // It can be preferable to a real-time clock when testing time-based functionality. type Mock struct { sync.Mutex now time.Time // current time timers Timers // timers } // NewMock returns an instance of a mock clock. // The current time of the mock clock on initialization is the Unix epoch. func NewMock() *Mock { return &Mock{now: time.Unix(0, 0)} } // NewMock returns an instance of a mock clock. // The current time of the mock clock on initialization is the Unix epoch. func NewMockAt(t time.Time) *Mock { return &Mock{now: t} } // Add moves the current time of the mock clock forward by the duration. // This should only be called from a single goroutine at a time. func (m *Mock) Add(d time.Duration) { m.Lock() // Calculate the final time. end := m.now.Add(d) for len(m.timers) > 0 && m.now.Before(end) { t := heap.Pop(&m.timers).(*Timer) m.now = t.next m.Unlock() t.Tick() m.Lock() } m.Unlock() // Give a small buffer to make sure the other goroutines get handled. nap() } // Timer produces a timer that will emit a time some duration after now. func (m *Mock) Timer(d time.Duration) *Timer { ch := make(chan time.Time) t := &Timer{ C: ch, c: ch, mock: m, next: m.now.Add(d), } m.addTimer(t) return t } func (m *Mock) addTimer(t *Timer) { m.Lock() defer m.Unlock() heap.Push(&m.timers, t) } // After produces a channel that will emit the time after a duration passes. func (m *Mock) After(d time.Duration) <-chan time.Time { return m.Timer(d).C } // AfterFunc waits for the duration to elapse and then executes a function. // A Timer is returned that can be stopped. func (m *Mock) AfterFunc(d time.Duration, f func()) *Timer { t := m.Timer(d) go func() { <-t.c f() }() nap() return t } // Now returns the current wall time on the mock clock. func (m *Mock) Now() time.Time { m.Lock() defer m.Unlock() return m.now } // Sleep pauses the goroutine for the given duration on the mock clock. // The clock must be moved forward in a separate goroutine. func (m *Mock) Sleep(d time.Duration) { <-m.After(d) } // Timer represents a single event. type Timer struct { C <-chan time.Time c chan time.Time next time.Time // next tick time mock *Mock // mock clock } func (t *Timer) Next() time.Time { return t.next } func (t *Timer) Tick() { select { case t.c <- t.next: default: } nap() } // Sleep momentarily so that other goroutines can process. func nap() { time.Sleep(1 * time.Millisecond) }
clock/clock.go
0.831143
0.446314
clock.go
starcoder
package block import ( "github.com/df-mc/dragonfly/server/block/cube" "github.com/df-mc/dragonfly/server/item" "github.com/df-mc/dragonfly/server/world" "github.com/go-gl/mathgl/mgl64" "math/rand" ) // Kelp is an underwater block which can grow on top of solids underwater. type Kelp struct { empty transparent // Age is the age of the kelp block which can be 0-25. If age is 25, kelp won't grow any further. Age int } // BoneMeal ... func (k Kelp) BoneMeal(pos cube.Pos, w *world.World) bool { for y := pos.Y(); y < cube.MaxY; y++ { currentPos := cube.Pos{pos.X(), y, pos.Z()} block := w.Block(currentPos) if kelp, ok := block.(Kelp); ok { if kelp.Age == 25 { break } continue } if water, ok := block.(Water); ok && water.Depth == 8 { w.PlaceBlock(currentPos, Kelp{Age: k.Age + 1}) return true } break } return false } // BreakInfo ... func (k Kelp) BreakInfo() BreakInfo { return newBreakInfo(0, alwaysHarvestable, nothingEffective, oneOf(k)) } // EncodeItem ... func (Kelp) EncodeItem() (name string, meta int16) { return "minecraft:kelp", 0 } // EncodeBlock ... func (k Kelp) EncodeBlock() (name string, properties map[string]interface{}) { return "minecraft:kelp", map[string]interface{}{"kelp_age": int32(k.Age)} } // CanDisplace will return true if the liquid is Water, since kelp can waterlog. func (Kelp) CanDisplace(b world.Liquid) bool { _, water := b.(Water) return water } // SideClosed will always return false since kelp doesn't close any side. func (Kelp) SideClosed(cube.Pos, cube.Pos, *world.World) bool { return false } // withRandomAge returns a new Kelp block with its age value randomized between 0 and 24. func (k Kelp) withRandomAge() Kelp { k.Age = rand.Intn(25) return k } // UseOnBlock ... func (k Kelp) UseOnBlock(pos cube.Pos, face cube.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) { pos, _, used = firstReplaceable(w, pos, face, k) if !used { return } below := pos.Add(cube.Pos{0, -1}) belowBlock := w.Block(below) if _, kelp := belowBlock.(Kelp); !kelp { if !belowBlock.Model().FaceSolid(below, cube.FaceUp, w) { return false } } liquid, ok := w.Liquid(pos) if !ok { return false } else if _, ok := liquid.(Water); !ok || liquid.LiquidDepth() < 8 { return false } // When first placed, kelp gets a random age between 0 and 24. place(w, pos, k.withRandomAge(), user, ctx) return placed(ctx) } // NeighbourUpdateTick ... func (k Kelp) NeighbourUpdateTick(pos, changed cube.Pos, w *world.World) { if _, ok := w.Liquid(pos); !ok { w.BreakBlockWithoutParticles(pos) return } if changed.Y()-1 == pos.Y() { // When a kelp block is broken above, the kelp block underneath it gets a new random age. w.PlaceBlock(pos, k.withRandomAge()) } below := pos.Add(cube.Pos{0, -1}) belowBlock := w.Block(below) if _, kelp := belowBlock.(Kelp); !kelp { if !belowBlock.Model().FaceSolid(below, cube.FaceUp, w) { w.BreakBlockWithoutParticles(pos) } } } // RandomTick ... func (k Kelp) RandomTick(pos cube.Pos, w *world.World, r *rand.Rand) { // Every random tick, there's a 14% chance for Kelp to grow if its age is below 25. if r.Intn(100) < 15 && k.Age < 25 { abovePos := pos.Add(cube.Pos{0, 1}) liquid, ok := w.Liquid(abovePos) // For kelp to grow, there must be only water above. if !ok { return } else if _, ok := liquid.(Water); ok { switch w.Block(abovePos).(type) { case Air, Water: w.PlaceBlock(abovePos, Kelp{Age: k.Age + 1}) if liquid.LiquidDepth() < 8 { // When kelp grows into a water block, the water block becomes a source block. w.SetLiquid(abovePos, Water{Still: true, Depth: 8, Falling: false}) } } } } } // allKelp returns all possible states of a kelp block. func allKelp() (b []world.Block) { for i := 0; i < 26; i++ { b = append(b, Kelp{Age: i}) } return }
server/block/kelp.go
0.631822
0.457016
kelp.go
starcoder
package main var cmdUsage = map[string]string{ "docs-commands-facts": `Discover and list facts on this system.`, "docs-commands-help": `The "help" shows a list of commands or help for one command.`, "docs-commands": `Arc is controlled via a very easy to use command-line interface (CLI).`, "docs-commands-init": `The "init" command initializes server configuration.`, "docs-commands-list": `The "list" command shows all available agents and their actions.`, "docs-commands-restart": `The "restart" command restart agent services.`, "docs-commands-run": `The "arc run" execute an agent action [REFERENCE ACTIONS DOC PAGE FROM HERE] on a remote Arc server.`, "docs-commands-server": `Run the Arc daemon.`, "docs-commands-start": `The "start" command start agent service.`, "docs-commands-status": `The "status" command gives the service status.`, "docs-commands-stop": `The "stop" command stop agent services.`, "docs-commands-update": `The "update" command check for new updates and update to the last version.`, "docs-commands-renewcert": `The "renewcert" command downloads a new cert.`, } var cmdDescription = map[string]string{ "docs-commands-facts": `Discover and list facts on this system. The "facts" command collects information from the system to provide a simple and easy to understand view of the machine where Arc is running.`, "docs-commands-help": `The "help" command shows a list of commands or help for one specific command.`, "docs-commands": `Arc is controlled via a very easy to use command-line interface (CLI). Arc is only a single command-line application: "arc". This application then takes a subcommand such as "server" or "run". The complete list of subcommands is in the navigation to the left. The Arc CLI is a well-behaved command line application. In erroneous cases, a non-zero exit status will be returned. It also responds to "-h" and "--help" as you'd most likely expect.`, "docs-commands-init": `Coming soon...`, "docs-commands-list": `The "list" command shows all available agents and their actions. The payload requirements is action dependent and it should be looked up in the corresponding implementation. Some payload examples can be found in the [run command](/docs/commands/run.html) documentation. A complete explanation over the available agents can be found in the [arc server](/docs/server/agents.html) documentation topic.`, "docs-commands-restart": `Coming soon...`, "docs-commands-run": `The "arc run" execute an agent action [REFERENCE ACTIONS DOC PAGE FROM HERE] on a remote Arc server. Example: "arc run -endpoint tcp://localhost:1883 -identity darwin rpc version" It prints the current version of the Arc running on the remote server with the identity "darwin". 0.1.0-dev(ae07667) Example: "arc run -endpoint tcp://localhost:1883 -identity darwin -payload "echo Script start; for i in {1..5}; do echo \$i; sleep 1s; done; echo Script done" execute script" Script start 1 2 3 4 5 Script done It runs the script given as a payload on the remote server with identity "darwin". If the script gets to complicated or too long to give it as a payload, there is possibility to write a bash script file and give it to the "run" command as the following example: Example: "arc run -endpoint tcp://localhost:1883 -identity darwin -stdin execute script < script.sh" #!/bin/bash # script.sh echo Scritp start for i in {1..5}; do echo $i sleep 1s done echo Scritp done`, "docs-commands-server": `Run the Arc daemon. Due to the power and complexity of this command, the Arc server is documented in its own section. See the [Arc Server](/docs/server/basics.html) section for more information on how to use this command and the options it has.`, "docs-commands-start": `Coming soon...`, "docs-commands-status": `Coming soon...`, "docs-commands-stop": `Coming soon...`, "docs-commands-update": `The "update" command checks for the last version available, asks for user confirmation and triggers an update. When the update is being triggered the existing Arc binary is replaced with the new one.`, }
descriptions.go
0.54819
0.46223
descriptions.go
starcoder
// Package boxtree provides a very fast, static, flat (augmented) 2D interval Tree for reverse 2D range searches (box overlap). package boxtree import ( "math" "math/rand" ) // Box is the main interface expected by NewBOXTree(); requires Limits method to access box limits. type Box interface { Limits() (Lower, Upper []float64) } // BOXTree is the main package object; // holds Slice of reference indices and the respective box limits. type BOXTree struct { idxs []int lmts [][]float64 } // buildTree is the internal tree construction function; // creates, sorts and augments nodes into Slices. func (boT *BOXTree) buildTree(bxs []Box) { boT.idxs = make([]int, len(bxs)) boT.lmts = make([][]float64, 3*len(bxs)) for i, v := range bxs { boT.idxs[i] = i l, u := v.Limits() boT.lmts[3*i] = l boT.lmts[3*i+1] = u boT.lmts[3*i+2] = []float64{0} } sort(boT.lmts, boT.idxs, 0) augment(boT.lmts, boT.idxs, 0) } // Overlaps is the main entry point for box searches; // traverses the tree and collects boxes that overlap with the given values. func (boT *BOXTree) Overlaps(vals []float64) []int { stk := []int{0, len(boT.idxs) - 1, 0} res := []int{} for len(stk) > 0 { ax := stk[len(stk)-1] stk = stk[:len(stk)-1] rb := stk[len(stk)-1] stk = stk[:len(stk)-1] lb := stk[len(stk)-1] stk = stk[:len(stk)-1] if lb == rb+1 { continue } cn := int(math.Ceil(float64(lb+rb) / 2.0)) nm := boT.lmts[3*cn+2][0] _ax := (ax + 1) % 2 if vals[ax] <= nm { stk = append(stk, lb) stk = append(stk, cn-1) stk = append(stk, _ax) } l := boT.lmts[3*cn] if l[ax] <= vals[ax] { stk = append(stk, cn+1) stk = append(stk, rb) stk = append(stk, _ax) u := boT.lmts[3*cn+1] if vals[ax] <= u[ax] && vals[_ax] <= u[_ax] && l[_ax] <= vals[_ax] { res = append(res, boT.idxs[cn]) } } } return res } // NewBOXTree is the main initialization function; // creates the tree from the given Slice of Box. func NewBOXTree(bxs []Box) *BOXTree { boT := BOXTree{} boT.buildTree(bxs) return &boT } // augment is an internal utility function, adding maximum value of all child nodes to the current node. func augment(lmts [][]float64, idxs []int, ax int) { if len(idxs) < 1 { return } max := 0.0 for idx := range idxs { if lmts[3*idx+1][ax] > max { max = lmts[3*idx+1][ax] } } r := len(idxs) >> 1 lmts[3*r+2][0] = max augment(lmts[:3*r], idxs[:r], (ax+1)%2) augment(lmts[3*r+3:], idxs[r+1:], (ax+1)%2) } // sort is an internal utility function, sorting the tree by lowest limits using Random Pivot QuickSearch func sort(lmts [][]float64, idxs []int, ax int) { if len(idxs) < 2 { return } l, r := 0, len(idxs)-1 p := rand.Int() % len(idxs) idxs[p], idxs[r] = idxs[r], idxs[p] lmts[3*p], lmts[3*p+1], lmts[3*p+2], lmts[3*r], lmts[3*r+1], lmts[3*r+2] = lmts[3*r], lmts[3*r+1], lmts[3*r+2], lmts[3*p], lmts[3*p+1], lmts[3*p+2] for i := range idxs { if lmts[3*i][ax] < lmts[3*r][ax] { idxs[l], idxs[i] = idxs[i], idxs[l] lmts[3*l], lmts[3*l+1], lmts[3*l+2], lmts[3*i], lmts[3*i+1], lmts[3*i+2] = lmts[3*i], lmts[3*i+1], lmts[3*i+2], lmts[3*l], lmts[3*l+1], lmts[3*l+2] l++ } } idxs[l], idxs[r] = idxs[r], idxs[l] lmts[3*l], lmts[3*l+1], lmts[3*l+2], lmts[3*r], lmts[3*r+1], lmts[3*r+2] = lmts[3*r], lmts[3*r+1], lmts[3*r+2], lmts[3*l], lmts[3*l+1], lmts[3*l+2] sort(lmts[:3*l], idxs[:l], (ax+1)%2) sort(lmts[3*l+3:], idxs[l+1:], (ax+1)%2) }
boxtree.go
0.666497
0.511595
boxtree.go
starcoder
package schedule import ( "fmt" "github.com/marcsantiago/gocron" "strings" "time" ) // Definition holds the data defining a schedule definition type Definition struct { // Internal value (every 1 minute would be expressed with an interval of 1). Must be set explicitly or implicitly (a weekday value implicitly sets the interval to 1) Interval uint64 // Must be set explicitly or implicitly ("weeks" is implicitly set when "Weekday" is set). Valid time units are: "weeks", "hours", "days", "minutes", "seconds" Unit string // Optional day of the week. If set, unit and interval are ignored and implicitly considered to be "every 1 week" Weekday string // Optional "at time" value (i.e. "10:30") AtTime string } // Unit values const ( Weeks = "weeks" Hours = "hours" Days = "days" Minutes = "minutes" Seconds = "seconds" ) var weekdayToNumeral = map[string]time.Weekday{ time.Monday.String(): time.Monday, time.Tuesday.String(): time.Tuesday, time.Wednesday.String(): time.Wednesday, time.Thursday.String(): time.Thursday, time.Friday.String(): time.Friday, time.Saturday.String(): time.Saturday, time.Sunday.String(): time.Sunday, } // Returns a human-friendly string for the schedule definition func (d Definition) String() string { var b strings.Builder fmt.Fprintf(&b, "Every ") if d.Weekday != "" { fmt.Fprintf(&b, "%s", d.Weekday) } else if d.Interval == 1 { fmt.Fprintf(&b, "%s", strings.TrimSuffix(d.Unit, "s")) } else { fmt.Fprintf(&b, "%d %s", d.Interval, d.Unit) } if d.AtTime != "" { fmt.Fprintf(&b, " at %s", d.AtTime) } return b.String() } // Option defines an option for a Slackscot type scheduleOption func(j *gocron.Job) // optionWeekday sets the weekday of a recurring job func optionWeekday(weekday string) func(j *gocron.Job) { return func(j *gocron.Job) { switch weekday { case time.Monday.String(): j = j.Monday() case time.Tuesday.String(): j = j.Tuesday() case time.Wednesday.String(): j = j.Wednesday() case time.Thursday.String(): j = j.Thursday() case time.Friday.String(): j = j.Friday() case time.Saturday.String(): j = j.Saturday() case time.Sunday.String(): j = j.Sunday() } } } // optionUnit sets the unit of a recurring job func optionUnit(unit string) func(j *gocron.Job) { return func(j *gocron.Job) { switch unit { case Weeks: j = j.Weeks() case Hours: j = j.Hours() case Days: j = j.Days() case Minutes: j = j.Minutes() case Seconds: j = j.Seconds() } } } // optionAtTime sets the AtTime of a recurring job func optionAtTime(atTime string) func(j *gocron.Job) { return func(j *gocron.Job) { j = j.At(atTime) } } // NewJob sets up the gocron.Job with the schedule and leaves the task undefined for the caller to set up func NewJob(s *gocron.Scheduler, def Definition) (j *gocron.Job, err error) { j = s.Every(def.Interval, false) scheduleOptions := make([]scheduleOption, 0) if def.Weekday != "" { scheduleOptions = append(scheduleOptions, optionWeekday(def.Weekday)) } else if def.Unit != "" { scheduleOptions = append(scheduleOptions, optionUnit(def.Unit)) } if def.AtTime != "" { scheduleOptions = append(scheduleOptions, optionAtTime(def.AtTime)) } for _, option := range scheduleOptions { option(j) } if j.Err() != nil { return nil, j.Err() } return j, nil }
schedule/schedule.go
0.69987
0.425784
schedule.go
starcoder
package size import ( "fmt" "math" "math/rand" "regexp" "strconv" "strings" ) // Size is a signed type to avoid overflow problems when doing arithmetic and // conversions to other signed types. type Size int64 const MaxSize = math.MaxInt64 const ( Bytes Size = 1 << (10 * iota) KiB MiB GiB TiB PiB EiB Byte = Bytes ) const ( KB Size = 1000 * Byte MB Size = 1000 * KB GB Size = 1000 * MB TB Size = 1000 * GB PB Size = 1000 * TB ) const ( BlockSize = 4 * KiB // ELFS block size ) func (s Size) String() string { var suffix string var value float64 value = float64(s) switch { case s >= EiB: suffix, value = "EiB", value/float64(EiB) case s >= PiB: suffix, value = "PiB", value/float64(PiB) case s >= TiB: suffix, value = "TiB", value/float64(TiB) case s >= GiB: suffix, value = "GiB", value/float64(GiB) case s >= MiB: suffix, value = "MiB", value/float64(MiB) case s >= KiB: suffix, value = "KiB", value/float64(KiB) case s == 1: suffix = "byte" case s == 0: suffix = "" default: suffix = "bytes" } formatted := fmt.Sprintf("%.1f", value) formatted = strings.TrimSuffix(formatted, ".0") if suffix != "" { formatted = formatted + " " + suffix } return formatted } func Parse(s string) (Size, error) { var ( suffix string value float64 err error newSize Size ) if s == "" { return 0, fmt.Errorf("size: invalid size '%v'", s) } re := regexp.MustCompile(`(\d+(:?\.\d+)?)\s*(B|(:?[EPTGMK](:?i?B)?))?`) groups := re.FindAllStringSubmatch(s, -1) if len(groups) == 0 { return 0, fmt.Errorf("size: Incorrect format: %s", s) } value, err = strconv.ParseFloat(groups[0][1], 64) if err != nil { return 0, fmt.Errorf( "size: failed converting '%v' to float64, error=%v", groups[0][1], err, ) } if len(groups[0]) > 3 { suffix = groups[0][3] } switch suffix { case "EiB", "E": newSize = Size(value * float64(EiB)) case "PiB", "P": newSize = Size(value * float64(PiB)) case "TiB", "T": newSize = Size(value * float64(TiB)) case "GiB", "G": newSize = Size(value * float64(GiB)) case "MiB", "M": newSize = Size(value * float64(MiB)) case "KiB", "K": newSize = Size(value * float64(KiB)) case "PB": newSize = Size(value * float64(PB)) case "TB": newSize = Size(value * float64(TB)) case "GB": newSize = Size(value * float64(GB)) case "MB": newSize = Size(value * float64(MB)) case "KB": newSize = Size(value * float64(KB)) default: newSize = Size(value) } return newSize, err } func (s *Size) Unmarshal(buf []byte) error { r, err := Parse(string(buf)) if err != nil { return err } *s = r return nil } // Blocks returns the number of blocks that the Size represents func (s Size) Blocks() int { return int(s / BlockSize) } // FromBlocks creates a size that is equal to the specified amount of blocks func FromBlocks(blocks int) Size { return Size(blocks) * BlockSize } // Max of two sizes func Max(x, y Size) Size { if x > y { return x } return y } // Min of two sizes func Min(x, y Size) Size { if x < y { return x } return y } // Abs value of size func Abs(x Size) Size { if x > 0 { return x } return -x } // Randn returns a random number in the range [0,n). func Randn(n Size) Size { if n == 0 { return Size(0) } return Size(rand.Int63n(int64(n))) } // Similar determines whether the provided sizes are "close enough". func Similar(x, y Size, epsilon float64) bool { if math.Abs(1-float64(x)/float64(y)) > epsilon { return false } return true }
pkg/size/size.go
0.655667
0.454896
size.go
starcoder
//nolint package p0641 type MyCircularDeque struct { values []int start int end int size int } /** Initialize your data structure here. Set the size of the deque to be k. */ func Constructor(k int) MyCircularDeque { return MyCircularDeque{ values: make([]int, k), start: 0, end: 0, size: 0, } } /** Adds an item at the front of Deque. Return true if the operation is successful. */ func (this *MyCircularDeque) InsertFront(value int) bool { if this.size >= len(this.values) { return false } this.start-- if this.start < 0 { this.start = len(this.values) - 1 } this.values[this.start] = value this.size++ return true } /** Adds an item at the rear of Deque. Return true if the operation is successful. */ func (this *MyCircularDeque) InsertLast(value int) bool { if this.size >= len(this.values) { return false } this.values[this.end] = value this.size++ this.end++ if this.end >= len(this.values) { this.end = this.end % len(this.values) } return true } /** Deletes an item from the front of Deque. Return true if the operation is successful. */ func (this *MyCircularDeque) DeleteFront() bool { if this.size <= 0 { return false } this.start++ if this.start >= len(this.values) { this.start = this.start % len(this.values) } this.size-- return true } /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ func (this *MyCircularDeque) DeleteLast() bool { if this.size == 0 { return false } this.size-- this.end-- if this.end < 0 { this.end = len(this.values) - 1 } return true } /** Get the front item from the deque. */ func (this *MyCircularDeque) GetFront() int { if this.size == 0 { return -1 } return this.values[this.start] } /** Get the last item from the deque. */ func (this *MyCircularDeque) GetRear() int { if this.size == 0 { return -1 } end := this.end - 1 if end < 0 { end = len(this.values) - 1 } return this.values[end] } /** Checks whether the circular deque is empty or not. */ func (this *MyCircularDeque) IsEmpty() bool { return this.size == 0 } /** Checks whether the circular deque is full or not. */ func (this *MyCircularDeque) IsFull() bool { return this.size == len(this.values) } /** * Your MyCircularDeque object will be instantiated and called as such: * obj := Constructor(k); * param_1 := obj.InsertFront(value); * param_2 := obj.InsertLast(value); * param_3 := obj.DeleteFront(); * param_4 := obj.DeleteLast(); * param_5 := obj.GetFront(); * param_6 := obj.GetRear(); * param_7 := obj.IsEmpty(); * param_8 := obj.IsFull(); */
pkg/p0641/p0641.go
0.605449
0.645846
p0641.go
starcoder
package geom func min(x, y int) int { if x < y { return x } return y } func max(x, y int) int { if x > y { return x } return y } type Coord struct { X, Y int } type Rectangle struct { Min, Max Coord } func Add(lhs, rhs Coord) Coord { return Coord{lhs.X + rhs.X, lhs.Y + rhs.Y} } func (c *Coord) Add(rhs Coord) { c.X += rhs.X c.Y += rhs.Y } func Sub(lhs, rhs Coord) Coord { return Coord{lhs.X - rhs.X, lhs.Y - rhs.Y} } func (c *Coord) Sub(rhs Coord) { c.X -= rhs.X c.Y -= rhs.Y } func (r *Rectangle) Normalise() { if r.Min.X > r.Max.X { r.Min.X, r.Max.X = r.Max.X, r.Min.X } if r.Min.Y > r.Max.Y { r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y } } func Normalise(r Rectangle) Rectangle { r.Normalise() return r } func (r *Rectangle) Width() int { return r.Max.X - r.Min.X } func (r *Rectangle) Height() int { return r.Max.Y - r.Min.Y } func (r *Rectangle) Size() Coord { return Coord{r.Width(), r.Height()} } func (r *Rectangle) IsEmpty() bool { return (r.Min.X == r.Max.X) || (r.Min.Y == r.Max.Y) } func (r *Rectangle) IsNormal() bool { return (r.Min.X <= r.Max.X) && (r.Min.Y <= r.Max.Y) } func (r *Rectangle) Expand(c Coord) { r.Min.Sub(c) r.Max.Add(c) } func Expand(r Rectangle, c Coord) Rectangle { r.Expand(c) return r } func (r *Rectangle) Translate(c Coord) { r.Min.Add(c) r.Max.Add(c) } func Translate(r Rectangle, c Coord) Rectangle { r.Translate(c) return r } func PointInRectangle(r Rectangle, p Coord) bool { return (r.Min.X <= p.X) && (r.Min.Y <= p.Y) && (p.X < r.Max.X) && (p.Y < r.Max.Y) } func RectangleIntersection(r1, r2 Rectangle) (intersect Rectangle, ok bool) { intersect = Rectangle{ Min: Coord{max(r1.Min.X, r2.Min.X), max(r1.Min.Y, r2.Min.Y)}, Max: Coord{min(r1.Max.X, r2.Max.X), min(r1.Max.Y, r2.Max.Y)}, } ok = intersect.IsNormal() return } func RectangleUnion(r1, r2 Rectangle) Rectangle { return Rectangle{ Min: Coord{min(r1.Min.X, r2.Min.X), min(r1.Min.Y, r2.Min.Y)}, Max: Coord{max(r1.Max.X, r2.Max.X), max(r1.Max.Y, r2.Max.Y)}, } } func RectangleContains(rOuter, rInner Rectangle) bool { return PointInRectangle(rOuter, rInner.Min) && PointInRectangle(rOuter, rInner.Max) } func RectangleFromPosSize(pos, size Coord) Rectangle { return Rectangle{pos, Add(pos, size)} } func RectangleFromSize(size Coord) Rectangle { return Rectangle{Max: size} }
geom/geom.go
0.877818
0.520009
geom.go
starcoder
package loader import ( "fmt" "strconv" "strings" "github.com/pingcap/log" "go.uber.org/zap" ) // DMLType represents the dml type type DMLType int // DMLType types const ( UnknownDMLType DMLType = 0 InsertDMLType DMLType = 1 UpdateDMLType DMLType = 2 DeleteDMLType DMLType = 3 ) // DML holds the dml info type DML struct { Database string Table string Tp DMLType // only set when Tp = UpdateDMLType OldValues map[string]interface{} Values map[string]interface{} info *tableInfo } // DDL holds the ddl info type DDL struct { Database string Table string SQL string } // Txn holds transaction info, an DDL or DML sequences type Txn struct { DMLs []*DML DDL *DDL AppliedTS int64 // This field is used to hold arbitrary data you wish to include so it // will be available when receiving on the Successes channel Metadata interface{} } // AppendDML append a dml func (t *Txn) AppendDML(dml *DML) { t.DMLs = append(t.DMLs, dml) } // NewDDLTxn return a Txn func NewDDLTxn(db string, table string, sql string) *Txn { txn := new(Txn) txn.DDL = &DDL{ Database: db, Table: table, SQL: sql, } return txn } func (t *Txn) String() string { if t.isDDL() { return fmt.Sprintf("{ddl: %s}", t.DDL.SQL) } return fmt.Sprintf("dml: %v", t.DMLs) } func (t *Txn) isDDL() bool { return t.DDL != nil } func (dml *DML) primaryKeys() []string { if dml.info.primaryKey == nil { return nil } return dml.info.primaryKey.columns } func (dml *DML) primaryKeyValues() []interface{} { names := dml.primaryKeys() values := make([]interface{}, 0, len(names)) for _, name := range names { v := dml.Values[name] values = append(values, v) } return values } func (dml *DML) formatKey() string { return formatKey(dml.primaryKeyValues()) } func (dml *DML) updateKey() bool { if len(dml.OldValues) == 0 { return false } values := dml.primaryKeyValues() oldValues := dml.oldPrimaryKeyValues() for i := 0; i < len(values); i++ { if values[i] != oldValues[i] { return true } } return false } func (dml *DML) String() string { return fmt.Sprintf("{db: %s, table: %s,tp: %v values: %d old_values: %d}", dml.Database, dml.Table, dml.Tp, len(dml.Values), len(dml.OldValues)) } func (dml *DML) oldPrimaryKeyValues() []interface{} { if len(dml.OldValues) == 0 { return dml.primaryKeyValues() } names := dml.primaryKeys() values := make([]interface{}, 0, len(names)) for _, name := range names { v := dml.OldValues[name] values = append(values, v) } return values } // TableName returns the fully qualified name of the DML's table func (dml *DML) TableName() string { return quoteSchema(dml.Database, dml.Table) } func (dml *DML) updateSQL() (sql string, args []interface{}) { builder := new(strings.Builder) fmt.Fprintf(builder, "UPDATE %s SET ", dml.TableName()) for name, arg := range dml.Values { if len(args) > 0 { builder.WriteByte(',') } fmt.Fprintf(builder, "%s = ?", quoteName(name)) args = append(args, arg) } builder.WriteString(" WHERE ") whereArgs := dml.buildWhere(builder) args = append(args, whereArgs...) builder.WriteString(" LIMIT 1") sql = builder.String() return } func (dml *DML) buildWhere(builder *strings.Builder) (args []interface{}) { wnames, wargs := dml.whereSlice() for i := 0; i < len(wnames); i++ { if i > 0 { builder.WriteString(" AND ") } if wargs[i] == nil { builder.WriteString(quoteName(wnames[i]) + " IS NULL") } else { builder.WriteString(quoteName(wnames[i]) + " = ?") args = append(args, wargs[i]) } } return } func (dml *DML) whereValues(names []string) (values []interface{}) { valueMap := dml.Values if dml.Tp == UpdateDMLType { valueMap = dml.OldValues } for _, name := range names { v := valueMap[name] values = append(values, v) } return } func (dml *DML) whereSlice() (colNames []string, args []interface{}) { // Try to use unique key values when available for _, index := range dml.info.uniqueKeys { values := dml.whereValues(index.columns) notAnyNil := true for i := 0; i < len(values); i++ { if values[i] == nil { notAnyNil = false break } } if notAnyNil { return index.columns, values } } // Fallback to use all columns return dml.info.columns, dml.whereValues(dml.info.columns) } func (dml *DML) deleteSQL() (sql string, args []interface{}) { builder := new(strings.Builder) fmt.Fprintf(builder, "DELETE FROM %s WHERE ", dml.TableName()) args = dml.buildWhere(builder) builder.WriteString(" LIMIT 1") sql = builder.String() return } func (dml *DML) replaceSQL() (sql string, args []interface{}) { info := dml.info sql = fmt.Sprintf("REPLACE INTO %s(%s) VALUES(%s)", dml.TableName(), buildColumnList(info.columns), holderString(len(info.columns))) for _, name := range info.columns { v := dml.Values[name] args = append(args, v) } return } func (dml *DML) insertSQL() (sql string, args []interface{}) { sql, args = dml.replaceSQL() sql = strings.Replace(sql, "REPLACE", "INSERT", 1) return } func (dml *DML) sql() (sql string, args []interface{}) { switch dml.Tp { case InsertDMLType: return dml.insertSQL() case UpdateDMLType: return dml.updateSQL() case DeleteDMLType: return dml.deleteSQL() } log.Debug("get sql for dml", zap.Reflect("dml", dml), zap.String("sql", sql), zap.Reflect("args", args)) return } func formatKey(values []interface{}) string { builder := new(strings.Builder) for i, v := range values { if i != 0 { builder.WriteString("--") } fmt.Fprintf(builder, "%v", v) } return builder.String() } func getKey(names []string, values map[string]interface{}) string { builder := new(strings.Builder) for _, name := range names { v := values[name] if v == nil { continue } fmt.Fprintf(builder, "(%s: %v)", name, v) } return builder.String() } func getKeys(dml *DML) (keys []string) { info := dml.info tableName := dml.TableName() var addOldKey int var addNewKey int for _, index := range info.uniqueKeys { key := getKey(index.columns, dml.Values) if len(key) > 0 { addNewKey++ keys = append(keys, key+tableName) } } if dml.Tp == UpdateDMLType { for _, index := range info.uniqueKeys { key := getKey(index.columns, dml.OldValues) if len(key) > 0 { addOldKey++ keys = append(keys, key+tableName) } } } if addNewKey == 0 { key := getKey(info.columns, dml.Values) + tableName key = strconv.Itoa(int(genHashKey(key))) keys = append(keys, key) } if dml.Tp == UpdateDMLType && addOldKey == 0 { key := getKey(info.columns, dml.OldValues) + tableName key = strconv.Itoa(int(genHashKey(key))) keys = append(keys, key) } return }
pkg/loader/model.go
0.588653
0.462352
model.go
starcoder
package xmetricstest import ( "github.com/Comcast/webpa-common/xmetrics" "github.com/go-kit/kit/metrics" ) // testingT is the expected behavior for a testing object. *testing.T implements this interface. type testingT interface { Errorf(string, ...interface{}) } // expectation is a metric expectation. The metric will implement one of the go-kit metrics interfaces, e.g. Counter. type expectation func(t testingT, name string, metric interface{}) bool // Value returns an expectation for a metric to be of a certain value. The metric in question must implement // xmetrics.Valuer, which both counter and gauge do. This assertion does not constrain the type of metric beyond // simply exposing a value. Use another expectation to assert that a metric is of a more specific type. func Value(expected float64) expectation { return func(t testingT, n string, m interface{}) bool { v, ok := m.(xmetrics.Valuer) if !ok { t.Errorf("metric %s does not expose a value (i.e. is not a counter or gauge)", n) return false } if actual := v.Value(); actual != expected { t.Errorf("metric %s does not have the expected value %f. actual value is %f", n, expected, actual) return false } return true } } // Minimum returns an expectation for a metric to be at least a certain value. The metric in question // must implement xmetrics.Valuer, as with the Value expectation. func Minimum(expected float64) expectation { return func(t testingT, n string, m interface{}) bool { v, ok := m.(xmetrics.Valuer) if !ok { t.Errorf("metric %s does not expose a value (i.e. is not a counter or gauge)", n) return false } if actual := v.Value(); actual < expected { t.Errorf("metric %s is smaller than the expected value %f. actual value is %f", n, expected, actual) return false } return true } } // Counter is an expectation that a certain metric is a counter. It must implement the go-kit metrics.Counter interface. func Counter(t testingT, n string, m interface{}) bool { _, ok := m.(metrics.Counter) if !ok { t.Errorf("metric %s is not a counter", n) } return ok } // Gauge is an expectation that a certain metric is a gauge. It must implement the go-kit metrics.Gauge interface. func Gauge(t testingT, n string, m interface{}) bool { _, ok := m.(metrics.Gauge) if !ok { t.Errorf("metric %s is not a gauge", n) } return ok } // Histogram is an expectation that a certain metric is a histogram. It must implement the go-kit metrics.Histogram interface. func Histogram(t testingT, n string, m interface{}) bool { _, ok := m.(metrics.Histogram) if !ok { t.Errorf("metric %s is not a histogram", n) } return ok }
xmetrics/xmetricstest/expectations.go
0.870694
0.57087
expectations.go
starcoder
package types import "github.com/genjidb/genji/internal/errors" // A Value stores encoded data alongside its type. type value struct { tp ValueType v interface{} } var _ Value = &value{} // NewNullValue returns a Null value. func NewNullValue() Value { return &value{ tp: NullValue, } } // NewBoolValue encodes x and returns a value. func NewBoolValue(x bool) Value { return &value{ tp: BoolValue, v: x, } } // NewIntegerValue encodes x and returns a value whose type depends on the // magnitude of x. func NewIntegerValue(x int64) Value { return &value{ tp: IntegerValue, v: int64(x), } } // NewDoubleValue encodes x and returns a value. func NewDoubleValue(x float64) Value { return &value{ tp: DoubleValue, v: x, } } // NewBlobValue encodes x and returns a value. func NewBlobValue(x []byte) Value { return &value{ tp: BlobValue, v: x, } } // NewTextValue encodes x and returns a value. func NewTextValue(x string) Value { return &value{ tp: TextValue, v: x, } } // NewArrayValue returns a value of type Array. func NewArrayValue(a Array) Value { return &value{ tp: ArrayValue, v: a, } } // NewDocumentValue returns a value of type Document. func NewDocumentValue(d Document) Value { return &value{ tp: DocumentValue, v: d, } } // NewEmptyValue creates an empty value with the given type. // V() always returns nil. func NewEmptyValue(t ValueType) Value { return &value{ tp: t, } } // NewValueWith creates a value with the given type and value. func NewValueWith(t ValueType, v interface{}) Value { return &value{ tp: t, v: v, } } func (v *value) V() interface{} { return v.v } func (v *value) Type() ValueType { return v.tp } // IsTruthy returns whether v is not equal to the zero value of its type. func IsTruthy(v Value) (bool, error) { if v.Type() == NullValue { return false, nil } b, err := IsZeroValue(v) return !b, err } // IsZeroValue indicates if the value data is the zero value for the value type. // This function doesn't perform any allocation. func IsZeroValue(v Value) (bool, error) { switch v.Type() { case BoolValue: return v.V() == false, nil case IntegerValue: return v.V() == int64(0), nil case DoubleValue: return v.V() == float64(0), nil case BlobValue: return v.V() == nil, nil case TextValue: return v.V() == "", nil case ArrayValue: // The zero value of an array is an empty array. // Thus, if GetByIndex(0) returns the ErrValueNotFound // it means that the array is empty. _, err := v.V().(Array).GetByIndex(0) if errors.Is(err, ErrValueNotFound) { return true, nil } return false, err case DocumentValue: err := v.V().(Document).Iterate(func(_ string, _ Value) error { // We return an error in the first iteration to stop it. return errors.Wrap(errStop) }) if err == nil { // If err is nil, it means that we didn't iterate, // thus the document is empty. return true, nil } if errors.Is(err, errStop) { // If err is errStop, it means that we iterate // at least once, thus the document is not empty. return false, nil } // An unexpecting error occurs, let's return it! return false, err } return false, nil }
types/value.go
0.782288
0.538255
value.go
starcoder
package distuv import ( "math" "golang.org/x/exp/rand" ) // AlphaStable represents an α-stable distribution with four parameters. // See https://en.wikipedia.org/wiki/Stable_distribution for more information. type AlphaStable struct { // Alpha is the stability parameter. // It is valid within the range 0 < α ≤ 2. Alpha float64 // Beta is the skewness parameter. // It is valid within the range -1 ≤ β ≤ 1. Beta float64 // C is the scale parameter. // It is valid when positive. C float64 // Mu is the location parameter. Mu float64 Src rand.Source } // ExKurtosis returns the excess kurtosis of the distribution. // ExKurtosis returns NaN when Alpha != 2. func (a AlphaStable) ExKurtosis() float64 { if a.Alpha == 2 { return 0 } return math.NaN() } // Mean returns the mean of the probability distribution. // Mean returns NaN when Alpha <= 1. func (a AlphaStable) Mean() float64 { if a.Alpha > 1 { return a.Mu } return math.NaN() } // Median returns the median of the distribution. // Median panics when Beta != 0, because then the mode is not analytically // expressible. func (a AlphaStable) Median() float64 { if a.Beta == 0 { return a.Mu } panic("distuv: cannot compute Median for Beta != 0") } // Mode returns the mode of the distribution. // Mode panics when Beta != 0, because then the mode is not analytically // expressible. func (a AlphaStable) Mode() float64 { if a.Beta == 0 { return a.Mu } panic("distuv: cannot compute Mode for Beta != 0") } // NumParameters returns the number of parameters in the distribution. func (a AlphaStable) NumParameters() int { return 4 } // Rand returns a random sample drawn from the distribution. func (a AlphaStable) Rand() float64 { // From https://en.wikipedia.org/wiki/Stable_distribution#Simulation_of_stable_variables const halfPi = math.Pi / 2 u := Uniform{-halfPi, halfPi, a.Src}.Rand() w := Exponential{1, a.Src}.Rand() if a.Alpha == 1 { f := halfPi + a.Beta*u x := (f*math.Tan(u) - a.Beta*math.Log(halfPi*w*math.Cos(u)/f)) / halfPi return a.C*(x+a.Beta*math.Log(a.C)/halfPi) + a.Mu } zeta := -a.Beta * math.Tan(halfPi*a.Alpha) xi := math.Atan(-zeta) / a.Alpha f := a.Alpha * (u + xi) g := math.Sqrt(1+zeta*zeta) * math.Pow(math.Cos(u-f)/w, 1-a.Alpha) / math.Cos(u) x := math.Pow(g, 1/a.Alpha) * math.Sin(f) return a.C*x + a.Mu } // Skewness returns the skewness of the distribution. // Skewness returns NaN when Alpha != 2. func (a AlphaStable) Skewness() float64 { if a.Alpha == 2 { return 0 } return math.NaN() } // StdDev returns the standard deviation of the probability distribution. func (a AlphaStable) StdDev() float64 { return math.Sqrt(a.Variance()) } // Variance returns the variance of the probability distribution. // Variance returns +Inf when Alpha != 2. func (a AlphaStable) Variance() float64 { if a.Alpha == 2 { return 2 * a.C * a.C } return math.Inf(1) }
stat/distuv/alphastable.go
0.905283
0.566978
alphastable.go
starcoder
package graphite import ( "errors" "github.com/ovh/erlenmeyer/core" ) // ---------------------------------------------------------------------------- // graphite functions implementations func absolute(node *core.Node, args []string, kwargs map[string]string) (*core.Node, error) { if len(args) < 1 { return nil, errors.New("The absolute function take one parameter which is a series or a list of series") } node.Left = core.NewNode(core.MapperPayload{ Mapper: "abs", PostWindow: "0", PreWindow: "0", Occurrences: "0", }) if args[0] != swap { return fetch(node.Left, []string{args[0], kwargs["from"], kwargs["until"]}, kwargs) } return node.Left, nil } func integral(node *core.Node, args []string, kwargs map[string]string) (*core.Node, error) { if len(args) < 1 { return nil, errors.New("The integral function take one parameter which are a series or a list of series") } node.Left = core.NewNode(core.WarpScriptPayload{ WarpScript: "0 INTEGRATE", }) if args[0] != swap { return fetch(node.Left, []string{args[0], kwargs["from"], kwargs["until"]}, kwargs) } return node.Left, nil } func interpolate(node *core.Node, args []string, kwargs map[string]string) (*core.Node, error) { if len(args) < 1 { return nil, errors.New("The interpolate function take two parameters which are a series or a list of series and optionally a number") } node.Left = core.NewNode(core.WarpScriptPayload{ WarpScript: "INTERPOLATE SORT", }) if args[0] != swap { return fetch(node.Left, []string{args[0], kwargs["from"], kwargs["until"]}, kwargs) } return node.Left, nil } func logarithm(node *core.Node, args []string, kwargs map[string]string) (*core.Node, error) { if len(args) < 1 { return nil, errors.New("The logarithm function take at list one parameter which is a list of series and optionally a number") } constant := "10" if len(args) < 2 { constant = args[1] } node.Left = core.NewNode(core.MapperPayload{ Constant: constant, Mapper: "log", Occurrences: "0", PostWindow: "0", PreWindow: "0", }) if args[0] != swap { return fetch(node.Left, []string{args[0], kwargs["from"], kwargs["until"]}, kwargs) } return node.Left, nil } func minMax(node *core.Node, args []string, kwargs map[string]string) (*core.Node, error) { if len(args) < 1 { return nil, errors.New("The minMax function take two parameters which is a list of series") } node.Left = core.NewNode(core.WarpScriptPayload{ WarpScript: "<% DROP NORMALIZE %> LMAP", }) if args[0] != swap { return fetch(node.Left, []string{args[0], kwargs["from"], kwargs["until"]}, kwargs) } return node.Left, nil } func pow(node *core.Node, args []string, kwargs map[string]string) (*core.Node, error) { if len(args) < 2 { return nil, errors.New("The pow function take two parameters which is a list of series and a number") } node.Left = core.NewNode(core.MapperPayload{ Mapper: "pow", Constant: args[1], Occurrences: "0", PostWindow: "0", PreWindow: "0", }) if args[0] != swap { return fetch(node.Left, []string{args[0], kwargs["from"], kwargs["until"]}, kwargs) } return node.Left, nil } func squareRoot(node *core.Node, args []string, kwargs map[string]string) (*core.Node, error) { if len(args) < 1 { return nil, errors.New("The squareRoot function take one parameter which is a list of series") } node.Left = core.NewNode(core.MapperPayload{ Constant: "0.5", Mapper: "pow", Occurrences: "0", PostWindow: "0", PreWindow: "0", }) if args[0] != swap { return fetch(node.Left, []string{args[0], kwargs["from"], kwargs["until"]}, kwargs) } return node.Left, nil }
proto/graphite/math.go
0.719876
0.406391
math.go
starcoder
package cards import ("math/rand"; "time") // Card is a struct holding the suit and value associated with a card. type Card struct { Suit string Value string } // NewCard creates a new instance of the card struct. func NewCard(suit, value string) Card { return Card{Suit: suit, Value: value} } // NewDeck creates a new deck of cards from a slice of suits and a slice of values. func NewDeck(suits, values []string) []Card { var deck []Card for _, suit := range suits { for _, value := range values { card := NewCard(suit, value) deck = append(deck, card) } } return deck } // NewStandardDeck creates a new standard western deck of cards with French suits // (Spades, Clubs, Hearts, and Diamonds). func NewStandardDeck() []Card { suits := []string{"♠", "♣", "♥", "♦"} values := []string{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"} return NewDeck(suits, values) } // NewFifthDimensionDeck creates a deck of 5°Dimension Playing Cards. // 5°Dimension is unique in that it has five suits, a Princess, a '1' different from Ace, // and a Joker for each of the five suits. // The five suits are: Spades, Clubs, Hearts, Diamonds, and Stars. // The 5°Dimension deck has a total of 80 cards, as opposed to the usual 52. func NewFifthDimensionDeck() []Card { suits := []string{"♠", "♣", "♥", "♦", "★"} values := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "P", "Q", "K", "A", "Joker"} return NewDeck(suits, values) } // Shuffle randomises the order of the cards in-place. // It uses "math/rand" internally, and thus needs to be seeded before use. // cards.Seed() and cards.SeedInt(int64) can be used for this func Shuffle(deck []Card) { for i := range deck { j := rand.Intn(i + 1) if i != j { deck[i], deck[j] = deck[j], deck[i] } } } // Shuffled is like Shuffle, except it's not destructive func Shuffled(deck []Card) []Card { cp := make([]Card, len(deck)) copy(cp, deck) Shuffle(cp) return cp } // SeedInt seeds the card randomiser using an int64 value as its seed. func SeedInt(value int64) { rand.Seed(value) } // Seed seeds the card randomiser using the current time in nanoseconds func Seed() { SeedInt(time.Now().UTC().UnixNano()) }
cards.go
0.749546
0.470858
cards.go
starcoder
package converter import ( "math" ) var ( Float64 Float64Converter ) type Float64Converter float64 func (c Float64Converter) SampleSize() int { return 8 } func (c Float64Converter) ToFloat32(input []byte, output []float32) { for i, o, ln := 0, 0, len(input); i < ln; i += c.SampleSize() { output[o] = Float64ToFloat32(ByteToFloat64(input[i], input[i+1], input[i+2], input[i+3], input[i+4], input[i+5], input[i+6], input[i+7])) o++ } } func (c Float64Converter) ToFloat64(input []byte, output []float64) { for i, o, ln := 0, 0, len(input); i < ln; i += c.SampleSize() { output[o] = ByteToFloat64(input[i], input[i+1], input[i+2], input[i+3], input[i+4], input[i+5], input[i+6], input[i+7]) o++ } } func (c Float64Converter) FromFloat32(input []float32, output []byte) { o := 0 for _, s := range input { output[o], output[o+1], output[o+2], output[o+3], output[o+4], output[o+5], output[o+6], output[o+7] = Float64ToByte(Float32ToFloat64(s)) o += c.SampleSize() } } func (c Float64Converter) FromFloat64(input []float64, output []byte) { o := 0 for _, s := range input { output[o], output[o+1], output[o+2], output[o+3], output[o+4], output[o+5], output[o+6], output[o+7] = Float64ToByte(s) o += c.SampleSize() } } func (c Float64Converter) ToFloat32Interleaved(input []byte, outputs [][]float32) { chs := len(outputs) for ch, output := range outputs { for i, o, ln := ch*c.SampleSize(), 0, len(input); i < ln; i += chs * c.SampleSize() { output[o] = Float64ToFloat32(ByteToFloat64(input[i], input[i+1], input[i+2], input[i+3], input[i+4], input[i+5], input[i+6], input[i+7])) o++ } } } func (c Float64Converter) ToFloat64Interleaved(input []byte, outputs [][]float64) { chs := len(outputs) for ch, output := range outputs { for i, o, ln := ch*c.SampleSize(), 0, len(input); i < ln; i += chs * c.SampleSize() { output[o] = ByteToFloat64(input[i], input[i+1], input[i+2], input[i+3], input[i+4], input[i+5], input[i+6], input[i+7]) o++ } } } func (c Float64Converter) FromFloat32Interleaved(inputs [][]float32, output []byte) { for i, o := 0, 0; o < len(output); i++ { for _, input := range inputs { output[o], output[o+1], output[o+2], output[o+3], output[o+4], output[o+5], output[o+6], output[o+7] = Float64ToByte(Float32ToFloat64(input[i])) o += c.SampleSize() } } } func (c Float64Converter) FromFloat64Interleaved(inputs [][]float64, output []byte) { for i, o := 0, 0; o < len(output); i++ { for _, input := range inputs { output[o], output[o+1], output[o+2], output[o+3], output[o+4], output[o+5], output[o+6], output[o+7] = Float64ToByte(input[i]) o += c.SampleSize() } } } func ByteToFloat64(a, b, c, d, e, f, g, h byte) float64 { return math.Float64frombits(uint64(a) | (uint64(b) << 8) | (uint64(c) << 16) | (uint64(d) << 24) | (uint64(e) << 32) | (uint64(f) << 40) | (uint64(g) << 48) | (uint64(h) << 56)) } func Float64ToByte(s float64) (byte, byte, byte, byte, byte, byte, byte, byte) { i := math.Float64bits(s) return byte(i), byte(i >> 8), byte(i >> 16), byte(i >> 24), byte(i >> 32), byte(i >> 40), byte(i >> 48), byte(i >> 56) }
converter/float64.go
0.518302
0.411466
float64.go
starcoder
package iso20022 // Tax related to an investment fund order. type Tax16 struct { // Type of tax applied. Type *TaxType10Code `xml:"Tp"` // Type of tax applied. ExtendedType *Extended350Code `xml:"XtndedTp"` // Amount of money resulting from the calculation of the tax. Amount *ActiveCurrencyAnd13DecimalAmount `xml:"Amt,omitempty"` // Rate used to calculate the tax. Rate *PercentageRate `xml:"Rate,omitempty"` // Country where the tax is due. Country *CountryCode `xml:"Ctry,omitempty"` // Party that receives the tax. The recipient of, and the party entitled to, the tax may be two different parties. RecipientIdentification *PartyIdentification2Choice `xml:"RcptId,omitempty"` // Indicates whether a tax exemption applies. ExemptionIndicator *YesNoIndicator `xml:"XmptnInd"` // Reason for a tax exemption. ExemptionReason *TaxExemptReason1Code `xml:"XmptnRsn,omitempty"` // Reason for a tax exemption. ExtendedExemptionReason *Extended350Code `xml:"XtndedXmptnRsn,omitempty"` // Information used to calculate the tax. TaxCalculationDetails *TaxCalculationInformation5 `xml:"TaxClctnDtls,omitempty"` } func (t *Tax16) SetType(value string) { t.Type = (*TaxType10Code)(&value) } func (t *Tax16) SetExtendedType(value string) { t.ExtendedType = (*Extended350Code)(&value) } func (t *Tax16) SetAmount(value, currency string) { t.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency) } func (t *Tax16) SetRate(value string) { t.Rate = (*PercentageRate)(&value) } func (t *Tax16) SetCountry(value string) { t.Country = (*CountryCode)(&value) } func (t *Tax16) AddRecipientIdentification() *PartyIdentification2Choice { t.RecipientIdentification = new(PartyIdentification2Choice) return t.RecipientIdentification } func (t *Tax16) SetExemptionIndicator(value string) { t.ExemptionIndicator = (*YesNoIndicator)(&value) } func (t *Tax16) SetExemptionReason(value string) { t.ExemptionReason = (*TaxExemptReason1Code)(&value) } func (t *Tax16) SetExtendedExemptionReason(value string) { t.ExtendedExemptionReason = (*Extended350Code)(&value) } func (t *Tax16) AddTaxCalculationDetails() *TaxCalculationInformation5 { t.TaxCalculationDetails = new(TaxCalculationInformation5) return t.TaxCalculationDetails }
Tax16.go
0.781664
0.41182
Tax16.go
starcoder
package v1 func (VirtualMachine) SwaggerDoc() map[string]string { return map[string]string{ "": "VirtualMachine is *the* VM Definition. It represents a virtual machine in the runtime environment of kubernetes.", "spec": "VM Spec contains the VM specification.", "status": "Status is the high level overview of how the VM is doing. It contains information available to controllers and users.", } } func (VirtualMachineList) SwaggerDoc() map[string]string { return map[string]string{ "": "VirtualMachineList is a list of VirtualMachines", } } func (VirtualMachineSpec) SwaggerDoc() map[string]string { return map[string]string{ "": "VirtualMachineSpec is a description of a VirtualMachine.", "domain": "Specification of the desired behavior of the VirtualMachine on the host.", "nodeSelector": "NodeSelector is a selector which must be true for the vm to fit on a node.\nSelector which must match a node's labels for the vm to be scheduled on that node.\nMore info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/\n+optional", "affinity": "If affinity is specifies, obey all the affinity rules", "terminationGracePeriodSeconds": "Grace period observed after signalling a VM to stop after which the VM is force terminated.", "volumes": "List of volumes that can be mounted by disks belonging to the vm.", "hostname": "Specifies the hostname of the vm\nIf not specified, the hostname will be set to the name of the vm, if dhcp or cloud-init is configured properly.\n+optional", "subdomain": "If specified, the fully qualified vm hostname will be \"<hostname>.<subdomain>.<pod namespace>.svc.<cluster domain>\".\nIf not specified, the vm will not have a domainname at all. The DNS entry will resolve to the vm,\nno matter if the vm itself can pick up a hostname.\n+optional", } } func (Affinity) SwaggerDoc() map[string]string { return map[string]string{ "": "Affinity groups all the affinity rules related to a VM", "nodeAffinity": "Node affinity support", } } func (VirtualMachineStatus) SwaggerDoc() map[string]string { return map[string]string{ "": "VirtualMachineStatus represents information about the status of a VM. Status may trail the actual\nstate of a system.", "nodeName": "NodeName is the name where the VM is currently running.", "conditions": "Conditions are specific points in VM's pod runtime.", "phase": "Phase is the status of the VM in kubernetes world. It is not the VM status, but partially correlates to it.", "interfaces": "Interfaces represent the details of available network interfaces.", } } func (VirtualMachineCondition) SwaggerDoc() map[string]string { return map[string]string{} } func (VirtualMachineNetworkInterface) SwaggerDoc() map[string]string { return map[string]string{ "ipAddress": "IP address of a Virtual Machine interface", "mac": "Hardware address of a Virtual Machine interface", } } func (VMSelector) SwaggerDoc() map[string]string { return map[string]string{ "name": "Name of the VM to migrate", } } func (VirtualMachineReplicaSet) SwaggerDoc() map[string]string { return map[string]string{ "": "VM is *the* VM Definition. It represents a virtual machine in the runtime environment of kubernetes.", "spec": "VM Spec contains the VM specification.", "status": "Status is the high level overview of how the VM is doing. It contains information available to controllers and users.", } } func (VirtualMachineReplicaSetList) SwaggerDoc() map[string]string { return map[string]string{ "": "VMList is a list of VMs", } } func (VMReplicaSetSpec) SwaggerDoc() map[string]string { return map[string]string{ "replicas": "Number of desired pods. This is a pointer to distinguish between explicit\nzero and not specified. Defaults to 1.\n+optional", "selector": "Label selector for pods. Existing ReplicaSets whose pods are\nselected by this will be the ones affected by this deployment.", "template": "Template describes the pods that will be created.", "paused": "Indicates that the replica set is paused.\n+optional", } } func (VMReplicaSetStatus) SwaggerDoc() map[string]string { return map[string]string{ "replicas": "Total number of non-terminated pods targeted by this deployment (their labels match the selector).\n+optional", "readyReplicas": "The number of ready replicas for this replica set.\n+optional", } } func (VMReplicaSetCondition) SwaggerDoc() map[string]string { return map[string]string{} } func (VMTemplateSpec) SwaggerDoc() map[string]string { return map[string]string{ "spec": "VM Spec contains the VM specification.", } } func (VirtualMachinePreset) SwaggerDoc() map[string]string { return map[string]string{ "spec": "VM Spec contains the VM specification.", } } func (VirtualMachinePresetList) SwaggerDoc() map[string]string { return map[string]string{ "": "VirtualMachinePresetList is a list of VirtualMachinePresets", } } func (VirtualMachinePresetSpec) SwaggerDoc() map[string]string { return map[string]string{ "selector": "Selector is a label query over a set of VMs.\nRequired.", "domain": "Domain is the same object type as contained in VirtualMachineSpec", } } func (OfflineVirtualMachine) SwaggerDoc() map[string]string { return map[string]string{ "": "OfflineVirtualMachine handles the VirtualMachines that are not running\nor are in a stopped state\nThe OfflineVirtualMachine contains the template to create the\nVirtualMachine. It also mirrors the running state of the created\nVirtualMachine in its status.", "spec": "Spec contains the specification of VirtualMachine created", "status": "Status holds the current state of the controller and brief information\nabout its associated VirtualMachine", } } func (OfflineVirtualMachineList) SwaggerDoc() map[string]string { return map[string]string{ "": "OfflineVirtualMachineList is a list of offlinevirtualmachines", "items": "Items is a list of OfflineVirtualMachines", } } func (OfflineVirtualMachineSpec) SwaggerDoc() map[string]string { return map[string]string{ "": "OfflineVirtualMachineSpec describes how the proper OfflineVirtualMachine\nshould look like", "running": "Running controls whether the associatied VirtualMachine is created or not", "template": "Template is the direct specification of VirtualMachine", } } func (OfflineVirtualMachineStatus) SwaggerDoc() map[string]string { return map[string]string{ "": "OfflineVirtualMachineStatus represents the status returned by the\ncontroller to describe how the OfflineVirtualMachine is doing", "created": "Created indicates if the virtual machine is created in the cluster", "ready": "Ready indicates if the virtual machine is running and ready", "conditions": "Hold the state information of the OfflineVirtualMachine and its VirtualMachine", } } func (OfflineVirtualMachineCondition) SwaggerDoc() map[string]string { return map[string]string{ "": "OfflineVirtualMachineCondition represents the state of OfflineVirtualMachine", } }
pkg/api/v1/types_swagger_generated.go
0.838448
0.434941
types_swagger_generated.go
starcoder
package ast import ( "strconv" "strings" "time" "github.com/jacobsimpson/jt/datetime" "github.com/shopspring/decimal" ) func lt(environment *Environment, left, right Expression) bool { left = resolveVar(environment, left) right = resolveVar(environment, right) switch l := left.(type) { case *AnyValue: switch r := right.(type) { case *AnyValue: return anyGTAny(r, l) case *DateTimeValue: return dateTimeGTAny(r, l) case *DoubleValue: return doubleGTAny(r, l) case *IntegerValue: return integerGTAny(r, l) case *StringValue: return stringGTAny(r, l) } case *DateTimeValue: switch r := right.(type) { case *AnyValue: return dateTimeLTAny(l, r) case *DateTimeValue: return dateTimeLTDateTime(l, r) } case *DoubleValue: switch r := right.(type) { case *AnyValue: return doubleLTAny(l, r) case *DoubleValue: return doubleLTDouble(l, r) case *IntegerValue: return doubleLTInteger(l, r) } case *IntegerValue: switch r := right.(type) { case *AnyValue: return integerLTAny(l, r) case *DoubleValue: return integerLTDouble(l, r) case *IntegerValue: return integerLTInteger(l, r) } case *StringValue: switch r := right.(type) { case *AnyValue: return stringLTAny(l, r) case *StringValue: return stringLTString(l, r) } } return false } func le(environment *Environment, left, right Expression) bool { left = resolveVar(environment, left) right = resolveVar(environment, right) switch l := left.(type) { case *AnyValue: switch r := right.(type) { case *AnyValue: return anyGTAny(r, l) || anyEQAny(r, l) case *DateTimeValue: return dateTimeGTAny(r, l) || dateTimeEQAny(r, l) case *DoubleValue: return doubleGTAny(r, l) || doubleEQAny(r, l) case *IntegerValue: return integerGTAny(r, l) || integerEQAny(r, l) case *StringValue: return stringGTAny(r, l) || stringEQAny(r, l) } case *DateTimeValue: switch r := right.(type) { case *AnyValue: return dateTimeLTAny(l, r) || dateTimeEQAny(l, r) } case *IntegerValue: switch r := right.(type) { case *AnyValue: return integerLTAny(l, r) || integerEQAny(l, r) } case *StringValue: switch r := right.(type) { case *AnyValue: return stringLTAny(l, r) || stringEQAny(l, r) } } return false } func eq(environment *Environment, left, right Expression) bool { left = resolveVar(environment, left) right = resolveVar(environment, right) switch l := left.(type) { case *AnyValue: switch r := right.(type) { case *AnyValue: return anyEQAny(r, l) case *DateTimeValue: return dateTimeEQAny(r, l) case *DoubleValue: return doubleEQAny(r, l) case *IntegerValue: return integerEQAny(r, l) case *RegexpValue: return regexpEQAny(r, l) case *StringValue: return stringEQAny(r, l) } case *DateTimeValue: switch r := right.(type) { case *AnyValue: return dateTimeEQAny(l, r) } case *IntegerValue: switch r := right.(type) { case *AnyValue: return integerEQAny(l, r) } case *RegexpValue: switch r := right.(type) { case *AnyValue: return regexpEQAny(l, r) case *StringValue: return compareStringEQRegexp(r, l) } case *StringValue: switch r := right.(type) { case *AnyValue: return stringEQAny(l, r) case *RegexpValue: return compareStringEQRegexp(l, r) case *StringValue: return compareStringEQString(l, r) } } return false } func ne(environment *Environment, left, right Expression) bool { return !eq(environment, left, right) } func ge(environment *Environment, left, right Expression) bool { left = resolveVar(environment, left) right = resolveVar(environment, right) switch l := left.(type) { case *AnyValue: switch r := right.(type) { case *AnyValue: return anyLTAny(r, l) || anyEQAny(r, l) case *DateTimeValue: return dateTimeLTAny(r, l) || dateTimeEQAny(r, l) case *DoubleValue: return doubleLTAny(r, l) || doubleEQAny(r, l) case *IntegerValue: return integerLTAny(r, l) || integerEQAny(r, l) case *StringValue: return stringLTAny(r, l) || stringEQAny(r, l) } case *DateTimeValue: switch r := right.(type) { case *AnyValue: return dateTimeGTAny(l, r) || dateTimeEQAny(l, r) } case *IntegerValue: switch r := right.(type) { case *AnyValue: return integerGTAny(l, r) || integerEQAny(l, r) } case *StringValue: switch r := right.(type) { case *AnyValue: return stringGTAny(l, r) || stringEQAny(l, r) } } return false } func gt(environment *Environment, left, right Expression) bool { left = resolveVar(environment, left) right = resolveVar(environment, right) switch l := left.(type) { case *AnyValue: switch r := right.(type) { case *AnyValue: return anyGTAny(l, r) case *DateTimeValue: return dateTimeLTAny(r, l) case *DoubleValue: return doubleLTAny(r, l) case *IntegerValue: return integerLTAny(r, l) case *StringValue: return stringLTAny(r, l) } case *DateTimeValue: switch r := right.(type) { case *AnyValue: return dateTimeGTAny(l, r) case *DateTimeValue: return dateTimeGTDateTime(l, r) } case *DoubleValue: switch r := right.(type) { case *AnyValue: return doubleGTAny(l, r) case *DoubleValue: return doubleGTDouble(l, r) case *IntegerValue: return doubleGTInteger(l, r) } case *IntegerValue: switch r := right.(type) { case *AnyValue: return integerGTAny(l, r) case *DoubleValue: return integerGTDouble(l, r) case *IntegerValue: return integerGTInteger(l, r) } case *StringValue: switch r := right.(type) { case *AnyValue: return stringGTAny(l, r) case *StringValue: return stringGTString(l, r) } } return false } func compareStringEQRegexp(lhs *StringValue, rhs *RegexpValue) bool { return rhs.re.MatchString(lhs.value) } func compareStringEQString(lhs *StringValue, rhs *StringValue) bool { return lhs.value == rhs.value } func regexpEQAny(lhs *RegexpValue, rhs *AnyValue) bool { rev := lhs.re return rev.MatchString(rhs.raw) } func dateTimeEQAny(lhs *DateTimeValue, rhs *AnyValue) bool { dt := lhs.value coerced, err := datetime.ParseDateTime(datetime.CoercionFormats, rhs.raw) if err != nil { return false } return dt.Equal(coerced) } func dateTimeLTAny(lhs *DateTimeValue, rhs *AnyValue) bool { dt := lhs.value coerced, err := datetime.ParseDateTime(datetime.CoercionFormats, rhs.raw) if err != nil { return false } return dt.Before(coerced) } func dateTimeLTDateTime(lhs *DateTimeValue, rhs *DateTimeValue) bool { return lhs.value.Before(rhs.value) } func dateTimeGTAny(lhs *DateTimeValue, rhs *AnyValue) bool { coerced, err := datetime.ParseDateTime(datetime.CoercionFormats, rhs.raw) if err != nil { return false } return lhs.value.After(coerced) } func dateTimeGTDateTime(lhs *DateTimeValue, rhs *DateTimeValue) bool { return lhs.value.After(rhs.value) } func integerEQAny(lhs *IntegerValue, rhs *AnyValue) bool { i := lhs.value parsed, err := parseInt(rhs.raw) if err != nil { return false } return i == parsed } func integerLTAny(lhs *IntegerValue, rhs *AnyValue) bool { i := lhs.value parsed, err := parseInt(rhs.raw) if err != nil { return false } return i < parsed } func integerLTDouble(lhs *IntegerValue, rhs *DoubleValue) bool { return decimal.NewFromInt(lhs.value).LessThan(*rhs.value) } func integerLTInteger(lhs *IntegerValue, rhs *IntegerValue) bool { return lhs.value < rhs.value } func integerGTAny(lhs *IntegerValue, rhs *AnyValue) bool { i := lhs.value parsed, err := parseInt(rhs.raw) if err != nil { return false } return i > parsed } func integerGTDouble(lhs *IntegerValue, rhs *DoubleValue) bool { return decimal.NewFromInt(lhs.value).GreaterThan(*rhs.value) } func integerGTInteger(lhs *IntegerValue, rhs *IntegerValue) bool { return lhs.value > rhs.value } func doubleEQAny(lhs *DoubleValue, rhs *AnyValue) bool { d := lhs.value parsed, err := decimal.NewFromString(rhs.raw) if err != nil { return false } return d.Equal(parsed) } func doubleLTAny(lhs *DoubleValue, rhs *AnyValue) bool { d := lhs.value parsed, err := decimal.NewFromString(rhs.raw) if err != nil { parsedInt, err := parseInt(rhs.raw) if err != nil { return false } parsed = decimal.New(parsedInt, 0) } return d.LessThan(parsed) } func doubleGTAny(lhs *DoubleValue, rhs *AnyValue) bool { d := lhs.value parsed, err := decimal.NewFromString(rhs.raw) if err != nil { parsedInt, err := parseInt(rhs.raw) if err != nil { return false } parsed = decimal.New(parsedInt, 0) } return d.GreaterThan(parsed) } func doubleGTDouble(lhs *DoubleValue, rhs *DoubleValue) bool { return lhs.value.GreaterThan(*rhs.value) } func doubleGTInteger(lhs *DoubleValue, rhs *IntegerValue) bool { return lhs.value.GreaterThan(decimal.NewFromInt(rhs.value)) } func doubleLTDouble(lhs *DoubleValue, rhs *DoubleValue) bool { return lhs.value.LessThan(*rhs.value) } func doubleLTInteger(lhs *DoubleValue, rhs *IntegerValue) bool { return lhs.value.LessThan(decimal.NewFromInt(rhs.value)) } func stringEQAny(lhs *StringValue, rhs *AnyValue) bool { return lhs.value == rhs.raw } func stringLTAny(lhs *StringValue, rhs *AnyValue) bool { return lhs.value < rhs.raw } func stringGTAny(lhs *StringValue, rhs *AnyValue) bool { return lhs.value > rhs.raw } func stringGTString(lhs *StringValue, rhs *StringValue) bool { return lhs.value > rhs.value } func stringLTString(lhs *StringValue, rhs *StringValue) bool { return lhs.value < rhs.value } func anyGTAny(lhs *AnyValue, rhs *AnyValue) bool { return lhs.raw > rhs.raw } func anyEQAny(lhs *AnyValue, rhs *AnyValue) bool { return lhs.raw == rhs.raw } func anyLTAny(lhs *AnyValue, rhs *AnyValue) bool { return lhs.raw < rhs.raw } func parseInt(s string) (int64, error) { s = strings.Map(func(r rune) rune { if r == '_' { return -1 } return r }, s) if len(s) > 2 { if strings.HasPrefix(s, "0x") { return strconv.ParseInt(s, 0, 64) } } if len(s) > 2 { if strings.HasPrefix(s, "0b") { return strconv.ParseInt(s[2:], 2, 64) } } return strconv.ParseInt(s, 10, 64) } func resolveVar(environment *Environment, v Expression) Expression { // TODO: This is going to crash hard if the variable doesn't exist. switch vr := v.(type) { case *VarValue: return environment.Resolve(vr) case *KeywordValue: switch vr.value { case "yesterday": t := time.Now().Add(-24 * time.Hour) t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local) return &DateTimeValue{ raw: t.String(), value: t, } case "today": t := time.Now() t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local) return &DateTimeValue{ raw: t.String(), value: t, } case "now": t := time.Now() return &DateTimeValue{ raw: t.String(), value: t, } case "tomorrow": t := time.Now().Add(24 * time.Hour) t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local) return &DateTimeValue{ raw: t.String(), value: t, } } } return v }
ast/comparison_functions.go
0.593845
0.589894
comparison_functions.go
starcoder
package itertools //ProductIterator iterates over {0, ..., n[0] - 1} x {0, ..., n[1] - 1} x ... x {0, ..., n[len(n) - 1] - 1}. //It should be initliased using Product. type ProductIterator struct { state []int n []int empty bool } //Product returns a *ProductIterator to iterate over {0, ..., n[0] - 1} x {0, ..., n[1] - 1} x ... x {0, ..., n[len(n) - 1] - 1}. func Product(n ...int) *ProductIterator { empty := false for _, v := range n { if v < 1 { empty = true } } m := len(n) //Initialise the state to be (0, 0, ..., 0, -1). The first call to next will increase the last coordinate and the first value will be (0, 0, ..., 0, 0). state := make([]int, m) if m > 0 { state[m-1] = -1 } //Create a deep copy of n in case it changes. tmpN := make([]int, m) copy(tmpN, n) return &ProductIterator{state: state, n: tmpN, empty: empty} } //Value returns the current state of the iterator. It isn't safe to modify the state. func (p ProductIterator) Value() []int { return p.state } //Next attempts to move the iterator to the next state, returning true if there is one and false if there isn't. func (p *ProductIterator) Next() bool { n := len(p.state) for j := n - 1; j >= 0; j-- { if p.state[j] < p.n[j]-1 { p.state[j]++ for k := j + 1; k < n; k++ { p.state[k] = 0 } return !p.empty } } if n == 0 && !p.empty { p.empty = true return true } return false } //RestrictedPrefixProductIterator iterates over all elements (a_0, a_1, ..., a_{len(n)-1}) of {0, ..., n[0] - 1} x {0, ..., n[1] - 1} x ... x {0, ..., n[len(n) - 1] - 1} which pass the tests f(a_0), f(a_0, a_1), ... //If len(n) == 0, then the value []int{} is considered to pass. type RestrictedPrefixProductIterator struct { state []int n []int t func([]int) bool empty bool } //RestrictedPrefixProduct returns a *RestrictedPrefixProductIterator which iterates over all elements (a_0, a_1, ..., a_{len(n)-1}) of {0, ..., n[0] - 1} x {0, ..., n[1] - 1} x ... x {0, ..., n[len(n) - 1] - 1} which pass the test f(a_0), f(a_0, a_1), ... func RestrictedPrefixProduct(t func([]int) bool, n ...int) *RestrictedPrefixProductIterator { empty := false for _, v := range n { if v < 1 { empty = true } } m := len(n) state := make([]int, 0, m) //Create a deep copy of n in case it changes. tmpN := make([]int, m) copy(tmpN, n) return &RestrictedPrefixProductIterator{state: state, n: tmpN, t: t, empty: empty} } //Value returns the current value of the iterator. You must not modify the value. func (p RestrictedPrefixProductIterator) Value() []int { return p.state } //Next attempts to move the iterator to the next state, returning true if there is one and false if there isn't. func (p *RestrictedPrefixProductIterator) Next() bool { //This could be rewritten without goto statements if we wanted. m := len(p.n) if p.empty { return false } if len(p.state) == 0 { if m == 0 { p.empty = true return true } goto x1 } else { goto x2 } x1: //Increase the size p.state = append(p.state, 0) goto x3 x2: //Find the next state if p.state[len(p.state)-1] < p.n[len(p.state)-1]-1 { p.state[len(p.state)-1]++ } else { if len(p.state) == 1 { return false } p.state = p.state[:len(p.state)-1] goto x2 } x3: //Test the current state if !p.t(p.state) { //Fail - find the next state. goto x2 } if len(p.state) < m { //We pass the tests but we need to extend the product goto x1 } //We have a state! return true }
itertools/product.go
0.574156
0.442697
product.go
starcoder
package skiplist import ( "math" "sync" "sync/atomic" "unsafe" ) /* * Algorithm: * Access barrier is used to facilitize safe remory reclaimation in the lockfree * skiplist. Every skiplist access needs to be passed through a gate which tracks * the safety premitives to figure out when is the right time to deallocate a * skiplist node. * * Even though lockfree skiplist deletion algorithm takes care of completely unlinking * a skiplist node from the skiplist, still there could be a small perioid during which * deleted node is accessible to already live skiplist accessors. We need to wait until * a safe period before the memory for the node can be deallocated. * * In this algorithm, the unit of safety period is called barrier session. All the * live accessor of the skiplist are tracked in a barrier session. Whenever a * skiplist delete or group of deletes is performed, current barrier session is * closed and new barrier session is started. The previous barrier * session tracks all the live accessors until the session of closed. The right * time to safely reclaim the node is when all the accessor becomes dead. This makes * sure that unlinked node will be invisible to everyone. The accessors in the * barrier session can cooperatively detect and mark when each of them terminates. * When the last accessor leaves, it can take the action to call the destructor * for the node and barrier session terminates. * * Closing and installing a new barrier session: * A session liveCount is incremented everytime an accessor is entering the skiplist * and decremented when the leave the skiplist. When a session is closed and new * one needs to be installed, we just swap the global barrier session reference. * There could be race conditions while a session is being marked as closed. Still * an ongoing skiplist accessor can increment the counter of a session which was marked * as closed. To detect those accessors and make them retry, we add a large number * to the liveCount as part of the session close phase. When the accessor finds * that the incremented result is greater than that large offset, it needs to backoff * from the current session and acquire new session to increment the count. In this * scheme, whoever decrements the count and gets the count equal to the large offset * is responsible for deallocation of the object. * * The algorithm has to consider one more condition before it can call destructor for * the session. Multiple closed sessions can be active at a time. We cannot call the * destructor for a closed session while a previous closed session is still not terminated. * Because, even through accessors from a closed session has become zero, accessors from previous * closed session would be able to access items in the later closed session. Hence, a closed session * can be terminated only after termination of all previous closed sessions. * */ type BarrierSessionDestructor func(objectRef unsafe.Pointer) const barrierFlushOffset = math.MaxInt32 / 2 type BarrierSession struct { liveCount *int32 objectRef unsafe.Pointer seqno uint64 closed int32 } func CompareBS(this, that unsafe.Pointer) int { thisItm := (*BarrierSession)(this) thatItm := (*BarrierSession)(that) return int(thisItm.seqno) - int(thatItm.seqno) } func newBarrierSession() *BarrierSession { bs := &BarrierSession{ liveCount: new(int32), } return bs } type AccessBarrier struct { activeSeqno uint64 session unsafe.Pointer callb BarrierSessionDestructor freeq *Skiplist freeSeqno uint64 isDestructorRunning int32 active bool sync.Mutex } func newAccessBarrier(active bool, callb BarrierSessionDestructor) *AccessBarrier { ab := &AccessBarrier{ active: active, session: unsafe.Pointer(newBarrierSession()), callb: callb, } if active { ab.freeq = New() } return ab } func (ab *AccessBarrier) doCleanup() { buf1 := ab.freeq.MakeBuf() buf2 := ab.freeq.MakeBuf() defer ab.freeq.FreeBuf(buf1) defer ab.freeq.FreeBuf(buf2) iter := ab.freeq.NewIterator(CompareBS, buf1) defer iter.Close() for iter.SeekFirst(); iter.Valid(); iter.Next() { node := iter.GetNode() bs := (*BarrierSession)(node.Item()) if bs.seqno != ab.freeSeqno+1 { return } ab.freeSeqno++ ab.callb(bs.objectRef) ab.freeq.DeleteNode(node, CompareBS, buf2, &ab.freeq.Stats) } } func (ab *AccessBarrier) Acquire() *BarrierSession { if ab.active { retry: bs := (*BarrierSession)(atomic.LoadPointer(&ab.session)) liveCount := atomic.AddInt32(bs.liveCount, 1) if liveCount > barrierFlushOffset { ab.Release(bs) goto retry } return bs } return nil } func (ab *AccessBarrier) Release(bs *BarrierSession) { if ab.active { liveCount := atomic.AddInt32(bs.liveCount, -1) if liveCount == barrierFlushOffset { buf := ab.freeq.MakeBuf() defer ab.freeq.FreeBuf(buf) // Accessors which entered a closed barrier session steps down automatically // But, they may try to close an already closed session. if atomic.AddInt32(&bs.closed, 1) == 1 { ab.freeq.Insert(unsafe.Pointer(bs), CompareBS, buf, &ab.freeq.Stats) if atomic.CompareAndSwapInt32(&ab.isDestructorRunning, 0, 1) { ab.doCleanup() atomic.CompareAndSwapInt32(&ab.isDestructorRunning, 1, 0) } } } } } func (ab *AccessBarrier) FlushSession(ref unsafe.Pointer) { if ab.active { ab.Lock() defer ab.Unlock() bsPtr := atomic.LoadPointer(&ab.session) newBsPtr := unsafe.Pointer(newBarrierSession()) atomic.CompareAndSwapPointer(&ab.session, bsPtr, newBsPtr) bs := (*BarrierSession)(bsPtr) bs.objectRef = ref ab.activeSeqno++ bs.seqno = ab.activeSeqno atomic.AddInt32(bs.liveCount, barrierFlushOffset+1) ab.Release(bs) } }
secondary/memdb/skiplist/access_barrier.go
0.519521
0.520435
access_barrier.go
starcoder
package vile import ( "math" "math/rand" "strconv" ) /* // TEST type Test struct { Value float64 } func Integer(i int) *Test { return &Test{Value: float64(i)} } */ // Zero is the Vile 0 value var Zero = Number(0) // One is the Vile 1 value var One = Number(1) // MinusOne is the Vile -1 value var MinusOne = Number(-1) // Number - create a Number object for the given value func Number(f float64) *Object { num := new(Object) num.Type = NumberType num.fval = f return num } func Int(n int64) *Object { return Number(float64(n)) } // Round - return the closest integer value to the float value func Round(f float64) float64 { if f > 0 { return math.Floor(f + 0.5) } return math.Ceil(f - 0.5) } // ToNumber - convert object to a number, if possible func ToNumber(o *Object) (*Object, error) { switch o.Type { case NumberType: return o, nil case CharacterType: return Number(o.fval), nil case BooleanType: return Number(o.fval), nil case StringType: f, err := strconv.ParseFloat(o.text, 64) if err == nil { return Number(f), nil } } return nil, Error(ArgumentErrorKey, "cannot convert to an number: ", o) } // ToInt - convert the object to an integer number, if possible func ToInt(o *Object) (*Object, error) { switch o.Type { case NumberType: return Number(Round(o.fval)), nil case CharacterType: return Number(o.fval), nil case BooleanType: return Number(o.fval), nil case StringType: n, err := strconv.ParseInt(o.text, 10, 64) if err == nil { return Number(float64(n)), nil } } return nil, Error(ArgumentErrorKey, "cannot convert to an integer: ", o) } func IsInt(obj *Object) bool { if obj.Type == NumberType { f := obj.fval if math.Trunc(f) == f { return true } } return false } func IsFloat(obj *Object) bool { if obj.Type == NumberType { return !IsInt(obj) } return false } func AsFloat64Value(obj *Object) (float64, error) { if obj.Type == NumberType { return obj.fval, nil } return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type) } func AsInt64Value(obj *Object) (int64, error) { if obj.Type == NumberType { return int64(obj.fval), nil } return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type) } func AsIntValue(obj *Object) (int, error) { if obj.Type == NumberType { return int(obj.fval), nil } return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type) } func AsByteValue(obj *Object) (byte, error) { if obj.Type == NumberType { return byte(obj.fval), nil } return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type) } const epsilon = 0.000000001 // Equal returns true if the object is equal to the argument, within epsilon func NumberEqual(f1 float64, f2 float64) bool { if f1 == f2 { return true } if math.Abs(f1-f2) < epsilon { return true } return false } var randomGenerator = rand.New(rand.NewSource(1)) func RandomSeed(n int64) { randomGenerator = rand.New(rand.NewSource(n)) } func Random(min float64, max float64) *Object { return Number(min + (randomGenerator.Float64() * (max - min))) } func RandomList(size int, min float64, max float64) *Object { result := EmptyList tail := EmptyList for i := 0; i < size; i++ { tmp := List(Random(min, max)) if result == EmptyList { result = tmp tail = tmp } else { tail.cdr = tmp tail = tmp } } return result }
src/number.go
0.68595
0.457924
number.go
starcoder
package comparator import ( "fmt" "reflect" "strconv" "strings" "github.com/pkg/errors" ) // CompareInt compares integer numbers for specific operation // it check for the >=, >, <=, <, ==, != operators func (model Model) CompareInt() error { obj := Integer{} obj.setValues(reflect.ValueOf(model.a).String(), reflect.ValueOf(model.b).String()) switch model.operator { case ">=": if !obj.isGreaterorEqual() { return fmt.Errorf("{actual value: %v} is not greater than or equal to {expected value: %v}", obj.a, obj.b) } case "<=": if !obj.isLesserorEqual() { return fmt.Errorf("{actual value: %v} is not lesser than or equal to {expected value: %v}", obj.a, obj.b) } case ">": if !obj.isGreater() { return fmt.Errorf("{actual value: %v} is not greater than {expected value: %v}", obj.a, obj.b) } case "<": if !obj.isLesser() { return fmt.Errorf("{actual value: %v} is not lesser than {expected value: %v}", obj.a, obj.b) } case "==": if !obj.isEqual() { return fmt.Errorf("{actual value: %v} is not equal to {expected value: %v}", obj.a, obj.b) } case "!=": if !obj.isNotEqual() { return fmt.Errorf("{actual value: %v} is not NotEqual to {expected value: %v}", obj.a, obj.b) } case "OneOf", "oneOf": if !obj.isOneOf() { return errors.Errorf("Actual value: {%v} doesn't matched with any of the expected values: {%v}", obj.a, obj.c) } case "between", "Between": if len(obj.c) < 2 { return errors.Errorf("{expected value: %v} should contains both lower and upper limits", obj.c) } if !obj.isBetween() { return errors.Errorf("Actual value: {%v} doesn't lie in between expected range: {%v}", obj.a, obj.c) } default: return fmt.Errorf("criteria '%s' not supported in the probe", model.operator) } return nil } // Integer contains operands for integer comparator check type Integer struct { a int b int c []int } // SetValues sets the value inside Integer struct func (i *Integer) setValues(a, b string) { i.a, _ = strconv.Atoi(a) c := strings.Split(strings.TrimSpace(b), ",") if len(c) > 1 { list := []int{} for j := range c { x, _ := strconv.Atoi(c[j]) list = append(list, x) } i.c = list i.b = 0 } else { i.b, _ = strconv.Atoi(b) } } // isGreater check for the first number should be greater than second number func (i *Integer) isGreater() bool { return i.a > i.b } // isGreaterorEqual check for the first number should be greater than or equals to the second number func (i *Integer) isGreaterorEqual() bool { return i.isGreater() || i.isEqual() } // isLesser check for the first number should be lesser than second number func (i *Integer) isLesser() bool { return i.a < i.b } // isLesserorEqual check for the first number should be less than or equals to the second number func (i *Integer) isLesserorEqual() bool { return i.isLesser() || i.isEqual() } // isEqual check for the first number should be equals to the second number func (i *Integer) isEqual() bool { return i.a == i.b } // isNotEqual check for the first number should be not equals to the second number func (i *Integer) isNotEqual() bool { return i.a != i.b } // isOneOf check for the number should be present inside given list func (i *Integer) isOneOf() bool { for j := range i.c { if i.a == i.c[j] { return true } } return false } // isBetween check for the number should be lie in the given range func (i *Integer) isBetween() bool { if i.a >= i.c[0] && i.a <= i.c[1] { return true } return false }
pkg/probe/comparator/integer.go
0.657648
0.515376
integer.go
starcoder
package genetics import ( "fmt" "github.com/yaricom/goNEAT/v2/neat/network" ) // MIMOControlGene The Multiple-Input Multiple-Output (MIMO) control Gene allows creating modular genomes, in which several groups of genes // connected through single MIMO Gene and corresponding control function is applied to all inputs in order to produce // outputs. This allows to build modular hierarchical genomes which can be considered as sum of constituent components // and evolved as a whole and as a concrete parts simultaneously. type MIMOControlGene struct { // The current innovation number for this gene InnovationNum int64 // Used to see how much mutation has changed the link MutationNum float64 // If true the gene is enabled IsEnabled bool // The control node with control/activation function ControlNode *network.NNode // The list of associated IO nodes for fast traversal ioNodes []*network.NNode } // NewMIMOGene Creates new MIMO gene func NewMIMOGene(controlNode *network.NNode, innovNum int64, mutNum float64, enabled bool) *MIMOControlGene { gene := &MIMOControlGene{ ControlNode: controlNode, InnovationNum: innovNum, MutationNum: mutNum, IsEnabled: enabled, } // collect IO nodes list gene.ioNodes = make([]*network.NNode, 0) for _, l := range controlNode.Incoming { gene.ioNodes = append(gene.ioNodes, l.InNode) } for _, l := range controlNode.Outgoing { gene.ioNodes = append(gene.ioNodes, l.OutNode) } return gene } // NewMIMOGeneCopy The copy constructor taking parameters from provided control gene for given control node func NewMIMOGeneCopy(g *MIMOControlGene, controlNode *network.NNode) *MIMOControlGene { cg := NewMIMOGene(controlNode, g.InnovationNum, g.MutationNum, g.IsEnabled) return cg } // Tests whether this gene has intersection with provided map of nodes, i.e. any of it's IO nodes included into list func (g *MIMOControlGene) hasIntersection(nodes map[int]*network.NNode) bool { for _, nd := range g.ioNodes { if _, Ok := nodes[nd.Id]; Ok { // found return true } } return false } // The stringer func (g *MIMOControlGene) String() string { enabledStr := "" if !g.IsEnabled { enabledStr = " -DISABLED-" } return fmt.Sprintf("[MIMO Gene INNOV (%5d, %2.3f) %s control node: %s]", g.InnovationNum, g.MutationNum, enabledStr, g.ControlNode.String()) }
neat/genetics/mimo_gene.go
0.617397
0.466116
mimo_gene.go
starcoder
package aoc2019 import ( "io/ioutil" "log" "math" "strings" "github.com/pkg/errors" ) type day19Fact uint8 const ( day19FactNoMoveDownPossible day19Fact = 1 << iota day19FactNoMoveLeftPossible day19FactNoMoveRightPossible day19FactNoMoveTopPossible day19FactOriginNotInBeam day19FactX100NotInBeam day19FactY100NotInBeam ) func (f day19Fact) has(t day19Fact) bool { return f&t != 0 } func (f day19Fact) String() string { return map[day19Fact]string{ day19FactNoMoveDownPossible: "NoMoveDownPossible", day19FactNoMoveLeftPossible: "NoMoveLeftPossible", day19FactNoMoveRightPossible: "NoMoveRightPossible", day19FactNoMoveTopPossible: "NoMoveTopPossible", day19FactOriginNotInBeam: "OriginNotInBeam", day19FactX100NotInBeam: "X100NotInBeam", day19FactY100NotInBeam: "Y100NotInBeam", }[f] } func day19CountFieldsInTractorBeam(code []int64, maxX, maxY int64) int64 { var count int64 for y := int64(0); y <= maxY; y++ { for x := int64(0); x <= maxX; x++ { var ( in = make(chan int64) out = make(chan int64) ) go executeIntcode(code, in, out) // Submit coordinates in <- x in <- y // Count fields with tractor beam o := <-out count += o } } return count } func day19Find100x100ShipPlace(code []int64) int64 { var ( x, y int64 bvL, bvR int64 ) getBeamVectors := func() { for x := int64(0); x <= math.MaxInt64; x++ { var ( in = make(chan int64) out = make(chan int64) ) go executeIntcode(code, in, out) // Submit coordinates in <- x in <- 100 // Count fields with tractor beam o := <-out switch { case o == 0 && bvR == 0: // Did not yet find the beam case o == 1 && bvL == 0: // Left beam end has not been set bvL, bvR = x, x case o == 1 && x > bvR: // New right "edge" found bvR = x case 0 == 0 && bvR > 0: // End of right edge found, end return } } } checkCoordinate := func(x, y int64) day19Fact { var facts day19Fact for flag, c := range map[day19Fact][2]int64{ day19FactNoMoveDownPossible: {x, y + 100}, day19FactNoMoveLeftPossible: {x - 1, y + 99}, day19FactNoMoveRightPossible: {x + 100, y}, day19FactNoMoveTopPossible: {x + 99, y - 1}, day19FactOriginNotInBeam: {x, y}, day19FactX100NotInBeam: {x + 99, y}, day19FactY100NotInBeam: {x, y + 99}, } { if c[0] < 0 || c[1] < 0 { // Never check negative coordinates facts |= flag continue } var ( in = make(chan int64) out = make(chan int64) ) defer close(in) go executeIntcode(code, in, out) // Submit coordinates in <- c[0] in <- c[1] o := <-out if o == 0 { facts |= flag } } return facts } // Initially get vectors for beam edges getBeamVectors() // Try to get to the best position through movement var success bool for !success { var f = checkCoordinate(x, y) switch { case f.has(day19FactOriginNotInBeam): panic("Origin placed outside beam") case f.has(day19FactX100NotInBeam) || f.has(day19FactY100NotInBeam): // Ship does not fit, move further away y += 100 x = ((bvL * (y / 100)) + (bvR * (y / 100))) / 2 case !f.has(day19FactNoMoveTopPossible): // Ship can be moved up in beam y -= 1 case !f.has(day19FactNoMoveLeftPossible): // Ship can be moved left in beam x -= 1 case f.has(day19FactNoMoveTopPossible) && f.has(day19FactNoMoveLeftPossible): // No movement towards ship is possible and ship fits in: Perfect success = true } } log.Printf("Result before force-move: x=%d y=%d res=%d", x, y, x*10000+y) // This MIGHT not be the perfect position, force further movement // by ignoring some factors set above in order to compensate inaccurate // vectors due to working with integers only var fX, fY = x, y for success { var f = checkCoordinate(fX, fY) if !f.has(day19FactX100NotInBeam) && !f.has(day19FactY100NotInBeam) { // Found a better position through forcing x, y = fX, fY } switch { case !f.has(day19FactNoMoveTopPossible): // Ship can be moved up in beam fY -= 1 case f.has(day19FactOriginNotInBeam): // No further tests, there will be no better position success = false default: fX -= 1 } } log.Printf("Result after force-move: x=%d y=%d res=%d", x, y, x*10000+y) return x*10000 + y } func solveDay19Part1(inFile string) (int64, error) { rawCode, err := ioutil.ReadFile(inFile) if err != nil { return 0, errors.Wrap(err, "Unable to read intcode") } code, err := parseIntcode(strings.TrimSpace(string(rawCode))) if err != nil { return 0, errors.Wrap(err, "Unable to parse intcode") } return day19CountFieldsInTractorBeam(code, 49, 49), nil } func solveDay19Part2(inFile string) (int64, error) { rawCode, err := ioutil.ReadFile(inFile) if err != nil { return 0, errors.Wrap(err, "Unable to read intcode") } code, err := parseIntcode(strings.TrimSpace(string(rawCode))) if err != nil { return 0, errors.Wrap(err, "Unable to parse intcode") } return day19Find100x100ShipPlace(code), nil }
day19.go
0.512937
0.444806
day19.go
starcoder
package cmd import ( "github.com/spf13/cobra" ) var range_diffCmd = &cobra.Command{ Use: "range-diff", Short: "Compare two commit ranges (e.g. two versions of a branch)", Run: func(cmd *cobra.Command, args []string) { }, } func init() { range_diffCmd.Flags().StringS("G", "G", "", "look for differences that change the number of occurrences of the specified regex") range_diffCmd.Flags().StringS("O", "O", "", "control the order in which files appear in the output") range_diffCmd.Flags().BoolS("R", "R", false, "swap two inputs, reverse the diff") range_diffCmd.Flags().StringS("S", "S", "", "look for differences that change the number of occurrences of the specified string") range_diffCmd.Flags().String("abbrev", "", "use <n> digits to display SHA-1s") range_diffCmd.Flags().String("anchored", "", "generate diff using the \"anchored diff\" algorithm") range_diffCmd.Flags().Bool("binary", false, "output a binary diff that can be applied") range_diffCmd.Flags().StringP("break-rewrites", "B", "", "break complete rewrite changes into pairs of delete and create") range_diffCmd.Flags().Bool("check", false, "warn if changes introduce conflict markers or whitespace errors") range_diffCmd.Flags().String("color", "", "show colored diff") range_diffCmd.Flags().String("color-moved", "", "moved lines of code are colored differently") range_diffCmd.Flags().String("color-moved-ws", "", "how white spaces are ignored in --color-moved") range_diffCmd.Flags().String("color-words", "", "equivalent to --word-diff=color --word-diff-regex=<regex>") range_diffCmd.Flags().Bool("compact-summary", false, "generate compact summary in diffstat") range_diffCmd.Flags().String("creation-factor", "", "Percentage by which creation is weighted") range_diffCmd.Flags().Bool("cumulative", false, "synonym for --dirstat=cumulative") range_diffCmd.Flags().String("diff-algorithm", "", "choose a diff algorithm") range_diffCmd.Flags().String("diff-filter", "", "select files by diff type") range_diffCmd.Flags().StringP("dirstat", "X", "", "output the distribution of relative amount of changes for each sub-directory") range_diffCmd.Flags().String("dirstat-by-file", "", "synonym for --dirstat=files,param1,param2...") range_diffCmd.Flags().String("dst-prefix", "", "show the given destination prefix instead of \"b/\"") range_diffCmd.Flags().Bool("exit-code", false, "exit with 1 if there were differences, 0 otherwise") range_diffCmd.Flags().Bool("ext-diff", false, "allow an external diff helper to be executed") range_diffCmd.Flags().StringP("find-copies", "C", "", "detect copies") range_diffCmd.Flags().Bool("find-copies-harder", false, "use unmodified files as source to find copies") range_diffCmd.Flags().String("find-object", "", "look for differences that change the number of occurrences of the specified object") range_diffCmd.Flags().StringP("find-renames", "M", "", "detect renames") range_diffCmd.Flags().Bool("follow", false, "continue listing the history of a file beyond renames") range_diffCmd.Flags().Bool("full-index", false, "show full pre- and post-image object names on the \"index\" lines") range_diffCmd.Flags().BoolP("function-context", "W", false, "generate diffs with <n> lines context") range_diffCmd.Flags().Bool("histogram", false, "generate diff using the \"histogram diff\" algorithm") range_diffCmd.Flags().BoolP("ignore-all-space", "w", false, "ignore whitespace when comparing lines") range_diffCmd.Flags().Bool("ignore-blank-lines", false, "ignore changes whose lines are all blank") range_diffCmd.Flags().Bool("ignore-cr-at-eol", false, "ignore carrier-return at the end of line") range_diffCmd.Flags().Bool("ignore-space-at-eol", false, "ignore changes in whitespace at EOL") range_diffCmd.Flags().BoolP("ignore-space-change", "b", false, "ignore changes in amount of whitespace") range_diffCmd.Flags().String("ignore-submodules", "", "ignore changes to submodules in the diff generation") range_diffCmd.Flags().Bool("indent-heuristic", false, "heuristic to shift diff hunk boundaries for easy reading") range_diffCmd.Flags().String("inter-hunk-context", "", "show context between diff hunks up to the specified number of lines") range_diffCmd.Flags().BoolP("irreversible-delete", "D", false, "omit the preimage for deletes") range_diffCmd.Flags().Bool("ita-invisible-in-index", false, "hide 'git add -N' entries from the index") range_diffCmd.Flags().Bool("ita-visible-in-index", false, "treat 'git add -N' entries as real in the index") range_diffCmd.Flags().StringS("l", "l", "", "prevent rename/copy detection if the number of rename/copy targets exceeds given limit") range_diffCmd.Flags().String("line-prefix", "", "prepend an additional prefix to every line of output") range_diffCmd.Flags().Bool("minimal", false, "produce the smallest possible diff") range_diffCmd.Flags().Bool("name-only", false, "show only names of changed files") range_diffCmd.Flags().Bool("name-status", false, "show only names and status of changed files") range_diffCmd.Flags().Bool("no-dual-color", false, "use simple diff colors") range_diffCmd.Flags().BoolP("no-patch", "s", false, "suppress diff output") range_diffCmd.Flags().Bool("no-prefix", false, "do not show any source or destination prefix") range_diffCmd.Flags().Bool("no-renames", false, "disable rename detection") range_diffCmd.Flags().String("notes", "", "passed to 'git log'") range_diffCmd.Flags().Bool("numstat", false, "machine friendly --stat") range_diffCmd.Flags().String("output", "", "Output to a specific file") range_diffCmd.Flags().String("output-indicator-context", "", "specify the character to indicate a context instead of ' '") range_diffCmd.Flags().String("output-indicator-new", "", "specify the character to indicate a new line instead of '+'") range_diffCmd.Flags().String("output-indicator-old", "", "specify the character to indicate an old line instead of '-'") range_diffCmd.Flags().BoolP("patch", "p", false, "generate patch") range_diffCmd.Flags().Bool("patch-with-raw", false, "synonym for '-p --raw'") range_diffCmd.Flags().Bool("patch-with-stat", false, "synonym for '-p --stat'") range_diffCmd.Flags().Bool("patience", false, "generate diff using the \"patience diff\" algorithm") range_diffCmd.Flags().Bool("pickaxe-all", false, "show all changes in the changeset with -S or -G") range_diffCmd.Flags().Bool("pickaxe-regex", false, "treat <string> in -S as extended POSIX regular expression") range_diffCmd.Flags().Bool("quiet", false, "disable all output of the program") range_diffCmd.Flags().Bool("raw", false, "generate the diff in raw format") range_diffCmd.Flags().String("relative", "", "when run from subdir, exclude changes outside and show relative paths") range_diffCmd.Flags().Bool("rename-empty", false, "use empty blobs as rename source") range_diffCmd.Flags().Bool("shortstat", false, "output only the last line of --stat") range_diffCmd.Flags().String("src-prefix", "", "show the given source prefix instead of \"a/\"") range_diffCmd.Flags().String("stat", "", "generate diffstat") range_diffCmd.Flags().String("stat-count", "", "generate diffstat with limited lines") range_diffCmd.Flags().String("stat-graph-width", "", "generate diffstat with a given graph width") range_diffCmd.Flags().String("stat-name-width", "", "generate diffstat with a given name width") range_diffCmd.Flags().String("stat-width", "", "generate diffstat with a given width") range_diffCmd.Flags().String("submodule", "", "specify how differences in submodules are shown") range_diffCmd.Flags().Bool("summary", false, "condensed summary such as creations, renames and mode changes") range_diffCmd.Flags().BoolP("text", "a", false, "treat all files as text") range_diffCmd.Flags().Bool("textconv", false, "run external text conversion filters when comparing binary files") range_diffCmd.Flags().BoolS("u", "u", false, "generate patch") range_diffCmd.Flags().StringP("unified", "U", "", "generate diffs with <n> lines context") range_diffCmd.Flags().String("word-diff", "", "show word diff, using <mode> to delimit changed words") range_diffCmd.Flags().String("word-diff-regex", "", "use <regex> to decide what a word is") range_diffCmd.Flags().String("ws-error-highlight", "", "highlight whitespace errors in the 'context', 'old' or 'new' lines in the diff") range_diffCmd.Flags().BoolS("z", "z", false, "do not munge pathnames and use NULs as output field terminators in --raw or --numstat") rootCmd.AddCommand(range_diffCmd) }
completers/git_completer/cmd/range_diff_generated.go
0.526586
0.468304
range_diff_generated.go
starcoder
package sunrisesunset import ( "errors" "math" "time" ) // The Parameters struct can also be used to manipulate // the data and get the sunrise and sunset type Parameters struct { Latitude float64 Longitude float64 UtcOffset float64 Date time.Time } // Just call the 'general' GetSunriseSunset function and return the results func (p *Parameters) GetSunriseSunset() (time.Time, time.Time, error) { return GetSunriseSunset(p.Latitude, p.Longitude, p.UtcOffset, p.Date) } // Convert radians to degrees func rad2deg(radians float64) float64 { return radians * (180.0 / math.Pi) } // Convert degrees to radians func deg2rad(degrees float64) float64 { return degrees * (math.Pi / 180.0) } // Creates a vector with the seconds normalized to the range 0~1. // seconds - The number of seconds will be normalized to 1 // Return A vector with the seconds normalized to 0~1 func createSecondsNormalized(seconds int) (vector []float64) { for index := 0; index < seconds; index++ { temp := float64(index) / float64(seconds-1) vector = append(vector, temp) } return } // Calculate Julian Day based on the formula: nDays+2415018.5+secondsNorm-UTCoff/24 // numDays - The number of days calculated in the calculate function // secondsNorm - Seconds normalized calculated by the createSecondsNormalized function // utcOffset - UTC offset defined by the user // Return Julian day slice func calcJulianDay(numDays int64, secondsNorm []float64, utcOffset float64) (julianDay []float64) { for index := 0; index < len(secondsNorm); index++ { temp := float64(numDays) + 2415018.5 + secondsNorm[index] - utcOffset/24.0 julianDay = append(julianDay, temp) } return } // Calculate the Julian Century based on the formula: (julianDay - 2451545.0) / 36525.0 // julianDay - Julian day vector calculated by the calcJulianDay function // Return Julian century slice func calcJulianCentury(julianDay []float64) (julianCentury []float64) { for index := 0; index < len(julianDay); index++ { temp := (julianDay[index] - 2451545.0) / 36525.0 julianCentury = append(julianCentury, temp) } return } // Calculate the Geom Mean Long Sun in degrees based on the formula: 280.46646 + julianCentury * (36000.76983 + julianCentury * 0.0003032) // julianCentury - Julian century calculated by the calcJulianCentury function // Return The Geom Mean Long Sun slice func calcGeomMeanLongSun(julianCentury []float64) (geomMeanLongSun []float64) { for index := 0; index < len(julianCentury); index++ { a := 280.46646 + julianCentury[index]*(36000.76983+julianCentury[index]*0.0003032) temp := math.Mod(a, 360.0) geomMeanLongSun = append(geomMeanLongSun, temp) } return } // Calculate the Geom Mean Anom Sun in degrees based on the formula: 357.52911 + julianCentury * (35999.05029 - 0.0001537 * julianCentury) // julianCentury - Julian century calculated by the calcJulianCentury function // Return The Geom Mean Anom Sun slice func calcGeomMeanAnomSun(julianCentury []float64) (geomMeanAnomSun []float64) { for index := 0; index < len(julianCentury); index++ { temp := 357.52911 + julianCentury[index]*(35999.05029-0.0001537*julianCentury[index]) geomMeanAnomSun = append(geomMeanAnomSun, temp) } return } // Calculate the Eccent Earth Orbit based on the formula: 0.016708634 - julianCentury * (0.000042037 + 0.0000001267 * julianCentury) // julianCentury - Julian century calculated by the calcJulianCentury function // Return The Eccent Earth Orbit slice func calcEccentEarthOrbit(julianCentury []float64) (eccentEarthOrbit []float64) { for index := 0; index < len(julianCentury); index++ { temp := 0.016708634 - julianCentury[index]*(0.000042037+0.0000001267*julianCentury[index]) eccentEarthOrbit = append(eccentEarthOrbit, temp) } return } // Calculate the Sun Eq Ctr based on the formula: sin(deg2rad(geomMeanAnomSun))*(1.914602-julianCentury*(0.004817+0.000014*julianCentury))+sin(deg2rad(2*geomMeanAnomSun))*(0.019993-0.000101*julianCentury)+sin(deg2rad(3*geomMeanAnomSun))*0.000289; // julianCentury - Julian century calculated by the calcJulianCentury function // geomMeanAnomSun - Geom Mean Anom Sun calculated by the calcGeomMeanAnomSun function // Return The Sun Eq Ctr slice func calcSunEqCtr(julianCentury []float64, geomMeanAnomSun []float64) (sunEqCtr []float64) { if len(julianCentury) != len(geomMeanAnomSun) { return } for index := 0; index < len(julianCentury); index++ { temp := math.Sin(deg2rad(geomMeanAnomSun[index]))*(1.914602-julianCentury[index]*(0.004817+0.000014*julianCentury[index])) + math.Sin(deg2rad(2*geomMeanAnomSun[index]))*(0.019993-0.000101*julianCentury[index]) + math.Sin(deg2rad(3*geomMeanAnomSun[index]))*0.000289 sunEqCtr = append(sunEqCtr, temp) } return } // Calculate the Sun True Long in degrees based on the formula: sunEqCtr + geomMeanLongSun // sunEqCtr - Sun Eq Ctr calculated by the calcSunEqCtr function // geomMeanLongSun - Geom Mean Long Sun calculated by the calcGeomMeanLongSun function // Return The Sun True Long slice func calcSunTrueLong(sunEqCtr []float64, geomMeanLongSun []float64) (sunTrueLong []float64) { if len(sunEqCtr) != len(geomMeanLongSun) { return } for index := 0; index < len(sunEqCtr); index++ { temp := sunEqCtr[index] + geomMeanLongSun[index] sunTrueLong = append(sunTrueLong, temp) } return } // Calculate the Sun App Long in degrees based on the formula: sunTrueLong-0.00569-0.00478*sin(deg2rad(125.04-1934.136*julianCentury)) // sunTrueLong - Sun True Long calculated by the calcSunTrueLong function // julianCentury - Julian century calculated by the calcJulianCentury function // Return The Sun App Long slice func calcSunAppLong(sunTrueLong []float64, julianCentury []float64) (sunAppLong []float64) { if len(sunTrueLong) != len(julianCentury) { return } for index := 0; index < len(sunTrueLong); index++ { temp := sunTrueLong[index] - 0.00569 - 0.00478*math.Sin(deg2rad(125.04-1934.136*julianCentury[index])) sunAppLong = append(sunAppLong, temp) } return } // Calculate the Mean Obliq Ecliptic in degrees based on the formula: 23+(26+((21.448-julianCentury*(46.815+julianCentury*(0.00059-julianCentury*0.001813))))/60)/60 // julianCentury - Julian century calculated by the calcJulianCentury function // Return the Mean Obliq Ecliptic slice func calcMeanObliqEcliptic(julianCentury []float64) (meanObliqEcliptic []float64) { for index := 0; index < len(julianCentury); index++ { temp := 23.0 + (26.0+(21.448-julianCentury[index]*(46.815+julianCentury[index]*(0.00059-julianCentury[index]*0.001813)))/60.0)/60.0 meanObliqEcliptic = append(meanObliqEcliptic, temp) } return } // Calculate the Obliq Corr in degrees based on the formula: meanObliqEcliptic+0.00256*cos(deg2rad(125.04-1934.136*julianCentury)) // meanObliqEcliptic - Mean Obliq Ecliptic calculated by the calcMeanObliqEcliptic function // julianCentury - Julian century calculated by the calcJulianCentury function // Return the Obliq Corr slice func calcObliqCorr(meanObliqEcliptic []float64, julianCentury []float64) (obliqCorr []float64) { if len(meanObliqEcliptic) != len(julianCentury) { return } for index := 0; index < len(julianCentury); index++ { temp := meanObliqEcliptic[index] + 0.00256*math.Cos(deg2rad(125.04-1934.136*julianCentury[index])) obliqCorr = append(obliqCorr, temp) } return } // Calculate the Sun Declination in degrees based on the formula: rad2deg(asin(sin(deg2rad(obliqCorr))*sin(deg2rad(sunAppLong)))) // obliqCorr - Obliq Corr calculated by the calcObliqCorr function // sunAppLong - Sun App Long calculated by the calcSunAppLong function // Return the sun declination slice func calcSunDeclination(obliqCorr []float64, sunAppLong []float64) (sunDeclination []float64) { if len(obliqCorr) != len(sunAppLong) { return } for index := 0; index < len(obliqCorr); index++ { temp := rad2deg(math.Asin(math.Sin(deg2rad(obliqCorr[index])) * math.Sin(deg2rad(sunAppLong[index])))) sunDeclination = append(sunDeclination, temp) } return } // Calculate the equation of time (minutes) based on the formula: // 4*rad2deg(multiFactor*sin(2*deg2rad(geomMeanLongSun))-2*eccentEarthOrbit*sin(deg2rad(geomMeanAnomSun))+4*eccentEarthOrbit*multiFactor*sin(deg2rad(geomMeanAnomSun))*cos(2*deg2rad(geomMeanLongSun))-0.5*multiFactor*multiFactor*sin(4*deg2rad(geomMeanLongSun))-1.25*eccentEarthOrbit*eccentEarthOrbit*sin(2*deg2rad(geomMeanAnomSun))) // multiFactor - The Multi Factor vector calculated in the calculate function // geomMeanLongSun - The Geom Mean Long Sun vector calculated by the calcGeomMeanLongSun function // eccentEarthOrbit - The Eccent Earth vector calculated by the calcEccentEarthOrbit function // geomMeanAnomSun - The Geom Mean Anom Sun vector calculated by the calcGeomMeanAnomSun function // Return the equation of time slice func calcEquationOfTime(multiFactor []float64, geomMeanLongSun []float64, eccentEarthOrbit []float64, geomMeanAnomSun []float64) (equationOfTime []float64) { if len(multiFactor) != len(geomMeanLongSun) || len(multiFactor) != len(eccentEarthOrbit) || len(multiFactor) != len(geomMeanAnomSun) { return } for index := 0; index < len(multiFactor); index++ { a := multiFactor[index] * math.Sin(2.0*deg2rad(geomMeanLongSun[index])) b := 2.0 * eccentEarthOrbit[index] * math.Sin(deg2rad(geomMeanAnomSun[index])) c := 4.0 * eccentEarthOrbit[index] * multiFactor[index] * math.Sin(deg2rad(geomMeanAnomSun[index])) d := math.Cos(2.0 * deg2rad(geomMeanLongSun[index])) e := 0.5 * multiFactor[index] * multiFactor[index] * math.Sin(4.0*deg2rad(geomMeanLongSun[index])) f := 1.25 * eccentEarthOrbit[index] * eccentEarthOrbit[index] * math.Sin(2.0*deg2rad(geomMeanAnomSun[index])) temp := 4.0 * rad2deg(a-b+c*d-e-f) equationOfTime = append(equationOfTime, temp) } return } // Calculate the HaSunrise in degrees based on the formula: rad2deg(acos(cos(deg2rad(90.833))/(cos(deg2rad(latitude))*cos(deg2rad(sunDeclination)))-tan(deg2rad(latitude))*tan(deg2rad(sunDeclination)))) // latitude - The latitude defined by the user // sunDeclination - The Sun Declination calculated by the calcSunDeclination function // Return the HaSunrise slice func calcHaSunrise(latitude float64, sunDeclination []float64) (haSunrise []float64) { for index := 0; index < len(sunDeclination); index++ { temp := rad2deg(math.Acos(math.Cos(deg2rad(90.833))/(math.Cos(deg2rad(latitude))*math.Cos(deg2rad(sunDeclination[index]))) - math.Tan(deg2rad(latitude))*math.Tan(deg2rad(sunDeclination[index])))) haSunrise = append(haSunrise, temp) } return } // Calculate the Solar Noon based on the formula: (720 - 4 * longitude - equationOfTime + utcOffset * 60) * 60 // longitude - The longitude is defined by the user // equationOfTime - The Equation of Time slice is calculated by the calcEquationOfTime function // utcOffset - The UTC offset is defined by the user // Return the Solar Noon slice func calcSolarNoon(longitude float64, equationOfTime []float64, utcOffset float64) (solarNoon []float64) { for index := 0; index < len(equationOfTime); index++ { temp := (720.0 - 4.0*longitude - equationOfTime[index] + utcOffset*60.0) * 60.0 solarNoon = append(solarNoon, temp) } return } // Check if the latitude is valid. Range: -90 - 90 func checkLatitude(latitude float64) bool { if latitude < -90.0 || latitude > 90.0 { return false } return true } // Check if the longitude is valid. Range: -180 - 180 func checkLongitude(longitude float64) bool { if longitude < -180.0 || longitude > 180.0 { return false } return true } // Check if the UTC offset is valid. Range: -12 - 14 func checkUtcOffset(utcOffset float64) bool { if utcOffset < -12.0 || utcOffset > 14.0 { return false } return true } // Check if the date is valid. func checkDate(date time.Time) bool { minDate := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC) maxDate := time.Date(2200, 1, 1, 0, 0, 0, 0, time.UTC) if date.Before(minDate) || date.After(maxDate) { return false } return true } // Compute the number of days between two dates func diffDays(date1, date2 time.Time) int64 { return int64(date2.Sub(date1) / (24 * time.Hour)) } // Find the index of the minimum value func minIndex(slice []float64) int { if len(slice) == 0 { return -1 } min := slice[0] minIndex := 0 for index := 0; index < len(slice); index++ { if slice[index] < min { min = slice[index] minIndex = index } } return minIndex } // Convert each value to the absolute value func abs(slice []float64) []float64 { var newSlice []float64 for _, value := range slice { if value < 0.0 { value = math.Abs(value) } newSlice = append(newSlice, value) } return newSlice } func round(value float64) int { if value < 0 { return int(value - 0.5) } return int(value + 0.5) } // GetSunriseSunset function is responsible for calculate the apparent Sunrise and Sunset times. // If some parameter is wrong it will return an error. func GetSunriseSunset(latitude float64, longitude float64, utcOffset float64, date time.Time) (sunrise time.Time, sunset time.Time, err error) { // Check latitude if !checkLatitude(latitude) { err = errors.New("Invalid latitude") return } // Check longitude if !checkLongitude(longitude) { err = errors.New("Invalid longitude") return } // Check UTC offset if !checkUtcOffset(utcOffset) { err = errors.New("Invalid UTC offset") return } // Check date if !checkDate(date) { err = errors.New("Invalid date") return } // The number of days since 30/12/1899 since := time.Date(1899, 12, 30, 0, 0, 0, 0, time.UTC) numDays := diffDays(since, date) // Seconds of a full day 86400 seconds := 24 * 60 * 60 // Creates a vector that represents each second in the range 0~1 secondsNorm := createSecondsNormalized(seconds) // Calculate Julian Day julianDay := calcJulianDay(numDays, secondsNorm, utcOffset) // Calculate Julian Century julianCentury := calcJulianCentury(julianDay) // Geom Mean Long Sun (deg) geomMeanLongSun := calcGeomMeanLongSun(julianCentury) // Geom Mean Anom Sun (deg) geomMeanAnomSun := calcGeomMeanAnomSun(julianCentury) // Eccent Earth Orbit eccentEarthOrbit := calcEccentEarthOrbit(julianCentury) // Sun Eq of Ctr sunEqCtr := calcSunEqCtr(julianCentury, geomMeanAnomSun) // Sun True Long (deg) sunTrueLong := calcSunTrueLong(sunEqCtr, geomMeanLongSun) // Sun App Long (deg) sunAppLong := calcSunAppLong(sunTrueLong, julianCentury) // Mean Obliq Ecliptic (deg) meanObliqEcliptic := calcMeanObliqEcliptic(julianCentury) // Obliq Corr (deg) obliqCorr := calcObliqCorr(meanObliqEcliptic, julianCentury) // Sun Declin (deg) sunDeclination := calcSunDeclination(obliqCorr, sunAppLong) // var y var multiFactor []float64 for index := 0; index < len(obliqCorr); index++ { temp := math.Tan(deg2rad(obliqCorr[index]/2.0)) * math.Tan(deg2rad(obliqCorr[index]/2.0)) multiFactor = append(multiFactor, temp) } // Eq of Time (minutes) equationOfTime := calcEquationOfTime(multiFactor, geomMeanLongSun, eccentEarthOrbit, geomMeanAnomSun) // HA Sunrise (deg) haSunrise := calcHaSunrise(latitude, sunDeclination) // Solar Noon (LST) solarNoon := calcSolarNoon(longitude, equationOfTime, utcOffset) // Sunrise and Sunset Times (LST) var tempSunrise []float64 var tempSunset []float64 for index := 0; index < len(solarNoon); index++ { tempSunrise = append(tempSunrise, (solarNoon[index] - float64(round(haSunrise[index]*4.0*60.0)) - float64(seconds)*secondsNorm[index])) tempSunset = append(tempSunset, (solarNoon[index] + float64(round(haSunrise[index]*4.0*60.0)) - float64(seconds)*secondsNorm[index])) } // Get the sunrise and sunset in seconds sunriseSeconds := minIndex(abs(tempSunrise)) sunsetSeconds := minIndex(abs(tempSunset)) // Convert the seconds to time defaultTime := new(time.Time) sunrise = defaultTime.Add(time.Duration(sunriseSeconds) * time.Second) sunset = defaultTime.Add(time.Duration(sunsetSeconds) * time.Second) return }
vendor/github.com/kelvins/sunrisesunset/sunrisesunset.go
0.859605
0.828419
sunrisesunset.go
starcoder
package boleto import ( "errors" "time" ) const ( // DefaultFebrabanType defines the default febraban type used in the document DefaultFebrabanType = "dm" maxInstructionsSize = 6 ) var ( // ErrDiscountHigherThanValue is used when the discount value is higher than the value of the bank slip ErrDiscountHigherThanValue = errors.New("discount value cannot be higher than the value") // ErrForfeitHigherThanValue is used when the forfeit value is higher than the value of the bank slip ErrForfeitHigherThanValue = errors.New("forfeit value cannot be higher than the value") // ErrTooManyInstructions is used when the ammount of instructions reaches the limit ErrTooManyInstructions = errors.New("you cannot add more instructions to the document") // ErrEmptyPayer is used when the given payer is nil ErrEmptyPayer = errors.New("you need to pass a payer pointer") ) // Document holds the data of the billet itself type Document struct { // ID identifier of your program orders/payments ID int Date time.Time DateDue time.Time Value uint // ValueTax is the tax for emitting the bank slip ValueTax uint // ValueDiscount if any discount is required ValueDiscount uint // ValueForfeit if any interest or debt needs to be calculated ValueForfeit uint // OurNumber literely translates to `Nosso Numero`. This is a number that is provided by the partner bank // where this boleto is going to be payed for. OurNumber int // FebrabanType is the document type according FEBRABAN, the default used is "DM" (Duplicata mercantil), // Source: (http://www.bb.com.br/docs/pub/emp/empl/dwn/011DescrCampos.pdf) FebrabanType string // Instructions are any instructions that should be printed in the bank slip Instructions []string // Payer is to whom this boleto is being emitted Payer *Payer } // NewDocument creates a new instance of Document with the emission date set to now func NewDocument(id int, ourNumber int, dueDate time.Time) *Document { return NewDocumentFrom(id, ourNumber, time.Now(), dueDate) } // NewDocumentFrom creates a new instance of Document where you must provide the emission date func NewDocumentFrom(id int, ourNumber int, date time.Time, dueDate time.Time) *Document { return &Document{ ID: id, OurNumber: ourNumber, Date: date, DateDue: dueDate, FebrabanType: DefaultFebrabanType, } } // DefineValue defines the values for the document func (d *Document) DefineValue(value uint, discount uint, forfeit uint) error { if discount > value { return ErrDiscountHigherThanValue } if forfeit > value { return ErrForfeitHigherThanValue } d.Value = value d.ValueDiscount = discount d.ValueForfeit = forfeit return nil } // AddInstruction add a single instruction to the document func (d *Document) AddInstruction(i string) error { if len(d.Instructions) > maxInstructionsSize { return ErrTooManyInstructions } d.Instructions = append(d.Instructions, i) return nil } // To defines to whom the document will be addressed func (d *Document) To(p *Payer) error { if p == nil { return ErrEmptyPayer } d.Payer = p return nil } // Total calculates the total of the boleto func (d *Document) Total() uint { return (d.Value + d.ValueForfeit) - d.ValueDiscount }
document.go
0.680242
0.415254
document.go
starcoder
package srg import ( "fmt" "sort" "strings" "github.com/serulian/compiler/compilergraph" "github.com/serulian/compiler/sourceshape" ) // FindCommentedNode attempts to find the node in the SRG with the given comment attached. func (g *SRG) FindCommentedNode(commentValue string) (compilergraph.GraphNode, bool) { return g.layer.StartQuery(commentValue). In(sourceshape.NodeCommentPredicateValue). In(sourceshape.NodePredicateChild). TryGetNode() } // FindComment attempts to find the comment in the SRG with the given value. func (g *SRG) FindComment(commentValue string) (SRGComment, bool) { commentNode, ok := g.layer.StartQuery(commentValue). In(sourceshape.NodeCommentPredicateValue). TryGetNode() if !ok { return SRGComment{}, false } return SRGComment{commentNode, g}, true } // AllComments returns an iterator over all the comment nodes found in the SRG. func (g *SRG) AllComments() compilergraph.NodeIterator { return g.layer.StartQuery().Has(sourceshape.NodeCommentPredicateValue).BuildNodeIterator() } // getDocumentationForNode returns the documentation attached to the given node, if any. func (g *SRG) getDocumentationForNode(node compilergraph.GraphNode) (SRGDocumentation, bool) { cit := node.StartQuery(). Out(sourceshape.NodePredicateChild). Has(sourceshape.NodeCommentPredicateValue). BuildNodeIterator() var docComment *SRGComment for cit.Next() { commentNode := cit.Node() srgComment := SRGComment{commentNode, g} if docComment == nil { docComment = &srgComment } // Doc comments always win. if srgComment.IsDocComment() { docComment = &srgComment } } if docComment == nil { return SRGDocumentation{}, false } return docComment.Documentation() } // getDocumentationCommentForNode returns the last comment attached to the given SRG node, if any. func (g *SRG) getDocumentationCommentForNode(node compilergraph.GraphNode) (SRGComment, bool) { // The documentation on a node is its *last* comment. cit := node.StartQuery(). Out(sourceshape.NodePredicateChild). Has(sourceshape.NodeCommentPredicateValue). BuildNodeIterator() var comment SRGComment var commentFound = false for cit.Next() { commentFound = true comment = SRGComment{cit.Node(), g} } return comment, commentFound } // srgCommentKind defines a struct for specifying various pieces of config about a kind of // comment found in the SRG. type srgCommentKind struct { prefix string suffix string multilinePrefix string isDocComment bool } // commentsKinds defines the various kinds of comments. var commentsKinds = []srgCommentKind{ srgCommentKind{"/**", "*/", "*", true}, srgCommentKind{"/*", "*/", "*", false}, srgCommentKind{"//", "", "", false}, } // getCommentKind returns the kind of the comment, if any. func getCommentKind(value string) (srgCommentKind, bool) { for _, kind := range commentsKinds { if strings.HasPrefix(value, kind.prefix) { return kind, true } } return srgCommentKind{}, false } // getTrimmedCommentContentsString returns trimmed contents of the given comment. func getTrimmedCommentContentsString(value string) string { kind, isValid := getCommentKind(value) if !isValid { return "" } lines := strings.Split(value, "\n") var newLines = make([]string, 0, len(lines)) for index, line := range lines { var updatedLine = line if index == 0 { updatedLine = strings.TrimPrefix(strings.TrimSpace(updatedLine), kind.prefix) } if index == len(lines)-1 { updatedLine = strings.TrimSuffix(strings.TrimSpace(updatedLine), kind.suffix) } if index > 0 && index < len(lines)-1 { updatedLine = strings.TrimPrefix(strings.TrimSpace(updatedLine), kind.multilinePrefix) } updatedLine = strings.TrimSpace(updatedLine) newLines = append(newLines, updatedLine) } return strings.TrimSpace(strings.Join(newLines, "\n")) } // SRGComment wraps a comment node with helpers for accessing documentation. type SRGComment struct { compilergraph.GraphNode srg *SRG // The parent SRG. } // kind returns the kind of the comment. func (c SRGComment) kind() srgCommentKind { value := c.GraphNode.Get(sourceshape.NodeCommentPredicateValue) kind, isValid := getCommentKind(value) if !isValid { panic("Invalid comment kind") } return kind } // IsDocComment returns true if the comment is a doc comment, instead of a normal // comment. func (c SRGComment) IsDocComment() bool { return c.kind().isDocComment } // ParentNode returns the node that contains this comment. func (c SRGComment) ParentNode() compilergraph.GraphNode { return c.GraphNode.GetIncomingNode(sourceshape.NodePredicateChild) } // Contents returns the trimmed contents of the comment. func (c SRGComment) Contents() string { value := c.GraphNode.Get(sourceshape.NodeCommentPredicateValue) return getTrimmedCommentContentsString(value) } // Documentation returns the documentation found in this comment, if any. func (c SRGComment) Documentation() (SRGDocumentation, bool) { return SRGDocumentation{ parentComment: c, commentValue: c.Contents(), isDocComment: c.IsDocComment(), }, true } // SRGDocumentation represents documentation found on an SRG node. It is distinct from a comment in // that it can be *part* of another comment. type SRGDocumentation struct { parentComment SRGComment commentValue string isDocComment bool } // String returns the human-readable documentation string. func (d SRGDocumentation) String() string { return d.commentValue } // IsDocComment returns true if the documentation was found in a doc-comment style // comment (instead of a standard comment). func (d SRGDocumentation) IsDocComment() bool { return d.isDocComment } type byLocation struct { values []string strValue string } func (s byLocation) Len() int { return len(s.values) } func (s byLocation) Swap(i, j int) { s.values[i], s.values[j] = s.values[j], s.values[i] } func (s byLocation) Less(i, j int) bool { return strings.Index(s.values[i], s.strValue) < strings.Index(s.values[j], s.strValue) } // ForParameter returns the documentation associated with the given parameter name, if any. func (d SRGDocumentation) ForParameter(paramName string) (SRGDocumentation, bool) { strValue, hasValue := documentationForParameter(d.String(), paramName) if !hasValue { return SRGDocumentation{}, false } return SRGDocumentation{ parentComment: d.parentComment, isDocComment: d.isDocComment, commentValue: strValue, }, true } func documentationForParameter(commentValue string, paramName string) (string, bool) { // Find all sentences in the documentation. sentences := strings.Split(commentValue, ".") // Find any sentences with a ticked reference to the parameter. tickedParam := fmt.Sprintf("`%s`", paramName) tickedSentences := make([]string, 0, len(sentences)) for _, sentence := range sentences { if strings.Contains(sentence, tickedParam) { tickedSentences = append(tickedSentences, sentence) } } if len(tickedSentences) == 0 { return "", false } sort.Sort(byLocation{tickedSentences, tickedParam}) paramComment := strings.TrimSpace(tickedSentences[0]) return paramComment, true }
graphs/srg/comments.go
0.696887
0.42471
comments.go
starcoder
package pricing import ( "fmt" "go.uber.org/zap" "github.com/transcom/mymove/pkg/models" ) var parsePriceEscalationDiscount processXlsxSheet = func(params ParamConfig, sheetIndex int, logger Logger) (interface{}, error) { const xlsxDataSheetNum int = 18 const discountsRowIndexStart int = 9 const contractYearColumn int = 7 const forecastingAdjustmentColumn int = 8 const discountColumn int = 9 const priceEscalationColumn int = 10 if xlsxDataSheetNum != sheetIndex { return nil, fmt.Errorf("parsePriceEscalationDiscount expected to process sheet %d, but received sheetIndex %d", xlsxDataSheetNum, sheetIndex) } logger.Info("Parsing price escalation discount") var priceEscalationDiscounts []models.StagePriceEscalationDiscount dataRows := params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[discountsRowIndexStart:] for _, row := range dataRows { priceEscalationDiscount := models.StagePriceEscalationDiscount{ ContractYear: getCell(row.Cells, contractYearColumn), ForecastingAdjustment: getCell(row.Cells, forecastingAdjustmentColumn), Discount: getCell(row.Cells, discountColumn), PriceEscalation: getCell(row.Cells, priceEscalationColumn), } if priceEscalationDiscount.ContractYear == "" { break } if params.ShowOutput { logger.Info("", zap.Any("StagePriceEscalationDiscount", priceEscalationDiscount)) } priceEscalationDiscounts = append(priceEscalationDiscounts, priceEscalationDiscount) } return priceEscalationDiscounts, nil } var verifyPriceEscalationDiscount verifyXlsxSheet = func(params ParamConfig, sheetIndex int) error { const xlsxDataSheetNum int = 18 const discountsRowIndexStart int = 9 const contractYearColumn int = 7 const forecastingAdjustmentColumn int = 8 const discountColumn int = 9 const priceEscalationColumn int = 10 if xlsxDataSheetNum != sheetIndex { return fmt.Errorf("verifyPriceEscalationDiscount expected to process sheet %d, but received sheetIndex %d", xlsxDataSheetNum, sheetIndex) } // Check names on header row headerRow := params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[discountsRowIndexStart-2] // header 2 rows above data headers := []headerInfo{ {"Contract Year", contractYearColumn}, {"Government-set IHS Markit Pricing and Purchasing Industry Forecasting Adjustment", forecastingAdjustmentColumn}, {"Discount", discountColumn}, {"Resulting Price Escalation", priceEscalationColumn}, } for _, header := range headers { if err := verifyHeader(headerRow, header.column, header.headerName); err != nil { return err } } // Check name on example row exampleRow := params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[discountsRowIndexStart-1] // example 1 row above data return verifyHeader(exampleRow, contractYearColumn, "EXAMPLE") }
pkg/parser/pricing/parse_price_escalation_discount.go
0.634317
0.42477
parse_price_escalation_discount.go
starcoder
package proj import ( "fmt" "math" ) // AEA is an Albers Conical Equal Area projection. func AEA(this *SR) (forward, inverse Transformer, err error) { if math.Abs(this.Lat1+this.Lat2) < epsln { err = fmt.Errorf("proj.AEA: standard Parallels cannot be equal and on opposite sides of the equator") } temp := this.B / this.A es := 1 - math.Pow(temp, 2) e3 := math.Sqrt(es) sin_po := math.Sin(this.Lat1) cos_po := math.Cos(this.Lat1) //t1 := sin_po con := sin_po ms1 := msfnz(e3, sin_po, cos_po) qs1 := qsfnz(e3, sin_po) sin_po = math.Sin(this.Lat2) cos_po = math.Cos(this.Lat2) //t2 := sin_po ms2 := msfnz(e3, sin_po, cos_po) qs2 := qsfnz(e3, sin_po) sin_po = math.Sin(this.Lat0) //cos_po = math.Cos(this.Lat0) //t3 := sin_po qs0 := qsfnz(e3, sin_po) var ns0 float64 if math.Abs(this.Lat1-this.Lat2) > epsln { ns0 = (ms1*ms1 - ms2*ms2) / (qs2 - qs1) } else { ns0 = con } c := ms1*ms1 + ns0*qs1 rh := this.A * math.Sqrt(c-ns0*qs0) / ns0 /* Albers Conical Equal Area forward equations--mapping lat,long to x,y -------------------------------------------------------------------*/ forward = func(lon, lat float64) (x, y float64, err error) { sin_phi := math.Sin(lat) //cos_phi := math.Cos(lat) var qs = qsfnz(e3, sin_phi) var rh1 = this.A * math.Sqrt(c-ns0*qs) / ns0 var theta = ns0 * adjust_lon(lon-this.Long0) x = rh1*math.Sin(theta) + this.X0 y = rh - rh1*math.Cos(theta) + this.Y0 return } inverse = func(x, y float64) (lon, lat float64, err error) { var rh1, qs, con, theta float64 x -= this.X0 y = rh - y + this.Y0 if ns0 >= 0 { rh1 = math.Sqrt(x*x + y*y) con = 1 } else { rh1 = -math.Sqrt(x*x + y*y) con = -1 } theta = 0 if rh1 != 0 { theta = math.Atan2(con*x, con*y) } con = rh1 * ns0 / this.A if this.sphere { lat = math.Asin((c - con*con) / (2 * ns0)) } else { qs = (c - con*con) / ns0 lat, err = aeaPhi1z(e3, qs) if err != nil { return } } lon = adjust_lon(theta/ns0 + this.Long0) return } return } // aeaPhi1z is a function to compute phi1, the latitude for the inverse of the // Albers Conical Equal-Area projection. func aeaPhi1z(eccent, qs float64) (float64, error) { var sinphi, cosphi, con, com, dphi float64 var phi = asinz(0.5 * qs) if eccent < epsln { return phi, nil } var eccnts = eccent * eccent for i := 1; i <= 25; i++ { sinphi = math.Sin(phi) cosphi = math.Cos(phi) con = eccent * sinphi com = 1 - con*con dphi = 0.5 * com * com / cosphi * (qs/(1-eccnts) - sinphi/com + 0.5/eccent*math.Log((1-con)/(1+con))) phi = phi + dphi if math.Abs(dphi) <= 1e-7 { return phi, nil } } return math.NaN(), fmt.Errorf("proj.aeaPhi1z: didn't converge") } func init() { registerTrans(AEA, "Albers_Conic_Equal_Area", "Albers", "aea") }
proj/aea.go
0.619126
0.516291
aea.go
starcoder
package flow import ( "sync" ) // Tracker represents a structure responsible of tracking nodes type Tracker interface { // Flow returns the flow name of the assigned tracker Flow() string // Mark marks the given node as called Mark(node *Node) // Skip marks the given node as marked and flag the given node as skipped Skip(node *Node) // Skipped returns a boolean representing whether the given node has been skipped Skipped(node *Node) bool // Reached checks whether the required dependencies counter have been reached Reached(node *Node, nodes int) bool // Met checks whether the given nodes have been called Met(nodes ...*Node) bool // Lock locks the given node Lock(node *Node) // Unlock unlocks the given node Unlock(node *Node) } // NewTracker constructs a new tracker func NewTracker(flow string, nodes int) Tracker { return &tracker{ flow: flow, nodes: make(map[string]int, nodes), locks: make(map[*Node]*sync.Mutex, nodes), } } // Tracker represents a structure responsible of tracking nodes type tracker struct { flow string mutex sync.Mutex nodes map[string]int locks map[*Node]*sync.Mutex } // Flow returns the flow name of the assigned tracker func (tracker *tracker) Flow() string { return tracker.flow } // Mark marks the given node as called func (tracker *tracker) Mark(node *Node) { tracker.mutex.Lock() tracker.nodes[node.Name]++ tracker.mutex.Unlock() } // Skip marks the given node as marked and flag the given node as skipped func (tracker *tracker) Skip(node *Node) { tracker.mutex.Lock() tracker.nodes[node.Name] = -1 tracker.mutex.Unlock() } // Skip marks the given node as marked and flag the given node as skipped func (tracker *tracker) Skipped(node *Node) bool { tracker.mutex.Lock() value := tracker.nodes[node.Name] tracker.mutex.Unlock() return value < 0 } // Reached checks whether the required dependencies counter have been reached func (tracker *tracker) Reached(node *Node, nodes int) bool { tracker.mutex.Lock() defer tracker.mutex.Unlock() if tracker.nodes[node.Name] != nodes { return false } return true } // Met checks whether the given nodes have been called func (tracker *tracker) Met(nodes ...*Node) bool { tracker.mutex.Lock() defer tracker.mutex.Unlock() for _, node := range nodes { value := tracker.nodes[node.Name] if value <= 0 { return false } } return true } // Lock locks the given node func (tracker *tracker) Lock(node *Node) { tracker.mutex.Lock() mutex := tracker.locks[node] if mutex == nil { mutex = &sync.Mutex{} tracker.locks[node] = mutex } tracker.mutex.Unlock() mutex.Lock() } // Unlock unlocks the given node func (tracker *tracker) Unlock(node *Node) { tracker.mutex.Lock() mutex := tracker.locks[node] tracker.mutex.Unlock() mutex.Unlock() }
pkg/flow/tracker.go
0.727782
0.444987
tracker.go
starcoder
package markov import ( "bufio" "fmt" "io" "math/rand" "strings" "encoding/json" "os" "github.com/sdukhovni/clyde-go/stringutil" ) // Prefix is a Markov chain prefix of one or more lowercase words. It // may begin with some number of empty strings followed by the string // "START" in all-caps, to indicate the start of a block of // input/output text. type Prefix []string // NewPrefix creates a new Prefix ending with the "START" symbol. func NewPrefix(prefixLen int) (Prefix) { p := make([]string, prefixLen) p[prefixLen-1] = "START" return p } // Shift removes the first word from the Prefix and appends the given word lowercased. func (p Prefix) Shift(word string) { copy(p, p[1:]) p[len(p)-1] = strings.ToLower(word) } // Chain contains a map ("chain") of prefixes to a map of suffixes to // frequencies. A prefix is a string of zero to prefixLen lowercase // words joined with spaces. A suffix is a single word. type Chain struct { chain map[string]map[string]int prefixLen int stats []int } // NewChain returns a new Chain with prefixes of prefixLen words. func NewChain(prefixLen int) *Chain { return &Chain{make(map[string]map[string]int), prefixLen, make([]int, prefixLen+1)} } // Add increments the frequency count for a suffix following each // distinct tail of a prefix func (c *Chain) Add(p Prefix, s string) { for i := 0; i <= c.prefixLen; i++ { if i < c.prefixLen && p[i] == "" { continue } key := strings.Join(p[i:], " ") if c.chain[key] == nil { c.chain[key] = make(map[string]int) } c.chain[key][s]++ } } // Build reads text from the provided Reader and // parses it into prefixes and suffixes that are stored in Chain. func (c *Chain) Build(r io.Reader) { br := bufio.NewReader(r) p := NewPrefix(c.prefixLen) for { var s string if _, err := fmt.Fscan(br, &s); err != nil { break } c.Add(p, s) p.Shift(s) } } // NextWord randomly chooses a word to follow the given prefix, using // the weights provided by Chain. func (c *Chain) NextWord(p Prefix) string { // Try each tail of the prefix, starting with the longest for i := 0; i <= c.prefixLen; i++ { key := strings.Join(p[i:], " ") if c.chain[key] == nil { continue } c.stats[c.prefixLen-i]++ // Make a random choice weighted by frequency total := 0 for _, freq := range c.chain[key] { total += freq } if total == 0 { continue } n := rand.Intn(total) var result string for w, freq := range c.chain[key] { n -= freq if n <= 0 { result = w break } } // If we're making an uninformed choice because we // don't recognize the tail word, at least try to get // capitalization right. if key == "" { if stringutil.IsEndOfSentence(p[c.prefixLen-1]) { result = stringutil.Capitalize(result) } else { result = strings.ToLower(result) } } return result } return "" } // Generate returns a string of at most maxWords words (in addition to // any words in the start string) generated from Chain. It attempts // to generate exactly the requested number of sentences, but may // generate fewer if the chain doesn't produce enough // sentence-endings, or may generate a single sentence fragment if the // chain produces no sentence endings within the word limit. func (c *Chain) Generate(start string, sentences, maxWords int) string { words := strings.Fields(start) p := NewPrefix(c.prefixLen) lastWordsStart := len(words) - c.prefixLen if lastWordsStart < 0 { lastWordsStart = 0 } for _,w := range words[lastWordsStart:] { p.Shift(w) } sentenceCount := 0 sentenceEndIndex := 0 for i := 0; i < maxWords && sentenceCount < sentences; i++ { next := c.NextWord(p) if len(next) == 0 { break } words = append(words, next) p.Shift(next) if stringutil.IsEndOfSentence(next) { sentenceCount++ sentenceEndIndex = len(words) } } if sentenceCount < sentences && sentenceEndIndex > 0 { words = words[:sentenceEndIndex] } return strings.Join(words, " ") } // Load attempts to load a suffix frequency map in JSON format from // the given file to use in Chain. func (c *Chain) Load(filename string) error { f, err := os.Open(filename) if err != nil { return err } defer f.Close() dec := json.NewDecoder(f) err = dec.Decode(&(c.chain)) if err != nil { return err } return nil } // Save saves a chain's suffix frequency map to the given file in JSON // format func (c *Chain) Save(filename string) error { f, err := os.Create(filename) if err != nil { return err } defer f.Close() enc := json.NewEncoder(f) err = enc.Encode(c.chain) if err != nil { return err } return nil } // Size returns the number of prefixes stored in the chain. func (c *Chain) Size() int { return len(c.chain) } // Stats returns a histogram of what prefix lengths are being used to // generate words. The nth entry in the returned array holds the // number of words generated using length-n prefixes. func (c *Chain) Stats() []int { retval := make([]int, len(c.stats)) copy(retval, c.stats) return retval }
markov/markov.go
0.733929
0.400925
markov.go
starcoder
package geom // A MultiPoint is a collection of Points. type MultiPoint struct { geom1 } // NewMultiPoint returns a new, empty, MultiPoint. func NewMultiPoint(layout Layout) *MultiPoint { return NewMultiPointFlat(layout, nil) } // NewMultiPointFlat returns a new MultiPoint with the given flat coordinates. func NewMultiPointFlat(layout Layout, flatCoords []float64) *MultiPoint { mp := new(MultiPoint) mp.layout = layout mp.stride = layout.Stride() mp.flatCoords = flatCoords return mp } // Area returns zero. func (mp *MultiPoint) Area() float64 { return 0 } // Clone returns a deep copy. func (mp *MultiPoint) Clone() *MultiPoint { flatCoords := make([]float64, len(mp.flatCoords)) copy(flatCoords, mp.flatCoords) return NewMultiPointFlat(mp.layout, flatCoords) } // Empty returns true if the collection is empty. func (mp *MultiPoint) Empty() bool { return mp.NumPoints() == 0 } // Length returns zero. func (mp *MultiPoint) Length() float64 { return 0 } // MustSetCoords sets the coordinates and panics on any error. func (mp *MultiPoint) MustSetCoords(coords []Coord) *MultiPoint { Must(mp.SetCoords(coords)) return mp } // SetCoords sets the coordinates. func (mp *MultiPoint) SetCoords(coords []Coord) (*MultiPoint, error) { if err := mp.setCoords(coords); err != nil { return nil, err } return mp, nil } // SetSRID sets the SRID of mp. func (mp *MultiPoint) SetSRID(srid int) *MultiPoint { mp.srid = srid return mp } // NumPoints returns the number of Points. func (mp *MultiPoint) NumPoints() int { return mp.NumCoords() } // Point returns the ith Point. func (mp *MultiPoint) Point(i int) *Point { return NewPointFlat(mp.layout, mp.Coord(i)) } // Push appends a point. func (mp *MultiPoint) Push(p *Point) error { if p.layout != mp.layout { return ErrLayoutMismatch{Got: p.layout, Want: mp.layout} } mp.flatCoords = append(mp.flatCoords, p.flatCoords...) return nil } // Swap swaps the values of mp and mp2. func (mp *MultiPoint) Swap(mp2 *MultiPoint) { mp.geom1.swap(&mp2.geom1) }
vendor/github.com/twpayne/go-geom/multipoint.go
0.907246
0.490175
multipoint.go
starcoder
package codec import ( "encoding/binary" "github.com/pingcap/errors" ) const ( encGroupSize = 9 encPad = 0x0 ) /* This is the new algorithm. Similarly to the legacy format the input is split up into N-1 bytes and a flag byte is used as the Nth byte in the output. - If the previous segment needed any padding the flag is set to the number of bytes used (0..N-2). 0 is possible in the first segment if the input is 0 bytes long. - If no padding was used and there is no more data left in the input the flag is set to N-1 - If no padding was used and there is still data left in the input the flag is set to N. For N=9, the following input values encode to the specified outout (where 'X' indicates a byte of the original input): - 0 bytes is encoded as 0 0 0 0 0 0 0 0 0 - 1 byte is encoded as X 0 0 0 0 0 0 0 1 - 2 bytes is encoded as X X 0 0 0 0 0 0 2 - 7 bytes is encoded as X X X X X X X 0 7 - 8 bytes is encoded as X X X X X X X X 8 - 9 bytes is encoded as X X X X X X X X 9 X 0 0 0 0 0 0 0 1 - 10 bytes is encoded as X X X X X X X X 9 X X 0 0 0 0 0 0 2 */ func EncodeBytes(b []byte, data []byte) []byte { start := 0 copyLen := encGroupSize - 1 left := len(data) for { if left < encGroupSize-1 { copyLen = left } b = append(b, data[start:start+copyLen]...) left = left - copyLen if left == 0 { padding := make([]byte, encGroupSize-1-copyLen) b = append(b, padding...) b = append(b, byte(copyLen)) break } b = append(b, byte(encGroupSize)) start = start + encGroupSize - 1 } return b } func decodeBytes(b, buf []byte) ([]byte, []byte, error) { if buf == nil { buf = make([]byte, 0, len(b)) } if len(b) < encGroupSize { return b, buf, errors.New("No enough bytes to decode") } buf = buf[:0] for { used := b[encGroupSize-1] if used > encGroupSize { return b, buf, errors.Errorf("Invalid flag, groupBytes: %q", b[:encGroupSize]) } if used <= encGroupSize-1 { for _, pad := range b[used : encGroupSize-1] { if pad != encPad { return b, buf, errors.Errorf("Pad bytes not 0x0, groupBytes: %q", b[:encGroupSize]) } } buf = append(buf, b[:used]...) break } buf = append(buf, b[:encGroupSize-1]...) b = b[encGroupSize:] } return b[encGroupSize:], buf, nil } func DecodeBytes(b, buf []byte) ([]byte, []byte, error) { return decodeBytes(b, buf) } // EncodeCompactBytes joins bytes with its length into a byte slice. It is more // efficient in both space and time compare to EncodeBytes. Note that the encoded // result is not memcomparable. func EncodeCompactBytes(b []byte, data []byte) []byte { b = reallocBytes(b, binary.MaxVarintLen64+len(data)) b = EncodeVarint(b, int64(len(data))) return append(b, data...) } // DecodeCompactBytes decodes bytes which is encoded by EncodeCompactBytes before. func DecodeCompactBytes(b []byte) ([]byte, []byte, error) { b, n, err := DecodeVarint(b) if err != nil { return nil, nil, errors.Trace(err) } if int64(len(b)) < n { return nil, nil, errors.Errorf("insufficient bytes to decode value, expected length: %v", n) } return b[n:], b[:n], nil } // reallocBytes is like realloc. func reallocBytes(b []byte, n int) []byte { newSize := len(b) + n if cap(b) < newSize { bs := make([]byte, len(b), newSize) copy(bs, b) return bs } // slice b has capability to store n bytes return b }
pkg/codec/bytes.go
0.643777
0.538741
bytes.go
starcoder
package ast // These are the available root node types. In JSON it will either be an // object or an array at the base. const ( ObjectRoot RootNodeType = iota ArrayRoot ) // RootNodeType is a type alias for an int type RootNodeType int // RootNode is what starts every parsed AST. There is a `Type` field so that // you can ask which root node type starts the tree. type RootNode struct { RootValue *Value Type RootNodeType } // Available ast value types const ( ObjectType Type = iota ArrayType ArrayItemType LiteralType PropertyType IdentifierType ) const ( StringLiteralValueType LiteralValueType = iota NumberLiteralValueType NullLiteralValueType BooleanLiteralValueType ) // Type is a type alias for int. Represents a node's type. type Type int // LiteralValueType is a type alias for int. Represents the type of the value in a Literal node type LiteralValueType int type StructuralItem struct { Value string } // Object represents a JSON object. It holds a slice of Property as its children, // a Type ("Object"), and start & end code points for displaying. type Object struct { Type Type Children []Property Start int End int SuffixStructure []StructuralItem } // Array represents a JSON array It holds a slice of Value as its children, // a Type ("Array"), and start & end code points for displaying. type Array struct { Type Type PrefixStructure []StructuralItem Children []ArrayItem SuffixStructure []StructuralItem Start int End int } // Array holds a Type ("ArrayItem") as well as a `Value` and whether there is a comma after the item type ArrayItem struct { Type Type PrefixStructure []StructuralItem Value ValueContent PostValueStructure []StructuralItem HasCommaSeparator bool } // Literal represents a JSON literal value. It holds a Type ("Literal") and the actual value. type Literal struct { Type Type ValueType LiteralValueType Value ValueContent Delimiter string // Delimiter is set for string values OriginalRendering string // Allows preservig numeric formatting from source documents } // Property holds a Type ("Property") as well as a `Key` and `Value`. The Key is an Identifier // and the value is any Value. type Property struct { Type Type PrefixStructure []StructuralItem Key Identifier PostKeyStructure []StructuralItem // NOTE: Colon is between PostKeyStructure and PreValue Structure PreValueStructure []StructuralItem Value ValueContent PostValueStructure []StructuralItem HasCommaSeparator bool } // Identifier represents a JSON object property key type Identifier struct { Type Type Value string // "key1" Delimiter string } type Value struct { PrefixStructure []StructuralItem Content ValueContent SuffixStructure []StructuralItem } // ValueContent will eventually have some methods that all Values must implement. For now // it represents any JSON value (object | array | boolean | string | number | null) type ValueContent interface{} // state is a type alias for int and used to create the available value states below type state int // Available states for each type used in parsing const ( // Object states ObjStart state = iota ObjOpen ObjProperty ObjComma // Property states PropertyStart PropertyKey PropertyColon PropertyValue // Array states ArrayStart ArrayOpen ArrayValue ArrayComma // String states StringStart StringQuoteOrChar Escape // Number states NumberStart NumberMinus NumberZero NumberDigit NumberPoint NumberDigitFraction NumberExp NumberExpDigitOrSign )
pkg/ast/ast.go
0.71423
0.508971
ast.go
starcoder
package cdn import ( "encoding/json" ) // CustconfDynamicContent The dynamic content caching policy allows you to specify a set of query string and/or HTTP header key/value pairs that should create a unique cache entry for a given URL. This policy is useful when your origin returns unique content for the same URL based on a set of query string parameters provided in the request. type CustconfDynamicContent struct { // This is used by the API to perform conflict checking Id *string `json:"id,omitempty"` // String of values delimited by a ',' character. A comma separated list of query string parameters you want to include in the cache key generation. NOTE: This list is ignored when the Key Location is set to header. QueryParams *string `json:"queryParams,omitempty"` // String of values delimited by a ',' character. A comma-separated list of glob patterns that represent HTTP request headers you want included in the cache key generation. Via the use of a colon ':', users can define each glob pattern to match a header name only, or the pattern can be used to match both the header name and value. A pattern without a colon ':' is treated as a header name ONLY match. If the pattern matches the header, then all values are used as a part of the cache key. If the pattern contains a colon, the CDN uses the pattern on the left of the colon to match the header. The pattern to the right of the colon is used to match the value. The CDN only uses the header/value as a part of the cache key if both patterns result in a match. Note, no pattern after a colon indicates an empty header (no value). See the fnmatch manpage for acceptable glob patterns. HeaderFields *string `json:"headerFields,omitempty"` Enabled *bool `json:"enabled,omitempty"` // String of values delimited by a ',' character. MethodFilter *string `json:"methodFilter,omitempty"` // String of values delimited by a ',' character. PathFilter *string `json:"pathFilter,omitempty"` // String of values delimited by a ',' character. HeaderFilter *string `json:"headerFilter,omitempty"` } // NewCustconfDynamicContent instantiates a new CustconfDynamicContent 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 NewCustconfDynamicContent() *CustconfDynamicContent { this := CustconfDynamicContent{} return &this } // NewCustconfDynamicContentWithDefaults instantiates a new CustconfDynamicContent 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 NewCustconfDynamicContentWithDefaults() *CustconfDynamicContent { this := CustconfDynamicContent{} return &this } // GetId returns the Id field value if set, zero value otherwise. func (o *CustconfDynamicContent) GetId() string { if o == nil || o.Id == nil { var ret string return ret } return *o.Id } // GetIdOk returns a tuple with the Id field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CustconfDynamicContent) GetIdOk() (*string, bool) { if o == nil || o.Id == nil { return nil, false } return o.Id, true } // HasId returns a boolean if a field has been set. func (o *CustconfDynamicContent) HasId() bool { if o != nil && o.Id != nil { return true } return false } // SetId gets a reference to the given string and assigns it to the Id field. func (o *CustconfDynamicContent) SetId(v string) { o.Id = &v } // GetQueryParams returns the QueryParams field value if set, zero value otherwise. func (o *CustconfDynamicContent) GetQueryParams() string { if o == nil || o.QueryParams == nil { var ret string return ret } return *o.QueryParams } // GetQueryParamsOk returns a tuple with the QueryParams field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CustconfDynamicContent) GetQueryParamsOk() (*string, bool) { if o == nil || o.QueryParams == nil { return nil, false } return o.QueryParams, true } // HasQueryParams returns a boolean if a field has been set. func (o *CustconfDynamicContent) HasQueryParams() bool { if o != nil && o.QueryParams != nil { return true } return false } // SetQueryParams gets a reference to the given string and assigns it to the QueryParams field. func (o *CustconfDynamicContent) SetQueryParams(v string) { o.QueryParams = &v } // GetHeaderFields returns the HeaderFields field value if set, zero value otherwise. func (o *CustconfDynamicContent) GetHeaderFields() string { if o == nil || o.HeaderFields == nil { var ret string return ret } return *o.HeaderFields } // GetHeaderFieldsOk returns a tuple with the HeaderFields field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CustconfDynamicContent) GetHeaderFieldsOk() (*string, bool) { if o == nil || o.HeaderFields == nil { return nil, false } return o.HeaderFields, true } // HasHeaderFields returns a boolean if a field has been set. func (o *CustconfDynamicContent) HasHeaderFields() bool { if o != nil && o.HeaderFields != nil { return true } return false } // SetHeaderFields gets a reference to the given string and assigns it to the HeaderFields field. func (o *CustconfDynamicContent) SetHeaderFields(v string) { o.HeaderFields = &v } // GetEnabled returns the Enabled field value if set, zero value otherwise. func (o *CustconfDynamicContent) GetEnabled() bool { if o == nil || o.Enabled == nil { var ret bool return ret } return *o.Enabled } // GetEnabledOk returns a tuple with the Enabled field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CustconfDynamicContent) GetEnabledOk() (*bool, bool) { if o == nil || o.Enabled == nil { return nil, false } return o.Enabled, true } // HasEnabled returns a boolean if a field has been set. func (o *CustconfDynamicContent) HasEnabled() bool { if o != nil && o.Enabled != nil { return true } return false } // SetEnabled gets a reference to the given bool and assigns it to the Enabled field. func (o *CustconfDynamicContent) SetEnabled(v bool) { o.Enabled = &v } // GetMethodFilter returns the MethodFilter field value if set, zero value otherwise. func (o *CustconfDynamicContent) GetMethodFilter() string { if o == nil || o.MethodFilter == nil { var ret string return ret } return *o.MethodFilter } // GetMethodFilterOk returns a tuple with the MethodFilter field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CustconfDynamicContent) GetMethodFilterOk() (*string, bool) { if o == nil || o.MethodFilter == nil { return nil, false } return o.MethodFilter, true } // HasMethodFilter returns a boolean if a field has been set. func (o *CustconfDynamicContent) HasMethodFilter() bool { if o != nil && o.MethodFilter != nil { return true } return false } // SetMethodFilter gets a reference to the given string and assigns it to the MethodFilter field. func (o *CustconfDynamicContent) SetMethodFilter(v string) { o.MethodFilter = &v } // GetPathFilter returns the PathFilter field value if set, zero value otherwise. func (o *CustconfDynamicContent) GetPathFilter() string { if o == nil || o.PathFilter == nil { var ret string return ret } return *o.PathFilter } // GetPathFilterOk returns a tuple with the PathFilter field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CustconfDynamicContent) GetPathFilterOk() (*string, bool) { if o == nil || o.PathFilter == nil { return nil, false } return o.PathFilter, true } // HasPathFilter returns a boolean if a field has been set. func (o *CustconfDynamicContent) HasPathFilter() bool { if o != nil && o.PathFilter != nil { return true } return false } // SetPathFilter gets a reference to the given string and assigns it to the PathFilter field. func (o *CustconfDynamicContent) SetPathFilter(v string) { o.PathFilter = &v } // GetHeaderFilter returns the HeaderFilter field value if set, zero value otherwise. func (o *CustconfDynamicContent) GetHeaderFilter() string { if o == nil || o.HeaderFilter == nil { var ret string return ret } return *o.HeaderFilter } // GetHeaderFilterOk returns a tuple with the HeaderFilter field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CustconfDynamicContent) GetHeaderFilterOk() (*string, bool) { if o == nil || o.HeaderFilter == nil { return nil, false } return o.HeaderFilter, true } // HasHeaderFilter returns a boolean if a field has been set. func (o *CustconfDynamicContent) HasHeaderFilter() bool { if o != nil && o.HeaderFilter != nil { return true } return false } // SetHeaderFilter gets a reference to the given string and assigns it to the HeaderFilter field. func (o *CustconfDynamicContent) SetHeaderFilter(v string) { o.HeaderFilter = &v } func (o CustconfDynamicContent) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Id != nil { toSerialize["id"] = o.Id } if o.QueryParams != nil { toSerialize["queryParams"] = o.QueryParams } if o.HeaderFields != nil { toSerialize["headerFields"] = o.HeaderFields } if o.Enabled != nil { toSerialize["enabled"] = o.Enabled } if o.MethodFilter != nil { toSerialize["methodFilter"] = o.MethodFilter } if o.PathFilter != nil { toSerialize["pathFilter"] = o.PathFilter } if o.HeaderFilter != nil { toSerialize["headerFilter"] = o.HeaderFilter } return json.Marshal(toSerialize) } type NullableCustconfDynamicContent struct { value *CustconfDynamicContent isSet bool } func (v NullableCustconfDynamicContent) Get() *CustconfDynamicContent { return v.value } func (v *NullableCustconfDynamicContent) Set(val *CustconfDynamicContent) { v.value = val v.isSet = true } func (v NullableCustconfDynamicContent) IsSet() bool { return v.isSet } func (v *NullableCustconfDynamicContent) Unset() { v.value = nil v.isSet = false } func NewNullableCustconfDynamicContent(val *CustconfDynamicContent) *NullableCustconfDynamicContent { return &NullableCustconfDynamicContent{value: val, isSet: true} } func (v NullableCustconfDynamicContent) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCustconfDynamicContent) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
pkg/cdn/model_custconf_dynamic_content.go
0.841272
0.428951
model_custconf_dynamic_content.go
starcoder
package square // Represents a line item in an order. Each line item describes a different product to purchase, with its own quantity and price details. type OrderLineItem struct { // Unique ID that identifies the line item only within this order. Uid string `json:"uid,omitempty"` // The name of the line item. Name string `json:"name,omitempty"` // The quantity purchased, formatted as a decimal number. For example: `\"3\"`. Line items with a quantity of `\"0\"` will be automatically removed upon paying for or otherwise completing the order. Line items with a `quantity_unit` can have non-integer quantities. For example: `\"1.70000\"`. Quantity string `json:"quantity"` QuantityUnit *OrderQuantityUnit `json:"quantity_unit,omitempty"` // The note of the line item. Note string `json:"note,omitempty"` // The `CatalogItemVariation` id applied to this line item. CatalogObjectId string `json:"catalog_object_id,omitempty"` // The name of the variation applied to this line item. VariationName string `json:"variation_name,omitempty"` // Application-defined data attached to this line item. Metadata fields are intended to store descriptive references or associations with an entity in another system or store brief information about the object. Square does not process this field; it only stores and returns it in relevant API calls. Do not use metadata to store any sensitive information (personally identifiable information, card details, etc.). Keys written by applications must be 60 characters or less and must be in the character set `[a-zA-Z0-9_-]`. Entries may also include metadata generated by Square. These keys are prefixed with a namespace, separated from the key with a ':' character. Values have a max length of 255 characters. An application may have up to 10 entries per metadata field. Entries written by applications are private and can only be read or modified by the same application. See [Metadata](https://developer.squareup.com/docs/build-basics/metadata) for more information. Metadata map[string]string `json:"metadata,omitempty"` // The `CatalogModifier`s applied to this line item. Modifiers []OrderLineItemModifier `json:"modifiers,omitempty"` // The list of references to taxes applied to this line item. Each `OrderLineItemAppliedTax` has a `tax_uid` that references the `uid` of a top-level `OrderLineItemTax` applied to the line item. On reads, the amount applied is populated. An `OrderLineItemAppliedTax` will be automatically created on every line item for all `ORDER` scoped taxes added to the order. `OrderLineItemAppliedTax` records for `LINE_ITEM` scoped taxes must be added in requests for the tax to apply to any line items. To change the amount of a tax, modify the referenced top-level tax. AppliedTaxes []OrderLineItemAppliedTax `json:"applied_taxes,omitempty"` // The list of references to discounts applied to this line item. Each `OrderLineItemAppliedDiscount` has a `discount_uid` that references the `uid` of a top-level `OrderLineItemDiscounts` applied to the line item. On reads, the amount applied is populated. An `OrderLineItemAppliedDiscount` will be automatically created on every line item for all `ORDER` scoped discounts that are added to the order. `OrderLineItemAppliedDiscount` records for `LINE_ITEM` scoped discounts must be added in requests for the discount to apply to any line items. To change the amount of a discount, modify the referenced top-level discount. AppliedDiscounts []OrderLineItemAppliedDiscount `json:"applied_discounts,omitempty"` BasePriceMoney *Money `json:"base_price_money,omitempty"` VariationTotalPriceMoney *Money `json:"variation_total_price_money,omitempty"` GrossSalesMoney *Money `json:"gross_sales_money,omitempty"` TotalTaxMoney *Money `json:"total_tax_money,omitempty"` TotalDiscountMoney *Money `json:"total_discount_money,omitempty"` TotalMoney *Money `json:"total_money,omitempty"` PricingBlocklists *OrderLineItemPricingBlocklists `json:"pricing_blocklists,omitempty"` }
square/model_order_line_item.go
0.907235
0.464841
model_order_line_item.go
starcoder
// Package atomic provides simple wrappers around numerics to enforce atomic // access. package atomic import ( "encoding/json" "math" "strconv" "sync/atomic" "time" ) // Bool is an atomic Boolean. type Bool struct { nocmp // disallow non-atomic comparison v uint32 } // NewBool creates a Bool. func NewBool(initial bool) *Bool { return &Bool{v: boolToInt(initial)} } // Load atomically loads the Boolean. func (b *Bool) Load() bool { return truthy(atomic.LoadUint32(&b.v)) } // CAS is an atomic compare-and-swap. func (b *Bool) CAS(old, new bool) bool { return atomic.CompareAndSwapUint32(&b.v, boolToInt(old), boolToInt(new)) } // Store atomically stores the passed value. func (b *Bool) Store(new bool) { atomic.StoreUint32(&b.v, boolToInt(new)) } // Swap sets the given value and returns the previous value. func (b *Bool) Swap(new bool) bool { return truthy(atomic.SwapUint32(&b.v, boolToInt(new))) } // Toggle atomically negates the Boolean and returns the previous value. func (b *Bool) Toggle() bool { for { old := b.Load() if b.CAS(old, !old) { return old } } } func truthy(n uint32) bool { return n == 1 } func boolToInt(b bool) uint32 { if b { return 1 } return 0 } // MarshalJSON encodes the wrapped bool into JSON. func (b *Bool) MarshalJSON() ([]byte, error) { return json.Marshal(b.Load()) } // UnmarshalJSON decodes JSON into the wrapped bool. func (b *Bool) UnmarshalJSON(t []byte) error { var v bool if err := json.Unmarshal(t, &v); err != nil { return err } b.Store(v) return nil } // String encodes the wrapped value as a string. func (b *Bool) String() string { return strconv.FormatBool(b.Load()) } // Float64 is an atomic wrapper around float64. type Float64 struct { nocmp // disallow non-atomic comparison v uint64 } // NewFloat64 creates a Float64. func NewFloat64(f float64) *Float64 { return &Float64{v: math.Float64bits(f)} } // Load atomically loads the wrapped value. func (f *Float64) Load() float64 { return math.Float64frombits(atomic.LoadUint64(&f.v)) } // Store atomically stores the passed value. func (f *Float64) Store(s float64) { atomic.StoreUint64(&f.v, math.Float64bits(s)) } // Add atomically adds to the wrapped float64 and returns the new value. func (f *Float64) Add(s float64) float64 { for { old := f.Load() new := old + s if f.CAS(old, new) { return new } } } // Sub atomically subtracts from the wrapped float64 and returns the new value. func (f *Float64) Sub(s float64) float64 { return f.Add(-s) } // CAS is an atomic compare-and-swap. func (f *Float64) CAS(old, new float64) bool { return atomic.CompareAndSwapUint64(&f.v, math.Float64bits(old), math.Float64bits(new)) } // MarshalJSON encodes the wrapped float64 into JSON. func (f *Float64) MarshalJSON() ([]byte, error) { return json.Marshal(f.Load()) } // UnmarshalJSON decodes JSON into the wrapped float64. func (f *Float64) UnmarshalJSON(b []byte) error { var v float64 if err := json.Unmarshal(b, &v); err != nil { return err } f.Store(v) return nil } // String encodes the wrapped value as a string. func (f *Float64) String() string { // 'g' is the behavior for floats with %v. return strconv.FormatFloat(f.Load(), 'g', -1, 64) } // Duration is an atomic wrapper around time.Duration // https://godoc.org/time#Duration type Duration struct { nocmp // disallow non-atomic comparison v Int64 } // NewDuration creates a Duration. func NewDuration(d time.Duration) *Duration { return &Duration{v: *NewInt64(int64(d))} } // Load atomically loads the wrapped value. func (d *Duration) Load() time.Duration { return time.Duration(d.v.Load()) } // Store atomically stores the passed value. func (d *Duration) Store(n time.Duration) { d.v.Store(int64(n)) } // Add atomically adds to the wrapped time.Duration and returns the new value. func (d *Duration) Add(n time.Duration) time.Duration { return time.Duration(d.v.Add(int64(n))) } // Sub atomically subtracts from the wrapped time.Duration and returns the new value. func (d *Duration) Sub(n time.Duration) time.Duration { return time.Duration(d.v.Sub(int64(n))) } // Swap atomically swaps the wrapped time.Duration and returns the old value. func (d *Duration) Swap(n time.Duration) time.Duration { return time.Duration(d.v.Swap(int64(n))) } // CAS is an atomic compare-and-swap. func (d *Duration) CAS(old, new time.Duration) bool { return d.v.CAS(int64(old), int64(new)) } // MarshalJSON encodes the wrapped time.Duration into JSON. func (d *Duration) MarshalJSON() ([]byte, error) { return json.Marshal(d.Load()) } // UnmarshalJSON decodes JSON into the wrapped time.Duration. func (d *Duration) UnmarshalJSON(b []byte) error { var v time.Duration if err := json.Unmarshal(b, &v); err != nil { return err } d.Store(v) return nil } // String encodes the wrapped value as a string. func (d *Duration) String() string { return d.Load().String() } // Value shadows the type of the same name from sync/atomic // https://godoc.org/sync/atomic#Value type Value struct { nocmp // disallow non-atomic comparison atomic.Value }
vendor/go.uber.org/atomic/atomic.go
0.830078
0.499878
atomic.go
starcoder
package common const ( // LabelAnnotationPrefix is the prefix of every labels and annotations added by the controller. LabelAnnotationPrefix = "fluid.io/" // The format is fluid.io/s-{runtime_type}-{data_set_name}, s means storage LabelAnnotationStorageCapacityPrefix = LabelAnnotationPrefix + "s-" // The dataset annotation LabelAnnotationDataset = LabelAnnotationPrefix + "dataset" // LabelAnnotationDatasetNum indicates the number of the dataset in specific node LabelAnnotationDatasetNum = LabelAnnotationPrefix + "dataset-num" // fluid adminssion webhook inject flag EnableFluidInjectionFlag = LabelAnnotationPrefix + "enable-injection" ) type OperationType string const ( // AddLabel means adding a new label on the specific node. AddLabel OperationType = "Add" // DeleteLabel means deleting the label of the specific node. DeleteLabel OperationType = "Delete" // UpdateLabel means updating the label value of the specific node. UpdateLabel OperationType = "UpdateValue" ) // LabelToModify modifies the labelKey in operationType. type LabelToModify struct { labelKey string labelValue string operationType OperationType } func (labelToModify *LabelToModify) GetLabelKey() string { return labelToModify.labelKey } func (labelToModify *LabelToModify) GetLabelValue() string { return labelToModify.labelValue } func (labelToModify *LabelToModify) GetOperationType() OperationType { return labelToModify.operationType } type LabelsToModify struct { labels []LabelToModify } func (labels *LabelsToModify) GetLabels() []LabelToModify { return labels.labels } func (labels *LabelsToModify) operator(labelKey string, labelValue string, operationType OperationType) { newLabelToModify := LabelToModify{ labelKey: labelKey, operationType: operationType, } if operationType != DeleteLabel { newLabelToModify.labelValue = labelValue } labels.labels = append(labels.labels, newLabelToModify) } func (labels *LabelsToModify) Add(labelKey string, labelValue string) { labels.operator(labelKey, labelValue, AddLabel) } func (labels *LabelsToModify) Update(labelKey string, labelValue string) { labels.operator(labelKey, labelValue, UpdateLabel) } func (labels *LabelsToModify) Delete(labelKey string) { labels.operator(labelKey, "", DeleteLabel) } func GetDatasetNumLabelName() string { return LabelAnnotationDatasetNum } // Check if the key has the expected value func CheckExpectValue(m map[string]string, key string, targetValue string) bool { if len(m) == 0 { return false } if v, ok := m[key]; ok { return v == targetValue } return false }
pkg/common/label.go
0.73848
0.433862
label.go
starcoder
package light import ( "github.com/austingebauer/go-ray-tracer/color" "github.com/austingebauer/go-ray-tracer/material" "github.com/austingebauer/go-ray-tracer/point" "github.com/austingebauer/go-ray-tracer/vector" "math" ) // Lighting computes the shading for a material given the light source, point being illuminated, // eye and normal vectors, and shadow flag using the Phong reflection model. func Lighting(mat *material.Material, light *PointLight, pt *point.Point, eyeVec, normalVec *vector.Vector, inShadow bool) *color.Color { // The three reflection contributions to get the // final shading are ambient, diffuse, and specular. // Combine the surface color with the light's color/intensity effectiveColor := color.Multiply(mat.Color, light.Intensity) // Compute the ambient contribution ambient := color.Scale(*effectiveColor, mat.Ambient) // If the point is in a shadow, use only the ambient contribution. if inShadow { return ambient } // Get the vector from the point to the light source lightVec := vector.Normalize(*point.Subtract(light.Position, *pt)) // lightDotNormal represents the cosine of the angle between the // light vector and the normal vector. lightDotNormal := vector.DotProduct(*lightVec, *normalVec) // A negative number means the light is on the other side of the surface // and only ambient light is present if lightDotNormal < 0 { return ambient } // Compute the diffuse contribution diffuse := color.Scale(*color.Scale(*effectiveColor, mat.Diffuse), lightDotNormal) // reflectDotEye represents the cosine of the angle between the // reflection vector and the eye vector. reflectVec := vector.Reflect(*vector.Scale(*lightVec, -1), *normalVec) reflectDotEye := vector.DotProduct(*reflectVec, *eyeVec) // Compute the specular contribution specular := color.NewColor(0, 0, 0) // A positive number means that the light reflects into the eye. // A zero or negative number means the light reflects away from (not into) the eye. if reflectDotEye > 0 { factor := math.Pow(reflectDotEye, mat.Shininess) specular = color.Scale(*color.Scale(light.Intensity, mat.Specular), factor) } return color.Add(*color.Add(*ambient, *diffuse), *specular) }
light/lighting.go
0.879509
0.441673
lighting.go
starcoder
package go2linq import ( "sort" "sync" ) // Reimplementing LINQ to Objects: Part 17 – Except // https://codeblog.jonskeet.uk/2010/12/30/reimplementing-linq-to-objects-part-17-except/ // https://docs.microsoft.com/dotnet/api/system.linq.enumerable.except // Except produces the set difference of two sequences using reflect.DeepEqual to compare values. // 'second' is enumerated immediately. // 'first' and 'second' must not be based on the same Enumerator, otherwise use ExceptSelf instead. func Except[Source any](first, second Enumerator[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } return ExceptEq(first, second, nil) } // ExceptMust is like Except but panics in case of error. func ExceptMust[Source any](first, second Enumerator[Source]) Enumerator[Source] { r, err := Except(first, second) if err != nil { panic(err) } return r } // ExceptSelf produces the set difference of two sequences using reflect.DeepEqual to compare values. // 'second' is enumerated immediately. // 'first' and 'second' may be based on the same Enumerator, // 'first' must have real Reset method. func ExceptSelf[Source any](first, second Enumerator[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } sl2 := Slice(second) first.Reset() return Except(first, NewOnSliceEn(sl2...)) } // ExceptSelfMust is like ExceptSelf but panics in case of error. func ExceptSelfMust[Source any](first, second Enumerator[Source]) Enumerator[Source] { r, err := ExceptSelf(first, second) if err != nil { panic(err) } return r } // ExceptEq produces the set difference of two sequences using the specified Equaler to compare values. // If 'equaler' is nil reflect.DeepEqual is used. // 'second' is enumerated immediately. // Order of elements in the result corresponds to the order of elements in 'first'. // 'first' and 'second' must not be based on the same Enumerator, otherwise use ExceptEqSelf instead. func ExceptEq[Source any](first, second Enumerator[Source], equaler Equaler[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } if equaler == nil { equaler = EqualerFunc[Source](DeepEqual[Source]) } var once sync.Once var dsl2 []Source d1 := DistinctEqMust(first, equaler) var c Source return OnFunc[Source]{ mvNxt: func() bool { once.Do(func() { dsl2 = Slice(DistinctEqMust(second, equaler)) }) for d1.MoveNext() { c = d1.Current() if !elInElelEq(c, dsl2, equaler) { return true } } return false }, crrnt: func() Source { return c }, rst: func() { d1.Reset() }, }, nil } // ExceptEqMust is like ExceptEq but panics in case of error. func ExceptEqMust[Source any](first, second Enumerator[Source], equaler Equaler[Source]) Enumerator[Source] { r, err := ExceptEq(first, second, equaler) if err != nil { panic(err) } return r } // ExceptEqSelf produces the set difference of two sequences using the specified Equaler to compare values. // If 'equaler' is nil reflect.DeepEqual is used. // 'second' is enumerated immediately. // Order of elements in the result corresponds to the order of elements in 'first'. // 'first' and 'second' may be based on the same Enumerator. // 'first' must have real Reset method. func ExceptEqSelf[Source any](first, second Enumerator[Source], equaler Equaler[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } sl2 := Slice(second) first.Reset() return ExceptEq(first, NewOnSliceEn(sl2...), equaler) } // ExceptEqSelfMust is like ExceptEqSelf but panics in case of error. func ExceptEqSelfMust[Source any](first, second Enumerator[Source], equaler Equaler[Source]) Enumerator[Source] { r, err := ExceptEqSelf(first, second, equaler) if err != nil { panic(err) } return r } // ExceptCmp produces the set difference of two sequences using the specified Comparer to compare values. // (See DistinctCmp function.) // 'second' is enumerated immediately. // Order of elements in the result corresponds to the order of elements in 'first'. // 'first' and 'second' must not be based on the same Enumerator, otherwise use ExceptCmpSelf instead. func ExceptCmp[Source any](first, second Enumerator[Source], comparer Comparer[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } if comparer == nil { return nil, ErrNilComparer } var once sync.Once var dsl2 []Source d1 := DistinctCmpMust(first, comparer) var c Source return OnFunc[Source]{ mvNxt: func() bool { once.Do(func() { dsl2 = Slice(DistinctCmpMust(second, comparer)) sort.Slice(dsl2, func(i, j int) bool { return comparer.Compare(dsl2[i], dsl2[j]) < 0 }) }) for d1.MoveNext() { c = d1.Current() if !elInElelCmp(c, dsl2, comparer) { return true } } return false }, crrnt: func() Source { return c }, rst: func() { d1.Reset() }, }, nil } // ExceptCmpMust is like ExceptCmp but panics in case of error. func ExceptCmpMust[Source any](first, second Enumerator[Source], comparer Comparer[Source]) Enumerator[Source] { r, err := ExceptCmp(first, second, comparer) if err != nil { panic(err) } return r } // ExceptCmpSelf produces the set difference of two sequences using the specified Comparer to compare values. // (See DistinctCmp function.) // 'second' is enumerated immediately. // Order of elements in the result corresponds to the order of elements in 'first'. // 'first' and 'second' may be based on the same Enumerator. // 'first' must have real Reset method. func ExceptCmpSelf[Source any](first, second Enumerator[Source], comparer Comparer[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } if comparer == nil { return nil, ErrNilComparer } sl2 := Slice(second) first.Reset() return ExceptCmp(first, NewOnSliceEn(sl2...), comparer) } // ExceptCmpSelfMust is like ExceptCmpSelf but panics in case of error. func ExceptCmpSelfMust[Source any](first, second Enumerator[Source], comparer Comparer[Source]) Enumerator[Source] { r, err := ExceptCmpSelf(first, second, comparer) if err != nil { panic(err) } return r }
except.go
0.734215
0.444866
except.go
starcoder
package graphics // A Rectanglef contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. // It is well-formed if Min.X <= Max.X and likewise for Y. Pointfs are always // well-formed. A rectangle's methods always return well-formed outputs for // well-formed inputs. type Rectanglef struct { Min, Max Pointf } // String returns a string representation of r like "(3,4)-(6,5)". func (r Rectanglef) String() string { return r.Min.String() + "-" + r.Max.String() } // Dx returns r's width. func (r Rectanglef) Dx() float32 { return r.Max.X - r.Min.X } // Dy returns r's height. func (r Rectanglef) Dy() float32 { return r.Max.Y - r.Min.Y } // Size returns r's width and height. func (r Rectanglef) Size() Pointf { return Pointf{ r.Max.X - r.Min.X, r.Max.Y - r.Min.Y, } } // Add returns the rectangle r translated by p. func (r Rectanglef) Add(p Pointf) Rectanglef { return Rectanglef{ Pointf{r.Min.X + p.X, r.Min.Y + p.Y}, Pointf{r.Max.X + p.X, r.Max.Y + p.Y}, } } // Sub returns the rectangle r translated by -p. func (r Rectanglef) Sub(p Pointf) Rectanglef { return Rectanglef{ Pointf{r.Min.X - p.X, r.Min.Y - p.Y}, Pointf{r.Max.X - p.X, r.Max.Y - p.Y}, } } // Intersect returns the largest rectangle contained by both r and s. If the // two rectangles do not overlap then the zero rectangle will be returned. func (r Rectanglef) Intersect(s Rectanglef) Rectanglef { if r.Min.X < s.Min.X { r.Min.X = s.Min.X } if r.Min.Y < s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X > s.Max.X { r.Max.X = s.Max.X } if r.Max.Y > s.Max.Y { r.Max.Y = s.Max.Y } if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y { return ZR } return r } // Union returns the smallest rectangle that contains both r and s. func (r Rectanglef) Union(s Rectanglef) Rectanglef { if r.Min.X > s.Min.X { r.Min.X = s.Min.X } if r.Min.Y > s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X < s.Max.X { r.Max.X = s.Max.X } if r.Max.Y < s.Max.Y { r.Max.Y = s.Max.Y } return r } // Empty reports whether the rectangle contains no points. func (r Rectanglef) Empty() bool { return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y } // Eq reports whether r and s are equal. func (r Rectanglef) Eq(s Rectanglef) bool { return r.Min.X == s.Min.X && r.Min.Y == s.Min.Y && r.Max.X == s.Max.X && r.Max.Y == s.Max.Y } // Overlaps reports whether r and s have a non-empty intersection. func (r Rectanglef) Overlaps(s Rectanglef) bool { return r.Min.X < s.Max.X && s.Min.X < r.Max.X && r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y } // In reports whether every point in r is in s. func (r Rectanglef) In(s Rectanglef) bool { if r.Empty() { return true } // Note that r.Max is an exclusive bound for r, so that r.In(s) // does not require that r.Max.In(s). return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X && s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y } // Canon returns the canonical version of r. The returned rectangle has minimum // and maximum coordinates swapped if necessary so that it is well-formed. func (r Rectanglef) Canon() Rectanglef { if r.Max.X < r.Min.X { r.Min.X, r.Max.X = r.Max.X, r.Min.X } if r.Max.Y < r.Min.Y { r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y } return r } // ZR is the zero Rectanglef. var ZR Rectanglef // Rect is shorthand for Rectanglef{Pt(x0, y0), Pt(x1, y1)}. func Rect(x0, y0, x1, y1 float32) Rectanglef { if x0 > x1 { x0, x1 = x1, x0 } if y0 > y1 { y0, y1 = y1, y0 } return Rectanglef{Pointf{x0, y0}, Pointf{x1, y1}} }
graphics/rectanglef.go
0.923773
0.561455
rectanglef.go
starcoder
package membufio import ( "errors" "io" ) var ErrEmptyData = errors.New("empty data") var ErrRange = errors.New("index out of range") // This package implements an IO interface to perform stream operations on a byte slice type ByteSliceIO struct { Buffer []byte Index int64 BufferLength int64 } // New creates a new ByteSliceIO instance pointed at the passed byte slice func New(p []byte) ByteSliceIO { var out ByteSliceIO out.Open(p) return out } // Make creates a new ByteSliceIO and allocates a memory buffer of the requested size func Make(bufsize uint64) ByteSliceIO { p := make([]byte, bufsize) var out ByteSliceIO out.Open(p) return out } // Open points the ByteSliceIO instance at a new byte slice. It does not take ownership of the data. func (bs *ByteSliceIO) Open(p []byte) error { targetLength := int64(len(p)) if targetLength == 0 { return ErrEmptyData } bs.Buffer = p bs.BufferLength = targetLength bs.Index = 0 return nil } // Close detaches from the specified byte slice and returns to an uninitialized state func (bs *ByteSliceIO) Close() { bs.Buffer = nil bs.BufferLength = 0 bs.Index = 0 } func (bs *ByteSliceIO) IsEOF() bool { return bs.Index >= bs.BufferLength } // Read copies data from the source buffer into another byte slice from the current file position. // It returns ErrEmptyData if given a target with no capacity (zero length or nil). func (bs *ByteSliceIO) Read(p []byte) (int, error) { bytesRead, err := bs.ReadAt(p, bs.Index) if err == nil { bs.Index += int64(bytesRead) if bs.Index > bs.BufferLength { bs.Index = bs.BufferLength return bytesRead, errors.New("EOF") } } return bytesRead, err } // ReadAt copies data from the source buffer into another byte slice from the specified offset. // It returns ErrEmptyData if given a target with no capacity (zero length or nil). func (bs *ByteSliceIO) ReadAt(p []byte, offset int64) (int, error) { targetLength := int64(len(p)) if targetLength == 0 { return 0, ErrEmptyData } bytesToRead := bs.BufferLength - offset if bytesToRead <= 0 { return 0, errors.New("EOF") } if bytesToRead > targetLength { bytesToRead = targetLength } bytesRead := copy(p, bs.Buffer[offset:offset+bytesToRead]) return bytesRead, nil } // ReadByte reads a byte from the source buffer and returns it. func (bs *ByteSliceIO) ReadByte() (byte, error) { if bs.Index >= bs.BufferLength { return 0, io.EOF } out := bs.Buffer[bs.Index] bs.Index++ return out, nil } // Write copies data from the ByteSliceIO instance into another byte slice from the current file // position. It returns ErrEmptyData if given a target with no capacity (zero length or nil). func (bs *ByteSliceIO) Write(p []byte) (int, error) { bytesWritten, err := bs.WriteAt(p, bs.Index) if err == nil { bs.Index += int64(bytesWritten) if bs.Index > bs.BufferLength { bs.Index = bs.BufferLength } } return bytesWritten, err } // Write copies data from the ByteSliceIO instance into another byte slice from the specified // offset. It returns ErrEmptyData if given a target with no capacity (zero length or nil). func (bs *ByteSliceIO) WriteAt(p []byte, offset int64) (int, error) { sourceLength := int64(len(p)) if len(p) == 0 { return 0, ErrEmptyData } bytesToWrite := bs.BufferLength - offset if bytesToWrite <= 0 { return 0, nil } if bytesToWrite > sourceLength { bytesToWrite = sourceLength } bytesWritten := copy(bs.Buffer[offset:offset+bytesToWrite], p[:bytesToWrite]) return bytesWritten, nil } // WriteByte writes a byte to the source buffer. func (bs *ByteSliceIO) WriteByte(value byte) error { if bs.Index >= bs.BufferLength { return io.EOF } bs.Buffer[bs.Index] = value bs.Index++ return nil } // Seek jumps to the specified offset relative to the `whence` specifier, which can be io.SeekStart, // io.SeekEnd, or io.SeekCurrent. func (bs *ByteSliceIO) Seek(offset int64, whence int) (int64, error) { var start int64 switch whence { case io.SeekStart: break case io.SeekEnd: start = bs.BufferLength offset *= -1 case io.SeekCurrent: start = bs.Index default: return 0, errors.New("invalid whence value") } if start+offset < 0 { return 0, ErrRange } bs.Index = start + offset if bs.Index >= bs.BufferLength { return bs.Index, errors.New("EOF") } return bs.Index, nil }
membufio/membufio.go
0.809728
0.45175
membufio.go
starcoder
package internal import ( "fmt" "math" "reflect" "strconv" "github.com/lyraproj/dgo/util" "github.com/lyraproj/dgo/dgo" ) type ( // floatVal is a float64 that implements the dgo.Value interface floatVal float64 defaultFloatType int exactFloatType struct { exactType value floatVal } floatType struct { min float64 max float64 inclusive bool } ) // DefaultFloatType is the unconstrained floatVal type const DefaultFloatType = defaultFloatType(0) var reflectFloatType = reflect.TypeOf(float64(0)) // FloatType returns a dgo.FloatType that is limited to the inclusive range given by min and max // If inclusive is true, then the range has an inclusive end. func FloatType(min, max float64, inclusive bool) dgo.FloatType { if min == max { if !inclusive { panic(fmt.Errorf(`non inclusive range cannot have equal min and max`)) } return floatVal(min).Type().(dgo.FloatType) } if max < min { t := max max = min min = t } if min == -math.MaxFloat64 && max == math.MaxFloat64 { return DefaultFloatType } return &floatType{min: min, max: max, inclusive: inclusive} } func (t *floatType) Assignable(other dgo.Type) bool { switch ot := other.(type) { case *exactFloatType: return t.IsInstance(float64(ot.value)) case *floatType: if t.min > ot.min { return false } if t.inclusive || t.inclusive == ot.inclusive { return t.max >= ot.max } return t.max > ot.max } return CheckAssignableTo(nil, other, t) } func (t *floatType) Equals(other interface{}) bool { if ot, ok := other.(*floatType); ok { return *t == *ot } return false } func (t *floatType) HashCode() int { h := int(dgo.TiFloatRange) if t.min > 0 { h = h*31 + int(t.min) } if t.max < math.MaxInt64 { h = h*31 + int(t.max) } if t.inclusive { h *= 3 } return h } func (t *floatType) Instance(value interface{}) bool { f, ok := ToFloat(value) return ok && t.IsInstance(f) } func (t *floatType) IsInstance(value float64) bool { if t.min <= value { if t.inclusive { return value <= t.max } return value < t.max } return false } func (t *floatType) Max() float64 { return t.max } func (t *floatType) Inclusive() bool { return t.inclusive } func (t *floatType) Min() float64 { return t.min } func (t *floatType) New(arg dgo.Value) dgo.Value { return newFloat(t, arg) } func (t *floatType) String() string { return TypeString(t) } func (t *floatType) ReflectType() reflect.Type { return reflectFloatType } func (t *floatType) Type() dgo.Type { return &metaType{t} } func (t *floatType) TypeIdentifier() dgo.TypeIdentifier { return dgo.TiFloatRange } func (t *exactFloatType) Generic() dgo.Type { return DefaultFloatType } func (t *exactFloatType) Inclusive() bool { return true } func (t *exactFloatType) IsInstance(value float64) bool { return float64(t.value) == value } func (t *exactFloatType) Max() float64 { return float64(t.value) } func (t *exactFloatType) Min() float64 { return float64(t.value) } func (t *exactFloatType) New(arg dgo.Value) dgo.Value { return newFloat(t, arg) } func (t *exactFloatType) ReflectType() reflect.Type { return reflectFloatType } func (t *exactFloatType) TypeIdentifier() dgo.TypeIdentifier { return dgo.TiFloatExact } func (t *exactFloatType) ExactValue() dgo.Value { return t.value } func (t defaultFloatType) Assignable(other dgo.Type) bool { switch other.(type) { case defaultFloatType, *exactFloatType, *floatType: return true } return false } func (t defaultFloatType) Equals(other interface{}) bool { _, ok := other.(defaultFloatType) return ok } func (t defaultFloatType) HashCode() int { return int(dgo.TiFloat) } func (t defaultFloatType) Inclusive() bool { return true } func (t defaultFloatType) Instance(value interface{}) bool { _, ok := ToFloat(value) return ok } func (t defaultFloatType) IsInstance(value float64) bool { return true } func (t defaultFloatType) Max() float64 { return math.MaxFloat64 } func (t defaultFloatType) Min() float64 { return -math.MaxFloat64 } func (t defaultFloatType) New(arg dgo.Value) dgo.Value { return newFloat(t, arg) } func (t defaultFloatType) ReflectType() reflect.Type { return reflectFloatType } func (t defaultFloatType) String() string { return TypeString(t) } func (t defaultFloatType) Type() dgo.Type { return &metaType{t} } func (t defaultFloatType) TypeIdentifier() dgo.TypeIdentifier { return dgo.TiFloat } // Float returns the dgo.Float for the given float64 func Float(f float64) dgo.Float { return floatVal(f) } func (v floatVal) Type() dgo.Type { et := &exactFloatType{value: v} et.ExactType = et return et } func (v floatVal) CompareTo(other interface{}) (int, bool) { r := 0 if ov, isFloat := ToFloat(other); isFloat { fv := float64(v) switch { case fv > ov: r = 1 case fv < ov: r = -1 } return r, true } if oi, isInt := ToInt(other); isInt { fv := float64(v) ov := float64(oi) switch { case fv > ov: r = 1 case fv < ov: r = -1 } return r, true } if other == Nil || other == nil { return 1, true } return 0, false } func (v floatVal) Equals(other interface{}) bool { f, ok := ToFloat(other) return ok && float64(v) == f } func (v floatVal) GoFloat() float64 { return float64(v) } func (v floatVal) HashCode() int { return int(v) } func (v floatVal) ReflectTo(value reflect.Value) { switch value.Kind() { case reflect.Interface: value.Set(reflect.ValueOf(float64(v))) case reflect.Ptr: if value.Type().Elem().Kind() == reflect.Float32 { gv := float32(v) value.Set(reflect.ValueOf(&gv)) } else { gv := float64(v) value.Set(reflect.ValueOf(&gv)) } default: value.SetFloat(float64(v)) } } func (v floatVal) String() string { return util.Ftoa(float64(v)) } func (v floatVal) ToFloat() float64 { return float64(v) } func (v floatVal) ToInt() int64 { return int64(v) } // ToFloat returns the given value as a float64 if, and only if, the value is a float32 or float64. An // additional boolean is returned to indicate if that was the case or not. func ToFloat(value interface{}) (v float64, ok bool) { ok = true switch value := value.(type) { case floatVal: v = float64(value) case float64: v = value case float32: v = float64(value) default: ok = false } return } func newFloat(t dgo.Type, arg dgo.Value) (f dgo.Float) { if args, ok := arg.(dgo.Arguments); ok { args.AssertSize(`float`, 1, 1) arg = args.Get(0) } f = Float(floatFromConvertible(arg)) if !t.Instance(f) { panic(IllegalAssignment(t, f)) } return f } func floatFromConvertible(from dgo.Value) float64 { switch from := from.(type) { case dgo.Float: return from.GoFloat() case dgo.Integer: return float64(from.GoInt()) case *timeVal: return from.SecondsWithFraction() case dgo.Boolean: if from.GoBool() { return 1 } return 0 case dgo.String: if i, err := strconv.ParseFloat(from.GoString(), 64); err == nil { return i } } panic(fmt.Errorf(`the value '%s' cannot be converted to a float`, from)) }
internal/float.go
0.804367
0.554169
float.go
starcoder
package api import ( "strings" "github.com/pkg/errors" ) // PostReactionType represents a post reaction type type PostReactionType int const ( // Celebration represents a reaction emotion Celebration PostReactionType = iota // Love represents a reaction emotion Love // Anger represents a reaction emotion Anger // Approval represents a reaction emotion Approval // Confusion represents a reaction emotion Confusion // Fear represents a reaction emotion Fear // Thinking represents a reaction emotion Thinking // Dislike represents a reaction emotion Dislike // Cry represents a reaction emotion Cry // Shock represents a reaction emotion Shock ) // String stringifies the value func (rt PostReactionType) String() string { switch rt { case Celebration: return "celebration" case Love: return "love" case Anger: return "anger" case Approval: return "approval" case Confusion: return "confusion" case Fear: return "fear" case Thinking: return "thinking" case Dislike: return "dislike" case Cry: return "cry" case Shock: return "shock" } panic(errors.Errorf("Invalid PostReactionType value: %d", int(rt))) } // Utf8Symbol returns the UTF8 symbol corresponding to the reaction func (rt PostReactionType) Utf8Symbol() rune { switch rt { case Celebration: return '🎉' case Love: return '😍' case Anger: return '😡' case Approval: return '👍' case Confusion: return '😕' case Fear: return '😱' case Thinking: return '💭' case Dislike: return '👎' case Cry: return '😭' case Shock: return '😲' } return '🎁' } // FromString parses the value from a string func (rt *PostReactionType) FromString(str string) error { switch strings.ToLower(str) { case "celebration": *rt = Celebration case "love": *rt = Love case "anger": *rt = Anger case "approval": *rt = Approval case "confusion": *rt = Confusion case "fear": *rt = Fear case "thinking": *rt = Thinking case "dislike": *rt = Dislike case "cry": *rt = Cry case "shock": *rt = Shock default: return errors.Errorf( "invalid string representation of the PostReactionType type: %s", str, ) } return nil }
server/apisrv/api/postReactionType.go
0.684791
0.451568
postReactionType.go
starcoder
package array // Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. // Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. // https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/727/ func removeDuplicates(nums []int) int { var length int for _, v := range nums { if length == 0 || v != nums[length-1] { nums[length] = v length++ } } return length } // Given an array of integers, every element appears twice except for one. Find that single one. // Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory ? // https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/549/ func singleNumber(nums []int) int { m := make(map[int]struct{}) for _, v := range nums { if _, ok := m[v]; !ok { m[v] = struct{}{} } else { delete(m, v) } } for k := range m { return k } return 0 } // Given an array of integers, find if the array contains any duplicates. // Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. // https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/578/ func containsDuplicate(nums []int) bool { m := make(map[int]struct{}) for _, v := range nums { if _, ok := m[v]; !ok { m[v] = struct{}{} } else { return true } } return false } // Given an array of integers, return indices of the two numbers such that they add up to a specific target. // You may assume that each input would have exactly one solution, and you may not use the same element twice. // https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/546/ func twoSum(nums []int, target int) []int { m := make(map[int]int) for i, k := range nums { if v, ok := m[k]; !ok { m[target-k] = i } else { return []int{v, i} } } return nil }
algorithms/interview/array/easy.go
0.853943
0.44734
easy.go
starcoder
package chunk import ( "bytes" "crypto/sha256" "errors" "image" "io" "dennis-tra/image-stego/pkg/bit" "github.com/cbergoon/merkletree" "github.com/icza/bitio" ) // Chunk is a wrapper around an image.RGBA struct that keeps track of // the read and written bytes to the least significant bits of the underlying *image.RGBA. type Chunk struct { *image.RGBA // The number of read bytes. Subsequent calls to read will continue where the last read left off. rOff int // The number of written bytes. Subsequent calls to write will continue where the last write left off. wOff int } // MaxPayloadSize returns the maximum number of bytes that can be written to this chunk func (c *Chunk) MaxPayloadSize() int { return c.LSBCount() / 8 } // Width is a short hand to return the width in pixels of the chunk func (c *Chunk) Width() int { return c.Bounds().Dx() } // Height is a short hand to return the height in pixels of the chunk func (c *Chunk) Height() int { return c.Bounds().Dy() } // PixelCount returns the total number of pixels func (c *Chunk) PixelCount() int { return len(c.Pix) / 4 } // LSBCount returns the total number of least significant bits (LSB) available for encoding a message. // Currently only the RGB values are considered not the A. func (c *Chunk) LSBCount() int { return c.PixelCount() * BitsPerPixel } // MinX in this context returns the starting value for iterating over the horizontal axis of the image func (c *Chunk) MinX() int { return c.Bounds().Min.X } // MaxX in this context returns the ending value for iterating over the horizontal axis of the image func (c *Chunk) MaxX() int { return c.Bounds().Max.X } // MinY in this context returns the starting value for iterating over the vertical axis of the image func (c *Chunk) MinY() int { return c.Bounds().Min.Y } // MaxY in this context returns the ending value for iterating over the vertical axis of the image func (c *Chunk) MaxY() int { return c.Bounds().Max.Y } // CalculateHash calculates the SHA256 hash of the 7 most significant bits. The least // significant bit (LSB) is not considered in the hash generation as it is used to // store the (derived) Merkle leaves/nodes. // Note: From an implementation point of view the LSB is actually considered but // always overwritten by a 0. // This method (among Equal) lets Chunk conform to the merkletree.Content interface. func (c *Chunk) CalculateHash() ([]byte, error) { h := sha256.New() for x := c.MinX(); x < c.MaxX(); x++ { for y := c.MinY(); y < c.MaxY(); y++ { rgba := c.RGBAAt(x, y) byt := []byte{ bit.WithLSB(rgba.R, false), bit.WithLSB(rgba.G, false), bit.WithLSB(rgba.B, false), } if _, err := h.Write(byt); err != nil { return nil, err } } } return h.Sum(nil), nil } // Write writes the given bytes to the least significant bits of the chunk. // It returns the number of bytes written from p and an error if one occurred. // Consult the io.Writer documentation for the intended behaviour of this function. // A byte from p is either written completely or not at all to the least significant bits. // Subsequent calls to write will continue were the last write left off. func (c *Chunk) Write(p []byte) (n int, err error) { r := bitio.NewReader(bytes.NewBuffer(p)) defer func() { c.wOff += n }() for i := 0; i < len(p); i++ { bitOff := (c.wOff + i) * BitsPerByte // Stop early if there is not enough LSB space left if bitOff+7 >= len(c.Pix)-len(c.Pix)/4 { return n, io.EOF } // At this point we're sure that a whole byte can still be written for j := 0; j < BitsPerByte; j++ { bitVal, err := r.ReadBool() if err != nil { return n, err } idx := bitOff + j + (bitOff+j)/BitsPerPixel c.Pix[idx] = bit.WithLSB(c.Pix[idx], bitVal) } // As one byte was written increment the counter n += 1 } return n, nil } // Read reads the amount of bytes given in p from the LSBs of the image chunk. // It returns the number of bytes read from the least significant bits and an error if one occurred. // p will contain the contents from the least significant bits after the call has finished. func (c *Chunk) Read(p []byte) (n int, err error) { b := bytes.NewBuffer(p) w := bitio.NewWriter(b) b.Reset() defer func() { w.Close() c.rOff += n }() for i := 0; i < len(p); i++ { // calculate current read bit offset: static read offset from potential last run plus idx-var times bits in a byte bitOff := (c.rOff + i) * BitsPerByte // Stop early if there are not enough LSBs left if bitOff+BitsPerByte+(bitOff+BitsPerByte)/BitsPerPixel > len(c.Pix) { return n, io.EOF } // At this point we're sure that a whole byte can still be read for j := 0; j < BitsPerByte; j++ { idx := bitOff + j + (bitOff+j)/BitsPerPixel v := bit.GetLSB(c.Pix[idx]) err := w.WriteBool(v) if err != nil { return n, err } } // As one whole byte was read increment the counter n += 1 } return n, err } // Equals tests for equality of two Contents. It only considers the 7 most significant bits since the last bit contains // the hash data of the other chunks and doesn't count to the equality. func (c *Chunk) Equals(o merkletree.Content) (bool, error) { oc, ok := o.(*Chunk) // other chunk if !ok { return false, errors.New("invalid type casting") } if oc.Width() != c.Width() || oc.Height() != c.Height() { return false, nil } for x := c.MinX(); x < c.MaxX(); x++ { for y := c.MinY(); y < c.MaxY(); y++ { thisColor := c.RGBAAt(x, y) otherColor := oc.RGBAAt(x, y) if bit.WithLSB(thisColor.R, false) != bit.WithLSB(otherColor.R, false) { return false, nil } if bit.WithLSB(thisColor.G, false) != bit.WithLSB(otherColor.G, false) { return false, nil } if bit.WithLSB(thisColor.B, false) != bit.WithLSB(otherColor.B, false) { return false, nil } if bit.WithLSB(thisColor.A, false) != bit.WithLSB(otherColor.A, false) { return false, nil } } } return true, nil }
internal/chunk/chunk.go
0.765243
0.481759
chunk.go
starcoder
package circle import ( "github.com/gravestench/pho/geom" "github.com/gravestench/pho/geom/point" "github.com/gravestench/pho/geom/rectangle" ) // New creates a new circle func New(x, y, radius float64) *Circle { c := &Circle{ Type: geom.Circle, } return c.SetPosition(x, y).SetRadius(radius) } type Circle struct { Type geom.ShapeType X, Y float64 radius, diameter float64 } // Area returns the circle area func (c *Circle) Area() float64 { return Area(c) } // Radius returns the circle radius func (c *Circle) Radius() float64 { return c.radius } // SetRadius returns the circle radius, which also updates the diameter func (c *Circle) SetRadius(r float64) *Circle { c.radius = r c.diameter = r * 2 return c } // Diameter returns the circle diameter func (c *Circle) Diameter() float64 { return c.diameter } // SetDiameter sets the circle diameter, which also updates the radius func (c *Circle) SetDiameter(d float64) *Circle { c.diameter = d c.radius = d / 2 return c } // Left returns the left position of the circle func (c *Circle) Left() float64 { return c.X - c.radius } // SetLeft sets the left position of the circle, which also sets the x coordinate func (c *Circle) SetLeft(value float64) *Circle { c.X = value + c.radius return c } func (c *Circle) Right() float64 { return c.X + c.radius } func (c *Circle) SetRight(value float64) *Circle { c.X = value - c.radius return c } func (c *Circle) Top() float64 { return c.Y - c.radius } func (c *Circle) SetTop(value float64) *Circle { c.Y = value + c.radius return c } func (c *Circle) Bottom() float64 { return c.Y + c.radius } func (c *Circle) SetBottom(value float64) *Circle { c.Y = value - c.radius return c } // Contains checks to see if the Circle contains the given x / y coordinates. func (c *Circle) Contains(x, y float64) bool { return Contains(c, x, y) } // ContainsPoint checks to see if the Circle contains the given point. func (c *Circle) ContainsPoint(p *point.Point) bool { return ContainsPoint(c, p) } // ContainsRectangle checks to see if the Circle contains the given rectangle. func (c *Circle) ContainsRectangle(r *rectangle.Rectangle) bool { return ContainsRectangle(c, r) } // GetPoint returns a Point object containing the coordinates of a point on the circumference of // the Circle based on the given angle normalized to the range 0 to 1. I.e. a value of 0.5 will give // the point at 180 degrees around the circle. func (c *Circle) GetPoint(position float64, point *point.Point) *point.Point { return GetPoint(c, position, point) } // GetPoints Returns an array of Point objects containing the coordinates of the points around the // circumference of the Circle, based on the given quantity or stepRate values. func (c *Circle) GetPoints(quantity int, stepRate float64, points []*point.Point) []*point.Point { return GetPoints(c, quantity, stepRate, points) } // Circumference returns the circumference of the given Circle. func (c *Circle) Circumference() float64 { return Circumference(c) } // GetRandomPoint returns a uniformly distributed random point from anywhere within the given Circle func (c *Circle) GetRandomPoint(p *point.Point) *point.Point { return GetRandomPoint(c, p) } // SetTo sets the x, y and radius of this circle. func (c *Circle) SetTo(x, y, radius float64) *Circle { c.X, c.Y, c.radius = x, y, radius c.diameter = 2 * radius return c } // SetEmpty sets this Circle to be empty with a radius of zero. func (c *Circle) SetEmpty() *Circle { c.radius = 0 c.diameter = 0 return c } // SetPosition sets the position of this circle func (c *Circle) SetPosition(x, y float64) *Circle { c.X, c.Y = x, y return c } // IsEmpty checks to see if the Circle is empty: has a radius of zero. func (c *Circle) IsEmpty() bool { return c.radius <= 0 } // Clone returns a clone of this circle func (c *Circle) Clone() *Circle { return Clone(c) } // Copy the given circle x, y, and radius to this circle. func (c *Circle) Copy(from *Circle) *Circle { return CopyFrom(c, from) } // Equals compares the `x`, `y` and `radius` properties of this circle with the other circle. // Returns `true` if they all match, otherwise returns `false`. func (c *Circle) Equals(other *Circle) bool { return Equals(c, other) } // GetBounds returns the bounds (a rectangle) of the Circle object. func (c *Circle) GetBounds(assignTo *rectangle.Rectangle) *rectangle.Rectangle { return GetBounds(c, assignTo) } // Offset the circle position by the given x, y func (c *Circle) Offset(x, y float64) *Circle { return Offset(c, x, y) } // OffsetPoint offsets the circle with the x,y of the given point func (c *Circle) OffsetPoint(p *point.Point) *Circle { return Offset(c, p.X, p.Y) }
geom/circle/circle.go
0.944842
0.692843
circle.go
starcoder
package ast import ( "fmt" "go/token" "strconv" "github.com/dave/dst" ) // AssignDSL translates to a dst.AssignStmt type AssignDSL struct{ Obj *dst.AssignStmt } // Assign creates a new AssignDSL func Assign(lhs ...dst.Expr) AssignDSL { return AssignDSL{Obj: &dst.AssignStmt{Lhs: lhs}} } // Tok specifies the token used in an assignment func (d AssignDSL) Tok(tok token.Token) AssignDSL { d.Obj.Tok = tok return d } // Rhs specifies the right-hand expressions in the assignment func (d AssignDSL) Rhs(rhs ...dst.Expr) AssignDSL { d.Obj.Rhs = append(d.Obj.Rhs, rhs...) return d } // Decs adds decorations to an AssignDSL func (d AssignDSL) Decs(decs dst.AssignStmtDecorations) AssignDSL { d.Obj.Decs = decs return d } // AssignDecsDSL translates to a dst.AssignStmtDecorations type AssignDecsDSL struct{ Obj dst.AssignStmtDecorations } // AssignDecs creates a new AssignDecsDSL func AssignDecs(before dst.SpaceType) AssignDecsDSL { return AssignDecsDSL{Obj: dst.AssignStmtDecorations{ NodeDecs: dst.NodeDecs{Before: before}, }} } // After adds whitespace after an assign statement func (d AssignDecsDSL) After(after dst.SpaceType) AssignDecsDSL { d.Obj.After = after return d } // BinDSL translates to a dst.BinaryExpr type BinDSL struct{ Obj *dst.BinaryExpr } // Bin creates a new BinDSL func Bin(x dst.Expr) BinDSL { return BinDSL{Obj: &dst.BinaryExpr{X: x}} } // Op specifies the operator func (d BinDSL) Op(op token.Token) BinDSL { d.Obj.Op = op return d } // Y specifies the right side expression func (d BinDSL) Y(y dst.Expr) BinDSL { d.Obj.Y = y return d } // BlockDSL translates to a dst.BlockStmt type BlockDSL struct{ Obj *dst.BlockStmt } // Block creates a new BlockDSL for a list of statements func Block(list ...dst.Stmt) BlockDSL { return BlockDSL{Obj: &dst.BlockStmt{List: list}} } // Break creates a break dst.BranchStmt func Break() *dst.BranchStmt { return &dst.BranchStmt{Tok: token.BREAK} } // CallDSL translates to a dst.CallExpr type CallDSL struct{ Obj *dst.CallExpr } // Call creates a new CallDSL func Call(fun dst.Expr) CallDSL { return CallDSL{Obj: &dst.CallExpr{Fun: fun}} } // Args specifies the arguments to a call func (d CallDSL) Args(args ...dst.Expr) CallDSL { d.Obj.Args = args return d } // Ellipsis specifies if the last argument is variadic func (d CallDSL) Ellipsis(ellipsis bool) CallDSL { d.Obj.Ellipsis = ellipsis return d } // CompDSL translates to a dst.CompositeLit type CompDSL struct{ Obj *dst.CompositeLit } // Comp creates a new CompDSL func Comp(typ dst.Expr) CompDSL { return CompDSL{Obj: &dst.CompositeLit{Type: typ}} } // Elts defines the elements of a CompDSL func (d CompDSL) Elts(elts ...dst.Expr) CompDSL { d.Obj.Elts = elts return d } // Decs adds decorations to a CompDSL func (d CompDSL) Decs(decs dst.CompositeLitDecorations) CompDSL { d.Obj.Decs = decs return d } // Continue creates a continue dst.BranchStmt func Continue() *dst.BranchStmt { return &dst.BranchStmt{Tok: token.CONTINUE} } // Ellipsis translates an expression to a dst.Ellipsis func Ellipsis(elt dst.Expr) *dst.Ellipsis { return &dst.Ellipsis{Elt: elt} } // ExprDSL translates to a dst.ExprStmt type ExprDSL struct{ Obj *dst.ExprStmt } // Expr returns a new ExprDSL func Expr(x dst.Expr) ExprDSL { return ExprDSL{Obj: &dst.ExprStmt{X: x}} } // Decs adds decorations to a ExprDSL func (d ExprDSL) Decs(decs dst.ExprStmtDecorations) ExprDSL { d.Obj.Decs = decs return d } // ExprDecsDSL translates to a dst.ExprStmtDecorations type ExprDecsDSL struct{ Obj dst.ExprStmtDecorations } // ExprDecs creates a new ExprDecsDSL func ExprDecs(after dst.SpaceType) ExprDecsDSL { return ExprDecsDSL{Obj: dst.ExprStmtDecorations{ NodeDecs: dst.NodeDecs{After: after}, }} } // FieldDSL translates to a dst.Field type FieldDSL struct{ Obj *dst.Field } // Field creates a new FieldDSL func Field(typ dst.Expr) FieldDSL { return FieldDSL{Obj: &dst.Field{Type: typ}} } // Names sets the names of a field func (d FieldDSL) Names(names ...*dst.Ident) FieldDSL { d.Obj.Names = names return d } // FieldList translates to a dst.FieldList func FieldList(fields ...*dst.Field) *dst.FieldList { return &dst.FieldList{List: fields} } // FuncDSL translates to a dst.GenDecl containing a function type type FuncDSL struct{ Obj *dst.FuncDecl } // Fn creates a new FuncDSL func Fn(name string) FuncDSL { return FuncDSL{Obj: &dst.FuncDecl{Name: Id(name), Type: &dst.FuncType{}}} } // Recv specifies the receiver for a function func (d FuncDSL) Recv(fields ...*dst.Field) FuncDSL { d.Obj.Recv = FieldList(fields...) return d } // ParamList specifies a parameter FieldList for a function func (d FuncDSL) ParamList(fieldList *dst.FieldList) FuncDSL { d.Obj.Type.Params = fieldList return d } // Params specifies parameters for a function func (d FuncDSL) Params(fields ...*dst.Field) FuncDSL { d.Obj.Type.Params = FieldList(fields...) return d } // ResultList specifies a result FieldList for a function func (d FuncDSL) ResultList(fieldList *dst.FieldList) FuncDSL { d.Obj.Type.Results = fieldList return d } // Results specifies results for a function func (d FuncDSL) Results(fields ...*dst.Field) FuncDSL { d.Obj.Type.Results = FieldList(fields...) return d } // Body specifies the body for a function func (d FuncDSL) Body(list ...dst.Stmt) FuncDSL { d.Obj.Body = Block(list...).Obj return d } // Decs adds decorations to a FuncDSL func (d FuncDSL) Decs(decs dst.FuncDeclDecorations) FuncDSL { d.Obj.Decs = decs return d } // FuncTypeDSL translates to a dst.FuncType type FuncTypeDSL struct { Obj *dst.FuncType } // FuncType creates a new FuncTypeDSL func FuncType(fieldList *dst.FieldList) FuncTypeDSL { return FuncTypeDSL{Obj: &dst.FuncType{Params: fieldList}} } // ResultList specifies a dst.FieldList for a func type's results func (d FuncTypeDSL) ResultList(fieldList *dst.FieldList) FuncTypeDSL { d.Obj.Results = fieldList return d } // FnLitDSL translates to a dst.FuncLit type FnLitDSL struct{ Obj *dst.FuncLit } // FnLit creates a new FnLitDSL func FnLit(typ *dst.FuncType) FnLitDSL { return FnLitDSL{Obj: &dst.FuncLit{Type: typ}} } // Body specifies a body func (d FnLitDSL) Body(list ...dst.Stmt) FnLitDSL { d.Obj.Body = Block(list...).Obj return d } // FnTypeDSL translates to a dst.FuncType type FnTypeDSL struct{ Obj *dst.FuncType } // FnType creates a new FnTypeDSL func FnType(paramFieldList *dst.FieldList) FnTypeDSL { return FnTypeDSL{Obj: &dst.FuncType{Params: paramFieldList}} } // Results adds a result field list func (d FnTypeDSL) Results(resultFieldList *dst.FieldList) FnTypeDSL { d.Obj.Results = resultFieldList return d } // ForDSL translatesto a dst.ForStmt type ForDSL struct{ Obj *dst.ForStmt } // For returns a new ForDSL func For(init dst.Stmt) ForDSL { return ForDSL{Obj: &dst.ForStmt{Init: init}} } // Cond specifies the condition of a for statement func (d ForDSL) Cond(cond dst.Expr) ForDSL { d.Obj.Cond = cond return d } // Post specifies the post statement of a for statement func (d ForDSL) Post(post dst.Stmt) ForDSL { d.Obj.Post = post return d } // Body defines the body of a for statement func (d ForDSL) Body(list ...dst.Stmt) ForDSL { d.Obj.Body = Block(list...).Obj return d } // Id returns a named dst.Ident func Id(name string) *dst.Ident { return dst.NewIdent(name) } // Idf returns a formatted dst.Ident func Idf(format string, a ...interface{}) *dst.Ident { return Id(fmt.Sprintf(format, a...)) } // IdPath returns a dst.Ident with a name and path func IdPath(name, path string) *dst.Ident { return &dst.Ident{Name: name, Path: path} } // IncStmt creates a dst.IncDecStmt for incrementing an expression func IncStmt(x dst.Expr) *dst.IncDecStmt { return &dst.IncDecStmt{X: x, Tok: token.INC} } // IndexDSL translates to a dst.IndexExpr type IndexDSL struct{ Obj *dst.IndexExpr } // Index creates a new IndexDSL func Index(x dst.Expr) IndexDSL { return IndexDSL{Obj: &dst.IndexExpr{X: x}} } // Sub specifies the sub-expression func (d IndexDSL) Sub(index dst.Expr) IndexDSL { d.Obj.Index = index return d } // IfDSL translates to a dst.IfStmt type IfDSL struct{ Obj *dst.IfStmt } // IfInit creates a new If with an initialization statement func IfInit(init dst.Stmt) IfDSL { return IfDSL{Obj: &dst.IfStmt{Init: init}} } // If creates a new If func If(cond dst.Expr) IfDSL { return IfDSL{Obj: &dst.IfStmt{Cond: cond}} } // Cond set the condition of the If func (d IfDSL) Cond(cond dst.Expr) IfDSL { d.Obj.Cond = cond return d } // Body specifies the body of the If func (d IfDSL) Body(list ...dst.Stmt) IfDSL { d.Obj.Body = Block(list...).Obj return d } // Decs adds decorations to a IfDSL func (d IfDSL) Decs(decs dst.IfStmtDecorations) IfDSL { d.Obj.Decs = decs return d } // IfDecsDSL translates to a dst.IfStmtDecorations type IfDecsDSL struct{ Obj dst.IfStmtDecorations } // IfDecs creates a new IfDecsDSL func IfDecs(after dst.SpaceType) IfDecsDSL { return IfDecsDSL{Obj: dst.IfStmtDecorations{ NodeDecs: dst.NodeDecs{After: after}, }} } // KeyValueDSL translates to a dst.KeyValueExpr type KeyValueDSL struct{ Obj *dst.KeyValueExpr } // Key creates a new KeyValueDSL func Key(key dst.Expr) KeyValueDSL { return KeyValueDSL{Obj: &dst.KeyValueExpr{Key: key}} } // Value specifies the value func (d KeyValueDSL) Value(value dst.Expr) KeyValueDSL { d.Obj.Value = value return d } // Decs adds decorations to a KeyValueDSL func (d KeyValueDSL) Decs(decs dst.KeyValueExprDecorations) KeyValueDSL { d.Obj.Decs = decs return d } // KeyValueDecsDSL translates to a dst.KeyValueExprDecorations type KeyValueDecsDSL struct{ Obj dst.KeyValueExprDecorations } // KeyValueDecs creates a new KeyValueDecsDSL func KeyValueDecs(before dst.SpaceType) KeyValueDecsDSL { return KeyValueDecsDSL{Obj: dst.KeyValueExprDecorations{ NodeDecs: dst.NodeDecs{Before: before}, }} } // After adds decorations after the KeyValueDSL func (d KeyValueDecsDSL) After(after dst.SpaceType) KeyValueDecsDSL { d.Obj.After = after return d } // LitInt returns a dst.BasicLit with a literal int value func LitInt(value int) *dst.BasicLit { return &dst.BasicLit{Kind: token.INT, Value: strconv.Itoa(value)} } // LitString returns a dst.BasicLit with a literal string value func LitString(value string) *dst.BasicLit { return &dst.BasicLit{Kind: token.STRING, Value: "\"" + value + "\""} } // LitStringf returns a formatted dst.BasicLit with a literal string value func LitStringf(format string, a ...interface{}) *dst.BasicLit { return &dst.BasicLit{ Kind: token.STRING, Value: fmt.Sprintf("\""+format+"\"", a...), } } // MapTypeDSL translates to a dst.MapType type MapTypeDSL struct{ Obj *dst.MapType } // MapType returns a new MapTypeDSL func MapType(key dst.Expr) MapTypeDSL { return MapTypeDSL{Obj: &dst.MapType{Key: key}} } // Value specifies the value expression of a dst.MapType func (d MapTypeDSL) Value(value dst.Expr) MapTypeDSL { d.Obj.Value = value return d } // Paren translates to a dst.ParenExpr func Paren(x dst.Expr) *dst.ParenExpr { return &dst.ParenExpr{X: x} } // RangeDSL translates to a dst.RangeStmt type RangeDSL struct{ Obj *dst.RangeStmt } // Range returns a new RangeDSL func Range(x dst.Expr) RangeDSL { return RangeDSL{Obj: &dst.RangeStmt{X: x}} } // Key sets the key of a range statement func (d RangeDSL) Key(key dst.Expr) RangeDSL { d.Obj.Key = key return d } // Value sets the value of a range statement func (d RangeDSL) Value(value dst.Expr) RangeDSL { d.Obj.Value = value return d } // Tok sets the token of a range statement func (d RangeDSL) Tok(tok token.Token) RangeDSL { d.Obj.Tok = tok return d } // Body defines the body of a range statement func (d RangeDSL) Body(list ...dst.Stmt) RangeDSL { d.Obj.Body = Block(list...).Obj return d } // Return returns a dst.ReturnStmt func Return(results ...dst.Expr) *dst.ReturnStmt { return &dst.ReturnStmt{Results: results} } // SelDSL translates to a dst.SelectorExpr type SelDSL struct{ Obj *dst.SelectorExpr } // Sel creates a new SelDSL func Sel(x dst.Expr) SelDSL { return SelDSL{Obj: &dst.SelectorExpr{X: x}} } // Dot specifies what is selected func (d SelDSL) Dot(sel *dst.Ident) SelDSL { d.Obj.Sel = sel return d } // SliceExprDSL translates to a dst.SliceExpr type SliceExprDSL struct{ Obj *dst.SliceExpr } // SliceExpr creates a new slice expression func SliceExpr(x dst.Expr) SliceExprDSL { return SliceExprDSL{Obj: &dst.SliceExpr{X: x}} } // Low specifies the low expression of a slice expression func (d SliceExprDSL) Low(low dst.Expr) SliceExprDSL { d.Obj.Low = low return d } // High specifies the high expression of a slice expression func (d SliceExprDSL) High(high dst.Expr) SliceExprDSL { d.Obj.High = high return d } // SliceType returns a dst.ArrayType representing a slice func SliceType(elt dst.Expr) *dst.ArrayType { return &dst.ArrayType{Elt: elt} } // Star returns a dst.StarExpr func Star(x dst.Expr) *dst.StarExpr { return &dst.StarExpr{X: x} } // StructDSL translates to a dst.StructType type StructDSL struct { Obj *dst.StructType } // Struct returns a dst.StructType func Struct(fields ...*dst.Field) *dst.StructType { return StructFromList(FieldList(fields...)) } // StructFromList returns a dst.StructType given a dst.FieldList func StructFromList(fieldList *dst.FieldList) *dst.StructType { if fieldList == nil { fieldList = emptyFieldList() } return &dst.StructType{Fields: fieldList} } // TypeSpecDSL translates to a dst.TypeSpec type TypeSpecDSL struct { Obj *dst.TypeSpec } // TypeSpec creates a new TypeSpecDSL func TypeSpec(name string) TypeSpecDSL { return TypeSpecDSL{Obj: &dst.TypeSpec{Name: Id(name)}} } func (d TypeSpecDSL) Type(typ dst.Expr) TypeSpecDSL { d.Obj.Type = typ return d } // TypeDeclDSL translates to various types into a dst.GenDecl type TypeDeclDSL struct { Obj *dst.GenDecl } // TypeDecl creates a new TypeDeclDSL func TypeDecl(typeSpec *dst.TypeSpec) TypeDeclDSL { return TypeDeclDSL{ Obj: &dst.GenDecl{ Tok: token.TYPE, Specs: []dst.Spec{typeSpec}, }, } } // Decs adds decorations to a TypeDeclDSL func (d TypeDeclDSL) Decs(decs dst.GenDeclDecorations) TypeDeclDSL { d.Obj.Decs = decs return d } // Un returns a dst.UnaryExpr func Un(op token.Token, x dst.Expr) *dst.UnaryExpr { return &dst.UnaryExpr{Op: op, X: x} } // ValueDSL translates to a dst.ValueSpec type ValueDSL struct{ Obj *dst.ValueSpec } // Value creates a new ValueDSL func Value(typ dst.Expr) ValueDSL { return ValueDSL{Obj: &dst.ValueSpec{Type: typ}} } // Names sets the names of a value func (d ValueDSL) Names(names ...*dst.Ident) ValueDSL { d.Obj.Names = names return d } // Var returns a var dst.DeclStmt func Var(specs ...dst.Spec) *dst.DeclStmt { return &dst.DeclStmt{Decl: &dst.GenDecl{ Tok: token.VAR, Specs: specs, }} } // emptyFieldList returns an empty field list (renders as `struct {}` with no // new lines) func emptyFieldList() *dst.FieldList { return &dst.FieldList{ Opening: true, Closing: true, } }
ast/dsl.go
0.758242
0.439747
dsl.go
starcoder
package geo import ( "fmt" "math" ) type Cell struct { X float64 // Cell center X Y float64 // Cell center Y H float64 // Half cell size D float64 // Distance from cell center to polygon Max float64 // max distance to polygon within a cell } func NewCell(x float64, y float64, h float64, p Polygon) *Cell { var d float64 = pointToPolygonDist(x, y, p) return &Cell{ x, y, h, d, d + h*math.Sqrt2, } } func pointToPolygonDist(x float64, y float64, p Polygon) float64 { inside := false minDistSq := math.MaxFloat64 for k := 0; k < len(p.Rings); k++ { ring := p.Rings[k] for i, length, j := 0, len(ring), len(ring)-1; i < length; i, j = i+1, i { a := ring[i] b := ring[j] if ((a.Y() > y) != (b.Y() > y)) && (x < (b.X()-a.X())*(y-a.Y())/(b.Y()-a.Y())+a.X()) { inside = !inside } minDistSq = math.Min(minDistSq, getSegDistSq(x, y, a, b)) } } if inside { return math.Sqrt(minDistSq) } else { return -1 * math.Sqrt(minDistSq) } } func getSegDistSq(px float64, py float64, a Point, b Point) float64 { var x = a.X() var y = a.Y() var dx = b.X() - x var dy = b.Y() - y if (dx != 0) || (dy != 0) { var t = ((px-x)*dx + (py-y)*dy) / (dx*dx + dy*dy) if t > 1 { x = b[0] y = b[1] } else if t > 0 { x += dx * t y += dy * t } } dx = px - x dy = py - y return dx*dx + dy*dy } func getCentroidCell(polygon Polygon) *Cell { var area = 0.0 var x = 0.0 var y = 0.0 var points = polygon.Rings[0] for i, length, j := 0, len(points), len(points)-1; i < length; i, j = i+1, i { var a = points[i] var b = points[j] var f = a.X()*b.Y() - b.X()*a.Y() x += (a.X() + b.X()) * f y += (a.Y() + b.Y()) * f area += f * 3 } if area == 0 { return NewCell(points[0].X(), points[0].Y(), 0, polygon) } else { return NewCell(x/area, y/area, 0, polygon) } } func Polylabel(polygon Polygon, precision float64, debug bool) Point { minX, minY, maxX, maxY := math.MaxFloat64, math.MaxFloat64, -math.MaxFloat64, -math.MaxFloat64 for i := 0; i < len(polygon.Rings[0]); i++ { var p = polygon.Rings[0][i] minX = math.Min(minX, p.X()) minY = math.Min(minY, p.Y()) maxX = math.Max(maxX, p.X()) maxY = math.Max(maxY, p.Y()) } var width = maxX - minX var height = maxY - minY var cellSize = math.Min(width, height) var h = cellSize / 2 cellQueue := NewPriorityQueue() if cellSize == 0 { return Point{minX, minY} } for x := minX; x < maxX; x += cellSize { for y := minY; y < maxY; y += cellSize { cell := NewCell(x+h, y+h, h, polygon) cellQueue.Insert(*cell, cell.Max) } } bestCell := getCentroidCell(polygon) var bboxCell = NewCell(minX+width/2, minY+height/2, 0, polygon) if bboxCell.D > bestCell.D { bestCell = bboxCell } numProbes := cellQueue.Len() for cellQueue.Len() != 0 { cellInterface, _ := cellQueue.Pop() cell := cellInterface.(Cell) // update the best cell if we found a better one if cell.D > bestCell.D { bestCell = &cell } // do not drill down further if there's no chance of a better solution if cell.Max-bestCell.D <= precision { continue } // split the cell into four cells h = cell.H / 2 cells := []*Cell{ NewCell(cell.X-h, cell.Y-h, h, polygon), NewCell(cell.X+h, cell.Y-h, h, polygon), NewCell(cell.X-h, cell.Y+h, h, polygon), NewCell(cell.X+h, cell.Y+h, h, polygon), } for _, ncell := range cells { cellQueue.Insert(*ncell, ncell.Max) } numProbes += 4 } if debug { fmt.Sprintf("%d, num probes: ", numProbes) } return Point{bestCell.X, bestCell.Y} }
geo/polylabel.go
0.728169
0.562417
polylabel.go
starcoder
package types import ( "context" "fmt" "reflect" "github.com/google/gapid/core/data/pod" "github.com/google/gapid/core/log" "github.com/google/gapid/core/math/sint" "github.com/google/gapid/core/os/device" "github.com/google/gapid/gapis/memory" ) type typeData struct { tp *Type rt reflect.Type } var type_map = make(map[uint64]*typeData) func AddType(i uint64, t *Type, rt reflect.Type) { if _, ok := type_map[i]; ok { panic(fmt.Errorf("Error identical types exist %+v", i)) } type_map[i] = &typeData{t, rt} } func GetType(i uint64) (*Type, error) { t, ok := type_map[i] if !ok { return nil, fmt.Errorf("Could not find type %v", i) } return t.tp, nil } func TryGetType(i uint64) (*Type, bool) { t, ok := type_map[i] if !ok { return nil, false } return t.tp, ok } func GetReflectedType(i uint64) (reflect.Type, error) { t, ok := type_map[i] if !ok { return nil, fmt.Errorf("Could not find type %v", i) } return t.rt, nil } const BoolType = uint64(1) const IntType = uint64(2) const UintType = uint64(3) const SizeType = uint64(4) const CharType = uint64(5) const Uint8Type = uint64(6) const Int8Type = uint64(7) const Uint16Type = uint64(8) const Int16Type = uint64(9) const Float32Type = uint64(10) const Uint32Type = uint64(11) const Int32Type = uint64(12) const Float64Type = uint64(13) const Uint64Type = uint64(14) const Int64Type = uint64(15) const StringType = uint64(16) // GetTypeIndex returns the index of the type. func GetTypeIndex(i interface{}) (uint64, error) { switch i := i.(type) { case TypeProvider: return i.GetTypeIndex(), nil case bool: return 1, nil case memory.IntTy: return 2, nil case memory.UintTy: return 3, nil case memory.SizeTy: return 4, nil case memory.CharTy: return 5, nil case uint8: return 6, nil case int8: return 7, nil case uint16: return 8, nil case int16: return 9, nil case float32: return 10, nil case uint32: return 11, nil case int32: return 12, nil case float64: return 13, nil case uint64: return 14, nil case int64: return 15, nil case string: return 16, nil } return 0, fmt.Errorf("Unknown type %T", i) } // TypeProvider is an interface for any type that // has a registered type. type TypeProvider interface { GetTypeIndex() uint64 } func init() { AddType(BoolType, &Type{ TypeId: BoolType, Name: "bool", Ty: &Type_Pod{ pod.Type_bool, }, }, reflect.TypeOf(bool(false))) AddType(Uint8Type, &Type{ TypeId: Uint8Type, Name: "uint8_t", Ty: &Type_Pod{ pod.Type_uint8, }, }, reflect.TypeOf(uint8(0))) AddType(Int8Type, &Type{ TypeId: Int8Type, Name: "int8_t", Ty: &Type_Pod{ pod.Type_sint8, }, }, reflect.TypeOf(int8(0))) AddType(Uint16Type, &Type{ TypeId: Uint16Type, Name: "uint16_t", Ty: &Type_Pod{ pod.Type_uint16, }, }, reflect.TypeOf(uint16(0))) AddType(Int16Type, &Type{ TypeId: Int16Type, Name: "int16_t", Ty: &Type_Pod{ pod.Type_sint16, }, }, reflect.TypeOf(int16(0))) AddType(Float32Type, &Type{ TypeId: Float32Type, Name: "float32", Ty: &Type_Pod{ pod.Type_float32, }, }, reflect.TypeOf(float32(0))) AddType(Uint32Type, &Type{ TypeId: Uint32Type, Name: "uint32_t", Ty: &Type_Pod{ pod.Type_uint32, }, }, reflect.TypeOf(uint32(0))) AddType(Int32Type, &Type{ TypeId: Int32Type, Name: "int32_t", Ty: &Type_Pod{ pod.Type_sint32, }, }, reflect.TypeOf(int32(0))) AddType(Float64Type, &Type{ TypeId: Float64Type, Name: "float64", Ty: &Type_Pod{ pod.Type_float64, }, }, reflect.TypeOf(float64(0))) AddType(Uint64Type, &Type{ TypeId: Uint64Type, Name: "uint64_t", Ty: &Type_Pod{ pod.Type_uint64, }, }, reflect.TypeOf(uint64(0))) AddType(Int64Type, &Type{ TypeId: Int64Type, Name: "int64_t", Ty: &Type_Pod{ pod.Type_sint64, }, }, reflect.TypeOf(int64(0))) AddType(StringType, &Type{ TypeId: StringType, Name: "string", Ty: &Type_Pod{ pod.Type_string, }, }, reflect.TypeOf(string(""))) AddType(IntType, &Type{ TypeId: IntType, Name: "int", Ty: &Type_Sized{ SizedType_sized_int, }, }, reflect.TypeOf(memory.Int(0))) AddType(UintType, &Type{ TypeId: UintType, Name: "uint_t", Ty: &Type_Sized{ SizedType_sized_uint, }, }, reflect.TypeOf(memory.Uint(0))) AddType(SizeType, &Type{ TypeId: SizeType, Name: "size_t", Ty: &Type_Sized{ SizedType_sized_size, }, }, reflect.TypeOf(memory.Size(0))) AddType(CharType, &Type{ TypeId: CharType, Name: "char_t", Ty: &Type_Sized{ SizedType_sized_char, }, }, reflect.TypeOf(memory.Char(0))) } func (t *Type) Alignment(ctx context.Context, d *device.MemoryLayout) (int, error) { switch t := t.Ty.(type) { case *Type_Pod: switch t.Pod { case pod.Type_uint: return int(d.Integer.Alignment), nil case pod.Type_sint: return int(d.Integer.Alignment), nil case pod.Type_uint8: return int(d.I8.Alignment), nil case pod.Type_sint8: return int(d.I8.Alignment), nil case pod.Type_uint16: return int(d.I16.Alignment), nil case pod.Type_sint16: return int(d.I16.Alignment), nil case pod.Type_uint32: return int(d.I32.Alignment), nil case pod.Type_sint32: return int(d.I32.Alignment), nil case pod.Type_uint64: return int(d.I64.Alignment), nil case pod.Type_sint64: return int(d.I64.Alignment), nil case pod.Type_float32: return int(d.F32.Alignment), nil case pod.Type_float64: return int(d.F64.Alignment), nil case pod.Type_bool: return int(d.I8.Alignment), nil case pod.Type_string: return int(d.Pointer.Alignment), nil // String is a char* in memory } case *Type_Pointer: return int(d.Pointer.Alignment), nil case *Type_Struct: maxAlign := 1 for _, f := range t.Struct.Fields { elem, ok := TryGetType(f.Type) if !ok { return 0, log.Err(ctx, nil, "Incomplete type in struct alignment") } m, err := elem.Alignment(ctx, d) if err != nil { return 0, err } if m > maxAlign { maxAlign = m } } return maxAlign, nil case *Type_Sized: switch t.Sized { case SizedType_sized_int: return int(d.Integer.Alignment), nil case SizedType_sized_uint: return int(d.Integer.Alignment), nil case SizedType_sized_size: return int(d.Size.Alignment), nil case SizedType_sized_char: return int(d.Char.Alignment), nil } case *Type_Pseudonym: if elem, ok := TryGetType(t.Pseudonym.Underlying); ok { return elem.Alignment(ctx, d) } case *Type_Array: if elem, ok := TryGetType(t.Array.ElementType); ok { return elem.Alignment(ctx, d) } case *Type_Enum: if elem, ok := TryGetType(t.Enum.Underlying); ok { return elem.Alignment(ctx, d) } case *Type_Map: return 0, log.Err(ctx, nil, "Cannot decode map from memory") case *Type_Reference: return 0, log.Err(ctx, nil, "Cannot decode ref from memory") case *Type_Slice: return 0, log.Err(ctx, nil, "Cannot decode slice from memory") } return 0, log.Err(ctx, nil, fmt.Sprintf("Unhandled type alignment %T", t.Ty)) } func (t *Type) Size(ctx context.Context, d *device.MemoryLayout) (int, error) { switch t := t.Ty.(type) { case *Type_Pod: switch t.Pod { case pod.Type_uint: return int(d.Integer.Size), nil case pod.Type_sint: return int(d.Integer.Size), nil case pod.Type_uint8: return int(d.I8.Size), nil case pod.Type_sint8: return int(d.I8.Size), nil case pod.Type_uint16: return int(d.I16.Size), nil case pod.Type_sint16: return int(d.I16.Size), nil case pod.Type_uint32: return int(d.I32.Size), nil case pod.Type_sint32: return int(d.I32.Size), nil case pod.Type_uint64: return int(d.I64.Size), nil case pod.Type_sint64: return int(d.I64.Size), nil case pod.Type_float32: return int(d.F32.Size), nil case pod.Type_float64: return int(d.F64.Size), nil case pod.Type_bool: return int(d.I8.Size), nil case pod.Type_string: return int(d.Pointer.Size), nil // String is a char* in memory } case *Type_Pointer: return int(d.Pointer.Size), nil // String is a char* in memory case *Type_Struct: size := 0 maxAlign := 0 for _, f := range t.Struct.Fields { elem, ok := TryGetType(f.Type) if !ok { return 0, log.Err(ctx, nil, "Incomplete type in struct size") } a, err := elem.Alignment(ctx, d) if err != nil { return 0, err } if a > maxAlign { maxAlign = a } size = sint.AlignUp(size, a) m, err := elem.Size(ctx, d) if err != nil { return 0, err } size += m } size = sint.AlignUp(size, maxAlign) return size, nil case *Type_Sized: switch t.Sized { case SizedType_sized_int: return int(d.Integer.Size), nil case SizedType_sized_uint: return int(d.Integer.Size), nil case SizedType_sized_size: return int(d.Size.Size), nil case SizedType_sized_char: return int(d.Char.Size), nil } case *Type_Pseudonym: if elem, ok := TryGetType(t.Pseudonym.Underlying); ok { return elem.Size(ctx, d) } case *Type_Array: if elem, ok := TryGetType(t.Array.ElementType); ok { sz, err := elem.Size(ctx, d) if err != nil { return 0, err } return sz * int(t.Array.Size), nil } case *Type_Enum: if elem, ok := TryGetType(t.Enum.Underlying); ok { return elem.Size(ctx, d) } case *Type_Map: return 0, log.Err(ctx, nil, "Cannot decode map from memory") case *Type_Reference: return 0, log.Err(ctx, nil, "Cannot decode refs from memory") case *Type_Slice: return 0, log.Err(ctx, nil, "Cannot decode slices from memory") } return 0, log.Err(ctx, nil, "Incomplete type size") }
gapis/service/types/types.go
0.506347
0.434941
types.go
starcoder
package geometry import ( "github.com/samuelyuan/openbiohazard2/fileio" ) func NewMD1Geometry(meshData *fileio.MD1Output, textureData *fileio.TIMOutput) []float32 { vertexBuffer := make([]float32, 0) for _, entityModel := range meshData.Components { // Triangles for j := 0; j < len(entityModel.TriangleIndices); j++ { triangleIndex := entityModel.TriangleIndices[j] textureInfo := entityModel.TriangleTextures[j] vertex0 := buildModelVertex(entityModel.TriangleVertices[triangleIndex.IndexVertex0]) uv0 := buildTextureUV(float32(textureInfo.U0), float32(textureInfo.V0), textureInfo.Page, textureData) normal0 := buildModelNormal(entityModel.TriangleNormals[triangleIndex.IndexNormal0]) vertex1 := buildModelVertex(entityModel.TriangleVertices[triangleIndex.IndexVertex1]) uv1 := buildTextureUV(float32(textureInfo.U1), float32(textureInfo.V1), textureInfo.Page, textureData) normal1 := buildModelNormal(entityModel.TriangleNormals[triangleIndex.IndexNormal1]) vertex2 := buildModelVertex(entityModel.TriangleVertices[triangleIndex.IndexVertex2]) uv2 := buildTextureUV(float32(textureInfo.U2), float32(textureInfo.V2), textureInfo.Page, textureData) normal2 := buildModelNormal(entityModel.TriangleNormals[triangleIndex.IndexNormal2]) tri := NewTriangleNormals([3][]float32{vertex0, vertex1, vertex2}, [3][]float32{uv0, uv1, uv2}, [3][]float32{normal0, normal1, normal2}) vertexBuffer = append(vertexBuffer, tri.VertexBuffer...) } // Quads for j := 0; j < len(entityModel.QuadIndices); j++ { quadIndex := entityModel.QuadIndices[j] textureInfo := entityModel.QuadTextures[j] vertex0 := buildModelVertex(entityModel.QuadVertices[quadIndex.IndexVertex0]) uv0 := buildTextureUV(float32(textureInfo.U0), float32(textureInfo.V0), textureInfo.Page, textureData) normal0 := buildModelNormal(entityModel.QuadNormals[quadIndex.IndexNormal0]) vertex1 := buildModelVertex(entityModel.QuadVertices[quadIndex.IndexVertex1]) uv1 := buildTextureUV(float32(textureInfo.U1), float32(textureInfo.V1), textureInfo.Page, textureData) normal1 := buildModelNormal(entityModel.QuadNormals[quadIndex.IndexNormal1]) vertex2 := buildModelVertex(entityModel.QuadVertices[quadIndex.IndexVertex2]) uv2 := buildTextureUV(float32(textureInfo.U2), float32(textureInfo.V2), textureInfo.Page, textureData) normal2 := buildModelNormal(entityModel.QuadNormals[quadIndex.IndexNormal2]) vertex3 := buildModelVertex(entityModel.QuadVertices[quadIndex.IndexVertex3]) uv3 := buildTextureUV(float32(textureInfo.U3), float32(textureInfo.V3), textureInfo.Page, textureData) normal3 := buildModelNormal(entityModel.QuadNormals[quadIndex.IndexNormal3]) quad := NewQuadMD1([4][]float32{vertex0, vertex1, vertex2, vertex3}, [4][]float32{uv0, uv1, uv2, uv3}, [4][]float32{normal0, normal1, normal2, normal3}) vertexBuffer = append(vertexBuffer, quad.VertexBuffer...) } } return vertexBuffer } func buildModelVertex(vertex fileio.MD1Vertex) []float32 { return []float32{float32(vertex.X), float32(vertex.Y), float32(vertex.Z)} } func buildTextureUV(u float32, v float32, texturePage uint16, textureData *fileio.TIMOutput) []float32 { textureOffsetUnit := float32(textureData.ImageWidth) / float32(textureData.NumPalettes) textureCoordOffset := textureOffsetUnit * float32(texturePage&3) newU := (float32(u) + textureCoordOffset) / float32(textureData.ImageWidth) newV := float32(v) / float32(textureData.ImageHeight) return []float32{newU, newV} } func buildModelNormal(normal fileio.MD1Vertex) []float32 { return []float32{float32(normal.X), float32(normal.Y), float32(normal.Z)} }
geometry/md1geometry.go
0.771155
0.584093
md1geometry.go
starcoder
package BuildablePowerPole import ( "fmt" "github.com/l-ross/ficsit-toolkit/resource" ) type FGBuildablePowerPole struct { Name string ClassName string MAllowColoring bool MAttachmentPoints string MBuildEffectSpeed float64 MCreateClearanceMeshRepresentation bool MDescription string MDisplayName string MForceNetUpdateOnRegisterPlayer bool MHasPower bool MHideOnBuildEffectStart bool MHighlightVector string MInteractingPlayers string MIsUseable bool MPowerConnections string MPowerPoleType resource.PowerPoleType MShouldModifyWorldGrid bool MShouldShowAttachmentPointVisuals bool MShouldShowHighlight bool MSkipBuildEffect bool MToggleDormancyOnInteraction bool MaxRenderDistance float64 } var ( PowerPoleMk1 = FGBuildablePowerPole{ Name: "PowerPoleMk1", ClassName: "Build_PowerPoleMk1_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Can handle up to 4 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Power Pole Mk.1`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: true, MPowerConnections: ``, MPowerPoleType: resource.Pole, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleMk2 = FGBuildablePowerPole{ Name: "PowerPoleMk2", ClassName: "Build_PowerPoleMk2_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Can handle up to 7 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Power Pole Mk.2`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: true, MPowerConnections: ``, MPowerPoleType: resource.Pole, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleMk3 = FGBuildablePowerPole{ Name: "PowerPoleMk3", ClassName: "Build_PowerPoleMk3_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Can handle up to 10 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Power Pole Mk.3`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: true, MPowerConnections: ``, MPowerPoleType: resource.Pole, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleWall = FGBuildablePowerPole{ Name: "PowerPoleWall", ClassName: "Build_PowerPoleWall_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Power Pole that attaches to a wall. Can handle up to 4 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Wall Outlet Mk.1`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: false, MPowerConnections: ``, MPowerPoleType: resource.Wall, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleWallDouble = FGBuildablePowerPole{ Name: "PowerPoleWallDouble", ClassName: "Build_PowerPoleWallDouble_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Power Pole that attaches to a wall. Has one connector on each side of the wall. Can handle up to 4 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Double Wall Outlet Mk.1`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: false, MPowerConnections: ``, MPowerPoleType: resource.WallDouble, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleWallDoubleMk2 = FGBuildablePowerPole{ Name: "PowerPoleWallDoubleMk2", ClassName: "Build_PowerPoleWallDouble_Mk2_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Power Pole that attaches to a wall. Has one connector on each side of the wall. Can handle up to 7 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Double Wall Outlet Mk.2`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: false, MPowerConnections: ``, MPowerPoleType: resource.WallDouble, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleWallDoubleMk3 = FGBuildablePowerPole{ Name: "PowerPoleWallDoubleMk3", ClassName: "Build_PowerPoleWallDouble_Mk3_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Power Pole that attaches to a wall. Has one connector on each side of the wall. Can handle up to 10 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Double Wall Outlet Mk.3`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: false, MPowerConnections: ``, MPowerPoleType: resource.WallDouble, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleWallMk2 = FGBuildablePowerPole{ Name: "PowerPoleWallMk2", ClassName: "Build_PowerPoleWall_Mk2_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Power Pole that attaches to a wall. Can handle up to 7 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Wall Outlet Mk.2`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: false, MPowerConnections: ``, MPowerPoleType: resource.Wall, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } PowerPoleWallMk3 = FGBuildablePowerPole{ Name: "PowerPoleWallMk3", ClassName: "Build_PowerPoleWall_Mk3_C", MAllowColoring: true, MAttachmentPoints: ``, MBuildEffectSpeed: 0.000000, MCreateClearanceMeshRepresentation: true, MDescription: `Power Pole that attaches to a wall. Can handle up to 10 Power Line connections. Connect Power Poles, Power Generators and factory buildings together with Power Lines to create a power grid. The power grid supplies the connected buildings with power.`, MDisplayName: `Wall Outlet Mk.3`, MForceNetUpdateOnRegisterPlayer: false, MHasPower: false, MHideOnBuildEffectStart: false, MHighlightVector: `(X=0.000000,Y=0.000000,Z=0.000000)`, MInteractingPlayers: ``, MIsUseable: false, MPowerConnections: ``, MPowerPoleType: resource.Wall, MShouldModifyWorldGrid: true, MShouldShowAttachmentPointVisuals: false, MShouldShowHighlight: false, MSkipBuildEffect: false, MToggleDormancyOnInteraction: false, MaxRenderDistance: -1.000000, } ) func GetByClassName(className string) (FGBuildablePowerPole, error) { if v, ok := ClassNameToDescriptor[className]; ok { return v, nil } return FGBuildablePowerPole{}, fmt.Errorf("failed to find FGBuildablePowerPole with class name %s", className) } var ClassNameToDescriptor = map[string]FGBuildablePowerPole{ "Build_PowerPoleMk1_C": PowerPoleMk1, "Build_PowerPoleMk2_C": PowerPoleMk2, "Build_PowerPoleMk3_C": PowerPoleMk3, "Build_PowerPoleWall_C": PowerPoleWall, "Build_PowerPoleWallDouble_C": PowerPoleWallDouble, "Build_PowerPoleWallDouble_Mk2_C": PowerPoleWallDoubleMk2, "Build_PowerPoleWallDouble_Mk3_C": PowerPoleWallDoubleMk3, "Build_PowerPoleWall_Mk2_C": PowerPoleWallMk2, "Build_PowerPoleWall_Mk3_C": PowerPoleWallMk3, }
resource/buildable_power_pole/buildable_power_pole.go
0.580947
0.405743
buildable_power_pole.go
starcoder
package graphics2d // General purpose interface that takes a path and turns it into // a slice of paths. For example, a stroked outline of the path or breaks the // path up into a series of dashes. // PathProcessor defines the interface required for function passed to the Process function in Path. type PathProcessor interface { Process(p *Path) []*Path } // CompoundProc applies a collection of PathProcessors to a path. type CompoundProc struct { Procs []PathProcessor Concatenate bool } // NewCompoundProc creates a new CompundProcessor with the supplied path processors. func NewCompoundProc(procs ...PathProcessor) *CompoundProc { return &CompoundProc{procs, false} } // Process implements the PathProcessor interface. func (cp *CompoundProc) Process(p *Path) []*Path { paths := []*Path{p} if len(cp.Procs) == 0 { return paths } for _, proc := range cp.Procs { npaths := []*Path{} for _, path := range paths { npaths = append(npaths, proc.Process(path)...) } if cp.Concatenate { path, _ := ConcatenatePaths(npaths...) paths = []*Path{path} } else { paths = npaths } } return paths } // PathProcessor wrappers for Flatten, Simplify and Linepath functions // FlattenProc is a wrapper around Path.Flatten() and contains the minimum required // distance to the control points. type FlattenProc struct { Flatten float64 } // Process implements the PathProcessor interface. func (fp *FlattenProc) Process(p *Path) []*Path { path := p.Flatten(fp.Flatten) return []*Path{path} } // LineProc replaces a path with a single line. type LineProc struct{} // Process implements the PathProcessor interface. func (lp *LineProc) Process(p *Path) []*Path { path := p.Line() return []*Path{path} } // OpenProc replaces a path with its open version. type OpenProc struct{} // Process implements the PathProcessor interface. func (op *OpenProc) Process(p *Path) []*Path { path := p.Open() return []*Path{path} } // ReverseProc replaces a path with its reverse. type ReverseProc struct{} // Process implements the PathProcessor interface. func (rp *ReverseProc) Process(p *Path) []*Path { path := p.Reverse() return []*Path{path} } // SimplifyProc is a wrpper around Path.Simplify(). type SimplifyProc struct{} // Process implements the PathProcessor interface. func (sp *SimplifyProc) Process(p *Path) []*Path { path := p.Simplify() return []*Path{path} } // TransformProc is a wrapper around Path.Transform() and contains the Aff3 // transform to be applied. type TransformProc struct { Transform *Aff3 } // Process implements the PathProcessor interface. func (tp *TransformProc) Process(p *Path) []*Path { path := p.Transform(tp.Transform) return []*Path{path} }
pathprocess.go
0.815967
0.532
pathprocess.go
starcoder
package market import ( "bufio" "fmt" "strings" ) const maxScanTokenSize = 64 * 1024 const matrixMktBanner = `%%MatrixMarket` const ( // object mtxObjectMatrix = "matrix" // format mtxFormatArray = "array" mtxFormatCoordinate = "coordinate" mtxFormatDense = "array" mtxFormatSparse = "coordinate" // field mtxFieldComplex = "complex" mtxFieldInteger = "integer" mtxFieldPattern = "pattern" mtxFieldReal = "real" // symmetry mtxSymmetryGeneral = "general" mtxSymmetryHermitian = "hermitian" mtxSymmetrySkew = "skew-symmetric" mtxSymmetrySymm = "symmetric" ) // Errors returned by failures to read a matrix var ( ErrInputScanError = fmt.Errorf("error while scanning matrix input") ErrLineTooLong = fmt.Errorf("input line exceeds maximum length") ErrPrematureEOF = fmt.Errorf("required header items are missing") ErrNoHeader = fmt.Errorf("missing matrix market header line") ErrNotMTX = fmt.Errorf("input is not a matrix market file") ErrUnsupportedType = fmt.Errorf("unrecognizable matrix description") ErrUnwritable = fmt.Errorf("error writing matrix to io writer") ) var supported = map[int]mmType{ 1: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldReal, mtxSymmetryGeneral}, 2: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldReal, mtxSymmetrySymm}, 3: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldReal, mtxSymmetrySkew}, 4: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldInteger, mtxSymmetryGeneral}, 5: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldInteger, mtxSymmetrySymm}, 6: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldInteger, mtxSymmetrySkew}, 7: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldComplex, mtxSymmetryGeneral}, 8: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldComplex, mtxSymmetrySymm}, 9: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldComplex, mtxSymmetrySkew}, 10: {mtxObjectMatrix, mtxFormatArray, mtxFieldReal, mtxSymmetryGeneral}, 11: {mtxObjectMatrix, mtxFormatArray, mtxFieldReal, mtxSymmetrySymm}, 12: {mtxObjectMatrix, mtxFormatArray, mtxFieldReal, mtxSymmetrySkew}, 13: {mtxObjectMatrix, mtxFormatArray, mtxFieldInteger, mtxSymmetryGeneral}, 14: {mtxObjectMatrix, mtxFormatArray, mtxFieldInteger, mtxSymmetrySymm}, 15: {mtxObjectMatrix, mtxFormatArray, mtxFieldInteger, mtxSymmetrySkew}, 16: {mtxObjectMatrix, mtxFormatArray, mtxFieldComplex, mtxSymmetryGeneral}, 17: {mtxObjectMatrix, mtxFormatArray, mtxFieldComplex, mtxSymmetrySymm}, 18: {mtxObjectMatrix, mtxFormatArray, mtxFieldComplex, mtxSymmetrySkew}, 19: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldComplex, mtxSymmetryHermitian}, 20: {mtxObjectMatrix, mtxFormatArray, mtxFieldComplex, mtxSymmetryHermitian}, 21: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldPattern, mtxSymmetryGeneral}, 22: {mtxObjectMatrix, mtxFormatCoordinate, mtxFieldPattern, mtxSymmetrySymm}, } type mmType struct { Object string Format string Field string Symmetry string } func (t *mmType) isMatrix() bool { return t.Object == mtxObjectMatrix } func (t *mmType) isArray() bool { return t.Format == mtxFormatArray } func (t *mmType) isCoordinate() bool { return t.Format == mtxFormatCoordinate } func (t *mmType) isDense() bool { return t.Format == mtxFormatDense } func (t *mmType) isSparse() bool { return t.Format == mtxFormatSparse } func (t *mmType) isComplex() bool { return t.Field == mtxFieldComplex } func (t *mmType) isInteger() bool { return t.Field == mtxFieldInteger } func (t *mmType) isPattern() bool { return t.Field == mtxFieldPattern } func (t *mmType) isReal() bool { return t.Field == mtxFieldReal } func (t *mmType) isGeneral() bool { return t.Symmetry == mtxSymmetryGeneral } func (t *mmType) isHermitian() bool { return t.Symmetry == mtxSymmetryHermitian } func (t *mmType) isSkew() bool { return t.Symmetry == mtxSymmetrySkew } func (t *mmType) isSymmetric() bool { return t.Symmetry == mtxSymmetrySymm } // isMMType tests equality of two Matrix Market headers func (t *mmType) isMMType(t2 *mmType) bool { if strings.ToLower(t.Object) != t2.Object { return false } if strings.ToLower(t.Format) != t2.Format { return false } if strings.ToLower(t.Field) != t2.Field { return false } if strings.ToLower(t.Symmetry) != t2.Symmetry { return false } return true } // Bytes returns a formatted Matrix Market headers func (t *mmType) Bytes() []byte { s := fmt.Sprintf( "%s %s %s %s %s\n", matrixMktBanner, t.Object, t.Format, t.Field, t.Symmetry, ) return []byte(s) } // isSupported reports if receiver is among supported Matrix Market types, // based on comparison against object, format, field and symmetry. func (t *mmType) isSupported() bool { for _, t2 := range supported { if t.isMMType(&t2) { return true } } return false } // index returns the (one-indexed) index of the Matrix Market type or -1 func (t *mmType) index() int { for i, t2 := range supported { if t.isMMType(&t2) { return i } } return -1 } // scanHeader scans one line from a scanner and attempts to parse as a // Matrix Market header func scanHeader(scanner *bufio.Scanner) (*mmType, error) { var ( banner string t mmType ) if ok := scanner.Scan(); !ok { return nil, ErrInputScanError } _, err := fmt.Sscan(scanner.Text(), &banner, &t.Object, &t.Format, &t.Field, &t.Symmetry) if err != nil { return nil, ErrPrematureEOF } if banner != matrixMktBanner { return nil, ErrNoHeader } if !(t.isSupported()) { return nil, ErrUnsupportedType } return &t, nil } // counter tallies the number of bytes written to it type counter struct { total int } // Write implements the io.Writer interface. func (c *counter) Write(p []byte) (int, error) { var n int = len(p) c.total += n return n, nil }
market.go
0.731634
0.475057
market.go
starcoder
package main import ( "aoc2021/utils/conversions" "aoc2021/utils/files" "aoc2021/utils/intMath" "fmt" "sort" "strings" ) type coordinate struct { x, y int } type heightMap struct { grid map[coordinate]int height, width int } func (h heightMap) localMinimums() []coordinate { var minimums []coordinate for x := 0; x < h.width; x++ { for y := 0; y < h.height; y++ { coord := coordinate{x, y} cell := h.grid[coord] left, up, right, down := x-1, y-1, x+1, y+1 if left >= 0 && cell >= h.grid[coordinate{left, y}] { continue } if up >= 0 && cell >= h.grid[coordinate{x, up}] { continue } if right < h.width && cell >= h.grid[coordinate{right, y}] { continue } if down < h.height && cell >= h.grid[coordinate{x, down}] { continue } minimums = append(minimums, coordinate{x, y}) } } return minimums } func (h heightMap) riskLevelSum() int { total := 0 for _, coord := range h.localMinimums() { total += h.grid[coord] + 1 } return total } func (h heightMap) basinSize(coord coordinate, visited map[coordinate]bool) int { if _, ok := visited[coord]; ok { return 0 } else if v, ok := h.grid[coord]; v == 9 || !ok { return 0 } visited[coord] = true size := 1 size += h.basinSize(coordinate{coord.x - 1, coord.y}, visited) // left size += h.basinSize(coordinate{coord.x, coord.y - 1}, visited) // up size += h.basinSize(coordinate{coord.x + 1, coord.y}, visited) // right size += h.basinSize(coordinate{coord.x, coord.y + 1}, visited) // down return size } func (h heightMap) basinSizes() []int { var sizes []int for _, minimum := range h.localMinimums() { sizes = append(sizes, h.basinSize(minimum, map[coordinate]bool{})) } sort.Ints(sizes) return sizes } func parseInput(input string) heightMap { lines := strings.Split(input, "\n") grid := make(map[coordinate]int) for i, l := range lines { horizontal := make([]int, len(l)) for j, c := range l { horizontal[j] = conversions.MustAtoi(string(c)) grid[coordinate{j, i}] = horizontal[j] } } return heightMap{grid, len(lines), len(lines)} } func main() { puzzleInput := files.ReadInput() heightMap := parseInput(puzzleInput) fmt.Println(heightMap.riskLevelSum()) basinSizes := heightMap.basinSizes() fmt.Println(intMath.IntProduct(basinSizes[len(basinSizes)-3:]...)) }
days/day09/day09.go
0.66454
0.407982
day09.go
starcoder
package epoch import ( "time" ) func nHourly(e Epoch, n int, prev time.Time, next time.Time) bool { if prev.After(next) { return e.IsEpochal(next, prev) } if next.Sub(prev).Hours() >= float64(n) { return true } return prev.Hour()/n != next.Hour()/n } // TwelveHourly models an epoch that changes every 12 hours. type TwelveHourly struct{} // GetData exposes data for every-12-hours epoch. func (TwelveHourly) GetData() Data { return Data{ "Once every 12 hours", "The last PR merge commit of 12-hour partition of the day, by UTC commit timestamp on master. E.g., epoch changes at 00:00:00, 00:12:00, etc..", time.Hour * 12, time.Hour * 12, "", } } // IsEpochal indicates whether or not an every-12-hours epochal change occur between prev and next. func (e TwelveHourly) IsEpochal(prev time.Time, next time.Time) bool { return nHourly(e, 12, prev.UTC(), next.UTC()) } // EightHourly models an epoch that changes every eight hours. type EightHourly struct{} // GetData exposes data for every-eight-hours epoch. func (EightHourly) GetData() Data { return Data{ "Once every eight hours", "The last PR merge commit of eight-hour partition of the day, by UTC commit timestamp on master. E.g., epoch changes at 00:00:00, 00:08:00, etc..", time.Hour * 8, time.Hour * 8, "DEPRECATED: The eight_hourly epoch is being deprecated in favour of six_hourly and twelve_hourly.", } } // IsEpochal indicates whether or not an every-eight-hours epochal change occur between prev and next. func (e EightHourly) IsEpochal(prev time.Time, next time.Time) bool { return nHourly(e, 8, prev.UTC(), next.UTC()) } // SixHourly models an epoch that changes every six hours. type SixHourly struct{} // GetData exposes data for every-six-hours epoch. func (SixHourly) GetData() Data { return Data{ "Once every six hours", "The last PR merge commit of six-hour partition of the day, by UTC commit timestamp on master. E.g., epoch changes at 00:00:00, 00:06:00, etc..", time.Hour * 6, time.Hour * 6, "", } } // IsEpochal indicates whether or not an every-six-hours epochal change occur between prev and next. func (e SixHourly) IsEpochal(prev time.Time, next time.Time) bool { return nHourly(e, 6, prev.UTC(), next.UTC()) } // FourHourly models an epoch that changes every four hours. type FourHourly struct{} // GetData exposes data for every-four-hours epoch. func (FourHourly) GetData() Data { return Data{ "Once every four hours", "The last PR merge commit of four-hour partition of the day, by UTC commit timestamp on master. E.g., epoch changes at 00:00:00, 00:04:00, etc..", time.Hour * 4, time.Hour * 4, "DEPRECATED: The four_hourly epoch is being deprecated in favour of six_hourly and twelve_hourly.", } } // IsEpochal indicates whether or not an every-four-hours epochal change occur between prev and next. func (e FourHourly) IsEpochal(prev time.Time, next time.Time) bool { return nHourly(e, 4, prev.UTC(), next.UTC()) } // TwoHourly models an epoch that changes every two hours. type TwoHourly struct{} // GetData exposes data for every-two-hours epoch. func (TwoHourly) GetData() Data { return Data{ "Once every two hours", "The last PR merge commit of two-hour partition of the day, by UTC commit timestamp on master. E.g., epoch changes at 00:00:00, 00:02:00, etc..", time.Hour * 2, time.Hour * 2, "", } } // IsEpochal indicates whether or not an every-two-hours epochal change occur between prev and next. func (e TwoHourly) IsEpochal(prev time.Time, next time.Time) bool { return nHourly(e, 2, prev.UTC(), next.UTC()) }
revisions/epoch/fractional.go
0.825203
0.494751
fractional.go
starcoder
package parser import ( "io" "github.com/arr-ai/wbnf/errors" ) // The following methods assume a valid parse. Call (Term).ValidateParse first if // unsure. func (t S) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { return w.Write([]byte(e.(Scanner).String())) } func (t RE) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { return w.Write([]byte(e.(Scanner).String())) } func (t REF) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { return w.Write([]byte("\\" + e.(Scanner).String())) } func unparse(g Grammar, term Term, e TreeElement, w io.Writer, N *int) error { n, err := term.Unparse(g, e, w) if err == nil { *N += n } return err } func (t Seq) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { node := e.(Node) for i, term := range t { if err = unparse(g, term, node.Children[i], w, &n); err != nil { return } } return n, nil } func (t Oneof) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { node := e.(Node) return t[node.Extra.(Choice)].Unparse(g, node.Children[0], w) } func (t Delim) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { node := e.(Node) tgen := t.LRTerms(node) for _, child := range node.Children { if err = unparse(g, tgen.Next(), child, w, &n); err != nil { return } } return } func (t Quant) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { for _, child := range e.(Node).Children { if err = unparse(g, t.Term, child, w, &n); err != nil { return } } return } //----------------------------------------------------------------------------- func (t Rule) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { return g[t].Unparse(g, e, w) } //----------------------------------------------------------------------------- func (t Stack) Unparse(_ Grammar, _ TreeElement, _ io.Writer) (int, error) { panic(errors.Inconceivable) } //----------------------------------------------------------------------------- func (t Named) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { err = unparse(g, t.Term, e, w, &n) return } //----------------------------------------------------------------------------- func (t ScopedGrammar) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { panic(errors.Inconceivable) } func (t CutPoint) Unparse(g Grammar, e TreeElement, w io.Writer) (n int, err error) { return t.Term.Unparse(g, e, w) } func (t ExtRef) Unparse(g Grammar, te TreeElement, w io.Writer) (n int, err error) { panic("implement me") }
parser/unparse.go
0.695855
0.402304
unparse.go
starcoder
// Attack sbox lookup of first round of AES-128 using differential power analysis. // https://www.paulkocher.com/doc/DifferentialPowerAnalysis.pdf // $ go run power_analysis/attack_sbox_dpa.go -logtostderr -v=1 // [attack_sbox_dpa.go:89] Loaded capture with 500 traces / 5000 samples per trace // [attack_sbox_dpa.go:95] T is 500 x 2000 matrix // [attack_sbox_dpa.go:130] Best guess for index 9: <Key:0xf7, Diff:0.003849, Loc: 1277> // [attack_sbox_dpa.go:130] Best guess for index 14: <Key:0x4f, Diff:0.004740, Loc: 1493> // [attack_sbox_dpa.go:130] Best guess for index 8: <Key:0xab, Diff:0.006338, Loc: 1101> // [attack_sbox_dpa.go:130] Best guess for index 10: <Key:0x15, Diff:0.005330, Loc: 1453> // [attack_sbox_dpa.go:130] Best guess for index 13: <Key:0xcf, Diff:0.005314, Loc: 1317> // [attack_sbox_dpa.go:130] Best guess for index 11: <Key:0x88, Diff:0.005222, Loc: 1629> // [attack_sbox_dpa.go:130] Best guess for index 3: <Key:0x16, Diff:0.005074, Loc: 1549> // [attack_sbox_dpa.go:130] Best guess for index 2: <Key:0x15, Diff:0.004392, Loc: 1373> // [attack_sbox_dpa.go:130] Best guess for index 0: <Key:0x2b, Diff:0.005253, Loc: 1021> // [attack_sbox_dpa.go:130] Best guess for index 7: <Key:0xa6, Diff:0.005045, Loc: 1589> // [attack_sbox_dpa.go:130] Best guess for index 12: <Key:0x09, Diff:0.005581, Loc: 1141> // [attack_sbox_dpa.go:130] Best guess for index 15: <Key:0x3c, Diff:0.005395, Loc: 1669> // [attack_sbox_dpa.go:130] Best guess for index 4: <Key:0x28, Diff:0.007074, Loc: 1061> // [attack_sbox_dpa.go:130] Best guess for index 5: <Key:0xae, Diff:0.004561, Loc: 1237> // [attack_sbox_dpa.go:130] Best guess for index 1: <Key:0x7e, Diff:0.004438, Loc: 1197> // [attack_sbox_dpa.go:130] Best guess for index 6: <Key:0xd2, Diff:0.005460, Loc: 1413> // [attack_sbox_dpa.go:136] Fully recovered key: <KEY> package main import ( "encoding/hex" "flag" "fmt" "math" "sync" "github.com/google/gocw" "github.com/golang/glog" "gonum.org/v1/gonum/mat" ) var ( inputFlag = flag.String("input", "captures/stm_aes_t500_s5000.json.gz", "Capture input file") winStartFlag = flag.Int("t1", 0, "Window start") winEndFlag = flag.Int("t2", 0, "Window end") // Copied from third_party/tiny-AES-c/aes.c sbox = [256]byte{ //0 1 2 3 4 5 6 7 8 9 A B C D E F 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16} ) // Splits the capture into two sets: the ones where the expected sbox bit is one, // and the ones where the expected sbox bit is zero. // Returns boolean vectors. func leakModel(key byte, keyIdx int, capture gocw.Capture) (mat.Vector, mat.Vector) { split0 := mat.NewVecDense(len(capture), nil) split1 := mat.NewVecDense(len(capture), nil) // Any bit can be used as a predicate for the split. indicatorBit := byte(2) for i := 0; i < len(capture); i++ { pt := capture[i].Pt[keyIdx] ct := sbox[pt^key] if ct&(1<<indicatorBit) > 0 { split0.SetVec(i, 0.0) split1.SetVec(i, 1.0) } else { split0.SetVec(i, 1.0) split1.SetVec(i, 0.0) } } return split0, split1 } type keyGuess struct { key byte maxDiff float64 maxLocation int } func (g keyGuess) String() string { return fmt.Sprintf("<Key:0x%02x, Diff:%f, Loc: %d>", g.key, g.maxDiff, g.maxLocation) } func init() { flag.Parse() } func main() { defer glog.Flush() capture, err := gocw.LoadCapture(*inputFlag) if err != nil { glog.Fatal(err) } glog.Infof("Loaded capture with %d traces / %d samples per trace", len(capture), len(capture[0].PowerMeasurements)) M := capture.SamplesMatrix() if *winEndFlag == 0 { *winEndFlag = len(capture[0].PowerMeasurements) } T := M.(*mat.Dense).Slice(0, len(capture), *winStartFlag, *winEndFlag) r, c := T.Dims() glog.Infof("T is %d x %d matrix", r, c) fullKey := make([]byte, 16) var wg sync.WaitGroup wg.Add(16) for k := 0; k < 16; k++ { go func(keyIdx int) { defer wg.Done() bestGuess := keyGuess{byte(0), 0, 0} for key := 0; key < 256; key++ { S0, S1 := leakModel(byte(key), keyIdx, capture) // Compute difference of means. var avg0 mat.Dense S0.(*mat.VecDense).ScaleVec(1.0/mat.Sum(S0), S0) avg0.Product(mat.TransposeVec{S0}, T) var avg1 mat.Dense S1.(*mat.VecDense).ScaleVec(1.0/mat.Sum(S1), S1) avg1.Product(mat.TransposeVec{S1}, T) var diff mat.Dense diff.Sub(&avg0, &avg1) // Best guess is the key with the highest difference-of-means between all possible keys, // across all possible time-slices. for i, v := range diff.RawRowView(0) { v = math.Abs(v) if v > bestGuess.maxDiff { bestGuess = keyGuess{byte(key), v, *winStartFlag + i} } } } glog.V(1).Infof("Best guess for index %d: %v", keyIdx, bestGuess) fullKey[keyIdx] = bestGuess.key }(k) } wg.Wait() glog.Infof("Fully recovered key: %v", hex.EncodeToString(fullKey)) }
cmd/attack_sbox_dpa.go
0.592195
0.653932
attack_sbox_dpa.go
starcoder
package binparsergen import "fmt" // A parser is an object which generates code to extract a specific // object from binary data. type Parser interface { // Generate a method on struct_name that extracts field field_name. Compile(struct_name string, field_name string) string // The name of the profile we are generating. ProfileName() string // Generate a free function which can parse this object from a // reader at a particular offset. Prototype() string // The name of the Prototype() method. PrototypeName() string // The GoType we will use to represent this object. GoType() string // If we use a pointer to represent the object this method // should return a "*" GoTypePointer() string // The size of the object. Size(value string) string } type BaseParser struct { Profile string } func (self BaseParser) Compile(struct_name string, field_name string) string { return "" } func (self BaseParser) Prototype() string { return "" } func (self BaseParser) PrototypeName() string { return "" } func (self BaseParser) ProfileName() string { return self.Profile } func (self BaseParser) GoType() string { return "" } func (self BaseParser) GoTypePointer() string { return "" } func (self BaseParser) Size(value string) string { return "" } type NullParser struct { BaseParser } type Uint64Parser struct { BaseParser } func (self Uint64Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() uint64 { return ParseUint64(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name) } func (self Uint64Parser) Prototype() string { return fmt.Sprintf(` func ParseUint64(reader io.ReaderAt, offset int64) uint64 { data := make([]byte, 8) _, err := reader.ReadAt(data, offset) if err != nil { return 0 } return binary.LittleEndian.Uint64(data) } `) } func (self Uint64Parser) PrototypeName() string { return "ParseUint64" } func (self Uint64Parser) GoType() string { return "uint64" } func (self Uint64Parser) Size(value string) string { return "8" } type Int64Parser struct { BaseParser } func (self Int64Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() int64 { return int64(ParseUint64(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset)) } `, struct_name, field_name) } func (self Int64Parser) Prototype() string { return fmt.Sprintf(` func ParseInt64(reader io.ReaderAt, offset int64) int64 { data := make([]byte, 8) _, err := reader.ReadAt(data, offset) if err != nil { return 0 } return int64(binary.LittleEndian.Uint64(data)) } `) } func (self Int64Parser) PrototypeName() string { return "ParseInt64" } func (self Int64Parser) GoType() string { return "int64" } func (self Int64Parser) Size(value string) string { return "8" } type Uint32Parser struct { BaseParser } func (self Uint32Parser) Prototype() string { return ` func ParseUint32(reader io.ReaderAt, offset int64) uint32 { data := make([]byte, 4) _, err := reader.ReadAt(data, offset) if err != nil { return 0 } return binary.LittleEndian.Uint32(data) } ` } func (self Uint32Parser) PrototypeName() string { return "ParseUint32" } func (self Uint32Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() uint32 { return ParseUint32(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name) } func (self Uint32Parser) GoType() string { return "uint32" } func (self Uint32Parser) Size(value string) string { return "4" } type Int32Parser struct { BaseParser } func (self Int32Parser) Prototype() string { return ` func ParseInt32(reader io.ReaderAt, offset int64) int32 { data := make([]byte, 4) _, err := reader.ReadAt(data, offset) if err != nil { return 0 } return int32(binary.LittleEndian.Uint32(data)) } ` } func (self Int32Parser) PrototypeName() string { return "ParseInt32" } func (self Int32Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() int32 { return ParseInt32(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name) } func (self Int32Parser) GoType() string { return "int32" } func (self Int32Parser) Size(value string) string { return "4" } type Uint16Parser struct { BaseParser } func (self Uint16Parser) Prototype() string { return ` func ParseUint16(reader io.ReaderAt, offset int64) uint16 { data := make([]byte, 2) _, err := reader.ReadAt(data, offset) if err != nil { return 0 } return binary.LittleEndian.Uint16(data) } ` } func (self Uint16Parser) PrototypeName() string { return "ParseUint16" } func (self Uint16Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() uint16 { return ParseUint16(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name) } func (self Uint16Parser) GoType() string { return "uint16" } func (self Uint16Parser) Size(value string) string { return "2" } type Int16Parser struct { BaseParser } func (self Int16Parser) Prototype() string { return ` func ParseInt16(reader io.ReaderAt, offset int64) int16 { data := make([]byte, 2) _, err := reader.ReadAt(data, offset) if err != nil { return 0 } return int16(binary.LittleEndian.Uint16(data)) } ` } func (self Int16Parser) PrototypeName() string { return "ParseInt16" } func (self Int16Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() int16 { return ParseInt16(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name) } func (self Int16Parser) GoType() string { return "int16" } func (self Int16Parser) Size(value string) string { return "2" } type Uint8Parser struct { BaseParser } func (self Uint8Parser) Prototype() string { return ` func ParseUint8(reader io.ReaderAt, offset int64) byte { result := make([]byte, 1) _, err := reader.ReadAt(result, offset) if err != nil { return 0 } return result[0] } ` } func (self Uint8Parser) PrototypeName() string { return "ParseUint8" } func (self Uint8Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() byte { return ParseUint8(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name) } func (self Uint8Parser) GoType() string { return "byte" } func (self Uint8Parser) Size(v string) string { return "1" } type Int8Parser struct { BaseParser } func (self Int8Parser) Prototype() string { return ` func ParseInt8(reader io.ReaderAt, offset int64) int8 { result := make([]byte, 1) _, err := reader.ReadAt(result, offset) if err != nil { return 0 } return int8(result[0]) } ` } func (self Int8Parser) PrototypeName() string { return "ParseInt8" } func (self Int8Parser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() int8 { return ParseInt8(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name) } func (self Int8Parser) GoType() string { return "int8" } func (self Int8Parser) Size(v string) string { return "1" } type ArrayParser struct { BaseParser Target *FieldDefinition Count int } func (self ArrayParser) Prototype() string { parser := self.Target.GetParser() return fmt.Sprintf(` func ParseArray_%[1]s(profile *%[2]s, reader io.ReaderAt, offset int64, count int) []%[3]s%[1]s { result := make([]%[3]s%[1]s, 0, count) for i:=0; i<count; i++ { value := %[4]s(reader, offset) result = append(result, value) offset += int64(%[5]s) } return result } `, parser.GoType(), parser.ProfileName(), parser.GoTypePointer(), parser.PrototypeName(), parser.Size("value")) } func (self ArrayParser) PrototypeName() string { parser := self.Target.GetParser() return fmt.Sprintf("ParseArray_%s", parser.GoType()) } func (self ArrayParser) Compile(struct_name string, field_name string) string { parser := self.Target.GetParser() return fmt.Sprintf(` func (self *%[1]s) %[2]s() []%[3]s%[4]s { return %[5]s(self.Profile, self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset, %[6]d) } `, struct_name, field_name, parser.GoTypePointer(), parser.GoType(), self.PrototypeName(), self.Count) } func (self ArrayParser) GoType() string { return "XXX" } func (self ArrayParser) Size(value string) string { parser := self.Target.GetParser() return fmt.Sprintf("%d * %s", self.Count, parser.Size(value)) } type StructParser struct { BaseParser Target string } func (self StructParser) Prototype() string { return "" return fmt.Sprintf(` func Parse_%[1]s(profile %[2]s, reader io.ReaderAt, offset int) *%[3]s { return profile.%[3]s(reader, offset) } `, self.Target, self.ProfileName(), self.Target) } func (self StructParser) PrototypeName() string { return fmt.Sprintf("profile.%s", self.Target) } func (self StructParser) Compile(struct_name string, field_name string) string { return fmt.Sprintf(` func (self *%[1]s) %[2]s() *%[3]s { return self.Profile.%[3]s(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) } `, struct_name, field_name, self.Target) } func (self StructParser) GoType() string { return self.Target } func (self StructParser) GoTypePointer() string { return "*" } func (self StructParser) Size(value string) string { return fmt.Sprintf("%s.Size()", value) } type Pointer struct { BaseParser Target *FieldDefinition } func (self *Pointer) Prototype() string { return "" } func (self Pointer) PrototypeName() string { return "" } func (self Pointer) Compile(struct_name string, field_name string) string { parser := self.Target.GetParser() return fmt.Sprintf(` func (self *%[1]s) %[2]s() *%[3]s { deref := ParseUint64(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) return self.Profile.%[3]s(self.Reader, int64(deref)) } `, struct_name, field_name, parser.GoType()) } func (self Pointer) GoType() string { parser := self.Target.GetParser() return "*" + parser.GoType() } func (self Pointer) Size(value string) string { return "8" } type BitField struct { BaseParser StartBit uint64 `json:"start_bit,omitempty"` EndBit uint64 `json:"end_bit,omitempty"` Target string `json:"target,omitempty"` } func (self *BitField) Prototype() string { return "" } func (self BitField) PrototypeName() string { return "" } func (self BitField) Compile(struct_name string, field_name string) string { parser_func := "ParseUint64" switch self.Target { case "unsigned long long": parser_func = "ParseUint64" case "unsigned long": parser_func = "ParseUint32" case "unsigned short": parser_func = "ParseUint16" case "unsigned char": parser_func = "ParseUint8" } return fmt.Sprintf(` func (self *%[1]s) %[2]s() uint64 { value := %[3]s(self.Reader, self.Profile.Off_%[1]s_%[2]s + self.Offset) return (uint64(value) & %#[4]x) >> %#[5]x } `, struct_name, field_name, parser_func, (1<<uint64(self.EndBit))-1, self.StartBit) } func (self BitField) GoType() string { return "uint64" } func (self BitField) Size(value string) string { return "8" }
parser.go
0.768777
0.425605
parser.go
starcoder
package ts import ( "math" "time" ) // LTTB down-samples the data to contain only threshold number of points that // have the same visual shape as the original data. Inspired from // https://github.com/dgryski/go-lttb which is based on // https://skemman.is/bitstream/1946/15343/3/SS_MSthesis.pdf func LTTB(b *Series, start time.Time, end time.Time, millisPerStep int) *Series { if end.After(b.EndTime()) { end = b.EndTime() } seriesValuesPerStep := millisPerStep / b.MillisPerStep() seriesStart, seriesEnd := b.StepAtTime(start), b.StepAtTime(end) // This threshold is different than max datapoints since we ensure step size is an integer multiple of original series step threshold := int(math.Ceil(float64(seriesEnd-seriesStart) / float64(seriesValuesPerStep))) if threshold == 0 || threshold > b.Len() { return b // Nothing to do } values := NewValues(b.ctx, millisPerStep, threshold) // Bucket size. Leave room for start and end data points every := float64(seriesValuesPerStep) // Always add the first point values.SetValueAt(0, b.ValueAt(seriesStart)) // Set a to be the first chosen point a := seriesStart bucketStart := seriesStart + 1 bucketCenter := bucketStart + int(math.Floor(every)) + 1 for i := 0; i < threshold-2; i++ { bucketEnd := bucketCenter + int(math.Floor(every)) // Calculate point average for next bucket (containing c) avgRangeStart := bucketCenter avgRangeEnd := bucketEnd if avgRangeEnd >= seriesEnd { avgRangeEnd = seriesEnd } avgRangeLength := float64(avgRangeEnd - avgRangeStart) var avgX, avgY float64 var valuesRead int for ; avgRangeStart < avgRangeEnd; avgRangeStart++ { yVal := b.ValueAt(avgRangeStart) if math.IsNaN(yVal) { continue } valuesRead++ avgX += float64(avgRangeStart) avgY += yVal } if valuesRead > 0 { avgX /= avgRangeLength avgY /= avgRangeLength } else { // If all nulls then should not assign a value to average avgX = math.NaN() avgY = math.NaN() } // Get the range for this bucket rangeOffs := bucketStart rangeTo := bucketCenter // Point a pointAX := float64(a) pointAY := b.ValueAt(a) var nextA int // If all points in left or right bucket are null, then fallback to average if math.IsNaN(avgY) || math.IsNaN(pointAY) { nextA = indexClosestToAverage(b, rangeOffs, rangeTo) } else { nextA = indexWithLargestTriangle(b, rangeOffs, rangeTo, pointAX, pointAY, avgX, avgY) } values.SetValueAt(i+1, b.ValueAt(nextA)) // Pick this point from the bucket a = nextA // This a is the next a (chosen b) bucketStart = bucketCenter bucketCenter = bucketEnd } if values.Len() > 1 { // Always add last if not just a single step values.SetValueAt(values.Len()-1, b.ValueAt(seriesEnd-1)) } // Derive a new series sampledSeries := b.DerivedSeries(start, values) return sampledSeries } func indexWithLargestTriangle(b *Series, start int, end int, leftX float64, leftY float64, rightX float64, rightY float64) int { // The original algorithm implementation initializes the maxArea as 0 which is a bug! maxArea := -1.0 var largestIndex int xDifference := leftX - rightX yDifference := rightY - leftY for index := start; index < end; index++ { // Calculate triangle area over three buckets area := xDifference*(b.ValueAt(index)-leftY) - (leftX-float64(index))*yDifference // We only care about the relative area here. area = math.Abs(area) // Handle nulls properly if math.IsNaN(area) { area = 0 } if area > maxArea { maxArea = area largestIndex = index } } return largestIndex } func indexClosestToAverage(b *Series, start int, end int) int { var sum float64 var count int for index := start; index < end; index++ { if math.IsNaN(b.ValueAt(index)) { continue } sum += b.ValueAt(index) count++ } if count == 0 { return start } average := sum / float64(count) minDifference := math.MaxFloat64 closestIndex := start for index := start; index < end; index++ { difference := math.Abs(average - b.ValueAt(index)) if !math.IsNaN(b.ValueAt(index)) && difference < minDifference { closestIndex = index minDifference = difference } } return closestIndex }
src/query/graphite/ts/lttb.go
0.79158
0.597285
lttb.go
starcoder
package plaid import ( "encoding/json" ) // NumbersBACS Identifying information for transferring money to or from a UK bank account via BACS. type NumbersBACS struct { // The Plaid account ID associated with the account numbers AccountId string `json:"account_id"` // The BACS account number for the account Account string `json:"account"` // The BACS sort code for the account SortCode string `json:"sort_code"` AdditionalProperties map[string]interface{} } type _NumbersBACS NumbersBACS // NewNumbersBACS instantiates a new NumbersBACS 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 NewNumbersBACS(accountId string, account string, sortCode string) *NumbersBACS { this := NumbersBACS{} this.AccountId = accountId this.Account = account this.SortCode = sortCode return &this } // NewNumbersBACSWithDefaults instantiates a new NumbersBACS 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 NewNumbersBACSWithDefaults() *NumbersBACS { this := NumbersBACS{} return &this } // GetAccountId returns the AccountId field value func (o *NumbersBACS) GetAccountId() string { if o == nil { var ret string return ret } return o.AccountId } // GetAccountIdOk returns a tuple with the AccountId field value // and a boolean to check if the value has been set. func (o *NumbersBACS) GetAccountIdOk() (*string, bool) { if o == nil { return nil, false } return &o.AccountId, true } // SetAccountId sets field value func (o *NumbersBACS) SetAccountId(v string) { o.AccountId = v } // GetAccount returns the Account field value func (o *NumbersBACS) GetAccount() string { if o == nil { var ret string return ret } return o.Account } // GetAccountOk returns a tuple with the Account field value // and a boolean to check if the value has been set. func (o *NumbersBACS) GetAccountOk() (*string, bool) { if o == nil { return nil, false } return &o.Account, true } // SetAccount sets field value func (o *NumbersBACS) SetAccount(v string) { o.Account = v } // GetSortCode returns the SortCode field value func (o *NumbersBACS) GetSortCode() string { if o == nil { var ret string return ret } return o.SortCode } // GetSortCodeOk returns a tuple with the SortCode field value // and a boolean to check if the value has been set. func (o *NumbersBACS) GetSortCodeOk() (*string, bool) { if o == nil { return nil, false } return &o.SortCode, true } // SetSortCode sets field value func (o *NumbersBACS) SetSortCode(v string) { o.SortCode = v } func (o NumbersBACS) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["account_id"] = o.AccountId } if true { toSerialize["account"] = o.Account } if true { toSerialize["sort_code"] = o.SortCode } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *NumbersBACS) UnmarshalJSON(bytes []byte) (err error) { varNumbersBACS := _NumbersBACS{} if err = json.Unmarshal(bytes, &varNumbersBACS); err == nil { *o = NumbersBACS(varNumbersBACS) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "account_id") delete(additionalProperties, "account") delete(additionalProperties, "sort_code") o.AdditionalProperties = additionalProperties } return err } type NullableNumbersBACS struct { value *NumbersBACS isSet bool } func (v NullableNumbersBACS) Get() *NumbersBACS { return v.value } func (v *NullableNumbersBACS) Set(val *NumbersBACS) { v.value = val v.isSet = true } func (v NullableNumbersBACS) IsSet() bool { return v.isSet } func (v *NullableNumbersBACS) Unset() { v.value = nil v.isSet = false } func NewNullableNumbersBACS(val *NumbersBACS) *NullableNumbersBACS { return &NullableNumbersBACS{value: val, isSet: true} } func (v NullableNumbersBACS) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableNumbersBACS) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_numbers_bacs.go
0.723798
0.423041
model_numbers_bacs.go
starcoder
package definition import ( "fmt" "reflect" "github.com/drgomesp/cargo/argument" "github.com/drgomesp/cargo/method" ) // Definition of a service or an argument type Definition struct { arguments []argument.Interface methodCalls []*method.Method constructor reflect.Value t reflect.Type } // New definition based on factory functions or pointers func New(arg interface{}, args ...interface{}) (def Interface, err error) { switch reflect.TypeOf(arg).Kind() { case reflect.Func: if reflect.TypeOf(arg).NumOut() == 0 { err = fmt.Errorf("Constructor function must have a return type") return } if constructor, err := createFromConstructorFunction(reflect.ValueOf(arg)); nil == err { def = constructor } case reflect.Ptr: if constructor, err := createFromPointer(&arg); nil == err { def = constructor } default: err = fmt.Errorf("A definition must be created from a pointer to a struct or a constructor function") } return } // AddArguments to the definition func (d *Definition) AddArguments(arg ...argument.Interface) Interface { d.arguments = append(d.arguments, arg...) return Interface(d) } // AddMethodCall to the definition func (d *Definition) AddMethodCall(method *method.Method) Interface { d.methodCalls = append(d.methodCalls, method) return Interface(d) } // Arguments of the definition func (d *Definition) Arguments() []argument.Interface { return d.arguments } // Method calls of the definition func (d *Definition) MethodCalls() []*method.Method { return d.methodCalls } // Constructor for the definition func (d *Definition) Constructor() reflect.Value { return d.constructor } // Type for the definition func (d *Definition) Type() reflect.Type { return d.t } func createFromConstructorFunction(fn reflect.Value) (def Interface, err error) { var returnType reflect.Type constructor := reflect.MakeFunc(fn.Type(), func(in []reflect.Value) []reflect.Value { returnType = reflect.TypeOf(fn.Interface()).Out(0) return []reflect.Value{reflect.New(returnType.Elem())} }) def = &Definition{ arguments: make([]argument.Interface, 0), methodCalls: make([]*method.Method, 0), constructor: constructor, t: reflect.TypeOf(constructor.Interface()).Out(0), } return } func createFromPointer(ptr interface{}, args ...interface{}) (def Interface, err error) { def = &Definition{ arguments: make([]argument.Interface, 0), methodCalls: make([]*method.Method, 0), t: reflect.TypeOf(ptr), } return }
definition/definition.go
0.609989
0.422147
definition.go
starcoder
package elastic import ( "fmt" "math" "gopkg.in/olivere/elastic.v3" "github.com/unchartedsoftware/veldt/binning" "github.com/unchartedsoftware/veldt/tile" ) // Bivariate represents an elasticsearch implementation of the bivariate tile. type Bivariate struct { tile.Bivariate // tiling tiling bool minX int64 maxX int64 minY int64 maxY int64 // binning binning bool intervalX int64 intervalY int64 } func (b *Bivariate) computeTilingProps(coord *binning.TileCoord) { if b.tiling { return } // tiling params extents := &binning.Bounds{ BottomLeft: &binning.Coord{ X: b.Left, Y: b.Bottom, }, TopRight: &binning.Coord{ X: b.Right, Y: b.Top, }, } b.Bounds = binning.GetTileBounds(coord, extents) b.minX = int64(math.Min(b.Bounds.BottomLeft.X, b.Bounds.TopRight.X)) b.maxX = int64(math.Max(b.Bounds.BottomLeft.X, b.Bounds.TopRight.X)) b.minY = int64(math.Min(b.Bounds.BottomLeft.Y, b.Bounds.TopRight.Y)) b.maxY = int64(math.Max(b.Bounds.BottomLeft.Y, b.Bounds.TopRight.Y)) // flag as computed b.tiling = true } func (b *Bivariate) computeBinningProps(coord *binning.TileCoord) { if b.binning { return } // ensure we have tiling props b.computeTilingProps(coord) // binning params xRange := math.Abs(b.Bounds.TopRight.X - b.Bounds.BottomLeft.X) yRange := math.Abs(b.Bounds.TopRight.Y - b.Bounds.BottomLeft.Y) b.intervalX = int64(math.Max(1, xRange/float64(b.Resolution))) b.intervalY = int64(math.Max(1, yRange/float64(b.Resolution))) b.BinSizeX = xRange / float64(b.Resolution) b.BinSizeY = yRange / float64(b.Resolution) // flag as computed b.binning = true } // GetQuery returns the tiling query. func (b *Bivariate) GetQuery(coord *binning.TileCoord) elastic.Query { // compute the tiling properties b.computeTilingProps(coord) // create the range queries query := elastic.NewBoolQuery() query.Must(elastic.NewRangeQuery(b.XField). Gte(b.minX). Lt(b.maxX)) query.Must(elastic.NewRangeQuery(b.YField). Gte(b.minY). Lt(b.maxY)) return query } // GetAggs returns the tiling aggregation. func (b *Bivariate) GetAggs(coord *binning.TileCoord) map[string]elastic.Aggregation { // compute the binning properties b.computeBinningProps(coord) // create the binning aggregations x := elastic.NewHistogramAggregation(). Field(b.XField). Offset(b.minX). Interval(b.intervalX). MinDocCount(1) y := elastic.NewHistogramAggregation(). Field(b.YField). Offset(b.minY). Interval(b.intervalY). MinDocCount(1) x.SubAggregation("y", y) return map[string]elastic.Aggregation{ "x": x, "y": y, } } // GetBins parses the resulting histograms into bins. func (b *Bivariate) GetBins(aggs *elastic.Aggregations) ([]*elastic.AggregationBucketHistogramItem, error) { if !b.binning { return nil, fmt.Errorf("binning properties have not been computed, ensure `GetAggs` is called") } // parse aggregations xAgg, ok := aggs.Histogram("x") if !ok { return nil, fmt.Errorf("histogram aggregation `x` was not found") } // allocate bins bins := make([]*elastic.AggregationBucketHistogramItem, b.Resolution*b.Resolution) // fill bins for _, xBucket := range xAgg.Buckets { x := xBucket.Key xBin := b.GetXBin(x) yAgg, ok := xBucket.Histogram("y") if !ok { return nil, fmt.Errorf("histogram aggregation `y` was not found") } for _, yBucket := range yAgg.Buckets { y := yBucket.Key yBin := b.GetYBin(y) index := xBin + b.Resolution*yBin bins[index] = yBucket } } return bins, nil }
vendor/github.com/unchartedsoftware/veldt/generation/elastic/bivariate.go
0.755817
0.416144
bivariate.go
starcoder
package common import ( "math" "math/big" "strconv" ) // IsPrime Checks if the input number is prime or not func IsPrime(n int) bool { out := false if n == 2 { out = true } else if (n % 2) == 0 { out = false } else if n < 2 { out = false } else { max := int(math.Sqrt(float64(n))) factors := 1 for factor := 2; factor < max+1; factor = factor + 1 { if n%factor == 0 { factors++ } if factors > 1 { break } } if factors < 2 { out = true } } return out } // IsFactor returns true/false based on the two inputs func IsFactor(n int, factor int) bool { return (n % factor) == 0 } // DigitSum adds the individual digits of a long number func DigitSum(value big.Int) int { digits := GetDigits(value) sum := 0 for _, digit := range digits { sum += digit } return sum } // CalculatePower takes the root and the power to calculate func CalculatePower(number uint64, power uint64) big.Int { bigNum := new(big.Int) bigNum.SetUint64(number) powerBig := new(big.Int) powerBig.SetUint64(power) result := new(big.Int) if power < 1 { result.SetUint64(1) } else if power == 1 { result.SetUint64(number) } else { result.SetUint64(1) for index := 1; uint64(index) <= power; index++ { result = result.Mul(result, bigNum) } } return *result } func FindDigitCount(number big.Int) int { digits := GetDigits(number) return len(digits) } // GetDigits gives an array of integers that are part of a supplied bigInt number func GetDigits(number big.Int) []int { var nums []int zero := new(big.Int) zero.SetUint64(0) ten := new(big.Int) ten.SetUint64(10) one := new(big.Int) one.SetUint64(1) tmp := new(big.Int) tmp.SetUint64(0) tmp = tmp.Add(tmp, &number) for i := tmp; i.Cmp(zero) > 0; { rem := new(big.Int) _, rem = i.DivMod(i, ten, rem) v, _ := strconv.Atoi(rem.Text(10)) nums = append(nums, v) } digits := make([]int, len(nums)) numsLen := len(nums) for i := 0; i < numsLen; i++ { digits[i] = nums[numsLen-i-1] } return digits } func IsPalindrome(n int) bool { str := strconv.Itoa(n) length := len(str) for index := 0; index < length-1; index++ { if int(str[index]) != int(str[length-index-1]) { return false } } return true }
src/common/num-ops.go
0.688049
0.50708
num-ops.go
starcoder
Coding Exercise #1 1. Using the var keyword, declare a bidirectional unbuffered channel called c1 that works with values of type float64 2. Using the make() built-in function declare and initialize a receive-only channel called c2 and a send-only channel called c3. Both work with data of type rune. 3. Declare a bidirectional buffered channel called c4 with a capacity of 10 ints. 4. Print out the type of all the channels declared. Are you stuck? Do you want to see the solution for this exercise? Click https://play.golang.org/p/AAy5k4dp_3t. Coding Exercise #2 Create a function literal (a.k.a. anonymous function) that sends the string value if receives as argument to main func using a channel. Are you stuck? Do you want to see the solution for this exercise? Click https://play.golang.org/p/BJ5I1RlZemV. Coding Exercise #3 There are some errors in the following Go program. Try to identify the errors, change the code and run the program without errors. package main import ( "fmt" ) func main() { c := make(<-chan int) go func(n int) { c <- n }(100) fmt.Println(<-c) } Are you stuck? Do you want to see the solution for this exercise? Click https://play.golang.org/p/n803fVTWSKi. Coding Exercise #4 Create a goroutine named power() that has one parameter of type int, calculates the square value of its parameter and then sends the result into a channel. In the main function launch 50 goroutines that calculate the square values of all numbers between 1 and 50 included. Print out the square values. A square(or raising to power 2) is the result of multiplying a number by itself. e.g., 25 is the square of 5. Are you stuck? Do you want to see the solution for this exercise? Click https://play.golang.org/p/hcR7GUZlpn1. Coding Exercise #5 Change the program from Exercise #4 and calculate the square of all values between 1 and 50 included using an anonymous function. Are you stuck? Do you want to see the solution for this exercise? Click https://play.golang.org/p/NufTb2AaDhy.
more_code/coding_tasks/concurrency/gorutines_channels.go
0.874305
0.658431
gorutines_channels.go
starcoder
package notation import ( "bytes" "fmt" "reflect" "sort" "strconv" "strings" ) func withType(o opts) (opts, bool, bool) { if o&types == 0 && o&allTypes == 0 { return o, false, false } if o&skipTypes != 0 && o&allTypes == 0 { return o &^ skipTypes, false, false } return o, true, o&allTypes != 0 } func reflectPrimitive(o opts, r reflect.Value, v interface{}, suppressType ...string) node { s := fmt.Sprint(v) if s[0] == '(' && s[len(s)-1] == ')' { s = s[1 : len(s)-1] } _, t, a := withType(o) if !t { return nodeOf(s) } tn := reflectType(r.Type()) if a { return nodeOf(tn, "(", s, ")") } for _, suppress := range suppressType { if tn.parts[0] == suppress { return nodeOf(s) } } return nodeOf(tn, "(", s, ")") } func reflectNil(o opts, groupUnnamedType bool, r reflect.Value) node { if _, _, a := withType(o); !a { return nodeOf("nil") } rt := r.Type() if groupUnnamedType && rt.Name() == "" { return nodeOf("(", reflectType(rt), ")(nil)") } return nodeOf(reflectType(rt), "(nil)") } func reflectItems(o opts, p *pending, prefix string, r reflect.Value) node { typ := r.Type() var w wrapper if typ.Elem().Kind() == reflect.Uint8 { w.sep = " " w.mode = line for i := 0; i < r.Len(); i++ { w.items = append( w.items, nodeOf(fmt.Sprintf("%02x", r.Index(i).Uint())), ) } } else { w.sep = ", " w.suffix = "," itemOpts := o | skipTypes for i := 0; i < r.Len(); i++ { w.items = append( w.items, reflectValue(itemOpts, p, r.Index(i)), ) } } if _, t, _ := withType(o); t { return nodeOf(reflectType(typ), "{", w, "}") } return nodeOf(prefix, "{", w, "}") } func reflectHidden(o opts, hidden string, r reflect.Value) node { if r.IsNil() { return reflectNil(o, true, r) } if _, t, _ := withType(o); t { return reflectType(r.Type()) } return nodeOf(hidden) } func reflectArray(o opts, p *pending, r reflect.Value) node { return reflectItems(o, p, fmt.Sprintf("[%d]", r.Len()), r) } func reflectChan(o opts, r reflect.Value) node { return reflectHidden(o, "chan", r) } func reflectFunc(o opts, r reflect.Value) node { return reflectHidden(o, "func()", r) } func reflectInterface(o opts, p *pending, r reflect.Value) node { if r.IsNil() { return reflectNil(o, false, r) } e := reflectValue(o&^skipTypes, p, r.Elem()) if _, t, _ := withType(o); !t { return e } return nodeOf( reflectType(r.Type()), "(", wrapper{items: []node{e}}, ")", ) } func reflectMap(o opts, p *pending, r reflect.Value) node { if r.IsNil() { return reflectNil(o, true, r) } var skeys []string itemOpts := o | skipTypes sv := make(map[string]reflect.Value) sn := make(map[string]node) for _, key := range r.MapKeys() { kn := reflectValue(itemOpts, p, key) knExt := reflectValue(itemOpts|_pointerValues, p, key) var b bytes.Buffer wr := writer{w: &b} fprint(&wr, 0, knExt) skey := b.String() skeys = append(skeys, skey) sv[skey] = key sn[skey] = kn } if o&randomMaps == 0 { sort.Strings(skeys) } w := wrapper{sep: ", ", suffix: ","} for _, skey := range skeys { vn := reflectValue(itemOpts, p, r.MapIndex(sv[skey])) w.items = append( w.items, nodeOf(sn[skey], ": ", vn), ) } if _, t, _ := withType(o); !t { return nodeOf("map{", w, "}") } return nodeOf(reflectType(r.Type()), "{", w, "}") } func reflectPointer(o opts, p *pending, r reflect.Value) node { if r.IsNil() { return reflectNil(o, true, r) } e := reflectValue(o, p, r.Elem()) if o&_pointerValues != 0 { e = nodeOf(e, "_", r.Pointer()) } if _, t, _ := withType(o); !t { return e } return nodeOf("*", e) } func reflectList(o opts, p *pending, r reflect.Value) node { if r.IsNil() { return reflectNil(o, true, r) } return reflectItems(o, p, "[]", r) } func reflectString(o opts, r reflect.Value) node { sv := r.String() s := str{val: strconv.Quote(sv)} if !strings.Contains(sv, "`") && strings.Contains(sv, "\n") { s.raw = fmt.Sprintf("`%s`", sv) } n := nodeOf(s) _, t, a := withType(o) if !t { return n } tn := reflectType(r.Type()) if !a && tn.parts[0] == "string" { return n } return nodeOf(tn, "(", wrapper{items: []node{n}}, ")") } func reflectStruct(o opts, p *pending, r reflect.Value) node { wr := wrapper{sep: ", ", suffix: ","} fieldOpts := o | skipTypes rt := r.Type() for i := 0; i < r.NumField(); i++ { name := rt.Field(i).Name fv := reflectValue(fieldOpts, p, r.FieldByName(name)) wr.items = append( wr.items, nodeOf(name, ": ", fv), ) } if _, t, _ := withType(o); !t { return nodeOf("{", wr, "}") } return nodeOf(reflectType(rt), "{", wr, "}") } func reflectUnsafePointer(o opts, r reflect.Value) node { if r.IsNil() { return reflectNil(o, false, r) } if _, _, a := withType(o); !a { return nodeOf("pointer") } return nodeOf(reflectType(r.Type()), "(pointer)") } func checkPending(p *pending, r reflect.Value) (applyRef func(node) node, ref node, isPending bool) { applyRef = func(n node) node { return n } switch r.Kind() { case reflect.Slice, reflect.Map, reflect.Ptr: default: return } if r.IsNil() { return } var nr nodeRef key := r.Pointer() nr, isPending = p.values[key] if isPending { nr.refCount++ p.values[key] = nr ref = nodeOf("r", nr.id) return } nr = nodeRef{id: p.idCounter} p.idCounter++ p.values[key] = nr applyRef = func(n node) node { nr = p.values[key] if nr.refCount > 0 { def := []interface{}{"r", nr.id, "="} pp := make([]interface{}, len(def)+len(n.parts)) copy(pp, def) copy(pp[len(def):], n.parts) n.parts = pp } delete(p.values, key) return n } return } func reflectValue(o opts, p *pending, r reflect.Value) node { applyRef, ref, isPending := checkPending(p, r) if isPending { return ref } var n node switch r.Kind() { case reflect.Bool: n = reflectPrimitive(o, r, r.Bool(), "bool") case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n = reflectPrimitive(o, r, r.Int(), "int") case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: n = reflectPrimitive(o, r, r.Uint()) case reflect.Float32, reflect.Float64: n = reflectPrimitive(o, r, r.Float()) case reflect.Complex64, reflect.Complex128: n = reflectPrimitive(o, r, r.Complex()) case reflect.Array: n = reflectArray(o, p, r) case reflect.Chan: n = reflectChan(o, r) case reflect.Func: n = reflectFunc(o, r) case reflect.Interface: n = reflectInterface(o, p, r) case reflect.Map: n = reflectMap(o, p, r) case reflect.Ptr: n = reflectPointer(o, p, r) case reflect.Slice: n = reflectList(o, p, r) case reflect.String: n = reflectString(o, r) case reflect.UnsafePointer: n = reflectUnsafePointer(o, r) default: n = reflectStruct(o, p, r) } return applyRef(n) }
reflect.go
0.618089
0.41484
reflect.go
starcoder
package expect import ( "encoding/json" "fmt" "regexp" "sort" mtjson "github.com/jefflinse/melatonin/json" ) // A Predicate is a function that takes a test result value and possibly returns an error. type Predicate func(interface{}) error // Then chains a new Predicate to run after the current Predicate. func (p Predicate) Then(next Predicate) Predicate { if next == nil { return p } return func(actual interface{}) error { if err := p(actual); err != nil { return err } return next(actual) } } // And chains a new Predicate to run after the current Predicate if the current Predicate succeeds. func (p Predicate) And(next Predicate) Predicate { return p.Then(next) } // Or chains a new Predicate to run after the current Predicate if the current Predicate fails. func (p Predicate) Or(next Predicate) Predicate { if next == nil { return p } return func(actual interface{}) error { if err := p(actual); err != nil { return next(actual) } return nil } } // Bool creates a predicate requiring a value to be a bool, optionally matching // against a set of values. func Bool(expected ...bool) Predicate { return func(actual interface{}) error { n, ok := actual.(bool) if !ok { return wrongTypeError(true, actual) } if len(expected) > 0 { for _, e := range expected { if err := compareBoolValues(e, n); err == nil { return nil } } return fmt.Errorf("expected one of %+v, got %t", expected, n) } return nil } } // Float creates a predicate requiring a value to be an floating point number, // optionally matching against a set of values. func Float(expected ...float64) Predicate { return func(actual interface{}) error { n, ok := toFloat(actual) if !ok { return wrongTypeError(float64(0), actual) } if len(expected) > 0 { for _, value := range expected { if n == value { return nil } } return fmt.Errorf("expected one of %+v, got %g", expected, n) } return nil } } // Int creates a predicate requiring a value to be an integer, optionally matching // against a set of values. func Int(expected ...int64) Predicate { return func(actual interface{}) error { n, ok := toInt(actual) if !ok { return wrongTypeError(expected, actual) } if len(expected) > 0 { for _, value := range expected { if n == value { return nil } } return fmt.Errorf("expected one of %+v, got %d", expected, n) } return nil } } // Map creates a predicate requiring a value to be a map, optionally matching // against a set of values. func Map(expected ...map[string]interface{}) Predicate { return func(actual interface{}) error { m, ok := actual.(map[string]interface{}) if !ok { return fmt.Errorf("expected map, got %T: %+v", actual, actual) } if len(expected) > 0 { for _, value := range expected { if errs := CompareValues(value, m, true); len(errs) == 0 { return nil } } return fmt.Errorf("expected one of %+v, got %+v", expected, m) } return nil } } // Pattern creates a predicate requiring a value to be a string that matches a // regular expression, optionally matching against a set of values. func Pattern(regex string) Predicate { r, err := regexp.Compile(regex) if err != nil { return func(interface{}) error { return fmt.Errorf("invalid regex: %q", regex) } } return Regex(r) } // Regex creates a predicate requiring a value to be a string that matches a // regular expression, optionally matching against a set of values. func Regex(regex *regexp.Regexp) Predicate { return String().Then(func(actual interface{}) error { s, _ := actual.(string) if !regex.MatchString(s) { return fmt.Errorf("expected to match pattern %q, got %q", regex.String(), s) } return nil }) } // Slice creates a predicate requiring a value to be a slice, optionally matching // against a set of values. func Slice(expected ...[]interface{}) Predicate { return func(actual interface{}) error { s, ok := actual.([]interface{}) if !ok { return fmt.Errorf("expected slice, got %T: %+v", actual, actual) } if len(expected) > 0 { for _, value := range expected { if errs := CompareValues(value, s, true); len(errs) == 0 { return nil } } return fmt.Errorf("expected one of %+v, got %+v", expected, s) } return nil } } // String creates a predicate requiring a value to be a string, optionally matching // against a set of values. func String(expected ...string) Predicate { return func(actual interface{}) error { s, ok := actual.(string) if !ok { return fmt.Errorf("expected string, got %T: %+v", actual, actual) } if len(expected) > 0 { for _, value := range expected { if s == value { return nil } } return fmt.Errorf("expected one of %+v, got %q", expected, s) } return nil } } // CompareValues compares an expected value to an actual value. func CompareValues(expected, actual interface{}, exactJSON bool) []*FailedPredicateError { errs := []*FailedPredicateError{} if expected == nil && actual != nil { errs = append(errs, failedPredicate(fmt.Errorf("expected nil, got %T: %+v", actual, actual))) } switch expectedValue := expected.(type) { case bool: if err := compareBoolValues(expectedValue, actual); err != nil { errs = append(errs, err) return errs } case *bool: if err := compareBoolValues(*expectedValue, actual); err != nil { errs = append(errs, err) return errs } case float64: if err := compareFloat64Values(expectedValue, actual); err != nil { errs = append(errs, err) return errs } case *float64: if err := compareFloat64Values(*expectedValue, actual); err != nil { errs = append(errs, err) return errs } case int64: if err := compareInt64Values(expectedValue, actual); err != nil { errs = append(errs, err) return errs } case *int64: if err := compareInt64Values(*expectedValue, actual); err != nil { errs = append(errs, err) return errs } case string: if err := compareStringValues(expectedValue, actual); err != nil { errs = append(errs, err) return errs } case *string: if err := compareStringValues(*expectedValue, actual); err != nil { errs = append(errs, err) return errs } case mtjson.Object, map[string]interface{}: ev, ok := expectedValue.(map[string]interface{}) if !ok { ev = map[string]interface{}(expectedValue.(mtjson.Object)) } return compareMapValues(ev, actual, exactJSON) case mtjson.Array, []interface{}: ev, ok := expectedValue.([]interface{}) if !ok { ev = []interface{}(expectedValue.(mtjson.Array)) } return compareSliceValues(ev, actual, exactJSON) case Predicate, func(interface{}) error: f, ok := expectedValue.(Predicate) if !ok { f = Predicate(expectedValue.(func(interface{}) error)) } if err := f(actual); err != nil { errs = append(errs, failedPredicate(err)) return errs } default: errs = append(errs, failedPredicate(fmt.Errorf("unexpected value type: %T", actual))) } return nil } // compareBoolValues compares an expected bool to an actual bool. func compareBoolValues(expected bool, actual interface{}) *FailedPredicateError { b, ok := actual.(bool) if !ok { return wrongTypeError(expected, actual) } if b != expected { return wrongValueError([]interface{}{expected}, actual) } return nil } // compareFloat64Values compares an expected float64 to an actual float64. func compareFloat64Values(expected float64, actual interface{}) *FailedPredicateError { n, ok := actual.(float64) if !ok { return wrongTypeError(expected, actual) } if n != expected { return wrongValueError([]interface{}{expected}, actual) } return nil } // compareInt64Values compares an expected int64 to an actual int64. func compareInt64Values(expected int64, actual interface{}) *FailedPredicateError { n, ok := actual.(int64) if !ok { f, ok := actual.(float64) if !ok { return wrongTypeError(expected, actual) } n, ok = floatToInt(f) if !ok { return wrongTypeError(expected, actual) } } if n != expected { return wrongValueError([]interface{}{expected}, actual) } return nil } // compareMapValues compares an expected JSON object to an actual JSON object. func compareMapValues(expected map[string]interface{}, actual interface{}, exact bool) []*FailedPredicateError { errs := []*FailedPredicateError{} m, ok := actual.(map[string]interface{}) if !ok { errs = append(errs, wrongTypeError(expected, actual)) return errs } if exact { if len(m) != len(expected) { j, err := json.MarshalIndent(m, "", " ") if err != nil { errs = append(errs, failedPredicate(err)) } errs = append(errs, failedPredicate(fmt.Errorf("expected %d fields, got %d:\n%+v", len(expected), len(m), string(j)))) return errs } expectedKeys := make([]string, 0, len(expected)) for k := range expected { expectedKeys = append(expectedKeys, k) } actualKeys := make([]string, 0, len(m)) for k := range m { actualKeys = append(actualKeys, k) } sort.Strings(expectedKeys) sort.Strings(actualKeys) for i := range expectedKeys { if expectedKeys[i] != actualKeys[i] { errs = append(errs, failedPredicate(fmt.Errorf("expected key %q, got %q: %+v", expectedKeys[i], actualKeys[i], m[actualKeys[i]]))) } } } for k, v := range expected { for _, err := range CompareValues(v, m[k], exact) { err.PushField(k) errs = append(errs, err) } } return errs } // compareSliceValues compares an expected slice to an actual slice. func compareSliceValues(expected []interface{}, actual interface{}, exact bool) []*FailedPredicateError { errs := []*FailedPredicateError{} a, ok := actual.([]interface{}) if !ok { errs = append(errs, wrongTypeError(expected, actual)) return errs } if len(a) < len(expected) { j, err := json.MarshalIndent(a, "", " ") if err != nil { errs = append(errs, failedPredicate(err)) } errs = append(errs, failedPredicate(fmt.Errorf("expected at least %d elements, got %d: %+v", len(expected), len(a), string(j)))) return errs } else if exact && len(a) > len(expected) { j, err := json.MarshalIndent(a, "", " ") if err != nil { errs = append(errs, failedPredicate(err)) } errs = append(errs, failedPredicate(fmt.Errorf("expected %d elements, got %d: %+v", len(expected), len(a), string(j)))) return errs } for i, v := range expected { for _, err := range CompareValues(v, a[i], exact) { err.PushField(fmt.Sprintf("[%d]", i)) errs = append(errs, err) } } return errs } // compareStringValues compares an expected string to an actual string. func compareStringValues(expected string, actual interface{}) *FailedPredicateError { s, ok := actual.(string) if !ok { return wrongTypeError(expected, actual) } if s != expected { return wrongValueError([]interface{}{expected}, actual) } return nil } func floatToInt(f float64) (int64, bool) { n := int64(f) return n, float64(n) == f } func toInt(v interface{}) (int64, bool) { switch v := v.(type) { case int64: return v, true case float64: return floatToInt(v) case float32: return floatToInt(float64(v)) case int: return int64(v), true case int8: return int64(v), true case int16: return int64(v), true case int32: return int64(v), true default: return 0, false } } func toFloat(v interface{}) (float64, bool) { switch v := v.(type) { case float64: return v, true case float32: return float64(v), true } if i, ok := toInt(v); ok { return float64(i), true } return 0, false }
expect/expect.go
0.755997
0.631566
expect.go
starcoder
package lib import ( "image" "image/draw" "math" lib_image "github.com/mchapman87501/go_mars_2020_img_utils/lib/image" lib_color "github.com/mchapman87501/go_mars_2020_img_utils/lib/image/color" ) // Compositor builds a composite image from constituent tile // images. type Compositor struct { Bounds image.Rectangle addedAreas []image.Rectangle Result *lib_image.CIELab } func NewCompositor(rect image.Rectangle) Compositor { return Compositor{ rect, []image.Rectangle{}, lib_image.NewCIELab(rect), } } // Add a new image. Adjust its colors as necessary to match // any overlapping image data that has already been composited. func (comp *Compositor) AddImage(image image.Image, subframeRect image.Rectangle) { adjustedImage := comp.matchColors(image, subframeRect) srcPoint := adjustedImage.Bounds().Min draw.Src.Draw(comp.Result, subframeRect, adjustedImage, srcPoint) comp.addedAreas = append(comp.addedAreas, subframeRect) } func (comp *Compositor) matchColors(tileImage image.Image, destRect image.Rectangle) image.Image { result := lib_image.CIELabFromImage(tileImage) adjustments := comp.makeValueAdjustmentMap(result, destRect) adjustColors(result, adjustments) return result } func (comp *Compositor) makeValueAdjustmentMap(tileImage *lib_image.CIELab, destRect image.Rectangle) *AdjustmentMap { // What is the tile image's origin in composite image coordinates? tileOrigin := tileImage.Bounds().Min // 'translate' the tile to destRect. tileOffset := destRect.Bounds().Min.Sub(tileOrigin) // Build an adjustment mapping, for all overlapping addedAreas, that // maps from result's pixel V channel to that of the corresponding // comp.Result pixel. result := NewAdjustmentMap() for _, rect := range comp.addedAreas { overlap := rect.Intersect(destRect) if !overlap.Empty() { for x := overlap.Min.X; x < overlap.Max.X; x++ { for y := overlap.Min.Y; y < overlap.Max.Y; y++ { srcPix := tileImage.CIELabAt(x-tileOffset.X, y-tileOffset.Y) targetPix := comp.Result.CIELabAt(x, y) result.AddSample(srcPix, targetPix) } } } } result.Complete() return result } func adjustColors(image *lib_image.CIELab, adjustments *AdjustmentMap) { lInterp := NewFloat64Interpolator(adjustments.L) aInterp := NewFloat64Interpolator(adjustments.A) bInterp := NewFloat64Interpolator(adjustments.B) for y := image.Bounds().Min.Y; y < image.Bounds().Max.Y; y++ { for x := image.Bounds().Min.X; x < image.Bounds().Max.X; x++ { pix := image.CIELabAt(x, y) pix.L = lInterp.Interp(pix.L) pix.A = aInterp.Interp(pix.A) pix.B = bInterp.Interp(pix.B) image.SetCIELab(x, y, pix) } } } // Compress the dynamic range of the result image to make it more likely that // it will fit within the sRGB color gamut. // sRGB bounding cube, from image/color/print_srgb_gamut.py, is roughly // {'labL': [0.0, 99.99998453333127], 'laba': [-86.1829494051608, 98.23532017664644], 'labb': [-107.86546414496824, 94.47731817969378]} type LabBounds struct { Min lib_color.CIELab Max lib_color.CIELab } func (comp *Compositor) CompressDynamicRange() { compressAsNeeded(getDynamicRange(comp.Result), comp.Result) } func getDynamicRange(image *lib_image.CIELab) LabBounds { min := lib_color.CIELab{L: 100.0, A: 127.0, B: 127.0} max := lib_color.CIELab{L: 0.0, A: -128.0, B: -128.0} for y := image.Bounds().Min.Y; y < image.Bounds().Max.Y; y++ { for x := image.Bounds().Min.X; x < image.Bounds().Max.X; x++ { pix := image.CIELabAt(x, y) if pix.A > max.A { max.A = pix.A } if pix.A < min.A { min.A = pix.A } if pix.B > max.B { max.B = pix.B } if pix.B < min.B { min.B = pix.B } } } // Special case for Lab L: Adjust exposure so that some large fraction // of pixels are within gamut. exposure := NewImageExposure(image) min.L = exposure.cdf(0.0) max.L = exposure.cdf(0.95) return LabBounds{Min: min, Max: max} } type channelGetter func(p *lib_color.CIELab) float64 type channelSetter func(p *lib_color.CIELab, v float64) type scaler struct { MinIn, MinOut, Scale float64 getChan channelGetter setChan channelSetter } func newScaler( minIn, minOut, maxIn, maxOut float64, getChan channelGetter, setChan channelSetter) scaler { // Is the input already in bounds? if (minIn >= minOut) && (maxIn <= maxOut) { return scaler{minIn, minIn, 1.0, nil, nil} } dIn := maxIn - minIn dOut := maxOut - minOut if dIn <= 0.0 { return scaler{minIn, minIn, 1.0, nil, nil} } scale := dOut / dIn return scaler{minIn, minOut, scale, getChan, setChan} } func (s *scaler) UpdatePix(p *lib_color.CIELab) { v := s.getChan(p) vNew := (v-s.MinIn)*s.Scale + s.MinOut s.setChan(p, vNew) } func (s *scaler) isIdentity() bool { dMin := math.Abs(s.MinOut - s.MinIn) return (dMin <= 1.0e-6) && (math.Abs(s.Scale-1.0) <= 1.0e-6) } // Compress dynamic range as needed, to fit sRGB gamut. // NOTE that this naive implementation is sensitive to outliers. // Probably better to use a method, for L channel at least, // that ensures some fraction f of pixels are unclipped. func compressAsNeeded(imageRange LabBounds, image *lib_image.CIELab) { // {'labL': [0.0, 99.99998453333127], 'laba': [-86.1829494051608, 98.23532017664644], 'labb': [-107.86546414496824, 94.47731817969378]} minRGB := lib_color.CIELab{L: 0.0, A: -86.0, B: -107.0} maxRGB := lib_color.CIELab{L: 100.0, A: 98.0, B: 94.0} scalers := []scaler{} getL := func(p *lib_color.CIELab) float64 { return p.L } setL := func(p *lib_color.CIELab, v float64) { p.L = v } lScaler := newScaler(imageRange.Min.L, minRGB.L, imageRange.Max.L, maxRGB.L, getL, setL) if !lScaler.isIdentity() { scalers = append(scalers, lScaler) } getA := func(p *lib_color.CIELab) float64 { return p.A } setA := func(p *lib_color.CIELab, v float64) { p.A = v } aScaler := newScaler(imageRange.Min.A, minRGB.A, imageRange.Max.A, maxRGB.A, getA, setA) if !aScaler.isIdentity() { scalers = append(scalers, aScaler) } getB := func(p *lib_color.CIELab) float64 { return p.B } setB := func(p *lib_color.CIELab, v float64) { p.B = v } bScaler := newScaler(imageRange.Min.B, minRGB.B, imageRange.Max.B, maxRGB.B, getB, setB) if !bScaler.isIdentity() { scalers = append(scalers, bScaler) } compressChannels(image, scalers) } func compressChannels(image *lib_image.CIELab, scalers []scaler) { if len(scalers) > 0 { for y := image.Bounds().Min.Y; y < image.Bounds().Max.Y; y++ { for x := image.Bounds().Min.X; x < image.Bounds().Max.X; x++ { pix := image.CIELabAt(x, y) for _, s := range scalers { s.UpdatePix(&pix) } image.SetCIELab(x, y, pix) } } } }
lib/compositor.go
0.731251
0.603202
compositor.go
starcoder
package jen // Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order. func Parens(item ...Code) *Statement { return newStatement().Parens(item...) } // Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order. func (g *Group) Parens(item ...Code) *Statement { s := Parens(item...) g.items = append(g.items, s) return s } // Parens renders a single item in parenthesis. Use for type conversion or to specify evaluation order. func (s *Statement) Parens(item ...Code) *Statement { g := &Group{ close: ")", items: item, multi: true, name: "parens", open: "(", separator: "", } *s = append(*s, g) return s } // ParensFunc renders a single item in parenthesis. Use for type conversion or to specify evaluation order. func ParensFunc(f func(*Group)) *Statement { return newStatement().ParensFunc(f) } // ParensFunc renders a single item in parenthesis. Use for type conversion or to specify evaluation order. func (g *Group) ParensFunc(f func(*Group)) *Statement { s := ParensFunc(f) g.items = append(g.items, s) return s } // ParensFunc renders a single item in parenthesis. Use for type conversion or to specify evaluation order. func (s *Statement) ParensFunc(f func(*Group)) *Statement { g := &Group{ close: ")", multi: true, name: "parens", open: "(", separator: "", } f(g) *s = append(*s, g) return s } // List renders a comma separated list. Use for multiple return functions. func List(items ...Code) *Statement { return newStatement().List(items...) } // List renders a comma separated list. Use for multiple return functions. func (g *Group) List(items ...Code) *Statement { s := List(items...) g.items = append(g.items, s) return s } // List renders a comma separated list. Use for multiple return functions. func (s *Statement) List(items ...Code) *Statement { g := &Group{ close: "", items: items, multi: false, name: "list", open: "", separator: ",", } *s = append(*s, g) return s } // ListFunc renders a comma separated list. Use for multiple return functions. func ListFunc(f func(*Group)) *Statement { return newStatement().ListFunc(f) } // ListFunc renders a comma separated list. Use for multiple return functions. func (g *Group) ListFunc(f func(*Group)) *Statement { s := ListFunc(f) g.items = append(g.items, s) return s } // ListFunc renders a comma separated list. Use for multiple return functions. func (s *Statement) ListFunc(f func(*Group)) *Statement { g := &Group{ close: "", multi: false, name: "list", open: "", separator: ",", } f(g) *s = append(*s, g) return s } // Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions. func Index(items ...Code) *Statement { return newStatement().Index(items...) } // Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions. func (g *Group) Index(items ...Code) *Statement { s := Index(items...) g.items = append(g.items, s) return s } // Index renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions. func (s *Statement) Index(items ...Code) *Statement { g := &Group{ close: "]", items: items, multi: false, name: "index", open: "[", separator: ":", } *s = append(*s, g) return s } // IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions. func IndexFunc(f func(*Group)) *Statement { return newStatement().IndexFunc(f) } // IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions. func (g *Group) IndexFunc(f func(*Group)) *Statement { s := IndexFunc(f) g.items = append(g.items, s) return s } // IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions. func (s *Statement) IndexFunc(f func(*Group)) *Statement { g := &Group{ close: "]", multi: false, name: "index", open: "[", separator: ":", } f(g) *s = append(*s, g) return s } // Block renders a statement list enclosed by curly braces. Use for code blocks. func Block(statements ...Code) *Statement { return newStatement().Block(statements...) } // Block renders a statement list enclosed by curly braces. Use for code blocks. func (g *Group) Block(statements ...Code) *Statement { s := Block(statements...) g.items = append(g.items, s) return s } // Block renders a statement list enclosed by curly braces. Use for code blocks. func (s *Statement) Block(statements ...Code) *Statement { g := &Group{ close: "}", items: statements, multi: true, name: "block", open: "{", separator: "", } *s = append(*s, g) return s } // BlockFunc renders a statement list enclosed by curly braces. Use for code blocks. func BlockFunc(f func(*Group)) *Statement { return newStatement().BlockFunc(f) } // BlockFunc renders a statement list enclosed by curly braces. Use for code blocks. func (g *Group) BlockFunc(f func(*Group)) *Statement { s := BlockFunc(f) g.items = append(g.items, s) return s } // BlockFunc renders a statement list enclosed by curly braces. Use for code blocks. func (s *Statement) BlockFunc(f func(*Group)) *Statement { g := &Group{ close: "}", multi: true, name: "block", open: "{", separator: "", } f(g) *s = append(*s, g) return s } // Defs renders a statement list enclosed in parenthesis. Use for definition lists. func Defs(definitions ...Code) *Statement { return newStatement().Defs(definitions...) } // Defs renders a statement list enclosed in parenthesis. Use for definition lists. func (g *Group) Defs(definitions ...Code) *Statement { s := Defs(definitions...) g.items = append(g.items, s) return s } // Defs renders a statement list enclosed in parenthesis. Use for definition lists. func (s *Statement) Defs(definitions ...Code) *Statement { g := &Group{ close: ")", items: definitions, multi: true, name: "defs", open: "(", separator: "", } *s = append(*s, g) return s } // DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists. func DefsFunc(f func(*Group)) *Statement { return newStatement().DefsFunc(f) } // DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists. func (g *Group) DefsFunc(f func(*Group)) *Statement { s := DefsFunc(f) g.items = append(g.items, s) return s } // DefsFunc renders a statement list enclosed in parenthesis. Use for definition lists. func (s *Statement) DefsFunc(f func(*Group)) *Statement { g := &Group{ close: ")", multi: true, name: "defs", open: "(", separator: "", } f(g) *s = append(*s, g) return s } // Call renders a comma separated list enclosed by parenthesis. Use for function calls. func Call(params ...Code) *Statement { return newStatement().Call(params...) } // Call renders a comma separated list enclosed by parenthesis. Use for function calls. func (g *Group) Call(params ...Code) *Statement { s := Call(params...) g.items = append(g.items, s) return s } // Call renders a comma separated list enclosed by parenthesis. Use for function calls. func (s *Statement) Call(params ...Code) *Statement { g := &Group{ close: ")", items: params, multi: false, name: "call", open: "(", separator: ",", } *s = append(*s, g) return s } // CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls. func CallFunc(f func(*Group)) *Statement { return newStatement().CallFunc(f) } // CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls. func (g *Group) CallFunc(f func(*Group)) *Statement { s := CallFunc(f) g.items = append(g.items, s) return s } // CallFunc renders a comma separated list enclosed by parenthesis. Use for function calls. func (s *Statement) CallFunc(f func(*Group)) *Statement { g := &Group{ close: ")", multi: false, name: "call", open: "(", separator: ",", } f(g) *s = append(*s, g) return s } // Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers. func Params(params ...Code) *Statement { return newStatement().Params(params...) } // Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers. func (g *Group) Params(params ...Code) *Statement { s := Params(params...) g.items = append(g.items, s) return s } // Params renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers. func (s *Statement) Params(params ...Code) *Statement { g := &Group{ close: ")", items: params, multi: false, name: "params", open: "(", separator: ",", } *s = append(*s, g) return s } // ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers. func ParamsFunc(f func(*Group)) *Statement { return newStatement().ParamsFunc(f) } // ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers. func (g *Group) ParamsFunc(f func(*Group)) *Statement { s := ParamsFunc(f) g.items = append(g.items, s) return s } // ParamsFunc renders a comma separated list enclosed by parenthesis. Use for function parameters and method receivers. func (s *Statement) ParamsFunc(f func(*Group)) *Statement { g := &Group{ close: ")", multi: false, name: "params", open: "(", separator: ",", } f(g) *s = append(*s, g) return s } // Cast renders a period followed by a single item enclosed by parenthesis. Use for type casting. func Cast(typ Code) *Statement { return newStatement().Cast(typ) } // Cast renders a period followed by a single item enclosed by parenthesis. Use for type casting. func (g *Group) Cast(typ Code) *Statement { s := Cast(typ) g.items = append(g.items, s) return s } // Cast renders a period followed by a single item enclosed by parenthesis. Use for type casting. func (s *Statement) Cast(typ Code) *Statement { g := &Group{ close: ")", items: []Code{typ}, multi: false, name: "cast", open: ".(", separator: "", } *s = append(*s, g) return s } // For renders the keyword followed by a semicolon separated list. func For(conditions ...Code) *Statement { return newStatement().For(conditions...) } // For renders the keyword followed by a semicolon separated list. func (g *Group) For(conditions ...Code) *Statement { s := For(conditions...) g.items = append(g.items, s) return s } // For renders the keyword followed by a semicolon separated list. func (s *Statement) For(conditions ...Code) *Statement { g := &Group{ close: "", items: conditions, multi: false, name: "for", open: "for ", separator: ";", } *s = append(*s, g) return s } // ForFunc renders the keyword followed by a semicolon separated list. func ForFunc(f func(*Group)) *Statement { return newStatement().ForFunc(f) } // ForFunc renders the keyword followed by a semicolon separated list. func (g *Group) ForFunc(f func(*Group)) *Statement { s := ForFunc(f) g.items = append(g.items, s) return s } // ForFunc renders the keyword followed by a semicolon separated list. func (s *Statement) ForFunc(f func(*Group)) *Statement { g := &Group{ close: "", multi: false, name: "for", open: "for ", separator: ";", } f(g) *s = append(*s, g) return s } // Set renders a set literal expression, i.e. a comma separated list enclosed by square brackets. func Set(items ...Code) *Statement { return newStatement().Set(items...) } // Set renders a set literal expression, i.e. a comma separated list enclosed by square brackets. func (g *Group) Set(items ...Code) *Statement { s := Set(items...) g.items = append(g.items, s) return s } // Set renders a set literal expression, i.e. a comma separated list enclosed by square brackets. func (s *Statement) Set(items ...Code) *Statement { g := &Group{ close: "]", items: items, multi: false, name: "set", open: "[", separator: ",", } *s = append(*s, g) return s } // SetFunc renders a set literal expression, i.e. a comma separated list enclosed by square brackets. func SetFunc(f func(*Group)) *Statement { return newStatement().SetFunc(f) } // SetFunc renders a set literal expression, i.e. a comma separated list enclosed by square brackets. func (g *Group) SetFunc(f func(*Group)) *Statement { s := SetFunc(f) g.items = append(g.items, s) return s } // SetFunc renders a set literal expression, i.e. a comma separated list enclosed by square brackets. func (s *Statement) SetFunc(f func(*Group)) *Statement { g := &Group{ close: "]", multi: false, name: "set", open: "[", separator: ",", } f(g) *s = append(*s, g) return s } // Any renders an `any` expression. func Any(vars Code, formula Code, expression Code) *Statement { return newStatement().Any(vars, formula, expression) } // Any renders an `any` expression. func (g *Group) Any(vars Code, formula Code, expression Code) *Statement { s := Any(vars, formula, expression) g.items = append(g.items, s) return s } // Any renders an `any` expression. func (s *Statement) Any(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "any", open: "any(", separator: " | ", } *s = append(*s, g) return s } // Exists renders the `exists` quantifier. func Exists(vars Code, formula1 Code, formula2 Code) *Statement { return newStatement().Exists(vars, formula1, formula2) } // Exists renders the `exists` quantifier. func (g *Group) Exists(vars Code, formula1 Code, formula2 Code) *Statement { s := Exists(vars, formula1, formula2) g.items = append(g.items, s) return s } // Exists renders the `exists` quantifier. func (s *Statement) Exists(vars Code, formula1 Code, formula2 Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula1, formula2}, multi: true, name: "exists", open: "exists(", separator: " | ", } *s = append(*s, g) return s } // ForAll renders the `forall` quantifier. func ForAll(vars Code, formula1 Code, formula2 Code) *Statement { return newStatement().ForAll(vars, formula1, formula2) } // ForAll renders the `forall` quantifier. func (g *Group) ForAll(vars Code, formula1 Code, formula2 Code) *Statement { s := ForAll(vars, formula1, formula2) g.items = append(g.items, s) return s } // ForAll renders the `forall` quantifier. func (s *Statement) ForAll(vars Code, formula1 Code, formula2 Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula1, formula2}, multi: true, name: "forall", open: "forall(", separator: " | ", } *s = append(*s, g) return s } // ForEx renders the `forex` quantifier. func ForEx(vars Code, formula1 Code, formula2 Code) *Statement { return newStatement().ForEx(vars, formula1, formula2) } // ForEx renders the `forex` quantifier. func (g *Group) ForEx(vars Code, formula1 Code, formula2 Code) *Statement { s := ForEx(vars, formula1, formula2) g.items = append(g.items, s) return s } // ForEx renders the `forex` quantifier. func (s *Statement) ForEx(vars Code, formula1 Code, formula2 Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula1, formula2}, multi: true, name: "forex", open: "forex(", separator: " | ", } *s = append(*s, g) return s } // Count renders a `count` aggregator. func Count(vars Code, formula Code, expression Code) *Statement { return newStatement().Count(vars, formula, expression) } // Count renders a `count` aggregator. func (g *Group) Count(vars Code, formula Code, expression Code) *Statement { s := Count(vars, formula, expression) g.items = append(g.items, s) return s } // Count renders a `count` aggregator. func (s *Statement) Count(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "count", open: "count(", separator: " | ", } *s = append(*s, g) return s } // Min renders a `min` aggregator. func Min(vars Code, formula Code, expression Code) *Statement { return newStatement().Min(vars, formula, expression) } // Min renders a `min` aggregator. func (g *Group) Min(vars Code, formula Code, expression Code) *Statement { s := Min(vars, formula, expression) g.items = append(g.items, s) return s } // Min renders a `min` aggregator. func (s *Statement) Min(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "min", open: "min(", separator: " | ", } *s = append(*s, g) return s } // Max renders a `max` aggregator. func Max(vars Code, formula Code, expression Code) *Statement { return newStatement().Max(vars, formula, expression) } // Max renders a `max` aggregator. func (g *Group) Max(vars Code, formula Code, expression Code) *Statement { s := Max(vars, formula, expression) g.items = append(g.items, s) return s } // Max renders a `max` aggregator. func (s *Statement) Max(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "max", open: "max(", separator: " | ", } *s = append(*s, g) return s } // Avg renders an `avg` aggregator. func Avg(vars Code, formula Code, expression Code) *Statement { return newStatement().Avg(vars, formula, expression) } // Avg renders an `avg` aggregator. func (g *Group) Avg(vars Code, formula Code, expression Code) *Statement { s := Avg(vars, formula, expression) g.items = append(g.items, s) return s } // Avg renders an `avg` aggregator. func (s *Statement) Avg(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "avg", open: "avg(", separator: " | ", } *s = append(*s, g) return s } // Sum renders a `sum` aggregator. func Sum(vars Code, formula Code, expression Code) *Statement { return newStatement().Sum(vars, formula, expression) } // Sum renders a `sum` aggregator. func (g *Group) Sum(vars Code, formula Code, expression Code) *Statement { s := Sum(vars, formula, expression) g.items = append(g.items, s) return s } // Sum renders a `sum` aggregator. func (s *Statement) Sum(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "sum", open: "sum(", separator: " | ", } *s = append(*s, g) return s } // Concat renders a `concat` aggregator. func Concat(vars Code, formula Code, expression Code) *Statement { return newStatement().Concat(vars, formula, expression) } // Concat renders a `concat` aggregator. func (g *Group) Concat(vars Code, formula Code, expression Code) *Statement { s := Concat(vars, formula, expression) g.items = append(g.items, s) return s } // Concat renders a `concat` aggregator. func (s *Statement) Concat(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "concat", open: "concat(", separator: " | ", } *s = append(*s, g) return s } // Unique renders a `unique` aggregator. func Unique(vars Code, formula Code, expression Code) *Statement { return newStatement().Unique(vars, formula, expression) } // Unique renders a `unique` aggregator. func (g *Group) Unique(vars Code, formula Code, expression Code) *Statement { s := Unique(vars, formula, expression) g.items = append(g.items, s) return s } // Unique renders a `unique` aggregator. func (s *Statement) Unique(vars Code, formula Code, expression Code) *Statement { g := &Group{ close: ")", items: []Code{vars, formula, expression}, multi: true, name: "unique", open: "unique(", separator: " | ", } *s = append(*s, g) return s } // Boolean renders the `boolean` identifier. func Boolean() *Statement { return newStatement().Boolean() } // Boolean renders the `boolean` identifier. func (g *Group) Boolean() *Statement { s := Boolean() g.items = append(g.items, s) return s } // Boolean renders the `boolean` identifier. func (s *Statement) Boolean() *Statement { t := token{ content: "boolean", typ: identifierToken, } *s = append(*s, t) return s } // True renders the `true` identifier. func True() *Statement { // notest return newStatement().True() } // True renders the `true` identifier. func (g *Group) True() *Statement { // notest s := True() g.items = append(g.items, s) return s } // True renders the `true` identifier. func (s *Statement) True() *Statement { // notest t := token{ content: "true", typ: identifierToken, } *s = append(*s, t) return s } // False renders the `false` identifier. func False() *Statement { // notest return newStatement().False() } // False renders the `false` identifier. func (g *Group) False() *Statement { // notest s := False() g.items = append(g.items, s) return s } // False renders the `false` identifier. func (s *Statement) False() *Statement { // notest t := token{ content: "false", typ: identifierToken, } *s = append(*s, t) return s } // Float renders the `float` identifier. func Float() *Statement { // notest return newStatement().Float() } // Float renders the `float` identifier. func (g *Group) Float() *Statement { // notest s := Float() g.items = append(g.items, s) return s } // Float renders the `float` identifier. func (s *Statement) Float() *Statement { // notest t := token{ content: "float", typ: identifierToken, } *s = append(*s, t) return s } // Int renders the `int` identifier. func Int() *Statement { // notest return newStatement().Int() } // Int renders the `int` identifier. func (g *Group) Int() *Statement { // notest s := Int() g.items = append(g.items, s) return s } // Int renders the `int` identifier. func (s *Statement) Int() *Statement { // notest t := token{ content: "int", typ: identifierToken, } *s = append(*s, t) return s } // String renders the `string` identifier. func String() *Statement { // notest return newStatement().String() } // String renders the `string` identifier. func (g *Group) String() *Statement { // notest s := String() g.items = append(g.items, s) return s } // String renders the `string` identifier. func (s *Statement) String() *Statement { // notest t := token{ content: "string", typ: identifierToken, } *s = append(*s, t) return s } // Date renders the `date` identifier. func Date() *Statement { // notest return newStatement().Date() } // Date renders the `date` identifier. func (g *Group) Date() *Statement { // notest s := Date() g.items = append(g.items, s) return s } // Date renders the `date` identifier. func (s *Statement) Date() *Statement { // notest t := token{ content: "date", typ: identifierToken, } *s = append(*s, t) return s } // Abstract renders the `abstract` keyword. func Abstract() *Statement { // notest return newStatement().Abstract() } // Abstract renders the `abstract` keyword. func (g *Group) Abstract() *Statement { // notest s := Abstract() g.items = append(g.items, s) return s } // Abstract renders the `abstract` keyword. func (s *Statement) Abstract() *Statement { // notest t := token{ content: "abstract", typ: keywordToken, } *s = append(*s, t) return s } // And renders the `and` keyword. func And() *Statement { // notest return newStatement().And() } // And renders the `and` keyword. func (g *Group) And() *Statement { // notest s := And() g.items = append(g.items, s) return s } // And renders the `and` keyword. func (s *Statement) And() *Statement { // notest t := token{ content: "and", typ: keywordToken, } *s = append(*s, t) return s } // As renders the `as` keyword. func As() *Statement { // notest return newStatement().As() } // As renders the `as` keyword. func (g *Group) As() *Statement { // notest s := As() g.items = append(g.items, s) return s } // As renders the `as` keyword. func (s *Statement) As() *Statement { // notest t := token{ content: "as", typ: keywordToken, } *s = append(*s, t) return s } // Asc renders the `asc` keyword. func Asc() *Statement { // notest return newStatement().Asc() } // Asc renders the `asc` keyword. func (g *Group) Asc() *Statement { // notest s := Asc() g.items = append(g.items, s) return s } // Asc renders the `asc` keyword. func (s *Statement) Asc() *Statement { // notest t := token{ content: "asc", typ: keywordToken, } *s = append(*s, t) return s } // Class renders the `class` keyword. func Class() *Statement { // notest return newStatement().Class() } // Class renders the `class` keyword. func (g *Group) Class() *Statement { // notest s := Class() g.items = append(g.items, s) return s } // Class renders the `class` keyword. func (s *Statement) Class() *Statement { // notest t := token{ content: "class", typ: keywordToken, } *s = append(*s, t) return s } // Desc renders the `desc` keyword. func Desc() *Statement { // notest return newStatement().Desc() } // Desc renders the `desc` keyword. func (g *Group) Desc() *Statement { // notest s := Desc() g.items = append(g.items, s) return s } // Desc renders the `desc` keyword. func (s *Statement) Desc() *Statement { // notest t := token{ content: "desc", typ: keywordToken, } *s = append(*s, t) return s } // Else renders the `else` keyword. func Else() *Statement { // notest return newStatement().Else() } // Else renders the `else` keyword. func (g *Group) Else() *Statement { // notest s := Else() g.items = append(g.items, s) return s } // Else renders the `else` keyword. func (s *Statement) Else() *Statement { // notest t := token{ content: "else", typ: keywordToken, } *s = append(*s, t) return s } // Extends renders the `extends` keyword. func Extends() *Statement { // notest return newStatement().Extends() } // Extends renders the `extends` keyword. func (g *Group) Extends() *Statement { // notest s := Extends() g.items = append(g.items, s) return s } // Extends renders the `extends` keyword. func (s *Statement) Extends() *Statement { // notest t := token{ content: "extends", typ: keywordToken, } *s = append(*s, t) return s } // If renders the `if` keyword. func If() *Statement { // notest return newStatement().If() } // If renders the `if` keyword. func (g *Group) If() *Statement { // notest s := If() g.items = append(g.items, s) return s } // If renders the `if` keyword. func (s *Statement) If() *Statement { // notest t := token{ content: "if", typ: keywordToken, } *s = append(*s, t) return s } // Implies renders the `implies` keyword. func Implies() *Statement { // notest return newStatement().Implies() } // Implies renders the `implies` keyword. func (g *Group) Implies() *Statement { // notest s := Implies() g.items = append(g.items, s) return s } // Implies renders the `implies` keyword. func (s *Statement) Implies() *Statement { // notest t := token{ content: "implies", typ: keywordToken, } *s = append(*s, t) return s } // In renders the `in` keyword. func In() *Statement { // notest return newStatement().In() } // In renders the `in` keyword. func (g *Group) In() *Statement { // notest s := In() g.items = append(g.items, s) return s } // In renders the `in` keyword. func (s *Statement) In() *Statement { // notest t := token{ content: "in", typ: keywordToken, } *s = append(*s, t) return s } // Instanceof renders the `instanceof` keyword. func Instanceof() *Statement { // notest return newStatement().Instanceof() } // Instanceof renders the `instanceof` keyword. func (g *Group) Instanceof() *Statement { // notest s := Instanceof() g.items = append(g.items, s) return s } // Instanceof renders the `instanceof` keyword. func (s *Statement) Instanceof() *Statement { // notest t := token{ content: "instanceof", typ: keywordToken, } *s = append(*s, t) return s } // Module renders the `module` keyword. func Module() *Statement { // notest return newStatement().Module() } // Module renders the `module` keyword. func (g *Group) Module() *Statement { // notest s := Module() g.items = append(g.items, s) return s } // Module renders the `module` keyword. func (s *Statement) Module() *Statement { // notest t := token{ content: "module", typ: keywordToken, } *s = append(*s, t) return s } // Newtype renders the `newtype` keyword. func Newtype() *Statement { // notest return newStatement().Newtype() } // Newtype renders the `newtype` keyword. func (g *Group) Newtype() *Statement { // notest s := Newtype() g.items = append(g.items, s) return s } // Newtype renders the `newtype` keyword. func (s *Statement) Newtype() *Statement { // notest t := token{ content: "newtype", typ: keywordToken, } *s = append(*s, t) return s } // Not renders the `not` keyword. func Not() *Statement { // notest return newStatement().Not() } // Not renders the `not` keyword. func (g *Group) Not() *Statement { // notest s := Not() g.items = append(g.items, s) return s } // Not renders the `not` keyword. func (s *Statement) Not() *Statement { // notest t := token{ content: "not", typ: keywordToken, } *s = append(*s, t) return s } // Or renders the `or` keyword. func Or() *Statement { // notest return newStatement().Or() } // Or renders the `or` keyword. func (g *Group) Or() *Statement { // notest s := Or() g.items = append(g.items, s) return s } // Or renders the `or` keyword. func (s *Statement) Or() *Statement { // notest t := token{ content: "or", typ: keywordToken, } *s = append(*s, t) return s } // Override renders the `override` keyword. func Override() *Statement { // notest return newStatement().Override() } // Override renders the `override` keyword. func (g *Group) Override() *Statement { // notest s := Override() g.items = append(g.items, s) return s } // Override renders the `override` keyword. func (s *Statement) Override() *Statement { // notest t := token{ content: "override", typ: keywordToken, } *s = append(*s, t) return s } // Predicate renders the `predicate` keyword. func Predicate() *Statement { // notest return newStatement().Predicate() } // Predicate renders the `predicate` keyword. func (g *Group) Predicate() *Statement { // notest s := Predicate() g.items = append(g.items, s) return s } // Predicate renders the `predicate` keyword. func (s *Statement) Predicate() *Statement { // notest t := token{ content: "predicate", typ: keywordToken, } *s = append(*s, t) return s } // Private renders the `private` keyword. func Private() *Statement { // notest return newStatement().Private() } // Private renders the `private` keyword. func (g *Group) Private() *Statement { // notest s := Private() g.items = append(g.items, s) return s } // Private renders the `private` keyword. func (s *Statement) Private() *Statement { // notest t := token{ content: "private", typ: keywordToken, } *s = append(*s, t) return s } // Query renders the `query` keyword. func Query() *Statement { // notest return newStatement().Query() } // Query renders the `query` keyword. func (g *Group) Query() *Statement { // notest s := Query() g.items = append(g.items, s) return s } // Query renders the `query` keyword. func (s *Statement) Query() *Statement { // notest t := token{ content: "query", typ: keywordToken, } *s = append(*s, t) return s } // Result renders the `result` keyword. func Result() *Statement { // notest return newStatement().Result() } // Result renders the `result` keyword. func (g *Group) Result() *Statement { // notest s := Result() g.items = append(g.items, s) return s } // Result renders the `result` keyword. func (s *Statement) Result() *Statement { // notest t := token{ content: "result", typ: keywordToken, } *s = append(*s, t) return s } // Then renders the `then` keyword. func Then() *Statement { // notest return newStatement().Then() } // Then renders the `then` keyword. func (g *Group) Then() *Statement { // notest s := Then() g.items = append(g.items, s) return s } // Then renders the `then` keyword. func (s *Statement) Then() *Statement { // notest t := token{ content: "then", typ: keywordToken, } *s = append(*s, t) return s } // This renders the `this` keyword. func This() *Statement { // notest return newStatement().This() } // This renders the `this` keyword. func (g *Group) This() *Statement { // notest s := This() g.items = append(g.items, s) return s } // This renders the `this` keyword. func (s *Statement) This() *Statement { // notest t := token{ content: "this", typ: keywordToken, } *s = append(*s, t) return s }
jen/generated.go
0.878835
0.483709
generated.go
starcoder
package output import ( "os" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeFile] = TypeSpec{ constructor: NewFile, Summary: ` Writes messages in line delimited format to a file.`, Description: ` Each message written is followed by a delimiter (defaults to '\n' if left empty) and when sending multipart messages (message batches) the last message ends with double delimiters. E.g. the messages "foo", "bar" and "baz" would be written as: ` + "```" + ` foo\n bar\n baz\n ` + "```" + ` Whereas a multipart message [ "foo", "bar", "baz" ] would be written as: ` + "```" + ` foo\n bar\n baz\n\n ` + "```" + ``, FieldSpecs: docs.FieldSpecs{ docs.FieldCommon("path", "The file to write to, if the file does not yet exist it will be created."), docs.FieldCommon("delimiter", "A custom delimiter to separate messages with. If left empty defaults to a line break."), }, Categories: []Category{ CategoryLocal, }, } } //------------------------------------------------------------------------------ // FileConfig contains configuration fields for the file based output type. type FileConfig struct { Path string `json:"path" yaml:"path"` Delim string `json:"delimiter" yaml:"delimiter"` } // NewFileConfig creates a new FileConfig with default values. func NewFileConfig() FileConfig { return FileConfig{ Path: "", Delim: "", } } //------------------------------------------------------------------------------ // NewFile creates a new File output type. func NewFile(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) { file, err := os.OpenFile(conf.File.Path, os.O_CREATE|os.O_RDWR|os.O_APPEND, os.FileMode(0666)) if err != nil { return nil, err } return NewLineWriter(file, true, []byte(conf.File.Delim), "file", log, stats) } //------------------------------------------------------------------------------
lib/output/file.go
0.640636
0.649023
file.go
starcoder
package main import ( "fmt" "math" "math/rand" "time" "github.com/Knetic/govaluate" "gonum.org/v1/gonum/integrate" ) // Expr is an expression type Expr struct { Expr string `label:"" desc:"Equation: use x for the x value, t for the time passed since the marbles were ran (incremented by TimeStep), and a for 10*sin(t) (swinging back and forth version of t)"` Val *govaluate.EvaluableExpression `view:"-" json:"-"` Params map[string]interface{} `view:"-" json:"-"` } // factorial variables const lim = 100 var randNum float64 var facts [lim]float64 // Integrate returns the integral of an expression func (ex *Expr) Integrate(min, max float64, h int) float64 { var vals []float64 sign := float64(1) diff := max - min if diff == 0 { return 0 } if diff < 0 { diff = -diff sign = -1 min, max = max, min } accuracy := 16 dx := diff / float64(accuracy) for x := min; x <= max; x += dx { vals = append(vals, ex.Eval(x, TheGraph.State.Time, h)) } if len(vals) != accuracy+1 { vals = append(vals, ex.Eval(max, TheGraph.State.Time, h)) } val := integrate.Romberg(vals, dx) return sign * val } // Compile gets an expression ready for evaluation. func (ex *Expr) Compile() error { expr, functions := ex.PrepareExpr(TheGraph.Functions) var err error ex.Val, err = govaluate.NewEvaluableExpressionWithFunctions(expr, functions) if HandleError(err) { ex.Val = nil return err } if ex.Params == nil { ex.Params = make(map[string]interface{}, 2) } ex.Params["π"] = math.Pi ex.Params["e"] = math.E return err } // Eval gives the y value of the function for given x, t and h value func (ex *Expr) Eval(x, t float64, h int) float64 { if ex.Expr == "" { return 0 } ex.Params["x"] = x ex.Params["t"] = t ex.Params["a"] = 10 * math.Sin(t) ex.Params["h"] = h yi, err := ex.Val.Evaluate(ex.Params) if HandleError(err) { return 0 } switch yi.(type) { case float64: return yi.(float64) default: TheGraph.Stop() HandleError(fmt.Errorf("expression %v is invalid, it is a %T value, should be a float64 value", ex.Expr, yi)) return 0 } } // EvalWithY calls eval but with a y value set func (ex *Expr) EvalWithY(x, t float64, h int, y float64) float64 { ex.Params["y"] = y return ex.Eval(x, t, h) } // EvalBool checks if a statement is true based on the x, y, t and h values func (ex *Expr) EvalBool(x, y, t float64, h int) bool { if ex.Expr == "" { return true } ex.Params["x"] = x ex.Params["t"] = t ex.Params["a"] = 10 * math.Sin(t) ex.Params["h"] = h ex.Params["y"] = y ri, err := ex.Val.Evaluate(ex.Params) if HandleError(err) { return true } switch ri.(type) { case bool: return ri.(bool) default: TheGraph.Stop() HandleError(fmt.Errorf("expression %v is invalid, it is a %T value, should be a bool value", ex.Expr, ri)) return false } } // FactorialMemoization is used to take the factorial for the fact() function func FactorialMemoization(n int) (res float64) { if n < 0 { return 1 } if facts[n] != 0 { res = facts[n] return res } if n > 0 { res = float64(n) * FactorialMemoization(n-1) return res } return 1 } // SetRandNum sets the random number used in the rand(v) function func SetRandNum() { rand.Seed(time.Now().UnixNano()) randNum = rand.Float64() }
expr.go
0.684897
0.446796
expr.go
starcoder
package dpos import "github.com/DxChainNetwork/godx/common" const ( // Fixed number of extra-data prefix bytes reserved for signer vanity extraVanity = 32 // Fixed number of extra-data suffix bytes reserved for signer seal extraSeal = 65 // Number of recent block signatures to keep in memory inmemorySignatures = 4096 // MaxValidatorSize indicates that the max number of validators in dpos consensus MaxValidatorSize = 21 // SafeSize indicates that the least number of validators in dpos consensus SafeSize = MaxValidatorSize*2/3 + 1 // ConsensusSize indicates that a confirmed block needs the least number of validators to approve ConsensusSize = MaxValidatorSize*2/3 + 1 // RewardRatioDenominator is the max value of reward ratio RewardRatioDenominator uint64 = 100 // ThawingEpochDuration defines that if user cancel candidates or vote, the deposit will be thawed after 2 epochs ThawingEpochDuration = 2 // eligibleValidatorDenominator defines the denominator of the minimum expected block. If a validator // produces block less than expected by this denominator, it is considered as ineligible. eligibleValidatorDenominator = 2 // BlockInterval indicates that a block will be produced every 10 seconds BlockInterval = int64(10) // EpochInterval indicates that a new epoch will be elected every a day EpochInterval = int64(86400) // MaxVoteCount is the maximum number of candidates that a vote transaction could // include MaxVoteCount = 30 ) var ( // Block reward in camel for successfully mining a block frontierBlockReward = common.NewBigIntUint64(1e18).MultInt64(5) // Block reward in camel for successfully mining a block upward from Byzantium byzantiumBlockReward = common.NewBigIntUint64(1e18).MultInt64(3) // Block reward in camel for successfully mining a block upward from Constantinople constantinopleBlockReward = common.NewBigIntUint64(1e18).MultInt64(2) // minDeposit defines the minimum deposit of candidate minDeposit = common.NewBigIntUint64(1e18).MultInt64(10000) )
consensus/dpos/defaults.go
0.520009
0.486271
defaults.go
starcoder
package typesutils import ( "errors" "reflect" ) // RecordSet is an approximation of models.RecordSet so as not to import models. type RecordSet interface { // ModelName returns the name of the model of this RecordSet ModelName() string // Ids returns the ids in this set of Records Ids() []int64 // Len returns the number of records in this RecordSet Len() int // IsEmpty returns true if this RecordSet has no records IsEmpty() bool } // IsZero returns true if the given value is the zero value of its type or nil func IsZero(value interface{}) bool { if value == nil { return true } if rc, ok := value.(RecordSet); ok { return rc.IsEmpty() } val := reflect.ValueOf(value) return reflect.DeepEqual(val.Interface(), reflect.Zero(val.Type()).Interface()) } var ( errBadComparisonType = errors.New("invalid type for comparison") errBadComparison = errors.New("incompatible types for comparison") ) type kind int const ( invalidKind kind = iota boolKind complexKind intKind floatKind stringKind uintKind ) func basicKind(v reflect.Value) (kind, error) { switch v.Kind() { case reflect.Bool: return boolKind, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return intKind, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return uintKind, nil case reflect.Float32, reflect.Float64: return floatKind, nil case reflect.Complex64, reflect.Complex128: return complexKind, nil case reflect.String: return stringKind, nil } return invalidKind, errBadComparisonType } // AreEqual returns true if both given values are equal. func AreEqual(arg1, arg2 interface{}) (bool, error) { v1 := reflect.ValueOf(arg1) k1, err := basicKind(v1) if err != nil { return false, err } v2 := reflect.ValueOf(arg2) k2, err := basicKind(v2) if err != nil { return false, err } truth := false if k1 != k2 { // Special case: Can compare integer values regardless of type's sign. switch { case k1 == intKind && k2 == uintKind: truth = v1.Int() >= 0 && uint64(v1.Int()) == v2.Uint() case k1 == uintKind && k2 == intKind: truth = v2.Int() >= 0 && v1.Uint() == uint64(v2.Int()) default: return false, errBadComparison } } else { switch k1 { case boolKind: truth = v1.Bool() == v2.Bool() case complexKind: truth = v1.Complex() == v2.Complex() case floatKind: truth = v1.Float() == v2.Float() case intKind: truth = v1.Int() == v2.Int() case stringKind: truth = v1.String() == v2.String() case uintKind: truth = v1.Uint() == v2.Uint() default: panic("invalid kind") } } if truth { return true, nil } return false, nil } // IsLessThan returns true if arg1 is less than arg2 // It panics if the kind of arg1 or arg2 is not a basic kind. func IsLessThan(arg1, arg2 interface{}) (bool, error) { v1 := reflect.ValueOf(arg1) k1, err := basicKind(v1) if err != nil { return false, err } v2 := reflect.ValueOf(arg2) k2, err := basicKind(v2) if err != nil { return false, err } truth := false if k1 != k2 { // Special case: Can compare integer values regardless of type's sign. switch { case k1 == intKind && k2 == uintKind: truth = v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() case k1 == uintKind && k2 == intKind: truth = v2.Int() >= 0 && v1.Uint() < uint64(v2.Int()) default: return false, errBadComparison } } else { switch k1 { case boolKind, complexKind: return false, errBadComparisonType case floatKind: truth = v1.Float() < v2.Float() case intKind: truth = v1.Int() < v2.Int() case stringKind: truth = v1.String() < v2.String() case uintKind: truth = v1.Uint() < v2.Uint() default: panic("invalid kind") } } return truth, nil }
doxa/tools/typesutils/typesutils.go
0.621541
0.455441
typesutils.go
starcoder
package gfx import ( "image" "image/draw" "math" ) // GeoPoint represents a geographic point with Lat/Lon. type GeoPoint struct { Lon float64 Lat float64 } // GP creates a new GeoPoint func GP(lat, lon float64) GeoPoint { return GeoPoint{Lon: lon, Lat: lat} } // Vec returns a vector for the geo point based on the given tileSize and zoom level. func (gp GeoPoint) Vec(tileSize, zoom int) Vec { scale := math.Pow(2, float64(zoom)) fts := float64(tileSize) return V( ((float64(gp.Lon)+180)/360)*scale*fts, (fts/2)-(fts*math.Log(math.Tan((Pi/4)+((float64(gp.Lat)*Pi/180)/2)))/(2*Pi))*scale, ) } // In returns a Vec for the position of the GeoPoint in a GeoTile. func (gp GeoPoint) In(gt GeoTile, tileSize int) Vec { return gt.Vec(gp, tileSize) } // GeoTile for the GeoPoint at the given zoom level. func (gp GeoPoint) GeoTile(zoom int) GeoTile { latRad := Degrees(gp.Lat).Radians() n := math.Pow(2, float64(zoom)) return GeoTile{ Zoom: zoom, X: int(n * (float64(gp.Lon) + 180) / 360), Y: int((1.0 - math.Log(math.Tan(latRad)+(1/math.Cos(latRad)))/Pi) / 2.0 * n), } } // NewGeoPointFromTileNumbers creates a new GeoPoint based on the given tile numbers. // https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_numbers_to_lon..2Flat. func NewGeoPointFromTileNumbers(zoom, x, y int) GeoPoint { n := math.Pow(2, float64(zoom)) latRad := math.Atan(math.Sinh(Pi * (1 - (2 * float64(y) / n)))) return GP(latRad*180/Pi, (float64(x)/n*360)-180) } // GeoTiles is a slice of GeoTile. type GeoTiles []GeoTile // GeoTile consists of a Zoom level, X and Y values. type GeoTile struct { Zoom int X int Y int } // GT creates a new GeoTile. func GT(zoom, x, y int) GeoTile { return GeoTile{Zoom: zoom, X: x, Y: y} } // GeoPoint for the GeoTile. func (gt GeoTile) GeoPoint() GeoPoint { n := math.Pow(2, float64(gt.Zoom)) latRad := math.Atan(math.Sinh(Pi * (1 - (2 * float64(gt.Y) / n)))) return GP(latRad*180/Pi, (float64(gt.X)/n*360)-180) } // Vec returns the Vec for the GeoPoint in the GeoTile. func (gt GeoTile) Vec(gp GeoPoint, tileSize int) Vec { return gp.Vec(tileSize, gt.Zoom).Sub(gt.GeoPoint().Vec(tileSize, gt.Zoom)) } // Rawurl formats a URL string with Zoom, X and Y. func (gt GeoTile) Rawurl(format string) string { return Sprintf(format, gt.Zoom, gt.X, gt.Y) } // AddXY adds x and y. func (gt GeoTile) AddXY(x, y int) GeoTile { return GT(gt.Zoom, gt.X+x, gt.Y+y) } // Neighbors returns the neighboring tiles. func (gt GeoTile) Neighbors() GeoTiles { return GeoTiles{ gt.N(), gt.NE(), gt.E(), gt.SE(), gt.S(), gt.SW(), gt.W(), gt.NW(), } } // N is the tile to the north. func (gt GeoTile) N() GeoTile { if gt.Zoom > 0 && gt.Y > 0 { gt.Y-- } return gt } // NE is the tile to the northeast. func (gt GeoTile) NE() GeoTile { if gt.Zoom > 0 { if gt.Y > 0 { gt.Y-- } gt.X++ } return gt } // E is the tile to the east. func (gt GeoTile) E() GeoTile { if gt.Zoom > 0 { gt.X++ } return gt } // SE is the tile to the southeast. func (gt GeoTile) SE() GeoTile { if gt.Zoom > 0 { gt.X++ gt.Y++ } return gt } // S is the tile to the south. func (gt GeoTile) S() GeoTile { if gt.Zoom > 0 { gt.Y++ } return gt } // SW is the tile to the southwest. func (gt GeoTile) SW() GeoTile { if gt.Zoom > 0 { if gt.X > 0 { gt.X-- } gt.Y++ } return gt } // W is the tile to the west. func (gt GeoTile) W() GeoTile { if gt.Zoom > 0 && gt.X > 0 { gt.X-- } return gt } // NW is the tile to the northwest. func (gt GeoTile) NW() GeoTile { if gt.Zoom > 0 { if gt.Y > 0 { gt.Y-- } if gt.X > 0 { gt.X-- } } return gt } // GetImage for the tile. func (gt GeoTile) GetImage(format string) (image.Image, error) { return GetImage(gt.Rawurl(format)) } // Draw the tile on dst. func (gt GeoTile) Draw(dst draw.Image, gp GeoPoint, src image.Image) { Draw(dst, gt.Bounds(dst, gp, src.Bounds().Dx()), src) } // Bounds returns an image.Rectangle for the GeoTile based on the dst, gp and tileSize. func (gt GeoTile) Bounds(dst image.Image, gp GeoPoint, tileSize int) image.Rectangle { c := BoundsCenter(dst.Bounds()) return dst.Bounds().Add(c.Pt()).Sub(gp.In(gt, tileSize).Pt()) } // GeoTileServer represents a tile server. type GeoTileServer struct { Format string } // GTS creates a GeoTileServer. func GTS(format string) GeoTileServer { return GeoTileServer{Format: format} } // GetImage for the given GeoTile from the tile server. func (gts GeoTileServer) GetImage(gt GeoTile) (image.Image, error) { return gt.GetImage(gts.Format) } // DrawTileAndNeighbors on dst. func (gts GeoTileServer) DrawTileAndNeighbors(dst draw.Image, gt GeoTile, gp GeoPoint) error { if err := gts.DrawTile(dst, gt, gp); err != nil { return nil } return gts.DrawNeighbors(dst, gt, gp) } // DrawTile on dst. func (gts GeoTileServer) DrawTile(dst draw.Image, gt GeoTile, gp GeoPoint) error { src, err := gts.GetImage(gt) if err != nil { return err } gt.Draw(dst, gp, src) return nil } // DrawNeighbors on dst. func (gts GeoTileServer) DrawNeighbors(dst draw.Image, gt GeoTile, gp GeoPoint) error { for _, n := range gt.Neighbors() { if err := gts.DrawTile(dst, n, gp); err != nil { return err } } return nil }
vendor/github.com/peterhellberg/gfx/geo.go
0.897712
0.703116
geo.go
starcoder
package h3 import ( "math" ) //lint:file-ignore U1000 Ignore all unused code // CoordIJK holds IJK hexagon coordinates. // Each axis is spaced 120 degrees apart. type CoordIJK struct { i int // i component j int // j component k int // k component } var ( // UNIT_VECS are CoordIJK unit vectors corresponding to the 7 H3 digits. UNIT_VECS = []CoordIJK{ {0, 0, 0}, // direction 0 {0, 0, 1}, // direction 1 {0, 1, 0}, // direction 2 {0, 1, 1}, // direction 3 {1, 0, 0}, // direction 4 {1, 0, 1}, // direction 5 {1, 1, 0}, // direction 6 } ) // Direction is H3 digit representing ijk+ axes direction. // Values will be within the lowest 3 bits of an integer. type Direction int const ( CENTER_DIGIT Direction = 0 // H3 digit in center K_AXES_DIGIT Direction = 1 // H3 digit in k-axes direction J_AXES_DIGIT Direction = 2 // H3 digit in j-axes direction JK_AXES_DIGIT = J_AXES_DIGIT | K_AXES_DIGIT // 3 - H3 digit in j == k direction I_AXES_DIGIT Direction = 4 // H3 digit in i-axes direction IK_AXES_DIGIT = I_AXES_DIGIT | K_AXES_DIGIT // 5 - H3 digit in i == k direction IJ_AXES_DIGIT = I_AXES_DIGIT | J_AXES_DIGIT // 6 - H3 digit in i == j direction INVALID_DIGIT Direction = 7 // H3 digit in the invalid direction NUM_DIGITS = INVALID_DIGIT // Valid digits will be less than this value. Same value as INVALID_DIGIT. ) // _setIJK sets an IJK coordinate to the specified component values. // `ijk`: The IJK coordinate to set. // `i`: The desired i component value. // `j`: The desired j component value. // `k`: The desired k component value. func _setIJK(ijk *CoordIJK, i int, j int, k int) { ijk.i = i ijk.j = j ijk.k = k } // _hex2dToCoordIJK determines the containing hex in ijk+ coordinates for a 2D cartesian // coordinate vector (from DGGRID). // `v`: The 2D cartesian coordinate vector. // `h`: The ijk+ coordinates of the containing hex. func _hex2dToCoordIJK(v *Vec2d, h *CoordIJK) { // quantize into the ij system and then normalize h.k = 0 a1 := math.Abs(v.x) a2 := math.Abs(v.y) // first do a reverse conversion x2 := a2 / M_SIN60 x1 := a1 + x2/2.0 // check if we have the center of a hex m1 := int(x1) m2 := int(x2) // otherwise round correctly r1 := x1 - float64(m1) r2 := x2 - float64(m2) if r1 < 0.5 { if r1 < 1.0/3.0 { if r2 < (1.0+r1)/2.0 { h.i = m1 h.j = m2 } else { h.i = m1 h.j = m2 + 1 } } else { if r2 < (1.0 - r1) { h.j = m2 } else { h.j = m2 + 1 } if (1.0-r1) <= r2 && r2 < (2.0*r1) { h.i = m1 + 1 } else { h.i = m1 } } } else { if r1 < 2.0/3.0 { if r2 < (1.0 - r1) { h.j = m2 } else { h.j = m2 + 1 } if (2.0*r1-1.0) < r2 && r2 < (1.0-r1) { h.i = m1 } else { h.i = m1 + 1 } } else { if r2 < (r1 / 2.0) { h.i = m1 + 1 h.j = m2 } else { h.i = m1 + 1 h.j = m2 + 1 } } } // now fold across the axes if necessary if v.x < 0.0 { if (h.j % 2) == 0 { // even var axisi = int64(h.j / 2) var diff = int64(h.i) - axisi h.i = int(int64(h.i) - 2*diff) } else { var axisi = int64((h.j + 1) / 2) var diff = int64(h.i) - axisi h.i = int(int64(h.i) - (2*diff + 1)) } } if v.y < 0.0 { h.i = h.i - (2*h.j+1)/2 h.j = -1 * h.j } _ijkNormalize(h) } // _ijkToHex2d finds the center point in 2D cartesian coordinates of a hex. // `h`: The ijk coordinates of the hex. // `v`: The 2D cartesian coordinates of the hex center point. func _ijkToHex2d(h *CoordIJK, v *Vec2d) { i := h.i - h.k j := h.j - h.k v.x = float64(i) - 0.5*float64(j) v.y = float64(j) * M_SQRT3_2 } // _ijkMatches returns whether or not two ijk coordinates contain exactly the same // component values. // `c1`: The first set of ijk coordinates. // `c2`: The second set of ijk coordinates. // Returns true if the two addresses match, false if they do not. func _ijkMatches(c1 *CoordIJK, c2 *CoordIJK) bool { return c1.i == c2.i && c1.j == c2.j && c1.k == c2.k } // _ijkAdd adds two ijk coordinates. // `h1`: The first set of ijk coordinates. // `h2`: The second set of ijk coordinates. // `sum`: The sum of the two sets of ijk coordinates. func _ijkAdd(h1 *CoordIJK, h2 *CoordIJK, sum *CoordIJK) { sum.i = h1.i + h2.i sum.j = h1.j + h2.j sum.k = h1.k + h2.k } // _ijkSub subtracts two ijk coordinates. // `h1`: The first set of ijk coordinates. // `h2`: The second set of ijk coordinates. // `diff`: The difference of the two sets of ijk coordinates (`h1` - `h2`). func _ijkSub(h1 *CoordIJK, h2 *CoordIJK, diff *CoordIJK) { diff.i = h1.i - h2.i diff.j = h1.j - h2.j diff.k = h1.k - h2.k } // _ijkScale uniformly scales ijk coordinates by a scalar. Works in place. // `c`: The ijk coordinates to scale. // `factor`: The scaling factor. func _ijkScale(c *CoordIJK, factor int) { c.i *= factor c.j *= factor c.k *= factor } // _ijkNormalize normalizes ijk coordinates by setting the components to the smallest possible // values. Works in place. // `c`: The ijk coordinates to normalize. func _ijkNormalize(c *CoordIJK) { // remove any negative values if c.i < 0 { c.j -= c.i c.k -= c.i c.i = 0 } if c.j < 0 { c.i -= c.j c.k -= c.j c.j = 0 } if c.k < 0 { c.i -= c.k c.j -= c.k c.k = 0 } // remove the min value if needed min := c.i if c.j < min { min = c.j } if c.k < min { min = c.k } if min > 0 { c.i -= min c.j -= min c.k -= min } } // _unitIjkToDigit determines the H3 digit corresponding to a unit vector in ijk coordinates. // `ijk`: The ijk coordinates; must be a unit vector. // Returns the H3 digit (0-6) corresponding to the ijk unit vector, or // INVALID_DIGIT on failure. func _unitIjkToDigit(ijk *CoordIJK) Direction { c := *ijk _ijkNormalize(&c) digit := INVALID_DIGIT for i := CENTER_DIGIT; i < NUM_DIGITS; i++ { if _ijkMatches(&c, &UNIT_VECS[i]) { digit = i break } } return digit } // _upAp7 finds the normalized ijk coordinates of the indexing parent of a cell in a // counter-clockwise aperture 7 grid. Works in place. // `ijk`: The ijk coordinates. func _upAp7(ijk *CoordIJK) { // convert to CoordIJ i := ijk.i - ijk.k j := ijk.j - ijk.k ijk.i = int(math.Round(float64(3*i-j) / 7.0)) ijk.j = int(math.Round(float64(i+2*j) / 7.0)) ijk.k = 0 _ijkNormalize(ijk) } // _upAp7r finds the normalized ijk coordinates of the indexing parent of a cell in a // clockwise aperture 7 grid. Works in place. // `ijk`: The ijk coordinates. func _upAp7r(ijk *CoordIJK) { // convert to CoordIJ i := ijk.i - ijk.k j := ijk.j - ijk.k ijk.i = int(math.Round(float64(2*i+j) / 7.0)) ijk.j = int(math.Round(float64(3*j-i) / 7.0)) ijk.k = 0 _ijkNormalize(ijk) } // _downAp7 finds the normalized ijk coordinates of the hex centered on the indicated // hex at the next finer aperture 7 counter-clockwise resolution. Works in // place. // `ijk`: The ijk coordinates. func _downAp7(ijk *CoordIJK) { // res r unit vectors in res r+1 iVec := CoordIJK{3, 0, 1} jVec := CoordIJK{1, 3, 0} kVec := CoordIJK{0, 1, 3} _ijkScale(&iVec, ijk.i) _ijkScale(&jVec, ijk.j) _ijkScale(&kVec, ijk.k) _ijkAdd(&iVec, &jVec, ijk) _ijkAdd(ijk, &kVec, ijk) _ijkNormalize(ijk) } // _downAp7r finds the normalized ijk coordinates of the hex centered on the indicated // hex at the next finer aperture 7 clockwise resolution. Works in place. // `ijk`: The ijk coordinates. func _downAp7r(ijk *CoordIJK) { // res r unit vectors in res r+1 iVec := CoordIJK{3, 1, 0} jVec := CoordIJK{0, 3, 1} kVec := CoordIJK{1, 0, 3} _ijkScale(&iVec, ijk.i) _ijkScale(&jVec, ijk.j) _ijkScale(&kVec, ijk.k) _ijkAdd(&iVec, &jVec, ijk) _ijkAdd(ijk, &kVec, ijk) _ijkNormalize(ijk) } // _neighbor finds the normalized ijk coordinates of the hex in the specified digit // direction from the specified ijk coordinates. Works in place. // `ijk`: The ijk coordinates. // `digit`: The digit direction from the original ijk coordinates. func _neighbor(ijk *CoordIJK, digit Direction) { if digit > CENTER_DIGIT && digit < NUM_DIGITS { _ijkAdd(ijk, &UNIT_VECS[digit], ijk) _ijkNormalize(ijk) } } // _ijkRotate60ccw rotates ijk coordinates 60 degrees counter-clockwise. Works in place. // `ijk`: The ijk coordinates. func _ijkRotate60ccw(ijk *CoordIJK) { // unit vector rotations iVec := CoordIJK{1, 1, 0} jVec := CoordIJK{0, 1, 1} kVec := CoordIJK{1, 0, 1} _ijkScale(&iVec, ijk.i) _ijkScale(&jVec, ijk.j) _ijkScale(&kVec, ijk.k) _ijkAdd(&iVec, &jVec, ijk) _ijkAdd(ijk, &kVec, ijk) _ijkNormalize(ijk) } // _ijkRotate60cw rotates ijk coordinates 60 degrees clockwise. Works in place. // `ijk`: The ijk coordinates. func _ijkRotate60cw(ijk *CoordIJK) { // unit vector rotations iVec := CoordIJK{1, 0, 1} jVec := CoordIJK{1, 1, 0} kVec := CoordIJK{0, 1, 1} _ijkScale(&iVec, ijk.i) _ijkScale(&jVec, ijk.j) _ijkScale(&kVec, ijk.k) _ijkAdd(&iVec, &jVec, ijk) _ijkAdd(ijk, &kVec, ijk) _ijkNormalize(ijk) } // _rotate60ccw rotates indexing digit 60 degrees counter-clockwise. Returns result. // `digit`: Indexing digit (between 1 and 6 inclusive) func _rotate60ccw(digit Direction) Direction { switch digit { case K_AXES_DIGIT: return IK_AXES_DIGIT case IK_AXES_DIGIT: return I_AXES_DIGIT case I_AXES_DIGIT: return IJ_AXES_DIGIT case IJ_AXES_DIGIT: return J_AXES_DIGIT case J_AXES_DIGIT: return JK_AXES_DIGIT case JK_AXES_DIGIT: return K_AXES_DIGIT default: return digit } } // _rotate60cw rotates indexing digit 60 degrees clockwise. Returns result. // `digit`: Indexing digit (between 1 and 6 inclusive) func _rotate60cw(digit Direction) Direction { switch digit { case K_AXES_DIGIT: return JK_AXES_DIGIT case JK_AXES_DIGIT: return J_AXES_DIGIT case J_AXES_DIGIT: return IJ_AXES_DIGIT case IJ_AXES_DIGIT: return I_AXES_DIGIT case I_AXES_DIGIT: return IK_AXES_DIGIT case IK_AXES_DIGIT: return K_AXES_DIGIT default: return digit } } // _downAp3 finds the normalized ijk coordinates of the hex centered on the indicated // hex at the next finer aperture 3 counter-clockwise resolution. Works in // place. // `ijk`: The ijk coordinates. func _downAp3(ijk *CoordIJK) { // res r unit vectors in res r+1 iVec := CoordIJK{2, 0, 1} jVec := CoordIJK{1, 2, 0} kVec := CoordIJK{0, 1, 2} _ijkScale(&iVec, ijk.i) _ijkScale(&jVec, ijk.j) _ijkScale(&kVec, ijk.k) _ijkAdd(&iVec, &jVec, ijk) _ijkAdd(ijk, &kVec, ijk) _ijkNormalize(ijk) } // _downAp3r finds the normalized ijk coordinates of the hex centered on the indicated // hex at the next finer aperture 3 clockwise resolution. Works in place. // `ijk`: The ijk coordinates. func _downAp3r(ijk *CoordIJK) { // res r unit vectors in res r+1 iVec := CoordIJK{2, 1, 0} jVec := CoordIJK{0, 2, 1} kVec := CoordIJK{1, 0, 2} _ijkScale(&iVec, ijk.i) _ijkScale(&jVec, ijk.j) _ijkScale(&kVec, ijk.k) _ijkAdd(&iVec, &jVec, ijk) _ijkAdd(ijk, &kVec, ijk) _ijkNormalize(ijk) } // ijkDistance finds the distance between the two coordinates. Returns result. // `c1`: The first set of ijk coordinates. // `c2`: The second set of ijk coordinates. func ijkDistance(c1 *CoordIJK, c2 *CoordIJK) int { var diff CoordIJK _ijkSub(c1, c2, &diff) _ijkNormalize(&diff) absDiff := CoordIJK{absInt(diff.i), absInt(diff.j), absInt(diff.k)} return maxInt(absDiff.i, maxInt(absDiff.j, absDiff.k)) } // ijkToIj transforms coordinates from the IJK+ coordinate system to the IJ coordinate // system. // `ijk`: The input IJK+ coordinates // `ij`: The output IJ coordinates func ijkToIj(ijk *CoordIJK, ij *CoordIJ) { ij.i = ijk.i - ijk.k ij.j = ijk.j - ijk.k } // ijToIjk transforms coordinates from the IJ coordinate system to the IJK+ coordinate // system. // `ij`: The input IJ coordinates // `ijk`: The output IJK+ coordinates func ijToIjk(ij *CoordIJ, ijk *CoordIJK) { ijk.i = ij.i ijk.j = ij.j ijk.k = 0 _ijkNormalize(ijk) } // ijkToCube converts IJK coordinates to cube coordinates, in place // `ijk`: Coordinate to convert func ijkToCube(ijk *CoordIJK) { ijk.i = -ijk.i + ijk.k ijk.j = ijk.j - ijk.k ijk.k = -ijk.i - ijk.j } // cubeToIjk convert cube coordinates to IJK coordinates, in place // `ijk`: Coordinate to convert func cubeToIjk(ijk *CoordIJK) { ijk.i = -ijk.i ijk.k = 0 _ijkNormalize(ijk) }
coordijk.go
0.681091
0.520374
coordijk.go
starcoder
package complete import ( "src.elv.sh/pkg/eval" "src.elv.sh/pkg/parse" ) type nodePath []parse.Node // Returns the path of Node's from n to a leaf at position p. Leaf first in the // returned slice. func findNodePath(root parse.Node, p int) nodePath { n := root descend: for len(parse.Children(n)) > 0 { for _, ch := range parse.Children(n) { if rg := ch.Range(); rg.From <= p && p <= rg.To { n = ch continue descend } } return nil } var path []parse.Node for { path = append(path, n) if n == root { break } n = parse.Parent(n) } return path } func (ns nodePath) match(ms ...nodesMatcher) bool { for _, m := range ms { ns2, ok := m.matchNodes(ns) if !ok { return false } ns = ns2 } return true } type nodesMatcher interface { // Matches from the beginning of nodes. Returns the remaining nodes and // whether the match succeeded. matchNodes([]parse.Node) ([]parse.Node, bool) } // Matches one node of a given type, without storing it. type typedMatcher[T parse.Node] struct{} func (m typedMatcher[T]) matchNodes(ns []parse.Node) ([]parse.Node, bool) { if len(ns) > 0 { if _, ok := ns[0].(T); ok { return ns[1:], true } } return nil, false } var ( aChunk = typedMatcher[*parse.Chunk]{} aPipeline = typedMatcher[*parse.Pipeline]{} aArray = typedMatcher[*parse.Array]{} aRedir = typedMatcher[*parse.Redir]{} aSep = typedMatcher[*parse.Sep]{} ) // Matches one node of a certain type, and stores it into a pointer. type storeMatcher[T parse.Node] struct{ p *T } func store[T parse.Node](p *T) nodesMatcher { return storeMatcher[T]{p} } func (m storeMatcher[T]) matchNodes(ns []parse.Node) ([]parse.Node, bool) { if len(ns) > 0 { if n, ok := ns[0].(T); ok { *m.p = n return ns[1:], true } } return nil, false } // Matches an expression that can be evaluated statically. Consumes 3 nodes // (Primary, Indexing and Compound). type simpleExprMatcher struct { ev *eval.Evaler s string compound *parse.Compound quote parse.PrimaryType } func simpleExpr(ev *eval.Evaler) *simpleExprMatcher { return &simpleExprMatcher{ev: ev} } func (m *simpleExprMatcher) matchNodes(ns []parse.Node) ([]parse.Node, bool) { if len(ns) < 3 { return nil, false } primary, ok := ns[0].(*parse.Primary) if !ok { return nil, false } indexing, ok := ns[1].(*parse.Indexing) if !ok { return nil, false } compound, ok := ns[2].(*parse.Compound) if !ok { return nil, false } s, ok := m.ev.PurelyEvalPartialCompound(compound, indexing.To) if !ok { return nil, false } m.compound, m.quote, m.s = compound, primary.Type, s return ns[3:], true }
pkg/edit/complete/node_path.go
0.627267
0.479138
node_path.go
starcoder
package imports import ( . "reflect" "crypto/elliptic" "math/big" ) // reflection: allow interpreted code to import "crypto/elliptic" func init() { Packages["crypto/elliptic"] = Package{ Binds: map[string]Value{ "GenerateKey": ValueOf(elliptic.GenerateKey), "Marshal": ValueOf(elliptic.Marshal), "P224": ValueOf(elliptic.P224), "P256": ValueOf(elliptic.P256), "P384": ValueOf(elliptic.P384), "P521": ValueOf(elliptic.P521), "Unmarshal": ValueOf(elliptic.Unmarshal), }, Types: map[string]Type{ "Curve": TypeOf((*elliptic.Curve)(nil)).Elem(), "CurveParams": TypeOf((*elliptic.CurveParams)(nil)).Elem(), }, Proxies: map[string]Type{ "Curve": TypeOf((*P_crypto_elliptic_Curve)(nil)).Elem(), }, } } // --------------- proxy for crypto/elliptic.Curve --------------- type P_crypto_elliptic_Curve struct { Object interface{} Add_ func(_proxy_obj_ interface{}, x1 *big.Int, y1 *big.Int, x2 *big.Int, y2 *big.Int) (x *big.Int, y *big.Int) Double_ func(_proxy_obj_ interface{}, x1 *big.Int, y1 *big.Int) (x *big.Int, y *big.Int) IsOnCurve_ func(_proxy_obj_ interface{}, x *big.Int, y *big.Int) bool Params_ func(interface{}) *elliptic.CurveParams ScalarBaseMult_ func(_proxy_obj_ interface{}, k []byte) (x *big.Int, y *big.Int) ScalarMult_ func(_proxy_obj_ interface{}, x1 *big.Int, y1 *big.Int, k []byte) (x *big.Int, y *big.Int) } func (P *P_crypto_elliptic_Curve) Add(x1 *big.Int, y1 *big.Int, x2 *big.Int, y2 *big.Int) (x *big.Int, y *big.Int) { return P.Add_(P.Object, x1, y1, x2, y2) } func (P *P_crypto_elliptic_Curve) Double(x1 *big.Int, y1 *big.Int) (x *big.Int, y *big.Int) { return P.Double_(P.Object, x1, y1) } func (P *P_crypto_elliptic_Curve) IsOnCurve(x *big.Int, y *big.Int) bool { return P.IsOnCurve_(P.Object, x, y) } func (P *P_crypto_elliptic_Curve) Params() *elliptic.CurveParams { return P.Params_(P.Object) } func (P *P_crypto_elliptic_Curve) ScalarBaseMult(k []byte) (x *big.Int, y *big.Int) { return P.ScalarBaseMult_(P.Object, k) } func (P *P_crypto_elliptic_Curve) ScalarMult(x1 *big.Int, y1 *big.Int, k []byte) (x *big.Int, y *big.Int) { return P.ScalarMult_(P.Object, x1, y1, k) }
vendor/github.com/cosmos72/gomacro/imports/crypto_elliptic.go
0.581184
0.46041
crypto_elliptic.go
starcoder
package primeproofs import "github.com/privacybydesign/keyproof/common" import "github.com/privacybydesign/gabi/big" type expStepStructure struct { bitname string stepa expStepAStructure stepb expStepBStructure } type expStepCommit struct { isTypeA bool Acommit expStepACommit Aproof expStepAProof Achallenge *big.Int Bcommit expStepBCommit Bproof expStepBProof Bchallenge *big.Int } type expStepProof struct { Achallenge *big.Int Aproof expStepAProof Bchallenge *big.Int Bproof expStepBProof } func newExpStepStructure(bitname, prename, postname, mulname, modname string, bitlen uint) expStepStructure { var structure expStepStructure structure.bitname = bitname structure.stepa = newExpStepAStructure(bitname, prename, postname) structure.stepb = newExpStepBStructure(bitname, prename, postname, mulname, modname, bitlen) return structure } func (s *expStepStructure) NumRangeProofs() int { return s.stepa.NumRangeProofs() + s.stepb.NumRangeProofs() } func (s *expStepStructure) NumCommitments() int { return s.stepa.NumCommitments() + s.stepb.NumCommitments() } func (s *expStepStructure) GenerateCommitmentsFromSecrets(g group, list []*big.Int, bases BaseLookup, secretdata SecretLookup) ([]*big.Int, expStepCommit) { var commit expStepCommit if secretdata.GetSecret(s.bitname).Cmp(big.NewInt(0)) == 0 { commit.isTypeA = true // prove a list, commit.Acommit = s.stepa.GenerateCommitmentsFromSecrets(g, list, bases, secretdata) // fake b commit.Bchallenge = common.RandomBigInt(new(big.Int).Lsh(big.NewInt(1), 256)) commit.Bproof = s.stepb.FakeProof(g) list = s.stepb.GenerateCommitmentsFromProof(g, list, commit.Bchallenge, bases, commit.Bproof) } else { commit.isTypeA = false // fake a commit.Achallenge = common.RandomBigInt(new(big.Int).Lsh(big.NewInt(1), 256)) commit.Aproof = s.stepa.FakeProof(g) list = s.stepa.GenerateCommitmentsFromProof(g, list, commit.Achallenge, bases, commit.Aproof) // prove b list, commit.Bcommit = s.stepb.GenerateCommitmentsFromSecrets(g, list, bases, secretdata) } return list, commit } func (s *expStepStructure) BuildProof(g group, challenge *big.Int, commit expStepCommit, secretdata SecretLookup) expStepProof { var proof expStepProof if commit.isTypeA { // Build a proof proof.Achallenge = new(big.Int).Xor(challenge, commit.Bchallenge) proof.Aproof = s.stepa.BuildProof(g, proof.Achallenge, commit.Acommit, secretdata) // Copy b proof proof.Bchallenge = commit.Bchallenge proof.Bproof = commit.Bproof } else { // Copy a proof proof.Achallenge = commit.Achallenge proof.Aproof = commit.Aproof // Build b proof proof.Bchallenge = new(big.Int).Xor(challenge, commit.Achallenge) proof.Bproof = s.stepb.BuildProof(g, proof.Bchallenge, commit.Bcommit, secretdata) } return proof } func (s *expStepStructure) FakeProof(g group, challenge *big.Int) expStepProof { var proof expStepProof proof.Achallenge = common.RandomBigInt(new(big.Int).Lsh(big.NewInt(1), 256)) proof.Bchallenge = new(big.Int).Xor(challenge, proof.Achallenge) proof.Aproof = s.stepa.FakeProof(g) proof.Bproof = s.stepb.FakeProof(g) return proof } func (s *expStepStructure) VerifyProofStructure(challenge *big.Int, proof expStepProof) bool { if proof.Achallenge == nil || proof.Bchallenge == nil { return false } if challenge.Cmp(new(big.Int).Xor(proof.Achallenge, proof.Bchallenge)) != 0 { return false } return s.stepa.VerifyProofStructure(proof.Aproof) && s.stepb.VerifyProofStructure(proof.Bproof) } func (s *expStepStructure) GenerateCommitmentsFromProof(g group, list []*big.Int, challenge *big.Int, bases BaseLookup, proof expStepProof) []*big.Int { list = s.stepa.GenerateCommitmentsFromProof(g, list, proof.Achallenge, bases, proof.Aproof) list = s.stepb.GenerateCommitmentsFromProof(g, list, proof.Bchallenge, bases, proof.Bproof) return list } func (s *expStepStructure) IsTrue(secretdata SecretLookup) bool { return s.stepa.IsTrue(secretdata) || s.stepb.IsTrue(secretdata) }
primeproofs/expstep.go
0.566738
0.483466
expstep.go
starcoder
package minhash import "math" // MinWise is a collection of minimum hashes for a set type MinWise struct { minimums []uint64 h1 Hash64 h2 Hash64 } type Hash64 func([]byte) uint64 // NewMinWise returns a new MinWise Hashing implementation func NewMinWise(h1, h2 Hash64, size int) *MinWise { minimums := make([]uint64, size) for i := range minimums { minimums[i] = math.MaxUint64 } return &MinWise{ h1: h1, h2: h2, minimums: minimums, } } // NewMinWise returns a new MinWise Hashing implementation // using a user-provided set of signatures func NewMinWiseFromSignatures(h1, h2 Hash64, signatures []uint64) *MinWise { minimums := make([]uint64, len(signatures)) copy(minimums, signatures) return &MinWise{ h1: h1, h2: h2, minimums: signatures, } } // Push adds an element to the set. func (m *MinWise) Push(b []byte) { v1 := m.h1(b) v2 := m.h2(b) for i, v := range m.minimums { hv := v1 + uint64(i)*v2 if hv < v { m.minimums[i] = hv } } } // Merge combines the signatures of the second set, creating the signature of their union. func (m *MinWise) Merge(m2 *MinWise) { for i, v := range m2.minimums { if v < m.minimums[i] { m.minimums[i] = v } } } // Cardinality estimates the cardinality of the set func (m *MinWise) Cardinality() int { // http://www.cohenwang.com/edith/Papers/tcest.pdf sum := 0.0 for _, v := range m.minimums { sum += -math.Log(float64(math.MaxUint64-v) / float64(math.MaxUint64)) } return int(float64(len(m.minimums)-1) / sum) } // Signature returns a signature for the set. func (m *MinWise) Signature() []uint64 { return m.minimums } // Similarity computes an estimate for the similarity between the two sets. func (m *MinWise) Similarity(m2 *MinWise) float64 { if len(m.minimums) != len(m2.minimums) { panic("minhash minimums size mismatch") } intersect := 0 for i := range m.minimums { if m.minimums[i] == m2.minimums[i] { intersect++ } } return float64(intersect) / float64(len(m.minimums)) } // SignatureBbit returns a b-bit reduction of the signature. This will result in unused bits at the high-end of the words if b does not divide 64 evenly. func (m *MinWise) SignatureBbit(b uint) []uint64 { var sig []uint64 // full signature var w uint64 // current word bits := uint(64) // bits free in current word mask := uint64(1<<b) - 1 for _, v := range m.minimums { if bits >= b { w <<= b w |= v & mask bits -= b } else { sig = append(sig, w) w = 0 bits = 64 } } if bits != 64 { sig = append(sig, w) } return sig } // SimilarityBbit computes an estimate for the similarity between two b-bit signatures func SimilarityBbit(sig1, sig2 []uint64, b uint) float64 { if len(sig1) != len(sig2) { panic("signature size mismatch") } intersect := 0 count := 0 mask := uint64(1<<b) - 1 for i := range sig1 { w1 := sig1[i] w2 := sig2[i] bits := uint(64) for bits >= b { v1 := (w1 & mask) v2 := (w2 & mask) count++ if v1 == v2 { intersect++ } bits -= b w1 >>= b w2 >>= b } } return float64(intersect) / float64(count) }
minwise.go
0.841761
0.437042
minwise.go
starcoder
// Package utf16 implements encoding and decoding of UTF-16 sequences. package utf16 import "unicode" const ( // 0xd800-0xdc00 encodes the high 10 bits of a pair. // 0xdc00-0xe000 encodes the low 10 bits of a pair. // the value is those 20 bits plus 0x10000. surr1 = 0xd800 surr2 = 0xdc00 surr3 = 0xe000 surrSelf = 0x10000 ) // IsSurrogate returns true if the specified Unicode code point // can appear in a surrogate pair. func IsSurrogate(rune int) bool { return surr1 <= rune && rune < surr3 } // DecodeRune returns the UTF-16 decoding of a surrogate pair. // If the pair is not a valid UTF-16 surrogate pair, DecodeRune returns // the Unicode replacement code point U+FFFD. func DecodeRune(r1, r2 int) int { if surr1 <= r1 && r1 < surr2 && surr2 <= r2 && r2 < surr3 { return (int(r1)-surr1)<<10 | (int(r2) - surr2) + 0x10000 } return unicode.ReplacementChar } // EncodeRune returns the UTF-16 surrogate pair r1, r2 for the given rune. // If the rune is not a valid Unicode code point or does not need encoding, // EncodeRune returns U+FFFD, U+FFFD. func EncodeRune(rune int) (r1, r2 int) { if rune < surrSelf || rune > unicode.MaxRune || IsSurrogate(rune) { return unicode.ReplacementChar, unicode.ReplacementChar } rune -= surrSelf return surr1 + (rune>>10)&0x3ff, surr2 + rune&0x3ff } // Encode returns the UTF-16 encoding of the Unicode code point sequence s. func Encode(s []int) []uint16 { n := len(s) for _, v := range s { if v >= surrSelf { n++ } } a := make([]uint16, n) n = 0 for _, v := range s { switch { case v < 0, surr1 <= v && v < surr3, v > unicode.MaxRune: v = unicode.ReplacementChar fallthrough case v < surrSelf: a[n] = uint16(v) n++ default: r1, r2 := EncodeRune(v) a[n] = uint16(r1) a[n+1] = uint16(r2) n += 2 } } return a[0:n] } // Decode returns the Unicode code point sequence represented // by the UTF-16 encoding s. func Decode(s []uint16) []int { a := make([]int, len(s)) n := 0 for i := 0; i < len(s); i++ { switch r := s[i]; { case surr1 <= r && r < surr2 && i+1 < len(s) && surr2 <= s[i+1] && s[i+1] < surr3: // valid surrogate sequence a[n] = DecodeRune(int(r), int(s[i+1])) i++ n++ case surr1 <= r && r < surr3: // invalid surrogate sequence a[n] = unicode.ReplacementChar n++ default: // normal rune a[n] = int(r) n++ } } return a[0:n] }
src/pkg/utf16/utf16.go
0.538741
0.421671
utf16.go
starcoder
package logging import ( "errors" "fmt" "strings" ) // LogLevel is the numeric score of the significance of a message, where zero is non-significant and higher values are more significant. type LogLevel uint const ( // All allows all messages to be logged All = 0 // Trace allows messages with a significance of Trace or higher to be logged Trace = 10 // Debug allows messages with a significance of Debug or higher to be logged Debug = 20 // Info allows messages with a significance of Info or higher to be logged Info = 40 // Warn allows messages with a significance of Warn or higher to be logged Warn = 50 // Error allows messages with a significance of Error or higher to be logged Error = 60 // Fatal allows messages with a significance of Fatal or higher to be logged Fatal = 70 ) const ( //AllLabel maps the string ALL to the numeric log level All AllLabel = "ALL" //TraceLabel maps the string TRACE to the numeric log level Trace TraceLabel = "TRACE" //DebugLabel maps the string DEBUG to the numeric log level Debug DebugLabel = "DEBUG" //InfoLabel maps the string INFO to the numeric log level Debug InfoLabel = "INFO" //WarnLabel maps the string WARN to the numeric log level Warn WarnLabel = "WARN" //ErrorLabel maps the string ERROR to the numeric log level Error ErrorLabel = "ERROR" //FatalLabel maps the string FATAL to the numeric log level Fatal FatalLabel = "FATAL" ) // LogLevelFromLabel takes a string name for a log level (TRACE, DEBUG etc) and finds a numeric threshold associated with // that type of message. func LogLevelFromLabel(label string) (LogLevel, error) { u := strings.ToUpper(label) switch u { case AllLabel: return All, nil case WarnLabel: return Warn, nil case TraceLabel: return Trace, nil case DebugLabel: return Debug, nil case InfoLabel: return Info, nil case ErrorLabel: return Error, nil case FatalLabel: return Fatal, nil } m := invalidLogLevelMessage(label) return All, errors.New(m) } // LabelFromLevel takes a member of the LogLevel enumeration (All, Fatal) and converts it to a string code ('ALL', 'FATAL'). // If the supplied LogLevel cannot be mapped to a defined level, the word 'CUSTOM' is returned. func LabelFromLevel(ll LogLevel) string { switch ll { case All: return AllLabel case Trace: return TraceLabel case Debug: return DebugLabel case Info: return InfoLabel case Warn: return WarnLabel case Error: return ErrorLabel case Fatal: return FatalLabel default: return "CUSTOM" } } func invalidLogLevelMessage(label string) string { return fmt.Sprintf("%s is not valid log level. Valid levels are %s, %s, %s, %s, %s, %s, %s.", label, AllLabel, TraceLabel, DebugLabel, InfoLabel, WarnLabel, ErrorLabel, FatalLabel) }
logging/level.go
0.580471
0.404743
level.go
starcoder
package netmap import ( "sort" ) type ( // aggregator can calculate some value across all netmap // such as median, minimum or maximum. aggregator interface { Add(float64) Compute() float64 } // normalizer normalizes weight. normalizer interface { Normalize(w float64) float64 } meanSumAgg struct { sum float64 count int } meanAgg struct { mean float64 count int } minAgg struct { min float64 } maxAgg struct { max float64 } meanIQRAgg struct { k float64 arr []float64 } reverseMinNorm struct { min float64 } maxNorm struct { max float64 } sigmoidNorm struct { scale float64 } constNorm struct { value float64 } // weightFunc calculates n's weight. weightFunc = func(n *Node) float64 ) var ( _ aggregator = (*meanSumAgg)(nil) _ aggregator = (*meanAgg)(nil) _ aggregator = (*minAgg)(nil) _ aggregator = (*maxAgg)(nil) _ aggregator = (*meanIQRAgg)(nil) _ normalizer = (*reverseMinNorm)(nil) _ normalizer = (*maxNorm)(nil) _ normalizer = (*sigmoidNorm)(nil) _ normalizer = (*constNorm)(nil) ) // newWeightFunc returns weightFunc which multiplies normalized // capacity and price. func newWeightFunc(capNorm, priceNorm normalizer) weightFunc { return func(n *Node) float64 { return capNorm.Normalize(float64(n.Capacity)) * priceNorm.Normalize(float64(n.Price)) } } // newMeanAgg returns an aggregator which // computes mean value by recalculating it on // every addition. func newMeanAgg() aggregator { return new(meanAgg) } // newMinAgg returns an aggregator which // computes min value. func newMinAgg() aggregator { return new(minAgg) } // newMeanIQRAgg returns an aggregator which // computes mean value of values from IQR interval. func newMeanIQRAgg() aggregator { return new(meanIQRAgg) } // newReverseMinNorm returns a normalizer which // normalize values in range of 0.0 to 1.0 to a minimum value. func newReverseMinNorm(min float64) normalizer { return &reverseMinNorm{min: min} } // newSigmoidNorm returns a normalizer which // normalize values in range of 0.0 to 1.0 to a scaled sigmoid. func newSigmoidNorm(scale float64) normalizer { return &sigmoidNorm{scale: scale} } func (a *meanSumAgg) Add(n float64) { a.sum += n a.count++ } func (a *meanSumAgg) Compute() float64 { if a.count == 0 { return 0 } return a.sum / float64(a.count) } func (a *meanAgg) Add(n float64) { c := a.count + 1 a.mean = a.mean*(float64(a.count)/float64(c)) + n/float64(c) a.count++ } func (a *meanAgg) Compute() float64 { return a.mean } func (a *minAgg) Add(n float64) { if a.min == 0 || n < a.min { a.min = n } } func (a *minAgg) Compute() float64 { return a.min } func (a *maxAgg) Add(n float64) { if n > a.max { a.max = n } } func (a *maxAgg) Compute() float64 { return a.max } func (a *meanIQRAgg) Add(n float64) { a.arr = append(a.arr, n) } func (a *meanIQRAgg) Compute() float64 { l := len(a.arr) if l == 0 { return 0 } sort.Slice(a.arr, func(i, j int) bool { return a.arr[i] < a.arr[j] }) var min, max float64 const minLn = 4 if l < minLn { min, max = a.arr[0], a.arr[l-1] } else { start, end := l/minLn, l*3/minLn-1 iqr := a.k * (a.arr[end] - a.arr[start]) min, max = a.arr[start]-iqr, a.arr[end]+iqr } count := 0 sum := float64(0) for _, e := range a.arr { if e >= min && e <= max { sum += e count++ } } return sum / float64(count) } func (r *reverseMinNorm) Normalize(w float64) float64 { if w == 0 { return 0 } return r.min / w } func (r *maxNorm) Normalize(w float64) float64 { if r.max == 0 { return 0 } return w / r.max } func (r *sigmoidNorm) Normalize(w float64) float64 { if r.scale == 0 { return 0 } x := w / r.scale return x / (1 + x) } func (r *constNorm) Normalize(_ float64) float64 { return r.value }
pkg/netmap/aggregator.go
0.845305
0.540499
aggregator.go
starcoder
package vox import "github.com/mbrlabs/vox/glm" type FpsCameraController struct { MouseSensivity float32 // degress per pixel Velocity float32 cam *Camera pressedKeys map[Key]bool tmp *glm.Vector3 } func NewFpsController(cam *Camera) *FpsCameraController { return &FpsCameraController{ MouseSensivity: 0.2, Velocity: 50, cam: cam, pressedKeys: make(map[Key]bool), tmp: &glm.Vector3{}, } } func (c *FpsCameraController) Update(delta float32) { progress := delta * c.Velocity if _, left := c.pressedKeys[KeyA]; left { c.tmp.SetVector3(c.cam.direction).Cross(c.cam.up).Norm().Scale(-progress) c.cam.Move(c.tmp.X, c.tmp.Y, c.tmp.Z) } if _, right := c.pressedKeys[KeyD]; right { c.tmp.SetVector3(c.cam.direction).Cross(c.cam.up).Norm().Scale(progress) c.cam.Move(c.tmp.X, c.tmp.Y, c.tmp.Z) } if _, forward := c.pressedKeys[KeyW]; forward { c.tmp.SetVector3(c.cam.direction).Norm().Scale(progress) c.cam.Move(c.tmp.X, c.tmp.Y, c.tmp.Z) } if _, back := c.pressedKeys[KeyS]; back { c.tmp.SetVector3(c.cam.direction).Norm().Scale(-progress) c.cam.Move(c.tmp.X, c.tmp.Y, c.tmp.Z) } if _, up := c.pressedKeys[KeyQ]; up { c.tmp.SetVector3(c.cam.up).Norm().Scale(progress) c.cam.Move(c.tmp.X, c.tmp.Y, c.tmp.Z) } if _, down := c.pressedKeys[KeyE]; down { c.tmp.SetVector3(c.cam.up).Norm().Scale(-progress) c.cam.Move(c.tmp.X, c.tmp.Y, c.tmp.Z) } c.cam.Update() } func (c *FpsCameraController) KeyDown(key Key) bool { c.pressedKeys[key] = true return false } func (c *FpsCameraController) KeyUp(key Key) bool { delete(c.pressedKeys, key) return false } func (c *FpsCameraController) KeyPressed(key Key) bool { return false } func (c *FpsCameraController) MouseMoved(x, y float64) bool { dx := -Vox.DeltaMouseX() * c.MouseSensivity dy := -Vox.DeltaMouseY() * c.MouseSensivity c.cam.direction.Rotate(c.cam.up, dx) c.tmp.SetVector3(c.cam.direction).Cross(c.cam.up).Norm() c.cam.direction.Rotate(c.tmp, dy) return false }
nav.go
0.568895
0.403067
nav.go
starcoder
package graphics // https://github.com/ozankasikci/go-image-merge/blob/master/go-image-merge.go import ( "image" "image/color" "image/draw" ) // Specifies how the grid pixel size should be calculated type gridSizeMode int const ( // The size in pixels is fixed for all the grids fixedGridSize gridSizeMode = iota // The size in pixels is set to the nth image size gridSizeFromImage ) // Grid holds the data for each grid type Grid struct { Image image.Image BackgroundColor color.Color OffsetX int OffsetY int Grids []*Grid } // MergedImage is responsible for merging the given images type MergedImage struct { Grids []*Grid ImageCountDX int ImageCountDY int BaseDir string FixedGridSizeX int FixedGridSizeY int GridSizeMode gridSizeMode GridSizeFromNth int } // NewMergedImage returns a new *MergedImage instance func NewMergedImage(grids []*Grid, imageCountDX, imageCountDY int, opts ...func(*MergedImage)) *MergedImage { mi := &MergedImage{ Grids: grids, ImageCountDX: imageCountDX, ImageCountDY: imageCountDY, } for _, option := range opts { option(mi) } return mi } // OptBaseDir is an functional option to set the BaseDir field func OptBaseDir(dir string) func(*MergedImage) { return func(mi *MergedImage) { mi.BaseDir = dir } } // OptGridSize is an functional option to set the GridSize X & Y func OptGridSize(sizeX, sizeY int) func(*MergedImage) { return func(mi *MergedImage) { mi.GridSizeMode = fixedGridSize mi.FixedGridSizeX = sizeX mi.FixedGridSizeY = sizeY } } // OptGridSizeFromNthImageSize is an functional option to set the GridSize from the nth image func OptGridSizeFromNthImageSize(n int) func(*MergedImage) { return func(mi *MergedImage) { mi.GridSizeMode = gridSizeFromImage mi.GridSizeFromNth = n } } func (m *MergedImage) mergeGrids(images []image.Image) (*image.RGBA, error) { var canvas *image.RGBA imageBoundX := 0 imageBoundY := 0 if m.GridSizeMode == fixedGridSize && m.FixedGridSizeX != 0 && m.FixedGridSizeY != 0 { imageBoundX = m.FixedGridSizeX imageBoundY = m.FixedGridSizeY } else if m.GridSizeMode == gridSizeFromImage { imageBoundX = images[m.GridSizeFromNth].Bounds().Dx() imageBoundY = images[m.GridSizeFromNth].Bounds().Dy() } else { imageBoundX = images[0].Bounds().Dx() imageBoundY = images[0].Bounds().Dy() } canvasBoundX := m.ImageCountDX * imageBoundX canvasBoundY := m.ImageCountDY * imageBoundY canvasMaxPoint := image.Point{canvasBoundX, canvasBoundY} canvasRect := image.Rectangle{image.Point{0, 0}, canvasMaxPoint} canvas = image.NewRGBA(canvasRect) // Draw grids one by one for i, grid := range m.Grids { img := images[i] x := i % m.ImageCountDX y := i / m.ImageCountDX minPoint := image.Point{x * imageBoundX, y * imageBoundY} maxPoint := minPoint.Add(image.Point{imageBoundX, imageBoundY}) nextGridRect := image.Rectangle{minPoint, maxPoint} if grid.BackgroundColor != nil { draw.Draw(canvas, nextGridRect, &image.Uniform{grid.BackgroundColor}, image.Point{}, draw.Src) draw.Draw(canvas, nextGridRect, img, image.Point{}, draw.Over) } else { draw.Draw(canvas, nextGridRect, img, image.Point{}, draw.Src) } if grid.Grids == nil { continue } // Draw top layer grids for _, grid := range grid.Grids { gridRect := nextGridRect.Bounds().Add(image.Point{grid.OffsetX, grid.OffsetY}) draw.Draw(canvas, gridRect, grid.Image, image.Point{}, draw.Over) } } return canvas, nil } // Merge merges the images according to given configuration func (m *MergedImage) Merge() (*image.RGBA, error) { var images []image.Image for _, grid := range m.Grids { images = append(images, grid.Image) } return m.mergeGrids(images) }
graphics/mergedimage.go
0.866726
0.598635
mergedimage.go
starcoder
package generator import "strings" // Params is a slice of Param. type Params []Param // Param is an argument to a function. type Param struct { Name string Type string IsVariadic bool IsSlice bool } // Slices returns those params that are a slice. func (p Params) Slices() Params { var result Params for i := range p { if p[i].IsSlice { result = append(result, p[i]) } } return result } // HasLength returns true if there are params. It returns false if there are no // params. func (p Params) HasLength() bool { return len(p) > 0 } // WithPrefix builds a string representing a functions parameters, and adds a // prefix to each. func (p Params) WithPrefix(prefix string) string { if len(p) == 0 { return "" } params := []string{} for i := range p { if prefix == "" { params = append(params, unexport(p[i].Name)) } else { params = append(params, prefix+unexport(p[i].Name)) } } return strings.Join(params, ", ") } // AsArgs builds a string that represents the parameters to a function as // arguments to a function invocation. func (p Params) AsArgs() string { if len(p) == 0 { return "" } params := []string{} for i := range p { params = append(params, p[i].Type) } return strings.Join(params, ", ") } // AsNamedArgsWithTypes builds a string that represents parameters as named // arugments to a function, with associated types. func (p Params) AsNamedArgsWithTypes() string { if len(p) == 0 { return "" } params := []string{} for i := range p { params = append(params, unexport(p[i].Name)+" "+p[i].Type) } return strings.Join(params, ", ") } // AsNamedArgs builds a string that represents parameters as named arguments. func (p Params) AsNamedArgs() string { if len(p) == 0 { return "" } params := []string{} for i := range p { if p[i].IsSlice { params = append(params, unexport(p[i].Name)+"Copy") } else { params = append(params, unexport(p[i].Name)) } } return strings.Join(params, ", ") } // AsNamedArgsForInvocation builds a string that represents a function's // arguments as required for invocation of the function. func (p Params) AsNamedArgsForInvocation() string { if len(p) == 0 { return "" } params := []string{} for i := range p { if p[i].IsVariadic { params = append(params, unexport(p[i].Name)+"...") } else { params = append(params, unexport(p[i].Name)) } } return strings.Join(params, ", ") } // AsReturnSignature builds a string representing signature for the params of // a function. func (p Params) AsReturnSignature() string { if len(p) == 0 { return "" } if len(p) == 1 { if p[0].IsVariadic { return strings.Replace(p[0].Type, "...", "[]", -1) } return p[0].Type } result := "(" for i := range p { t := p[i].Type if p[i].IsVariadic { t = strings.Replace(t, "...", "[]", -1) } result = result + t if i < len(p) { result = result + ", " } } result = result + ")" return result }
vendor/github.com/maxbrunsfeld/counterfeiter/v6/generator/param.go
0.729905
0.426501
param.go
starcoder
package data const ColorsDataText = `[ { "name": "Absolute Zero", "hex": "#0048BA" }, { "name": "Acid Green", "hex": "#B0BF1A" }, { "name": "Aero", "hex": "#7CB9E8" }, { "name": "Aero Blue", "hex": "#C9FFE5" }, { "name": "African Violet", "hex": "#B284BE" }, { "name": "Air Force Blue (RAF)", "hex": "#5D8AA8" }, { "name": "Air Force Blue (USAF)", "hex": "#00308F" }, { "name": "Air Superiority Blue", "hex": "#72A0C1" }, { "name": "<NAME>", "hex": "#AF002A" }, { "name": "Alabaster", "hex": "#F2F0E6" }, { "name": "<NAME>", "hex": "#F0F8FF" }, { "name": "<NAME>", "hex": "#84DE02" }, { "name": "<NAME>", "hex": "#E32636" }, { "name": "<NAME>", "hex": "#C46210" }, { "name": "Almond", "hex": "#EFDECD" }, { "name": "Amaranth", "hex": "#E52B50" }, { "name": "<NAME>", "hex": "#9F2B68" }, { "name": "<NAME>", "hex": "#F19CBB" }, { "name": "<NAME>", "hex": "#AB274F" }, { "name": "<NAME>", "hex": "#D3212D" }, { "name": "Amazon Store", "hex": "#3B7A57" }, { "name": "Amazonite", "hex": "#00C4B0" }, { "name": "Amber", "hex": "#FFBF00" }, { "name": "Amber (SAE/ECE)", "hex": "#FF7E00" }, { "name": "<NAME>", "hex": "#FF033E" }, { "name": "Amethyst", "hex": "#9966CC" }, { "name": "<NAME>", "hex": "#A4C639" }, { "name": "<NAME>", "hex": "#F2F3F4" }, { "name": "<NAME>", "hex": "#CD9575" }, { "name": "<NAME>", "hex": "#665D1E" }, { "name": "<NAME>", "hex": "#915C83" }, { "name": "<NAME>", "hex": "#841B2D" }, { "name": "<NAME>", "hex": "#FAEBD7" }, { "name": "Ao (English)", "hex": "#008000" }, { "name": "<NAME>", "hex": "#8DB600" }, { "name": "Apricot", "hex": "#FBCEB1" }, { "name": "Aqua", "hex": "#00FFFF" }, { "name": "Aquamarine", "hex": "#7FFFD4" }, { "name": "<NAME>", "hex": "#D0FF14" }, { "name": "<NAME>", "hex": "#4B5320" }, { "name": "Arsenic", "hex": "#3B444B" }, { "name": "Artichoke", "hex": "#8F9779" }, { "name": "<NAME>", "hex": "#E9D66B" }, { "name": "<NAME>", "hex": "#B2BEB5" }, { "name": "Asparagus", "hex": "#87A96B" }, { "name": "<NAME>", "hex": "#FF9966" }, { "name": "Auburn", "hex": "#A52A2A" }, { "name": "Aureolin", "hex": "#FDEE00" }, { "name": "AuroMetalSaurus", "hex": "#6E7F80" }, { "name": "Avocado", "hex": "#568203" }, { "name": "Awesome", "hex": "#FF2052" }, { "name": "<NAME>", "hex": "#C39953" }, { "name": "Azure", "hex": "#007FFF" }, { "name": "Azure (Web Color)", "hex": "#F0FFFF" }, { "name": "<NAME>", "hex": "#F0FFFF" }, { "name": "<NAME>", "hex": "#DBE9F4" }, { "name": "<NAME>", "hex": "#89CFF0" }, { "name": "<NAME>", "hex": "#A1CAF1" }, { "name": "<NAME>", "hex": "#F4C2C2" }, { "name": "<NAME>", "hex": "#FEFEFA" }, { "name": "<NAME>", "hex": "#FF91AF" }, { "name": "<NAME>", "hex": "#21ABCD" }, { "name": "<NAME>", "hex": "#FAE7B5" }, { "name": "<NAME>", "hex": "#FFE135" }, { "name": "<NAME>", "hex": "#006A4E" }, { "name": "<NAME>", "hex": "#E0218A" }, { "name": "<NAME>", "hex": "#7C0A02" }, { "name": "Battery <NAME>", "hex": "#1DACD6" }, { "name": "<NAME>", "hex": "#848482" }, { "name": "Bazaar", "hex": "#98777B" }, { "name": "<NAME>", "hex": "#BCD4E6" }, { "name": "Beaver", "hex": "#9F8170" }, { "name": "Begonia", "hex": "#FA6E79" }, { "name": "Beige", "hex": "#F5F5DC" }, { "name": "<NAME>", "hex": "#2E5894" }, { "name": "<NAME>", "hex": "#9C2542" }, { "name": "<NAME>", "hex": "#E88E5A" }, { "name": "Bisque", "hex": "#FFE4C4" }, { "name": "Bistre", "hex": "#3D2B1F" }, { "name": "<NAME>", "hex": "#967117" }, { "name": "<NAME>", "hex": "#CAE00D" }, { "name": "<NAME>", "hex": "#BFFF00" }, { "name": "Bittersweet", "hex": "#FE6F5E" }, { "name": "<NAME>", "hex": "#BF4F51" }, { "name": "Black", "hex": "#000000" }, { "name": "Black Bean", "hex": "#3D0C02" }, { "name": "Black Coral", "hex": "#54626F" }, { "name": "Black Leather Jacket", "hex": "#253529" }, { "name": "Black Olive", "hex": "#3B3C36" }, { "name": "Black Shadows", "hex": "#BFAFB2" }, { "name": "<NAME>", "hex": "#FFEBCD" }, { "name": "<NAME>", "hex": "#A57164" }, { "name": "<NAME>", "hex": "#318CE7" }, { "name": "<NAME>", "hex": "#ACE5EE" }, { "name": "Blond", "hex": "#FAF0BE" }, { "name": "Blue", "hex": "#0000FF" }, { "name": "Blue (Crayola)", "hex": "#1F75FE" }, { "name": "Blue (Munsell)", "hex": "#0093AF" }, { "name": "Blue (NCS)", "hex": "#0087BD" }, { "name": "Blue (Pantone)", "hex": "#0018A8" }, { "name": "Blue (Pigment)", "hex": "#333399" }, { "name": "Blue (RYB)", "hex": "#0247FE" }, { "name": "Blue Bell", "hex": "#A2A2D0" }, { "name": "Blue Bolt", "hex": "#00B9FB" }, { "name": "Blue-Gray", "hex": "#6699CC" }, { "name": "Blue-Green", "hex": "#0D98BA" }, { "name": "Blue Jeans", "hex": "#5DADEC" }, { "name": "Blue Lagoon", "hex": "#ACE5EE" }, { "name": "Blue-Magenta Violet", "hex": "#553592" }, { "name": "Blue Sapphire", "hex": "#126180" }, { "name": "Blue-Violet", "hex": "#8A2BE2" }, { "name": "<NAME>", "hex": "#5072A7" }, { "name": "Blueberry", "hex": "#4F86F7" }, { "name": "Bluebonnet", "hex": "#1C1CF0" }, { "name": "Blush", "hex": "#DE5D83" }, { "name": "Bole", "hex": "#79443B" }, { "name": "<NAME>", "hex": "#0095B6" }, { "name": "Bone", "hex": "#E3DAC9" }, { "name": "<NAME>", "hex": "#DDE26A" }, { "name": "<NAME>", "hex": "#CC0000" }, { "name": "Bottle Green", "hex": "#006A4E" }, { "name": "Boysenberry", "hex": "#873260" }, { "name": "<NAME>", "hex": "#0070FF" }, { "name": "Brass", "hex": "#B5A642" }, { "name": "<NAME>", "hex": "#CB4154" }, { "name": "<NAME>", "hex": "#1DACD6" }, { "name": "<NAME>", "hex": "#66FF00" }, { "name": "<NAME>", "hex": "#BF94E4" }, { "name": "<NAME>", "hex": "#D891EF" }, { "name": "<NAME>", "hex": "#C32148" }, { "name": "<NAME>", "hex": "#1974D2" }, { "name": "<NAME>", "hex": "#FF007F" }, { "name": "<NAME>", "hex": "#08E8DE" }, { "name": "<NAME>", "hex": "#D19FE8" }, { "name": "<NAME> (Crayola)", "hex": "#FFAA1D" }, { "name": "<NAME>", "hex": "#3399FF" }, { "name": "<NAME>", "hex": "#F4BBFF" }, { "name": "<NAME>", "hex": "#FF55A3" }, { "name": "<NAME>", "hex": "#FB607F" }, { "name": "<NAME>", "hex": "#004225" }, { "name": "Bronze", "hex": "#CD7F32" }, { "name": "<NAME>", "hex": "#737000" }, { "name": "Brown (Traditional)", "hex": "#964B00" }, { "name": "Brown (Web)", "hex": "#A52A2A" }, { "name": "Brown-Nose", "hex": "#6B4423" }, { "name": "<NAME>", "hex": "#AF6E4D" }, { "name": "<NAME>", "hex": "#cc9966" }, { "name": "<NAME>", "hex": "#1B4D3E" }, { "name": "<NAME>", "hex": "#FFC1CC" }, { "name": "Bubbles", "hex": "#E7FEFF" }, { "name": "<NAME>", "hex": "#7BB661" }, { "name": "Buff", "hex": "#F0DC82" }, { "name": "<NAME>", "hex": "#480607" }, { "name": "Burgundy", "hex": "#800020" }, { "name": "Burlywood", "hex": "#DEB887" }, { "name": "<NAME>", "hex": "#A17A74" }, { "name": "<NAME>", "hex": "#CC5500" }, { "name": "<NAME>", "hex": "#E97451" }, { "name": "<NAME>", "hex": "#8A3324" }, { "name": "<NAME>", "hex": "#24A0ED" }, { "name": "Byzantine", "hex": "#BD33A4" }, { "name": "Byzantium", "hex": "#702963" }, { "name": "Cadet", "hex": "#536872" }, { "name": "<NAME>", "hex": "#5F9EA0" }, { "name": "<NAME>", "hex": "#91A3B0" }, { "name": "<NAME>", "hex": "#006B3C" }, { "name": "<NAME>", "hex": "#ED872D" }, { "name": "<NAME>", "hex": "#E30022" }, { "name": "<NAME>", "hex": "#FFF600" }, { "name": "<NAME>", "hex": "#A67B5B" }, { "name": "<NAME>", "hex": "#4B3621" }, { "name": "<NAME>", "hex": "#1E4D2B" }, { "name": "<NAME>", "hex": "#A3C1AD" }, { "name": "Camel", "hex": "#C19A6B" }, { "name": "<NAME>", "hex": "#EFBBCC" }, { "name": "<NAME>", "hex": "#78866B" }, { "name": "Canary", "hex": "#FFFF99" }, { "name": "<NAME>", "hex": "#FFEF00" }, { "name": "<NAME>", "hex": "#FF0800" }, { "name": "<NAME>", "hex": "#E4717A" }, { "name": "Capri", "hex": "#00BFFF" }, { "name": "<NAME>", "hex": "#592720" }, { "name": "Cardinal", "hex": "#C41E3A" }, { "name": "<NAME>", "hex": "#00CC99" }, { "name": "Carmine", "hex": "#960018" }, { "name": "Carmine (M&P)", "hex": "#D70040" }, { "name": "<NAME>", "hex": "#EB4C42" }, { "name": "<NAME>", "hex": "#FF0038" }, { "name": "<NAME>", "hex": "#FFA6C9" }, { "name": "Carnelian", "hex": "#B31B1B" }, { "name": "<NAME>", "hex": "#56A0D3" }, { "name": "<NAME>", "hex": "#ED9121" }, { "name": "<NAME>", "hex": "#00563F" }, { "name": "<NAME>", "hex": "#062A78" }, { "name": "Catawba", "hex": "#703642" }, { "name": "<NAME>", "hex": "#C95A49" }, { "name": "Ceil", "hex": "#92A1CF" }, { "name": "Celadon", "hex": "#ACE1AF" }, { "name": "<NAME>", "hex": "#007BA7" }, { "name": "<NAME>", "hex": "#2F847C" }, { "name": "Celeste", "hex": "#B2FFFF" }, { "name": "<NAME>", "hex": "#4997D0" }, { "name": "Cerise", "hex": "#DE3163" }, { "name": "<NAME>", "hex": "#EC3B83" }, { "name": "Cerulean", "hex": "#007BA7" }, { "name": "<NAME>", "hex": "#2A52BE" }, { "name": "<NAME>", "hex": "#6D9BC3" }, { "name": "<NAME>", "hex": "#007AA5" }, { "name": "<NAME>", "hex": "#E03C31" }, { "name": "Chamoisee", "hex": "#A0785A" }, { "name": "Champagne", "hex": "#F7E7CE" }, { "name": "<NAME>", "hex": "#F1DDCF" }, { "name": "Charcoal", "hex": "#36454F" }, { "name": "<NAME>", "hex": "#232B2B" }, { "name": "<NAME>", "hex": "#E68FAC" }, { "name": "Chartreuse (Traditional)", "hex": "#DFFF00" }, { "name": "Chartreuse (Web)", "hex": "#7FFF00" }, { "name": "Cherry", "hex": "#DE3163" }, { "name": "<NAME>", "hex": "#FFB7C5" }, { "name": "Chestnut", "hex": "#954535" }, { "name": "<NAME>", "hex": "#DE6FA1" }, { "name": "<NAME>", "hex": "#A8516E" }, { "name": "Chinese Red", "hex": "#AA381E" }, { "name": "Chinese Violet", "hex": "#856088" }, { "name": "<NAME>", "hex": "#4AFF00" }, { "name": "Chocolate (Traditional)", "hex": "#7B3F00" }, { "name": "Chocolate (Web)", "hex": "#D2691E" }, { "name": "<NAME>", "hex": "#FFA700" }, { "name": "Cinereous", "hex": "#98817B" }, { "name": "Cinnabar", "hex": "#E34234" }, { "name": "Cinnamon", "hex": "#D2691E" }, { "name": "<NAME>", "hex": "#CD607E" }, { "name": "Citrine", "hex": "#E4D00A" }, { "name": "Citron", "hex": "#9FA91F" }, { "name": "Claret", "hex": "#7F1734" }, { "name": "<NAME>", "hex": "#FBCCE7" }, { "name": "<NAME>", "hex": "#0047AB" }, { "name": "<NAME>", "hex": "#D2691E" }, { "name": "Coconut", "hex": "#965A3E" }, { "name": "Coffee", "hex": "#6F4E37" }, { "name": "<NAME>", "hex": "#C4D8E2" }, { "name": "<NAME>", "hex": "#F88379" }, { "name": "<NAME>", "hex": "#002E63" }, { "name": "<NAME>", "hex": "#8C92AC" }, { "name": "Copper", "hex": "#B87333" }, { "name": "<NAME>)", "hex": "#DA8A67" }, { "name": "<NAME>", "hex": "#AD6F69" }, { "name": "<NAME>", "hex": "#CB6D51" }, { "name": "<NAME>", "hex": "#996666" }, { "name": "Coquelicot", "hex": "#FF3800" }, { "name": "Coral", "hex": "#FF7F50" }, { "name": "<NAME>", "hex": "#F88379" }, { "name": "<NAME>", "hex": "#FF4040" }, { "name": "<NAME>", "hex": "#FD7C6E" }, { "name": "Cordovan", "hex": "#893F45" }, { "name": "Corn", "hex": "#FBEC5D" }, { "name": "<NAME>", "hex": "#B31B1B" }, { "name": "<NAME>", "hex": "#6495ED" }, { "name": "Cornsilk", "hex": "#FFF8DC" }, { "name": "<NAME>", "hex": "#2E2D88" }, { "name": "<NAME>", "hex": "#FFF8E7" }, { "name": "<NAME>", "hex": "#81613C" }, { "name": "<NAME>", "hex": "#FFBCD9" }, { "name": "Cream", "hex": "#FFFDD0" }, { "name": "Crimson", "hex": "#DC143C" }, { "name": "<NAME>", "hex": "#BE0032" }, { "name": "<NAME>", "hex": "#990000" }, { "name": "Cultured", "hex": "#F5F5F5" }, { "name": "Cyan", "hex": "#00FFFF" }, { "name": "<NAME>", "hex": "#4E82B4" }, { "name": "Cyan-Blue Azure", "hex": "#4682BF" }, { "name": "Cyan Cobalt Blue", "hex": "#28589C" }, { "name": "Cyan Cornflower Blue", "hex": "#188BC2" }, { "name": "Cyan (Process)", "hex": "#00B7EB" }, { "name": "<NAME>", "hex": "#58427C" }, { "name": "<NAME>", "hex": "#FFD300" }, { "name": "Cyclamen", "hex": "#F56FA1" }, { "name": "Daffodil", "hex": "#FFFF31" }, { "name": "Dandelion", "hex": "#F0E130" }, { "name": "Dark Blue", "hex": "#00008B" }, { "name": "Dark Blue-Gray", "hex": "#666699" }, { "name": "Dark Brown", "hex": "#654321" }, { "name": "Dark Brown-Tangelo", "hex": "#88654E" }, { "name": "Dark Byzantium", "hex": "#5D3954" }, { "name": "Dark Candy Apple Red", "hex": "#A40000" }, { "name": "Dark Cerulean", "hex": "#08457E" }, { "name": "Dark Chestnut", "hex": "#986960" }, { "name": "Dark Coral", "hex": "#CD5B45" }, { "name": "Dark Cyan", "hex": "#008B8B" }, { "name": "Dark Electric Blue", "hex": "#536878" }, { "name": "Dark Goldenrod", "hex": "#B8860B" }, { "name": "Dark Gray (X11)", "hex": "#A9A9A9" }, { "name": "Dark Green", "hex": "#013220" }, { "name": "Dark Green (X11)", "hex": "#006400" }, { "name": "Dark Gunmetal", "hex": "#1F262A" }, { "name": "Dark Imperial Blue", "hex": "#00416A" }, { "name": "Dark Imperial Blue", "hex": "#00147E" }, { "name": "Dark Jungle Green", "hex": "#1A2421" }, { "name": "Dark Khaki", "hex": "#BDB76B" }, { "name": "Dark Lava", "hex": "#483C32" }, { "name": "Dark Lavender", "hex": "#734F96" }, { "name": "Dark Liver", "hex": "#534B4F" }, { "name": "Dark Liver (Horses)", "hex": "#543D37" }, { "name": "Dark Magenta", "hex": "#8B008B" }, { "name": "Dark Medium Gray", "hex": "#A9A9A9" }, { "name": "Dark Midnight Blue", "hex": "#003366" }, { "name": "Dark Moss Green", "hex": "#4A5D23" }, { "name": "Dark Olive Green", "hex": "#556B2F" }, { "name": "Dark Orange", "hex": "#FF8C00" }, { "name": "Dark Orchid", "hex": "#9932CC" }, { "name": "Dark Pastel Blue", "hex": "#779ECB" }, { "name": "Dark Pastel Green", "hex": "#03C03C" }, { "name": "Dark Pastel Purple", "hex": "#966FD6" }, { "name": "Dark Pastel Red", "hex": "#C23B22" }, { "name": "Dark Pink", "hex": "#E75480" }, { "name": "Dark Powder Blue", "hex": "#003399" }, { "name": "Dark Puce", "hex": "#4F3A3C" }, { "name": "Dark Purple", "hex": "#301934" }, { "name": "Dark Raspberry", "hex": "#872657" }, { "name": "Dark Red", "hex": "#8B0000" }, { "name": "Dark Salmon", "hex": "#E9967A" }, { "name": "Dark Scarlet", "hex": "#560319" }, { "name": "Dark Sea Green", "hex": "#8FBC8F" }, { "name": "Dark Sienna", "hex": "#3C1414" }, { "name": "Dark Sky Blue", "hex": "#8CBED6" }, { "name": "Dark Slate Blue", "hex": "#483D8B" }, { "name": "Dark Slate Gray", "hex": "#2F4F4F" }, { "name": "Dark Spring Green", "hex": "#177245" }, { "name": "Dark Tan", "hex": "#918151" }, { "name": "Dark Tangerine", "hex": "#FFA812" }, { "name": "Dark Taupe", "hex": "#483C32" }, { "name": "Dark Terra Cotta", "hex": "#CC4E5C" }, { "name": "Dark Turquoise", "hex": "#00CED1" }, { "name": "Dark Vanilla", "hex": "#D1BEA8" }, { "name": "Dark Violet", "hex": "#9400D3" }, { "name": "Dark Yellow", "hex": "#9B870C" }, { "name": "Dartmouth Green", "hex": "#00703C" }, { "name": "Davy's Grey", "hex": "#555555" }, { "name": "Debian Red", "hex": "#D70A53" }, { "name": "Deep Aquamarine", "hex": "#40826D" }, { "name": "Deep Carmine", "hex": "#A9203E" }, { "name": "Deep Carmine Pink", "hex": "#EF3038" }, { "name": "Deep Carrot Orange", "hex": "#E9692C" }, { "name": "Deep Cerise", "hex": "#DA3287" }, { "name": "Deep Champagne", "hex": "#FAD6A5" }, { "name": "Deep Chestnut", "hex": "#B94E48" }, { "name": "Deep Coffee", "hex": "#704241" }, { "name": "Deep Fuchsia", "hex": "#C154C1" }, { "name": "Deep Green", "hex": "#056608" }, { "name": "Deep Green-Cyan Turquoise", "hex": "#0E7C61" }, { "name": "Deep Jungle Green", "hex": "#004B49" }, { "name": "Deep Koamaru", "hex": "#333366" }, { "name": "Deep Lemon", "hex": "#F5C71A" }, { "name": "Deep Lilac", "hex": "#9955BB" }, { "name": "Deep Magenta", "hex": "#CC00CC" }, { "name": "Deep Maroon", "hex": "#820000" }, { "name": "Deep Mauve", "hex": "#D473D4" }, { "name": "Deep Moss Green", "hex": "#355E3B" }, { "name": "Deep Peach", "hex": "#FFCBA4" }, { "name": "Deep Pink", "hex": "#FF1493" }, { "name": "Deep Puce", "hex": "#A95C68" }, { "name": "Deep Red", "hex": "#850101" }, { "name": "Deep Ruby", "hex": "#843F5B" }, { "name": "Deep Saffron", "hex": "#FF9933" }, { "name": "Deep Sky Blue", "hex": "#00BFFF" }, { "name": "Deep Space Sparkle", "hex": "#4A646C" }, { "name": "Deep Spring Bud", "hex": "#556B2F" }, { "name": "<NAME>", "hex": "#7E5E60" }, { "name": "<NAME>", "hex": "#66424D" }, { "name": "<NAME>", "hex": "#330066" }, { "name": "Deer", "hex": "#BA8759" }, { "name": "Denim", "hex": "#1560BD" }, { "name": "<NAME>", "hex": "#2243B6" }, { "name": "<NAME>", "hex": "#669999" }, { "name": "Desert", "hex": "#C19A6B" }, { "name": "<NAME>", "hex": "#EDC9AF" }, { "name": "Desire", "hex": "#EA3C53" }, { "name": "Diamond", "hex": "#B9F2FF" }, { "name": "<NAME>", "hex": "#696969" }, { "name": "<NAME>", "hex": "#C53151" }, { "name": "Dirt", "hex": "#9B7653" }, { "name": "<NAME>", "hex": "#1E90FF" }, { "name": "<NAME>", "hex": "#FEF65B" }, { "name": "<NAME>", "hex": "#D71868" }, { "name": "<NAME>", "hex": "#85BB65" }, { "name": "<NAME>", "hex": "#828E84" }, { "name": "<NAME>", "hex": "#664C28" }, { "name": "Drab", "hex": "#967117" }, { "name": "<NAME>", "hex": "#00009C" }, { "name": "<NAME>", "hex": "#E5CCC9" }, { "name": "<NAME>", "hex": "#EFDFBB" }, { "name": "<NAME>", "hex": "#E1A95F" }, { "name": "Ebony", "hex": "#555D50" }, { "name": "Ecru", "hex": "#C2B280" }, { "name": "<NAME>", "hex": "#1B1B1B" }, { "name": "Eggplant", "hex": "#614051" }, { "name": "Eggshell", "hex": "#F0EAD6" }, { "name": "Egyptian Blue", "hex": "#1034A6" }, { "name": "Electric Blue", "hex": "#7DF9FF" }, { "name": "Electric Crimson", "hex": "#FF003F" }, { "name": "Electric Cyan", "hex": "#00FFFF" }, { "name": "Electric Green", "hex": "#00FF00" }, { "name": "Electric Indigo", "hex": "#6F00FF" }, { "name": "Electric Lavender", "hex": "#F4BBFF" }, { "name": "Electric Lime", "hex": "#CCFF00" }, { "name": "Electric Purple", "hex": "#BF00FF" }, { "name": "Electric Ultramarine", "hex": "#3F00FF" }, { "name": "Electric Violet", "hex": "#8F00FF" }, { "name": "Electric Yellow", "hex": "#FFFF33" }, { "name": "Emerald", "hex": "#50C878" }, { "name": "Eminence", "hex": "#6C3082" }, { "name": "English Green", "hex": "#1B4D3E" }, { "name": "English Lavender", "hex": "#B48395" }, { "name": "English Red", "hex": "#AB4B52" }, { "name": "English Vermillion", "hex": "#CC474B" }, { "name": "English Violet", "hex": "#563C5C" }, { "name": "<NAME>", "hex": "#96C8A2" }, { "name": "Eucalyptus", "hex": "#44D7A8" }, { "name": "Fallow", "hex": "#C19A6B" }, { "name": "<NAME>", "hex": "#801818" }, { "name": "Fandango", "hex": "#B53389" }, { "name": "<NAME>", "hex": "#DE5285" }, { "name": "<NAME>", "hex": "#F400A1" }, { "name": "Fawn", "hex": "#E5AA70" }, { "name": "Feldgrau", "hex": "#4D5D53" }, { "name": "Feldspar", "hex": "#FDD5B1" }, { "name": "<NAME>", "hex": "#4F7942" }, { "name": "<NAME>", "hex": "#FF2800" }, { "name": "<NAME>", "hex": "#6C541E" }, { "name": "<NAME>", "hex": "#FF5470" }, { "name": "Firebrick", "hex": "#B22222" }, { "name": "Fire Engine Red", "hex": "#CE2029" }, { "name": "Flame", "hex": "#E25822" }, { "name": "<NAME>", "hex": "#FC8EAC" }, { "name": "Flattery", "hex": "#6B4423" }, { "name": "Flavescent", "hex": "#F7E98E" }, { "name": "Flax", "hex": "#EEDC82" }, { "name": "Flirt", "hex": "#A2006D" }, { "name": "<NAME>", "hex": "#FFFAF0" }, { "name": "<NAME>", "hex": "#FFBF00" }, { "name": "<NAME>", "hex": "#FF1493" }, { "name": "<NAME>", "hex": "#CCFF00" }, { "name": "Folly", "hex": "#FF004F" }, { "name": "Forest Green (Traditional)", "hex": "#014421" }, { "name": "Forest Green (Web)", "hex": "#228B22" }, { "name": "<NAME>", "hex": "#A67B5B" }, { "name": "<NAME>", "hex": "#856D4D" }, { "name": "<NAME>", "hex": "#0072BB" }, { "name": "French Fuchsia", "hex": "#FD3F92" }, { "name": "French Lilac", "hex": "#86608E" }, { "name": "French Lime", "hex": "#9EFD38" }, { "name": "French Mauve", "hex": "#D473D4" }, { "name": "French Pink", "hex": "#FD6C9E" }, { "name": "French Plum", "hex": "#811453" }, { "name": "French Puce", "hex": "#4E1609" }, { "name": "French Raspberry", "hex": "#C72C48" }, { "name": "French Rose", "hex": "#F64A8A" }, { "name": "French Sky Blue", "hex": "#77B5FE" }, { "name": "French Violet", "hex": "#8806CE" }, { "name": "French Wine", "hex": "#AC1E44" }, { "name": "Fresh Air", "hex": "#A6E7FF" }, { "name": "Frogert", "hex": "#E936A7" }, { "name": "Fuchsia", "hex": "#FF00FF" }, { "name": "Fuchsia (Crayola)", "hex": "#C154C1" }, { "name": "Fuchsia Pink", "hex": "#FF77FF" }, { "name": "Fuchsia Purple", "hex": "#CC397B" }, { "name": "Fuchsia Rose", "hex": "#C74375" }, { "name": "Fulvous", "hex": "#E48400" }, { "name": "Fuzzy Wuzzy", "hex": "#CC6666" }, { "name": "Gainsboro", "hex": "#DCDCDC" }, { "name": "Gamboge", "hex": "#E49B0F" }, { "name": "<NAME> (Brown)", "hex": "#996600" }, { "name": "<NAME>", "hex": "#FFDF46" }, { "name": "<NAME>", "hex": "#007F66" }, { "name": "<NAME>", "hex": "#F8F8FF" }, { "name": "<NAME>", "hex": "#B05C52" }, { "name": "<NAME>", "hex": "#FE5A1D" }, { "name": "Ginger", "hex": "#B06500" }, { "name": "Glaucous", "hex": "#6082B6" }, { "name": "Glitter", "hex": "#E6E8FA" }, { "name": "<NAME>", "hex": "#AB92B3" }, { "name": "<NAME>", "hex": "#00AB66" }, { "name": "Gold (Metallic)", "hex": "#D4AF37" }, { "name": "Gold (Web) (Golden)", "hex": "#FFD700" }, { "name": "<NAME>", "hex": "#85754E" }, { "name": "<NAME>", "hex": "#996515" }, { "name": "<NAME>", "hex": "#FCC200" }, { "name": "<NAME>", "hex": "#FFDF00" }, { "name": "Goldenrod", "hex": "#DAA520" }, { "name": "<NAME>", "hex": "#676767" }, { "name": "<NAME>", "hex": "#A8E4A0" }, { "name": "Grape", "hex": "#6F2DA8" }, { "name": "Gray", "hex": "#808080" }, { "name": "Gray (HTML/CSS Gray)", "hex": "#808080" }, { "name": "Gray (X11 Gray)", "hex": "#BEBEBE" }, { "name": "Gray-Asparagus", "hex": "#465945" }, { "name": "Gray-Blue", "hex": "#8C92AC" }, { "name": "Green (Color Wheel) (X11 Green)", "hex": "#00FF00" }, { "name": "Green (Crayola)", "hex": "#1CAC78" }, { "name": "Green (HTML/CSS Color)", "hex": "#008000" }, { "name": "Green (Munsell)", "hex": "#00A877" }, { "name": "Green (NCS)", "hex": "#009F6B" }, { "name": "Green (Pantone)", "hex": "#00AD43" }, { "name": "Green (Pigment)", "hex": "#00A550" }, { "name": "Green (RYB)", "hex": "#66B032" }, { "name": "Green-Blue", "hex": "#1164B4" }, { "name": "Green-Cyan", "hex": "#009966" }, { "name": "Green Lizard", "hex": "#A7F432" }, { "name": "Green Sheen", "hex": "#6EAEA1" }, { "name": "Green-Yellow", "hex": "#ADFF2F" }, { "name": "Grizzly", "hex": "#885818" }, { "name": "Grullo", "hex": "#A99A86" }, { "name": "<NAME>", "hex": "#00FF7F" }, { "name": "Gunmetal", "hex": "#2a3439" }, { "name": "<NAME>", "hex": "#663854" }, { "name": "<NAME>", "hex": "#446CCF" }, { "name": "<NAME>", "hex": "#5218FA" }, { "name": "<NAME>", "hex": "#E9D66B" }, { "name": "Harlequin", "hex": "#3FFF00" }, { "name": "<NAME>", "hex": "#46CB18" }, { "name": "<NAME>", "hex": "#C90016" }, { "name": "<NAME>", "hex": "#DA9100" }, { "name": "<NAME>", "hex": "#808000" }, { "name": "<NAME>", "hex": "#FF7A00" }, { "name": "<NAME>", "hex": "#960018" }, { "name": "Heliotrope", "hex": "#DF73FF" }, { "name": "<NAME>", "hex": "#AA98A9" }, { "name": "<NAME>", "hex": "#AA00BB" }, { "name": "<NAME>", "hex": "#F400A1" }, { "name": "Honeydew", "hex": "#F0FFF0" }, { "name": "Honolulu Blue", "hex": "#006DB0" }, { "name": "<NAME>", "hex": "#49796B" }, { "name": "Hot Magenta", "hex": "#FF1DCE" }, { "name": "<NAME>", "hex": "#FF69B4" }, { "name": "<NAME>", "hex": "#355E3B" }, { "name": "Iceberg", "hex": "#71A6D2" }, { "name": "Icterine", "hex": "#FCF75E" }, { "name": "<NAME>", "hex": "#71BC78" }, { "name": "<NAME>", "hex": "#319177" }, { "name": "Imperial", "hex": "#602F6B" }, { "name": "Imperial Blue", "hex": "#002395" }, { "name": "Imperial Purple", "hex": "#66023C" }, { "name": "Imperial Red", "hex": "#ED2939" }, { "name": "Inchworm", "hex": "#B2EC5D" }, { "name": "Independence", "hex": "#4C516D" }, { "name": "India Green", "hex": "#138808" }, { "name": "Indian Red", "hex": "#CD5C5C" }, { "name": "Indian Yellow", "hex": "#E3A857" }, { "name": "Indigo", "hex": "#4B0082" }, { "name": "Indigo Dye", "hex": "#091F92" }, { "name": "Indigo (Web)", "hex": "#4B0082" }, { "name": "Infra Red", "hex": "#FF496C" }, { "name": "Interdimensional Blue", "hex": "#360CCC" }, { "name": "International Klein Blue", "hex": "#002FA7" }, { "name": "International Orange (Aerospace)", "hex": "#FF4F00" }, { "name": "International Orange (Engineering)", "hex": "#BA160C" }, { "name": "International Orange (Golden Gate Bridge)", "hex": "#C0362C" }, { "name": "Iris", "hex": "#5A4FCF" }, { "name": "Irresistible", "hex": "#B3446C" }, { "name": "Isabelline", "hex": "#F4F0EC" }, { "name": "<NAME>", "hex": "#009000" }, { "name": "Italian Sky Blue", "hex": "#B2FFFF" }, { "name": "Ivory", "hex": "#FFFFF0" }, { "name": "Jade", "hex": "#00A86B" }, { "name": "<NAME>", "hex": "#9D2933" }, { "name": "<NAME>", "hex": "#264348" }, { "name": "<NAME>", "hex": "#5B3256" }, { "name": "Jasmine", "hex": "#F8DE7E" }, { "name": "Jasper", "hex": "#D73B3E" }, { "name": "<NAME>", "hex": "#A50B5E" }, { "name": "<NAME>", "hex": "#DA614E" }, { "name": "Jet", "hex": "#343434" }, { "name": "Jonquil", "hex": "#F4CA16" }, { "name": "<NAME>", "hex": "#8AB9F1" }, { "name": "<NAME>", "hex": "#BDDA57" }, { "name": "<NAME>", "hex": "#29AB87" }, { "name": "<NAME>", "hex": "#4CBB17" }, { "name": "<NAME>", "hex": "#7C1C05" }, { "name": "Keppel", "hex": "#3AB09E" }, { "name": "<NAME>", "hex": "#E8F48C" }, { "name": "Khaki (HTML/CSS) (Khaki)", "hex": "#C3B091" }, { "name": "Khaki (X11) (Light Khaki)", "hex": "#F0E68C" }, { "name": "Kiwi", "hex": "#8EE53F" }, { "name": "Kobe", "hex": "#882D17" }, { "name": "Kobi", "hex": "#E79FC4" }, { "name": "Kobicha", "hex": "#6B4423" }, { "name": "<NAME>", "hex": "#354230" }, { "name": "<NAME>", "hex": "#512888" }, { "name": "<NAME>", "hex": "#E8000D" }, { "name": "<NAME>", "hex": "#087830" }, { "name": "<NAME>", "hex": "#D6CADD" }, { "name": "<NAME>", "hex": "#26619C" }, { "name": "<NAME>", "hex": "#FFFF66" }, { "name": "<NAME>", "hex": "#A9BA9D" }, { "name": "Lava", "hex": "#CF1020" }, { "name": "Lavender (Floral)", "hex": "#B57EDC" }, { "name": "Lavender (Web)", "hex": "#E6E6FA" }, { "name": "<NAME>", "hex": "#CCCCFF" }, { "name": "<NAME>", "hex": "#FFF0F5" }, { "name": "<NAME>", "hex": "#C4C3D0" }, { "name": "<NAME>", "hex": "#9457EB" }, { "name": "<NAME>", "hex": "#EE82EE" }, { "name": "<NAME>", "hex": "#E6E6FA" }, { "name": "<NAME>", "hex": "#FBAED2" }, { "name": "<NAME>", "hex": "#967BB6" }, { "name": "<NAME>", "hex": "#FBA0E3" }, { "name": "<NAME>", "hex": "#7CFC00" }, { "name": "Lemon", "hex": "#FFF700" }, { "name": "<NAME>", "hex": "#FFFACD" }, { "name": "<NAME>", "hex": "#CCA01D" }, { "name": "<NAME>", "hex": "#FDFF00" }, { "name": "<NAME>", "hex": "#E3FF00" }, { "name": "<NAME>", "hex": "#F6EABE" }, { "name": "<NAME>", "hex": "#FFF44F" }, { "name": "Licorice", "hex": "#1A1110" }, { "name": "Liberty", "hex": "#545AA7" }, { "name": "Light Apricot", "hex": "#FDD5B1" }, { "name": "Light Blue", "hex": "#ADD8E6" }, { "name": "Light Brown", "hex": "#B5651D" }, { "name": "Light Carmine Pink", "hex": "#E66771" }, { "name": "Light Cobalt Blue", "hex": "#88ACE0" }, { "name": "Light Coral", "hex": "#F08080" }, { "name": "Light Cornflower Blue", "hex": "#93CCEA" }, { "name": "Light Crimson", "hex": "#F56991" }, { "name": "Light Cyan", "hex": "#E0FFFF" }, { "name": "Light Deep Pink", "hex": "#FF5CCD" }, { "name": "Light French Beige", "hex": "#C8AD7F" }, { "name": "Light Fuchsia Pink", "hex": "#F984EF" }, { "name": "Light Goldenrod Yellow", "hex": "#FAFAD2" }, { "name": "Light Gray", "hex": "#D3D3D3" }, { "name": "Light Grayish Magenta", "hex": "#CC99CC" }, { "name": "Light Green", "hex": "#90EE90" }, { "name": "Light Hot Pink", "hex": "#FFB3DE" }, { "name": "Light Khaki", "hex": "#F0E68C" }, { "name": "Light Medium Orchid", "hex": "#D39BCB" }, { "name": "Light Moss Green", "hex": "#ADDFAD" }, { "name": "Light Orange", "hex": "#FED8B1" }, { "name": "Light Orchid", "hex": "#E6A8D7" }, { "name": "Light Pastel Purple", "hex": "#B19CD9" }, { "name": "Light Pink", "hex": "#FFB6C1" }, { "name": "Light Red Ochre", "hex": "#E97451" }, { "name": "Light Salmon", "hex": "#FFA07A" }, { "name": "Light Salmon Pink", "hex": "#FF9999" }, { "name": "Light Sea Green", "hex": "#20B2AA" }, { "name": "Light Sky Blue", "hex": "#87CEFA" }, { "name": "Light Slate Gray", "hex": "#778899" }, { "name": "Light Steel Blue", "hex": "#B0C4DE" }, { "name": "Light Taupe", "hex": "#B38B6D" }, { "name": "Light Thulian Pink", "hex": "#E68FAC" }, { "name": "Light Yellow", "hex": "#FFFFE0" }, { "name": "Lilac", "hex": "#C8A2C8" }, { "name": "<NAME>", "hex": "#AE98AA" }, { "name": "Lime (Color Wheel)", "hex": "#BFFF00" }, { "name": "Lime (Web) (X11 Green)", "hex": "#00FF00" }, { "name": "<NAME>", "hex": "#32CD32" }, { "name": "Limerick", "hex": "#9DC209" }, { "name": "<NAME>", "hex": "#195905" }, { "name": "Linen", "hex": "#FAF0E6" }, { "name": "Loeen (Lopen) Look", "hex": "#15F2FD" }, { "name": "<NAME>", "hex": "#DE6FA1" }, { "name": "<NAME>", "hex": "#6CA0DC" }, { "name": "Liver", "hex": "#674C47" }, { "name": "Liver (Dogs)", "hex": "#B86D29" }, { "name": "Liver (Organ)", "hex": "#6C2E1F" }, { "name": "<NAME>", "hex": "#987456" }, { "name": "Livid", "hex": "#6699CC" }, { "name": "Lumber", "hex": "#FFE4CD" }, { "name": "Lust", "hex": "#E62020" }, { "name": "<NAME>", "hex": "#001C3D" }, { "name": "<NAME>", "hex": "#FFBD88" }, { "name": "<NAME>", "hex": "#CC3336" }, { "name": "Magenta", "hex": "#FF00FF" }, { "name": "Magenta (Crayola)", "hex": "#FF55A3" }, { "name": "Magenta (Dye)", "hex": "#CA1F7B" }, { "name": "Magenta (Pantone)", "hex": "#D0417E" }, { "name": "Magenta (Process)", "hex": "#FF0090" }, { "name": "Magenta Haze", "hex": "#9F4576" }, { "name": "Magenta-Pink", "hex": "#CC338B" }, { "name": "<NAME>", "hex": "#AAF0D1" }, { "name": "<NAME>", "hex": "#FF4466" }, { "name": "Magnolia", "hex": "#F8F4FF" }, { "name": "Mahogany", "hex": "#C04000" }, { "name": "Maize", "hex": "#FBEC5D" }, { "name": "<NAME>", "hex": "#6050DC" }, { "name": "Malachite", "hex": "#0BDA51" }, { "name": "Manatee", "hex": "#979AAA" }, { "name": "Mandarin", "hex": "#F37A48" }, { "name": "<NAME>", "hex": "#FF8243" }, { "name": "Mantis", "hex": "#74C365" }, { "name": "<NAME>", "hex": "#880085" }, { "name": "Marigold", "hex": "#EAA221" }, { "name": "Maroon (Crayola)", "hex": "#C32148" }, { "name": "Maroon (HTML/CSS)", "hex": "#800000" }, { "name": "Maroon (X11)", "hex": "#B03060" }, { "name": "Mauve", "hex": "#E0B0FF" }, { "name": "<NAME>", "hex": "#915F6D" }, { "name": "Mauvelous", "hex": "#EF98AA" }, { "name": "Maximum Blue", "hex": "#47ABCC" }, { "name": "Maximum Blue Green", "hex": "#30BFBF" }, { "name": "Maximum Blue Purple", "hex": "#ACACE6" }, { "name": "Maximum Green", "hex": "#5E8C31" }, { "name": "Maximum Green Yellow", "hex": "#D9E650" }, { "name": "Maximum Purple", "hex": "#733380" }, { "name": "Maximum Red", "hex": "#D92121" }, { "name": "Maximum Red Purple", "hex": "#A63A79" }, { "name": "Maximum Yellow", "hex": "#FAFA37" }, { "name": "Maximum Yellow Red", "hex": "#F2BA49" }, { "name": "<NAME>", "hex": "#4C9141" }, { "name": "<NAME>", "hex": "#73C2FB" }, { "name": "<NAME>", "hex": "#E5B73B" }, { "name": "Medium Aquamarine", "hex": "#66DDAA" }, { "name": "Medium Blue", "hex": "#0000CD" }, { "name": "Medium Candy Apple Red", "hex": "#E2062C" }, { "name": "Medium Carmine", "hex": "#AF4035" }, { "name": "Medium Champagne", "hex": "#F3E5AB" }, { "name": "Medium Electric Blue", "hex": "#035096" }, { "name": "Medium Jungle Green", "hex": "#1C352D" }, { "name": "Medium Lavender Magenta", "hex": "#DDA0DD" }, { "name": "Medium Orchid", "hex": "#BA55D3" }, { "name": "Medium Persian Blue", "hex": "#0067A5" }, { "name": "Medium Purple", "hex": "#9370DB" }, { "name": "Medium Red-Violet", "hex": "#BB3385" }, { "name": "Medium Ruby", "hex": "#AA4069" }, { "name": "Medium Sea Green", "hex": "#3CB371" }, { "name": "Medium Sky Blue", "hex": "#80DAEB" }, { "name": "Medium Slate Blue", "hex": "#7B68EE" }, { "name": "Medium Spring Bud", "hex": "#C9DC87" }, { "name": "Medium Spring Green", "hex": "#00FA9A" }, { "name": "Medium Taupe", "hex": "#674C47" }, { "name": "Medium Turquoise", "hex": "#48D1CC" }, { "name": "Medium Tuscan Red", "hex": "#79443B" }, { "name": "Medium Vermilion", "hex": "#D9603B" }, { "name": "Medium Violet-Red", "hex": "#C71585" }, { "name": "Mellow Apricot", "hex": "#F8B878" }, { "name": "Mellow Yellow", "hex": "#F8DE7E" }, { "name": "Melon", "hex": "#FDBCB4" }, { "name": "Metallic Seaweed", "hex": "#0A7E8C" }, { "name": "Metallic Sunburst", "hex": "#9C7C38" }, { "name": "Mexican Pink", "hex": "#E4007C" }, { "name": "Middle Blue", "hex": "#7ED4E6" }, { "name": "Middle Blue Green", "hex": "#8DD9CC" }, { "name": "Middle Blue Purple", "hex": "#8B72BE" }, { "name": "Middle Red Purple", "hex": "#210837" }, { "name": "Middle Green", "hex": "#4D8C57" }, { "name": "Middle Green Yellow", "hex": "#ACBF60" }, { "name": "Middle Purple", "hex": "#D982B5" }, { "name": "Middle Red", "hex": "#E58E73" }, { "name": "Middle Red Purple", "hex": "#A55353" }, { "name": "Middle Yellow", "hex": "#FFEB00" }, { "name": "Middle Yellow Red", "hex": "#ECB176" }, { "name": "Midnight", "hex": "#702670" }, { "name": "Midnight Blue", "hex": "#191970" }, { "name": "Midnight Green (Eagle Green)", "hex": "#004953" }, { "name": "Mikado Yellow", "hex": "#FFC40C" }, { "name": "Milk", "hex": "#FDFFF5" }, { "name": "<NAME>", "hex": "#FFDAE9" }, { "name": "Mindaro", "hex": "#E3F988" }, { "name": "Ming", "hex": "#36747D" }, { "name": "<NAME>", "hex": "#F5E050" }, { "name": "Mint", "hex": "#3EB489" }, { "name": "<NAME>", "hex": "#F5FFFA" }, { "name": "<NAME>", "hex": "#98FF98" }, { "name": "<NAME>", "hex": "#BBB477" }, { "name": "<NAME>", "hex": "#FFE4E1" }, { "name": "Moccasin", "hex": "#FAEBD7" }, { "name": "<NAME>", "hex": "#967117" }, { "name": "<NAME>", "hex": "#73A9C2" }, { "name": "<NAME>", "hex": "#AE0C00" }, { "name": "<NAME>", "hex": "#8DA399" }, { "name": "<NAME>", "hex": "#8A9A5B" }, { "name": "<NAME>", "hex": "#30BA8F" }, { "name": "<NAME>", "hex": "#997A8D" }, { "name": "<NAME>", "hex": "#18453B" }, { "name": "<NAME>", "hex": "#306030" }, { "name": "Mulberry", "hex": "#C54B8C" }, { "name": "<NAME>", "hex": "#828E84" }, { "name": "Mustard", "hex": "#FFDB58" }, { "name": "<NAME>", "hex": "#317873" }, { "name": "Mystic", "hex": "#D65282" }, { "name": "<NAME>", "hex": "#AD4379" }, { "name": "<NAME>", "hex": "#F6ADC6" }, { "name": "<NAME>", "hex": "#2A8000" }, { "name": "<NAME>", "hex": "#FADA5E" }, { "name": "<NAME>", "hex": "#FFDEAD" }, { "name": "Navy", "hex": "#000080" }, { "name": "<NAME>", "hex": "#9457EB" }, { "name": "<NAME>", "hex": "#FFA343" }, { "name": "<NAME>", "hex": "#FE4164" }, { "name": "<NAME>", "hex": "#39FF14" }, { "name": "<NAME>", "hex": "#214FC6" }, { "name": "<NAME>", "hex": "#D7837F" }, { "name": "Nickel", "hex": "#727472" }, { "name": "Non-<NAME>", "hex": "#A4DDED" }, { "name": "North Texas Green", "hex": "#059033" }, { "name": "Nyanza", "hex": "#E9FFDB" }, { "name": "Ocean Blue", "hex": "#4F42B5" }, { "name": "Ocean Boat Blue", "hex": "#0077BE" }, { "name": "<NAME>", "hex": "#48BF91" }, { "name": "Ochre", "hex": "#CC7722" }, { "name": "<NAME>", "hex": "#008000" }, { "name": "<NAME>", "hex": "#FD5240" }, { "name": "<NAME>", "hex": "#43302E" }, { "name": "<NAME>", "hex": "#CFB53B" }, { "name": "<NAME>", "hex": "#563C5C" }, { "name": "<NAME>", "hex": "#FDF5E6" }, { "name": "<NAME>", "hex": "#796878" }, { "name": "<NAME>", "hex": "#673147" }, { "name": "<NAME>", "hex": "#867E36" }, { "name": "<NAME>", "hex": "#C08081" }, { "name": "<NAME>", "hex": "#848482" }, { "name": "Olive", "hex": "#808000" }, { "name": "<NAME> (#3)", "hex": "#6B8E23" }, { "name": "<NAME> #7", "hex": "#3C341F" }, { "name": "Olivine", "hex": "#9AB973" }, { "name": "Onyx", "hex": "#353839" }, { "name": "<NAME>", "hex": "#B784A7" }, { "name": "Orange (Color Wheel)", "hex": "#FF7F00" }, { "name": "Orange (Crayola)", "hex": "#FF7538" }, { "name": "Orange (Pantone)", "hex": "#FF5800" }, { "name": "Orange (RYB)", "hex": "#FB9902" }, { "name": "Orange (Web)", "hex": "#FFA500" }, { "name": "Orange Peel", "hex": "#FF9F00" }, { "name": "Orange-Red", "hex": "#FF4500" }, { "name": "Orange Soda", "hex": "#FA5B3D" }, { "name": "Orange-Yellow", "hex": "#F8D568" }, { "name": "Orchid", "hex": "#DA70D6" }, { "name": "Orchid Pink", "hex": "#F2BDCD" }, { "name": "Orioles Orange", "hex": "#FB4F14" }, { "name": "<NAME>", "hex": "#654321" }, { "name": "Outer Space", "hex": "#414A4C" }, { "name": "Outrageous Orange", "hex": "#FF6E4A" }, { "name": "Oxford Blue", "hex": "#002147" }, { "name": "OU Crimson Red", "hex": "#990000" }, { "name": "Pacific Blue", "hex": "#1CA9C9" }, { "name": "Pakistan Green", "hex": "#006600" }, { "name": "Palatinate Blue", "hex": "#273BE2" }, { "name": "Palatinate Purple", "hex": "#682860" }, { "name": "<NAME>", "hex": "#BCD4E6" }, { "name": "<NAME>", "hex": "#AFEEEE" }, { "name": "<NAME>", "hex": "#987654" }, { "name": "<NAME>", "hex": "#AF4035" }, { "name": "<NAME>", "hex": "#9BC4E2" }, { "name": "<NAME>", "hex": "#DDADAF" }, { "name": "<NAME>", "hex": "#DA8A67" }, { "name": "<NAME>", "hex": "#ABCDEF" }, { "name": "<NAME>", "hex": "#87D3F8" }, { "name": "<NAME>", "hex": "#E6BE8A" }, { "name": "<NAME>", "hex": "#EEE8AA" }, { "name": "<NAME>", "hex": "#98FB98" }, { "name": "<NAME>", "hex": "#DCD0FF" }, { "name": "<NAME>", "hex": "#F984E5" }, { "name": "<NAME>-Pink", "hex": "#FF99CC" }, { "name": "<NAME>", "hex": "#FADADD" }, { "name": "<NAME>", "hex": "#DDA0DD" }, { "name": "<NAME>", "hex": "#DB7093" }, { "name": "<NAME>", "hex": "#96DED1" }, { "name": "<NAME>", "hex": "#C9C0BB" }, { "name": "<NAME>", "hex": "#ECEBBD" }, { "name": "<NAME>", "hex": "#BC987E" }, { "name": "<NAME>", "hex": "#AFEEEE" }, { "name": "<NAME>", "hex": "#CC99FF" }, { "name": "<NAME>", "hex": "#DB7093" }, { "name": "<NAME>", "hex": "#6F9940" }, { "name": "<NAME>", "hex": "#78184A" }, { "name": "<NAME>", "hex": "#009B7D" }, { "name": "<NAME>", "hex": "#FFEFD5" }, { "name": "<NAME>", "hex": "#E63E62" }, { "name": "<NAME>", "hex": "#50C878" }, { "name": "<NAME>", "hex": "#D998A0" }, { "name": "<NAME>", "hex": "#AEC6CF" }, { "name": "<NAME>", "hex": "#836953" }, { "name": "<NAME>", "hex": "#CFCFC4" }, { "name": "<NAME>", "hex": "#77DD77" }, { "name": "<NAME>", "hex": "#F49AC2" }, { "name": "<NAME>", "hex": "#FFB347" }, { "name": "<NAME>", "hex": "#DEA5A4" }, { "name": "<NAME>", "hex": "#B39EB5" }, { "name": "<NAME>", "hex": "#FF6961" }, { "name": "<NAME>", "hex": "#CB99C9" }, { "name": "<NAME>", "hex": "#FDFD96" }, { "name": "Patriarch", "hex": "#800080" }, { "name": "<NAME>", "hex": "#536878" }, { "name": "Peach", "hex": "#FFE5B4" }, { "name": "Peach", "hex": "#FFCBA4" }, { "name": "Peach-Orange", "hex": "#FFCC99" }, { "name": "<NAME>", "hex": "#FFDAB9" }, { "name": "Peach-Yellow", "hex": "#FADFAD" }, { "name": "Pear", "hex": "#D1E231" }, { "name": "Pearl", "hex": "#EAE0C8" }, { "name": "<NAME>", "hex": "#88D8C0" }, { "name": "<NAME>", "hex": "#B768A2" }, { "name": "Peridot", "hex": "#E6E200" }, { "name": "Periwinkle", "hex": "#CCCCFF" }, { "name": "<NAME>", "hex": "#E12C2C" }, { "name": "<NAME>", "hex": "#1C39BB" }, { "name": "<NAME>", "hex": "#00A693" }, { "name": "<NAME>", "hex": "#32127A" }, { "name": "<NAME>", "hex": "#D99058" }, { "name": "Persian Pink", "hex": "#F77FBE" }, { "name": "<NAME>", "hex": "#701C1C" }, { "name": "<NAME>", "hex": "#CC3333" }, { "name": "<NAME>", "hex": "#FE28A2" }, { "name": "Persimmon", "hex": "#EC5800" }, { "name": "Peru", "hex": "#CD853F" }, { "name": "<NAME>", "hex": "#8BA8B7" }, { "name": "Phlox", "hex": "#DF00FF" }, { "name": "<NAME>", "hex": "#000F89" }, { "name": "<NAME>", "hex": "#123524" }, { "name": "<NAME>", "hex": "#45B1E8" }, { "name": "<NAME>", "hex": "#C30B4E" }, { "name": "<NAME>", "hex": "#FDDDE6" }, { "name": "<NAME>", "hex": "#01796F" }, { "name": "Pineapple", "hex": "#563C0D" }, { "name": "Pink", "hex": "#FFC0CB" }, { "name": "Pink (Pantone)", "hex": "#D74894" }, { "name": "P<NAME>o", "hex": "#FC74FD" }, { "name": "Pink Lace", "hex": "#FFDDF4" }, { "name": "Pink Lavender", "hex": "#D8B2D1" }, { "name": "Pink-Orange", "hex": "#FF9966" }, { "name": "<NAME>", "hex": "#E7ACCF" }, { "name": "<NAME>", "hex": "#980036" }, { "name": "<NAME>", "hex": "#F78FA7" }, { "name": "Pistachio", "hex": "#93C572" }, { "name": "<NAME>", "hex": "#391285" }, { "name": "Platinum", "hex": "#E5E4E2" }, { "name": "Plum", "hex": "#8E4585" }, { "name": "Plum (Web)", "hex": "#DDA0DD" }, { "name": "<NAME>", "hex": "#5946B2" }, { "name": "<NAME>", "hex": "#5DA493" }, { "name": "<NAME>", "hex": "#86608E" }, { "name": "Popstar", "hex": "#BE4F62" }, { "name": "<NAME>", "hex": "#FF5A36" }, { "name": "<NAME>", "hex": "#B0E0E6" }, { "name": "<NAME>", "hex": "#FF85CF" }, { "name": "<NAME>", "hex": "#F58025" }, { "name": "Prune", "hex": "#701C1C" }, { "name": "<NAME>", "hex": "#003153" }, { "name": "<NAME>", "hex": "#DF00FF" }, { "name": "Puce", "hex": "#CC8899" }, { "name": "<NAME>", "hex": "#722F37" }, { "name": "<NAME> (UPS Brown)", "hex": "#644117" }, { "name": "<NAME>", "hex": "#3B331C" }, { "name": "Pumpkin", "hex": "#FF7518" }, { "name": "Purple (HTML)", "hex": "#800080" }, { "name": "Purple (Munsell)", "hex": "#9F00C5" }, { "name": "Purple (X11)", "hex": "#A020F0" }, { "name": "Pur<NAME>", "hex": "#69359C" }, { "name": "<NAME>esty", "hex": "#9678B6" }, { "name": "<NAME>", "hex": "#4E5180" }, { "name": "<NAME>", "hex": "#FE4EDA" }, { "name": "<NAME>", "hex": "#9C51B6" }, { "name": "<NAME>", "hex": "#50404D" }, { "name": "Purpureus", "hex": "#9A4EAE" }, { "name": "Quartz", "hex": "#51484F" }, { "name": "Queen Blue", "hex": "#436B95" }, { "name": "<NAME>", "hex": "#E8CCD7" }, { "name": "<NAME>", "hex": "#A6A6A6" }, { "name": "<NAME>", "hex": "#8E3A59" }, { "name": "Rackley", "hex": "#5D8AA8" }, { "name": "<NAME>", "hex": "#FF355E" }, { "name": "<NAME>", "hex": "#242124" }, { "name": "Rajah", "hex": "#FBAB60" }, { "name": "Raspberry", "hex": "#E30B5D" }, { "name": "<NAME>", "hex": "#915F6D" }, { "name": "<NAME>", "hex": "#E25098" }, { "name": "<NAME>", "hex": "#B3446C" }, { "name": "<NAME>", "hex": "#D68A59" }, { "name": "<NAME>", "hex": "#826644" }, { "name": "<NAME>", "hex": "#FF33CC" }, { "name": "Razzmatazz", "hex": "#E3256B" }, { "name": "<NAME>", "hex": "#8D4E85" }, { "name": "<NAME>", "hex": "#663399" }, { "name": "Red", "hex": "#FF0000" }, { "name": "Red (Crayola)", "hex": "#EE204D" }, { "name": "Red (Munsell)", "hex": "#F2003C" }, { "name": "Red (NCS)", "hex": "#C40233" }, { "name": "Red (Pantone)", "hex": "#ED2939" }, { "name": "Red (Pigment)", "hex": "#ED1C24" }, { "name": "Red (RYB)", "hex": "#FE2712" }, { "name": "Red-Brown", "hex": "#A52A2A" }, { "name": "<NAME>", "hex": "#860111" }, { "name": "Red-Orange", "hex": "#FF5349" }, { "name": "Red-Purple", "hex": "#E40078" }, { "name": "<NAME>", "hex": "#FD3A4A" }, { "name": "Red-Violet", "hex": "#C71585" }, { "name": "Redwood", "hex": "#A45A52" }, { "name": "Regalia", "hex": "#522D80" }, { "name": "<NAME>", "hex": "#000000" }, { "name": "<NAME>", "hex": "#002387" }, { "name": "Rhythm", "hex": "#777696" }, { "name": "<NAME>", "hex": "#004040" }, { "name": "<NAME> (FOGRA29)", "hex": "#010B13" }, { "name": "<NAME> (FOGRA39)", "hex": "#010203" }, { "name": "<NAME>", "hex": "#F1A7FE" }, { "name": "<NAME>", "hex": "#D70040" }, { "name": "<NAME>", "hex": "#0892D0" }, { "name": "<NAME>", "hex": "#A76BCF" }, { "name": "<NAME>", "hex": "#B666D2" }, { "name": "<NAME>", "hex": "#B03060" }, { "name": "<NAME>", "hex": "#444C38" }, { "name": "<NAME>", "hex": "#704241" }, { "name": "<NAME>", "hex": "#00CCCC" }, { "name": "<NAME>", "hex": "#8A7F80" }, { "name": "<NAME>", "hex": "#838996" }, { "name": "Rose", "hex": "#FF007F" }, { "name": "<NAME>", "hex": "#F9429E" }, { "name": "<NAME>", "hex": "#9E5E6F" }, { "name": "<NAME>", "hex": "#674846" }, { "name": "<NAME>", "hex": "#B76E79" }, { "name": "<NAME>", "hex": "#E32636" }, { "name": "<NAME>", "hex": "#FF66CC" }, { "name": "<NAME>", "hex": "#AA98A9" }, { "name": "<NAME>", "hex": "#C21E56" }, { "name": "<NAME>", "hex": "#905D5D" }, { "name": "<NAME>", "hex": "#AB4E52" }, { "name": "Rosewood", "hex": "#65000B" }, { "name": "<NAME>", "hex": "#D40000" }, { "name": "<NAME>", "hex": "#BC8F8F" }, { "name": "<NAME>", "hex": "#0038A8" }, { "name": "Royal Blue", "hex": "#002366" }, { "name": "<NAME>", "hex": "#4169E1" }, { "name": "<NAME>", "hex": "#CA2C92" }, { "name": "<NAME>", "hex": "#7851A9" }, { "name": "<NAME>", "hex": "#FADA5E" }, { "name": "Ruber", "hex": "#CE4676" }, { "name": "<NAME>", "hex": "#D10056" }, { "name": "Ruby", "hex": "#E0115F" }, { "name": "<NAME>", "hex": "#9B111E" }, { "name": "Ruddy", "hex": "#FF0028" }, { "name": "<NAME>", "hex": "#BB6528" }, { "name": "<NAME>", "hex": "#E18E96" }, { "name": "Rufous", "hex": "#A81C07" }, { "name": "Russet", "hex": "#80461B" }, { "name": "<NAME>", "hex": "#679267" }, { "name": "<NAME>", "hex": "#32174D" }, { "name": "Rust", "hex": "#B7410E" }, { "name": "<NAME>", "hex": "#DA2C43" }, { "name": "Sacramento State Green", "hex": "#00563F" }, { "name": "<NAME>", "hex": "#8B4513" }, { "name": "<NAME>", "hex": "#FF7800" }, { "name": "Safety Orange (Blaze Orange)", "hex": "#FF6700" }, { "name": "<NAME>", "hex": "#EED202" }, { "name": "Saffron", "hex": "#F4C430" }, { "name": "Sage", "hex": "#BCB88A" }, { "name": "<NAME>", "hex": "#23297A" }, { "name": "Salmon", "hex": "#FA8072" }, { "name": "<NAME>", "hex": "#FF91A4" }, { "name": "Sand", "hex": "#C2B280" }, { "name": "<NAME>", "hex": "#967117" }, { "name": "Sandstorm", "hex": "#ECD540" }, { "name": "<NAME>", "hex": "#F4A460" }, { "name": "<NAME>", "hex": "#FDD9B5" }, { "name": "<NAME>", "hex": "#967117" }, { "name": "Sangria", "hex": "#92000A" }, { "name": "<NAME>", "hex": "#507D2A" }, { "name": "Sapphire", "hex": "#0F52BA" }, { "name": "<NAME>", "hex": "#0067A5" }, { "name": "<NAME>", "hex": "#FF4681" }, { "name": "<NAME>", "hex": "#CBA135" }, { "name": "Scarlet", "hex": "#FF2400" }, { "name": "Scarlet", "hex": "#FD0E35" }, { "name": "<NAME>", "hex": "#FF91AF" }, { "name": "School Bus Yellow", "hex": "#FFD800" }, { "name": "Screamin' Green", "hex": "#66FF66" }, { "name": "Sea Blue", "hex": "#006994" }, { "name": "Sea Foam Green", "hex": "#9FE2BF" }, { "name": "Sea Green", "hex": "#2E8B57" }, { "name": "Sea Serpent", "hex": "#4BC7CF" }, { "name": "Seal Brown", "hex": "#59260B" }, { "name": "Seashell", "hex": "#FFF5EE" }, { "name": "Selective Yellow", "hex": "#FFBA00" }, { "name": "Sepia", "hex": "#704214" }, { "name": "Shadow", "hex": "#8A795D" }, { "name": "Shadow Blue", "hex": "#778BA5" }, { "name": "Shampoo", "hex": "#FFCFF1" }, { "name": "Shamrock Green", "hex": "#009E60" }, { "name": "<NAME>", "hex": "#8FD400" }, { "name": "Shimmering Blush", "hex": "#D98695" }, { "name": "<NAME>", "hex": "#5FA778" }, { "name": "Shocking Pink", "hex": "#FC0FC0" }, { "name": "Shocking Pink (Crayola)", "hex": "#FF6FFF" }, { "name": "Sienna", "hex": "#882D17" }, { "name": "Silver", "hex": "#C0C0C0" }, { "name": "Silver Chalice", "hex": "#ACACAC" }, { "name": "Silver Lake Blue", "hex": "#5D89BA" }, { "name": "Silver Pink", "hex": "#C4AEAD" }, { "name": "Silver Sand", "hex": "#BFC1C2" }, { "name": "Sinopia", "hex": "#CB410B" }, { "name": "Sizzling Red", "hex": "#FF3855" }, { "name": "Sizzling Sunrise", "hex": "#FFDB00" }, { "name": "Skobeloff", "hex": "#007474" }, { "name": "Sky Blue", "hex": "#87CEEB" }, { "name": "Sky Magenta", "hex": "#CF71AF" }, { "name": "Slate Blue", "hex": "#6A5ACD" }, { "name": "Slate Gray", "hex": "#708090" }, { "name": "Smalt (Dark Powder Blue)", "hex": "#003399" }, { "name": "<NAME>", "hex": "#299617" }, { "name": "<NAME>", "hex": "#FF6D3A" }, { "name": "Smitten", "hex": "#C84186" }, { "name": "Smoke", "hex": "#738276" }, { "name": "<NAME>", "hex": "#832A0D" }, { "name": "Smoky Black", "hex": "#100C08" }, { "name": "<NAME>", "hex": "#933D41" }, { "name": "Snow", "hex": "#FFFAFA" }, { "name": "Soap", "hex": "#CEC8EF" }, { "name": "Solid Pink", "hex": "#893843" }, { "name": "<NAME>", "hex": "#757575" }, { "name": "<NAME>", "hex": "#9E1316" }, { "name": "Space Cadet", "hex": "#1D2951" }, { "name": "Spanish Bistre", "hex": "#807532" }, { "name": "Spanish Blue", "hex": "#0070B8" }, { "name": "Spanish Carmine", "hex": "#D10047" }, { "name": "Spanish Crimson", "hex": "#E51A4C" }, { "name": "Spanish Gray", "hex": "#989898" }, { "name": "Spanish Green", "hex": "#009150" }, { "name": "Spanish Orange", "hex": "#E86100" }, { "name": "Spanish Pink", "hex": "#F7BFBE" }, { "name": "Spanish Red", "hex": "#E60026" }, { "name": "Spanish Sky Blue", "hex": "#00FFFF" }, { "name": "Spanish Violet", "hex": "#4C2882" }, { "name": "Spanish Viridian", "hex": "#007F5C" }, { "name": "Spicy Mix", "hex": "#8B5f4D" }, { "name": "<NAME> Ball", "hex": "#0FC0FC" }, { "name": "Spring Bud", "hex": "#A7FC00" }, { "name": "Spring Frost", "hex": "#87FF2A" }, { "name": "Spring Green", "hex": "#00FF7F" }, { "name": "Star Command Blue", "hex": "#007BB8" }, { "name": "<NAME>", "hex": "#4682B4" }, { "name": "<NAME>", "hex": "#CC33CC" }, { "name": "<NAME>", "hex": "#5F8A8B" }, { "name": "<NAME>", "hex": "#FADA5E" }, { "name": "Stizza", "hex": "#990000" }, { "name": "Stormcloud", "hex": "#4F666A" }, { "name": "Straw", "hex": "#E4D96F" }, { "name": "Strawberry", "hex": "#FC5A8D" }, { "name": "<NAME>", "hex": "#914E75" }, { "name": "<NAME>", "hex": "#FF404C" }, { "name": "Sunglow", "hex": "#FFCC33" }, { "name": "Sunny", "hex": "#F2F27A" }, { "name": "Sunray", "hex": "#E3AB57" }, { "name": "Sunset", "hex": "#FAD6A5" }, { "name": "Sunset Orange", "hex": "#FD5E53" }, { "name": "Super Pink", "hex": "#CF6BA9" }, { "name": "<NAME>", "hex": "#A83731" }, { "name": "Tan", "hex": "#D2B48C" }, { "name": "Tangelo", "hex": "#F94D00" }, { "name": "Tangerine", "hex": "#F28500" }, { "name": "<NAME>", "hex": "#FFCC00" }, { "name": "<NAME>", "hex": "#E4717A" }, { "name": "<NAME>", "hex": "#FB4D46" }, { "name": "Taupe", "hex": "#483C32" }, { "name": "<NAME>", "hex": "#8B8589" }, { "name": "<NAME>", "hex": "#D0F0C0" }, { "name": "<NAME>", "hex": "#F88379" }, { "name": "<NAME>", "hex": "#F4C2C2" }, { "name": "Teal", "hex": "#008080" }, { "name": "<NAME>", "hex": "#367588" }, { "name": "<NAME>", "hex": "#99E6B3" }, { "name": "<NAME>", "hex": "#00827F" }, { "name": "Telemagenta", "hex": "#CF3476" }, { "name": "<NAME>)", "hex": "#CD5700" }, { "name": "<NAME>", "hex": "#E2725B" }, { "name": "Thistle", "hex": "#D8BFD8" }, { "name": "<NAME>", "hex": "#DE6FA1" }, { "name": "<NAME>", "hex": "#FC89AC" }, { "name": "<NAME>", "hex": "#0ABAB5" }, { "name": "<NAME>", "hex": "#E08D3C" }, { "name": "Timberwolf", "hex": "#DBD7D2" }, { "name": "<NAME>", "hex": "#EEE600" }, { "name": "Tomato", "hex": "#FF6347" }, { "name": "Toolbox", "hex": "#746CC0" }, { "name": "Topaz", "hex": "#FFC87C" }, { "name": "<NAME>", "hex": "#FD0E35" }, { "name": "<NAME>", "hex": "#808080" }, { "name": "<NAME>", "hex": "#00755E" }, { "name": "<NAME>", "hex": "#CDA4DE" }, { "name": "<NAME>", "hex": "#0073CF" }, { "name": "<NAME>", "hex": "#3E8EDE" }, { "name": "Tulip", "hex": "#FF878D" }, { "name": "Tumbleweed", "hex": "#DEAA88" }, { "name": "<NAME>", "hex": "#B57281" }, { "name": "Turquoise", "hex": "#40E0D0" }, { "name": "<NAME>", "hex": "#00FFEF" }, { "name": "<NAME>", "hex": "#A0D6B4" }, { "name": "Turquoise Surf", "hex": "#00C5CD" }, { "name": "<NAME>", "hex": "#8A9A5B" }, { "name": "Tuscan", "hex": "#FAD6A5" }, { "name": "<NAME>", "hex": "#6F4E37" }, { "name": "<NAME>", "hex": "#7C4848" }, { "name": "<NAME>", "hex": "#A67B5B" }, { "name": "Tuscany", "hex": "#C09999" }, { "name": "<NAME>", "hex": "#8A496B" }, { "name": "<NAME>", "hex": "#66023C" }, { "name": "<NAME>", "hex": "#0033AA" }, { "name": "<NAME>", "hex": "#D9004C" }, { "name": "Ube", "hex": "#8878C3" }, { "name": "<NAME>", "hex": "#536895" }, { "name": "<NAME>", "hex": "#FFB300" }, { "name": "<NAME>", "hex": "#3CD070" }, { "name": "Ultramarine", "hex": "#3F00FF" }, { "name": "Ultramarine Blue", "hex": "#4166F5" }, { "name": "<NAME>", "hex": "#FF6FFF" }, { "name": "<NAME>", "hex": "#FC6C85" }, { "name": "Umber", "hex": "#635147" }, { "name": "<NAME>", "hex": "#FFDDCA" }, { "name": "United Nations Blue", "hex": "#5B92E5" }, { "name": "University Of California Gold", "hex": "#B78727" }, { "name": "<NAME>", "hex": "#FFFF66" }, { "name": "UP Forest Green", "hex": "#014421" }, { "name": "UP Maroon", "hex": "#7B1113" }, { "name": "<NAME>", "hex": "#AE2029" }, { "name": "Urobilin", "hex": "#E1AD21" }, { "name": "<NAME>", "hex": "#004F98" }, { "name": "USC Cardinal", "hex": "#990000" }, { "name": "<NAME>", "hex": "#FFCC00" }, { "name": "University Of Tennessee Orange", "hex": "#F77F00" }, { "name": "<NAME>", "hex": "#D3003F" }, { "name": "<NAME>", "hex": "#664228" }, { "name": "Vanilla", "hex": "#F3E5AB" }, { "name": "<NAME>", "hex": "#F38FA9" }, { "name": "<NAME>", "hex": "#C5B358" }, { "name": "<NAME>", "hex": "#C80815" }, { "name": "Verdigris", "hex": "#43B3AE" }, { "name": "Vermilion", "hex": "#E34234" }, { "name": "Vermilion", "hex": "#D9381E" }, { "name": "Veronica", "hex": "#A020F0" }, { "name": "Very Light Azure", "hex": "#74BBFB" }, { "name": "Very Light Blue", "hex": "#6666FF" }, { "name": "Very Light Malachite Green", "hex": "#64E986" }, { "name": "Very Light Tangelo", "hex": "#FFB077" }, { "name": "Very Pale Orange", "hex": "#FFDFBF" }, { "name": "Very Pale Yellow", "hex": "#FFFFBF" }, { "name": "Violet", "hex": "#8F00FF" }, { "name": "Violet (Color Wheel)", "hex": "#7F00FF" }, { "name": "Violet (RYB)", "hex": "#8601AF" }, { "name": "Violet (Web)", "hex": "#EE82EE" }, { "name": "Violet-Blue", "hex": "#324AB2" }, { "name": "Violet-Red", "hex": "#F75394" }, { "name": "Viridian", "hex": "#40826D" }, { "name": "<NAME>", "hex": "#009698" }, { "name": "<NAME>", "hex": "#7C9ED9" }, { "name": "<NAME>", "hex": "#CC9900" }, { "name": "<NAME>", "hex": "#922724" }, { "name": "<NAME>", "hex": "#9F1D35" }, { "name": "<NAME>", "hex": "#DA1D81" }, { "name": "<NAME>", "hex": "#00AAEE" }, { "name": "<NAME>", "hex": "#CC0033" }, { "name": "<NAME>", "hex": "#FF9900" }, { "name": "<NAME>", "hex": "#A6D608" }, { "name": "<NAME>", "hex": "#00CC33" }, { "name": "<NAME>", "hex": "#B80CE3" }, { "name": "<NAME>", "hex": "#FF5F00" }, { "name": "<NAME>", "hex": "#FFA000" }, { "name": "<NAME>", "hex": "#CC00FF" }, { "name": "<NAME>", "hex": "#FF006C" }, { "name": "<NAME>", "hex": "#F70D1A" }, { "name": "<NAME>", "hex": "#DF6124" }, { "name": "<NAME>", "hex": "#00CCFF" }, { "name": "<NAME>", "hex": "#F07427" }, { "name": "<NAME>", "hex": "#FFA089" }, { "name": "<NAME>", "hex": "#E56024" }, { "name": "<NAME>", "hex": "#9F00FF" }, { "name": "<NAME>", "hex": "#FFE302" }, { "name": "Volt", "hex": "#CEFF00" }, { "name": "<NAME>", "hex": "#34B233" }, { "name": "<NAME>", "hex": "#004242" }, { "name": "Waterspout", "hex": "#A4F4F9" }, { "name": "<NAME>", "hex": "#7C98AB" }, { "name": "Wenge", "hex": "#645452" }, { "name": "Wheat", "hex": "#F5DEB3" }, { "name": "White", "hex": "#FFFFFF" }, { "name": "<NAME>", "hex": "#F5F5F5" }, { "name": "<NAME>", "hex": "#A2ADD0" }, { "name": "<NAME>", "hex": "#D470A2" }, { "name": "<NAME>", "hex": "#FF43A4" }, { "name": "<NAME>", "hex": "#FC6C85" }, { "name": "<NAME>", "hex": "#FD5800" }, { "name": "<NAME>", "hex": "#A75502" }, { "name": "Wine", "hex": "#722F37" }, { "name": "<NAME>", "hex": "#673147" }, { "name": "<NAME>", "hex": "#FF007C" }, { "name": "<NAME>", "hex": "#A0E6FF" }, { "name": "<NAME>", "hex": "#56887D" }, { "name": "Wisteria", "hex": "#C9A0DC" }, { "name": "<NAME>", "hex": "#C19A6B" }, { "name": "Xanadu", "hex": "#738678" }, { "name": "Y<NAME>", "hex": "#0F4D92" }, { "name": "<NAME>", "hex": "#1C2841" }, { "name": "Yellow", "hex": "#FFFF00" }, { "name": "Yellow (Crayola)", "hex": "#FCE883" }, { "name": "Yellow (Munsell)", "hex": "#EFCC00" }, { "name": "Yellow (NCS)", "hex": "#FFD300" }, { "name": "Yellow (Pantone)", "hex": "#FEDF00" }, { "name": "Yellow (Process)", "hex": "#FFEF00" }, { "name": "Yellow (RYB)", "hex": "#FEFE33" }, { "name": "Yellow-Green", "hex": "#9ACD32" }, { "name": "Yellow Orange", "hex": "#FFAE42" }, { "name": "Yellow Rose", "hex": "#FFF000" }, { "name": "Yellow Sunshine", "hex": "#FFF700" }, { "name": "Zaffre", "hex": "#0014A8" }, { "name": "<NAME>", "hex": "#2C1608" }, { "name": "Zomp", "hex": "#39A78E" } ]`
data/colors.go
0.500977
0.523116
colors.go
starcoder
package stats import ( "math" "strconv" "time" ) type Value struct { typ Type pad int32 bits uint64 } func MustValueOf(v Value) Value { if v.Type() == Invalid { panic("stats.MustValueOf received a value of unsupported type") } return v } func ValueOf(v interface{}) Value { switch x := v.(type) { case Value: return x case nil: return Value{} case bool: return boolValue(x) case int: return intValue(x) case int8: return int8Value(x) case int16: return int16Value(x) case int32: return int32Value(x) case int64: return int64Value(x) case uint: return uintValue(x) case uint8: return uint8Value(x) case uint16: return uint16Value(x) case uint32: return uint32Value(x) case uint64: return uint64Value(x) case uintptr: return uintptrValue(x) case float32: return float32Value(x) case float64: return float64Value(x) case time.Duration: return durationValue(x) default: return Value{typ: Invalid} } } func boolValue(v bool) Value { return Value{typ: Bool, bits: boolBits(v)} } func intValue(v int) Value { return int64Value(int64(v)) } func int8Value(v int8) Value { return int64Value(int64(v)) } func int16Value(v int16) Value { return int64Value(int64(v)) } func int32Value(v int32) Value { return int64Value(int64(v)) } func int64Value(v int64) Value { return Value{typ: Int, bits: uint64(v)} } func uintValue(v uint) Value { return uint64Value(uint64(v)) } func uint8Value(v uint8) Value { return uint64Value(uint64(v)) } func uint16Value(v uint16) Value { return uint64Value(uint64(v)) } func uint32Value(v uint32) Value { return uint64Value(uint64(v)) } func uint64Value(v uint64) Value { return Value{typ: Uint, bits: v} } func uintptrValue(v uintptr) Value { return uint64Value(uint64(v)) } func float32Value(v float32) Value { return float64Value(float64(v)) } func float64Value(v float64) Value { return Value{typ: Float, bits: math.Float64bits(v)} } func durationValue(v time.Duration) Value { return Value{typ: Duration, bits: uint64(v)} } func (v Value) Type() Type { return v.typ } func (v Value) Bool() bool { return v.bits != 0 } func (v Value) Int() int64 { return int64(v.bits) } func (v Value) Uint() uint64 { return v.bits } func (v Value) Float() float64 { return math.Float64frombits(v.bits) } func (v Value) Duration() time.Duration { return time.Duration(v.bits) } func (v Value) Interface() interface{} { switch v.Type() { case Null: return nil case Bool: return v.Bool() case Int: return v.Int() case Uint: return v.Uint() case Float: return v.Float() case Duration: return v.Duration() default: panic("unknown type found in a stats.Value") } } func (v Value) String() string { switch v.Type() { case Null: return "<nil>" case Bool: return strconv.FormatBool(v.Bool()) case Int: return strconv.FormatInt(v.Int(), 10) case Uint: return strconv.FormatUint(v.Uint(), 10) case Float: return strconv.FormatFloat(v.Float(), 'g', -1, 64) case Duration: return v.Duration().String() default: return "<unknown>" } } type Type int32 const ( Null Type = iota Bool Int Uint Float Duration Invalid ) func (t Type) String() string { switch t { case Null: return "<nil>" case Bool: return "bool" case Int: return "int64" case Uint: return "uint64" case Float: return "float64" case Duration: return "time.Duration" default: return "<unknown>" } } func (t Type) GoString() string { switch t { case Null: return "stats.Null" case Bool: return "stats.Bool" case Int: return "stats.Int" case Uint: return "stats.Uint" case Float: return "stats.Float" case Duration: return "stats.Duration" default: return "stats.Type(" + strconv.Itoa(int(t)) + ")" } } func boolBits(v bool) uint64 { if v { return 1 } return 0 }
value.go
0.619817
0.476275
value.go
starcoder
package assertions import ( "fmt" "reflect" "strings" ) // ShouldStartWith receives exactly 2 string parameters and ensures that the first starts with the second. func ShouldStartWith(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } value, valueIsString := actual.(string) prefix, prefixIsString := expected[0].(string) if !valueIsString || !prefixIsString { return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) } return shouldStartWith(value, prefix) } func shouldStartWith(value, prefix string) string { if !strings.HasPrefix(value, prefix) { shortval := value if len(shortval) > len(prefix) { shortval = shortval[:len(prefix)] + "..." } return serializer.serialize(prefix, shortval, fmt.Sprintf(shouldHaveStartedWith, value, prefix)) } return success } // ShouldNotStartWith receives exactly 2 string parameters and ensures that the first does not start with the second. func ShouldNotStartWith(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } value, valueIsString := actual.(string) prefix, prefixIsString := expected[0].(string) if !valueIsString || !prefixIsString { return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) } return shouldNotStartWith(value, prefix) } func shouldNotStartWith(value, prefix string) string { if strings.HasPrefix(value, prefix) { if value == "" { value = "<empty>" } if prefix == "" { prefix = "<empty>" } return fmt.Sprintf(shouldNotHaveStartedWith, value, prefix) } return success } // ShouldEndWith receives exactly 2 string parameters and ensures that the first ends with the second. func ShouldEndWith(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } value, valueIsString := actual.(string) suffix, suffixIsString := expected[0].(string) if !valueIsString || !suffixIsString { return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) } return shouldEndWith(value, suffix) } func shouldEndWith(value, suffix string) string { if !strings.HasSuffix(value, suffix) { shortval := value if len(shortval) > len(suffix) { shortval = "..." + shortval[len(shortval)-len(suffix):] } return serializer.serialize(suffix, shortval, fmt.Sprintf(shouldHaveEndedWith, value, suffix)) } return success } // ShouldEndWith receives exactly 2 string parameters and ensures that the first does not end with the second. func ShouldNotEndWith(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } value, valueIsString := actual.(string) suffix, suffixIsString := expected[0].(string) if !valueIsString || !suffixIsString { return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) } return shouldNotEndWith(value, suffix) } func shouldNotEndWith(value, suffix string) string { if strings.HasSuffix(value, suffix) { if value == "" { value = "<empty>" } if suffix == "" { suffix = "<empty>" } return fmt.Sprintf(shouldNotHaveEndedWith, value, suffix) } return success } // ShouldContainSubstring receives exactly 2 string parameters and ensures that the first contains the second as a substring. func ShouldContainSubstring(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } long, longOk := actual.(string) short, shortOk := expected[0].(string) if !longOk || !shortOk { return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) } if !strings.Contains(long, short) { return serializer.serialize(expected[0], actual, fmt.Sprintf(shouldHaveContainedSubstring, long, short)) } return success } // ShouldNotContainSubstring receives exactly 2 string parameters and ensures that the first does NOT contain the second as a substring. func ShouldNotContainSubstring(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } long, longOk := actual.(string) short, shortOk := expected[0].(string) if !longOk || !shortOk { return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) } if strings.Contains(long, short) { return fmt.Sprintf(shouldNotHaveContainedSubstring, long, short) } return success } // ShouldBeBlank receives exactly 1 string parameter and ensures that it is equal to "". func ShouldBeBlank(actual interface{}, expected ...interface{}) string { if fail := need(0, expected); fail != success { return fail } value, ok := actual.(string) if !ok { return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) } if value != "" { return serializer.serialize("", value, fmt.Sprintf(shouldHaveBeenBlank, value)) } return success } // ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is equal to "". func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string { if fail := need(0, expected); fail != success { return fail } value, ok := actual.(string) if !ok { return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual)) } if value == "" { return shouldNotHaveBeenBlank } return success } // ShouldEqualWithout receives exactly 3 string parameters and ensures that the first is equal to the second // after removing all instances of the third from the first using strings.Replace(first, third, "", -1). func ShouldEqualWithout(actual interface{}, expected ...interface{}) string { if fail := need(2, expected); fail != success { return fail } actualString, ok1 := actual.(string) expectedString, ok2 := expected[0].(string) replace, ok3 := expected[1].(string) if !ok1 || !ok2 || !ok3 { return fmt.Sprintf(shouldAllBeStrings, []reflect.Type{ reflect.TypeOf(actual), reflect.TypeOf(expected[0]), reflect.TypeOf(expected[1]), }) } replaced := strings.Replace(actualString, replace, "", -1) if replaced == expectedString { return "" } return fmt.Sprintf("Expected '%s' to equal '%s' but without any '%s' (but it didn't).", actualString, expectedString, replace) } // ShouldEqualTrimSpace receives exactly 2 string parameters and ensures that the first is equal to the second // after removing all leading and trailing whitespace using strings.TrimSpace(first). func ShouldEqualTrimSpace(actual interface{}, expected ...interface{}) string { if fail := need(1, expected); fail != success { return fail } actualString, valueIsString := actual.(string) _, value2IsString := expected[0].(string) if !valueIsString || !value2IsString { return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0])) } actualString = strings.TrimSpace(actualString) return ShouldEqual(actualString, expected[0]) }
vendor/github.com/smartystreets/assertions/strings.go
0.721056
0.470311
strings.go
starcoder
package gittest import ( "crypto/rand" "io" "io/ioutil" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/internal/git" "gitlab.com/gitlab-org/gitaly/internal/gitaly/config" ) // TestDeltaIslands is based on the tests in // https://github.com/git/git/blob/master/t/t5320-delta-islands.sh . func TestDeltaIslands(t *testing.T, cfg config.Cfg, repoPath string, repack func() error) { // Create blobs that we expect Git to use delta compression on. blob1, err := ioutil.ReadAll(io.LimitReader(rand.Reader, 100000)) require.NoError(t, err) blob2 := append(blob1, "\nblob 2"...) // Assume Git prefers the largest blob as the delta base. badBlob := append(blob2, "\nbad blob"...) blob1ID := commitBlob(t, cfg, repoPath, "refs/heads/branch1", blob1) blob2ID := commitBlob(t, cfg, repoPath, "refs/tags/tag2", blob2) // The bad blob will only be reachable via a non-standard ref. Because of // that it should be excluded from delta chains in the main island. badBlobID := commitBlob(t, cfg, repoPath, "refs/bad/ref3", badBlob) // So far we have create blobs and commits but they will be in loose // object files; we want them to be delta compressed. Run repack to make // that happen. Exec(t, cfg, "-C", repoPath, "repack", "-ad") assert.Equal(t, badBlobID, deltaBase(t, cfg, repoPath, blob1ID), "expect blob 1 delta base to be bad blob after test setup") assert.Equal(t, badBlobID, deltaBase(t, cfg, repoPath, blob2ID), "expect blob 2 delta base to be bad blob after test setup") require.NoError(t, repack(), "repack after delta island setup") assert.Equal(t, blob2ID, deltaBase(t, cfg, repoPath, blob1ID), "blob 1 delta base should be blob 2 after repack") // blob2 is the bigger of the two so it should be the delta base assert.Equal(t, git.ZeroOID.String(), deltaBase(t, cfg, repoPath, blob2ID), "blob 2 should not be delta compressed after repack") } func commitBlob(t *testing.T, cfg config.Cfg, repoPath, ref string, content []byte) string { blobID := WriteBlob(t, cfg, repoPath, content) // No parent, that means this will be an initial commit. Not very // realistic but it doesn't matter for delta compression. commitID := WriteCommit(t, cfg, repoPath, WithTreeEntries(TreeEntry{ Mode: "100644", OID: blobID, Path: "file", }), WithParents(), ) Exec(t, cfg, "-C", repoPath, "update-ref", ref, commitID.String()) return blobID.String() } func deltaBase(t *testing.T, cfg config.Cfg, repoPath string, blobID string) string { catfileOut := ExecStream(t, cfg, strings.NewReader(blobID), "-C", repoPath, "cat-file", "--batch-check=%(deltabase)") return chompToString(catfileOut) } func chompToString(s []byte) string { return strings.TrimSuffix(string(s), "\n") }
internal/git/gittest/delta_islands.go
0.77586
0.584627
delta_islands.go
starcoder
package parse import "nli-go/lib/mentalese" type workingStep struct { states []chartState nodes []*mentalese.ParseTreeNode stateIndex int } func (step workingStep) getCurrentState() chartState { return step.states[step.stateIndex - 1] } func (step workingStep) getCurrentNode() *mentalese.ParseTreeNode { return step.nodes[step.stateIndex - 1] } type treeInProgress struct { root *mentalese.ParseTreeNode path []workingStep } func (tip treeInProgress) clone() treeInProgress { newRoot, aMap := tip.cloneTree(tip.root) newSteps := []workingStep{} for _, step := range tip.path { newNodes := []*mentalese.ParseTreeNode{} for _, node := range step.nodes { newNode, _ := aMap[node] newNodes = append(newNodes, newNode) } newStep := workingStep{ states: step.states, nodes: newNodes, stateIndex: step.stateIndex, } newSteps = append(newSteps, newStep) } newStack := treeInProgress{ root: newRoot, path: newSteps, } return newStack } func (tip *treeInProgress) cloneTree(tree *mentalese.ParseTreeNode) (*mentalese.ParseTreeNode, map[*mentalese.ParseTreeNode]*mentalese.ParseTreeNode) { aMap := map[*mentalese.ParseTreeNode]*mentalese.ParseTreeNode{} newTree := tip.cloneNodeWithMap(tree, &aMap) return newTree, aMap } func (tip *treeInProgress) cloneNodeWithMap(node *mentalese.ParseTreeNode, aMap *map[*mentalese.ParseTreeNode]*mentalese.ParseTreeNode) *mentalese.ParseTreeNode { constituents := []*mentalese.ParseTreeNode{} for _, constituent := range node.Constituents { clone := tip.cloneNodeWithMap(constituent, aMap) constituents = append(constituents, clone) } newNode := &mentalese.ParseTreeNode{ Category: node.Category, Constituents: constituents, Form: node.Form, Rule: node.Rule, } (*aMap)[node] = newNode return newNode } func (tip treeInProgress) advance() (treeInProgress, bool) { newTip := tip done := true if len(newTip.path) > 0 { step := &newTip.path[len(newTip.path)-1] if step.stateIndex < len(step.states) { step.stateIndex++ } else { return newTip.pop().advance() } done = false } return newTip, done } func (tip treeInProgress) peek() workingStep { if len(tip.path) == 0 { panic("empty stack!") } else { return tip.path[len(tip.path) - 1] } } func (tip treeInProgress) push(step workingStep) treeInProgress { newStack := tip newStack.path = append(newStack.path, step) return newStack } func (tip treeInProgress) pop() treeInProgress { newStack := tip newStack.path = newStack.path[0:len(newStack.path) - 1] return newStack }
lib/parse/working_stack.go
0.610802
0.45175
working_stack.go
starcoder