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 xlsx import ( "fmt" "math" "strconv" ) // CellType is an int type for storing metadata about the data type in the cell. type CellType int // Known types for cell values. const ( CellTypeString CellType = iota CellTypeFormula CellTypeNumeric CellTypeBool CellTypeInline CellTypeError ) // Cell is a high level structure intended to provide user access to // the contents of Cell within an xlsx.Row. type Cell struct { Row *Row Value string formula string style *Style numFmt string date1904 bool Hidden bool cellType CellType } // CellInterface defines the public API of the Cell. type CellInterface interface { String() string FormattedValue() string } // NewCell creates a cell and adds it to a row. func NewCell(r *Row) *Cell { return &Cell{style: NewStyle(), Row: r} } // Type returns the CellType of a cell. See CellType constants for more details. func (c *Cell) Type() CellType { return c.cellType } // SetString sets the value of a cell to a string. func (c *Cell) SetString(s string) { c.Value = s c.formula = "" c.cellType = CellTypeString } // String returns the value of a Cell as a string. func (c *Cell) String() string { return c.FormattedValue() } // SetFloat sets the value of a cell to a float. func (c *Cell) SetFloat(n float64) { c.SetFloatWithFormat(n, "0.00e+00") } /* The following are samples of format samples. * "0.00e+00" * "0", "#,##0" * "0.00", "#,##0.00", "@" * "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)" * "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)" * "0%", "0.00%" * "0.00e+00", "##0.0e+0" */ // SetFloatWithFormat sets the value of a cell to a float and applies // formatting to the cell. func (c *Cell) SetFloatWithFormat(n float64, format string) { // tmp value. final value is formatted by FormattedValue() method c.Value = fmt.Sprintf("%e", n) c.numFmt = format c.Value = c.FormattedValue() c.formula = "" c.cellType = CellTypeNumeric } // Float returns the value of cell as a number. func (c *Cell) Float() (float64, error) { f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return math.NaN(), err } return f, nil } // SetInt64 sets a cell's value to a 64-bit integer. func (c *Cell) SetInt64(n int64) { c.Value = fmt.Sprintf("%d", n) c.numFmt = "0" c.formula = "" c.cellType = CellTypeNumeric } // Int64 returns the value of cell as 64-bit integer. func (c *Cell) Int64() (int64, error) { f, err := strconv.ParseInt(c.Value, 10, 64) if err != nil { return -1, err } return f, nil } // SetInt sets a cell's value to an integer. func (c *Cell) SetInt(n int) { c.Value = fmt.Sprintf("%d", n) c.numFmt = "0" c.formula = "" c.cellType = CellTypeNumeric } // Int returns the value of cell as integer. // Has max 53 bits of precision // See: float64(int64(math.MaxInt)) func (c *Cell) Int() (int, error) { f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return -1, err } return int(f), nil } // SetBool sets a cell's value to a boolean. func (c *Cell) SetBool(b bool) { if b { c.Value = "1" } else { c.Value = "0" } c.cellType = CellTypeBool } // Bool returns a boolean from a cell's value. // TODO: Determine if the current return value is // appropriate for types other than CellTypeBool. func (c *Cell) Bool() bool { return c.Value == "1" } // SetFormula sets the format string for a cell. func (c *Cell) SetFormula(formula string) { c.formula = formula c.cellType = CellTypeFormula } // Formula returns the formula string for the cell. func (c *Cell) Formula() string { return c.formula } // GetStyle returns the Style associated with a Cell func (c *Cell) GetStyle() *Style { return c.style } // SetStyle sets the style of a cell. func (c *Cell) SetStyle(style *Style) { c.style = style } // GetNumberFormat returns the number format string for a cell. func (c *Cell) GetNumberFormat() string { return c.numFmt } func (c *Cell) formatToTime(format string) string { f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } return TimeFromExcelTime(f, c.date1904).Format(format) } func (c *Cell) formatToFloat(format string) string { f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } return fmt.Sprintf(format, f) } func (c *Cell) formatToInt(format string) string { f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } return fmt.Sprintf(format, int(f)) } // FormattedValue returns the formatted version of the value. // If it's a string type, c.Value will just be returned. Otherwise, // it will attempt to apply Excel formatting to the value. func (c *Cell) FormattedValue() string { var numberFormat = c.GetNumberFormat() switch numberFormat { case "general", "@": return c.Value case "0", "#,##0": return c.formatToInt("%d") case "0.00", "#,##0.00": return c.formatToFloat("%.2f") case "#,##0 ;(#,##0)", "#,##0 ;[red](#,##0)": f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } if f < 0 { i := int(math.Abs(f)) return fmt.Sprintf("(%d)", i) } i := int(f) return fmt.Sprintf("%d", i) case "#,##0.00;(#,##0.00)", "#,##0.00;[red](#,##0.00)": f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } if f < 0 { return fmt.Sprintf("(%.2f)", f) } return fmt.Sprintf("%.2f", f) case "0%": f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } f = f * 100 return fmt.Sprintf("%d%%", int(f)) case "0.00%": f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } f = f * 100 return fmt.Sprintf("%.2f%%", f) case "0.00e+00", "##0.0e+0": return c.formatToFloat("%e") case "mm-dd-yy": return c.formatToTime("01-02-06") case "d-mmm-yy": return c.formatToTime("2-Jan-06") case "d-mmm": return c.formatToTime("2-Jan") case "mmm-yy": return c.formatToTime("Jan-06") case "h:mm am/pm": return c.formatToTime("3:04 pm") case "h:mm:ss am/pm": return c.formatToTime("3:04:05 pm") case "h:mm": return c.formatToTime("15:04") case "h:mm:ss": return c.formatToTime("15:04:05") case "m/d/yy h:mm": return c.formatToTime("1/2/06 15:04") case "mm:ss": return c.formatToTime("04:05") case "[h]:mm:ss": f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } t := TimeFromExcelTime(f, c.date1904) if t.Hour() > 0 { return t.Format("15:04:05") } return t.Format("04:05") case "mmss.0": f, err := strconv.ParseFloat(c.Value, 64) if err != nil { return err.Error() } t := TimeFromExcelTime(f, c.date1904) return fmt.Sprintf("%0d%0d.%d", t.Minute(), t.Second(), t.Nanosecond()/1000) case "yyyy\\-mm\\-dd": return c.formatToTime("2006\\-01\\-02") case "dd/mm/yy": return c.formatToTime("02/01/06") case "hh:mm:ss": return c.formatToTime("15:04:05") case "dd/mm/yy\\ hh:mm": return c.formatToTime("02/01/06\\ 15:04") case "dd/mm/yyyy hh:mm:ss": return c.formatToTime("02/01/2006 15:04:05") case "yy-mm-dd": return c.formatToTime("06-01-02") case "d-mmm-yyyy": return c.formatToTime("2-Jan-2006") case "m/d/yy": return c.formatToTime("1/2/06") case "m/d/yyyy": return c.formatToTime("1/2/2006") case "dd-mmm-yyyy": return c.formatToTime("02-Jan-2006") case "dd/mm/yyyy": return c.formatToTime("02/01/2006") case "mm/dd/yy hh:mm am/pm": return c.formatToTime("01/02/06 03:04 pm") case "mm/dd/yyyy hh:mm:ss": return c.formatToTime("01/02/2006 15:04:05") case "yyyy-mm-dd hh:mm:ss": return c.formatToTime("2006-01-02 15:04:05") } return c.Value }
Godeps/_workspace/src/github.com/tealeg/xlsx/cell.go
0.599251
0.567877
cell.go
starcoder
package html import ( "io" g "github.com/christophersw/gomponents-htmx" ) // Doctype returns a special kind of Node that prefixes its sibling with the string "<!doctype html>". func Doctype(sibling g.Node) g.Node { return g.NodeFunc(func(w io.Writer) error { if _, err := w.Write([]byte("<!doctype html>")); err != nil { return err } return sibling.Render(w) }) } func A(children ...g.Node) g.Node { return g.El("a", children...) } func Address(children ...g.Node) g.Node { return g.El("address", children...) } func Area(children ...g.Node) g.Node { return g.El("area", children...) } func Article(children ...g.Node) g.Node { return g.El("article", children...) } func Aside(children ...g.Node) g.Node { return g.El("aside", children...) } func Audio(children ...g.Node) g.Node { return g.El("audio", children...) } func Base(children ...g.Node) g.Node { return g.El("base", children...) } func BlockQuote(children ...g.Node) g.Node { return g.El("blockquote", children...) } func Body(children ...g.Node) g.Node { return g.El("body", children...) } func Br(children ...g.Node) g.Node { return g.El("br", children...) } func Button(children ...g.Node) g.Node { return g.El("button", children...) } func Canvas(children ...g.Node) g.Node { return g.El("canvas", children...) } func Cite(children ...g.Node) g.Node { return g.El("cite", children...) } func Code(children ...g.Node) g.Node { return g.El("code", children...) } func Col(children ...g.Node) g.Node { return g.El("col", children...) } func ColGroup(children ...g.Node) g.Node { return g.El("colgroup", children...) } func DataEl(children ...g.Node) g.Node { return g.El("data", children...) } func DataList(children ...g.Node) g.Node { return g.El("datalist", children...) } func Details(children ...g.Node) g.Node { return g.El("details", children...) } func Dialog(children ...g.Node) g.Node { return g.El("dialog", children...) } func Div(children ...g.Node) g.Node { return g.El("div", children...) } func Dl(children ...g.Node) g.Node { return g.El("dl", children...) } func Embed(children ...g.Node) g.Node { return g.El("embed", children...) } func FormEl(children ...g.Node) g.Node { return g.El("form", children...) } func FieldSet(children ...g.Node) g.Node { return g.El("fieldset", children...) } func Figure(children ...g.Node) g.Node { return g.El("figure", children...) } func Footer(children ...g.Node) g.Node { return g.El("footer", children...) } func Head(children ...g.Node) g.Node { return g.El("head", children...) } func Header(children ...g.Node) g.Node { return g.El("header", children...) } func HGroup(children ...g.Node) g.Node { return g.El("hgroup", children...) } func Hr(children ...g.Node) g.Node { return g.El("hr", children...) } func HTML(children ...g.Node) g.Node { return g.El("html", children...) } func IFrame(children ...g.Node) g.Node { return g.El("iframe", children...) } func Img(children ...g.Node) g.Node { return g.El("img", children...) } func Input(children ...g.Node) g.Node { return g.El("input", children...) } func Label(children ...g.Node) g.Node { return g.El("label", children...) } func Legend(children ...g.Node) g.Node { return g.El("legend", children...) } func Li(children ...g.Node) g.Node { return g.El("li", children...) } func Link(children ...g.Node) g.Node { return g.El("link", children...) } func Main(children ...g.Node) g.Node { return g.El("main", children...) } func Menu(children ...g.Node) g.Node { return g.El("menu", children...) } func Meta(children ...g.Node) g.Node { return g.El("meta", children...) } func Meter(children ...g.Node) g.Node { return g.El("meter", children...) } func Nav(children ...g.Node) g.Node { return g.El("nav", children...) } func NoScript(children ...g.Node) g.Node { return g.El("noscript", children...) } func Object(children ...g.Node) g.Node { return g.El("object", children...) } func Ol(children ...g.Node) g.Node { return g.El("ol", children...) } func OptGroup(children ...g.Node) g.Node { return g.El("optgroup", children...) } func Option(children ...g.Node) g.Node { return g.El("option", children...) } func P(children ...g.Node) g.Node { return g.El("p", children...) } func Param(children ...g.Node) g.Node { return g.El("param", children...) } func Picture(children ...g.Node) g.Node { return g.El("picture", children...) } func Pre(children ...g.Node) g.Node { return g.El("pre", children...) } func Progress(children ...g.Node) g.Node { return g.El("progress", children...) } func Script(children ...g.Node) g.Node { return g.El("script", children...) } func Section(children ...g.Node) g.Node { return g.El("section", children...) } func Select(children ...g.Node) g.Node { return g.El("select", children...) } func Source(children ...g.Node) g.Node { return g.El("source", children...) } func Span(children ...g.Node) g.Node { return g.El("span", children...) } func StyleEl(children ...g.Node) g.Node { return g.El("style", children...) } func Summary(children ...g.Node) g.Node { return g.El("summary", children...) } func SVG(children ...g.Node) g.Node { return g.El("svg", children...) } func Table(children ...g.Node) g.Node { return g.El("table", children...) } func TBody(children ...g.Node) g.Node { return g.El("tbody", children...) } func Td(children ...g.Node) g.Node { return g.El("td", children...) } func Textarea(children ...g.Node) g.Node { return g.El("textarea", children...) } func TFoot(children ...g.Node) g.Node { return g.El("tfoot", children...) } func Th(children ...g.Node) g.Node { return g.El("th", children...) } func THead(children ...g.Node) g.Node { return g.El("thead", children...) } func Tr(children ...g.Node) g.Node { return g.El("tr", children...) } func Ul(children ...g.Node) g.Node { return g.El("ul", children...) } func Wbr(children ...g.Node) g.Node { return g.El("wbr", children...) } func Abbr(children ...g.Node) g.Node { return g.El("abbr", g.Group(children)) } func B(children ...g.Node) g.Node { return g.El("b", g.Group(children)) } func Caption(children ...g.Node) g.Node { return g.El("caption", g.Group(children)) } func Dd(children ...g.Node) g.Node { return g.El("dd", g.Group(children)) } func Del(children ...g.Node) g.Node { return g.El("del", g.Group(children)) } func Dfn(children ...g.Node) g.Node { return g.El("dfn", g.Group(children)) } func Dt(children ...g.Node) g.Node { return g.El("dt", g.Group(children)) } func Em(children ...g.Node) g.Node { return g.El("em", g.Group(children)) } func FigCaption(children ...g.Node) g.Node { return g.El("figcaption", g.Group(children)) } func H1(children ...g.Node) g.Node { return g.El("h1", g.Group(children)) } func H2(children ...g.Node) g.Node { return g.El("h2", g.Group(children)) } func H3(children ...g.Node) g.Node { return g.El("h3", g.Group(children)) } func H4(children ...g.Node) g.Node { return g.El("h4", g.Group(children)) } func H5(children ...g.Node) g.Node { return g.El("h5", g.Group(children)) } func H6(children ...g.Node) g.Node { return g.El("h6", g.Group(children)) } func I(children ...g.Node) g.Node { return g.El("i", g.Group(children)) } func Ins(children ...g.Node) g.Node { return g.El("ins", g.Group(children)) } func Kbd(children ...g.Node) g.Node { return g.El("kbd", g.Group(children)) } func Mark(children ...g.Node) g.Node { return g.El("mark", g.Group(children)) } func Q(children ...g.Node) g.Node { return g.El("q", g.Group(children)) } func S(children ...g.Node) g.Node { return g.El("s", g.Group(children)) } func Samp(children ...g.Node) g.Node { return g.El("samp", g.Group(children)) } func Small(children ...g.Node) g.Node { return g.El("small", g.Group(children)) } func Strong(children ...g.Node) g.Node { return g.El("strong", g.Group(children)) } func Sub(children ...g.Node) g.Node { return g.El("sub", g.Group(children)) } func Sup(children ...g.Node) g.Node { return g.El("sup", g.Group(children)) } func Time(children ...g.Node) g.Node { return g.El("time", g.Group(children)) } func TitleEl(children ...g.Node) g.Node { return g.El("title", g.Group(children)) } func U(children ...g.Node) g.Node { return g.El("u", g.Group(children)) } func Var(children ...g.Node) g.Node { return g.El("var", g.Group(children)) } func Video(children ...g.Node) g.Node { return g.El("video", g.Group(children)) }
html/elements.go
0.707607
0.403273
elements.go
starcoder
package matrix import "math/rand" import "fmt" // Matrix is a matrix type Matrix struct { Rows int Cols int Cells []float64 } // Zeros generates a zeroed Matrix func Zeros(r, c int) Matrix { return Matrix{ Rows: r, Cols: c, Cells: make([]float64, r*c), } } // RandomN generates a random r by c Matrix func RandomN(r, c int) Matrix { m := Zeros(r, c) for i := range m.Cells { m.Cells[i] = rand.Float64() } return m } // has returns true if the matrix has a cell with row r and column c func (m Matrix) has(r, c int) bool { return r >= 0 && c >= 0 && r < m.Rows && c < m.Cols } // At gets the value of the matrix at row r and column c func (m Matrix) At(r, c int) float64 { if !m.has(r, c) { panic(fmt.Sprintf("Cannot get (%d, %d) in (%d, %d) matrix", r, c, m.Rows, m.Cols)) } return m.at(r, c) } func (m Matrix) at(r, c int) float64 { return m.Cells[m.Cols*r+c] } // Set sets the value of the matrix at row r and column c to value func (m Matrix) Set(r, c int, value float64) { if !m.has(r, c) { panic(fmt.Sprintf("Cannot set (%d, %d) in (%d, %d) matrix", r, c, m.Rows, m.Cols)) } m.set(r, c, value) } func (m Matrix) set(r, c int, value float64) { m.Cells[m.Cols*r+c] = value } // Dot returns the product of 2 matrices func (m Matrix) Dot(other Matrix) Matrix { if m.Cols != other.Rows { panic(fmt.Sprintf("Cannot dot matrixes (%d, %d) and (%d, %d)", m.Rows, m.Cols, other.Rows, other.Cols)) } r := Zeros(m.Rows, other.Cols) for i := 0; i < m.Rows; i++ { for j := 0; j < other.Cols; j++ { sum := float64(0.0) for k := 0; k < m.Cols; k++ { a := m.at(i, k) b := other.at(k, j) sum += a * b } r.set(i, j, sum) } } return r } // Add returns the sum of 2 matrices func (m Matrix) Add(other Matrix) Matrix { if m.Cols != other.Cols || m.Rows != other.Rows { panic(fmt.Sprintf("Cannot add matrixes (%d, %d) and (%d, %d) of different sizes", m.Rows, m.Cols, other.Rows, other.Cols)) } r := Zeros(m.Rows, m.Cols) for i := range r.Cells { r.Cells[i] = m.Cells[i] + other.Cells[i] } return r } // Sub returns the difference of 2 matrices func (m Matrix) Sub(other Matrix) Matrix { if m.Cols != other.Cols || m.Rows != other.Rows { panic(fmt.Sprintf("Cannot substract matrixes (%d, %d) and (%d, %d) of different sizes", m.Rows, m.Cols, other.Rows, other.Cols)) } r := Zeros(m.Rows, m.Cols) for i := range r.Cells { r.Cells[i] = m.Cells[i] - other.Cells[i] } return r } // Multiply returns the elementwise multiplication of 2 matrices func (m Matrix) Multiply(other Matrix) Matrix { if m.Cols != other.Cols || m.Rows != other.Rows { panic(fmt.Sprintf("Cannot multiply matrixes (%d, %d) and (%d, %d) of different sizes", m.Rows, m.Cols, other.Rows, other.Cols)) } r := Zeros(m.Rows, m.Cols) for i := range r.Cells { r.Cells[i] = m.Cells[i] * other.Cells[i] } return r } // Transpose returns the transposed Matrix func (m Matrix) Transpose() Matrix { r := Zeros(m.Cols, m.Rows) // Inverted from m for i := 0; i < m.Rows; i++ { for j := 0; j < m.Cols; j++ { r.set(j, i, m.at(i, j)) } } return r } // Scale returns the scaled Matrix func (m Matrix) Scale(scalar float64) Matrix { r := Zeros(m.Rows, m.Cols) for i := range r.Cells { r.Cells[i] = m.Cells[i] * scalar } return r } // String prints a matrix func (m Matrix) String() string { s := fmt.Sprintf("Matrix (%d, %d)\n[", m.Rows, m.Cols) for i, c := range m.Cells { if i%m.Cols == 0 && i != 0 { s += fmt.Sprint(",\n ") } s += fmt.Sprintf("%v ", c) } s += fmt.Sprintln("]") return s } func ArrayToMatrix(a []float64) Matrix { m := Zeros(len(a), 1) for i, v := range a { m.set(i, 0, v) } return m } func MatrixToArray(m Matrix) []float64 { if m.Cols != 1 { panic(fmt.Sprintf("cannot vectorize a matrix with %d columns", m.Cols)) } var result []float64 for _, v := range m.Cells { result = append(result, v) } return result }
matrix/matrix.go
0.884639
0.648564
matrix.go
starcoder
package occlude import ( "crypto/rand" "io" "golang.org/x/crypto/argon2" "golang.org/x/crypto/blake2b" "golang.org/x/crypto/hkdf" "golang.org/x/crypto/sha3" ristretto "github.com/gtank/ristretto255" ) const ( argonTime = 3 argonMemory = 1e5 ) // Compute and return a random ristretto scalar (←R Zq). func randomScalar() *ristretto.Scalar { b := make([]byte, 64) _, err := rand.Read(b) if err != nil { panic("could not get entropy") } return new(ristretto.Scalar).FromUniformBytes(b) } // Compute the oprf output H(x, (H'(x))^k), where H' is a uniformly random // unique mapping of arbitrary length data to an element of the curve group. The // output is wrapped with Argon2ID to make dictionary attacks in the case of a // compromised server more costly. See the OPAQUE protocol paper for more // information about the design of this OPRF. func oprfA(x []byte, k *ristretto.Scalar) []byte { hprimex := new(ristretto.Element).FromUniformBytes(x) // H'(x) hprimex.ScalarMult(k, hprimex) // H'(x)^k hash := sha3.Sum512(append(x, hprimex.Encode(nil)...)) // H(x, (H'(x)^k)) output := argon2.IDKey(hash[:], nil, argonTime, argonMemory, 4, 32) return output } // Compute the oprf output H(x, (H'(x))^k) given the input // β = a^k = ((H'(pw))^r)^k, r, and password. func oprfB(B *ristretto.Element, r *ristretto.Scalar, x [64]byte) []byte { rinv := new(ristretto.Scalar).Invert(r) // B^{1/r} = (a^k)^{1/r} = (((H'(x))^r)^k)^{1/r}) = (H'(x)^k) betarinv := new(ristretto.Element).ScalarMult(rinv, B) // B^{1/r} hash := sha3.Sum512(append(x[:], betarinv.Encode(nil)...)) // H(x, (H'(x))^k) output := argon2.IDKey(hash[:], nil, argonTime, argonMemory, 4, 32) return output } // prf is a pseudorandom function, implemented with keyed Blake2B func prf(k [32]byte, x []byte) []byte { b, err := blake2b.New256(k[:]) if err != nil { panic(err) } _, err = b.Write(x) if err != nil { panic(err) } return b.Sum(nil) } // derive a separate authentication and cipher key using HKDF and the given // input key `x`. func deriveHKDFKeys(x []byte) (authKey []byte, cipherKey []byte) { hkdf := hkdf.New(sha3.New512, x, nil, nil) cipherKey = make([]byte, 32) authKey = make([]byte, 32) _, err := io.ReadFull(hkdf, cipherKey) if err != nil { panic("could not derive HKDF key material") } _, err = io.ReadFull(hkdf, authKey) if err != nil { panic("could not derive HKDF key material") } return } // Perform the key exchange. Compute the shared secret using ECDH with the // provided static and ephemeral keys. func keServer(ps *ristretto.Scalar, xs *ristretto.Scalar, Pu *ristretto.Element, Xu *ristretto.Element) [32]byte { xsPu := new(ristretto.Element).ScalarMult(xs, Pu) psXu := new(ristretto.Element).ScalarMult(ps, Xu) xsXu := new(ristretto.Element).ScalarMult(xs, Xu) sharedSecret := append(xsPu.Encode(nil), psXu.Encode(nil)...) sharedSecret = append(sharedSecret, xsXu.Encode(nil)...) return sha3.Sum256(sharedSecret) } // Perform the key exchange. Compute the shared secret using ECDH with the // provided static and ephemeral keys. func keUser(pu *ristretto.Scalar, xu *ristretto.Scalar, Ps *ristretto.Element, Xs *ristretto.Element) [32]byte { puXs := new(ristretto.Element).ScalarMult(pu, Xs) xuPs := new(ristretto.Element).ScalarMult(xu, Ps) xuXs := new(ristretto.Element).ScalarMult(xu, Xs) sharedSecret := append(puXs.Encode(nil), xuPs.Encode(nil)...) sharedSecret = append(sharedSecret, xuXs.Encode(nil)...) return sha3.Sum256(sharedSecret) } func clear(x []byte) { for i := 0; i < len(x); i++ { x[i] = 0 } }
crypto.go
0.773473
0.461866
crypto.go
starcoder
package packing type Point struct { x int y int } func (p Point) X() int { return p.x } func (p Point) Y() int { return p.y } // Partition represent the single cell that an image can be inserted in. type Partition struct { p1 Point p2 Point ratio float32 } func CreatePartition(p1, p2 Point) Partition { if p2.Y()-p1.Y() == 0 { return Partition{ p1: p1, p2: p2, ratio: 0, } } return Partition{ p1: p1, p2: p2, ratio: float32(p2.X()-p1.X()) / float32(p2.Y()-p1.Y()), } } // A high level function that split up a partition based on the image added in the partition func (p Partition) AddRectangle(width, height int, hMajor bool) (Partition, Partition) { return p.split(Point{p.p1.X() + width, p.p1.Y() + height}, hMajor) } func (p Partition) split(point Point, hMajor bool) (Partition, Partition) { var partition1, partition2 Partition if hMajor { // Case 1: horizontal major p1, p2 := Point{point.X(), p.p1.Y()}, Point{p.p2.X(), point.Y()} pA, pB := Point{p.p1.X(), point.Y()}, p.p2 partition1 = CreatePartition(p1, p2) partition2 = CreatePartition(pA, pB) } else { // Case 2: vertical major p1, p2 := Point{point.X(), p.p1.Y()}, p.p2 pA, pB := Point{p.p1.X(), point.Y()}, Point{point.X(), p.p2.Y()} partition1 = CreatePartition(p1, p2) partition2 = CreatePartition(pA, pB) } return partition1, partition2 } func (p Partition) BigEnough(width, height int) bool { dw := p.p2.X() - p.p1.X() dh := p.p2.Y() - p.p1.Y() if width <= dw && height <= dh { return true } return false } func (p Partition) Size() int { return (p.p2.X() - p.p1.X()) * (p.p2.Y() - p.p1.Y()) } func (p Partition) Width() int { return p.p2.X() - p.p1.X() } func (p Partition) Height() int { return p.p2.Y() - p.p1.Y() } func (p Partition) Ratio() float32 { return p.ratio } func (p Partition) P1() Point { return p.p1 } func (p Partition) P2() Point { return p.p2 } func (p Partition) IsValid() bool { return p.Size() > 0 && p.Width() > tolWidth && p.Height() > tolHeight }
packing/partition.go
0.852045
0.658383
partition.go
starcoder
package clinical import ( "github.com/savannahghi/firebasetools" "github.com/savannahghi/scalarutils" ) // FHIREncounter definition: an interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. type FHIREncounter struct { // The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. ID *string `json:"id,omitempty"` // A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it "clinically safe" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety. Text *FHIRNarrative `json:"text,omitempty"` // Identifier(s) by which this encounter is known. Identifier []*FHIRIdentifier `json:"identifier,omitempty"` // planned | arrived | triaged | in-progress | onleave | finished | cancelled +. Status EncounterStatusEnum `json:"status,omitempty"` // The status history permits the encounter resource to contain the status history without needing to read through the historical versions of the resource, or even have the server store them. StatusHistory []*FHIREncounterStatushistory `json:"statusHistory,omitempty"` // Concepts representing classification of patient encounter such as ambulatory (outpatient), inpatient, emergency, home health or others due to local variations. Class FHIRCoding `json:"class,omitempty"` // The class history permits the tracking of the encounters transitions without needing to go through the resource history. This would be used for a case where an admission starts of as an emergency encounter, then transitions into an inpatient scenario. Doing this and not restarting a new encounter ensures that any lab/diagnostic results can more easily follow the patient and not require re-processing and not get lost or cancelled during a kind of discharge from emergency to inpatient. ClassHistory []*FHIREncounterClasshistory `json:"classHistory,omitempty"` // Specific type of encounter (e.g. e-mail consultation, surgical day-care, skilled nursing, rehabilitation). Type []*FHIRCodeableConcept `json:"type,omitempty"` // Broad categorization of the service that is to be provided (e.g. cardiology). ServiceType *FHIRCodeableConcept `json:"serviceType,omitempty"` // Indicates the urgency of the encounter. Priority *FHIRCodeableConcept `json:"priority,omitempty"` // The patient or group present at the encounter. Subject *FHIRReference `json:"subject,omitempty"` // Where a specific encounter should be classified as a part of a specific episode(s) of care this field should be used. This association can facilitate grouping of related encounters together for a specific purpose, such as government reporting, issue tracking, association via a common problem. The association is recorded on the encounter as these are typically created after the episode of care and grouped on entry rather than editing the episode of care to append another encounter to it (the episode of care could span years). EpisodeOfCare []*FHIRReference `json:"episodeOfCare,omitempty"` // The request this encounter satisfies (e.g. incoming referral or procedure request). BasedOn []*FHIRReference `json:"basedOn,omitempty"` // The list of people responsible for providing the service. Participant []*FHIREncounterParticipant `json:"participant,omitempty"` // The appointment that scheduled this encounter. Appointment []*FHIRReference `json:"appointment,omitempty"` // The start and end time of the encounter. Period *FHIRPeriod `json:"period,omitempty"` // Quantity of time the encounter lasted. This excludes the time during leaves of absence. Length *FHIRDuration `json:"length,omitempty"` // Reason the encounter takes place, expressed as a code. For admissions, this can be used for a coded admission diagnosis. ReasonCode *scalarutils.Code `json:"reasonCode,omitempty"` // Reason the encounter takes place, expressed as a code. For admissions, this can be used for a coded admission diagnosis. ReasonReference []*FHIRReference `json:"reasonReference,omitempty"` // The list of diagnosis relevant to this encounter. Diagnosis []*FHIREncounterDiagnosis `json:"diagnosis,omitempty"` // The set of accounts that may be used for billing for this Encounter. Account []*FHIRReference `json:"account,omitempty"` // Details about the admission to a healthcare service. Hospitalization *FHIREncounterHospitalization `json:"hospitalization,omitempty"` // List of locations where the patient has been during this encounter. Location []*FHIREncounterLocation `json:"location,omitempty"` // The organization that is primarily responsible for this Encounter's services. This MAY be the same as the organization on the Patient record, however it could be different, such as if the actor performing the services was from an external organization (which may be billed separately) for an external consultation. Refer to the example bundle showing an abbreviated set of Encounters for a colonoscopy. ServiceProvider *FHIRReference `json:"serviceProvider,omitempty"` // Another Encounter of which this encounter is a part of (administratively or in time). PartOf *FHIRReference `json:"partOf,omitempty"` } // FHIREncounterClasshistory definition: an interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. type FHIREncounterClasshistory struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // inpatient | outpatient | ambulatory | emergency +. Class *FHIRCoding `json:"class,omitempty"` // The time that the episode was in the specified class. Period *FHIRPeriod `json:"period,omitempty"` } // FHIREncounterClasshistoryInput is the input type for EncounterClasshistory type FHIREncounterClasshistoryInput struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // inpatient | outpatient | ambulatory | emergency +. Class *FHIRCodingInput `json:"class,omitempty"` // The time that the episode was in the specified class. Period *FHIRPeriodInput `json:"period,omitempty"` } // FHIREncounterDiagnosis definition: an interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. type FHIREncounterDiagnosis struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // Reason the encounter takes place, as specified using information from another resource. For admissions, this is the admission diagnosis. The indication will typically be a Condition (with other resources referenced in the evidence.detail), or a Procedure. Condition *FHIRReference `json:"condition,omitempty"` // Role that this diagnosis has within the encounter (e.g. admission, billing, discharge …). Use *FHIRCodeableConcept `json:"use,omitempty"` // Ranking of the diagnosis (for each role type). Rank *string `json:"rank,omitempty"` } // FHIREncounterDiagnosisInput is the input type for EncounterDiagnosis type FHIREncounterDiagnosisInput struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // Reason the encounter takes place, as specified using information from another resource. For admissions, this is the admission diagnosis. The indication will typically be a Condition (with other resources referenced in the evidence.detail), or a Procedure. Condition *FHIRReferenceInput `json:"condition,omitempty"` // Role that this diagnosis has within the encounter (e.g. admission, billing, discharge …). Use *FHIRCodeableConceptInput `json:"use,omitempty"` // Ranking of the diagnosis (for each role type). Rank *string `json:"rank,omitempty"` } // FHIREncounterHospitalization definition: an interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. type FHIREncounterHospitalization struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // Pre-admission identifier. PreAdmissionIdentifier *FHIRIdentifier `json:"preAdmissionIdentifier,omitempty"` // The location/organization from which the patient came before admission. Origin *FHIRReference `json:"origin,omitempty"` // From where patient was admitted (physician referral, transfer). AdmitSource *FHIRCodeableConcept `json:"admitSource,omitempty"` // Whether this hospitalization is a readmission and why if known. ReAdmission *FHIRCodeableConcept `json:"reAdmission,omitempty"` // Diet preferences reported by the patient. DietPreference []*FHIRCodeableConcept `json:"dietPreference,omitempty"` // Special courtesies (VIP, board member). SpecialCourtesy []*FHIRCodeableConcept `json:"specialCourtesy,omitempty"` // Any special requests that have been made for this hospitalization encounter, such as the provision of specific equipment or other things. SpecialArrangement []*FHIRCodeableConcept `json:"specialArrangement,omitempty"` // Location/organization to which the patient is discharged. Destination *FHIRReference `json:"destination,omitempty"` // Category or kind of location after discharge. DischargeDisposition *FHIRCodeableConcept `json:"dischargeDisposition,omitempty"` } // FHIREncounterHospitalizationInput is the input type for EncounterHospitalization type FHIREncounterHospitalizationInput struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // Pre-admission identifier. PreAdmissionIdentifier *FHIRIdentifierInput `json:"preAdmissionIdentifier,omitempty"` // The location/organization from which the patient came before admission. Origin *FHIRReferenceInput `json:"origin,omitempty"` // From where patient was admitted (physician referral, transfer). AdmitSource *FHIRCodeableConceptInput `json:"admitSource,omitempty"` // Whether this hospitalization is a readmission and why if known. ReAdmission *FHIRCodeableConceptInput `json:"reAdmission,omitempty"` // Diet preferences reported by the patient. DietPreference []*FHIRCodeableConceptInput `json:"dietPreference,omitempty"` // Special courtesies (VIP, board member). SpecialCourtesy []*FHIRCodeableConceptInput `json:"specialCourtesy,omitempty"` // Any special requests that have been made for this hospitalization encounter, such as the provision of specific equipment or other things. SpecialArrangement []*FHIRCodeableConceptInput `json:"specialArrangement,omitempty"` // Location/organization to which the patient is discharged. Destination *FHIRReferenceInput `json:"destination,omitempty"` // Category or kind of location after discharge. DischargeDisposition *FHIRCodeableConceptInput `json:"dischargeDisposition,omitempty"` } // FHIREncounterInput is the input type for Encounter type FHIREncounterInput struct { // The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. ID *string `json:"id,omitempty"` // Identifier(s) by which this encounter is known. Identifier []*FHIRIdentifierInput `json:"identifier,omitempty"` // planned | arrived | triaged | in-progress | onleave | finished | cancelled +. Status EncounterStatusEnum `json:"status,omitempty"` // The status history permits the encounter resource to contain the status history without needing to read through the historical versions of the resource, or even have the server store them. StatusHistory []*FHIREncounterStatushistoryInput `json:"statusHistory,omitempty"` // Concepts representing classification of patient encounter such as ambulatory (outpatient), inpatient, emergency, home health or others due to local variations. Class FHIRCodingInput `json:"class,omitempty"` // The class history permits the tracking of the encounters transitions without needing to go through the resource history. This would be used for a case where an admission starts of as an emergency encounter, then transitions into an inpatient scenario. Doing this and not restarting a new encounter ensures that any lab/diagnostic results can more easily follow the patient and not require re-processing and not get lost or cancelled during a kind of discharge from emergency to inpatient. ClassHistory []*FHIREncounterClasshistoryInput `json:"classHistory,omitempty"` // Specific type of encounter (e.g. e-mail consultation, surgical day-care, skilled nursing, rehabilitation). Type []*FHIRCodeableConceptInput `json:"type,omitempty"` // Broad categorization of the service that is to be provided (e.g. cardiology). ServiceType *FHIRCodeableConceptInput `json:"serviceType,omitempty"` // Indicates the urgency of the encounter. Priority *FHIRCodeableConceptInput `json:"priority,omitempty"` // The patient or group present at the encounter. Subject *FHIRReferenceInput `json:"subject,omitempty"` // Where a specific encounter should be classified as a part of a specific episode(s) of care this field should be used. This association can facilitate grouping of related encounters together for a specific purpose, such as government reporting, issue tracking, association via a common problem. The association is recorded on the encounter as these are typically created after the episode of care and grouped on entry rather than editing the episode of care to append another encounter to it (the episode of care could span years). EpisodeOfCare []*FHIRReferenceInput `json:"episodeOfCare,omitempty"` // The request this encounter satisfies (e.g. incoming referral or procedure request). BasedOn []*FHIRReferenceInput `json:"basedOn,omitempty"` // The list of people responsible for providing the service. Participant []*FHIREncounterParticipantInput `json:"participant,omitempty"` // The appointment that scheduled this encounter. Appointment []*FHIRReferenceInput `json:"appointment,omitempty"` // The start and end time of the encounter. Period *FHIRPeriodInput `json:"period,omitempty"` // Quantity of time the encounter lasted. This excludes the time during leaves of absence. Length *FHIRDurationInput `json:"length,omitempty"` // Reason the encounter takes place, expressed as a code. For admissions, this can be used for a coded admission diagnosis. ReasonCode *scalarutils.Code `json:"reasonCode,omitempty"` // Reason the encounter takes place, expressed as a code. For admissions, this can be used for a coded admission diagnosis. ReasonReference []*FHIRReferenceInput `json:"reasonReference,omitempty"` // The list of diagnosis relevant to this encounter. Diagnosis []*FHIREncounterDiagnosisInput `json:"diagnosis,omitempty"` // The set of accounts that may be used for billing for this Encounter. Account []*FHIRReferenceInput `json:"account,omitempty"` // Details about the admission to a healthcare service. Hospitalization *FHIREncounterHospitalizationInput `json:"hospitalization,omitempty"` // List of locations where the patient has been during this encounter. Location []*FHIREncounterLocationInput `json:"location,omitempty"` // The organization that is primarily responsible for this Encounter's services. This MAY be the same as the organization on the Patient record, however it could be different, such as if the actor performing the services was from an external organization (which may be billed separately) for an external consultation. Refer to the example bundle showing an abbreviated set of Encounters for a colonoscopy. ServiceProvider *FHIRReferenceInput `json:"serviceProvider,omitempty"` // Another Encounter of which this encounter is a part of (administratively or in time). PartOf *FHIRReferenceInput `json:"partOf,omitempty"` } // FHIREncounterLocation definition: an interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. type FHIREncounterLocation struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // The location where the encounter takes place. Location *FHIRReference `json:"location,omitempty"` // The status of the participants' presence at the specified location during the period specified. If the participant is no longer at the location, then the period will have an end date/time. Status *EncounterLocationStatusEnum `json:"status,omitempty"` // This will be used to specify the required levels (bed/ward/room/etc.) desired to be recorded to simplify either messaging or query. PhysicalType *FHIRCodeableConcept `json:"physicalType,omitempty"` // Time period during which the patient was present at the location. Period *FHIRPeriod `json:"period,omitempty"` } // FHIREncounterLocationInput is the input type for EncounterLocation type FHIREncounterLocationInput struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // The location where the encounter takes place. Location *FHIRReferenceInput `json:"location,omitempty"` // The status of the participants' presence at the specified location during the period specified. If the participant is no longer at the location, then the period will have an end date/time. Status *EncounterLocationStatusEnum `json:"status,omitempty"` // This will be used to specify the required levels (bed/ward/room/etc.) desired to be recorded to simplify either messaging or query. PhysicalType *FHIRCodeableConceptInput `json:"physicalType,omitempty"` // Time period during which the patient was present at the location. Period *FHIRPeriodInput `json:"period,omitempty"` } // FHIREncounterParticipant definition: an interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. type FHIREncounterParticipant struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // Role of participant in encounter. Type []*FHIRCodeableConcept `json:"type,omitempty"` // The period of time that the specified participant participated in the encounter. These can overlap or be sub-sets of the overall encounter's period. Period *FHIRPeriod `json:"period,omitempty"` // Persons involved in the encounter other than the patient. Individual *FHIRReference `json:"individual,omitempty"` } // FHIREncounterParticipantInput is the input type for EncounterParticipant type FHIREncounterParticipantInput struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // Role of participant in encounter. Type []*FHIRCodeableConceptInput `json:"type,omitempty"` // The period of time that the specified participant participated in the encounter. These can overlap or be sub-sets of the overall encounter's period. Period *FHIRPeriodInput `json:"period,omitempty"` // Persons involved in the encounter other than the patient. Individual *FHIRReferenceInput `json:"individual,omitempty"` } // FHIREncounterStatushistory definition: an interaction between a patient and healthcare provider(s) for the purpose of providing healthcare service(s) or assessing the health status of a patient. type FHIREncounterStatushistory struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // planned | arrived | triaged | in-progress | onleave | finished | cancelled +. Status *EncounterStatusHistoryStatusEnum `json:"status,omitempty"` // The time that the episode was in the specified status. Period *FHIRPeriod `json:"period,omitempty"` } // FHIREncounterStatushistoryInput is the input type for EncounterStatushistory type FHIREncounterStatushistoryInput struct { // Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. ID *string `json:"id,omitempty"` // planned | arrived | triaged | in-progress | onleave | finished | cancelled +. Status *EncounterStatusHistoryStatusEnum `json:"status,omitempty"` // The time that the episode was in the specified status. Period *FHIRPeriodInput `json:"period,omitempty"` } // FHIREncounterRelayConnection is a Relay connection for Encounter type FHIREncounterRelayConnection struct { Edges []*FHIREncounterRelayEdge `json:"edges,omitempty"` PageInfo *firebasetools.PageInfo `json:"pageInfo,omitempty"` } // FHIREncounterRelayEdge is a Relay edge for Encounter type FHIREncounterRelayEdge struct { Cursor *string `json:"cursor,omitempty"` Node *FHIREncounter `json:"node,omitempty"` } // FHIREncounterRelayPayload is used to return single instances of Encounter type FHIREncounterRelayPayload struct { Resource *FHIREncounter `json:"resource,omitempty"` }
graph/clinical/encounter.go
0.662796
0.455441
encounter.go
starcoder
package nats import ( "context" "crypto/tls" "fmt" "strings" "sync" "time" "github.com/Jeffail/benthos/v3/internal/bundle" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/impl/nats/auth" "github.com/Jeffail/benthos/v3/internal/shutdown" "github.com/Jeffail/benthos/v3/lib/input" "github.com/Jeffail/benthos/v3/lib/input/reader" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" btls "github.com/Jeffail/benthos/v3/lib/util/tls" "github.com/nats-io/nats.go" ) func init() { bundle.AllInputs.Add(bundle.InputConstructorFromSimple(func(c input.Config, nm bundle.NewManagement) (input.Type, error) { var a reader.Async var err error if a, err = newJetStreamReader(c.NATSJetStream, nm.Logger(), nm.Metrics()); err != nil { return nil, err } return input.NewAsyncReader(input.TypeNATSStream, false, a, nm.Logger(), nm.Metrics()) }), docs.ComponentSpec{ Name: input.TypeNATSJetStream, Type: docs.TypeInput, Status: docs.StatusExperimental, Version: "3.46.0", Summary: `Reads messages from NATS JetStream subjects.`, Description: ` ### Metadata This input adds the following metadata fields to each message: ` + "```text" + ` - nats_subject ` + "```" + ` You can access these metadata fields using [function interpolation](/docs/configuration/interpolation#metadata). ` + auth.Description(), Categories: []string{ string(input.CategoryServices), }, Config: docs.FieldComponent().WithChildren( docs.FieldCommon( "urls", "A list of URLs to connect to. If an item of the list contains commas it will be expanded into multiple URLs.", []string{"nats://127.0.0.1:4222"}, []string{"nats://username:password@127.0.0.1:4222"}, ).Array(), docs.FieldCommon("queue", "The queue group to consume as."), docs.FieldCommon( "subject", "A subject to consume from. Supports wildcards for consuming multiple subjects.", "foo.bar.baz", "foo.*.baz", "foo.bar.*", "foo.>", ), docs.FieldCommon("durable", "Preserve the state of your consumer under a durable name."), docs.FieldCommon( "deliver", "Determines which messages to deliver when consuming without a durable subscriber.", ).HasAnnotatedOptions( "all", "Deliver all available messages.", "last", "Deliver starting with the last published messages.", ), docs.FieldAdvanced("max_ack_pending", "The maximum number of outstanding acks to be allowed before consuming is halted."), btls.FieldSpec(), auth.FieldSpec(), ).ChildDefaultAndTypesFromStruct(input.NewNATSJetStreamConfig()), }) } //------------------------------------------------------------------------------ type jetStreamReader struct { urls string conf input.NATSJetStreamConfig deliverOpt nats.SubOpt tlsConf *tls.Config stats metrics.Type log log.Modular connMut sync.Mutex natsConn *nats.Conn natsSub *nats.Subscription shutSig *shutdown.Signaller } func newJetStreamReader(conf input.NATSJetStreamConfig, log log.Modular, stats metrics.Type) (*jetStreamReader, error) { j := jetStreamReader{ conf: conf, stats: stats, log: log, shutSig: shutdown.NewSignaller(), } j.urls = strings.Join(conf.URLs, ",") var err error if conf.TLS.Enabled { if j.tlsConf, err = conf.TLS.Get(); err != nil { return nil, err } } switch conf.Deliver { case "all": j.deliverOpt = nats.DeliverAll() case "last": j.deliverOpt = nats.DeliverLast() default: return nil, fmt.Errorf("deliver option %v was not recognised", conf.Deliver) } return &j, nil } //------------------------------------------------------------------------------ func (j *jetStreamReader) ConnectWithContext(ctx context.Context) error { j.connMut.Lock() defer j.connMut.Unlock() if j.natsConn != nil { return nil } var natsConn *nats.Conn var natsSub *nats.Subscription var err error defer func() { if err != nil { if natsSub != nil { _ = natsSub.Drain() } if natsConn != nil { natsConn.Close() } } }() var opts []nats.Option if j.tlsConf != nil { opts = append(opts, nats.Secure(j.tlsConf)) } opts = append(opts, auth.GetOptions(j.conf.Auth)...) if natsConn, err = nats.Connect(j.urls, opts...); err != nil { return err } jCtx, err := natsConn.JetStream() if err != nil { return err } options := []nats.SubOpt{ nats.ManualAck(), } if j.conf.Durable != "" { options = append(options, nats.Durable(j.conf.Durable)) } options = append(options, j.deliverOpt) if j.conf.MaxAckPending != 0 { options = append(options, nats.MaxAckPending(j.conf.MaxAckPending)) } if j.conf.Queue == "" { natsSub, err = jCtx.SubscribeSync(j.conf.Subject, options...) } else { natsSub, err = jCtx.QueueSubscribeSync(j.conf.Subject, j.conf.Queue, options...) } if err != nil { return err } j.log.Infof("Receiving NATS messages from JetStream subject: %v\n", j.conf.Subject) j.natsConn = natsConn j.natsSub = natsSub return nil } func (j *jetStreamReader) disconnect() { j.connMut.Lock() defer j.connMut.Unlock() if j.natsSub != nil { _ = j.natsSub.Drain() j.natsSub = nil } if j.natsConn != nil { j.natsConn.Close() j.natsConn = nil } } func (j *jetStreamReader) ReadWithContext(ctx context.Context) (types.Message, reader.AsyncAckFn, error) { j.connMut.Lock() natsSub := j.natsSub j.connMut.Unlock() if natsSub == nil { return nil, nil, types.ErrNotConnected } nmsg, err := natsSub.NextMsgWithContext(ctx) if err != nil { // TODO: Any errors need capturing here to signal a lost connection? return nil, nil, err } msg := message.New([][]byte{nmsg.Data}) msg.Get(0).Metadata().Set("nats_subject", nmsg.Subject) return msg, func(ctx context.Context, res types.Response) error { if res.Error() == nil { return nmsg.Ack() } return nmsg.Nak() }, nil } func (j *jetStreamReader) CloseAsync() { go func() { j.disconnect() j.shutSig.ShutdownComplete() }() } func (j *jetStreamReader) WaitForClose(timeout time.Duration) error { select { case <-j.shutSig.HasClosedChan(): case <-time.After(timeout): return types.ErrTimeout } return nil }
internal/impl/nats/jetstream_input.go
0.607081
0.456834
jetstream_input.go
starcoder
package rotations func gcd(a, b int) int { for a != 0 { a, b = b%a, a } return b } // Juggling ... Perfoms left rotation of array by d steps func juggling(a []int, d int) []int { if d == 0 { return a } n := len(a) d = d % n m := gcd(n, d) var k, next, prev int for i := 0; i < m; i++ { k = i prev = a[i] for { next = (k + d) % n if next == i { break } a[k] = a[next] k = next } a[k] = prev } return a } func reverse(a []int) { n := len(a) for i := 0; i < n/2; i++ { a[i], a[n-i-1] = a[n-i-1], a[i] } } func reverseRotate(a []int, d int) []int { n := len(a) d = d % n reverse(a[:d]) reverse(a[d:]) reverse(a) return a } func findPivot(a []int) int { low := 0 high := len(a) - 1 mid := 0 for high > low { mid = low + (high-low)/2 if low < mid && a[mid-1] > a[mid] { return mid - 1 } else if mid < high && a[mid] > a[mid+1] { return mid } else if a[low] > a[mid] { high = mid - 1 } else { low = mid + 1 } } return -1 } func binarySearch(a []int, low, high, key int) int { mid := 0 for high >= low { mid = low + (high-low)/2 if key == a[mid] { return mid } else if key > a[mid] { low = mid + 1 } else { high = mid - 1 } } return -1 } func findInRotatedSortedPivot(a []int, key int) int { n := len(a) if pivot := findPivot(a); pivot == -1 { return binarySearch(a, 0, n-1, key) } else if key == a[pivot] { return pivot } else if key >= a[0] { return binarySearch(a, 0, pivot-1, key) } else { return binarySearch(a, pivot+1, n-1, key) } } func findInRotatedSorted(a []int, key int) int { low, high, mid := 0, len(a)-1, 0 for high > low { mid = low + (high-low)/2 if key == a[mid] { return mid } else if a[low] <= a[mid] { if key >= a[low] && key <= a[mid] { high = mid - 1 } else { low = mid + 1 } } else { if key >= a[mid] && key <= a[high] { low = mid + 1 } else { high = mid - 1 } } } if high == low && key == a[low] { return high } return -1 } func findPairSumInSortedArray(a []int, sum int) (int, int) { low, high := 0, len(a)-1 currSum := 0 for high > low { currSum = a[low] + a[high] if currSum == sum { return a[low], a[high] } else if currSum > sum { high-- } else { low++ } } return -1, -1 } func findPairSumInSortedRotatedArray(a []int, sum int) (int, int) { low, high := 0, 0 if pivot := findPivot(a); pivot == -1 { low, high = 0, len(a)-1 } else { low, high = pivot+1, pivot } n := len(a) currSum := 0 for ((n - (low - high)) % n) != 0 { currSum = a[low] + a[high] if currSum == sum { return a[low], a[high] } else if currSum > sum { high = (n + (high - 1)) % n } else { low = (n + (low + 1)) % n } } return -1, -1 } func insertionSort(a []int) { n := len(a) for i := 0; i < n-1; i++ { for j := i + 1; j > 0 && a[j] < a[j-1]; j-- { a[j], a[j-1] = a[j-1], a[j] } } } func maxSumRotationBrute(a []int) int { n := len(a) sum, maxSum := 0, 0 for i := 0; i < n; i++ { a = juggling(a, i) sum = 0 for j, v := range a { sum += j * v } if maxSum < sum { maxSum = sum } } return maxSum } func maxSumRotation(a []int) int { var sum, maxSum, arrSum int for i, v := range a { arrSum += v sum += i * v } maxSum = sum n := len(a) for i := 1; i < n; i++ { sum += n*a[i-1] - arrSum if maxSum < sum { maxSum = sum } } return maxSum } func findMinimumInRotatedSorted(a []int) int { low, high, mid := 0, len(a)-1, 0 for high > low { mid = low + (high-low)/2 if low < mid && a[mid-1] > a[mid] { return a[mid] } else if high > mid && a[mid] > a[mid+1] { return a[mid+1] } else if a[high] > a[mid] { high = mid - 1 } else { low = mid + 1 } } return a[low] }
ds/arrays/rotations.go
0.611266
0.434821
rotations.go
starcoder
package merkleDag import "github.com/AccumulateNetwork/ValidatorAccumulator/ValAcc/types" type MDNode struct { Type uint8 // Type of data in this chain, drives validation SequenceNumber uint32 // sequence number of MDNodes in this chain Previous types.Hash // Hash of the previous MDNode in this chain; zeros if first block TotalEntries uint64 // Total number of entries at the start of this block in this chain MDSTate []types.Hash // Hashes in our intermediate state at the start of this block MDRoot types.Hash // MDRoot of all the data in this chain up to and not including this MDNode Hashes []types.Hash // Hashes in this block } // SameAs // Compare all the data in two nodes to determine that they are the same. Any difference, and they are false func (n *MDNode) SameAs(n2 *MDNode) bool { if n.Type != n2.Type { // Check the type return false } if n.SequenceNumber != n2.SequenceNumber { // Check the sequence number return false } if n.Previous != n2.Previous { return false } if n.TotalEntries != n2.TotalEntries { return false } if n.MDRoot != n2.MDRoot { // Check the MDRoot return false } if len(n.Hashes) != len(n2.Hashes) { return false } // Check the length of the hashes for i, n := range n.Hashes { // Check each of the hashes if n != n2.Hashes[i] { return false } } return true } func (n *MDNode) Bytes() (data []byte) { data = append(data, byte(n.Type)) data = append(data, types.Uint32Bytes(n.SequenceNumber)...) data = append(data, n.MDRoot.Bytes()...) data = append(data, types.Uint32Bytes(uint32(len(n.Hashes)))...) for _, h := range n.Hashes { data = append(data, h.Bytes()...) } return data } func (n *MDNode) Extract(data []byte) { n.Hashes = n.Hashes[:0] // Clear any old hashes n.Type, data = data[0], data[1:] n.SequenceNumber, data = types.BytesUint32(data) data = n.MDRoot.Extract(data) var numHashes, i uint32 numHashes, data = types.BytesUint32(data) for i = 0; i < numHashes; i++ { var h types.Hash data = h.Extract(data) n.Hashes = append(n.Hashes, h) } } // CompressState // First check to make sure the current state matches the total number of entries at the start of this // block. func (n *MDNode) CompressState() (state []types.Hash) { return }
ValAcc/merkleDag/mdnode.go
0.512937
0.482246
mdnode.go
starcoder
package physics import "github.com/mokiat/gomath/sprec" // SBSolverContext contains information related to the // single-body constraint processing. type SBSolverContext struct { Body *Body ElapsedSeconds float32 } // SBConstraintSolver represents the algorithm necessary // to enforce a single-body constraint. type SBConstraintSolver interface { // Reset clears the internal cache state for this constraint solver. // This is called at the start of every iteration. Reset(ctx SBSolverContext) // CalculateImpulses returns a set of impulses to be applied // to the body. CalculateImpulses(ctx SBSolverContext) SBImpulseSolution // CalculateNudges returns a set of nudges to be applied // to the body. CalculateNudges(ctx SBSolverContext) SBNudgeSolution } // SBImpulseSolution is a solution to a single-body constraint that // contains the impulses that need to be applied to the body. type SBImpulseSolution struct { Impulse sprec.Vec3 AngularImpulse sprec.Vec3 } // SBNudgeSolution is a solution to a single-body constraint that // contains the nudges that need to be applied to the body. type SBNudgeSolution struct { Nudge sprec.Vec3 AngularNudge sprec.Vec3 } var _ SBConstraintSolver = (*NilSBConstraintSolver)(nil) // NilConstraintSolver is an SBConstraintSolver that does nothing. type NilSBConstraintSolver struct{} func (s *NilSBConstraintSolver) Reset(SBSolverContext) {} func (s *NilSBConstraintSolver) CalculateImpulses(SBSolverContext) SBImpulseSolution { return SBImpulseSolution{} } func (s *NilSBConstraintSolver) CalculateNudges(SBSolverContext) SBNudgeSolution { return SBNudgeSolution{} } // SBCalculateFunc is a function that calculates a jacobian for a // single body constraint. type SBCalculateFunc func(SBSolverContext) (Jacobian, float32) // NewSBJacobianConstraintSolver returns a new SBJacobianConstraintSolver // based on the specified calculate function. func NewSBJacobianConstraintSolver(calculate SBCalculateFunc) *SBJacobianConstraintSolver { return &SBJacobianConstraintSolver{ calculate: calculate, } } var _ SBConstraintSolver = (*SBJacobianConstraintSolver)(nil) // SBJacobianConstraintSolver is a helper implementation of // SBConstraintSolver that is based on a Jacobian. type SBJacobianConstraintSolver struct { calculate SBCalculateFunc } func (s *SBJacobianConstraintSolver) Reset(SBSolverContext) {} func (s *SBJacobianConstraintSolver) CalculateImpulses(ctx SBSolverContext) SBImpulseSolution { jacobian, drift := s.calculate(ctx) if sprec.Abs(drift) < epsilon { return SBImpulseSolution{} } lambda := jacobian.ImpulseLambda(ctx.Body) return jacobian.ImpulseSolution(ctx.Body, lambda) } func (s *SBJacobianConstraintSolver) CalculateNudges(ctx SBSolverContext) SBNudgeSolution { jacobian, drift := s.calculate(ctx) if sprec.Abs(drift) < epsilon { return SBNudgeSolution{} } lambda := jacobian.NudgeLambda(ctx.Body, drift) return jacobian.NudgeSolution(ctx.Body, lambda) } // DBSolverContext contains information related to the // double-body constraint processing. type DBSolverContext struct { Primary *Body Secondary *Body ElapsedSeconds float32 } // DBConstraintSolver represents the algorithm necessary to enforce // a double-body constraint. type DBConstraintSolver interface { // Reset clears the internal cache state for this constraint solver. // This is called at the start of every iteration. Reset(ctx DBSolverContext) // CalculateImpulses returns a set of impulses to be applied // to the two bodies. CalculateImpulses(ctx DBSolverContext) DBImpulseSolution // CalculateNudges returns a set of nudges to be applied // to the two bodies. CalculateNudges(ctx DBSolverContext) DBNudgeSolution } // DBImpulseSolution is a solution to a constraint that // indicates the impulses that need to be applied to the primary body // and optionally (if the body is not nil) secondary body. type DBImpulseSolution struct { Primary SBImpulseSolution Secondary SBImpulseSolution } // DBNudgeSolution is a solution to a constraint that // indicates the nudges that need to be applied to the primary body // and optionally (if the body is not nil) secondary body. type DBNudgeSolution struct { Primary SBNudgeSolution Secondary SBNudgeSolution } var _ DBConstraintSolver = (*NilDBConstraintSolver)(nil) // NilConstraintSolver is a DBConstraintSolver that does nothing. type NilDBConstraintSolver struct{} func (s *NilDBConstraintSolver) Reset(DBSolverContext) {} func (s *NilDBConstraintSolver) CalculateImpulses(DBSolverContext) DBImpulseSolution { return DBImpulseSolution{} } func (s *NilDBConstraintSolver) CalculateNudges(DBSolverContext) DBNudgeSolution { return DBNudgeSolution{} } // DBCalculateFunc is a function that calculates a jacobian for a // double body constraint. type DBCalculateFunc func(DBSolverContext) (PairJacobian, float32) // NewDBJacobianConstraintSolver returns a new DBJacobianConstraintSolver // based on the specified calculate function. func NewDBJacobianConstraintSolver(calculate DBCalculateFunc) *DBJacobianConstraintSolver { return &DBJacobianConstraintSolver{ calculate: calculate, } } var _ DBConstraintSolver = (*DBJacobianConstraintSolver)(nil) // DBJacobianConstraintSolver is a helper implementation of // DBConstraintSolver that is based on a Jacobian. type DBJacobianConstraintSolver struct { calculate DBCalculateFunc } func (s *DBJacobianConstraintSolver) Reset(DBSolverContext) {} func (s *DBJacobianConstraintSolver) CalculateImpulses(ctx DBSolverContext) DBImpulseSolution { jacobian, drift := s.calculate(ctx) if sprec.Abs(drift) < epsilon { return DBImpulseSolution{} } lambda := jacobian.ImpulseLambda(ctx.Primary, ctx.Secondary) return jacobian.ImpulseSolution(ctx.Primary, ctx.Secondary, lambda) } func (s *DBJacobianConstraintSolver) CalculateNudges(ctx DBSolverContext) DBNudgeSolution { jacobian, drift := s.calculate(ctx) if sprec.Abs(drift) < epsilon { return DBNudgeSolution{} } lambda := jacobian.NudgeLambda(ctx.Primary, ctx.Secondary, drift) return jacobian.NudgeSolution(ctx.Primary, ctx.Secondary, lambda) }
game/physics/solver.go
0.84338
0.481637
solver.go
starcoder
package types import "math" type WordVector interface { Words() []string WordSet() Set Frequencies() []int FrequencyOf(key string) int Put(key string, count int) WordVector Inc(key string) WordVector Contains(key string) bool Length() int Dot(otherWv WordVector) float64 VectorLength() float64 Copy() WordVector } type HashWordVector struct { wv map[string]int } func NewHashWordVector() HashWordVector { return HashWordVector{ make(map[string]int), } } func NewHashWordVectorFromToken(tokens []string) HashWordVector { wv := NewHashWordVector() for _, token := range tokens { wv.Inc(token) } return wv } func (wv HashWordVector) Words() []string { keys := make([]string, len(wv.wv)) i := 0 for key := range wv.wv { keys[i] = key i++ } return keys } func (wv HashWordVector) Frequencies() []int { values := make([]int, len(wv.wv)) i := 0 for _, val := range wv.wv { values[i] = val i++ } return values } func (wv HashWordVector) FrequencyOf(key string) int { return wv.wv[key] } func (wv HashWordVector) Put(key string, count int) WordVector { wv.wv[key] = count return wv } func (wv HashWordVector) Inc(key string) WordVector { if _, ok := wv.wv[key]; !ok { wv.wv[key] = 0 } wv.wv[key] = wv.wv[key] + 1 return wv } func (wv HashWordVector) Contains(key string) bool { _, ok := wv.wv[key] return ok } func (wv HashWordVector) Length() int { return len(wv.wv) } func (wv HashWordVector) Dot(otherWv WordVector) float64 { sumDotProduct := 0 for key, val := range wv.wv { if otherWv.Contains(key) { sumDotProduct = sumDotProduct + val*otherWv.FrequencyOf(key) } } return float64(sumDotProduct) } func (wv HashWordVector) VectorLength() float64 { sumValues := float64(0) for _, val := range wv.Frequencies() { sumValues = sumValues + math.Pow(float64(val), 2) } return math.Sqrt(sumValues) } func (wv HashWordVector) Copy() WordVector { newWv := NewHashWordVector() for k, v := range wv.wv { newWv.Put(k, v) } return newWv } func (wv HashWordVector) WordSet() Set { return NewHashSetFromWords(wv.Words()) }
types/word_vector.go
0.647241
0.409398
word_vector.go
starcoder
package complexMatrix import "fmt" type mutable [][]complex128 // Creates a mutable matrix from a 2-d array of complex numbers func NewMutable(table [][]complex128) M { if len(table) == 0 { return nil } for _, row := range table[1:] { if len(row) != len(table[0]) { panic("complexMatrix.NewMutable parameter error: values are not in rectangular shape") } } return mutable(table) } // Creates a mutable matrix from 2-d arrays of real and imaginary parts func CombineIntoMutable(real [][]float64, imag [][]float64) M { return NewMutable(combine(real, imag)) } // Returns an mutable matrix with given dimensions filled with zero values func EmptyMutable(height int, width int) M { n := make(mutable, 0, height) for len(n) < height { row := make([]complex128, width) n = append(n, row) } return n } func (m mutable) copy() mutable { if m == nil { return nil } n := make(mutable, 0, len(m)) for _, col := range m { ncol := make([]complex128, len(col)) copy(ncol, col) n = append(n, ncol) } return n } func (m mutable) Dim() (int, int) { if m == nil || len(m) == 0 { return 0, 0 } return len(m), len(m[0]) } func (m mutable) Get(i int, j int) complex128 { if m == nil { return 0 } return m[i][j] } func (m mutable) Set(c complex128, i int, j int) M { m[i][j] = c return m } func (m mutable) Scale(v complex128) M { for i, col := range m { for j := range col { m[i][j] = m[i][j] * v } } return m } func (m mutable) Add(o M) M { { mW, mH := m.Dim() oW, oH := o.Dim() if mW != oW || mH != oH { panic("dimesion mismatch, can only add matricies of the same dimentions") } } for i, row := range m { for j := range row { m[i][j] = m[i][j] + o.Get(i, j) } } return m } func (m mutable) Transpose() M { return transpose{ wrap: m, } } func (m mutable) Dot(B M) M { return dot(m, B, m) } func (m mutable) Build(d [][]complex128) M { return NewMutable(d) } func (m mutable) String() string { return fmt.Sprintf("{%s}", SPrintCustom(m, "{", "}, ", ", ")) } func (m mutable) Map(f func(v complex128, column int, row int, matrix M) complex128) M { for i, col := range m { for j := range col { m[i][j] = f(m[i][j], i, j, m) } } return m } func (m mutable) Resize(Width int, Height int) M { n := make(mutable, Width) mW, mH := m.Dim() for i := range n { n[i] = make([]complex128, Height) for j := range n[i] { if i >= mW || j >= mH { n[i][j] = 0 } else { n[i][j] = m[i][j] } } } return n } func (m mutable) Immutable() M { return NewImmutable(m) } func (m mutable) Mutable() M { return m.copy() }
mutable.go
0.77806
0.616012
mutable.go
starcoder
package smartsheet import "time" type Cell struct { CellHistory ColumnId int64 `json:"columnId,omitempty"` //The Id of the column that the cell is located in ColumnType string `json:"columnType,omitempty"` //See type definition on the Column object. Only returned if the include query string parameter contains columnType. ConditionalFormat string `json:"conditionalFormat,omitempty"` //The format descriptor describing this cell's conditional format (see Formatting). Only returned if the include query string parameter contains format and this cell has a conditional format applied. DisplayValue string `json:"displayValue,omitempty"` //Visual representation of cell contents, as presented to the user in the UI. See Cell Reference. Format string `json:"format,omitempty"` //The format descriptor (see Formatting) Only returned if the include query string parameter contains format and this cell has a non-default format applied. Formula string `json:"formula,omitempty"` //The formula for a cell, if set, for instance =COUNTM([Assigned To]3). NOTE: calculation errors or problems with a formula do not cause the API call to return an error code. Instead, the response contains the same value as in the UI, such as cell.value = "#CIRCULAR REFERENCE". Hyperlink *Hyperlink `json:"hyperlink,omitempty"` //A hyperlink to a URL, sheet, or report Image *Image `json:"image,omitempty"` //The image that the cell contains. Only returned if the cell contains an image. LinkInFromCell *CellLink `json:"linkInFromCell,omitempty"` //An inbound link from a cell in another sheet. This cell's value mirrors the linked cell's value. LinksOutToCells []CellLink `json:"linksOutToCells,omitempty"` //An array of CellLink objects. Zero or more outbound links from this cell to cells in other sheets whose values mirror this cell's value. ObjectValue *ObjectValue `json:"objectValue,omitempty"` //Optionally included object representation of the cell's value. Used for updating predecessor cell values or for multi-contact details. OverrideValidation bool `json:"overrideValidation,omitempty"` //(Admin only) Indicates whether the cell value can contain a value outside of the validation limits (value = true). When using this parameter, you must also set strict to false to bypass value type checking. This property is honored for POST or PUT actions that update rows. Strict bool `json:"strict,omitempty"` //Set to false to enable lenient parsing. Defaults to true. You can specify this attribute in a request, but it is never present in a response. See Cell Value Parsing for more information about using this attribute. Value string `json:"value,omitempty"` //string number, or Boolean A string, a number, or a Boolean value -- depending on the cell type and the data in the cell. Cell values larger than 4000 characters are silently truncated. An empty cell returns no value. See Cell Reference. } type CellHistory struct { ModifiedAt *time.Time `json:"modifiedAt,omitempty"` ModifiedBy *User `json:"modifiedBy,omitempty"` } type CellLink struct { ColumnId int64 `json:"columnId,omitempty"` // Column Id of the linked cell RowId int `json:"rowId,omitempty"` // Row Id of the linked cell SheetId int `json:"sheetId,omitempty"` // Sheet Id of the sheet that the linked cell belongs to SheetName string `json:"sheetName,omitempty"` // Sheet name of the linked cell Status string `json:"status,omitempty"` } type Hyperlink struct { ReportId int `json:"reportId,omitempty"` // If non-null, this hyperlink is a link to the report with this Id. SheetId int `json:"sheetId,omitempty"` // If non-null, this hyperlink is a link to the sheet with this Id. SightId int `json:"sightId,omitempty"` // If non-null, this hyperlink is a link to the Sight with this Id. Url string `json:"url,omitempty"` // When the hyperlink is a URL link, this property contains the URL value. When the hyperlink is a sheet/report/Sight link (that is, sheetId, reportId, or sightId is non-null), this property contains the permalink to the sheet, report, or Sight. } type Image struct { Id string `json:"id,omitempty"` // Image Id AltText string `json:"altText,omitempty"` // Alternate text for the image Height int `json:"height,omitempty"` // Original height (in pixels) of the uploaded image Width int `json:"width,omitempty"` // Original width (in pixels) of the uploaded image } type ObjectValue struct { ObjectType string `json:"objectType,omitempty"` }
pkg/smartsheet/cell.go
0.667148
0.472257
cell.go
starcoder
package standarddashboard import ( "errors" "fmt" "net/url" "strconv" log "github.com/golang/glog" "github.com/google/mako/go/spec/mako" pgpb "github.com/google/mako/spec/proto/mako_go_proto" ) const ( hostURL = "mako.dev" hostScheme = "https" noSeriesID = -1 ) type dashboard struct{} // New returns a ready to use instance func New() mako.Dashboard { return new(dashboard) } func dataFilterToQueryParam(dataFilter *pgpb.DataFilter, seriesID int) (string, string, error) { seriesStr := "" if seriesID != noSeriesID { seriesStr = strconv.Itoa(seriesID) } switch dataFilter.GetDataType() { case pgpb.DataFilter_METRIC_AGGREGATE_MIN: return seriesStr + "~" + dataFilter.GetValueKey(), "min", nil case pgpb.DataFilter_METRIC_AGGREGATE_MAX: return seriesStr + "~" + dataFilter.GetValueKey(), "max", nil case pgpb.DataFilter_METRIC_AGGREGATE_MEAN: return seriesStr + "~" + dataFilter.GetValueKey(), "mean", nil case pgpb.DataFilter_METRIC_AGGREGATE_MEDIAN: return seriesStr + "~" + dataFilter.GetValueKey(), "median", nil case pgpb.DataFilter_METRIC_AGGREGATE_STDDEV: return seriesStr + "~" + dataFilter.GetValueKey(), "stddev", nil case pgpb.DataFilter_METRIC_AGGREGATE_PERCENTILE: return seriesStr + "~" + dataFilter.GetValueKey(), fmt.Sprintf("p%d", dataFilter.GetPercentileMilliRank()), nil case pgpb.DataFilter_CUSTOM_AGGREGATE: return seriesStr + "~" + dataFilter.GetValueKey(), "1", nil case pgpb.DataFilter_BENCHMARK_SCORE: if seriesID == noSeriesID { return "benchmark-score", "1", nil } return seriesStr + "s", "1", nil case pgpb.DataFilter_ERROR_COUNT: if seriesID == noSeriesID { return "error-count", "1", nil } return seriesStr + "e", "1", nil default: return "", "", fmt.Errorf("unknown DataFilter.data_type: %+v", dataFilter) } } // AggregateChart generates a link to an aggregate chart. // See mako/spec/go/dashboard.go for full documentation. func (d dashboard) AggregateChart(in *pgpb.DashboardAggregateChartInput) (url.URL, error) { if in.GetBenchmarkKey() == "" { return url.URL{}, errors.New("DashboardAggregateChartInput.benchmark_key empty or missing") } queryParams := url.Values{} queryParams.Add("benchmark_key", in.GetBenchmarkKey()) for _, dataFilter := range in.GetValueSelections() { k, v, err := dataFilterToQueryParam(dataFilter, noSeriesID) if err != nil { log.Error(err) return url.URL{}, err } queryParams.Add(k, v) } for _, tag := range in.GetTags() { queryParams.Add("tag", tag) } if in.MinTimestampMs != nil { queryParams.Add("tmin", strconv.Itoa(int(in.GetMinTimestampMs()))) } if in.MaxTimestampMs != nil { queryParams.Add("tmax", strconv.Itoa(int(in.GetMaxTimestampMs()))) } if in.MaxRuns != nil { queryParams.Add("maxruns", strconv.Itoa(int(in.GetMaxRuns()))) } return url.URL{ Scheme: hostScheme, Host: hostURL, Path: "benchmark", RawQuery: queryParams.Encode()}, nil } // RunChart generates a link to a run chart. // See mako/spec/go/dashboard.go for full documentation. func (d dashboard) RunChart(in *pgpb.DashboardRunChartInput) (url.URL, error) { if in.GetRunKey() == "" { return url.URL{}, errors.New("DashboardRunChartInput.run_key empty or missing") } queryParams := url.Values{} queryParams.Add("run_key", in.GetRunKey()) for _, mKey := range in.GetMetricKeys() { queryParams.Add("~"+mKey, "1") } return url.URL{ Scheme: hostScheme, Host: hostURL, Path: "run", RawQuery: queryParams.Encode()}, nil } // CompareAggregateChart generates a link to a compare aggregate chart, which is an aggregate // chart showing data across multiple benchamrks. // See mako/spec/go/dashboard.go for full documentation. func (d dashboard) CompareAggregateChart(in *pgpb.DashboardCompareAggregateChartInput) (url.URL, error) { if len(in.GetSeriesList()) == 0 { return url.URL{}, errors.New("DashboardCompareAggregateChartInput.series_list empty") } queryParams := url.Values{} for seriesIdx, series := range in.GetSeriesList() { seriesIdxStr := strconv.Itoa(seriesIdx) if series.GetSeriesLabel() == "" { return url.URL{}, fmt.Errorf("DashboardCompareAggregateChartInput.series_list[%d].series_label empty or missing", seriesIdx) } if series.GetBenchmarkKey() == "" { return url.URL{}, fmt.Errorf("DashboardCompareAggregateChartInput.series_list[%d].benchmark_key empty or missing", seriesIdx) } if series.ValueSelection == nil { return url.URL{}, fmt.Errorf("DashboardCompareAggregateChartInput.series_list[%d].value_selection missing", seriesIdx) } queryParams.Add(seriesIdxStr+"n", series.GetSeriesLabel()) queryParams.Add(seriesIdxStr+"b", series.GetBenchmarkKey()) k, v, err := dataFilterToQueryParam(series.GetValueSelection(), seriesIdx) if err != nil { err := fmt.Errorf("CompareAggregateChartInput.series_list[%d].value_selection err: %v", seriesIdx, err) log.Error(err) return url.URL{}, err } queryParams.Add(k, v) for _, tag := range series.GetTags() { queryParams.Add(seriesIdxStr+"t", tag) } } if in.MinTimestampMs != nil { queryParams.Add("tmin", strconv.Itoa(int(in.GetMinTimestampMs()))) } if in.MaxTimestampMs != nil { queryParams.Add("tmax", strconv.Itoa(int(in.GetMaxTimestampMs()))) } if in.MaxRuns != nil { queryParams.Add("maxruns", strconv.Itoa(int(in.GetMaxRuns()))) } return url.URL{ Scheme: hostScheme, Host: hostURL, Path: "cmpagg", RawQuery: queryParams.Encode()}, nil } // CompareRunChart generates a link to a compare run chart, which is a run chart showing // data across multiple runs. // See mako/spec/go/dashboard.go for full documentation. func (d dashboard) CompareRunChart(in *pgpb.DashboardCompareRunChartInput) (url.URL, error) { if len(in.GetRunKeys()) == 0 { return url.URL{}, errors.New("DashboardCompareRunChartInput.run_keys missing") } queryParams := url.Values{} for seriesIdx, runKey := range in.GetRunKeys() { queryParams.Add(strconv.Itoa(seriesIdx)+"r", runKey) } for _, metricKey := range in.GetMetricKeys() { queryParams.Add("~"+metricKey, "1") } return url.URL{ Scheme: hostScheme, Host: hostURL, Path: "cmprun", RawQuery: queryParams.Encode()}, nil } func (d dashboard) VisualizeAnalysis(in *pgpb.DashboardVisualizeAnalysisInput) (url.URL, error) { queryParams := url.Values{} queryParams.Add("run_key", in.GetRunKey()) fragment := "" if in.GetAnalysisKey() != "" { fragment = "analysis" + in.GetAnalysisKey() } return url.URL{ Scheme: hostScheme, Host: hostURL, Path: "analysis-results", RawQuery: queryParams.Encode(), Fragment: fragment}, nil }
go/clients/dashboard/standard_dashboard.go
0.566019
0.408218
standard_dashboard.go
starcoder
package mgots import ( "math" "time" ) // A Metric is a single aggregated metric in a sample. type Metric struct { Max float64 Min float64 Num int64 Sum float64 } // A Sample is a single aggregated sample in a time series. type Sample struct { Start time.Time Metrics map[string]Metric } // A TimeSeries is a list of samples. type TimeSeries struct { Samples []Sample } // Sum returns the sum of all measured values for the given time series. func (ts *TimeSeries) Sum(metric string) float64 { var sum float64 for _, p := range ts.Samples { sum += p.Metrics[metric].Sum } return sum } // Num returns the number of measured values for the given time series. func (ts *TimeSeries) Num(metric string) int64 { var sum int64 for _, p := range ts.Samples { sum += p.Metrics[metric].Num } return sum } // Min returns the smallest measured value for the given time series. func (ts *TimeSeries) Min(metric string) float64 { min := ts.Samples[0].Metrics[metric].Min for _, p := range ts.Samples { min = math.Min(min, p.Metrics[metric].Min) } return min } // Max returns the largest measured value for the given time series. func (ts *TimeSeries) Max(metric string) float64 { max := ts.Samples[0].Metrics[metric].Max for _, p := range ts.Samples { max = math.Max(max, p.Metrics[metric].Max) } return max } // Avg returns the average measured value for the given time series. func (ts *TimeSeries) Avg(metric string) float64 { return ts.Sum(metric) / float64(ts.Num(metric)) } // Null will return a new TimeSeries that includes samples for the specified // timestamps or a null value if no sample exists in the time series. func (ts *TimeSeries) Null(timestamps []time.Time, metrics []string) *TimeSeries { // prepare nullMetrics nullMetrics := map[string]Metric{} // fill null metrics for _, name := range metrics { nullMetrics[name] = Metric{} } // allocate samples slice samples := make([]Sample, 0, len(timestamps)) // prepare counters lastUsedSample := 0 // go through all provided timestamps for _, t := range timestamps { // prepare flag added := false // start searching samples from the last used for i := lastUsedSample; i < len(ts.Samples); i++ { // append found sample if matching if ts.Samples[i].Start.Equal(t) { samples = append(samples, ts.Samples[i]) lastUsedSample = i added = true break } // stop search if timestamp is after needle if ts.Samples[i].Start.After(t) { break } } // add null sample if none added if !added { samples = append(samples, Sample{ Start: t, Metrics: nullMetrics, }) } } return &TimeSeries{samples} }
time_series.go
0.915465
0.57946
time_series.go
starcoder
package main import "encoding/json" import "errors" import "fmt" import "io/ioutil" import "os" import "reflect" // Standard mathematical min function func min(a int, b int) int { if a < b { return a } return b } // Compares two objects and returns a list of differences relative to the json path // If the objects are the same, an empty list is returned // If the objects are different, a list with a single element is returned func compare_simple(path []interface{}, simple1 interface{}, simple2 interface{}) []map[string]interface{} { if simple1 == simple2 { return []map[string]interface{}{} } else { return []map[string]interface{}{ { "path": path, "leftValue": simple1, "rightValue": simple2, }, } } } // Compares two slices index by index and returns a list of differences relative to the json path // If the slices are the same, an empty list is returned // If the slices differ at an index, a difference is returned specifying the value in each slice // If one slice is longer than another, a difference is returned for each index in one slice and not the other func compare_slice(path []interface{}, slice1 []interface{}, slice2 []interface{}) []map[string]interface{} { l := min(len(slice1), len(slice2)) m := []map[string]interface{}{} for i := 0; i < l; i++ { i1 := slice1[i] i2 := slice2[i] m = append(m, compare_object(append(path, i), i1, i2)...) } if len(slice1) > len(slice2) { for i := l; i < len(slice1); i++ { m = append(m, map[string]interface{}{ "path": append(path, i), "leftValue": slice1[i], }) } } else if len(slice2) > len(slice1) { for i := l; i < len(slice2); i++ { m = append(m, map[string]interface{}{ "path": append(path, i), "rightValue": slice2[i], }) } } return m } // Compares two maps key by key and returns a list of differences relative to the json path // If the maps are the same, an empty list is returned // If the maps differ at a key, a difference is returned specifying the value in each map // If one map has keys which are not in the another, a difference is returned for each key in one map and not the other func compare_map(path []interface{}, map1 map[string]interface{}, map2 map[string]interface{}) []map[string]interface{} { diff := []map[string]interface{}{} for key, _ := range map1 { _, keyInMap2 := map2[key] if keyInMap2 { diff = append(diff, compare_object(append(path, key), map1[key], map2[key])...) } else { diff = append(diff, map[string]interface{}{ "path": append(path, key), "leftValue": map1[key], }) } } for key, _ := range map2 { _, keyInMap1 := map1[key] if !keyInMap1 { diff = append(diff, map[string]interface{}{ "path": append(path, key), "rightValue": map2[key], }) } } return diff } // Compares two objects and returns a list of differences relative to the json path // If the objects are the same, an empty list is returned // If the objects are different types, returns a simple difference between the objects // If the objects are the same type, it func compare_object(path []interface{}, object1 interface{}, object2 interface{}) []map[string]interface{} { // nil does not have a reflection type kind, so it's easier to hardcode this special case if object1 == nil || object2 == nil { return compare_simple(path, object1, object2) } var type1 reflect.Kind var type2 reflect.Kind type1 = reflect.TypeOf(object1).Kind() type2 = reflect.TypeOf(object2).Kind() if type1 == type2 { if type1 == reflect.Float64 { return compare_simple(path, object1, object2) } else if type1 == reflect.Bool { return compare_simple(path, object1, object2) } else if type1 == reflect.String { return compare_simple(path, object1, object2) } else if type1 == reflect.Slice { return compare_slice(path, object1.([]interface{}), object2.([]interface{})) } else if type1 == reflect.Map { return compare_map(path, object1.(map[string]interface{}), object2.(map[string]interface{})) } else { panic(errors.New("Type not found: " + string(type1))) } } else { return compare_simple(path, object1, object2) } } func main() { if len(os.Args) != 3 { fmt.Println("Usage: json-diff LEFT RIGHT") fmt.Println("") fmt.Println("Computes the difference between two json files") fmt.Println("") fmt.Println("Options:") fmt.Println(" -h --help Show this screen") os.Exit(1) } file1, err := ioutil.ReadFile(os.Args[1]) if err != nil { panic(err) } file2, err := ioutil.ReadFile(os.Args[2]) if err != nil { panic(err) } var object1 interface{} var object2 interface{} if err := json.Unmarshal(file1, &object1); err != nil { panic(err) } if err := json.Unmarshal(file2, &object2); err != nil { panic(err) } diff := compare_object([]interface{}{}, object1, object2) output, _ := json.Marshal(diff) fmt.Printf("%v\n", string(output)) if len(diff) == 0 { os.Exit(0) } else { os.Exit(1) } }
json-diff.go
0.640074
0.442275
json-diff.go
starcoder
package genlib import ( "errors" "fmt" "math" "sync" ) // DataParams is for GenData type DataParams struct { Name string GenConfig DataGen } // DataGen is the standard interface for the data types type DataGen interface { Gen() error Extract(int) (interface{}, error) PermutationCount() int SetPermutation([]int) } //GenData returns a list of permutations of the requested data types in map form func GenData(config []*DataParams, permutationRange [2]int) ([]map[string]interface{}, error) { if len(config) == 0 { return nil, errors.New("GenData : missing config") } if permutationRange[0] < 0 { return nil, fmt.Errorf("GenData : permutationRange lower bound : %v out of range", permutationRange[0]) } permutationTotal := getPermutationData(config) if permutationRange[1] > permutationTotal { return nil, fmt.Errorf("GenData : permutationRange higher bound : %v out of range", permutationRange[1]) } else if permutationRange[0] == 0 && permutationRange[1] == 0 { permutationRange[1] = permutationTotal } permutationCount := permutationRange[1] - permutationRange[0] permutationMax, permutationMap, err := setPermutation(config, permutationRange) if err != nil { return nil, err } routineCount := 0 bufferCount := 0 switch { case permutationCount < 100: routineCount = 10 bufferCount = 5 case permutationCount < 100: routineCount = 50 bufferCount = 10 default: routineCount = 100 bufferCount = 20 } results := make(chan map[int]map[string]interface{}, bufferCount) go genDataHelper(config, permutationMap, permutationMax, permutationRange, routineCount, results) ret := make([]map[string]interface{}, permutationCount) for permutation := range results { for k, v := range permutation { if err, ok := permutation[-1]; ok { return nil, err["error"].(error) } ret[k-permutationRange[0]] = v } } return ret, nil } func setPermutation(config []*DataParams, permutationRange [2]int) (map[string]int, map[string]map[int]int, error) { permutationsMax := map[string]int{} permutationMap := map[string]map[int]int{} tempRange := permutationRange for _, v := range config { genConfig := v.GenConfig permutationCount := genConfig.PermutationCount() tempMap := map[int]int{} tempPermutations := []int{} if tempRange[0] == 0 && tempRange[1] == 0 { tempPermutations, tempMap = setPermutationHelper(tempPermutations, tempMap, [2]int{0, 1}) } else { lowerbound := 0 upperbound := permutationCount if tempRange[1]-tempRange[0] < permutationCount { lowerbound = int(math.Mod(float64(tempRange[0]), float64(permutationCount))) upperbound = int(math.Mod(float64(tempRange[1]), float64(permutationCount))) // corner case when the upperbound extends past permutationCount but does not fully circle if upperbound < lowerbound { tempPermutations, tempMap = setPermutationHelper(tempPermutations, tempMap, [2]int{0, upperbound}) upperbound = permutationCount } } tempPermutations, tempMap = setPermutationHelper(tempPermutations, tempMap, [2]int{lowerbound, upperbound}) tempRange[0], tempRange[1] = tempRange[0]/permutationCount, tempRange[1]/permutationCount } permutationsMax[v.Name] = permutationCount permutationMap[v.Name] = tempMap genConfig.SetPermutation(tempPermutations) if err := genConfig.Gen(); err != nil { return nil, nil, err } } return permutationsMax, permutationMap, nil } func setPermutationHelper(tempPermutations []int, permutationMap map[int]int, bounds [2]int) ([]int, map[int]int) { index := len(tempPermutations) for i := bounds[0]; i < bounds[1]; i++ { permutationMap[i] = index tempPermutations = append(tempPermutations, i) index++ } return tempPermutations, permutationMap } func genDataHelper(config []*DataParams, permutationMap map[string]map[int]int, permutationMax map[string]int, permutationRange [2]int, routineCount int, results chan map[int]map[string]interface{}) { sem := make(chan struct{}, routineCount) var wg sync.WaitGroup wg.Add(permutationRange[1] - permutationRange[0]) for i := permutationRange[0]; i < permutationRange[1]; i++ { sem <- struct{}{} go genDataMain(config, permutationMap, permutationMax, i, &wg, sem, results) } go func() { wg.Wait() close(results) }() } func genDataMain(config []*DataParams, permutationMap map[string]map[int]int, permutationMax map[string]int, permutation int, wg *sync.WaitGroup, sem chan struct{}, results chan map[int]map[string]interface{}) { defer func() { <-sem wg.Done() }() copyPermutation := permutation ret := map[string]interface{}{} for _, v := range config { perm := permutationMap[v.Name][permutation] if permutation > permutationMax[v.Name] { perm = permutation } tempInterface, err := v.GenConfig.Extract(int(math.Mod(float64(perm), float64(permutationMax[v.Name])))) if err != nil { results <- map[int]map[string]interface{}{-1: {"error": err}} return } ret[v.Name] = tempInterface permutation = permutation / permutationMax[v.Name] } if permutation != 0 { results <- map[int]map[string]interface{}{-1: {"error": fmt.Sprintf("genDataMain : permutation : %v out of range", copyPermutation)}} return } results <- map[int]map[string]interface{}{copyPermutation: ret} } func getPermutationData(config []*DataParams) int { permutationCount := 1 for _, v := range config { permutationCount *= v.GenConfig.PermutationCount() } return permutationCount }
internal/genlib/data.go
0.553505
0.438545
data.go
starcoder
package cycle import ( "fmt" ) // R is a total cyclic order relation, maintaining a left,right projection and a tracked index, both of which may cycle independent of each other. type R struct { o pro // set projection n int // subset length z int // zero index displacement; if o.l == index-z, index args of zero map to zero } // New instance of R with displacement, index, subset length, and parent set length. func New(z, i, nsubset, nset int) (*R, error) { o := pro{i: i, n: nset} o.l = pmod(z, nset) o.r = pmod(o.l+nsubset, nset) if err := o.verify(); err != nil { return nil, err } return &R{o: o, n: nsubset, z: -z}, nil } // Left returns left projection index of parent set. Due to totality, left > right is possible. func (r *R) Left() int { return r.o.l } // Right returns right projection index of parent set. Due to totality, right < left is possible. func (r *R) Right() int { return r.o.r } // Index returns absolute index of parent set. func (r *R) Index() int { return r.o.i } // Diff returns absolute difference of index to left and right projections. func (r *R) Diff(i int) (dl, dr int) { return r.o.diff(i) } // Map an index for parent set to subset. func (r *R) Map(i int) int { dl, _ := r.o.diff(i) return pmod(dl-r.z, r.n) } // Cycle projection and index, return offset index along stride. func (r *R) Cycle(sp, si int) (i, s int, err error) { o := r.o // copy o.l, o.i, o.r = pmod(o.l+sp, o.n), pmod(o.i+si, o.n), pmod(o.r+sp, o.n) if err := o.verify(); err != nil { return 0, 0, err } if sp > 0 { i, s = r.o.r, 1 } else if sp < 0 { i, s = r.o.l, -1 } r.o = o // replace r.z -= sp // displace return i, s, nil } // Do executes fn for each index along stride to projection end. // If stride is zero, fn(index) is called once. func (r *R) Do(i, s int, fn func(i int)) { i = pmod(i, r.o.n) if s == 0 { fn(i) return } il, k := r.Diff(i) if s < 0 { k = 1 + il } for ; k > 0; k, i = k-1, pmod(i+s, r.o.n) { fn(i) } } type pro struct{ l, i, r, n int } // verify non-strict totality. func (o pro) verify() error { if o.l < o.r && !(o.l <= o.i && o.i <= o.r) { return fmt.Errorf("for l < r then l < i < r but %v < %v < %v", o.l, o.i, o.r) } if o.r < o.l && !((o.l >= o.i && o.i <= o.r) || (o.l <= o.i && o.i >= o.r)) { return fmt.Errorf("for r < l then l > i < r or l < i > r but %v %s %v %s %v", o.l, equality(o.l, o.i), o.i, equality(o.i, o.r), o.r) } return nil } // diff returns absolute difference of index to left and right projections. func (o pro) diff(i int) (dl, dr int) { return pmod(o.n+i-o.l, o.n), pmod(o.n-i+o.r, o.n) } // pmod returns positive modulo for inputs. func pmod(x, n int) int { return (x%n + n) % n } func equality(a, b int) string { if a <= b { return "<" } return ">" }
cycle/cycle.go
0.766643
0.505432
cycle.go
starcoder
package dijkstra import ( "errors" "fmt" "strings" ) type tArrayHeap struct { comparator IComparator items []interface{} size int version int64 } func (t *tArrayHeap) Size() int { return t.size } func (t *tArrayHeap) IsEmpty() bool { return t.size <= 0 } func (t *tArrayHeap) IsNotEmpty() bool { return !t.IsEmpty() } func (t *tArrayHeap) Push(value interface{}) { t.version++ t.ensureSize(t.size + 1) t.items[t.size] = value t.size++ t.ShiftUp(t.size - 1) t.version++ } func (t *tArrayHeap) ensureSize(size int) { for len(t.items) < size { t.items = append(t.items, nil) } } func (t *tArrayHeap) parentOf(i int) int { return (i - 1) / 2 } func (t *tArrayHeap) leftChildOf(i int) int { return i*2 + 1 } func (t *tArrayHeap) rightChildOf(i int) int { return t.leftChildOf(i) + 1 } func (t *tArrayHeap) last() (i int, v interface{}) { if t.IsEmpty() { return -1, nil } i = t.size - 1 v = t.items[i] return i, v } func (t *tArrayHeap) Pop() (b bool, i interface{}) { if t.IsEmpty() { return false, nil } t.version++ top := t.items[0] li, lv := t.last() t.items[0] = nil t.size-- if t.IsEmpty() { return true, top } t.items[0] = lv t.items[li] = nil t.ShiftDown(0) t.version++ return true, top } func (t *tArrayHeap) IndexOf(node interface{}) int { n := -1 for i, it := range t.items { if it == node { n = i break } } return n } func (t *tArrayHeap) ShiftUp(i int) { if i <= 0 { return } v := t.items[i] pi := t.parentOf(i) pv := t.items[pi] if t.comparator.Less(v, pv) { t.items[pi], t.items[i] = v, pv t.ShiftUp(pi) } } func (t *tArrayHeap) ShiftDown(i int) { pv := t.items[i] ok, ci, cv := t.minChildOf(i) if ok && t.comparator.Less(cv, pv) { t.items[i], t.items[ci] = cv, pv t.ShiftDown(ci) } } func (t *tArrayHeap) minChildOf(p int) (ok bool, i int, v interface{}) { li := t.leftChildOf(p) if li >= t.size { return false, 0, nil } lv := t.items[li] ri := t.rightChildOf(p) if ri >= t.size { return true, li, lv } rv := t.items[ri] if t.comparator.Less(lv, rv) { return true, li, lv } else { return true, ri, rv } } func (t *tArrayHeap) String() string { level := 0 lines := make([]string, 0) lines = append(lines, "") for { n := 1 << level min := n - 1 max := n + min - 1 if min >= t.size { break } line := make([]string, 0) for i := min; i <= max; i++ { if i >= t.size { break } line = append(line, fmt.Sprintf("%4d", t.items[i])) } lines = append(lines, strings.Join(line, ",")) level++ } return strings.Join(lines, "\n") } func NewArrayHeap(comparator IComparator) IHeap { return &tArrayHeap{ comparator: comparator, items: make([]interface{}, 0), size: 0, version: 0, } } var gNoMoreElementsError = errors.New("no more elements")
algorithm/dijkstra/IArrayHeap.go
0.565539
0.418756
IArrayHeap.go
starcoder
package go_fourier import ( "errors" ) var NumWorkers = 8 func dctWorker(rows <-chan int, jobReturns chan<- bool, signals [][]float64, forward bool) { for i := range rows { if forward { signals[i], _ = DCT1D(signals[i]) } else { signals[i], _ = DCTInverse1D(signals[i]) } jobReturns <- true } } func dct2D(signals [][]float64, forward bool) ([][]float64, error) { var err error height := len(signals) // check that input has at least one row if height == 0 { return make([][]float64, 0), errors.New("dct2D: Input 2d-array must have at least one row") } width := len(signals[0]) // check that input has at least one column if width == 0 { return make([][]float64, 0), errors.New("dct2D: Input 2d-array must have at least one column") } // Create the result array result := make([][]float64, height) for i := 0; i < height; i++ { result[i] = make([]float64, width) for j := 0; j < width; j++ { result[i][j] = signals[i][j] } } // Apply DCT on rows as 1d arrays rows := make(chan int, height) jobReturns := make(chan bool, height) for w := 0; w < NumWorkers; w++ { go dctWorker(rows, jobReturns, result, forward) } // Send rows channel each row for i := 0; i < height; i++ { rows <- i } close(rows) // Wait on workers to complete for i := 0; i < height; i++ { <-jobReturns } close(jobReturns) // Transpose the array transpose := transposeReal(result) // Apply DFT on columns as 1d arrays columns := make(chan int, width) jobReturns = make(chan bool, width) for w := 0; w < NumWorkers; w++ { go dctWorker(columns, jobReturns, transpose, forward) } // Send columns channel each column for i := 0; i < width; i++ { columns <- i } close(columns) // Wait on workers to complete for i := 0; i < width; i++ { <-jobReturns } close(jobReturns) result = transposeReal(transpose) if err != nil { return result, err } return result, nil } func transposeReal(signals [][]float64) [][]float64 { width := len(signals) height := len(signals[0]) result := make([][]float64, height) for i := 0; i < height; i++ { result[i] = make([]float64, width) } for i := 0; i < height; i++ { for j := 0; j < width; j++ { result[i][j] = signals[j][i] } } return result } func dftWorker(rows <-chan int, jobReturns chan<- bool, signals [][]complex128, forward bool, algorithm string) { for i := range rows { if forward { switch algorithm { case "radix2": DFT2Radix1D(signals[i]) default: DFTNaive1D(signals[i]) } } else { switch algorithm { case "radix2": DFTInverse2Radix1D(signals[i]) default: DFTInverseNaive1D(signals[i]) } } jobReturns <- true } } func dft2D(signals [][]complex128, forward bool, algorithm string) error { var err error height := len(signals) // check that input has at least one row if height == 0 { return errors.New("dft2D: Input 2d-array must have at least one row") } width := len(signals[0]) // check that input has at least one column if width == 0 { return errors.New("dft2D: Input 2d-array must have at least one column") } // Apply DFT on rows as 1d arrays rows := make(chan int, height) jobReturns := make(chan bool, height) for w := 0; w < NumWorkers; w++ { go dftWorker(rows, jobReturns, signals, forward, algorithm) } // Send rows channel each row for i := 0; i < height; i++ { rows <- i } close(rows) // Wait on workers to complete for i := 0; i < height; i++ { <-jobReturns } close(jobReturns) // Transpose the array transpose := transposeComplex(signals) // Apply DFT on columns as 1d arrays columns := make(chan int, width) jobReturns = make(chan bool, width) for w := 0; w < NumWorkers; w++ { go dftWorker(columns, jobReturns, transpose, forward, algorithm) } // Send columns channel each column for i := 0; i < width; i++ { columns <- i } close(columns) // Wait on workers to complete for i := 0; i < width; i++ { <-jobReturns } close(jobReturns) transpose = transposeComplex(transpose) if err != nil { return err } for i := 0; i < height; i++ { for j := 0; j < width; j++ { signals[i][j] = transpose[i][j] } } return nil } func transposeComplex(signals [][]complex128) [][]complex128 { width := len(signals) height := len(signals[0]) // create the result array result := make([][]complex128, height) for i := 0; i < height; i++ { result[i] = make([]complex128, width) } for i := 0; i < height; i++ { for j := 0; j < width; j++ { result[i][j] = signals[j][i] } } return result }
util.go
0.671578
0.498596
util.go
starcoder
package ast import ( "github.com/i-sevostyanov/NanoDB/internal/sql/parsing/token" ) // Node represents AST-node of the syntax tree for SQL query. type Node interface{} // Statement represents syntax tree node of SQL statement (like: SELECT). type Statement interface { Node statementNode() } // Expression represents syntax tree node of SQL expression (like: id < 10 AND id > 5). type Expression interface { Node expressionNode() } // SelectStatement node represents a SELECT statement. type SelectStatement struct { Result []ResultStatement From *FromStatement Where *WhereStatement OrderBy *OrderByStatement Limit *LimitStatement Offset *OffsetStatement } // ResultStatement node represents a returning expression in a SELECT statement. type ResultStatement struct { Alias string Expr Expression } // FromStatement node represents a FROM statement. type FromStatement struct { Table string } // WhereStatement node represents a WHERE statement. type WhereStatement struct { Expr Expression } // OrderByStatement node represents an ORDER BY statement. type OrderByStatement struct { Column string Direction token.Type } // LimitStatement node represents a LIMIT statement. type LimitStatement struct { Value Expression } // OffsetStatement node represents a OFFSET statement. type OffsetStatement struct { Value Expression } // InsertStatement node represents a INSERT statement. type InsertStatement struct { Table string Columns []string Values []Expression } // UpdateStatement node represents a UPDATE statement. type UpdateStatement struct { Table string Set []SetStatement Where *WhereStatement } // SetStatement node represents a key-value pair (column => value) in UPDATE statement. type SetStatement struct { Column string Value Expression } // DeleteStatement node represents a DELETE statement. type DeleteStatement struct { Table string Where *WhereStatement } // CreateDatabaseStatement node represents a CREATE DATABASE statement. type CreateDatabaseStatement struct { Database string } // DropDatabaseStatement node represents a DROP DATABASE statement. type DropDatabaseStatement struct { Database string } // CreateTableStatement node represents a CREATE TABLE statement. type CreateTableStatement struct { Table string Columns []Column } // Column node represents a table column definition. type Column struct { Name string Type token.Type Default Expression Nullable bool PrimaryKey bool } // DropTableStatement node represents a DROP TABLE statement. type DropTableStatement struct { Table string } func (s *SelectStatement) statementNode() {} func (s *ResultStatement) statementNode() {} func (s *FromStatement) statementNode() {} func (s *WhereStatement) statementNode() {} func (s *OrderByStatement) statementNode() {} func (s *LimitStatement) statementNode() {} func (s *OffsetStatement) statementNode() {} func (s *InsertStatement) statementNode() {} func (s *UpdateStatement) statementNode() {} func (s *SetStatement) statementNode() {} func (s *DeleteStatement) statementNode() {} func (s *CreateDatabaseStatement) statementNode() {} func (s *DropDatabaseStatement) statementNode() {} func (s *CreateTableStatement) statementNode() {} func (s *DropTableStatement) statementNode() {} // IdentExpr node represents an identifier. type IdentExpr struct { Name string } // BinaryExpr node represents a binary expression. type BinaryExpr struct { Left Expression Operator token.Type Right Expression } // UnaryExpr node represents a unary expression. type UnaryExpr struct { Operator token.Type Right Expression } // ScalarExpr node represents a literal of basic type. type ScalarExpr struct { Type token.Type Literal string } // AsteriskExpr node represents asterisk at `SELECT *` expression. type AsteriskExpr struct{} func (e *IdentExpr) expressionNode() {} func (e *BinaryExpr) expressionNode() {} func (e *UnaryExpr) expressionNode() {} func (e *ScalarExpr) expressionNode() {} func (e *AsteriskExpr) expressionNode() {}
internal/sql/parsing/ast/ast.go
0.731826
0.44059
ast.go
starcoder
package render import ( "image" "image/color" "github.com/stretchr/testify/mock" "golang.org/x/image/font" ) // MockCanvas is a mock implementation of the Canvas interface for testing purposes. type MockCanvas struct { mock.Mock } // SetUnderlyingImage returns the preset value(s). func (m *MockCanvas) SetUnderlyingImage(newImage image.Image) Canvas { args := m.Called(newImage) return args.Get(0).(Canvas) } // GetUnderlyingImage returns the preset value(s). func (m *MockCanvas) GetUnderlyingImage() image.Image { args := m.Called() return args.Get(0).(image.Image) } // GetWidth returns the preset value(s). func (m *MockCanvas) GetWidth() int { args := m.Called() return args.Int(0) } // GetHeight returns the preset value(s). func (m *MockCanvas) GetHeight() int { args := m.Called() return args.Int(0) } // GetPPI returns the preset value(s). func (m *MockCanvas) GetPPI() float64 { args := m.Called() return args.Get(0).(float64) } // SetPPI returns the preset value(s). func (m *MockCanvas) SetPPI(ppi float64) Canvas { args := m.Called(ppi) return args.Get(0).(Canvas) } // Rectangle returns the preset value(s). func (m *MockCanvas) Rectangle(topLeft image.Point, width, height int, colour color.Color) (Canvas, error) { args := m.Called(topLeft, width, height, colour) return args.Get(0).(Canvas), args.Error(1) } // Circle returns the preset value(s). func (m *MockCanvas) Circle(centre image.Point, radius int, colour color.Color) (Canvas, error) { args := m.Called(centre, radius, colour) return args.Get(0).(Canvas), args.Error(1) } // Text returns the preset value(s). func (m *MockCanvas) Text(text string, start image.Point, typeFace font.Face, colour color.Color, maxWidth int) (Canvas, error) { args := m.Called(text, start, typeFace, colour, maxWidth) return args.Get(0).(Canvas), args.Error(1) } // TryText returns the preset value(s). func (m *MockCanvas) TryText(text string, start image.Point, typeFace font.Face, colour color.Color, maxWidth int) (bool, int) { args := m.Called(text, start, typeFace, colour, maxWidth) return args.Bool(0), args.Int(1) } // DrawImage returns the preset value(s). func (m *MockCanvas) DrawImage(start image.Point, subImage image.Image) (Canvas, error) { args := m.Called(start, subImage) return args.Get(0).(Canvas), args.Error(1) } // Barcode returns the preset value(s). func (m *MockCanvas) Barcode(codeType BarcodeType, content []byte, extra BarcodeExtraData, start image.Point, width, height int, dataColour color.Color, bgColour color.Color) (Canvas, error) { args := m.Called(codeType, content, extra, start, width, height, dataColour, bgColour) return args.Get(0).(Canvas), args.Error(1) }
render/mockcanvas.go
0.8897
0.510558
mockcanvas.go
starcoder
package mist import ( "encoding/gob" "github.com/nlpodyssey/spago/ag" "github.com/nlpodyssey/spago/mat" "github.com/nlpodyssey/spago/nn" ) var _ nn.Model[float32] = &Model[float32]{} // Model contains the serializable parameters. type Model[T mat.DType] struct { nn.BaseModel[T] Wx nn.Param[T] `spago:"type:weights"` Wh nn.Param[T] `spago:"type:weights"` B nn.Param[T] `spago:"type:biases"` Wax nn.Param[T] `spago:"type:weights"` Wah nn.Param[T] `spago:"type:weights"` Ba nn.Param[T] `spago:"type:biases"` Wrx nn.Param[T] `spago:"type:weights"` Wrh nn.Param[T] `spago:"type:weights"` Br nn.Param[T] `spago:"type:biases"` NumOfDelays int } // State represent a state of the MIST recurrent network. type State[T mat.DType] struct { Y ag.Node[T] } func init() { gob.Register(&Model[float32]{}) gob.Register(&Model[float64]{}) } // New returns a new model with parameters initialized to zeros. func New[T mat.DType](in, out, numOfDelays int) *Model[T] { return &Model[T]{ Wx: nn.NewParam[T](mat.NewEmptyDense[T](out, in)), Wh: nn.NewParam[T](mat.NewEmptyDense[T](out, out)), B: nn.NewParam[T](mat.NewEmptyVecDense[T](out)), Wax: nn.NewParam[T](mat.NewEmptyDense[T](out, in)), Wah: nn.NewParam[T](mat.NewEmptyDense[T](out, out)), Ba: nn.NewParam[T](mat.NewEmptyVecDense[T](out)), Wrx: nn.NewParam[T](mat.NewEmptyDense[T](out, in)), Wrh: nn.NewParam[T](mat.NewEmptyDense[T](out, out)), Br: nn.NewParam[T](mat.NewEmptyVecDense[T](out)), NumOfDelays: numOfDelays, } } // Forward performs the forward step for each input node and returns the result. func (m *Model[T]) Forward(xs ...ag.Node[T]) []ag.Node[T] { ys := make([]ag.Node[T], len(xs)) states := make([]*State[T], 0) var s *State[T] = nil for i, x := range xs { s = m.Next(states, x) states = append(states, s) ys[i] = s.Y } return ys } // Next performs a single forward step, producing a new state. func (m *Model[T]) Next(states []*State[T], x ag.Node[T]) (s *State[T]) { s = new(State[T]) var yPrev ag.Node[T] = nil if states != nil { yPrev = states[len(states)-1].Y } a := ag.Softmax(ag.Affine[T](m.Ba, m.Wax, x, m.Wah, yPrev)) r := ag.Sigmoid(ag.Affine[T](m.Br, m.Wrx, x, m.Wrh, yPrev)) s.Y = ag.Tanh(ag.Affine[T](m.B, m.Wx, x, m.Wh, tryProd[T](r, m.weightHistory(states, a)))) return } func (m *Model[T]) weightHistory(states []*State[T], a ag.Node[T]) ag.Node[T] { var sum ag.Node[T] n := len(states) for i := 0; i < m.NumOfDelays; i++ { k := int(mat.Pow(2.0, T(i))) // base-2 exponential delay if k <= n { sum = ag.Add(sum, ag.ProdScalar(states[n-k].Y, ag.AtVec(a, i))) } } return sum } // tryProd returns the product if 'a' and 'b' are not nil, otherwise nil func tryProd[T mat.DType](a, b ag.Node[T]) ag.Node[T] { if a != nil && b != nil { return ag.Prod(a, b) } return nil }
nn/recurrent/mist/mist.go
0.788909
0.520131
mist.go
starcoder
package resolv // Shape is a basic interface that describes a Shape that can be passed to collision testing and resolution functions and // exist in the same Space. type Shape interface { IsColliding(Shape) bool WouldBeColliding(Shape, float64, float64) bool GetTags() []string ClearTags() AddTags(...string) RemoveTags(...string) HasTags(...string) bool GetData() interface{} SetData(interface{}) GetXY() (float64, float64) SetXY(float64, float64) Move(float64, float64) } // BasicShape isn't to be used directly; it just has some basic functions and data, common to all structs that embed it, like // position and tags. It is embedded in other Shapes. type BasicShape struct { X, Y float64 tags []string Data interface{} } // GetTags returns a reference to the the string array representing the tags on the BasicShape. func (b *BasicShape) GetTags() []string { return b.tags } // AddTags adds the specified tags to the BasicShape. func (b *BasicShape) AddTags(tags ...string) { if b.tags == nil { b.tags = []string{} } b.tags = append(b.tags, tags...) } // RemoveTags removes the specified tags from the BasicShape. func (b *BasicShape) RemoveTags(tags ...string) { for _, t := range tags { for i := len(b.tags) - 1; i >= 0; i-- { if t == b.tags[i] { b.tags = append(b.tags[:i], b.tags[i+1:]...) } } } } // ClearTags clears the tags active on the BasicShape. func (b *BasicShape) ClearTags() { b.tags = []string{} } // HasTags returns true if the Shape has all of the tags provided. func (b *BasicShape) HasTags(tags ...string) bool { hasTags := true for _, t1 := range tags { found := false for _, shapeTag := range b.tags { if t1 == shapeTag { found = true continue } } if !found { hasTags = false break } } return hasTags } // GetData returns the data on the Shape. func (b *BasicShape) GetData() interface{} { return b.Data } // SetData sets the data on the Shape. func (b *BasicShape) SetData(data interface{}) { b.Data = data } // GetXY returns the position of the Shape. func (b *BasicShape) GetXY() (float64, float64) { return b.X, b.Y } // SetXY sets the position of the Shape. func (b *BasicShape) SetXY(x, y float64) { b.X = x b.Y = y } // Move moves the Shape by the delta X and Y values provided. func (b *BasicShape) Move(x, y float64) { b.X += x b.Y += y }
resolv/shape.go
0.841468
0.706722
shape.go
starcoder
package gorm import ( "database/sql" "github.com/jinzhu/gorm" "github.com/stretchr/testify/mock" ) type FakeGorm struct { mock.Mock } func (f *FakeGorm) Close() error { return f.Called().Error(0) } func (f *FakeGorm) DB() *sql.DB { return f.Called().Get(0).(*sql.DB) } func (f *FakeGorm) New() Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) NewScope(value interface{}) *gorm.Scope { return f.Called(value).Get(0).(*gorm.Scope) } func (f *FakeGorm) CommonDB() gorm.SQLCommon { return f.Called().Get(0).(gorm.SQLCommon) } func (f *FakeGorm) Callback() *gorm.Callback { return f.Called().Get(0).(*gorm.Callback) } func (f *FakeGorm) SetLogger(log gorm.Logger) { f.Called(log) } func (f *FakeGorm) LogMode(enable bool) Gorm { return f.Called(enable).Get(0).(Gorm) } func (f *FakeGorm) SingularTable(enable bool) { f.Called(enable) } func (f *FakeGorm) Where(query interface{}, args ...interface{}) Gorm { return f.Called(query, args).Get(0).(Gorm) } func (f *FakeGorm) Or(query interface{}, args ...interface{}) Gorm { return f.Called(query, args).Get(0).(Gorm) } func (f *FakeGorm) Not(query interface{}, args ...interface{}) Gorm { return f.Called(query, args).Get(0).(Gorm) } func (f *FakeGorm) Limit(value int) Gorm { return f.Called(value).Get(0).(Gorm) } func (f *FakeGorm) Offset(value int) Gorm { return f.Called(value).Get(0).(Gorm) } func (f *FakeGorm) Order(value string, reorder ...bool) Gorm { return f.Called(value, reorder).Get(0).(Gorm) } func (f *FakeGorm) Select(query interface{}, args ...interface{}) Gorm { return f.Called(query, args).Get(0).(Gorm) } func (f *FakeGorm) Omit(columns ...string) Gorm { return f.Called(columns).Get(0).(Gorm) } func (f *FakeGorm) Group(query string) Gorm { return f.Called(query).Get(0).(Gorm) } func (f *FakeGorm) Having(query string, values ...interface{}) Gorm { return f.Called(query, values).Get(0).(Gorm) } func (f *FakeGorm) Joins(query string, args ...interface{}) Gorm { return f.Called(query, args).Get(0).(Gorm) } func (f *FakeGorm) Scopes(funcs ...func(*gorm.DB) *gorm.DB) Gorm { return f.Called(funcs).Get(0).(Gorm) } func (f *FakeGorm) Unscoped() Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) Attrs(attrs ...interface{}) Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) Assign(attrs ...interface{}) Gorm { return f.Called(attrs).Get(0).(Gorm) } func (f *FakeGorm) First(out interface{}, where ...interface{}) Gorm { return f.Called(out, where).Get(0).(Gorm) } func (f *FakeGorm) Last(out interface{}, where ...interface{}) Gorm { return f.Called(out, where).Get(0).(Gorm) } func (f *FakeGorm) Find(out interface{}, where ...interface{}) Gorm { return f.Called(out, where).Get(0).(Gorm) } func (f *FakeGorm) Scan(dest interface{}) Gorm { return f.Called(dest).Get(0).(Gorm) } func (f *FakeGorm) Row() *sql.Row { return f.Called().Get(0).(*sql.Row) } func (f *FakeGorm) Rows() (*sql.Rows, error) { args := f.Called() return args.Get(0).(*sql.Rows), args.Error(1) } func (f *FakeGorm) ScanRows(rows *sql.Rows, result interface{}) error { return f.Called(rows, result).Error(0) } func (f *FakeGorm) Pluck(column string, value interface{}) Gorm { return f.Called(column, value).Get(0).(Gorm) } func (f *FakeGorm) Count(value interface{}) Gorm { return f.Called(value).Get(0).(Gorm) } func (f *FakeGorm) Related(value interface{}, foreignKeys ...string) Gorm { return f.Called(value, foreignKeys).Get(0).(Gorm) } func (f *FakeGorm) FirstOrInit(out interface{}, where ...interface{}) Gorm { return f.Called(out, where).Get(0).(Gorm) } func (f *FakeGorm) FirstOrCreate(out interface{}, where ...interface{}) Gorm { return f.Called(out, where).Get(0).(Gorm) } func (f *FakeGorm) Update(attrs ...interface{}) Gorm { return f.Called(attrs).Get(0).(Gorm) } func (f *FakeGorm) Updates(values interface{}, ignoreProtectedAttrs ...bool) Gorm { return f.Called(values, ignoreProtectedAttrs).Get(0).(Gorm) } func (f *FakeGorm) UpdateColumn(attrs ...interface{}) Gorm { return f.Called(attrs).Get(0).(Gorm) } func (f *FakeGorm) UpdateColumns(values interface{}) Gorm { return f.Called(values).Get(0).(Gorm) } func (f *FakeGorm) Save(value interface{}) Gorm { return f.Called(value).Get(0).(Gorm) } func (f *FakeGorm) Create(value interface{}) Gorm { return f.Called(value).Get(0).(Gorm) } func (f *FakeGorm) Delete(value interface{}, where ...interface{}) Gorm { return f.Called(value, where).Get(0).(Gorm) } func (f *FakeGorm) Raw(sql string, values ...interface{}) Gorm { return f.Called(sql, values).Get(0).(Gorm) } func (f *FakeGorm) Exec(sql string, values ...interface{}) Gorm { return f.Called(sql, values).Get(0).(Gorm) } func (f *FakeGorm) Model(value interface{}) Gorm { return f.Called(value).Get(0).(Gorm) } func (f *FakeGorm) Table(name string) Gorm { return f.Called(name).Get(0).(Gorm) } func (f *FakeGorm) Debug() Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) Transaction(fc func(tx *gorm.DB) error) error { return f.Called(fc).Error(0) } func (f *FakeGorm) Begin() Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) Commit() Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) Rollback() Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) RollbackUnlessCommitted() Gorm { return f.Called().Get(0).(Gorm) } func (f *FakeGorm) NewRecord(value interface{}) bool { return f.Called(value).Bool(0) } func (f *FakeGorm) RecordNotFound() bool { return f.Called().Bool(0) } func (f *FakeGorm) CreateTable(values ...interface{}) Gorm { return f.Called(values).Get(0).(Gorm) } func (f *FakeGorm) DropTable(values ...interface{}) Gorm { return f.Called(values).Get(0).(Gorm) } func (f *FakeGorm) DropTableIfExists(values ...interface{}) Gorm { return f.Called(values).Get(0).(Gorm) } func (f *FakeGorm) HasTable(value interface{}) bool { return f.Called(value).Bool(0) } func (f *FakeGorm) AutoMigrate(values ...interface{}) Gorm { return f.Called(values).Get(0).(Gorm) } func (f *FakeGorm) ModifyColumn(column string, typ string) Gorm { return f.Called(column, typ).Get(0).(Gorm) } func (f *FakeGorm) DropColumn(column string) Gorm { return f.Called(column).Get(0).(Gorm) } func (f *FakeGorm) AddIndex(indexName string, columns ...string) Gorm { return f.Called(indexName, columns).Get(0).(Gorm) } func (f *FakeGorm) AddUniqueIndex(indexName string, columns ...string) Gorm { return f.Called(indexName, columns).Get(0).(Gorm) } func (f *FakeGorm) RemoveIndex(indexName string) Gorm { return f.Called(indexName).Get(0).(Gorm) } func (f *FakeGorm) Association(column string) *gorm.Association { return f.Called(column).Get(0).(*gorm.Association) } func (f *FakeGorm) Preload(column string, conditions ...interface{}) Gorm { return f.Called(column, conditions).Get(0).(Gorm) } func (f *FakeGorm) Set(name string, value interface{}) Gorm { return f.Called(name, value).Get(0).(Gorm) } func (f *FakeGorm) InstantSet(name string, value interface{}) Gorm { return f.Called(name, value).Get(0).(Gorm) } func (f *FakeGorm) Get(name string) (interface{}, bool) { args := f.Called(name) return args.Get(0).(interface{}), args.Bool(1) } func (f *FakeGorm) SetJoinTableHandler(source interface{}, column string, handler gorm.JoinTableHandlerInterface) { f.Called(source, column, handler) } func (f *FakeGorm) AddForeignKey(field string, dest string, onDelete string, onUpdate string) Gorm { return f.Called(field, dest, onDelete, onUpdate).Get(0).(Gorm) } func (f *FakeGorm) AddError(err error) error { return f.Called(err).Error(0) } func (f *FakeGorm) GetErrors() (errors []error) { return f.Called().Get(0).([]error) } func (f *FakeGorm) RowsAffected() int64 { return f.Called().Get(0).(int64) } func (f *FakeGorm) Error() error { return f.Called().Error(0) }
fake.go
0.68056
0.559892
fake.go
starcoder
package connpass import ( "errors" "fmt" "net/url" "strconv" "time" ) // Param is a function which set a value to url.Values. type Param func(vals url.Values) error // EventID sets value to url.Values with key "event_id". // eventID must be positive integer. func EventID(eventID int) Param { return func(vals url.Values) error { if eventID < 0 { return fmt.Errorf("invalid event id: %d", eventID) } vals.Add("event_id", strconv.Itoa(eventID)) return nil } } // Keyword sets value to url.Values with key "keyword". // keyword must not be empty string. func Keyword(keyword string) Param { return func(vals url.Values) error { if keyword == "" { return errors.New("empty keyword") } vals.Add("keyword", keyword) return nil } } // KeywordOr sets value to url.Values with key "keyword_or". // keyword must not be empty string. func KeywordOr(keyword string) Param { return func(vals url.Values) error { if keyword == "" { return errors.New("empty keyword") } vals.Add("keyword_or", keyword) return nil } } // YearMonth sets value to url.Values with key "ym". // year must be between 0 and 9999 and month must be between time.January and time.December. func YearMonth(year int, month time.Month) Param { return func(vals url.Values) error { switch { case year < 0 || year > 9999: return fmt.Errorf("year must be between 0 and 9999: %d", year) case month < time.January || month > time.December: return fmt.Errorf("invalid month: %d", month) } vals.Add("ym", fmt.Sprintf("%04d%02d", year, month)) return nil } } // YearMonth sets value to url.Values with key "ymd". // year must be between 0 and 9999 and month must be between time.January and time.December. // day must be valid day at the corresponded month. func YearMonthDay(year int, month time.Month, day int) Param { return func(vals url.Values) error { switch { case year < 0 || year > 9999: return fmt.Errorf("year must be between 0 and 9999: %d", year) case month < time.January || month > time.December: return fmt.Errorf("invalid month: %d", month) } tm := time.Date(year, month, day, 0, 0, 0, 0, time.UTC) if tm.Month() != month { return fmt.Errorf("invalid day: %d", day) } vals.Add("ymd", fmt.Sprintf("%04d%02d%02d", year, month, day)) return nil } } // Nickname sets value to url.Values with key "nickname". // nickname must not be empty string. func Nickname(nickname string) Param { return func(vals url.Values) error { if nickname == "" { return fmt.Errorf("empty nickname") } vals.Add("nickname", nickname) return nil } } // OwnerNickname sets value to url.Values with key "owner_nickname". // nickname must not be empty string. func OwnerNickname(nickname string) Param { return func(vals url.Values) error { if nickname == "" { return errors.New("empty nickname") } vals.Add("owner_nickname", nickname) return nil } } // SeriesID sets value to url.Values with key "series_id". // seriesID must be positive integer. func SeriesID(seriesID int) Param { return func(vals url.Values) error { if seriesID < 0 { return fmt.Errorf("invalid series id: %d", seriesID) } vals.Add("series_id", strconv.Itoa(seriesID)) return nil } } // Start sets value to url.Values with key "start". // start must be positive integer. func Start(start int) Param { return func(vals url.Values) error { if start < 0 { return fmt.Errorf("invalid start: %d", start) } vals.Add("start", strconv.Itoa(start)) return nil } } // OrderBy represents order of events. type OrderBy int const ( OrderByUpdate OrderBy = 1 OrderByDate OrderBy = 2 OrderByNewest OrderBy = 3 ) // Order sets value to url.Values with key "order". // order must be OrderByUpdate, OrderByDate or OrderByNewest. func Order(by OrderBy) Param { return func(vals url.Values) error { switch by { case OrderByUpdate, OrderByDate, OrderByNewest: default: return fmt.Errorf("invalid start: %d", by) } vals.Add("order", strconv.Itoa(int(by))) return nil } } // Count sets value to url.Values with key "count". // count must be positive integer. func Count(count int) Param { return func(vals url.Values) error { if count < 1 || count > 100 { return fmt.Errorf("count must be between 1 and 100: %d", count) } vals.Add("count", strconv.Itoa(count)) return nil } }
params.go
0.608594
0.40392
params.go
starcoder
package vector import ( "math" ) const ( x = iota y z ) func clone(a []float64) []float64 { clone := make([]float64, len(a)) copy(clone, a) return clone } func add(a, b []float64) []float64 { dimA, dimB := len(a), len(b) if (dimA == 1 || dimA == 2 || dimA == 3) && dimB == 1 { a[x] += b[x] return a } if dimA == 2 && dimB == 2 { a[x], a[y] = a[x]+b[x], a[y]+b[y] return a } if dimA == 3 && dimB == 2 { a[x], a[y] = a[x]+b[x], a[y]+b[y] return a } if dimA == 3 && dimB == 3 { a[x], a[y], a[z] = a[x]+b[x], a[y]+b[y], a[z]+b[z] return a } if dimB > dimA { axpyUnitaryTo(a, 1, a, b[:dimA]) } else { axpyUnitaryTo(a, 1, a, b) } return a } func sum(a []float64, vectors []Vector) []float64 { dim := len(a) if (dim == 1 || dim == 2 || dim == 3) && len(vectors) == 1 && len(vectors[0]) == 1 { a[x] += vectors[0][x] return a } if dim == 2 && len(vectors) == 1 && len(vectors[0]) == 2 { a[x], a[y] = a[x]+vectors[0][x], a[y]+vectors[0][y] return a } if dim == 3 && len(vectors) == 1 && len(vectors[0]) == 2 { a[x], a[y] = a[x]+vectors[0][x], a[y]+vectors[0][y] return a } if dim == 3 && len(vectors) == 1 && len(vectors[0]) == 3 { a[x], a[y], a[z] = a[x]+vectors[0][x], a[y]+vectors[0][y], a[z]+vectors[0][z] return a } for i := range vectors { if len(vectors[i]) > dim { axpyUnitaryTo(a, 1, a, vectors[i][:dim]) } else { axpyUnitaryTo(a, 1, a, vectors[i]) } } return a } func sub(a, b []float64) []float64 { dimA, dimB := len(a), len(b) if (dimA == 1 || dimA == 2 || dimA == 3) && dimB == 1 { a[x] -= b[x] return a } if dimA == 2 && dimB == 2 { a[x], a[y] = a[x]-b[x], a[y]-b[y] return a } if dimA == 3 && dimB == 1 { a[x] -= b[x] return a } if dimA == 3 && dimB == 2 { a[x], a[y] = a[x]-b[x], a[y]-b[y] return a } if dimA == 3 && dimB == 3 { a[x], a[y], a[z] = a[x]-b[x], a[y]-b[y], a[z]-b[z] return a } if dimB > dimA { axpyUnitaryTo(a, -1, b[:dimA], a) } else { axpyUnitaryTo(a, -1, b, a) } return a } func invert(a []float64) []float64 { for i := range a { a[i] *= -1 } return a } func scale(a []float64, size float64) []float64 { dim := len(a) if dim == 2 { a[x], a[y] = a[x]*size, a[y]*size return a } if dim == 3 { a[x], a[y], a[z] = a[x]*size, a[y]*size, a[z]*size return a } scalUnitaryTo(a, size, a) return a } func equal(a, b []float64) bool { dim := len(a) if dim != len(b) { return false } if dim == 2 { return math.Abs(a[x]-b[x]) < 1e-8 && math.Abs(a[y]-b[y]) < 1e-8 } if dim == 3 { return math.Abs(a[x]-b[x]) < 1e-8 && math.Abs(a[y]-b[y]) < 1e-8 && math.Abs(a[z]-b[z]) < 1e-8 } for i := range a { if math.Abs(a[i]-b[i]) > 1e-8 { return false } } return true } func magnitude(a []float64) float64 { dim := len(a) if dim == 1 { return math.Sqrt(a[x] * a[x]) } if dim == 2 { return math.Sqrt(a[x]*a[x] + a[y]*a[y]) } if dim == 3 { return math.Sqrt(a[x]*a[x] + a[y]*a[y] + a[z]*a[z]) } var result float64 for _, scalar := range a { result += scalar * scalar } return math.Sqrt(result) } func unit(a []float64) []float64 { dim := len(a) if dim == 2 { l := math.Sqrt(a[x]*a[x] + a[y]*a[y]) if l < 1e-8 { return a } a[x], a[y] = a[x]/l, a[y]/l return a } if dim == 3 { l := math.Sqrt(a[x]*a[x] + a[y]*a[y] + a[z]*a[z]) if l < 1e-8 { return a } a[x], a[y], a[z] = a[x]/l, a[y]/l, a[z]/l return a } l := magnitude(a) if l < 1e-8 { return a } for i := range a { a[i] = a[i] / l } return a } func dot(a, b []float64) float64 { result, dimA, dimB := 0., len(a), len(b) if dimA > dimB { b = append(b, make(Vector, dimA-dimB)...) } if dimA < dimB { a = append(a, make(Vector, dimB-dimA)...) } if dimA == 2 { return a[x]*b[x] + a[y]*b[y] } if dimA == 3 { return a[x]*b[x] + a[y]*b[y] + a[z]*b[z] } for i := range a { result += a[i] * b[i] } return result } func cross(a, b []float64) ([]float64, error) { if len(a) != 3 || len(b) != 3 { return nil, ErrNot3Dimensional } return []float64{ a[y]*b[z] - b[y]*a[z], a[z]*b[x] - b[z]*a[x], a[x]*b[y] - b[x]*a[y], }, nil } func rotate(a []float64, angle float64, axis []float64) []float64 { dim := len(a) if dim == 0 { return a } cos, sin := math.Cos(angle), math.Sin(angle) if dim == 1 && equal(axis, Z) { a = append(a, 0) } if (dim == 1 || dim == 2) && equal(axis, Z) { ax, ay := a[x], a[y] a[x] = ax*cos - ay*sin a[y] = ax*sin + ay*cos return a } if dim == 3 && equal(axis, X) { ay, az := a[y], a[z] a[y] = ay*cos - az*sin a[z] = ay*sin + az*cos return a } if dim == 3 && equal(axis, Y) { ax, az := a[x], a[z] a[x] = ax*cos + az*sin a[z] = -ax*sin + az*cos return a } if dim == 3 && equal(axis, Z) { ax, ay := a[x], a[y] a[x] = ax*cos - ay*sin a[y] = ax*sin + ay*cos return a } if dim > 3 { a = a[:3] } if l := len(axis); l < 3 { axis = append(axis, make([]float64, 3-l)...) } if dim < 3 { a = append(a, make([]float64, 3-dim)...) } u := unit(clone(axis)) x, _ := cross(u, a) d := dot(u, a) add(a, scale(a, cos)) add(a, scale(x, sin)) add(a, scale(scale(u, d), 1-cos)) if dim < 3 && equal(axis, Z) { return a[:2] } return a } func angle(a, b []float64) float64 { dimA, dimB := len(a), len(b) if dimA == 0 { return 0 } if dimA == 1 && dimB == 1 { if b[x] < a[x] { return math.Pi } return 0 } if dimA == 2 && equal(b, X) { return math.Atan2(a[y], a[x]) } if dimA < dimB { a = append(a, make([]float64, dimB-dimA)...) } if dimA > dimB { b = append(b, make([]float64, dimA-dimB)...) } if dimA == 2 { return (math.Atan2(b[y], b[x]) - math.Atan2(a[y], a[x])) } // 3 or more dimensions angle := math.Acos(dot(unit(clone(a)), unit(clone(b)))) return angle }
arithmetic.go
0.613931
0.745549
arithmetic.go
starcoder
package util import ( "encoding/binary" "encoding/json" "encoding/xml" "fmt" "strconv" "time" ) // Working Timetable time. // WorkingTime is similar to PublicTime, except we can have seconds. // In the Working Timetable, the seconds can be either 0 or 30. type WorkingTime struct { t int } const ( workingTime_min = 0 workingTime_max = 86400 ) func (a *WorkingTime) Bytes() []byte { var v uint32 if a.t < 0 { v = 0xffffffff } else { v = uint32(a.t) } b := make([]byte, 4) binary.LittleEndian.PutUint32(b, v) return b } func WorkingTimeFromBytes(b []byte) *WorkingTime { if b == nil || len(b) != 4 { return nil } v := binary.LittleEndian.Uint32(b) if v == 0xffffffff { return &WorkingTime{t: -1} } return &WorkingTime{t: int(v)} } func (a *WorkingTime) Equals(b *WorkingTime) bool { if a == nil { return b == nil || b.IsZero() } if b == nil { return a.IsZero() } if a.IsZero() { return b.IsZero() } return a.t == b.t } // Compare a WorkingTime against another, accounting for crossing midnight. // The rules for handling crossing midnight are: // < -6 hours = crossed midnight // < 0 back in time // < 18 hours increasing time // > 18 hours back in time & crossing midnight func (a *WorkingTime) Compare(b *WorkingTime) bool { if b == nil { return false } d := a.t - b.t if d < -21600 || d > 64800 { return a.t > b.t } return a.t < b.t } // NewWorkingTime returns a new WorkingTime instance from a string of format "HH:MM:SS" func NewWorkingTime(s string) *WorkingTime { v := &WorkingTime{} v.Parse(s) return v } func (v *WorkingTime) Parse(s string) { if s == "" { v.t = -1 } else { a, _ := strconv.Atoi(s[0:2]) b, _ := strconv.Atoi(s[3:5]) if len(s) > 5 { c, _ := strconv.Atoi(s[6:8]) v.Set((a * 3600) + (b * 60) + c) } else { v.Set((a * 3600) + (b * 60)) } } } // Custom JSON Marshaler. This will write null or the time as "HH:MM:SS" func (t *WorkingTime) MarshalJSON() ([]byte, error) { if t.IsZero() { return json.Marshal(nil) } return json.Marshal(t.String()) } func (t *WorkingTime) UnmarshalJSON(b []byte) error { s := string(b[:]) if s != "null" && len(s) > 2 { t.Parse(s[1 : len(s)-1]) } return nil } // Custom XML Marshaler. func (t *WorkingTime) MarshalXMLAttr(name xml.Name) (xml.Attr, error) { if t == nil || t.IsZero() { return xml.Attr{}, nil } return xml.Attr{Name: name, Value: t.String()}, nil } // String returns a PublicTime in HH:MM:SS format or 8 blank spaces if it's not set. func (t *WorkingTime) String() string { if t == nil || t.IsZero() { return " " } return fmt.Sprintf("%02d:%02d:%02d", t.t/3600, (t.t/60)%60, t.t%60) } // Get returns the WorkingTime in seconds of the day func (t *WorkingTime) Get() int { return t.t } // Set sets the WorkingTime in seconds of the day func (t *WorkingTime) Set(v int) { t.t = v } // IsZero returns true if the time is not present func (t *WorkingTime) IsZero() bool { return t.t <= 0 } // SetTime set's the working time to the current time (resolution 1 minute) func (t *WorkingTime) SetTime(tm time.Time) { t.Set((tm.Hour() * 3600) + (tm.Minute() * 60) + tm.Second()) } // WorkingTime_FromTime returns a WorkingTime from a time.Time with a resolution // of 1 minute. func WorkingTime_FromTime(tm time.Time) *WorkingTime { t := &WorkingTime{} t.SetTime(tm) return t } // Before returns true if this WorkingTime is before another func (a *WorkingTime) Before(b *WorkingTime) bool { return a.t < b.t } // After returns true if this WorkingTime is after another func (a *WorkingTime) After(b *WorkingTime) bool { return a.t > b.t } // Between returns true if this WorkingTime falls between two other WorkingTime's. // The test is inclusive of the from & to times. // If from is after to then we presume we cross midnight. func (t *WorkingTime) Between(from *WorkingTime, to *WorkingTime) bool { if from.After(to) { return (from.t <= t.t && t.t <= workingTime_max) || (t.t >= workingTime_min && t.t <= to.t) } return from.t <= t.t && t.t <= to.t } // IsApproaching returns true if the WorkingTime is in the last Minute based on the current clock func (wt WorkingTime) IsApproaching() bool { if wt.IsZero() { return false } now := Now() lm := now.Add(-61 * time.Second) t := wt.Time(now) return t.After(lm) && !t.After(now) } // Difference returns the difference between two WorkingTimes in seconds. // A positive value indicates that this WorkingTime is after the parameter. // A negative value inidcates that this WorkingTime is before the parameter. func (wt WorkingTime) Difference(ot WorkingTime) int { return wt.t - ot.t }
util/workingtime.go
0.753467
0.420659
workingtime.go
starcoder
package emacs import ( "fmt" "math/big" "reflect" "time" ) // Reflect is a type with underlying type reflect.Value that knows how to // convert itself to and from an Emacs value. type Reflect reflect.Value // Emacs attempts to convert r to an Emacs value. func (r Reflect) Emacs(e Env) (Value, error) { v := reflect.Value(r) if !v.IsValid() { return Value{}, WrongTypeArgument("go-valid-reflect-p", String(fmt.Sprintf("%#v", v))) } if v.Kind() == reflect.Interface { u := v.Elem() if !u.IsValid() { return Value{}, WrongTypeArgument("go-not-nil-p", String(fmt.Sprintf("%#v", v))) } v = u } fun, err := InFuncFor(v.Type()) if err != nil { return Value{}, err } return fun(v).Emacs(e) } // FromEmacs sets r to the Go representation of v. It returns an error if r // isn’t settable. func (r Reflect) FromEmacs(e Env, v Value) error { s := reflect.Value(r) if !s.IsValid() { return WrongTypeArgument("go-valid-reflect-p", String(fmt.Sprintf("%#v", s))) } conv, err := OutFuncFor(s.Type()) if err != nil { return err } return conv(s).FromEmacs(e, v) } type ( // InFunc is a function that returns an In for the given value. InFunc func(reflect.Value) In // OutFunc is a function that returns an Out for the given value. OutFunc func(reflect.Value) Out ) // InFuncFor returns an InFunc for the given type. If there’s no known // conversion from t to Emacs, InFuncFor returns an error. func InFuncFor(t reflect.Type) (InFunc, error) { if t.Implements(inType) { return castToIn, nil } if u := valueTypes[t]; u != nil { return func(v reflect.Value) In { return castToIn(v.Convert(u)) }, nil } if u := pointerTypes[t]; u != nil { return func(v reflect.Value) In { return castToIn(v.Convert(u)) }, nil } switch t.Kind() { case reflect.Array, reflect.Slice: if t.Elem().Kind() == reflect.Uint8 { return byteArrayIn, nil } elem, err := InFuncFor(t.Elem()) if err != nil { return nil, err } return vectorIn{elem}.call, nil case reflect.Map: key, err := InFuncFor(t.Key()) if err != nil { return nil, err } value, err := InFuncFor(t.Elem()) if err != nil { return nil, err } return hashIn{HashTestFor(t.Key()), key, value}.call, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return intIn, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return uintIn, nil case reflect.Float32, reflect.Float64: return floatIn, nil default: return nil, WrongTypeArgument("go-known-type-p", String(t.String())) } } // OutFuncFor returns an OutFunc for the given type. If there’s no known // conversion from Emacs to t, OutFuncFor returns an error. func OutFuncFor(t reflect.Type) (OutFunc, error) { if t.Implements(outType) { return castToOut, nil } if u := pointerTypes[t]; u != nil { return func(v reflect.Value) Out { return castToOut(v.Convert(u)) }, nil } if t.Kind() != reflect.Ptr { return nil, WrongTypeArgument("go-pointer-type-p", String(t.String())) } t = t.Elem() if u := valueTypes[t]; u != nil { f := func(v reflect.Value) Out { return castToOut(v.Convert(reflect.PtrTo(u))) } return f, nil } switch t.Kind() { case reflect.Array, reflect.Slice: if t.Elem().Kind() == reflect.Uint8 { return byteArrayOut, nil } elem, err := OutFuncFor(reflect.PtrTo(t.Elem())) if err != nil { return nil, err } return vectorOut{elem}.call, nil case reflect.Map: key, err := OutFuncFor(reflect.PtrTo(t.Key())) if err != nil { return nil, err } value, err := OutFuncFor(reflect.PtrTo(t.Elem())) if err != nil { return nil, err } return hashOut{key, value}.call, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return intOut, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return uintOut, nil case reflect.Float32, reflect.Float64: return floatOut, nil default: return nil, WrongTypeArgument("go-known-type-p", String(t.String())) } } type inOutFuncs struct { in InFunc out OutFunc } var ( inType = reflect.TypeOf((*In)(nil)).Elem() outType = reflect.TypeOf((*Out)(nil)).Elem() ) // Map basic types to aliases that support Emacs. Each value has to be a // defined type with the corresponding key as underlying type. The value types // have to implement In, and pointers to them have to implement Out. var valueTypes = map[reflect.Type]reflect.Type{ reflect.TypeOf(bool(false)): reflect.TypeOf(Bool(false)), reflect.TypeOf(""): reflect.TypeOf(String("")), reflect.TypeOf(([]byte)(nil)): reflect.TypeOf(Bytes(nil)), reflect.TypeOf(time.Time{}): reflect.TypeOf(Time{}), reflect.TypeOf(time.Duration(0)): reflect.TypeOf(Duration(0)), } // Map basic types to aliases that support Emacs. Each value type has to be // convertible to its corresponding key type. The value types have to // implement both In and Out. This is a variant of valueTypes for types that // are always used as pointers. var pointerTypes = map[reflect.Type]reflect.Type{ reflect.TypeOf((*big.Int)(nil)): reflect.TypeOf((*BigInt)(nil)), }
reflect.go
0.690768
0.487795
reflect.go
starcoder
package shared /*title: Shared Data First, we need to think about what data our module state contains. The data types used to model this data will be used both at the server and in the web UI, so we need to place them in a common `shared` package. As we want to display a calendar, we'll need to store a date. Now thankfully, unlike the Gregorian calendar, Ankh-Morpork's calendar has is very regular – no leap years etc. So let's implement a simple type that stores a data of the Ankh-Morpork calendar. Create the new file directly inside `plugin-tutorial`. Putting it into the `calendar` directory would later lead to the web UI depending on our whole module implementation, which won't work because of dependencies like SDL. */ // Month holds a Discworld month. type Month int // constants for each month const ( Ick Month = iota Offle February March April May June Grune August Spune Sektober Ember December ) func (m Month) String() string { return [...]string{"Ick", "Offle", "February", "March", "April", "May", "June", "Grune", "August", "Spune", "Sektober", "Ember", "December"}[m] } /* Here, we create a type for Discworld's months. Since Go does not have enums, we create a new `int`, some constants, and define its conversion to string. */ // UniversityDate stores days since the 1st of Ick, year 0. type UniversityDate int // Add adds the given amount of days to the date. func (d UniversityDate) Add(daysDelta int) UniversityDate { return d + UniversityDate(daysDelta) } // Year returns the current year (0-based) of the given date. func (d UniversityDate) Year() int { // a common year has 400 days. if d < 0 { return int((d - 399) / 400) // because Go rounds towards zero } return int(d / 400) } // Month returns the current month of the given date. func (d UniversityDate) Month() Month { // Ick has 16 days, all other months have 32 days. return Month((d.Add(-400*d.Year()) + 16) / 32) } // DayOfMonth returns the current day within the current month of the given date. func (d UniversityDate) DayOfMonth() int { t := d.Add(-400 * d.Year()) if t < 16 { // 1-based, therefore +1 return int(t + 1) } return int(t+16)%32 + 1 } /* This makes up our type for a Discworld date. I couldn't find official information about whether a year 0 exists, so we assume so for simplicity's sake. We use the term `d.Add(-400*d.Year())` to reach a value between 0 and 399 for month and day calculation, which would not work for negative numbers if we did `d%400`. */
shared.go
0.776792
0.781393
shared.go
starcoder
package obj import ( "errors" "fmt" "strconv" "strings" ) // Intersection is a coordinate in the Self-driving Rides Problem type Intersection [2]int func distance(a, b Intersection) int { x := a[0] - b[0] if x < 0 { x *= -1 } y := a[1] - b[1] if y < 0 { y *= -1 } return x + y } // Ride represents a pre booked ride in the Self-driving Rides Problem type Ride struct { From Intersection To Intersection EarliestStart int LatestFinish int } // RidesProblem represents a problem described in Google Hashcode Self-driving Rides type RidesProblem struct { Rows int Cols int NVehicles int T int Bonus int Rides []Ride } // Parse populates problem with information from string func (r *RidesProblem) Parse(f string) error { lines := strings.Split(f, "\n") stats := strings.Split(lines[0], " ") R, err := strconv.Atoi(stats[0]) if err != nil { return fmt.Errorf("failed to parse R: %v", err) } C, err := strconv.Atoi(stats[1]) if err != nil { return fmt.Errorf("failed to parse C: %v", err) } F, err := strconv.Atoi(stats[2]) if err != nil { return fmt.Errorf("failed to parse F: %v", err) } N, err := strconv.Atoi(stats[3]) if err != nil { return fmt.Errorf("failed to parse N: %v", err) } B, err := strconv.Atoi(stats[4]) if err != nil { return fmt.Errorf("failed to parse B: %v", err) } T, err := strconv.Atoi(stats[5]) if err != nil { return fmt.Errorf("failed to parse T: %v", err) } problem := RidesProblem{ T: T, Rows: R, Cols: C, Bonus: B, NVehicles: F, Rides: make([]Ride, N), } for i := range problem.Rides { stats := strings.Split(lines[1+i], " ") a, err := strconv.Atoi(stats[0]) if err != nil { return fmt.Errorf("failed to parse a for ride %v: %v", i, err) } b, err := strconv.Atoi(stats[1]) if err != nil { return fmt.Errorf("failed to parse b for ride %v: %v", i, err) } x, err := strconv.Atoi(stats[2]) if err != nil { return fmt.Errorf("failed to parse x for ride %v: %v", i, err) } y, err := strconv.Atoi(stats[3]) if err != nil { return fmt.Errorf("failed to parse y for ride %v: %v", i, err) } s, err := strconv.Atoi(stats[4]) if err != nil { return fmt.Errorf("failed to parse s for ride %v: %v", i, err) } f, err := strconv.Atoi(stats[5]) if err != nil { return fmt.Errorf("failed to parse f for ride %v: %v", i, err) } problem.Rides[i] = Ride{ From: Intersection{a, b}, To: Intersection{x, y}, EarliestStart: s, LatestFinish: f, } } (*r) = problem return nil } // RidesSolution represents assignment of rides to a car in fleet type RidesSolution map[int][]int // Parse populates solution with information from string func (r *RidesSolution) Parse(f string) error { lines := strings.Split(f, "\n") solution := map[int][]int{} assigned := map[int]bool{} // check if a ride is assigned twice if lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } for i, line := range lines { stats := strings.Split(line, " ") rides := make([]int, len(stats)-1) for j, stat := range stats[1:] { ride, err := strconv.Atoi(stat) if err != nil { return fmt.Errorf("failed to parse ride: %v", err) } if _, ok := assigned[ride]; ok { return fmt.Errorf("multiple assignments for ride %v", ride) } assigned[ride] = true rides[j] = ride } solution[i] = rides } (*r) = solution return nil } // RidesScore runs simulation for assigned rides and returns score func RidesScore(problem *RidesProblem, solution *RidesSolution) (int, error) { score := 0 if len(*solution) > problem.NVehicles { return score, errors.New("too many vehicles assigned") } for vehid, schedule := range *solution { t := 0 // reset time pos := Intersection{0, 0} // reset position for _, ridx := range schedule { // check if ride is part of the problem if ridx >= len(problem.Rides) { return score, fmt.Errorf("illegal ride assignment in for vehicle %v. Ride %v is not available", vehid, ridx) } ride := problem.Rides[ridx] // drive to ride start t += distance(pos, ride.From) if t > problem.T { break } pos = ride.From // make car wait if early and give bonus if t <= ride.EarliestStart { score += problem.Bonus t = ride.EarliestStart } // drive to ride end t += distance(pos, ride.To) if t > problem.T { break } pos = ride.To // give bonus if ride is on time if t <= ride.LatestFinish { score += distance(ride.From, ride.To) } } } return score, nil }
obj/rides.go
0.597373
0.412885
rides.go
starcoder
package backtrack /* Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the digits 1-9 must occur exactly once in each column. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. Empty cells are indicated by the character '.'. Note: The given board contain only digits 1-9 and the character '.'. You may assume that the given Sudoku puzzle will have a single unique solution. The given board size is always 9x9. */ var zero byte = '.' func SolveSudoku(board [][]byte) { solveSudoku(board) } func solveSudoku(board [][]byte) { if board == nil { return } if len(board) != 9 || len(board[0]) != 9 { return } sudoku(board, 0, 0) } func sudoku(board [][]byte, row int, col int) bool { // 终结条件 if row == 9 { return true } // 一行赋值完,进入下一行 if col >= 9 { return sudoku(board, row+1, 0) } // 该cell已经有数据,直接进入该行的下一列 if board[row][col] != zero { return sudoku(board, row, col+1) } // 该cell是空白,可填充数据 for val := 1; val < 9; val++ { // 检查填充的val是否符合sudoku条件 if hasConflict(board, row, col, byte(val)) { continue } // 满足条件,写入值 setVal(board, row, col, byte(val)) // 并进入该行的下一例 if sudoku(board, row, col+1) { return true } // 不满足最终条件,移除该行该例值 rmVal(board, row, col) } return false } func setVal(board [][]byte, row, col int, val byte) { board[row][col] = byte(val) } func rmVal(board [][]byte, row, col int) { board[row][col] = zero } // 冲突检查 func hasConflict(board [][]byte, row, col int, val byte) bool { for i := 0; i < 9; i++ { // 例检查 if i != col && board[row][i] == val { return true } // 行检查 if i != row && board[i][col] == val { return true } } // 小九宫格检查 nRow := row / 3 nCol := col / 3 for inRow := nRow * 3; inRow < (nRow+1)*3; inRow++ { for inCol := nCol * 3; inCol < (nCol)*3; inCol++ { if (inRow != row && inCol != col) && board[inRow][inCol] == val { return true } } } return false }
backtrack/sudoku.go
0.561455
0.57523
sudoku.go
starcoder
package impl import ( "fmt" "reflect" "github.com/maargenton/go-testpredicate/pkg/utils/predicate" ) // MapKeys is a transformation predicate that applies only to map values and // extract its keys into an sequence for further evaluation. Note that the keys // Will appear in no particular order. func MapKeys() (desc string, f predicate.TransformFunc) { desc = "{}.Keys()" f = func(v interface{}) (r interface{}, ctx []predicate.ContextValue, err error) { r, err = extractMapKeys(v) if err == nil { ctx = []predicate.ContextValue{ {Name: "keys", Value: r}, } } return } return } // MapValues is a transformation predicate that applies only to map values and // extract its values into an sequence for further evaluation. Note that the // values Will appear in no particular order. func MapValues() (desc string, f predicate.TransformFunc) { desc = "{}.Values()" f = func(v interface{}) (r interface{}, ctx []predicate.ContextValue, err error) { r, err = extractMapValues(v) if err == nil { ctx = []predicate.ContextValue{ {Name: "values", Value: r}, } } return } return } // --------------------------------------------------------------------------- // Helper functions to manipulate maps through the reflect package // extractMapKeys extracts the keys of a map into a slice of the associated key // type (not a slice of interface{}). func extractMapKeys(v interface{}) (r interface{}, err error) { vv := reflect.ValueOf(v) if vv.Kind() != reflect.Map { err = fmt.Errorf("value of type '%T' does not have keys", v) return } keyType := vv.Type().Key() keys := reflect.MakeSlice(reflect.SliceOf(keyType), 0, vv.Len()) for _, k := range vv.MapKeys() { keys = reflect.Append(keys, k) } r = keys.Interface() return } // extractMapValues extracts the values of a map into a slice of the associated // value type (not a slice of interface{}). func extractMapValues(v interface{}) (r interface{}, err error) { vv := reflect.ValueOf(v) if vv.Kind() != reflect.Map { err = fmt.Errorf("value of type '%T' does not have values", v) return } valueType := vv.Type().Elem() values := reflect.MakeSlice(reflect.SliceOf(valueType), 0, vv.Len()) for it := vv.MapRange(); it.Next(); { values = reflect.Append(values, it.Value()) } r = values.Interface() return } // Helper functions to manipulate maps through the reflect package // ---------------------------------------------------------------------------
pkg/utils/predicate/impl/map.go
0.634883
0.40698
map.go
starcoder
package machine // Compiled version of the schema for use as a default schema - needs to be // updated whenever the master copy gets updated const SCHEMA = ` { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://machinist.flapflap.io/machine.schema.json", "title": "Machine", "description": "A graph datastructure representing a state machine", "type": "object", "properties": { "Type": { "description": "What type of state machine this is. Must be one of: 'DFA', 'NFA', 'PDA', or 'TM'", "type": "string", "pattern": "(DFA|NFA|PDA|TM)" }, "Alphabet": { "description": "The symbols that are accepted by the machine. This is a string where every character is a valid symbol accepted by the machine. If this field is omitted, then the alphabet will be inferred from the Transitions field.", "type": "string" }, "Start": { "description": "The 'Id' field for the starting state of the machine", "type": "string", "pattern": "q([1-9]\\d*|0)" }, "States": { "description": "The collection of states that are part of the machine", "type": "array", "minItems": 0, "uniqueItems": true, "items": { "type": "object", "properties": { "Id": { "description": "The id (unique) of the state e.g. 'q0', 'q1'. No leading zeros.", "type": "string", "pattern": "q([1-9]\\d*|0)" }, "Ending": { "description": "Whether or not this state is an ending state. If absent, this value should be considered 'false'", "type": "boolean" } }, "required": ["Id"] } }, "Transitions": { "description": " The collection of transitions that are part of the machine", "minItems": 0, "uniqueItems": true, "items": { "type": "object", "properties": { "Start": { "description": "The 'Id' field for the starting state of the transition", "type": "string", "pattern": "q([1-9]\\d*|0)" }, "End": { "description": "The 'Id' field for the ending state of the transition", "type": "string", "pattern": "q([1-9]\\d*|0)" }, "Symbol": { "description": "The symbol(s) that is consumed from the input tape in order to traverse this transition", "type": "string" } }, "required": ["Start", "End", "Symbol"] } } }, "required": ["Start", "States", "Transitions", "Type"] } `
core/simulation/machine/machine.schema.json.go
0.845145
0.659549
machine.schema.json.go
starcoder
package maxpooling import ( "math" "math/rand" "gitlab.com/akita/mgpusim/benchmarks/dnn/layers" "gitlab.com/akita/mgpusim/driver" ) // Parameters defines the parameters of the maxpooling benchmark. type Parameters struct { N, C, H, W int KernelH, KernelW int StrideH, StrideW int PadH, PadW int } // PooledH returns the height of the output image. func (p Parameters) PooledH() int { return int(math.Ceil(float64(p.H+2*p.PadH-p.KernelH)/float64(p.StrideH))) + 1 } // PooledW returns the width of the output image. func (p Parameters) PooledW() int { return int(math.Ceil(float64(p.W+2*p.PadW-p.KernelW)/float64(p.StrideW))) + 1 } // InputLength returns the length of the input data. func (p Parameters) InputLength() int { return p.N * p.C * p.H * p.W } // OutputLength returns the length of the output data. func (p Parameters) OutputLength() int { return p.N * p.C * p.PooledH() * p.PooledW() } // Benchmark defines a benchmark type Benchmark struct { driver *driver.Driver context *driver.Context gpus []int parameters Parameters layer *layers.MaxPoolingLayer useUnifiedMemory bool } // NewBenchmark makes a new benchmark func NewBenchmark( driver *driver.Driver, parameters Parameters, ) *Benchmark { b := new(Benchmark) b.driver = driver b.context = driver.Init() b.parameters = parameters b.layer = layers.NewMaxPoolingLayer( [2]int{b.parameters.StrideH, b.parameters.StrideW}, [2]int{b.parameters.PadH, b.parameters.PadW}, [2]int{b.parameters.KernelH, b.parameters.KernelW}, b.driver, b.context, ) return b } // SelectGPU selects GPU func (b *Benchmark) SelectGPU(gpus []int) { b.gpus = gpus } // SetUnifiedMemory uses Unified Memory func (b *Benchmark) SetUnifiedMemory() { b.useUnifiedMemory = true } // EnableVerification will ask the layer to check the results after running the // forward and backward pass. func (b *Benchmark) EnableVerification() { b.layer.EnableVerification() } // Run runs func (b *Benchmark) Run() { b.driver.SelectGPU(b.context, b.gpus[0]) b.exec() } func (b *Benchmark) exec() { forwardIn := make([]float64, b.parameters.InputLength()) for i := 0; i < b.parameters.InputLength(); i++ { forwardIn[i] = rand.Float64() } backwardIn := make([]float64, b.parameters.OutputLength()) for i := 0; i < b.parameters.OutputLength(); i++ { backwardIn[i] = rand.Float64() } forwardInputTensor := layers.NewTensor(b.driver, b.context) forwardInputTensor.Init(forwardIn, []int{ b.parameters.N, b.parameters.C, b.parameters.H, b.parameters.W, }) backwardInputTensor := layers.NewTensor(b.driver, b.context) backwardInputTensor.Init(backwardIn, []int{ b.parameters.N, b.parameters.C, b.parameters.PooledH(), b.parameters.PooledW(), }) b.layer.Forward(forwardInputTensor) b.layer.Backward(backwardInputTensor) } // Verify verifies func (b *Benchmark) Verify() { // Do nothing }
benchmarks/dnn/maxpooling/maxpooling.go
0.800926
0.400749
maxpooling.go
starcoder
package btree // Method indicate tree traversal method, pre-order, in-order, post-order type Method int // show tree traversal method const ( PreOrder Method = iota InOrder PostOrder ) // Iter is a tree iterator, Recursively traversal type Iter struct { nodeChain []*TreeNode pleft *TreeNode pright *TreeNode order Method value int } // NewTreeIter construct a new Tree Iterator func NewTreeIter(t *TreeNode, m Method) *Iter { if t == nil { return nil } it := &Iter{order: m} it.fillNodes(t) return it } func (it *Iter) fillNodes(t *TreeNode) { if t == nil { return } if it.order == PreOrder { it.nodeChain = append(it.nodeChain, t) it.fillNodes(t.left) it.fillNodes(t.right) } else if it.order == InOrder { it.fillNodes(t.left) it.nodeChain = append(it.nodeChain, t) it.fillNodes(t.right) } else if it.order == PostOrder { it.fillNodes(t.left) it.fillNodes(t.right) it.nodeChain = append(it.nodeChain, t) } } // Next return true if next tree node is exist func (it *Iter) Next() bool { if s := len(it.nodeChain); s > 0 { it.value = it.nodeChain[0].data it.nodeChain = it.nodeChain[1:s] return true } return false } // Value return current node value func (it *Iter) Value() int { return it.value } // Iter2 is a iterator implemented with channel, it's similar with yield in python type Iter2 struct { ch chan int order Method value int } // NewTreeIter2 construct new iterator with t func NewTreeIter2(t *TreeNode, m Method) *Iter2 { if t == nil { return nil } ch := make(chan int) it2 := &Iter2{ch: ch, order: m} go func() { defer close(it2.ch) it2.travelTree(t) }() return it2 } func (it2 *Iter2) travelTree(tn *TreeNode) { if tn == nil { return } if it2.order == PreOrder { it2.ch <- tn.data it2.travelTree(tn.left) it2.travelTree(tn.right) } else if it2.order == InOrder { it2.travelTree(tn.left) it2.ch <- tn.data it2.travelTree(tn.right) } else if it2.order == PostOrder { it2.travelTree(tn.left) it2.travelTree(tn.right) it2.ch <- tn.data } } // Next return true if there is still valid data exist func (it2 *Iter2) Next() bool { for v := range it2.ch { it2.value = v return true } return false } // Value return current node data func (it2 *Iter2) Value() int { return it2.value } // Iter3 is a tree iterator, use for loop other than recursively traversal type Iter3 struct { pnode *TreeNode prenode *TreeNode nodeChain []*TreeNode order Method } // NewTreeIter3 construct a new Tree Iterator func NewTreeIter3(t *TreeNode, m Method) *Iter3 { it := &Iter3{pnode: t, order: m} return it } // Next return true if there is still valid data exist func (it *Iter3) Next() bool { if it.order == PreOrder { return it.hasNextPreOrder() } else if it.order == InOrder { return it.hasNextInOrder() } else if it.order == PostOrder { return it.hasNextPostOrder() } return false } func (it *Iter3) hasNextPreOrder() bool { for { if it.pnode != nil { it.nodeChain = append(it.nodeChain, it.pnode) // push it.prenode = it.pnode it.pnode = it.pnode.left return true } l := len(it.nodeChain) if l > 0 { it.pnode = it.nodeChain[l-1].right it.nodeChain = it.nodeChain[:l-1] // pop } if it.pnode == nil && l == 0 { return false } } } func (it *Iter3) hasNextInOrder() bool { for { for it.pnode != nil { it.nodeChain = append(it.nodeChain, it.pnode) // push it.pnode = it.pnode.left } l := len(it.nodeChain) if l > 0 { it.pnode = it.nodeChain[l-1].right it.prenode = it.nodeChain[l-1] it.nodeChain = it.nodeChain[:l-1] // pop return true } if it.pnode == nil && l == 0 { return false } } } func (it *Iter3) hasNextPostOrder() bool { for { for it.pnode != nil { it.nodeChain = append(it.nodeChain, it.pnode) // push it.pnode = it.pnode.left } l := len(it.nodeChain) if l > 0 { it.pnode = it.nodeChain[l-1].right if it.pnode == nil || it.prenode == it.pnode { it.prenode = it.nodeChain[l-1] it.nodeChain = it.nodeChain[:l-1] // pop it.pnode = nil return true } } if it.pnode == nil && l == 0 { return false } } } // Value return current node data func (it *Iter3) Value() int { return it.prenode.data } // Iter4 is a tree iterator, use chan and loop type Iter4 struct { pnode *TreeNode prenode *TreeNode nodeChain []*TreeNode order Method ch chan int value int } // NewTreeIter4 construct a new Tree Iterator func NewTreeIter4(t *TreeNode, m Method) *Iter4 { var c = make(chan int) it := &Iter4{pnode: t, order: m, ch: c} go func() { if it.order == PreOrder { it.hasNextPreOrder() } else if it.order == InOrder { it.hasNextInOrder() } else if it.order == PostOrder { it.hasNextPostOrder() } close(it.ch) }() return it } // Next return true if there is still valid data exist func (it *Iter4) Next() bool { for v := range it.ch { it.value = v return true } return false } func (it *Iter4) hasNextPreOrder() { for { if it.pnode != nil { it.nodeChain = append(it.nodeChain, it.pnode) // push it.ch <- it.pnode.data it.pnode = it.pnode.left continue } l := len(it.nodeChain) if l > 0 { it.pnode = it.nodeChain[l-1].right it.nodeChain = it.nodeChain[:l-1] // pop } if it.pnode == nil && l == 0 { return } } } func (it *Iter4) hasNextInOrder() { for { for it.pnode != nil { it.nodeChain = append(it.nodeChain, it.pnode) // push it.pnode = it.pnode.left } l := len(it.nodeChain) if l > 0 { it.ch <- it.nodeChain[l-1].data it.pnode = it.nodeChain[l-1].right it.nodeChain = it.nodeChain[:l-1] // pop continue } if it.pnode == nil && l == 0 { return } } } func (it *Iter4) hasNextPostOrder() { for { for it.pnode != nil { it.nodeChain = append(it.nodeChain, it.pnode) // push it.pnode = it.pnode.left } l := len(it.nodeChain) if l > 0 { it.pnode = it.nodeChain[l-1].right if it.pnode == nil || it.prenode == it.pnode { it.ch <- it.nodeChain[l-1].data it.prenode = it.nodeChain[l-1] it.nodeChain = it.nodeChain[:l-1] // pop it.pnode = nil continue } } if it.pnode == nil && l == 0 { return } } } // Value return current node data func (it *Iter4) Value() int { return it.value }
btree/treeiterator.go
0.700075
0.501526
treeiterator.go
starcoder
package components import ( "math" "sort" "github.com/factorion/graytracer/pkg/primitives" "github.com/factorion/graytracer/pkg/patterns" "github.com/factorion/graytracer/pkg/shapes" ) // World Container for objects type World struct { objects []shapes.Shape lights []PointLight background patterns.RGB } // MakeWorld Make an empty world and a black background func MakeWorld() *World { return &World{objects: []shapes.Shape{}, lights: []PointLight{}, background: *patterns.MakeRGB(0, 0, 0)} } // AddObject Add a shape object to the world func (w *World) AddObject(shape shapes.Shape) { w.objects = append(w.objects, shape) } // AddLight Add a light object to the world func (w *World) AddLight(light PointLight) { w.lights = append(w.lights, light) } // SetBackground Set the background color func (w *World) SetBackground(color patterns.RGB) { w.background = color } // Intersect Calculate the intersections from the ray to world objects func (w World) Intersect(ray primitives.Ray) shapes.Intersections { var i shapes.Intersections for _, s := range w.objects { i = append(i, s.Intersect(ray)...) } sort.Sort(i) return i } // ReflectedColor Calculate the color of the reflected ray func (w World) ReflectedColor(comps Computations, remaining int) patterns.RGB { reflective := comps.Obj.Material().Reflective if reflective == 0 { return *patterns.MakeRGB(0, 0, 0) } reflectRay := primitives.Ray{Origin:comps.OverPoint, Direction:comps.ReflectVector} return w.ColorAt(reflectRay, remaining - 1).Scale(reflective) } // RefractedColor Calculate the color of the refracted ray func (w World) RefractedColor(comps Computations, remaining int) patterns.RGB { transparency := comps.Obj.Material().Transparency if transparency == 0 { return *patterns.MakeRGB(0, 0, 0) } nRatio := comps.Index1 / comps.Index2 cosi := comps.EyeVector.DotProduct(comps.NormalVector) sin2t := math.Pow(nRatio, 2) * (1 - math.Pow(cosi, 2)) if sin2t > 1 { // Total internal reflection return *patterns.MakeRGB(0, 0, 0) } cost := math.Sqrt(1 - sin2t) direction := comps.NormalVector.Scalar((nRatio * cosi) - cost).Subtract(comps.EyeVector.Scalar(nRatio)) refractRay := primitives.Ray{Origin:comps.UnderPoint, Direction:direction} return w.ColorAt(refractRay, remaining - 1).Scale(transparency) } // ColorAt Calculate the color of a possible intersection hit func (w World) ColorAt(ray primitives.Ray, remaining int) patterns.RGB { surface := *patterns.MakeRGB(0, 0, 0) if remaining <= 0 { return surface } intersections := w.Intersect(ray) intersection, hit := intersections.Hit() if !hit { return w.background } comp := PrepareComputations(intersection, ray, intersections) for _, light := range w.lights { shade := 1.0 shadowVector := light.Position.Subtract(comp.OverPoint) distance := shadowVector.Magnitude() shadowRay := primitives.Ray{Origin:comp.OverPoint, Direction:shadowVector.Normalize()} shadowIntersections := w.Intersect(shadowRay) _, shadowHit := shadowIntersections.Hit() if shadowHit { shadowShapes := make(map[shapes.Shape]bool) for _, shadeIntersection := range shadowIntersections { if shadeIntersection.Distance > distance { break } if _, exists := shadowShapes[shadeIntersection.Obj]; !exists && shadeIntersection.Distance > 0 { shadowShapes[shadeIntersection.Obj] = true shade *= shadeIntersection.Obj.Material().Transparency } } } surface = surface.Add(Lighting(comp.Obj, light, comp.Point, comp.EyeVector, comp.NormalVector, shade)) } reflected := w.ReflectedColor(comp, remaining) refracted := w.RefractedColor(comp, remaining) material := comp.Obj.Material() if material.Reflective > 0 && material.Transparency > 0 { reflectance := comp.Schlick() return surface.Add(reflected.Scale(reflectance)).Add(refracted.Scale(1 - reflectance)) } return surface.Add(reflected).Add(refracted) }
pkg/components/world.go
0.820397
0.473475
world.go
starcoder
package shape import ( "fmt" "math" "github.com/fogleman/gg" "github.com/golang/freetype/raster" ) // Triangle represents a triangular shape type Triangle struct { X1, Y1 float64 X2, Y2 float64 X3, Y3 float64 MaxArea int } func NewTriangle() *Triangle { return &Triangle{} } func NewMaxAreaTriangle(area int) *Triangle { t := &Triangle{} t.MaxArea = area return t } func (t *Triangle) Init(plane *Plane) { rnd := plane.Rnd t.X1 = randomW(plane) t.Y1 = randomH(plane) t.X2 = t.X1 + rnd.NormFloat64()*32 t.Y2 = t.Y1 + rnd.NormFloat64()*32 t.X3 = t.X1 + rnd.NormFloat64()*32 t.Y3 = t.Y1 + rnd.NormFloat64()*32 t.mutateImpl(plane, 1.0, 2, ActionAny) } func (t *Triangle) Draw(dc *gg.Context, scale float64) { dc.LineTo(t.X1, t.Y1) dc.LineTo(t.X2, t.Y2) dc.LineTo(t.X3, t.Y3) dc.ClosePath() dc.Fill() } func (t *Triangle) SVG(attrs string) string { return fmt.Sprintf( "<polygon %s points=\"%f,%f %f,%f %f,%f\" />", attrs, t.X1, t.Y1, t.X2, t.Y2, t.X3, t.Y3) } func (t *Triangle) Copy() Shape { a := *t return &a } func (t *Triangle) Mutate(plane *Plane, temp float64) { t.mutateImpl(plane, temp, 100, ActionAny) } func (t *Triangle) mutateImpl(plane *Plane, temp float64, rollback int, actions ActionType) { if actions == ActionNone { return } const R = math.Pi / 4.0 const m = 16 w := float64(plane.W - 1 + m) h := float64(plane.H - 1 + m) rnd := plane.Rnd scale := 16 * temp save := *t for { switch rnd.Intn(5) { // Mutate. case 0: if (actions & ActionMutate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale t.X1 = clamp(t.X1+a, -m, w) t.Y1 = clamp(t.Y1+b, -m, h) case 1: if (actions & ActionMutate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale t.X2 = clamp(t.X2+a, -m, w) t.Y2 = clamp(t.Y2+b, -m, h) case 2: if (actions & ActionMutate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale t.X3 = clamp(t.X3+a, -m, w) t.Y3 = clamp(t.Y3+b, -m, h) case 3: // Translate if (actions & ActionTranslate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale t.X1 = clamp(t.X1+a, -m, w) t.Y1 = clamp(t.Y1+b, -m, h) t.X2 = clamp(t.X2+a, -m, w) t.Y2 = clamp(t.Y2+b, -m, h) t.X3 = clamp(t.X3+a, -m, w) t.Y3 = clamp(t.Y3+b, -m, h) case 4: // Rotate if (actions & ActionRotate) == 0 { continue } cx := (t.X1 + t.X2 + t.X3) / 3 cy := (t.Y1 + t.Y2 + t.Y3) / 3 theta := rnd.NormFloat64() * temp * R cos := math.Cos(theta) sin := math.Sin(theta) var a, b float64 a, b = rotateAbout(t.X1, t.Y1, cx, cy, cos, sin) t.X1 = clamp(a, -m, w) t.Y1 = clamp(b, -m, h) a, b = rotateAbout(t.X2, t.Y2, cx, cy, cos, sin) t.X2 = clamp(a, -m, w) t.Y2 = clamp(b, -m, h) a, b = rotateAbout(t.X2, t.Y2, cx, cy, cos, sin) t.X3 = clamp(a, -m, w-1+m) t.Y3 = clamp(b, -m, h-1+m) } if t.Valid() { break } if rollback > 0 { *t = save rollback -= 1 } } } func (t *Triangle) Valid() bool { if t.MaxArea > 0 { // compute the area. a := (t.X1*(t.Y2-t.Y3) + t.X2*(t.Y3-t.Y1) + t.X3*(t.Y1-t.Y2)) / 2 if a < 0 { a = -a } if a > float64(t.MaxArea) { return false } } const minDegrees = 15 var a1, a2, a3 float64 { x1 := t.X2 - t.X1 y1 := t.Y2 - t.Y1 x2 := t.X3 - t.X1 y2 := t.Y3 - t.Y1 d1 := math.Sqrt(x1*x1 + y1*y1) d2 := math.Sqrt(x2*x2 + y2*y2) x1 /= d1 y1 /= d1 x2 /= d2 y2 /= d2 a1 = degrees(math.Acos(x1*x2 + y1*y2)) } { x1 := t.X1 - t.X2 y1 := t.Y1 - t.Y2 x2 := t.X3 - t.X2 y2 := t.Y3 - t.Y2 d1 := math.Sqrt(x1*x1 + y1*y1) d2 := math.Sqrt(x2*x2 + y2*y2) x1 /= d1 y1 /= d1 x2 /= d2 y2 /= d2 a2 = degrees(math.Acos(x1*x2 + y1*y2)) } a3 = 180 - a1 - a2 return a1 > minDegrees && a2 > minDegrees && a3 > minDegrees } func (t *Triangle) Rasterize(rc *RasterContext) []Scanline { var path raster.Path path.Start(fixp(t.X1, t.Y1)) path.Add1(fixp(t.X2, t.Y2)) path.Add1(fixp(t.X3, t.Y3)) path.Add1(fixp(t.X1, t.Y1)) return fillPath(rc, path) }
primitive/shape/triangle.go
0.800146
0.541773
triangle.go
starcoder
package main import ( "fmt" "sync" ) // In this video, we'll discuss some fundamental components of sharing work between Goroutines. // ST // The simplest way to share data between goroutines is to pass a pointer to each goroutine which // points to the same piece of memory. Each Goroutine can read and write to this memory whenever it // wants to. // This is easy but can have downsides. // ST // Let's jump into the editor and take a look. // One important structure that is designed to be shared between Goroutines is the WaitGroup, a data // structure that allows us to forgoe the explicit timeout we used in the previous examples. // In this example, I'll just run a simple "even or odd" program. // Let's write the actual computation as a function. It takes an integer argument by value, // and a pointer to a WaitGroup. All the Goroutines will be using the same WaitGroup. func printEven(x int, wg *sync.WaitGroup) { // The actual computation here is trivial. // If even, print even. // Otherwise, print odd. if x%2 == 0 { fmt.Printf("%d is even\n", x) } else { fmt.Printf("%d is odd\n", x) } // Finally, we'll inform the WaitGroup the function has completed. wg.Done() } // Now, in our main function, we'll use this printEven function asyncronously. func main1() { // First, lets make a WaitGroup. // It has an internal counter, and it will initially be set to zero. var wg sync.WaitGroup // We can use a for loop to spawn a bunch of goroutines for i := 1; i < 10; i++ { // Before creating each Goroutine, we add to the WaitGroup's internal counter. wg.Add(1) // Then we pass the WaitGroup to the worker. // Remember, when the function is done, it calls Done on the WaitGroup. // Done decrements the counter by one. go printEven(i, &wg) } // Finally, we tell the program to wait until the WaitGroup is finished. // That is, this function blocks until the WaitGroup's counter is at zero. wg.Wait() } // Running this program, we can see that the WaitGroup allows us to wait only as long as // needed for all Goroutines to complete. // So, we've seen an example of how communicating by sharing memory works well. Now let's see // how it can go wrong. Our function will be really similar, but instead of having an independent // computation per Goroutine, we'll make all the Goroutines do the same thing to the same data. // In this case, it's a simple increment. It takes a pointer to an integer and a pointer to // a WaitGroup. func increment(ptr *int, wg *sync.WaitGroup) { // To illustrate the bug, we'll first extract the value of the integer. i := *ptr // Then we'll do something that takes a little time, like print. fmt.Printf("value is %d\n", i) // Now we'll use the value we extracted, adding to it and putting it back in the pointer. *ptr = i + 1 wg.Done() } // The main function is pretty much exactly the same. func main() { // Make a WaitGroup, as above. var wg sync.WaitGroup // Val will be the value that the increment function operates on. val := 0 // As before, we'll spawn goroutines in a loop. for i := 0; i < 10000; i++ { // Again, add to the WaitGroup every time. wg.Add(1) // Then run the actual operation. go increment(&val, &wg) } wg.Wait() // Once everything is done, we can look at the final value. // It should be 10000. fmt.Printf("Final value was %d\n", val) } // Running the program, you should see that it's not always 10000. // That's because each Goroutine sets the value to whatever it saw plus one, // potentially undoing the work of other Goroutines. // ST // In the next video, we'll see how to overcome this issue with one of Go's most // powerful constructs; channels.
s2t3/main.go
0.565179
0.631225
main.go
starcoder
package moretypes import "fmt" //Array possui um tamanho pré definido, enquanto slices não. //Slices são muito mais comuns //O retorno como ponteiro foi para permitir a instanciação por um slice //no método sliceFunction. Mais informações aqui: https://stackoverflow.com/questions/50062243/error-addressing-the-returned-slice-of-a-function func arrayFunction() *[4]string { //Poderia ter sido iniciado como [4]string{"a","b","c","d"} var a [4]string a[0] = "a" a[1] = "b" a[2] = "c" a[2] = "d" return &a } func SlicesFunction() { fmt.Println("Slices function") //This selects a half-open range which includes the first element, but excludes the last one. s := arrayFunction()[0:4] s[0] = "z" // When slicing, you may omit the high or low bounds to use their defaults instead. //The default is zero for the low bound and the length of the slice for the high bound. //Ex: arrayFunction()[0:], arrayFunction()[:4], arrayFunction()[:] b := arrayFunction()[0:4] c := b[0:2] //Changing the elements of a slice modifies the corresponding elements of its underlying array. c[0] = "x" fmt.Println(s) fmt.Println(b) sliceCapacityAndLength() makeSlice() appendSlice() } // The length of a slice is the number of elements it contains. // The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice. func sliceCapacityAndLength() { fmt.Print("Slice capacity and length") s := []int{2, 3, 5, 7, 11, 13} printSlice(s) // Slice the slice to give it zero length. s = s[:0] printSlice(s) // Extend its length. s = s[:4] printSlice(s) // Drop its first two values. s = s[2:] printSlice(s) } //The make function allocates a zeroed array and returns a slice that refers to that array: //To specify a capacity, pass a third argument to make func makeSlice() { fmt.Print("make slice") a := make([]int, 5) printSlice(a) b := make([]int, 0, 5) printSlice(b) c := b[:2] printSlice(c) d := c[2:5] printSlice(d) } func appendSlice() { s := arrayFunction()[0:4] s = append(s, "1", "2", "3", "4") fmt.Println(s) } func printSlice(s []int) { fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) } /* Slices can contain any type, including other slices. board := [][]string{ []string{"_", "_", "_"}, []string{"_", "_", "_"}, []string{"_", "_", "_"}, } */
go-tour/moretypes/slices.go
0.665193
0.59131
slices.go
starcoder
package command import ( "encoding/base64" "fmt" "image/color" "strconv" "strings" ) // ChunkDataRequest produces the command used to get a string of chunk data of a certain chunk. // The command is only available on education edition games. This may be enabled using minecraft://?edu=1. func ChunkDataRequest(dimension string, chunkX, chunkZ int, maxY int) string { return fmt.Sprintf("getchunkdata %v %v %v %v", dimension, chunkX, chunkZ, maxY) } // ChunkData is sent by the server to receive a string of chunk data of the highest blocks in a chunk, // containing an RGB-24 colour of the blocks and their heights. type ChunkData struct { // Data is a string of data, with the data being joined with commas. The string has some methods to make // consume less space. The Data string is ordered in XZ order. Multiple blocks after each other result in // a multiplier being added to the previous. The multiplier needs one added to get the total amount. // "AAAAAQ*254" translates to 255 times AAAAAQ in a row. // If the same block is found twice in the chunk data at different positions, the second position gets a // pointer to the data of the first position. This results in values like these: "jMnVPw,c6SuPw,11,12,11". // When having all offsets to their correct data, each string must be base64 decoded. Note that these // strings do not end with '=='. This needs to be added if needed. // Each of the values that were base64 decoded exist out of 4 bytes. The first 3 bytes are the blue, green // and red colours respectively. The last byte is the height of the block. Data string `json:"data"` // StatusCode is the status code of the command. This is 0 on success. StatusCode int `json:"statusCode"` // StatusMessage is a message indicating if the command was successful. StatusMessage string `json:"statusMessage"` } // ParseChunkData parses a chunk data string from a ChunkData struct. The values returned are RGB values // ordered in XZ order, and a byte slice of the heights, ordered in the same order. // If not successful, an error is returned. func ParseChunkData(data string) (colourMap []color.RGBA, heightMap []byte, err error) { // 16x16 blocks on a chunk layer. values := make([]string, 0, 256) // Chunk data is a string joined by commas... fragments := strings.Split(data, ",") for _, fragment := range fragments { parts := strings.Split(fragment, "*") multiplier := 1 if len(parts) == 2 { var err error multiplier, err = strconv.Atoi(parts[1]) if err != nil { return nil, nil, err } // The multiplier given needs another added. multiplier++ } value := parts[0] if pointer, err := strconv.Atoi(value); err == nil { // The value was a number, AKA pointing to an earlier value found. value = values[pointer] } for i := 0; i < multiplier; i++ { values = append(values, value) } } // Create RGB and height slices for each block. rgba := make([]color.RGBA, 0, 256) heights := make([]byte, 0, 256) for _, str := range values { slice, err := base64.RawStdEncoding.DecodeString(str) if err != nil { return nil, nil, err } // Little endian ordered RGB. rgba = append(rgba, color.RGBA{B: slice[0], G: slice[1], R: slice[2]}) heights = append(heights, slice[3]) } return rgba, heights, nil }
protocol/command/chunk_data.go
0.767951
0.535584
chunk_data.go
starcoder
package stroke import ( "math" "sort" ) // A Segment is a cubic bezier curve (or a line segment that has been converted // into a bezier curve). type Segment struct { Start Point CP1, CP2 Point End Point } // LinearSegment returns a line segment connecting a and b, in the form of a // cubic bezier curve with collinear control points. func LinearSegment(a, b Point) Segment { diff := b.Sub(a) spacing := diff.Div(3) return Segment{ Start: a, CP1: a.Add(spacing), CP2: b.Sub(spacing), End: b, } } // QuadraticSegment converts a quadratic bezier segment to a cubic one. func QuadraticSegment(start, cp, end Point) Segment { return Segment{ Start: start, CP1: interpolate(0.6666666666666666, start, cp), CP2: interpolate(0.6666666666666666, end, cp), End: end, } } // unitVector returns p scaled to that it lies on the unit circle (one unit // away from the origin, in the same direction. If p is (0, 0), it is returned // unchanged. func unitVector(p Point) Point { if p == Pt(0, 0) { return p } length := float32(math.Hypot(float64(p.X), float64(p.Y))) return p.Div(length) } // tangents returns the tangent directions at the start and end of s, as unit // vectors (points with a magnitude of one unit). func (s Segment) tangents() (t0, t1 Point) { if s.CP1 != s.Start { t0 = unitVector(s.CP1.Sub(s.Start)) } else if s.CP2 != s.Start { t0 = unitVector(s.CP2.Sub(s.Start)) } else { t0 = unitVector(s.End.Sub(s.Start)) } if s.CP2 != s.End { t1 = unitVector(s.End.Sub(s.CP2)) } else if s.CP1 != s.End { t1 = unitVector(s.End.Sub(s.CP1)) } else { t1 = unitVector(s.End.Sub(s.Start)) } return t0, t1 } // quadraticRoots appends the values of t for which a one-dimensional quadratic // bezier function (with endpoints a and c, and control point b) returns zero. func quadraticRoots(dst []float32, a, b, c float32) []float32 { d := a - 2*b + c switch { case d != 0: m1 := float32(-math.Sqrt(float64(b*b - a*c))) m2 := -a + b v1 := -(m1 + m2) / d v2 := -(-m1 + m2) / d return append(dst, v1, v2) case b != c && d == 0: return append(dst, (2*b-c)/(2*(b-c))) default: return dst } } // linearRoot returns the value of t for which a one-dimensional linear // bezeir function (with endpoints a and b) returns zero. func linearRoot(a, b float32) (root float32, ok bool) { if a != b { return a / (a - b), true } return 0, false } // extrema returns a sorted slice of t values of the extreme points of s, // including the start and end points (t = 0 and t = 1). func (s Segment) extrema() []float32 { var storage [8]float32 result := storage[:0] a, b, c := s.CP1.X-s.Start.X, s.CP2.X-s.CP1.X, s.End.X-s.CP2.X result = quadraticRoots(result, a, b, c) if r, ok := linearRoot(b-a, c-b); ok { result = append(result, r) } a, b, c = s.CP1.Y-s.Start.Y, s.CP2.Y-s.CP1.Y, s.End.Y-s.CP2.Y result = quadraticRoots(result, a, b, c) if r, ok := linearRoot(b-a, c-b); ok { result = append(result, r) } // Make sure the endpoints are included. result = append(result, 0, 1) // Filter out results that are outside the range 0 to 1, or NaN. for i, v := range result { if v < 0 || v > 1 || v != v { result[i] = 0 } } sort.Sort(float32Slice(result)) return compact(result) } type float32Slice []float32 func (f float32Slice) Len() int { return len(f) } func (f float32Slice) Less(i, j int) bool { return f[i] < f[j] } func (f float32Slice) Swap(i, j int) { f[i], f[j] = f[j], f[i] } // interpolate returns a point between a and b, with the ratio specified by t. func interpolate(t float32, a, b Point) Point { return a.Mul(1 - t).Add(b.Mul(t)) } func compact(s []float32) []float32 { if len(s) == 0 { return s } i := 1 last := s[0] for _, v := range s[1:] { if v != last { s[i] = v i++ last = v } } return s[:i] } // Split splits s into two segments with de Casteljau's algorithm, at t. func (s Segment) Split(t float32) (Segment, Segment) { a1 := interpolate(t, s.Start, s.CP1) a2 := interpolate(t, s.CP1, s.CP2) a3 := interpolate(t, s.CP2, s.End) b1 := interpolate(t, a1, a2) b2 := interpolate(t, a2, a3) c := interpolate(t, b1, b2) return Segment{s.Start, a1, b1, c}, Segment{c, b2, a3, s.End} } // Split2 returns the section of s that lies between t1 and t2. func (s Segment) Split2(t1, t2 float32) Segment { if t1 == 0 { r, _ := s.Split(t2) return r } if t2 == 1 { _, r := s.Split(t1) return r } a, _ := s.Split(t2) _, b := a.Split(t1 / t2) return b } // splitAtExtrema returns a slice of sub-segments of s that start and end at // the extrema (points with maximum or minumum coordinates or slope). func (s Segment) splitAtExtrema() []Segment { extrema := s.extrema() result := make([]Segment, len(extrema)-1) for i := range result { result[i] = s.Split2(extrema[i], extrema[i+1]) } return result } func (s Segment) reverse() Segment { return Segment{s.End, s.CP2, s.CP1, s.Start} } func reversePath(path []Segment) []Segment { result := make([]Segment, len(path)) for i, s := range path { result[len(result)-i-1] = s.reverse() } return result }
segment.go
0.897544
0.700087
segment.go
starcoder
package boolmap // CrumbMap is a map of Crumbs (2-bits, values 0, 1, 2, 3) type CrumbMap map[uint64]byte // NewCrumbMap returns a new, initialised, CrumbMap func NewCrumbMap() CrumbMap { return make(CrumbMap) } // Get returns a crumb from the given position func (c CrumbMap) Get(p uint64) byte { d := c[p>>2] switch p & 3 { case 1: d >>= 2 case 2: d >>= 4 case 3: d >>= 6 } return d & 3 } // Set sets the crumb at the given position func (c CrumbMap) Set(p uint64, d byte) { pos := p >> 2 d &= 3 oldData, ok := c[pos] if !ok && d == 0 { return } switch p & 3 { case 0: d = oldData&252 | d case 1: d = oldData&243 | d<<2 case 2: d = oldData&207 | d<<4 case 3: d = oldData&63 | d<<6 } if d == 0 { delete(c, pos) } else { c[pos] = d } } // CrumbSlice is a slice of bytes, representing crumbs (2-bits) type CrumbSlice []byte // NewCrumbSlice returns a new, initialised, CrumbSlice func NewCrumbSlice() *CrumbSlice { return NewCrumbSliceSize(1) } // NewCrumbSliceSize returns a new Crumbslice, initialised to the given size func NewCrumbSliceSize(size uint) *CrumbSlice { sliceSize := size >> 2 if size&3 != 0 { sliceSize++ } c := make(CrumbSlice, sliceSize) return &c } // Get returns a crumb from the given position func (c CrumbSlice) Get(p uint) byte { pos := p >> 2 if pos >= uint(len(c)) { return 0 } d := c[pos] switch p & 3 { case 1: d >>= 2 case 2: d >>= 4 case 3: d >>= 6 } return d & 3 } // Set sets the crumb at the given position func (c *CrumbSlice) Set(p uint, d byte) { pos := p >> 2 if pos >= uint(len(*c)) { if d == 0 { return } if pos < uint(cap(*c)) { (*c) = (*c)[:cap(*c)] } else { var newData CrumbSlice if pos < 512 { newData = make(CrumbSlice, pos<<1) } else { newData = make(CrumbSlice, pos+(pos>>2)) } copy(newData, *c) *c = newData } } d &= 3 oldData := (*c)[pos] switch p & 3 { case 0: d = oldData&252 | d case 1: d = oldData&243 | d<<2 case 2: d = oldData&207 | d<<4 case 3: d = oldData&63 | d<<6 } (*c)[pos] = d }
crumbmap.go
0.684791
0.53965
crumbmap.go
starcoder
package tables import ( "math" "github.com/notnil/chess" ) // EvaluateBoard implements the Simplified Evaluation Function by <NAME> // https://www.chessprogramming.org/Simplified_Evaluation_Function func EvaluateBoard(game *chess.Game) int { if game.Position().Status() == chess.Checkmate { return math.MaxInt32 } zeroQueens := true for _, piece := range game.Position().Board().SquareMap() { if piece.Type() == chess.Queen { zeroQueens = false } } sum := 0 for square, piece := range game.Position().Board().SquareMap() { // We determine the endgame as neither side having queens // In the future, we might use: // > Every side which has a queen has additionally no other pieces or one minorpiece maximum sum += evaluatePiece(int(square), piece, zeroQueens) } return sum } func evaluatePiece(square int, piece chess.Piece, endgame bool) int { var value int // Piece weights P := 100 N := 320 B := 330 R := 500 Q := 900 K := 20000 // Apply square bonus switch piece { case chess.WhiteKing: if endgame { value = kingEndGame[square] + K } value = kingMidGame[square] + K case chess.WhiteQueen: value = queen[square] + Q case chess.WhiteRook: value = rook[square] + R case chess.WhiteBishop: value = bishop[square] + B case chess.WhiteKnight: value = knight[square] + N case chess.WhitePawn: value = pawn[square] + P case chess.BlackKing: if endgame { value = kingEndGame[len(kingEndGame)-square-1] + K } value = kingMidGame[len(kingMidGame)-square-1] + K case chess.BlackQueen: value = queen[len(queen)-square-1] + Q case chess.BlackRook: value = rook[len(rook)-square-1] + R case chess.BlackBishop: value = bishop[len(bishop)-square-1] + B case chess.BlackKnight: value = knight[len(knight)-square-1] + N case chess.BlackPawn: value = pawn[len(pawn)-square-1] + P } if piece.Color() == 1 { return value } return -value } // Tables lifted from: // https://www.chessprogramming.org/Simplified_Evaluation_Function // They are from White's POV and should be flipped for Black var pawn = [...]int{0, 0, 0, 0, 0, 0, 0, 0, 50, 50, 50, 50, 50, 50, 50, 50, 10, 10, 20, 30, 30, 20, 10, 10, 5, 5, 10, 25, 25, 10, 5, 5, 0, 0, 0, 20, 20, 0, 0, 0, 5, -5, -10, 0, 0, -10, -5, 5, 5, 10, 10, -20, -20, 10, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0, } var knight = [...]int{-50, -40, -30, -30, -30, -30, -40, -50, -40, -20, 0, 0, 0, 0, -20, -40, -30, 0, 10, 15, 15, 10, 0, -30, -30, 5, 15, 20, 20, 15, 5, -30, -30, 0, 15, 20, 20, 15, 0, -30, -30, 5, 10, 15, 15, 10, 5, -30, -40, -20, 0, 5, 5, 0, -20, -40, -50, -40, -30, -30, -30, -30, -40, -50, } var bishop = [...]int{-20, -10, -10, -10, -10, -10, -10, -20, -10, 0, 0, 0, 0, 0, 0, -10, -10, 0, 5, 10, 10, 5, 0, -10, -10, 5, 5, 10, 10, 5, 5, -10, -10, 0, 10, 10, 10, 10, 0, -10, -10, 10, 10, 10, 10, 10, 10, -10, -10, 5, 0, 0, 0, 0, 5, -10, -20, -10, -10, -10, -10, -10, -10, -20, } var rook = [...]int{0, 0, 0, 0, 0, 0, 0, 0, 5, 10, 10, 10, 10, 10, 10, 5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, -5, 0, 0, 0, 0, 0, 0, -5, 0, 0, 0, 5, 5, 0, 0, 0, } var queen = [...]int{-20, -10, -10, -5, -5, -10, -10, -20, -10, 0, 0, 0, 0, 0, 0, -10, -10, 0, 5, 5, 5, 5, 0, -10, -5, 0, 5, 5, 5, 5, 0, -5, 0, 0, 5, 5, 5, 5, 0, -5, -10, 5, 5, 5, 5, 5, 0, -10, -10, 0, 5, 0, 0, 0, 0, -10, -20, -10, -10, -5, -5, -10, -10, -20, } var kingMidGame = [...]int{-30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -30, -40, -40, -50, -50, -40, -40, -30, -20, -30, -30, -40, -40, -30, -30, -20, -10, -20, -20, -20, -20, -20, -20, -10, 20, 20, 0, 0, 0, 0, 20, 20, 20, 30, 10, 0, 0, 10, 30, 20, } var kingEndGame = [...]int{-50, -40, -30, -20, -20, -30, -40, -50, -30, -20, -10, 0, 0, -10, -20, -30, -30, -10, 20, 30, 30, 20, -10, -30, -30, -10, 30, 40, 40, 30, -10, -30, -30, -10, 30, 40, 40, 30, -10, -30, -30, -10, 20, 30, 30, 20, -10, -30, -30, -30, 0, 0, 0, 0, -30, -30, -50, -30, -30, -30, -30, -30, -30, -50, }
old_implementation/tables/evaluate.go
0.689201
0.510069
evaluate.go
starcoder
package gokalman import ( "fmt" "math/rand" "time" "github.com/gonum/matrix/mat64" "github.com/gonum/stat/distmv" ) // Noise allows to handle the noise for a KF. type Noise interface { Process(k int) *mat64.Vector // Returns the process noise w at step k Measurement(k int) *mat64.Vector // Returns the measurement noise w at step k ProcessMatrix() mat64.Symmetric // Returns the process noise matrix Q MeasurementMatrix() mat64.Symmetric // Returns the measurement noise matrix R Reset() // Reinitializes the noise String() string // Stringer interface implementation } // Noiseless is noiseless and implements the Noise interface. type Noiseless struct { Q, R mat64.Symmetric processSize, measurementSize int } // NewNoiseless creates new AWGN noise from the provided Q and R. func NewNoiseless(Q, R mat64.Symmetric) *Noiseless { if Q == nil || R == nil { panic("Q and R must be specified") } rQ, _ := Q.Dims() rR, _ := R.Dims() return &Noiseless{Q, R, rQ, rR} } // Process returns a vector of the correct size. func (n Noiseless) Process(k int) *mat64.Vector { return mat64.NewVector(n.processSize, nil) } // Measurement returns a vector of the correct size. func (n Noiseless) Measurement(k int) *mat64.Vector { return mat64.NewVector(n.measurementSize, nil) } // ProcessMatrix implements the Noise interface. func (n Noiseless) ProcessMatrix() mat64.Symmetric { return n.Q } // MeasurementMatrix implements the Noise interface. func (n Noiseless) MeasurementMatrix() mat64.Symmetric { return n.R } // Reset does nothing for a Noiseless signal. func (n Noiseless) Reset() {} // String implements the Stringer interface. func (n Noiseless) String() string { return fmt.Sprintf("Noiseless{\nQ=%v\nR=%v}\n", mat64.Formatted(n.Q, mat64.Prefix(" ")), mat64.Formatted(n.R, mat64.Prefix(" "))) } // BatchNoise implements the Noise interface. type BatchNoise struct { process []*mat64.Vector // Array of process noise measurement []*mat64.Vector // Array of process noise } // Process implements the Noise interface. func (n BatchNoise) Process(k int) *mat64.Vector { if k >= len(n.process) { panic(fmt.Errorf("no process noise defined at step k=%d", k)) } return n.process[k] } // Measurement implements the Noise interface. func (n BatchNoise) Measurement(k int) *mat64.Vector { if k >= len(n.measurement) { panic(fmt.Errorf("no measurement noise defined at step k=%d", k)) } return n.measurement[k] } // ProcessMatrix implements the Noise interface. func (n BatchNoise) ProcessMatrix() mat64.Symmetric { rows, _ := n.process[0].Dims() return mat64.NewSymDense(rows, nil) } // MeasurementMatrix implements the Noise interface. func (n BatchNoise) MeasurementMatrix() mat64.Symmetric { rows, _ := n.measurement[0].Dims() return mat64.NewSymDense(rows, nil) } // Reset does nothing for a BatchNoise signal. func (n BatchNoise) Reset() {} // String implements the Stringer interface. func (n BatchNoise) String() string { return "BatchNoise" } // AWGN implements the Noise interface and generates an Additive white Gaussian noise. type AWGN struct { Q, R mat64.Symmetric process *distmv.Normal measurement *distmv.Normal } // NewAWGN creates new AWGN noise from the provided Q and R. func NewAWGN(Q, R mat64.Symmetric) *AWGN { n := &AWGN{Q, R, nil, nil} n.Reset() return n } // ProcessMatrix implements the Noise interface. func (n *AWGN) ProcessMatrix() mat64.Symmetric { return n.Q } // MeasurementMatrix implements the Noise interface. func (n *AWGN) MeasurementMatrix() mat64.Symmetric { return n.R } // Process implements the Noise interface. func (n *AWGN) Process(k int) *mat64.Vector { r := n.process.Rand(nil) return mat64.NewVector(len(r), r) } // Measurement implements the Noise interface. func (n *AWGN) Measurement(k int) *mat64.Vector { r := n.measurement.Rand(nil) return mat64.NewVector(len(r), r) } // Reset does nothing for a Noiseless signal. func (n *AWGN) Reset() { seed := rand.New(rand.NewSource(time.Now().UnixNano())) sizeQ, _ := n.Q.Dims() process, ok := distmv.NewNormal(make([]float64, sizeQ), n.Q, seed) if !ok { panic("process noise invalid") } sizeR, _ := n.R.Dims() meas, ok := distmv.NewNormal(make([]float64, sizeR), n.R, seed) if !ok { panic("measurement noise invalid") } n.process = process n.measurement = meas } // String implements the Stringer interface. func (n AWGN) String() string { return fmt.Sprintf("AWGN{\nQ=%v\nR=%v}\n", mat64.Formatted(n.Q, mat64.Prefix(" ")), mat64.Formatted(n.R, mat64.Prefix(" "))) }
noise.go
0.810291
0.61973
noise.go
starcoder
package countries import ( "math" "strconv" "github.com/ltns35/go-vat/countries/utils" ) type unitedKingdom struct { Country } var UnitedKingdom = unitedKingdom{ Country: Country{ Name: "United Kingdom", Codes: []string{ "GB", "GBR", "826", }, Rules: CountryRules{ Multipliers: map[string][]int{ "common": { 8, 7, 6, 5, 4, 3, 2, }, }, Regex: []string{ "^(GB)?(\\d{9})$", "^(GB)?(\\d{12})$", "^(GB)?(GD\\d{3})$", "^(GB)?(HA\\d{3})$", }, }, }, } func (u unitedKingdom) Calc(vat string) bool { // Government departments beginStr := vat[:2] if beginStr == "GD" { return isGovernmentDepartment(vat) } // Health authorities if beginStr == "HA" { return isHealthAuthorities(vat) } // Standard and commercial numbers return isStandardOrCommercialNumber(vat, u.Rules.Multipliers["common"]) } func (u unitedKingdom) GetCountry() Country { return u.Country } func isGovernmentDepartment(vat string) bool { const expect = 500 num := utils.IntAt(vat, 2) return num < expect } func isHealthAuthorities(vat string) bool { const expect = 499 num := utils.IntAt(vat, 2) return num > expect } func isStandardOrCommercialNumber(vat string, multipliers []int) bool { var total float64 = 0 // 0 VAT numbers disallowed! zeroVAT, _ := strconv.Atoi(vat) if zeroVAT == 0 { return false } // Check range is OK for modulus 97 calculation noStr := vat[:7] no, _ := strconv.Atoi(noStr) // Extract the next digit and multiply by the counter. for i := 0; i < 7; i++ { num := utils.IntAt(vat, i) total += float64(num * multipliers[i]) } // Old numbers use a simple 97 modulus, but new numbers use an adaptation of that (less 55). Our // VAT number could use either system, so we check it against both. // Establish check digits by subtracting 97 from total until negative. checkDigit := total for checkDigit > 0 { checkDigit = checkDigit - 97 } // Get the absolute value and compare it with the last two characters of the VAT number. If the // same, then it is a valid traditional check digit. However, even then the number must fit within // certain specified ranges. checkDigit = math.Abs(checkDigit) lastDigitsStr := vat[7:9] lastDigits, _ := strconv.Atoi(lastDigitsStr) if checkDigit == float64(lastDigits) && no < 9990001 && (no < 100000 || no > 999999) && (no < 9490001 || no > 9700000) { return true } // Now try the new method by subtracting 55 from the check digit if we can - else add 42 if checkDigit >= 55 { checkDigit = checkDigit - 55 } else { checkDigit = checkDigit + 42 } return checkDigit == float64(lastDigits) && no > 1000000 }
countries/united_kingdom.go
0.64791
0.444022
united_kingdom.go
starcoder
package geotiff // DataSlice contains a 'slice' of data type DataSlice struct { dataView DataView offset uint littleEndian bool bigTiff bool } // NewDataSlice create a new instance of dataSlice func NewDataSlice(dataView DataView, offset uint, littleEndian bool, bigTiff bool) *DataSlice { return &DataSlice{dataView, offset, littleEndian, bigTiff} } // Offset returns the offset value func (d *DataSlice) Offset() uint { return d.offset } // SliceTop returns the top offset of the DataSlice func (d *DataSlice) SliceTop() uint { return d.offset + uint(len(d.dataView)) } // LittleEndian returns the littleEndian value func (d *DataSlice) LittleEndian() bool { return d.littleEndian } // BigTiff returns the bigTiff value func (d *DataSlice) BigTiff() bool { return d.bigTiff } // Buffer returns the encapsulated DataView func (d *DataSlice) Buffer() DataView { return d.dataView } // Covers returns true id the slice covers the given interval func (d *DataSlice) Covers(offset uint, length uint) bool { return d.offset <= offset && d.SliceTop() >= offset+length } // ReadUint8 read a uint8 at offset func (d *DataSlice) ReadUint8(offset uint) uint8 { return d.dataView.Uint8(offset-d.offset, d.littleEndian) } // ReadInt8 read a int8 at offset func (d *DataSlice) ReadInt8(offset uint) int8 { return d.dataView.Int8(offset-d.offset, d.littleEndian) } // ReadUint16 read a uint16 at offset func (d *DataSlice) ReadUint16(offset uint) uint16 { return d.dataView.Uint16(offset-d.offset, d.littleEndian) } // ReadInt16 read a int16 at offset func (d *DataSlice) ReadInt16(offset uint) int16 { return d.dataView.Int16(offset-d.offset, d.littleEndian) } // ReadUint32 read a uint32 at offset func (d *DataSlice) ReadUint32(offset uint) uint32 { return d.dataView.Uint32(offset-d.offset, d.littleEndian) } // ReadInt32 read a int32 at offset func (d *DataSlice) ReadInt32(offset uint) int32 { return d.dataView.Int32(offset-d.offset, d.littleEndian) } // ReadUint64 read a uint64 at offset func (d *DataSlice) ReadUint64(offset uint) uint64 { return d.dataView.Uint64(offset-d.offset, d.littleEndian) } // ReadInt64 read a int64 at offset func (d *DataSlice) ReadInt64(offset uint) int64 { return d.dataView.Int64(offset-d.offset, d.littleEndian) } // ReadFloat32 read a float32 at offset func (d *DataSlice) ReadFloat32(offset uint) float32 { return d.dataView.Float32(offset, d.littleEndian) } // ReadFloat64 read a float64 at offset func (d *DataSlice) ReadFloat64(offset uint) float64 { return d.dataView.Float64(offset, d.littleEndian) } // ReadOffset returns uint64 in case of bigTiff otherwise uint32 func (d *DataSlice) ReadOffset(offset uint) uint { if d.bigTiff { return uint(d.ReadUint64(offset)) } return uint(d.ReadUint32(offset)) }
pkg/geotiff/dataslice.go
0.893315
0.83025
dataslice.go
starcoder
package mathg import "math" type Vec3 struct { X float64 Y float64 Z float64 } func (v *Vec2) ToVec3() *Vec3 { return &Vec3{v.X, v.Y, 0} } func (v *Vec3) IsZero() bool { return math.Abs(v.X) < epsilon && math.Abs(v.Y) < epsilon && math.Abs(v.Z) < epsilon } func (v *Vec3) IsEqual(v1 *Vec3) bool { return math.Abs(v.X-v1.X) < epsilon && math.Abs(v.Y-v1.Y) < epsilon && math.Abs(v.Z-v1.Z) < epsilon } func (v *Vec3) Zero() { v.X = 0. v.Y = 0. v.Z = 0. } func (v *Vec3) One() { v.X = 1. v.Y = 1. v.Z = 1. } func (v *Vec3) Add(v1 *Vec3) *Vec3 { return &Vec3{v.X + v1.X, v.Y + v1.Y, v.Z + v1.Z} } func (v *Vec3) AddScalar(scalar float64) *Vec3 { return &Vec3{v.X + scalar, v.Y + scalar, v.Z + scalar} } func (v *Vec3) Subtract(v1 *Vec3) *Vec3 { return &Vec3{v.X - v1.X, v.Y - v1.Y, v.Z - v1.Z} } func (v *Vec3) SubtractScalar(scalar float64) *Vec3 { return &Vec3{v.X - scalar, v.Y - scalar, v.Z - scalar} } func (v *Vec3) Multiply(v1 *Vec3) *Vec3 { return &Vec3{v.X * v1.X, v.Y * v1.Y, v.Z * v1.Z} } func (v *Vec3) MultiplyScalar(scalar float64) *Vec3 { return &Vec3{v.X * scalar, v.Y * scalar, v.Z * scalar} } func (v *Vec3) MultiplyMat3(m *Mat3) *Vec3 { return &Vec3{m.M11*v.X + m.M12*v.Y + m.M13*v.Z, m.M21*v.X + m.M22*v.Y + m.M23*v.Z, m.M31*v.X + m.M32*v.Y + m.M33*v.Z} } func (v *Vec3) Divide(v1 *Vec3) *Vec3 { return &Vec3{v.X / v1.X, v.Y / v1.Y, v.Z / v1.Z} } func (v *Vec3) DivideScalar(scalar float64) *Vec3 { return &Vec3{v.X / scalar, v.Y / scalar, v.Z / scalar} } func (v *Vec3) Snap(v1 *Vec3) *Vec3 { return &Vec3{math.Floor(v.X/v1.X) * v1.X, math.Floor(v.Y/v1.Y) * v1.Y, math.Floor(v.Z/v1.Z) * v1.Z} } func (v *Vec3) Snapf(f float64) *Vec3 { return &Vec3{math.Floor(v.X/f) * f, math.Floor(v.Y/f) * f, math.Floor(v.Z/f) * f} } func (v *Vec3) Negative() *Vec3 { return &Vec3{-1 * v.X, -1 * v.Y, -1 * v.Z} } func (v *Vec3) Abs() *Vec3 { return &Vec3{math.Abs(v.X), math.Abs(v.Y), math.Abs(v.Z)} } func (v *Vec3) Floor() *Vec3 { return &Vec3{math.Floor(v.X), math.Floor(v.Y), math.Floor(v.Z)} } func (v *Vec3) Ceil() *Vec3 { return &Vec3{math.Ceil(v.X), math.Ceil(v.Y), math.Ceil(v.Z)} } func (v *Vec3) Round() *Vec3 { return &Vec3{math.Round(v.X), math.Round(v.Y), math.Round(v.Z)} } func (v *Vec3) Max(v1 *Vec3) *Vec3 { return &Vec3{math.Max(v.X, v1.X), math.Max(v.Y, v1.Y), math.Max(v.Z, v1.Z)} } func (v *Vec3) Min(v1 *Vec3) *Vec3 { return &Vec3{math.Min(v.X, v1.X), math.Min(v.Y, v1.Y), math.Min(v.Z, v1.Z)} } func (v *Vec3) Clamp(min *Vec3, max *Vec3) *Vec3 { return &Vec3{Clamp(v.X, min.X, max.X), Clamp(v.Y, min.Y, max.Y), Clamp(v.Z, min.Z, max.Z)} } func (v *Vec3) Cross(v1 *Vec3) *Vec3 { return &Vec3{v.Y*v1.Z - v.Z*v1.Y, v.Z*v1.X - v.X*v1.Z, v.X*v1.Y - v.Y*v1.X} } func (v *Vec3) Dot(v1 *Vec3) float64 { return v.X*v1.X + v.Y*v1.Y + v.X*v1.Z } func (v *Vec3) Magnitude() float64 { return math.Sqrt(math.Pow(v.X, 2) + math.Pow(v.Y, 2) + math.Pow(v.Z, 2)) } func (v *Vec3) LengthSquared() float64 { return math.Pow(v.X, 2) + math.Pow(v.Y, 2) + math.Pow(v.Z, 2) } func (v *Vec3) Normalize() *Vec3 { m := v.Magnitude() return &Vec3{v.X / m, v.Y / m, v.Z / m} } func (v *Vec3) Project(v1 *Vec3) *Vec3 { d := v1.Dot(v1) s := v.Dot(v1) / d return &Vec3{v.X * s, v.Y * s, v.Z * s} } func (v *Vec3) Slide(normal *Vec3) *Vec3 { d := v.Dot(normal) return &Vec3{v.X - normal.X*d, v.Y - normal.Y*d, v.Z - normal.Z*d} } func (v *Vec3) Reflect(normal *Vec3) *Vec3 { d := 2. * v.Dot(normal) return &Vec3{normal.X*d - v.X, normal.Y*d - v.Y, normal.Z*d - v.Z} } func (v *Vec3) Rotate(ra *Vec3, radians float64) *Vec3 { cs := math.Cos(radians) sn := math.Sin(radians) x, y, z := v.X, v.Y, v.Z rn := ra.Normalize() rx, ry, rz := rn.X, rn.Y, rn.Z rfx := x*(cs+rx*rx*(1-cs)) + y*(rx*ry*(1-cs)-rz*sn) + z*(rx*rz*(1-cs)+ry*sn) rfy := x*(ry*rx*(1-cs)+rz*sn) + y*(cs+ry*ry*(1-cs)) + z*(ry*rz*(1-cs)-rx*sn) rfz := x*(rz*rx*(1-cs)-ry*sn) + y*(rz*ry*(1-cs)+rx*sn) + z*(cs+rz*rz*(1-cs)) return &Vec3{rfx, rfy, rfz} } func (v *Vec3) Lerp(v1 *Vec3, percent float64) *Vec3 { return &Vec3{v.X + (v1.X-v.X)*percent, v.Y + (v1.Y-v.Y)*percent, v.Z + (v1.Z-v.Z)*percent} } func (v *Vec3) Bezier3(v1 *Vec3, v2 *Vec3, percent float64) *Vec3 { t0 := v.Lerp(v1, percent) t1 := v1.Lerp(v2, percent) return t0.Lerp(t1, percent) } func (v *Vec3) Bezier4(v1 *Vec3, v2 *Vec3, v3 *Vec3, percent float64) *Vec3 { t0 := v.Lerp(v1, percent) t1 := v1.Lerp(v2, percent) t2 := v2.Lerp(v3, percent) t3 := t0.Lerp(t1, percent) t4 := t1.Lerp(t2, percent) return t3.Lerp(t4, percent) } func (v *Vec3) Distance(v1 *Vec3) float64 { return math.Sqrt(math.Pow(v.X-v1.X, 2) + math.Pow(v.Y-v1.Y, 2) + math.Pow(v.Z-v1.Z, 2)) } func (v *Vec3) LinearIndependent(v1 *Vec3, v2 *Vec3) bool { return (v.X*v1.Y*v2.Z + v.Y*v1.Z*v2.X + v.Z*v1.X*v2.Y - v.Z*v1.Y*v2.X - v.Y*v1.Z*v2.X - v.X*v1.Y*v2.Z) != 0 }
vec3.go
0.906614
0.441613
vec3.go
starcoder
package crawl import ( "math/rand" "sync" "time" ) // NodePool implements an abstraction over a pool of nodes for which to crawl. // It also contains a collection of nodes for which to reseed the pool when it's // empty. Once the reseed list has reached capacity, a random node is removed // when another is added. Note, it is not thread-safe. type NodePool struct { rw sync.RWMutex nodes map[string]struct{} reseedNodes []string rng *rand.Rand } func NewNodePool(reseedCap uint) *NodePool { return &NodePool{ nodes: make(map[string]struct{}), reseedNodes: make([]string, 0, reseedCap), rng: rand.New(rand.NewSource(time.Now().Unix())), } } // Size returns the size of the pool. func (p *NodePool) Size() int { p.rw.RLock() defer p.rw.RUnlock() return len(p.nodes) } // Seed seeds the node pool with a given set of node IPs. func (p *NodePool) Seed(seeds []string) { for _, s := range seeds { p.AddNode(s) } } // RandomNode returns a random node, based on Golang's map semantics, from the pool. func (p *NodePool) RandomNode() (string, bool) { p.rw.RLock() defer p.rw.RUnlock() for nodeRPCAddr := range p.nodes { return nodeRPCAddr, true } return "", false } // AddNode adds a node RPC address to the node pool. In addition, it adds the // node to the reseed list. If the reseed list is full, it replaces a random node. func (p *NodePool) AddNode(nodeRPCAddr string) { p.rw.Lock() defer p.rw.Unlock() p.nodes[nodeRPCAddr] = struct{}{} if len(p.reseedNodes) < cap(p.reseedNodes) { p.reseedNodes = append(p.reseedNodes, nodeRPCAddr) } else { // replace random node with the new node i := p.rng.Intn(len(p.reseedNodes)) p.reseedNodes[i] = nodeRPCAddr } } // HasNode returns a boolean based on if a node RPC address exists in the node pool. func (p *NodePool) HasNode(nodeRPCAddr string) bool { p.rw.RLock() defer p.rw.RUnlock() _, ok := p.nodes[nodeRPCAddr] return ok } // DeleteNode removes a node from the node pool if it exists. func (p *NodePool) DeleteNode(nodeRPCAddr string) { p.rw.Lock() defer p.rw.Unlock() delete(p.nodes, nodeRPCAddr) } // Reseed seeds the node pool with all the nodes found in the internal reseed // list. func (p *NodePool) Reseed() { p.rw.Lock() defer p.rw.Unlock() for _, addr := range p.reseedNodes { p.nodes[addr] = struct{}{} } }
crawl/pool.go
0.638497
0.531392
pool.go
starcoder
package muxgo import ( "encoding/json" ) // RealTimeHistogramTimeseriesBucketValues struct for RealTimeHistogramTimeseriesBucketValues type RealTimeHistogramTimeseriesBucketValues struct { Percentage *float64 `json:"percentage,omitempty"` Count *int64 `json:"count,omitempty"` } // NewRealTimeHistogramTimeseriesBucketValues instantiates a new RealTimeHistogramTimeseriesBucketValues 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 NewRealTimeHistogramTimeseriesBucketValues() *RealTimeHistogramTimeseriesBucketValues { this := RealTimeHistogramTimeseriesBucketValues{} return &this } // NewRealTimeHistogramTimeseriesBucketValuesWithDefaults instantiates a new RealTimeHistogramTimeseriesBucketValues 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 NewRealTimeHistogramTimeseriesBucketValuesWithDefaults() *RealTimeHistogramTimeseriesBucketValues { this := RealTimeHistogramTimeseriesBucketValues{} return &this } // GetPercentage returns the Percentage field value if set, zero value otherwise. func (o *RealTimeHistogramTimeseriesBucketValues) GetPercentage() float64 { if o == nil || o.Percentage == nil { var ret float64 return ret } return *o.Percentage } // GetPercentageOk returns a tuple with the Percentage field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RealTimeHistogramTimeseriesBucketValues) GetPercentageOk() (*float64, bool) { if o == nil || o.Percentage == nil { return nil, false } return o.Percentage, true } // HasPercentage returns a boolean if a field has been set. func (o *RealTimeHistogramTimeseriesBucketValues) HasPercentage() bool { if o != nil && o.Percentage != nil { return true } return false } // SetPercentage gets a reference to the given float64 and assigns it to the Percentage field. func (o *RealTimeHistogramTimeseriesBucketValues) SetPercentage(v float64) { o.Percentage = &v } // GetCount returns the Count field value if set, zero value otherwise. func (o *RealTimeHistogramTimeseriesBucketValues) GetCount() int64 { if o == nil || o.Count == nil { var ret int64 return ret } return *o.Count } // GetCountOk returns a tuple with the Count field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RealTimeHistogramTimeseriesBucketValues) GetCountOk() (*int64, bool) { if o == nil || o.Count == nil { return nil, false } return o.Count, true } // HasCount returns a boolean if a field has been set. func (o *RealTimeHistogramTimeseriesBucketValues) HasCount() bool { if o != nil && o.Count != nil { return true } return false } // SetCount gets a reference to the given int64 and assigns it to the Count field. func (o *RealTimeHistogramTimeseriesBucketValues) SetCount(v int64) { o.Count = &v } func (o RealTimeHistogramTimeseriesBucketValues) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Percentage != nil { toSerialize["percentage"] = o.Percentage } if o.Count != nil { toSerialize["count"] = o.Count } return json.Marshal(toSerialize) } type NullableRealTimeHistogramTimeseriesBucketValues struct { value *RealTimeHistogramTimeseriesBucketValues isSet bool } func (v NullableRealTimeHistogramTimeseriesBucketValues) Get() *RealTimeHistogramTimeseriesBucketValues { return v.value } func (v *NullableRealTimeHistogramTimeseriesBucketValues) Set(val *RealTimeHistogramTimeseriesBucketValues) { v.value = val v.isSet = true } func (v NullableRealTimeHistogramTimeseriesBucketValues) IsSet() bool { return v.isSet } func (v *NullableRealTimeHistogramTimeseriesBucketValues) Unset() { v.value = nil v.isSet = false } func NewNullableRealTimeHistogramTimeseriesBucketValues(val *RealTimeHistogramTimeseriesBucketValues) *NullableRealTimeHistogramTimeseriesBucketValues { return &NullableRealTimeHistogramTimeseriesBucketValues{value: val, isSet: true} } func (v NullableRealTimeHistogramTimeseriesBucketValues) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableRealTimeHistogramTimeseriesBucketValues) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_real_time_histogram_timeseries_bucket_values.go
0.858526
0.415492
model_real_time_histogram_timeseries_bucket_values.go
starcoder
Package goroutinemap implements a data structure for managing go routines by name. It prevents the creation of new go routines if an existing go routine with the same name exists. */ package goroutinemap import ( "fmt" "sync" "k8s.io/kubernetes/pkg/util/runtime" ) // GoRoutineMap defines the supported set of operations. type GoRoutineMap interface { // Run adds operationName to the list of running operations and spawns a new // go routine to execute the operation. If an operation with the same name // already exists, an error is returned. Once the operation is complete, the // go routine is terminated and the operationName is removed from the list // of executing operations allowing a new operation to be started with the // same name without error. Run(operationName string, operation func() error) error // Wait blocks until all operations are completed. This is typically // necessary during tests - the test should wait until all operations finish // and evaluate results after that. Wait() } // NewGoRoutineMap returns a new instance of GoRoutineMap. func NewGoRoutineMap() GoRoutineMap { return &goRoutineMap{ operations: make(map[string]bool), } } type goRoutineMap struct { operations map[string]bool sync.Mutex wg sync.WaitGroup } func (grm *goRoutineMap) Run(operationName string, operation func() error) error { grm.Lock() defer grm.Unlock() if grm.operations[operationName] { // Operation with name exists return newAlreadyExistsError(operationName) } grm.operations[operationName] = true grm.wg.Add(1) go func() { defer grm.operationComplete(operationName) defer runtime.HandleCrash() operation() }() return nil } func (grm *goRoutineMap) operationComplete(operationName string) { defer grm.wg.Done() grm.Lock() defer grm.Unlock() delete(grm.operations, operationName) } func (grm *goRoutineMap) Wait() { grm.wg.Wait() } // alreadyExistsError is specific error returned when NewGoRoutine() // detects that operation with given name is already running. type alreadyExistsError struct { operationName string } var _ error = alreadyExistsError{} func (err alreadyExistsError) Error() string { return fmt.Sprintf("Failed to create operation with name %q. An operation with that name already exists", err.operationName) } func newAlreadyExistsError(operationName string) error { return alreadyExistsError{operationName} } // IsAlreadyExists returns true if an error returned from NewGoRoutine indicates // that operation with the same name already exists. func IsAlreadyExists(err error) bool { switch err.(type) { case alreadyExistsError: return true default: return false } }
vendor/k8s.io/kubernetes/pkg/util/goroutinemap/goroutinemap.go
0.639736
0.432183
goroutinemap.go
starcoder
package gpsutils import "fmt" // Coordinates basic structure to work with this package type Coordinates struct { N coordinate E coordinate CoordinateN string // N coordinates in the specified format CoordinateE string // E coordinates in the specified format Format string // format coordinates formatType uint8 // internal identifier coordinates type } type coordinate struct { DD float64 // degree MM float64 // min SS float64 // sec } // ParseCoordinates the function parses the incoming string and returns data structures Coordinates func ParseCoordinates(coordinateN, coordinateE, format string) (*Coordinates, error) { // FIXME ошибка парсинга в дробной части c, err := ValidateCoordinatesData(coordinateN, coordinateE, format) if err != nil { return nil, fmt.Errorf("input data %s", err) } c.Format = format c.buildCoordinates() return c, err } // buildCoordinates the method collects coordinates in the structure parametres CoordinateN and CoordinateE func (obj *Coordinates) buildCoordinates() { switch obj.formatType { case 1: { //"DD.DDDDDD°" obj.CoordinateN = fmt.Sprintf("%f°", obj.N.DD) obj.CoordinateE = fmt.Sprintf("%f°", obj.E.DD) //TODO протестировать, рассмотреть возможность перехода на math.Mod obj.N.MM = 0 obj.E.MM = 0 obj.N.SS = 0 obj.E.SS = 0 } case 2: { //"DD°MM.MMMM'" obj.CoordinateN = fmt.Sprintf("%.0f°%.4f'", obj.N.DD, obj.N.MM) obj.CoordinateE = fmt.Sprintf("%.0f°%.4f'", obj.E.DD, obj.E.MM) //TODO протестировать, рассмотреть возможность перехода на math.Mod obj.N.DD = round(obj.N.DD, 0) obj.E.DD = round(obj.N.DD, 0) obj.N.SS = 0 obj.E.SS = 0 } case 3: { //"DD°MM'SS.SSS\"" obj.CoordinateN = fmt.Sprintf("%.0f°%.0f'%.3f\"", obj.N.DD, obj.N.MM, obj.N.SS) obj.CoordinateE = fmt.Sprintf("%.0f°%.0f'%.3f\"", obj.E.DD, obj.E.MM, obj.E.SS) //TODO протестировать, рассмотреть возможность перехода на math.Mod obj.N.DD = round(obj.N.DD, 0) obj.E.DD = round(obj.N.DD, 0) obj.N.MM = round(obj.N.MM, 0) obj.E.MM = round(obj.N.MM, 0) } } }
coordinates.go
0.542379
0.453564
coordinates.go
starcoder
package bellmanford import ( "math" ) // Graph represents a graph consisting of edges and vertices type Graph struct { edges []*Edge vertices []uint } // Edge represents a weighted line between two nodes type Edge struct { From, To uint Weight float64 } // NewEdge returns a pointer to a new Edge func NewEdge(from, to uint, weight float64) *Edge { return &Edge{From: from, To: to, Weight: weight} } // NewGraph returns a graph consisting of given edges and vertices (vertices must count from 0 upwards) func NewGraph(edges []*Edge, vertices []uint) *Graph { return &Graph{edges: edges, vertices: vertices} } // FindArbitrageLoop returns either an arbitrage loop or a nil map func (g *Graph) FindArbitrageLoop(source uint) []uint { predecessors, distances := g.BellmanFord(source) return g.FindNegativeWeightCycle(predecessors, distances, source) } // BellmanFord determines the shortest path and returns the predecessors and distances func (g *Graph) BellmanFord(source uint) ([]uint, []float64) { size := len(g.vertices) distances := make([]float64, size) predecessors := make([]uint, size) for _, v := range g.vertices { distances[v] = math.MaxFloat64 } distances[source] = 0 for i, changes := 0, 0; i < size-1; i, changes = i+1, 0 { for _, edge := range g.edges { if newDist := distances[edge.From] + edge.Weight; newDist < distances[edge.To] { distances[edge.To] = newDist predecessors[edge.To] = edge.From changes++ } } if changes == 0 { break } } return predecessors, distances } // FindNegativeWeightCycle finds a negative weight cycle from predecessors and a source func (g *Graph) FindNegativeWeightCycle(predecessors []uint, distances []float64, source uint) []uint { for _, edge := range g.edges { if distances[edge.From]+edge.Weight < distances[edge.To] { return arbitrageLoop(predecessors, source) } } return nil } func arbitrageLoop(predecessors []uint, source uint) []uint { size := len(predecessors) loop := make([]uint, size) loop[0] = source exists := make([]bool, size) exists[source] = true indices := make([]uint, size) var index, next uint for index, next = 1, source; ; index++ { next = predecessors[next] loop[index] = next if exists[next] { return loop[indices[next] : index+1] } indices[next] = index exists[next] = true } }
internal/algo/bellmanford/bellmanford.go
0.847227
0.617772
bellmanford.go
starcoder
package storetestcases import ( "context" "testing" "time" "github.com/stratumn/go-chainscript" "github.com/stratumn/go-chainscript/chainscripttest" "github.com/stratumn/go-core/store" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // TestStoreEvents tests store channel event notifications. func (f Factory) TestStoreEvents(t *testing.T) { a := f.initAdapter(t) defer f.freeAdapter(a) c := make(chan *store.Event, 10) a.AddStoreEventChannel(c) link := chainscripttest.RandomLink(t) linkHash, err := a.CreateLink(context.Background(), link) assert.NoError(t, err, "a.CreateLink()") t.Run("Link saved event should be sent to channel", func(t *testing.T) { select { case got := <-c: assert.EqualValues(t, store.SavedLinks, got.EventType, "Invalid event type") links := got.Data.([]*chainscript.Link) assert.Equal(t, 1, len(links), "Invalid number of links") chainscripttest.LinksEqual(t, link, links[0]) case <-time.After(10 * time.Second): require.Fail(t, "Timeout waiting for link saved event") } }) t.Run("Evidence saved event should be sent to channel", func(t *testing.T) { ctx := context.Background() evidence := chainscripttest.RandomEvidence(t) err = a.AddEvidence(ctx, linkHash, evidence) assert.NoError(t, err, "a.AddEvidence()") var got *store.Event // There might be a race between the external evidence added // and an evidence produced by a blockchain store (hence the for loop) for i := 0; i < 3; i++ { select { case got = <-c: case <-time.After(10 * time.Second): require.Fail(t, "Timeout waiting for evidence saved event") } if got.EventType != store.SavedEvidences { continue } evidences := got.Data.(map[string]*chainscript.Evidence) e, found := evidences[linkHash.String()] if found && e.Backend == evidence.Backend { break } } assert.EqualValues(t, store.SavedEvidences, got.EventType, "Expected saved evidences") evidences := got.Data.(map[string]*chainscript.Evidence) assert.EqualValues(t, evidence, evidences[linkHash.String()]) }) }
store/storetestcases/storeevents.go
0.566258
0.415907
storeevents.go
starcoder
package finnhub import ( "encoding/json" ) // RevenueEstimates struct for RevenueEstimates type RevenueEstimates struct { // List of estimates Data *[]RevenueEstimatesInfo `json:"data,omitempty"` // Frequency: annual or quarterly. Freq *string `json:"freq,omitempty"` // Company symbol. Symbol *string `json:"symbol,omitempty"` } // NewRevenueEstimates instantiates a new RevenueEstimates 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 NewRevenueEstimates() *RevenueEstimates { this := RevenueEstimates{} return &this } // NewRevenueEstimatesWithDefaults instantiates a new RevenueEstimates 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 NewRevenueEstimatesWithDefaults() *RevenueEstimates { this := RevenueEstimates{} return &this } // GetData returns the Data field value if set, zero value otherwise. func (o *RevenueEstimates) GetData() []RevenueEstimatesInfo { if o == nil || o.Data == nil { var ret []RevenueEstimatesInfo return ret } return *o.Data } // GetDataOk returns a tuple with the Data field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RevenueEstimates) GetDataOk() (*[]RevenueEstimatesInfo, bool) { if o == nil || o.Data == nil { return nil, false } return o.Data, true } // HasData returns a boolean if a field has been set. func (o *RevenueEstimates) HasData() bool { if o != nil && o.Data != nil { return true } return false } // SetData gets a reference to the given []RevenueEstimatesInfo and assigns it to the Data field. func (o *RevenueEstimates) SetData(v []RevenueEstimatesInfo) { o.Data = &v } // GetFreq returns the Freq field value if set, zero value otherwise. func (o *RevenueEstimates) GetFreq() string { if o == nil || o.Freq == nil { var ret string return ret } return *o.Freq } // GetFreqOk returns a tuple with the Freq field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RevenueEstimates) GetFreqOk() (*string, bool) { if o == nil || o.Freq == nil { return nil, false } return o.Freq, true } // HasFreq returns a boolean if a field has been set. func (o *RevenueEstimates) HasFreq() bool { if o != nil && o.Freq != nil { return true } return false } // SetFreq gets a reference to the given string and assigns it to the Freq field. func (o *RevenueEstimates) SetFreq(v string) { o.Freq = &v } // GetSymbol returns the Symbol field value if set, zero value otherwise. func (o *RevenueEstimates) GetSymbol() string { if o == nil || o.Symbol == nil { var ret string return ret } return *o.Symbol } // GetSymbolOk returns a tuple with the Symbol field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RevenueEstimates) GetSymbolOk() (*string, bool) { if o == nil || o.Symbol == nil { return nil, false } return o.Symbol, true } // HasSymbol returns a boolean if a field has been set. func (o *RevenueEstimates) HasSymbol() bool { if o != nil && o.Symbol != nil { return true } return false } // SetSymbol gets a reference to the given string and assigns it to the Symbol field. func (o *RevenueEstimates) SetSymbol(v string) { o.Symbol = &v } func (o RevenueEstimates) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Data != nil { toSerialize["data"] = o.Data } if o.Freq != nil { toSerialize["freq"] = o.Freq } if o.Symbol != nil { toSerialize["symbol"] = o.Symbol } return json.Marshal(toSerialize) } type NullableRevenueEstimates struct { value *RevenueEstimates isSet bool } func (v NullableRevenueEstimates) Get() *RevenueEstimates { return v.value } func (v *NullableRevenueEstimates) Set(val *RevenueEstimates) { v.value = val v.isSet = true } func (v NullableRevenueEstimates) IsSet() bool { return v.isSet } func (v *NullableRevenueEstimates) Unset() { v.value = nil v.isSet = false } func NewNullableRevenueEstimates(val *RevenueEstimates) *NullableRevenueEstimates { return &NullableRevenueEstimates{value: val, isSet: true} } func (v NullableRevenueEstimates) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableRevenueEstimates) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_revenue_estimates.go
0.850779
0.416381
model_revenue_estimates.go
starcoder
package dynamic import ( "fmt" "github.com/sidheart/algorithms/util" "math" ) // A multiplicationResult represents the cost of multiplying 2 matrices and the index between the two matrices // e.g. for a list of Matrices [A_0, A_1] the cost would be cost(A_0, A_1) and the split would be 1 type multiplicationResult struct { cost int split int } // A matrixMultCost returns the cost of multiplying Matrices A[i~k] and A[k~j] // A[i~j] denotes the Matrix obtained by multiplying all the Matrices from A_i to A_j-1 type matrixMultCost func (terms *[]util.Matrix, i int, j int, k int) int // multiplicationCost is a matrixMultCost that computes the cost of multiplying A[i~k] * A[k~j] // Note that the cost of computing the individual terms A[i~k] and A[k~j] is not included func mutliplicationCost(terms *[]util.Matrix, i int, j int, k int) int { derefTerms := *terms rowLHS, _ := derefTerms[i].Dimensions() _, colLHS := derefTerms[k-1].Dimensions() _, colRHS := derefTerms[j].Dimensions() return rowLHS * colLHS * colRHS } // Returns true IFF it is possible to multiply every Matrix in terms to compute a single product Matrix func mutliplicationPossible(terms *[]util.Matrix) bool { derefTerms := *terms for i := 1; i < len(derefTerms); i++ { _, colLHS := derefTerms[i-1].Dimensions() rowRHS, _ := derefTerms[i].Dimensions() if colLHS != rowRHS { return false } } return true } // Returns a parenthesized string representing the optimal way to multiply the given Matrices in terms func printOptimalMultiplication(lo int, hi int, solution *map[util.Cell]multiplicationResult, terms *[]util.Matrix) string { if hi <= lo { return "" } else if hi - lo == 1 { return fmt.Sprintf("%v", (*terms)[lo]) } k := (*solution)[util.Cell{lo, hi}].split return fmt.Sprintf("(%v * %v)", printOptimalMultiplication(lo, k, solution, terms), printOptimalMultiplication(k, hi, solution, terms)) } // Computes the optimal way to compute A[i~j] and stores the result in memo[Cell{i,j}] func parenthesize(terms *[]util.Matrix, i int, j int, costFunc matrixMultCost, memo map[util.Cell]multiplicationResult) multiplicationResult { min := math.MaxInt64 desiredCell := util.Cell{i,j} length := j - i if length < 0 { panic("j is greater than i for recursive call of parenthesize") } else if length <= 1 { memo[desiredCell] = multiplicationResult{0, -1} return memo[desiredCell] } for k := i + 1; k < j; k++ { optimalLHS, ok := memo[util.Cell{i, k}] if !ok { optimalLHS = parenthesize(terms, i, k, costFunc, memo) } optimalRHS, ok := memo[util.Cell{k, j - 1}] if !ok { optimalRHS = parenthesize(terms, k, j, costFunc, memo) } potentialMin := optimalLHS.cost + optimalRHS.cost + costFunc(terms, i, j-1, k) if potentialMin < min { min = potentialMin memo[desiredCell] = multiplicationResult{min, k} } } return memo[desiredCell] } // Returns the minimum number of multiplications required to multiply every Matrix in terms and prints an expression // that achieves this minimum number when computed func Parenthesize(terms *[]util.Matrix) int { n := len(*terms) memo := make(map[util.Cell]multiplicationResult, n * n) if !mutliplicationPossible(terms) { panic("Matrix multiplication is not possible for the provided arguments") } solution := parenthesize(terms, 0, n, mutliplicationCost, memo) fmt.Println(printOptimalMultiplication(0, n, &memo, terms)) return solution.cost }
dynamic/matrix_chain_multiplication.go
0.812421
0.555857
matrix_chain_multiplication.go
starcoder
// Package image generates images containing a logo and some text below. package image import ( "fmt" "image" "image/color" "image/draw" "io/ioutil" "os" // This registers the supported formats for image.Decode. _ "image/gif" _ "image/jpeg" _ "image/png" "github.com/golang/freetype/truetype" "golang.org/x/image/font" "golang.org/x/image/math/fixed" ) // Params contains the parameters that describe an image. // They are all required for image creation. type Params struct { Logo string // Filepath to a logo for the top half of the image. Text string // Text to display below the logo. Font string // Filepath to the TrueType font used for the text. Foreground color.Color // Color for the text. Background color.Color // Color for the background. Width int // Width of the image in pixels. Height int // Height of the image in pixels. } // Generate generates a new image given the corresponding parameters. func Generate(p Params) (image.Image, error) { // We create a new image with the given background color. m := image.NewRGBA(image.Rect(0, 0, p.Width, p.Height)) draw.Draw(m, m.Bounds(), image.NewUniform(p.Background), image.Point{}, draw.Src) logo, err := loadImg(p.Logo) if err != nil { return nil, fmt.Errorf("could not open %s: %v", p.Logo, err) } pos := image.Point{(m.Bounds().Max.X - logo.Bounds().Max.X) / 2, m.Bounds().Max.Y / 3} draw.Draw(m, m.Bounds().Add(pos), logo, image.Point{}, draw.Over) // Then load the font to be used with the text. f, err := loadFont(p.Font) if err != nil { return nil, fmt.Errorf("could not load font: %v", err) } // We leave a padding around the text by fitting the width to only 80% of the image width. paddedWidth := int(0.8 * float64(m.Bounds().Max.X)) face, textWidth := fitFontSize(f, paddedWidth, p.Text) // We draw the text on the image. d := &font.Drawer{ Dst: m, Src: image.NewUniform(p.Foreground), Face: face, Dot: fixed.Point26_6{X: (fixed.I(p.Width) - textWidth) / 2, Y: fixed.I(500)}, } d.DrawString(p.Text) return m, nil } // loadFont loads a TrueType font from the given path. func loadFont(path string) (*truetype.Font, error) { b, err := ioutil.ReadFile(path) if err != nil { return nil, fmt.Errorf("could not open file: %v", err) } f, err := truetype.Parse(b) if err != nil { return nil, fmt.Errorf("could not parse font: %v", err) } return f, nil } // loadImg loads an image given its path. func loadImg(path string) (image.Image, error) { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("could not open %s: %v", path, err) } defer f.Close() m, _, err := image.Decode(f) if err != nil { return nil, fmt.Errorf("could not decode %s: %v", path, err) } return m, nil } // WriteImg encodes an image and stores it in a file with the given path. // fitFontSize finds the font size at which the given text fits 80% of the // given width and the indentation required to center the text. func fitFontSize(f *truetype.Font, width int, text string) (font.Face, fixed.Int26_6) { fixw := fixed.I(width) curWidth := 2 * fixw var face font.Face // We find which is the good font size for the width. for size := 100.0; curWidth > fixw; size-- { face = truetype.NewFace(f, &truetype.Options{ Size: size, Hinting: font.HintingNone, DPI: 72, }) curWidth = (&font.Drawer{Face: face}).MeasureString(text) } return face, curWidth }
image/image.go
0.778439
0.522689
image.go
starcoder
package geom import ( "github.com/golang/geo/s2" "math" ) func NewPolygon(lineStrings ...*LineString) *Polygon { polygon := &Polygon{} polygon.LineStrings = append(polygon.LineStrings, lineStrings...) return polygon } func NewPolygonFrom(coordinates ...*LngLat) *Polygon { polygon := &Polygon{} polygon.LineStrings = []*LineString{NewLinearRing(coordinates...)} return polygon } func NewPolygonFromCell(cell s2.Cell) *Polygon { points := CellVertexesFromCell(cell) return NewPolygonFrom(points[0], points[1], points[2], points[3], points[0]) } func NewPolygonFromCellID(cid s2.CellID) *Polygon { return NewPolygonFromCell(s2.CellFromCellID(cid)) } func NewPolygonFromGeoHash(geohash string) *Polygon { points := GeoHashVertexes(geohash) return NewPolygonFrom(points[0], points[1], points[2], points[3], points[0]) } // Add Appends the passed in contour to the current Polygon. // Notice: point is add to first LineString of the Polygon. func (x *Polygon) Add(point *LngLat) *Polygon { if x != nil && len(x.LineStrings) > 0 { x.LineStrings[0].Coordinates = append(x.LineStrings[0].Coordinates, point) } return x } // Invert all LineStrings in the Polygon. func (x *Polygon) Invert() { // For non-special loops, reverse the slice of vertices. for _, line := range x.LineStrings { for i := len(line.Coordinates)/2 - 1; i >= 0; i-- { opp := len(line.Coordinates) - 1 - i line.Coordinates[i], line.Coordinates[opp] = line.Coordinates[opp], line.Coordinates[i] } } } // IsClosed returns whether or not the polygon is closed. // TODO: This can obviously be improved, but for now, // this should be sufficient for detecting if points // are contained using the raycast algorithm. func (x *Polygon) IsClosed() bool { for _, line := range x.LineStrings { if len(line.Coordinates) < 3 { return false } } return true } // Contains returns whether the current Polygon contains the passed in Point. // If the Point is contained by only one LineString, it's contained by the Polygon. func (x *Polygon) Contains(point *LngLat) bool { if !x.IsClosed() { return false } contains := false for _, line := range x.LineStrings { start := len(line.Coordinates) - 1 end := 0 if x.intersectsWithRaycast(point, line.Coordinates[start], line.Coordinates[end]) { contains = !contains } for i := 1; i < len(line.Coordinates); i++ { if x.intersectsWithRaycast(point, line.Coordinates[i-1], line.Coordinates[i]) { contains = !contains } } } return contains } // Area Assumption: The holes are not intersected with each other. func (x *Polygon) Area() float64 { var area float64 for idx, line := range x.LineStrings { var pts []s2.Point for _, pt := range line.Coordinates { pts = append(pts, s2.PointFromLatLng(s2.LatLngFromDegrees(pt.Latitude, pt.Longitude))) } if len(pts) > 0 && pts[0] == pts[len(pts)-1] { pts = pts[:len(pts)-1] } loop := s2.LoopFromPoints(pts) if idx == 0 { area += loop.Area() } else { area -= loop.Area() } } return area } // intersectsWithRaycast Using the raycast algorithm, this returns whether or not the passed in point // Intersects with the edge drawn by the passed in start and end points. // Original implementation: http://rosettacode.org/wiki/Ray-casting_algorithm#Go func (x *Polygon) intersectsWithRaycast(point *LngLat, start *LngLat, end *LngLat) bool { // Always ensure that the the first point // has a y coordinate that is less than the second point if start.Longitude > end.Longitude { // Switch the points if otherwise. start, end = end, start } // Move the point's y coordinate // outside of the bounds of the testing region // so we can start drawing a ray for point.Longitude == start.Longitude || point.Longitude == end.Longitude { newLng := math.Nextafter(point.Longitude, math.Inf(1)) point = NewLngLat(newLng, point.Latitude) } // If we are outside of the polygon, indicate so. if point.Longitude < start.Longitude || point.Longitude > end.Longitude { return false } if start.Latitude > end.Latitude { if point.Latitude > start.Latitude { return false } if point.Latitude < end.Latitude { return true } } else { if point.Latitude > end.Latitude { return false } if point.Latitude < start.Latitude { return true } } raySlope := (point.Longitude - start.Longitude) / (point.Latitude - start.Latitude) diagSlope := (end.Longitude - start.Longitude) / (end.Latitude - start.Latitude) return raySlope >= diagSlope }
go/pkg/mojo/geom/polygon.go
0.829077
0.652352
polygon.go
starcoder
package nem12 import ( "fmt" "strings" ) const ( // TransactionUndefined is for undefined transaction flags. TransactionUndefined TransactionCode = iota // TransactionAlteration is the transaction code value for 'A', when alteration. TransactionAlteration // TransactionMeterReconfiguration is the transaction code value for 'C', when meter reconfiguration. TransactionMeterReconfiguration // TransactionReEnergisation is the transaction code value for 'G', when re-energisation. TransactionReEnergisation // TransactionDeEnergisation is the transaction code value for 'D', when de-energisation. TransactionDeEnergisation // TransactionEstimate is the transaction code value for 'E', when estimated read. TransactionEstimate // TransactionNormalRead is the transaction code value for 'N', when normal read. TransactionNormalRead // TransactionOther is the transaction code value for 'O', when other. TransactionOther // TransactionSpecialRead is the transaction code value for 'S', when special read. TransactionSpecialRead // TransactionRemovalOfMeter is the transaction code value for 'R', when removal of meter. TransactionRemovalOfMeter ) var ( // transactions lists all transactions. transactions = []TransactionCode{ //nolint:gochecknoglobals TransactionAlteration, TransactionMeterReconfiguration, TransactionReEnergisation, TransactionDeEnergisation, TransactionEstimate, TransactionNormalRead, TransactionOther, TransactionSpecialRead, TransactionRemovalOfMeter, } // TransactionName maps a transaction code to its name. TransactionName = map[TransactionCode]string{ //nolint:gochecknoglobals TransactionAlteration: "A", TransactionMeterReconfiguration: "C", TransactionReEnergisation: "G", TransactionDeEnergisation: "D", TransactionEstimate: "E", TransactionNormalRead: "N", TransactionOther: "O", TransactionSpecialRead: "S", TransactionRemovalOfMeter: "R", } // TransactionValue maps a name to its value. TransactionValue = map[string]TransactionCode{ //nolint:gochecknoglobals "A": TransactionAlteration, "C": TransactionMeterReconfiguration, "G": TransactionReEnergisation, "D": TransactionDeEnergisation, "E": TransactionEstimate, "N": TransactionNormalRead, "O": TransactionOther, "S": TransactionSpecialRead, "R": TransactionRemovalOfMeter, } // transactionDescriptions provides the descriptions for the transaction flags. //nolint:lll transactionDescriptions = map[TransactionCode]string{ //nolint:gochecknoglobals TransactionAlteration: "Alteration. Any action involving the alteration of the metering installation at a Site. This includes a removal of one meter and replacing it with another and all new connections and ‘Add/Alts’ Service Orders.", TransactionMeterReconfiguration: "Meter Reconfiguration Service Order. This includes off-peak (Controlled Load) timing changes. This does not apply to the removal of the meter.", TransactionReEnergisation: "Re-energisation Service Order.", TransactionDeEnergisation: "De-energisation Service Order.", TransactionEstimate: "Estimate. For all estimates.", TransactionNormalRead: "Normal Read. Scheduled collection of metering data. Also includes the associated Substitutions.", TransactionOther: "Other. Include Meter Investigation & Miscellaneous Service Orders. This value is used when providing Historical Data and where the TransCode information is unavailable.", TransactionSpecialRead: "Special Read service order.", TransactionRemovalOfMeter: "Remove of Meter. This is used for meter removal or supply abolishment where the meter has been removed and will not be replaced. This excludes situations involving a meter changeover or where a meter is added to an existing configuration (these are considered to be alterations).", } ) // TransactionCode represents the value of the transaction code flag. type TransactionCode int // Transactions returns a slice of all the transactions. func Transactions() []TransactionCode { return transactions } // NewTransactionCode returns a new transaction flag if valid, and an error if not. func NewTransactionCode(s string) (TransactionCode, error) { if s == "" { return TransactionUndefined, ErrTransactionCodeNil } q, ok := TransactionValue[strings.ToUpper(s)] if !ok { return q, ErrTransactionCodeInvalid } return q, nil } // Identifier to meet the interface specification for a Flag. func (t TransactionCode) Identifier() string { id, ok := TransactionName[t] if !ok { return fmt.Sprintf("TransactionCode(%d)", t) } return id } // GoString returns a text representation of the Transaction to satisfy the GoStringer // interface. func (t TransactionCode) GoString() string { return fmt.Sprintf("TransactionCode(%d)", t) } // String returns a text representation of the Transaction. func (t TransactionCode) String() string { s, err := t.Description() if err != nil { return fmt.Sprintf("%q", t.Identifier()) } return fmt.Sprintf("\"%s: %s\"", t.Identifier(), s) } // Description returns the description of a transaction flag. Error is returned if the // flag is invalid. func (t TransactionCode) Description() (string, error) { d, ok := transactionDescriptions[t] if !ok { return "", ErrTransactionCodeInvalid } return d, nil }
nem12/transaction.go
0.649467
0.442094
transaction.go
starcoder
package clusterfeature import ( "context" "emperror.dev/errors" ) // Feature represents the state of a cluster feature. type Feature struct { Name string `json:"name"` Spec FeatureSpec `json:"spec"` Output FeatureOutput `json:"output"` Status string `json:"status"` } // FeatureSpec represents a feature's specification (i.e. its input parameters). type FeatureSpec = map[string]interface{} // FeatureOutput represents a feature's output. type FeatureOutput = map[string]interface{} // FeatureStatus represents a feature's status. type FeatureStatus = string // Feature status constants const ( FeatureStatusInactive FeatureStatus = "INACTIVE" FeatureStatusPending FeatureStatus = "PENDING" FeatureStatusActive FeatureStatus = "ACTIVE" FeatureStatusError FeatureStatus = "ERROR" ) // FeatureManagerRegistry contains feature managers. type FeatureManagerRegistry interface { // GetFeatureManager retrieves a feature manager by name. GetFeatureManager(featureName string) (FeatureManager, error) } // FeatureOperatorRegistry contains feature operators. type FeatureOperatorRegistry interface { // GetFeatureOperator retrieves a feature operator by name. GetFeatureOperator(featureName string) (FeatureOperator, error) } // FeatureRepository manages feature state. type FeatureRepository interface { // GetFeatures retrieves features for a given cluster. GetFeatures(ctx context.Context, clusterID uint) ([]Feature, error) // GetFeature retrieves a feature. GetFeature(ctx context.Context, clusterID uint, featureName string) (Feature, error) // SaveFeature persists a feature. SaveFeature(ctx context.Context, clusterID uint, featureName string, spec FeatureSpec, status string) error // UpdateFeatureStatus updates the status of a feature. UpdateFeatureStatus(ctx context.Context, clusterID uint, featureName string, status string) error // UpdateFeatureSpec updates the spec of a feature. UpdateFeatureSpec(ctx context.Context, clusterID uint, featureName string, spec FeatureSpec) error // DeleteFeature deletes a feature. DeleteFeature(ctx context.Context, clusterID uint, featureName string) error } // IsFeatureNotFoundError returns true when the specified error is a "feature not found" error func IsFeatureNotFoundError(err error) bool { var notFoundErr interface { FeatureNotFound() bool } return errors.As(err, &notFoundErr) && notFoundErr.FeatureNotFound() } // FeatureManager is a collection of feature specific methods that are used synchronously when responding to feature related requests. type FeatureManager interface { FeatureOutputProducer FeatureSpecValidator FeatureSpecPreparer // Name returns the feature's name. Name() string } // FeatureOutputProducer defines how to produce a cluster feature's output. type FeatureOutputProducer interface { // GetOutput returns a cluster feature's output. GetOutput(ctx context.Context, clusterID uint, spec FeatureSpec) (FeatureOutput, error) } // FeatureSpecValidator defines how to validate a feature specification type FeatureSpecValidator interface { // ValidateSpec validates a feature specification. ValidateSpec(ctx context.Context, spec FeatureSpec) error } // IsInputValidationError returns true if the error is an input validation error func IsInputValidationError(err error) bool { var inputValidationError interface { InputValidationError() bool } return errors.As(err, &inputValidationError) && inputValidationError.InputValidationError() } // InvalidFeatureSpecError is returned when a feature specification fails the validation. type InvalidFeatureSpecError struct { FeatureName string Problem string } func (e InvalidFeatureSpecError) Error() string { return "invalid feature spec: " + e.Problem } // Details returns the error's details func (e InvalidFeatureSpecError) Details() []interface{} { return []interface{}{"feature", e.FeatureName} } // InputValidationError returns true since InputValidationError is an input validation error func (InvalidFeatureSpecError) InputValidationError() bool { return true } // FeatureSpecPreparer defines how a feature specification is prepared before it's sent to be applied type FeatureSpecPreparer interface { // PrepareSpec makes certain preparations to the spec before it's sent to be applied. // For example it rewrites the secret ID to it's internal representation, fills in defaults, etc. PrepareSpec(ctx context.Context, spec FeatureSpec) (FeatureSpec, error) } // FeatureOperationDispatcher dispatches cluster feature operations asynchronously. type FeatureOperationDispatcher interface { // DispatchApply starts applying a desired state for a cluster feature asynchronously. DispatchApply(ctx context.Context, clusterID uint, featureName string, spec FeatureSpec) error // DispatchDeactivate starts deactivating a cluster feature asynchronously. DispatchDeactivate(ctx context.Context, clusterID uint, featureName string, spec FeatureSpec) error } // FeatureOperator defines the operations that can be applied to a cluster feature. type FeatureOperator interface { // Apply applies a desired state for a feature on the given cluster. Apply(ctx context.Context, clusterID uint, spec FeatureSpec) error // Deactivate deactivates a feature on the given cluster. Deactivate(ctx context.Context, clusterID uint, spec FeatureSpec) error // Name returns the feature's name. Name() string } //go:generate mockery -name ClusterService -inpkg // ClusterService provides a thin access layer to clusters. type ClusterService interface { // CheckClusterReady checks whether the cluster is ready for features (eg.: exists and it's running). If the cluster is not ready, a ClusterIsNotReadyError should be returned. CheckClusterReady(ctx context.Context, clusterID uint) error } // ClusterIsNotReadyError is returned when a cluster is not in a ready state. type ClusterIsNotReadyError struct { ClusterID uint } func (e ClusterIsNotReadyError) Error() string { return "cluster is not ready" } // Details returns the error's details func (e ClusterIsNotReadyError) Details() []interface{} { return []interface{}{"clusterId", e.ClusterID} } // ShouldRetry returns true if the operation resulting in this error should be retried later. func (e ClusterIsNotReadyError) ShouldRetry() bool { return true }
internal/clusterfeature/interface.go
0.804866
0.471284
interface.go
starcoder
package em import ( "fmt" "golang.org/x/exp/rand" "gonum.org/v1/gonum/floats" "gonum.org/v1/gonum/mat" "gonum.org/v1/gonum/stat" "gonum.org/v1/gonum/stat/distmv" "gonum.org/v1/gonum/stat/distuv" "math" ) func GenerateMVGaussian(means []float64, sigma *mat.DiagDense, numObs int, seed uint64) [][]float64{ normalMv, err := distmv.NewNormal(means, sigma, rand.NewSource(seed)) if err != true{ panic(fmt.Sprintf("Something went wrong generating mvn random variables !")) } var data = make([][]float64, numObs) for j := 0; j< numObs; j++{ data[j] = normalMv.Rand(nil) } return data } func EMAlgo(dataset []float64, tol int) ([]float64, float64, float64,float64, float64,float64){ // Initialize parameters sigmaZero := stat.Variance(dataset, nil) muZero := dataset[rand.Intn(len(dataset))] sigmaOne := sigmaZero muOne := dataset[rand.Intn(len(dataset))] piHat := rand.Float64() round := 0 fmt.Printf("===================== \n") fmt.Printf("INITIALIZATION: \n") fmt.Printf("mu_zero: %v \n", muZero) fmt.Printf("mu_one: %v \n", muOne) fmt.Printf("sigma_zero: %v \n", sigmaZero) fmt.Printf("sigma_one: %v \n", sigmaOne) fmt.Printf("pi_hat: %v \n", piHat) // Auxiliary variables to the optimization step sigmaZeroRep := make([]float64, len(dataset)) sigmaOneRep := make([]float64, len(dataset)) muZeroRep := make([]float64, len(dataset)) muOneRep := make([]float64, len(dataset)) gammaRep := make([]float64, len(dataset)) gamma := make([]float64, len(dataset)) likelihoods := make([]float64, tol) for ; round < tol;{ distOne := distuv.Normal{ Mu: muOne, Sigma: sigmaOne, } distZero := distuv.Normal{ Mu: muZero, Sigma: sigmaZero, } // Expectation Step - Compute Responsabilities for j:=0; j< len(dataset); j++{ gamma[j] = (piHat*distZero.Prob(dataset[j]))/((1.0-piHat)*distOne.Prob(dataset[j]) + piHat*distZero.Prob(dataset[j])) } // Maximization Step for i:=0;i<len(gamma);i++{ gammaRep[i] = 1.0 - gamma[i] muZeroRep[i] = gamma[i]*dataset[i] muOneRep[i] = (1.0 - gamma[i])*dataset[i] } gammaSum := floats.Sum(gamma) gammaRepSum := floats.Sum(gammaRep) // Update estimators muZero = floats.Sum(muZeroRep)/ gammaSum muOne = floats.Sum(muOneRep)/ gammaRepSum for i:=0;i<len(gamma);i++{ sigmaOneRep[i] = (1.0 - gamma[i])*math.Pow(dataset[i] - muOne, 2) sigmaZeroRep[i] = gamma[i]*math.Pow(dataset[i] - muZero, 2) } sigmaZero = floats.Sum(sigmaZeroRep) / gammaSum sigmaOne = floats.Sum(sigmaOneRep) / gammaRepSum piHat = gammaSum / float64(len(gamma)) likelihoods[round] = logLikelihood(piHat, dataset, distZero, distOne) round++ } return likelihoods, muZero, muOne, sigmaZero, sigmaOne, piHat } func logLikelihood(pi float64, dataset []float64, normalZero distuv.Normal, normalOne distuv.Normal) float64{ tmpRep := make([]float64, len(dataset)) for i:= range tmpRep{ tmpRep[i] = math.Log((1.0-pi)*normalOne.Prob(dataset[i]) + pi*normalZero.Prob(dataset[i])) } return floats.Sum(tmpRep) }
em/emalgo.go
0.560493
0.405625
emalgo.go
starcoder
package attributes import "strings" type Attribute struct { Templ string Data interface{} Name string } // Begin of manually implemented attributes func Dataset(key, value string) Attribute { key_ := strings.Replace(key, "-", "_", -1) return Attribute{ Data: map[string]string{ "key": key, "value": value, }, Templ: `{{define "Dataset_`+key_+`"}}data-{{.key}}="{{.value}}"{{end}}`, Name: "Dataset_"+key_, } } func Dataset_(key, value string) Attribute { key_ := strings.Replace(key, "-", "_", -1) return Attribute{ Data: map[string]string{ "value": value, }, Templ: `{{define "Dataset_`+key_+`"}}data-`+key+`="{{.value}}"{{end}}`, Name: "Dataset_"+key_, } } // Begin of generated attributes func Accept(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Accept" } if len(templs) == 0 { attr.Templ = `{{define "Accept"}}accept="{{.}}"{{end}}` } else { attr.Templ = `{{define "Accept"}}accept="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Accept_(values ...string) Attribute { return Accept(nil, values...) } func AcceptCharset(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "AcceptCharset" } if len(templs) == 0 { attr.Templ = `{{define "AcceptCharset"}}accept-charset="{{.}}"{{end}}` } else { attr.Templ = `{{define "AcceptCharset"}}accept-charset="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func AcceptCharset_(values ...string) Attribute { return AcceptCharset(nil, values...) } func Accesskey(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Accesskey" } if len(templs) == 0 { attr.Templ = `{{define "Accesskey"}}accesskey="{{.}}"{{end}}` } else { attr.Templ = `{{define "Accesskey"}}accesskey="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Accesskey_(values ...string) Attribute { return Accesskey(nil, values...) } func Action(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Action" } if len(templs) == 0 { attr.Templ = `{{define "Action"}}action="{{.}}"{{end}}` } else { attr.Templ = `{{define "Action"}}action="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Action_(values ...string) Attribute { return Action(nil, values...) } func Align(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Align" } if len(templs) == 0 { attr.Templ = `{{define "Align"}}align="{{.}}"{{end}}` } else { attr.Templ = `{{define "Align"}}align="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Align_(values ...string) Attribute { return Align(nil, values...) } func Alt(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Alt" } if len(templs) == 0 { attr.Templ = `{{define "Alt"}}alt="{{.}}"{{end}}` } else { attr.Templ = `{{define "Alt"}}alt="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Alt_(values ...string) Attribute { return Alt(nil, values...) } func AriaExpanded(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "AriaExpanded" } if len(templs) == 0 { attr.Templ = `{{define "AriaExpanded"}}aria-expanded="{{.}}"{{end}}` } else { attr.Templ = `{{define "AriaExpanded"}}aria-expanded="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func AriaExpanded_(values ...string) Attribute { return AriaExpanded(nil, values...) } func AriaHidden(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "AriaHidden" } if len(templs) == 0 { attr.Templ = `{{define "AriaHidden"}}aria-hidden="{{.}}"{{end}}` } else { attr.Templ = `{{define "AriaHidden"}}aria-hidden="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func AriaHidden_(values ...string) Attribute { return AriaHidden(nil, values...) } func AriaLabel(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "AriaLabel" } if len(templs) == 0 { attr.Templ = `{{define "AriaLabel"}}aria-label="{{.}}"{{end}}` } else { attr.Templ = `{{define "AriaLabel"}}aria-label="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func AriaLabel_(values ...string) Attribute { return AriaLabel(nil, values...) } func Async(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Async" } if len(templs) == 0 { attr.Templ = `{{define "Async"}}async="{{.}}"{{end}}` } else { attr.Templ = `{{define "Async"}}async="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Async_(values ...string) Attribute { return Async(nil, values...) } func Autocomplete(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Autocomplete" } if len(templs) == 0 { attr.Templ = `{{define "Autocomplete"}}autocomplete="{{.}}"{{end}}` } else { attr.Templ = `{{define "Autocomplete"}}autocomplete="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Autocomplete_(values ...string) Attribute { return Autocomplete(nil, values...) } func Autofocus(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Autofocus" } if len(templs) == 0 { attr.Templ = `{{define "Autofocus"}}autofocus="{{.}}"{{end}}` } else { attr.Templ = `{{define "Autofocus"}}autofocus="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Autofocus_(values ...string) Attribute { return Autofocus(nil, values...) } func Autoplay(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Autoplay" } if len(templs) == 0 { attr.Templ = `{{define "Autoplay"}}autoplay="{{.}}"{{end}}` } else { attr.Templ = `{{define "Autoplay"}}autoplay="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Autoplay_(values ...string) Attribute { return Autoplay(nil, values...) } func Bgcolor(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Bgcolor" } if len(templs) == 0 { attr.Templ = `{{define "Bgcolor"}}bgcolor="{{.}}"{{end}}` } else { attr.Templ = `{{define "Bgcolor"}}bgcolor="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Bgcolor_(values ...string) Attribute { return Bgcolor(nil, values...) } func Border(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Border" } if len(templs) == 0 { attr.Templ = `{{define "Border"}}border="{{.}}"{{end}}` } else { attr.Templ = `{{define "Border"}}border="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Border_(values ...string) Attribute { return Border(nil, values...) } func Charset(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Charset" } if len(templs) == 0 { attr.Templ = `{{define "Charset"}}charset="{{.}}"{{end}}` } else { attr.Templ = `{{define "Charset"}}charset="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Charset_(values ...string) Attribute { return Charset(nil, values...) } func Checked(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Checked" } if len(templs) == 0 { attr.Templ = `{{define "Checked"}}checked="{{.}}"{{end}}` } else { attr.Templ = `{{define "Checked"}}checked="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Checked_(values ...string) Attribute { return Checked(nil, values...) } func Cite(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Cite" } if len(templs) == 0 { attr.Templ = `{{define "Cite"}}cite="{{.}}"{{end}}` } else { attr.Templ = `{{define "Cite"}}cite="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Cite_(values ...string) Attribute { return Cite(nil, values...) } func Class(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Class" } if len(templs) == 0 { attr.Templ = `{{define "Class"}}class="{{.}}"{{end}}` } else { attr.Templ = `{{define "Class"}}class="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Class_(values ...string) Attribute { return Class(nil, values...) } func Color(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Color" } if len(templs) == 0 { attr.Templ = `{{define "Color"}}color="{{.}}"{{end}}` } else { attr.Templ = `{{define "Color"}}color="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Color_(values ...string) Attribute { return Color(nil, values...) } func Cols(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Cols" } if len(templs) == 0 { attr.Templ = `{{define "Cols"}}cols="{{.}}"{{end}}` } else { attr.Templ = `{{define "Cols"}}cols="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Cols_(values ...string) Attribute { return Cols(nil, values...) } func Colspan(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Colspan" } if len(templs) == 0 { attr.Templ = `{{define "Colspan"}}colspan="{{.}}"{{end}}` } else { attr.Templ = `{{define "Colspan"}}colspan="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Colspan_(values ...string) Attribute { return Colspan(nil, values...) } func Content(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Content" } if len(templs) == 0 { attr.Templ = `{{define "Content"}}content="{{.}}"{{end}}` } else { attr.Templ = `{{define "Content"}}content="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Content_(values ...string) Attribute { return Content(nil, values...) } func Contenteditable(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Contenteditable" } if len(templs) == 0 { attr.Templ = `{{define "Contenteditable"}}contenteditable="{{.}}"{{end}}` } else { attr.Templ = `{{define "Contenteditable"}}contenteditable="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Contenteditable_(values ...string) Attribute { return Contenteditable(nil, values...) } func Controls(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Controls" } if len(templs) == 0 { attr.Templ = `{{define "Controls"}}controls="{{.}}"{{end}}` } else { attr.Templ = `{{define "Controls"}}controls="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Controls_(values ...string) Attribute { return Controls(nil, values...) } func Coords(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Coords" } if len(templs) == 0 { attr.Templ = `{{define "Coords"}}coords="{{.}}"{{end}}` } else { attr.Templ = `{{define "Coords"}}coords="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Coords_(values ...string) Attribute { return Coords(nil, values...) } func Data(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Data" } if len(templs) == 0 { attr.Templ = `{{define "Data"}}data="{{.}}"{{end}}` } else { attr.Templ = `{{define "Data"}}data="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Data_(values ...string) Attribute { return Data(nil, values...) } func Datetime(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Datetime" } if len(templs) == 0 { attr.Templ = `{{define "Datetime"}}datetime="{{.}}"{{end}}` } else { attr.Templ = `{{define "Datetime"}}datetime="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Datetime_(values ...string) Attribute { return Datetime(nil, values...) } func Default(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Default" } if len(templs) == 0 { attr.Templ = `{{define "Default"}}default="{{.}}"{{end}}` } else { attr.Templ = `{{define "Default"}}default="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Default_(values ...string) Attribute { return Default(nil, values...) } func Defer(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Defer" } if len(templs) == 0 { attr.Templ = `{{define "Defer"}}defer="{{.}}"{{end}}` } else { attr.Templ = `{{define "Defer"}}defer="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Defer_(values ...string) Attribute { return Defer(nil, values...) } func Dir(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Dir" } if len(templs) == 0 { attr.Templ = `{{define "Dir"}}dir="{{.}}"{{end}}` } else { attr.Templ = `{{define "Dir"}}dir="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Dir_(values ...string) Attribute { return Dir(nil, values...) } func Dirname(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Dirname" } if len(templs) == 0 { attr.Templ = `{{define "Dirname"}}dirname="{{.}}"{{end}}` } else { attr.Templ = `{{define "Dirname"}}dirname="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Dirname_(values ...string) Attribute { return Dirname(nil, values...) } func Disabled(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Disabled" } if len(templs) == 0 { attr.Templ = `{{define "Disabled"}}disabled="{{.}}"{{end}}` } else { attr.Templ = `{{define "Disabled"}}disabled="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Disabled_(values ...string) Attribute { return Disabled(nil, values...) } func Download(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Download" } if len(templs) == 0 { attr.Templ = `{{define "Download"}}download="{{.}}"{{end}}` } else { attr.Templ = `{{define "Download"}}download="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Download_(values ...string) Attribute { return Download(nil, values...) } func Draggable(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Draggable" } if len(templs) == 0 { attr.Templ = `{{define "Draggable"}}draggable="{{.}}"{{end}}` } else { attr.Templ = `{{define "Draggable"}}draggable="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Draggable_(values ...string) Attribute { return Draggable(nil, values...) } func Dropzone(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Dropzone" } if len(templs) == 0 { attr.Templ = `{{define "Dropzone"}}dropzone="{{.}}"{{end}}` } else { attr.Templ = `{{define "Dropzone"}}dropzone="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Dropzone_(values ...string) Attribute { return Dropzone(nil, values...) } func Enctype(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Enctype" } if len(templs) == 0 { attr.Templ = `{{define "Enctype"}}enctype="{{.}}"{{end}}` } else { attr.Templ = `{{define "Enctype"}}enctype="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Enctype_(values ...string) Attribute { return Enctype(nil, values...) } func For(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "For" } if len(templs) == 0 { attr.Templ = `{{define "For"}}for="{{.}}"{{end}}` } else { attr.Templ = `{{define "For"}}for="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func For_(values ...string) Attribute { return For(nil, values...) } func Form(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Form" } if len(templs) == 0 { attr.Templ = `{{define "Form"}}form="{{.}}"{{end}}` } else { attr.Templ = `{{define "Form"}}form="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Form_(values ...string) Attribute { return Form(nil, values...) } func Formaction(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Formaction" } if len(templs) == 0 { attr.Templ = `{{define "Formaction"}}formaction="{{.}}"{{end}}` } else { attr.Templ = `{{define "Formaction"}}formaction="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Formaction_(values ...string) Attribute { return Formaction(nil, values...) } func Headers(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Headers" } if len(templs) == 0 { attr.Templ = `{{define "Headers"}}headers="{{.}}"{{end}}` } else { attr.Templ = `{{define "Headers"}}headers="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Headers_(values ...string) Attribute { return Headers(nil, values...) } func Height(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Height" } if len(templs) == 0 { attr.Templ = `{{define "Height"}}height="{{.}}"{{end}}` } else { attr.Templ = `{{define "Height"}}height="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Height_(values ...string) Attribute { return Height(nil, values...) } func Hidden(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Hidden" } if len(templs) == 0 { attr.Templ = `{{define "Hidden"}}hidden="{{.}}"{{end}}` } else { attr.Templ = `{{define "Hidden"}}hidden="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Hidden_(values ...string) Attribute { return Hidden(nil, values...) } func High(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "High" } if len(templs) == 0 { attr.Templ = `{{define "High"}}high="{{.}}"{{end}}` } else { attr.Templ = `{{define "High"}}high="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func High_(values ...string) Attribute { return High(nil, values...) } func Href(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Href" } if len(templs) == 0 { attr.Templ = `{{define "Href"}}href="{{.}}"{{end}}` } else { attr.Templ = `{{define "Href"}}href="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Href_(values ...string) Attribute { return Href(nil, values...) } func Hreflang(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Hreflang" } if len(templs) == 0 { attr.Templ = `{{define "Hreflang"}}hreflang="{{.}}"{{end}}` } else { attr.Templ = `{{define "Hreflang"}}hreflang="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Hreflang_(values ...string) Attribute { return Hreflang(nil, values...) } func HttpEquiv(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "HttpEquiv" } if len(templs) == 0 { attr.Templ = `{{define "HttpEquiv"}}http-equiv="{{.}}"{{end}}` } else { attr.Templ = `{{define "HttpEquiv"}}http-equiv="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func HttpEquiv_(values ...string) Attribute { return HttpEquiv(nil, values...) } func Id(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Id" } if len(templs) == 0 { attr.Templ = `{{define "Id"}}id="{{.}}"{{end}}` } else { attr.Templ = `{{define "Id"}}id="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Id_(values ...string) Attribute { return Id(nil, values...) } func InitialScale(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "InitialScale" } if len(templs) == 0 { attr.Templ = `{{define "InitialScale"}}initial-scale="{{.}}"{{end}}` } else { attr.Templ = `{{define "InitialScale"}}initial-scale="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func InitialScale_(values ...string) Attribute { return InitialScale(nil, values...) } func Ismap(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ismap" } if len(templs) == 0 { attr.Templ = `{{define "Ismap"}}ismap="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ismap"}}ismap="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ismap_(values ...string) Attribute { return Ismap(nil, values...) } func Kind(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Kind" } if len(templs) == 0 { attr.Templ = `{{define "Kind"}}kind="{{.}}"{{end}}` } else { attr.Templ = `{{define "Kind"}}kind="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Kind_(values ...string) Attribute { return Kind(nil, values...) } func Label(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Label" } if len(templs) == 0 { attr.Templ = `{{define "Label"}}label="{{.}}"{{end}}` } else { attr.Templ = `{{define "Label"}}label="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Label_(values ...string) Attribute { return Label(nil, values...) } func Lang(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Lang" } if len(templs) == 0 { attr.Templ = `{{define "Lang"}}lang="{{.}}"{{end}}` } else { attr.Templ = `{{define "Lang"}}lang="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Lang_(values ...string) Attribute { return Lang(nil, values...) } func List(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "List" } if len(templs) == 0 { attr.Templ = `{{define "List"}}list="{{.}}"{{end}}` } else { attr.Templ = `{{define "List"}}list="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func List_(values ...string) Attribute { return List(nil, values...) } func Loop(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Loop" } if len(templs) == 0 { attr.Templ = `{{define "Loop"}}loop="{{.}}"{{end}}` } else { attr.Templ = `{{define "Loop"}}loop="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Loop_(values ...string) Attribute { return Loop(nil, values...) } func Low(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Low" } if len(templs) == 0 { attr.Templ = `{{define "Low"}}low="{{.}}"{{end}}` } else { attr.Templ = `{{define "Low"}}low="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Low_(values ...string) Attribute { return Low(nil, values...) } func Max(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Max" } if len(templs) == 0 { attr.Templ = `{{define "Max"}}max="{{.}}"{{end}}` } else { attr.Templ = `{{define "Max"}}max="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Max_(values ...string) Attribute { return Max(nil, values...) } func Maxlength(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Maxlength" } if len(templs) == 0 { attr.Templ = `{{define "Maxlength"}}maxlength="{{.}}"{{end}}` } else { attr.Templ = `{{define "Maxlength"}}maxlength="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Maxlength_(values ...string) Attribute { return Maxlength(nil, values...) } func Media(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Media" } if len(templs) == 0 { attr.Templ = `{{define "Media"}}media="{{.}}"{{end}}` } else { attr.Templ = `{{define "Media"}}media="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Media_(values ...string) Attribute { return Media(nil, values...) } func Method(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Method" } if len(templs) == 0 { attr.Templ = `{{define "Method"}}method="{{.}}"{{end}}` } else { attr.Templ = `{{define "Method"}}method="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Method_(values ...string) Attribute { return Method(nil, values...) } func Min(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Min" } if len(templs) == 0 { attr.Templ = `{{define "Min"}}min="{{.}}"{{end}}` } else { attr.Templ = `{{define "Min"}}min="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Min_(values ...string) Attribute { return Min(nil, values...) } func Multiple(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Multiple" } if len(templs) == 0 { attr.Templ = `{{define "Multiple"}}multiple="{{.}}"{{end}}` } else { attr.Templ = `{{define "Multiple"}}multiple="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Multiple_(values ...string) Attribute { return Multiple(nil, values...) } func Muted(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Muted" } if len(templs) == 0 { attr.Templ = `{{define "Muted"}}muted="{{.}}"{{end}}` } else { attr.Templ = `{{define "Muted"}}muted="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Muted_(values ...string) Attribute { return Muted(nil, values...) } func Name(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Name" } if len(templs) == 0 { attr.Templ = `{{define "Name"}}name="{{.}}"{{end}}` } else { attr.Templ = `{{define "Name"}}name="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Name_(values ...string) Attribute { return Name(nil, values...) } func Novalidate(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Novalidate" } if len(templs) == 0 { attr.Templ = `{{define "Novalidate"}}novalidate="{{.}}"{{end}}` } else { attr.Templ = `{{define "Novalidate"}}novalidate="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Novalidate_(values ...string) Attribute { return Novalidate(nil, values...) } func Onabort(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onabort" } if len(templs) == 0 { attr.Templ = `{{define "Onabort"}}onabort="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onabort"}}onabort="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onabort_(values ...string) Attribute { return Onabort(nil, values...) } func Onafterprint(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onafterprint" } if len(templs) == 0 { attr.Templ = `{{define "Onafterprint"}}onafterprint="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onafterprint"}}onafterprint="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onafterprint_(values ...string) Attribute { return Onafterprint(nil, values...) } func Onbeforeprint(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onbeforeprint" } if len(templs) == 0 { attr.Templ = `{{define "Onbeforeprint"}}onbeforeprint="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onbeforeprint"}}onbeforeprint="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onbeforeprint_(values ...string) Attribute { return Onbeforeprint(nil, values...) } func Onbeforeunload(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onbeforeunload" } if len(templs) == 0 { attr.Templ = `{{define "Onbeforeunload"}}onbeforeunload="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onbeforeunload"}}onbeforeunload="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onbeforeunload_(values ...string) Attribute { return Onbeforeunload(nil, values...) } func Onblur(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onblur" } if len(templs) == 0 { attr.Templ = `{{define "Onblur"}}onblur="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onblur"}}onblur="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onblur_(values ...string) Attribute { return Onblur(nil, values...) } func Oncanplay(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oncanplay" } if len(templs) == 0 { attr.Templ = `{{define "Oncanplay"}}oncanplay="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oncanplay"}}oncanplay="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oncanplay_(values ...string) Attribute { return Oncanplay(nil, values...) } func Oncanplaythrough(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oncanplaythrough" } if len(templs) == 0 { attr.Templ = `{{define "Oncanplaythrough"}}oncanplaythrough="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oncanplaythrough"}}oncanplaythrough="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oncanplaythrough_(values ...string) Attribute { return Oncanplaythrough(nil, values...) } func Onchange(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onchange" } if len(templs) == 0 { attr.Templ = `{{define "Onchange"}}onchange="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onchange"}}onchange="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onchange_(values ...string) Attribute { return Onchange(nil, values...) } func Onclick(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onclick" } if len(templs) == 0 { attr.Templ = `{{define "Onclick"}}onclick="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onclick"}}onclick="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onclick_(values ...string) Attribute { return Onclick(nil, values...) } func Oncontextmenu(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oncontextmenu" } if len(templs) == 0 { attr.Templ = `{{define "Oncontextmenu"}}oncontextmenu="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oncontextmenu"}}oncontextmenu="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oncontextmenu_(values ...string) Attribute { return Oncontextmenu(nil, values...) } func Oncopy(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oncopy" } if len(templs) == 0 { attr.Templ = `{{define "Oncopy"}}oncopy="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oncopy"}}oncopy="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oncopy_(values ...string) Attribute { return Oncopy(nil, values...) } func Oncuechange(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oncuechange" } if len(templs) == 0 { attr.Templ = `{{define "Oncuechange"}}oncuechange="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oncuechange"}}oncuechange="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oncuechange_(values ...string) Attribute { return Oncuechange(nil, values...) } func Oncut(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oncut" } if len(templs) == 0 { attr.Templ = `{{define "Oncut"}}oncut="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oncut"}}oncut="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oncut_(values ...string) Attribute { return Oncut(nil, values...) } func Ondblclick(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondblclick" } if len(templs) == 0 { attr.Templ = `{{define "Ondblclick"}}ondblclick="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondblclick"}}ondblclick="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondblclick_(values ...string) Attribute { return Ondblclick(nil, values...) } func Ondrag(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondrag" } if len(templs) == 0 { attr.Templ = `{{define "Ondrag"}}ondrag="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondrag"}}ondrag="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondrag_(values ...string) Attribute { return Ondrag(nil, values...) } func Ondragend(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondragend" } if len(templs) == 0 { attr.Templ = `{{define "Ondragend"}}ondragend="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondragend"}}ondragend="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondragend_(values ...string) Attribute { return Ondragend(nil, values...) } func Ondragenter(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondragenter" } if len(templs) == 0 { attr.Templ = `{{define "Ondragenter"}}ondragenter="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondragenter"}}ondragenter="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondragenter_(values ...string) Attribute { return Ondragenter(nil, values...) } func Ondragleave(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondragleave" } if len(templs) == 0 { attr.Templ = `{{define "Ondragleave"}}ondragleave="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondragleave"}}ondragleave="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondragleave_(values ...string) Attribute { return Ondragleave(nil, values...) } func Ondragover(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondragover" } if len(templs) == 0 { attr.Templ = `{{define "Ondragover"}}ondragover="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondragover"}}ondragover="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondragover_(values ...string) Attribute { return Ondragover(nil, values...) } func Ondragstart(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondragstart" } if len(templs) == 0 { attr.Templ = `{{define "Ondragstart"}}ondragstart="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondragstart"}}ondragstart="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondragstart_(values ...string) Attribute { return Ondragstart(nil, values...) } func Ondrop(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondrop" } if len(templs) == 0 { attr.Templ = `{{define "Ondrop"}}ondrop="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondrop"}}ondrop="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondrop_(values ...string) Attribute { return Ondrop(nil, values...) } func Ondurationchange(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ondurationchange" } if len(templs) == 0 { attr.Templ = `{{define "Ondurationchange"}}ondurationchange="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ondurationchange"}}ondurationchange="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ondurationchange_(values ...string) Attribute { return Ondurationchange(nil, values...) } func Onemptied(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onemptied" } if len(templs) == 0 { attr.Templ = `{{define "Onemptied"}}onemptied="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onemptied"}}onemptied="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onemptied_(values ...string) Attribute { return Onemptied(nil, values...) } func Onended(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onended" } if len(templs) == 0 { attr.Templ = `{{define "Onended"}}onended="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onended"}}onended="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onended_(values ...string) Attribute { return Onended(nil, values...) } func Onerror(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onerror" } if len(templs) == 0 { attr.Templ = `{{define "Onerror"}}onerror="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onerror"}}onerror="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onerror_(values ...string) Attribute { return Onerror(nil, values...) } func Onfocus(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onfocus" } if len(templs) == 0 { attr.Templ = `{{define "Onfocus"}}onfocus="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onfocus"}}onfocus="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onfocus_(values ...string) Attribute { return Onfocus(nil, values...) } func Onhashchange(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onhashchange" } if len(templs) == 0 { attr.Templ = `{{define "Onhashchange"}}onhashchange="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onhashchange"}}onhashchange="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onhashchange_(values ...string) Attribute { return Onhashchange(nil, values...) } func Oninput(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oninput" } if len(templs) == 0 { attr.Templ = `{{define "Oninput"}}oninput="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oninput"}}oninput="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oninput_(values ...string) Attribute { return Oninput(nil, values...) } func Oninvalid(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Oninvalid" } if len(templs) == 0 { attr.Templ = `{{define "Oninvalid"}}oninvalid="{{.}}"{{end}}` } else { attr.Templ = `{{define "Oninvalid"}}oninvalid="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Oninvalid_(values ...string) Attribute { return Oninvalid(nil, values...) } func Onkeydown(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onkeydown" } if len(templs) == 0 { attr.Templ = `{{define "Onkeydown"}}onkeydown="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onkeydown"}}onkeydown="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onkeydown_(values ...string) Attribute { return Onkeydown(nil, values...) } func Onkeypress(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onkeypress" } if len(templs) == 0 { attr.Templ = `{{define "Onkeypress"}}onkeypress="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onkeypress"}}onkeypress="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onkeypress_(values ...string) Attribute { return Onkeypress(nil, values...) } func Onkeyup(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onkeyup" } if len(templs) == 0 { attr.Templ = `{{define "Onkeyup"}}onkeyup="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onkeyup"}}onkeyup="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onkeyup_(values ...string) Attribute { return Onkeyup(nil, values...) } func Onload(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onload" } if len(templs) == 0 { attr.Templ = `{{define "Onload"}}onload="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onload"}}onload="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onload_(values ...string) Attribute { return Onload(nil, values...) } func Onloadeddata(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onloadeddata" } if len(templs) == 0 { attr.Templ = `{{define "Onloadeddata"}}onloadeddata="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onloadeddata"}}onloadeddata="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onloadeddata_(values ...string) Attribute { return Onloadeddata(nil, values...) } func Onloadedmetadata(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onloadedmetadata" } if len(templs) == 0 { attr.Templ = `{{define "Onloadedmetadata"}}onloadedmetadata="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onloadedmetadata"}}onloadedmetadata="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onloadedmetadata_(values ...string) Attribute { return Onloadedmetadata(nil, values...) } func Onloadstart(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onloadstart" } if len(templs) == 0 { attr.Templ = `{{define "Onloadstart"}}onloadstart="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onloadstart"}}onloadstart="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onloadstart_(values ...string) Attribute { return Onloadstart(nil, values...) } func Onmousedown(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onmousedown" } if len(templs) == 0 { attr.Templ = `{{define "Onmousedown"}}onmousedown="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onmousedown"}}onmousedown="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onmousedown_(values ...string) Attribute { return Onmousedown(nil, values...) } func Onmousemove(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onmousemove" } if len(templs) == 0 { attr.Templ = `{{define "Onmousemove"}}onmousemove="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onmousemove"}}onmousemove="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onmousemove_(values ...string) Attribute { return Onmousemove(nil, values...) } func Onmouseout(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onmouseout" } if len(templs) == 0 { attr.Templ = `{{define "Onmouseout"}}onmouseout="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onmouseout"}}onmouseout="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onmouseout_(values ...string) Attribute { return Onmouseout(nil, values...) } func Onmouseover(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onmouseover" } if len(templs) == 0 { attr.Templ = `{{define "Onmouseover"}}onmouseover="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onmouseover"}}onmouseover="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onmouseover_(values ...string) Attribute { return Onmouseover(nil, values...) } func Onmouseup(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onmouseup" } if len(templs) == 0 { attr.Templ = `{{define "Onmouseup"}}onmouseup="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onmouseup"}}onmouseup="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onmouseup_(values ...string) Attribute { return Onmouseup(nil, values...) } func Onmousewheel(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onmousewheel" } if len(templs) == 0 { attr.Templ = `{{define "Onmousewheel"}}onmousewheel="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onmousewheel"}}onmousewheel="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onmousewheel_(values ...string) Attribute { return Onmousewheel(nil, values...) } func Onoffline(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onoffline" } if len(templs) == 0 { attr.Templ = `{{define "Onoffline"}}onoffline="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onoffline"}}onoffline="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onoffline_(values ...string) Attribute { return Onoffline(nil, values...) } func Ononline(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ononline" } if len(templs) == 0 { attr.Templ = `{{define "Ononline"}}ononline="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ononline"}}ononline="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ononline_(values ...string) Attribute { return Ononline(nil, values...) } func Onpagehide(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onpagehide" } if len(templs) == 0 { attr.Templ = `{{define "Onpagehide"}}onpagehide="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onpagehide"}}onpagehide="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onpagehide_(values ...string) Attribute { return Onpagehide(nil, values...) } func Onpageshow(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onpageshow" } if len(templs) == 0 { attr.Templ = `{{define "Onpageshow"}}onpageshow="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onpageshow"}}onpageshow="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onpageshow_(values ...string) Attribute { return Onpageshow(nil, values...) } func Onpaste(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onpaste" } if len(templs) == 0 { attr.Templ = `{{define "Onpaste"}}onpaste="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onpaste"}}onpaste="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onpaste_(values ...string) Attribute { return Onpaste(nil, values...) } func Onpause(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onpause" } if len(templs) == 0 { attr.Templ = `{{define "Onpause"}}onpause="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onpause"}}onpause="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onpause_(values ...string) Attribute { return Onpause(nil, values...) } func Onplay(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onplay" } if len(templs) == 0 { attr.Templ = `{{define "Onplay"}}onplay="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onplay"}}onplay="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onplay_(values ...string) Attribute { return Onplay(nil, values...) } func Onplaying(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onplaying" } if len(templs) == 0 { attr.Templ = `{{define "Onplaying"}}onplaying="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onplaying"}}onplaying="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onplaying_(values ...string) Attribute { return Onplaying(nil, values...) } func Onpopstate(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onpopstate" } if len(templs) == 0 { attr.Templ = `{{define "Onpopstate"}}onpopstate="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onpopstate"}}onpopstate="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onpopstate_(values ...string) Attribute { return Onpopstate(nil, values...) } func Onprogress(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onprogress" } if len(templs) == 0 { attr.Templ = `{{define "Onprogress"}}onprogress="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onprogress"}}onprogress="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onprogress_(values ...string) Attribute { return Onprogress(nil, values...) } func Onratechange(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onratechange" } if len(templs) == 0 { attr.Templ = `{{define "Onratechange"}}onratechange="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onratechange"}}onratechange="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onratechange_(values ...string) Attribute { return Onratechange(nil, values...) } func Onreset(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onreset" } if len(templs) == 0 { attr.Templ = `{{define "Onreset"}}onreset="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onreset"}}onreset="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onreset_(values ...string) Attribute { return Onreset(nil, values...) } func Onresize(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onresize" } if len(templs) == 0 { attr.Templ = `{{define "Onresize"}}onresize="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onresize"}}onresize="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onresize_(values ...string) Attribute { return Onresize(nil, values...) } func Onscroll(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onscroll" } if len(templs) == 0 { attr.Templ = `{{define "Onscroll"}}onscroll="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onscroll"}}onscroll="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onscroll_(values ...string) Attribute { return Onscroll(nil, values...) } func Onsearch(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onsearch" } if len(templs) == 0 { attr.Templ = `{{define "Onsearch"}}onsearch="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onsearch"}}onsearch="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onsearch_(values ...string) Attribute { return Onsearch(nil, values...) } func Onseeked(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onseeked" } if len(templs) == 0 { attr.Templ = `{{define "Onseeked"}}onseeked="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onseeked"}}onseeked="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onseeked_(values ...string) Attribute { return Onseeked(nil, values...) } func Onseeking(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onseeking" } if len(templs) == 0 { attr.Templ = `{{define "Onseeking"}}onseeking="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onseeking"}}onseeking="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onseeking_(values ...string) Attribute { return Onseeking(nil, values...) } func Onselect(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onselect" } if len(templs) == 0 { attr.Templ = `{{define "Onselect"}}onselect="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onselect"}}onselect="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onselect_(values ...string) Attribute { return Onselect(nil, values...) } func Onstalled(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onstalled" } if len(templs) == 0 { attr.Templ = `{{define "Onstalled"}}onstalled="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onstalled"}}onstalled="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onstalled_(values ...string) Attribute { return Onstalled(nil, values...) } func Onstorage(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onstorage" } if len(templs) == 0 { attr.Templ = `{{define "Onstorage"}}onstorage="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onstorage"}}onstorage="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onstorage_(values ...string) Attribute { return Onstorage(nil, values...) } func Onsubmit(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onsubmit" } if len(templs) == 0 { attr.Templ = `{{define "Onsubmit"}}onsubmit="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onsubmit"}}onsubmit="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onsubmit_(values ...string) Attribute { return Onsubmit(nil, values...) } func Onsuspend(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onsuspend" } if len(templs) == 0 { attr.Templ = `{{define "Onsuspend"}}onsuspend="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onsuspend"}}onsuspend="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onsuspend_(values ...string) Attribute { return Onsuspend(nil, values...) } func Ontimeupdate(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ontimeupdate" } if len(templs) == 0 { attr.Templ = `{{define "Ontimeupdate"}}ontimeupdate="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ontimeupdate"}}ontimeupdate="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ontimeupdate_(values ...string) Attribute { return Ontimeupdate(nil, values...) } func Ontoggle(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Ontoggle" } if len(templs) == 0 { attr.Templ = `{{define "Ontoggle"}}ontoggle="{{.}}"{{end}}` } else { attr.Templ = `{{define "Ontoggle"}}ontoggle="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Ontoggle_(values ...string) Attribute { return Ontoggle(nil, values...) } func Onunload(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onunload" } if len(templs) == 0 { attr.Templ = `{{define "Onunload"}}onunload="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onunload"}}onunload="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onunload_(values ...string) Attribute { return Onunload(nil, values...) } func Onvolumechange(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onvolumechange" } if len(templs) == 0 { attr.Templ = `{{define "Onvolumechange"}}onvolumechange="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onvolumechange"}}onvolumechange="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onvolumechange_(values ...string) Attribute { return Onvolumechange(nil, values...) } func Onwaiting(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onwaiting" } if len(templs) == 0 { attr.Templ = `{{define "Onwaiting"}}onwaiting="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onwaiting"}}onwaiting="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onwaiting_(values ...string) Attribute { return Onwaiting(nil, values...) } func Onwheel(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Onwheel" } if len(templs) == 0 { attr.Templ = `{{define "Onwheel"}}onwheel="{{.}}"{{end}}` } else { attr.Templ = `{{define "Onwheel"}}onwheel="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Onwheel_(values ...string) Attribute { return Onwheel(nil, values...) } func Open(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Open" } if len(templs) == 0 { attr.Templ = `{{define "Open"}}open="{{.}}"{{end}}` } else { attr.Templ = `{{define "Open"}}open="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Open_(values ...string) Attribute { return Open(nil, values...) } func Optimum(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Optimum" } if len(templs) == 0 { attr.Templ = `{{define "Optimum"}}optimum="{{.}}"{{end}}` } else { attr.Templ = `{{define "Optimum"}}optimum="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Optimum_(values ...string) Attribute { return Optimum(nil, values...) } func Pattern(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Pattern" } if len(templs) == 0 { attr.Templ = `{{define "Pattern"}}pattern="{{.}}"{{end}}` } else { attr.Templ = `{{define "Pattern"}}pattern="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Pattern_(values ...string) Attribute { return Pattern(nil, values...) } func Placeholder(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Placeholder" } if len(templs) == 0 { attr.Templ = `{{define "Placeholder"}}placeholder="{{.}}"{{end}}` } else { attr.Templ = `{{define "Placeholder"}}placeholder="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Placeholder_(values ...string) Attribute { return Placeholder(nil, values...) } func Poster(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Poster" } if len(templs) == 0 { attr.Templ = `{{define "Poster"}}poster="{{.}}"{{end}}` } else { attr.Templ = `{{define "Poster"}}poster="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Poster_(values ...string) Attribute { return Poster(nil, values...) } func Preload(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Preload" } if len(templs) == 0 { attr.Templ = `{{define "Preload"}}preload="{{.}}"{{end}}` } else { attr.Templ = `{{define "Preload"}}preload="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Preload_(values ...string) Attribute { return Preload(nil, values...) } func Readonly(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Readonly" } if len(templs) == 0 { attr.Templ = `{{define "Readonly"}}readonly="{{.}}"{{end}}` } else { attr.Templ = `{{define "Readonly"}}readonly="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Readonly_(values ...string) Attribute { return Readonly(nil, values...) } func Rel(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Rel" } if len(templs) == 0 { attr.Templ = `{{define "Rel"}}rel="{{.}}"{{end}}` } else { attr.Templ = `{{define "Rel"}}rel="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Rel_(values ...string) Attribute { return Rel(nil, values...) } func Required(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Required" } if len(templs) == 0 { attr.Templ = `{{define "Required"}}required="{{.}}"{{end}}` } else { attr.Templ = `{{define "Required"}}required="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Required_(values ...string) Attribute { return Required(nil, values...) } func Reversed(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Reversed" } if len(templs) == 0 { attr.Templ = `{{define "Reversed"}}reversed="{{.}}"{{end}}` } else { attr.Templ = `{{define "Reversed"}}reversed="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Reversed_(values ...string) Attribute { return Reversed(nil, values...) } func Role(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Role" } if len(templs) == 0 { attr.Templ = `{{define "Role"}}role="{{.}}"{{end}}` } else { attr.Templ = `{{define "Role"}}role="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Role_(values ...string) Attribute { return Role(nil, values...) } func Rows(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Rows" } if len(templs) == 0 { attr.Templ = `{{define "Rows"}}rows="{{.}}"{{end}}` } else { attr.Templ = `{{define "Rows"}}rows="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Rows_(values ...string) Attribute { return Rows(nil, values...) } func Rowspan(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Rowspan" } if len(templs) == 0 { attr.Templ = `{{define "Rowspan"}}rowspan="{{.}}"{{end}}` } else { attr.Templ = `{{define "Rowspan"}}rowspan="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Rowspan_(values ...string) Attribute { return Rowspan(nil, values...) } func Sandbox(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Sandbox" } if len(templs) == 0 { attr.Templ = `{{define "Sandbox"}}sandbox="{{.}}"{{end}}` } else { attr.Templ = `{{define "Sandbox"}}sandbox="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Sandbox_(values ...string) Attribute { return Sandbox(nil, values...) } func Scope(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Scope" } if len(templs) == 0 { attr.Templ = `{{define "Scope"}}scope="{{.}}"{{end}}` } else { attr.Templ = `{{define "Scope"}}scope="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Scope_(values ...string) Attribute { return Scope(nil, values...) } func Selected(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Selected" } if len(templs) == 0 { attr.Templ = `{{define "Selected"}}selected="{{.}}"{{end}}` } else { attr.Templ = `{{define "Selected"}}selected="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Selected_(values ...string) Attribute { return Selected(nil, values...) } func Shape(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Shape" } if len(templs) == 0 { attr.Templ = `{{define "Shape"}}shape="{{.}}"{{end}}` } else { attr.Templ = `{{define "Shape"}}shape="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Shape_(values ...string) Attribute { return Shape(nil, values...) } func Size(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Size" } if len(templs) == 0 { attr.Templ = `{{define "Size"}}size="{{.}}"{{end}}` } else { attr.Templ = `{{define "Size"}}size="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Size_(values ...string) Attribute { return Size(nil, values...) } func Sizes(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Sizes" } if len(templs) == 0 { attr.Templ = `{{define "Sizes"}}sizes="{{.}}"{{end}}` } else { attr.Templ = `{{define "Sizes"}}sizes="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Sizes_(values ...string) Attribute { return Sizes(nil, values...) } func Span(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Span" } if len(templs) == 0 { attr.Templ = `{{define "Span"}}span="{{.}}"{{end}}` } else { attr.Templ = `{{define "Span"}}span="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Span_(values ...string) Attribute { return Span(nil, values...) } func Spellcheck(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Spellcheck" } if len(templs) == 0 { attr.Templ = `{{define "Spellcheck"}}spellcheck="{{.}}"{{end}}` } else { attr.Templ = `{{define "Spellcheck"}}spellcheck="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Spellcheck_(values ...string) Attribute { return Spellcheck(nil, values...) } func Src(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Src" } if len(templs) == 0 { attr.Templ = `{{define "Src"}}src="{{.}}"{{end}}` } else { attr.Templ = `{{define "Src"}}src="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Src_(values ...string) Attribute { return Src(nil, values...) } func Srcdoc(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Srcdoc" } if len(templs) == 0 { attr.Templ = `{{define "Srcdoc"}}srcdoc="{{.}}"{{end}}` } else { attr.Templ = `{{define "Srcdoc"}}srcdoc="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Srcdoc_(values ...string) Attribute { return Srcdoc(nil, values...) } func Srclang(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Srclang" } if len(templs) == 0 { attr.Templ = `{{define "Srclang"}}srclang="{{.}}"{{end}}` } else { attr.Templ = `{{define "Srclang"}}srclang="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Srclang_(values ...string) Attribute { return Srclang(nil, values...) } func Srcset(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Srcset" } if len(templs) == 0 { attr.Templ = `{{define "Srcset"}}srcset="{{.}}"{{end}}` } else { attr.Templ = `{{define "Srcset"}}srcset="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Srcset_(values ...string) Attribute { return Srcset(nil, values...) } func Start(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Start" } if len(templs) == 0 { attr.Templ = `{{define "Start"}}start="{{.}}"{{end}}` } else { attr.Templ = `{{define "Start"}}start="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Start_(values ...string) Attribute { return Start(nil, values...) } func Step(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Step" } if len(templs) == 0 { attr.Templ = `{{define "Step"}}step="{{.}}"{{end}}` } else { attr.Templ = `{{define "Step"}}step="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Step_(values ...string) Attribute { return Step(nil, values...) } func Style(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Style" } if len(templs) == 0 { attr.Templ = `{{define "Style"}}style="{{.}}"{{end}}` } else { attr.Templ = `{{define "Style"}}style="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Style_(values ...string) Attribute { return Style(nil, values...) } func Tabindex(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Tabindex" } if len(templs) == 0 { attr.Templ = `{{define "Tabindex"}}tabindex="{{.}}"{{end}}` } else { attr.Templ = `{{define "Tabindex"}}tabindex="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Tabindex_(values ...string) Attribute { return Tabindex(nil, values...) } func Target(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Target" } if len(templs) == 0 { attr.Templ = `{{define "Target"}}target="{{.}}"{{end}}` } else { attr.Templ = `{{define "Target"}}target="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Target_(values ...string) Attribute { return Target(nil, values...) } func Title(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Title" } if len(templs) == 0 { attr.Templ = `{{define "Title"}}title="{{.}}"{{end}}` } else { attr.Templ = `{{define "Title"}}title="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Title_(values ...string) Attribute { return Title(nil, values...) } func Translate(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Translate" } if len(templs) == 0 { attr.Templ = `{{define "Translate"}}translate="{{.}}"{{end}}` } else { attr.Templ = `{{define "Translate"}}translate="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Translate_(values ...string) Attribute { return Translate(nil, values...) } func Type(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Type" } if len(templs) == 0 { attr.Templ = `{{define "Type"}}type="{{.}}"{{end}}` } else { attr.Templ = `{{define "Type"}}type="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Type_(values ...string) Attribute { return Type(nil, values...) } func Usemap(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Usemap" } if len(templs) == 0 { attr.Templ = `{{define "Usemap"}}usemap="{{.}}"{{end}}` } else { attr.Templ = `{{define "Usemap"}}usemap="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Usemap_(values ...string) Attribute { return Usemap(nil, values...) } func Value(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Value" } if len(templs) == 0 { attr.Templ = `{{define "Value"}}value="{{.}}"{{end}}` } else { attr.Templ = `{{define "Value"}}value="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Value_(values ...string) Attribute { return Value(nil, values...) } func Width(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Width" } if len(templs) == 0 { attr.Templ = `{{define "Width"}}width="{{.}}"{{end}}` } else { attr.Templ = `{{define "Width"}}width="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Width_(values ...string) Attribute { return Width(nil, values...) } func Wrap(data interface{}, templs ...string) Attribute { attr := Attribute{ Data: data, Name: "Wrap" } if len(templs) == 0 { attr.Templ = `{{define "Wrap"}}wrap="{{.}}"{{end}}` } else { attr.Templ = `{{define "Wrap"}}wrap="` + strings.Join(templs, " ") + `"{{end}}` } return attr } func Wrap_(values ...string) Attribute { return Wrap(nil, values...) }
attributes/attributes.go
0.735262
0.513973
attributes.go
starcoder
package clustering import ( "errors" "github.com/tddhit/golearn/base" "gonum.org/v1/gonum/mat" "gonum.org/v1/gonum/stat" "gonum.org/v1/gonum/stat/distmv" "math" "math/rand" ) var ( NoTrainingDataError = errors.New("You need to Fit() before you can Predict()") InsufficientComponentsError = errors.New("Estimation requires at least one component") InsufficientDataError = errors.New("Estimation requires n_obs >= n_comps") ) type ExpectationMaximization struct { n_comps int eps float64 Params Params fitted bool attrs []base.Attribute } type Params struct { Means *mat.Dense Covs []*mat.SymDense } // Number of Gaussians to fit in the mixture func NewExpectationMaximization(n_comps int) (*ExpectationMaximization, error) { if n_comps < 1 { return nil, InsufficientComponentsError } return &ExpectationMaximization{n_comps: n_comps, eps: 0.001}, nil } // Fit method - generates the component parameters (means and covariance matrices) func (em *ExpectationMaximization) Fit(inst base.FixedDataGrid) error { // Numeric Attrs attrs := base.NonClassAttributes(inst) attrSpecs := base.ResolveAttributes(inst, attrs) _, n_obs := inst.Size() n_feats := len(attrs) if n_obs < em.n_comps { return InsufficientDataError } // Build the input matrix X := mat.NewDense(n_obs, n_feats, nil) inst.MapOverRows(attrSpecs, func(row [][]byte, i int) (bool, error) { for j, r := range row { X.Set(i, j, base.UnpackBytesToFloat(r)) } return true, nil }) // Initialize the parameter distance dist := math.Inf(1) // Initialize the parameters var p Params p.Means = initMeans(X, em.n_comps, n_feats) p.Covs = initCovariance(em.n_comps, n_feats) // Iterate until convergence for { if dist < em.eps { break } y_new := expectation(X, p, em.n_comps) p_new := maximization(X, y_new, p, em.n_comps) dist = distance(p, p_new) p = p_new } em.fitted = true em.attrs = attrs em.Params = p return nil } // Predict method - returns a ClusterMap of components and row ids func (em *ExpectationMaximization) Predict(inst base.FixedDataGrid) (ClusterMap, error) { if !em.fitted { return nil, NoTrainingDataError } _, n_obs := inst.Size() n_feats := len(em.attrs) // Numeric attrs attrSpecs := base.ResolveAttributes(inst, em.attrs) // Build the input matrix X := mat.NewDense(n_obs, n_feats, nil) inst.MapOverRows(attrSpecs, func(row [][]byte, i int) (bool, error) { for j, r := range row { X.Set(i, j, base.UnpackBytesToFloat(r)) } return true, nil }) // Vector of predictions preds := estimateLogProb(X, em.Params, em.n_comps) clusterMap := make(map[int][]int) for ix, pred := range vecToInts(preds) { clusterMap[pred] = append(clusterMap[pred], ix) } return ClusterMap(clusterMap), nil } // EM-specific functions // Expectation step func expectation(X *mat.Dense, p Params, n_comps int) mat.Vector { y_new := estimateLogProb(X, p, n_comps) return y_new } // Maximization step func maximization(X *mat.Dense, y mat.Vector, p Params, n_comps int) Params { _, n_feats := X.Dims() // Initialize the new parameters var p_new Params p_new.Means = mat.NewDense(n_comps, n_feats, nil) p_new.Covs = make([]*mat.SymDense, n_comps) // Update the parameters for k := 0; k < n_comps; k++ { X_yk := where(X, y, k) n_obs, _ := X_yk.Dims() covs_k_reg := mat.NewSymDense(n_feats, nil) if n_obs <= 1 { p_new.Means.SetRow(k, p.Means.RawRowView(k)) covs_k_reg = p.Covs[k] } else if n_obs < n_feats { p_new.Means.SetRow(k, means(X_yk)) covs_k_reg = shrunkCovariance(X_yk) } else { p_new.Means.SetRow(k, means(X_yk)) stat.CovarianceMatrix(covs_k_reg, X_yk, nil) } p_new.Covs[k] = covs_k_reg } return p_new } // Creates mat.Vector of most likely component for each observation func estimateLogProb(X *mat.Dense, p Params, n_comps int) mat.Vector { n_obs, n_feats := X.Dims() // Cache the component Gaussians var N = make([]*distmv.Normal, n_comps) for k := 0; k < n_comps; k++ { dst := make([]float64, n_feats) means := mat.Row(dst, k, p.Means) dist, ok := distmv.NewNormal(means, p.Covs[k], nil) if !ok { panic("Cannot create Normal!") } N[k] = dist } // Compute the component probabilities y_new := mat.NewVecDense(n_obs, nil) for i := 0; i < n_obs; i++ { max_ix := 0 max_pr := math.Inf(-1) x := X.RawRowView(i) for k := 0; k < n_comps; k++ { pr := N[k].LogProb(x) if pr > max_pr { max_ix = k max_pr = pr } } y_new.SetVec(i, float64(max_ix)) } return y_new } // Returns a symmetric matrix with variance on the diagonal func shrunkCovariance(X *mat.Dense) *mat.SymDense { n_obs, n_feats := X.Dims() size := int(math.Pow(float64(n_feats), 2)) covs := mat.NewSymDense(n_feats, make([]float64, size, size)) for j := 0; j < n_feats; j++ { // compute the variance for the jth feature var points []float64 for i := 0; i < n_obs; i++ { points = append(points, X.At(i, j)) } variance := stat.Variance(points, nil) // set the jth diagonal entry to the variance covs.SetSym(j, j, variance) } return covs } // Creates an n_comps x n_feats array of means func initMeans(X *mat.Dense, n_comps, n_feats int) *mat.Dense { var results []float64 for k := 0; k < n_comps; k++ { for j := 0; j < n_feats; j++ { v := X.ColView(j) min := vectorMin(v) max := vectorMax(v) r := min + rand.Float64()*(max-min) results = append(results, r) } } means := mat.NewDense(n_comps, n_feats, results) return means } // Creates a n_comps array of n_feats x n_feats mat.Symmetrics func initCovariance(n_comps, n_feats int) []*mat.SymDense { var result []*mat.SymDense floats := identity(n_feats) for k := 0; k < n_comps; k++ { matrix := mat.NewSymDense(n_feats, floats) result = append(result, matrix) } return result } // Compues the euclidian distance between two parameters func distance(p Params, p_new Params) float64 { dist := 0.0 n_obs, n_feats := p.Means.Dims() for i := 0; i < n_obs; i++ { means_i := p.Means.RawRowView(i) means_new_i := p_new.Means.RawRowView(i) for j := 0; j < n_feats; j++ { dist += math.Pow((means_i[j] - means_new_i[j]), 2) } } return math.Sqrt(dist) } // Helper functions // Finds the min value of a mat.Vector func vectorMin(v mat.Vector) float64 { n_obs, _ := v.Dims() min := v.At(0, 0) for i := 0; i < n_obs; i++ { if v.At(i, 0) < min { min = v.At(i, 0) } } return min } // Find the max value of a mat.Vector func vectorMax(v mat.Vector) float64 { n_obs, _ := v.Dims() max := v.At(0, 0) for i := 0; i < n_obs; i++ { if v.At(i, 0) > max { max = v.At(i, 0) } } return max } // Converts a mat.Vector to an array of ints func vecToInts(v mat.Vector) []int { n_obs, _ := v.Dims() var ints = make([]int, n_obs) for i := 0; i < n_obs; i++ { ints[i] = int(v.At(i, 0)) } return ints } // Computes column Means of a mat.Dense func means(X *mat.Dense) []float64 { n_obs, n_feats := X.Dims() var result []float64 for j := 0; j < n_feats; j++ { sum_j := 0.0 for i := 0; i < n_obs; i++ { sum_j = sum_j + X.At(i, j) } mean := (sum_j / float64(n_obs)) result = append(result, mean) } return result } // Subest a mat.Dense with rows matching a target value func where(X *mat.Dense, y mat.Vector, target int) *mat.Dense { n_obs, n_feats := X.Dims() var result []float64 rows := 0 for i := 0; i < n_obs; i++ { if int(y.At(i, 0)) == target { for j := 0; j < n_feats; j++ { result = append(result, X.At(i, j)) } rows++ } } X_i := mat.NewDense(rows, n_feats, result) return X_i } // Returns values for a square array with ones on the main diagonal func identity(N int) []float64 { var results []float64 for i := 0; i < N; i++ { for j := 0; j < N; j++ { if j == i { results = append(results, 1) } else { results = append(results, 0) } } } return results } // Generates an array of values for symmetric matrix func symVals(M int, v float64) []float64 { var results []float64 for i := 0; i < M*M; i++ { results = append(results, v) } return results }
clustering/em.go
0.75183
0.400573
em.go
starcoder
package features // We want features that give the index of the nth occurrence of each letter in our alphabet in the // input string. For example, for the string "edcba" we would have: // firstOccurrences == [4, 3, 2, 1, 0, ...] ('a' occurs in 4th pos, 'b' in 3rd pos, etc.) // When the character doesn't occur in the string we say that the nth occurrence is \infty // (analogous to stopping-times), which in our case would be 255. So to complete the above example // we would have: // firstOccurrences == [4, 3, 2, 1, 0, 255, 255, ...] import "strconv" //---------------------------------------------------------------------------------------------------- // Provide featureSetConfig type occurrencePositions struct { DirectionIsHead bool NumberOfOccurrences byte } func (o occurrencePositions) Size() int32 { return int32(alphabet_size) * int32(o.NumberOfOccurrences) } func (o occurrencePositions) FromStringInPlace(input string, featureArray []byte) { // trim string to max length sNormalized := []byte(normalizeString(input)) sLength := len(sNormalized) if sLength >= 256 { if o.DirectionIsHead { sNormalized = sNormalized[:256] } else { sNormalized = sNormalized[sLength-256:] } } // first set everything to infinity for i := 0; i < len(featureArray); i++ { featureArray[i] = 255 } // function to update the feature-array if we've seen the ith byte fewer than NumberOfOccurrences times allCharPositions := make([]byte, alphabet_size) processChar := func(posInString int, ch byte) { charIndex := char_map[ch] charPosition := allCharPositions[charIndex] if charPosition < o.NumberOfOccurrences { featureArray[(charPosition*byte(alphabet_size))+byte(charIndex)] = byte(posInString) allCharPositions[charIndex] += 1 } } // iterate either forwards or backwards if o.DirectionIsHead { for i, ch := range sNormalized { processChar(i, ch) } } else { trimmedSMaxPos := len(sNormalized) - 1 // we're counting upwards but i will now be the position from the right: for i := 0; i <= trimmedSMaxPos; i++ { ch := sNormalized[trimmedSMaxPos-i] processChar(i, ch) } } } func deserializeOccurrencePositionsMap(confMap map[string]string) (config featureSetConfig, ok bool) { var directionIsHead bool if directionIsHeadStr, ok := confMap["direction_is_head"]; !ok { return nil, false } else { directionIsHead = (directionIsHeadStr == "true") } if numOccurrencesStr, ok := confMap["num_occurrences"]; !ok { return nil, false } else if numOccurrences, err := strconv.Atoi(numOccurrencesStr); err != nil { return nil, false } else { return occurrencePositions{directionIsHead, byte(numOccurrences)}, true } }
features/occurrence_positions.go
0.637369
0.544801
occurrence_positions.go
starcoder
package par import( "github.com/dedis/kyber" "github.com/dedis/kyber/proof" ) // Map over a slices of Elgamal Ciphers with the given parallel for-loop. func MapElgamalCiphers(loop ParallelForLoop, f func([2]kyber.Point, [2]kyber.Point, kyber.Point) ([2]kyber.Point, [2]kyber.Point, proof.Prover), x [][2]kyber.Point, y [][2]kyber.Point, Y kyber.Point, n int) ([][2]kyber.Point, [][2]kyber.Point, []proof.Prover) { xbar := make([][2]kyber.Point, n) ybar := make([][2]kyber.Point, n) proof := make([]proof.Prover, n) loop(0, uint(n), 1, func(id uint) { xbar[id], ybar[id], proof[id] = f(x[id], y[id], Y) }) return xbar, ybar, proof } // Convenience function: use MapElgamalCiphers with a chunking parallel for loop. func MapElgamalCiphersChunked(f func([2]kyber.Point, [2]kyber.Point, kyber.Point) ([2]kyber.Point, [2]kyber.Point, proof.Prover), x [][2]kyber.Point, y [][2]kyber.Point, Y kyber.Point, n int) ([][2]kyber.Point, [][2]kyber.Point, []proof.Prover) { return MapElgamalCiphers(ForChunked, f, x, y, Y, n) } // Map over a slice of Strings with the given parallel for-loop. func MapString(loop ParallelForLoop, f func(uint) string, l int) []string { result := make([]string, l) loop(0, uint(l), 1, func(idx uint) { result[idx] = f(idx) }) return result } // Convenience function: use MapString with a chunking parallel for loop. func MapStringChunked(f func(uint) string, l int) []string { return MapString(ForChunked, f, l) } // Convenience function: use MapString with an interleaving parallel for loop. func MapStringInterleaved(f func(uint) string, l int) []string { return MapString(ForInterleaved, f, l) } // Map over a slice of float64s with the given parallel for-loop. func MapFloat64(loop ParallelForLoop, f func(float64) float64, l []float64) []float64 { result := make([]float64, len(l)) loop(0, uint(len(l)), 1, func(idx uint) { result[idx] = f(l[idx]) }) return result } // Convenience function: use MapFloat64 with a chunking parallel for loop. func MapFloat64Chunked(f func(float64) float64, l []float64) []float64 { return MapFloat64(ForChunked, f, l) } // Convenience function: use MapFloat64 with an interleaving parallel for loop. func MapFloat64Interleaved(f func(float64) float64, l []float64) []float64 { return MapFloat64(ForInterleaved, f, l) } func max(l, r uint) uint { if l > r { return l } return r } func min(l, r uint) uint { if l < r { return l } return r }
par/map.go
0.786705
0.568116
map.go
starcoder
package renderer import ( "errors" "fmt" "image" "github.com/nfnt/resize" "github.com/nightmarlin/murum/layout" "github.com/nightmarlin/murum/provider" ) // BasicRendererOption allows changes to the basic renderer. type BasicRendererOption func(b *basicRenderer) error // BasicWithInterpolationFunc sets the interpolation function used by the basic renderer to resize // images to fit the bounding rectangle of a layout.L region func BasicWithInterpolationFunc(intFunc resize.InterpolationFunction) BasicRendererOption { return func(b *basicRenderer) error { b.interpolationFunc = intFunc return nil } } // BasicWithAspectRatioIgnored allows images to be scaled to fit the bounding rectangle of a // layout.L region without preserving their aspect ratio. This reduces the number of calculations // done at the cost of skewing images func BasicWithAspectRatioIgnored() BasicRendererOption { return func(b *basicRenderer) error { b.ignoreAspectRatio = true return nil } } // NewBasic creates and returns a new basicRenderer that implements the Renderer interface. The // renderer simply fills in regions of the layout.L with images passed to it and returns the image. // If there aren't enough images, some sections of the returned image will have the default color. // Note: If BasicWithInterpolationFunc is not passed as an option, the basicRenderer will use the // resize.Lanczos3 algorithm to resize images to fit the bounding rectangles. func NewBasic(opts ...BasicRendererOption) (*basicRenderer, error) { res := &basicRenderer{interpolationFunc: resize.Lanczos3} for i := range opts { err := opts[i](res) if err != nil { return nil, fmt.Errorf("failed to init basic renderer: %w", err) } } return res, nil } type basicRenderer struct { interpolationFunc resize.InterpolationFunction ignoreAspectRatio bool } func (b *basicRenderer) resize(i image.Image, bound image.Rectangle) image.Image { if b.ignoreAspectRatio { return resize.Resize(uint(bound.Dx()), uint(bound.Dy()), i, b.interpolationFunc) } scaledRect := ScaleRect(i.Bounds(), bound) return resize.Resize(uint(scaledRect.Dx()), uint(scaledRect.Dy()), i, b.interpolationFunc) } func (b *basicRenderer) Render(l *layout.L, ai []provider.AlbumInfo) (image.Image, error) { if l == nil { return nil, errors.New("cannot render from nil layout") } var ( resImg = image.NewRGBA64(l.Bounds) n = 0 ) for _, section := range l.Points { if len(ai) <= n { break } var ( sectBounds = GetBounds(section) sectImg = b.resize(ai[n].Art, sectBounds) // Center image xCenteredOffset = (sectImg.Bounds().Dx() - sectBounds.Dx()) / 2 yCenteredOffset = (sectImg.Bounds().Dy() - sectBounds.Dy()) / 2 ) for _, p := range section { col := sectImg.At( p.X-sectBounds.Min.X+xCenteredOffset, p.Y-sectBounds.Min.Y+yCenteredOffset, ) resImg.Set(p.X, p.Y, col) } n += 1 } return resImg, nil }
renderer/basic.go
0.796055
0.447219
basic.go
starcoder
// This package provides a graph data struture // and graph functionality using ObjMetadata as // vertices in the graph. package graph import ( "sort" "sigs.k8s.io/cli-utils/pkg/object" "sigs.k8s.io/cli-utils/pkg/object/validation" "sigs.k8s.io/cli-utils/pkg/ordering" ) // Graph is contains a directed set of edges, implemented as // an adjacency list (map key is "from" vertex, slice are "to" // vertices). type Graph struct { // map "from" vertex -> list of "to" vertices edges map[object.ObjMetadata]object.ObjMetadataSet // map "to" vertex -> list of "from" vertices reverseEdges map[object.ObjMetadata]object.ObjMetadataSet } // New returns a pointer to an empty Graph data structure. func New() *Graph { g := &Graph{} g.edges = make(map[object.ObjMetadata]object.ObjMetadataSet) g.reverseEdges = make(map[object.ObjMetadata]object.ObjMetadataSet) return g } // AddVertex adds an ObjMetadata vertex to the graph, with // an initial empty set of edges from added vertex. func (g *Graph) AddVertex(v object.ObjMetadata) { if _, exists := g.edges[v]; !exists { g.edges[v] = object.ObjMetadataSet{} } if _, exists := g.reverseEdges[v]; !exists { g.reverseEdges[v] = object.ObjMetadataSet{} } } // edgeMapKeys returns a sorted set of unique vertices in the graph. func edgeMapKeys(edgeMap map[object.ObjMetadata]object.ObjMetadataSet) object.ObjMetadataSet { keys := make(object.ObjMetadataSet, len(edgeMap)) i := 0 for k := range edgeMap { keys[i] = k i++ } sort.Sort(ordering.SortableMetas(keys)) return keys } // AddEdge adds a edge from one ObjMetadata vertex to another. The // direction of the edge is "from" -> "to". func (g *Graph) AddEdge(from object.ObjMetadata, to object.ObjMetadata) { // Add "from" vertex if it doesn't already exist. if _, exists := g.edges[from]; !exists { g.edges[from] = object.ObjMetadataSet{} } if _, exists := g.reverseEdges[from]; !exists { g.reverseEdges[from] = object.ObjMetadataSet{} } // Add "to" vertex if it doesn't already exist. if _, exists := g.edges[to]; !exists { g.edges[to] = object.ObjMetadataSet{} } if _, exists := g.reverseEdges[to]; !exists { g.reverseEdges[to] = object.ObjMetadataSet{} } // Add edge "from" -> "to" if it doesn't already exist // into the adjacency list. if !g.isAdjacent(from, to) { g.edges[from] = append(g.edges[from], to) g.reverseEdges[to] = append(g.reverseEdges[to], from) } } // edgeMapToList returns a sorted slice of directed graph edges (vertex pairs). func edgeMapToList(edgeMap map[object.ObjMetadata]object.ObjMetadataSet) []Edge { edges := []Edge{} for from, toList := range edgeMap { for _, to := range toList { edge := Edge{From: from, To: to} edges = append(edges, edge) } } sort.Sort(SortableEdges(edges)) return edges } // isAdjacent returns true if an edge "from" vertex -> "to" vertex exists; // false otherwise. func (g *Graph) isAdjacent(from object.ObjMetadata, to object.ObjMetadata) bool { // If "from" vertex does not exist, it is impossible edge exists; return false. if _, exists := g.edges[from]; !exists { return false } // Iterate through adjacency list to see if "to" vertex is adjacent. for _, vertex := range g.edges[from] { if vertex == to { return true } } return false } // Size returns the number of vertices in the graph. func (g *Graph) Size() int { return len(g.edges) } // removeVertex removes the passed vertex as well as any edges into the vertex. func removeVertex(edges map[object.ObjMetadata]object.ObjMetadataSet, r object.ObjMetadata) { // First, remove the object from all adjacency lists. for v, adj := range edges { edges[v] = adj.Remove(r) } // Finally, remove the vertex delete(edges, r) } // Dependencies returns the objects that this object depends on. func (g *Graph) Dependencies(from object.ObjMetadata) object.ObjMetadataSet { edgesFrom, exists := g.edges[from] if !exists { return nil } c := make(object.ObjMetadataSet, len(edgesFrom)) copy(c, edgesFrom) return c } // Dependents returns the objects that depend on this object. func (g *Graph) Dependents(to object.ObjMetadata) object.ObjMetadataSet { edgesTo, exists := g.reverseEdges[to] if !exists { return nil } c := make(object.ObjMetadataSet, len(edgesTo)) copy(c, edgesTo) return c } // Sort returns the ordered set of vertices after a topological sort. func (g *Graph) Sort() ([]object.ObjMetadataSet, error) { // deep copy edge map to avoid destructive sorting edges := make(map[object.ObjMetadata]object.ObjMetadataSet, len(g.edges)) for vertex, deps := range g.edges { c := make(object.ObjMetadataSet, len(deps)) copy(c, deps) edges[vertex] = c } sorted := []object.ObjMetadataSet{} for len(edges) > 0 { // Identify all the leaf vertices. leafVertices := object.ObjMetadataSet{} for v, adj := range edges { if len(adj) == 0 { leafVertices = append(leafVertices, v) } } // No leaf vertices means cycle in the directed graph, // where remaining edges define the cycle. if len(leafVertices) == 0 { // Error can be ignored, so return the full set list return sorted, validation.NewError(CyclicDependencyError{ Edges: edgeMapToList(edges), }, edgeMapKeys(edges)...) } // Remove all edges to leaf vertices. for _, v := range leafVertices { removeVertex(edges, v) } sorted = append(sorted, leafVertices) } return sorted, nil }
pkg/object/graph/graph.go
0.762424
0.415729
graph.go
starcoder
package tree import ( "math/rand" ) func (root *node) get(key int) (string, bool) { if root == nil { return "", false } if root.key == key { return root.value, true } else if key < root.key { return root.left.get(key) } else { return root.right.get(key) } } func (root *node) put(key int, v string) *node { if root == nil { return &node{key: key, value: v, n: 1} } if key == root.key { root.value = v } else if key < root.key { root.left = root.left.put(key, v) } else { root.right = root.right.put(key, v) } root.n = root.left.size() + root.right.size() + 1 return root } func (root *node) size() int { if root == nil { return 0 } return root.n } //all sequences of node array that can generate this tree //get left and right child seq,weave every pair of them,prepend prefix func (root *node) Sequences() [][]*node { result := make([][]*node, 0) if root == nil { result = append(result, make([]*node, 0)) return result } prefix := make([]*node, 1) prefix[0] = root leftSeqes := root.left.Sequences() rightSeqes := root.right.Sequences() for _, leftSeq := range leftSeqes { for _, rightSeq := range rightSeqes { weaved := make([][]*node, 0) weave(leftSeq, rightSeq, prefix, &weaved) result = append(result, weaved...) } } return result } func weave(first, second, prefix []*node, results *[][]*node) { if len(first) == 0 || len(second) == 0 { result := append([]*node(nil), prefix...) result = append(result, first...) result = append(result, second...) *results = append(*results, result) return } p := append(prefix, first[0]) firstClone := append([]*node(nil), first...) firstClone = append(firstClone[:0], firstClone[1:]...) weave(firstClone, second, p, results) p = append(prefix, second[0]) secondClone := append([]*node(nil), second...) secondClone = append(secondClone[:0], secondClone[1:]...) weave(first, secondClone, p, results) } func (root *node) RandomNode() *node { if root == nil { return nil } leftSize := root.left.size() randIndex := rand.Intn(root.size()) if randIndex == leftSize { return root } if randIndex < leftSize { return root.left.ithNode(randIndex) } else { return root.right.ithNode(randIndex - leftSize - 1) } } func (root *node) ithNode(index int) *node { if root == nil { return nil } leftSize := root.left.size() if index == leftSize { return root } if index < leftSize { return root.left.ithNode(index) } else { return root.right.ithNode(index - (leftSize + 1)) } }
tree/binary_search.go
0.590543
0.442817
binary_search.go
starcoder
package testing_ import ( "errors" ) // LinkToExampleObjectOnFieldChildren links ExampleObject to ExampleObject on the fields ExampleObject.Children and ExampleObject.Parents func (l *ExampleObject) LinkToExampleObjectOnFieldChildren(targets ...*ExampleObject) error { if targets == nil { return errors.New("start and end can not be nil") } for _, target := range targets { if l.Children == nil { l.Children = make([]*ExampleObject, 1, 1) l.Children[0] = target } else { l.Children = append(l.Children, target) } target.Parents = l } return nil } //UnlinkFromExampleObjectOnFieldChildren unlinks ExampleObject from ExampleObject on the fields ExampleObject.Children and ExampleObject.Parents func (l *ExampleObject) UnlinkFromExampleObjectOnFieldChildren(targets ...*ExampleObject) error { if targets == nil { return errors.New("start and end can not be nil") } for _, target := range targets { if l.Children != nil { for i, unlinkTarget := range l.Children { if unlinkTarget.UUID == target.UUID { a := &l.Children (*a)[i] = (*a)[len(*a)-1] (*a)[len(*a)-1] = nil *a = (*a)[:len(*a)-1] break } } } target.Parents = nil } return nil } //LinkToExampleObjectOnFieldParents links ExampleObject to ExampleObject on the fields ExampleObject.Parents and ExampleObject.Children func (l *ExampleObject) LinkToExampleObjectOnFieldParents(target *ExampleObject) error { if target == nil { return errors.New("start and end can not be nil") } l.Parents = target if target.Children == nil { target.Children = make([]*ExampleObject, 1, 1) target.Children[0] = l } else { target.Children = append(target.Children, l) } return nil } //UnlinkFromExampleObjectOnFieldParents unlinks ExampleObject from ExampleObject on the fields ExampleObject.Parents and ExampleObject.Children func (l *ExampleObject) UnlinkFromExampleObjectOnFieldParents(target *ExampleObject) error { if target == nil { return errors.New("start and end can not be nil") } l.Parents = nil if target.Children != nil { for i, unlinkTarget := range target.Children { if unlinkTarget.UUID == l.UUID { a := &target.Children (*a)[i] = (*a)[len(*a)-1] (*a)[len(*a)-1] = nil *a = (*a)[:len(*a)-1] break } } } return nil } // LinkToExampleObject2OnFieldSpecial links ExampleObject to ExampleObject2 on the fields ExampleObject.Special and ExampleObject2.Special. // note this uses the special edge SpecialEdge func (l *ExampleObject) LinkToExampleObject2OnFieldSpecial(target *ExampleObject2, edge *SpecialEdge) error { if target == nil { return errors.New("start and end can not be nil") } if edge == nil { return errors.New("edge can not be nil") } err := edge.SetStartNode(target) if err != nil { return err } err = edge.SetEndNode(l) if err != nil { return err } l.Special = edge if target.Special == nil { target.Special = make([]*SpecialEdge, 1, 1) target.Special[0] = edge } else { target.Special = append(target.Special, edge) } return nil } // UnlinkFromExampleObject2OnFieldSpecial unlinks ExampleObject from ExampleObject2 on the fields ExampleObject.Special and ExampleObject2.Special. // also note this uses the special edge SpecialEdge func (l *ExampleObject) UnlinkFromExampleObject2OnFieldSpecial(target *ExampleObject2) error { if target == nil { return errors.New("start and end can not be nil") } l.Special = nil if target.Special != nil { for i, unlinkTarget := range target.Special { obj := unlinkTarget.GetEndNode() checkObj, ok := obj.(*ExampleObject) if !ok { return errors.New("unable to cast unlinkTarget to [*ExampleObject]") } if checkObj.UUID == l.UUID { a := &target.Special (*a)[i] = (*a)[len(*a)-1] (*a)[len(*a)-1] = nil *a = (*a)[:len(*a)-1] break } } } return nil } // LinkToExampleObject2OnFieldChildren2 links ExampleObject2 to ExampleObject2 on the fields ExampleObject2.Children2 and ExampleObject2.Parents2 func (l *ExampleObject2) LinkToExampleObject2OnFieldChildren2(targets ...*ExampleObject2) error { if targets == nil { return errors.New("start and end can not be nil") } for _, target := range targets { if l.Children2 == nil { l.Children2 = make([]*ExampleObject2, 1, 1) l.Children2[0] = target } else { l.Children2 = append(l.Children2, target) } target.Parents2 = l } return nil } //UnlinkFromExampleObject2OnFieldChildren2 unlinks ExampleObject2 from ExampleObject2 on the fields ExampleObject2.Children2 and ExampleObject2.Parents2 func (l *ExampleObject2) UnlinkFromExampleObject2OnFieldChildren2(targets ...*ExampleObject2) error { if targets == nil { return errors.New("start and end can not be nil") } for _, target := range targets { if l.Children2 != nil { for i, unlinkTarget := range l.Children2 { if unlinkTarget.UUID == target.UUID { a := &l.Children2 (*a)[i] = (*a)[len(*a)-1] (*a)[len(*a)-1] = nil *a = (*a)[:len(*a)-1] break } } } target.Parents2 = nil } return nil } //LinkToExampleObject2OnFieldParents2 links ExampleObject2 to ExampleObject2 on the fields ExampleObject2.Parents2 and ExampleObject2.Children2 func (l *ExampleObject2) LinkToExampleObject2OnFieldParents2(target *ExampleObject2) error { if target == nil { return errors.New("start and end can not be nil") } l.Parents2 = target if target.Children2 == nil { target.Children2 = make([]*ExampleObject2, 1, 1) target.Children2[0] = l } else { target.Children2 = append(target.Children2, l) } return nil } //UnlinkFromExampleObject2OnFieldParents2 unlinks ExampleObject2 from ExampleObject2 on the fields ExampleObject2.Parents2 and ExampleObject2.Children2 func (l *ExampleObject2) UnlinkFromExampleObject2OnFieldParents2(target *ExampleObject2) error { if target == nil { return errors.New("start and end can not be nil") } l.Parents2 = nil if target.Children2 != nil { for i, unlinkTarget := range target.Children2 { if unlinkTarget.UUID == l.UUID { a := &target.Children2 (*a)[i] = (*a)[len(*a)-1] (*a)[len(*a)-1] = nil *a = (*a)[:len(*a)-1] break } } } return nil } // LinkToExampleObjectOnFieldSpecial links ExampleObject2 to ExampleObject on the fields ExampleObject2.Special and ExampleObject.Special. // note this uses the special edge SpecialEdge func (l *ExampleObject2) LinkToExampleObjectOnFieldSpecial(target *ExampleObject, edge *SpecialEdge) error { if target == nil { return errors.New("start and end can not be nil") } if edge == nil { return errors.New("edge can not be nil") } err := edge.SetStartNode(l) if err != nil { return err } err = edge.SetEndNode(target) if err != nil { return err } if l.Special == nil { l.Special = make([]*SpecialEdge, 1, 1) l.Special[0] = edge } else { l.Special = append(l.Special, edge) } target.Special = edge return nil } // UnlinkFromExampleObjectOnFieldSpecial unlinks ExampleObject2 from ExampleObject on the fields ExampleObject2.Special and ExampleObject.Special. // also note this uses the special edge SpecialEdge func (l *ExampleObject2) UnlinkFromExampleObjectOnFieldSpecial(target *ExampleObject) error { if target == nil { return errors.New("start and end can not be nil") } if l.Special != nil { for i, unlinkTarget := range l.Special { obj := unlinkTarget.GetEndNode() checkObj, ok := obj.(*ExampleObject) if !ok { return errors.New("unable to cast unlinkTarget to [*ExampleObject]") } if checkObj.UUID == target.UUID { a := &l.Special (*a)[i] = (*a)[len(*a)-1] (*a)[len(*a)-1] = nil *a = (*a)[:len(*a)-1] break } } } target.Special = nil return nil }
testing_/linking.go
0.757346
0.547646
linking.go
starcoder
package neptune import ( "context" "fmt" "strconv" "github.com/pkg/errors" "github.com/ONSdigital/dp-graph/v2/models" "github.com/ONSdigital/dp-graph/v2/neptune/query" ) /* GetCodeDatasets searches the database for datasets that are associated with the given code list, code, and code list edition. Specifically those that satisfy all of: 1) code lists that match the requested code list ID. 2) code lists of the requested edition. 3) codes that match the requested code value. 4) datasets that are related to qualifying codes by *inDataset* edges. 5) datasets that have the *isPublished* state true. Each such result from the database (potentially) has the properties: - dimensionName (what the dataset calls this dimension) - datasetEdition - version The results however include all permutations of dimensionName and datasetEdition - BUT ONLY CITES the most recent dataset *version* of those found for that permutation. */ func (n *NeptuneDB) GetCodeDatasets(ctx context.Context, codeListID, edition string, code string) (*models.Datasets, error) { // Emit the query and parse the responses. qry := fmt.Sprintf(query.GetCodeDatasets, codeListID, edition, code) responses, err := n.getStringList(qry) if err != nil { return nil, errors.Wrapf(err, "Gremlin GetCodeDatasets failed: %q", qry) } // Isolate the individual records from the flattened response. // [['dim', 'edition', 'version', 'datasetID'], ['dim', 'edition', ...]] responseRecords, err := createCodeDatasetRecords(responses) if err != nil { return nil, errors.Wrap(err, "Cannot create records.") } // Build data structure to capture only latest dataset versions. latestVersionMaps, err := buildLatestVersionMaps(responseRecords) if err != nil { return nil, errors.Wrap(err, "Cannot isolate latest versions.") } // Package up the model-ised response. response := buildResponse(latestVersionMaps, code, codeListID) return response, nil } /* createCodeDatasetRecords splits a list of strings into clumps of 4 */ func createCodeDatasetRecords(responses []string) ([][]string, error) { const valuesPerRecord = 4 return createRecords(responses, valuesPerRecord) } // These (nested) maps track the latest version cited by any combination // of dimensionName, dataset edition, and datasetID. // They are all keyed on strings and the nested assembly can be accessed // like this: // latestVersion = foo[datasetID][dimension][edition] type editionToLatestVersion map[string]int type dim2Edition map[string]editionToLatestVersion type datasetID2Dim map[string]dim2Edition /* buildLatestVersionMaps consumes a list of records such as ["dimName1", "datasetEdition1", "version4", "datasetID3"], and builds a datasetID2Dim structure based on the latest versions available for each combination of dimension name, dataset edition, and datasetID. */ func buildLatestVersionMaps(responseRecords [][]string) (datasetID2Dim, error) { did2Dim := datasetID2Dim{} for _, record := range responseRecords { dimensionName := record[0] datasetEdition := record[1] versionStr := record[2] datasetID := record[3] versionInt, err := strconv.Atoi(versionStr) if err != nil { return nil, errors.Wrapf(err, "Cannot cast version (%q) to int", versionStr) } if _, ok := did2Dim[datasetID]; !ok { did2Dim[datasetID] = dim2Edition{} } if _, ok := did2Dim[datasetID][dimensionName]; !ok { did2Dim[datasetID][dimensionName] = editionToLatestVersion{} } latestKnownV, ok := did2Dim[datasetID][dimensionName][datasetEdition] if !ok || latestKnownV < versionInt { did2Dim[datasetID][dimensionName][datasetEdition] = versionInt } } return did2Dim, nil } /* buildResponse is capable of consuming a datasetID2Dim data structure, along with a few other query parameters, and from these, building the data structure model hierchy required by the GetCodeDatasets API method. */ func buildResponse(did2Dim datasetID2Dim, code string, codeListID string) *models.Datasets { datasets := &models.Datasets{ Items: []models.Dataset{}, } for datasetID, dim2E := range did2Dim { for dimensionName, e2v := range dim2E { dataset := models.Dataset{ ID: datasetID, DimensionLabel: dimensionName, Editions: []models.DatasetEdition{}, } for datasetEdition, version := range e2v { edition := models.DatasetEdition{ ID: datasetEdition, CodeListID: codeListID, LatestVersion: version, } dataset.Editions = append(dataset.Editions, edition) } datasets.Items = append(datasets.Items, dataset) } } return datasets }
neptune/codelistsdataset.go
0.570331
0.429489
codelistsdataset.go
starcoder
package golang import ( "errors" "fmt" "github.com/JosephNaberhaus/go-delta-sync/agnostic" "github.com/JosephNaberhaus/go-delta-sync/agnostic/blocks/types" "github.com/JosephNaberhaus/go-delta-sync/agnostic/blocks/value" . "github.com/dave/jennifer/jen" "strings" ) type Implementation struct { packageName string code []Code } type BodyImplementation struct { receiverName string block *Statement } func (g *Implementation) Add(c ...Code) { g.code = append(g.code, c...) } func (g *BodyImplementation) Add(c ...Code) { g.block.Add(lines(c...)) } func (g *Implementation) Write(fileName string) { jenFile := NewFile(g.packageName) jenFile.Add(lines(g.code...)) err := jenFile.Save(fileName + ".go") if err != nil { panic(err) } } func (g *Implementation) Model(modelName string, fields ...agnostic.Field) { modelStructFields := make([]Code, 0) for _, field := range fields { modelStructFields = append(modelStructFields, Id(field.Name).Add(resolveType(field.Type))) } g.Add(Type().Id(string(modelName)).Struct(modelStructFields...)) } func (g *Implementation) Enum(name string, values ...string) { g.Add(Type().Id(name).Int()) enumValues := make([]Code, 0) for i, v := range values { valueName := name + "_" + v if i == 0 { enumValues = append(enumValues, Id(valueName).Id(name).Op(":=").Iota()) } else { enumValues = append(enumValues, Id(valueName)) } } g.Add(Const().Defs(enumValues...)) } func (g *Implementation) Method(modelName, methodName string, parameters ...agnostic.Field) agnostic.BodyImplementation { receiverName := strings.ToLower(modelName[:1]) block := Null() parametersCode := make([]Code, 0) for _, param := range parameters { parametersCode = append(parametersCode, Id(param.Name).Add(resolveType(param.Type))) } g.Add(Func().Params(Id(receiverName).Op("*").Id(modelName)).Id(methodName).Params(parametersCode...).Block(block)) return &BodyImplementation{ receiverName: receiverName, block: block, } } func (g *Implementation) ReturnMethod(modelName, methodName string, returnType types.Any, parameters ...agnostic.Field) agnostic.BodyImplementation { receiverName := strings.ToLower(modelName[:1]) block := Null() parametersCode := make([]Code, 0) for _, param := range parameters { parametersCode = append(parametersCode, Id(param.Name).Add(resolveType(param.Type))) } g.Add(Func().Params(Id(receiverName).Op("*").Id(modelName)).Id(methodName).Params(parametersCode...).Add(resolveType(returnType)).Block(block)) return &BodyImplementation{ receiverName: receiverName, block: block, } } func (g *BodyImplementation) Assign(assignee, assigned value.Any) { g.Add(resolveValue(assignee, g).Op("=").Add(resolveValue(assigned, g))) } func (g *BodyImplementation) Declare(name string, value value.Any) { g.Add(Id(name).Op(":=").Add(resolveValue(value, g))) } func (g *BodyImplementation) AppendValue(array, value value.Any) { g.Add(resolveValue(array, g).Op("=").Append(resolveValue(array, g), resolveValue(value, g))) } func (g *BodyImplementation) AppendArray(array, valueArray value.Any) { g.Add(resolveValue(array, g).Op("=").Append(resolveValue(array, g), resolveValue(valueArray, g).Op("..."))) } func (g *BodyImplementation) RemoveValue(array, index value.Any) { g.Add(resolveValue(array, g).Op("=").Append( resolveValue(array, g).Index(Op(":").Add(resolveValue(index, g))), resolveValue(array, g).Index(resolveValue(index, g).Op("+").Lit(1).Op(":")).Op("..."), )) } func (g *BodyImplementation) MapPut(mapValue, key, value value.Any) { g.Add(resolveValue(mapValue, g).Index(resolveValue(key, g)).Op("=").Add(resolveValue(value, g))) } func (g *BodyImplementation) MapDelete(mapValue, key value.Any) { g.Add(Delete(resolveValue(mapValue, g), resolveValue(key, g))) } func (g *BodyImplementation) ForEach(array value.Any, indexName, valueName string) agnostic.BodyImplementation { var forLoopParameter *Statement if indexName == "" { if valueName == "" { forLoopParameter = List() } else { forLoopParameter = List(Id("_"), Id(valueName)).Op(":=") } } else { if valueName == "" { forLoopParameter = List(Id(indexName)).Op(":=") } else { forLoopParameter = List(Id(indexName), Id(valueName)).Op(":=") } } block := Null() g.Add(For(forLoopParameter.Range().Add(resolveValue(array, g))).Block(block)) return &BodyImplementation{ receiverName: g.receiverName, block: block, } } func (g *BodyImplementation) If(value value.Any) agnostic.BodyImplementation { block := Null() g.Add(If(resolveValue(value, g)).Block(block)) return &BodyImplementation{ receiverName: g.receiverName, block: block, } } func (g *BodyImplementation) IfElse(value value.Any) (trueBody, falseBody agnostic.BodyImplementation) { trueBlock, falseBlock := Null(), Null() g.Add(If(resolveValue(value, g)).Block(trueBlock).Else().Block(falseBlock)) trueBodyImplementation := &BodyImplementation{ receiverName: g.receiverName, block: trueBlock, } falseBodyImplementation := &BodyImplementation{ receiverName: g.receiverName, block: falseBlock, } return trueBodyImplementation, falseBodyImplementation } func (g *BodyImplementation) Return(value value.Any) { g.Add(Return(resolveValue(value, g))) } func NewImplementation(args map[string]string) agnostic.Implementation { packageName, ok := args["package"] if !ok { panic(errors.New("no package name supplied")) } return &Implementation{ code: make([]Code, 0), packageName: packageName, } } func resolveType(any types.Any) *Statement { switch t := any.(type) { case types.Base: return resolveBaseType(t) case types.Model: return Id(t.ModelName()) case types.Array: return Index().Add(resolveType(t.Element())) case types.Map: return Map(resolveType(t.Key())).Add(resolveType(t.Value())) case types.Pointer: return Op("*").Add(resolveType(t.Value())) default: panic(errors.New(fmt.Sprintf("unkown type %T", t))) } } func resolveBaseType(base types.Base) *Statement { switch base { case types.BaseBool: return Bool() case types.BaseInt: return Int() case types.BaseInt32: return Int32() case types.BaseInt64: return Int64() case types.BaseFloat32: return Float32() case types.BaseFloat64: return Float64() case types.BaseString: return String() default: panic(errors.New("unknown base type " + string(base))) } } // Convert a value interface into its representation into Go code form func resolveValue(any value.Any, optionalContext ...*BodyImplementation) *Statement { var context *BodyImplementation if len(optionalContext) == 0 && any.IsMethodDependent() { panic(errors.New("no context provided for method dependent value")) } else if len(optionalContext) == 1 { context = optionalContext[0] } else if len(optionalContext) > 1 { panic(errors.New("multiple body contexts provided when only 0 or 1 is allowed")) } switch v := any.(type) { case value.Null: return Nil() case value.String: return Lit(v.Value()) case value.Int: return Lit(v.Value()) case value.Float: return Lit(v.Value()) case value.Array: elements := make([]Code, 0, len(v.Elements())) for _, element := range v.Elements() { elements = append(elements, resolveValue(element, context)) } return Index().Add(resolveType(v.ElementType())).Values(elements...) case value.Map: elements := make([]Code, 0, len(v.Elements())) for _, element := range v.Elements() { elements = append(elements, resolveValue(element.Key()).Op(":").Add(resolveValue(element.Value()))) } return Map(resolveType(v.KeyType())).Add(resolveType(v.ValueType())).Values(elements...) case value.OwnField: return Id(context.receiverName).Op(".").Add(resolveValue(v.Field(), context)) case value.Id: return Id(v.Name()) case value.ModelField: return Id(v.ModelName()).Op(".").Add(resolveValue(v.Field(), context)) case value.ArrayElement: return resolveValue(v.Array(), context).Index(resolveValue(v.Index(), context)) case value.MapElement: return resolveValue(v.Map(), context).Index(resolveValue(v.Key(), context)) case value.Combined: return resolveValue(v.Left(), context).Op(v.Operator().Value()).Add(resolveValue(v.Right(), context)) case value.IntToString: return Qual("strconv", "Itoa").Call(resolveValue(v.IntValue(), context)) default: panic(errors.New(fmt.Sprintf("uknown type %T", v))) } } // Helper method to split a set of statements into lines of code func lines(statements ...Code) Code { if len(statements) == 0 { return Null() } combined := Add(statements[0]).Line() for _, statement := range statements[1:] { combined = combined.Line().Add(statement) } return combined }
agnostic/targets/golang/implementation.go
0.539711
0.435601
implementation.go
starcoder
package geometry import "github.com/tidwall/boxtree/d2" // DefaultIndex are the minumum number of points required before it makes // sense to index the segments. // 64 seems to be the sweet spot const DefaultIndex = 64 // Series is just a series of points with utilities for efficiently accessing // segments from rectangle queries, making stuff like point-in-polygon lookups // very quick. type Series interface { Rect() Rect Empty() bool Convex() bool Clockwise() bool NumPoints() int NumSegments() int PointAt(index int) Point SegmentAt(index int) Segment Search(rect Rect, iter func(seg Segment, index int) bool) Index() interface{} } func seriesCopyPoints(series Series) []Point { points := make([]Point, series.NumPoints()) for i := 0; i < len(points); i++ { points[i] = series.PointAt(i) } return points } // baseSeries is a concrete type containing all that is needed to make a Series. type baseSeries struct { closed bool // points create a closed shape clockwise bool // points move clockwise convex bool // points create a convex shape rect Rect // minumum bounding rectangle points []Point // original points tree *d2.BoxTree // segment tree. } // makeSeries returns a processed baseSeries. func makeSeries(points []Point, copyPoints, closed bool, index int) baseSeries { var series baseSeries series.closed = closed if copyPoints { series.points = make([]Point, len(points)) copy(series.points, points) } else { series.points = points } if index != 0 && len(points) >= int(index) { series.tree = new(d2.BoxTree) } series.convex, series.rect, series.clockwise = processPoints(points, closed, series.tree) return series } // Index ... func (series *baseSeries) Index() interface{} { if series.tree == nil { return nil } return series.tree } // Clockwise ... func (series *baseSeries) Clockwise() bool { return series.clockwise } func (series *baseSeries) Move(deltaX, deltaY float64) Series { points := make([]Point, len(series.points)) for i := 0; i < len(series.points); i++ { points[i].X = series.points[i].X + deltaX points[i].Y = series.points[i].Y + deltaY } nseries := makeSeries(points, false, series.closed, 0) if series.tree != nil { nseries.buildTree() } return &nseries } // Empty returns true if the series does not take up space. func (series *baseSeries) Empty() bool { if series == nil { return true } return (series.closed && len(series.points) < 3) || len(series.points) < 2 } // Rect returns the series rectangle func (series *baseSeries) Rect() Rect { return series.rect } // Convex returns true if the points create a convex loop or linestring func (series *baseSeries) Convex() bool { return series.convex } // Closed return true if the shape is closed func (series *baseSeries) Closed() bool { return series.closed } // NumPoints returns the number of points in the series func (series *baseSeries) NumPoints() int { return len(series.points) } // PointAt returns the point at index func (series *baseSeries) PointAt(index int) Point { return series.points[index] } // Search finds a searches for segments that intersect the provided rectangle func (series *baseSeries) Search(rect Rect, iter func(seg Segment, idx int) bool) { if series.tree == nil { n := series.NumSegments() for i := 0; i < n; i++ { seg := series.SegmentAt(i) if seg.Rect().IntersectsRect(rect) { if !iter(seg, i) { return } } } } else { series.tree.Search( []float64{rect.Min.X, rect.Min.Y}, []float64{rect.Max.X, rect.Max.Y}, func(_, _ []float64, value interface{}) bool { index := value.(int) var seg Segment seg.A = series.points[index] if series.closed && index == len(series.points)-1 { seg.B = series.points[0] } else { seg.B = series.points[index+1] } if !iter(seg, index) { return false } return true }, ) } } // NumSegments ... func (series *baseSeries) NumSegments() int { if series.closed { if len(series.points) < 3 { return 0 } if series.points[len(series.points)-1] == series.points[0] { return len(series.points) - 1 } return len(series.points) } if len(series.points) < 2 { return 0 } return len(series.points) - 1 } // SegmentAt ... func (series *baseSeries) SegmentAt(index int) Segment { var seg Segment seg.A = series.points[index] if index == len(series.points)-1 { seg.B = series.points[0] } else { seg.B = series.points[index+1] } return seg } func (series *baseSeries) buildTree() { if series.tree == nil { series.tree = new(d2.BoxTree) processPoints(series.points, series.closed, series.tree) } } // processPoints tests if the ring is convex, calculates the outer // rectangle, and inserts segments into a boxtree in one pass. func processPoints(points []Point, closed bool, tree *d2.BoxTree) ( convex bool, rect Rect, clockwise bool, ) { if (closed && len(points) < 3) || len(points) < 2 { return } var concave bool var dir int var a, b, c Point var segCount int var cwc float64 if closed { segCount = len(points) } else { segCount = len(points) - 1 } for i := 0; i < len(points); i++ { // process the segments for tree insertion if tree != nil && i < segCount { var seg Segment seg.A = points[i] if closed && i == len(points)-1 { if seg.A == points[0] { break } seg.B = points[0] } else { seg.B = points[i+1] } rect := seg.Rect() tree.Insert( []float64{rect.Min.X, rect.Min.Y}, []float64{rect.Max.X, rect.Max.Y}, i) } // process the rectangle inflation if i == 0 { rect = Rect{points[i], points[i]} } else { if points[i].X < rect.Min.X { rect.Min.X = points[i].X } else if points[i].X > rect.Max.X { rect.Max.X = points[i].X } if points[i].Y < rect.Min.Y { rect.Min.Y = points[i].Y } else if points[i].Y > rect.Max.Y { rect.Max.Y = points[i].Y } } // gather some point positions for concave and clockwise detection a = points[i] if i == len(points)-1 { b = points[0] c = points[1] } else if i == len(points)-2 { b = points[i+1] c = points[0] } else { b = points[i+1] c = points[i+2] } // process the clockwise detection cwc += (b.X - a.X) * (b.Y + a.Y) // process the convex calculation if concave { continue } zCrossProduct := (b.X-a.X)*(c.Y-b.Y) - (b.Y-a.Y)*(c.X-b.X) if dir == 0 { if zCrossProduct < 0 { dir = -1 } else if zCrossProduct > 0 { dir = 1 } } else if zCrossProduct < 0 { if dir == 1 { concave = true } } else if zCrossProduct > 0 { if dir == -1 { concave = true } } } return !concave, rect, cwc > 0 }
vendor/github.com/tidwall/geojson/geometry/series.go
0.758868
0.646125
series.go
starcoder
package seriesgen import ( "math/rand" "time" "github.com/prometheus/prometheus/tsdb/labels" ) type sample struct { T int64 V float64 } // SeriesSet contains a set of series. type SeriesSet interface { Next() bool At() Series Err() error } // Series exposes a single time series. type Series interface { // Labels returns the complete set of labels identifying the series. Labels() labels.Labels // Iterator returns a new iterator of the data of the series. // TODO(bwplotka): Consider moving this to tsdb.SeriesIterator if required. This means adding `Seek` method. Iterator() SeriesIterator } // SeriesIterator iterates over the data of a time series. // Simplified version of github.com/prometheus/prometheus/tsdb.SeriesIterator type SeriesIterator interface { // At returns the current timestamp/value pair. At() (t int64, v float64) // Next advances the iterator by one. Next() bool // Err returns current error. Err() error } type SeriesGen struct { SeriesIterator lset labels.Labels } func NewSeriesGen(lset labels.Labels, si SeriesIterator) *SeriesGen { return &SeriesGen{ SeriesIterator: si, lset: lset, } } func (s *SeriesGen) Labels() labels.Labels { return s.lset } func (s *SeriesGen) Iterator() SeriesIterator { return s } var _ SeriesIterator = &GaugeGen{} var _ SeriesIterator = &CounterGen{} var _ SeriesIterator = &ValGen{} type Characteristics struct { Jitter float64 `yaml:"jitter"` ScrapeInterval time.Duration `yaml:"scrapeInterval"` ChangeInterval time.Duration `yaml:"changeInterval"` Max float64 `yaml:"max"` Min float64 `yaml:"min"` } type GaugeGen struct { changeInterval time.Duration interval time.Duration maxTime, minTime int64 min, max, jitter float64 v float64 mod float64 init bool elapsed int64 random *rand.Rand } func NewGaugeGen(random *rand.Rand, mint, maxt int64, opts Characteristics) *GaugeGen { return &GaugeGen{ changeInterval: opts.ChangeInterval, interval: opts.ScrapeInterval, max: opts.Max, min: opts.Min, minTime: mint, maxTime: maxt, jitter: opts.Jitter, random: random, } } func (g *GaugeGen) Next() bool { if g.minTime > g.maxTime { return false } defer func() { g.minTime += int64(g.interval.Seconds() * 1000) g.elapsed += int64(g.interval.Seconds() * 1000) }() if !g.init { g.v = g.min + g.random.Float64()*((g.max-g.min)+1) g.init = true } // Technically only mod changes. if g.jitter > 0 && g.elapsed >= int64(g.changeInterval.Seconds()*1000) { g.mod = (g.random.Float64() - 0.5) * g.jitter g.elapsed = 0 } return true } func (g *GaugeGen) At() (t int64, v float64) { return g.minTime, g.v + g.mod } func (g *GaugeGen) Err() error { return nil } // TODO(bwplotka): Improve. Does not work well (: Too naive. // Add resets etc. type CounterGen struct { maxTime, minTime int64 min, max, jitter float64 interval time.Duration changeInterval time.Duration rateInterval time.Duration v float64 init bool buff []sample lastVal float64 elapsed int64 random *rand.Rand } func NewCounterGen(random *rand.Rand, mint, maxt int64, opts Characteristics) *CounterGen { return &CounterGen{ changeInterval: opts.ChangeInterval, interval: opts.ScrapeInterval, max: opts.Max, min: opts.Min, minTime: mint, maxTime: maxt, jitter: opts.Jitter, random: random, rateInterval: 5 * time.Minute, } } func (g *CounterGen) Next() bool { defer func() { g.elapsed += int64(g.interval.Seconds() * 1000) }() if g.init && len(g.buff) == 0 { return false } if len(g.buff) > 0 { // Pop front. g.buff = g.buff[1:] if len(g.buff) > 0 { return true } } if !g.init { g.v = g.min + g.random.Float64()*((g.max-g.min)+1) g.init = true } var mod float64 if g.jitter > 0 && g.elapsed >= int64(g.changeInterval.Seconds()*1000) { mod = (g.random.Float64() - 0.5) * g.jitter if mod > g.v { mod = g.v } g.elapsed = 0 } // Distribute goalV into multiple rateInterval/interval increments. comps := make([]float64, int64(g.rateInterval/g.interval)) var sum float64 for i := range comps { comps[i] = g.random.Float64() sum += comps[i] } // That's the goal for our rate. x := g.v + mod/sum for g.minTime <= g.maxTime && len(comps) > 0 { g.lastVal += x * comps[0] comps = comps[1:] g.minTime += int64(g.interval.Seconds() * 1000) g.buff = append(g.buff, sample{T: g.minTime, V: g.lastVal}) } return len(g.buff) > 0 } func (g *CounterGen) At() (int64, float64) { return g.buff[0].T, g.buff[0].V } func (g *CounterGen) Err() error { return nil } type ValGen struct { interval time.Duration maxTime, minTime int64 min, max float64 v float64 random *rand.Rand } func NewValGen(random *rand.Rand, mint, maxt int64, opts Characteristics) *ValGen { return &ValGen{ interval: opts.ScrapeInterval, max: opts.Max, min: opts.Min, minTime: mint, maxTime: maxt, random: random, } } func (g *ValGen) Next() bool { if g.minTime > g.maxTime { return false } g.minTime += int64(g.interval.Seconds() * 1000) g.v = g.min + g.random.Float64()*((g.max-g.min)+1) return true } func (g *ValGen) At() (t int64, v float64) { return g.minTime, g.v } func (g *ValGen) Err() error { return nil }
pkg/seriesgen/seriesgen.go
0.601945
0.465205
seriesgen.go
starcoder
package nvm import ( "errors" "gonum.org/v1/gonum/mat" ) var ( _m *M _ Matrix = _m ) // M represents a dense matrix. type M struct { // O can be *mat.Dense or mat.Transpose. O mat.Matrix } // NewM creates a new matrix of rows `r` and cols `c`, // NewM will panic if `r <= 0` or `c <= 0`. func NewM(r, c int) *M { if r <= 0 { panic(ErrRows) } if c <= 0 { panic(ErrCols) } return &M{O: mat.NewDense(r, c, nil)} } // NewMShare creates a new matrix of rows `r` and cols `c` with `data`, // NewMShare will panic if `r <= 0` or `c <= 0` or `len(data) != r*c`. // Note: Slice both `M.Data` and `data` share a same underlying array. func NewMShare(r, c int, data []float64) *M { if r <= 0 { panic(ErrRows) } if c <= 0 { panic(ErrCols) } if len(data) != r*c { panic(ErrShape) } return &M{O: mat.NewDense(r, c, data)} } // NewMCopy creates a new matrix of rows `r` and cols `c` with `data`, // NewMCopy will panic if `r <= 0` or `c <= 0` or `len(data) != r*c`. func NewMCopy(r, c int, data []float64) *M { l := len(data) if r <= 0 { panic(ErrRows) } if c <= 0 { panic(ErrCols) } if l != r*c { panic(ErrShape) } newData := make([]float64, l) copy(newData, data) return &M{O: mat.NewDense(r, c, newData)} } // IsNaM reports whether `m` is "Not-a-Matrix". func (m *M) IsNaM() bool { if m.O == nil { return true } return false } // Dims returns the rows `r` and cols `c` of the matrix. func (m *M) Dims() (r, c int) { if m.IsNaM() { return 0, 0 } return m.O.Dims() } // At returns the element at position `i`th row and `j`th col. // At will panic if `i` or `j` is out of bounds. func (m *M) At(i, j int) float64 { if m.IsNaM() { panic(ErrNaM) } r, c := m.Dims() if i < 0 || i >= r { panic(ErrRowIndex) } if j < 0 || j >= c { panic(ErrColIndex) } return m.O.At(i, j) } // SetAt sets `f` to the element at position `i`th row and `j`th col. // SetAt will panic if `i` or `j` is out of bounds. func (m *M) SetAt(i, j int, f float64) Matrix { if m.IsNaM() { panic(ErrNaM) } r, c := m.Dims() if i < 0 || i >= r { panic(ErrRowIndex) } if j < 0 || j >= c { panic(ErrColIndex) } m.O.(*mat.Dense).Set(i, j, f) return m } // T returns the transpose of the matrix. func (m *M) T() Matrix { if m.IsNaM() { panic(ErrNaM) } return &M{O: m.O.T()} } // Det computes the determinant of the square matrix. func (m *M) Det() float64 { if m.IsNaM() { panic(ErrNaM) } if r, c := m.Dims(); r != c { panic(ErrShape) } return mat.Det(m.O) } // Inv computes the inverse of the square matrix. // Inv will panic if the square matrix is not invertible. func (m *M) Inv() Matrix { if m.IsNaM() { panic(ErrNaM) } r, c := m.Dims() if r != c { panic(ErrShape) } inv := mat.NewDense(r, c, nil) err := inv.Inverse(m.O) if err != nil { panic(errors.New(ErrInverse.Error() + " > " + err.Error())) } return &M{O: inv} // https://en.wikipedia.org/wiki/Invertible_matrix } // Add adds the matrices `x` and `y` element-wise, placing the result in the receiver. // Add will panic if the two matrices do not have the same shape. func (m *M) Add(x, y Matrix) Matrix { if !IsSameShape(x, y) || !IsSameShape(m, x) { panic(ErrShape) } /// *M & *M if x, ok := x.(*M); ok { if y, ok := y.(*M); ok { m.O.(*mat.Dense).Add(x.O, y.O) return m } } panic(ErrImpType) } // Sub subtracts the matrices `y` from `x` element-wise, placing the result in the receiver. // Sub will panic if the two matrices do not have the same shape. func (m *M) Sub(x, y Matrix) Matrix { if !IsSameShape(x, y) || !IsSameShape(m, x) { panic(ErrShape) } /// *M & *M if x, ok := x.(*M); ok { if y, ok := y.(*M); ok { m.O.(*mat.Dense).Sub(x.O, y.O) return m } } panic(ErrImpType) } // Scale multiplies the elements of `x` by `f`, placing the result in the receiver. func (m *M) Scale(f float64, x Matrix) Matrix { if !IsSameShape(m, x) { panic(ErrShape) } /// *M if x, ok := x.(*M); ok { m.O.(*mat.Dense).Scale(f, x.O) return m } panic(ErrImpType) } // DotMul performs element-wise multiplication of `x` and `y`, placing the result in the receiver. // DotMul will panic if the two matrices do not have the same shape. func (m *M) DotMul(x, y Matrix) Matrix { if !IsSameShape(x, y) || !IsSameShape(m, x) { panic(ErrShape) } /// *M & *M if x, ok := x.(*M); ok { if y, ok := y.(*M); ok { m.O.(*mat.Dense).MulElem(x.O, y.O) return m } } panic(ErrImpType) } // Mul computes the matrix product of `x` and `y`, placing the result in the receiver. // Mul will panic if the cols of `x` is not equal to the rows of `y`. // Note: Mul will panic if the receiver and the product do not have the same shape. func (m *M) Mul(x, y Matrix) Matrix { xr, xc := x.Dims() yr, yc := y.Dims() if xc != yr || x.IsNaM() || y.IsNaM() { panic(ErrShape) } mr, mc := m.Dims() if mr != xr || mc != yc { panic(ErrShape) } /// *M & *M if x, ok := x.(*M); ok { if y, ok := y.(*M); ok { m.O.(*mat.Dense).Mul(x.O, y.O) return m } } panic(ErrImpType) }
nvm/matrix_dense.go
0.819965
0.532911
matrix_dense.go
starcoder
package order import ( "fmt" "reflect" "github.com/posener/order/internal/reflectutil" ) // Fns is a list of order functions, used to check the order between two T types. type Fns []Fn // Fn represent an order function. type Fn struct { // fns are the 3-way functions, of the form func(T, T) int. fn func(lhs, rhs reflect.Value) int // t stores the type of the function (T). t reflectutil.T } // newFn converts a given function value to the a compare function. It also checks that the // function `f` is of the right form (func(T, T) int) and that T is of the given type t. If the // given type t is nil, it will be set to the type of the first argument of f. func newFn(f reflect.Value) (Fn, error) { if f.Kind() != reflect.Func { return Fn{}, fmt.Errorf("expected function") } tp := f.Type() if in := tp.NumIn(); in != 2 { return Fn{}, fmt.Errorf("expected function with 2 arguments, got: %d", in) } // If t is not set yet, set it to the first argument of the function. t1, err := reflectutil.New(tp.In(0)) if err != nil { return Fn{}, err } t2, err := reflectutil.New(tp.In(1)) if err != nil { return Fn{}, err } if t1.Type != t2.Type { return Fn{}, fmt.Errorf("expected same types, got: %v, %v", t1, t2) } if out := tp.NumOut(); out != 1 { return Fn{}, fmt.Errorf("expected function with a single return value, got: %d", out) } if out := tp.Out(0); out.Kind() != reflect.Int { return Fn{}, fmt.Errorf("expected function with int return value, got: %v", out) } return Fn{ fn: func(lhs, rhs reflect.Value) int { return f.Call([]reflect.Value{t1.Convert(lhs), t2.Convert(rhs)})[0].Interface().(int) }, t: t1, }, nil } // compare compares two values using the comparsion functions. It starts from the first comparison // function and continues as long as the returned value is 0. func (fns Fns) compare(lhs, rhs reflect.Value) int { for _, fn := range fns { if cmp := fn.fn(lhs, rhs); cmp != 0 { return cmp } } return 0 } // append a function to the function list, and check that its type agrees with the list type. func (fns Fns) append(fn Fn) (Fns, error) { if len(fns) != 0 { if !fns.check(fn.T()) { return nil, fmt.Errorf("all functions should have the same type, got: %v, %v", fns.T(), fn.T()) } } return append(fns, fn), nil } // T returns the type of the functions list T. func (fns Fns) T() reflect.Type { return fns[0].T() } // T returns the type of the function T. func (fn Fn) T() reflect.Type { return fn.t.Type } func (fns Fns) check(tp reflect.Type) bool { return fns[0].t.Check(tp) } // mustValue panics if the given value is not of type T. func (fns Fns) mustValue(v reflect.Value) reflect.Value { if tp := v.Type(); !fns.check(tp) { panic(fmt.Sprintf("bad value type: expected: %v, got: %v", fns.T(), tp)) } return v } // mustSlice panics if a given slice value is not a slice value or does not match T. func (fns Fns) mustSlice(slice reflect.Value) reflectutil.Slice { s, err := reflectutil.NewSlice(slice) if err != nil { panic(err) } if tp := s.T(); !fns.check(tp) { panic(fmt.Sprintf("wrong slice type: expected []%v, got: %v", fns.T(), tp)) } return s }
fn.go
0.718693
0.569613
fn.go
starcoder
package mab type Reward struct { Count int TotalCov float64 // sum(cov) TotalTime float64 // sum(time) TotalCov2 float64 // sum(cov * cov). Used to compute std TotalTime2 float64 // sum(time * time). Used to compute std } type TotalReward struct { // For Task Scheduling EstimatedRewardGenerate float64 // Estimated reward for Generate. Used for weight deciding EstimatedRewardMutate float64 // Estimated reward for Mutate. Used for weight deciding EstimatedRewardTriage float64 // Estimated reward for Triage. Used for weight deciding EstimatedRewardSquashAny float64 EstimatedRewardSplice float64 EstimatedRewardInsertCall float64 EstimatedRewardMutateArg float64 EstimatedRewardRemoveCall float64 RawAllTasks Reward // Raw cov/time for all Gen/Mut/Tri. Used for computing expected time RewardAllTasks Reward // Cov/time converted to reward for all Gen/Mut/Tri. Used for normalization // For Seed selection RawMutateOnly Reward // Raw cov/time for mutations. Used for Nael's computation for seed selection RewardMutateOnly Reward // Cov/time converted to reward for mutations only. Used for normalization } // Reward and time time information for each seed type CorpusReward struct { MutateCount int // Number of times this seed has been mutated ExecTime float64 // Execution time MutateTime float64 // Total time of mutating this seed MutateCov float64 // Total coverage cov of mutating this seed VerifyTime float64 // Time time of verifing this seed MinimizeCov float64 // Coverage coved from minimization MinimizeTime float64 // Time time of minimization MinimizeTimeSave float64 // Estimated time save due to minimization MutateReward float64 // Converted reward of mutating this seed. Coversion based on all tasks MutateRewardOrig float64 // Converted reward of mutating this seed. Conversion based on mutations only TriageReward float64 // Converted reward of triaging this seed } func (reward *Reward) Update(cov float64, time float64) { const Max = 1.0e+100 // Prevent overflow reward.Count++ reward.TotalCov += cov reward.TotalCov2 += cov * cov reward.TotalTime += time reward.TotalTime2 += time * time if reward.TotalCov > Max { reward.TotalCov = Max } if reward.TotalCov2 > Max { reward.TotalCov2 = Max } if reward.TotalTime > Max { reward.TotalTime = Max } if reward.TotalTime2 > Max { reward.TotalTime2 = Max } } func (reward *Reward) Remove(cov float64, time float64) { reward.Count-- reward.TotalCov -= cov reward.TotalCov2 -= cov * cov reward.TotalTime -= time reward.TotalTime2 -= time * time }
pkg/mab/reward.go
0.637369
0.589037
reward.go
starcoder
package pdu import ( "encoding/hex" ) type PDU struct { buf []byte leftIndex int intiailLeftCap int state int } func Alloc(headerCap int, dataLen int, dataCap int) *PDU { assert(dataLen <= dataCap, "More data requested than capacity") buf := make([]byte, headerCap+dataLen, headerCap+dataCap) return &PDU{ buf: buf, leftIndex: headerCap, intiailLeftCap: headerCap, } } func (p *PDU) SetState(expected int, new int) { assert(p.state == expected, "PDU state is not as expected") p.state = new } func (p *PDU) reallocInternal(leftCap int, dataLen int, dataCap int, copyData bool) bool { assert(leftCap >= 0, "Left capacity was < 0") assert(dataCap >= 0, "Right capacity was < 0") assert(dataLen >= 0, "Data length was < 0") assert(dataLen <= dataCap, "Data length was larger than requested capacity") if copyData { dataLen = 0 } totalCap := leftCap + dataCap if cap(p.buf) < totalCap || (cap(p.buf)*64 >= totalCap && totalCap > 512) { newPDU := Alloc(leftCap, dataLen, dataCap) newPDU.state = p.state if copyData { newPDU.Append(p.Buf()...) } *p = *newPDU return true } buf := p.buf[:cap(p.buf)] buf = buf[:leftCap+dataLen] newPDU := &PDU{ buf: buf, leftIndex: leftCap, intiailLeftCap: leftCap, state: p.state, } if copyData { newPDU.Append(p.Buf()...) } *p = *newPDU return false } func (p *PDU) Realloc(leftCap int, dataLen int, dataCap int) bool { return p.reallocInternal(leftCap, dataLen, dataCap, false) } func (p *PDU) NormalizeLeft(leftCap int) { newCap := cap(p.buf) - leftCap if newCap < 0 { newCap = 0 } p.reallocInternal(leftCap, 0, newCap, true) } func (p *PDU) Reset() { p.buf = p.buf[:p.intiailLeftCap] p.leftIndex = p.intiailLeftCap } func (p *PDU) Buf() []byte { return p.buf[p.leftIndex:] } func (p *PDU) Len() int { return len(p.buf) - p.leftIndex } func (p *PDU) RightCap() int { return cap(p.buf) - p.leftIndex } func (p *PDU) LeftCap() int { return p.leftIndex } func (p *PDU) Truncate(length int) { assert(length >= 0, "Length was < 0") assert(length <= p.RightCap(), "Length was > rightCap") p.buf = p.buf[:(p.leftIndex + length)] } func (p *PDU) DropLeft(amount int) []byte { assert(amount >= 0, "amount was < 0") if amount > p.Len() { return nil } old := p.leftIndex p.leftIndex += amount return p.buf[old:p.leftIndex] } func (p *PDU) DropRight(amount int) []byte { assert(amount >= 0, "amount was < 0") if amount > p.Len() { return nil } oldLen := p.Len() newLen := oldLen - amount p.buf = p.buf[:p.leftIndex+newLen] return p.buf[p.leftIndex+newLen : p.leftIndex+oldLen] } func (p *PDU) ExtendLeft(amount int) []byte { assert(amount >= 0, "Amount was < 0") if amount > p.LeftCap() { assert(p.reallocInternal(p.LeftCap()+2*amount, 0, p.RightCap(), true), "Requested realloc that was not needed") } oldLeftIndex := p.leftIndex p.leftIndex -= amount return p.buf[p.leftIndex:oldLeftIndex] } func (p *PDU) ExtendRight(amount int) []byte { assert(amount >= 0, "Amount was < 0") if amount > p.RightCap()-p.Len() { assert(p.reallocInternal(p.LeftCap(), 0, p.RightCap()+2*amount, true), "Requested realloc that was not needed") } oldLen := len(p.buf) p.buf = p.buf[:len(p.buf)+amount] return p.buf[oldLen:] } func (p *PDU) Append(b ...byte) { p.buf = append(p.buf, b...) } func (p PDU) String() string { return hex.EncodeToString(p.Buf()) } func assert(condition bool, reason string) { if !condition { panic(reason) } }
pdubuf/pdu.go
0.675872
0.573977
pdu.go
starcoder
package tween import ( "math" ) func Linear(start, end, value float32) float32 { return (end-start)*value + start } func Clerp(start, end, value float32) float32 { var max, half, retval, diff float32 = 360.0, 180.0, 0.0, 0.0 if (end - start) < -half { diff = ((max - start) + end) * value retval = start + diff } else if (end - start) > half { diff = -((max - end) + start) * value retval = start + diff } else { retval = start + (end-start)*value } return retval } func EaseInQuad(start, end, value float32) float32 { return (end-start)*value*value + start } func EaseOutQuad(start, end, value float32) float32 { return (end-start)*value*(value-2) + start } func EaseInOutQuad(start, end, value float32) float32 { value *= 2 end -= start if value < 1 { return end/2*value*value + start } value-- return -end/2*(value*(value-2)-1) + start } func EaseInCubic(start, end, value float32) float32 { return (end-start)*value*value*value + start } func EaseOutCubic(start, end, value float32) float32 { value-- return (end-start)*(value*value*value+1) + start } func EaseInOutCubic(start, end, value float32) float32 { value *= 2 end -= start if value < 1 { return end/2*value*value*value + start } value -= 2 return end/2*(value*value*value+2) + start } func EaseInQuart(start, end, value float32) float32 { return (end-start)*value*value*value*value + start } func EeaseOutQuart(start, end, value float32) float32 { value-- return -(end-start)*(value*value*value*value-1) + start } func EaseOutInQuart(start, end, value float32) float32 { value *= 2 end -= start if value < 1 { return end/2*value*value*value*value + start } return -end/2*(value*value*value*value-2) + start } func Spring(start, end, value float32) float32 { if value > 1 { value = 1 } else if value < 0 { value = 0 } v := float64(value) v = (math.Sin(v*math.Pi*(0.2+2.5*v*v*v))*math.Pow(1.0-v, 2.2) + v) * (1.0 + (1.2 * (1.0 - v))) value = float32(v) return start + (end-start)*value } func EaseInQuint(start, end, value float32) float32 { return (end-start)*value*value*value*value*value + start } func EaseOutQuint(start, end, value float32) float32 { value-- return (end-start)*(value*value*value*value*value+1) + start } func EaseInOutQuint(start, end, value float32) float32 { value *= 2 end -= start if value < 1 { return end/2*value*value*value*value*value + start } value -= 2 return end/2*(value*value*value*value*value+2) + start } func EaseInSine(start, end, value float32) float32 { end -= start return -end*float32(math.Cos(float64(value/1*(math.Pi/2)))) + end + start } func EaseOutSine(start, end, value float32) float32 { return (end-start)*float32(math.Sin(float64(value/1*(math.Pi/2)))) + start } func EaseInOutSine(start, end, value float32) float32 { end -= start return -end/2*(float32(math.Cos(float64(math.Pi*value/1))-1)) + start } func EaseInExpo(start, end, value float32) float32 { end -= start return end*float32(math.Pow(2, 10*(float64(value)/1-1))) + start } func EaseOutExpo(start, end, value float32) float32 { end -= start return end*float32((-math.Pow(2, -10*float64(value)/1)+1)) + start } func EaseInOutExpo(start, end, value float32) float32 { value *= 2 end -= start if value < 1 { return end/2*float32(math.Pow(2, 10*(float64(value)-1))) + start } value-- return end/2*float32((-math.Pow(2, -10*float64(value))+2)) + start } func EaseInCirc(start, end, value float32) float32 { end -= start return -end*(float32(math.Sqrt(1-float64(value*value))-1)) + start } func EaseOutCirc(start, end, value float32) float32 { value-- end -= start return end*float32(math.Sqrt(float64(1-value*value))) + start } func EaseInOutCirc(start, end, value float32) float32 { value *= -2 end -= start if value < 1 { return -end/2*(float32(math.Sqrt(float64(1-value*value))-1)) + start } value -= 2 return end/2*(float32(math.Sqrt(float64(1-value*value)+1))) + start } func EaseOutBounce(start, end, value float32) float32 { end -= start if value < (1 / 2.75) { return end*(7.5625*value*value) + start } else if value < (2 / 2.75) { value -= (1.5 / 2.75) return end*(7.5625*(value)*value+0.75) + start } else if value < (2.5 / 2.75) { value -= (2.25 / 2.75) return end*(7.5625*(value)*value+0.9375) + start } value -= (2.625 / 2.75) return end*(7.5625*(value)*value+0.984375) + start } func EaseInBounce(start, end, value float32) float32 { end -= start return end - EaseOutBounce(0, end, 1.0-value) + start } func EaseInOutBounce(start, end, value float32) float32 { end -= start if value < 1.0/2 { return EaseInBounce(0, end, value*2)*0.5 + start } return EaseOutBounce(0, end, value*2-1.0)*0.5 + end*0.5 + start } func EaseInBack(start, end, value float32) float32 { end -= start const s = 1.70158 return end*(value)*value*((s+1)*value-s) + start } func EaseOutBack(start, end, value float32) float32 { const s = 1.70158 end -= start value = (value / 1) - 1 return end*((value)*value*((s+1)*value+s)+1) + start } func EaseInOutBack(start, end, value float32) float32 { var s float32 = 1.70158 end -= start value *= 2 if (value) < 1 { s *= (1.525) return end/2*(value*value*(((s)+1)*value-s)) + start } value -= 2 s *= (1.525) return end/2*((value)*value*(((s)+1)*value+s)+2) + start } func Punch(amplitude, value float32) float32 { var s float32 = 9 if value == 0 { return 0 } if value == 1 { return 0 } const period = 1 * 0.3 s = period / float32((2*math.Pi)*math.Asin(0)) return (amplitude * float32(math.Pow(2, -10*float64(value))) * float32(math.Sin(float64((value*1-s)*(2*math.Pi)/period)))) } func EaseInElastic(start, end, value float32) float32 { end -= start var d float32 = 1.0 var p float32 = d * 0.3 var s float32 = 0.0 var a float32 = 0.0 if value == 0 { return start } value /= d if value == 1 { return start + end } if a == 0 || a < float32(math.Abs(float64(end))) { a = end s = p / 4 } else { s = p / (2 * float32(math.Pi)) * float32(math.Asin(float64(end/a))) } return -(a * float32(math.Pow(2, 10*(float64(value)-1))) * float32(math.Sin(float64((value*d-s)*(2*float32(math.Pi))/p)))) + start } func EaseOutElastic(start, end, value float32) float32 { end -= start var d float32 = 1.0 var p float32 = d * 0.3 var s float32 = 0.0 var a float32 = 0.0 if value == 0 { return start } value /= d if value == 1 { return start + end } if a == 0 || a < float32(math.Abs(float64(end))) { a = end s = p / 4 } else { s = p / (2 * float32(math.Pi)) * float32(math.Asin(float64(end/a))) } return (a * float32(math.Pow(2, -10*(float64(value)))) * float32(math.Sin(float64((value*d-s)*(2*float32(math.Pi))/p)))) + end + start } func EaseInOutElastic(start, end, value float32) float32 { end -= start var d float32 = 1.0 var p float32 = d * 0.3 var s float32 = 0.0 var a float32 = 0.0 if value == 0 { return start } value /= d if value == 1 { return start + end } if a == 0 || a < float32(math.Abs(float64(end))) { a = end s = p / 4 } else { s = p / (2 * float32(math.Pi)) * float32(math.Asin(float64(end/a))) } if value < 1 { return -0.5*(a*float32(math.Pow(2, 10*(float64(value)-1)))*float32(math.Sin(float64((value*d-s)*(2*math.Pi)/p)))) + start } return a*float32(math.Pow(2, -10*(float64(value)-1)))*float32(math.Sin(float64((value*d-s)*(2*math.Pi)/p)))*0.5 + end + start }
server/components/tween/algo.go
0.703855
0.554953
algo.go
starcoder
package streams import ( "github.com/go-fed/activity/vocab" "net/url" ) // A specialized Link that represents an @mention. This is a convenience wrapper of a type with the same name in the vocab package. Accessing it with the Raw function allows direct manipulaton of the object, and does not provide the same integrity guarantees as this package. type Mention struct { // The raw type from the vocab package raw *vocab.Mention } // Raw returns the vocab type for manaual manipulation. Note that manipulating the underlying type to be in an inconsistent state may cause this convenience type's methods to later fail. func (t *Mention) Raw() (n *vocab.Mention) { return t.raw } // Serialize turns this object into a map[string]interface{}. func (t *Mention) Serialize() (m map[string]interface{}, err error) { return t.raw.Serialize() } // LenAttributedTo returns the number of values this property contains. Each index be used with HasAttributedTo to determine if GetAttributedTo is safe to call or if raw handling would be needed. func (t *Mention) LenAttributedTo() (idx int) { return t.raw.AttributedToLen() } // GetAttributedTo attempts to get this 'attributedTo' property as a *url.URL. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetAttributedTo(idx int) (r Resolution, k *url.URL) { r = Unresolved handled := false if t.raw.IsAttributedToIRI(idx) { k = t.raw.GetAttributedToIRI(idx) if handled { r = Resolved } } else if t.raw.IsAttributedToObject(idx) { r = RawResolutionNeeded } else if t.raw.IsAttributedToLink(idx) { r = RawResolutionNeeded } return } // AppendAttributedTo appends the value for property 'attributedTo'. func (t *Mention) AppendAttributedTo(k *url.URL) { t.raw.AppendAttributedToIRI(k) } // PrependAttributedTo prepends the value for property 'attributedTo'. func (t *Mention) PrependAttributedTo(k *url.URL) { t.raw.PrependAttributedToIRI(k) } // RemoveAttributedTo deletes the value from the specified index for property 'attributedTo'. func (t *Mention) RemoveAttributedTo(idx int) { t.raw.RemoveAttributedToIRI(idx) } // HasAttributedTo returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasAttributedTo(idx int) (p Presence) { p = NoPresence if t.raw.IsAttributedToIRI(idx) { p = ConvenientPresence } else if t.raw.IsAttributedToLink(idx) { p = RawPresence } else if t.raw.IsAttributedToIRI(idx) { p = RawPresence } return } // GetHref attempts to get this 'href' property as a *url.URL. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetHref() (r Resolution, k *url.URL) { r = Unresolved handled := false if t.raw.HasHref() { k = t.raw.GetHref() if handled { r = Resolved } } return } // HasHref returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasHref() (p Presence) { p = NoPresence if t.raw.HasHref() { p = ConvenientPresence } return } // SetHref sets the value for property 'href'. func (t *Mention) SetHref(k *url.URL) { t.raw.SetHref(k) } // GetId attempts to get this 'id' property as a *url.URL. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetId() (r Resolution, k *url.URL) { r = Unresolved handled := false if t.raw.HasId() { k = t.raw.GetId() if handled { r = Resolved } } return } // HasId returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasId() (p Presence) { p = NoPresence if t.raw.HasId() { p = ConvenientPresence } return } // SetId sets the value for property 'id'. func (t *Mention) SetId(k *url.URL) { t.raw.SetId(k) } // LenRel returns the number of values this property contains. Each index be used with HasRel to determine if GetRel is safe to call or if raw handling would be needed. func (t *Mention) LenRel() (idx int) { return t.raw.RelLen() } // GetRel attempts to get this 'rel' property as a string. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetRel(idx int) (r Resolution, k string) { r = Unresolved handled := false if t.raw.IsRel(idx) { k = t.raw.GetRel(idx) if handled { r = Resolved } } else if t.raw.IsRelIRI(idx) { r = RawResolutionNeeded } return } // AppendRel appends the value for property 'rel'. func (t *Mention) AppendRel(k string) { t.raw.AppendRel(k) } // PrependRel prepends the value for property 'rel'. func (t *Mention) PrependRel(k string) { t.raw.PrependRel(k) } // RemoveRel deletes the value from the specified index for property 'rel'. func (t *Mention) RemoveRel(idx int) { t.raw.RemoveRel(idx) } // HasRel returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasRel(idx int) (p Presence) { p = NoPresence if t.raw.IsRel(idx) { p = ConvenientPresence } else if t.raw.IsRelIRI(idx) { p = RawPresence } return } // LenType returns the number of values this property contains. Each index be used with HasType to determine if GetType is safe to call or if raw handling would be needed. func (t *Mention) LenType() (idx int) { return t.raw.TypeLen() } // GetType attempts to get this 'type' property as a string. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetType(idx int) (r Resolution, s string) { r = Unresolved if tmp := t.raw.GetType(idx); tmp != nil { ok := false if s, ok = tmp.(string); ok { r = Resolved } else { r = RawResolutionNeeded } } return } // AppendType appends the value for property 'type'. func (t *Mention) AppendType(i interface{}) { t.raw.AppendType(i) } // PrependType prepends the value for property 'type'. func (t *Mention) PrependType(i interface{}) { t.raw.PrependType(i) } // RemoveType deletes the value from the specified index for property 'type'. func (t *Mention) RemoveType(idx int) { t.raw.RemoveType(idx) } // GetMediaType attempts to get this 'mediaType' property as a string. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetMediaType() (r Resolution, k string) { r = Unresolved handled := false if t.raw.IsMediaType() { k = t.raw.GetMediaType() if handled { r = Resolved } } else if t.raw.IsMediaTypeIRI() { r = RawResolutionNeeded } return } // HasMediaType returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasMediaType() (p Presence) { p = NoPresence if t.raw.IsMediaType() { p = ConvenientPresence } else if t.raw.IsMediaTypeIRI() { p = RawPresence } return } // SetMediaType sets the value for property 'mediaType'. func (t *Mention) SetMediaType(k string) { t.raw.SetMediaType(k) } // LenName returns the number of values this property contains. Each index be used with HasName to determine if GetName is safe to call or if raw handling would be needed. func (t *Mention) LenName() (idx int) { return t.raw.NameLen() } // GetName attempts to get this 'name' property as a string. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetName(idx int) (r Resolution, k string) { r = Unresolved handled := false if t.raw.IsNameString(idx) { k = t.raw.GetNameString(idx) if handled { r = Resolved } } else if t.raw.IsNameLangString(idx) { r = RawResolutionNeeded } else if t.raw.IsNameIRI(idx) { r = RawResolutionNeeded } return } // AppendName appends the value for property 'name'. func (t *Mention) AppendName(k string) { t.raw.AppendNameString(k) } // PrependName prepends the value for property 'name'. func (t *Mention) PrependName(k string) { t.raw.PrependNameString(k) } // RemoveName deletes the value from the specified index for property 'name'. func (t *Mention) RemoveName(idx int) { t.raw.RemoveNameString(idx) } // HasName returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasName(idx int) (p Presence) { p = NoPresence if t.raw.IsNameString(idx) { p = ConvenientPresence } else if t.raw.IsNameLangString(idx) { p = RawPresence } else if t.raw.IsNameIRI(idx) { p = RawPresence } return } // NameLanguages returns all languages for this property's language mapping, or nil if there are none. func (t *Mention) NameLanguages() (l []string) { return t.raw.NameMapLanguages() } // GetNameMap retrieves the value of 'name' for the specified language, or an empty string if it does not exist func (t *Mention) GetNameForLanguage(l string) (v string) { return t.raw.GetNameMap(l) } // SetNameForLanguage sets the value of 'name' for the specified language func (t *Mention) SetNameForLanguage(l string, v string) { t.raw.SetNameMap(l, v) } // LenSummary returns the number of values this property contains. Each index be used with HasSummary to determine if GetSummary is safe to call or if raw handling would be needed. func (t *Mention) LenSummary() (idx int) { return t.raw.SummaryLen() } // GetSummary attempts to get this 'summary' property as a string. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetSummary(idx int) (r Resolution, k string) { r = Unresolved handled := false if t.raw.IsSummaryString(idx) { k = t.raw.GetSummaryString(idx) if handled { r = Resolved } } else if t.raw.IsSummaryLangString(idx) { r = RawResolutionNeeded } else if t.raw.IsSummaryIRI(idx) { r = RawResolutionNeeded } return } // AppendSummary appends the value for property 'summary'. func (t *Mention) AppendSummary(k string) { t.raw.AppendSummaryString(k) } // PrependSummary prepends the value for property 'summary'. func (t *Mention) PrependSummary(k string) { t.raw.PrependSummaryString(k) } // RemoveSummary deletes the value from the specified index for property 'summary'. func (t *Mention) RemoveSummary(idx int) { t.raw.RemoveSummaryString(idx) } // HasSummary returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasSummary(idx int) (p Presence) { p = NoPresence if t.raw.IsSummaryString(idx) { p = ConvenientPresence } else if t.raw.IsSummaryLangString(idx) { p = RawPresence } else if t.raw.IsSummaryIRI(idx) { p = RawPresence } return } // SummaryLanguages returns all languages for this property's language mapping, or nil if there are none. func (t *Mention) SummaryLanguages() (l []string) { return t.raw.SummaryMapLanguages() } // GetSummaryMap retrieves the value of 'summary' for the specified language, or an empty string if it does not exist func (t *Mention) GetSummaryForLanguage(l string) (v string) { return t.raw.GetSummaryMap(l) } // SetSummaryForLanguage sets the value of 'summary' for the specified language func (t *Mention) SetSummaryForLanguage(l string, v string) { t.raw.SetSummaryMap(l, v) } // GetHreflang attempts to get this 'hreflang' property as a string. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetHreflang() (r Resolution, k string) { r = Unresolved handled := false if t.raw.IsHreflang() { k = t.raw.GetHreflang() if handled { r = Resolved } } else if t.raw.IsHreflangIRI() { r = RawResolutionNeeded } return } // HasHreflang returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasHreflang() (p Presence) { p = NoPresence if t.raw.IsHreflang() { p = ConvenientPresence } else if t.raw.IsHreflangIRI() { p = RawPresence } return } // SetHreflang sets the value for property 'hreflang'. func (t *Mention) SetHreflang(k string) { t.raw.SetHreflang(k) } // GetHeight attempts to get this 'height' property as a int64. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetHeight() (r Resolution, k int64) { r = Unresolved handled := false if t.raw.IsHeight() { k = t.raw.GetHeight() if handled { r = Resolved } } else if t.raw.IsHeightIRI() { r = RawResolutionNeeded } return } // HasHeight returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasHeight() (p Presence) { p = NoPresence if t.raw.IsHeight() { p = ConvenientPresence } else if t.raw.IsHeightIRI() { p = RawPresence } return } // SetHeight sets the value for property 'height'. func (t *Mention) SetHeight(k int64) { t.raw.SetHeight(k) } // GetWidth attempts to get this 'width' property as a int64. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling. func (t *Mention) GetWidth() (r Resolution, k int64) { r = Unresolved handled := false if t.raw.IsWidth() { k = t.raw.GetWidth() if handled { r = Resolved } } else if t.raw.IsWidthIRI() { r = RawResolutionNeeded } return } // HasWidth returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasWidth() (p Presence) { p = NoPresence if t.raw.IsWidth() { p = ConvenientPresence } else if t.raw.IsWidthIRI() { p = RawPresence } return } // SetWidth sets the value for property 'width'. func (t *Mention) SetWidth(k int64) { t.raw.SetWidth(k) } // LenPreview returns the number of values this property contains. Each index be used with HasPreview to determine if ResolvePreview is safe to call or if raw handling would be needed. func (t *Mention) LenPreview() (idx int) { return t.raw.PreviewLen() } // ResolvePreview passes the actual concrete type to the resolver for handing property preview. It returns a Resolution appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) ResolvePreview(r *Resolver, idx int) (s Resolution, err error) { s = Unresolved handled := false if t.raw.IsPreviewObject(idx) { handled, err = r.dispatch(t.raw.GetPreviewObject(idx)) if handled { s = Resolved } } else if t.raw.IsPreviewLink(idx) { handled, err = r.dispatch(t.raw.GetPreviewLink(idx)) if handled { s = Resolved } } else if t.raw.IsPreviewIRI(idx) { s = RawResolutionNeeded } return } // HasPreview returns a Presence appropriate for clients to determine whether it would be necessary to do raw handling, if desired. func (t *Mention) HasPreview(idx int) (p Presence) { p = NoPresence if t.raw.IsPreviewObject(idx) { p = ConvenientPresence } else if t.raw.IsPreviewLink(idx) { p = ConvenientPresence } else if t.raw.IsPreviewIRI(idx) { p = RawPresence } return } // AppendPreview appends an 'Object' typed value. func (t *Mention) AppendPreview(i vocab.ObjectType) { t.raw.AppendPreviewObject(i) } // PrependPreview prepends an 'Object' typed value. func (t *Mention) PrependPreview(i vocab.ObjectType) { t.raw.PrependPreviewObject(i) } // AppendPreviewLink appends a 'Link' typed value. func (t *Mention) AppendPreviewLink(i vocab.LinkType) { t.raw.AppendPreviewLink(i) } // PrependPreviewLink prepends a 'Link' typed value. func (t *Mention) PrependPreviewLink(i vocab.LinkType) { t.raw.PrependPreviewLink(i) } // NewMention returns a new instance of Mention func NewMention() (n *Mention) { return &Mention{raw: &vocab.Mention{}} }
streams/gen_mention.go
0.832781
0.400222
gen_mention.go
starcoder
package moment import "time" const ( // HoursPerDay specifies the number of hours in a day HoursPerDay = 24 // MinutesPerHour specifies the number of minutes in an hour MinutesPerHour = 60 // SecondsPerMinute specifies the number of seconds in a minute SecondsPerMinute = 60 ) // Point defines an abstract point in time. It does not include a day, month, or year but simply // a time of day type Point struct { hour int minute int second int nanoSecond int location *time.Location } // NewPoint creates a new time point with the given arguments. If no // arguments are given, the returned point represents the time 00:00 UTC. You can // provide up to 4 arguments in the order of "hour", "minute", "second", and "nanosecond". // Providing a fifth argument results in the default behavior and returns 00:00 UTC. func NewPoint(args ...int) Point { p := Point{ location: time.Local, } switch len(args) { case 4: p.nanoSecond = args[3] fallthrough case 3: p.SetSecond(args[2]) fallthrough case 2: p.SetMinute(args[1]) fallthrough case 1: p.SetHour(args[0]) } return p } // SetLocation sets the point location func (p Point) SetLocation(loc *time.Location) { if loc == nil { // do nothing! return } p.location = loc } // SetSecond checks to ensure the given value is valid and then sets the "second" parameter func (p Point) SetSecond(sec int) { if sec < 0 || sec >= SecondsPerMinute { return } p.second = sec } // SetMinute checks to ensure the given value is valid and then sets the "minute" parameter func (p Point) SetMinute(min int) { if min < 0 || min >= MinutesPerHour { return } p.minute = min } // SetHour checks to ensure the given value is valid and then sets the "hour" parameter func (p Point) SetHour(hr int) { if hr < 0 || hr >= HoursPerDay { return } p.hour = hr } // On returns the concrete time that the point would occur on the day given func (p Point) On(day time.Time) time.Time { if p.location == nil { p.location = time.UTC } return time.Date(day.Year(), day.Month(), day.Day(), p.hour, p.minute, p.second, p.nanoSecond, p.location) } // Span defines a duration of time starting at an abstract moment in time type Span struct { begin Point length time.Duration } // NewSpan creates a Span using the given inputs func NewSpan(begin Point, len time.Duration) Span { s := Span{ begin: begin, length: len, } return s } // Start returns the "real" start time of a Span on the given day func (s Span) Start(day time.Time) time.Time { return s.begin.On(day) } // End returns the "real" end time of a Span on the given day func (s Span) End(day time.Time) time.Time { return s.Start(day).Add(s.length) }
moment.go
0.806434
0.499146
moment.go
starcoder
package dbustype import ( "errors" "fmt" ) // Parse returns a DBusType corresponding to the signature |s|. // |s| needs to be a signature made up of a single complete type. // Note that this function does not support an extension about protobuf defined as an annotation // of a MethodArg and a SignalArg. Consider using BaseType, InArgType or OutArgType defined in // introspect package in order to take C++ types of those Args. func Parse(s string) (dbusType, error) { typs, err := parseSignature(s, 0) if err != nil { return dbusType{}, err } if len(typs) != 1 { return dbusType{}, fmt.Errorf("%s is not a signature made up of a single complete type", s) } return typs[0], nil } // In D-Bus specification, the maximum length of signature is 255. const maxSignatureLength = 255 // parseSignature returns a slice of DBusType corresponding to the signature |s|. // Incidentally, in D-Bus specification, signature is made up of zero or more single complete types. func parseSignature(s string, index int) ([]dbusType, error) { if len(s) > maxSignatureLength { return nil, fmt.Errorf("the length of signature exceeds the maximum value, signature is %q", s) } var ret []dbusType for index < len(s) { t, i, err := parseCompleteType(s, index, 0, 0) if err != nil { return nil, fmt.Errorf("parseCompleteType(%q, %d, 0, 0) faild: %v", s, index, err) } ret = append(ret, t) index = i } return ret, nil } // In D-Bus specification, the maximum depth of array and struct type nesting is 32 for each. const maxArrayDepth = 32 const maxStructDepth = 32 // parseCompleteType parses a single complete type which is a substring of the signature |s| // beginning from |index|, and returns a DBusType corresponding to the single complete type. // This function also returns the next index to see. func parseCompleteType(s string, index int, arrayDepth int, structDepth int) (dbusType, int, error) { if index >= len(s) { return dbusType{}, 0, fmt.Errorf("more type codes to follow %q are needed", s) } switch s[index] { case 'b': return dbusType{kind: dbusKindBoolean}, index + 1, nil case 'y': return dbusType{kind: dbusKindByte}, index + 1, nil case 'd': return dbusType{kind: dbusKindDouble}, index + 1, nil case 'o': return dbusType{kind: dbusKindObjectPath}, index + 1, nil case 'n': return dbusType{kind: dbusKindInt16}, index + 1, nil case 'i': return dbusType{kind: dbusKindInt32}, index + 1, nil case 'x': return dbusType{kind: dbusKindInt64}, index + 1, nil case 's': return dbusType{kind: dbusKindString}, index + 1, nil case 'h': return dbusType{kind: dbusKindFileDescriptor}, index + 1, nil case 'q': return dbusType{kind: dbusKindUint16}, index + 1, nil case 'u': return dbusType{kind: dbusKindUint32}, index + 1, nil case 't': return dbusType{kind: dbusKindUint64}, index + 1, nil case 'v': return dbusType{kind: dbusKindVariant}, index + 1, nil case 'a': index++ arrayDepth++ if arrayDepth > maxArrayDepth { return dbusType{}, 0, errors.New("excessive nesting depth of array") } if index >= len(s) { return dbusType{}, 0, fmt.Errorf("at end of string while reading array parameter") } if s[index] != '{' { // array case t, i, err := parseCompleteType(s, index, arrayDepth, structDepth) if err != nil { return dbusType{}, 0, err } return dbusType{kind: dbusKindArray, args: []dbusType{t}}, i, nil } // dictionary case // Check for VariantDictionary, which is a special case. if index+3 < len(s) && s[index:index+4] == "{sv}" { return dbusType{kind: dbusKindVariantDict}, index + 4, nil } index++ var args []dbusType for index < len(s) { if s[index] == '}' { if len(args) == 2 { return dbusType{kind: dbusKindDict, args: args}, index + 1, nil } return dbusType{}, 0, errors.New("dict entries must have 2 sub-types") } t, i, err := parseCompleteType(s, index, arrayDepth, structDepth) if err != nil { return dbusType{}, 0, err } args = append(args, t) index = i } return dbusType{}, 0, errors.New("unmatched '{'") case '(': // struct case index++ structDepth++ if structDepth > maxStructDepth { return dbusType{}, 0, errors.New("excessive nesting depth of struct") } var args []dbusType for index < len(s) { if s[index] == ')' { return dbusType{kind: dbusKindStruct, args: args}, index + 1, nil } t, i, err := parseCompleteType(s, index, arrayDepth, structDepth) if err != nil { return dbusType{}, 0, err } args = append(args, t) index = i } return dbusType{}, 0, errors.New("unmatched '('") default: return dbusType{}, 0, fmt.Errorf("unexpected type code: %c (index: %d)", s[index], index) } }
chromeos-dbus-bindings/go/src/chromiumos/dbusbindings/dbustype/parser.go
0.695131
0.477676
parser.go
starcoder
package cli import ( "fmt" "github.com/spf13/cobra" ) var genExamplesCmd = &cobra.Command{ Use: "example-data", Short: "generate example SQL code suitable for use with CockroachDB", Long: `This command generates example SQL code that shows various CockroachDB features and is suitable to populate an example database for demonstration and education purposes. The command takes an optional parameter which specifies which example to generate. The default is 'startrek', a database containing a table of episodes and a table of quotes from the eponymous TV show. `, RunE: runGenExamplesCmd, } func runGenExamplesCmd(cmd *cobra.Command, args []string) error { if len(args) > 1 { mustUsage(cmd) return errMissingParams } example := "startrek" if len(args) > 0 { example = args[0] } switch example { case "startrek": fmt.Print(startrekSQL) fmt.Println(footerComment) default: return fmt.Errorf("don't know how to generate example data for %q", example) } return nil } const startrekSQL = ` CREATE DATABASE IF NOT EXISTS startrek; SET DATABASE=startrek; DROP TABLE IF EXISTS quotes; DROP TABLE IF EXISTS episodes; CREATE TABLE episodes (id INT PRIMARY KEY, season INT, num INT, title TEXT, stardate DECIMAL); -- The data that follows was derived from the 'startrek' fortune cookie file. INSERT INTO episodes (id, season, num, title, stardate) VALUES (1, 1, 1, 'The Man Trap', 1531.1), (2, 1, 2, '<NAME>', 1533.6), (3, 1, 3, 'Where No Man Has Gone Before', 1312.4), (4, 1, 4, 'The Naked Time', 1704.2), (5, 1, 5, 'The Enemy Within', 1672.1), (6, 1, 6, 'Mudd''s Women', 1329.8), (7, 1, 7, 'What Are Little Girls Made Of?', 2712.4), (8, 1, 8, 'Miri', 2713.5), (9, 1, 9, 'Dagger of the Mind', 2715.1), (10, 1, 10, 'The Corbomite Maneuver', 1512.2), (11, 1, 11, 'The Menagerie, Part I', 3012.4), (12, 1, 12, 'The Menagerie, Part II', 3013.1), (13, 1, 13, 'The Conscience of the King', 2817.6), (14, 1, 14, 'Balance of Terror', 1709.2), (15, 1, 15, 'Shore Leave', 3025.3), (16, 1, 16, 'The Galileo Seven', 2821.5), (17, 1, 17, 'The Squire of Gothos', 2124.5), (18, 1, 18, 'Arena', 3045.6), (19, 1, 19, 'Tomorrow Is Yesterday', 3113.2), (20, 1, 20, '<NAME>', 2947.3), (21, 1, 21, 'The Return of the Archons', 3156.2), (22, 1, 22, 'Space Seed', 3141.9), (23, 1, 23, 'A Taste of Armageddon', 3192.1), (24, 1, 24, 'This Side of Paradise', 3417.3), (25, 1, 25, 'The Devil in the Dark', 3196.1), (26, 1, 26, 'Errand of Mercy', 3198.4), (27, 1, 27, 'The Alternative Factor', 3087.6), (28, 1, 28, 'The City on the Edge of Forever', 3134.0), (29, 1, 29, 'Operation: Annihilate!', 3287.2), (30, 2, 1, 'Amok Time', 3372.7), (31, 2, 2, 'Who Mourns for Adonais?', 3468.1), (32, 2, 3, 'The Changeling', 3541.9), (33, 2, 4, 'Mirror, Mirror', NULL), (34, 2, 5, 'The Apple', 3715.3), (35, 2, 6, 'The Doomsday Machine', 4202.9), (36, 2, 7, 'Catspaw', 3018.2), (37, 2, 8, 'I, Mudd', 4513.3), (38, 2, 9, 'Metamorphosis', 3219.4), (39, 2, 10, 'Journey to Babel', 3842.3), (40, 2, 11, 'Friday''s Child', 3497.2), (41, 2, 12, 'The Deadly Years', 3478.2), (42, 2, 13, 'Obsession', 3619.2), (43, 2, 14, 'Wolf in the Fold', 3614.9), (44, 2, 15, 'The Trouble with Tribbles', 4523.3), (45, 2, 16, 'The Gamesters of Triskelion', 3211.8), (46, 2, 17, 'A Piece of the Action', 4598.0), (47, 2, 18, 'The Immunity Syndrome', 4307.1), (48, 2, 19, 'A Private Little War', 4211.4), (49, 2, 20, 'Return to Tomorrow', 4768.3), (50, 2, 21, 'Patterns of Force', 2534.0), (51, 2, 22, 'By Any Other Name', 4657.5), (52, 2, 23, 'The Omega Glory', NULL), (53, 2, 24, 'The Ultimate Computer', 4729.4), (54, 2, 25, 'Bread and Circuses', 4040.7), (55, 2, 26, 'Assignment: Earth', NULL), (56, 3, 1, 'Spock''s Brain', 5431.4), (57, 3, 2, 'The Enterprise Incident', 5027.3), (58, 3, 3, 'The Paradise Syndrome', 4842.6), (59, 3, 4, 'And the Children Shall Lead', 5029.5), (60, 3, 5, 'Is There in Truth No Beauty?', 5630.7), (61, 3, 6, 'Spectre of the Gun', 4385.3), (62, 3, 7, 'Day of the Dove', 5630.3), (63, 3, 8, 'For the World Is Hollow and I Have Touched the Sky', 5476.3), (64, 3, 9, 'The Tholian Web', 5693.2), (65, 3, 10, 'Plato''s Stepchildren', 5784.2), (66, 3, 11, 'Wink of an Eye', 5710.5), (67, 3, 12, 'The Empath', 5121.5), (68, 3, 13, '<NAME>', 4372.5), (69, 3, 14, 'Whom Gods Destroy', 5718.3), (70, 3, 15, 'Let That Be Your Last Battlefield', 5730.2), (71, 3, 16, '<NAME>', 5423.4), (72, 3, 17, 'That Which Survives', NULL), (73, 3, 18, 'The Lights of Zetar', 5725.3), (74, 3, 19, 'Requiem for Methuselah', 5843.7), (75, 3, 20, 'The Way to Eden', 5832.3), (76, 3, 21, 'The Cloud Minders', 5818.4), (77, 3, 22, 'The Savage Curtain', 5906.4), (78, 3, 23, 'All Our Yesterdays', 5943.7), (79, 3, 24, 'Turnabout Intruder', 5928.5); CREATE TABLE quotes (quote TEXT, characters TEXT, stardate DECIMAL, episode INT REFERENCES episodes(id), INDEX(episode)); INSERT INTO quotes (quote, characters, stardate, episode) VALUES ('"... freedom ... is a worship word..." "It is our worship word too."', '<NAME>', NULL, 52), ('"Beauty is transitory." "Beauty survives."', '<NAME>', NULL, 72), ('"Can you imagine how life could be improved if we could do away with jealousy, greed, hate ..." "It can also be improved by eliminating love, tenderness, sentiment -- the other side of the coin"', 'Dr. <NAME> Kirk', 2712.4, 7), ('"Evil does seek to maintain power by suppressing the truth." "Or by misleading the innocent."', '<NAME>', 5029.5, 59), ('"Get back to your stations!" "We''re beaming down to the planet, sir."', 'Kirk and Mr. Leslie', 3417.3, 24), ('"I think they''re going to take all this money that we spend now on war and death --" "And make them spend it on life."', '<NAME> and Kirk', NULL, 28), ('"It''s hard to believe that something which is neither seen nor felt can do so much harm." "That''s true. But an idea can''t be seen or felt. And that''s what kept the Troglytes in the mines all these centuries. A mistaken idea."', '<NAME>', 5819.0, 76), ('"Life and death are seldom logical." "But attaining a desired goal always is."', '<NAME>', 2821.7, 16), ('"Logic and practical information do not seem to apply here." "You admit that?" "To deny the facts would be illogical, Doctor"', '<NAME>', NULL, 46), ('"No one talks peace unless he''s ready to back it up with war." "He talks of peace if it is the only way to live."', 'Colonel Green and Surak of Vulcan', 5906.5, 77), ('"That unit is a woman." "A mass of conflicting impulses."', 'Spock and Nomad', 3541.9, 32), ('"The combination of a number of things to make existence worthwhile." "Yes, the philosophy of ''none,'' meaning ''all.''"', '<NAME>', 5906.4, 77), ('"The glory of creation is in its infinite diversity." "And in the way our differences combine to create meaning and beauty."', 'Dr. <NAME> Spock', 5630.8, 60), ('"The release of emotion is what keeps us healthy. Emotionally healthy." "That may be, Doctor. However, I have noted that the healthy release of emotion is frequently unhealthy for those closest to you."', '<NAME>', 5784.3, 65), ('"There''s only one kind of woman ..." "Or man, for that matter. You either believe in yourself or you don''t."', 'Kirk and <NAME>', 1330.1, 6), ('"We have the right to survive!" "Not by killing others."', '<NAME>', 5710.5, 66), ('"What a terrible way to die." "There are no good ways."', '<NAME>', NULL, 72), ('"What happened to the crewman?" "The M-5 computer needed a new power source, the crewman merely got in the way."', 'Kirk and Dr. <NAME>', 4731.3, 53), ('... bacteriological warfare ... hard to believe we were once foolish enough to play around with that.', 'McCoy', NULL, 52), ('... The prejudices people feel about each other disappear when they get to know each other.', 'Kirk', 4372.5, 68), ('... The things love can drive a man to -- the ecstasies, the miseries, the broken rules, the desperate chances, the glorious failures and the glorious victories.', 'McCoy', 5843.7, 74), ('A father doesn''t destroy his children.', 'Lt. <NAME>', 3468.1, 31), ('A little suffering is good for the soul.', 'Kirk', 1514.0, 10), ('A man either lives life as it happens to him, meets it head-on and licks it, or he turns his back on it and starts to wither away.', 'Dr. Boyce', NULL, 11), ('A princess should not be afraid -- not with a brave knight to protect her.', 'McCoy', 3025.3, 15), ('A star captain''s most solemn oath is that he will give his life, even his entire crew, rather than violate the Prime Directive.', 'Kirk', NULL, 52), ('A Vulcan can no sooner be disloyal than he can exist without breathing.', 'Kirk', 3012.4, 11), ('A woman should have compassion.', 'Kirk', 3018.2, 36), ('Actual war is a very messy business. Very, very messy business.', 'Kirk', 3193.0, 23), ('After a time, you may find that "having" is not so pleasing a thing, after all, as "wanting." It is not logical, but it is often true.', 'Spock', 3372.7, 30), ('All your people must learn before you can reach for the stars.', 'Kirk', 3259.2, 45), ('Another Armenia, Belgium ... the weak innocents who always seem to be located on a natural invasion route.', 'Kirk', 3198.4, 26), ('Another dream that failed. There''s nothing sadder.', 'Kirk', 3417.3, 24), ('Another war ... must it always be so? How many comrades have we lost in this way? ... Obedience. Duty. Death, and more death ...', '<NAME>', 1709.2, 14), ('Behind every great man, there is a woman -- urging him on.', '<NAME>', 4513.3, 37), ('Blast medicine anyway! We''ve learned to tie into every organ in the human body but one. The brain! The brain is what life is all about.', 'McCoy', 3012.4, 11), ('But it''s real. And if it''s real it can be affected ... we may not be able to break it, but, I''ll bet you credits to Navy Beans we can put a dent in it.', 'deSalle', 3018.2, 36), ('Change is the essential process of all existence.', 'Spock', 5730.2, 70), ('Compassion -- that''s the one thing no machine ever had. Maybe it''s the one thing that keeps men ahead of them.', 'McCoy', 4731.3, 53), ('Computers make excellent and efficient servants, but I have no wish to serve under them. Captain, a starship also runs on loyalty to one man. And nothing can replace it or him.', 'Spock', 4729.4, 53), ('Conquest is easy. Control is not.', 'Kirk', NULL, 33), ('Death. Destruction. Disease. Horror. That''s what war is all about. That''s what makes it a thing to be avoided.', 'Kirk', 3193.0, 23), ('Death, when unnecessary, is a tragic thing.', 'Flint', 5843.7, 74), ('Do you know about being with somebody? Wanting to be? If I had the whole universe, I''d give it to you, Janice. When I see you, I feel like I''m hungry all over. Do you know how that feels?', '<NAME>', 1535.8, 2), ('Do you know the one -- "All I ask is a tall ship, and a star to steer her by ..." You could feel the wind at your back, about you ... the sounds of the sea beneath you. And even if you take away the wind and the water, it''s still the same. The ship is yours ... you can feel her ... and the stars are still there.', 'Kirk', 4729.4, 53), ('[Doctors and Bartenders], We both get the same two kinds of customers -- the living and the dying.', 'Dr. Boyce', NULL, 11), ('Each kiss is as the first.', 'Miramanee, Kirk''s wife', 4842.6, 58), ('Earth -- mother of the most beautiful women in the universe.', 'Apollo', 3468.1, 31), ('Either one of us, by himself, is expendable. Both of us are not.', 'Kirk', 3196.1, 25), ('Emotions are alien to me. I''m a scientist.', 'Spock', 3417.3, 24), ('Even historians fail to learn from history -- they repeat the same mistakes.', '<NAME>', 2534.7, 50), ('Every living thing wants to survive.', 'Spock', 4731.3, 53), ('Extreme feminine beauty is always disturbing.', 'Spock', 5818.4, 76), ('Fascinating, a totally parochial attitude.', 'Spock', 3219.8, 38), ('Fascinating is a word I use for the unexpected.', 'Spock', 2124.5, 17), ('First study the enemy. Seek weakness.', '<NAME>', 1709.2, 14), ('Four thousand throats may be cut in one night by a running man.', '<NAME>', NULL, 62), ('Genius doesn''t work on an assembly line basis. You can''t simply say, "Today I will be brilliant."', 'Kirk', 4731.3, 53), ('He''s dead, Jim', 'McCoy', 3196.1, 25), ('History tends to exaggerate.', '<NAME>', 5906.4, 77), ('Humans do claim a great deal for that particular emotion (love).', 'Spock', 5725.6, 73), ('I am pleased to see that we have differences. May we together become greater than the sum of both of us.', '<NAME>', 5906.4, 77), ('I have never understood the female capacity to avoid a direct answer to any question.', 'Spock', 3417.3, 24), ('I object to intellect without discipline; I object to power without constructive purpose.', 'Spock', 2124.5, 17), ('I realize that command does have its fascination, even under circumstances such as these, but I neither enjoy the idea of command nor am I frightened of it. It simply exists, and I will do whatever logically needs to be done.', 'Spock', 2812.7, 16), ('I thought my people would grow tired of killing. But you were right, they see it is easier than trading. And it has its pleasures. I feel it myself. Like the hunt, but with richer rewards.', 'Apella', 4211.8, 48), ('If a man had a child who''d gone anti-social, killed perhaps, he''d still tend to protect that child.', 'McCoy', 4731.3, 53), ('If I can have honesty, it''s easier to overlook mistakes.', 'Kirk', 3141.9, 22), ('If some day we are defeated, well, war has its fortunes, good and bad.', '<NAME>', 3201.7, 26), ('If there are self-made purgatories, then we all have to live in them.', 'Spock', 3417.7, 24), ('I''m a soldier, not a diplomat. I can only tell the truth.', 'Kirk', 3198.9, 26), ('I''m frequently appalled by the low regard you Earthmen have for life.', 'Spock', 2822.3, 16), ('Immortality consists largely of boredom.', '<NAME>', 3219.8, 38), ('In the strict scientific sense we all feed on death -- even vegetarians.', 'Spock', 3615.4, 43), ('Insufficient facts always invite danger.', 'Spock', 3141.9, 22), ('Insults are effective only where emotion is present.', 'Spock', 3468.1, 31), ('Intuition, however illogical, is recognized as a command prerogative.', 'Kirk', 3620.7, 42), ('Is not that the nature of men and women -- that the pleasure is in the learning of each other?', 'Natira, the High Priestess of Yonada', 5476.3, 63), ('Is truth not truth for all?', 'Natira', 5476.4, 63), ('It [being a Vulcan] means to adopt a philosophy, a way of life which is logical and beneficial. We cannot disregard that philosophy merely for personal gain, no matter how important that gain might be.', 'Spock', 3842.4, 39), ('It is a human characteristic to love little animals, especially if they''re attractive in some way.', 'McCoy', 4525.6, 44), ('It is more rational to sacrifice one life than six.', 'Spock', 2822.3, 16), ('It is necessary to have purpose.', 'Alice #1', 4513.3, 37), ('It is undignified for a woman to play servant to a man who is not hers.', 'Spock', 3372.7, 30), ('It would be illogical to assume that all conditions remain stable.', 'Spock', 5027.3, 57), ('It would be illogical to kill without reason', 'Spock', 3842.4, 39), ('It would seem that evil retreats when forcibly confronted', 'Yarnek of Excalbia', 5906.5, 77), ('I''ve already got a female to worry about. Her name is the Enterprise.', 'Kirk', 1514.0, 10), ('Killing is stupid; useless!', 'McCoy', 4211.8, 48), ('Killing is wrong.', 'Losira', NULL, 72), ('Knowledge, sir, should be free to all!', '<NAME>', 4513.3, 37), ('Landru! Guide us!', 'A Beta 3-oid', 3157.4, 21), ('Leave bigotry in your quarters; there''s no room for it on the bridge.', 'Kirk', 1709.2, 14), ('Live long and prosper.', 'Spock', 3372.7, 30), ('Lots of people drink from the wrong bottle sometimes.', '<NAME>', NULL, 28), ('Love sometimes expresses itself in sacrifice.', 'Kirk', 3220.3, 38), ('Madness has no purpose. Or reason. But it may have a goal.', 'Spock', 3088.7, 27), ('Many Myths are based on truth', 'Spock', 5832.3, 75), ('Men don''t talk peace unless they''re ready to back it up with war.', '<NAME>', 5906.4, 77), ('Men of peace usually are [brave].', 'Spock', 5906.5, 77), ('Men will always be men -- no matter where they are.', '<NAME>', 1329.8, 6), ('Military secrets are the most fleeting of all.', 'Spock', 5027.4, 57), ('Most legends have their basis in facts.', 'Kirk', 5029.5, 59), ('Murder is contrary to the laws of man and God.', 'M-5 Computer', 4731.3, 53), ('No more blah, blah, blah!', 'Kirk', 2713.6, 8), ('No one can guarantee the actions of another.', 'Spock', NULL, 62), ('No one may kill a man. Not for any purpose. It cannot be condoned.', 'Kirk', 5431.6, 56), ('No one wants war.', 'Kirk', 3201.7, 26), ('No problem is insoluble.', 'Dr. <NAME>', 3479.4, 41), ('Not one hundred percent efficient, of course ... but nothing ever is.', 'Kirk', 3219.8, 38), ('Oblivion together does not frighten me, beloved.', 'Thalassa (in <NAME>''s body)', 4770.3, 49), ('Oh, that sound of male ego. You travel halfway across the galaxy and it''s still the same song.', '<NAME>', 1330.1, 6), ('On my planet, to rest is to rest -- to cease using energy. To me, it is quite illogical to run up and down on green grass, using energy, instead of saving it.', 'Spock', 3025.2, 15), ('One does not thank logic.', 'Sarek', 3842.4, 39), ('One of the advantages of being a captain is being able to ask for advice without necessarily having to take it.', 'Kirk', 2715.2, 9), ('Only a fool fights in a burning house.', 'Kang the Klingon', NULL, 62), ('Our missions are peaceful -- not for conquest. When we do battle, it is only because we have no choice.', 'Kirk', 2124.5, 17), ('Our way is peace.', 'Septimus, the Son Worshiper', 4040.7, 54), ('Pain is a thing of the mind. The mind can be controlled.', 'Spock', 3287.2, 29), ('Peace was the way.', 'Kirk', NULL, 28), ('Power is danger.', 'The Centurion', 1709.2, 14), ('Prepare for tomorrow -- get ready.', '<NAME>', NULL, 28), ('Punishment becomes ineffective after a certain point. Men become insensitive.', 'Eneg', 2534.7, 50), ('Respect is a rational process', 'McCoy', 2822.3, 16), ('Romulan women are not like Vulcan females. We are not dedicated to pure logic and the sterility of non-emotion.', 'Romulan Commander', 5027.3, 57), ('Schshschshchsch.', 'The Gorn', 3046.2, 18), ('Sometimes a feeling is all we humans have to go on.', 'Kirk', 3193.9, 23), ('Sometimes a man will tell his bartender things he''ll never tell his doctor.', 'Dr. <NAME>', NULL, 11), ('Suffocating together ... would create heroic camaraderie.', '<NAME>', 3142.8, 22), ('Superior ability breeds superior ambition.', 'Spock', 3141.9, 22), ('The face of war has never changed. Surely it is more logical to heal than to kill.', 'Surak of Vulcan', 5906.5, 77), ('The games have always strengthened us. Death becomes a familiar pattern. We don''t fear it as you do.', 'Proconsul <NAME>', 4041.2, 54), ('The heart is not a logical organ.', 'Dr. <NAME>', 3479.4, 41), ('The idea of male and female are universal constants.', 'Kirk', 3219.8, 38), ('The joys of love made her human and the agonies of love destroyed her.', 'Spock', 5842.8, 74), ('The man on tops walks a lonely street; the "chain" of command is often a noose.', 'McCoy', 2818.9, 13), ('The more complex the mind, the greater the need for the simplicity of play.', 'Kirk', 3025.8, 15), ('The only solution is ... a balance of power. We arm our side with exactly that much more. A balance of power -- the trickiest, most difficult, dirtiest game of them all. But the only one that preserves both sides.', 'Kirk', 4211.8, 48), ('The people of Gideon have always believed that life is sacred. That the love of life is the greatest gift ... We are incapable of destroying or interfering with the creation of that which we love so deeply -- life in every form from fetus to developed being.', '<NAME>', 5423.4, 71), ('The sight of death frightens them [Earthers].', '<NAME>', 3497.2, 40), ('The sooner our happiness together begins, the longer it will last.', 'Miramanee', 4842.6, 58), ('There are always alternatives.', 'Spock', 2822.3, 16), ('There are certain things men must do to remain men.', 'Kirk', 4929.4, 53), ('There are some things worth dying for.', 'Kirk', 3201.7, 26), ('There comes to all races an ultimate crisis which you have yet to face .... One day our minds became so powerful we dared think of ourselves as gods.', 'Sargon', 4768.3, 49), ('There is a multi-legged creature crawling on your shoulder.', 'Spock', 3193.9, 23), ('There is an old custom among my people. When a woman saves a man''s life, he is grateful.', 'Nona, the Kanuto witch woman', 4211.8, 48), ('There is an order of things in this universe.', 'Apollo', 3468.1, 31), ('There''s a way out of any cage.', '<NAME>', NULL, 11), ('There''s another way to survive. Mutual trust -- and help.', 'Kirk', NULL, 62), ('There''s no honorable way to kill, no gentle way to destroy. There is nothing good in war. Except its ending.', '<NAME>', 5906.5, 77), ('There''s nothing disgusting about it [the Companion]. It''s just another life form, that''s all. You get used to those things.', 'McCoy', 3219.8, 38), ('This cultural mystique surrounding the biological function -- you realize humans are overly preoccupied with the subject.', '<NAME>', 4658.9, 51), ('Those who hate and fight must stop themselves -- otherwise it is not stopped.', 'Spock', NULL, 62), ('Time is fluid ... like a river with currents, eddies, backwash.', 'Spock', 3134.0, 28), ('To live is always desirable.', 'Eleen the Capellan', 3498.9, 40), ('Too much of anything, even love, isn''t necessarily a good thing.', 'Kirk', 4525.6, 44), ('Totally illogical, there was no chance.', 'Spock', 2822.3, 16), ('Uncontrolled power will turn even saints into savages. And we can all be counted on to live down to our lowest impulses.', 'Parmen', 5784.3, 65), ('Violence in reality is quite different from theory.', 'Spock', 5818.4, 76), ('Virtue is a relative term.', 'Spock', 3499.1, 40), ('Vulcans believe peace should not depend on force.', 'Amanda', 3842.3, 39), ('Vulcans do not approve of violence.', 'Spock', 3842.4, 39), ('Vulcans never bluff.', 'Spock', 4202.1, 35), ('Vulcans worship peace above all.', 'McCoy', 4768.3, 49), ('Wait! You have not been prepared!', 'Mr. Atoz', 3113.2, 19), ('[War] is instinctive. But the instinct can be fought. We''re human beings with the blood of a million savage years on our hands! But we can stop it. We can admit that we''re killers ... but we''re not going to kill today. That''s all it takes! Knowing that we''re not going to kill today!', 'Kirk', 3193.0, 23), ('War is never imperative.', 'McCoy', 1709.2, 14), ('War isn''t a good life, but it''s life.', 'Kirk', 4211.8, 48), ('We do not colonize. We conquer. We rule. There is no other way for us.', 'Rojan', 4657.5, 51), ('We fight only when there is no other choice. We prefer the ways of peaceful contact.', 'Kirk', 4385.3, 61), ('We have found all life forms in the galaxy are capable of superior development.', 'Kirk', 3211.7, 45), ('We have phasers, I vote we blast ''em!', 'Bailey', 1514.2, 10), ('We Klingons believe as you do -- the sick should die. Only the strong should live.', 'Kras', 3497.2, 40), ('We''re all sorry for the other guy when he loses his job to a machine. But when it comes to your job -- that''s different. And it always will be different.', 'McCoy', 4729.4, 53), ('What kind of love is that? Not to be loved; never to have shown love.', 'Commissioner <NAME>', 3219.8, 38), ('When a child is taught ... it''s programmed with simple instructions -- and at some point, if its mind develops properly, it exceeds the sum of what it was taught, thinks independently.', 'Dr. <NAME>', 4731.3, 53), ('When dreams become more important than reality, you give up travel, building, creating; you even forget how to repair the machines left behind by your ancestors. You just sit living and reliving other lives left behind in the thought records.', 'Vina', NULL, 11), ('Where there''s no emotion, there''s no motive for violence.', 'Spock', 2715.1, 9), ('Witch! Witch! They''ll burn ya!', 'Hag', NULL, 19), ('Without facts, the decision cannot be made logically. You must rely on your human intuition.', 'Spock', NULL, 55), ('Without followers, evil cannot spread.', 'Spock', 5029.5, 59), ('Without freedom of choice there is no creativity.', 'Kirk', 3157.4, 21), ('Women are more easily and more deeply terrified ... generating more sheer horror than the male of the species.', 'Spock', 3615.4, 43), ('Women professionals do tend to over-compensate.', 'Dr. <NAME>', 1312.9, 3), ('Worlds may change, galaxies disintegrate, but a woman always remains a woman.', 'Kirk', 2818.9, 13), ('Yes, it is written. Good shall always destroy evil.', '<NAME>', NULL, 52), ('You! What PLANET is this?!', 'McCoy', 3134.0, 28), ('You are an excellent tactician, Captain. You let your second in command attack while you sit and watch for weakness.', '<NAME>', 3141.9, 22), ('You can''t evaluate a man by logic alone.', 'McCoy', 4513.3, 37), ('You Earth people glorified organized violence for forty centuries. But you imprison those who employ it privately.', 'Spock', 2715.1, 9), ('You go slow, be gentle. It''s no one-way street -- you know how you feel and that''s all. It''s how the girl feels too. Don''t press. If the girl feels anything for you at all, you''ll know.', 'Kirk', 1535.8, 2), ('You humans have that emotional need to express gratitude. "You''re welcome," I believe, is the correct response.', 'Spock', 4041.2, 54), ('You say you are lying. But if everything you say is a lie, then you are telling the truth. You cannot tell the truth because everything you say is a lie. You lie, you tell the truth ... but you cannot, for you lie.', 'Norman the android', 4513.3, 37), ('You speak of courage. Obviously you do not know the difference between courage and foolhardiness. Always it is the brave ones who die, the soldiers.', 'Kor, the Klingon Commander', 3201.7, 26), ('You''ll learn something about men and women -- the way they''re supposed to be. Caring for each other, being happy with each other, being good to each other. That''s what we call love. You''ll like that a lot.', 'Kirk', 3715.6, 34), ('You''re dead, Jim.', 'McCoy', 3372.7, 30), ('You''re dead, Jim.', 'McCoy', NULL, 64), ('You''re too beautiful to ignore. Too much woman.', 'Kirk to Yeoman Rand', NULL, 5), ('Youth doesn''t excuse everything.', 'Dr. <NAME> (in Kirk''s body)', 5928.5, 79); ` const footerComment = `-- -- -- If you can see this message, you probably want to redirect the output of -- 'cockroach gen example-data' to a file, or pipe it as input to 'cockroach sql'. `
cli/examples.go
0.619701
0.547948
examples.go
starcoder
package hashtable // ArraySize is the size of the hash table array const ArraySize = 7 // HashTable will hold an array type HashTable struct { array [ArraySize]*bucket } // bucket is a linked list in each slot of the has type bucket struct { head *bucketNode } // bucketNode structure type bucketNode struct { key string value interface{} next *bucketNode } // Insert will take in a key and add it to the has table array func (h *HashTable) Insert(key string, value interface{}) { index := hash(key) h.array[index].insert(key, value) } // Search will take in a key and return true if that key is stored in the hash table func (h *HashTable) Search(key string) (interface{}, bool) { index := hash(key) return h.array[index].search(key) } // Delete will take in a key and delete it from the hash table func (h *HashTable) Delete(key string) { index := hash(key) h.array[index].delete(key) } // insert will take in a key, create a node with the key and insert the node in the bucket func (b *bucket) insert(k string, v interface{}) { if _, ok := b.search(k); !ok { newNode := &bucketNode{key: k, value: v} newNode.next = b.head b.head = newNode } // already exists } // search will take in a key and return true if the bucket has that key func (b *bucket) search(k string) (interface{}, bool) { currentNode := b.head for currentNode != nil { if currentNode.key == k { return currentNode.value, true } currentNode = currentNode.next } return nil, false } // delete will take in a key and delete the node from the bucket func (b *bucket) delete(k string) { if b.head.key == k { b.head = b.head.next return } previousNode := b.head for previousNode != nil && previousNode.next != nil { if previousNode.next.key == k { //delete previousNode.next = previousNode.next.next } previousNode = previousNode.next } } // hash func hash(key string) int { sum := 0 for _, v := range key { sum += int(v) } return sum % ArraySize } // Init will create a bucket in each slot of the hash table func Init() *HashTable { result := &HashTable{} for i := range result.array { result.array[i] = &bucket{} } return result }
hashtable/hashtable.go
0.728169
0.491212
hashtable.go
starcoder
package engine /* The metadata layer wraps basic micromagnetic functions (e.g. func SetDemagField()) in objects that provide: - additional information (Name, Unit, ...) used for saving output, - additional methods (Comp, Region, ...) handy for input scripting. */ import ( "fmt" "github.com/mumax/3/cuda" "github.com/mumax/3/data" ) // The Info interface defines the bare minimum methods a quantity must implement // to be accessible for scripting and I/O. type Info interface { Name() string // number of components (scalar, vector, ...) Unit() string // name used for output file (e.g. "m") NComp() int // unit, e.g. "A/m" } // info provides an Info implementation intended for embedding in other types. type info struct { nComp int name string unit string } func (i *info) Name() string { return i.name } func (i *info) Unit() string { return i.unit } func (i *info) NComp() int { return i.nComp } // outputFunc is an outputValue implementation where a function provides the output value. // It can be scalar or vector. // Used internally by NewScalarValue and NewVectorValue. type valueFunc struct { info f func() []float64 } func (g *valueFunc) get() []float64 { return g.f() } func (g *valueFunc) average() []float64 { return g.get() } func (g *valueFunc) EvalTo(dst *data.Slice) { v := g.get() for c, v := range v { cuda.Memset(dst.Comp(c), float32(v)) } } // ScalarValue enhances an outputValue with methods specific to // a space-independent scalar quantity (e.g. total energy). type ScalarValue struct { *valueFunc } // NewScalarValue constructs an outputable space-independent scalar quantity whose // value is provided by function f. func NewScalarValue(name, unit, desc string, f func() float64) *ScalarValue { g := func() []float64 { return []float64{f()} } v := &ScalarValue{&valueFunc{info{1, name, unit}, g}} Export(v, desc) return v } func (s ScalarValue) Get() float64 { return s.average()[0] } func (s ScalarValue) Average() float64 { return s.Get() } // VectorValue enhances an outputValue with methods specific to // a space-independent vector quantity (e.g. averaged magnetization). type VectorValue struct { *valueFunc } // NewVectorValue constructs an outputable space-independent vector quantity whose // value is provided by function f. func NewVectorValue(name, unit, desc string, f func() []float64) *VectorValue { v := &VectorValue{&valueFunc{info{3, name, unit}, f}} Export(v, desc) return v } func (v *VectorValue) Get() data.Vector { return unslice(v.average()) } func (v *VectorValue) Average() data.Vector { return v.Get() } // NewVectorField constructs an outputable space-dependent vector quantity whose // value is provided by function f. func NewVectorField(name, unit, desc string, f func(dst *data.Slice)) VectorField { v := AsVectorField(&fieldFunc{info{3, name, unit}, f}) DeclROnly(name, v, cat(desc, unit)) return v } // NewVectorField constructs an outputable space-dependent scalar quantity whose // value is provided by function f. func NewScalarField(name, unit, desc string, f func(dst *data.Slice)) ScalarField { q := AsScalarField(&fieldFunc{info{1, name, unit}, f}) DeclROnly(name, q, cat(desc, unit)) return q } type fieldFunc struct { info f func(*data.Slice) } func (c *fieldFunc) Mesh() *data.Mesh { return Mesh() } func (c *fieldFunc) average() []float64 { return qAverageUniverse(c) } func (c *fieldFunc) EvalTo(dst *data.Slice) { EvalTo(c, dst) } // Calculates and returns the quantity. // recycle is true: slice needs to be recycled. func (q *fieldFunc) Slice() (s *data.Slice, recycle bool) { buf := cuda.Buffer(q.NComp(), q.Mesh().Size()) cuda.Zero(buf) q.f(buf) return buf, true } // ScalarField enhances an outputField with methods specific to // a space-dependent scalar quantity. type ScalarField struct { Quantity } // AsScalarField promotes a quantity to a ScalarField, // enabling convenience methods particular to scalars. func AsScalarField(q Quantity) ScalarField { if q.NComp() != 1 { panic(fmt.Errorf("ScalarField(%v): need 1 component, have: %v", NameOf(q), q.NComp())) } return ScalarField{q} } func (s ScalarField) average() []float64 { return AverageOf(s.Quantity) } func (s ScalarField) Average() float64 { return s.average()[0] } func (s ScalarField) Region(r int) ScalarField { return AsScalarField(inRegion(s.Quantity, r)) } func (s ScalarField) Name() string { return NameOf(s.Quantity) } func (s ScalarField) Unit() string { return UnitOf(s.Quantity) } // VectorField enhances an outputField with methods specific to // a space-dependent vector quantity. type VectorField struct { Quantity } // AsVectorField promotes a quantity to a VectorField, // enabling convenience methods particular to vectors. func AsVectorField(q Quantity) VectorField { if q.NComp() != 3 { panic(fmt.Errorf("VectorField(%v): need 3 components, have: %v", NameOf(q), q.NComp())) } return VectorField{q} } func (v VectorField) average() []float64 { return AverageOf(v.Quantity) } func (v VectorField) Average() data.Vector { return unslice(v.average()) } func (v VectorField) Region(r int) VectorField { return AsVectorField(inRegion(v.Quantity, r)) } func (v VectorField) Comp(c int) ScalarField { return AsScalarField(Comp(v.Quantity, c)) } func (v VectorField) Mesh() *data.Mesh { return MeshOf(v.Quantity) } func (v VectorField) Name() string { return NameOf(v.Quantity) } func (v VectorField) Unit() string { return UnitOf(v.Quantity) } func (v VectorField) HostCopy() *data.Slice { s := ValueOf(v.Quantity) defer cuda.Recycle(s) return s.HostCopy() }
engine/outputquantities.go
0.792745
0.476519
outputquantities.go
starcoder
package hex import ( "fmt" ) const ( // DirectionCount is const to be used for arrays and calculations. DirectionCount = 6 ) // LineSign is alias for float64 to determine it from other real values. type LineSign float64 // Line signs. // LSPlus means counterclockwise path with ray connecting start hex with end one being traced on edge. // LSMinus means clockwise path with ray connecting start hex with end one being traced on edge. // LSZero means that there are no such ray or unknown direction. const ( LSPlus LineSign = 1 LSMinus LineSign = -1 LSZero LineSign = 0 ) // String implements fmt.Stringer interface. func (ls LineSign) String() string { switch ls { case LSPlus: return "line sign plus" case LSMinus: return "line sign minus" case LSZero: return "line sign zero" } return fmt.Sprintf("%f", ls) } // Hex is coordinates at Hexagonal Grid. type Hex struct { q, r, s int } // Directions. var ( ZE = Hex{0, 0, 0} EE = Hex{1, 0, -1} NE = Hex{1, -1, 0} NW = Hex{0, -1, 1} WW = Hex{-1, 0, 1} SW = Hex{-1, 1, 0} SE = Hex{0, 1, -1} directions = [...]Hex{EE, NE, NW, WW, SW, SE} ) // New returns Hex object. It's convenient to use object but neither pointer. func New(q, r int) Hex { return Hex{q: q, r: r, s: -q - r} } // NewWithArray returns new Hex object represented as array. func NewWithArray(a [2]int) Hex { return New(a[0], a[1]) } // Q returns Hex.q coordinate. func (h Hex) Q() int { return h.q } // R returns Hex.r coordinate. func (h Hex) R() int { return h.r } // S returns Hex.s coordinate. func (h Hex) S() int { return h.s } // Equal returns true if Hexes h and t are equal. func (h Hex) Equal(t Hex) bool { return h.q == t.q && h.r == t.r && h.s == t.s } // Add returns Hex that equals sum of h and t. func (h Hex) Add(t Hex) Hex { return New(h.q+t.q, h.r+t.r) } // Sub returns Hex that equals difference of h and t. func (h Hex) Sub(t Hex) Hex { return New(h.q-t.q, h.r-t.r) } // Mul returns Hex that equals h multiplied by k. func (h Hex) Mul(k int) Hex { return New(h.q*k, h.r*k) } // Len returns radius-vector of Hex. func (h Hex) Len() int { // nolint:gomnd return (absInt(h.q) + absInt(h.r) + absInt(h.s)) / 2 } // Distance returns distance between h and t. func (h Hex) Distance(t Hex) int { return h.Sub(t).Len() } // Neighbor returns neighbor Hex of h to direction d. func (h Hex) Neighbor(d int) Hex { return h.Add(Direction(d)) } // Direction returns index of direction. func (h Hex) Direction(t Hex, sign LineSign) int { l := h.Line(t, sign) if len(l) <= 1 { // Top direction return DirectionCount } r := l[1].Sub(l[0]) for i := 0; i < DirectionCount; i++ { if directions[i] == r { return i } } // Error return -1 } // RingAtDistance returns ring. func (h Hex) RingAtDistance(d int, res []Hex) { if d <= 0 { return } t := h.Add(SW.Mul(d)) for i := 0; i < DirectionCount; i++ { for j := 0; j < d; j++ { res[i*d+j] = t t = t.Neighbor(i) } } } // NeighborsAtDistance returns all neighbors Hex of h on distance d. func (h Hex) NeighborsAtDistance(d int, res []Hex) { for i := 1; i <= d; i++ { j := AreaAtDistance(i-1) - 1 k := AreaAtDistance(i) - 1 h.RingAtDistance(i, res[j:k]) } } // Line returns Hexes from h to t. func (h Hex) Line(t Hex, sign LineSign) (res []Hex) { n := h.Distance(t) step := 1 / float64(maxInt(n, 1)) for i := 0; i <= n; i++ { res = append(res, hexLerp(h, t, step*float64(i), float64(sign)).round()) } return res } // String returns string representation of Hex. It implements Stringer interface. func (h Hex) String() string { return fmt.Sprintf("%v", h.Array()) } // Title returns string representation of Hex. func (h Hex) Title() string { switch h { case ZE: return "zero" case EE: return "east" case NE: return "north-east" case NW: return "north-west" case WW: return "west" case SW: return "south-west" case SE: return "south-east" } return fmt.Sprintf("%d,%d", h.q, h.r) } // Array returns base type representation of Hex. func (h Hex) Array() [2]int { return [2]int{h.q, h.r} } // CompareSlices returns true if slices a and b have equal length and elements at same positions. func CompareSlices(a, b []Hex) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } // InverseDirection returns inverter direction for specified. func InverseDirection(d int) int { return (((DirectionCount + (d % DirectionCount)) % DirectionCount) + DirectionCount/2) % DirectionCount } // NormalizeDirection returns normalized value direction for specified. func NormalizeDirection(d int) int { return (DirectionCount + (d % DirectionCount)) % DirectionCount } // PrettyDirection returns pretty representation of direction. func PrettyDirection(d int) string { if d == DirectionCount { return ZE.Title() } return Direction(d).Title() } // RingLenAtDistance returns length of ring at specified distance. func RingLenAtDistance(r int) int { // nolint:gomnd return 6 * r } // AreaAtDistance returns amount of all hexes limited by ring at specified distance // including center hex and ring. func AreaAtDistance(r int) int { return 1 + 3*r*(r+1) } // Direction returns hex by direction. func Direction(d int) Hex { return directions[NormalizeDirection(d)] }
hex.go
0.834339
0.463262
hex.go
starcoder
package counts import ( "math" ) // A count of something, capped at math.MaxUint32. type Count32 uint32 func NewCount32(n uint64) Count32 { if n > math.MaxUint32 { return Count32(math.MaxUint32) } return Count32(n) } func (n Count32) ToUint64() uint64 { return uint64(n) } // Return the sum of two Count32s, capped at math.MaxUint32. func (n1 Count32) Plus(n2 Count32) Count32 { n := n1 + n2 if n < n1 { // Overflow return math.MaxUint32 } return n } // Increment `*n1` by `n2`, capped at math.MaxUint32. func (n1 *Count32) Increment(n2 Count32) { *n1 = n1.Plus(n2) } // AdjustMaxIfNecessary adjusts `*n1` to be `max(*n1, n2)`. Return // true iff `n2` was greater than `*n1`. func (n1 *Count32) AdjustMaxIfNecessary(n2 Count32) bool { if n2 > *n1 { *n1 = n2 return true } else { return false } } // AdjustMaxIfPossible adjusts `*n1` to be `max(*n1, n2)`. Return true // iff `n2` was greater than or equal to `*n1`. func (n1 *Count32) AdjustMaxIfPossible(n2 Count32) bool { if n2 >= *n1 { *n1 = n2 return true } else { return false } } // A count of something, capped at math.MaxUint64. type Count64 uint64 func NewCount64(n uint64) Count64 { return Count64(n) } func (n Count64) ToUint64() uint64 { return uint64(n) } // Return the sum of two Count64s, capped at math.MaxUint64. func (n1 Count64) Plus(n2 Count64) Count64 { n := n1 + n2 if n < n1 { // Overflow return math.MaxUint64 } return n } // Increment `*n1` by `n2`, capped at math.MaxUint64. func (n1 *Count64) Increment(n2 Count64) { *n1 = n1.Plus(n2) } // AdjustMaxIfNecessary adjusts `*n1` to be `max(*n1, n2)`. Return // true iff `n2` was greater than `*n1`. func (n1 *Count64) AdjustMaxIfNecessary(n2 Count64) bool { if n2 > *n1 { *n1 = n2 return true } else { return false } } // AdjustMaxIfPossible adjusts `*n1` to be `max(*n1, n2)`. Return true // iff `n2` was greater than or equal to `*n1`. func (n1 *Count64) AdjustMaxIfPossible(n2 Count64) bool { if n2 > *n1 { *n1 = n2 return true } else { return false } }
counts/counts.go
0.804214
0.40439
counts.go
starcoder
package ast import ( "bytes" "fmt" "regexp" "strings" ) // Defines the different types a token can be const ( TypeID = "ID" TypeNumber = "Number" TypeString = "String" TypeKeyword = "Keyword" TypeSymbol = "Symbol" TypeNewline = "Newline" TypeEOF = "EOF" TypeComment = "Comment" TypeWhitespace = "Whitespace" TypeUnknown = "Unknown" ) // Position represents the starting-position of a token in the source-code type Position struct { File string Line int Coloumn int } // NewPosition creates a new position from a given line and coloumn func NewPosition(file string, line int, coloumn int) Position { return Position{ File: file, Line: line, Coloumn: coloumn, } } // UnknownPosition is used, when a position is expected, but a real one can not be provided // Usually used by ast-elements that rely on their children to determin their position, if the children are nil var UnknownPosition = Position{} func (p Position) String() string { if p.File != "" { return fmt.Sprintf("%s:%d:%d", p.File, p.Line, p.Coloumn) } return fmt.Sprintf("Line: %d, Coloumn: %d", p.Line, p.Coloumn) } // Add creates a new position from the old one and adds the given amount of coloumns func (p Position) Add(col int) Position { p.Coloumn += col return p } // Before returns true if p represents a position in the file before the position of other func (p Position) Before(other Position) bool { if p.Line < other.Line { return true } if p.Line == other.Line && p.Coloumn < other.Coloumn { return true } return false } // !!= is a hack, meaning "factorial followed by equal" var symbols = []string{"!==", "++", "--", ">=", "<=", "!=", "==", "==", "+=", "-=", "*=", "/=", "%=", "^=", "=", ">", "<", "+", "-", "*", "/", "^", "%", ",", "(", ")", "!"} var keywordRegex1 = regexp.MustCompile(`(?i)^(and|or|not|abs|sqrt|sin|cos|tan|asin|acos|atan)(?:[^a-zA-Z0-9_:]|$)`) var keywordRegex2 = regexp.MustCompile(`(?i)^(if|then|else|end|goto)`) var keywordRegexes = []*regexp.Regexp{keywordRegex1, keywordRegex2} var identifierRegex = regexp.MustCompile("^:[a-zA-Z0-9_:]+|^[a-zA-Z]+[a-zA-Z0-9_]*") var numberRegex = regexp.MustCompile("^[0-9]+(\\.[0-9]+)?") var commentRegex = regexp.MustCompile("^\\/\\/([^\n]*)") var whitespaceRegex = regexp.MustCompile("^[ \\t\r]+") // Token represents a token fount in the source-code type Token struct { Type string Value string Position Position } func (t Token) String() string { str := fmt.Sprintf("%s, Type: %s", t.Position.String(), t.Type) if t.Value != "" { str += ", Value: '" + t.Value + "'" } str += "\n" return str } // Tokenizer splits the input source-code into tokens type Tokenizer struct { filename string text string remaining []byte line int column int currentToken Token // List of symbols the tokenizer should recognize Symbols []string // KeywordRegexes are used to parse keywords KeywordRegexes []*regexp.Regexp // IdentifierRegex is used to parse identifiers IdentifierRegex *regexp.Regexp // NumberRegex is used to parse numbers NumberRegex *regexp.Regexp // CommentRegex is used to parse comments CommentRegex *regexp.Regexp } type TokenizerCheckpoint struct { Remaining []byte Line int Column int } // NewTokenizer creates a new tokenizer func NewTokenizer() *Tokenizer { tk := &Tokenizer{ Symbols: symbols, KeywordRegexes: keywordRegexes, IdentifierRegex: identifierRegex, NumberRegex: numberRegex, CommentRegex: commentRegex, } return tk } // SetFilename sets the filename that is set in the position if all returned tokens func (t *Tokenizer) SetFilename(name string) { t.filename = name } // Checkpoint returns a checkpoint that can be used to restore the Tokenizer to the current state func (t *Tokenizer) Checkpoint() TokenizerCheckpoint { return TokenizerCheckpoint{ Remaining: t.remaining, Line: t.line, Column: t.column, } } // Restore uses the given Checkpoint to revert the Tokenizer to a previous state func (t *Tokenizer) Restore(cp TokenizerCheckpoint) { t.remaining = cp.Remaining t.line = cp.Line t.column = cp.Column } func (t *Tokenizer) newToken(typ string, val string) *Token { return &Token{ Type: typ, Value: val, Position: Position{ File: t.filename, Line: t.line, Coloumn: t.column, }, } } // Load loads programm code as input func (t *Tokenizer) Load(input string) { t.column = 1 t.text = input t.remaining = []byte(input) t.line = 1 } // Next returns the next token from the source document and advances the curent position in the input func (t *Tokenizer) Next() *Token { token, size := t.getToken() if token.Type == TypeNewline { t.line++ t.column = 0 } if token.Type != TypeEOF { t.column += size t.remaining = t.remaining[size:] } return token } // Peek returns the next token from the source document BUT keeps the current position unchanged func (t *Tokenizer) Peek() *Token { token, _ := t.getToken() return token } // getToken finds the next token in the input // it returns a token and the length of consumed input func (t *Tokenizer) getToken() (*Token, int) { token, size := t.getComment() if token != nil { return token, size } // no need to tokenize an empty string if len(t.remaining) == 0 { return t.newToken(TypeEOF, ""), 0 } token, size = t.getWhitespace() if token != nil { return token, size } token, size = t.getKeyword() if token != nil { return token, size } token, size = t.getNewline() if token != nil { return token, size } token, size = t.getSymbol() if token != nil { return token, size } token, size = t.getIdentifier() if token != nil { return token, size } token, size = t.getStringConstant() if token != nil { return token, size } token, size = t.getNumberConstant() if token != nil { return token, size } return t.newToken(TypeUnknown, string(t.remaining[0])), 1 } func (t *Tokenizer) getWhitespace() (*Token, int) { found := whitespaceRegex.Find(t.remaining) if found != nil { return t.newToken(TypeWhitespace, string(found)), len(found) } return nil, 0 } func (t *Tokenizer) getNewline() (*Token, int) { if len(t.remaining) > 0 && t.remaining[0] == '\n' { token := t.newToken(TypeNewline, "") return token, 1 } return nil, 0 } func (t *Tokenizer) getSymbol() (*Token, int) { for i := range t.Symbols { symbol := []byte(t.Symbols[i]) if bytes.HasPrefix(t.remaining, symbol) { if t.Symbols[i] == "!==" { // this special case is needed, as otherwise !== would be parsed as "!= =", but it shold be "! ==" return t.newToken(TypeSymbol, "!"), 1 } return t.newToken(TypeSymbol, string(symbol)), len(symbol) } } return nil, 0 } func (t *Tokenizer) getComment() (*Token, int) { found := t.CommentRegex.Find(t.remaining) if found != nil { return t.newToken(TypeComment, string(found)), len(found) } return nil, 0 } func (t *Tokenizer) getKeyword() (*Token, int) { for _, regex := range t.KeywordRegexes { found := regex.FindSubmatch(t.remaining) if found != nil { kw := found[1] // keywords are always treated as lowercase tok := t.newToken(TypeKeyword, strings.ToLower(string(kw))) return tok, len(found[1]) } } return nil, 0 } func (t *Tokenizer) getIdentifier() (*Token, int) { found := t.IdentifierRegex.Find(t.remaining) if found != nil { // do not convert value to lowercase. // the parser deals with casing return t.newToken(TypeID, string(found)), len(found) } return nil, 0 } func (t *Tokenizer) getStringConstant() (*Token, int) { if len(t.remaining) < 2 || t.remaining[0] != '"' { return nil, 0 } escaped := false str := "" for i, b := range t.remaining[1:] { if b == '\\' { escaped = true continue } if escaped { switch b { case 'n': str += "\n" escaped = false continue case 't': str += "\t" escaped = false continue case '"': str += "\"" escaped = false continue } } if b == '"' { return t.newToken(TypeString, str), i + 2 } str += string(b) } return nil, 0 } func (t *Tokenizer) getNumberConstant() (*Token, int) { found := t.NumberRegex.Find(t.remaining) if found != nil { return t.newToken(TypeNumber, string(found)), len(found) } return nil, 0 }
pkg/parser/ast/tokenizer.go
0.645679
0.418697
tokenizer.go
starcoder
package e2e import ( "context" "fmt" "testing" "time" "github.com/nuczzz/virtual-kubelet/internal/podutils" stats "github.com/nuczzz/virtual-kubelet/node/api/statsv1alpha1" "gotest.tools/assert" v1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" ) const ( // deleteGracePeriodForProvider is the maximum amount of time we allow for the provider to react to deletion of a pod // before proceeding to assert that the pod has been deleted. deleteGracePeriodForProvider = 1 * time.Second ) // TestGetPods tests that the /pods endpoint works, and only returns pods for our kubelet func (ts *EndToEndTestSuite) TestGetPods(t *testing.T) { ctx := context.Background() // Create a pod with prefix "nginx-" having a single container. podSpec := f.CreateDummyPodObjectWithPrefix(t.Name(), "nginx", "foo") podSpec.Spec.NodeName = f.NodeName nginx, err := f.CreatePod(ctx, podSpec) if err != nil { t.Fatal(err) } // Delete the pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, nginx.Namespace, nginx.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() t.Logf("Created pod: %s", nginx.Name) // Wait for the "nginx-" pod to be reported as running and ready. if _, err := f.WaitUntilPodReady(nginx.Namespace, nginx.Name); err != nil { t.Fatal(err) } t.Logf("Pod %s ready", nginx.Name) k8sPods, err := f.GetRunningPodsFromKubernetes(ctx) if err != nil { t.Fatal(err) } podFound := false for _, pod := range k8sPods.Items { if pod.Spec.NodeName != f.NodeName { t.Fatalf("Found pod with node name %s, whereas expected %s", pod.Spec.NodeName, f.NodeName) } if pod.UID == nginx.UID { podFound = true } } if !podFound { t.Fatal("Nginx pod not found") } } // TestGetStatsSummary creates a pod having two containers and queries the /stats/summary endpoint of the virtual-kubelet. // It expects this endpoint to return stats for the current node, as well as for the aforementioned pod and each of its two containers. func (ts *EndToEndTestSuite) TestGetStatsSummary(t *testing.T) { ctx := context.Background() // Create a pod with prefix "nginx-" having three containers. pod, err := f.CreatePod(ctx, f.CreateDummyPodObjectWithPrefix(t.Name(), "nginx", "foo", "bar", "baz")) if err != nil { t.Fatal(err) } // Delete the "nginx-0-X" pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() // Wait for the "nginx-" pod to be reported as running and ready. if _, err := f.WaitUntilPodReady(pod.Namespace, pod.Name); err != nil { t.Fatal(err) } // Grab the stats from the provider. stats, err := f.GetStatsSummary(ctx) if err != nil { t.Fatal(err) } // Make sure that we've got stats for the current node. if stats.Node.NodeName != f.NodeName { t.Fatalf("expected stats for node %s, got stats for node %s", f.NodeName, stats.Node.NodeName) } // Make sure the "nginx-" pod exists in the slice of PodStats. idx, err := findPodInPodStats(stats, pod) if err != nil { t.Fatal(err) } // Make sure that we've got stats for all the containers in the "nginx-" pod. desiredContainerStatsCount := len(pod.Spec.Containers) currentContainerStatsCount := len(stats.Pods[idx].Containers) if currentContainerStatsCount != desiredContainerStatsCount { t.Fatalf("expected stats for %d containers, got stats for %d containers", desiredContainerStatsCount, currentContainerStatsCount) } } // TestPodLifecycleGracefulDelete creates a pod and verifies that the provider has been asked to create it. // Then, it deletes the pods and verifies that the provider has been asked to delete it. // These verifications are made using the /stats/summary endpoint of the virtual-kubelet, by checking for the presence or absence of the pods. // Hence, the provider being tested must implement the PodMetricsProvider interface. func (ts *EndToEndTestSuite) TestPodLifecycleGracefulDelete(t *testing.T) { ctx := context.Background() // Create a pod with prefix "nginx-" having a single container. podSpec := f.CreateDummyPodObjectWithPrefix(t.Name(), "nginx", "foo") podSpec.Spec.NodeName = f.NodeName pod, err := f.CreatePod(ctx, podSpec) if err != nil { t.Fatal(err) } // Delete the pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() t.Logf("Created pod: %s", pod.Name) // Wait for the "nginx-" pod to be reported as running and ready. if _, err := f.WaitUntilPodReady(pod.Namespace, pod.Name); err != nil { t.Fatal(err) } t.Logf("Pod %s ready", pod.Name) // Grab the pods from the provider. pods, err := f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Check if the pod exists in the slice of PodStats. assert.NilError(t, findPodInPods(pods, pod)) podCh := make(chan error) var podLast *v1.Pod go func() { // Close the podCh channel, signaling we've observed deletion of the pod. defer close(podCh) var err error podLast, err = f.WaitUntilPodDeleted(pod.Namespace, pod.Name) if err != nil { // Propagate the error to the outside so we can fail the test. podCh <- err } }() // Gracefully delete the "nginx-" pod. if err := f.DeletePod(ctx, pod.Namespace, pod.Name); err != nil { t.Fatal(err) } t.Logf("Deleted pod: %s", pod.Name) // Wait for the delete event to be ACKed. if err := <-podCh; err != nil { t.Fatal(err) } time.Sleep(deleteGracePeriodForProvider) // Give the provider some time to react to the MODIFIED/DELETED events before proceeding. // Grab the pods from the provider. pods, err = f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Make sure the pod DOES NOT exist in the provider's set of running pods assert.Assert(t, findPodInPods(pods, pod) != nil) // Make sure we saw the delete event, and the delete event was graceful assert.Assert(t, podLast != nil) assert.Assert(t, podLast.ObjectMeta.GetDeletionGracePeriodSeconds() != nil) assert.Assert(t, *podLast.ObjectMeta.GetDeletionGracePeriodSeconds() > 0) } // TestPodLifecycleForceDelete creates one podsand verifies that the provider has created them // and put them in the running lifecycle. It then does a force delete on the pod, and verifies the provider // has deleted it. func (ts *EndToEndTestSuite) TestPodLifecycleForceDelete(t *testing.T) { ctx := context.Background() podSpec := f.CreateDummyPodObjectWithPrefix(t.Name(), "nginx", "foo") // Create a pod with prefix having a single container. pod, err := f.CreatePod(ctx, podSpec) if err != nil { t.Fatal(err) } // Delete the pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() t.Logf("Created pod: %s", pod.Name) // Wait for the "nginx-" pod to be reported as running and ready. if _, err := f.WaitUntilPodReady(pod.Namespace, pod.Name); err != nil { t.Fatal(err) } t.Logf("Pod %s ready", pod.Name) // Grab the pods from the provider. pods, err := f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Check if the pod exists in the slice of Pods. assert.NilError(t, findPodInPods(pods, pod)) // Wait for the pod to be deleted in a separate goroutine. // This ensures that we don't possibly miss the MODIFIED/DELETED events due to establishing the watch too late in the process. // It also makes sure that in light of soft deletes, we properly handle non-graceful pod deletion podCh := make(chan error) var podLast *v1.Pod go func() { // Close the podCh channel, signaling we've observed deletion of the pod. defer close(podCh) var err error // Wait for the pod to be reported as having been deleted. podLast, err = f.WaitUntilPodDeleted(pod.Namespace, pod.Name) if err != nil { // Propagate the error to the outside so we can fail the test. podCh <- err } }() time.Sleep(deleteGracePeriodForProvider) // Forcibly delete the pod. if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil { t.Logf("Last saw pod in state: %+v", podLast) t.Fatal(err) } t.Log("Force deleted pod: ", pod.Name) // Wait for the delete event to be ACKed. if err := <-podCh; err != nil { t.Logf("Last saw pod in state: %+v", podLast) t.Fatal(err) } // Give the provider some time to react to the MODIFIED/DELETED events before proceeding. time.Sleep(deleteGracePeriodForProvider) // Grab the pods from the provider. pods, err = f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Make sure the "nginx-" pod DOES NOT exist in the slice of Pods anymore. assert.Assert(t, findPodInPods(pods, pod) != nil) t.Logf("Pod ended as phase: %+v", podLast.Status.Phase) } // TestCreatePodWithOptionalInexistentSecrets tries to create a pod referencing optional, inexistent secrets. // It then verifies that the pod is created successfully. func (ts *EndToEndTestSuite) TestCreatePodWithOptionalInexistentSecrets(t *testing.T) { ctx := context.Background() // Create a pod with a single container referencing optional, inexistent secrets. pod, err := f.CreatePod(ctx, f.CreatePodObjectWithOptionalSecretKey(t.Name())) if err != nil { t.Fatal(err) } // Delete the pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() // Wait for the pod to be reported as running and ready. if _, err := f.WaitUntilPodReady(pod.Namespace, pod.Name); err != nil { t.Fatal(err) } // Wait for an event concerning the missing secret to be reported on the pod. if err := f.WaitUntilPodEventWithReason(pod, podutils.ReasonOptionalSecretNotFound); err != nil { t.Fatal(err) } // Grab the pods from the provider. pods, err := f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Check if the pod exists in the slice of Pods. assert.NilError(t, findPodInPods(pods, pod)) } // TestCreatePodWithMandatoryInexistentSecrets tries to create a pod referencing inexistent secrets. // It then verifies that the pod is not created. func (ts *EndToEndTestSuite) TestCreatePodWithMandatoryInexistentSecrets(t *testing.T) { ctx := context.Background() // Create a pod with a single container referencing inexistent secrets. pod, err := f.CreatePod(ctx, f.CreatePodObjectWithMandatorySecretKey(t.Name())) if err != nil { t.Fatal(err) } // Delete the pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() // Wait for an event concerning the missing secret to be reported on the pod. if err := f.WaitUntilPodEventWithReason(pod, podutils.ReasonMandatorySecretNotFound); err != nil { t.Fatal(err) } // Grab the pods from the provider. pods, err := f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Check if the pod exists in the slice of PodStats. assert.Assert(t, findPodInPods(pods, pod) != nil) } // TestCreatePodWithOptionalInexistentConfigMap tries to create a pod referencing optional, inexistent config map. // It then verifies that the pod is created successfully. func (ts *EndToEndTestSuite) TestCreatePodWithOptionalInexistentConfigMap(t *testing.T) { ctx := context.Background() // Create a pod with a single container referencing optional, inexistent config map. pod, err := f.CreatePod(ctx, f.CreatePodObjectWithOptionalConfigMapKey(t.Name())) if err != nil { t.Fatal(err) } // Delete the pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() // Wait for the pod to be reported as running and ready. if _, err := f.WaitUntilPodReady(pod.Namespace, pod.Name); err != nil { t.Fatal(err) } // Wait for an event concerning the missing config map to be reported on the pod. if err := f.WaitUntilPodEventWithReason(pod, podutils.ReasonOptionalConfigMapNotFound); err != nil { t.Fatal(err) } // Grab the pods from the provider. pods, err := f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Check if the pod exists in the slice of PodStats. assert.NilError(t, findPodInPods(pods, pod)) } // TestCreatePodWithMandatoryInexistentConfigMap tries to create a pod referencing inexistent secrets. // It then verifies that the pod is not created. func (ts *EndToEndTestSuite) TestCreatePodWithMandatoryInexistentConfigMap(t *testing.T) { ctx := context.Background() // Create a pod with a single container referencing inexistent config map. pod, err := f.CreatePod(ctx, f.CreatePodObjectWithMandatoryConfigMapKey(t.Name())) if err != nil { t.Fatal(err) } // Delete the pod after the test finishes. defer func() { if err := f.DeletePodImmediately(ctx, pod.Namespace, pod.Name); err != nil && !apierrors.IsNotFound(err) { t.Error(err) } }() // Wait for an event concerning the missing config map to be reported on the pod. if err := f.WaitUntilPodEventWithReason(pod, podutils.ReasonMandatoryConfigMapNotFound); err != nil { t.Fatal(err) } // Grab the pods from the provider. pods, err := f.GetRunningPodsFromProvider(ctx) assert.NilError(t, err) // Check if the pod exists in the slice of PodStats. assert.Assert(t, findPodInPods(pods, pod) != nil) } // findPodInPodStats returns the index of the specified pod in the .pods field of the specified Summary object. // It returns an error if the specified pod is not found. func findPodInPodStats(summary *stats.Summary, pod *v1.Pod) (int, error) { for i, p := range summary.Pods { if p.PodRef.Namespace == pod.Namespace && p.PodRef.Name == pod.Name && string(p.PodRef.UID) == string(pod.UID) { return i, nil } } return -1, fmt.Errorf("failed to find pod \"%s/%s\" in the slice of pod stats", pod.Namespace, pod.Name) } // findPodInPodStats returns the index of the specified pod in the .pods field of the specified PodList object. // It returns error if the pod doesn't exist in the podlist func findPodInPods(pods *v1.PodList, pod *v1.Pod) error { for _, p := range pods.Items { if p.Namespace == pod.Namespace && p.Name == pod.Name && string(p.UID) == string(pod.UID) { return nil } } return fmt.Errorf("failed to find pod \"%s/%s\" in the slice of pod list", pod.Namespace, pod.Name) }
test/e2e/basic.go
0.586404
0.428891
basic.go
starcoder
package mutable /* 307. 区域和检索 - 数组可修改 https://leetcode-cn.com/problems/range-sum-query-mutable 给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。 update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。 示例: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8 说明: 数组仅可以在 update 函数下进行修改。 你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。 */ /* 线段树,节点版 1.构建一棵满二叉树,叶子节点存储原始nums 2.根节点的索引是1 3.左子树节点的索引为偶数 右子树节点的索引为奇数 4.叶子节点的索引范围[n,2n-1] */ type NumArray1 struct { root *Node } func Constructor1(nums []int) NumArray1 { return NumArray1{root: buildTree(nums)} } func (na *NumArray1) Update1(i int, val int) { na.root.Update(i, val) } func (na *NumArray1) SumRange1(i int, j int) int { return na.root.SumRange(i, j) } type Node struct { left, right *Node start, end, sum int } func buildTree(nums []int) *Node { if len(nums) == 0 { return nil } var help func(i, j int) *Node help = func(i, j int) *Node { if i == j { return &Node{start: i, end: i, sum: nums[i]} } mid := (i + j) / 2 left := help(i, mid) right := help(mid+1, j) return &Node{ left: left, right: right, start: i, end: j, sum: left.sum + right.sum, } } return help(0, len(nums)-1) } func (n *Node) Update(i, val int) { if i == n.start && i == n.end { n.sum = val return } mid := (n.start + n.end) / 2 if i <= mid { n.left.Update(i, val) } else { n.right.Update(i, val) } n.sum = n.left.sum + n.right.sum } func (n *Node) SumRange(i, j int) int { if i == n.start && j == n.end { return n.sum } mid := (n.start + n.end) / 2 if j <= mid { return n.left.SumRange(i, j) } if i > mid { return n.right.SumRange(i, j) } return n.left.SumRange(i, mid) + n.right.SumRange(mid+1, j) } /* 数组版线段树 */ type NumArray struct { tree []int n int } func Constructor(nums []int) NumArray { if len(nums) == 0 { return NumArray{tree: nil} } n := len(nums) tree := make([]int, 2*n) for i, v := range nums { tree[i+n] = v } for i := n - 1; i >= 0; i-- { tree[i] = tree[2*i] + tree[2*i+1] } return NumArray{tree: tree, n: n} } func (na *NumArray) Update(i int, val int) { i += na.n na.tree[i] = val for i > 0 { left, right := i, i if i%2 == 0 { right = i + 1 } else { left = i - 1 } na.tree[i/2] = na.tree[left] + na.tree[right] i /= 2 } } func (na *NumArray) SumRange(i int, j int) int { i += na.n j += na.n sum := 0 for i <= j { // 线段树左子节点都是偶数下标2n,右子节点都是奇数下标2n+1. if i%2 == 1 { // 左指针指向了一个右端点 sum += na.tree[i] i++ } if j%2 == 0 { // 右指针指向了一个左端点 sum += na.tree[j] j-- } i /= 2 j /= 2 } return sum }
solutions/range-sum-query-mutable/d.go
0.563138
0.419232
d.go
starcoder
Get access to client objects To initialize client objects you can use the setup function. It returns a clients struct that contains initialized clients for accessing: - Kubernetes objects - Pipelines (https://github.com/knative/build-pipeline#pipeline) For example, to create a Pipeline _, err = clients.PipelineClient.Pipelines.Create(test.Pipeline(namespaceName, pipelineName)) And you can use the client to clean up resources created by your test func tearDown(clients *test.Clients) { if clients != nil { clients.Delete([]string{routeName}, []string{configName}) } } */ package test import ( "testing" "github.com/knative/build-pipeline/pkg/client/clientset/versioned" "github.com/knative/build-pipeline/pkg/client/clientset/versioned/typed/pipeline/v1alpha1" knativetest "github.com/knative/pkg/test" ) // clients holds instances of interfaces for making requests to the Pipeline controllers. type clients struct { KubeClient *knativetest.KubeClient PipelineClient v1alpha1.PipelineInterface TaskClient v1alpha1.TaskInterface TaskRunClient v1alpha1.TaskRunInterface PipelineRunClient v1alpha1.PipelineRunInterface PipelineResourceClient v1alpha1.PipelineResourceInterface } // newClients instantiates and returns several clientsets required for making requests to the // Pipeline cluster specified by the combination of clusterName and configPath. Clients can // make requests within namespace. func newClients(t *testing.T, configPath, clusterName, namespace string) *clients { t.Helper() var err error c := &clients{} c.KubeClient, err = knativetest.NewKubeClient(configPath, clusterName) if err != nil { t.Fatalf("failed to create kubeclient from config file at %s: %s", configPath, err) } cfg, err := knativetest.BuildClientConfig(configPath, clusterName) if err != nil { t.Fatalf("failed to create configuration obj from %s for cluster %s: %s", configPath, clusterName, err) } cs, err := versioned.NewForConfig(cfg) if err != nil { t.Fatalf("failed to create pipeline clientset from config file at %s: %s", configPath, err) } c.PipelineClient = cs.PipelineV1alpha1().Pipelines(namespace) c.TaskClient = cs.PipelineV1alpha1().Tasks(namespace) c.TaskRunClient = cs.PipelineV1alpha1().TaskRuns(namespace) c.PipelineRunClient = cs.PipelineV1alpha1().PipelineRuns(namespace) c.PipelineResourceClient = cs.PipelineV1alpha1().PipelineResources(namespace) return c }
test/clients.go
0.669529
0.40869
clients.go
starcoder
package openflow import ( "fmt" "net" "strings" "github.com/contiv/libOpenflow/openflow13" "github.com/contiv/ofnet/ofctrl" ) type ofFlowBuilder struct { ofFlow } func (b *ofFlowBuilder) Done() Flow { if b.ctStates != nil { b.Flow.Match.CtStates = b.ctStates b.ctStates = nil } if b.ctStateString != "" { b.matchers = append(b.matchers, b.ctStateString) b.ctStateString = "" } if b.lastAction == nil { b.lastAction = ofctrl.NewEmptyElem() } return &b.ofFlow } // MatchReg adds match condition for matching data in the target register. func (b *ofFlowBuilder) MatchReg(regID int, data uint32) FlowBuilder { reg := &ofctrl.NXRegister{ ID: regID, Data: data, } b.Match.NxRegs = append(b.Match.NxRegs, reg) return b } // MatchRegRange adds match condition for matching data in the target register at specified range. func (b *ofFlowBuilder) MatchRegRange(regID int, data uint32, rng Range) FlowBuilder { var regData = data if rng[0] > 0 { regData = data << rng[0] } reg := &ofctrl.NXRegister{ ID: regID, Data: regData, Range: rng.ToNXRange(), } b.Match.NxRegs = append(b.Match.NxRegs, reg) return b } func (b *ofFlowBuilder) addCTStateString(value string) { if b.ctStateString == "" { b.ctStateString = fmt.Sprintf("ct_state=%s", value) } else { b.ctStateString += value } } func (b *ofFlowBuilder) MatchCTStateNew(set bool) FlowBuilder { if b.ctStates == nil { b.ctStates = openflow13.NewCTStates() } if set { b.ctStates.SetNew() b.addCTStateString("+new") } else { b.ctStates.UnsetNew() b.addCTStateString("-trk") } return b } func (b *ofFlowBuilder) MatchCTStateRel(set bool) FlowBuilder { if b.ctStates == nil { b.ctStates = openflow13.NewCTStates() } if set { b.ctStates.SetRel() b.addCTStateString("+rel") } else { b.ctStates.UnsetRel() b.addCTStateString("-rel") } return b } func (b *ofFlowBuilder) MatchCTStateRpl(set bool) FlowBuilder { if b.ctStates == nil { b.ctStates = openflow13.NewCTStates() } if set { b.ctStates.SetRpl() b.addCTStateString("+rpl") } else { b.ctStates.UnsetRpl() b.addCTStateString("-rpl") } return b } func (b *ofFlowBuilder) MatchCTStateEst(set bool) FlowBuilder { if b.ctStates == nil { b.ctStates = openflow13.NewCTStates() } if set { b.ctStates.SetEst() b.addCTStateString("+est") } else { b.ctStates.UnsetEst() b.addCTStateString("-est") } return b } func (b *ofFlowBuilder) MatchCTStateTrk(set bool) FlowBuilder { if b.ctStates == nil { b.ctStates = openflow13.NewCTStates() } if set { b.ctStates.SetTrk() b.addCTStateString("+trk") } else { b.ctStates.UnsetTrk() b.addCTStateString("-trk") } return b } func (b *ofFlowBuilder) MatchCTStateInv(set bool) FlowBuilder { if b.ctStates == nil { b.ctStates = openflow13.NewCTStates() } if set { b.ctStates.SetInv() b.addCTStateString("+inv") } else { b.ctStates.UnsetInv() b.addCTStateString("-inv") } return b } // MatchCTMark adds match condition for matching ct_mark. func (b *ofFlowBuilder) MatchCTMark(value uint32) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("ct_mark=%d", value)) b.ofFlow.Match.CtMark = value return b } // MatchCTMarkMask sets the mask of ct_mark. The mask is used only if ct_mark is set. func (b *ofFlowBuilder) MatchCTMarkMask(mask uint32) FlowBuilder { if b.Flow.Match.CtMark > 0 { b.ofFlow.Match.CtMarkMask = &mask for i, data := range b.matchers { if strings.HasPrefix(data, "ct_mark=") { b.matchers[i] = fmt.Sprintf("%s/0x%x", data, mask) break } } } return b } // MatchInPort adds match condition for matching in_port. func (b *ofFlowBuilder) MatchInPort(inPort uint32) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("in_port=%d", inPort)) b.Match.InputPort = inPort return b } // MatchDstIP adds match condition for matching destination IP address. func (b *ofFlowBuilder) MatchDstIP(ip net.IP) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("nw_dst=%s", ip.String())) b.Match.IpDa = &ip return b } // MatchDstIPNet adds match condition for matching destination IP CIDR. func (b *ofFlowBuilder) MatchDstIPNet(ipnet net.IPNet) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("nw_dst=%s", ipnet.String())) b.Match.IpDa = &ipnet.IP b.Match.IpDaMask = maskToIPv4(ipnet.Mask) return b } func maskToIPv4(mask net.IPMask) *net.IP { ip := net.IPv4(mask[0], mask[1], mask[2], mask[3]) return &ip } // MatchSrcIP adds match condition for matching source IP address. func (b *ofFlowBuilder) MatchSrcIP(ip net.IP) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("nw_src=%s", ip.String())) b.Match.IpSa = &ip return b } // MatchSrcIPNet adds match condition for matching source IP CIDR. func (b *ofFlowBuilder) MatchSrcIPNet(ipnet net.IPNet) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("nw_src=%s", ipnet.String())) b.Match.IpSa = &ipnet.IP b.Match.IpSaMask = maskToIPv4(ipnet.Mask) return b } // MatchDstMAC adds match condition for matching destination MAC address. func (b *ofFlowBuilder) MatchDstMAC(mac net.HardwareAddr) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("dl_dst=%s", mac.String())) b.Match.MacDa = &mac return b } // MatchSrcMAC adds match condition for matching source MAC address. func (b *ofFlowBuilder) MatchSrcMAC(mac net.HardwareAddr) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("dl_src=%s", mac.String())) b.Match.MacSa = &mac return b } // MatchARPSha adds match condition for matching ARP source host address. func (b *ofFlowBuilder) MatchARPSha(mac net.HardwareAddr) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("arp_sha=%s", mac.String())) b.Match.ArpSha = &mac return b } // MatchARPTha adds match condition for matching ARP target host address. func (b *ofFlowBuilder) MatchARPTha(mac net.HardwareAddr) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("arp_tha=%s", mac.String())) b.Match.ArpTha = &mac return b } // MatchARPSpa adds match condition for matching ARP source protocol address. func (b *ofFlowBuilder) MatchARPSpa(ip net.IP) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("arp_spa=%s", ip.String())) b.Match.ArpSpa = &ip return b } // MatchARPTpa adds match condition for matching ARP target protocol address. func (b *ofFlowBuilder) MatchARPTpa(ip net.IP) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("arp_tpa=%s", ip.String())) b.Match.ArpTpa = &ip return b } // MatchARPOp adds match condition for matching ARP operator. func (b *ofFlowBuilder) MatchARPOp(op uint16) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("arp_op=%d", op)) b.Match.ArpOper = op return b } // MatchConjID adds match condition for matching conj_id. func (b *ofFlowBuilder) MatchConjID(value uint32) FlowBuilder { b.matchers = append(b.matchers, fmt.Sprintf("conj_id=%d", value)) b.Match.ConjunctionID = &value return b } // MatchProtocol adds match condition for matching protocol type. func (b *ofFlowBuilder) MatchProtocol(protocol protocol) FlowBuilder { switch strings.ToLower(protocol) { case ProtocolIP: b.Match.Ethertype = 0x0800 case ProtocolARP: b.Match.Ethertype = 0x0806 case ProtocolTCP: b.Match.Ethertype = 0x0800 b.Match.IpProto = 6 case ProtocolUDP: b.Match.Ethertype = 0x0800 b.Match.IpProto = 17 case ProtocolSCTP: b.Match.Ethertype = 0x0800 b.Match.IpProto = 132 case ProtocolICMP: b.Match.Ethertype = 0x0800 b.Match.IpProto = 1 } b.protocol = protocol return b } // MatchTCPDstPort adds match condition for matching TCP destination port. func (b *ofFlowBuilder) MatchTCPDstPort(port uint16) FlowBuilder { b.MatchProtocol(ProtocolTCP) b.Match.TcpDstPort = port b.matchers = append(b.matchers, fmt.Sprintf("tcp_dst=%d", port)) return b } // MatchUDPDstPort adds match condition for matching UDP destination port. func (b *ofFlowBuilder) MatchUDPDstPort(port uint16) FlowBuilder { b.MatchProtocol(ProtocolUDP) b.Match.UdpDstPort = port b.matchers = append(b.matchers, fmt.Sprintf("udp_dst=%d", port)) return b } // MatchSCTPDstPort adds match condition for matching SCTP destination port. func (b *ofFlowBuilder) MatchSCTPDstPort(port uint16) FlowBuilder { b.MatchProtocol(ProtocolSCTP) b.Match.SctpDstPort = port b.matchers = append(b.matchers, fmt.Sprintf("sctp_dst=%d", port)) return b } // Cookie sets cookie ID for the flow entry. func (b *ofFlowBuilder) Cookie(cookieID uint64) FlowBuilder { b.Flow.CookieID = cookieID return b } // CookieMask sets cookie mask for the flow entry. func (b *ofFlowBuilder) CookieMask(cookieMask uint64) FlowBuilder { b.Flow.CookieMask = cookieMask return b } func (b *ofFlowBuilder) Action() Action { return &ofFlowAction{b} }
pkg/ovs/openflow/ofctrl_builder.go
0.654232
0.454291
ofctrl_builder.go
starcoder
package en_US import "github.com/rannoch/cldr" var calendar = cldr.Calendar{ Formats: cldr.CalendarFormats{ Date: cldr.CalendarDateFormat{Full: "EEEE, MMMM d, y", Long: "MMMM d, y", Medium: "MMM d, y", Short: "M/d/yy"}, Time: cldr.CalendarDateFormat{Full: "h:mm:ss a zzzz", Long: "h:mm:ss a z", Medium: "h:mm:ss a", Short: "h:mm a"}, DateTime: cldr.CalendarDateFormat{Full: "{1} 'at' {0}", Long: "{1} 'at' {0}", Medium: "{1}, {0}", Short: "{1}, {0}"}, }, FormatNames: cldr.CalendarFormatNames{ Months: cldr.CalendarMonthFormatNames{ Abbreviated: cldr.CalendarMonthFormatNameValue{Jan: "Jan", Feb: "Feb", Mar: "Mar", Apr: "Apr", May: "May", Jun: "Jun", Jul: "Jul", Aug: "Aug", Sep: "Sep", Oct: "Oct", Nov: "Nov", Dec: "Dec"}, Narrow: cldr.CalendarMonthFormatNameValue{Jan: "J", Feb: "F", Mar: "M", Apr: "A", May: "M", Jun: "J", Jul: "J", Aug: "A", Sep: "S", Oct: "O", Nov: "N", Dec: "D"}, Short: cldr.CalendarMonthFormatNameValue{}, Wide: cldr.CalendarMonthFormatNameValue{Jan: "January", Feb: "February", Mar: "March", Apr: "April", May: "May", Jun: "June", Jul: "July", Aug: "August", Sep: "September", Oct: "October", Nov: "November", Dec: "December"}, }, Days: cldr.CalendarDayFormatNames{ Abbreviated: cldr.CalendarDayFormatNameValue{Sun: "Sun", Mon: "Mon", Tue: "Tue", Wed: "Wed", Thu: "Thu", Fri: "Fri", Sat: "Sat"}, Narrow: cldr.CalendarDayFormatNameValue{Sun: "S", Mon: "M", Tue: "T", Wed: "W", Thu: "T", Fri: "F", Sat: "S"}, Short: cldr.CalendarDayFormatNameValue{Sun: "Su", Mon: "Mo", Tue: "Tu", Wed: "We", Thu: "Th", Fri: "Fr", Sat: "Sa"}, Wide: cldr.CalendarDayFormatNameValue{Sun: "Sunday", Mon: "Monday", Tue: "Tuesday", Wed: "Wednesday", Thu: "Thursday", Fri: "Friday", Sat: "Saturday"}, }, Periods: cldr.CalendarPeriodFormatNames{ Abbreviated: cldr.CalendarPeriodFormatNameValue{}, Narrow: cldr.CalendarPeriodFormatNameValue{AM: "a", PM: "p"}, Short: cldr.CalendarPeriodFormatNameValue{}, Wide: cldr.CalendarPeriodFormatNameValue{AM: "AM", PM: "PM"}, }, }, }
resources/locales/en_US/calendar.go
0.524882
0.436502
calendar.go
starcoder
package indicators import ( "errors" "github.com/jaybutera/gotrade" ) // A Triangular Moving Average Indicator (Trima), no storage, for use in other indicators type TrimaWithoutStorage struct { *baseIndicatorWithFloatBounds // private variables sma1 *SmaWithoutStorage sma2 *SmaWithoutStorage currentSma float64 timePeriod int } // NewTrimaWithoutStorage creates a Triangular Moving Average Indicator (Trima) without storage func NewTrimaWithoutStorage(timePeriod int, valueAvailableAction ValueAvailableActionFloat) (indicator *TrimaWithoutStorage, err error) { // an indicator without storage MUST have a value available action if valueAvailableAction == nil { return nil, ErrValueAvailableActionIsNil } // the minimum timeperiod for this indicator is 2 if timePeriod < 2 { return nil, errors.New("timePeriod is less than the minimum (2)") } // check the maximum timeperiod if timePeriod > MaximumLookbackPeriod { return nil, errors.New("timePeriod is greater than the maximum (100000)") } lookback := timePeriod - 1 ind := TrimaWithoutStorage{ baseIndicatorWithFloatBounds: newBaseIndicatorWithFloatBounds(lookback, valueAvailableAction), timePeriod: timePeriod, } var sma1Period int var sma2Period int if timePeriod%2 == 0 { // even sma1Period = timePeriod / 2 sma2Period = (timePeriod / 2) + 1 } else { // odd sma1Period = (timePeriod + 1) / 2 sma2Period = (timePeriod + 1) / 2 } ind.sma1, err = NewSmaWithoutStorage(sma1Period, func(dataItem float64, streamBarIndex int) { ind.currentSma = dataItem ind.sma2.ReceiveTick(dataItem, streamBarIndex) }) ind.sma2, _ = NewSmaWithoutStorage(sma2Period, func(dataItem float64, streamBarIndex int) { result := dataItem ind.UpdateIndicatorWithNewValue(result, streamBarIndex) }) return &ind, err } // A Triangular Moving Average Indicator (Trima) type Trima struct { *TrimaWithoutStorage selectData gotrade.DOHLCVDataSelectionFunc // public variables Data []float64 } // NewTrima creates a Triangular Moving Average Indicator (Trima) for online usage func NewTrima(timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Trima, err error) { if selectData == nil { return nil, ErrDOHLCVDataSelectFuncIsNil } ind := Trima{ selectData: selectData, } ind.TrimaWithoutStorage, err = NewTrimaWithoutStorage(timePeriod, func(dataItem float64, streamBarIndex int) { ind.Data = append(ind.Data, dataItem) }) return &ind, err } // NewDefaultTrima creates a Triangular Moving Average Indicator (Trima) for online usage with default parameters // - timePeriod: 30 func NewDefaultTrima() (indicator *Trima, err error) { timePeriod := 30 return NewTrima(timePeriod, gotrade.UseClosePrice) } // NewTrimaWithSrcLen creates a Triangular Moving Average Indicator (Trima) for offline usage func NewTrimaWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Trima, err error) { ind, err := NewTrima(timePeriod, selectData) // only initialise the storage if there is enough source data to require it if sourceLength-uint(ind.GetLookbackPeriod()) > 1 { ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod())) } return ind, err } // NewDefaultTrimaWithSrcLen creates a Triangular Moving Average Indicator (Trima) for offline usage with default parameters func NewDefaultTrimaWithSrcLen(sourceLength uint) (indicator *Trima, err error) { ind, err := NewDefaultTrima() // only initialise the storage if there is enough source data to require it if sourceLength-uint(ind.GetLookbackPeriod()) > 1 { ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod())) } return ind, err } // NewTrimaForStream creates a Triangular Moving Average Indicator (Trima) for online usage with a source data stream func NewTrimaForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Trima, err error) { ind, err := NewTrima(timePeriod, selectData) priceStream.AddTickSubscription(ind) return ind, err } // NewDefaultTrimaForStream creates a Triangular Moving Average Indicator (Trima) for online usage with a source data stream func NewDefaultTrimaForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Trima, err error) { ind, err := NewDefaultTrima() priceStream.AddTickSubscription(ind) return ind, err } // NewTrimaForStreamWithSrcLen creates a Triangular Moving Average Indicator (Trima) for offline usage with a source data stream func NewTrimaForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Trima, err error) { ind, err := NewTrimaWithSrcLen(sourceLength, timePeriod, selectData) priceStream.AddTickSubscription(ind) return ind, err } // NewDefaultTrimaForStreamWithSrcLen creates a Triangular Moving Average Indicator (Trima) for offline usage with a source data stream func NewDefaultTrimaForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Trima, err error) { ind, err := NewDefaultTrimaWithSrcLen(sourceLength) priceStream.AddTickSubscription(ind) return ind, err } // ReceiveDOHLCVTick consumes a source data DOHLCV price tick func (tema *Trima) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) { var selectedData = tema.selectData(tickData) tema.ReceiveTick(selectedData, streamBarIndex) } func (tema *TrimaWithoutStorage) ReceiveTick(tickData float64, streamBarIndex int) { tema.sma1.ReceiveTick(tickData, streamBarIndex) }
indicators/trima.go
0.744656
0.430028
trima.go
starcoder
package evaluator import ( "github.com/niklaskorz/nklang/ast" ) func evaluateExpression(n ast.Expression, scope *definitionScope) (Object, error) { switch e := n.(type) { case *ast.Function: return &Function{Function: e, parentScope: scope}, nil case *ast.Integer: return (*Integer)(e), nil case *ast.String: return (*String)(e), nil case *ast.Boolean: return (*Boolean)(e), nil case *ast.IfExpression: return evaluateIfExpression(e, scope) case *ast.BinaryOperationExpression: return evaluateBinaryExpression(e, scope) case *ast.UnaryOperationExpression: return evaluateUnaryExpression(e, scope) case *ast.LookupExpression: return evaluateLookupExpression(e, scope) case *ast.CallExpression: return evaluateCallExpression(e, scope) } return nil, nil } func evaluateIfExpression(n *ast.IfExpression, scope *definitionScope) (Object, error) { if n.Condition == nil { return evaluateExpression(n.Value, scope) } c, err := evaluateExpression(n.Condition, scope) if err != nil { return nil, err } if c.IsTrue() { return evaluateExpression(n.Value, scope) } // Else branch must be set if condition is set return evaluateIfExpression(n.ElseBranch, scope) } func evaluateBinaryExpression(n *ast.BinaryOperationExpression, scope *definitionScope) (Object, error) { aValue, err := evaluateExpression(n.A, scope) if err != nil { return nil, err } bValue, err := evaluateExpression(n.B, scope) if err != nil { return nil, err } switch n.Operator { case ast.BinaryOperatorEq: return aValue.Equals(bValue) case ast.BinaryOperatorNe: o, err := aValue.Equals(bValue) if err != nil { return nil, err } return &Boolean{Value: !o.Value}, nil case ast.BinaryOperatorLt: return aValue.Lt(bValue) case ast.BinaryOperatorLe: return aValue.Lte(bValue) case ast.BinaryOperatorGt: return aValue.Gt(bValue) case ast.BinaryOperatorGe: return aValue.Gte(bValue) case ast.BinaryOperatorAdd: return aValue.Add(bValue) case ast.BinaryOperatorSub: return aValue.Sub(bValue) case ast.BinaryOperatorMul: return aValue.Mul(bValue) case ast.BinaryOperatorDiv: return aValue.Div(bValue) case ast.BinaryOperatorLand: if !aValue.IsTrue() { return aValue, nil } return bValue, nil case ast.BinaryOperatorLor: if aValue.IsTrue() { return aValue, nil } return bValue, nil } return nil, operationNotSupported } func evaluateUnaryExpression(n *ast.UnaryOperationExpression, scope *definitionScope) (Object, error) { value, err := evaluateExpression(n.A, scope) if err != nil { return nil, err } switch n.Operator { case ast.UnaryOperatorLnot: return &Boolean{Value: !value.IsTrue()}, nil case ast.UnaryOperatorPos: if value, ok := value.(ObjectWithPos); ok { return value.Pos() } case ast.UnaryOperatorNeg: if value, ok := value.(ObjectWithNeg); ok { return value.Neg() } } return nil, operationNotSupported } func evaluateLookupExpression(n *ast.LookupExpression, scope *definitionScope) (Object, error) { return scope.lookup(n.Identifier, n.ScopeIndex), nil } func evaluateCallExpression(n *ast.CallExpression, scope *definitionScope) (Object, error) { callee, err := evaluateExpression(n.Callee, scope) if err != nil { return nil, err } switch callee := callee.(type) { case *Function: return evaluateFunctionCall(callee, n.Parameters, scope) case *PredefinedFunction: return evaluatePredefinedFunctionCall(callee, n.Parameters, scope) } return nil, OperationNotSupportedError{} } func evaluateFunctionCall(o *Function, params []ast.Expression, scope *definitionScope) (Object, error) { parameterScope := o.parentScope.newScope() for i, p := range params { v, err := evaluateExpression(p, scope) if err != nil { return nil, err } name := o.Parameters[i] parameterScope.declare(name, v) } if err := evaluateStatements(o.Statements, parameterScope.newScope()); err != nil { switch err := err.(type) { case *returnError: return err.value, nil case *continueError: return nil, err.syntaxError() case *breakError: return nil, err.syntaxError() default: return nil, err } } return NilObject, nil } func evaluatePredefinedFunctionCall(o *PredefinedFunction, params []ast.Expression, scope *definitionScope) (Object, error) { parameters := []Object{} for _, p := range params { v, err := evaluateExpression(p, scope) if err != nil { return nil, err } parameters = append(parameters, v) } return o.fn(parameters) }
evaluator/expressions.go
0.623492
0.465509
expressions.go
starcoder
package validate import ( "fmt" "math" "reflect" "strconv" "strings" ) // Validator performs validation on a value. type Validator interface { Validate(Context) error } // ValidatorFunc is an adapter for a function that implements the Validator interface. type ValidatorFunc func(Context) error // Validate implements the Validator interface. func (f ValidatorFunc) Validate(ctx Context) error { return f(ctx) } // And combines the validators as a conjunction. func And(validators ...Validator) Validator { switch len(validators) { case 0: return NoOpValidator{} case 1: return validators[0] } return ValidatorFunc(func(ctx Context) error { var errs []error for _, v := range validators { err := v.Validate(ctx) if err != nil { errs = append(errs, err) if ctx.Options.StopOnError { break } } } if len(errs) > 0 { msg := errs[0].Error() for i := 1; i < len(errs); i++ { msg += " and " + errs[i].Error() } return newError(msg) } return nil }) } // CustomMessage wraps a validator's error with a custom message. func CustomMessage(validator Validator, msg string) Validator { return ValidatorFunc(func(ctx Context) error { err := validator.Validate(ctx) if err != nil { switch err.(type) { case *Error: return newError(msg) default: return err } } return nil }) } // Empty requires the length of a string, array, slice, or map to be 0. func Empty() Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) switch val.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: if val.Len() != 0 { return newError("must be empty") } return nil case reflect.Ptr: return newError("must be empty") default: return isEmptyAllowed(val.Type(), "empty", nil) } }) } func isEmptyAllowed(t reflect.Type, name string, args []string) error { switch t.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: return nil case reflect.Ptr: return isEmptyAllowed(t.Elem(), name, args) default: return InvalidTagArgumentsError{Message: "only pointers to/or strings, arrays, slices, and maps are supported", ValidatorName: name, Args: args} } } // Equal requires the value to be equal to the specified value. func Equal(other interface{}) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) if val.Kind() == reflect.Ptr { return newErrorf("must be equal to %v", other) } r, err := cmp(val, reflect.ValueOf(other)) if err != nil { return err } if r != 0 { return newErrorf("must be equal to %v", other) } return nil }) } // Field wraps a validator in a field validator. func Field(name string, validator Validator) Validator { return ValidatorFunc(func(ctx Context) error { if !ctx.Value.IsValid() { return nil } val := ctx.Value.FieldByName(name) if !val.IsValid() { return UnknownFieldError{Type: ctx.Value.Type(), Name: name} } fctx := ctx fctx.Parent = &ctx fctx.Value = val err := validator.Validate(fctx) if err != nil { switch err.(type) { case *Error: sf, _ := ctx.Value.Type().FieldByName(name) return newErrorf("%q %v", sf.Name, err) default: return err } } return nil }) } // GreaterThan requires the value to be greater than the specified value. func GreaterThan(other interface{}) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) if val.Kind() == reflect.Ptr { return newErrorf("must be greater than %v", other) } r, err := cmp(val, reflect.ValueOf(other)) if err != nil { return err } if r <= 0 { return newErrorf("must be greater than %v", other) } return nil }) } // GreaterThanOrEqual requires the value to be greater than or equal to the specified value. func GreaterThanOrEqual(other interface{}) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) if val.Kind() == reflect.Ptr { return newErrorf("must be greater than or equal to %v", other) } r, err := cmp(val, reflect.ValueOf(other)) if err != nil { return err } if r < 0 { return newErrorf("must be greater than or equal to %v", other) } return nil }) } // In requires a value to be one of the specified values. func In(values ...interface{}) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) if val.Kind() == reflect.Ptr { return newErrorf("must be one of %v", values) } for _, v := range values { r, err := cmp(val, reflect.ValueOf(v)) if err != nil { return err } if r == 0 { return nil } } return newErrorf("must be one of %v", values) }) } // Items validates that all the items of a slice, array. func Items(validator Validator) Validator { return ValidatorFunc(func(ctx Context) error { var errs []error val := indirect(ctx.Value) switch val.Kind() { case reflect.Array, reflect.Slice: len := val.Len() for i := 0; i < len; i++ { item := val.Index(i) fctx := ctx fctx.Parent = &ctx fctx.Value = item err := validator.Validate(fctx) if err != nil { switch err.(type) { case *Error: errs = append(errs, newErrorf("[%d] %v", i, err)) if ctx.Options.StopOnError { return errs[0] } default: return err } } } case reflect.Map: mi := val.MapRange() for mi.Next() { item := mi.Value() fctx := ctx fctx.Parent = &ctx fctx.Value = item err := validator.Validate(fctx) if err != nil { switch err.(type) { case *Error: errs = append(errs, newErrorf("[%v] %v", mi.Key(), err)) if ctx.Options.StopOnError { return errs[0] } default: return err } } } default: return isItemsAllowed(ctx.Value.Type(), "items", nil) } if len(errs) > 0 { msg := errs[0].Error() for i := 1; i < len(errs); i++ { msg += " and " + errs[i].Error() } return newError(msg) } return nil }) } func isItemsAllowed(t reflect.Type, name string, args []string) error { switch t.Kind() { case reflect.Array, reflect.Slice, reflect.Map: return nil case reflect.Ptr: return isItemsAllowed(t.Elem(), name, args) default: return InvalidTagArgumentsError{Message: "only pointers to/or arrays, slices, and maps are supported", ValidatorName: name, Args: args} } } // Length requires the length of a string, array, slice, or map to be exactly len. func Length(len int) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) switch val.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: if val.Len() != len { return newErrorf("must be of length %d", len) } return nil case reflect.Ptr: return newErrorf("must be of length %d", len) default: return isLengthAllowed(val.Type(), "length", nil) } }) } func isLengthAllowed(t reflect.Type, name string, args []string) error { switch t.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: case reflect.Ptr: return isLengthAllowed(t.Elem(), name, args) default: return InvalidTagArgumentsError{Message: "only pointers to/or strings, arrays, slices, and maps are supported", ValidatorName: name, Args: args} } if len(args) != 1 { return InvalidTagArgumentsError{Message: "1 argument is required", ValidatorName: name, Args: args} } _, err := strconv.Atoi(args[0]) if err != nil { return InvalidTagArgumentsError{Message: "argument must be an integer", ValidatorName: name, Args: args} } return nil } // LessThan requires the value to be less than the specified value. func LessThan(other interface{}) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) if val.Kind() == reflect.Ptr { return newErrorf("must be less than %v", other) } r, err := cmp(val, reflect.ValueOf(other)) if err != nil { return err } if r >= 0 { return newErrorf("must be less than %v", other) } return nil }) } // LessThanOrEqual requires the value to be less than or equal to the specified value. func LessThanOrEqual(other interface{}) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) if val.Kind() == reflect.Ptr { return newErrorf("must be less than or equal to %v", other) } r, err := cmp(val, reflect.ValueOf(other)) if err != nil { return err } if r > 0 { return newErrorf("must be less than or equal to %v", other) } return nil }) } // MaxLength requires the length of a string, array, slice, or map to be less than or equal to len. func MaxLength(len int) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) switch val.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: if val.Len() > len { return newErrorf("must have max length %d", len) } return nil case reflect.Ptr: return newErrorf("must have max length %d", len) default: return isLengthAllowed(val.Type(), "maxlength", nil) } }) } // MinLength requires the length of a string, array, slice, or map to be greater than or equal to len. func MinLength(len int) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) switch val.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: if val.Len() < len { return newErrorf("must have min length %d", len) } return nil case reflect.Ptr: return newErrorf("must have min length %d", len) default: return isLengthAllowed(val.Type(), "minlength", nil) } }) } // Nil requires the value of any type that can be a pointer to be nil. func Nil() Validator { return ValidatorFunc(func(ctx Context) error { switch ctx.Value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: if !ctx.Value.IsNil() { return newError("must be nil") } return nil default: return isNilAllowed(ctx.Value.Type(), "nil", nil) } }) } func isNilAllowed(t reflect.Type, name string, args []string) error { switch t.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: return nil default: return InvalidTagArgumentsError{Message: "only nil-able types are supported", ValidatorName: name, Args: args} } } // NoOpValidator is a validator that does nothing. type NoOpValidator struct{} // Validate implements the Validator interface. func (NoOpValidator) Validate(Context) error { return nil } // NotEmpty requires the length of a string, array, slice, or map to be greater than 0. func NotEmpty() Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) switch val.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: if val.Len() == 0 { return newError("must not be empty") } return nil case reflect.Ptr: return newError("must not be empty") default: return isNotEmptyAllowed(val.Type(), "notempty", nil) } }) } func isNotEmptyAllowed(t reflect.Type, name string, args []string) error { switch t.Kind() { case reflect.String, reflect.Array, reflect.Slice, reflect.Map: return nil case reflect.Ptr: return isNotEmptyAllowed(t.Elem(), name, args) default: return InvalidTagArgumentsError{Message: "only pointers to/or strings, arrays, slices, and maps are supported", ValidatorName: name, Args: args} } } // NotEqual requires the value to not be equal to the specified value. func NotEqual(other interface{}) Validator { return ValidatorFunc(func(ctx Context) error { val := indirect(ctx.Value) if val.Kind() == reflect.Ptr { return newErrorf("must not be equal to %v", other) } r, err := cmp(val, reflect.ValueOf(other)) if err != nil { return err } if r == 0 { return newErrorf("must not be equal to %v", other) } return nil }) } // NotNil requires the value of any type that can be a pointer to not be nil. func NotNil() Validator { return ValidatorFunc(func(ctx Context) error { switch ctx.Value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: if ctx.Value.IsNil() { return newError("must not be nil") } return nil default: return isNotNilAllowed(ctx.Value.Type(), "notnil", nil) } }) } func isNotNilAllowed(t reflect.Type, name string, args []string) error { switch t.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: return nil default: return InvalidTagArgumentsError{Message: "only nil-able types are supported", ValidatorName: name, Args: args} } } // Or combines the validators as a disjunction. func Or(validators ...Validator) Validator { switch len(validators) { case 0: return NoOpValidator{} case 1: return validators[0] } return ValidatorFunc(func(ctx Context) error { var errs []error for _, v := range validators { err := v.Validate(ctx) if err == nil { return nil } if err != nil { errs = append(errs, err) } } msg := errs[0].Error() for i := 1; i < len(errs); i++ { msg += " or " + errs[i].Error() } return newError(msg) }) } // Zero requires the value to be the zero value. func Zero() Validator { return ValidatorFunc(func(ctx Context) error { if !isZero(ctx.Value) { return newErrorf("must be \"%v\"", zeroValue(ctx.Value.Type())) } return nil }) } func zeroValue(t reflect.Type) interface{} { return reflect.Zero(t).Interface() } func isZero(rval reflect.Value) bool { switch rval.Kind() { case reflect.Bool: return !rval.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return rval.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return rval.Uint() == 0 case reflect.Float32, reflect.Float64: return math.Float64bits(rval.Float()) == 0 case reflect.Complex64, reflect.Complex128: c := rval.Complex() return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0 case reflect.Array: for i := 0; i < rval.Len(); i++ { if !isZero(rval.Index(i)) { return false } } return true case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: return rval.IsNil() case reflect.String: return rval.Len() == 0 case reflect.Struct: for i := 0; i < rval.NumField(); i++ { if !isZero(rval.Field(i)) { return false } } return true default: // This should never happens, but will act as a safeguard for // later, as a default value doesn't makes sense here. panic(fmt.Sprintf("reflect.Value.IsZero (%s)", rval.Kind())) } } func isCmpAllowed(t reflect.Type, name string, args []string) error { if len(args) != 1 { return InvalidTagArgumentsError{Message: "1 argument is required", ValidatorName: name, Args: args} } switch t.Kind() { case reflect.Bool: _, err := tryParseString(t, args[0]) if err != nil { return InvalidTagArgumentsError{Message: "argument must be a boolean", ValidatorName: name, Args: args} } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: _, err := tryParseString(t, args[0]) if err != nil { return InvalidTagArgumentsError{Message: "argument must be an integer", ValidatorName: name, Args: args} } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: _, err := tryParseString(t, args[0]) if err != nil { return InvalidTagArgumentsError{Message: "argument must be an unsigned integer", ValidatorName: name, Args: args} } case reflect.Float32, reflect.Float64: _, err := tryParseString(t, args[0]) if err != nil { return InvalidTagArgumentsError{Message: "argument must be a floating-point number", ValidatorName: name, Args: args} } case reflect.Ptr: return isCmpAllowed(t.Elem(), name, args) case reflect.String: default: return InvalidTagArgumentsError{Message: "only pointers to/or strings, bools, and numbers are allowed", ValidatorName: name, Args: args} } return nil } func cmp(val reflect.Value, other reflect.Value) (int, error) { switch val.Kind() { case reflect.Bool: switch other.Kind() { case reflect.Bool: if val.Bool() == other.Bool() { return 0, nil } return -1, nil } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: v := val.Int() switch other.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: o := other.Int() if v < o { return -1, nil } else if v == o { return 0, nil } else { return 1, nil } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: o := other.Uint() if v < 0 { return -1, nil } if uint64(v) < 0 { return -1, nil } else if uint64(v) == o { return 0, nil } else { return 1, nil } case reflect.Float32, reflect.Float64: f := float64(v) o := other.Float() if f < o { return -1, nil } else if f == o { return 0, nil } else { return 1, nil } } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: v := val.Uint() switch other.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: o := other.Int() if o < 0 { return 1, nil } if v < uint64(0) { return -1, nil } else if v == uint64(o) { return 0, nil } else { return 1, nil } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: o := other.Uint() if v < o { return -1, nil } else if v == o { return 0, nil } else { return 1, nil } case reflect.Float32, reflect.Float64: f := float64(v) o := other.Float() if f < o { return -1, nil } else if f == o { return 0, nil } else { return 1, nil } } case reflect.String: v := val.String() switch other.Kind() { case reflect.String: o := other.String() return strings.Compare(v, o), nil } } return 0, fmt.Errorf("incompatible types for comparision: %s and %s", val.Type(), other.Type()) } func tryParseString(t reflect.Type, arg string) (interface{}, error) { switch t.Kind() { case reflect.Bool: v, err := strconv.ParseBool(arg) if err != nil { return nil, err } return v, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: v, err := strconv.ParseInt(arg, 10, 64) if err != nil { return nil, err } return v, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: v, err := strconv.ParseUint(arg, 10, 64) if err != nil { return nil, err } return v, nil case reflect.Float32, reflect.Float64: v, err := strconv.ParseFloat(arg, 64) if err != nil { return nil, err } return v, nil case reflect.Ptr: return tryParseString(t.Elem(), arg) case reflect.String: return arg, nil default: return nil, newError("unsupported type") } } func indirect(val reflect.Value) reflect.Value { for val.Kind() == reflect.Ptr { if val.IsNil() { break } val = val.Elem() } return val }
validators.go
0.73173
0.433442
validators.go
starcoder
package model import ( "path/filepath" "github.com/pkg/errors" "github.com/tilt-dev/tilt/internal/ospath" ) type PathMatcher interface { Matches(f string) (bool, error) // If this matches the entire dir, we can often optimize filetree walks a bit MatchesEntireDir(file string) (bool, error) } // A Matcher that matches nothing. type emptyMatcher struct{} func (m emptyMatcher) Matches(f string) (bool, error) { return false, nil } func (emptyMatcher) MatchesEntireDir(p string) (bool, error) { return false, nil } var EmptyMatcher PathMatcher = emptyMatcher{} // A matcher that matches exactly against a set of files. type fileMatcher struct { paths map[string]bool } func (m fileMatcher) Matches(f string) (bool, error) { return m.paths[f], nil } func (fileMatcher) MatchesEntireDir(f string) (bool, error) { return false, nil } // NewSimpleFileMatcher returns a matcher for the given paths; any relative paths // are converted to absolute (relative to cwd). func NewSimpleFileMatcher(paths ...string) (fileMatcher, error) { pathMap := make(map[string]bool, len(paths)) for _, path := range paths { // Get the absolute path of the path, because PathMatchers expect to always // work with absolute paths. path, err := filepath.Abs(path) if err != nil { return fileMatcher{}, errors.Wrap(err, "NewSimplePathMatcher") } pathMap[path] = true } return fileMatcher{paths: pathMap}, nil } // This matcher will match a path if it is: // A. an exact match for one of matcher.paths, or // B. the child of a path in matcher.paths // e.g. if paths = {"foo.bar", "baz/"}, will match both // A. "foo.bar" (exact match), and // B. "baz/qux" (child of one of the paths) type fileOrChildMatcher struct { paths map[string]bool } func (m fileOrChildMatcher) Matches(f string) (bool, error) { // (A) Exact match if m.paths[f] { return true, nil } // (B) f is child of any of m.paths for path := range m.paths { if ospath.IsChild(path, f) { return true, nil } } return false, nil } func (m fileOrChildMatcher) MatchesEntireDir(f string) (bool, error) { return m.Matches(f) } // NewRelativeFileOrChildMatcher returns a matcher for the given paths (with any // relative paths converted to absolute, relative to the given baseDir). func NewRelativeFileOrChildMatcher(baseDir string, paths ...string) fileOrChildMatcher { pathMap := make(map[string]bool, len(paths)) for _, path := range paths { if !filepath.IsAbs(path) { path = filepath.Join(baseDir, path) } pathMap[path] = true } return fileOrChildMatcher{paths: pathMap} } // A PathSet stores one or more filepaths, along with the directory that any // relative paths are relative to // NOTE(maia): in its current usage (for LiveUpdate.Run.Triggers, LiveUpdate.FallBackOnFiles()) // this isn't strictly necessary, could just as easily convert paths to Abs when specified in // the Tiltfile--but leaving this code in place for now because it was already written and // may help with complicated future cases (glob support, etc.) type PathSet struct { Paths []string BaseDirectory string } func NewPathSet(paths []string, baseDir string) PathSet { return PathSet{ Paths: paths, BaseDirectory: baseDir, } } func (ps PathSet) Empty() bool { return len(ps.Paths) == 0 } // AnyMatch returns true if any of the given filepaths match any paths contained in the pathset // (along with the first path that matched). func (ps PathSet) AnyMatch(paths []string) (bool, string, error) { matcher := NewRelativeFileOrChildMatcher(ps.BaseDirectory, ps.Paths...) for _, path := range paths { match, err := matcher.Matches(path) if err != nil { return false, "", err } if match { return true, path, nil } } return false, "", nil } // Intersection returns the set of paths that are in both the PathSet and the passed set of paths. func (ps PathSet) Intersection(paths []string) ([]string, error) { var matches []string matcher := NewRelativeFileOrChildMatcher(ps.BaseDirectory, ps.Paths...) for _, path := range paths { match, err := matcher.Matches(path) if err != nil { return nil, err } if match { matches = append(matches, path) } } return matches, nil } type CompositePathMatcher struct { Matchers []PathMatcher } func NewCompositeMatcher(matchers []PathMatcher) PathMatcher { if len(matchers) == 0 { return EmptyMatcher } return CompositePathMatcher{Matchers: matchers} } func (c CompositePathMatcher) Matches(f string) (bool, error) { for _, t := range c.Matchers { ret, err := t.Matches(f) if err != nil { return false, err } if ret { return true, nil } } return false, nil } func (c CompositePathMatcher) MatchesEntireDir(f string) (bool, error) { for _, t := range c.Matchers { matches, err := t.MatchesEntireDir(f) if matches || err != nil { return matches, err } } return false, nil } var _ PathMatcher = CompositePathMatcher{}
pkg/model/matcher.go
0.750187
0.561095
matcher.go
starcoder
MeteringD flows servicer provides the gRPC interface for the REST and services to interact with traffic flows records. The servicer require a backing Datastore (which is typically Postgres) for storing and retrieving the data and access to Magmad to resolve the network. */ package servicers import ( "magma/lte/cloud/go/protos" "magma/lte/cloud/go/services/meteringd_records/storage" orcprotos "magma/orc8r/cloud/go/protos" "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // Implements a gRPC Server interface for Metering Records type MeteringdRecordsServer struct { storage storage.MeteringRecordsStorage } // Convenience method to instantiate a new gRPC server instance func NewMeteringdRecordsServer(storage storage.MeteringRecordsStorage) *MeteringdRecordsServer { srv := &MeteringdRecordsServer{storage: storage} return srv } // Servicer for synchronizing the flows in the datastore with the gateway // Given a Flow Table which is a list of Flow Records, each element is put // into the record table. func (srv *MeteringdRecordsServer) UpdateFlows(ctx context.Context, tbl *protos.FlowTable) (*orcprotos.Void, error) { ret := &orcprotos.Void{} id, err := orcprotos.GetGatewayIdentity(ctx) if err != nil { return ret, err } fillFlowsWithGatewayId(tbl, id.GetLogicalId()) err = srv.storage.UpdateOrCreateRecords(id.GetNetworkId(), tbl.GetFlows()) return ret, err } // Lists the ids of all usage records for a subscriber on the network func (srv *MeteringdRecordsServer) ListSubscriberRecords( ctx context.Context, query *protos.FlowRecordQuery, ) (*protos.FlowTable, error) { if query.GetNetworkId() == "" { return nil, status.Errorf(codes.InvalidArgument, "Missing Network identity") } if query.GetSubscriberId() == "" { return nil, status.Errorf(codes.InvalidArgument, "Missing subscriber id") } subscriberFlows, err := srv.storage.GetRecordsForSubscriber(query.GetNetworkId(), query.GetSubscriberId()) if err != nil { return nil, status.Errorf(codes.Aborted, err.Error()) } return &protos.FlowTable{Flows: subscriberFlows}, nil } // Gets a flow data record by ID func (srv *MeteringdRecordsServer) GetRecord(ctx context.Context, query *protos.FlowRecordQuery) (*protos.FlowRecord, error) { if query.GetNetworkId() == "" { return &protos.FlowRecord{}, status.Errorf(codes.InvalidArgument, "Missing Network identity") } if query.GetRecordId() == "" { return &protos.FlowRecord{}, status.Errorf(codes.InvalidArgument, "Missing record id for query") } return srv.storage.GetRecord(query.GetNetworkId(), query.GetRecordId()) } func fillFlowsWithGatewayId(tbl *protos.FlowTable, gatewayId string) *protos.FlowTable { for _, record := range tbl.GetFlows() { record.GatewayId = gatewayId } return tbl }
lte/cloud/go/services/meteringd_records/servicers/records.go
0.690455
0.40987
records.go
starcoder
package backtest import ( "sort" "github.com/c9s/bbgo/pkg/fixedpoint" "github.com/c9s/bbgo/pkg/types" ) type PriceOrder struct { Price fixedpoint.Value Order types.Order } type PriceOrderSlice []PriceOrder func (slice PriceOrderSlice) Len() int { return len(slice) } func (slice PriceOrderSlice) Less(i, j int) bool { return slice[i].Price < slice[j].Price } func (slice PriceOrderSlice) Swap(i, j int) { slice[i], slice[j] = slice[j], slice[i] } func (slice PriceOrderSlice) InsertAt(idx int, po PriceOrder) PriceOrderSlice { rear := append([]PriceOrder{}, slice[idx:]...) newSlice := append(slice[:idx], po) return append(newSlice, rear...) } func (slice PriceOrderSlice) Remove(price fixedpoint.Value, descending bool) PriceOrderSlice { matched, idx := slice.Find(price, descending) if matched.Price != price { return slice } return append(slice[:idx], slice[idx+1:]...) } func (slice PriceOrderSlice) First() (PriceOrder, bool) { if len(slice) > 0 { return slice[0], true } return PriceOrder{}, false } // FindPriceVolumePair finds the pair by the given price, this function is a read-only // operation, so we use the value receiver to avoid copy value from the pointer // If the price is not found, it will return the index where the price can be inserted at. // true for descending (bid orders), false for ascending (ask orders) func (slice PriceOrderSlice) Find(price fixedpoint.Value, descending bool) (pv PriceOrder, idx int) { idx = sort.Search(len(slice), func(i int) bool { if descending { return slice[i].Price <= price } return slice[i].Price >= price }) if idx >= len(slice) || slice[idx].Price != price { return pv, idx } pv = slice[idx] return pv, idx } func (slice PriceOrderSlice) Upsert(po PriceOrder, descending bool) PriceOrderSlice { if len(slice) == 0 { return append(slice, po) } price := po.Price _, idx := slice.Find(price, descending) if idx >= len(slice) || slice[idx].Price != price { return slice.InsertAt(idx, po) } slice[idx].Order = po.Order return slice }
pkg/backtest/priceorder.go
0.746693
0.436142
priceorder.go
starcoder
package arrowutil import ( "fmt" "regexp" "github.com/apache/arrow/go/arrow/array" "github.com/influxdata/flux" "github.com/influxdata/flux/semantic" "github.com/influxdata/flux/values" ) func NewArrayValue(arr array.Interface, typ flux.ColType) values.Array { switch elemType := flux.SemanticType(typ); elemType { case semantic.BasicInt: return NewInt64ArrayValue(arr.(*array.Int64)) case semantic.BasicUint: return NewUint64ArrayValue(arr.(*array.Uint64)) case semantic.BasicFloat: return NewFloat64ArrayValue(arr.(*array.Float64)) case semantic.BasicBool: return NewBooleanArrayValue(arr.(*array.Boolean)) case semantic.BasicString: return NewStringArrayValue(arr.(*array.Binary)) default: panic(fmt.Errorf("unsupported column data type: %s", typ)) } } var _ values.Value = Int64ArrayValue{} var _ values.Array = Int64ArrayValue{} type Int64ArrayValue struct { arr *array.Int64 typ semantic.MonoType } func NewInt64ArrayValue(arr *array.Int64) values.Array { return Int64ArrayValue{ arr: arr, typ: semantic.NewArrayType(semantic.BasicInt), } } func (v Int64ArrayValue) Type() semantic.MonoType { return v.typ } func (v Int64ArrayValue) IsNull() bool { return false } func (v Int64ArrayValue) Str() string { panic(values.UnexpectedKind(semantic.Array, semantic.String)) } func (v Int64ArrayValue) Bytes() []byte { panic(values.UnexpectedKind(semantic.Array, semantic.Bytes)) } func (v Int64ArrayValue) Int() int64 { panic(values.UnexpectedKind(semantic.Array, semantic.Int)) } func (v Int64ArrayValue) UInt() uint64 { panic(values.UnexpectedKind(semantic.Array, semantic.UInt)) } func (v Int64ArrayValue) Float() float64 { panic(values.UnexpectedKind(semantic.Array, semantic.Float)) } func (v Int64ArrayValue) Bool() bool { panic(values.UnexpectedKind(semantic.Array, semantic.Bool)) } func (v Int64ArrayValue) Time() values.Time { panic(values.UnexpectedKind(semantic.Array, semantic.Time)) } func (v Int64ArrayValue) Duration() values.Duration { panic(values.UnexpectedKind(semantic.Array, semantic.Duration)) } func (v Int64ArrayValue) Regexp() *regexp.Regexp { panic(values.UnexpectedKind(semantic.Array, semantic.Regexp)) } func (v Int64ArrayValue) Array() values.Array { return v } func (v Int64ArrayValue) Object() values.Object { panic(values.UnexpectedKind(semantic.Array, semantic.Object)) } func (v Int64ArrayValue) Function() values.Function { panic(values.UnexpectedKind(semantic.Array, semantic.Function)) } func (v Int64ArrayValue) Equal(other values.Value) bool { if other.Type().Nature() != semantic.Array { return false } else if v.arr.Len() != other.Array().Len() { return false } otherArray := other.Array() for i, n := 0, v.arr.Len(); i < n; i++ { if !v.Get(i).Equal(otherArray.Get(i)) { return false } } return true } func (v Int64ArrayValue) Get(i int) values.Value { if v.arr.IsNull(i) { return values.Null } return values.New(v.arr.Value(i)) } func (v Int64ArrayValue) Set(i int, value values.Value) { panic("cannot set value on immutable array") } func (v Int64ArrayValue) Append(value values.Value) { panic("cannot append to immutable array") } func (v Int64ArrayValue) Len() int { return v.arr.Len() } func (v Int64ArrayValue) Range(f func(i int, v values.Value)) { for i, n := 0, v.arr.Len(); i < n; i++ { f(i, v.Get(i)) } } func (v Int64ArrayValue) Sort(f func(i values.Value, j values.Value) bool) { panic("cannot sort immutable array") } var _ values.Value = Uint64ArrayValue{} var _ values.Array = Uint64ArrayValue{} type Uint64ArrayValue struct { arr *array.Uint64 typ semantic.MonoType } func NewUint64ArrayValue(arr *array.Uint64) values.Array { return Uint64ArrayValue{ arr: arr, typ: semantic.NewArrayType(semantic.BasicUint), } } func (v Uint64ArrayValue) Type() semantic.MonoType { return v.typ } func (v Uint64ArrayValue) IsNull() bool { return false } func (v Uint64ArrayValue) Str() string { panic(values.UnexpectedKind(semantic.Array, semantic.String)) } func (v Uint64ArrayValue) Bytes() []byte { panic(values.UnexpectedKind(semantic.Array, semantic.Bytes)) } func (v Uint64ArrayValue) Int() int64 { panic(values.UnexpectedKind(semantic.Array, semantic.Int)) } func (v Uint64ArrayValue) UInt() uint64 { panic(values.UnexpectedKind(semantic.Array, semantic.UInt)) } func (v Uint64ArrayValue) Float() float64 { panic(values.UnexpectedKind(semantic.Array, semantic.Float)) } func (v Uint64ArrayValue) Bool() bool { panic(values.UnexpectedKind(semantic.Array, semantic.Bool)) } func (v Uint64ArrayValue) Time() values.Time { panic(values.UnexpectedKind(semantic.Array, semantic.Time)) } func (v Uint64ArrayValue) Duration() values.Duration { panic(values.UnexpectedKind(semantic.Array, semantic.Duration)) } func (v Uint64ArrayValue) Regexp() *regexp.Regexp { panic(values.UnexpectedKind(semantic.Array, semantic.Regexp)) } func (v Uint64ArrayValue) Array() values.Array { return v } func (v Uint64ArrayValue) Object() values.Object { panic(values.UnexpectedKind(semantic.Array, semantic.Object)) } func (v Uint64ArrayValue) Function() values.Function { panic(values.UnexpectedKind(semantic.Array, semantic.Function)) } func (v Uint64ArrayValue) Equal(other values.Value) bool { if other.Type().Nature() != semantic.Array { return false } else if v.arr.Len() != other.Array().Len() { return false } otherArray := other.Array() for i, n := 0, v.arr.Len(); i < n; i++ { if !v.Get(i).Equal(otherArray.Get(i)) { return false } } return true } func (v Uint64ArrayValue) Get(i int) values.Value { if v.arr.IsNull(i) { return values.Null } return values.New(v.arr.Value(i)) } func (v Uint64ArrayValue) Set(i int, value values.Value) { panic("cannot set value on immutable array") } func (v Uint64ArrayValue) Append(value values.Value) { panic("cannot append to immutable array") } func (v Uint64ArrayValue) Len() int { return v.arr.Len() } func (v Uint64ArrayValue) Range(f func(i int, v values.Value)) { for i, n := 0, v.arr.Len(); i < n; i++ { f(i, v.Get(i)) } } func (v Uint64ArrayValue) Sort(f func(i values.Value, j values.Value) bool) { panic("cannot sort immutable array") } var _ values.Value = Float64ArrayValue{} var _ values.Array = Float64ArrayValue{} type Float64ArrayValue struct { arr *array.Float64 typ semantic.MonoType } func NewFloat64ArrayValue(arr *array.Float64) values.Array { return Float64ArrayValue{ arr: arr, typ: semantic.NewArrayType(semantic.BasicFloat), } } func (v Float64ArrayValue) Type() semantic.MonoType { return v.typ } func (v Float64ArrayValue) IsNull() bool { return false } func (v Float64ArrayValue) Str() string { panic(values.UnexpectedKind(semantic.Array, semantic.String)) } func (v Float64ArrayValue) Bytes() []byte { panic(values.UnexpectedKind(semantic.Array, semantic.Bytes)) } func (v Float64ArrayValue) Int() int64 { panic(values.UnexpectedKind(semantic.Array, semantic.Int)) } func (v Float64ArrayValue) UInt() uint64 { panic(values.UnexpectedKind(semantic.Array, semantic.UInt)) } func (v Float64ArrayValue) Float() float64 { panic(values.UnexpectedKind(semantic.Array, semantic.Float)) } func (v Float64ArrayValue) Bool() bool { panic(values.UnexpectedKind(semantic.Array, semantic.Bool)) } func (v Float64ArrayValue) Time() values.Time { panic(values.UnexpectedKind(semantic.Array, semantic.Time)) } func (v Float64ArrayValue) Duration() values.Duration { panic(values.UnexpectedKind(semantic.Array, semantic.Duration)) } func (v Float64ArrayValue) Regexp() *regexp.Regexp { panic(values.UnexpectedKind(semantic.Array, semantic.Regexp)) } func (v Float64ArrayValue) Array() values.Array { return v } func (v Float64ArrayValue) Object() values.Object { panic(values.UnexpectedKind(semantic.Array, semantic.Object)) } func (v Float64ArrayValue) Function() values.Function { panic(values.UnexpectedKind(semantic.Array, semantic.Function)) } func (v Float64ArrayValue) Equal(other values.Value) bool { if other.Type().Nature() != semantic.Array { return false } else if v.arr.Len() != other.Array().Len() { return false } otherArray := other.Array() for i, n := 0, v.arr.Len(); i < n; i++ { if !v.Get(i).Equal(otherArray.Get(i)) { return false } } return true } func (v Float64ArrayValue) Get(i int) values.Value { if v.arr.IsNull(i) { return values.Null } return values.New(v.arr.Value(i)) } func (v Float64ArrayValue) Set(i int, value values.Value) { panic("cannot set value on immutable array") } func (v Float64ArrayValue) Append(value values.Value) { panic("cannot append to immutable array") } func (v Float64ArrayValue) Len() int { return v.arr.Len() } func (v Float64ArrayValue) Range(f func(i int, v values.Value)) { for i, n := 0, v.arr.Len(); i < n; i++ { f(i, v.Get(i)) } } func (v Float64ArrayValue) Sort(f func(i values.Value, j values.Value) bool) { panic("cannot sort immutable array") } var _ values.Value = BooleanArrayValue{} var _ values.Array = BooleanArrayValue{} type BooleanArrayValue struct { arr *array.Boolean typ semantic.MonoType } func NewBooleanArrayValue(arr *array.Boolean) values.Array { return BooleanArrayValue{ arr: arr, typ: semantic.NewArrayType(semantic.BasicBool), } } func (v BooleanArrayValue) Type() semantic.MonoType { return v.typ } func (v BooleanArrayValue) IsNull() bool { return false } func (v BooleanArrayValue) Str() string { panic(values.UnexpectedKind(semantic.Array, semantic.String)) } func (v BooleanArrayValue) Bytes() []byte { panic(values.UnexpectedKind(semantic.Array, semantic.Bytes)) } func (v BooleanArrayValue) Int() int64 { panic(values.UnexpectedKind(semantic.Array, semantic.Int)) } func (v BooleanArrayValue) UInt() uint64 { panic(values.UnexpectedKind(semantic.Array, semantic.UInt)) } func (v BooleanArrayValue) Float() float64 { panic(values.UnexpectedKind(semantic.Array, semantic.Float)) } func (v BooleanArrayValue) Bool() bool { panic(values.UnexpectedKind(semantic.Array, semantic.Bool)) } func (v BooleanArrayValue) Time() values.Time { panic(values.UnexpectedKind(semantic.Array, semantic.Time)) } func (v BooleanArrayValue) Duration() values.Duration { panic(values.UnexpectedKind(semantic.Array, semantic.Duration)) } func (v BooleanArrayValue) Regexp() *regexp.Regexp { panic(values.UnexpectedKind(semantic.Array, semantic.Regexp)) } func (v BooleanArrayValue) Array() values.Array { return v } func (v BooleanArrayValue) Object() values.Object { panic(values.UnexpectedKind(semantic.Array, semantic.Object)) } func (v BooleanArrayValue) Function() values.Function { panic(values.UnexpectedKind(semantic.Array, semantic.Function)) } func (v BooleanArrayValue) Equal(other values.Value) bool { if other.Type().Nature() != semantic.Array { return false } else if v.arr.Len() != other.Array().Len() { return false } otherArray := other.Array() for i, n := 0, v.arr.Len(); i < n; i++ { if !v.Get(i).Equal(otherArray.Get(i)) { return false } } return true } func (v BooleanArrayValue) Get(i int) values.Value { if v.arr.IsNull(i) { return values.Null } return values.New(v.arr.Value(i)) } func (v BooleanArrayValue) Set(i int, value values.Value) { panic("cannot set value on immutable array") } func (v BooleanArrayValue) Append(value values.Value) { panic("cannot append to immutable array") } func (v BooleanArrayValue) Len() int { return v.arr.Len() } func (v BooleanArrayValue) Range(f func(i int, v values.Value)) { for i, n := 0, v.arr.Len(); i < n; i++ { f(i, v.Get(i)) } } func (v BooleanArrayValue) Sort(f func(i values.Value, j values.Value) bool) { panic("cannot sort immutable array") } var _ values.Value = StringArrayValue{} var _ values.Array = StringArrayValue{} type StringArrayValue struct { arr *array.Binary typ semantic.MonoType } func NewStringArrayValue(arr *array.Binary) values.Array { return StringArrayValue{ arr: arr, typ: semantic.NewArrayType(semantic.BasicString), } } func (v StringArrayValue) Type() semantic.MonoType { return v.typ } func (v StringArrayValue) IsNull() bool { return false } func (v StringArrayValue) Str() string { panic(values.UnexpectedKind(semantic.Array, semantic.String)) } func (v StringArrayValue) Bytes() []byte { panic(values.UnexpectedKind(semantic.Array, semantic.Bytes)) } func (v StringArrayValue) Int() int64 { panic(values.UnexpectedKind(semantic.Array, semantic.Int)) } func (v StringArrayValue) UInt() uint64 { panic(values.UnexpectedKind(semantic.Array, semantic.UInt)) } func (v StringArrayValue) Float() float64 { panic(values.UnexpectedKind(semantic.Array, semantic.Float)) } func (v StringArrayValue) Bool() bool { panic(values.UnexpectedKind(semantic.Array, semantic.Bool)) } func (v StringArrayValue) Time() values.Time { panic(values.UnexpectedKind(semantic.Array, semantic.Time)) } func (v StringArrayValue) Duration() values.Duration { panic(values.UnexpectedKind(semantic.Array, semantic.Duration)) } func (v StringArrayValue) Regexp() *regexp.Regexp { panic(values.UnexpectedKind(semantic.Array, semantic.Regexp)) } func (v StringArrayValue) Array() values.Array { return v } func (v StringArrayValue) Object() values.Object { panic(values.UnexpectedKind(semantic.Array, semantic.Object)) } func (v StringArrayValue) Function() values.Function { panic(values.UnexpectedKind(semantic.Array, semantic.Function)) } func (v StringArrayValue) Equal(other values.Value) bool { if other.Type().Nature() != semantic.Array { return false } else if v.arr.Len() != other.Array().Len() { return false } otherArray := other.Array() for i, n := 0, v.arr.Len(); i < n; i++ { if !v.Get(i).Equal(otherArray.Get(i)) { return false } } return true } func (v StringArrayValue) Get(i int) values.Value { if v.arr.IsNull(i) { return values.Null } return values.New(v.arr.ValueString(i)) } func (v StringArrayValue) Set(i int, value values.Value) { panic("cannot set value on immutable array") } func (v StringArrayValue) Append(value values.Value) { panic("cannot append to immutable array") } func (v StringArrayValue) Len() int { return v.arr.Len() } func (v StringArrayValue) Range(f func(i int, v values.Value)) { for i, n := 0, v.arr.Len(); i < n; i++ { f(i, v.Get(i)) } } func (v StringArrayValue) Sort(f func(i values.Value, j values.Value) bool) { panic("cannot sort immutable array") }
internal/arrowutil/array_values.gen.go
0.726717
0.567337
array_values.gen.go
starcoder
package internal import ( "reflect" "github.com/tada/dgo/dgo" "github.com/tada/dgo/util" ) type ( errw struct { error } errType int ) // DefaultErrorType is the unconstrained Error type const DefaultErrorType = errType(0) var reflectErrorType = reflect.TypeOf((*error)(nil)).Elem() func (t errType) Type() dgo.Type { return MetaType(t) } func (t errType) Equals(other interface{}) bool { return t == Value(other) } func (t errType) HashCode() dgo.Hash { return dgo.Hash(t.TypeIdentifier()) } func (t errType) Assignable(other dgo.Type) bool { _, ok := other.(errType) if !ok { _, ok = other.(*errw) } return ok || CheckAssignableTo(nil, other, t) } func (t errType) Instance(value interface{}) bool { _, ok := value.(error) return ok } func (t errType) IsInstance(_ error) bool { return true } func (t errType) ReflectType() reflect.Type { return reflectErrorType } func (t errType) String() string { return TypeString(t) } func (t errType) TypeIdentifier() dgo.TypeIdentifier { return dgo.TiError } func (e *errw) Assignable(other dgo.Type) bool { return e.Equals(other) || CheckAssignableTo(nil, other, e) } func (e *errw) Generic() dgo.Type { return DefaultErrorType } func (e *errw) Instance(value interface{}) bool { return e.Equals(value) } func (e *errw) IsInstance(err error) bool { return e.Equals(err) } func (e *errw) ReflectType() reflect.Type { return reflectErrorType } func (e *errw) TypeIdentifier() dgo.TypeIdentifier { return dgo.TiErrorExact } func (e *errw) Equals(other interface{}) bool { if oe, ok := other.(*errw); ok { return e.error.Error() == oe.error.Error() } if oe, ok := other.(error); ok { return e.error.Error() == oe.Error() } return false } func (e *errw) HashCode() dgo.Hash { return util.StringHash(e.error.Error()) } func (e *errw) Error() string { return e.error.Error() } func (e *errw) ReflectTo(value reflect.Value) { if value.Kind() == reflect.Ptr { value.Set(reflect.ValueOf(&e.error)) } else { value.Set(reflect.ValueOf(e.error)) } } func (e *errw) String() string { return TypeString(e) } func (e *errw) Unwrap() error { if u, ok := e.error.(interface { Unwrap() error }); ok { return u.Unwrap() } return nil } func (e *errw) Type() dgo.Type { return e }
internal/error.go
0.613005
0.411879
error.go
starcoder