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 camera import ( "github.com/alexandreLamarre/Golang-Ray-Tracing-Renderer/pkg/algebra" "github.com/alexandreLamarre/Golang-Ray-Tracing-Renderer/pkg/canvas" "github.com/alexandreLamarre/Golang-Ray-Tracing-Renderer/pkg/geometry" "math" ) var RECURSIONDEPTH int = 3 //Camera describes a camera object that renders pixels from the setup scene type Camera struct { hSize float64 // horizontal size of picture to be rendered in pixels vSize float64 // vertical size of picture to be rendered in pixels fov float64 //determines the zoom of the camera halfWidth float64 halfHeight float64 pixelSize float64 transform *algebra.Matrix } //NewDefaultCamera returns a new camera with the given size and fov, that has 4x4 identity matrix as // the camera transformation func NewDefaultCamera(hSize, vSize, fov float64) *Camera { halfView := math.Tan(fov / 2) aspect := hSize / vSize var halfWidth float64 var halfHeight float64 if aspect >= 1 { halfWidth = halfView halfHeight = halfView / aspect } else { halfWidth = halfView * aspect halfHeight = halfView } pixelSize := (halfWidth * 2) / hSize return &Camera{hSize: hSize, vSize: vSize, fov: fov, halfWidth: halfWidth, halfHeight: halfHeight, pixelSize: pixelSize, transform: algebra.IdentityMatrix(4)} } //NewCamera return a new camera with the given size and fov and the provided 4x4 transform matrix func NewCamera(hSize, vSize, fov float64, transform *algebra.Matrix) (*Camera, error) { if len(transform.Get()) != 4 || len(transform.Get()[0]) != 4 { return nil, algebra.ExpectedDimension(4) } halfView := math.Tan(fov / 2) aspect := hSize / vSize var halfWidth float64 var halfHeight float64 if aspect >= 1 { halfWidth = halfView halfHeight = halfView / aspect } else { halfWidth = halfView * aspect halfHeight = halfView } pixelSize := (halfWidth * 2) / hSize return &Camera{hSize: hSize, vSize: vSize, fov: fov, halfWidth: halfWidth, halfHeight: halfHeight, pixelSize: pixelSize, transform: transform}, nil } func (c Camera) RayForPixel(px, py float64) *algebra.Ray { xOffset := (px + 0.5) * c.pixelSize yOffset := (py + 0.5) * c.pixelSize worldX := c.halfWidth - xOffset worldY := c.halfHeight - yOffset intermediate := c.transform.Inverse() pixel := intermediate.MultiplyByVec(algebra.NewPoint(worldX, worldY, -1)) origin := intermediate.MultiplyByVec(algebra.NewPoint(0, 0, 0)) direction, err := pixel.Subtract(origin) if err != nil { panic(err) return nil } direction, err = direction.Normalize() if err != nil { panic(err) return nil } rDirection := direction.Get()[:3] rOrigin := origin.Get()[:3] res := append(rOrigin, rDirection...) return algebra.NewRay(res...) } func (c Camera) Render(w *geometry.World) *canvas.Canvas { image := canvas.NewCanvas(int(c.hSize), int(c.vSize)) for y := 0.0; y < c.vSize; y++ { for x := 0.0; x < c.hSize; x++ { ray := c.RayForPixel(x, y) color := w.ColorAt(ray, RECURSIONDEPTH) image.WritePixel(int(x), int(y), color) } } return image }
pkg/camera/camera.go
0.829803
0.555918
camera.go
starcoder
package cell import ( "math" "github.com/wdevore/Deuron8-Go/neuron_simulation/api" "github.com/wdevore/Deuron8-Go/neuron_simulation/model" ) // Dendrite is part of a compartment type Dendrite struct { soma api.ISoma simJ *model.SimJSON simModel api.IModel taoEff float64 // Minimum value. Typically 0.0 minPsp float64 // Contains Compartments compartments []api.ICompartment // Average weight over time // average float64 synapses int } // NewDendrite creates a new dendrite func NewDendrite(simModel api.IModel, soma api.ISoma) api.IDendrite { o := new(Dendrite) o.simModel = simModel o.compartments = []api.ICompartment{} o.soma = soma simJ, ok := simModel.Data().(*model.SimJSON) if !ok { panic("Dendrite: can't cast simModel to SimJSON") } o.simJ = simJ return o } // Initialize dendrite func (d *Dendrite) Initialize() { for _, compartment := range d.compartments { compartment.Initialize() } } // AddCompartment adds compartment func (d *Dendrite) AddCompartment(compartment api.ICompartment) { d.compartments = append(d.compartments, compartment) } // Reset dendrite func (d *Dendrite) Reset() { for _, compartment := range d.compartments { compartment.Reset() } // d.average = 0 } // APEfficacy Calc this synapses's reaction to the AP based on its // distance from the soma. func (d *Dendrite) APEfficacy(distance float64) float64 { dendrite := d.simJ.Neuron.Dendrites if distance < dendrite.Length { return 1.0 } return math.Exp(-(dendrite.Length - distance) / dendrite.TaoEff) } // Integrate is the actual integration func (d *Dendrite) Integrate(spanT, t int) (psp float64) { dendrite := d.simJ.Neuron.Dendrites // totalWeight := 0.0 for _, compartment := range d.compartments { // sum, total := compartment.Integrate(spanT, t) sum, _ := compartment.Integrate(spanT, t) psp += sum // totalWeight += total } psp = math.Max(psp, dendrite.MinPSPValue) // d.average = totalWeight / float64(d.synapses) return psp }
neuron_simulation/cell/dendrite.go
0.732113
0.453625
dendrite.go
starcoder
package bigc import ( "errors" "fmt" "go/ast" "go/parser" "go/token" "math/big" "strconv" "strings" ) // A BigC object represents a rational complex number. // BigCは複素数を表します type BigC struct { re *big.Rat im *big.Rat } // NewBigC creates a new BigC with real-part r and imaginary-part i. func NewBigC(r *big.Rat, i *big.Rat) *BigC { return &BigC{ re: r, im: i, } } func (z *BigC) adjust(x *BigC) { *z.re = *x.re *z.im = *x.im } // Abs sets z to square of |x| (the absolute value of x) and returns z. func (x *BigC) AbsSq() *big.Rat { res := new(big.Rat).Set(x.re) res.Mul(res, res) img := new(big.Rat).Set(x.im) return res.Add(res, img.Mul(img, img)) } // Add sets z to the sum x+y and returns z. func (z *BigC) Add(x *BigC, y *BigC) *BigC { z.adjust(x) z.re.Add(z.re, y.re) z.im.Add(z.im, y.im) return z } // Conj sets z to the conjugate complex number of x and returns z. func (z *BigC) Conj(x *BigC) *BigC { z.adjust(x) z.im.Neg(z.im) return z } // Equal reports whether whether x equals z. func (z *BigC) Equal(x *BigC) bool { return z.re.Cmp(x.re) == 0 && z.im.Cmp(x.im) == 0 } // Imag returns the imaginary-part of x. // The result is a reference to x's imaginary-part; it // may change if a new value is assigned to x, and vice versa. func (x *BigC) Imag() *big.Rat { return x.im } // Inv sets z to 1/x and returns z. // If x == 0, Inv panics. func (z *BigC) Inv(x *BigC) *BigC { z.adjust(x) denom := z.AbsSq() z.re.Quo(z.re, denom) z.im.Quo(z.im, denom) return z.Conj(z) } // IsPureImag reports whether whether x is a pure imaginary number. func (x *BigC) IsPureImag() bool { return !x.IsReal() && x.re.Sign() == 0 } // IsReal reports whether whether x is a real number. func (x *BigC) IsReal() bool { return x.im.Sign() == 0 } // Mul sets z to the product x*y and returns z. func (z *BigC) Mul(x *BigC, y *BigC) *BigC { z.adjust(x) imag_temp := new(big.Rat).Set(z.re) z.re.Mul(z.re, y.re) real_temp := new(big.Rat).Set(z.im) real_temp.Mul(real_temp, y.im) z.re.Sub(z.re, real_temp) z.im.Mul(z.im, y.re) imag_temp.Mul(imag_temp, y.im) z.im.Add(z.im, imag_temp) return z } // Neg sets z to -x and returns z. func (z *BigC) Neg(x *BigC) *BigC { z.adjust(x) z.re.Neg(z.re) z.im.Neg(z.im) return z } // Quo sets z to the quotient x/y and returns z. // If y == 0, Quo panics. func (z *BigC) Quo(x *BigC, y *BigC) *BigC { z.adjust(x) temp := new(BigC).Set(y) temp.Inv(temp) z.Mul(z, temp) return z } // Real returns the real-part of x. // The result is a reference to x's real-part; it // may change if a new value is assigned to x, and vice versa. func (x *BigC) Real() *big.Rat { return x.re } // Set sets z to x (by making a copy of x) and returns z. func (z *BigC) Set(x *BigC) *BigC { z = &BigC{ re: x.re, im: x.im, } return z } // FloatString returns a string representation of x in decimal form with prec // digits of precision after the radix point. The last digit is rounded to // nearest, with halves rounded away from zero. func (x *BigC) FloatString(prec int) string { if x.re.Sign() == 0 && x.im.Sign() == 0 { return "0" } if x.re.Sign() == 0 { return fmt.Sprintf("%si", x.im.FloatString(prec)) } if x.im.Sign() == 0 { return fmt.Sprintf("%s", x.re.FloatString(prec)) } if x.im.Sign() == 1 { return fmt.Sprintf("%s+%s", x.re.FloatString(prec), x.im.FloatString(prec)) } return fmt.Sprintf("%s%s", x.re.FloatString(prec), x.im.FloatString(prec)) } // String returns a string exact representation of x. func (x *BigC) String() string { if x.re.Sign() == 0 && x.im.Sign() == 0 { return "0" } i_sign_char := "" i_str := "" if x.im.Sign() == 1 { i_sign_char = "+" } denom := fmt.Sprintf("/%s", x.im.Denom().String()) if x.im.Denom().Cmp(big.NewInt(1)) == 0 { denom = "" } if x.im.Num().Cmp(big.NewInt(1)) == 0 { i_str = fmt.Sprintf("i%s", denom) } else if x.im.Num().Cmp(big.NewInt(-1)) == 0 { i_str = fmt.Sprintf("-i%s", denom) } else if x.im.Sign() == 0 { i_str = "" } else { i_str = fmt.Sprintf("%si%s", x.im.Num().String(), denom) } if x.re.Sign() == 0 { return i_str } return fmt.Sprintf("%s%s%s", x.re.RatString(), i_sign_char, i_str) } // Sub sets z to the difference x-y and returns z. func (z *BigC) Sub(x *BigC, y *BigC) *BigC { z.adjust(x) z.re.Sub(z.re, y.re) z.im.Sub(z.im, y.im) return z } // ParseString returns a new BigC instance of the result of the expression expr. // Arithmetic operations and parentheses are supported. func ParseString(expr string) (*BigC, error) { no_w := strings.Join(strings.Fields(strings.TrimSpace(expr)), "") ast, err := parser.ParseExpr(no_w) if err != nil { return nil, err } a, err := walk(ast) if err != nil { return nil, err } return a, nil } func walk(ex interface{}) (*BigC, error) { switch node := ex.(type) { case *ast.BinaryExpr: x, e1 := walk(node.X) if e1 != nil { return nil, e1 } y, e2 := walk(node.Y) if e2 != nil { return nil, e2 } switch node.Op { case token.ADD: x.Add(x, y) return x, nil case token.SUB: x.Sub(x, y) return x, nil case token.MUL: x.Mul(x, y) return x, nil case token.QUO: x.Quo(x, y) return x, nil } return nil, errors.New("unexpected operator.") case *ast.UnaryExpr: x, err := walk(node.X) if err != nil { return nil, err } switch node.Op { case token.ADD: return x, nil case token.SUB: x.Neg(x) return x, nil } return nil, errors.New("unexpected operator.") case *ast.ParenExpr: i, err := walk(node.X) if err != nil { return nil, err } return i, nil case *ast.BasicLit: switch node.Kind { case token.INT: num, err := strconv.ParseInt(node.Value, 10, 64) if err != nil { return nil, err } return &BigC{ re: big.NewRat(num, 1), im: big.NewRat(0, 1), }, nil case token.FLOAT: num, err := strconv.ParseFloat(node.Value, 64) if err != nil { return nil, err } var res big.Rat res.SetFloat64(num) return &BigC{ re: &res, im: big.NewRat(0, 1), }, nil case token.IMAG: if node.Value[len(node.Value)-1] != 'i' { return nil, errors.New("unknown error.") } num, err := strconv.ParseFloat(node.Value[:len(node.Value)-1], 64) if err != nil { return nil, err } var res big.Rat res.SetFloat64(num) return &BigC{ re: big.NewRat(0, 1), im: &res, }, nil } case *ast.Ident: if node.Name == "i" { return &BigC{ re: big.NewRat(0, 1), im: big.NewRat(1, 1), }, nil } return nil, errors.New("unexpected identier.") } return nil, errors.New("parse error.") }
bigc.go
0.731155
0.433981
bigc.go
starcoder
// Package graphic provides simple BLAST report graphic rendering. package graphic import ( "fmt" "image/color" "math" "github.com/biogo/ncbi/blast" "gonum.org/v1/plot/vg" ) const maxInt = int(^uint(0) >> 1) var ( black = color.RGBA{R: 0x00, G: 0x00, B: 0x00, A: 0xff} purple = color.RGBA{R: 0xc4, G: 0x00, B: 0xff, A: 0xff} blue = color.RGBA{R: 0x00, G: 0x00, B: 0xff, A: 0xff} cyan = color.RGBA{R: 0x00, G: 0xff, B: 0xff, A: 0xff} green = color.RGBA{R: 0x00, G: 0xff, B: 0x00, A: 0xff} yellow = color.RGBA{R: 0xff, G: 0xff, B: 0x00, A: 0xff} orange = color.RGBA{R: 0xff, G: 0xc4, B: 0x00, A: 0xff} red = color.RGBA{R: 0xff, G: 0x00, B: 0x00, A: 0xff} grey = color.RGBA{R: 0x80, G: 0x80, B: 0x80, A: 0xff} white = color.RGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff} pallete = colors{ color.RGBA{}, color.RGBA{}, grey, red, orange, yellow, green, cyan, blue, purple, black, } ) type colors []color.Color func (c colors) color(f float64) color.Color { if f >= 1 { return black } return pallete[int(f*10)] } const ( maxNameLen = 20 header vg.Length = 40 footer vg.Length = 20 gutter vg.Length = 5 leftMargin vg.Length = 150 bodyWidth vg.Length = 600 rightMargin vg.Length = 50 lineWidth vg.Length = 3 hitGap vg.Length = 16 hspGap vg.Length = 20 fontName = "Helvetica" tinySize = vg.Length(7) smallSize = vg.Length(12) mediumSize = vg.Length(13) largeSize = vg.Length(16) ) func mustMakeFont(font vg.Font, err error) vg.Font { if err != nil { panic(err) } return font } var ( tinyFont = mustMakeFont(vg.MakeFont(fontName, tinySize)) smallFont = mustMakeFont(vg.MakeFont(fontName, smallSize)) mediumFont = mustMakeFont(vg.MakeFont(fontName+"-Bold", mediumSize)) largeFont = mustMakeFont(vg.MakeFont(fontName, mediumSize)) ) func fracId(id, ln *int) float64 { if id == nil || ln == nil { return math.NaN() } return float64(*id) / float64(*ln) } // A Summary can display a graphical summary of a blast output result. type Summary struct { // Legend, Aligns and Depths specify whether the legend, alignments // and depth plots are drawn. All are set to true by NewSummary. Legend bool Aligns bool Depths bool w, h vg.Length scale float64 query string labels []string hits map[string][]hspSum n int min, max int } type hspSum struct { queryFrom int queryTo int hitFrom int hitTo int identity float64 } // NewSummary returns a Summary of the provided blast output. func NewSummary(o blast.Output) Summary { if o.Program == "" { return Summary{} } var ( n int labels []string hits = make(map[string][]hspSum) min = maxInt max = 0 ) for _, i := range o.Iterations { for _, h := range i.Hits { if _, ok := hits[h.Id]; !ok { labels = append(labels, h.Id) } for _, hsp := range h.Hsps { if hsp.QueryFrom > hsp.QueryTo { hsp.QueryFrom, hsp.QueryTo = hsp.QueryTo, hsp.QueryFrom hsp.HitFrom, hsp.HitTo = hsp.HitTo, hsp.HitFrom } if hsp.QueryTo > max { max = hsp.QueryTo } if hsp.QueryFrom < min { min = hsp.QueryFrom } hits[h.Id] = append(hits[h.Id], hspSum{ queryFrom: hsp.QueryFrom, queryTo: hsp.QueryTo, hitFrom: hsp.HitFrom, hitTo: hsp.HitTo, identity: fracId(hsp.HspIdentity, hsp.AlignLen), }) n++ } } } if min >= max { min = 1 max = o.QueryLen } return Summary{ Legend: true, Aligns: true, Depths: true, scale: float64(bodyWidth) / float64(max-min), query: o.QueryId, labels: labels, hits: hits, n: n, min: min, max: max, } } // Render returns a vg.Canvas that has had the receiver's summary information // rendered to it. The function cf must return a vg.Canvas that is w by h in size. func (s Summary) Render(cf func(w, h vg.Length) vg.Canvas) vg.Canvas { w := leftMargin + bodyWidth + rightMargin h := header + footer if s.Aligns { h += hitGap*vg.Length(s.n) + hspGap*vg.Length(len(s.hits)) } c := cf(w, h) s.w = w s.h = h s.renderHeader(c) if s.Legend && s.Aligns && s.n > 0 { s.renderLegend(c) } s.renderAlignments(c) return c } func min(a, b int) int { if a < b { return a } return b } // invert inverts the y-axis coordinates so that the origin is at the top of the page. func (s Summary) invert(y vg.Length) vg.Length { return s.h - y } // renderHeader renders the header to c. func (s Summary) renderHeader(c vg.Canvas) { var p vg.Path p.Move(vg.Point{0, 0}) p.Line(vg.Point{s.w, 0}) p.Line(vg.Point{s.w, s.h}) p.Line(vg.Point{0, s.h}) p.Close() c.SetColor(white) c.Fill(p) c.SetColor(black) c.FillString(mediumFont, vg.Point{gutter, s.invert(header - smallSize)}, s.query[:min(len(s.query), maxNameLen)]) p = p[:0] p.Move(vg.Point{leftMargin, s.invert(header)}) p.Line(vg.Point{leftMargin + bodyWidth, s.invert(header)}) c.SetLineWidth(1) c.Stroke(p) c.FillString(smallFont, vg.Point{leftMargin, s.invert(header - smallSize)}, fmt.Sprint(s.min)) queryMax := fmt.Sprint(fmt.Sprint(s.max)) offQueryMax := smallFont.Width(queryMax) c.FillString(smallFont, vg.Point{leftMargin + bodyWidth - offQueryMax, s.invert(header - smallSize)}, queryMax) } // renderLegend renders the legend to c. func (s Summary) renderLegend(c vg.Canvas) { c.SetColor(black) c.FillString(smallFont, vg.Point{leftMargin + bodyWidth - 80, s.invert(smallSize + 2)}, "% Identity") var p vg.Path for i := 20; i <= 100; i += 10 { x := leftMargin + bodyWidth/2 + vg.Length(i)*2 p.Move(vg.Point{x, s.invert(gutter)}) p.Line(vg.Point{x + 10, s.invert(gutter)}) p.Line(vg.Point{x + 10, s.invert(gutter + 10)}) p.Line(vg.Point{x, s.invert(gutter + 10)}) p.Close() c.SetColor(pallete.color(float64(i) / 100)) c.Fill(p) p = p[:0] c.SetColor(black) c.FillString(tinyFont, vg.Point{x, s.invert(tinySize + gutter + 10)}, fmt.Sprint(i)) } } // xCoordOf returns the scales and translated x-coordinate of a query position. func (s Summary) xCoordOf(p int) vg.Length { return vg.Length(p-s.min)*vg.Length(s.scale) + leftMargin } // renderAlignments renders the alignments to c. func (s Summary) renderAlignments(c vg.Canvas) { var ( v vg.Length depth = make(map[int]int) p vg.Path ) for _, id := range s.labels { v += hspGap if s.Aligns { c.SetColor(black) c.FillString(smallFont, vg.Point{2 * gutter, s.invert(header + v + 2*tinySize)}, id[:min(len(id), maxNameLen)]) } c.SetLineWidth(lineWidth) for _, hsp := range s.hits[id] { v += hitGap x1 := s.xCoordOf(hsp.queryFrom) x2 := s.xCoordOf(hsp.queryTo) y := header + v for i := int(x1); i < int(x2); i++ { depth[i]++ } if s.Aligns { p.Move(vg.Point{x1, s.invert(y - smallSize/1.5)}) p.Line(vg.Point{x2, s.invert(y - smallSize/1.5)}) c.SetColor(pallete.color(hsp.identity)) c.Stroke(p) p = p[:0] c.SetColor(black) c.FillString(tinyFont, vg.Point{x1, s.invert(y - 2*tinySize)}, fmt.Sprint(hsp.queryFrom)) queryTo := fmt.Sprint(hsp.queryTo) offQueryTo := tinyFont.Width(queryTo) c.FillString(tinyFont, vg.Point{x2 - offQueryTo, s.invert(y - 2*tinySize)}, queryTo) c.FillString(tinyFont, vg.Point{x1, s.invert(y)}, fmt.Sprint(hsp.hitFrom)) hitTo := fmt.Sprint(hsp.hitTo, strand(hsp.hitTo-hsp.hitFrom)) offHitTo := tinyFont.Width(hitTo) c.FillString(tinyFont, vg.Point{x2 - offHitTo, s.invert(y)}, hitTo) } } } if s.Depths && s.n > 0 { c.SetLineWidth(0.25) var ( maxd int min = maxInt max = 0 ) for p, d := range depth { if d > maxd { maxd = d } if p > max { max = p } if p < min { min = p } } dScale := maxd/10 + 1 const offset = 3 c.FillString(tinyFont, vg.Point{leftMargin + bodyWidth + offset, s.invert(header + tinySize)}, fmt.Sprintf("%d/line", dScale)) for i := min; i <= max; i++ { d, ok := depth[i] if !ok { continue } l := vg.Length(d / dScale) p.Move(vg.Point{vg.Length(i), s.invert(header + offset)}) p.Line(vg.Point{vg.Length(i), s.invert(header + offset + l)}) c.Stroke(p) p = p[:0] } } } type strand int func (s strand) String() string { if s < 0 { return "-" } return "+" }
blast/graphic/graphic.go
0.748076
0.428353
graphic.go
starcoder
package flightid import( "fmt" "math" "math/rand" "sort" "github.com/skypies/geo" ) // Randomness in public: Fri Mar 17, 18:00, until Sat Mar 18, 11:00 // Selector is a role for things (algorithms) that can select a problem aircraft from an airspace type Selector interface { String() string // Pick out the noise-making flight from the array, and a oneline explanation. If none // was identified, returns nil (but the string will explain why). // The aircraft slice is initially sorted by Dist3. Identify(pos geo.Latlong, elev float64, aircraft []Aircraft) (*Aircraft, string) } // SelectorNames is the list of selectors we want users to be able to pick from var SelectorNames = []string{"conservative","cone"} func NewSelector(name string) Selector { switch name { case "random": return AlgoRandom{} case "conservative": return AlgoConservativeNoCongestion{} case "cone": return AlgoLowestInCone{} default: return AlgoConservativeNoCongestion{} } } func ListSelectors() [][]string { ret := [][]string{} for _,name := range SelectorNames { ret = append(ret, []string{name, NewSelector(name).String()}) } return ret } type AlgoRandom struct{} func (a AlgoRandom)String() string { return "Picks at random" } func (a AlgoRandom)Identify(pos geo.Latlong, elev float64, in []Aircraft) (*Aircraft,string) { if len(in) == 0 { return nil, "list was empty" } i := rand.Intn(len(in)) return &in[i], fmt.Sprintf("random (grabbed aircraft %d from list of %d)", i+1, len(in)) } // The original, "no congestion allowed" heuristic ... type AlgoConservativeNoCongestion struct{} func (a AlgoConservativeNoCongestion)String() string { return "Conservative, gives up on congestion" } func (a AlgoConservativeNoCongestion)Identify(pos geo.Latlong, elev float64, in []Aircraft) (*Aircraft,string) { if len(in) == 0 { return nil, "nothing in list" } else if (in[0].Dist3 >= 12.0) { return nil, "not picked; 1st closest was too far away (>12KM)" } else if (len(in) == 1) || (in[1].Dist3 - in[0].Dist3) > 4.0 { return &in[0], "selected 1st closest" } else { return nil, "not picked; 2nd closest was too close to 1st (<4KM)" } } type AlgoLowestInCone struct{} func (a AlgoLowestInCone)String() string { return "Picks lowest inside a 60deg cone [EXPERIMENTAL]" } func (a AlgoLowestInCone)Identify(pos geo.Latlong, elev float64, in []Aircraft) (*Aircraft,string) { if len(in) == 0 { return nil, "nothing in list" } else if (in[0].Dist3 >= 12.0) { return nil, "not picked; 1st closest was too far away (>12KM)" } else if (len(in) == 1) || (in[1].Dist3 - in[0].Dist3) > 4.0 { return &in[0], "selected 1st closest" } // Build new list of just those flights which are within the cone (i.e. angle <60deg) enconed := []Aircraft{} for _,a := range in { // angle between a vertical line from pos, and the line from pos to the aircraft. horizDistKM := a.Dist vertDistKM := (a.Altitude - elev) / geo.KFeetPerKM if angle := math.Atan2(horizDistKM,vertDistKM) * (180.0 / math.Pi); angle <= 60 { enconed = append(enconed, a) } } if len(enconed) == 0 { return nil, "not picked; nothing found inside 60deg cone." } sort.Sort(AircraftByAltitude(enconed)) return &enconed[0], "picked lowest in cone." }
flightid/selector.go
0.657758
0.440289
selector.go
starcoder
package grpc import ( "fmt" "reflect" "strconv" "strings" "google.golang.org/grpc/status" "github.com/golang/protobuf/proto" "github.com/pkg/errors" "github.com/zoncoen/scenarigo/assert" "github.com/zoncoen/scenarigo/context" "github.com/zoncoen/yaml" ) // Expect represents expected response values. type Expect struct { Code string `yaml:"code"` Body yaml.KeyOrderPreservedInterface `yaml:"body"` Status ExpectStatus `yaml:"status"` } // ExpectStatus represents expected gRPC status. type ExpectStatus struct { Code string `yaml:"code"` Message string `yaml:"message"` Details []map[string]yaml.MapSlice `yaml:"details"` } // Build implements protocol.AssertionBuilder interface. func (e *Expect) Build(ctx *context.Context) (assert.Assertion, error) { expectBody, err := ctx.ExecuteTemplate(e.Body) if err != nil { return nil, errors.Errorf("invalid expect response: %s", err) } assertion := assert.Build(expectBody) return assert.AssertionFunc(func(v interface{}) error { message, stErr, err := extract(v) if err != nil { return err } if err := e.assertStatusCode(stErr); err != nil { return err } if err := e.assertStatusMessage(stErr); err != nil { return err } if err := e.assertStatusDetails(stErr); err != nil { return err } if err := assertion.Assert(message); err != nil { return err } return nil }), nil } func (e *Expect) assertStatusCode(sts *status.Status) error { expectedCode := "OK" if e.Code != "" { expectedCode = e.Code } if e.Status.Code != "" { expectedCode = e.Status.Code } if got, expected := sts.Code().String(), expectedCode; got == expected { return nil } if got, expected := strconv.Itoa(int(int32(sts.Code()))), expectedCode; got == expected { return nil } return errors.Errorf(`expected code is "%s" but got "%s": message="%s": details=[ %s ]`, expectedCode, sts.Code().String(), sts.Message(), detailsString(sts)) } func (e *Expect) assertStatusMessage(sts *status.Status) error { if e.Status.Message == "" { return nil } if sts.Message() == e.Status.Message { return nil } return errors.Errorf(`expected status.message is "%s" but got "%s": code="%s": details=[ %s ]`, e.Status.Message, sts.Message(), sts.Code().String(), detailsString(sts)) } func (e *Expect) assertStatusDetails(sts *status.Status) error { if len(e.Status.Details) == 0 { return nil } actualDetails := sts.Details() for i, expecteDetailMap := range e.Status.Details { if i >= len(actualDetails) { return errors.Errorf(`expected status.details[%d] is not found: details=[ %s ]`, i, detailsString(sts)) } if len(expecteDetailMap) != 1 { return errors.Errorf("invalid yaml: expect status.details[%d]:"+ "An element of status.details list must be a map of size 1 with the detail message name as the key and the value as the detail message object.", i) } var expectName string var expectDetail interface{} for k, v := range expecteDetailMap { expectName = k expectDetail = v break } actual, ok := actualDetails[i].(proto.Message) if !ok { return errors.Errorf(`expected status.details[%d] is "%s" but got detail is not a proto message: "%#v"`, i, expectName, actualDetails[i]) } if name := proto.MessageName(actual); name != expectName { return errors.Errorf(`expected status.details[%d] is "%s" but got detail is "%s": details=[ %s ]`, i, expectName, name, detailsString(sts)) } if err := assert.Build(expectDetail).Assert(actual); err != nil { return err } } return nil } func detailsString(sts *status.Status) string { format := "%s: {%s}" var details []string for _, i := range sts.Details() { if pb, ok := i.(proto.Message); ok { details = append(details, fmt.Sprintf(format, proto.MessageName(pb), pb.String())) continue } if e, ok := i.(interface{ Error() string }); ok { details = append(details, fmt.Sprintf(format, "<non proto message>", e.Error())) continue } details = append(details, fmt.Sprintf(format, "<non proto message>", fmt.Sprintf("{%#v}", i))) } return strings.Join(details, ", ") } func extract(v interface{}) (proto.Message, *status.Status, error) { vs, ok := v.([]reflect.Value) if !ok { return nil, nil, errors.Errorf("expected []reflect.Value but got %T", v) } if len(vs) != 2 { return nil, nil, errors.Errorf("expected return value length of method call is 2 but %d", len(vs)) } if !vs[0].IsValid() { return nil, nil, errors.New("first return value is invalid") } message, ok := vs[0].Interface().(proto.Message) if !ok { if !vs[0].IsNil() { return nil, nil, errors.Errorf("expected first return value is proto.Message but %T", vs[0].Interface()) } } if !vs[1].IsValid() { return nil, nil, errors.New("second return value is invalid") } callErr, ok := vs[1].Interface().(error) if !ok { if !vs[1].IsNil() { return nil, nil, errors.Errorf("expected second return value is error but %T", vs[1].Interface()) } } var sts *status.Status if ok { sts, ok = status.FromError(callErr) if !ok { return nil, nil, errors.Errorf(`expected error is status but got %T: "%s"`, callErr, callErr.Error()) } } return message, sts, nil }
protocol/grpc/expect.go
0.624866
0.406509
expect.go
starcoder
package byteorder import "math" var _ = (BigEndian)(nil) // BE is an Alias for BigEndian. type BE = BigEndian // BigEndian defines big-endian serialization. type BigEndian []byte // ReadUint16 reads the first 2 bytes. Panics when len(b) < 2. func (b BigEndian) ReadUint16() uint16 { _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 return uint16(b[1]) | uint16(b[0])<<8 } // WriteUint16 writes an unsigned 16 bit integer. Panics when len(b) < 2. func (b BigEndian) WriteUint16(v uint16) { _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 b[0] = byte(v >> 8) //nolint:gomnd b[1] = byte(v) } // ReadUint24 reads the first 3 bytes. Panics when len(b) < 3. func (b BigEndian) ReadUint24() uint32 { _ = b[2] // bounds check hint to compiler; see golang.org/issue/14808 return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16 } // WriteUint24 writes the first 3 bytes. Panics when len(b) < 3. func (b BigEndian) WriteUint24(v uint32) { _ = b[2] // early bounds check to guarantee safety of writes below b[0] = byte(v >> 16) //nolint:gomnd b[1] = byte(v >> 8) //nolint:gomnd b[2] = byte(v) } // ReadUint32 reads the first 4 bytes. Panics when len(b) < 4. func (b BigEndian) ReadUint32() uint32 { _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 } // WriteUint32 writes the first 4 bytes. Panics when len(b) < 4. func (b BigEndian) WriteUint32(v uint32) { _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 b[0] = byte(v >> 24) //nolint:gomnd b[1] = byte(v >> 16) //nolint:gomnd b[2] = byte(v >> 8) //nolint:gomnd b[3] = byte(v) } // ReadUint40 reads the first 5 bytes. Panics when len(b) < 5. func (b BigEndian) ReadUint40() uint64 { _ = b[4] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[4]) | uint64(b[3])<<8 | uint64(b[2])<<16 | uint64(b[1])<<24 | uint64(b[0])<<32 } // WriteUint40 writes the first 5 bytes. Panics when len(b) < 5. func (b BigEndian) WriteUint40(v uint64) { _ = b[4] // bounds check hint to compiler; see golang.org/issue/14808 b[0] = byte(v >> 32) //nolint:gomnd b[1] = byte(v >> 24) //nolint:gomnd b[2] = byte(v >> 16) //nolint:gomnd b[3] = byte(v >> 8) //nolint:gomnd b[4] = byte(v) } // ReadUint48 reads the first 6 bytes. Panics when len(b) < 6. func (b BigEndian) ReadUint48() uint64 { _ = b[5] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[5]) | uint64(b[4])<<8 | uint64(b[3])<<16 | uint64(b[2])<<24 | uint64(b[1])<<32 | uint64(b[0])<<40 } // WriteUint48 writes the first 6 bytes. Panics when len(b) < 6. func (b BigEndian) WriteUint48(v uint64) { _ = b[5] // bounds check hint to compiler; see golang.org/issue/14808 b[0] = byte(v >> 40) //nolint:gomnd b[1] = byte(v >> 32) //nolint:gomnd b[2] = byte(v >> 24) //nolint:gomnd b[3] = byte(v >> 16) //nolint:gomnd b[4] = byte(v >> 8) //nolint:gomnd b[5] = byte(v) } // ReadUint56 reads the first 7 bytes. Panics when len(b) < 7. func (b BigEndian) ReadUint56() uint64 { _ = b[6] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[6]) | uint64(b[5])<<8 | uint64(b[4])<<16 | uint64(b[3])<<24 | uint64(b[2])<<32 | uint64(b[1])<<40 | uint64(b[0])<<48 } // WriteUint56 writes the first 7 bytes. Panics when len(b) < 7. func (b BigEndian) WriteUint56(v uint64) { _ = b[6] // bounds check hint to compiler; see golang.org/issue/14808 b[0] = byte(v >> 48) //nolint:gomnd b[1] = byte(v >> 40) //nolint:gomnd b[2] = byte(v >> 32) //nolint:gomnd b[3] = byte(v >> 24) //nolint:gomnd b[4] = byte(v >> 16) //nolint:gomnd b[5] = byte(v >> 8) //nolint:gomnd b[6] = byte(v) } // ReadUint64 reads the first 8 bytes. Panics when len(b) < 8. func (b BigEndian) ReadUint64() uint64 { _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 } // WriteUint64 writes the first 8 bytes. Panics when len(b) < 8. func (b BigEndian) WriteUint64(v uint64) { _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 b[0] = byte(v >> 56) //nolint:gomnd b[1] = byte(v >> 48) //nolint:gomnd b[2] = byte(v >> 40) //nolint:gomnd b[3] = byte(v >> 32) //nolint:gomnd b[4] = byte(v >> 24) //nolint:gomnd b[5] = byte(v >> 16) //nolint:gomnd b[6] = byte(v >> 8) //nolint:gomnd b[7] = byte(v) } // ReadFloat64 reads 8 bytes and interprets them as a float64 IEEE 754 4 byte bit sequence. // Panics when len(b) < 8. func (b BigEndian) ReadFloat64() float64 { bits := b.ReadUint64() return math.Float64frombits(bits) } // WriteFloat64 writes a float64 IEEE 754 8 byte bit sequence. // Panics when len(b) < 8. func (b BigEndian) WriteFloat64(v float64) { bits := math.Float64bits(v) b.WriteUint64(bits) } // ReadFloat32 reads 4 bytes and interprets them as a float32 IEEE 754 4 byte bit sequence. // Panics when len(b) < 4. func (b BigEndian) ReadFloat32() float32 { bits := b.ReadUint32() return math.Float32frombits(bits) } // WriteFloat32 writes a float32 IEEE 754 4 byte bit sequence. // Panics when len(b) < 4. func (b BigEndian) WriteFloat32(v float32) { bits := math.Float32bits(v) b.WriteUint32(bits) }
bigendian.go
0.621885
0.5835
bigendian.go
starcoder
package iso20022 // Conversion between the currency of a card acceptor and the currency of a card issuer, provided by a dedicated service provider. The currency conversion has to be accepted by the cardholder. type CurrencyConversion6 struct { // Identification of the currency conversion operation for the service provider. CurrencyConversionIdentification *Max35Text `xml:"CcyConvsId,omitempty"` // Currency into which the amount is converted (ISO 4217, 3 alphanumeric characters). TargetCurrency *CurrencyDetails1 `xml:"TrgtCcy"` // Amount converted in the target currency, including additional charges. ResultingAmount *ImpliedCurrencyAndAmount `xml:"RsltgAmt"` // Exchange rate, expressed as a percentage, applied to convert the original amount into the resulting amount. ExchangeRate *PercentageRate `xml:"XchgRate"` // Exchange rate, expressed as a percentage, applied to convert the resulting amount into the original amount. InvertedExchangeRate *PercentageRate `xml:"NvrtdXchgRate,omitempty"` // Date and time at which the exchange rate has been quoted. QuotationDate *ISODateTime `xml:"QtnDt,omitempty"` // Validity limit of the exchange rate. ValidUntil *ISODateTime `xml:"VldUntil,omitempty"` // Currency from which the amount is converted (ISO 4217, 3 alphanumeric characters). SourceCurrency *CurrencyDetails1 `xml:"SrcCcy"` // Original amount in the source currency. OriginalAmount *ImpliedCurrencyAndAmount `xml:"OrgnlAmt"` // Commission or additional charges made as part of a currency conversion. CommissionDetails []*Commission19 `xml:"ComssnDtls,omitempty"` // Markup made as part of a currency conversion. MarkUpDetails []*Commission18 `xml:"MrkUpDtls,omitempty"` // Card scheme declaration (disclaimer) to present to the cardholder. DeclarationDetails *ActionMessage5 `xml:"DclrtnDtls,omitempty"` } func (c *CurrencyConversion6) SetCurrencyConversionIdentification(value string) { c.CurrencyConversionIdentification = (*Max35Text)(&value) } func (c *CurrencyConversion6) AddTargetCurrency() *CurrencyDetails1 { c.TargetCurrency = new(CurrencyDetails1) return c.TargetCurrency } func (c *CurrencyConversion6) SetResultingAmount(value, currency string) { c.ResultingAmount = NewImpliedCurrencyAndAmount(value, currency) } func (c *CurrencyConversion6) SetExchangeRate(value string) { c.ExchangeRate = (*PercentageRate)(&value) } func (c *CurrencyConversion6) SetInvertedExchangeRate(value string) { c.InvertedExchangeRate = (*PercentageRate)(&value) } func (c *CurrencyConversion6) SetQuotationDate(value string) { c.QuotationDate = (*ISODateTime)(&value) } func (c *CurrencyConversion6) SetValidUntil(value string) { c.ValidUntil = (*ISODateTime)(&value) } func (c *CurrencyConversion6) AddSourceCurrency() *CurrencyDetails1 { c.SourceCurrency = new(CurrencyDetails1) return c.SourceCurrency } func (c *CurrencyConversion6) SetOriginalAmount(value, currency string) { c.OriginalAmount = NewImpliedCurrencyAndAmount(value, currency) } func (c *CurrencyConversion6) AddCommissionDetails() *Commission19 { newValue := new(Commission19) c.CommissionDetails = append(c.CommissionDetails, newValue) return newValue } func (c *CurrencyConversion6) AddMarkUpDetails() *Commission18 { newValue := new(Commission18) c.MarkUpDetails = append(c.MarkUpDetails, newValue) return newValue } func (c *CurrencyConversion6) AddDeclarationDetails() *ActionMessage5 { c.DeclarationDetails = new(ActionMessage5) return c.DeclarationDetails }
CurrencyConversion6.go
0.810028
0.567277
CurrencyConversion6.go
starcoder
package poly import ( "fmt" "math/rand" "strings" ) // Int64M is a matrix with polynomial elements that have int64 terms and coefficients. // The matrix itself is implemented as a dense representation, i.e. all elements are stored. type Int64M struct { // Elements contains the actual elements, top-left to bottom-right, row by row. Elements []Int64P // Stride is the length of each row in the matrix. Stride uint } // NewInt64M creates a new zero-filled matrix wich each element set to the constant value 0. func NewInt64M(rows, cols uint) *Int64M { m := Int64M{ Elements: make([]Int64P, rows*cols), Stride: cols, } for i := range m.Elements { m.Elements[i] = Int64P{Int64T{}} } return &m } // Det calculates the determinant of the square matrix. func (m Int64M) Det() Int64P { if m.Stride*m.Stride != uint(len(m.Elements)) { panic("math error: determinant of non-square matrix") } switch m.Stride { case 0: panic("math error: determinant of empty matrix") case 1: return m.Elements[0] } ret, sign := Int64P{}, int64(1) for i := uint(0); i < m.Stride; i++ { p := m.Elements[i].MulT(Int64T{Ind{}, sign}) ret = ret.Add(p.Mul(m.Minor(0, i).Det())) sign *= -1 } return ret } // Minor returns a copy of 'm' with the 'i'-th row and 'j'-th column removed. func (m Int64M) Minor(i, j uint) Int64M { ret := Int64M{Stride: m.Stride - 1} for k, p := range m.Elements { if uint(k)/m.Stride == i { // Remove the i-th row. continue } if uint(k)%m.Stride == j { // Remove the j-th column. continue } ret.Elements = append(ret.Elements, p) } return ret } // AnyMinor randomly picks a minor and returns it. func (m Int64M) AnyMinor() Int64M { return m.Minor(uint(rand.Intn(int(m.Stride))), uint(rand.Intn(int(m.Stride)))) } // String returns a compact, human-readable representation of the matrix. func (m Int64M) String() string { if len(m.Elements) == 0 || m.Stride == 0 { return "[]" } parts := make([]string, len(m.Elements)) sizes := make([]int, m.Stride) for i, e := range m.Elements { s := e.String() if len(e) > 1 { s = fmt.Sprintf("(%s)", s) } if size := len(strings.Split(s, "")); size > sizes[uint(i)%m.Stride] { sizes[uint(i)%m.Stride] = size } parts[i] = s } for i, s := range parts { parts[i] = fmt.Sprintf(fmt.Sprintf("%%%dv", sizes[uint(i)%m.Stride]), s) } rows := []string{} for len(parts) > 0 { rows = append(rows, strings.Join(parts[:m.Stride], " ")) parts = parts[m.Stride:] } if len(rows) == 1 { return "[" + rows[0] + "]" } ret := []string{} for i, row := range rows { switch i { case 0: ret = append(ret, "⎡"+row+"⎤") case len(rows) - 1: ret = append(ret, "⎣"+row+"⎦") default: ret = append(ret, "⎢"+row+"⎥") } } return strings.Join(ret, "\n") }
go/poly/int64_m.go
0.676299
0.588091
int64_m.go
starcoder
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // Float4ArrayFromFloat32Slice returns a driver.Valuer that produces a PostgreSQL float4[] from the given Go []float32. func Float4ArrayFromFloat32Slice(val []float32) driver.Valuer { return float4ArrayFromFloat32Slice{val: val} } // Float4ArrayToFloat32Slice returns an sql.Scanner that converts a PostgreSQL float4[] into a Go []float32 and sets it to val. func Float4ArrayToFloat32Slice(val *[]float32) sql.Scanner { return float4ArrayToFloat32Slice{val: val} } // Float4ArrayFromFloat64Slice returns a driver.Valuer that produces a PostgreSQL float4[] from the given Go []float64. func Float4ArrayFromFloat64Slice(val []float64) driver.Valuer { return float4ArrayFromFloat64Slice{val: val} } // Float4ArrayToFloat64Slice returns an sql.Scanner that converts a PostgreSQL float4[] into a Go []float64 and sets it to val. func Float4ArrayToFloat64Slice(val *[]float64) sql.Scanner { return float4ArrayToFloat64Slice{val: val} } type float4ArrayFromFloat32Slice struct { val []float32 } func (v float4ArrayFromFloat32Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for i := 0; i < len(v.val); i++ { out = strconv.AppendFloat(out, float64(v.val[i]), 'f', -1, 32) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type float4ArrayToFloat32Slice struct { val *[]float32 } func (v float4ArrayToFloat32Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) float32s := make([]float32, len(elems)) for i := 0; i < len(elems); i++ { f32, err := strconv.ParseFloat(string(elems[i]), 32) if err != nil { return err } float32s[i] = float32(f32) } *v.val = float32s return nil } type float4ArrayFromFloat64Slice struct { val []float64 } func (v float4ArrayFromFloat64Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for i := 0; i < len(v.val); i++ { out = strconv.AppendFloat(out, v.val[i], 'f', -1, 64) out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type float4ArrayToFloat64Slice struct { val *[]float64 } func (v float4ArrayToFloat64Slice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseCommaArray(arr) float64s := make([]float64, len(elems)) for i := 0; i < len(elems); i++ { f64, err := strconv.ParseFloat(string(elems[i]), 64) if err != nil { return err } float64s[i] = float64(f64) } *v.val = float64s return nil }
pgsql/float4arr.go
0.772616
0.525734
float4arr.go
starcoder
package waveforms import ( "errors" "math" "time" ) /** Waveforms is a simple library to generate wave formed signals with given amplitude, wavelength and phase for some period of time. This library is useful for generating of the sample time-series data i.e some metrics or stub telemetry. */ // generator is a periodic waveform generator function type generator func(wavelength float64, amplitude float64, phase float64, t float64) float64 // sine waveform generator func sine(wavelength float64, amplitude float64, phase float64, t float64) float64 { return amplitude * math.Sin((2*math.Pi*t-phase)/wavelength) } // square waveform generator func square(wavelength float64, amplitude float64, phase float64, t float64) float64 { switch { case math.Mod(t-phase, wavelength) < (wavelength / 2.0): return amplitude default: return -amplitude } } // triangle waveform generator func triangle(wavelength float64, amplitude float64, phase float64, t float64) float64 { return 2 * amplitude / math.Pi * math.Asin(math.Sin((2*math.Pi*t-phase)/wavelength)) } // sawtooth waveform generator func sawtooth(wavelength float64, amplitude float64, phase float64, t float64) float64 { return 2 * amplitude / math.Pi * math.Atan(math.Tan((2*math.Pi*t-phase)/(2*wavelength))) } // Waveform is a definition of a waveform. type Waveform struct { wavelength float64 amplitude float64 phase float64 ticker *time.Ticker flowRunning bool } func NewWaveform(wavelength float64, amplitude float64, phase float64) *Waveform { return &Waveform{wavelength: wavelength, amplitude: amplitude, phase: phase} } func (wv *Waveform) run(interval int64, g generator) (out chan float64, err error) { out = make(chan float64) if wv.flowRunning { err = errors.New("waveform is running already") return out, err } wv.ticker = time.NewTicker(time.Duration(interval) * time.Millisecond) wv.flowRunning = true go func() { for { v, ok := <-wv.ticker.C if ok { out <- g(wv.wavelength, wv.amplitude, wv.phase, float64(v.UnixNano()/(int64(time.Millisecond)/int64(time.Nanosecond)))) } } close(out) }() return out, nil } func (wv *Waveform) Sine(t float64) float64 { return sine(wv.wavelength, wv.amplitude, wv.phase, t) } func (wv *Waveform) Square(t float64) float64 { return square(wv.wavelength, wv.amplitude, wv.phase, t) } func (wv *Waveform) Triangle(t float64) float64 { return triangle(wv.wavelength, wv.amplitude, wv.phase, t) } func (wv *Waveform) Sawtooth(t float64) float64 { return sawtooth(wv.wavelength, wv.amplitude, wv.phase, t) } func (wv *Waveform) SineFlow(interval int64) (out chan float64, err error) { return wv.run(interval, sine) } func (wv *Waveform) SquareFlow(interval int64) (out chan float64, err error) { return wv.run(interval, square) } func (wv *Waveform) TriangleFlow(interval int64) (out chan float64, err error) { return wv.run(interval, triangle) } func (wv *Waveform) SawtoothFlow(interval int64) (out chan float64, err error) { return wv.run(interval, sawtooth) } // StopFlow ends generation of signal. func (wv *Waveform) StopFlow() { wv.flowRunning = false wv.ticker.Stop() }
waveforms.go
0.874198
0.667744
waveforms.go
starcoder
package d2 import ( "strconv" "strings" "github.com/adamcolton/geom/angle" "github.com/adamcolton/geom/calc/cmpr" "github.com/adamcolton/geom/geomerr" ) // V represents a Vector, the difference between two points. type V D2 // Pt converts a V to Pt func (v V) Pt() Pt { return Pt(v) } // V fulfills the Vector interface func (v V) V() V { return v } // Polar converts V to Polar func (v V) Polar() Polar { return D2(v).Polar() } // Angle of the vector func (v V) Angle() angle.Rad { return D2(v).Angle() } // Mag2 returns the square magnitude of the vector. This can be useful for comparisons // to avoid the additional cost of a Sqrt call. func (v V) Mag2() float64 { return D2(v).Mag2() } // Mag returns the magnitude of the vector func (v V) Mag() float64 { return D2(v).Mag() } // Cross returns the cross product of the two vectors func (v V) Cross(v2 V) float64 { return v.X*v2.Y - v2.X*v.Y } // Dot returns the dot product of two vectors func (v V) Dot(v2 V) float64 { return v.X*v2.X + v.Y*v2.Y } // Multiply returns the scalar product of a vector. func (v V) Multiply(scale float64) V { return V{v.X * scale, v.Y * scale} } // Product of two vectors func (v V) Product(v2 V) V { return V{ X: v.X * v2.X, Y: v.Y * v2.Y, } } // String fulfills Stringer, returns the vector as "V(X, Y)" func (v V) String() string { return strings.Join([]string{ "V(", strconv.FormatFloat(v.X, 'f', Prec, 64), ", ", strconv.FormatFloat(v.Y, 'f', Prec, 64), ")", }, "") } // Add two vectors func (v V) Add(v2 V) V { return V{ X: v.X + v2.X, Y: v.Y + v2.Y, } } // Subtract two vectors func (v V) Subtract(v2 V) V { return V{ X: v.X - v2.X, Y: v.Y - v2.Y, } } // Abs of vector for both X and Y func (v V) Abs() V { if v.X < 0 { v.X = -v.X } if v.Y < 0 { v.Y = -v.Y } return v } // AssertEqual fulfils geomtest.AssertEqualizer func (v V) AssertEqual(actual interface{}, t cmpr.Tolerance) error { v2, ok := actual.(V) if !ok { return geomerr.TypeMismatch(v, actual) } d := v.Subtract(v2) if !t.Zero(d.X) || !t.Zero(d.Y) { return geomerr.NotEqual(v, v2) } return nil }
d2/v.go
0.881104
0.565119
v.go
starcoder
package option import "math" type OptionType bool const ( CALL OptionType = true PUT OptionType = false ) // A probablity distribution of a value. type Distribution interface { // Probability density function. Pdf(value float64) float64 // Cumulative distribution function. Cdf(value float64) float64 } func MakeStdNormDist() *NormDist { return &NormDist{ mean: 0.0, stdDev: 1.0, } } type NormDist struct { mean, stdDev float64 } func (d *NormDist) Pdf(value float64) float64 { return math.Exp(-math.Pow(value-d.mean, 2)/(2*d.stdDev*d.stdDev)) / (d.stdDev * math.Sqrt(math.Pi*2)) } func (d *NormDist) Cdf(value float64) float64 { return 0.5 * (1 + math.Erf((value-d.mean)/(d.stdDev*math.Sqrt2))) } type blackSholeModelParams struct { K, // ExerciePrice S, // UnderlyingPrice T, // YearsToExpiration R, // ApplicableInterestRate V float64 // Future realized volatilty of the underlying } func (p *blackSholeModelParams) d1() float64 { return (math.Log(p.S/p.K) + (p.R+0.5*p.V*p.V)*p.T) / (p.V * (math.Sqrt(p.T))) } func (p *blackSholeModelParams) d2() float64 { return (math.Log(p.S/p.K) + (p.R-0.5*p.V*p.V)*p.T) / (p.V * (math.Sqrt(p.T))) } func MakeBlackSholeModel(dist Distribution) *BlackSholeModel { return &BlackSholeModel{ dist: dist, } } type BlackSholeModel struct { dist Distribution } type BlackSholeModelResults struct { Price, Delta, Gamma, Theta, Vega, Rho float64 } func (m *BlackSholeModel) Calc(p blackSholeModelParams, optionType OptionType) BlackSholeModelResults { return BlackSholeModelResults{ Price: m.Price(p, optionType), Delta: m.Delta(p, optionType), Gamma: m.Gamma(p, optionType), Theta: m.Theta(p, optionType), Vega: m.Vega(p, optionType), Rho: m.Rho(p, optionType), } } func (m *BlackSholeModel) Price(p blackSholeModelParams, optionType OptionType) float64 { return p.S*m.Delta(p, optionType) - m.Rho(p, optionType)/p.T } func (m *BlackSholeModel) Delta(p blackSholeModelParams, optionType OptionType) float64 { if optionType == CALL { return m.dist.Cdf(p.d1()) } else { return -m.dist.Cdf(-p.d1()) } } func (m *BlackSholeModel) Gamma(p blackSholeModelParams, optionType OptionType) float64 { return m.dist.Pdf(p.d1()) / (p.S * p.V * math.Sqrt(p.T)) } func (m *BlackSholeModel) Theta(p blackSholeModelParams, optionType OptionType) float64 { return -p.V*.5*m.Vega(p, optionType)/p.T - p.R*m.Rho(p, optionType)/p.T } func (m *BlackSholeModel) Vega(p blackSholeModelParams, optionType OptionType) float64 { return p.S * m.dist.Pdf(p.d1()) * math.Sqrt(p.T) } func (m *BlackSholeModel) Rho(p blackSholeModelParams, optionType OptionType) float64 { if optionType == CALL { return p.K * p.T * math.Exp(-p.R*p.T) * m.dist.Cdf(p.d2()) } else { return -p.K * p.T * math.Exp(-p.R*p.T) * m.dist.Cdf(-p.d2()) } }
option/model.go
0.621426
0.443661
model.go
starcoder
package shape import ( "fmt" "math" "strings" "github.com/fogleman/gg" "github.com/golang/freetype/raster" ) // Quadratic represents a single quadratic bezier type Quadratic struct { X1, Y1 float64 X2, Y2 float64 X3, Y3 float64 Width float64 MinLineWidth float64 MaxLineWidth float64 MinArcLength float64 } func NewQuadratic() *Quadratic { q := &Quadratic{} q.MaxLineWidth = 1.0 / 2 q.MinLineWidth = 0.2 q.MinArcLength = 5 return q } func (q *Quadratic) Init(plane *Plane) { rnd := plane.Rnd q.X1 = randomW(plane) q.Y1 = randomH(plane) q.X2 = q.X1 + rnd.Float64()*40 - 20 q.Y2 = q.Y1 + rnd.Float64()*40 - 20 q.X3 = q.X2 + rnd.Float64()*40 - 20 q.Y3 = q.Y2 + rnd.Float64()*40 - 20 q.Width = 1.0 / 2 q.mutateImpl(plane, 1.0, 2, ActionAny) } func (q *Quadratic) Draw(dc *gg.Context, scale float64) { dc.MoveTo(q.X1, q.Y1) dc.QuadraticTo(q.X2, q.Y2, q.X3, q.Y3) dc.SetLineWidth(q.Width * scale) dc.Stroke() } func (q *Quadratic) SVG(attrs string) string { // TODO: this is a little silly attrs = strings.Replace(attrs, "fill", "stroke", -1) return fmt.Sprintf( "<path %s fill=\"none\" d=\"M %f %f Q %f %f, %f %f\" stroke-width=\"%f\" />", attrs, q.X1, q.Y1, q.X2, q.Y2, q.X3, q.Y3, q.Width) } func (q *Quadratic) Copy() Shape { a := *q return &a } func (q *Quadratic) Mutate(plane *Plane, temp float64) { q.mutateImpl(plane, temp, 10, ActionAny) } func (q *Quadratic) mutateImpl(plane *Plane, temp float64, rollback int, actions ActionType) { if actions == ActionNone { return } const R = math.Pi / 4.0 const m = 16 w := plane.W h := plane.H rnd := plane.Rnd scale := temp * 16 save := *q for { switch rnd.Intn(6) { case 0: // Move if (actions & ActionMutate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale q.X1 = clamp(q.X1+a, -m, float64(w-1+m)) q.Y1 = clamp(q.Y1+b, -m, float64(h-1+m)) case 1: if (actions & ActionMutate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale q.X2 = clamp(q.X2+a, -m, float64(w-1+m)) q.Y2 = clamp(q.Y2+b, -m, float64(h-1+m)) case 2: if (actions & ActionMutate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale q.X3 = clamp(q.X3+a, -m, float64(w-1+m)) q.Y3 = clamp(q.Y3+b, -m, float64(h-1+m)) case 3: // Width q.Width = clamp(q.Width+rnd.NormFloat64()*temp, q.MinLineWidth, q.MaxLineWidth) case 4: // Translate if (actions & ActionTranslate) == 0 { continue } a := rnd.NormFloat64() * scale b := rnd.NormFloat64() * scale q.X1 = clamp(q.X1+a, -m, float64(w-1+m)) q.Y1 = clamp(q.Y1+b, -m, float64(h-1+m)) q.X2 = clamp(q.X2+a, -m, float64(w-1+m)) q.Y2 = clamp(q.Y2+b, -m, float64(h-1+m)) q.X3 = clamp(q.X3+a, -m, float64(w-1+m)) q.Y3 = clamp(q.Y3+b, -m, float64(h-1+m)) case 5: // Rotate if (actions & ActionRotate) == 0 { continue } cx := (q.X1 + q.X2 + q.X3) / 3 cy := (q.Y1 + q.Y2 + q.Y3) / 3 theta := rnd.NormFloat64() * temp * R cos := math.Cos(theta) sin := math.Sin(theta) var a, b float64 a, b = rotateAbout(q.X1, q.Y1, cx, cy, cos, sin) q.X1 = clamp(a, -m, float64(w-1+m)) q.Y1 = clamp(b, -m, float64(h-1+m)) a, b = rotateAbout(q.X2, q.Y2, cx, cy, cos, sin) q.X2 = clamp(a, -m, float64(w-1+m)) q.Y2 = clamp(b, -m, float64(h-1+m)) a, b = rotateAbout(q.X3, q.Y3, cx, cy, cos, sin) q.X3 = clamp(a, -m, float64(w-1+m)) q.Y3 = clamp(b, -m, float64(h-1+m)) } if q.Valid() { break } if rollback > 0 { *q = save rollback -= 1 } } } func (q *Quadratic) Valid() bool { dx12 := int(q.X1 - q.X2) dy12 := int(q.Y1 - q.Y2) d12 := dx12*dx12 + dy12*dy12 dx23 := int(q.X2 - q.X3) dy23 := int(q.Y2 - q.Y3) d23 := dx23*dx23 + dy23*dy23 return d12 > 1 && d23 > 1 && q.arcLength() > q.MinArcLength } func (q *Quadratic) arcLength() float64 { // closed form solution to quadratic arcLength from stack overflow: // https://math.stackexchange.com/questions/12186/arc-length-of-bezier-curves xv := 2 * (q.X2 - q.X1) yv := 2 * (q.Y2 - q.Y1) xw := q.X3 - 2*q.X2 + q.X1 yw := q.Y3 - 2*q.Y2 + q.Y1 uu := 4 * (xw*xw + yw*yw) if uu < 0.0001 { return math.Sqrt((q.X3-q.X1)*(q.X3-q.X1) + (q.Y3-q.Y1)*(q.Y3-q.Y1)) } vv := 4 * (xv*xw + yv*yw) ww := xv*xv + yv*yv t1 := 2.0 * math.Sqrt(uu*(uu+vv+ww)) t2 := 2*uu + vv t3 := vv*vv - 4*uu*ww t4 := 2.0 * math.Sqrt(uu*ww) return ((t1*t2 - t3*math.Log(t2+t1) - (vv*t4 - t3*math.Log(vv+t4))) / (8 * math.Pow(uu, 1.5))) } func (q *Quadratic) Rasterize(rc *RasterContext) []Scanline { var path raster.Path p1 := fixp(q.X1, q.Y1) p2 := fixp(q.X2, q.Y2) p3 := fixp(q.X3, q.Y3) path.Start(p1) path.Add2(p2, p3) width := fix(q.Width) return strokePath(rc, path, width, raster.RoundCapper, raster.RoundJoiner) }
primitive/shape/quadratic.go
0.687
0.547222
quadratic.go
starcoder
package clock import ( "strconv" "time" ) var datetimeLayouts = [48]string{ // Day first month 2nd abbreviated. "Mon, 2 Jan 2006 15:04:05 MST", "Mon, 2 Jan 2006 15:04:05 -0700", "Mon, 2 Jan 2006 15:04:05 -0700 (MST)", "2 Jan 2006 15:04:05 MST", "2 Jan 2006 15:04:05 -0700", "2 Jan 2006 15:04:05 -0700 (MST)", "Mon, 2 Jan 2006 15:04 MST", "Mon, 2 Jan 2006 15:04 -0700", "Mon, 2 Jan 2006 15:04 -0700 (MST)", "2 Jan 2006 15:04 MST", "2 Jan 2006 15:04 -0700", "2 Jan 2006 15:04 -0700 (MST)", // Month first day 2nd abbreviated. "Mon, Jan 2 2006 15:04:05 MST", "Mon, Jan 2 2006 15:04:05 -0700", "Mon, Jan 2 2006 15:04:05 -0700 (MST)", "Jan 2 2006 15:04:05 MST", "Jan 2 2006 15:04:05 -0700", "Jan 2 2006 15:04:05 -0700 (MST)", "Mon, Jan 2 2006 15:04 MST", "Mon, Jan 2 2006 15:04 -0700", "Mon, Jan 2 2006 15:04 -0700 (MST)", "Jan 2 2006 15:04 MST", "Jan 2 2006 15:04 -0700", "Jan 2 2006 15:04 -0700 (MST)", // Day first month 2nd not abbreviated. "Mon, 2 January 2006 15:04:05 MST", "Mon, 2 January 2006 15:04:05 -0700", "Mon, 2 January 2006 15:04:05 -0700 (MST)", "2 January 2006 15:04:05 MST", "2 January 2006 15:04:05 -0700", "2 January 2006 15:04:05 -0700 (MST)", "Mon, 2 January 2006 15:04 MST", "Mon, 2 January 2006 15:04 -0700", "Mon, 2 January 2006 15:04 -0700 (MST)", "2 January 2006 15:04 MST", "2 January 2006 15:04 -0700", "2 January 2006 15:04 -0700 (MST)", // Month first day 2nd not abbreviated. "Mon, January 2 2006 15:04:05 MST", "Mon, January 2 2006 15:04:05 -0700", "Mon, January 2 2006 15:04:05 -0700 (MST)", "January 2 2006 15:04:05 MST", "January 2 2006 15:04:05 -0700", "January 2 2006 15:04:05 -0700 (MST)", "Mon, January 2 2006 15:04 MST", "Mon, January 2 2006 15:04 -0700", "Mon, January 2 2006 15:04 -0700 (MST)", "January 2 2006 15:04 MST", "January 2 2006 15:04 -0700", "January 2 2006 15:04 -0700 (MST)", } // Allows seamless JSON encoding/decoding of rfc822 formatted timestamps. // https://www.ietf.org/rfc/rfc822.txt section 5. type RFC822Time struct { Time } // NewRFC822Time creates RFC822Time from a standard Time. The created value is // truncated down to second precision because RFC822 does not allow for better. func NewRFC822Time(t Time) RFC822Time { return RFC822Time{Time: t.Truncate(Second)} } // ParseRFC822Time parses an RFC822 time string. func ParseRFC822Time(s string) (Time, error) { var t time.Time var err error for _, layout := range datetimeLayouts { t, err = Parse(layout, s) if err == nil { return t, err } } return t, err } // NewRFC822Time creates RFC822Time from a Unix timestamp (seconds from Epoch). func NewRFC822TimeFromUnix(timestamp int64) RFC822Time { return RFC822Time{Time: Unix(timestamp, 0).UTC()} } func (t RFC822Time) MarshalJSON() ([]byte, error) { return []byte(strconv.Quote(t.Format(RFC1123))), nil } func (t *RFC822Time) UnmarshalJSON(s []byte) error { q, err := strconv.Unquote(string(s)) if err != nil { return err } parsed, err := ParseRFC822Time(q) if err != nil { return err } t.Time = parsed return nil } func (t RFC822Time) String() string { return t.Format(RFC1123) } func (t RFC822Time) StringWithOffset() string { return t.Format(RFC1123Z) }
vendor/github.com/vulcand/oxy/internal/holsterv4/clock/rfc822.go
0.623721
0.442396
rfc822.go
starcoder
package types import ( "regexp" "time" "github.com/pkg/errors" "github.com/shopspring/decimal" ) // CurrencyTime represents a currency denom and associated date type CurrencyTime struct { Cur string Date time.Time } // AmtCurTime represents a CurrencyTime and associated amount type AmtCurTime struct { CurTime CurrencyTime Amount string //Decimal Number } // ParseAmtCurTime parse AmtCurTime from <amt><cur> and date func ParseAmtCurTime(amtCur string, date time.Time) (*AmtCurTime, error) { if len(amtCur) == 0 { return nil, errors.New("not enought information to parse AmtCurTime") } var reAmt = regexp.MustCompile("([\\d\\.]+)") var reCur = regexp.MustCompile("([^\\d\\W]+)") amt := reAmt.FindString(amtCur) cur := reCur.FindString(amtCur) return &AmtCurTime{CurrencyTime{cur, date}, amt}, nil } //AmtCurTime Algebra //nolint func (a *AmtCurTime) Add(a2 *AmtCurTime) (*AmtCurTime, error) { switch { case a == nil && a2 != nil: return a2, nil case a != nil && a2 == nil: return a, nil case a != nil && a2 != nil: amt1, amt2, err := getDecimals(a, a2) if err != nil { return nil, err } return &AmtCurTime{CurrencyTime{a.CurTime.Cur, a.CurTime.Date}, amt1.Add(amt2).String()}, nil case a == nil && a2 == nil: return nil, nil } return nil, nil //never called } //nolint func (a *AmtCurTime) Minus(a2 *AmtCurTime) (*AmtCurTime, error) { switch { case a == nil && a2 != nil: return nil, errors.New("a is nil") case a != nil && a2 == nil: return a, nil case a != nil && a2 != nil: amt1, amt2, err := getDecimals(a, a2) if err != nil { return nil, err } return &AmtCurTime{CurrencyTime{a.CurTime.Cur, a.CurTime.Date}, amt1.Sub(amt2).String()}, nil case a == nil && a2 == nil: return nil, errors.New("a is nil") } return nil, nil //never called } //AmtCurTime Equalities //nolint func (a *AmtCurTime) EQ(a2 *AmtCurTime) (bool, error) { amt1, amt2, err := getDecimals(a, a2) if err != nil { return false, err } return amt1.Equal(amt2), nil } //nolint func (a *AmtCurTime) GT(a2 *AmtCurTime) (bool, error) { amt1, amt2, err := getDecimals(a, a2) if err != nil { return false, err } return amt1.GreaterThan(amt2), nil } //nolint func (a *AmtCurTime) GTE(a2 *AmtCurTime) (bool, error) { amt1, amt2, err := getDecimals(a, a2) if err != nil { return false, err } return amt1.GreaterThanOrEqual(amt2), nil } //nolint func (a *AmtCurTime) LT(a2 *AmtCurTime) (bool, error) { amt1, amt2, err := getDecimals(a, a2) if err != nil { return false, err } return amt1.LessThan(amt2), nil } //nolint func (a *AmtCurTime) LTE(a2 *AmtCurTime) (bool, error) { amt1, amt2, err := getDecimals(a, a2) if err != nil { return false, err } return amt1.LessThanOrEqual(amt2), nil } func getDecimals(a1 *AmtCurTime, a2 *AmtCurTime) (amt1 decimal.Decimal, amt2 decimal.Decimal, err error) { if a1 == nil { return amt1, amt2, errors.New("input a1 is nil") } if a2 == nil { return amt1, amt2, errors.New("input a2 is nil") } amt1, err = decimal.NewFromString(a1.Amount) if err != nil { return } amt2, err = decimal.NewFromString(a2.Amount) if err != nil { return } err = a1.validateOperation(a2) return } func (a *AmtCurTime) validateOperation(a2 *AmtCurTime) error { if a.CurTime.Cur != a2.CurTime.Cur { return errors.New("Can't operate on two different currencies") } return nil }
types/currency.go
0.634883
0.551574
currency.go
starcoder
package feed_attributes import ( "math/big" "strconv" ) type Reputation int64 const REPUTATION_BASE = 100 var PostReputationCost Reputation = 10 * REPUTATION_BASE var ReplyReputationCost Reputation = 1 * REPUTATION_BASE var AduitReputationCost Reputation = 100 * REPUTATION_BASE func PenaltyForPostType(postType PostType, counter int64) Reputation { var reputations Reputation switch postType { case PostPostType: reputations = PostReputationCost.MulByPower(big.NewInt(2), big.NewInt(counter)) case ReplyPostType: reputations = ReplyReputationCost.MulByPower(big.NewInt(2), big.NewInt(counter)) case AuditPostType: reputations = AduitReputationCost.MulByPower(big.NewInt(2), big.NewInt(counter)) } return reputations } func CreateReputationFromStr(rep string) Reputation { i, _ := strconv.ParseInt(rep, 10, 64) return Reputation(i) } func PenaltyForVote(base Reputation, counter int64) Reputation { return base.MulByPower(big.NewInt(2), big.NewInt(counter)) } func BigIntToReputation(num *big.Int) Reputation { return Reputation(num.Int64()) } func (reputation Reputation) Value() int64 { return int64(reputation) } func (reputation Reputation) ToBigInt() *big.Int { return big.NewInt(reputation.Value()) } func (reputation Reputation) AddToReputations(reputationToAdd Reputation) Reputation { num := new(big.Int) num.Add(reputation.ToBigInt(), reputationToAdd.ToBigInt()) return BigIntToReputation(num) } func (reputation Reputation) SubReputations(reputationToSub Reputation) Reputation { num := new(big.Int) num.Sub(reputation.ToBigInt(), reputationToSub.ToBigInt()) return BigIntToReputation(num) } func (reputation Reputation) MulByPower(base *big.Int, factor *big.Int) Reputation { num := new(big.Int) numInt := new(big.Int).Exp(base, factor, nil ) num.Mul(reputation.ToBigInt(), numInt) return BigIntToReputation(num) } func (reputation Reputation) Sign() int { num := reputation.ToBigInt() return num.Sign() } func (reputation Reputation) Abs() int64 { num := new(big.Int) return num.Abs(reputation.ToBigInt()).Int64() } func (reputation Reputation) Neg() Reputation { num := new(big.Int) return BigIntToReputation(num.Neg(reputation.ToBigInt())) }
aws/go/src/feed/feed_attributes/reputation.go
0.625209
0.40642
reputation.go
starcoder
package ml import ( "math" "github.com/cpmech/gosl/chk" "github.com/cpmech/gosl/la" ) // PolyDataMapper maps features to expanded polynomial type PolyDataMapper struct { nOriFeatures int // number of original features nExtraFeatures int // number of added features iFeature int // selected iFeature to map jFeature int // selected jFeature to map degree int // degree of polynomial } // NewPolyDataMapper returns a new object func NewPolyDataMapper(nOriFeatures, iFeature, jFeature, degree int) (o *PolyDataMapper) { // check if degree < 2 { chk.Panic("PolyDataMapper is useful for degree >= 2. degree = %d is invalid\n", degree) } if iFeature > nOriFeatures-1 { chk.Panic("iFeature must be within [0, %d]. iFeature = %d is invalid\n", nOriFeatures-1, iFeature) } if jFeature > nOriFeatures { chk.Panic("jFeature must be within [0, %d]. jFeature = %d is invalid\n", nOriFeatures-1, jFeature) } // input data o = new(PolyDataMapper) o.nOriFeatures = nOriFeatures o.iFeature = iFeature o.jFeature = jFeature o.degree = degree // derived p := o.degree + 1 // auxiliary nPascal := p*(p+1)/2 - 1 // -1 because first row in Pascal triangle is neglected o.nExtraFeatures = nPascal - 2 // -2 because iFeature and jFeatureare were considered in nPascal already return } // NumOriginalFeatures returns the number of original features, before mapping/augmentation func (o *PolyDataMapper) NumOriginalFeatures() int { return o.nOriFeatures } // NumExtraFeatures returns the number of extra features added by this mapper func (o *PolyDataMapper) NumExtraFeatures() int { return o.nExtraFeatures } // Map maps xRaw into x and ignores y[:] = xyRaw[len(xyRaw)-1] // Input: // xRaw -- array with x values // Output: // x -- pre-allocated vector such that len(x) = nFeatures func (o *PolyDataMapper) Map(x, xRaw la.Vector) { // copy existent features for j := 0; j < o.nOriFeatures; j++ { x[j] = xRaw[j] } // mapped features xi := xRaw[o.iFeature] xj := xRaw[o.jFeature] // compute new features k := o.nOriFeatures for e := 2; e <= o.degree; e++ { for d := 0; d <= e; d++ { x[k] = math.Pow(xi, float64(e-d)) * math.Pow(xj, float64(d)) k++ } } } // GetMapped returns a new Regression data with mapped/augmented X values func (o *PolyDataMapper) GetMapped(XYraw [][]float64, useY bool) (data *Data) { // check nRows := len(XYraw) if nRows < 1 { chk.Panic("need at least 1 data row. nRows = %d is invalid\n", nRows) } nColumns := len(XYraw[0]) if nColumns < 3 { chk.Panic("need at least 3 columns (x0, x1, y). nColumns = %d is invalid\n", nColumns) } if nColumns != o.nOriFeatures+1 { chk.Panic("number of columns does not correspond to number of original features + 1 (y value). %d != %d\n", nColumns, o.nOriFeatures+1) } // set data nSamples := nRows nFeatures := o.NumOriginalFeatures() + o.NumExtraFeatures() data = NewData(nSamples, nFeatures, useY, true) x := la.NewVector(nFeatures) for i := 0; i < nSamples; i++ { o.Map(x, XYraw[i]) for j := 0; j < nFeatures; j++ { data.X.Set(i, j, x[j]) } if useY { data.Y[i] = XYraw[i][o.nOriFeatures] // last column of XYraw } } return }
ml/polydatamapper.go
0.621426
0.459197
polydatamapper.go
starcoder
package set_intersection_size_at_least_two import ( "container/list" "sort" ) /* 757. 设置交集大小至少为2 https://leetcode-cn.com/problems/set-intersection-size-at-least-two 一个整数区间 [a, b] ( a < b ) 代表着从 a 到 b 的所有连续整数,包括 a 和 b。 给你一组整数区间intervals,请找到一个最小的集合 S, 使得 S 里的元素与区间intervals中的每一个整数区间都至少有2个元素相交。 输出这个最小集合S的大小。 示例 1: 输入: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]] 输出: 3 解释: 考虑集合 S = {2, 3, 4}. S与intervals中的四个区间都有至少2个相交的元素。 且这是S最小的情况,故我们输出3。 示例 2: 输入: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]] 输出: 5 解释: 最小的集合S = {1, 2, 3, 4, 5}. 注意: intervals 的长度范围为[1, 3000]。 intervals[i] 长度为 2,分别代表左、右边界。 intervals[i][j] 的值是 [0, 10^8]范围内的整数。 */ /* 贪心策略: 先将所有区间按照起点降序排序,如果起点相同则终点升序排列——或者反过来,起点升序,起点相同时终点降序 这样排序的好处是在遍历的过程中只需要关注集合中最小的两个数字 遍历时根据当前区间[start, end]和交集中两个最小数字min1, min2的关系,分情况讨论: 1)、min1、min2都不在区间内, 集合中应该加入start和start+1两个数字,同时更新min1、min2为这两个数字 2)、min1、min2都在区间内,不需更新 3)、只有min1在区间内, 如果min1==start, 集合加入start+1,同时min2更新为start+1 否则,min2更新为min1, min1更新为start, 集合加入start 时间复杂度O(n*lgn + n) = O(nlgn), 主要为排序的复杂度,排序后只是一次遍历 空间复杂度为set集合的复杂度,set元素不会超过 2*n, 所以空间复杂度为O(n) */ func intersectionSizeTwo(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { if intervals[i][0] == intervals[j][0] { return intervals[i][1] < intervals[j][1] } return intervals[i][0] > intervals[j][0] }) return help(intervals) } func help(intervals [][]int) int { min1, min2 := -1, -1 set := list.New() // 用map或slice也行 for _, v := range intervals { switch { case !isInRange(min1, v) && !isInRange(min2, v): set.PushBack(v[0]) set.PushBack(v[1]) min1, min2 = v[0], v[0]+1 case isInRange(min1, v) && !isInRange(min2, v): if v[0] == min1 { set.PushBack(v[0] + 1) min2 = min1 + 1 } else { set.PushBack(v[0]) min1, min2 = v[0], min1 } } } return set.Len() } // 这个题目求最终集合元素的个数,可以用一个int变量统计,不必开辟一个真正的集合去装元素,空间复杂度降为O(1) func help1(intervals [][]int) int { min1, min2 := -1, -1 result := 0 for _, v := range intervals { switch { case !isInRange(min1, v) && !isInRange(min2, v): result += 2 // 集合中加入 v[0]和v[0]+1 min1, min2 = v[0], v[0]+1 case isInRange(min1, v) && !isInRange(min2, v): result++ if v[0] == min1 { // 集合中加入v[0]+1 min2 = min1 + 1 } else { // 集合中加入v[0] min1, min2 = v[0], min1 } } } return result } func isInRange(m int, interval []int) bool { return interval[0] <= m && m <= interval[1] }
solutions/set-intersection-size-at-least-two/d.go
0.569613
0.468243
d.go
starcoder
package atlas import ( "math" "github.com/go-gl/gl/v4.5-core/gl" "github.com/wdevore/ranger/rendering" "github.com/wdevore/ranger/rmath" ) // BasicAtlas is an Atlas of basic vector shapes, for example, Square or Circle. type BasicAtlas struct { Atlas } // NewBasicAtlas creates a basic atlas. func NewBasicAtlas() *BasicAtlas { ba := new(BasicAtlas) ba.initialize() return ba } // Popupate loads atlas with a starter set of basic shapes func (ba *BasicAtlas) Popupate() { uAtlas := ba.vo.UniAtlas ba.AddShape(buildSquare(uAtlas)) ba.AddShape(buildCenteredSquare(uAtlas)) ba.AddShape(buildCenteredTriangle(uAtlas)) } func buildSquare(uAtlas *rendering.VectorUniformAtlas) *rendering.VectorShape { s := rendering.NewVectorShape() s.Name = "Square" s.PrimitiveMode = gl.TRIANGLES s.SetOffset(uAtlas.Begin()) // These vertices are specified in unit local-space v0 := uAtlas.AddVertex(0.0, 0.0, 0.0) v1 := uAtlas.AddVertex(0.0, 1.0, 0.0) v2 := uAtlas.AddVertex(1.0, 1.0, 0.0) v3 := uAtlas.AddVertex(1.0, 0.0, 0.0) uAtlas.AddIndex(v0) uAtlas.AddIndex(v1) uAtlas.AddIndex(v3) uAtlas.AddIndex(v1) uAtlas.AddIndex(v2) uAtlas.AddIndex(v3) s.Count = int32(uAtlas.End()) return s } func buildCenteredSquare(uAtlas *rendering.VectorUniformAtlas) *rendering.VectorShape { s := rendering.NewVectorShape() s.Name = "CenteredSquare" s.PrimitiveMode = gl.TRIANGLES s.SetOffset(uAtlas.Begin()) const l float32 = 0.5 // side length // These vertices are specified in unit local-space v0 := uAtlas.AddVertex(l, l, 0.0) v1 := uAtlas.AddVertex(l, -l, 0.0) v2 := uAtlas.AddVertex(-l, -l, 0.0) v3 := uAtlas.AddVertex(-l, l, 0.0) uAtlas.AddIndex(v0) uAtlas.AddIndex(v3) uAtlas.AddIndex(v1) uAtlas.AddIndex(v1) uAtlas.AddIndex(v3) uAtlas.AddIndex(v2) s.Count = int32(uAtlas.End()) return s } func buildCenteredTriangle(uAtlas *rendering.VectorUniformAtlas) *rendering.VectorShape { s := rendering.NewVectorShape() s.Name = "CenteredTriangle" s.PrimitiveMode = gl.TRIANGLES s.SetOffset(uAtlas.Begin()) const l float32 = 0.25 // side length // 30 degrees yields triangle sides of equal length but the bbox is // rectangular not square. // 0 degrees yields a square bbox with unequal triangle sides. h := float32(0.5 * math.Cos(float64(rmath.ToRadians(30.0)))) // These vertices are specified in unit local-space v0 := uAtlas.AddVertex(-l, -h, 0.0) v1 := uAtlas.AddVertex(l, -h, 0.0) v2 := uAtlas.AddVertex(0.0, h, 0.0) uAtlas.AddIndex(v0) uAtlas.AddIndex(v1) uAtlas.AddIndex(v2) s.Count = int32(uAtlas.End()) return s }
ranger/rendering/atlas/basic_atlas.go
0.845624
0.560072
basic_atlas.go
starcoder
package compress // DeltaStats is a histogram containing delta values which can be used // to compute various statistics of the delta distribution. type DeltaStats struct { hist, cSum []int nMin, nMax int64 } // Load loads an array into the DeltaStas array. It must be called // before other methods are called. func (stats *DeltaStats) Load(delta []int64) { if len(delta) == 0 { stats.nMin, stats.nMax = 0, 0 stats.hist, stats.cSum = stats.hist[:0], stats.cSum[:0] return } stats.nMin, stats.nMax = delta[0], delta[0] // Find how long the histogram is. for i := range delta { if delta[i] < stats.nMin { stats.nMin = delta[i] } else if delta[i] > stats.nMax { stats.nMax = delta[i] } } n := stats.nMax - stats.nMin + 1 stats.hist = expandInts(stats.hist, int(n)) stats.cSum = expandInts(stats.cSum, int(n)) // Clear histogram for i := range stats.hist { stats.hist[i] = 0 } // Update histogram for i := range delta { stats.hist[delta[i] - stats.nMin]++ } // Update cumulative sum stats.cSum[0] = stats.hist[0] for i := 1; i < len(stats.cSum); i++ { stats.cSum[i] = stats.cSum[i-1] + stats.hist[i] } } // expandInts expands x to have length n, making the minimum number of // heap allocations. func expandInts(x []int, n int) []int { if x == nil { return make([]int, n) } if cap(x) >= n { x = x[:n] } else { x = x[:cap(x)] x = append(x, make([]int, n - cap(x))...) } return x } // Mean returns the mean of the histogram. func (stats *DeltaStats) Mean() int64 { sum := int64(0) n := int64(0) for i := range stats.hist { sum += int64(stats.hist[i]*(i + int(stats.nMin))) n += int64(stats.hist[i]) } return sum / n } // Mode returns the mode of the histogram. func (stats *DeltaStats) Mode() int64 { maxI := 0 for i := range stats.hist { if stats.hist[i] > stats.hist[maxI] { maxI = i } } return int64(maxI) + stats.nMin } // Window returns the center of "window" of the given size which contains // the maximum number of values. func (stats *DeltaStats) Window(size int) int64 { if size >= len(stats.hist) { return int64(len(stats.hist)) / 2 + stats.nMin } max := stats.cSum[size - 1] maxFirst := 0 for first := 1; first + size - 1 < len(stats.hist); first++ { diff := stats.cSum[first + size - 1] - stats.cSum[first - 1] if diff > max { maxFirst = first max = diff } } return (2*(stats.nMin + int64(maxFirst)) + int64(size)) / 2 } // NeededRotation returns how many values higher the each element in delta // woudl need to shift to make sure that all elements are positive and // that mid % 256 = 127. If mid is chosen approppriately, this latter // condition can allow zlib to compress values more efficeintly. func (stats *DeltaStats) NeededRotation(mid int64) int64 { // This would be the rotation if we didn't care about aligning // mid to the middle of a byte. offset := -int64(stats.nMin) // Rotation needed to align mid to the middle of a byte. Sorry, but the // next couple lines are confusing. var centering int64 midMod := (offset + mid) % 256 if midMod < 0 { midMod += 256 } centering = 127 - midMod if centering < 0 { centering += 256 } return offset + centering } func RotateEncode(delta []int64, rot int64) { for i := range delta { delta[i] += rot } } func RotateDecode(delta []int64, rot int64) { for i := range delta { delta[i] -= rot } }
lib/compress/rotate.go
0.838779
0.703626
rotate.go
starcoder
package cntl // Equals returns whether the two given objects are equal func (v1 *SetList) Equals(v2 *SetList) bool { return v1.ID == v2.ID && v1.Name == v2.Name && songSelectorList(v1.Songs).Equals(songSelectorList(v2.Songs)) } // Equals returns whether the two given objects are equal func (v1 BarChange) Equals(v2 BarChange) bool { return v1.At == v2.At && v1.NoteCount == v2.NoteCount && v1.NoteValue == v2.NoteValue && v1.Speed == v2.Speed } // Equals returns whether the two given objects are equal func (v1 DMXScenePosition) Equals(v2 DMXScenePosition) bool { return v1.At == v2.At && v1.ID == v2.ID && v1.Repeat == v2.Repeat } // Equals returns whether the two given objects are equal func (v1 *Song) Equals(v2 *Song) bool { return v1.ID == v2.ID && v1.Name == v2.Name && barChangeList(v1.BarChanges).Equals(barChangeList(v2.BarChanges)) && scenePositionList(v1.DMXScenes).Equals(scenePositionList(v2.DMXScenes)) } // Equals returns whether the two given objects are equal func (t Tag) Equals(v2 Tag) bool { return t == v2 } // Equals returns whether the two given objects are equal func (v1 *DMXDevice) Equals(v2 *DMXDevice) bool { return v1.ID == v2.ID && v1.Name == v2.Name && v1.TypeID == v2.TypeID && v1.Universe == v2.Universe && v1.StartChannel == v2.StartChannel && tagList(v1.Tags).Equals(tagList(v2.Tags)) } // Equals returns whether the two given objects are equal func (v1 *DMXDeviceType) Equals(v2 *DMXDeviceType) bool { return v1.ID == v2.ID && v1.Name == v2.Name && v1.ChannelCount == v2.ChannelCount && v1.ChannelsPerLED == v2.ChannelsPerLED && v1.StrobeEnabled == v2.StrobeEnabled && v1.StrobeChannel == v2.StrobeChannel && v1.DimmerEnabled == v2.DimmerEnabled && v1.DimmerChannel == v2.DimmerChannel && v1.ModeEnabled == v2.ModeEnabled && v1.ModeChannel == v2.ModeChannel && ledList(v1.LEDs).Equals(ledList(v2.LEDs)) } // Equals returns whether the two given objects are equal func (v1 LED) Equals(v2 LED) bool { return v1.Red == v2.Red && v1.Green == v2.Green && v1.Blue == v2.Blue && v1.White == v2.White } // Equals returns whether the two given objects are equal func (v1 DMXDeviceSelector) Equals(v2 DMXDeviceSelector) bool { return v1.ID == v2.ID && tagList(v1.Tags).Equals(tagList(v2.Tags)) } // Equals returns whether the two given objects are equal func (v1 *DMXDeviceGroup) Equals(v2 *DMXDeviceGroup) bool { return v1.ID == v2.ID && v1.Name == v2.Name && dmxDeviceSelectorList(v1.Devices).Equals(dmxDeviceSelectorList(v2.Devices)) } // Equals returns whether the two given objects are equal func (v1 DMXDeviceParams) Equals(v2 DMXDeviceParams) bool { if v1.Group == nil && v2.Group != nil || v1.Group != nil && v2.Group == nil { return false } if v1.Device == nil && v2.Device != nil || v1.Device != nil && v2.Device == nil { return false } if v1.Params == nil && v2.Params != nil || v1.Params != nil && v2.Params == nil { return false } return dmxParamsList(v1.Params).Equals(dmxParamsList(v2.Params)) } // Equals returns whether the two given objects are equal func (v1 DMXScene) Equals(v2 DMXScene) bool { return v1.ID == v2.ID && v1.Name == v2.Name && v1.NoteValue == v2.NoteValue && v1.NoteCount == v2.NoteCount && dmxSubSceneList(v1.SubScenes).Equals(dmxSubSceneList(v2.SubScenes)) } // Equals returns whether the two given objects are equal func (v1 DMXSubScene) Equals(v2 DMXSubScene) bool { return atList(v1.At).Equals(atList(v2.At)) && v1.Preset == v2.Preset && dmxDeviceParamsList(v1.DeviceParams).Equals(dmxDeviceParamsList(v2.DeviceParams)) } // Equals returns whether the two given objects are equal func (v1 DMXParams) Equals(v2 DMXParams) bool { return v1.LED == v2.LED && (v1.Mode == nil && v2.Mode == nil || v1.Mode != nil && v2.Mode != nil && v1.Mode.Equals(v2.Mode)) && (v1.Strobe == nil && v2.Strobe == nil || v1.Strobe != nil && v2.Strobe != nil && v1.Strobe.Equals(v2.Strobe)) && (v1.White == nil && v2.White == nil || v1.White != nil && v2.White != nil && v1.White.Equals(v2.White)) && (v1.Red == nil && v2.Red == nil || v1.Red != nil && v2.Red != nil && v1.Red.Equals(v2.Red)) && (v1.Green == nil && v2.Green == nil || v1.Green != nil && v2.Green != nil && v1.Green.Equals(v2.Green)) && (v1.Blue == nil && v2.Blue == nil || v1.Blue != nil && v2.Blue != nil && v1.Blue.Equals(v2.Blue)) } // Equals returns whether the two given objects are equal func (v1 DMXAnimation) Equals(v2 DMXAnimation) bool { return v1.ID == v2.ID && dmxAnimationFrameList(v1.Frames).Equals(dmxAnimationFrameList(v2.Frames)) } // Equals returns whether the two given objects are equal func (v1 DMXAnimationFrame) Equals(v2 DMXAnimationFrame) bool { return v1.At == v2.At && v1.Params.Equals(v2.Params) } // Equals returns whether the two given objects are equal func (v1 DMXPreset) Equals(v2 DMXPreset) bool { return v1.ID == v2.ID && v1.Name == v2.Name && dmxDeviceParamsList(v1.DeviceParams).Equals(dmxDeviceParamsList(v2.DeviceParams)) } // Contains returns whether given DMXCommand is in the called collection func (cmds DMXCommands) Contains(c DMXCommand) bool { for _, cmd := range cmds { if cmd.Equals(c) { return true } } return false } // ContainsChannel returns whether given DMXCommand's channel and universe is in the called collection func (cmds DMXCommands) ContainsChannel(c DMXCommand) bool { for _, cmd := range cmds { if cmd.EqualsChannel(c) { return true } } return false } // Equals returns true when both the called and the given one have the same entries without caring for order func (cmds DMXCommands) Equals(c DMXCommands) bool { if len(cmds) != len(c) { return false } for _, cmd := range cmds { if !c.Contains(cmd) { return false } } return true } // Equals returns true if given DMXCommand is equal to the called one func (cmd DMXCommand) Equals(c DMXCommand) bool { return cmd.EqualsChannel(c) && cmd.Value == c.Value } // EqualsChannel returns true if given DMXCommand is equal to the called one in terms of channel and universe func (cmd DMXCommand) EqualsChannel(c DMXCommand) bool { return cmd.Channel == c.Channel && cmd.Universe == c.Universe }
pkg/cntl/types_equals.go
0.88382
0.545467
types_equals.go
starcoder
package common import ( "engo.io/engo" "engo.io/engo/math" "engo.io/gl" ) const ( orth = "orthogonal" iso = "isometric" ) // Level is a parsed TMX level containing all layers and default Tiled attributes type Level struct { // Orientation is the parsed level orientation from the TMX XML, like orthogonal, isometric, etc. Orientation string // RenderOrder is the in Tiled specified TileMap render order, like right-down, right-up, etc. RenderOrder string width int height int // TileWidth defines the width of each tile in the level TileWidth int // TileHeight defines the height of each tile in the level TileHeight int // NextObjectId is the next free Object ID defined by Tiled NextObjectID int // TileLayers contains all TileLayer of the level TileLayers []*TileLayer // ImageLayers contains all ImageLayer of the level ImageLayers []*ImageLayer // ObjectLayers contains all ObjectLayer of the level ObjectLayers []*ObjectLayer // Properties are custom properties of the level Properties []Property resourceMap map[uint32]Texture pointMap map[mapPoint]*Tile } // Property is any custom property. The Type corresponds to the type (int, // float, etc) stored in the Value as a string type Property struct { Name, Type, Value string } // TileLayer contains a list of its tiles plus all default Tiled attributes type TileLayer struct { // Name defines the name of the tile layer given in the TMX XML / Tiled Name string // Width is the integer width of each tile in this layer Width int // Height is the integer height of each tile in this layer Height int // Tiles contains the list of tiles Tiles []*Tile // Opacity is the opacity of the layer from [0,1] Opacity float32 // Visible is if the layer is visible Visible bool // X is the x position of the tile layer X float32 // Y is the y position of the tile layer Y float32 // XOffset is the x-offset of the tile layer OffSetX float32 // YOffset is the y-offset of the tile layer OffSetY float32 // Properties are the custom properties of the layer Properties []Property } // ImageLayer contains a list of its images plus all default Tiled attributes type ImageLayer struct { // Name defines the name of the image layer given in the TMX XML / Tiled Name string // Source contains the original image filename Source string // Images contains the list of all image tiles Images []*Tile // Opacity is the opacity of the layer from [0,1] Opacity float32 // Visible is if the layer is visible Visible bool // XOffset is the x-offset of the layer OffSetX float32 // YOffset is the y-offset of the layer OffSetY float32 // Properties are the custom properties of the layer Properties []Property } // ObjectLayer contains a list of its standard objects as well as a list of all its polyline objects type ObjectLayer struct { // Name defines the name of the object layer given in the TMX XML / Tiled Name string // Color is the color of the object Color string // OffSetX is the parsed X offset for the object layer OffSetX float32 // OffSetY is the parsed Y offset for the object layer OffSetY float32 // Opacity is the opacity of the layer from [0,1] Opacity float32 // Visible is if the layer is visible Visible bool // Properties are the custom properties of the layer Properties []Property // Objects contains the list of (regular) Object objects Objects []*Object // DrawOrder is whether the objects are drawn according to the order of // appearance (“index”) or sorted by their y-coordinate (“topdown”). // Defaults to “topdown”. DrawOrder string } // Object is a standard TMX object with all its default Tiled attributes type Object struct { // ID is the unique ID of each object defined by Tiled ID uint32 // Name defines the name of the object given in Tiled Name string // Type contains the string type which was given in Tiled Type string // X holds the X float64 coordinate of the object in the map X float32 // X holds the X float64 coordinate of the object in the map Y float32 // Width is the width of the object in pixels Width float32 // Height is the height of the object in pixels Height float32 // Properties are the custom properties of the object Properties []Property // Tiles are the tiles, if any, associated with the object Tiles []*Tile // Lines are the lines, if any, associated with the object Lines []TMXLine // Ellipses are the ellipses, if any, associated with the object Ellipses []TMXCircle // Text is the text, if any, associated with the object Text []TMXText } // TMXCircle is a circle from the tmx map // TODO: create a tile instead using the Shape (maybe a render component?) type TMXCircle struct { X, Y, Width, Height float32 } // TMXLine is a line from the tmx map // TODO: create a tile or render coponent instead? type TMXLine struct { Lines []*engo.Line Type string } // TMXText is text associated with a Tiled Map. It should contain all the // information needed to render text. // TODO: create a tile instead and have the text rendered as a texture type TMXText struct { Bold bool Color string FontFamily string Halign string Italic bool Kerning bool Size float32 Strikeout bool Underline bool Valign string WordWrap bool CharData string } // Bounds returns the level boundaries as an engo.AABB object func (l *Level) Bounds() engo.AABB { switch l.Orientation { case orth: return engo.AABB{ Min: l.screenPoint(engo.Point{X: 0, Y: 0}), Max: l.screenPoint(engo.Point{X: float32(l.width), Y: float32(l.height)}), } case iso: xMin := l.screenPoint(engo.Point{X: 0, Y: float32(l.height)}).X + float32(l.TileWidth)/2 xMax := l.screenPoint(engo.Point{X: float32(l.width), Y: 0}).X + float32(l.TileWidth)/2 yMin := l.screenPoint(engo.Point{X: 0, Y: 0}).Y yMax := l.screenPoint(engo.Point{X: float32(l.width), Y: float32(l.height)}).Y + float32(l.TileHeight)/2 return engo.AABB{ Min: engo.Point{X: xMin, Y: yMin}, Max: engo.Point{X: xMax, Y: yMax}, } } return engo.AABB{} } // mapPoint returns the map point of the passed in screen point func (l *Level) mapPoint(screenPt engo.Point) engo.Point { switch l.Orientation { case orth: screenPt.Multiply(engo.Point{X: 1 / float32(l.TileWidth), Y: 1 / float32(l.TileHeight)}) return screenPt case iso: return engo.Point{ X: (screenPt.X / float32(l.TileWidth)) + (screenPt.Y / float32(l.TileHeight)), Y: (screenPt.Y / float32(l.TileHeight)) - (screenPt.X / float32(l.TileWidth)), } } return engo.Point{X: 0, Y: 0} } // screenPoint returns the screen point of the passed in map point func (l *Level) screenPoint(mapPt engo.Point) engo.Point { switch l.Orientation { case orth: mapPt.Multiply(engo.Point{X: float32(l.TileWidth), Y: float32(l.TileHeight)}) return mapPt case iso: return engo.Point{ X: (mapPt.X - mapPt.Y) * float32(l.TileWidth) / 2, Y: (mapPt.X + mapPt.Y) * float32(l.TileHeight) / 2, } } return engo.Point{X: 0, Y: 0} } type mapPoint struct { X, Y int } // GetTile returns a *Tile at the given point (in space / render coordinates). func (l *Level) GetTile(pt engo.Point) *Tile { mp := l.mapPoint(pt) x := int(math.Floor(mp.X)) y := int(math.Floor(mp.Y)) t, ok := l.pointMap[mapPoint{X: x, Y: y}] if !ok { return nil } return t } // Width returns the integer width of the level func (l *Level) Width() int { return l.width } // Height returns the integer height of the level func (l *Level) Height() int { return l.height } // Height returns the integer height of the tile func (t *Tile) Height() float32 { return t.Image.Height() } // Width returns the integer width of the tile func (t *Tile) Width() float32 { return t.Image.Width() } // Texture returns the tile's Image texture func (t *Tile) Texture() *gl.Texture { return t.Image.id } // Close deletes the stored texture of a tile func (t *Tile) Close() { t.Image.Close() } // View returns the tile's viewport's min and max X & Y func (t *Tile) View() (float32, float32, float32, float32) { return t.Image.View() } // Tile represents a tile in the TMX map. type Tile struct { engo.Point Image *Texture }
common/level.go
0.523664
0.563438
level.go
starcoder
package block import "fmt" // Colour represents the colour of a block. Typically, Minecraft blocks have a total of 16 different colours. type Colour struct { colour } // ColourWhite returns the white colour. func ColourWhite() Colour { return Colour{colour(0)} } // ColourOrange returns the orange colour. func ColourOrange() Colour { return Colour{colour(1)} } // ColourMagenta returns the magenta colour. func ColourMagenta() Colour { return Colour{colour(2)} } // ColourLightBlue returns the light blue colour. func ColourLightBlue() Colour { return Colour{colour(3)} } // ColourYellow returns the yellow colour. func ColourYellow() Colour { return Colour{colour(4)} } // ColourLime returns the lime colour. func ColourLime() Colour { return Colour{colour(5)} } // ColourPink returns the pink colour. func ColourPink() Colour { return Colour{colour(6)} } // ColourGrey returns the grey colour. func ColourGrey() Colour { return Colour{colour(7)} } // ColourLightGrey returns the light grey colour. func ColourLightGrey() Colour { return Colour{colour(8)} } // ColourCyan returns the cyan colour. func ColourCyan() Colour { return Colour{colour(9)} } // ColourPurple returns the purple colour. func ColourPurple() Colour { return Colour{colour(10)} } // ColourBlue returns the blue colour. func ColourBlue() Colour { return Colour{colour(11)} } // ColourBrown returns the brown colour. func ColourBrown() Colour { return Colour{colour(12)} } // ColourGreen returns the green colour. func ColourGreen() Colour { return Colour{colour(13)} } // ColourRed returns the red colour. func ColourRed() Colour { return Colour{colour(14)} } // ColourBlack returns the black colour. func ColourBlack() Colour { return Colour{colour(15)} } // Colours returns a list of all existing colours. func Colours() []Colour { return []Colour{ ColourWhite(), ColourOrange(), ColourMagenta(), ColourLightBlue(), ColourYellow(), ColourLime(), ColourPink(), ColourGrey(), ColourLightGrey(), ColourCyan(), ColourPurple(), ColourBlue(), ColourBrown(), ColourGreen(), ColourRed(), ColourBlack(), } } type colour uint8 // String ... func (c colour) String() string { switch c { default: return "white" case 1: return "orange" case 2: return "magenta" case 3: return "light_blue" case 4: return "yellow" case 5: return "lime" case 6: return "pink" case 7: return "gray" case 8: return "silver" case 9: return "cyan" case 10: return "purple" case 11: return "blue" case 12: return "brown" case 13: return "green" case 14: return "red" case 15: return "black" } } // FromString ... func (c colour) FromString(s string) (interface{}, error) { switch s { case "white": return Colour{colour(0)}, nil case "orange": return Colour{colour(1)}, nil case "magenta": return Colour{colour(2)}, nil case "light_blue": return Colour{colour(3)}, nil case "yellow": return Colour{colour(4)}, nil case "lime", "light_green": return Colour{colour(5)}, nil case "pink": return Colour{colour(6)}, nil case "grey", "gray": return Colour{colour(7)}, nil case "light_grey", "light_gray", "silver": return Colour{colour(8)}, nil case "cyan": return Colour{colour(9)}, nil case "purple": return Colour{colour(10)}, nil case "blue": return Colour{colour(11)}, nil case "brown": return Colour{colour(12)}, nil case "green": return Colour{colour(13)}, nil case "red": return Colour{colour(14)}, nil case "black": return Colour{colour(15)}, nil } return nil, fmt.Errorf("unexpected colour '%v'", s) } // Uint8 ... func (c colour) Uint8() uint8 { return uint8(c) }
server/block/colour.go
0.890282
0.69383
colour.go
starcoder
package chart import ( "fmt" "time" ) // MarketHoursRange is a special type of range that compresses a time range into just the // market (i.e. NYSE operating hours and days) range. type MarketHoursRange struct { Min time.Time Max time.Time MarketOpen time.Time MarketClose time.Time HolidayProvider HolidayProvider ValueFormatter ValueFormatter Domain int } // GetTimezone returns the timezone for the market hours range. func (mhr MarketHoursRange) GetTimezone() *time.Location { return mhr.GetMarketOpen().Location() } // IsZero returns if the range is setup or not. func (mhr MarketHoursRange) IsZero() bool { return mhr.Min.IsZero() && mhr.Max.IsZero() } // GetMin returns the min value. func (mhr MarketHoursRange) GetMin() float64 { return Time.ToFloat64(mhr.Min) } // GetMax returns the max value. func (mhr MarketHoursRange) GetMax() float64 { return Time.ToFloat64(mhr.GetEffectiveMax()) } // GetEffectiveMax gets either the close on the max, or the max itself. func (mhr MarketHoursRange) GetEffectiveMax() time.Time { maxClose := Date.On(mhr.MarketClose, mhr.Max) if maxClose.After(mhr.Max) { return maxClose } return mhr.Max } // SetMin sets the min value. func (mhr *MarketHoursRange) SetMin(min float64) { mhr.Min = Time.FromFloat64(min) mhr.Min = mhr.Min.In(mhr.GetTimezone()) } // SetMax sets the max value. func (mhr *MarketHoursRange) SetMax(max float64) { mhr.Max = Time.FromFloat64(max) mhr.Max = mhr.Max.In(mhr.GetTimezone()) } // GetDelta gets the delta. func (mhr MarketHoursRange) GetDelta() float64 { min := mhr.GetMin() max := mhr.GetMax() return max - min } // GetDomain gets the domain. func (mhr MarketHoursRange) GetDomain() int { return mhr.Domain } // SetDomain sets the domain. func (mhr *MarketHoursRange) SetDomain(domain int) { mhr.Domain = domain } // GetHolidayProvider coalesces a userprovided holiday provider and the date.DefaultHolidayProvider. func (mhr MarketHoursRange) GetHolidayProvider() HolidayProvider { if mhr.HolidayProvider == nil { return defaultHolidayProvider } return mhr.HolidayProvider } // GetMarketOpen returns the market open time. func (mhr MarketHoursRange) GetMarketOpen() time.Time { if mhr.MarketOpen.IsZero() { return NYSEOpen } return mhr.MarketOpen } // GetMarketClose returns the market close time. func (mhr MarketHoursRange) GetMarketClose() time.Time { if mhr.MarketClose.IsZero() { return NYSEClose } return mhr.MarketClose } // GetTicks returns the ticks for the range. // This is to override the default continous ticks that would be generated for the range. func (mhr *MarketHoursRange) GetTicks(r Renderer, defaults Style, vf ValueFormatter) []Tick { times := Sequence.MarketHours(mhr.Min, mhr.Max, mhr.GetMarketOpen(), mhr.GetMarketClose(), mhr.GetHolidayProvider()) timesWidth := mhr.measureTimes(r, defaults, vf, times) if timesWidth <= mhr.Domain { return mhr.makeTicks(vf, times) } times = Sequence.MarketHourQuarters(mhr.Min, mhr.Max, mhr.GetMarketOpen(), mhr.GetMarketClose(), mhr.GetHolidayProvider()) timesWidth = mhr.measureTimes(r, defaults, vf, times) if timesWidth <= mhr.Domain { return mhr.makeTicks(vf, times) } times = Sequence.MarketDayCloses(mhr.Min, mhr.Max, mhr.GetMarketOpen(), mhr.GetMarketClose(), mhr.GetHolidayProvider()) timesWidth = mhr.measureTimes(r, defaults, vf, times) if timesWidth <= mhr.Domain { return mhr.makeTicks(vf, times) } times = Sequence.MarketDayAlternateCloses(mhr.Min, mhr.Max, mhr.GetMarketOpen(), mhr.GetMarketClose(), mhr.GetHolidayProvider()) timesWidth = mhr.measureTimes(r, defaults, vf, times) if timesWidth <= mhr.Domain { return mhr.makeTicks(vf, times) } times = Sequence.MarketDayMondayCloses(mhr.Min, mhr.Max, mhr.GetMarketOpen(), mhr.GetMarketClose(), mhr.GetHolidayProvider()) timesWidth = mhr.measureTimes(r, defaults, vf, times) if timesWidth <= mhr.Domain { return mhr.makeTicks(vf, times) } return GenerateContinuousTicks(r, mhr, false, defaults, vf) } func (mhr *MarketHoursRange) measureTimes(r Renderer, defaults Style, vf ValueFormatter, times []time.Time) int { defaults.GetTextOptions().WriteToRenderer(r) var total int for index, t := range times { timeLabel := vf(t) labelBox := r.MeasureText(timeLabel) total += labelBox.Width() if index > 0 { total += DefaultMinimumTickHorizontalSpacing } } return total } func (mhr *MarketHoursRange) makeTicks(vf ValueFormatter, times []time.Time) []Tick { ticks := make([]Tick, len(times)) for index, t := range times { ticks[index] = Tick{ Value: Time.ToFloat64(t), Label: vf(t), } } return ticks } func (mhr MarketHoursRange) String() string { return fmt.Sprintf("MarketHoursRange [%s, %s] => %d", mhr.Min.Format(time.RFC3339), mhr.Max.Format(time.RFC3339), mhr.Domain) } // Translate maps a given value into the ContinuousRange space. func (mhr MarketHoursRange) Translate(value float64) int { valueTime := Time.FromFloat64(value) valueTimeEastern := valueTime.In(Date.Eastern()) totalSeconds := Date.CalculateMarketSecondsBetween(mhr.Min, mhr.GetEffectiveMax(), mhr.GetMarketOpen(), mhr.GetMarketClose(), mhr.HolidayProvider) valueDelta := Date.CalculateMarketSecondsBetween(mhr.Min, valueTimeEastern, mhr.GetMarketOpen(), mhr.GetMarketClose(), mhr.HolidayProvider) translated := int((float64(valueDelta) / float64(totalSeconds)) * float64(mhr.Domain)) return translated }
vendor/github.com/nicholasjackson/bench/vendor/github.com/wcharczuk/go-chart/market_hours_range.go
0.801237
0.487063
market_hours_range.go
starcoder
package blockchain import ( "fmt" "github.com/essentiaone/divid/txscript" "github.com/essentiaone/divid/wire" "github.com/essentiaone/btcutil" ) const ( // MaxBlockWeight defines the maximum block weight, where "block // weight" is interpreted as defined in BIP0141. A block's weight is // calculated as the sum of the of bytes in the existing transactions // and header, plus the weight of each byte within a transaction. The // weight of a "base" byte is 4, while the weight of a witness byte is // 1. As a result, for a block to be valid, the BlockWeight MUST be // less than, or equal to MaxBlockWeight. MaxBlockWeight = 4000000 // MaxBlockBaseSize is the maximum number of bytes within a block // which can be allocated to non-witness data. MaxBlockBaseSize = 1000000 // MaxBlockSigOpsCost is the maximum number of signature operations // allowed for a block. It is calculated via a weighted algorithm which // weights segregated witness sig ops lower than regular sig ops. MaxBlockSigOpsCost = 80000 // WitnessScaleFactor determines the level of "discount" witness data // receives compared to "base" data. A scale factor of 4, denotes that // witness data is 1/4 as cheap as regular non-witness data. WitnessScaleFactor = 4 // MinTxOutputWeight is the minimum possible weight for a transaction // output. MinTxOutputWeight = WitnessScaleFactor * wire.MinTxOutPayload // MaxOutputsPerBlock is the maximum number of transaction outputs there // can be in a block of max weight size. MaxOutputsPerBlock = MaxBlockWeight / MinTxOutputWeight ) // GetBlockWeight computes the value of the weight metric for a given block. // Currently the weight metric is simply the sum of the block's serialized size // without any witness data scaled proportionally by the WitnessScaleFactor, // and the block's serialized size including any witness data. func GetBlockWeight(blk *btcutil.Block) int64 { msgBlock := blk.MsgBlock() baseSize := msgBlock.SerializeSizeStripped() totalSize := msgBlock.SerializeSize() // (baseSize * 3) + totalSize return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize) } // GetTransactionWeight computes the value of the weight metric for a given // transaction. Currently the weight metric is simply the sum of the // transactions's serialized size without any witness data scaled // proportionally by the WitnessScaleFactor, and the transaction's serialized // size including any witness data. func GetTransactionWeight(tx *btcutil.Tx) int64 { msgTx := tx.MsgTx() baseSize := msgTx.SerializeSizeStripped() totalSize := msgTx.SerializeSize() // (baseSize * 3) + totalSize return int64((baseSize * (WitnessScaleFactor - 1)) + totalSize) } // GetSigOpCost returns the unified sig op cost for the passed transaction // respecting current active soft-forks which modified sig op cost counting. // The unified sig op cost for a transaction is computed as the sum of: the // legacy sig op count scaled according to the WitnessScaleFactor, the sig op // count for all p2sh inputs scaled by the WitnessScaleFactor, and finally the // unscaled sig op count for any inputs spending witness programs. func GetSigOpCost(tx *btcutil.Tx, isCoinBaseTx bool, utxoView *UtxoViewpoint, bip16, segWit bool) (int, error) { numSigOps := CountSigOps(tx) * WitnessScaleFactor if bip16 { numP2SHSigOps, err := CountP2SHSigOps(tx, isCoinBaseTx, utxoView) if err != nil { return 0, nil } numSigOps += (numP2SHSigOps * WitnessScaleFactor) } if segWit && !isCoinBaseTx { msgTx := tx.MsgTx() for txInIndex, txIn := range msgTx.TxIn { // Ensure the referenced output is available and hasn't // already been spent. utxo := utxoView.LookupEntry(txIn.PreviousOutPoint) if utxo == nil || utxo.IsSpent() { str := fmt.Sprintf("output %v referenced from "+ "transaction %s:%d either does not "+ "exist or has already been spent", txIn.PreviousOutPoint, tx.Hash(), txInIndex) return 0, ruleError(ErrMissingTxOut, str) } witness := txIn.Witness sigScript := txIn.SignatureScript pkScript := utxo.PkScript() numSigOps += txscript.GetWitnessSigOpCount(sigScript, pkScript, witness) } } return numSigOps, nil }
blockchain/weight.go
0.832883
0.460289
weight.go
starcoder
package main import ( "math" ) const ( avgWindSpeed = iota minWindSpeed maxWindSpeed temperature gas relativeHumidity pressure ) func eliminateOutliers(weather []Weather) []Weather { means := computeMeans(weather) stdDevs := computeStdDevs(weather, means) weather1 := make([]Weather, 0) for _, w := range weather { if !isOutlier(means[avgWindSpeed], stdDevs[avgWindSpeed], w.AvgWindSpeed) && !isOutlier(means[minWindSpeed], stdDevs[avgWindSpeed], w.MinWindSpeed) && !isOutlier(means[maxWindSpeed], stdDevs[maxWindSpeed], w.MaxWindSpeed) && !isOutlier(means[temperature], stdDevs[temperature], w.Temperature) && !isOutlier(means[gas], stdDevs[gas], w.Gas) && !isOutlier(means[relativeHumidity], stdDevs[relativeHumidity], w.RelativeHumidity) && !isOutlier(means[pressure], stdDevs[pressure], w.Pressure) { weather1 = append(weather1, w) } } return weather1 } func computeMeans(weather []Weather) map[int]float64 { n := float64(len(weather)) means := map[int]float64{ avgWindSpeed: 0, minWindSpeed: 0, maxWindSpeed: 0, temperature: 0, gas: 0, relativeHumidity: 0, pressure: 0, } for _, w := range weather { means[avgWindSpeed] += w.AvgWindSpeed means[minWindSpeed] += w.MinWindSpeed means[maxWindSpeed] += w.MaxWindSpeed means[temperature] += w.Temperature means[gas] += w.Gas means[relativeHumidity] += w.RelativeHumidity means[pressure] += w.Pressure } for k, v := range means { means[k] = v / n } return means } func computeStdDevs(weather []Weather, means map[int]float64) map[int]float64 { n := float64(len(weather)) stdDeviations := map[int]float64{ avgWindSpeed: 0, minWindSpeed: 0, maxWindSpeed: 0, temperature: 0, gas: 0, relativeHumidity: 0, pressure: 0, } for _, w := range weather { stdDeviations[avgWindSpeed] += math.Pow(w.AvgWindSpeed-means[avgWindSpeed], 2) stdDeviations[minWindSpeed] += math.Pow(w.MinWindSpeed-means[minWindSpeed], 2) stdDeviations[maxWindSpeed] += math.Pow(w.MaxWindSpeed-means[maxWindSpeed], 2) stdDeviations[temperature] += math.Pow(w.Temperature-means[temperature], 2) stdDeviations[gas] += math.Pow(w.Gas-means[gas], 2) stdDeviations[relativeHumidity] += math.Pow(w.RelativeHumidity-means[relativeHumidity], 2) stdDeviations[pressure] += math.Pow(w.Pressure-means[pressure], 2) } for k, v := range stdDeviations { stdDeviations[k] = math.Sqrt(v / n) } return stdDeviations } func isOutlier(mean, stdDev, val float64) bool { max := mean + (3 * stdDev) min := mean - (3 * stdDev) return val > max || val < min }
server/stat.go
0.67405
0.484746
stat.go
starcoder
package models import ( i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" ) // FilterOperatorSchema type FilterOperatorSchema struct { Entity // Arity of the operator. Possible values are: Binary, Unary. The default is Binary. arity *ScopeOperatorType // Possible values are: All, Any. Applies only to multivalued attributes. All means that all values must satisfy the condition. Any means that at least one value has to satisfy the condition. The default is All. multivaluedComparisonType *ScopeOperatorMultiValuedComparisonType // Attribute types supported by the operator. Possible values are: Boolean, Binary, Reference, Integer, String. supportedAttributeTypes []AttributeType } // NewFilterOperatorSchema instantiates a new filterOperatorSchema and sets the default values. func NewFilterOperatorSchema()(*FilterOperatorSchema) { m := &FilterOperatorSchema{ Entity: *NewEntity(), } return m } // CreateFilterOperatorSchemaFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateFilterOperatorSchemaFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewFilterOperatorSchema(), nil } // GetArity gets the arity property value. Arity of the operator. Possible values are: Binary, Unary. The default is Binary. func (m *FilterOperatorSchema) GetArity()(*ScopeOperatorType) { if m == nil { return nil } else { return m.arity } } // GetFieldDeserializers the deserialization information for the current model func (m *FilterOperatorSchema) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := m.Entity.GetFieldDeserializers() res["arity"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseScopeOperatorType) if err != nil { return err } if val != nil { m.SetArity(val.(*ScopeOperatorType)) } return nil } res["multivaluedComparisonType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseScopeOperatorMultiValuedComparisonType) if err != nil { return err } if val != nil { m.SetMultivaluedComparisonType(val.(*ScopeOperatorMultiValuedComparisonType)) } return nil } res["supportedAttributeTypes"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfEnumValues(ParseAttributeType) if err != nil { return err } if val != nil { res := make([]AttributeType, len(val)) for i, v := range val { res[i] = *(v.(*AttributeType)) } m.SetSupportedAttributeTypes(res) } return nil } return res } // GetMultivaluedComparisonType gets the multivaluedComparisonType property value. Possible values are: All, Any. Applies only to multivalued attributes. All means that all values must satisfy the condition. Any means that at least one value has to satisfy the condition. The default is All. func (m *FilterOperatorSchema) GetMultivaluedComparisonType()(*ScopeOperatorMultiValuedComparisonType) { if m == nil { return nil } else { return m.multivaluedComparisonType } } // GetSupportedAttributeTypes gets the supportedAttributeTypes property value. Attribute types supported by the operator. Possible values are: Boolean, Binary, Reference, Integer, String. func (m *FilterOperatorSchema) GetSupportedAttributeTypes()([]AttributeType) { if m == nil { return nil } else { return m.supportedAttributeTypes } } // Serialize serializes information the current object func (m *FilterOperatorSchema) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { err := m.Entity.Serialize(writer) if err != nil { return err } if m.GetArity() != nil { cast := (*m.GetArity()).String() err = writer.WriteStringValue("arity", &cast) if err != nil { return err } } if m.GetMultivaluedComparisonType() != nil { cast := (*m.GetMultivaluedComparisonType()).String() err = writer.WriteStringValue("multivaluedComparisonType", &cast) if err != nil { return err } } if m.GetSupportedAttributeTypes() != nil { err = writer.WriteCollectionOfStringValues("supportedAttributeTypes", SerializeAttributeType(m.GetSupportedAttributeTypes())) if err != nil { return err } } return nil } // SetArity sets the arity property value. Arity of the operator. Possible values are: Binary, Unary. The default is Binary. func (m *FilterOperatorSchema) SetArity(value *ScopeOperatorType)() { if m != nil { m.arity = value } } // SetMultivaluedComparisonType sets the multivaluedComparisonType property value. Possible values are: All, Any. Applies only to multivalued attributes. All means that all values must satisfy the condition. Any means that at least one value has to satisfy the condition. The default is All. func (m *FilterOperatorSchema) SetMultivaluedComparisonType(value *ScopeOperatorMultiValuedComparisonType)() { if m != nil { m.multivaluedComparisonType = value } } // SetSupportedAttributeTypes sets the supportedAttributeTypes property value. Attribute types supported by the operator. Possible values are: Boolean, Binary, Reference, Integer, String. func (m *FilterOperatorSchema) SetSupportedAttributeTypes(value []AttributeType)() { if m != nil { m.supportedAttributeTypes = value } }
models/filter_operator_schema.go
0.757346
0.409221
filter_operator_schema.go
starcoder
package svc import ( "math/big" "techpay-api-graphql/internal/types" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" ) // handleFMintDeposit handles a new deposit on fMint contract. // event Deposited(address indexed token, address indexed user, uint256 amount) func handleFMintDeposit(lr *types.LogRecord) { // sanity check for data (1 uint256 = 32 bytes); call + token + user = 3 topics if len(lr.Data) != 32 || len(lr.Topics) != 3 { log.Criticalf("%s invalid event; expected 32 bytes, %d bytes given; expected 3 topics, %d given", lr.TxHash.String(), len(lr.Data), len(lr.Topics)) return } handleNewFMintRecord( lr, types.FMintTrxTypeDeposit, common.BytesToAddress(lr.Topics[2].Bytes()), common.BytesToAddress(lr.Topics[1].Bytes()), new(big.Int).SetBytes(lr.Data), new(big.Int), ) } // handleFMintWithdraw handles a new withdrawal on fMint contract. // event Withdrawn(address indexed token, address indexed user, uint256 amount) func handleFMintWithdraw(lr *types.LogRecord) { // sanity check for data (1 uint256 = 32 bytes); call + token + user = 3 topics if len(lr.Data) != 32 || len(lr.Topics) != 3 { log.Criticalf("%s invalid event; expected 32 bytes, %d bytes given; expected 3 topics, %d given", lr.TxHash.String(), len(lr.Data), len(lr.Topics)) return } handleNewFMintRecord( lr, types.FMintTrxTypeWithdraw, common.BytesToAddress(lr.Topics[2].Bytes()), common.BytesToAddress(lr.Topics[1].Bytes()), new(big.Int).SetBytes(lr.Data), new(big.Int), ) } // handleFMintMint handles a new mint (tokens borrow) on fMint contract. // event Minted(address indexed token, address indexed user, uint256 amount, uint256 fee) func handleFMintMint(lr *types.LogRecord) { // sanity check for data (2 uint256 = 64 bytes); call + token + user = 3 topics if len(lr.Data) != 64 || len(lr.Topics) != 3 { log.Criticalf("%s invalid event; expected 64 bytes, %d bytes given; expected 3 topics, %d given", lr.TxHash.String(), len(lr.Data), len(lr.Topics)) return } handleNewFMintRecord( lr, types.FMintTrxTypeMint, common.BytesToAddress(lr.Topics[2].Bytes()), common.BytesToAddress(lr.Topics[1].Bytes()), new(big.Int).SetBytes(lr.Data[:32]), new(big.Int).SetBytes(lr.Data[32:]), ) } // handleFMintRepay handles a new repay (debt repay) on fMint contract. // event Repaid(address indexed token, address indexed user, uint256 amount) func handleFMintRepay(lr *types.LogRecord) { // sanity check for data (1 uint256 = 32 bytes); call + token + user = 3 topics if len(lr.Data) != 32 || len(lr.Topics) != 3 { log.Criticalf("%s invalid event; expected 32 bytes, %d bytes given; expected 3 topics, %d given", lr.TxHash.String(), len(lr.Data), len(lr.Topics)) return } handleNewFMintRecord( lr, types.FMintTrxTypeRepay, common.BytesToAddress(lr.Topics[2].Bytes()), common.BytesToAddress(lr.Topics[1].Bytes()), new(big.Int).SetBytes(lr.Data), new(big.Int), ) } // handleNewFMintRecord creates an fMint record with the given data // and pushes it into the persistent storage for future reference. func handleNewFMintRecord(lr *types.LogRecord, tp int32, user common.Address, token common.Address, amount *big.Int, fee *big.Int) { err := repo.AddFMintTransaction(&types.FMintTransaction{ UserAddress: user, TokenAddress: token, Type: tp, Amount: (hexutil.Big)(*amount), Fee: (hexutil.Big)(*fee), TrxHash: lr.TxHash, TrxIndex: int64(lr.TxIndex)<<8 ^ int64(lr.Index), TimeStamp: lr.Block.TimeStamp, }) if err != nil { log.Errorf("can not register fMint trx %s; %s", lr.TxHash.String(), err.Error()) } } // handleFMintReward handles a new reward claim on fMint contract. // event RewardPaid(address indexed user, uint256 reward) func handleFMintReward(lr *types.LogRecord) { // sanity check for data (1 uint256 = 32 bytes); call + user = 2 topics if len(lr.Data) != 32 || len(lr.Topics) != 2 { log.Criticalf("%s invalid event; expected 32 bytes, %d bytes given; expected 2 topics, %d given", lr.TxHash.String(), len(lr.Data), len(lr.Topics)) return } }
internal/svc/logs_fmint.go
0.623377
0.452475
logs_fmint.go
starcoder
package _5_binarysearch // 二分查找的实现 func BinarySearch(a []int, v int) int { n := len(a) if n == 0 { return -1 } low := 0 high := n-1 for low <= high { mid := low + ((high - low) >> 1) if a[mid] == v { return mid } else if a[mid] > v { high = mid - 1 } else { low = mid + 1 } } return -1 } // 二分查找的递归实现 func BinarySearchRecursive(a []int, v int) int { n := len(a) if n == 0 { return -1 } return bs(a, v, 0, n-1) } // 递归函数 func bs(a []int, v int, low, high int) int { if low > high { return -1 } mid := low + ((high - low) >> 1) if a[mid] == v { return mid } else if a[mid] > v { return bs(a, v, low, mid-1) } else { return bs(a, v, mid+1, high) } } // 查找第一个等于给定值的元素 func BinarySearchFirst(a []int, v int) int { n := len(a) if n == 0 { return -1 } low := 0 high := n-1 for low <= high { mid := low + ((high - low) >> 1) if a[mid] > v { high = mid - 1 }else if a[mid] < v { low = mid + 1 } else { if mid == 0 || a[mid-1] != v { return mid } else { high = mid - 1 } } } return -1 } // 查找最后一个值等于给定值的元素 func BinarySearchLast(a []int, v int) int { n := len(a) if n == 0 { return -1 } low := 0 high := n-1 for low <= high { mid := low + ((high - low) >> 1) if a[mid] > v { high = mid - 1 } else if a[mid] < v { low = mid + 1 } else { if mid == n-1 || a[mid+1] != v { return mid } else { low = mid + 1 } } } return -1 } // 查找第一个大于等于给定值的元素 func BinarySearchFirstGT(a []int, v int) int { n := len(a) if n == 0 { return -1 } low := 0 high := n-1 for low <= high { mid := low + ((high - low) >> 1) if a[mid] >= v { if mid == 0 || a[mid-1] < v { return mid } else { high = mid - 1 } } else if a[mid] < v { low = mid + 1 } } return -1 } // 查找最后一个小于等于给定值的元素 func BinarySearchLastLT(a []int, v int) int { n := len(a) if n == 0 { return -1 } low := 0 high := n-1 for low <= high { mid := low + ((high - low) >> 1) if a[mid] > v { high = mid - 1 } else if a[mid] <= v { if mid == n-1 || a[mid+1] > v { return mid } low = mid + 1 } } return -1 }
data-structure/15_binarysearch/binarysearch.go
0.5083
0.445349
binarysearch.go
starcoder
package filter import ( "fmt" "github.com/tigrisdata/tigris/value" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) const ( EQ = "$eq" GT = "$gt" ) // ValueMatcher is an interface that has method like Matches. type ValueMatcher interface { // Matches returns true if the receiver has the value object that has the same value as input Matches(input value.Value) bool // Type return the type of the value matcher, syntactic sugar for logging, etc Type() string // GetValue returns the value on which the Matcher is operating GetValue() value.Value } // NewMatcher returns ValueMatcher that is derived from the key func NewMatcher(key string, v value.Value) (ValueMatcher, error) { switch key { case EQ: return &EqualityMatcher{ Value: v, }, nil case GT: return &GreaterThanMatcher{ Value: v, }, nil default: return nil, status.Errorf(codes.InvalidArgument, "unsupported operand '%s'", key) } } // EqualityMatcher implements "$eq" operand. type EqualityMatcher struct { Value value.Value } // NewEqualityMatcher returns EqualityMatcher object func NewEqualityMatcher(v value.Value) *EqualityMatcher { return &EqualityMatcher{ Value: v, } } func (e *EqualityMatcher) GetValue() value.Value { return e.Value } func (e *EqualityMatcher) Matches(input value.Value) bool { res, _ := e.Value.CompareTo(input) return res == 0 } func (e *EqualityMatcher) Type() string { return "$eq" } func (e *EqualityMatcher) String() string { return fmt.Sprintf("{$eq:%v}", e.Value) } // GreaterThanMatcher implements "$gt" operand. type GreaterThanMatcher struct { Value value.Value } func NewGreaterThanMatcher(v value.Value) *GreaterThanMatcher { return &GreaterThanMatcher{ Value: v, } } func (g *GreaterThanMatcher) GetValue() value.Value { return g.Value } func (g *GreaterThanMatcher) Matches(input value.Value) bool { res, _ := g.Value.CompareTo(input) return res > 0 } func (g *GreaterThanMatcher) Type() string { return "$gt" } func (g *GreaterThanMatcher) String() string { return fmt.Sprintf("{$gt:%v}", g.Value) }
query/filter/comparison.go
0.807688
0.45847
comparison.go
starcoder
// Package module provides a test module that can be used in tests. package module import ( "testing" "time" "github.com/stretchrcom/testify/assert" "github.com/soumya92/barista/bar" ) // Time to wait for events that are expected. Overridden in tests. var positiveTimeout = time.Second // Time to wait for events that are not expected. var negativeTimeout = 10 * time.Millisecond // TestModule represents a bar.Module used for testing. type TestModule struct { assert *assert.Assertions started bool outputs chan bar.Output pauses chan bool events chan bar.Event } // New creates a new module with the given testingT that can be used // to assert the behaviour of the bar (or related modules). func New(t assert.TestingT) *TestModule { m := &TestModule{assert: assert.New(t)} m.Reset() return m } // Stream conforms to bar.Module. func (t *TestModule) Stream() <-chan bar.Output { if t.started { panic("already streaming!") } t.started = true return t.outputs } // Click conforms to bar.Clickable. func (t *TestModule) Click(e bar.Event) { t.events <- e } // Pause conforms to bar.Pausable. func (t *TestModule) Pause() { t.pauses <- true } // Resume conforms to bar.Pausable. func (t *TestModule) Resume() { t.pauses <- false } // Output queues output to be sent over the channel on the next read. func (t *TestModule) Output(out bar.Output) { t.outputs <- out } // AssertStarted asserts that the module was started. func (t *TestModule) AssertStarted(message string) { t.assert.True(t.started, message) } // AssertNotStarted asserts that the module was not started. func (t *TestModule) AssertNotStarted(message string) { t.assert.False(t.started, message) } // AssertPaused asserts that the module was paused, // and consumes the pause invocation. func (t *TestModule) AssertPaused(message string) { select { case state := <-t.pauses: t.assert.True(state, message) case <-time.After(positiveTimeout): t.assert.Fail("expected pause", message) } } // AssertResumed asserts that the module was resumed, // and consumes the resume invocation. func (t *TestModule) AssertResumed(message string) { select { case state := <-t.pauses: t.assert.False(state, message) case <-time.After(positiveTimeout): t.assert.Fail("expected resume", message) } } // AssertNoPauseResume asserts that this module had no pause/resume interactions. func (t *TestModule) AssertNoPauseResume(message string) { select { case <-t.pauses: t.assert.Fail("expected no pause/resume", message) case <-time.After(negativeTimeout): } } // AssertClicked asserts that the module was clicked and returns the event. // Calling this multiple times asserts multiple click events. func (t *TestModule) AssertClicked(message string) bar.Event { select { case evt := <-t.events: return evt case <-time.After(positiveTimeout): t.assert.Fail("expected a click event", message) return bar.Event{} } } // AssertNotClicked asserts that the module received no events. func (t *TestModule) AssertNotClicked(message string) { select { case <-t.events: t.assert.Fail("expected no click event", message) case <-time.After(negativeTimeout): } } // Reset clears the history of pause/resume/click/stream invocations, // flushes any buffered events and resets the output channel. func (t *TestModule) Reset() { if t.outputs != nil { close(t.outputs) close(t.events) close(t.pauses) } t.outputs = make(chan bar.Output, 100) t.events = make(chan bar.Event, 100) t.pauses = make(chan bool, 100) t.started = false } // OutputTester groups an output channel and testing.T to simplify // testing of a bar module. type OutputTester struct { *testing.T outs <-chan bar.Output } // NewOutputTester creates a started outputTester from the given Module and testing.T. func NewOutputTester(t *testing.T, m bar.Module) *OutputTester { return &OutputTester{t, m.Stream()} } // AssertNoOutput asserts that no updates occur on the output channel. func (o *OutputTester) AssertNoOutput(message string) { select { case <-o.outs: assert.Fail(o, "expected no update", message) case <-time.After(negativeTimeout): } } // AssertOutput asserts that the output channel was updated and returns the output. func (o *OutputTester) AssertOutput(message string) bar.Output { select { case out := <-o.outs: return out case <-time.After(positiveTimeout): assert.Fail(o, "expected an update", message) return bar.Output{} } } // AssertEmpty asserts that the output channel was updated with empty output. func (o *OutputTester) AssertEmpty(message string) { out := o.AssertOutput(message) assert.Empty(o, out, message) } // AssertError asserts that the output channel was updated with an error, // and returns the error string. func (o *OutputTester) AssertError(message string) string { out := o.AssertOutput(message) if len(out) != 1 { assert.Fail(o, "Expected an error output", message) return "" } urgent, ok := out[0]["urgent"] if !ok { assert.Fail(o, "Expected an error output", message) return "" } assert.True(o, urgent.(bool), message) assert.Equal(o, out[0]["short_text"], "Error", message) return out[0].Text() } // Drain empties the output channel when the exact number of outputs // doesn't matter, to allow further testing to start with a clean slate. func (o *OutputTester) Drain() { for { select { case <-o.outs: case <-time.After(negativeTimeout): return } } }
testing/module/module.go
0.731826
0.691022
module.go
starcoder
package postgres import ( "fmt" "strings" "github.com/pkg/errors" "github.com/uncharted-distil/distil-compute/model" api "github.com/uncharted-distil/distil/api/model" ) const ( unnestedSuffix = "_unnested" ) // VectorField defines behaviour for any Vector type. type VectorField struct { BasicField Unnested string } // NewVectorField creates a new field of the vector type. A vector field // uses unnest to flatten the database array and then uses the underlying // data type to get summaries. func NewVectorField(storage *Storage, datasetName string, datasetStorageName string, key string, label string, typ string) *VectorField { field := &VectorField{ BasicField: BasicField{ Storage: storage, DatasetName: datasetName, DatasetStorageName: datasetStorageName, Key: key + unnestedSuffix, Label: label, Type: typ, }, Unnested: key, } return field } // FetchSummaryData pulls summary data from the database and builds a histogram. func (f *VectorField) FetchSummaryData(resultURI string, filterParams *api.FilterParams, extrema *api.Extrema, mode api.SummaryMode) (*api.VariableSummary, error) { var underlyingField Field if f.isNumerical() { underlyingField = NewNumericalFieldSubSelect(f.Storage, f.DatasetName, f.DatasetStorageName, f.Key, f.Label, f.Type, f.Count, f.subSelect) } else { underlyingField = NewCategoricalFieldSubSelect(f.Storage, f.DatasetName, f.DatasetStorageName, f.Key, f.Label, f.Type, f.Count, f.subSelect) } histo, err := underlyingField.FetchSummaryData(resultURI, filterParams, extrema, mode) if err != nil { return nil, err } histo.Key = f.Unnested return histo, nil } // FetchNumericalStats gets the variable's numerical summary info (mean, stddev). func (f *VectorField) FetchNumericalStats(filterParams *api.FilterParams, invert bool) (*NumericalStats, error) { // confirm that the underlying type is numerical if !f.isNumerical() { return nil, errors.Errorf("field '%s' is not a numerical vector", f.Key) } // use the underlying numerical field implementation field := NewNumericalFieldSubSelect(f.Storage, f.DatasetName, f.DatasetStorageName, f.Key, f.Label, f.Type, f.Count, f.subSelect) return field.FetchNumericalStats(filterParams) } // FetchNumericalStatsByResult gets the variable's numerical summary info (mean, stddev) for a result set. func (f *VectorField) FetchNumericalStatsByResult(resultURI string, filterParams *api.FilterParams) (*NumericalStats, error) { // confirm that the underlying type is numerical if !f.isNumerical() { return nil, errors.Errorf("field '%s' is not a numerical vector", f.Key) } // use the underlying numerical field implementation field := NewNumericalFieldSubSelect(f.Storage, f.DatasetName, f.DatasetStorageName, f.Key, f.Label, f.Type, f.Count, f.subSelect) return field.FetchNumericalStatsByResult(resultURI, filterParams) } // FetchPredictedSummaryData pulls predicted data from the result table and builds // the categorical histogram for the field. func (f *VectorField) FetchPredictedSummaryData(resultURI string, datasetResult string, filterParams *api.FilterParams, extrema *api.Extrema, mode api.SummaryMode) (*api.VariableSummary, error) { return nil, errors.Errorf("vector field cannot be a target so no result will be pulled") } func (f *VectorField) isNumerical() bool { replacer := strings.NewReplacer("Vector", "", "List", "") return model.IsNumerical(replacer.Replace(f.Type)) } func (f *VectorField) subSelect() string { countSQL := "" if f.Count != "" { countSQL = fmt.Sprintf(", \"%s\"", f.Count) } return fmt.Sprintf("(SELECT \"%s\"%s, unnest(\"%s\") as \"%s\" FROM %s)", model.D3MIndexFieldName, countSQL, f.Unnested, f.Key, f.DatasetStorageName) }
api/model/storage/postgres/vector.go
0.711331
0.498291
vector.go
starcoder
package xpath import ( "bytes" "math" "strings" "unicode/utf8" "github.com/santhosh-tekuri/dom" ) // Arg defines the signature of a function argument. // It encapsulates: // - dataType of argument // - cardinality of argument type Arg int // Mandatory creates function argument which is mandatory // of given type. func Mandatory(t DataType) Arg { return Arg(t) } // Optional creates function argument which is optional // of given type. func Optional(t DataType) Arg { return Arg(int(t) + 10) } // Variadic creates function argument which is variadic // of given type. func Variadic(t DataType) Arg { return Arg(int(t) + 20) } // Args represents the signature of function arguments. type Args []Arg func (a Args) canAccept(nArgs int) bool { return nArgs >= a.mandatory() && (a.variadic() || nArgs <= len(a)) } func (a Args) typeOf(i int) DataType { if i >= len(a) { i = len(a) - 1 } return DataType(a[i] % 10) } // Valid tells whether the signature is valid func (a Args) Valid() bool { prev := 0 for _, arg := range a { div := int(arg) / 10 switch div { case 0: if prev != 0 { return false } case 1: if prev != 0 && prev != 1 { return false } case 2: if prev >= 2 { return false } } prev = div } return true } func (a Args) mandatory() int { c := 0 for _, arg := range a { if arg/10 == 0 { c++ } else { break } } return c } func (a Args) variadic() bool { return len(a) > 0 && a[len(a)-1]/10 == 2 } // Function encapsulates all information required // to compile an xpath function call type Function struct { Returns DataType Args Args Compile func(f *Function, args []Expr) Expr } // CompileFunc returns a function which compiles given impl to an xpath expression func CompileFunc(impl func(args []interface{}) interface{}) func(f *Function, args []Expr) Expr { return func(f *Function, args []Expr) Expr { return &funcCall{args, f.Returns, impl} } } var coreFunctions = map[string]*Function{ "string": { String, Args{Optional(Any)}, func(f *Function, args []Expr) Expr { if len(args) == 0 { return &stringFunc{ContextExpr{}} } return &stringFunc{args[0]} }}, "number": { Number, Args{Optional(Any)}, func(f *Function, args []Expr) Expr { if len(args) == 0 { return &numberFunc{ContextExpr{}} } return &numberFunc{args[0]} }}, "boolean": { Boolean, Args{Optional(Any)}, func(f *Function, args []Expr) Expr { return &booleanFunc{args[0]} }}, "name": { String, Args{Optional(NodeSet)}, func(f *Function, args []Expr) Expr { if len(args) == 0 { return &qname{ContextExpr{}} } return &qname{args[0]} }}, "local-name": { String, Args{Optional(NodeSet)}, func(f *Function, args []Expr) Expr { if len(args) == 0 { return &localName{ContextExpr{}} } return &localName{args[0]} }}, "namespace-uri": { String, Args{Optional(NodeSet)}, func(f *Function, args []Expr) Expr { if len(args) == 0 { return &namespaceURI{ContextExpr{}} } return &namespaceURI{args[0]} }}, "position": { Number, nil, func(f *Function, args []Expr) Expr { return &position{} }}, "last": { Number, nil, func(f *Function, args []Expr) Expr { return &last{} }}, "count": { Number, Args{Mandatory(NodeSet)}, func(f *Function, args []Expr) Expr { return &count{args[0]} }}, "sum": { Number, Args{Mandatory(NodeSet)}, func(f *Function, args []Expr) Expr { return &sum{args[0]} }}, "floor": { Number, Args{Mandatory(Number)}, func(f *Function, args []Expr) Expr { return &floor{args[0]} }}, "ceiling": { Number, Args{Mandatory(Number)}, func(f *Function, args []Expr) Expr { return &ceiling{args[0]} }}, "round": { Number, Args{Mandatory(Number)}, func(f *Function, args []Expr) Expr { return &round{args[0]} }}, "normalize-space": { String, Args{Optional(String)}, func(f *Function, args []Expr) Expr { if len(args) == 0 { return &normalizeSpace{asString(ContextExpr{})} } return &normalizeSpace{args[0]} }}, "string-length": { Number, Args{Optional(String)}, func(f *Function, args []Expr) Expr { if len(args) == 0 { return &stringLength{asString(ContextExpr{})} } return &stringLength{args[0]} }}, "starts-with": { Boolean, Args{Mandatory(String), Mandatory(String)}, func(f *Function, args []Expr) Expr { return &startsWith{args[0], args[1]} }}, "ends-with": { Boolean, Args{Mandatory(String), Mandatory(String)}, func(f *Function, args []Expr) Expr { return &endsWith{args[0], args[1]} }}, "contains": { Boolean, Args{Mandatory(String), Mandatory(String)}, func(f *Function, args []Expr) Expr { return &contains{args[0], args[1]} }}, "concat": { String, Args{Mandatory(String), Mandatory(String), Variadic(String)}, func(f *Function, args []Expr) Expr { return &concat{args} }}, "translate": { String, Args{Mandatory(String), Mandatory(String), Mandatory(String)}, func(f *Function, args []Expr) Expr { return &translate{args[0], args[1], args[2]} }}, "substring": { String, Args{Mandatory(String), Mandatory(Number), Optional(Number)}, func(f *Function, args []Expr) Expr { if len(args) == 3 { return &substring{args[0], args[1], args[2]} } return &substring{args[0], args[1], nil} }}, "substring-before": { String, Args{Mandatory(String), Mandatory(String)}, func(f *Function, args []Expr) Expr { return &substringBefore{args[0], args[1]} }}, "substring-after": { String, Args{Mandatory(String), Mandatory(String)}, func(f *Function, args []Expr) Expr { return &substringAfter{args[0], args[1]} }}, "true": { Boolean, nil, func(f *Function, args []Expr) Expr { return booleanVal(true) }}, "false": { Boolean, nil, func(f *Function, args []Expr) Expr { return booleanVal(false) }}, "not": { Boolean, Args{Mandatory(Boolean)}, func(f *Function, args []Expr) Expr { return &not{args[0]} }}, "lang": { Boolean, Args{Mandatory(String)}, func(f *Function, args []Expr) Expr { return &lang{args[0]} }}, } /************************************************************************/ type numberFunc struct { arg Expr } func (*numberFunc) Returns() DataType { return Number } func (e *numberFunc) Eval(ctx *Context) interface{} { return Value2Number(e.arg.Eval(ctx)) } func (e *numberFunc) Simplify() Expr { e.arg = Simplify(e.arg) if Literals(e.arg) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type booleanFunc struct { arg Expr } func (*booleanFunc) Returns() DataType { return Boolean } func (e *booleanFunc) Eval(ctx *Context) interface{} { return Value2Boolean(e.arg.Eval(ctx)) } func (e *booleanFunc) Simplify() Expr { e.arg = Simplify(e.arg) if Literals(e.arg) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type stringFunc struct { arg Expr } func (*stringFunc) Returns() DataType { return String } func (e *stringFunc) Eval(ctx *Context) interface{} { return Value2String(e.arg.Eval(ctx)) } func (e *stringFunc) Simplify() Expr { e.arg = Simplify(e.arg) if Literals(e.arg) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type position struct{} func (position) Returns() DataType { return Number } func (position) Eval(ctx *Context) interface{} { return float64(ctx.Pos) } /************************************************************************/ type last struct{} func (last) Returns() DataType { return Number } func (last) Eval(ctx *Context) interface{} { return float64(ctx.Size) } /************************************************************************/ type count struct { arg Expr } func (*count) Returns() DataType { return Number } func (e *count) Eval(ctx *Context) interface{} { return float64(len(e.arg.Eval(ctx).([]dom.Node))) } /************************************************************************/ type sum struct { arg Expr } func (*sum) Returns() DataType { return Number } func (e *sum) Eval(ctx *Context) interface{} { var r float64 for _, n := range e.arg.Eval(ctx).([]dom.Node) { r += Node2Number(n) } return r } /************************************************************************/ type localName struct { arg Expr } func (*localName) Returns() DataType { return String } func (e *localName) Eval(ctx *Context) interface{} { ns := e.arg.Eval(ctx).([]dom.Node) if len(ns) > 0 { switch n := ns[0].(type) { case *dom.Element: return n.Local case *dom.Attr: return n.Local case *dom.ProcInst: return n.Target case *dom.NameSpace: return n.Prefix } } return "" } /************************************************************************/ type namespaceURI struct { arg Expr } func (*namespaceURI) Returns() DataType { return String } func (e *namespaceURI) Eval(ctx *Context) interface{} { ns := e.arg.Eval(ctx).([]dom.Node) if len(ns) > 0 { switch n := ns[0].(type) { case *dom.Element: return n.URI case *dom.Attr: return n.URI } } return "" } /************************************************************************/ type qname struct { arg Expr } func (*qname) Returns() DataType { return String } func (e *qname) Eval(ctx *Context) interface{} { ns := e.arg.Eval(ctx).([]dom.Node) if len(ns) > 0 { switch n := ns[0].(type) { case *dom.Element: return n.Name.String() case *dom.Attr: return n.Name.String() case *dom.ProcInst: return n.Target case *dom.NameSpace: return n.Prefix } } return "" } /************************************************************************/ type normalizeSpace struct { arg Expr } func (*normalizeSpace) Returns() DataType { return String } func (e *normalizeSpace) Eval(ctx *Context) interface{} { buf := []byte(e.arg.Eval(ctx).(string)) read, write, lastWrite := 0, 0, 0 wroteOne := false for read < len(buf) { b := buf[read] if isSpace(b) { if wroteOne { buf[write] = ' ' write++ } read++ for read < len(buf) && isSpace(buf[read]) { read++ } } else { buf[write] = buf[read] write++ read++ wroteOne = true lastWrite = write } } return string(buf[:lastWrite]) } func (e *normalizeSpace) Simplify() Expr { e.arg = Simplify(e.arg) if Literals(e.arg) { return Value2Expr(e.Eval(nil)) } return e } func isSpace(b byte) bool { switch b { case ' ', '\t', '\n', '\r': return true default: return false } } /************************************************************************/ type startsWith struct { str Expr prefix Expr } func (*startsWith) Returns() DataType { return Boolean } func (e *startsWith) Eval(ctx *Context) interface{} { return strings.HasPrefix(e.str.Eval(ctx).(string), e.prefix.Eval(ctx).(string)) } func (e *startsWith) Simplify() Expr { e.str, e.prefix = Simplify(e.str), Simplify(e.prefix) if Literals(e.str, e.prefix) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type endsWith struct { str Expr suffix Expr } func (*endsWith) Returns() DataType { return Boolean } func (e *endsWith) Eval(ctx *Context) interface{} { return strings.HasSuffix(e.str.Eval(ctx).(string), e.suffix.Eval(ctx).(string)) } func (e *endsWith) Simplify() Expr { e.str, e.suffix = Simplify(e.str), Simplify(e.suffix) if Literals(e.str, e.suffix) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type contains struct { str Expr substr Expr } func (*contains) Returns() DataType { return Boolean } func (e *contains) Eval(ctx *Context) interface{} { return strings.Contains(e.str.Eval(ctx).(string), e.substr.Eval(ctx).(string)) } func (e *contains) Simplify() Expr { e.str, e.substr = Simplify(e.str), Simplify(e.substr) if Literals(e.str, e.substr) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type stringLength struct { str Expr } func (*stringLength) Returns() DataType { return Number } func (e *stringLength) Eval(ctx *Context) interface{} { return float64(utf8.RuneCountInString(e.str.Eval(ctx).(string))) } func (e *stringLength) Simplify() Expr { e.str = Simplify(e.str) if Literals(e.str) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type concat struct { args []Expr } func (*concat) Returns() DataType { return String } func (e *concat) Eval(ctx *Context) interface{} { buf := new(bytes.Buffer) for _, arg := range e.args { buf.WriteString(arg.Eval(ctx).(string)) } return buf.String() } func (e *concat) Simplify() Expr { for i := range e.args { e.args[i] = Simplify(e.args[i]) } if Literals(e.args...) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type translate struct { str Expr from Expr to Expr } func (*translate) Returns() DataType { return String } func (e *translate) Eval(ctx *Context) interface{} { from := []rune(e.from.Eval(ctx).(string)) to := []rune(e.to.Eval(ctx).(string)) replace := make(map[rune]rune) remove := make(map[rune]struct{}) for i, frune := range from { if _, ok := replace[frune]; ok { continue } if _, ok := remove[frune]; ok { continue } if i < len(to) { replace[frune] = to[i] } else { remove[frune] = struct{}{} } } str := e.str.Eval(ctx).(string) buf := bytes.NewBuffer(make([]byte, 0, len(str))) for _, r := range str { if _, ok := remove[r]; ok { continue } if v, ok := replace[r]; ok { buf.WriteRune(v) } else { buf.WriteRune(r) } } return buf.String() } func (e *translate) Simplify() Expr { e.str, e.from, e.to = Simplify(e.str), Simplify(e.from), Simplify(e.to) if Literals(e.str, e.from, e.to) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type substringBefore struct { str Expr match Expr } func (*substringBefore) Returns() DataType { return String } func (e *substringBefore) Eval(ctx *Context) interface{} { str := e.str.Eval(ctx).(string) if i := strings.Index(str, e.match.Eval(ctx).(string)); i != -1 { return str[:i] } return "" } func (e *substringBefore) Simplify() Expr { e.str, e.match = Simplify(e.str), Simplify(e.match) if Literals(e.str, e.match) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type substringAfter struct { str Expr match Expr } func (*substringAfter) Returns() DataType { return String } func (e *substringAfter) Eval(ctx *Context) interface{} { str := e.str.Eval(ctx).(string) match := e.match.Eval(ctx).(string) if i := strings.Index(str, match); i != -1 { return str[i+len(match):] } return "" } func (e *substringAfter) Simplify() Expr { e.str, e.match = Simplify(e.str), Simplify(e.match) if Literals(e.str, e.match) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type substring struct { str Expr from Expr length Expr } func (*substring) Returns() DataType { return String } func (e *substring) Eval(ctx *Context) interface{} { str := e.str.Eval(ctx).(string) strLength := utf8.RuneCountInString(str) if strLength == 0 { return "" } d1 := e.from.Eval(ctx).(float64) if math.IsNaN(d1) { return "" } start := roundToInt(d1) - 1 substrLength := strLength if e.length != nil { d2 := e.length.Eval(ctx).(float64) if math.IsInf(d2, +1) { substrLength = math.MaxInt16 } else if math.IsInf(d2, -1) { substrLength = math.MinInt16 } else if math.IsNaN(d2) { substrLength = 0 } else { substrLength = roundToInt(d2) } } if substrLength < 0 { return "" } end := start + substrLength if e.length == nil { end = strLength } // negative start is treated as 0 if start < 0 { start = 0 } else if start > strLength { return "" } if end > strLength { end = strLength } else if end < start { return "" } if strLength == len(str) { return str[start:end] } return string([]rune(str)[start:end]) } func (e *substring) Simplify() Expr { e.str, e.from, e.length = Simplify(e.str), Simplify(e.from), Simplify(e.length) if Literals(e.str, e.from, e.length) { return Value2Expr(e.Eval(nil)) } return e } func roundToInt(val float64) int { if val != 0.5 { return int(math.Floor(val + 0.5)) } return 0 } /************************************************************************/ type not struct { arg Expr } func (*not) Returns() DataType { return Boolean } func (e *not) Eval(ctx *Context) interface{} { return !e.arg.Eval(ctx).(bool) } func (e *not) Simplify() Expr { e.arg = Simplify(e.arg) if Literals(e.arg) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type lang struct { lang Expr } func (*lang) Returns() DataType { return Boolean } func (e *lang) Eval(ctx *Context) interface{} { lang := e.lang.Eval(ctx).(string) n := ctx.Node if _, ok := n.(*dom.Element); !ok { n = n.Parent() } for n != nil { if elem, ok := n.(*dom.Element); ok { attr := elem.GetAttr("http://www.w3.org/XML/1998/namespace", "lang") if attr != nil { sublang := attr.Value if strings.EqualFold(sublang, lang) { return true } ll := len(lang) return len(sublang) > ll && sublang[ll] == '-' && strings.EqualFold(sublang[:ll], lang) } } else { break } n = n.Parent() } return false } /************************************************************************/ type floor struct { num Expr } func (*floor) Returns() DataType { return Number } func (e *floor) Eval(ctx *Context) interface{} { return math.Floor(e.num.Eval(ctx).(float64)) } func (e *floor) Simplify() Expr { e.num = Simplify(e.num) if Literals(e.num) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type ceiling struct { num Expr } func (*ceiling) Returns() DataType { return Number } func (e *ceiling) Eval(ctx *Context) interface{} { return math.Ceil(e.num.Eval(ctx).(float64)) } func (e *ceiling) Simplify() Expr { e.num = Simplify(e.num) if Literals(e.num) { return Value2Expr(e.Eval(nil)) } return e } /************************************************************************/ type round struct { num Expr } func (*round) Returns() DataType { return Number } func (e *round) Eval(ctx *Context) interface{} { num := e.num.Eval(ctx).(float64) switch { case math.IsNaN(num) || math.IsInf(num, 0): return num case num != 0.5: return math.Floor(num + 0.5) default: return float64(0) } } func (e *round) Simplify() Expr { e.num = Simplify(e.num) if Literals(e.num) { return Value2Expr(e.Eval(nil)) } return e }
functions.go
0.687735
0.436202
functions.go
starcoder
package tracee import ( "debug/dwarf" "encoding/binary" "fmt" "github.com/nkbai/tgo/log" ) // moduleData represents the value of the moduledata type. // It offers a set of methods to get the field value of the type rather than simply returns the parsed result. // It is because the moduledata can be large and the parsing cost is too high. // TODO: try to use the parser by optimizing the load array operation. type moduleData struct { moduleDataAddr uint64 moduleDataType dwarf.Type fields map[string]*dwarf.StructField } func newModuleData(moduleDataAddr uint64, moduleDataType dwarf.Type) *moduleData { fields := make(map[string]*dwarf.StructField) for _, field := range moduleDataType.(*dwarf.StructType).Field { fields[field.Name] = field } return &moduleData{moduleDataAddr: moduleDataAddr, moduleDataType: moduleDataType, fields: fields} } // pclntable retrieves the pclntable data specified by `index` because retrieving all the ftab data can be heavy. func (md *moduleData) pclntable(reader memoryReader, index int) uint64 { ptrToArrayType, ptrToArray := md.retrieveArrayInSlice(reader, "pclntable") elementType := ptrToArrayType.(*dwarf.PtrType).Type return ptrToArray + uint64(index)*uint64(elementType.Size()) } // functab retrieves the functab data specified by `index` because retrieving all the ftab data can be heavy. func (md *moduleData) functab(reader memoryReader, index int) (entry, funcoff uint64) { ptrToFtabType, ptrToArray := md.retrieveArrayInSlice(reader, "ftab") ftabType := ptrToFtabType.(*dwarf.PtrType).Type functabSize := uint64(ftabType.Size()) buff := make([]byte, functabSize) if err := reader.ReadMemory(ptrToArray+uint64(index)*functabSize, buff); err != nil { log.Debugf("failed to read memory: %v", err) return } if innerFtabType, ok := ftabType.(*dwarf.TypedefType); ok { // some go version wraps the ftab. ftabType = innerFtabType.Type } for _, field := range ftabType.(*dwarf.StructType).Field { val := binary.LittleEndian.Uint64(buff[field.ByteOffset : field.ByteOffset+field.Type.Size()]) switch field.Name { case "entry": entry = val case "funcoff": funcoff = val } } return } func (md *moduleData) ftabLen(reader memoryReader) int { return md.retrieveSliceLen(reader, "ftab") } func (md *moduleData) findfunctab(reader memoryReader) uint64 { return md.retrieveUint64(reader, "findfunctab") } func (md *moduleData) minpc(reader memoryReader) uint64 { return md.retrieveUint64(reader, "minpc") } func (md *moduleData) maxpc(reader memoryReader) uint64 { return md.retrieveUint64(reader, "maxpc") } func (md *moduleData) types(reader memoryReader) uint64 { return md.retrieveUint64(reader, "types") } func (md *moduleData) etypes(reader memoryReader) uint64 { return md.retrieveUint64(reader, "etypes") } func (md *moduleData) next(reader memoryReader) uint64 { return md.retrieveUint64(reader, "next") } func (md *moduleData) retrieveArrayInSlice(reader memoryReader, fieldName string) (dwarf.Type, uint64) { typ, buff := md.retrieveFieldOfStruct(reader, md.fields[fieldName], "array") if buff == nil { return nil, 0 } return typ, binary.LittleEndian.Uint64(buff) } func (md *moduleData) retrieveSliceLen(reader memoryReader, fieldName string) int { _, buff := md.retrieveFieldOfStruct(reader, md.fields[fieldName], "len") if buff == nil { return 0 } return int(binary.LittleEndian.Uint64(buff)) } func (md *moduleData) retrieveFieldOfStruct(reader memoryReader, strct *dwarf.StructField, fieldName string) (dwarf.Type, []byte) { strctType, ok := strct.Type.(*dwarf.StructType) if !ok { log.Printf("unexpected type: %#v", md.fields[fieldName].Type) return nil, nil } var field *dwarf.StructField for _, candidate := range strctType.Field { if candidate.Name == fieldName { field = candidate break } } if field == nil { panic(fmt.Sprintf("%s field not found", fieldName)) } buff := make([]byte, field.Type.Size()) addr := md.moduleDataAddr + uint64(strct.ByteOffset) + uint64(field.ByteOffset) if err := reader.ReadMemory(addr, buff); err != nil { log.Debugf("failed to read memory: %v", err) return nil, nil } return field.Type, buff } func (md *moduleData) retrieveUint64(reader memoryReader, fieldName string) uint64 { field := md.fields[fieldName] if field.Type.Size() != 8 { log.Printf("the type size is not expected value: %d", field.Type.Size()) } buff := make([]byte, 8) if err := reader.ReadMemory(md.moduleDataAddr+uint64(field.ByteOffset), buff); err != nil { log.Debugf("failed to read memory: %v", err) return 0 } return binary.LittleEndian.Uint64(buff) }
tracee/moduledata.go
0.513181
0.451871
moduledata.go
starcoder
package query // The Visitor interface allows to visit nodes for each respective part of the // query grammar. type Visitor interface { VisitNodes(v Visitor, node []Node) VisitOperator(v Visitor, kind operatorKind, operands []Node) VisitParameter(v Visitor, field, value string, negated bool, annotation Annotation) VisitPattern(v Visitor, value string, negated bool, annotation Annotation) } // BaseVisitor is a visitor that recursively visits each node in a query. A // BaseVisitor's methods may be overriden by embedding it a custom visitor's // definition. See OperatorVisitor for an example. type BaseVisitor struct{} func (*BaseVisitor) VisitNodes(visitor Visitor, nodes []Node) { for _, node := range nodes { switch v := node.(type) { case Pattern: visitor.VisitPattern(visitor, v.Value, v.Negated, v.Annotation) case Parameter: visitor.VisitParameter(visitor, v.Field, v.Value, v.Negated, v.Annotation) case Operator: visitor.VisitOperator(visitor, v.Kind, v.Operands) default: panic("unreachable") } } } func (*BaseVisitor) VisitOperator(visitor Visitor, kind operatorKind, operands []Node) { visitor.VisitNodes(visitor, operands) } func (*BaseVisitor) VisitParameter(visitor Visitor, field, value string, negated bool, annotation Annotation) { } func (*BaseVisitor) VisitPattern(visitor Visitor, value string, negated bool, annotation Annotation) { } // ParameterVisitor is a helper visitor that only visits operators in a query, // and supplies the operator members via a callback. type OperatorVisitor struct { BaseVisitor callback func(kind operatorKind, operands []Node) } func (s *OperatorVisitor) VisitOperator(visitor Visitor, kind operatorKind, operands []Node) { s.callback(kind, operands) visitor.VisitNodes(visitor, operands) } // ParameterVisitor is a helper visitor that only visits parameters in a query, // and supplies the parameter members via a callback. type ParameterVisitor struct { BaseVisitor callback func(field, value string, negated bool, annotation Annotation) } func (s *ParameterVisitor) VisitParameter(visitor Visitor, field, value string, negated bool, annotation Annotation) { s.callback(field, value, negated, annotation) } // PatternVisitor is a helper visitor that only visits patterns in a query, // and supplies the pattern members via a callback. type PatternVisitor struct { BaseVisitor callback func(value string, negated bool, annotation Annotation) } func (s *PatternVisitor) VisitPattern(visitor Visitor, value string, negated bool, annotation Annotation) { s.callback(value, negated, annotation) } // FieldVisitor is a helper visitor that only visits parameter fields in a // query, for a field specified in the state. For each parameter with // this field name it calls the callback with the field's members. type FieldVisitor struct { BaseVisitor field string callback func(value string, negated bool, annotation Annotation) } func (s *FieldVisitor) VisitParameter(visitor Visitor, field, value string, negated bool, annotation Annotation) { if s.field == field { s.callback(value, negated, annotation) } } // VisitOperator is a convenience function that calls callback on all operator // nodes. callback supplies the node's kind and operands. func VisitOperator(nodes []Node, callback func(kind operatorKind, operands []Node)) { visitor := &OperatorVisitor{callback: callback} visitor.VisitNodes(visitor, nodes) } // VisitParameter is a convenience function that calls callback on all parameter // nodes. callback supplies the node's field, value, and whether the value is // negated. func VisitParameter(nodes []Node, callback func(field, value string, negated bool, annotation Annotation)) { visitor := &ParameterVisitor{callback: callback} visitor.VisitNodes(visitor, nodes) } // VisitPattern is a convenience function that calls callback on all pattern // nodes. callback supplies the node's value value, and whether the value is // negated or quoted. func VisitPattern(nodes []Node, callback func(value string, negated bool, annotation Annotation)) { visitor := &PatternVisitor{callback: callback} visitor.VisitNodes(visitor, nodes) } // VisitField convenience function that calls callback on all parameter nodes // whose field matches the field argument. callback supplies the node's value // and whether the value is negated. func VisitField(nodes []Node, field string, callback func(value string, negated bool, annotation Annotation)) { visitor := &FieldVisitor{callback: callback, field: field} visitor.VisitNodes(visitor, nodes) }
internal/search/query/visitor.go
0.872551
0.601564
visitor.go
starcoder
package fn import ( "fmt" "log" "github.com/rwxrob/fn/each" ) // Number combines the primitives generally considered numbers by JSON // and other high-level structure data representations. type Number interface { int | int64 | int32 | int16 | int8 | uint64 | uint32 | uint16 | uint8 | float64 | float32 } // Text combines byte slice and string. type Text interface { []byte | string | []rune } // Sharable are the types that have representations in JSON, YAML, TOML // and other high-level structured data representations. type Sharable interface { int | int64 | int32 | int16 | int8 | uint64 | uint32 | uint16 | uint8 | float64 | float32 | []byte | string | bool } // A is the equivalent of an array primitive in other functional // languages. It is a generic slice of anything. type A[T any] []T // Each calls each.Do on self func (a A[any]) Each(f func(i any)) { each.Do(a, f) } // E calls Do function on self. func (a A[any]) E(f func(i any)) { each.Do(a, f) } // Map calls Map function on self. func (a A[any]) Map(f func(i any) any) A[any] { return Map(a, f) } // M calls Map function on self. func (a A[any]) M(f func(i any) any) A[any] { return Map(a, f) } // Filter calls Filter function on self. func (a A[any]) Filter(f func(i any) bool) A[any] { return Filter(a, f) } // Filter calls Filter function on self. func (a A[any]) F(f func(i any) bool) A[any] { return Filter(a, f) } // Reduce calls Reduce function on self. func (a A[any]) Reduce(f func(i any, r *any)) *any { return Reduce(a, f) } // Reduce calls Reduce function on self. func (a A[any]) R(f func(i any, r *any)) *any { return Reduce(a, f) } // Print calls each.Print on self. func (a A[any]) Print() { each.Print(a) } // Println calls each.Println on self. func (a A[any]) Println() { each.Println(a) } // Printf calls each.Printf on self. func (a A[any]) Printf(t string) { each.Printf(a, t) } // Log calls each.Log on self. func (a A[any]) Log() { each.Log(a) } // Logf calls each.Logf on self. func (a A[any]) Logf(f string) { each.Logf(a, f) } // Map executes an operator function provided on each item in the slice // returning a new slice with items of a potentially different type // completely (which is different from using the Array.Map method which // requires returning the same type). If error handling is needed it // should be handled within an enclosure within the function. This keeps // signatures simple and functional. func Map[I any, O any](slice []I, f func(in I) O) []O { list := []O{} for _, i := range slice { list = append(list, f(i)) } return list } // Filter applies the boolean function on each item only returning those // items that evaluate to true. func Filter[T any](slice []T, f func(in T) bool) []T { list := []T{} for _, i := range slice { if f(i) { list = append(list, i) } } return list } // Reduce calls the given reducer function for every item in the slice // passing a required reference to an item to hold the results If error // handling is needed it should be handled within an enclosure within // the function. This keeps signatures simple and functional. func Reduce[T any, R any](slice []T, f func(in T, ref *R)) *R { r := new(R) for _, i := range slice { f(i, r) } return r } // Pipe implements the closest thing to UNIX pipelines possible in Go by // passing each argument to the next assuming a func(in any) any format // where the input (in) is converted to a string (if not already // a string). If any return an error the pipeline returns an empty // string and logs an error. func Pipe(filter ...any) string { if len(filter) == 0 { return "" } var in any in = filter[0] for _, f := range filter[1:] { switch v := f.(type) { case func(any) any: in = v(in) default: in = f } if err, iserr := in.(error); iserr { log.Print(err) return "" } } return fmt.Sprintf("%v", in) } // PipePrint prints the output (and a newline) of a Pipe logging any // errors encountered. func PipePrint(filter ...any) { fmt.Println(Pipe(filter...)) }
fn.go
0.68458
0.488344
fn.go
starcoder
package parse import ( "math/rand" "time" "strings" ) func QuoteParserFactory(quoteChannelName string, QuotesMap map[string]interface{}, QuotesMapList []map[string]interface{}) map[string]interface{} { if strings.ToLower(quoteChannelName) == "programming" { return parseProgrammingQuotes(QuotesMap) } else if strings.ToLower(quoteChannelName) == "garden" { return parseGardenQuotes(QuotesMap) } else if strings.ToLower(quoteChannelName) == "advice" { return parseAdviceQuotes(QuotesMap) } else if strings.ToLower(quoteChannelName) == "design" { return parseDesignQuotes(QuotesMapList) } else if strings.ToLower(quoteChannelName) == "favorite" { return parseFavoriteQuotes(QuotesMap) } else if strings.ToLower(quoteChannelName) == "taylor" { return parseTaylorSwiftQuotes(QuotesMap) } else if strings.ToLower(quoteChannelName) == "trump" { return parseDonaldTrumpQuotes(QuotesMap) } else if strings.ToLower(quoteChannelName) == "kanye" { return parseKanyeWestQuotes(QuotesMap) } else { return parseForismaticQuotes(QuotesMap) } } func parseProgrammingQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["author"] = QuotesMap["author"] parsedMap["quote"] = QuotesMap["en"] return parsedMap } func parseGardenQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["author"] = QuotesMap["quote"].(map[string]interface{})["quoteAuthor"] parsedMap["quote"] = QuotesMap["quote"].(map[string]interface{})["quoteText"] parsedMap["genre"] = QuotesMap["quote"].(map[string]interface{})["quoteGenre"] return parsedMap } func parseAdviceQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["quote"] = QuotesMap["slip"].(map[string]interface{})["advice"] return parsedMap } func parseDesignQuotes(QuotesMapList []map[string]interface{}) map[string]interface{} { source := rand.NewSource(time.Now().UnixNano()) randomNumGenerator := rand.New(source) randomIndex := randomNumGenerator.Intn(len(QuotesMapList)) randomQuotesMap := QuotesMapList[randomIndex] parsedMap := make(map[string]interface{}) parsedMap["quote"] = randomQuotesMap["content"].(map[string]interface{})["rendered"] parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"<p>","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"</p>","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"&#8217","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"&#8211","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"&#8243;","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"&#8220;","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"&#8221;","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"<strong>","",-1) parsedMap["quote"] = strings.Replace(parsedMap["quote"].(string),"</strong>","",-1) parsedMap["author"] = randomQuotesMap["slug"] return parsedMap } func parseFavoriteQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["quote"] = QuotesMap["quote"].(map[string]interface{})["body"] parsedMap["author"] = QuotesMap["quote"].(map[string]interface{})["author"] return parsedMap } func parseForismaticQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["quote"] = QuotesMap["quoteText"] parsedMap["author"] = QuotesMap["quoteAuthor"] return parsedMap } func parseTaylorSwiftQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["quote"] = QuotesMap["quote"] return parsedMap } func parseDonaldTrumpQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["quote"] = QuotesMap["value"] return parsedMap } func parseKanyeWestQuotes(QuotesMap map[string]interface{}) map[string]interface{} { parsedMap := make(map[string]interface{}) parsedMap["quote"] = QuotesMap["quote"] return parsedMap }
backend/parse/quotesparser.go
0.530966
0.461563
quotesparser.go
starcoder
package resize import ( "image" "runtime" "sync" ) // An InterpolationFunction provides the parameters that describe an // interpolation kernel. It returns the number of samples to take // and the kernel function to use for sampling. type InterpolationFunction int // InterpolationFunction constants const ( // Nearest-neighbor interpolation NearestNeighbor InterpolationFunction = iota // Bilinear interpolation Bilinear // Bicubic interpolation (with cubic hermite spline) Bicubic // Mitchell-Netravali interpolation MitchellNetravali // Lanczos interpolation (a=2) Lanczos2 // Lanczos interpolation (a=3) Lanczos3 ) // kernal, returns an InterpolationFunctions taps and kernel. func (i InterpolationFunction) kernel() (int, func(float64) float64) { switch i { case Bilinear: return 2, linear case Bicubic: return 4, cubic case MitchellNetravali: return 4, mitchellnetravali case Lanczos2: return 4, lanczos2 case Lanczos3: return 6, lanczos3 default: // Default to NearestNeighbor. return 2, nearest } } // values <1 will sharpen the image var blur = 1.0 // Resize scales an image to new width and height using the interpolation function interp. // A new image with the given dimensions will be returned. // If one of the parameters width or height is set to 0, its size will be calculated so that // the aspect ratio is that of the originating image. // The resizing algorithm uses channels for parallel computation. // If the input image has width or height of 0, it is returned unchanged. func Resize(width, height uint, img image.Image, interp InterpolationFunction) image.Image { scaleX, scaleY := calcFactors(width, height, float64(img.Bounds().Dx()), float64(img.Bounds().Dy())) if width == 0 { width = uint(0.7 + float64(img.Bounds().Dx())/scaleX) } if height == 0 { height = uint(0.7 + float64(img.Bounds().Dy())/scaleY) } // Trivial case: return input image if int(width) == img.Bounds().Dx() && int(height) == img.Bounds().Dy() { return img } // Input image has no pixels if img.Bounds().Dx() <= 0 || img.Bounds().Dy() <= 0 { return img } if interp == NearestNeighbor { return resizeNearest(width, height, scaleX, scaleY, img, interp) } taps, kernel := interp.kernel() cpus := runtime.GOMAXPROCS(0) wg := sync.WaitGroup{} // Generic access to image.Image is slow in tight loops. // The optimal access has to be determined from the concrete image type. switch input := img.(type) { case *image.RGBA: // 8-bit precision temp := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA) go func() { defer wg.Done() resizeRGBA(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA) go func() { defer wg.Done() resizeRGBA(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.NRGBA: // 8-bit precision temp := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA) go func() { defer wg.Done() resizeNRGBA(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA) go func() { defer wg.Done() resizeRGBA(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.YCbCr: // 8-bit precision // accessing the YCbCr arrays in a tight loop is slow. // converting the image to ycc increases performance by 2x. temp := newYCC(image.Rect(0, 0, input.Bounds().Dy(), int(width)), input.SubsampleRatio) result := newYCC(image.Rect(0, 0, int(width), int(height)), image.YCbCrSubsampleRatio444) coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel) in := imageYCbCrToYCC(input) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*ycc) go func() { defer wg.Done() resizeYCbCr(in, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*ycc) go func() { defer wg.Done() resizeYCbCr(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result.YCbCr() case *image.RGBA64: // 16-bit precision temp := image.NewRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA64) go func() { defer wg.Done() resizeRGBA64(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA64) go func() { defer wg.Done() resizeRGBA64(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.NRGBA64: // 16-bit precision temp := image.NewRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA64) go func() { defer wg.Done() resizeNRGBA64(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA64) go func() { defer wg.Done() resizeRGBA64(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.Gray: // 8-bit precision temp := image.NewGray(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewGray(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.Gray) go func() { defer wg.Done() resizeGray(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.Gray) go func() { defer wg.Done() resizeGray(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.Gray16: // 16-bit precision temp := image.NewGray16(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewGray16(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.Gray16) go func() { defer wg.Done() resizeGray16(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.Gray16) go func() { defer wg.Done() resizeGray16(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result default: // 16-bit precision temp := image.NewRGBA64(image.Rect(0, 0, img.Bounds().Dy(), int(width))) result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA64) go func() { defer wg.Done() resizeGeneric(img, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA64) go func() { defer wg.Done() resizeRGBA64(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result } } func resizeNearest(width, height uint, scaleX, scaleY float64, img image.Image, interp InterpolationFunction) image.Image { taps, _ := interp.kernel() cpus := runtime.GOMAXPROCS(0) wg := sync.WaitGroup{} switch input := img.(type) { case *image.RGBA: // 8-bit precision temp := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA) go func() { defer wg.Done() nearestRGBA(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA) go func() { defer wg.Done() nearestRGBA(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.NRGBA: // 8-bit precision temp := image.NewNRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewNRGBA(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.NRGBA) go func() { defer wg.Done() nearestNRGBA(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.NRGBA) go func() { defer wg.Done() nearestNRGBA(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.YCbCr: // 8-bit precision // accessing the YCbCr arrays in a tight loop is slow. // converting the image to ycc increases performance by 2x. temp := newYCC(image.Rect(0, 0, input.Bounds().Dy(), int(width)), input.SubsampleRatio) result := newYCC(image.Rect(0, 0, int(width), int(height)), image.YCbCrSubsampleRatio444) coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) in := imageYCbCrToYCC(input) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*ycc) go func() { defer wg.Done() nearestYCbCr(in, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*ycc) go func() { defer wg.Done() nearestYCbCr(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result.YCbCr() case *image.RGBA64: // 16-bit precision temp := image.NewRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA64) go func() { defer wg.Done() nearestRGBA64(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA64) go func() { defer wg.Done() nearestRGBA64(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.NRGBA64: // 16-bit precision temp := image.NewNRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewNRGBA64(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.NRGBA64) go func() { defer wg.Done() nearestNRGBA64(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.NRGBA64) go func() { defer wg.Done() nearestNRGBA64(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.Gray: // 8-bit precision temp := image.NewGray(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewGray(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.Gray) go func() { defer wg.Done() nearestGray(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.Gray) go func() { defer wg.Done() nearestGray(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result case *image.Gray16: // 16-bit precision temp := image.NewGray16(image.Rect(0, 0, input.Bounds().Dy(), int(width))) result := image.NewGray16(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.Gray16) go func() { defer wg.Done() nearestGray16(input, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.Gray16) go func() { defer wg.Done() nearestGray16(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result default: // 16-bit precision temp := image.NewRGBA64(image.Rect(0, 0, img.Bounds().Dy(), int(width))) result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height))) // horizontal filter, results in transposed temporary image coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(temp, i, cpus).(*image.RGBA64) go func() { defer wg.Done() nearestGeneric(img, slice, scaleX, coeffs, offset, filterLength) }() } wg.Wait() // horizontal filter on transposed image, result is not transposed coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY) wg.Add(cpus) for i := 0; i < cpus; i++ { slice := makeSlice(result, i, cpus).(*image.RGBA64) go func() { defer wg.Done() nearestRGBA64(temp, slice, scaleY, coeffs, offset, filterLength) }() } wg.Wait() return result } } // Calculates scaling factors using old and new image dimensions. func calcFactors(width, height uint, oldWidth, oldHeight float64) (scaleX, scaleY float64) { if width == 0 { if height == 0 { scaleX = 1.0 scaleY = 1.0 } else { scaleY = oldHeight / float64(height) scaleX = scaleY } } else { scaleX = oldWidth / float64(width) if height == 0 { scaleY = scaleX } else { scaleY = oldHeight / float64(height) } } return } type imageWithSubImage interface { image.Image SubImage(image.Rectangle) image.Image } func makeSlice(img imageWithSubImage, i, n int) image.Image { return img.SubImage(image.Rect(img.Bounds().Min.X, img.Bounds().Min.Y+i*img.Bounds().Dy()/n, img.Bounds().Max.X, img.Bounds().Min.Y+(i+1)*img.Bounds().Dy()/n)) }
vendor/github.com/nfnt/resize/resize.go
0.66236
0.492371
resize.go
starcoder
package cryptohelper import ( "crypto/aes" "crypto/cipher" "crypto/hmac" crand "crypto/rand" "crypto/sha256" "crypto/sha512" "encoding/base64" "encoding/hex" "errors" "math/big" mrand "math/rand" "strconv" "time" ) const ( AES128KeyLength = 16 AES192KeyLength = 24 AES256KeyLength = 32 HMACSHA256KeyLength = 32 HMACSHA512KeyLength = 64 ) var ( ErrCipherTextMissingNonce = errors.New("The nonce cannot be parsed from the cipher text because the length of the cipher text is too short") ) // GeneratePIN creates a psuedo-random pin number style security code of the designated character length. // The output of this function is suitable for generating pin numbers for use in a two-factor auth system // which uses security code verification over a medium like SMS or email. func GeneratePIN(length int) string { mrand.Seed(time.Now().UnixNano()) pin := "" for len(pin) < length { pin += strconv.Itoa(mrand.Intn(9)) } return pin } // GenerateCryptoPIN creates a cryptographically secure random pin number style security code of the designated character length. // The output of this function is suitable for generating pin numbers for use in a two-factor auth system // which uses security code verification over a medium like SMS or email. func GenerateCryptoPIN(length int) (string, error) { pin := "" for len(pin) < length { num, err := crand.Int(crand.Reader, big.NewInt(9)) if err != nil { return "", err } pin += num.String() } return pin, nil } // GenerateCryptoSequence returns a cryptographically secure psuedo-random sequence of bytes of the // indicated length. The output of this function is suitable for generating a secret key for use in a // symmetrical encryption algorithm such as AES, a random nonce, etc. This method relies on specifics // of the underlying operating system and if a byte slice of the full indicated length cannot be generated // an error will be returned. func GenerateCryptoSequence(length int) ([]byte, error) { seq := make([]byte, length) _, err := crand.Read(seq) if err != nil { return nil, err } return seq, nil } // GenerateAES128Key is an alias for GenerateCryptoSequence(16). // An AES 128-bit key is expressed here as a byte slice. To obtain the plain text equivalent of this // key for storage use the EncodeB64 or EncodeHex function. func GenerateAES128Key() ([]byte, error) { return GenerateCryptoSequence(AES128KeyLength) } // GenerateAES192Key is an alias for GenerateCryptoSequence(24). // An AES 192-bit key is expressed here as a byte slice. To obtain the plain text equivalent of this // key for storage use the EncodeB64 or EncodeHex function. func GenerateAES192Key() ([]byte, error) { return GenerateCryptoSequence(AES192KeyLength) } // GenerateAES256Key is an alias for GenerateCryptoSequence(32). // An AES 256-bit key is expressed here as a byte slice. To obtain the plain text equivalent of this // key for storage use the EncodeB64 or EncodeHex function. func GenerateAES256Key() ([]byte, error) { return GenerateCryptoSequence(AES256KeyLength) } // GenerateHMACSHA256Key is an alias for GenerateCryptoSequence(32). // An HMAC SHA-256 key is expressed here as a byte slice. To obtain the plain text equivalent of this // key for storage use the EncodeB64 or EncodeHex function. func GenerateHMACSHA256Key() ([]byte, error) { return GenerateCryptoSequence(HMACSHA256KeyLength) } // GenerateHMACSHA512Key is an alias for GenerateCryptoSequence(64). // An HMAC SHA-512 key is expressed here as a byte slice. To obtain the plain text equivalent of this // key for storage use the EncodeB64 or EncodeHex function. func GenerateHMACSHA512Key() ([]byte, error) { return GenerateCryptoSequence(HMACSHA512KeyLength) } // EncryptTextAESGCM encrypts a chunk of plaintext using AES 128/192/256 symmetrical encryption with the // strength based on the key length. 128-bit requires a key length of 16, 192-bit requires a key length of 24, // and 256-bit requires a key length of 32. An error will be returned if the key is not of an acceptable // length. The mode of operation used for the block cipher is GCM (Galois/Counter Mode). A 12-byte random // nonce will be prepended to the final ciphertext and must be parsed back out and used during the decryption // process. If the DecryptTextAESGCM function is used to decrypt the ciphertext then the nonce will be // handled transparently. func EncryptTextAESGCM(key []byte, plaintext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } aesgcm, err := cipher.NewGCM(block) if err != nil { return nil, err } // Create a random nonce of the standard length required by the gcm. nonce, err := GenerateCryptoSequence(aesgcm.NonceSize()) if err != nil { return nil, err } // Encrypt the plaintext using the nonce and the key. Note that we pass the // nonce in as the first argument, which ensures that it will be prepended to // the encrypted text and stored along with it. When it comes time to decrypt // this text we will need to parse the nonse back out and use it again. ciphertext := aesgcm.Seal(nonce, nonce, plaintext, nil) return ciphertext, nil } // DecryptTextAESGCM decrypts a chunk of ciphertext which was encrypted using AES 128/192/256 // symmetrical encryption with the mode of operation used for the block cipher being GCM. This // function requires the same key used to encrypt the plaintext and also expects the 12-byte random // nonce used to encrypt the plaintext to be prepended to the ciphertext. If the EncryptTextAESGCM // function was used to generate the ciphertext then the nonce will be handled transparently. func DecryptTextAESGCM(key []byte, ciphertext []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } aesgcm, err := cipher.NewGCM(block) if err != nil { return nil, err } // Obtain the standard nonce length from the gcm and validate the ciphertext noncesize := aesgcm.NonceSize() if len(ciphertext) < noncesize { return nil, ErrCipherTextMissingNonce } // Parse the nonse from the ciphertext nonce, ciphertext := ciphertext[:noncesize], ciphertext[noncesize:] // Decrypt the ciphertext using the nonce and the key. plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil) if err != nil { return nil, err } return plaintext, nil } // CreateHMACSHA256 creates a cryptographic hash of a plaintext message using the Keyed-Hash Message // Authentication Code (HMAC) method and the SHA-256 hashing algorithm. While the key can be any length // it should be 32 random bytes for optimal security. The output can be converted to a string for storage using // EncodeHex or EncodeB64. For a secure way to compare the output with another hmac hash use CompareHMAC. func CreateHMACSHA256(key []byte, plaintext []byte) []byte { hash := hmac.New(sha256.New, key) hash.Write(plaintext) return hash.Sum(nil) } // CreateHMACSHA512 creates a cryptographic hash of a plaintext message using the Keyed-Hash Message // Authentication Code (HMAC) method and the SHA-512 hashing algorithm. While the key can be any length // it should be 64 random bytes for optimal security. The output can be converted to a string for storage using // EncodeHex or EncodeB64. For a secure way to compare the output with another hmac hash use CompareHMAC. func CreateHMACSHA512(key []byte, plaintext []byte) []byte { hash := hmac.New(sha512.New, key) hash.Write(plaintext) return hash.Sum(nil) } // CompareHMAC is a secure way to compare two HMAC hash outputs for equality without leaking timing // side-channel information. func CompareHMAC(hashA []byte, hashB []byte) bool { return hmac.Equal(hashA, hashB) } // EncodeHex converts a byte slice such as a key, hash, or ciphertext to a hexadecimal string for storage. func EncodeHex(seq []byte) string { return hex.EncodeToString(seq) } // DecodeHex converts a hexadecimal string such as a stored key, hash, or ciphertext back into a byte slice. func DecodeHex(str string) ([]byte, error) { seq, err := hex.DecodeString(str) if err != nil { return nil, err } return seq, nil } // EncodeB64 converts a byte slice such as a key, hash, or ciphertext to a base64-encoded string for storage. func EncodeB64(seq []byte) string { return base64.StdEncoding.EncodeToString(seq) } // DecodeB64 converts a base64-encoded string such as a stored key, hash, or ciphertext back into a byte slice. func DecodeB64(str string) ([]byte, error) { seq, err := base64.StdEncoding.DecodeString(str) if err != nil { return nil, err } return seq, nil }
cryptohelper.go
0.748352
0.492493
cryptohelper.go
starcoder
package executor import ( "github.com/turingchain2020/turingchain/types" dty "github.com/turingchain2020/plugin/plugin/dapp/dposvote/types" ) //Exec_Regist DPos执行器注册候选节点 func (d *DPos) Exec_Regist(payload *dty.DposCandidatorRegist, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.Regist(payload) } //Exec_CancelRegist DPos执行器取消注册候选节点 func (d *DPos) Exec_CancelRegist(payload *dty.DposCandidatorCancelRegist, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.CancelRegist(payload) } //Exec_ReRegist DPos执行器重新注册候选节点 func (d *DPos) Exec_ReRegist(payload *dty.DposCandidatorRegist, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.ReRegist(payload) } //Exec_Vote DPos执行器为候选节点投票 func (d *DPos) Exec_Vote(payload *dty.DposVote, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.Vote(payload) } //Exec_CancelVote DPos执行器撤销对一个候选节点的投票 func (d *DPos) Exec_CancelVote(payload *dty.DposCancelVote, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.CancelVote(payload) } //Exec_RegistVrfM DPos执行器注册一个受托节点的Vrf M信息 func (d *DPos) Exec_RegistVrfM(payload *dty.DposVrfMRegist, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.RegistVrfM(payload) } //Exec_RegistVrfRP DPos执行器注册一个受托节点的Vrf R/P信息 func (d *DPos) Exec_RegistVrfRP(payload *dty.DposVrfRPRegist, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.RegistVrfRP(payload) } //Exec_RecordCB DPos执行器记录CycleBoundary信息 func (d *DPos) Exec_RecordCB(payload *dty.DposCBInfo, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.RecordCB(payload) } //Exec_RegistTopN DPos执行器注册某一cycle中的TOPN信息 func (d *DPos) Exec_RegistTopN(payload *dty.TopNCandidatorRegist, tx *types.Transaction, index int) (*types.Receipt, error) { action := NewAction(d, tx, index) return action.RegistTopN(payload) }
plugin/dapp/dposvote/executor/exec.go
0.5
0.400925
exec.go
starcoder
package release import ( "math" "sort" "github.com/cespare/xxhash" shipper "github.com/bookingcom/shipper/pkg/apis/shipper/v1alpha1" ) const ( defaultClusterWeight = 100 ) type scoredCluster struct { cluster *shipper.Cluster score float64 } func buildPrefList(appIdentity string, clusterList []*shipper.Cluster) []*shipper.Cluster { /* This part is a bit subtle: we're creating a preference list of clusters by creating a sorting key composed of a hash of the Application name plus the cluster seed (defaulting to cluster name). This list is sorted by that key, and the resulting order is the "preference list" for this Application when it is choosing clusters. This is called the preference list because it is the order in which clusters will be selected for this Application. All other scheduling concerns (unschedulable, capability, capacity) just _mask_ this initial list by skipping over entries when requirements are not met. By using a good hash function and a key specific to this Application, we get distribution of Applications across clusters (load balancing). By making that key deterministic to the Cluster and Application names, we can be sure that this Application will continue to be scheduled to the same set of clusters from Release to Release. Furthermore, we ensure that any addition or removal of clusters has minimal impact on the overall set of clusters this Application resides on. Finally, this approach provides the possibility to raise or lower clusters in the preference list by weighting them, which is a valuable tool for managing capacity or incrementally phasing out clusters. This is Highest Random Weight Hashing, also known as Rendezvous hashing: https://en.wikipedia.org/wiki/Rendezvous_hashing. By transforming the hash value using a weight, it becomes an implementation of weighted rendezvous hashing, per http://www.snia.org/sites/default/files/SDC15_presentations/dist_sys/Jason_Resch_New_Consistent_Hashings_Rev.pdf. The weight enables system operators to tune the position of a cluster in the preflist. A high enough value will ensure that all Applications try the cluster first, while 0 will put the cluster at the end of the preflist. */ scoredClusters := make([]scoredCluster, 0, len(clusterList)) for _, cluster := range clusterList { var clusterIdentity string if cluster.Spec.Scheduler.Identity == nil { clusterIdentity = cluster.Name } else { clusterIdentity = *cluster.Spec.Scheduler.Identity } var weight int32 if cluster.Spec.Scheduler.Weight == nil { weight = defaultClusterWeight } else { weight = *cluster.Spec.Scheduler.Weight } hash := xxhash.New() hash.Write([]byte(appIdentity)) hash.Write([]byte(clusterIdentity)) sum := hash.Sum64() score := float64(-weight) * math.Log(float64(sum)/float64(math.MaxUint64)) // Decorate. scoredClusters = append(scoredClusters, scoredCluster{cluster: cluster, score: score}) } // Descending sort so highest scores are first (as you'd expect from higher // weight). sort.Slice(scoredClusters, func(i, j int) bool { return scoredClusters[j].score < scoredClusters[i].score }) // Undecorate. prefList := make([]*shipper.Cluster, 0, len(scoredClusters)) for _, scoredCluster := range scoredClusters { prefList = append(prefList, scoredCluster.cluster) } return prefList }
pkg/controller/release/weighted_preflist.go
0.617743
0.402128
weighted_preflist.go
starcoder
package period import ( "fmt" "io" "strings" "github.com/rickb777/plural" ) // Format converts the period to human-readable form using the default localisation. // Multiples of 7 days are shown as weeks. func (period Period) Format() string { return period.FormatWithPeriodNames(PeriodYearNames, PeriodMonthNames, PeriodWeekNames, PeriodDayNames, PeriodHourNames, PeriodMinuteNames, PeriodSecondNames) } // FormatWithoutWeeks converts the period to human-readable form using the default localisation. // Multiples of 7 days are not shown as weeks. func (period Period) FormatWithoutWeeks() string { return period.FormatWithPeriodNames(PeriodYearNames, PeriodMonthNames, plural.Plurals{}, PeriodDayNames, PeriodHourNames, PeriodMinuteNames, PeriodSecondNames) } // FormatWithPeriodNames converts the period to human-readable form in a localisable way. func (period Period) FormatWithPeriodNames(yearNames, monthNames, weekNames, dayNames, hourNames, minNames, secNames plural.Plurals) string { period = period.Abs() parts := make([]string, 0) parts = appendNonBlank(parts, yearNames.FormatFloat(float10(period.years))) parts = appendNonBlank(parts, monthNames.FormatFloat(float10(period.months))) if period.days > 0 || (period.IsZero()) { if len(weekNames) > 0 { weeks := period.days / 70 mdays := period.days % 70 //fmt.Printf("%v %#v - %d %d\n", period, period, weeks, mdays) if weeks > 0 { parts = appendNonBlank(parts, weekNames.FormatInt(int(weeks))) } if mdays > 0 || weeks == 0 { parts = appendNonBlank(parts, dayNames.FormatFloat(float10(mdays))) } } else { parts = appendNonBlank(parts, dayNames.FormatFloat(float10(period.days))) } } parts = appendNonBlank(parts, hourNames.FormatFloat(float10(period.hours))) parts = appendNonBlank(parts, minNames.FormatFloat(float10(period.minutes))) parts = appendNonBlank(parts, secNames.FormatFloat(float10(period.seconds))) return strings.Join(parts, ", ") } func appendNonBlank(parts []string, s string) []string { if s == "" { return parts } return append(parts, s) } // PeriodDayNames provides the English default format names for the days part of the period. // This is a sequence of plurals where the first match is used, otherwise the last one is used. // The last one must include a "%v" placeholder for the number. var PeriodDayNames = plural.FromZero("%v days", "%v day", "%v days") // PeriodWeekNames is as for PeriodDayNames but for weeks. var PeriodWeekNames = plural.FromZero("", "%v week", "%v weeks") // PeriodMonthNames is as for PeriodDayNames but for months. var PeriodMonthNames = plural.FromZero("", "%v month", "%v months") // PeriodYearNames is as for PeriodDayNames but for years. var PeriodYearNames = plural.FromZero("", "%v year", "%v years") // PeriodHourNames is as for PeriodDayNames but for hours. var PeriodHourNames = plural.FromZero("", "%v hour", "%v hours") // PeriodMinuteNames is as for PeriodDayNames but for minutes. var PeriodMinuteNames = plural.FromZero("", "%v minute", "%v minutes") // PeriodSecondNames is as for PeriodDayNames but for seconds. var PeriodSecondNames = plural.FromZero("", "%v second", "%v seconds") // String converts the period to ISO-8601 form. func (period Period) String() string { return period.toPeriod64("").String() } func (p64 period64) String() string { if p64 == (period64{}) { return "P0D" } buf := &strings.Builder{} if p64.neg { buf.WriteByte('-') } buf.WriteByte('P') writeField64(buf, p64.years, byte(Year)) writeField64(buf, p64.months, byte(Month)) if p64.days != 0 { if p64.days%70 == 0 { writeField64(buf, p64.days/7, byte(Week)) } else { writeField64(buf, p64.days, byte(Day)) } } if p64.hours != 0 || p64.minutes != 0 || p64.seconds != 0 { buf.WriteByte('T') } writeField64(buf, p64.hours, byte(Hour)) writeField64(buf, p64.minutes, byte(Minute)) writeField64(buf, p64.seconds, byte(Second)) return buf.String() } func writeField64(w io.Writer, field int64, designator byte) { if field != 0 { if field%10 != 0 { fmt.Fprintf(w, "%0.1f", float64(field)/10) } else { fmt.Fprintf(w, "%d", field/10) } w.(io.ByteWriter).WriteByte(designator) } } func float10(v int32) float32 { return float32(v) / 10 }
period/format.go
0.760117
0.517815
format.go
starcoder
package main import ( "bufio" "fmt" "log" "os" "regexp" "strconv" ) type Point struct { x, y, z int } func (p Point) AbsSum() int { return abs(p.x) + abs(p.y) + abs(p.z) } func (p Point) ScaleUp(p0 Point) Point { return Point{ x: p.x + p0.x, y: p.y + p0.y, z: p.z + p0.z, } } func (p Point) ScaleDown(p0 Point) Point { return Point{ x: p.x - p0.x, y: p.y - p0.y, z: p.z - p0.z, } } func (p Point) motionDirection() Point { return Point{ x: dir(p.x), y: dir(p.y), z: dir(p.z), } } type Moon struct { pos, vel Point } func main() { if len(os.Args) < 2 { log.Fatal(` [ERROR]: Provide the input dataset! **Usage: ./main /path/to/file `) } StoInt := func(s string) int { n, err := strconv.Atoi(s) if err != nil { log.Fatal(err) } return n } file, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } scanner := bufio.NewScanner(file) var lines []string for scanner.Scan() { lines = append(lines, scanner.Text()) } file.Close() pattern := regexp.MustCompile(`^<x=(-?\d+), y=(-?\d+), z=(-?\d+)>$`) var moonsData []Moon for _, line := range lines { axes := pattern.FindStringSubmatch(line) x, y, z := StoInt(axes[1]), StoInt(axes[2]), StoInt(axes[3]) moon := Moon{ pos: Point{x, y, z}, vel: Point{0, 0, 0}, } moonsData = append(moonsData, moon) } c1, c2 := make(chan int, 1), make(chan int, 1) go totalEnergy(moonsData, c1) go inspectForSameState(moonsData, c2) fmt.Println("Total energy of the system after 1000 steps:", <-c1) fmt.Printf("History repeated after %d steps!\n", <-c2) } func totalEnergy(moonsData []Moon, c1 chan<- int) { moons := make([]Moon, len(moonsData)) copy(moons, moonsData) for step := 0; step < 1000; step++ { simulateMoons(moons) } var total, pot, kin int = 0, 0, 0 for _, moon := range moons { pot, kin = moon.pos.AbsSum(), moon.vel.AbsSum() total += pot * kin } c1 <- total } func inspectForSameState(moonsData []Moon, c2 chan<- int) { moons := make([]Moon, len(moonsData)) copy(moons, moonsData) var xs, ys, zs int = 0, 0, 0 var repeatedState bool = false for steps := 1; xs == 0 || ys == 0 || zs == 0; steps++ { simulateMoons(moons) if xs == 0 { repeatedState = true for i, moon := range moons { if moon.pos.x != moonsData[i].pos.x || moon.vel.x != moonsData[i].vel.x { repeatedState = false; break } } if repeatedState { xs = steps } } if ys == 0 { repeatedState = true for i, moon := range moons { if moon.pos.y != moonsData[i].pos.y || moon.vel.y != moonsData[i].vel.y { repeatedState = false; break } } if repeatedState { ys = steps } } if zs == 0 { repeatedState = true for i, moon := range moons { if moon.pos.z != moonsData[i].pos.z || moon.vel.z != moonsData[i].vel.z { repeatedState = false; break } } if repeatedState { zs = steps } } } c2 <- lcm(lcm(xs, ys), zs) } func simulateMoons(moons []Moon) { for i, m1 := range moons { for _, m2 := range moons { if m1 == m2 { continue } m1.vel = m1.vel.ScaleUp(m2.pos.ScaleDown(m1.pos).motionDirection()) } moons[i] = m1 } for i, moon := range moons { moons[i].pos = moon.pos.ScaleUp(moon.vel) } } func abs(n int) int { if n < 0 { return -n } return n } func dir(n int) int { if n < 0 { return -1 } if n > 0 { return 1 } return 0 } func gcd(n1, n2 int) int { for n2 != 0 { n1, n2 = n2, n1 % n2 } return n1 } func lcm(n1, n2 int) int { return n1 / gcd(n1, n2) * n2 }
2019/Day-12/The_N-Body_Problem/main.go
0.639849
0.443902
main.go
starcoder
package money import ( "strings" ) // Currency represents money currency information required for formatting type Currency struct { Code string Fraction int Grapheme string Template string Decimal string Thousand string } // currencies represents a collection of currency var currencies = map[string]*Currency{ "AED": {Decimal: ".", Thousand: ",", Code: "AED", Fraction: 2, Grapheme: ".\u062f.\u0625", Template: "1 $"}, "AFN": {Decimal: ".", Thousand: ",", Code: "AFN", Fraction: 2, Grapheme: "\u060b", Template: "1 $"}, "ALL": {Decimal: ".", Thousand: ",", Code: "ALL", Fraction: 2, Grapheme: "L", Template: "$1"}, "AMD": {Decimal: ".", Thousand: ",", Code: "AMD", Fraction: 2, Grapheme: "\u0564\u0580.", Template: "1 $"}, "ANG": {Decimal: ".", Thousand: ",", Code: "ANG", Fraction: 2, Grapheme: "\u0192", Template: "$1"}, "ARS": {Decimal: ".", Thousand: ",", Code: "ARS", Fraction: 2, Grapheme: "$", Template: "$1"}, "AUD": {Decimal: ".", Thousand: ",", Code: "AUD", Fraction: 2, Grapheme: "$", Template: "$1"}, "AWG": {Decimal: ".", Thousand: ",", Code: "AWG", Fraction: 2, Grapheme: "\u0192", Template: "$1"}, "AZN": {Decimal: ".", Thousand: ",", Code: "AZN", Fraction: 2, Grapheme: "\u20bc", Template: "$1"}, "BAM": {Decimal: ".", Thousand: ",", Code: "BAM", Fraction: 2, Grapheme: "KM", Template: "$1"}, "BBD": {Decimal: ".", Thousand: ",", Code: "BBD", Fraction: 2, Grapheme: "$", Template: "$1"}, "BGN": {Decimal: ".", Thousand: ",", Code: "BGN", Fraction: 2, Grapheme: "\u043b\u0432", Template: "$1"}, "BHD": {Decimal: ".", Thousand: ",", Code: "BHD", Fraction: 3, Grapheme: ".\u062f.\u0628", Template: "1 $"}, "BMD": {Decimal: ".", Thousand: ",", Code: "BMD", Fraction: 2, Grapheme: "$", Template: "$1"}, "BND": {Decimal: ".", Thousand: ",", Code: "BND", Fraction: 2, Grapheme: "$", Template: "$1"}, "BOB": {Decimal: ".", Thousand: ",", Code: "BOB", Fraction: 2, Grapheme: "Bs.", Template: "$1"}, "BRL": {Decimal: ".", Thousand: ",", Code: "BRL", Fraction: 2, Grapheme: "R$", Template: "$1"}, "BSD": {Decimal: ".", Thousand: ",", Code: "BSD", Fraction: 2, Grapheme: "$", Template: "$1"}, "BWP": {Decimal: ".", Thousand: ",", Code: "BWP", Fraction: 2, Grapheme: "P", Template: "$1"}, "BYN": {Decimal: ".", Thousand: ",", Code: "BYN", Fraction: 2, Grapheme: "p.", Template: "1 $"}, "BYR": {Decimal: ".", Thousand: ",", Code: "BYR", Fraction: 0, Grapheme: "p.", Template: "1 $"}, "BZD": {Decimal: ".", Thousand: ",", Code: "BZD", Fraction: 2, Grapheme: "BZ$", Template: "$1"}, "CAD": {Decimal: ".", Thousand: ",", Code: "CAD", Fraction: 2, Grapheme: "$", Template: "$1"}, "CLP": {Decimal: ".", Thousand: ",", Code: "CLP", Fraction: 0, Grapheme: "$", Template: "$1"}, "CNY": {Decimal: ".", Thousand: ",", Code: "CNY", Fraction: 2, Grapheme: "\u5143", Template: "1 $"}, "COP": {Decimal: ".", Thousand: ",", Code: "COP", Fraction: 0, Grapheme: "$", Template: "$1"}, "CRC": {Decimal: ".", Thousand: ",", Code: "CRC", Fraction: 2, Grapheme: "\u20a1", Template: "$1"}, "CUP": {Decimal: ".", Thousand: ",", Code: "CUP", Fraction: 2, Grapheme: "$MN", Template: "$1"}, "CZK": {Decimal: ".", Thousand: ",", Code: "CZK", Fraction: 2, Grapheme: "K\u010d", Template: "1 $"}, "DKK": {Decimal: ".", Thousand: ",", Code: "DKK", Fraction: 2, Grapheme: "kr", Template: "1 $"}, "DOP": {Decimal: ".", Thousand: ",", Code: "DOP", Fraction: 2, Grapheme: "RD$", Template: "$1"}, "DZD": {Decimal: ".", Thousand: ",", Code: "DZD", Fraction: 2, Grapheme: ".\u062f.\u062c", Template: "1 $"}, "EEK": {Decimal: ".", Thousand: ",", Code: "EEK", Fraction: 2, Grapheme: "kr", Template: "$1"}, "EGP": {Decimal: ".", Thousand: ",", Code: "EGP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "EUR": {Decimal: ".", Thousand: ",", Code: "EUR", Fraction: 2, Grapheme: "\u20ac", Template: "$1"}, "FJD": {Decimal: ".", Thousand: ",", Code: "FJD", Fraction: 2, Grapheme: "$", Template: "$1"}, "FKP": {Decimal: ".", Thousand: ",", Code: "FKP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "GBP": {Decimal: ".", Thousand: ",", Code: "GBP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "GGP": {Decimal: ".", Thousand: ",", Code: "GGP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "GHC": {Decimal: ".", Thousand: ",", Code: "GHC", Fraction: 2, Grapheme: "\u00a2", Template: "$1"}, "GIP": {Decimal: ".", Thousand: ",", Code: "GIP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "GTQ": {Decimal: ".", Thousand: ",", Code: "GTQ", Fraction: 2, Grapheme: "Q", Template: "$1"}, "GYD": {Decimal: ".", Thousand: ",", Code: "GYD", Fraction: 2, Grapheme: "$", Template: "$1"}, "HKD": {Decimal: ".", Thousand: ",", Code: "HKD", Fraction: 2, Grapheme: "$", Template: "$1"}, "HNL": {Decimal: ".", Thousand: ",", Code: "HNL", Fraction: 2, Grapheme: "L", Template: "$1"}, "HRK": {Decimal: ".", Thousand: ",", Code: "HRK", Fraction: 2, Grapheme: "kn", Template: "$1"}, "HUF": {Decimal: ".", Thousand: ",", Code: "HUF", Fraction: 0, Grapheme: "Ft", Template: "$1"}, "IDR": {Decimal: ".", Thousand: ",", Code: "IDR", Fraction: 2, Grapheme: "Rp", Template: "$1"}, "ILS": {Decimal: ".", Thousand: ",", Code: "ILS", Fraction: 2, Grapheme: "\u20aa", Template: "$1"}, "IMP": {Decimal: ".", Thousand: ",", Code: "IMP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "INR": {Decimal: ".", Thousand: ",", Code: "INR", Fraction: 2, Grapheme: "\u20b9", Template: "$1"}, "IQD": {Decimal: ".", Thousand: ",", Code: "IQD", Fraction: 3, Grapheme: ".\u062f.\u0639", Template: "1 $"}, "IRR": {Decimal: ".", Thousand: ",", Code: "IRR", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"}, "ISK": {Decimal: ".", Thousand: ",", Code: "ISK", Fraction: 2, Grapheme: "kr", Template: "$1"}, "JEP": {Decimal: ".", Thousand: ",", Code: "JEP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "JMD": {Decimal: ".", Thousand: ",", Code: "JMD", Fraction: 2, Grapheme: "J$", Template: "$1"}, "JOD": {Decimal: ".", Thousand: ",", Code: "JOD", Fraction: 3, Grapheme: ".\u062f.\u0625", Template: "1 $"}, "JPY": {Decimal: ".", Thousand: ",", Code: "JPY", Fraction: 0, Grapheme: "\u00a5", Template: "$1"}, "KES": {Decimal: ".", Thousand: ",", Code: "KES", Fraction: 2, Grapheme: "KSh", Template: "$1"}, "KGS": {Decimal: ".", Thousand: ",", Code: "KGS", Fraction: 2, Grapheme: "\u0441\u043e\u043c", Template: "$1"}, "KHR": {Decimal: ".", Thousand: ",", Code: "KHR", Fraction: 2, Grapheme: "\u17db", Template: "$1"}, "KPW": {Decimal: ".", Thousand: ",", Code: "KPW", Fraction: 0, Grapheme: "\u20a9", Template: "$1"}, "KRW": {Decimal: ".", Thousand: ",", Code: "KRW", Fraction: 0, Grapheme: "\u20a9", Template: "$1"}, "KWD": {Decimal: ".", Thousand: ",", Code: "KWD", Fraction: 3, Grapheme: ".\u062f.\u0643", Template: "1 $"}, "KYD": {Decimal: ".", Thousand: ",", Code: "KYD", Fraction: 2, Grapheme: "$", Template: "$1"}, "KZT": {Decimal: ".", Thousand: ",", Code: "KZT", Fraction: 2, Grapheme: "\u20b8", Template: "$1"}, "LAK": {Decimal: ".", Thousand: ",", Code: "LAK", Fraction: 2, Grapheme: "\u20ad", Template: "$1"}, "LBP": {Decimal: ".", Thousand: ",", Code: "LBP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "LKR": {Decimal: ".", Thousand: ",", Code: "LKR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"}, "LRD": {Decimal: ".", Thousand: ",", Code: "LRD", Fraction: 2, Grapheme: "$", Template: "$1"}, "LTL": {Decimal: ".", Thousand: ",", Code: "LTL", Fraction: 2, Grapheme: "Lt", Template: "$1"}, "LVL": {Decimal: ".", Thousand: ",", Code: "LVL", Fraction: 2, Grapheme: "Ls", Template: "1 $"}, "LYD": {Decimal: ".", Thousand: ",", Code: "LYD", Fraction: 3, Grapheme: ".\u062f.\u0644", Template: "1 $"}, "MAD": {Decimal: ".", Thousand: ",", Code: "MAD", Fraction: 2, Grapheme: ".\u062f.\u0645", Template: "1 $"}, "MKD": {Decimal: ".", Thousand: ",", Code: "MKD", Fraction: 2, Grapheme: "\u0434\u0435\u043d", Template: "$1"}, "MNT": {Decimal: ".", Thousand: ",", Code: "MNT", Fraction: 2, Grapheme: "\u20ae", Template: "$1"}, "MUR": {Decimal: ".", Thousand: ",", Code: "MUR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"}, "MXN": {Decimal: ".", Thousand: ",", Code: "MXN", Fraction: 2, Grapheme: "$", Template: "$1"}, "MWK": {Decimal: ".", Thousand: ",", Code: "MWK", Fraction: 2, Grapheme: "MK", Template: "$1"}, "MYR": {Decimal: ".", Thousand: ",", Code: "MYR", Fraction: 2, Grapheme: "RM", Template: "$1"}, "MZN": {Decimal: ".", Thousand: ",", Code: "MZN", Fraction: 2, Grapheme: "MT", Template: "$1"}, "NAD": {Decimal: ".", Thousand: ",", Code: "NAD", Fraction: 2, Grapheme: "$", Template: "$1"}, "NGN": {Decimal: ".", Thousand: ",", Code: "NGN", Fraction: 2, Grapheme: "\u20a6", Template: "$1"}, "NIO": {Decimal: ".", Thousand: ",", Code: "NIO", Fraction: 2, Grapheme: "C$", Template: "$1"}, "NOK": {Decimal: ".", Thousand: ",", Code: "NOK", Fraction: 2, Grapheme: "kr", Template: "1 $"}, "NPR": {Decimal: ".", Thousand: ",", Code: "NPR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"}, "NZD": {Decimal: ".", Thousand: ",", Code: "NZD", Fraction: 2, Grapheme: "$", Template: "$1"}, "OMR": {Decimal: ".", Thousand: ",", Code: "OMR", Fraction: 3, Grapheme: "\ufdfc", Template: "1 $"}, "PAB": {Decimal: ".", Thousand: ",", Code: "PAB", Fraction: 2, Grapheme: "B/.", Template: "$1"}, "PEN": {Decimal: ".", Thousand: ",", Code: "PEN", Fraction: 2, Grapheme: "S/", Template: "$1"}, "PHP": {Decimal: ".", Thousand: ",", Code: "PHP", Fraction: 2, Grapheme: "\u20b1", Template: "$1"}, "PKR": {Decimal: ".", Thousand: ",", Code: "PKR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"}, "PLN": {Decimal: ".", Thousand: ",", Code: "PLN", Fraction: 2, Grapheme: "z\u0142", Template: "1 $"}, "PYG": {Decimal: ".", Thousand: ",", Code: "PYG", Fraction: 0, Grapheme: "Gs", Template: "1$"}, "QAR": {Decimal: ".", Thousand: ",", Code: "QAR", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"}, "RON": {Decimal: ".", Thousand: ",", Code: "RON", Fraction: 2, Grapheme: "lei", Template: "$1"}, "RSD": {Decimal: ".", Thousand: ",", Code: "RSD", Fraction: 2, Grapheme: "\u0414\u0438\u043d.", Template: "$1"}, "RUB": {Decimal: ".", Thousand: ",", Code: "RUB", Fraction: 2, Grapheme: "\u20bd", Template: "1 $"}, "RUR": {Decimal: ".", Thousand: ",", Code: "RUR", Fraction: 2, Grapheme: "\u20bd", Template: "1 $"}, "SAR": {Decimal: ".", Thousand: ",", Code: "SAR", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"}, "SBD": {Decimal: ".", Thousand: ",", Code: "SBD", Fraction: 2, Grapheme: "$", Template: "$1"}, "SCR": {Decimal: ".", Thousand: ",", Code: "SCR", Fraction: 2, Grapheme: "\u20a8", Template: "$1"}, "SEK": {Decimal: ".", Thousand: ",", Code: "SEK", Fraction: 2, Grapheme: "kr", Template: "1 $"}, "SGD": {Decimal: ".", Thousand: ",", Code: "SGD", Fraction: 2, Grapheme: "$", Template: "$1"}, "SHP": {Decimal: ".", Thousand: ",", Code: "SHP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "SOS": {Decimal: ".", Thousand: ",", Code: "SOS", Fraction: 2, Grapheme: "S", Template: "$1"}, "SRD": {Decimal: ".", Thousand: ",", Code: "SRD", Fraction: 2, Grapheme: "$", Template: "$1"}, "SVC": {Decimal: ".", Thousand: ",", Code: "SVC", Fraction: 2, Grapheme: "$", Template: "$1"}, "SYP": {Decimal: ".", Thousand: ",", Code: "SYP", Fraction: 2, Grapheme: "\u00a3", Template: "$1"}, "THB": {Decimal: ".", Thousand: ",", Code: "THB", Fraction: 2, Grapheme: "\u0e3f", Template: "$1"}, "TND": {Decimal: ".", Thousand: ",", Code: "TND", Fraction: 3, Grapheme: ".\u062f.\u062a", Template: "1 $"}, "TRL": {Decimal: ".", Thousand: ",", Code: "TRL", Fraction: 2, Grapheme: "\u20a4", Template: "$1"}, "TRY": {Decimal: ".", Thousand: ",", Code: "TRY", Fraction: 2, Grapheme: "\u20ba", Template: "$1"}, "TTD": {Decimal: ".", Thousand: ",", Code: "TTD", Fraction: 2, Grapheme: "TT$", Template: "$1"}, "TWD": {Decimal: ".", Thousand: ",", Code: "TWD", Fraction: 0, Grapheme: "NT$", Template: "$1"}, "TZS": {Decimal: ".", Thousand: ",", Code: "TZS", Fraction: 0, Grapheme: "TSh", Template: "$1"}, "UAH": {Decimal: ".", Thousand: ",", Code: "UAH", Fraction: 2, Grapheme: "\u20b4", Template: "$1"}, "UGX": {Decimal: ".", Thousand: ",", Code: "UGX", Fraction: 0, Grapheme: "USh", Template: "$1"}, "USD": {Decimal: ".", Thousand: ",", Code: "USD", Fraction: 2, Grapheme: "$", Template: "$1"}, "UYU": {Decimal: ".", Thousand: ",", Code: "UYU", Fraction: 0, Grapheme: "$U", Template: "$1"}, "UZS": {Decimal: ".", Thousand: ",", Code: "UZS", Fraction: 2, Grapheme: "so\u2019m", Template: "$1"}, "VEF": {Decimal: ".", Thousand: ",", Code: "VEF", Fraction: 2, Grapheme: "Bs", Template: "$1"}, "VND": {Decimal: ".", Thousand: ",", Code: "VND", Fraction: 0, Grapheme: "\u20ab", Template: "1 $"}, "XCD": {Decimal: ".", Thousand: ",", Code: "XCD", Fraction: 2, Grapheme: "$", Template: "$1"}, "YER": {Decimal: ".", Thousand: ",", Code: "YER", Fraction: 2, Grapheme: "\ufdfc", Template: "1 $"}, "ZAR": {Decimal: ".", Thousand: ",", Code: "ZAR", Fraction: 2, Grapheme: "R", Template: "$1"}, "ZMW": {Decimal: ".", Thousand: ",", Code: "ZMW", Fraction: 2, Grapheme: "ZK", Template: "$1"}, "ZWD": {Decimal: ".", Thousand: ",", Code: "ZWD", Fraction: 2, Grapheme: "Z$", Template: "$1"}, } // AddCurrency lets you insert or update currency in currencies list func AddCurrency(Code, Grapheme, Template, Decimal, Thousand string, Fraction int) *Currency { currencies[Code] = &Currency{ Code: Code, Grapheme: Grapheme, Template: Template, Decimal: Decimal, Thousand: Thousand, Fraction: Fraction, } return currencies[Code] } func newCurrency(code string) *Currency { return &Currency{Code: strings.ToUpper(code)} } // GetCurrency returns the currency given the code. func GetCurrency(code string) *Currency { return currencies[code] } // Formatter returns currency formatter representing // used currency structure func (c *Currency) Formatter() *Formatter { return &Formatter{ Fraction: c.Fraction, Decimal: c.Decimal, Thousand: c.Thousand, Grapheme: c.Grapheme, Template: c.Template, } } // getDefault represent default currency if currency is not found in currencies list. // Grapheme and Code fields will be changed by currency code func (c *Currency) getDefault() *Currency { return &Currency{Decimal: ".", Thousand: ",", Code: c.Code, Fraction: 2, Grapheme: c.Code, Template: "1$"} } // get extended currency using currencies list func (c *Currency) get() *Currency { if curr, ok := currencies[c.Code]; ok { return curr } return c.getDefault() } func (c *Currency) equals(oc *Currency) bool { return c.Code == oc.Code }
currency.go
0.504639
0.416915
currency.go
starcoder
package main func Frontend() *Container { return &Container{ Name: "frontend", Title: "Frontend", Description: "Serves all end-user browser and API requests.", Groups: []Group{ { Title: "Search at a glance", Rows: []Row{ { { Name: "99th_percentile_search_request_duration", Description: "99th percentile successful search request duration over 5m", Query: `histogram_quantile(0.99, sum by (le)(rate(src_graphql_field_seconds_bucket{type="Search",field="results",error="false",source="browser",name!="CodeIntelSearch"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, // See https://github.com/sourcegraph/sourcegraph/issues/9834 Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("duration").Unit(Seconds), PossibleSolutions: ` - **Get details on the exact queries that are slow** by configuring '"observability.logSlowSearches": 20,' in the site configuration and looking for 'frontend' warning logs prefixed with 'slow search request' for additional details. - **Check that most repositories are indexed** by visiting https://sourcegraph.example.com/site-admin/repositories?filter=needs-index (it should show few or no results.) - **Kubernetes:** Check CPU usage of zoekt-webserver in the indexed-search pod, consider increasing CPU limits in the 'indexed-search.Deployment.yaml' if regularly hitting max CPU utilization. - **Docker Compose:** Check CPU usage on the Zoekt Web Server dashboard, consider increasing 'cpus:' of the zoekt-webserver container in 'docker-compose.yml' if regularly hitting max CPU utilization. `, }, { Name: "90th_percentile_search_request_duration", Description: "90th percentile successful search request duration over 5m", Query: `histogram_quantile(0.90, sum by (le)(rate(src_graphql_field_seconds_bucket{type="Search",field="results",error="false",source="browser",name!="CodeIntelSearch"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, // See https://github.com/sourcegraph/sourcegraph/issues/9834 Warning: Alert{GreaterOrEqual: 15}, PanelOptions: PanelOptions().LegendFormat("duration").Unit(Seconds), PossibleSolutions: ` - **Get details on the exact queries that are slow** by configuring '"observability.logSlowSearches": 15,' in the site configuration and looking for 'frontend' warning logs prefixed with 'slow search request' for additional details. - **Check that most repositories are indexed** by visiting https://sourcegraph.example.com/site-admin/repositories?filter=needs-index (it should show few or no results.) - **Kubernetes:** Check CPU usage of zoekt-webserver in the indexed-search pod, consider increasing CPU limits in the 'indexed-search.Deployment.yaml' if regularly hitting max CPU utilization. - **Docker Compose:** Check CPU usage on the Zoekt Web Server dashboard, consider increasing 'cpus:' of the zoekt-webserver container in 'docker-compose.yml' if regularly hitting max CPU utilization. `, }, }, { { Name: "hard_timeout_search_responses", Description: "hard timeout search responses every 5m", Query: `sum(sum by (status)(increase(src_graphql_search_response{status="timeout",source="browser",name!="CodeIntelSearch"}[5m]))) + sum(sum by (status, alert_type)(increase(src_graphql_search_response{status="alert",alert_type="timed_out",source="browser",name!="CodeIntelSearch"}[5m])))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, Critical: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("hard timeout"), PossibleSolutions: "none", }, { Name: "hard_error_search_responses", Description: "hard error search responses every 5m", Query: `sum by (status)(increase(src_graphql_search_response{status=~"error",source="browser",name!="CodeIntelSearch"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, Critical: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("hard error"), PossibleSolutions: "none", }, { Name: "partial_timeout_search_responses", Description: "partial timeout search responses every 5m", Query: `sum by (status)(increase(src_graphql_search_response{status="partial_timeout",source="browser",name!="CodeIntelSearch"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, PanelOptions: PanelOptions().LegendFormat("partial timeout"), PossibleSolutions: "none", }, { Name: "search_alert_user_suggestions", Description: "search alert user suggestions shown every 5m", Query: `sum by (alert_type)(increase(src_graphql_search_response{status="alert",alert_type!~"timed_out",source="browser",name!="CodeIntelSearch"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 50}, PanelOptions: PanelOptions().LegendFormat("{{alert_type}}"), PossibleSolutions: ` - This indicates your user's are making syntax errors or similar user errors. `, }, }, }, }, { Title: "Search-based code intelligence at a glance", Hidden: true, Rows: []Row{ { { Name: "99th_percentile_search_codeintel_request_duration", Description: "99th percentile code-intel successful search request duration over 5m", Query: `histogram_quantile(0.99, sum by (le)(rate(src_graphql_field_seconds_bucket{type="Search",field="results",error="false",source="browser",request_name="CodeIntelSearch"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, // See https://github.com/sourcegraph/sourcegraph/issues/9834 Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("duration").Unit(Seconds), PossibleSolutions: ` - **Get details on the exact queries that are slow** by configuring '"observability.logSlowSearches": 20,' in the site configuration and looking for 'frontend' warning logs prefixed with 'slow search request' for additional details. - **Check that most repositories are indexed** by visiting https://sourcegraph.example.com/site-admin/repositories?filter=needs-index (it should show few or no results.) - **Kubernetes:** Check CPU usage of zoekt-webserver in the indexed-search pod, consider increasing CPU limits in the 'indexed-search.Deployment.yaml' if regularly hitting max CPU utilization. - **Docker Compose:** Check CPU usage on the Zoekt Web Server dashboard, consider increasing 'cpus:' of the zoekt-webserver container in 'docker-compose.yml' if regularly hitting max CPU utilization. `, }, { Name: "90th_percentile_search_codeintel_request_duration", Description: "90th percentile code-intel successful search request duration over 5m", Query: `histogram_quantile(0.90, sum by (le)(rate(src_graphql_field_seconds_bucket{type="Search",field="results",error="false",source="browser",request_name="CodeIntelSearch"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, // See https://github.com/sourcegraph/sourcegraph/issues/9834 Warning: Alert{GreaterOrEqual: 15}, PanelOptions: PanelOptions().LegendFormat("duration").Unit(Seconds), PossibleSolutions: ` - **Get details on the exact queries that are slow** by configuring '"observability.logSlowSearches": 15,' in the site configuration and looking for 'frontend' warning logs prefixed with 'slow search request' for additional details. - **Check that most repositories are indexed** by visiting https://sourcegraph.example.com/site-admin/repositories?filter=needs-index (it should show few or no results.) - **Kubernetes:** Check CPU usage of zoekt-webserver in the indexed-search pod, consider increasing CPU limits in the 'indexed-search.Deployment.yaml' if regularly hitting max CPU utilization. - **Docker Compose:** Check CPU usage on the Zoekt Web Server dashboard, consider increasing 'cpus:' of the zoekt-webserver container in 'docker-compose.yml' if regularly hitting max CPU utilization. `, }, }, { { Name: "hard_timeout_search_codeintel_responses", Description: "hard timeout search code-intel responses every 5m", Query: `sum(sum by (status)(increase(src_graphql_search_response{status="timeout",source="browser",request_name="CodeIntelSearch"}[5m]))) + sum(sum by (status, alert_type)(increase(src_graphql_search_response{status="alert",alert_type="timed_out",source="browser",request_name="CodeIntelSearch"}[5m])))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, Critical: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("hard timeout"), PossibleSolutions: "none", }, { Name: "hard_error_search_codeintel_responses", Description: "hard error search code-intel responses every 5m", Query: `sum by (status)(increase(src_graphql_search_response{status=~"error",source="browser",request_name="CodeIntelSearch"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, Critical: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("hard error"), PossibleSolutions: "none", }, { Name: "partial_timeout_search_codeintel_responses", Description: "partial timeout search code-intel responses every 5m", Query: `sum by (status)(increase(src_graphql_search_response{status="partial_timeout",source="browser",request_name="CodeIntelSearch"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, PanelOptions: PanelOptions().LegendFormat("partial timeout"), PossibleSolutions: "none", }, { Name: "search_codeintel_alert_user_suggestions", Description: "search code-intel alert user suggestions shown every 5m", Query: `sum by (alert_type)(increase(src_graphql_search_response{status="alert",alert_type!~"timed_out",source="browser",request_name="CodeIntelSearch"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 50}, PanelOptions: PanelOptions().LegendFormat("{{alert_type}}"), PossibleSolutions: ` - This indicates a bug in Sourcegraph, please [open an issue](https://github.com/sourcegraph/sourcegraph/issues/new/choose). `, }, }, }, }, { Title: "Search API usage at a glance", Hidden: true, Rows: []Row{ { { Name: "99th_percentile_search_api_request_duration", Description: "99th percentile successful search API request duration over 5m", Query: `histogram_quantile(0.99, sum by (le)(rate(src_graphql_field_seconds_bucket{type="Search",field="results",error="false",source="other"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, // See https://github.com/sourcegraph/sourcegraph/issues/9834 Warning: Alert{GreaterOrEqual: 50}, PanelOptions: PanelOptions().LegendFormat("duration").Unit(Seconds), PossibleSolutions: ` - **Get details on the exact queries that are slow** by configuring '"observability.logSlowSearches": 20,' in the site configuration and looking for 'frontend' warning logs prefixed with 'slow search request' for additional details. - **If your users are requesting many results** with a large 'count:' parameter, consider using our [search pagination API](../../api/graphql/search.md). - **Check that most repositories are indexed** by visiting https://sourcegraph.example.com/site-admin/repositories?filter=needs-index (it should show few or no results.) - **Kubernetes:** Check CPU usage of zoekt-webserver in the indexed-search pod, consider increasing CPU limits in the 'indexed-search.Deployment.yaml' if regularly hitting max CPU utilization. - **Docker Compose:** Check CPU usage on the Zoekt Web Server dashboard, consider increasing 'cpus:' of the zoekt-webserver container in 'docker-compose.yml' if regularly hitting max CPU utilization. `, }, { Name: "90th_percentile_search_api_request_duration", Description: "90th percentile successful search API request duration over 5m", Query: `histogram_quantile(0.90, sum by (le)(rate(src_graphql_field_seconds_bucket{type="Search",field="results",error="false",source="other"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, // See https://github.com/sourcegraph/sourcegraph/issues/9834 Warning: Alert{GreaterOrEqual: 40}, PanelOptions: PanelOptions().LegendFormat("duration").Unit(Seconds), PossibleSolutions: ` - **Get details on the exact queries that are slow** by configuring '"observability.logSlowSearches": 15,' in the site configuration and looking for 'frontend' warning logs prefixed with 'slow search request' for additional details. - **If your users are requesting many results** with a large 'count:' parameter, consider using our [search pagination API](../../api/graphql/search.md). - **Check that most repositories are indexed** by visiting https://sourcegraph.example.com/site-admin/repositories?filter=needs-index (it should show few or no results.) - **Kubernetes:** Check CPU usage of zoekt-webserver in the indexed-search pod, consider increasing CPU limits in the 'indexed-search.Deployment.yaml' if regularly hitting max CPU utilization. - **Docker Compose:** Check CPU usage on the Zoekt Web Server dashboard, consider increasing 'cpus:' of the zoekt-webserver container in 'docker-compose.yml' if regularly hitting max CPU utilization. `, }, }, { { Name: "hard_timeout_search_api_responses", Description: "hard timeout search API responses every 5m", Query: `sum(sum by (status)(increase(src_graphql_search_response{status="timeout",source="other"}[5m]))) + sum(sum by (status, alert_type)(increase(src_graphql_search_response{status="alert",alert_type="timed_out",source="other"}[5m])))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, Critical: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("hard timeout"), PossibleSolutions: "none", }, { Name: "hard_error_search_api_responses", Description: "hard error search API responses every 5m", Query: `sum by (status)(increase(src_graphql_search_response{status=~"error",source="other"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, Critical: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("hard error"), PossibleSolutions: "none", }, { Name: "partial_timeout_search_api_responses", Description: "partial timeout search API responses every 5m", Query: `sum by (status)(increase(src_graphql_search_response{status="partial_timeout",source="other"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, PanelOptions: PanelOptions().LegendFormat("partial timeout"), PossibleSolutions: "none", }, { Name: "search_api_alert_user_suggestions", Description: "search API alert user suggestions shown every 5m", Query: `sum by (alert_type)(increase(src_graphql_search_response{status="alert",alert_type!~"timed_out",source="other"}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 50}, PanelOptions: PanelOptions().LegendFormat("{{alert_type}}"), PossibleSolutions: ` - This indicates your user's search API requests have syntax errors or a similar user error. Check the responses the API sends back for an explanation. `, }, }, }, }, { Title: "Precise code intel usage at a glance", Hidden: true, Rows: []Row{ { { Name: "99th_percentile_precise_code_intel_api_duration", Description: "99th percentile successful precise code intel api query duration over 5m", // TODO(efritz) - ensure these exclude error durations Query: `histogram_quantile(0.99, sum by (le)(rate(src_code_intel_api_duration_seconds_bucket[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("api operation").Unit(Seconds), PossibleSolutions: "none", }, { Name: "precise_code_intel_api_errors", Description: "precise code intel api errors every 5m", Query: `increase(src_code_intel_api_errors_total[5m])`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("api operation"), PossibleSolutions: "none", }, }, { { Name: "99th_percentile_precise_code_intel_db_duration", Description: "99th percentile successful precise code intel database query duration over 5m", // TODO(efritz) - ensure these exclude error durations Query: `histogram_quantile(0.99, sum by (le)(rate(src_code_intel_db_duration_seconds_bucket{job="frontend"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("db operation").Unit(Seconds), PossibleSolutions: "none", }, { Name: "precise_code_intel_db_errors", Description: "precise code intel database errors every 5m", Query: `increase(src_code_intel_db_errors_total{job="frontend"}[5m])`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("db operation"), PossibleSolutions: "none", }, }, }, }, { Title: "Internal service requests", Hidden: true, Rows: []Row{ { { Name: "internal_indexed_search_error_responses", Description: "internal indexed search error responses every 5m", Query: `sum by (code)(increase(src_zoekt_request_duration_seconds_count{code!~"2.."}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, PanelOptions: PanelOptions().LegendFormat("{{code}}"), PossibleSolutions: ` - Check the Zoekt Web Server dashboard for indications it might be unhealthy. `, }, { Name: "internal_unindexed_search_error_responses", Description: "internal unindexed search error responses every 5m", Query: `sum by (code)(increase(searcher_service_request_total{code!~"2.."}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, PanelOptions: PanelOptions().LegendFormat("{{code}}"), PossibleSolutions: ` - Check the Searcher dashboard for indications it might be unhealthy. `, }, { Name: "internal_api_error_responses", Description: "internal API error responses every 5m by route", Query: `sum by (category)(increase(src_frontend_internal_request_duration_seconds_count{code!~"2.."}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 25}, PanelOptions: PanelOptions().LegendFormat("{{category}}"), PossibleSolutions: ` - May not be a substantial issue, check the 'frontend' logs for potential causes. `, }, }, { { Name: "99th_percentile_precise_code_intel_bundle_manager_query_duration", Description: "99th percentile successful precise-code-intel-bundle-manager query duration over 5m", Query: `histogram_quantile(0.99, sum by (le,category)(rate(src_precise_code_intel_bundle_manager_request_duration_seconds_bucket{job="frontend",category!="transfer"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("{{category}}").Unit(Seconds), PossibleSolutions: "none", }, { Name: "99th_percentile_precise_code_intel_bundle_manager_transfer_duration", Description: "99th percentile successful precise-code-intel-bundle-manager data transfer duration over 5m", Query: `histogram_quantile(0.99, sum by (le,category)(rate(src_precise_code_intel_bundle_manager_request_duration_seconds_bucket{job="frontend",category="transfer"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, Warning: Alert{GreaterOrEqual: 300}, PanelOptions: PanelOptions().LegendFormat("{{category}}").Unit(Seconds), PossibleSolutions: "none", }, { Name: "precise_code_intel_bundle_manager_error_responses", Description: "precise-code-intel-bundle-manager error responses every 5m", Query: `sum by (category)(increase(src_precise_code_intel_bundle_manager_request_duration_seconds_count{job="frontend",code!~"2.."}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, PanelOptions: PanelOptions().LegendFormat("{{category}}"), PossibleSolutions: "none", }, }, { { Name: "99th_percentile_gitserver_duration", Description: "99th percentile successful gitserver query duration over 5m", Query: `histogram_quantile(0.99, sum by (le,category)(rate(src_gitserver_request_duration_seconds_bucket{job="frontend"}[5m])))`, DataMayNotExist: true, DataMayBeNaN: true, Warning: Alert{GreaterOrEqual: 20}, PanelOptions: PanelOptions().LegendFormat("{{category}}").Unit(Seconds), PossibleSolutions: "none", }, { Name: "gitserver_error_responses", Description: "gitserver error responses every 5m", Query: `sum by (category)(increase(src_gitserver_request_duration_seconds_count{job="frontend",code!~"2.."}[5m]))`, DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 5}, PanelOptions: PanelOptions().LegendFormat("{{category}}"), PossibleSolutions: "none", }, }, }, }, { Title: "Container monitoring (not available on server)", Hidden: true, Rows: []Row{ { sharedContainerRestarts("frontend"), sharedContainerMemoryUsage("frontend"), sharedContainerCPUUsage("frontend"), }, }, }, }, } }
monitoring/frontend.go
0.650134
0.4231
frontend.go
starcoder
package elevation import ( "fmt" "math" ) // Elevation stores a numeric coordinate referencing a celestial bodies Z axis. type Elevation float32 // Absolute returns the numeric value held by the Elevation pointer to an absolute number. func (elevation *Elevation) Absolute() float32 { return float32(math.Abs(float64(*elevation))) } // Correct returns a boolean that identifies whether the Elevation value does not exceed the accepted Elevation bounds. func (elevation *Elevation) Correct() bool { return (elevation.Value() >= Minimum) && (elevation.Value() <= Maximum) } // Float64 returns a the Elevation value as a 64 bit floating number. func (elevation *Elevation) Float64() float64 { return float64(*elevation) } // From returns a Elevation expressing the distance between to Elevation pointers, using the current Elevation as the subtraction. func (elevation *Elevation) From(l *Elevation) *Elevation { return NewElevation(l.Value() - elevation.Value()) } func (elevation *Elevation) Kilometers() *Elevation { return NewElevation(elevation.Value() * Kilometer) } // Max returns a new Elevation pointer containing the largest sum of the two Elevations. func (elevation *Elevation) Max(l *Elevation) *Elevation { return NewElevation(float32(math.Max(math.Abs(float64(*elevation)), math.Abs(float64(*l))))) } // Measurement returns the measurement unit used by the Elevation pointer. func (elevation *Elevation) Measurement() string { return Measurement } // Min returns a new Elevation pointer containing the smallest sum of the two Elevations. func (elevation *Elevation) Min(l *Elevation) *Elevation { return NewElevation(float32(math.Min(math.Abs(float64(*elevation)), math.Abs(float64(*l))))) } func (elevation *Elevation) String() string { return fmt.Sprintf("%v", float32(*elevation)) } // To returns a Elevation expressing the distance between two Elevation pointers, using the argument Elevation as the subtraction. func (elevation *Elevation) To(l *Elevation) *Elevation { return NewElevation(elevation.Value() - l.Value()) } // Value returns the numeric value held by the Elevation pointer. func (elevation *Elevation) Value() float32 { return float32(*elevation) }
elevation/elevation.go
0.944855
0.680048
elevation.go
starcoder
package utils import ( "time" ) func GetCurrentDateMinute() int32 { return GetDateMinute(time.Now().UTC()) } func GetCurrentPartitionPeriod( partitionPeriodLength int, ) int32 { now := time.Now().UTC() return GetDateMinute(now.Add(-(time.Minute * time.Duration(now.Minute()%partitionPeriodLength)))) } func GetCurrentEs() int64 { return time.Now().UTC().Unix() } func GetCurrentDtb() int64 { return GetDecimalDateSecond(time.Now().UTC()) } func GetDateMinuteFromEpochSeconds( epochSeconds int64, ) int32 { return GetDateMinute(time.Unix(epochSeconds, 0).UTC()) } func GetCurrentAndPreviousParitionPeriods( partitionPeriodLength int, ) (int32, int32) { now := time.Now().UTC() return getOffsetPartitionPeriodsFromTime(partitionPeriodLength, now.Minute()%partitionPeriodLength, now) } func getOffsetPartitionPeriodsFromTime( partitionPeriodLength int, minuteOffset int, aTime time.Time, ) (int32, int32) { //log.Printf("aTime: %s\n", aTime.Format("2006-01-02 15:04:05")) //log.Printf("minuteOffset: %d\n", minuteOffset) currentPeriod := GetDateMinute(aTime.Add(-(time.Minute * time.Duration(minuteOffset)))) numMinutes := partitionPeriodLength + minuteOffset //log.Printf("numMinutes: %d\n", numMinutes) previousPeriod := GetDateMinute(aTime.Add(-(time.Minute * time.Duration(numMinutes)))) return currentPeriod, previousPeriod } func GetDateMinute( date time.Time, ) int32 { year := (date.Year() - 2020) << 20 month := int(date.Month()) << 16 monthDate := date.Day() << 11 hour := date.Hour() << 6 minute := date.Minute() //log.Printf("minute: %d\n", minute) return int32(year + month + monthDate + hour + minute) } func GetDecimalDateSecond( date time.Time, ) int64 { year := (date.Year() - 2020) * 10000000000 month := int(date.Month()) * 100000000 monthDate := date.Day() * 1000000 hour := date.Hour() * 10000 minute := date.Minute() * 100 second := date.Second() //log.Printf("minute: %d\n", minute) return int64(year + month + monthDate + hour + minute + second) }
utils/utils.go
0.722429
0.438665
utils.go
starcoder
package stats import ( "math" "sync" "time" ) // Tracker is a min/max value tracker that keeps track of its min/max values // over a given period of time, and with a given resolution. The initial min // and max values are math.MaxInt64 and math.MinInt64 respectively. type Tracker struct { mu sync.RWMutex min, max int64 // All time min/max. minTS, maxTS [3]*timeseries lastUpdate time.Time } // newTracker returns a new Tracker. func newTracker() *Tracker { now := TimeNow() t := &Tracker{} t.minTS[hour] = newTimeSeries(now, time.Hour, time.Minute) t.minTS[tenminutes] = newTimeSeries(now, 10*time.Minute, 10*time.Second) t.minTS[minute] = newTimeSeries(now, time.Minute, time.Second) t.maxTS[hour] = newTimeSeries(now, time.Hour, time.Minute) t.maxTS[tenminutes] = newTimeSeries(now, 10*time.Minute, 10*time.Second) t.maxTS[minute] = newTimeSeries(now, time.Minute, time.Second) t.init() return t } func (t *Tracker) init() { t.min = math.MaxInt64 t.max = math.MinInt64 for _, ts := range t.minTS { ts.set(math.MaxInt64) } for _, ts := range t.maxTS { ts.set(math.MinInt64) } } func (t *Tracker) advance() time.Time { now := TimeNow() for _, ts := range t.minTS { ts.advanceTimeWithFill(now, math.MaxInt64) } for _, ts := range t.maxTS { ts.advanceTimeWithFill(now, math.MinInt64) } return now } // LastUpdate returns the last update time of the range. func (t *Tracker) LastUpdate() time.Time { t.mu.RLock() defer t.mu.RUnlock() return t.lastUpdate } // Push adds a new value if it is a new minimum or maximum. func (t *Tracker) Push(value int64) { t.mu.Lock() defer t.mu.Unlock() t.lastUpdate = t.advance() if t.min > value { t.min = value } if t.max < value { t.max = value } for _, ts := range t.minTS { if ts.headValue() > value { ts.set(value) } } for _, ts := range t.maxTS { if ts.headValue() < value { ts.set(value) } } } // Min returns the minimum value of the tracker func (t *Tracker) Min() int64 { t.mu.RLock() defer t.mu.RUnlock() return t.min } // Max returns the maximum value of the tracker. func (t *Tracker) Max() int64 { t.mu.RLock() defer t.mu.RUnlock() return t.max } // Min1h returns the minimum value for the last hour. func (t *Tracker) Min1h() int64 { t.mu.Lock() defer t.mu.Unlock() t.advance() return t.minTS[hour].min() } // Max1h returns the maximum value for the last hour. func (t *Tracker) Max1h() int64 { t.mu.Lock() defer t.mu.Unlock() t.advance() return t.maxTS[hour].max() } // Min10m returns the minimum value for the last 10 minutes. func (t *Tracker) Min10m() int64 { t.mu.Lock() defer t.mu.Unlock() t.advance() return t.minTS[tenminutes].min() } // Max10m returns the maximum value for the last 10 minutes. func (t *Tracker) Max10m() int64 { t.mu.Lock() defer t.mu.Unlock() t.advance() return t.maxTS[tenminutes].max() } // Min1m returns the minimum value for the last 1 minute. func (t *Tracker) Min1m() int64 { t.mu.Lock() defer t.mu.Unlock() t.advance() return t.minTS[minute].min() } // Max1m returns the maximum value for the last 1 minute. func (t *Tracker) Max1m() int64 { t.mu.Lock() defer t.mu.Unlock() t.advance() return t.maxTS[minute].max() } // Reset resets the range to an empty state. func (t *Tracker) Reset() { t.mu.Lock() defer t.mu.Unlock() now := TimeNow() for _, ts := range t.minTS { ts.reset(now) } for _, ts := range t.maxTS { ts.reset(now) } t.init() }
vendor/github.com/aristanetworks/goarista/monitor/stats/tracker.go
0.716913
0.480966
tracker.go
starcoder
// Package lorawan provides LoRaWAN decoding/encoding interfaces. package lorawan import ( "fmt" "go.thethings.network/lorawan-stack/pkg/ttnpb" ) const maxUint24 = 1<<24 - 1 func boolToByte(b bool) byte { if b { return 1 } return 0 } func copyReverse(dst, src []byte) { for i := range src { dst[i] = src[len(src)-1-i] } } func appendReverse(dst []byte, src ...byte) []byte { for i := range src { dst = append(dst, src[len(src)-1-i]) } return dst } func parseUint32(b []byte) uint32 { switch len(b) { case 0: return 0 case 1: _ = b[0] return uint32(b[0]) case 2: _ = b[1] return uint32(b[0]) | uint32(b[1])<<8 case 3: _ = b[2] return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 default: _ = b[3] return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 } } func parseUint64(b []byte) uint64 { switch len(b) { case 0: return 0 case 1: _ = b[0] return uint64(b[0]) case 2: _ = b[1] return uint64(b[0]) | uint64(b[1])<<8 case 3: _ = b[2] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 case 4: _ = b[3] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 case 5: _ = b[4] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 case 6: _ = b[5] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 case 7: _ = b[6] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 default: _ = b[7] return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 } } func appendUint16(dst []byte, v uint16, byteCount uint8) []byte { switch byteCount { case 0: return dst case 1: return append(dst, byte(v)) default: dst = append(dst, byte(v), byte(v>>8)) for i := uint8(2); i < byteCount; i++ { dst = append(dst, 0) } return dst } } func appendUint32(dst []byte, v uint32, byteCount uint8) []byte { switch byteCount { case 0, 1, 2: return appendUint16(dst, uint16(v), byteCount) case 3: return append(dst, byte(v), byte(v>>8), byte(v>>16)) default: dst = append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24)) for i := uint8(4); i < byteCount; i++ { dst = append(dst, 0) } return dst } } func appendUint64(dst []byte, v uint64, byteCount uint8) []byte { switch byteCount { case 0, 1, 2, 3, 4: return appendUint32(dst, uint32(v), byteCount) case 5: return append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32)) case 6: return append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40)) case 7: return append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48)) default: dst = append(dst, byte(v), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48), byte(v>>56)) for i := uint8(8); i < byteCount; i++ { dst = append(dst, 0) } return dst } } // DeviceEIRPToFloat32 returns v as a float32 value. func DeviceEIRPToFloat32(v ttnpb.DeviceEIRP) float32 { switch v { case ttnpb.DEVICE_EIRP_36: return 36 case ttnpb.DEVICE_EIRP_33: return 33 case ttnpb.DEVICE_EIRP_30: return 30 case ttnpb.DEVICE_EIRP_29: return 29 case ttnpb.DEVICE_EIRP_27: return 27 case ttnpb.DEVICE_EIRP_26: return 26 case ttnpb.DEVICE_EIRP_24: return 24 case ttnpb.DEVICE_EIRP_21: return 21 case ttnpb.DEVICE_EIRP_20: return 20 case ttnpb.DEVICE_EIRP_18: return 18 case ttnpb.DEVICE_EIRP_16: return 16 case ttnpb.DEVICE_EIRP_14: return 14 case ttnpb.DEVICE_EIRP_13: return 13 case ttnpb.DEVICE_EIRP_12: return 12 case ttnpb.DEVICE_EIRP_10: return 10 case ttnpb.DEVICE_EIRP_8: return 8 } panic(fmt.Errorf("unknown DeviceEIRP value `%d`", v)) } // Float32ToDeviceEIRP returns v as a highest possible DeviceEIRP. func Float32ToDeviceEIRP(v float32) ttnpb.DeviceEIRP { switch { case v >= 36: return ttnpb.DEVICE_EIRP_36 case v >= 33: return ttnpb.DEVICE_EIRP_33 case v >= 30: return ttnpb.DEVICE_EIRP_30 case v >= 29: return ttnpb.DEVICE_EIRP_29 case v >= 27: return ttnpb.DEVICE_EIRP_27 case v >= 26: return ttnpb.DEVICE_EIRP_26 case v >= 24: return ttnpb.DEVICE_EIRP_24 case v >= 21: return ttnpb.DEVICE_EIRP_21 case v >= 20: return ttnpb.DEVICE_EIRP_20 case v >= 18: return ttnpb.DEVICE_EIRP_18 case v >= 16: return ttnpb.DEVICE_EIRP_16 case v >= 14: return ttnpb.DEVICE_EIRP_14 case v >= 13: return ttnpb.DEVICE_EIRP_13 case v >= 12: return ttnpb.DEVICE_EIRP_12 case v >= 10: return ttnpb.DEVICE_EIRP_10 } return ttnpb.DEVICE_EIRP_8 } // ADRAckLimitExponentToUint32 returns v as a uint32 value. func ADRAckLimitExponentToUint32(v ttnpb.ADRAckLimitExponent) uint32 { switch v { case ttnpb.ADR_ACK_LIMIT_32768: return 32768 case ttnpb.ADR_ACK_LIMIT_16384: return 16384 case ttnpb.ADR_ACK_LIMIT_8192: return 8192 case ttnpb.ADR_ACK_LIMIT_4096: return 4096 case ttnpb.ADR_ACK_LIMIT_2048: return 2048 case ttnpb.ADR_ACK_LIMIT_1024: return 1024 case ttnpb.ADR_ACK_LIMIT_512: return 512 case ttnpb.ADR_ACK_LIMIT_256: return 256 case ttnpb.ADR_ACK_LIMIT_128: return 128 case ttnpb.ADR_ACK_LIMIT_64: return 64 case ttnpb.ADR_ACK_LIMIT_32: return 32 case ttnpb.ADR_ACK_LIMIT_16: return 16 case ttnpb.ADR_ACK_LIMIT_8: return 8 case ttnpb.ADR_ACK_LIMIT_4: return 4 case ttnpb.ADR_ACK_LIMIT_2: return 2 case ttnpb.ADR_ACK_LIMIT_1: return 1 } panic(fmt.Errorf("unknown ADRAckLimitExponent value `%d`", v)) } // Uint32ToADRAckLimitExponent returns v as a highest possible ADRAckLimitExponent. func Uint32ToADRAckLimitExponent(v uint32) ttnpb.ADRAckLimitExponent { switch { case v >= 32768: return ttnpb.ADR_ACK_LIMIT_32768 case v >= 16384: return ttnpb.ADR_ACK_LIMIT_16384 case v >= 8192: return ttnpb.ADR_ACK_LIMIT_8192 case v >= 4096: return ttnpb.ADR_ACK_LIMIT_4096 case v >= 2048: return ttnpb.ADR_ACK_LIMIT_2048 case v >= 1024: return ttnpb.ADR_ACK_LIMIT_1024 case v >= 512: return ttnpb.ADR_ACK_LIMIT_512 case v >= 256: return ttnpb.ADR_ACK_LIMIT_256 case v >= 128: return ttnpb.ADR_ACK_LIMIT_128 case v >= 64: return ttnpb.ADR_ACK_LIMIT_64 case v >= 32: return ttnpb.ADR_ACK_LIMIT_32 case v >= 16: return ttnpb.ADR_ACK_LIMIT_16 case v >= 8: return ttnpb.ADR_ACK_LIMIT_8 case v >= 4: return ttnpb.ADR_ACK_LIMIT_4 case v >= 2: return ttnpb.ADR_ACK_LIMIT_2 } return ttnpb.ADR_ACK_LIMIT_1 } // ADRAckDelayExponentToUint32 returns v as a uint32 value. func ADRAckDelayExponentToUint32(v ttnpb.ADRAckDelayExponent) uint32 { switch v { case ttnpb.ADR_ACK_DELAY_32768: return 32768 case ttnpb.ADR_ACK_DELAY_16384: return 16384 case ttnpb.ADR_ACK_DELAY_8192: return 8192 case ttnpb.ADR_ACK_DELAY_4096: return 4096 case ttnpb.ADR_ACK_DELAY_2048: return 2048 case ttnpb.ADR_ACK_DELAY_1024: return 1024 case ttnpb.ADR_ACK_DELAY_512: return 512 case ttnpb.ADR_ACK_DELAY_256: return 256 case ttnpb.ADR_ACK_DELAY_128: return 128 case ttnpb.ADR_ACK_DELAY_64: return 64 case ttnpb.ADR_ACK_DELAY_32: return 32 case ttnpb.ADR_ACK_DELAY_16: return 16 case ttnpb.ADR_ACK_DELAY_8: return 8 case ttnpb.ADR_ACK_DELAY_4: return 4 case ttnpb.ADR_ACK_DELAY_2: return 2 case ttnpb.ADR_ACK_DELAY_1: return 1 } panic(fmt.Errorf("unknown ADRAckDelayExponent value `%d`", v)) } // Uint32ToADRAckDelayExponent returns v as a highest possible ADRAckDelayExponent. func Uint32ToADRAckDelayExponent(v uint32) ttnpb.ADRAckDelayExponent { switch { case v >= 32768: return ttnpb.ADR_ACK_DELAY_32768 case v >= 16384: return ttnpb.ADR_ACK_DELAY_16384 case v >= 8192: return ttnpb.ADR_ACK_DELAY_8192 case v >= 4096: return ttnpb.ADR_ACK_DELAY_4096 case v >= 2048: return ttnpb.ADR_ACK_DELAY_2048 case v >= 1024: return ttnpb.ADR_ACK_DELAY_1024 case v >= 512: return ttnpb.ADR_ACK_DELAY_512 case v >= 256: return ttnpb.ADR_ACK_DELAY_256 case v >= 128: return ttnpb.ADR_ACK_DELAY_128 case v >= 64: return ttnpb.ADR_ACK_DELAY_64 case v >= 32: return ttnpb.ADR_ACK_DELAY_32 case v >= 16: return ttnpb.ADR_ACK_DELAY_16 case v >= 8: return ttnpb.ADR_ACK_DELAY_8 case v >= 4: return ttnpb.ADR_ACK_DELAY_4 case v >= 2: return ttnpb.ADR_ACK_DELAY_2 } return ttnpb.ADR_ACK_DELAY_1 }
pkg/encoding/lorawan/lorawan.go
0.566738
0.434401
lorawan.go
starcoder
package oversampling import ( "fmt" "github.com/andrepxx/go-dsp-guitar/filter" "github.com/andrepxx/go-dsp-guitar/resample" ) /* * Global constants. */ const ( ATTENUATION_HALF_DECIBEL = 0.9440608762859234 LOOKAHEAD_SAMPLES_ONE_SIDE = 4 LOOKAHEAD_SAMPLES_BOTH_SIDES = 2 * LOOKAHEAD_SAMPLES_ONE_SIDE ) /* * An oversampler / decimator increases or decreases the sample rate of a * signal by a constant factor. * * When oversampling the signal, band-limited interpolation is applied. * * When decimating (downsampling) the signal, a band-limiting filter is * applied to prevent aliasing. */ type OversamplerDecimator interface { Oversample(in []float64, out []float64) error Decimate(in []float64, out []float64) error } /* * Data structure implementing an oversampler / decimator. */ type oversamplerDecimatorStruct struct { factor uint32 antiAliasingFilter filter.Filter attenuationFactor float64 bufferPreUpsampling []float64 bufferPostUpsampling []float64 bufferPreDecimation []float64 } /* * Oversamples the signal in the input buffer by an oversampling factor. * * The resulting output is M = factor * N samples long when the input provided * is N samples long. * * The oversampling is stateful, since it requires both some lookahead on the * input (and therefore needs to introduce a delay of a few samples) and some * input samples from past invocations. */ func (this *oversamplerDecimatorStruct) Oversample(in []float64, out []float64) error { factor32 := this.factor factor := int(factor32) /* * Check if signal has to be oversampled in time. */ if factor <= 1 { copy(out, in) return nil } else { numInputSamples := len(in) numInputSamples32 := uint32(numInputSamples) expectedNumOutputSamples := numInputSamples * factor expectedNumOutputSamples32 := uint32(expectedNumOutputSamples) numOutputSamples := len(out) numOutputSamples32 := uint32(numOutputSamples) /* * Ensure that input and output buffer has the correct size. */ if numOutputSamples32 != expectedNumOutputSamples32 { template := "Error while oversampling: Expected output buffer of size %d (= %d * %d), but buffer has size %d." return fmt.Errorf(template, expectedNumOutputSamples32, numInputSamples32, factor, numOutputSamples32) } else { bufferPre := this.bufferPreUpsampling bufferPreSize := numInputSamples + LOOKAHEAD_SAMPLES_BOTH_SIDES /* * Make sure the pre-upsampling buffer has the correct size. */ if len(bufferPre) != bufferPreSize { bufferPre = make([]float64, bufferPreSize) this.bufferPreUpsampling = bufferPre } tailStart := bufferPreSize - LOOKAHEAD_SAMPLES_BOTH_SIDES copy(bufferPre[0:LOOKAHEAD_SAMPLES_BOTH_SIDES], bufferPre[tailStart:bufferPreSize]) copy(bufferPre[LOOKAHEAD_SAMPLES_BOTH_SIDES:bufferPreSize], in) bufferPost := this.bufferPostUpsampling bufferPostSize := ((bufferPreSize - 1) * factor) + 1 /* * Make sure the post-upsampling buffer has the correct size. */ if len(bufferPost) != bufferPostSize { bufferPost = make([]float64, bufferPostSize) this.bufferPostUpsampling = bufferPost } resample.Oversample(bufferPre, bufferPost, factor32) idxStart := LOOKAHEAD_SAMPLES_ONE_SIDE * factor idxEnd := idxStart + expectedNumOutputSamples copy(out, bufferPost[idxStart:idxEnd]) return nil } } } /* * Decimates the signal in the input buffer by an oversampling factor. * * The resulting output is N = M / factor samples long when the input provided * is M samples long. * * The decimation is stateful, since it makes use of a stateful anti-aliasing * filter. */ func (this *oversamplerDecimatorStruct) Decimate(in []float64, out []float64) error { factor32 := this.factor factor := int(factor32) /* * Check if signal has to be decimated in time. */ if factor <= 1 { copy(out, in) return nil } else { numInputSamples := len(in) buffer := this.bufferPreDecimation /* * Ensure that the output buffer for the anti-aliasing filter * is as long as the input buffer. */ if len(buffer) != numInputSamples { buffer = make([]float64, numInputSamples) this.bufferPreDecimation = buffer } flt := this.antiAliasingFilter err := flt.Process(in, buffer) /* * Check if an error occured. */ if err != nil { msg := err.Error() return fmt.Errorf("Error while applying anti-aliasing filter for decimation: %s", msg) } else { bufferSize := len(buffer) /* * Decimate the output by taking one sample and dropping N - 1 * samples, where N is the oversampling factor. */ for i := range out { idx := factor * i /* * Check if we are still within the bounds of the buffer. */ if idx < bufferSize { out[i] = ATTENUATION_HALF_DECIBEL * buffer[idx] } else { out[i] = 0.0 } } return nil } } } /* * Creates an oversampler / decimator with the requested oversampling factor. * * The oversampling factor can be either 1, 2 or 4. * * (An oversampler / decimator with an oversampling factor of one technically * just copies buffers when oversampling / decimating though.) */ func CreateOversamplerDecimator(factor uint32) OversamplerDecimator { /* * The oversampling factor determines the coefficients for the * anti-aliasing filter used before decimation (= downsampling). */ switch factor { case 1: /* * An oversampler / decimator with an oversampling * factor of 1. */ osd := oversamplerDecimatorStruct{ factor: 1, antiAliasingFilter: nil, attenuationFactor: 1.0, } return &osd case 2: /* * Anti-aliasing filter for decimation after 2-times * oversampling. * * - Order: 77 * - Passband: 0 to 0.4 * fs * - Ripple: less than +/- 0.5 dB * - Stopband: from 0.5 * fs * - Attenuation: more than 120 dB * * Where fs is the sample rate after decimation. * * Examples: * * Sample rate | Oversampled | Passband | Stopband * -------------------------------------------------- * 44.1 kHz | 88.2 kHz | 17.64 kHz | 22.05 kHz * 48.0 kHz | 96.0 kHz | 19.20 kHz | 24.00 kHz * 88.2 kHz | 176.4 kHz | 35.28 kHz | 44.10 kHz * 96.0 kHz | 192.0 kHz | 38.40 kHz | 48.00 kHz * 176.4 kHz | 352.8 kHz | 70.56 kHz | 88.20 kHz * 192.0 kHz | 384.0 kHz | 76.80 kHz | 96.00 kHz */ coeffs := []float64{ -0.00003492934784890941, -0.0003392120149044798, -0.0014714158707716568, -0.0038999530054612506, -0.006911343940235415, -0.008083007705624154, -0.005071878685632956, 0.0010436432381931216, 0.005133162788276673, 0.0029441192777868346, -0.002966456827156262, -0.0049140011265012915, 0.0002504710726990459, 0.005677026805555885, 0.0029644609183865525, -0.00502776088831408, -0.006372346916246025, 0.0025325196219111606, 0.009161633713407162, 0.0019414998184190532, -0.010183325233642465, -0.007923283926229728, 0.008288108595786142, 0.014272756343260685, -0.0026415624384956015, -0.019218660155603737, -0.006932661398171457, 0.020610554179589805, 0.01985948065927744, -0.016017276726217215, -0.03475499073668333, 0.0026332590387740207, 0.049675468036826695, 0.02427989874123878, -0.062421162066919444, -0.08025548852929663, 0.07100233144132687, 0.30929817925728875, 0.4259645026667285, 0.30929817925728875, 0.07100233144132687, -0.08025548852929663, -0.062421162066919444, 0.02427989874123878, 0.049675468036826695, 0.0026332590387740207, -0.03475499073668333, -0.016017276726217215, 0.01985948065927744, 0.020610554179589805, -0.006932661398171457, -0.019218660155603737, -0.0026415624384956015, 0.014272756343260685, 0.008288108595786142, -0.007923283926229728, -0.010183325233642465, 0.0019414998184190532, 0.009161633713407162, 0.0025325196219111606, -0.006372346916246025, -0.00502776088831408, 0.0029644609183865525, 0.005677026805555885, 0.0002504710726990459, -0.0049140011265012915, -0.002966456827156262, 0.0029441192777868346, 0.005133162788276673, 0.0010436432381931216, -0.005071878685632956, -0.008083007705624154, -0.006911343940235415, -0.0038999530054612506, -0.0014714158707716568, -0.0003392120149044798, -0.00003492934784890941, } flt := filter.FromCoefficients(coeffs, 0, "Anti-aliasing filter for 2-times oversampling") /* * An oversampler / decimator with an oversampling * factor of 2. */ osd := oversamplerDecimatorStruct{ factor: 2, antiAliasingFilter: flt, attenuationFactor: ATTENUATION_HALF_DECIBEL, } return &osd case 4: /* * Anti-aliasing filter for decimation after 4-times * oversampling. * * - Order: 155 * - Passband: 0 to 0.4 * fs * - Ripple: less than +/- 0.5 dB * - Stopband: from 0.5 * fs * - Attenuation: more than 120 dB * * Where fs is the sample rate after decimation. * * Examples: * * Sample rate | Oversampled | Passband | Stopband * -------------------------------------------------- * 44.1 kHz | 176.4 kHz | 17.64 kHz | 22.05 kHz * 48.0 kHz | 192.0 kHz | 19.20 kHz | 24.00 kHz * 88.2 kHz | 352.8 kHz | 35.28 kHz | 44.10 kHz * 96.0 kHz | 384.0 kHz | 38.40 kHz | 48.00 kHz * 176.4 kHz | 705.6 kHz | 70.56 kHz | 88.20 kHz * 192.0 kHz | 768.0 kHz | 76.80 kHz | 96.00 kHz */ coeffs := []float64{ -0.0000015021121037413662, -0.000014247930232761388, -0.00005540231978931542, -0.00015630206030270148, -0.0003584399777348438, -0.000705026640710802, -0.0012235616110217874, -0.001903660659808354, -0.00267726234331065, -0.003411584910561322, -0.003924344675899259, -0.004025045645232759, -0.0035762101728860417, -0.0025573008067263044, -0.0011066687495094368, 0.0004821972926674136, 0.0018221416962137336, 0.002543137384860401, 0.00242138962866836, 0.0014804833709829318, 0.000018970679160808765, -0.0014609367040901548, -0.0024134283298567795, -0.0024492254183795556, -0.0015017106353334075, 0.00011357732553534381, 0.0017859787871056622, 0.0028277613883314974, 0.0027499128054293363, 0.0014872096489652376, -0.0005294306298690314, -0.002503516126880322, -0.003575536194224602, -0.003187701643215724, -0.00135969080293838, 0.0012559883020625854, 0.0035898853367056904, 0.004580083649141936, 0.0036424372986039993, 0.0009834739417648997, -0.0024017684965412264, -0.005083213814497091, -0.005784183213696061, -0.00396945510709691, -0.00016979882374028044, 0.004133247336931644, 0.0070622101801412545, 0.0071407896959270085, 0.004004024888678994, -0.0013073464277146174, -0.006649326836701509, -0.009608632396950771, -0.008557172161681335, -0.00348067806403019, 0.003816684112995466, 0.010298649251403313, 0.012908606169822902, 0.00994335100177495, 0.001997586597194608, -0.007994368492098312, -0.01575380865287906, -0.01738598716205188, -0.011180107332533986, 0.0012948642543910843, 0.015369959683332234, 0.024832317669641207, 0.024391753256398193, 0.012155808794391754, -0.00890111973242649, -0.031201026812293402, -0.04467639062071552, -0.04014181689513159, -0.01278803733109894, 0.035484245817926856, 0.0958427608403164, 0.15465705312784375, 0.19739158968717124, 0.21300669185029408, 0.19739158968717124, 0.15465705312784375, 0.0958427608403164, 0.035484245817926856, -0.01278803733109894, -0.04014181689513159, -0.04467639062071552, -0.031201026812293402, -0.00890111973242649, 0.012155808794391754, 0.024391753256398193, 0.024832317669641207, 0.015369959683332234, 0.0012948642543910843, -0.011180107332533986, -0.01738598716205188, -0.01575380865287906, -0.007994368492098312, 0.001997586597194608, 0.00994335100177495, 0.012908606169822902, 0.010298649251403313, 0.003816684112995466, -0.00348067806403019, -0.008557172161681335, -0.009608632396950771, -0.006649326836701509, -0.0013073464277146174, 0.004004024888678994, 0.0071407896959270085, 0.0070622101801412545, 0.004133247336931644, -0.00016979882374028044, -0.00396945510709691, -0.005784183213696061, -0.005083213814497091, -0.0024017684965412264, 0.0009834739417648997, 0.0036424372986039993, 0.004580083649141936, 0.0035898853367056904, 0.0012559883020625854, -0.00135969080293838, -0.003187701643215724, -0.003575536194224602, -0.002503516126880322, -0.0005294306298690314, 0.0014872096489652376, 0.0027499128054293363, 0.0028277613883314974, 0.0017859787871056622, 0.00011357732553534381, -0.0015017106353334075, -0.0024492254183795556, -0.0024134283298567795, -0.0014609367040901548, 0.000018970679160808765, 0.0014804833709829318, 0.00242138962866836, 0.002543137384860401, 0.0018221416962137336, 0.0004821972926674136, -0.0011066687495094368, -0.0025573008067263044, -0.0035762101728860417, -0.004025045645232759, -0.003924344675899259, -0.003411584910561322, -0.00267726234331065, -0.001903660659808354, -0.0012235616110217874, -0.000705026640710802, -0.0003584399777348438, -0.00015630206030270148, -0.00005540231978931542, -0.000014247930232761388, -0.0000015021121037413662, } flt := filter.FromCoefficients(coeffs, 0, "Anti-aliasing filter for 4-times oversampling") /* * An oversampler / decimator with an oversampling * factor of 4. */ osd := oversamplerDecimatorStruct{ factor: 4, antiAliasingFilter: flt, attenuationFactor: ATTENUATION_HALF_DECIBEL, } return &osd default: return nil } }
oversampling/oversampling.go
0.675015
0.445891
oversampling.go
starcoder
package schema // samSchema defined a JSON Schema that can be used to validate CloudFormation/SAM templates var samSchema = `{ "$schema": "http://json-schema.org/draft-04/schema#", "additionalProperties": false, "definitions": { "AWS::ApiGateway::Account": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CloudWatchRoleArn": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::Account" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ApiGateway::ApiKey": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CustomerId": { "type": "string" }, "Description": { "type": "string" }, "Enabled": { "type": "boolean" }, "GenerateDistinctId": { "type": "boolean" }, "Name": { "type": "string" }, "StageKeys": { "items": { "$ref": "#/definitions/AWS::ApiGateway::ApiKey.StageKey" }, "type": "array" } }, "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::ApiKey" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ApiGateway::ApiKey.StageKey": { "additionalProperties": false, "properties": { "RestApiId": { "type": "string" }, "StageName": { "type": "string" } }, "type": "object" }, "AWS::ApiGateway::Authorizer": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AuthType": { "type": "string" }, "AuthorizerCredentials": { "type": "string" }, "AuthorizerResultTtlInSeconds": { "type": "number" }, "AuthorizerUri": { "type": "string" }, "IdentitySource": { "type": "string" }, "IdentityValidationExpression": { "type": "string" }, "Name": { "type": "string" }, "ProviderARNs": { "items": { "type": "string" }, "type": "array" }, "RestApiId": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::Authorizer" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::BasePathMapping": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "BasePath": { "type": "string" }, "DomainName": { "type": "string" }, "RestApiId": { "type": "string" }, "Stage": { "type": "string" } }, "required": [ "DomainName" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::BasePathMapping" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::ClientCertificate": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::ClientCertificate" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ApiGateway::Deployment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "RestApiId": { "type": "string" }, "StageDescription": { "$ref": "#/definitions/AWS::ApiGateway::Deployment.StageDescription" }, "StageName": { "type": "string" } }, "required": [ "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::Deployment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::Deployment.MethodSetting": { "additionalProperties": false, "properties": { "CacheDataEncrypted": { "type": "boolean" }, "CacheTtlInSeconds": { "type": "number" }, "CachingEnabled": { "type": "boolean" }, "DataTraceEnabled": { "type": "boolean" }, "HttpMethod": { "type": "string" }, "LoggingLevel": { "type": "string" }, "MetricsEnabled": { "type": "boolean" }, "ResourcePath": { "type": "string" }, "ThrottlingBurstLimit": { "type": "number" }, "ThrottlingRateLimit": { "type": "number" } }, "type": "object" }, "AWS::ApiGateway::Deployment.StageDescription": { "additionalProperties": false, "properties": { "CacheClusterEnabled": { "type": "boolean" }, "CacheClusterSize": { "type": "string" }, "CacheDataEncrypted": { "type": "boolean" }, "CacheTtlInSeconds": { "type": "number" }, "CachingEnabled": { "type": "boolean" }, "ClientCertificateId": { "type": "string" }, "DataTraceEnabled": { "type": "boolean" }, "Description": { "type": "string" }, "DocumentationVersion": { "type": "string" }, "LoggingLevel": { "type": "string" }, "MethodSettings": { "items": { "$ref": "#/definitions/AWS::ApiGateway::Deployment.MethodSetting" }, "type": "array" }, "MetricsEnabled": { "type": "boolean" }, "ThrottlingBurstLimit": { "type": "number" }, "ThrottlingRateLimit": { "type": "number" }, "Variables": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "type": "object" }, "AWS::ApiGateway::DocumentationPart": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Location": { "$ref": "#/definitions/AWS::ApiGateway::DocumentationPart.Location" }, "Properties": { "type": "string" }, "RestApiId": { "type": "string" } }, "required": [ "Location", "Properties", "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::DocumentationPart" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::DocumentationPart.Location": { "additionalProperties": false, "properties": { "Method": { "type": "string" }, "Name": { "type": "string" }, "Path": { "type": "string" }, "StatusCode": { "type": "string" }, "Type": { "type": "string" } }, "type": "object" }, "AWS::ApiGateway::DocumentationVersion": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "DocumentationVersion": { "type": "string" }, "RestApiId": { "type": "string" } }, "required": [ "DocumentationVersion", "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::DocumentationVersion" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::DomainName": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CertificateArn": { "type": "string" }, "DomainName": { "type": "string" }, "EndpointConfiguration": { "$ref": "#/definitions/AWS::ApiGateway::DomainName.EndpointConfiguration" }, "RegionalCertificateArn": { "type": "string" } }, "required": [ "DomainName" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::DomainName" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::DomainName.EndpointConfiguration": { "additionalProperties": false, "properties": { "Types": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::ApiGateway::GatewayResponse": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ResponseParameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "ResponseTemplates": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "ResponseType": { "type": "string" }, "RestApiId": { "type": "string" }, "StatusCode": { "type": "string" } }, "required": [ "ResponseType", "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::GatewayResponse" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::Method": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApiKeyRequired": { "type": "boolean" }, "AuthorizationType": { "type": "string" }, "AuthorizerId": { "type": "string" }, "HttpMethod": { "type": "string" }, "Integration": { "$ref": "#/definitions/AWS::ApiGateway::Method.Integration" }, "MethodResponses": { "items": { "$ref": "#/definitions/AWS::ApiGateway::Method.MethodResponse" }, "type": "array" }, "OperationName": { "type": "string" }, "RequestModels": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "RequestParameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "boolean" } }, "type": "object" }, "RequestValidatorId": { "type": "string" }, "ResourceId": { "type": "string" }, "RestApiId": { "type": "string" } }, "required": [ "HttpMethod", "ResourceId", "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::Method" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::Method.Integration": { "additionalProperties": false, "properties": { "CacheKeyParameters": { "items": { "type": "string" }, "type": "array" }, "CacheNamespace": { "type": "string" }, "ContentHandling": { "type": "string" }, "Credentials": { "type": "string" }, "IntegrationHttpMethod": { "type": "string" }, "IntegrationResponses": { "items": { "$ref": "#/definitions/AWS::ApiGateway::Method.IntegrationResponse" }, "type": "array" }, "PassthroughBehavior": { "type": "string" }, "RequestParameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "RequestTemplates": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Type": { "type": "string" }, "Uri": { "type": "string" } }, "type": "object" }, "AWS::ApiGateway::Method.IntegrationResponse": { "additionalProperties": false, "properties": { "ContentHandling": { "type": "string" }, "ResponseParameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "ResponseTemplates": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "SelectionPattern": { "type": "string" }, "StatusCode": { "type": "string" } }, "required": [ "StatusCode" ], "type": "object" }, "AWS::ApiGateway::Method.MethodResponse": { "additionalProperties": false, "properties": { "ResponseModels": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "ResponseParameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "boolean" } }, "type": "object" }, "StatusCode": { "type": "string" } }, "required": [ "StatusCode" ], "type": "object" }, "AWS::ApiGateway::Model": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ContentType": { "type": "string" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "RestApiId": { "type": "string" }, "Schema": { "type": "object" } }, "required": [ "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::Model" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::RequestValidator": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "RestApiId": { "type": "string" }, "ValidateRequestBody": { "type": "boolean" }, "ValidateRequestParameters": { "type": "boolean" } }, "required": [ "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::RequestValidator" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::Resource": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ParentId": { "type": "string" }, "PathPart": { "type": "string" }, "RestApiId": { "type": "string" } }, "required": [ "ParentId", "PathPart", "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::Resource" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::RestApi": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApiKeySourceType": { "type": "string" }, "BinaryMediaTypes": { "items": { "type": "string" }, "type": "array" }, "Body": { "type": "object" }, "BodyS3Location": { "$ref": "#/definitions/AWS::ApiGateway::RestApi.S3Location" }, "CloneFrom": { "type": "string" }, "Description": { "type": "string" }, "EndpointConfiguration": { "$ref": "#/definitions/AWS::ApiGateway::RestApi.EndpointConfiguration" }, "FailOnWarnings": { "type": "boolean" }, "MinimumCompressionSize": { "type": "number" }, "Name": { "type": "string" }, "Parameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::RestApi" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ApiGateway::RestApi.EndpointConfiguration": { "additionalProperties": false, "properties": { "Types": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::ApiGateway::RestApi.S3Location": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "ETag": { "type": "string" }, "Key": { "type": "string" }, "Version": { "type": "string" } }, "type": "object" }, "AWS::ApiGateway::Stage": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CacheClusterEnabled": { "type": "boolean" }, "CacheClusterSize": { "type": "string" }, "ClientCertificateId": { "type": "string" }, "DeploymentId": { "type": "string" }, "Description": { "type": "string" }, "DocumentationVersion": { "type": "string" }, "MethodSettings": { "items": { "$ref": "#/definitions/AWS::ApiGateway::Stage.MethodSetting" }, "type": "array" }, "RestApiId": { "type": "string" }, "StageName": { "type": "string" }, "Variables": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "required": [ "RestApiId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::Stage" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::Stage.MethodSetting": { "additionalProperties": false, "properties": { "CacheDataEncrypted": { "type": "boolean" }, "CacheTtlInSeconds": { "type": "number" }, "CachingEnabled": { "type": "boolean" }, "DataTraceEnabled": { "type": "boolean" }, "HttpMethod": { "type": "string" }, "LoggingLevel": { "type": "string" }, "MetricsEnabled": { "type": "boolean" }, "ResourcePath": { "type": "string" }, "ThrottlingBurstLimit": { "type": "number" }, "ThrottlingRateLimit": { "type": "number" } }, "type": "object" }, "AWS::ApiGateway::UsagePlan": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApiStages": { "items": { "$ref": "#/definitions/AWS::ApiGateway::UsagePlan.ApiStage" }, "type": "array" }, "Description": { "type": "string" }, "Quota": { "$ref": "#/definitions/AWS::ApiGateway::UsagePlan.QuotaSettings" }, "Throttle": { "$ref": "#/definitions/AWS::ApiGateway::UsagePlan.ThrottleSettings" }, "UsagePlanName": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::UsagePlan" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ApiGateway::UsagePlan.ApiStage": { "additionalProperties": false, "properties": { "ApiId": { "type": "string" }, "Stage": { "type": "string" } }, "type": "object" }, "AWS::ApiGateway::UsagePlan.QuotaSettings": { "additionalProperties": false, "properties": { "Limit": { "type": "number" }, "Offset": { "type": "number" }, "Period": { "type": "string" } }, "type": "object" }, "AWS::ApiGateway::UsagePlan.ThrottleSettings": { "additionalProperties": false, "properties": { "BurstLimit": { "type": "number" }, "RateLimit": { "type": "number" } }, "type": "object" }, "AWS::ApiGateway::UsagePlanKey": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "KeyId": { "type": "string" }, "KeyType": { "type": "string" }, "UsagePlanId": { "type": "string" } }, "required": [ "KeyId", "KeyType", "UsagePlanId" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::UsagePlanKey" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApiGateway::VpcLink": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Name": { "type": "string" }, "TargetArns": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Name", "TargetArns" ], "type": "object" }, "Type": { "enum": [ "AWS::ApiGateway::VpcLink" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalableTarget": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "MaxCapacity": { "type": "number" }, "MinCapacity": { "type": "number" }, "ResourceId": { "type": "string" }, "RoleARN": { "type": "string" }, "ScalableDimension": { "type": "string" }, "ScheduledActions": { "items": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalableTarget.ScheduledAction" }, "type": "array" }, "ServiceNamespace": { "type": "string" } }, "required": [ "MaxCapacity", "MinCapacity", "ResourceId", "RoleARN", "ScalableDimension", "ServiceNamespace" ], "type": "object" }, "Type": { "enum": [ "AWS::ApplicationAutoScaling::ScalableTarget" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalableTarget.ScalableTargetAction": { "additionalProperties": false, "properties": { "MaxCapacity": { "type": "number" }, "MinCapacity": { "type": "number" } }, "type": "object" }, "AWS::ApplicationAutoScaling::ScalableTarget.ScheduledAction": { "additionalProperties": false, "properties": { "EndTime": { "type": "string" }, "ScalableTargetAction": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalableTarget.ScalableTargetAction" }, "Schedule": { "type": "string" }, "ScheduledActionName": { "type": "string" }, "StartTime": { "type": "string" } }, "required": [ "Schedule", "ScheduledActionName" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalingPolicy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PolicyName": { "type": "string" }, "PolicyType": { "type": "string" }, "ResourceId": { "type": "string" }, "ScalableDimension": { "type": "string" }, "ScalingTargetId": { "type": "string" }, "ServiceNamespace": { "type": "string" }, "StepScalingPolicyConfiguration": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalingPolicy.StepScalingPolicyConfiguration" }, "TargetTrackingScalingPolicyConfiguration": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalingPolicy.TargetTrackingScalingPolicyConfiguration" } }, "required": [ "PolicyName", "PolicyType" ], "type": "object" }, "Type": { "enum": [ "AWS::ApplicationAutoScaling::ScalingPolicy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalingPolicy.CustomizedMetricSpecification": { "additionalProperties": false, "properties": { "Dimensions": { "items": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalingPolicy.MetricDimension" }, "type": "array" }, "MetricName": { "type": "string" }, "Namespace": { "type": "string" }, "Statistic": { "type": "string" }, "Unit": { "type": "string" } }, "required": [ "MetricName", "Namespace", "Statistic" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalingPolicy.MetricDimension": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Name", "Value" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalingPolicy.PredefinedMetricSpecification": { "additionalProperties": false, "properties": { "PredefinedMetricType": { "type": "string" }, "ResourceLabel": { "type": "string" } }, "required": [ "PredefinedMetricType" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalingPolicy.StepAdjustment": { "additionalProperties": false, "properties": { "MetricIntervalLowerBound": { "type": "number" }, "MetricIntervalUpperBound": { "type": "number" }, "ScalingAdjustment": { "type": "number" } }, "required": [ "ScalingAdjustment" ], "type": "object" }, "AWS::ApplicationAutoScaling::ScalingPolicy.StepScalingPolicyConfiguration": { "additionalProperties": false, "properties": { "AdjustmentType": { "type": "string" }, "Cooldown": { "type": "number" }, "MetricAggregationType": { "type": "string" }, "MinAdjustmentMagnitude": { "type": "number" }, "StepAdjustments": { "items": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalingPolicy.StepAdjustment" }, "type": "array" } }, "type": "object" }, "AWS::ApplicationAutoScaling::ScalingPolicy.TargetTrackingScalingPolicyConfiguration": { "additionalProperties": false, "properties": { "CustomizedMetricSpecification": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalingPolicy.CustomizedMetricSpecification" }, "DisableScaleIn": { "type": "boolean" }, "PredefinedMetricSpecification": { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalingPolicy.PredefinedMetricSpecification" }, "ScaleInCooldown": { "type": "number" }, "ScaleOutCooldown": { "type": "number" }, "TargetValue": { "type": "number" } }, "required": [ "TargetValue" ], "type": "object" }, "AWS::Athena::NamedQuery": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Database": { "type": "string" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "QueryString": { "type": "string" } }, "required": [ "Database", "QueryString" ], "type": "object" }, "Type": { "enum": [ "AWS::Athena::NamedQuery" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::AutoScaling::AutoScalingGroup": { "additionalProperties": false, "properties": { "CreationPolicy": { "type": "object" }, "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AutoScalingGroupName": { "type": "string" }, "AvailabilityZones": { "items": { "type": "string" }, "type": "array" }, "Cooldown": { "type": "string" }, "DesiredCapacity": { "type": "string" }, "HealthCheckGracePeriod": { "type": "number" }, "HealthCheckType": { "type": "string" }, "InstanceId": { "type": "string" }, "LaunchConfigurationName": { "type": "string" }, "LifecycleHookSpecificationList": { "items": { "$ref": "#/definitions/AWS::AutoScaling::AutoScalingGroup.LifecycleHookSpecification" }, "type": "array" }, "LoadBalancerNames": { "items": { "type": "string" }, "type": "array" }, "MaxSize": { "type": "string" }, "MetricsCollection": { "items": { "$ref": "#/definitions/AWS::AutoScaling::AutoScalingGroup.MetricsCollection" }, "type": "array" }, "MinSize": { "type": "string" }, "NotificationConfigurations": { "items": { "$ref": "#/definitions/AWS::AutoScaling::AutoScalingGroup.NotificationConfiguration" }, "type": "array" }, "PlacementGroup": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/AWS::AutoScaling::AutoScalingGroup.TagProperty" }, "type": "array" }, "TargetGroupARNs": { "items": { "type": "string" }, "type": "array" }, "TerminationPolicies": { "items": { "type": "string" }, "type": "array" }, "VPCZoneIdentifier": { "items": { "type": "string" }, "type": "array" } }, "required": [ "MaxSize", "MinSize" ], "type": "object" }, "Type": { "enum": [ "AWS::AutoScaling::AutoScalingGroup" ], "type": "string" }, "UpdatePolicy": { "type": "object" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::AutoScaling::AutoScalingGroup.LifecycleHookSpecification": { "additionalProperties": false, "properties": { "DefaultResult": { "type": "string" }, "HeartbeatTimeout": { "type": "number" }, "LifecycleHookName": { "type": "string" }, "LifecycleTransition": { "type": "string" }, "NotificationMetadata": { "type": "string" }, "NotificationTargetARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "LifecycleHookName", "LifecycleTransition" ], "type": "object" }, "AWS::AutoScaling::AutoScalingGroup.MetricsCollection": { "additionalProperties": false, "properties": { "Granularity": { "type": "string" }, "Metrics": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Granularity" ], "type": "object" }, "AWS::AutoScaling::AutoScalingGroup.NotificationConfiguration": { "additionalProperties": false, "properties": { "NotificationTypes": { "items": { "type": "string" }, "type": "array" }, "TopicARN": { "type": "string" } }, "required": [ "TopicARN" ], "type": "object" }, "AWS::AutoScaling::AutoScalingGroup.TagProperty": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "PropagateAtLaunch": { "type": "boolean" }, "Value": { "type": "string" } }, "required": [ "Key", "PropagateAtLaunch", "Value" ], "type": "object" }, "AWS::AutoScaling::LaunchConfiguration": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AssociatePublicIpAddress": { "type": "boolean" }, "BlockDeviceMappings": { "items": { "$ref": "#/definitions/AWS::AutoScaling::LaunchConfiguration.BlockDeviceMapping" }, "type": "array" }, "ClassicLinkVPCId": { "type": "string" }, "ClassicLinkVPCSecurityGroups": { "items": { "type": "string" }, "type": "array" }, "EbsOptimized": { "type": "boolean" }, "IamInstanceProfile": { "type": "string" }, "ImageId": { "type": "string" }, "InstanceId": { "type": "string" }, "InstanceMonitoring": { "type": "boolean" }, "InstanceType": { "type": "string" }, "KernelId": { "type": "string" }, "KeyName": { "type": "string" }, "PlacementTenancy": { "type": "string" }, "RamDiskId": { "type": "string" }, "SecurityGroups": { "items": { "type": "string" }, "type": "array" }, "SpotPrice": { "type": "string" }, "UserData": { "type": "string" } }, "required": [ "ImageId", "InstanceType" ], "type": "object" }, "Type": { "enum": [ "AWS::AutoScaling::LaunchConfiguration" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::AutoScaling::LaunchConfiguration.BlockDevice": { "additionalProperties": false, "properties": { "DeleteOnTermination": { "type": "boolean" }, "Encrypted": { "type": "boolean" }, "Iops": { "type": "number" }, "SnapshotId": { "type": "string" }, "VolumeSize": { "type": "number" }, "VolumeType": { "type": "string" } }, "type": "object" }, "AWS::AutoScaling::LaunchConfiguration.BlockDeviceMapping": { "additionalProperties": false, "properties": { "DeviceName": { "type": "string" }, "Ebs": { "$ref": "#/definitions/AWS::AutoScaling::LaunchConfiguration.BlockDevice" }, "NoDevice": { "type": "boolean" }, "VirtualName": { "type": "string" } }, "required": [ "DeviceName" ], "type": "object" }, "AWS::AutoScaling::LifecycleHook": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AutoScalingGroupName": { "type": "string" }, "DefaultResult": { "type": "string" }, "HeartbeatTimeout": { "type": "number" }, "LifecycleHookName": { "type": "string" }, "LifecycleTransition": { "type": "string" }, "NotificationMetadata": { "type": "string" }, "NotificationTargetARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "AutoScalingGroupName", "LifecycleTransition" ], "type": "object" }, "Type": { "enum": [ "AWS::AutoScaling::LifecycleHook" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::AutoScaling::ScalingPolicy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AdjustmentType": { "type": "string" }, "AutoScalingGroupName": { "type": "string" }, "Cooldown": { "type": "string" }, "EstimatedInstanceWarmup": { "type": "number" }, "MetricAggregationType": { "type": "string" }, "MinAdjustmentMagnitude": { "type": "number" }, "PolicyType": { "type": "string" }, "ScalingAdjustment": { "type": "number" }, "StepAdjustments": { "items": { "$ref": "#/definitions/AWS::AutoScaling::ScalingPolicy.StepAdjustment" }, "type": "array" }, "TargetTrackingConfiguration": { "$ref": "#/definitions/AWS::AutoScaling::ScalingPolicy.TargetTrackingConfiguration" } }, "required": [ "AutoScalingGroupName" ], "type": "object" }, "Type": { "enum": [ "AWS::AutoScaling::ScalingPolicy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::AutoScaling::ScalingPolicy.CustomizedMetricSpecification": { "additionalProperties": false, "properties": { "Dimensions": { "items": { "$ref": "#/definitions/AWS::AutoScaling::ScalingPolicy.MetricDimension" }, "type": "array" }, "MetricName": { "type": "string" }, "Namespace": { "type": "string" }, "Statistic": { "type": "string" }, "Unit": { "type": "string" } }, "required": [ "MetricName", "Namespace", "Statistic" ], "type": "object" }, "AWS::AutoScaling::ScalingPolicy.MetricDimension": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Name", "Value" ], "type": "object" }, "AWS::AutoScaling::ScalingPolicy.PredefinedMetricSpecification": { "additionalProperties": false, "properties": { "PredefinedMetricType": { "type": "string" }, "ResourceLabel": { "type": "string" } }, "required": [ "PredefinedMetricType" ], "type": "object" }, "AWS::AutoScaling::ScalingPolicy.StepAdjustment": { "additionalProperties": false, "properties": { "MetricIntervalLowerBound": { "type": "number" }, "MetricIntervalUpperBound": { "type": "number" }, "ScalingAdjustment": { "type": "number" } }, "required": [ "ScalingAdjustment" ], "type": "object" }, "AWS::AutoScaling::ScalingPolicy.TargetTrackingConfiguration": { "additionalProperties": false, "properties": { "CustomizedMetricSpecification": { "$ref": "#/definitions/AWS::AutoScaling::ScalingPolicy.CustomizedMetricSpecification" }, "DisableScaleIn": { "type": "boolean" }, "PredefinedMetricSpecification": { "$ref": "#/definitions/AWS::AutoScaling::ScalingPolicy.PredefinedMetricSpecification" }, "TargetValue": { "type": "number" } }, "required": [ "TargetValue" ], "type": "object" }, "AWS::AutoScaling::ScheduledAction": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AutoScalingGroupName": { "type": "string" }, "DesiredCapacity": { "type": "number" }, "EndTime": { "type": "string" }, "MaxSize": { "type": "number" }, "MinSize": { "type": "number" }, "Recurrence": { "type": "string" }, "StartTime": { "type": "string" } }, "required": [ "AutoScalingGroupName" ], "type": "object" }, "Type": { "enum": [ "AWS::AutoScaling::ScheduledAction" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Batch::ComputeEnvironment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ComputeEnvironmentName": { "type": "string" }, "ComputeResources": { "$ref": "#/definitions/AWS::Batch::ComputeEnvironment.ComputeResources" }, "ServiceRole": { "type": "string" }, "State": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "ComputeResources", "ServiceRole", "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::Batch::ComputeEnvironment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Batch::ComputeEnvironment.ComputeResources": { "additionalProperties": false, "properties": { "BidPercentage": { "type": "number" }, "DesiredvCpus": { "type": "number" }, "Ec2KeyPair": { "type": "string" }, "ImageId": { "type": "string" }, "InstanceRole": { "type": "string" }, "InstanceTypes": { "items": { "type": "string" }, "type": "array" }, "MaxvCpus": { "type": "number" }, "MinvCpus": { "type": "number" }, "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SpotIamFleetRole": { "type": "string" }, "Subnets": { "items": { "type": "string" }, "type": "array" }, "Tags": { "type": "object" }, "Type": { "type": "string" } }, "required": [ "InstanceRole", "InstanceTypes", "MaxvCpus", "MinvCpus", "SecurityGroupIds", "Subnets", "Type" ], "type": "object" }, "AWS::Batch::JobDefinition": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ContainerProperties": { "$ref": "#/definitions/AWS::Batch::JobDefinition.ContainerProperties" }, "JobDefinitionName": { "type": "string" }, "Parameters": { "type": "object" }, "RetryStrategy": { "$ref": "#/definitions/AWS::Batch::JobDefinition.RetryStrategy" }, "Type": { "type": "string" } }, "required": [ "ContainerProperties", "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::Batch::JobDefinition" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Batch::JobDefinition.ContainerProperties": { "additionalProperties": false, "properties": { "Command": { "items": { "type": "string" }, "type": "array" }, "Environment": { "items": { "$ref": "#/definitions/AWS::Batch::JobDefinition.Environment" }, "type": "array" }, "Image": { "type": "string" }, "JobRoleArn": { "type": "string" }, "Memory": { "type": "number" }, "MountPoints": { "items": { "$ref": "#/definitions/AWS::Batch::JobDefinition.MountPoints" }, "type": "array" }, "Privileged": { "type": "boolean" }, "ReadonlyRootFilesystem": { "type": "boolean" }, "Ulimits": { "items": { "$ref": "#/definitions/AWS::Batch::JobDefinition.Ulimit" }, "type": "array" }, "User": { "type": "string" }, "Vcpus": { "type": "number" }, "Volumes": { "items": { "$ref": "#/definitions/AWS::Batch::JobDefinition.Volumes" }, "type": "array" } }, "required": [ "Image", "Memory", "Vcpus" ], "type": "object" }, "AWS::Batch::JobDefinition.Environment": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::Batch::JobDefinition.MountPoints": { "additionalProperties": false, "properties": { "ContainerPath": { "type": "string" }, "ReadOnly": { "type": "boolean" }, "SourceVolume": { "type": "string" } }, "type": "object" }, "AWS::Batch::JobDefinition.RetryStrategy": { "additionalProperties": false, "properties": { "Attempts": { "type": "number" } }, "type": "object" }, "AWS::Batch::JobDefinition.Ulimit": { "additionalProperties": false, "properties": { "HardLimit": { "type": "number" }, "Name": { "type": "string" }, "SoftLimit": { "type": "number" } }, "required": [ "HardLimit", "Name", "SoftLimit" ], "type": "object" }, "AWS::Batch::JobDefinition.Volumes": { "additionalProperties": false, "properties": { "Host": { "$ref": "#/definitions/AWS::Batch::JobDefinition.VolumesHost" }, "Name": { "type": "string" } }, "type": "object" }, "AWS::Batch::JobDefinition.VolumesHost": { "additionalProperties": false, "properties": { "SourcePath": { "type": "string" } }, "type": "object" }, "AWS::Batch::JobQueue": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ComputeEnvironmentOrder": { "items": { "$ref": "#/definitions/AWS::Batch::JobQueue.ComputeEnvironmentOrder" }, "type": "array" }, "JobQueueName": { "type": "string" }, "Priority": { "type": "number" }, "State": { "type": "string" } }, "required": [ "ComputeEnvironmentOrder", "Priority" ], "type": "object" }, "Type": { "enum": [ "AWS::Batch::JobQueue" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Batch::JobQueue.ComputeEnvironmentOrder": { "additionalProperties": false, "properties": { "ComputeEnvironment": { "type": "string" }, "Order": { "type": "number" } }, "required": [ "ComputeEnvironment", "Order" ], "type": "object" }, "AWS::CertificateManager::Certificate": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DomainName": { "type": "string" }, "DomainValidationOptions": { "items": { "$ref": "#/definitions/AWS::CertificateManager::Certificate.DomainValidationOption" }, "type": "array" }, "SubjectAlternativeNames": { "items": { "type": "string" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "DomainName" ], "type": "object" }, "Type": { "enum": [ "AWS::CertificateManager::Certificate" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CertificateManager::Certificate.DomainValidationOption": { "additionalProperties": false, "properties": { "DomainName": { "type": "string" }, "ValidationDomain": { "type": "string" } }, "required": [ "DomainName", "ValidationDomain" ], "type": "object" }, "AWS::Cloud9::EnvironmentEC2": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AutomaticStopTimeMinutes": { "type": "number" }, "Description": { "type": "string" }, "InstanceType": { "type": "string" }, "Name": { "type": "string" }, "OwnerArn": { "type": "string" }, "Repositories": { "items": { "$ref": "#/definitions/AWS::Cloud9::EnvironmentEC2.Repository" }, "type": "array" }, "SubnetId": { "type": "string" } }, "required": [ "InstanceType" ], "type": "object" }, "Type": { "enum": [ "AWS::Cloud9::EnvironmentEC2" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Cloud9::EnvironmentEC2.Repository": { "additionalProperties": false, "properties": { "PathComponent": { "type": "string" }, "RepositoryUrl": { "type": "string" } }, "required": [ "PathComponent", "RepositoryUrl" ], "type": "object" }, "AWS::CloudFormation::CustomResource": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ServiceToken": { "type": "string" } }, "required": [ "ServiceToken" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudFormation::CustomResource" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudFormation::Stack": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "NotificationARNs": { "items": { "type": "string" }, "type": "array" }, "Parameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TemplateURL": { "type": "string" }, "TimeoutInMinutes": { "type": "number" } }, "required": [ "TemplateURL" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudFormation::Stack" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudFormation::WaitCondition": { "additionalProperties": false, "properties": { "CreationPolicy": { "type": "object" }, "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Count": { "type": "number" }, "Handle": { "type": "string" }, "Timeout": { "type": "string" } }, "required": [ "Handle", "Timeout" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudFormation::WaitCondition" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudFormation::WaitConditionHandle": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": {}, "type": "object" }, "Type": { "enum": [ "AWS::CloudFormation::WaitConditionHandle" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::CloudFront::CloudFrontOriginAccessIdentity": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CloudFrontOriginAccessIdentityConfig": { "$ref": "#/definitions/AWS::CloudFront::CloudFrontOriginAccessIdentity.CloudFrontOriginAccessIdentityConfig" } }, "required": [ "CloudFrontOriginAccessIdentityConfig" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudFront::CloudFrontOriginAccessIdentity" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudFront::CloudFrontOriginAccessIdentity.CloudFrontOriginAccessIdentityConfig": { "additionalProperties": false, "properties": { "Comment": { "type": "string" } }, "required": [ "Comment" ], "type": "object" }, "AWS::CloudFront::Distribution": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DistributionConfig": { "$ref": "#/definitions/AWS::CloudFront::Distribution.DistributionConfig" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "DistributionConfig" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudFront::Distribution" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudFront::Distribution.CacheBehavior": { "additionalProperties": false, "properties": { "AllowedMethods": { "items": { "type": "string" }, "type": "array" }, "CachedMethods": { "items": { "type": "string" }, "type": "array" }, "Compress": { "type": "boolean" }, "DefaultTTL": { "type": "number" }, "ForwardedValues": { "$ref": "#/definitions/AWS::CloudFront::Distribution.ForwardedValues" }, "LambdaFunctionAssociations": { "items": { "$ref": "#/definitions/AWS::CloudFront::Distribution.LambdaFunctionAssociation" }, "type": "array" }, "MaxTTL": { "type": "number" }, "MinTTL": { "type": "number" }, "PathPattern": { "type": "string" }, "SmoothStreaming": { "type": "boolean" }, "TargetOriginId": { "type": "string" }, "TrustedSigners": { "items": { "type": "string" }, "type": "array" }, "ViewerProtocolPolicy": { "type": "string" } }, "required": [ "ForwardedValues", "PathPattern", "TargetOriginId", "ViewerProtocolPolicy" ], "type": "object" }, "AWS::CloudFront::Distribution.Cookies": { "additionalProperties": false, "properties": { "Forward": { "type": "string" }, "WhitelistedNames": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Forward" ], "type": "object" }, "AWS::CloudFront::Distribution.CustomErrorResponse": { "additionalProperties": false, "properties": { "ErrorCachingMinTTL": { "type": "number" }, "ErrorCode": { "type": "number" }, "ResponseCode": { "type": "number" }, "ResponsePagePath": { "type": "string" } }, "required": [ "ErrorCode" ], "type": "object" }, "AWS::CloudFront::Distribution.CustomOriginConfig": { "additionalProperties": false, "properties": { "HTTPPort": { "type": "number" }, "HTTPSPort": { "type": "number" }, "OriginKeepaliveTimeout": { "type": "number" }, "OriginProtocolPolicy": { "type": "string" }, "OriginReadTimeout": { "type": "number" }, "OriginSSLProtocols": { "items": { "type": "string" }, "type": "array" } }, "required": [ "OriginProtocolPolicy" ], "type": "object" }, "AWS::CloudFront::Distribution.DefaultCacheBehavior": { "additionalProperties": false, "properties": { "AllowedMethods": { "items": { "type": "string" }, "type": "array" }, "CachedMethods": { "items": { "type": "string" }, "type": "array" }, "Compress": { "type": "boolean" }, "DefaultTTL": { "type": "number" }, "ForwardedValues": { "$ref": "#/definitions/AWS::CloudFront::Distribution.ForwardedValues" }, "LambdaFunctionAssociations": { "items": { "$ref": "#/definitions/AWS::CloudFront::Distribution.LambdaFunctionAssociation" }, "type": "array" }, "MaxTTL": { "type": "number" }, "MinTTL": { "type": "number" }, "SmoothStreaming": { "type": "boolean" }, "TargetOriginId": { "type": "string" }, "TrustedSigners": { "items": { "type": "string" }, "type": "array" }, "ViewerProtocolPolicy": { "type": "string" } }, "required": [ "ForwardedValues", "TargetOriginId", "ViewerProtocolPolicy" ], "type": "object" }, "AWS::CloudFront::Distribution.DistributionConfig": { "additionalProperties": false, "properties": { "Aliases": { "items": { "type": "string" }, "type": "array" }, "CacheBehaviors": { "items": { "$ref": "#/definitions/AWS::CloudFront::Distribution.CacheBehavior" }, "type": "array" }, "Comment": { "type": "string" }, "CustomErrorResponses": { "items": { "$ref": "#/definitions/AWS::CloudFront::Distribution.CustomErrorResponse" }, "type": "array" }, "DefaultCacheBehavior": { "$ref": "#/definitions/AWS::CloudFront::Distribution.DefaultCacheBehavior" }, "DefaultRootObject": { "type": "string" }, "Enabled": { "type": "boolean" }, "HttpVersion": { "type": "string" }, "IPV6Enabled": { "type": "boolean" }, "Logging": { "$ref": "#/definitions/AWS::CloudFront::Distribution.Logging" }, "Origins": { "items": { "$ref": "#/definitions/AWS::CloudFront::Distribution.Origin" }, "type": "array" }, "PriceClass": { "type": "string" }, "Restrictions": { "$ref": "#/definitions/AWS::CloudFront::Distribution.Restrictions" }, "ViewerCertificate": { "$ref": "#/definitions/AWS::CloudFront::Distribution.ViewerCertificate" }, "WebACLId": { "type": "string" } }, "required": [ "Enabled" ], "type": "object" }, "AWS::CloudFront::Distribution.ForwardedValues": { "additionalProperties": false, "properties": { "Cookies": { "$ref": "#/definitions/AWS::CloudFront::Distribution.Cookies" }, "Headers": { "items": { "type": "string" }, "type": "array" }, "QueryString": { "type": "boolean" }, "QueryStringCacheKeys": { "items": { "type": "string" }, "type": "array" } }, "required": [ "QueryString" ], "type": "object" }, "AWS::CloudFront::Distribution.GeoRestriction": { "additionalProperties": false, "properties": { "Locations": { "items": { "type": "string" }, "type": "array" }, "RestrictionType": { "type": "string" } }, "required": [ "RestrictionType" ], "type": "object" }, "AWS::CloudFront::Distribution.LambdaFunctionAssociation": { "additionalProperties": false, "properties": { "EventType": { "type": "string" }, "LambdaFunctionARN": { "type": "string" } }, "type": "object" }, "AWS::CloudFront::Distribution.Logging": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "IncludeCookies": { "type": "boolean" }, "Prefix": { "type": "string" } }, "required": [ "Bucket" ], "type": "object" }, "AWS::CloudFront::Distribution.Origin": { "additionalProperties": false, "properties": { "CustomOriginConfig": { "$ref": "#/definitions/AWS::CloudFront::Distribution.CustomOriginConfig" }, "DomainName": { "type": "string" }, "Id": { "type": "string" }, "OriginCustomHeaders": { "items": { "$ref": "#/definitions/AWS::CloudFront::Distribution.OriginCustomHeader" }, "type": "array" }, "OriginPath": { "type": "string" }, "S3OriginConfig": { "$ref": "#/definitions/AWS::CloudFront::Distribution.S3OriginConfig" } }, "required": [ "DomainName", "Id" ], "type": "object" }, "AWS::CloudFront::Distribution.OriginCustomHeader": { "additionalProperties": false, "properties": { "HeaderName": { "type": "string" }, "HeaderValue": { "type": "string" } }, "required": [ "HeaderName", "HeaderValue" ], "type": "object" }, "AWS::CloudFront::Distribution.Restrictions": { "additionalProperties": false, "properties": { "GeoRestriction": { "$ref": "#/definitions/AWS::CloudFront::Distribution.GeoRestriction" } }, "required": [ "GeoRestriction" ], "type": "object" }, "AWS::CloudFront::Distribution.S3OriginConfig": { "additionalProperties": false, "properties": { "OriginAccessIdentity": { "type": "string" } }, "type": "object" }, "AWS::CloudFront::Distribution.ViewerCertificate": { "additionalProperties": false, "properties": { "AcmCertificateArn": { "type": "string" }, "CloudFrontDefaultCertificate": { "type": "boolean" }, "IamCertificateId": { "type": "string" }, "MinimumProtocolVersion": { "type": "string" }, "SslSupportMethod": { "type": "string" } }, "type": "object" }, "AWS::CloudFront::StreamingDistribution": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "StreamingDistributionConfig": { "$ref": "#/definitions/AWS::CloudFront::StreamingDistribution.StreamingDistributionConfig" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "StreamingDistributionConfig", "Tags" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudFront::StreamingDistribution" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudFront::StreamingDistribution.Logging": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "Enabled": { "type": "boolean" }, "Prefix": { "type": "string" } }, "required": [ "Bucket", "Enabled", "Prefix" ], "type": "object" }, "AWS::CloudFront::StreamingDistribution.S3Origin": { "additionalProperties": false, "properties": { "DomainName": { "type": "string" }, "OriginAccessIdentity": { "type": "string" } }, "required": [ "DomainName", "OriginAccessIdentity" ], "type": "object" }, "AWS::CloudFront::StreamingDistribution.StreamingDistributionConfig": { "additionalProperties": false, "properties": { "Aliases": { "items": { "type": "string" }, "type": "array" }, "Comment": { "type": "string" }, "Enabled": { "type": "boolean" }, "Logging": { "$ref": "#/definitions/AWS::CloudFront::StreamingDistribution.Logging" }, "PriceClass": { "type": "string" }, "S3Origin": { "$ref": "#/definitions/AWS::CloudFront::StreamingDistribution.S3Origin" }, "TrustedSigners": { "$ref": "#/definitions/AWS::CloudFront::StreamingDistribution.TrustedSigners" } }, "required": [ "Comment", "Enabled", "S3Origin", "TrustedSigners" ], "type": "object" }, "AWS::CloudFront::StreamingDistribution.TrustedSigners": { "additionalProperties": false, "properties": { "AwsAccountNumbers": { "items": { "type": "string" }, "type": "array" }, "Enabled": { "type": "boolean" } }, "required": [ "Enabled" ], "type": "object" }, "AWS::CloudTrail::Trail": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CloudWatchLogsLogGroupArn": { "type": "string" }, "CloudWatchLogsRoleArn": { "type": "string" }, "EnableLogFileValidation": { "type": "boolean" }, "EventSelectors": { "items": { "$ref": "#/definitions/AWS::CloudTrail::Trail.EventSelector" }, "type": "array" }, "IncludeGlobalServiceEvents": { "type": "boolean" }, "IsLogging": { "type": "boolean" }, "IsMultiRegionTrail": { "type": "boolean" }, "KMSKeyId": { "type": "string" }, "S3BucketName": { "type": "string" }, "S3KeyPrefix": { "type": "string" }, "SnsTopicName": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TrailName": { "type": "string" } }, "required": [ "IsLogging", "S3BucketName" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudTrail::Trail" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudTrail::Trail.DataResource": { "additionalProperties": false, "properties": { "Type": { "type": "string" }, "Values": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Type" ], "type": "object" }, "AWS::CloudTrail::Trail.EventSelector": { "additionalProperties": false, "properties": { "DataResources": { "items": { "$ref": "#/definitions/AWS::CloudTrail::Trail.DataResource" }, "type": "array" }, "IncludeManagementEvents": { "type": "boolean" }, "ReadWriteType": { "type": "string" } }, "type": "object" }, "AWS::CloudWatch::Alarm": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ActionsEnabled": { "type": "boolean" }, "AlarmActions": { "items": { "type": "string" }, "type": "array" }, "AlarmDescription": { "type": "string" }, "AlarmName": { "type": "string" }, "ComparisonOperator": { "type": "string" }, "Dimensions": { "items": { "$ref": "#/definitions/AWS::CloudWatch::Alarm.Dimension" }, "type": "array" }, "EvaluateLowSampleCountPercentile": { "type": "string" }, "EvaluationPeriods": { "type": "number" }, "ExtendedStatistic": { "type": "string" }, "InsufficientDataActions": { "items": { "type": "string" }, "type": "array" }, "MetricName": { "type": "string" }, "Namespace": { "type": "string" }, "OKActions": { "items": { "type": "string" }, "type": "array" }, "Period": { "type": "number" }, "Statistic": { "type": "string" }, "Threshold": { "type": "number" }, "TreatMissingData": { "type": "string" }, "Unit": { "type": "string" } }, "required": [ "ComparisonOperator", "EvaluationPeriods", "MetricName", "Namespace", "Period", "Threshold" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudWatch::Alarm" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CloudWatch::Alarm.Dimension": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Name", "Value" ], "type": "object" }, "AWS::CloudWatch::Dashboard": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DashboardBody": { "type": "string" }, "DashboardName": { "type": "string" } }, "required": [ "DashboardBody" ], "type": "object" }, "Type": { "enum": [ "AWS::CloudWatch::Dashboard" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CodeBuild::Project": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Artifacts": { "$ref": "#/definitions/AWS::CodeBuild::Project.Artifacts" }, "BadgeEnabled": { "type": "boolean" }, "Cache": { "$ref": "#/definitions/AWS::CodeBuild::Project.ProjectCache" }, "Description": { "type": "string" }, "EncryptionKey": { "type": "string" }, "Environment": { "$ref": "#/definitions/AWS::CodeBuild::Project.Environment" }, "Name": { "type": "string" }, "ServiceRole": { "type": "string" }, "Source": { "$ref": "#/definitions/AWS::CodeBuild::Project.Source" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TimeoutInMinutes": { "type": "number" }, "Triggers": { "$ref": "#/definitions/AWS::CodeBuild::Project.ProjectTriggers" }, "VpcConfig": { "$ref": "#/definitions/AWS::CodeBuild::Project.VpcConfig" } }, "required": [ "Artifacts", "Environment", "ServiceRole", "Source" ], "type": "object" }, "Type": { "enum": [ "AWS::CodeBuild::Project" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CodeBuild::Project.Artifacts": { "additionalProperties": false, "properties": { "Location": { "type": "string" }, "Name": { "type": "string" }, "NamespaceType": { "type": "string" }, "Packaging": { "type": "string" }, "Path": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::CodeBuild::Project.Environment": { "additionalProperties": false, "properties": { "ComputeType": { "type": "string" }, "EnvironmentVariables": { "items": { "$ref": "#/definitions/AWS::CodeBuild::Project.EnvironmentVariable" }, "type": "array" }, "Image": { "type": "string" }, "PrivilegedMode": { "type": "boolean" }, "Type": { "type": "string" } }, "required": [ "ComputeType", "Image", "Type" ], "type": "object" }, "AWS::CodeBuild::Project.EnvironmentVariable": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Type": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Name", "Value" ], "type": "object" }, "AWS::CodeBuild::Project.ProjectCache": { "additionalProperties": false, "properties": { "Location": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::CodeBuild::Project.ProjectTriggers": { "additionalProperties": false, "properties": { "Webhook": { "type": "boolean" } }, "type": "object" }, "AWS::CodeBuild::Project.Source": { "additionalProperties": false, "properties": { "Auth": { "$ref": "#/definitions/AWS::CodeBuild::Project.SourceAuth" }, "BuildSpec": { "type": "string" }, "GitCloneDepth": { "type": "number" }, "InsecureSsl": { "type": "boolean" }, "Location": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::CodeBuild::Project.SourceAuth": { "additionalProperties": false, "properties": { "Resource": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::CodeBuild::Project.VpcConfig": { "additionalProperties": false, "properties": { "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "Subnets": { "items": { "type": "string" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "SecurityGroupIds", "Subnets", "VpcId" ], "type": "object" }, "AWS::CodeCommit::Repository": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "RepositoryDescription": { "type": "string" }, "RepositoryName": { "type": "string" }, "Triggers": { "items": { "$ref": "#/definitions/AWS::CodeCommit::Repository.RepositoryTrigger" }, "type": "array" } }, "required": [ "RepositoryName" ], "type": "object" }, "Type": { "enum": [ "AWS::CodeCommit::Repository" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CodeCommit::Repository.RepositoryTrigger": { "additionalProperties": false, "properties": { "Branches": { "items": { "type": "string" }, "type": "array" }, "CustomData": { "type": "string" }, "DestinationArn": { "type": "string" }, "Events": { "items": { "type": "string" }, "type": "array" }, "Name": { "type": "string" } }, "type": "object" }, "AWS::CodeDeploy::Application": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "ComputePlatform": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::CodeDeploy::Application" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::CodeDeploy::DeploymentConfig": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DeploymentConfigName": { "type": "string" }, "MinimumHealthyHosts": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentConfig.MinimumHealthyHosts" } }, "type": "object" }, "Type": { "enum": [ "AWS::CodeDeploy::DeploymentConfig" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::CodeDeploy::DeploymentConfig.MinimumHealthyHosts": { "additionalProperties": false, "properties": { "Type": { "type": "string" }, "Value": { "type": "number" } }, "required": [ "Type", "Value" ], "type": "object" }, "AWS::CodeDeploy::DeploymentGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AlarmConfiguration": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.AlarmConfiguration" }, "ApplicationName": { "type": "string" }, "AutoRollbackConfiguration": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.AutoRollbackConfiguration" }, "AutoScalingGroups": { "items": { "type": "string" }, "type": "array" }, "Deployment": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.Deployment" }, "DeploymentConfigName": { "type": "string" }, "DeploymentGroupName": { "type": "string" }, "DeploymentStyle": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.DeploymentStyle" }, "Ec2TagFilters": { "items": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.EC2TagFilter" }, "type": "array" }, "LoadBalancerInfo": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.LoadBalancerInfo" }, "OnPremisesInstanceTagFilters": { "items": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.TagFilter" }, "type": "array" }, "ServiceRoleArn": { "type": "string" }, "TriggerConfigurations": { "items": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.TriggerConfig" }, "type": "array" } }, "required": [ "ApplicationName", "ServiceRoleArn" ], "type": "object" }, "Type": { "enum": [ "AWS::CodeDeploy::DeploymentGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.Alarm": { "additionalProperties": false, "properties": { "Name": { "type": "string" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.AlarmConfiguration": { "additionalProperties": false, "properties": { "Alarms": { "items": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.Alarm" }, "type": "array" }, "Enabled": { "type": "boolean" }, "IgnorePollAlarmFailure": { "type": "boolean" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.AutoRollbackConfiguration": { "additionalProperties": false, "properties": { "Enabled": { "type": "boolean" }, "Events": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.Deployment": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "IgnoreApplicationStopFailures": { "type": "boolean" }, "Revision": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.RevisionLocation" } }, "required": [ "Revision" ], "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.DeploymentStyle": { "additionalProperties": false, "properties": { "DeploymentOption": { "type": "string" }, "DeploymentType": { "type": "string" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.EC2TagFilter": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Type": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.ELBInfo": { "additionalProperties": false, "properties": { "Name": { "type": "string" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.GitHubLocation": { "additionalProperties": false, "properties": { "CommitId": { "type": "string" }, "Repository": { "type": "string" } }, "required": [ "CommitId", "Repository" ], "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.LoadBalancerInfo": { "additionalProperties": false, "properties": { "ElbInfoList": { "items": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.ELBInfo" }, "type": "array" }, "TargetGroupInfoList": { "items": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.TargetGroupInfo" }, "type": "array" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.RevisionLocation": { "additionalProperties": false, "properties": { "GitHubLocation": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.GitHubLocation" }, "RevisionType": { "type": "string" }, "S3Location": { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup.S3Location" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.S3Location": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "BundleType": { "type": "string" }, "ETag": { "type": "string" }, "Key": { "type": "string" }, "Version": { "type": "string" } }, "required": [ "Bucket", "Key" ], "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.TagFilter": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Type": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.TargetGroupInfo": { "additionalProperties": false, "properties": { "Name": { "type": "string" } }, "type": "object" }, "AWS::CodeDeploy::DeploymentGroup.TriggerConfig": { "additionalProperties": false, "properties": { "TriggerEvents": { "items": { "type": "string" }, "type": "array" }, "TriggerName": { "type": "string" }, "TriggerTargetArn": { "type": "string" } }, "type": "object" }, "AWS::CodePipeline::CustomActionType": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Category": { "type": "string" }, "ConfigurationProperties": { "items": { "$ref": "#/definitions/AWS::CodePipeline::CustomActionType.ConfigurationProperties" }, "type": "array" }, "InputArtifactDetails": { "$ref": "#/definitions/AWS::CodePipeline::CustomActionType.ArtifactDetails" }, "OutputArtifactDetails": { "$ref": "#/definitions/AWS::CodePipeline::CustomActionType.ArtifactDetails" }, "Provider": { "type": "string" }, "Settings": { "$ref": "#/definitions/AWS::CodePipeline::CustomActionType.Settings" }, "Version": { "type": "string" } }, "required": [ "Category", "InputArtifactDetails", "OutputArtifactDetails", "Provider" ], "type": "object" }, "Type": { "enum": [ "AWS::CodePipeline::CustomActionType" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CodePipeline::CustomActionType.ArtifactDetails": { "additionalProperties": false, "properties": { "MaximumCount": { "type": "number" }, "MinimumCount": { "type": "number" } }, "required": [ "MaximumCount", "MinimumCount" ], "type": "object" }, "AWS::CodePipeline::CustomActionType.ConfigurationProperties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Key": { "type": "boolean" }, "Name": { "type": "string" }, "Queryable": { "type": "boolean" }, "Required": { "type": "boolean" }, "Secret": { "type": "boolean" }, "Type": { "type": "string" } }, "required": [ "Key", "Name", "Required", "Secret" ], "type": "object" }, "AWS::CodePipeline::CustomActionType.Settings": { "additionalProperties": false, "properties": { "EntityUrlTemplate": { "type": "string" }, "ExecutionUrlTemplate": { "type": "string" }, "RevisionUrlTemplate": { "type": "string" }, "ThirdPartyConfigurationUrl": { "type": "string" } }, "type": "object" }, "AWS::CodePipeline::Pipeline": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ArtifactStore": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.ArtifactStore" }, "DisableInboundStageTransitions": { "items": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.StageTransition" }, "type": "array" }, "Name": { "type": "string" }, "RestartExecutionOnUpdate": { "type": "boolean" }, "RoleArn": { "type": "string" }, "Stages": { "items": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.StageDeclaration" }, "type": "array" } }, "required": [ "ArtifactStore", "RoleArn", "Stages" ], "type": "object" }, "Type": { "enum": [ "AWS::CodePipeline::Pipeline" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::CodePipeline::Pipeline.ActionDeclaration": { "additionalProperties": false, "properties": { "ActionTypeId": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.ActionTypeId" }, "Configuration": { "type": "object" }, "InputArtifacts": { "items": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.InputArtifact" }, "type": "array" }, "Name": { "type": "string" }, "OutputArtifacts": { "items": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.OutputArtifact" }, "type": "array" }, "RoleArn": { "type": "string" }, "RunOrder": { "type": "number" } }, "required": [ "ActionTypeId", "Name" ], "type": "object" }, "AWS::CodePipeline::Pipeline.ActionTypeId": { "additionalProperties": false, "properties": { "Category": { "type": "string" }, "Owner": { "type": "string" }, "Provider": { "type": "string" }, "Version": { "type": "string" } }, "required": [ "Category", "Owner", "Provider", "Version" ], "type": "object" }, "AWS::CodePipeline::Pipeline.ArtifactStore": { "additionalProperties": false, "properties": { "EncryptionKey": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.EncryptionKey" }, "Location": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Location", "Type" ], "type": "object" }, "AWS::CodePipeline::Pipeline.BlockerDeclaration": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Name", "Type" ], "type": "object" }, "AWS::CodePipeline::Pipeline.EncryptionKey": { "additionalProperties": false, "properties": { "Id": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Id", "Type" ], "type": "object" }, "AWS::CodePipeline::Pipeline.InputArtifact": { "additionalProperties": false, "properties": { "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "AWS::CodePipeline::Pipeline.OutputArtifact": { "additionalProperties": false, "properties": { "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "AWS::CodePipeline::Pipeline.StageDeclaration": { "additionalProperties": false, "properties": { "Actions": { "items": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.ActionDeclaration" }, "type": "array" }, "Blockers": { "items": { "$ref": "#/definitions/AWS::CodePipeline::Pipeline.BlockerDeclaration" }, "type": "array" }, "Name": { "type": "string" } }, "required": [ "Actions", "Name" ], "type": "object" }, "AWS::CodePipeline::Pipeline.StageTransition": { "additionalProperties": false, "properties": { "Reason": { "type": "string" }, "StageName": { "type": "string" } }, "required": [ "Reason", "StageName" ], "type": "object" }, "AWS::Cognito::IdentityPool": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllowUnauthenticatedIdentities": { "type": "boolean" }, "CognitoEvents": { "type": "object" }, "CognitoIdentityProviders": { "items": { "$ref": "#/definitions/AWS::Cognito::IdentityPool.CognitoIdentityProvider" }, "type": "array" }, "CognitoStreams": { "$ref": "#/definitions/AWS::Cognito::IdentityPool.CognitoStreams" }, "DeveloperProviderName": { "type": "string" }, "IdentityPoolName": { "type": "string" }, "OpenIdConnectProviderARNs": { "items": { "type": "string" }, "type": "array" }, "PushSync": { "$ref": "#/definitions/AWS::Cognito::IdentityPool.PushSync" }, "SamlProviderARNs": { "items": { "type": "string" }, "type": "array" }, "SupportedLoginProviders": { "type": "object" } }, "required": [ "AllowUnauthenticatedIdentities" ], "type": "object" }, "Type": { "enum": [ "AWS::Cognito::IdentityPool" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Cognito::IdentityPool.CognitoIdentityProvider": { "additionalProperties": false, "properties": { "ClientId": { "type": "string" }, "ProviderName": { "type": "string" }, "ServerSideTokenCheck": { "type": "boolean" } }, "type": "object" }, "AWS::Cognito::IdentityPool.CognitoStreams": { "additionalProperties": false, "properties": { "RoleArn": { "type": "string" }, "StreamName": { "type": "string" }, "StreamingStatus": { "type": "string" } }, "type": "object" }, "AWS::Cognito::IdentityPool.PushSync": { "additionalProperties": false, "properties": { "ApplicationArns": { "items": { "type": "string" }, "type": "array" }, "RoleArn": { "type": "string" } }, "type": "object" }, "AWS::Cognito::IdentityPoolRoleAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "IdentityPoolId": { "type": "string" }, "RoleMappings": { "type": "object" }, "Roles": { "type": "object" } }, "required": [ "IdentityPoolId" ], "type": "object" }, "Type": { "enum": [ "AWS::Cognito::IdentityPoolRoleAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Cognito::IdentityPoolRoleAttachment.MappingRule": { "additionalProperties": false, "properties": { "Claim": { "type": "string" }, "MatchType": { "type": "string" }, "RoleARN": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Claim", "MatchType", "RoleARN", "Value" ], "type": "object" }, "AWS::Cognito::IdentityPoolRoleAttachment.RoleMapping": { "additionalProperties": false, "properties": { "AmbiguousRoleResolution": { "type": "string" }, "RulesConfiguration": { "$ref": "#/definitions/AWS::Cognito::IdentityPoolRoleAttachment.RulesConfigurationType" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Cognito::IdentityPoolRoleAttachment.RulesConfigurationType": { "additionalProperties": false, "properties": { "Rules": { "items": { "$ref": "#/definitions/AWS::Cognito::IdentityPoolRoleAttachment.MappingRule" }, "type": "array" } }, "required": [ "Rules" ], "type": "object" }, "AWS::Cognito::UserPool": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AdminCreateUserConfig": { "$ref": "#/definitions/AWS::Cognito::UserPool.AdminCreateUserConfig" }, "AliasAttributes": { "items": { "type": "string" }, "type": "array" }, "AutoVerifiedAttributes": { "items": { "type": "string" }, "type": "array" }, "DeviceConfiguration": { "$ref": "#/definitions/AWS::Cognito::UserPool.DeviceConfiguration" }, "EmailConfiguration": { "$ref": "#/definitions/AWS::Cognito::UserPool.EmailConfiguration" }, "EmailVerificationMessage": { "type": "string" }, "EmailVerificationSubject": { "type": "string" }, "LambdaConfig": { "$ref": "#/definitions/AWS::Cognito::UserPool.LambdaConfig" }, "MfaConfiguration": { "type": "string" }, "Policies": { "$ref": "#/definitions/AWS::Cognito::UserPool.Policies" }, "Schema": { "items": { "$ref": "#/definitions/AWS::Cognito::UserPool.SchemaAttribute" }, "type": "array" }, "SmsAuthenticationMessage": { "type": "string" }, "SmsConfiguration": { "$ref": "#/definitions/AWS::Cognito::UserPool.SmsConfiguration" }, "SmsVerificationMessage": { "type": "string" }, "UserPoolName": { "type": "string" }, "UserPoolTags": { "type": "object" } }, "type": "object" }, "Type": { "enum": [ "AWS::Cognito::UserPool" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Cognito::UserPool.AdminCreateUserConfig": { "additionalProperties": false, "properties": { "AllowAdminCreateUserOnly": { "type": "boolean" }, "InviteMessageTemplate": { "$ref": "#/definitions/AWS::Cognito::UserPool.InviteMessageTemplate" }, "UnusedAccountValidityDays": { "type": "number" } }, "type": "object" }, "AWS::Cognito::UserPool.DeviceConfiguration": { "additionalProperties": false, "properties": { "ChallengeRequiredOnNewDevice": { "type": "boolean" }, "DeviceOnlyRememberedOnUserPrompt": { "type": "boolean" } }, "type": "object" }, "AWS::Cognito::UserPool.EmailConfiguration": { "additionalProperties": false, "properties": { "ReplyToEmailAddress": { "type": "string" }, "SourceArn": { "type": "string" } }, "type": "object" }, "AWS::Cognito::UserPool.InviteMessageTemplate": { "additionalProperties": false, "properties": { "EmailMessage": { "type": "string" }, "EmailSubject": { "type": "string" }, "SMSMessage": { "type": "string" } }, "type": "object" }, "AWS::Cognito::UserPool.LambdaConfig": { "additionalProperties": false, "properties": { "CreateAuthChallenge": { "type": "string" }, "CustomMessage": { "type": "string" }, "DefineAuthChallenge": { "type": "string" }, "PostAuthentication": { "type": "string" }, "PostConfirmation": { "type": "string" }, "PreAuthentication": { "type": "string" }, "PreSignUp": { "type": "string" }, "VerifyAuthChallengeResponse": { "type": "string" } }, "type": "object" }, "AWS::Cognito::UserPool.NumberAttributeConstraints": { "additionalProperties": false, "properties": { "MaxValue": { "type": "string" }, "MinValue": { "type": "string" } }, "type": "object" }, "AWS::Cognito::UserPool.PasswordPolicy": { "additionalProperties": false, "properties": { "MinimumLength": { "type": "number" }, "RequireLowercase": { "type": "boolean" }, "RequireNumbers": { "type": "boolean" }, "RequireSymbols": { "type": "boolean" }, "RequireUppercase": { "type": "boolean" } }, "type": "object" }, "AWS::Cognito::UserPool.Policies": { "additionalProperties": false, "properties": { "PasswordPolicy": { "$ref": "#/definitions/AWS::Cognito::UserPool.PasswordPolicy" } }, "type": "object" }, "AWS::Cognito::UserPool.SchemaAttribute": { "additionalProperties": false, "properties": { "AttributeDataType": { "type": "string" }, "DeveloperOnlyAttribute": { "type": "boolean" }, "Mutable": { "type": "boolean" }, "Name": { "type": "string" }, "NumberAttributeConstraints": { "$ref": "#/definitions/AWS::Cognito::UserPool.NumberAttributeConstraints" }, "Required": { "type": "boolean" }, "StringAttributeConstraints": { "$ref": "#/definitions/AWS::Cognito::UserPool.StringAttributeConstraints" } }, "type": "object" }, "AWS::Cognito::UserPool.SmsConfiguration": { "additionalProperties": false, "properties": { "ExternalId": { "type": "string" }, "SnsCallerArn": { "type": "string" } }, "type": "object" }, "AWS::Cognito::UserPool.StringAttributeConstraints": { "additionalProperties": false, "properties": { "MaxLength": { "type": "string" }, "MinLength": { "type": "string" } }, "type": "object" }, "AWS::Cognito::UserPoolClient": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ClientName": { "type": "string" }, "ExplicitAuthFlows": { "items": { "type": "string" }, "type": "array" }, "GenerateSecret": { "type": "boolean" }, "ReadAttributes": { "items": { "type": "string" }, "type": "array" }, "RefreshTokenValidity": { "type": "number" }, "UserPoolId": { "type": "string" }, "WriteAttributes": { "items": { "type": "string" }, "type": "array" } }, "required": [ "UserPoolId" ], "type": "object" }, "Type": { "enum": [ "AWS::Cognito::UserPoolClient" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Cognito::UserPoolGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "GroupName": { "type": "string" }, "Precedence": { "type": "number" }, "RoleArn": { "type": "string" }, "UserPoolId": { "type": "string" } }, "required": [ "UserPoolId" ], "type": "object" }, "Type": { "enum": [ "AWS::Cognito::UserPoolGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Cognito::UserPoolUser": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DesiredDeliveryMediums": { "items": { "type": "string" }, "type": "array" }, "ForceAliasCreation": { "type": "boolean" }, "MessageAction": { "type": "string" }, "UserAttributes": { "items": { "$ref": "#/definitions/AWS::Cognito::UserPoolUser.AttributeType" }, "type": "array" }, "UserPoolId": { "type": "string" }, "Username": { "type": "string" }, "ValidationData": { "items": { "$ref": "#/definitions/AWS::Cognito::UserPoolUser.AttributeType" }, "type": "array" } }, "required": [ "UserPoolId" ], "type": "object" }, "Type": { "enum": [ "AWS::Cognito::UserPoolUser" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Cognito::UserPoolUser.AttributeType": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::Cognito::UserPoolUserToGroupAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "GroupName": { "type": "string" }, "UserPoolId": { "type": "string" }, "Username": { "type": "string" } }, "required": [ "GroupName", "UserPoolId", "Username" ], "type": "object" }, "Type": { "enum": [ "AWS::Cognito::UserPoolUserToGroupAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Config::ConfigRule": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ConfigRuleName": { "type": "string" }, "Description": { "type": "string" }, "InputParameters": { "type": "object" }, "MaximumExecutionFrequency": { "type": "string" }, "Scope": { "$ref": "#/definitions/AWS::Config::ConfigRule.Scope" }, "Source": { "$ref": "#/definitions/AWS::Config::ConfigRule.Source" } }, "required": [ "Source" ], "type": "object" }, "Type": { "enum": [ "AWS::Config::ConfigRule" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Config::ConfigRule.Scope": { "additionalProperties": false, "properties": { "ComplianceResourceId": { "type": "string" }, "ComplianceResourceTypes": { "items": { "type": "string" }, "type": "array" }, "TagKey": { "type": "string" }, "TagValue": { "type": "string" } }, "type": "object" }, "AWS::Config::ConfigRule.Source": { "additionalProperties": false, "properties": { "Owner": { "type": "string" }, "SourceDetails": { "items": { "$ref": "#/definitions/AWS::Config::ConfigRule.SourceDetail" }, "type": "array" }, "SourceIdentifier": { "type": "string" } }, "required": [ "Owner", "SourceIdentifier" ], "type": "object" }, "AWS::Config::ConfigRule.SourceDetail": { "additionalProperties": false, "properties": { "EventSource": { "type": "string" }, "MaximumExecutionFrequency": { "type": "string" }, "MessageType": { "type": "string" } }, "required": [ "EventSource", "MessageType" ], "type": "object" }, "AWS::Config::ConfigurationRecorder": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "RecordingGroup": { "$ref": "#/definitions/AWS::Config::ConfigurationRecorder.RecordingGroup" }, "RoleARN": { "type": "string" } }, "required": [ "RoleARN" ], "type": "object" }, "Type": { "enum": [ "AWS::Config::ConfigurationRecorder" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Config::ConfigurationRecorder.RecordingGroup": { "additionalProperties": false, "properties": { "AllSupported": { "type": "boolean" }, "IncludeGlobalResourceTypes": { "type": "boolean" }, "ResourceTypes": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::Config::DeliveryChannel": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ConfigSnapshotDeliveryProperties": { "$ref": "#/definitions/AWS::Config::DeliveryChannel.ConfigSnapshotDeliveryProperties" }, "Name": { "type": "string" }, "S3BucketName": { "type": "string" }, "S3KeyPrefix": { "type": "string" }, "SnsTopicARN": { "type": "string" } }, "required": [ "S3BucketName" ], "type": "object" }, "Type": { "enum": [ "AWS::Config::DeliveryChannel" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Config::DeliveryChannel.ConfigSnapshotDeliveryProperties": { "additionalProperties": false, "properties": { "DeliveryFrequency": { "type": "string" } }, "type": "object" }, "AWS::DAX::Cluster": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AvailabilityZones": { "items": { "type": "string" }, "type": "array" }, "ClusterName": { "type": "string" }, "Description": { "type": "string" }, "IAMRoleARN": { "type": "string" }, "NodeType": { "type": "string" }, "NotificationTopicARN": { "type": "string" }, "ParameterGroupName": { "type": "string" }, "PreferredMaintenanceWindow": { "type": "string" }, "ReplicationFactor": { "type": "number" }, "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SubnetGroupName": { "type": "string" }, "Tags": { "type": "object" } }, "required": [ "IAMRoleARN", "NodeType", "ReplicationFactor" ], "type": "object" }, "Type": { "enum": [ "AWS::DAX::Cluster" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DAX::ParameterGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "ParameterGroupName": { "type": "string" }, "ParameterNameValues": { "type": "object" } }, "type": "object" }, "Type": { "enum": [ "AWS::DAX::ParameterGroup" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::DAX::SubnetGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "SubnetGroupName": { "type": "string" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "SubnetIds" ], "type": "object" }, "Type": { "enum": [ "AWS::DAX::SubnetGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DMS::Certificate": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CertificateIdentifier": { "type": "string" }, "CertificatePem": { "type": "string" }, "CertificateWallet": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::DMS::Certificate" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::DMS::Endpoint": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CertificateArn": { "type": "string" }, "DatabaseName": { "type": "string" }, "DynamoDbSettings": { "$ref": "#/definitions/AWS::DMS::Endpoint.DynamoDbSettings" }, "EndpointIdentifier": { "type": "string" }, "EndpointType": { "type": "string" }, "EngineName": { "type": "string" }, "ExtraConnectionAttributes": { "type": "string" }, "KmsKeyId": { "type": "string" }, "MongoDbSettings": { "$ref": "#/definitions/AWS::DMS::Endpoint.MongoDbSettings" }, "Password": { "type": "string" }, "Port": { "type": "number" }, "S3Settings": { "$ref": "#/definitions/AWS::DMS::Endpoint.S3Settings" }, "ServerName": { "type": "string" }, "SslMode": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Username": { "type": "string" } }, "required": [ "EndpointType", "EngineName" ], "type": "object" }, "Type": { "enum": [ "AWS::DMS::Endpoint" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DMS::Endpoint.DynamoDbSettings": { "additionalProperties": false, "properties": { "ServiceAccessRoleArn": { "type": "string" } }, "type": "object" }, "AWS::DMS::Endpoint.MongoDbSettings": { "additionalProperties": false, "properties": { "AuthMechanism": { "type": "string" }, "AuthSource": { "type": "string" }, "AuthType": { "type": "string" }, "DatabaseName": { "type": "string" }, "DocsToInvestigate": { "type": "string" }, "ExtractDocId": { "type": "string" }, "NestingLevel": { "type": "string" }, "Password": { "type": "string" }, "Port": { "type": "number" }, "ServerName": { "type": "string" }, "Username": { "type": "string" } }, "type": "object" }, "AWS::DMS::Endpoint.S3Settings": { "additionalProperties": false, "properties": { "BucketFolder": { "type": "string" }, "BucketName": { "type": "string" }, "CompressionType": { "type": "string" }, "CsvDelimiter": { "type": "string" }, "CsvRowDelimiter": { "type": "string" }, "ExternalTableDefinition": { "type": "string" }, "ServiceAccessRoleArn": { "type": "string" } }, "type": "object" }, "AWS::DMS::EventSubscription": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Enabled": { "type": "boolean" }, "EventCategories": { "items": { "type": "string" }, "type": "array" }, "SnsTopicArn": { "type": "string" }, "SourceIds": { "items": { "type": "string" }, "type": "array" }, "SourceType": { "type": "string" }, "SubscriptionName": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "SnsTopicArn" ], "type": "object" }, "Type": { "enum": [ "AWS::DMS::EventSubscription" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DMS::ReplicationInstance": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllocatedStorage": { "type": "number" }, "AllowMajorVersionUpgrade": { "type": "boolean" }, "AutoMinorVersionUpgrade": { "type": "boolean" }, "AvailabilityZone": { "type": "string" }, "EngineVersion": { "type": "string" }, "KmsKeyId": { "type": "string" }, "MultiAZ": { "type": "boolean" }, "PreferredMaintenanceWindow": { "type": "string" }, "PubliclyAccessible": { "type": "boolean" }, "ReplicationInstanceClass": { "type": "string" }, "ReplicationInstanceIdentifier": { "type": "string" }, "ReplicationSubnetGroupIdentifier": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcSecurityGroupIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "ReplicationInstanceClass" ], "type": "object" }, "Type": { "enum": [ "AWS::DMS::ReplicationInstance" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DMS::ReplicationSubnetGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ReplicationSubnetGroupDescription": { "type": "string" }, "ReplicationSubnetGroupIdentifier": { "type": "string" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "ReplicationSubnetGroupDescription", "SubnetIds" ], "type": "object" }, "Type": { "enum": [ "AWS::DMS::ReplicationSubnetGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DMS::ReplicationTask": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CdcStartTime": { "type": "number" }, "MigrationType": { "type": "string" }, "ReplicationInstanceArn": { "type": "string" }, "ReplicationTaskIdentifier": { "type": "string" }, "ReplicationTaskSettings": { "type": "string" }, "SourceEndpointArn": { "type": "string" }, "TableMappings": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TargetEndpointArn": { "type": "string" } }, "required": [ "MigrationType", "ReplicationInstanceArn", "SourceEndpointArn", "TableMappings", "TargetEndpointArn" ], "type": "object" }, "Type": { "enum": [ "AWS::DMS::ReplicationTask" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DataPipeline::Pipeline": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Activate": { "type": "boolean" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "ParameterObjects": { "items": { "$ref": "#/definitions/AWS::DataPipeline::Pipeline.ParameterObject" }, "type": "array" }, "ParameterValues": { "items": { "$ref": "#/definitions/AWS::DataPipeline::Pipeline.ParameterValue" }, "type": "array" }, "PipelineObjects": { "items": { "$ref": "#/definitions/AWS::DataPipeline::Pipeline.PipelineObject" }, "type": "array" }, "PipelineTags": { "items": { "$ref": "#/definitions/AWS::DataPipeline::Pipeline.PipelineTag" }, "type": "array" } }, "required": [ "Name", "ParameterObjects" ], "type": "object" }, "Type": { "enum": [ "AWS::DataPipeline::Pipeline" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DataPipeline::Pipeline.Field": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "RefValue": { "type": "string" }, "StringValue": { "type": "string" } }, "required": [ "Key" ], "type": "object" }, "AWS::DataPipeline::Pipeline.ParameterAttribute": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "StringValue": { "type": "string" } }, "required": [ "Key", "StringValue" ], "type": "object" }, "AWS::DataPipeline::Pipeline.ParameterObject": { "additionalProperties": false, "properties": { "Attributes": { "items": { "$ref": "#/definitions/AWS::DataPipeline::Pipeline.ParameterAttribute" }, "type": "array" }, "Id": { "type": "string" } }, "required": [ "Attributes", "Id" ], "type": "object" }, "AWS::DataPipeline::Pipeline.ParameterValue": { "additionalProperties": false, "properties": { "Id": { "type": "string" }, "StringValue": { "type": "string" } }, "required": [ "Id", "StringValue" ], "type": "object" }, "AWS::DataPipeline::Pipeline.PipelineObject": { "additionalProperties": false, "properties": { "Fields": { "items": { "$ref": "#/definitions/AWS::DataPipeline::Pipeline.Field" }, "type": "array" }, "Id": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "Fields", "Id", "Name" ], "type": "object" }, "AWS::DataPipeline::Pipeline.PipelineTag": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::DirectoryService::MicrosoftAD": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CreateAlias": { "type": "boolean" }, "EnableSso": { "type": "boolean" }, "Name": { "type": "string" }, "Password": { "type": "string" }, "ShortName": { "type": "string" }, "VpcSettings": { "$ref": "#/definitions/AWS::DirectoryService::MicrosoftAD.VpcSettings" } }, "required": [ "Name", "Password", "VpcSettings" ], "type": "object" }, "Type": { "enum": [ "AWS::DirectoryService::MicrosoftAD" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DirectoryService::MicrosoftAD.VpcSettings": { "additionalProperties": false, "properties": { "SubnetIds": { "items": { "type": "string" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "SubnetIds", "VpcId" ], "type": "object" }, "AWS::DirectoryService::SimpleAD": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CreateAlias": { "type": "boolean" }, "Description": { "type": "string" }, "EnableSso": { "type": "boolean" }, "Name": { "type": "string" }, "Password": { "type": "string" }, "ShortName": { "type": "string" }, "Size": { "type": "string" }, "VpcSettings": { "$ref": "#/definitions/AWS::DirectoryService::SimpleAD.VpcSettings" } }, "required": [ "Name", "Password", "Size", "VpcSettings" ], "type": "object" }, "Type": { "enum": [ "AWS::DirectoryService::SimpleAD" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DirectoryService::SimpleAD.VpcSettings": { "additionalProperties": false, "properties": { "SubnetIds": { "items": { "type": "string" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "SubnetIds", "VpcId" ], "type": "object" }, "AWS::DynamoDB::Table": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AttributeDefinitions": { "items": { "$ref": "#/definitions/AWS::DynamoDB::Table.AttributeDefinition" }, "type": "array" }, "GlobalSecondaryIndexes": { "items": { "$ref": "#/definitions/AWS::DynamoDB::Table.GlobalSecondaryIndex" }, "type": "array" }, "KeySchema": { "items": { "$ref": "#/definitions/AWS::DynamoDB::Table.KeySchema" }, "type": "array" }, "LocalSecondaryIndexes": { "items": { "$ref": "#/definitions/AWS::DynamoDB::Table.LocalSecondaryIndex" }, "type": "array" }, "ProvisionedThroughput": { "$ref": "#/definitions/AWS::DynamoDB::Table.ProvisionedThroughput" }, "SSESpecification": { "$ref": "#/definitions/AWS::DynamoDB::Table.SSESpecification" }, "StreamSpecification": { "$ref": "#/definitions/AWS::DynamoDB::Table.StreamSpecification" }, "TableName": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TimeToLiveSpecification": { "$ref": "#/definitions/AWS::DynamoDB::Table.TimeToLiveSpecification" } }, "required": [ "KeySchema", "ProvisionedThroughput" ], "type": "object" }, "Type": { "enum": [ "AWS::DynamoDB::Table" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::DynamoDB::Table.AttributeDefinition": { "additionalProperties": false, "properties": { "AttributeName": { "type": "string" }, "AttributeType": { "type": "string" } }, "required": [ "AttributeName", "AttributeType" ], "type": "object" }, "AWS::DynamoDB::Table.GlobalSecondaryIndex": { "additionalProperties": false, "properties": { "IndexName": { "type": "string" }, "KeySchema": { "items": { "$ref": "#/definitions/AWS::DynamoDB::Table.KeySchema" }, "type": "array" }, "Projection": { "$ref": "#/definitions/AWS::DynamoDB::Table.Projection" }, "ProvisionedThroughput": { "$ref": "#/definitions/AWS::DynamoDB::Table.ProvisionedThroughput" } }, "required": [ "IndexName", "KeySchema", "Projection", "ProvisionedThroughput" ], "type": "object" }, "AWS::DynamoDB::Table.KeySchema": { "additionalProperties": false, "properties": { "AttributeName": { "type": "string" }, "KeyType": { "type": "string" } }, "required": [ "AttributeName", "KeyType" ], "type": "object" }, "AWS::DynamoDB::Table.LocalSecondaryIndex": { "additionalProperties": false, "properties": { "IndexName": { "type": "string" }, "KeySchema": { "items": { "$ref": "#/definitions/AWS::DynamoDB::Table.KeySchema" }, "type": "array" }, "Projection": { "$ref": "#/definitions/AWS::DynamoDB::Table.Projection" } }, "required": [ "IndexName", "KeySchema", "Projection" ], "type": "object" }, "AWS::DynamoDB::Table.Projection": { "additionalProperties": false, "properties": { "NonKeyAttributes": { "items": { "type": "string" }, "type": "array" }, "ProjectionType": { "type": "string" } }, "type": "object" }, "AWS::DynamoDB::Table.ProvisionedThroughput": { "additionalProperties": false, "properties": { "ReadCapacityUnits": { "type": "number" }, "WriteCapacityUnits": { "type": "number" } }, "required": [ "ReadCapacityUnits", "WriteCapacityUnits" ], "type": "object" }, "AWS::DynamoDB::Table.SSESpecification": { "additionalProperties": false, "properties": { "SSEEnabled": { "type": "boolean" } }, "required": [ "SSEEnabled" ], "type": "object" }, "AWS::DynamoDB::Table.StreamSpecification": { "additionalProperties": false, "properties": { "StreamViewType": { "type": "string" } }, "required": [ "StreamViewType" ], "type": "object" }, "AWS::DynamoDB::Table.TimeToLiveSpecification": { "additionalProperties": false, "properties": { "AttributeName": { "type": "string" }, "Enabled": { "type": "boolean" } }, "required": [ "AttributeName", "Enabled" ], "type": "object" }, "AWS::EC2::CustomerGateway": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "BgpAsn": { "type": "number" }, "IpAddress": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Type": { "type": "string" } }, "required": [ "BgpAsn", "IpAddress", "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::CustomerGateway" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::DHCPOptions": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DomainName": { "type": "string" }, "DomainNameServers": { "items": { "type": "string" }, "type": "array" }, "NetbiosNameServers": { "items": { "type": "string" }, "type": "array" }, "NetbiosNodeType": { "type": "number" }, "NtpServers": { "items": { "type": "string" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "type": "object" }, "Type": { "enum": [ "AWS::EC2::DHCPOptions" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::EC2::EIP": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Domain": { "type": "string" }, "InstanceId": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::EC2::EIP" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::EC2::EIPAssociation": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllocationId": { "type": "string" }, "EIP": { "type": "string" }, "InstanceId": { "type": "string" }, "NetworkInterfaceId": { "type": "string" }, "PrivateIpAddress": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::EC2::EIPAssociation" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::EC2::EgressOnlyInternetGateway": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "VpcId": { "type": "string" } }, "required": [ "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::EgressOnlyInternetGateway" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::FlowLog": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DeliverLogsPermissionArn": { "type": "string" }, "LogGroupName": { "type": "string" }, "ResourceId": { "type": "string" }, "ResourceType": { "type": "string" }, "TrafficType": { "type": "string" } }, "required": [ "DeliverLogsPermissionArn", "LogGroupName", "ResourceId", "ResourceType", "TrafficType" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::FlowLog" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::Host": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AutoPlacement": { "type": "string" }, "AvailabilityZone": { "type": "string" }, "InstanceType": { "type": "string" } }, "required": [ "AvailabilityZone", "InstanceType" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::Host" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::Instance": { "additionalProperties": false, "properties": { "CreationPolicy": { "type": "object" }, "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AdditionalInfo": { "type": "string" }, "Affinity": { "type": "string" }, "AvailabilityZone": { "type": "string" }, "BlockDeviceMappings": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.BlockDeviceMapping" }, "type": "array" }, "CreditSpecification": { "$ref": "#/definitions/AWS::EC2::Instance.CreditSpecification" }, "DisableApiTermination": { "type": "boolean" }, "EbsOptimized": { "type": "boolean" }, "ElasticGpuSpecifications": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.ElasticGpuSpecification" }, "type": "array" }, "HostId": { "type": "string" }, "IamInstanceProfile": { "type": "string" }, "ImageId": { "type": "string" }, "InstanceInitiatedShutdownBehavior": { "type": "string" }, "InstanceType": { "type": "string" }, "Ipv6AddressCount": { "type": "number" }, "Ipv6Addresses": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.InstanceIpv6Address" }, "type": "array" }, "KernelId": { "type": "string" }, "KeyName": { "type": "string" }, "Monitoring": { "type": "boolean" }, "NetworkInterfaces": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.NetworkInterface" }, "type": "array" }, "PlacementGroupName": { "type": "string" }, "PrivateIpAddress": { "type": "string" }, "RamdiskId": { "type": "string" }, "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SecurityGroups": { "items": { "type": "string" }, "type": "array" }, "SourceDestCheck": { "type": "boolean" }, "SsmAssociations": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.SsmAssociation" }, "type": "array" }, "SubnetId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Tenancy": { "type": "string" }, "UserData": { "type": "string" }, "Volumes": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.Volume" }, "type": "array" } }, "required": [ "ImageId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::Instance" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::Instance.AssociationParameter": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::EC2::Instance.BlockDeviceMapping": { "additionalProperties": false, "properties": { "DeviceName": { "type": "string" }, "Ebs": { "$ref": "#/definitions/AWS::EC2::Instance.Ebs" }, "NoDevice": { "$ref": "#/definitions/AWS::EC2::Instance.NoDevice" }, "VirtualName": { "type": "string" } }, "required": [ "DeviceName" ], "type": "object" }, "AWS::EC2::Instance.CreditSpecification": { "additionalProperties": false, "properties": { "CPUCredits": { "type": "string" } }, "type": "object" }, "AWS::EC2::Instance.Ebs": { "additionalProperties": false, "properties": { "DeleteOnTermination": { "type": "boolean" }, "Encrypted": { "type": "boolean" }, "Iops": { "type": "number" }, "SnapshotId": { "type": "string" }, "VolumeSize": { "type": "number" }, "VolumeType": { "type": "string" } }, "type": "object" }, "AWS::EC2::Instance.ElasticGpuSpecification": { "additionalProperties": false, "properties": { "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::EC2::Instance.InstanceIpv6Address": { "additionalProperties": false, "properties": { "Ipv6Address": { "type": "string" } }, "required": [ "Ipv6Address" ], "type": "object" }, "AWS::EC2::Instance.NetworkInterface": { "additionalProperties": false, "properties": { "AssociatePublicIpAddress": { "type": "boolean" }, "DeleteOnTermination": { "type": "boolean" }, "Description": { "type": "string" }, "DeviceIndex": { "type": "string" }, "GroupSet": { "items": { "type": "string" }, "type": "array" }, "Ipv6AddressCount": { "type": "number" }, "Ipv6Addresses": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.InstanceIpv6Address" }, "type": "array" }, "NetworkInterfaceId": { "type": "string" }, "PrivateIpAddress": { "type": "string" }, "PrivateIpAddresses": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.PrivateIpAddressSpecification" }, "type": "array" }, "SecondaryPrivateIpAddressCount": { "type": "number" }, "SubnetId": { "type": "string" } }, "required": [ "DeviceIndex" ], "type": "object" }, "AWS::EC2::Instance.NoDevice": { "additionalProperties": false, "properties": {}, "type": "object" }, "AWS::EC2::Instance.PrivateIpAddressSpecification": { "additionalProperties": false, "properties": { "Primary": { "type": "boolean" }, "PrivateIpAddress": { "type": "string" } }, "required": [ "Primary", "PrivateIpAddress" ], "type": "object" }, "AWS::EC2::Instance.SsmAssociation": { "additionalProperties": false, "properties": { "AssociationParameters": { "items": { "$ref": "#/definitions/AWS::EC2::Instance.AssociationParameter" }, "type": "array" }, "DocumentName": { "type": "string" } }, "required": [ "DocumentName" ], "type": "object" }, "AWS::EC2::Instance.Volume": { "additionalProperties": false, "properties": { "Device": { "type": "string" }, "VolumeId": { "type": "string" } }, "required": [ "Device", "VolumeId" ], "type": "object" }, "AWS::EC2::InternetGateway": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "type": "object" }, "Type": { "enum": [ "AWS::EC2::InternetGateway" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::EC2::NatGateway": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllocationId": { "type": "string" }, "SubnetId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "AllocationId", "SubnetId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::NatGateway" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::NetworkAcl": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::NetworkAcl" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::NetworkAclEntry": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CidrBlock": { "type": "string" }, "Egress": { "type": "boolean" }, "Icmp": { "$ref": "#/definitions/AWS::EC2::NetworkAclEntry.Icmp" }, "Ipv6CidrBlock": { "type": "string" }, "NetworkAclId": { "type": "string" }, "PortRange": { "$ref": "#/definitions/AWS::EC2::NetworkAclEntry.PortRange" }, "Protocol": { "type": "number" }, "RuleAction": { "type": "string" }, "RuleNumber": { "type": "number" } }, "required": [ "CidrBlock", "NetworkAclId", "Protocol", "RuleAction", "RuleNumber" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::NetworkAclEntry" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::NetworkAclEntry.Icmp": { "additionalProperties": false, "properties": { "Code": { "type": "number" }, "Type": { "type": "number" } }, "type": "object" }, "AWS::EC2::NetworkAclEntry.PortRange": { "additionalProperties": false, "properties": { "From": { "type": "number" }, "To": { "type": "number" } }, "type": "object" }, "AWS::EC2::NetworkInterface": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "GroupSet": { "items": { "type": "string" }, "type": "array" }, "InterfaceType": { "type": "string" }, "Ipv6AddressCount": { "type": "number" }, "Ipv6Addresses": { "$ref": "#/definitions/AWS::EC2::NetworkInterface.InstanceIpv6Address" }, "PrivateIpAddress": { "type": "string" }, "PrivateIpAddresses": { "items": { "$ref": "#/definitions/AWS::EC2::NetworkInterface.PrivateIpAddressSpecification" }, "type": "array" }, "SecondaryPrivateIpAddressCount": { "type": "number" }, "SourceDestCheck": { "type": "boolean" }, "SubnetId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "SubnetId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::NetworkInterface" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::NetworkInterface.InstanceIpv6Address": { "additionalProperties": false, "properties": { "Ipv6Address": { "type": "string" } }, "required": [ "Ipv6Address" ], "type": "object" }, "AWS::EC2::NetworkInterface.PrivateIpAddressSpecification": { "additionalProperties": false, "properties": { "Primary": { "type": "boolean" }, "PrivateIpAddress": { "type": "string" } }, "required": [ "Primary", "PrivateIpAddress" ], "type": "object" }, "AWS::EC2::NetworkInterfaceAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DeleteOnTermination": { "type": "boolean" }, "DeviceIndex": { "type": "string" }, "InstanceId": { "type": "string" }, "NetworkInterfaceId": { "type": "string" } }, "required": [ "DeviceIndex", "InstanceId", "NetworkInterfaceId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::NetworkInterfaceAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::NetworkInterfacePermission": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AwsAccountId": { "type": "string" }, "NetworkInterfaceId": { "type": "string" }, "Permission": { "type": "string" } }, "required": [ "AwsAccountId", "NetworkInterfaceId", "Permission" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::NetworkInterfacePermission" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::PlacementGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Strategy": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::EC2::PlacementGroup" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::EC2::Route": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DestinationCidrBlock": { "type": "string" }, "DestinationIpv6CidrBlock": { "type": "string" }, "EgressOnlyInternetGatewayId": { "type": "string" }, "GatewayId": { "type": "string" }, "InstanceId": { "type": "string" }, "NatGatewayId": { "type": "string" }, "NetworkInterfaceId": { "type": "string" }, "RouteTableId": { "type": "string" }, "VpcPeeringConnectionId": { "type": "string" } }, "required": [ "RouteTableId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::Route" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::RouteTable": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::RouteTable" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SecurityGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "GroupDescription": { "type": "string" }, "GroupName": { "type": "string" }, "SecurityGroupEgress": { "items": { "$ref": "#/definitions/AWS::EC2::SecurityGroup.Egress" }, "type": "array" }, "SecurityGroupIngress": { "items": { "$ref": "#/definitions/AWS::EC2::SecurityGroup.Ingress" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "GroupDescription" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::SecurityGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SecurityGroup.Egress": { "additionalProperties": false, "properties": { "CidrIp": { "type": "string" }, "CidrIpv6": { "type": "string" }, "Description": { "type": "string" }, "DestinationPrefixListId": { "type": "string" }, "DestinationSecurityGroupId": { "type": "string" }, "FromPort": { "type": "number" }, "IpProtocol": { "type": "string" }, "ToPort": { "type": "number" } }, "required": [ "IpProtocol" ], "type": "object" }, "AWS::EC2::SecurityGroup.Ingress": { "additionalProperties": false, "properties": { "CidrIp": { "type": "string" }, "CidrIpv6": { "type": "string" }, "Description": { "type": "string" }, "FromPort": { "type": "number" }, "IpProtocol": { "type": "string" }, "SourceSecurityGroupId": { "type": "string" }, "SourceSecurityGroupName": { "type": "string" }, "SourceSecurityGroupOwnerId": { "type": "string" }, "ToPort": { "type": "number" } }, "required": [ "IpProtocol" ], "type": "object" }, "AWS::EC2::SecurityGroupEgress": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CidrIp": { "type": "string" }, "CidrIpv6": { "type": "string" }, "Description": { "type": "string" }, "DestinationPrefixListId": { "type": "string" }, "DestinationSecurityGroupId": { "type": "string" }, "FromPort": { "type": "number" }, "GroupId": { "type": "string" }, "IpProtocol": { "type": "string" }, "ToPort": { "type": "number" } }, "required": [ "GroupId", "IpProtocol" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::SecurityGroupEgress" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SecurityGroupIngress": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CidrIp": { "type": "string" }, "CidrIpv6": { "type": "string" }, "Description": { "type": "string" }, "FromPort": { "type": "number" }, "GroupId": { "type": "string" }, "GroupName": { "type": "string" }, "IpProtocol": { "type": "string" }, "SourceSecurityGroupId": { "type": "string" }, "SourceSecurityGroupName": { "type": "string" }, "SourceSecurityGroupOwnerId": { "type": "string" }, "ToPort": { "type": "number" } }, "required": [ "IpProtocol" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::SecurityGroupIngress" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SpotFleet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "SpotFleetRequestConfigData": { "$ref": "#/definitions/AWS::EC2::SpotFleet.SpotFleetRequestConfigData" } }, "required": [ "SpotFleetRequestConfigData" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::SpotFleet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SpotFleet.BlockDeviceMapping": { "additionalProperties": false, "properties": { "DeviceName": { "type": "string" }, "Ebs": { "$ref": "#/definitions/AWS::EC2::SpotFleet.EbsBlockDevice" }, "NoDevice": { "type": "string" }, "VirtualName": { "type": "string" } }, "required": [ "DeviceName" ], "type": "object" }, "AWS::EC2::SpotFleet.EbsBlockDevice": { "additionalProperties": false, "properties": { "DeleteOnTermination": { "type": "boolean" }, "Encrypted": { "type": "boolean" }, "Iops": { "type": "number" }, "SnapshotId": { "type": "string" }, "VolumeSize": { "type": "number" }, "VolumeType": { "type": "string" } }, "type": "object" }, "AWS::EC2::SpotFleet.GroupIdentifier": { "additionalProperties": false, "properties": { "GroupId": { "type": "string" } }, "required": [ "GroupId" ], "type": "object" }, "AWS::EC2::SpotFleet.IamInstanceProfileSpecification": { "additionalProperties": false, "properties": { "Arn": { "type": "string" } }, "type": "object" }, "AWS::EC2::SpotFleet.InstanceIpv6Address": { "additionalProperties": false, "properties": { "Ipv6Address": { "type": "string" } }, "required": [ "Ipv6Address" ], "type": "object" }, "AWS::EC2::SpotFleet.InstanceNetworkInterfaceSpecification": { "additionalProperties": false, "properties": { "AssociatePublicIpAddress": { "type": "boolean" }, "DeleteOnTermination": { "type": "boolean" }, "Description": { "type": "string" }, "DeviceIndex": { "type": "number" }, "Groups": { "items": { "type": "string" }, "type": "array" }, "Ipv6AddressCount": { "type": "number" }, "Ipv6Addresses": { "items": { "$ref": "#/definitions/AWS::EC2::SpotFleet.InstanceIpv6Address" }, "type": "array" }, "NetworkInterfaceId": { "type": "string" }, "PrivateIpAddresses": { "items": { "$ref": "#/definitions/AWS::EC2::SpotFleet.PrivateIpAddressSpecification" }, "type": "array" }, "SecondaryPrivateIpAddressCount": { "type": "number" }, "SubnetId": { "type": "string" } }, "type": "object" }, "AWS::EC2::SpotFleet.PrivateIpAddressSpecification": { "additionalProperties": false, "properties": { "Primary": { "type": "boolean" }, "PrivateIpAddress": { "type": "string" } }, "required": [ "PrivateIpAddress" ], "type": "object" }, "AWS::EC2::SpotFleet.SpotFleetLaunchSpecification": { "additionalProperties": false, "properties": { "BlockDeviceMappings": { "items": { "$ref": "#/definitions/AWS::EC2::SpotFleet.BlockDeviceMapping" }, "type": "array" }, "EbsOptimized": { "type": "boolean" }, "IamInstanceProfile": { "$ref": "#/definitions/AWS::EC2::SpotFleet.IamInstanceProfileSpecification" }, "ImageId": { "type": "string" }, "InstanceType": { "type": "string" }, "KernelId": { "type": "string" }, "KeyName": { "type": "string" }, "Monitoring": { "$ref": "#/definitions/AWS::EC2::SpotFleet.SpotFleetMonitoring" }, "NetworkInterfaces": { "items": { "$ref": "#/definitions/AWS::EC2::SpotFleet.InstanceNetworkInterfaceSpecification" }, "type": "array" }, "Placement": { "$ref": "#/definitions/AWS::EC2::SpotFleet.SpotPlacement" }, "RamdiskId": { "type": "string" }, "SecurityGroups": { "items": { "$ref": "#/definitions/AWS::EC2::SpotFleet.GroupIdentifier" }, "type": "array" }, "SpotPrice": { "type": "string" }, "SubnetId": { "type": "string" }, "TagSpecifications": { "items": { "$ref": "#/definitions/AWS::EC2::SpotFleet.SpotFleetTagSpecification" }, "type": "array" }, "UserData": { "type": "string" }, "WeightedCapacity": { "type": "number" } }, "required": [ "ImageId", "InstanceType" ], "type": "object" }, "AWS::EC2::SpotFleet.SpotFleetMonitoring": { "additionalProperties": false, "properties": { "Enabled": { "type": "boolean" } }, "type": "object" }, "AWS::EC2::SpotFleet.SpotFleetRequestConfigData": { "additionalProperties": false, "properties": { "AllocationStrategy": { "type": "string" }, "ExcessCapacityTerminationPolicy": { "type": "string" }, "IamFleetRole": { "type": "string" }, "LaunchSpecifications": { "items": { "$ref": "#/definitions/AWS::EC2::SpotFleet.SpotFleetLaunchSpecification" }, "type": "array" }, "ReplaceUnhealthyInstances": { "type": "boolean" }, "SpotPrice": { "type": "string" }, "TargetCapacity": { "type": "number" }, "TerminateInstancesWithExpiration": { "type": "boolean" }, "Type": { "type": "string" }, "ValidFrom": { "type": "string" }, "ValidUntil": { "type": "string" } }, "required": [ "IamFleetRole", "LaunchSpecifications", "TargetCapacity" ], "type": "object" }, "AWS::EC2::SpotFleet.SpotFleetTagSpecification": { "additionalProperties": false, "properties": { "ResourceType": { "type": "string" } }, "type": "object" }, "AWS::EC2::SpotFleet.SpotPlacement": { "additionalProperties": false, "properties": { "AvailabilityZone": { "type": "string" }, "GroupName": { "type": "string" } }, "type": "object" }, "AWS::EC2::Subnet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AssignIpv6AddressOnCreation": { "type": "boolean" }, "AvailabilityZone": { "type": "string" }, "CidrBlock": { "type": "string" }, "Ipv6CidrBlock": { "type": "string" }, "MapPublicIpOnLaunch": { "type": "boolean" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "CidrBlock", "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::Subnet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SubnetCidrBlock": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Ipv6CidrBlock": { "type": "string" }, "SubnetId": { "type": "string" } }, "required": [ "Ipv6CidrBlock", "SubnetId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::SubnetCidrBlock" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SubnetNetworkAclAssociation": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "NetworkAclId": { "type": "string" }, "SubnetId": { "type": "string" } }, "required": [ "NetworkAclId", "SubnetId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::SubnetNetworkAclAssociation" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::SubnetRouteTableAssociation": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "RouteTableId": { "type": "string" }, "SubnetId": { "type": "string" } }, "required": [ "RouteTableId", "SubnetId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::SubnetRouteTableAssociation" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::TrunkInterfaceAssociation": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "BranchInterfaceId": { "type": "string" }, "GREKey": { "type": "number" }, "TrunkInterfaceId": { "type": "string" }, "VLANId": { "type": "number" } }, "required": [ "BranchInterfaceId", "TrunkInterfaceId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::TrunkInterfaceAssociation" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPC": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CidrBlock": { "type": "string" }, "EnableDnsHostnames": { "type": "boolean" }, "EnableDnsSupport": { "type": "boolean" }, "InstanceTenancy": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "CidrBlock" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPC" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPCCidrBlock": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AmazonProvidedIpv6CidrBlock": { "type": "boolean" }, "CidrBlock": { "type": "string" }, "VpcId": { "type": "string" } }, "required": [ "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPCCidrBlock" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPCDHCPOptionsAssociation": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DhcpOptionsId": { "type": "string" }, "VpcId": { "type": "string" } }, "required": [ "DhcpOptionsId", "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPCDHCPOptionsAssociation" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPCEndpoint": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PolicyDocument": { "type": "object" }, "RouteTableIds": { "items": { "type": "string" }, "type": "array" }, "ServiceName": { "type": "string" }, "VpcId": { "type": "string" } }, "required": [ "ServiceName", "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPCEndpoint" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPCGatewayAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "InternetGatewayId": { "type": "string" }, "VpcId": { "type": "string" }, "VpnGatewayId": { "type": "string" } }, "required": [ "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPCGatewayAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPCPeeringConnection": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PeerOwnerId": { "type": "string" }, "PeerRoleArn": { "type": "string" }, "PeerVpcId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcId": { "type": "string" } }, "required": [ "PeerVpcId", "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPCPeeringConnection" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPNConnection": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CustomerGatewayId": { "type": "string" }, "StaticRoutesOnly": { "type": "boolean" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Type": { "type": "string" }, "VpnGatewayId": { "type": "string" }, "VpnTunnelOptionsSpecifications": { "items": { "$ref": "#/definitions/AWS::EC2::VPNConnection.VpnTunnelOptionsSpecification" }, "type": "array" } }, "required": [ "CustomerGatewayId", "Type", "VpnGatewayId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPNConnection" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPNConnection.VpnTunnelOptionsSpecification": { "additionalProperties": false, "properties": { "PreSharedKey": { "type": "string" }, "TunnelInsideCidr": { "type": "string" } }, "type": "object" }, "AWS::EC2::VPNConnectionRoute": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DestinationCidrBlock": { "type": "string" }, "VpnConnectionId": { "type": "string" } }, "required": [ "DestinationCidrBlock", "VpnConnectionId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPNConnectionRoute" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPNGateway": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AmazonSideAsn": { "type": "number" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPNGateway" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VPNGatewayRoutePropagation": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "RouteTableIds": { "items": { "type": "string" }, "type": "array" }, "VpnGatewayId": { "type": "string" } }, "required": [ "RouteTableIds", "VpnGatewayId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VPNGatewayRoutePropagation" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::Volume": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AutoEnableIO": { "type": "boolean" }, "AvailabilityZone": { "type": "string" }, "Encrypted": { "type": "boolean" }, "Iops": { "type": "number" }, "KmsKeyId": { "type": "string" }, "Size": { "type": "number" }, "SnapshotId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VolumeType": { "type": "string" } }, "required": [ "AvailabilityZone" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::Volume" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EC2::VolumeAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Device": { "type": "string" }, "InstanceId": { "type": "string" }, "VolumeId": { "type": "string" } }, "required": [ "Device", "InstanceId", "VolumeId" ], "type": "object" }, "Type": { "enum": [ "AWS::EC2::VolumeAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ECR::Repository": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "LifecyclePolicy": { "$ref": "#/definitions/AWS::ECR::Repository.LifecyclePolicy" }, "RepositoryName": { "type": "string" }, "RepositoryPolicyText": { "type": "object" } }, "type": "object" }, "Type": { "enum": [ "AWS::ECR::Repository" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ECR::Repository.LifecyclePolicy": { "additionalProperties": false, "properties": { "LifecyclePolicyText": { "type": "string" }, "RegistryId": { "type": "string" } }, "type": "object" }, "AWS::ECS::Cluster": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ClusterName": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::ECS::Cluster" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ECS::Service": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Cluster": { "type": "string" }, "DeploymentConfiguration": { "$ref": "#/definitions/AWS::ECS::Service.DeploymentConfiguration" }, "DesiredCount": { "type": "number" }, "HealthCheckGracePeriodSeconds": { "type": "number" }, "LaunchType": { "type": "string" }, "LoadBalancers": { "items": { "$ref": "#/definitions/AWS::ECS::Service.LoadBalancer" }, "type": "array" }, "NetworkConfiguration": { "$ref": "#/definitions/AWS::ECS::Service.NetworkConfiguration" }, "PlacementConstraints": { "items": { "$ref": "#/definitions/AWS::ECS::Service.PlacementConstraint" }, "type": "array" }, "PlacementStrategies": { "items": { "$ref": "#/definitions/AWS::ECS::Service.PlacementStrategy" }, "type": "array" }, "PlatformVersion": { "type": "string" }, "Role": { "type": "string" }, "ServiceName": { "type": "string" }, "TaskDefinition": { "type": "string" } }, "required": [ "TaskDefinition" ], "type": "object" }, "Type": { "enum": [ "AWS::ECS::Service" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ECS::Service.AwsVpcConfiguration": { "additionalProperties": false, "properties": { "AssignPublicIp": { "type": "string" }, "SecurityGroups": { "items": { "type": "string" }, "type": "array" }, "Subnets": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Subnets" ], "type": "object" }, "AWS::ECS::Service.DeploymentConfiguration": { "additionalProperties": false, "properties": { "MaximumPercent": { "type": "number" }, "MinimumHealthyPercent": { "type": "number" } }, "type": "object" }, "AWS::ECS::Service.LoadBalancer": { "additionalProperties": false, "properties": { "ContainerName": { "type": "string" }, "ContainerPort": { "type": "number" }, "LoadBalancerName": { "type": "string" }, "TargetGroupArn": { "type": "string" } }, "required": [ "ContainerPort" ], "type": "object" }, "AWS::ECS::Service.NetworkConfiguration": { "additionalProperties": false, "properties": { "AwsvpcConfiguration": { "$ref": "#/definitions/AWS::ECS::Service.AwsVpcConfiguration" } }, "type": "object" }, "AWS::ECS::Service.PlacementConstraint": { "additionalProperties": false, "properties": { "Expression": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ECS::Service.PlacementStrategy": { "additionalProperties": false, "properties": { "Field": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ECS::TaskDefinition": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ContainerDefinitions": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.ContainerDefinition" }, "type": "array" }, "Cpu": { "type": "string" }, "ExecutionRoleArn": { "type": "string" }, "Family": { "type": "string" }, "Memory": { "type": "string" }, "NetworkMode": { "type": "string" }, "PlacementConstraints": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.TaskDefinitionPlacementConstraint" }, "type": "array" }, "RequiresCompatibilities": { "items": { "type": "string" }, "type": "array" }, "TaskRoleArn": { "type": "string" }, "Volumes": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.Volume" }, "type": "array" } }, "type": "object" }, "Type": { "enum": [ "AWS::ECS::TaskDefinition" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ECS::TaskDefinition.ContainerDefinition": { "additionalProperties": false, "properties": { "Command": { "items": { "type": "string" }, "type": "array" }, "Cpu": { "type": "number" }, "DisableNetworking": { "type": "boolean" }, "DnsSearchDomains": { "items": { "type": "string" }, "type": "array" }, "DnsServers": { "items": { "type": "string" }, "type": "array" }, "DockerLabels": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "DockerSecurityOptions": { "items": { "type": "string" }, "type": "array" }, "EntryPoint": { "items": { "type": "string" }, "type": "array" }, "Environment": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.KeyValuePair" }, "type": "array" }, "Essential": { "type": "boolean" }, "ExtraHosts": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.HostEntry" }, "type": "array" }, "Hostname": { "type": "string" }, "Image": { "type": "string" }, "Links": { "items": { "type": "string" }, "type": "array" }, "LinuxParameters": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.LinuxParameters" }, "LogConfiguration": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.LogConfiguration" }, "Memory": { "type": "number" }, "MemoryReservation": { "type": "number" }, "MountPoints": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.MountPoint" }, "type": "array" }, "Name": { "type": "string" }, "PortMappings": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.PortMapping" }, "type": "array" }, "Privileged": { "type": "boolean" }, "ReadonlyRootFilesystem": { "type": "boolean" }, "Ulimits": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.Ulimit" }, "type": "array" }, "User": { "type": "string" }, "VolumesFrom": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.VolumeFrom" }, "type": "array" }, "WorkingDirectory": { "type": "string" } }, "type": "object" }, "AWS::ECS::TaskDefinition.Device": { "additionalProperties": false, "properties": { "ContainerPath": { "type": "string" }, "HostPath": { "type": "string" }, "Permissions": { "items": { "type": "string" }, "type": "array" } }, "required": [ "HostPath" ], "type": "object" }, "AWS::ECS::TaskDefinition.HostEntry": { "additionalProperties": false, "properties": { "Hostname": { "type": "string" }, "IpAddress": { "type": "string" } }, "required": [ "Hostname", "IpAddress" ], "type": "object" }, "AWS::ECS::TaskDefinition.HostVolumeProperties": { "additionalProperties": false, "properties": { "SourcePath": { "type": "string" } }, "type": "object" }, "AWS::ECS::TaskDefinition.KernelCapabilities": { "additionalProperties": false, "properties": { "Add": { "items": { "type": "string" }, "type": "array" }, "Drop": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::ECS::TaskDefinition.KeyValuePair": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::ECS::TaskDefinition.LinuxParameters": { "additionalProperties": false, "properties": { "Capabilities": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.KernelCapabilities" }, "Devices": { "items": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.Device" }, "type": "array" }, "InitProcessEnabled": { "type": "boolean" } }, "type": "object" }, "AWS::ECS::TaskDefinition.LogConfiguration": { "additionalProperties": false, "properties": { "LogDriver": { "type": "string" }, "Options": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "required": [ "LogDriver" ], "type": "object" }, "AWS::ECS::TaskDefinition.MountPoint": { "additionalProperties": false, "properties": { "ContainerPath": { "type": "string" }, "ReadOnly": { "type": "boolean" }, "SourceVolume": { "type": "string" } }, "type": "object" }, "AWS::ECS::TaskDefinition.PortMapping": { "additionalProperties": false, "properties": { "ContainerPort": { "type": "number" }, "HostPort": { "type": "number" }, "Protocol": { "type": "string" } }, "type": "object" }, "AWS::ECS::TaskDefinition.TaskDefinitionPlacementConstraint": { "additionalProperties": false, "properties": { "Expression": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ECS::TaskDefinition.Ulimit": { "additionalProperties": false, "properties": { "HardLimit": { "type": "number" }, "Name": { "type": "string" }, "SoftLimit": { "type": "number" } }, "required": [ "HardLimit", "Name", "SoftLimit" ], "type": "object" }, "AWS::ECS::TaskDefinition.Volume": { "additionalProperties": false, "properties": { "Host": { "$ref": "#/definitions/AWS::ECS::TaskDefinition.HostVolumeProperties" }, "Name": { "type": "string" } }, "type": "object" }, "AWS::ECS::TaskDefinition.VolumeFrom": { "additionalProperties": false, "properties": { "ReadOnly": { "type": "boolean" }, "SourceContainer": { "type": "string" } }, "type": "object" }, "AWS::EFS::FileSystem": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Encrypted": { "type": "boolean" }, "FileSystemTags": { "items": { "$ref": "#/definitions/AWS::EFS::FileSystem.ElasticFileSystemTag" }, "type": "array" }, "KmsKeyId": { "type": "string" }, "PerformanceMode": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::EFS::FileSystem" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::EFS::FileSystem.ElasticFileSystemTag": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::EFS::MountTarget": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "FileSystemId": { "type": "string" }, "IpAddress": { "type": "string" }, "SecurityGroups": { "items": { "type": "string" }, "type": "array" }, "SubnetId": { "type": "string" } }, "required": [ "FileSystemId", "SecurityGroups", "SubnetId" ], "type": "object" }, "Type": { "enum": [ "AWS::EFS::MountTarget" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EMR::Cluster": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AdditionalInfo": { "type": "object" }, "Applications": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.Application" }, "type": "array" }, "AutoScalingRole": { "type": "string" }, "BootstrapActions": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.BootstrapActionConfig" }, "type": "array" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.Configuration" }, "type": "array" }, "CustomAmiId": { "type": "string" }, "EbsRootVolumeSize": { "type": "number" }, "Instances": { "$ref": "#/definitions/AWS::EMR::Cluster.JobFlowInstancesConfig" }, "JobFlowRole": { "type": "string" }, "LogUri": { "type": "string" }, "Name": { "type": "string" }, "ReleaseLabel": { "type": "string" }, "ScaleDownBehavior": { "type": "string" }, "SecurityConfiguration": { "type": "string" }, "ServiceRole": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VisibleToAllUsers": { "type": "boolean" } }, "required": [ "Instances", "JobFlowRole", "Name", "ServiceRole" ], "type": "object" }, "Type": { "enum": [ "AWS::EMR::Cluster" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EMR::Cluster.Application": { "additionalProperties": false, "properties": { "AdditionalInfo": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Args": { "items": { "type": "string" }, "type": "array" }, "Name": { "type": "string" }, "Version": { "type": "string" } }, "type": "object" }, "AWS::EMR::Cluster.AutoScalingPolicy": { "additionalProperties": false, "properties": { "Constraints": { "$ref": "#/definitions/AWS::EMR::Cluster.ScalingConstraints" }, "Rules": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.ScalingRule" }, "type": "array" } }, "required": [ "Constraints", "Rules" ], "type": "object" }, "AWS::EMR::Cluster.BootstrapActionConfig": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "ScriptBootstrapAction": { "$ref": "#/definitions/AWS::EMR::Cluster.ScriptBootstrapActionConfig" } }, "required": [ "Name", "ScriptBootstrapAction" ], "type": "object" }, "AWS::EMR::Cluster.CloudWatchAlarmDefinition": { "additionalProperties": false, "properties": { "ComparisonOperator": { "type": "string" }, "Dimensions": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.MetricDimension" }, "type": "array" }, "EvaluationPeriods": { "type": "number" }, "MetricName": { "type": "string" }, "Namespace": { "type": "string" }, "Period": { "type": "number" }, "Statistic": { "type": "string" }, "Threshold": { "type": "number" }, "Unit": { "type": "string" } }, "required": [ "ComparisonOperator", "MetricName", "Period", "Threshold" ], "type": "object" }, "AWS::EMR::Cluster.Configuration": { "additionalProperties": false, "properties": { "Classification": { "type": "string" }, "ConfigurationProperties": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.Configuration" }, "type": "array" } }, "type": "object" }, "AWS::EMR::Cluster.EbsBlockDeviceConfig": { "additionalProperties": false, "properties": { "VolumeSpecification": { "$ref": "#/definitions/AWS::EMR::Cluster.VolumeSpecification" }, "VolumesPerInstance": { "type": "number" } }, "required": [ "VolumeSpecification" ], "type": "object" }, "AWS::EMR::Cluster.EbsConfiguration": { "additionalProperties": false, "properties": { "EbsBlockDeviceConfigs": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.EbsBlockDeviceConfig" }, "type": "array" }, "EbsOptimized": { "type": "boolean" } }, "type": "object" }, "AWS::EMR::Cluster.InstanceFleetConfig": { "additionalProperties": false, "properties": { "InstanceTypeConfigs": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.InstanceTypeConfig" }, "type": "array" }, "LaunchSpecifications": { "$ref": "#/definitions/AWS::EMR::Cluster.InstanceFleetProvisioningSpecifications" }, "Name": { "type": "string" }, "TargetOnDemandCapacity": { "type": "number" }, "TargetSpotCapacity": { "type": "number" } }, "type": "object" }, "AWS::EMR::Cluster.InstanceFleetProvisioningSpecifications": { "additionalProperties": false, "properties": { "SpotSpecification": { "$ref": "#/definitions/AWS::EMR::Cluster.SpotProvisioningSpecification" } }, "required": [ "SpotSpecification" ], "type": "object" }, "AWS::EMR::Cluster.InstanceGroupConfig": { "additionalProperties": false, "properties": { "AutoScalingPolicy": { "$ref": "#/definitions/AWS::EMR::Cluster.AutoScalingPolicy" }, "BidPrice": { "type": "string" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.Configuration" }, "type": "array" }, "EbsConfiguration": { "$ref": "#/definitions/AWS::EMR::Cluster.EbsConfiguration" }, "InstanceCount": { "type": "number" }, "InstanceType": { "type": "string" }, "Market": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "InstanceCount", "InstanceType" ], "type": "object" }, "AWS::EMR::Cluster.InstanceTypeConfig": { "additionalProperties": false, "properties": { "BidPrice": { "type": "string" }, "BidPriceAsPercentageOfOnDemandPrice": { "type": "number" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::Cluster.Configuration" }, "type": "array" }, "EbsConfiguration": { "$ref": "#/definitions/AWS::EMR::Cluster.EbsConfiguration" }, "InstanceType": { "type": "string" }, "WeightedCapacity": { "type": "number" } }, "required": [ "InstanceType" ], "type": "object" }, "AWS::EMR::Cluster.JobFlowInstancesConfig": { "additionalProperties": false, "properties": { "AdditionalMasterSecurityGroups": { "items": { "type": "string" }, "type": "array" }, "AdditionalSlaveSecurityGroups": { "items": { "type": "string" }, "type": "array" }, "CoreInstanceFleet": { "$ref": "#/definitions/AWS::EMR::Cluster.InstanceFleetConfig" }, "CoreInstanceGroup": { "$ref": "#/definitions/AWS::EMR::Cluster.InstanceGroupConfig" }, "Ec2KeyName": { "type": "string" }, "Ec2SubnetId": { "type": "string" }, "EmrManagedMasterSecurityGroup": { "type": "string" }, "EmrManagedSlaveSecurityGroup": { "type": "string" }, "HadoopVersion": { "type": "string" }, "MasterInstanceFleet": { "$ref": "#/definitions/AWS::EMR::Cluster.InstanceFleetConfig" }, "MasterInstanceGroup": { "$ref": "#/definitions/AWS::EMR::Cluster.InstanceGroupConfig" }, "Placement": { "$ref": "#/definitions/AWS::EMR::Cluster.PlacementType" }, "ServiceAccessSecurityGroup": { "type": "string" }, "TerminationProtected": { "type": "boolean" } }, "type": "object" }, "AWS::EMR::Cluster.MetricDimension": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::EMR::Cluster.PlacementType": { "additionalProperties": false, "properties": { "AvailabilityZone": { "type": "string" } }, "required": [ "AvailabilityZone" ], "type": "object" }, "AWS::EMR::Cluster.ScalingAction": { "additionalProperties": false, "properties": { "Market": { "type": "string" }, "SimpleScalingPolicyConfiguration": { "$ref": "#/definitions/AWS::EMR::Cluster.SimpleScalingPolicyConfiguration" } }, "required": [ "SimpleScalingPolicyConfiguration" ], "type": "object" }, "AWS::EMR::Cluster.ScalingConstraints": { "additionalProperties": false, "properties": { "MaxCapacity": { "type": "number" }, "MinCapacity": { "type": "number" } }, "required": [ "MaxCapacity", "MinCapacity" ], "type": "object" }, "AWS::EMR::Cluster.ScalingRule": { "additionalProperties": false, "properties": { "Action": { "$ref": "#/definitions/AWS::EMR::Cluster.ScalingAction" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "Trigger": { "$ref": "#/definitions/AWS::EMR::Cluster.ScalingTrigger" } }, "required": [ "Action", "Name", "Trigger" ], "type": "object" }, "AWS::EMR::Cluster.ScalingTrigger": { "additionalProperties": false, "properties": { "CloudWatchAlarmDefinition": { "$ref": "#/definitions/AWS::EMR::Cluster.CloudWatchAlarmDefinition" } }, "required": [ "CloudWatchAlarmDefinition" ], "type": "object" }, "AWS::EMR::Cluster.ScriptBootstrapActionConfig": { "additionalProperties": false, "properties": { "Args": { "items": { "type": "string" }, "type": "array" }, "Path": { "type": "string" } }, "required": [ "Path" ], "type": "object" }, "AWS::EMR::Cluster.SimpleScalingPolicyConfiguration": { "additionalProperties": false, "properties": { "AdjustmentType": { "type": "string" }, "CoolDown": { "type": "number" }, "ScalingAdjustment": { "type": "number" } }, "required": [ "ScalingAdjustment" ], "type": "object" }, "AWS::EMR::Cluster.SpotProvisioningSpecification": { "additionalProperties": false, "properties": { "BlockDurationMinutes": { "type": "number" }, "TimeoutAction": { "type": "string" }, "TimeoutDurationMinutes": { "type": "number" } }, "required": [ "TimeoutAction", "TimeoutDurationMinutes" ], "type": "object" }, "AWS::EMR::Cluster.VolumeSpecification": { "additionalProperties": false, "properties": { "Iops": { "type": "number" }, "SizeInGB": { "type": "number" }, "VolumeType": { "type": "string" } }, "required": [ "SizeInGB", "VolumeType" ], "type": "object" }, "AWS::EMR::InstanceFleetConfig": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ClusterId": { "type": "string" }, "InstanceFleetType": { "type": "string" }, "InstanceTypeConfigs": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.InstanceTypeConfig" }, "type": "array" }, "LaunchSpecifications": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.InstanceFleetProvisioningSpecifications" }, "Name": { "type": "string" }, "TargetOnDemandCapacity": { "type": "number" }, "TargetSpotCapacity": { "type": "number" } }, "required": [ "ClusterId", "InstanceFleetType" ], "type": "object" }, "Type": { "enum": [ "AWS::EMR::InstanceFleetConfig" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EMR::InstanceFleetConfig.Configuration": { "additionalProperties": false, "properties": { "Classification": { "type": "string" }, "ConfigurationProperties": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.Configuration" }, "type": "array" } }, "type": "object" }, "AWS::EMR::InstanceFleetConfig.EbsBlockDeviceConfig": { "additionalProperties": false, "properties": { "VolumeSpecification": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.VolumeSpecification" }, "VolumesPerInstance": { "type": "number" } }, "required": [ "VolumeSpecification" ], "type": "object" }, "AWS::EMR::InstanceFleetConfig.EbsConfiguration": { "additionalProperties": false, "properties": { "EbsBlockDeviceConfigs": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.EbsBlockDeviceConfig" }, "type": "array" }, "EbsOptimized": { "type": "boolean" } }, "type": "object" }, "AWS::EMR::InstanceFleetConfig.InstanceFleetProvisioningSpecifications": { "additionalProperties": false, "properties": { "SpotSpecification": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.SpotProvisioningSpecification" } }, "required": [ "SpotSpecification" ], "type": "object" }, "AWS::EMR::InstanceFleetConfig.InstanceTypeConfig": { "additionalProperties": false, "properties": { "BidPrice": { "type": "string" }, "BidPriceAsPercentageOfOnDemandPrice": { "type": "number" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.Configuration" }, "type": "array" }, "EbsConfiguration": { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig.EbsConfiguration" }, "InstanceType": { "type": "string" }, "WeightedCapacity": { "type": "number" } }, "required": [ "InstanceType" ], "type": "object" }, "AWS::EMR::InstanceFleetConfig.SpotProvisioningSpecification": { "additionalProperties": false, "properties": { "BlockDurationMinutes": { "type": "number" }, "TimeoutAction": { "type": "string" }, "TimeoutDurationMinutes": { "type": "number" } }, "required": [ "TimeoutAction", "TimeoutDurationMinutes" ], "type": "object" }, "AWS::EMR::InstanceFleetConfig.VolumeSpecification": { "additionalProperties": false, "properties": { "Iops": { "type": "number" }, "SizeInGB": { "type": "number" }, "VolumeType": { "type": "string" } }, "required": [ "SizeInGB", "VolumeType" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AutoScalingPolicy": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.AutoScalingPolicy" }, "BidPrice": { "type": "string" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.Configuration" }, "type": "array" }, "EbsConfiguration": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.EbsConfiguration" }, "InstanceCount": { "type": "number" }, "InstanceRole": { "type": "string" }, "InstanceType": { "type": "string" }, "JobFlowId": { "type": "string" }, "Market": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "InstanceCount", "InstanceRole", "InstanceType", "JobFlowId" ], "type": "object" }, "Type": { "enum": [ "AWS::EMR::InstanceGroupConfig" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.AutoScalingPolicy": { "additionalProperties": false, "properties": { "Constraints": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.ScalingConstraints" }, "Rules": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.ScalingRule" }, "type": "array" } }, "required": [ "Constraints", "Rules" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.CloudWatchAlarmDefinition": { "additionalProperties": false, "properties": { "ComparisonOperator": { "type": "string" }, "Dimensions": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.MetricDimension" }, "type": "array" }, "EvaluationPeriods": { "type": "number" }, "MetricName": { "type": "string" }, "Namespace": { "type": "string" }, "Period": { "type": "number" }, "Statistic": { "type": "string" }, "Threshold": { "type": "number" }, "Unit": { "type": "string" } }, "required": [ "ComparisonOperator", "MetricName", "Period", "Threshold" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.Configuration": { "additionalProperties": false, "properties": { "Classification": { "type": "string" }, "ConfigurationProperties": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Configurations": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.Configuration" }, "type": "array" } }, "type": "object" }, "AWS::EMR::InstanceGroupConfig.EbsBlockDeviceConfig": { "additionalProperties": false, "properties": { "VolumeSpecification": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.VolumeSpecification" }, "VolumesPerInstance": { "type": "number" } }, "required": [ "VolumeSpecification" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.EbsConfiguration": { "additionalProperties": false, "properties": { "EbsBlockDeviceConfigs": { "items": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.EbsBlockDeviceConfig" }, "type": "array" }, "EbsOptimized": { "type": "boolean" } }, "type": "object" }, "AWS::EMR::InstanceGroupConfig.MetricDimension": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.ScalingAction": { "additionalProperties": false, "properties": { "Market": { "type": "string" }, "SimpleScalingPolicyConfiguration": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.SimpleScalingPolicyConfiguration" } }, "required": [ "SimpleScalingPolicyConfiguration" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.ScalingConstraints": { "additionalProperties": false, "properties": { "MaxCapacity": { "type": "number" }, "MinCapacity": { "type": "number" } }, "required": [ "MaxCapacity", "MinCapacity" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.ScalingRule": { "additionalProperties": false, "properties": { "Action": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.ScalingAction" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "Trigger": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.ScalingTrigger" } }, "required": [ "Action", "Name", "Trigger" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.ScalingTrigger": { "additionalProperties": false, "properties": { "CloudWatchAlarmDefinition": { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig.CloudWatchAlarmDefinition" } }, "required": [ "CloudWatchAlarmDefinition" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.SimpleScalingPolicyConfiguration": { "additionalProperties": false, "properties": { "AdjustmentType": { "type": "string" }, "CoolDown": { "type": "number" }, "ScalingAdjustment": { "type": "number" } }, "required": [ "ScalingAdjustment" ], "type": "object" }, "AWS::EMR::InstanceGroupConfig.VolumeSpecification": { "additionalProperties": false, "properties": { "Iops": { "type": "number" }, "SizeInGB": { "type": "number" }, "VolumeType": { "type": "string" } }, "required": [ "SizeInGB", "VolumeType" ], "type": "object" }, "AWS::EMR::SecurityConfiguration": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "SecurityConfiguration": { "type": "object" } }, "required": [ "SecurityConfiguration" ], "type": "object" }, "Type": { "enum": [ "AWS::EMR::SecurityConfiguration" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EMR::Step": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ActionOnFailure": { "type": "string" }, "HadoopJarStep": { "$ref": "#/definitions/AWS::EMR::Step.HadoopJarStepConfig" }, "JobFlowId": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "ActionOnFailure", "HadoopJarStep", "JobFlowId", "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::EMR::Step" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::EMR::Step.HadoopJarStepConfig": { "additionalProperties": false, "properties": { "Args": { "items": { "type": "string" }, "type": "array" }, "Jar": { "type": "string" }, "MainClass": { "type": "string" }, "StepProperties": { "items": { "$ref": "#/definitions/AWS::EMR::Step.KeyValue" }, "type": "array" } }, "required": [ "Jar" ], "type": "object" }, "AWS::EMR::Step.KeyValue": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::ElastiCache::CacheCluster": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AZMode": { "type": "string" }, "AutoMinorVersionUpgrade": { "type": "boolean" }, "CacheNodeType": { "type": "string" }, "CacheParameterGroupName": { "type": "string" }, "CacheSecurityGroupNames": { "items": { "type": "string" }, "type": "array" }, "CacheSubnetGroupName": { "type": "string" }, "ClusterName": { "type": "string" }, "Engine": { "type": "string" }, "EngineVersion": { "type": "string" }, "NotificationTopicArn": { "type": "string" }, "NumCacheNodes": { "type": "number" }, "Port": { "type": "number" }, "PreferredAvailabilityZone": { "type": "string" }, "PreferredAvailabilityZones": { "items": { "type": "string" }, "type": "array" }, "PreferredMaintenanceWindow": { "type": "string" }, "SnapshotArns": { "items": { "type": "string" }, "type": "array" }, "SnapshotName": { "type": "string" }, "SnapshotRetentionLimit": { "type": "number" }, "SnapshotWindow": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcSecurityGroupIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "CacheNodeType", "Engine", "NumCacheNodes" ], "type": "object" }, "Type": { "enum": [ "AWS::ElastiCache::CacheCluster" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElastiCache::ParameterGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CacheParameterGroupFamily": { "type": "string" }, "Description": { "type": "string" }, "Properties": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "required": [ "CacheParameterGroupFamily", "Description" ], "type": "object" }, "Type": { "enum": [ "AWS::ElastiCache::ParameterGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElastiCache::ReplicationGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AtRestEncryptionEnabled": { "type": "boolean" }, "AuthToken": { "type": "string" }, "AutoMinorVersionUpgrade": { "type": "boolean" }, "AutomaticFailoverEnabled": { "type": "boolean" }, "CacheNodeType": { "type": "string" }, "CacheParameterGroupName": { "type": "string" }, "CacheSecurityGroupNames": { "items": { "type": "string" }, "type": "array" }, "CacheSubnetGroupName": { "type": "string" }, "Engine": { "type": "string" }, "EngineVersion": { "type": "string" }, "NodeGroupConfiguration": { "items": { "$ref": "#/definitions/AWS::ElastiCache::ReplicationGroup.NodeGroupConfiguration" }, "type": "array" }, "NotificationTopicArn": { "type": "string" }, "NumCacheClusters": { "type": "number" }, "NumNodeGroups": { "type": "number" }, "Port": { "type": "number" }, "PreferredCacheClusterAZs": { "items": { "type": "string" }, "type": "array" }, "PreferredMaintenanceWindow": { "type": "string" }, "PrimaryClusterId": { "type": "string" }, "ReplicasPerNodeGroup": { "type": "number" }, "ReplicationGroupDescription": { "type": "string" }, "ReplicationGroupId": { "type": "string" }, "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SnapshotArns": { "items": { "type": "string" }, "type": "array" }, "SnapshotName": { "type": "string" }, "SnapshotRetentionLimit": { "type": "number" }, "SnapshotWindow": { "type": "string" }, "SnapshottingClusterId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TransitEncryptionEnabled": { "type": "boolean" } }, "required": [ "ReplicationGroupDescription" ], "type": "object" }, "Type": { "enum": [ "AWS::ElastiCache::ReplicationGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElastiCache::ReplicationGroup.NodeGroupConfiguration": { "additionalProperties": false, "properties": { "PrimaryAvailabilityZone": { "type": "string" }, "ReplicaAvailabilityZones": { "items": { "type": "string" }, "type": "array" }, "ReplicaCount": { "type": "number" }, "Slots": { "type": "string" } }, "type": "object" }, "AWS::ElastiCache::SecurityGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" } }, "required": [ "Description" ], "type": "object" }, "Type": { "enum": [ "AWS::ElastiCache::SecurityGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElastiCache::SecurityGroupIngress": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CacheSecurityGroupName": { "type": "string" }, "EC2SecurityGroupName": { "type": "string" }, "EC2SecurityGroupOwnerId": { "type": "string" } }, "required": [ "CacheSecurityGroupName", "EC2SecurityGroupName" ], "type": "object" }, "Type": { "enum": [ "AWS::ElastiCache::SecurityGroupIngress" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElastiCache::SubnetGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CacheSubnetGroupName": { "type": "string" }, "Description": { "type": "string" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Description", "SubnetIds" ], "type": "object" }, "Type": { "enum": [ "AWS::ElastiCache::SubnetGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticBeanstalk::Application": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "Description": { "type": "string" }, "ResourceLifecycleConfig": { "$ref": "#/definitions/AWS::ElasticBeanstalk::Application.ApplicationResourceLifecycleConfig" } }, "type": "object" }, "Type": { "enum": [ "AWS::ElasticBeanstalk::Application" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ElasticBeanstalk::Application.ApplicationResourceLifecycleConfig": { "additionalProperties": false, "properties": { "ServiceRole": { "type": "string" }, "VersionLifecycleConfig": { "$ref": "#/definitions/AWS::ElasticBeanstalk::Application.ApplicationVersionLifecycleConfig" } }, "type": "object" }, "AWS::ElasticBeanstalk::Application.ApplicationVersionLifecycleConfig": { "additionalProperties": false, "properties": { "MaxAgeRule": { "$ref": "#/definitions/AWS::ElasticBeanstalk::Application.MaxAgeRule" }, "MaxCountRule": { "$ref": "#/definitions/AWS::ElasticBeanstalk::Application.MaxCountRule" } }, "type": "object" }, "AWS::ElasticBeanstalk::Application.MaxAgeRule": { "additionalProperties": false, "properties": { "DeleteSourceFromS3": { "type": "boolean" }, "Enabled": { "type": "boolean" }, "MaxAgeInDays": { "type": "number" } }, "type": "object" }, "AWS::ElasticBeanstalk::Application.MaxCountRule": { "additionalProperties": false, "properties": { "DeleteSourceFromS3": { "type": "boolean" }, "Enabled": { "type": "boolean" }, "MaxCount": { "type": "number" } }, "type": "object" }, "AWS::ElasticBeanstalk::ApplicationVersion": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "Description": { "type": "string" }, "SourceBundle": { "$ref": "#/definitions/AWS::ElasticBeanstalk::ApplicationVersion.SourceBundle" } }, "required": [ "ApplicationName", "SourceBundle" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticBeanstalk::ApplicationVersion" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticBeanstalk::ApplicationVersion.SourceBundle": { "additionalProperties": false, "properties": { "S3Bucket": { "type": "string" }, "S3Key": { "type": "string" } }, "required": [ "S3Bucket", "S3Key" ], "type": "object" }, "AWS::ElasticBeanstalk::ConfigurationTemplate": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "Description": { "type": "string" }, "EnvironmentId": { "type": "string" }, "OptionSettings": { "items": { "$ref": "#/definitions/AWS::ElasticBeanstalk::ConfigurationTemplate.ConfigurationOptionSetting" }, "type": "array" }, "PlatformArn": { "type": "string" }, "SolutionStackName": { "type": "string" }, "SourceConfiguration": { "$ref": "#/definitions/AWS::ElasticBeanstalk::ConfigurationTemplate.SourceConfiguration" } }, "required": [ "ApplicationName" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticBeanstalk::ConfigurationTemplate" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticBeanstalk::ConfigurationTemplate.ConfigurationOptionSetting": { "additionalProperties": false, "properties": { "Namespace": { "type": "string" }, "OptionName": { "type": "string" }, "ResourceName": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Namespace", "OptionName" ], "type": "object" }, "AWS::ElasticBeanstalk::ConfigurationTemplate.SourceConfiguration": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "TemplateName": { "type": "string" } }, "required": [ "ApplicationName", "TemplateName" ], "type": "object" }, "AWS::ElasticBeanstalk::Environment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "CNAMEPrefix": { "type": "string" }, "Description": { "type": "string" }, "EnvironmentName": { "type": "string" }, "OptionSettings": { "items": { "$ref": "#/definitions/AWS::ElasticBeanstalk::Environment.OptionSetting" }, "type": "array" }, "PlatformArn": { "type": "string" }, "SolutionStackName": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TemplateName": { "type": "string" }, "Tier": { "$ref": "#/definitions/AWS::ElasticBeanstalk::Environment.Tier" }, "VersionLabel": { "type": "string" } }, "required": [ "ApplicationName" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticBeanstalk::Environment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticBeanstalk::Environment.OptionSetting": { "additionalProperties": false, "properties": { "Namespace": { "type": "string" }, "OptionName": { "type": "string" }, "ResourceName": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Namespace", "OptionName" ], "type": "object" }, "AWS::ElasticBeanstalk::Environment.Tier": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Type": { "type": "string" }, "Version": { "type": "string" } }, "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AccessLoggingPolicy": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.AccessLoggingPolicy" }, "AppCookieStickinessPolicy": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.AppCookieStickinessPolicy" }, "type": "array" }, "AvailabilityZones": { "items": { "type": "string" }, "type": "array" }, "ConnectionDrainingPolicy": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.ConnectionDrainingPolicy" }, "ConnectionSettings": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.ConnectionSettings" }, "CrossZone": { "type": "boolean" }, "HealthCheck": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.HealthCheck" }, "Instances": { "items": { "type": "string" }, "type": "array" }, "LBCookieStickinessPolicy": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.LBCookieStickinessPolicy" }, "type": "array" }, "Listeners": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.Listeners" }, "type": "array" }, "LoadBalancerName": { "type": "string" }, "Policies": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer.Policies" }, "type": "array" }, "Scheme": { "type": "string" }, "SecurityGroups": { "items": { "type": "string" }, "type": "array" }, "Subnets": { "items": { "type": "string" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "Listeners" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticLoadBalancing::LoadBalancer" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.AccessLoggingPolicy": { "additionalProperties": false, "properties": { "EmitInterval": { "type": "number" }, "Enabled": { "type": "boolean" }, "S3BucketName": { "type": "string" }, "S3BucketPrefix": { "type": "string" } }, "required": [ "Enabled", "S3BucketName" ], "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.AppCookieStickinessPolicy": { "additionalProperties": false, "properties": { "CookieName": { "type": "string" }, "PolicyName": { "type": "string" } }, "required": [ "CookieName", "PolicyName" ], "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.ConnectionDrainingPolicy": { "additionalProperties": false, "properties": { "Enabled": { "type": "boolean" }, "Timeout": { "type": "number" } }, "required": [ "Enabled" ], "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.ConnectionSettings": { "additionalProperties": false, "properties": { "IdleTimeout": { "type": "number" } }, "required": [ "IdleTimeout" ], "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.HealthCheck": { "additionalProperties": false, "properties": { "HealthyThreshold": { "type": "string" }, "Interval": { "type": "string" }, "Target": { "type": "string" }, "Timeout": { "type": "string" }, "UnhealthyThreshold": { "type": "string" } }, "required": [ "HealthyThreshold", "Interval", "Target", "Timeout", "UnhealthyThreshold" ], "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.LBCookieStickinessPolicy": { "additionalProperties": false, "properties": { "CookieExpirationPeriod": { "type": "string" }, "PolicyName": { "type": "string" } }, "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.Listeners": { "additionalProperties": false, "properties": { "InstancePort": { "type": "string" }, "InstanceProtocol": { "type": "string" }, "LoadBalancerPort": { "type": "string" }, "PolicyNames": { "items": { "type": "string" }, "type": "array" }, "Protocol": { "type": "string" }, "SSLCertificateId": { "type": "string" } }, "required": [ "InstancePort", "LoadBalancerPort", "Protocol" ], "type": "object" }, "AWS::ElasticLoadBalancing::LoadBalancer.Policies": { "additionalProperties": false, "properties": { "Attributes": { "items": { "type": "object" }, "type": "array" }, "InstancePorts": { "items": { "type": "string" }, "type": "array" }, "LoadBalancerPorts": { "items": { "type": "string" }, "type": "array" }, "PolicyName": { "type": "string" }, "PolicyType": { "type": "string" } }, "required": [ "Attributes", "PolicyName", "PolicyType" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::Listener": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Certificates": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::Listener.Certificate" }, "type": "array" }, "DefaultActions": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::Listener.Action" }, "type": "array" }, "LoadBalancerArn": { "type": "string" }, "Port": { "type": "number" }, "Protocol": { "type": "string" }, "SslPolicy": { "type": "string" } }, "required": [ "DefaultActions", "LoadBalancerArn", "Port", "Protocol" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticLoadBalancingV2::Listener" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::Listener.Action": { "additionalProperties": false, "properties": { "TargetGroupArn": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "TargetGroupArn", "Type" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::Listener.Certificate": { "additionalProperties": false, "properties": { "CertificateArn": { "type": "string" } }, "type": "object" }, "AWS::ElasticLoadBalancingV2::ListenerCertificate": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Certificates": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::ListenerCertificate.Certificate" }, "type": "array" }, "ListenerArn": { "type": "string" } }, "required": [ "Certificates", "ListenerArn" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticLoadBalancingV2::ListenerCertificate" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::ListenerCertificate.Certificate": { "additionalProperties": false, "properties": { "CertificateArn": { "type": "string" } }, "type": "object" }, "AWS::ElasticLoadBalancingV2::ListenerRule": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Actions": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::ListenerRule.Action" }, "type": "array" }, "Conditions": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::ListenerRule.RuleCondition" }, "type": "array" }, "ListenerArn": { "type": "string" }, "Priority": { "type": "number" } }, "required": [ "Actions", "Conditions", "ListenerArn", "Priority" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticLoadBalancingV2::ListenerRule" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::ListenerRule.Action": { "additionalProperties": false, "properties": { "TargetGroupArn": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "TargetGroupArn", "Type" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::ListenerRule.RuleCondition": { "additionalProperties": false, "properties": { "Field": { "type": "string" }, "Values": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::ElasticLoadBalancingV2::LoadBalancer": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "IpAddressType": { "type": "string" }, "LoadBalancerAttributes": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::LoadBalancer.LoadBalancerAttribute" }, "type": "array" }, "Name": { "type": "string" }, "Scheme": { "type": "string" }, "SecurityGroups": { "items": { "type": "string" }, "type": "array" }, "SubnetMappings": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::LoadBalancer.SubnetMapping" }, "type": "array" }, "Subnets": { "items": { "type": "string" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Type": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::ElasticLoadBalancingV2::LoadBalancer" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::LoadBalancer.LoadBalancerAttribute": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::ElasticLoadBalancingV2::LoadBalancer.SubnetMapping": { "additionalProperties": false, "properties": { "AllocationId": { "type": "string" }, "SubnetId": { "type": "string" } }, "required": [ "AllocationId", "SubnetId" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::TargetGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "HealthCheckIntervalSeconds": { "type": "number" }, "HealthCheckPath": { "type": "string" }, "HealthCheckPort": { "type": "string" }, "HealthCheckProtocol": { "type": "string" }, "HealthCheckTimeoutSeconds": { "type": "number" }, "HealthyThresholdCount": { "type": "number" }, "Matcher": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::TargetGroup.Matcher" }, "Name": { "type": "string" }, "Port": { "type": "number" }, "Protocol": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "TargetGroupAttributes": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::TargetGroup.TargetGroupAttribute" }, "type": "array" }, "TargetType": { "type": "string" }, "Targets": { "items": { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::TargetGroup.TargetDescription" }, "type": "array" }, "UnhealthyThresholdCount": { "type": "number" }, "VpcId": { "type": "string" } }, "required": [ "Port", "Protocol", "VpcId" ], "type": "object" }, "Type": { "enum": [ "AWS::ElasticLoadBalancingV2::TargetGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::TargetGroup.Matcher": { "additionalProperties": false, "properties": { "HttpCode": { "type": "string" } }, "required": [ "HttpCode" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::TargetGroup.TargetDescription": { "additionalProperties": false, "properties": { "AvailabilityZone": { "type": "string" }, "Id": { "type": "string" }, "Port": { "type": "number" } }, "required": [ "Id" ], "type": "object" }, "AWS::ElasticLoadBalancingV2::TargetGroup.TargetGroupAttribute": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::Elasticsearch::Domain": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AccessPolicies": { "type": "object" }, "AdvancedOptions": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "DomainName": { "type": "string" }, "EBSOptions": { "$ref": "#/definitions/AWS::Elasticsearch::Domain.EBSOptions" }, "ElasticsearchClusterConfig": { "$ref": "#/definitions/AWS::Elasticsearch::Domain.ElasticsearchClusterConfig" }, "ElasticsearchVersion": { "type": "string" }, "SnapshotOptions": { "$ref": "#/definitions/AWS::Elasticsearch::Domain.SnapshotOptions" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VPCOptions": { "$ref": "#/definitions/AWS::Elasticsearch::Domain.VPCOptions" } }, "type": "object" }, "Type": { "enum": [ "AWS::Elasticsearch::Domain" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Elasticsearch::Domain.EBSOptions": { "additionalProperties": false, "properties": { "EBSEnabled": { "type": "boolean" }, "Iops": { "type": "number" }, "VolumeSize": { "type": "number" }, "VolumeType": { "type": "string" } }, "type": "object" }, "AWS::Elasticsearch::Domain.ElasticsearchClusterConfig": { "additionalProperties": false, "properties": { "DedicatedMasterCount": { "type": "number" }, "DedicatedMasterEnabled": { "type": "boolean" }, "DedicatedMasterType": { "type": "string" }, "InstanceCount": { "type": "number" }, "InstanceType": { "type": "string" }, "ZoneAwarenessEnabled": { "type": "boolean" } }, "type": "object" }, "AWS::Elasticsearch::Domain.SnapshotOptions": { "additionalProperties": false, "properties": { "AutomatedSnapshotStartHour": { "type": "number" } }, "type": "object" }, "AWS::Elasticsearch::Domain.VPCOptions": { "additionalProperties": false, "properties": { "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::Events::Rule": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "EventPattern": { "type": "object" }, "Name": { "type": "string" }, "RoleArn": { "type": "string" }, "ScheduleExpression": { "type": "string" }, "State": { "type": "string" }, "Targets": { "items": { "$ref": "#/definitions/AWS::Events::Rule.Target" }, "type": "array" } }, "type": "object" }, "Type": { "enum": [ "AWS::Events::Rule" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Events::Rule.EcsParameters": { "additionalProperties": false, "properties": { "TaskCount": { "type": "number" }, "TaskDefinitionArn": { "type": "string" } }, "required": [ "TaskDefinitionArn" ], "type": "object" }, "AWS::Events::Rule.InputTransformer": { "additionalProperties": false, "properties": { "InputPathsMap": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "InputTemplate": { "type": "string" } }, "required": [ "InputTemplate" ], "type": "object" }, "AWS::Events::Rule.KinesisParameters": { "additionalProperties": false, "properties": { "PartitionKeyPath": { "type": "string" } }, "required": [ "PartitionKeyPath" ], "type": "object" }, "AWS::Events::Rule.RunCommandParameters": { "additionalProperties": false, "properties": { "RunCommandTargets": { "items": { "$ref": "#/definitions/AWS::Events::Rule.RunCommandTarget" }, "type": "array" } }, "required": [ "RunCommandTargets" ], "type": "object" }, "AWS::Events::Rule.RunCommandTarget": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Values": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Key", "Values" ], "type": "object" }, "AWS::Events::Rule.Target": { "additionalProperties": false, "properties": { "Arn": { "type": "string" }, "EcsParameters": { "$ref": "#/definitions/AWS::Events::Rule.EcsParameters" }, "Id": { "type": "string" }, "Input": { "type": "string" }, "InputPath": { "type": "string" }, "InputTransformer": { "$ref": "#/definitions/AWS::Events::Rule.InputTransformer" }, "KinesisParameters": { "$ref": "#/definitions/AWS::Events::Rule.KinesisParameters" }, "RoleArn": { "type": "string" }, "RunCommandParameters": { "$ref": "#/definitions/AWS::Events::Rule.RunCommandParameters" } }, "required": [ "Arn", "Id" ], "type": "object" }, "AWS::GameLift::Alias": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Name": { "type": "string" }, "RoutingStrategy": { "$ref": "#/definitions/AWS::GameLift::Alias.RoutingStrategy" } }, "required": [ "Name", "RoutingStrategy" ], "type": "object" }, "Type": { "enum": [ "AWS::GameLift::Alias" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::GameLift::Alias.RoutingStrategy": { "additionalProperties": false, "properties": { "FleetId": { "type": "string" }, "Message": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::GameLift::Build": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "StorageLocation": { "$ref": "#/definitions/AWS::GameLift::Build.S3Location" }, "Version": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::GameLift::Build" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::GameLift::Build.S3Location": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "Key": { "type": "string" }, "RoleArn": { "type": "string" } }, "required": [ "Bucket", "Key", "RoleArn" ], "type": "object" }, "AWS::GameLift::Fleet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "BuildId": { "type": "string" }, "Description": { "type": "string" }, "DesiredEC2Instances": { "type": "number" }, "EC2InboundPermissions": { "items": { "$ref": "#/definitions/AWS::GameLift::Fleet.IpPermission" }, "type": "array" }, "EC2InstanceType": { "type": "string" }, "LogPaths": { "items": { "type": "string" }, "type": "array" }, "MaxSize": { "type": "number" }, "MinSize": { "type": "number" }, "Name": { "type": "string" }, "ServerLaunchParameters": { "type": "string" }, "ServerLaunchPath": { "type": "string" } }, "required": [ "BuildId", "DesiredEC2Instances", "EC2InstanceType", "Name", "ServerLaunchPath" ], "type": "object" }, "Type": { "enum": [ "AWS::GameLift::Fleet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::GameLift::Fleet.IpPermission": { "additionalProperties": false, "properties": { "FromPort": { "type": "number" }, "IpRange": { "type": "string" }, "Protocol": { "type": "string" }, "ToPort": { "type": "number" } }, "required": [ "FromPort", "IpRange", "Protocol", "ToPort" ], "type": "object" }, "AWS::Glue::Classifier": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "GrokClassifier": { "$ref": "#/definitions/AWS::Glue::Classifier.GrokClassifier" } }, "type": "object" }, "Type": { "enum": [ "AWS::Glue::Classifier" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Glue::Classifier.GrokClassifier": { "additionalProperties": false, "properties": { "Classification": { "type": "string" }, "CustomPatterns": { "type": "string" }, "GrokPattern": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "Classification", "GrokPattern" ], "type": "object" }, "AWS::Glue::Connection": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CatalogId": { "type": "string" }, "ConnectionInput": { "$ref": "#/definitions/AWS::Glue::Connection.ConnectionInput" } }, "required": [ "CatalogId", "ConnectionInput" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::Connection" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Connection.ConnectionInput": { "additionalProperties": false, "properties": { "ConnectionProperties": { "type": "object" }, "ConnectionType": { "type": "string" }, "Description": { "type": "string" }, "MatchCriteria": { "items": { "type": "string" }, "type": "array" }, "Name": { "type": "string" }, "PhysicalConnectionRequirements": { "$ref": "#/definitions/AWS::Glue::Connection.PhysicalConnectionRequirements" } }, "required": [ "ConnectionProperties", "ConnectionType" ], "type": "object" }, "AWS::Glue::Connection.PhysicalConnectionRequirements": { "additionalProperties": false, "properties": { "AvailabilityZone": { "type": "string" }, "SecurityGroupIdList": { "items": { "type": "string" }, "type": "array" }, "SubnetId": { "type": "string" } }, "type": "object" }, "AWS::Glue::Crawler": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Classifiers": { "items": { "type": "string" }, "type": "array" }, "DatabaseName": { "type": "string" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "Role": { "type": "string" }, "Schedule": { "$ref": "#/definitions/AWS::Glue::Crawler.Schedule" }, "SchemaChangePolicy": { "$ref": "#/definitions/AWS::Glue::Crawler.SchemaChangePolicy" }, "TablePrefix": { "type": "string" }, "Targets": { "$ref": "#/definitions/AWS::Glue::Crawler.Targets" } }, "required": [ "DatabaseName", "Role", "Targets" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::Crawler" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Crawler.JdbcTarget": { "additionalProperties": false, "properties": { "ConnectionName": { "type": "string" }, "Exclusions": { "items": { "type": "string" }, "type": "array" }, "Path": { "type": "string" } }, "type": "object" }, "AWS::Glue::Crawler.S3Target": { "additionalProperties": false, "properties": { "Exclusions": { "items": { "type": "string" }, "type": "array" }, "Path": { "type": "string" } }, "type": "object" }, "AWS::Glue::Crawler.Schedule": { "additionalProperties": false, "properties": { "ScheduleExpression": { "type": "string" } }, "type": "object" }, "AWS::Glue::Crawler.SchemaChangePolicy": { "additionalProperties": false, "properties": { "DeleteBehavior": { "type": "string" }, "UpdateBehavior": { "type": "string" } }, "type": "object" }, "AWS::Glue::Crawler.Targets": { "additionalProperties": false, "properties": { "JdbcTargets": { "items": { "$ref": "#/definitions/AWS::Glue::Crawler.JdbcTarget" }, "type": "array" }, "S3Targets": { "items": { "$ref": "#/definitions/AWS::Glue::Crawler.S3Target" }, "type": "array" } }, "type": "object" }, "AWS::Glue::Database": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CatalogId": { "type": "string" }, "DatabaseInput": { "$ref": "#/definitions/AWS::Glue::Database.DatabaseInput" } }, "required": [ "CatalogId", "DatabaseInput" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::Database" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Database.DatabaseInput": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "LocationUri": { "type": "string" }, "Name": { "type": "string" }, "Parameters": { "type": "object" } }, "type": "object" }, "AWS::Glue::DevEndpoint": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "EndpointName": { "type": "string" }, "ExtraJarsS3Path": { "type": "string" }, "ExtraPythonLibsS3Path": { "type": "string" }, "NumberOfNodes": { "type": "number" }, "PublicKey": { "type": "string" }, "RoleArn": { "type": "string" }, "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SubnetId": { "type": "string" } }, "required": [ "PublicKey", "RoleArn" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::DevEndpoint" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Job": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllocatedCapacity": { "type": "number" }, "Command": { "$ref": "#/definitions/AWS::Glue::Job.JobCommand" }, "Connections": { "$ref": "#/definitions/AWS::Glue::Job.ConnectionsList" }, "DefaultArguments": { "type": "object" }, "Description": { "type": "string" }, "ExecutionProperty": { "$ref": "#/definitions/AWS::Glue::Job.ExecutionProperty" }, "LogUri": { "type": "string" }, "MaxRetries": { "type": "number" }, "Name": { "type": "string" }, "Role": { "type": "string" } }, "required": [ "Command", "Role" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::Job" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Job.ConnectionsList": { "additionalProperties": false, "properties": { "Connections": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::Glue::Job.ExecutionProperty": { "additionalProperties": false, "properties": { "MaxConcurrentRuns": { "type": "number" } }, "type": "object" }, "AWS::Glue::Job.JobCommand": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "ScriptLocation": { "type": "string" } }, "type": "object" }, "AWS::Glue::Partition": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CatalogId": { "type": "string" }, "DatabaseName": { "type": "string" }, "PartitionInput": { "$ref": "#/definitions/AWS::Glue::Partition.PartitionInput" }, "TableName": { "type": "string" } }, "required": [ "CatalogId", "DatabaseName", "PartitionInput", "TableName" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::Partition" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Partition.Column": { "additionalProperties": false, "properties": { "Comment": { "type": "string" }, "Name": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "AWS::Glue::Partition.Order": { "additionalProperties": false, "properties": { "Column": { "type": "string" }, "SortOrder": { "type": "number" } }, "required": [ "Column" ], "type": "object" }, "AWS::Glue::Partition.PartitionInput": { "additionalProperties": false, "properties": { "Parameters": { "type": "object" }, "StorageDescriptor": { "$ref": "#/definitions/AWS::Glue::Partition.StorageDescriptor" }, "Values": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Values" ], "type": "object" }, "AWS::Glue::Partition.SerdeInfo": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Parameters": { "type": "object" }, "SerializationLibrary": { "type": "string" } }, "type": "object" }, "AWS::Glue::Partition.SkewedInfo": { "additionalProperties": false, "properties": { "SkewedColumnNames": { "items": { "type": "string" }, "type": "array" }, "SkewedColumnValueLocationMaps": { "type": "object" }, "SkewedColumnValues": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::Glue::Partition.StorageDescriptor": { "additionalProperties": false, "properties": { "BucketColumns": { "items": { "type": "string" }, "type": "array" }, "Columns": { "items": { "$ref": "#/definitions/AWS::Glue::Partition.Column" }, "type": "array" }, "Compressed": { "type": "boolean" }, "InputFormat": { "type": "string" }, "Location": { "type": "string" }, "NumberOfBuckets": { "type": "number" }, "OutputFormat": { "type": "string" }, "Parameters": { "type": "object" }, "SerdeInfo": { "$ref": "#/definitions/AWS::Glue::Partition.SerdeInfo" }, "SkewedInfo": { "$ref": "#/definitions/AWS::Glue::Partition.SkewedInfo" }, "SortColumns": { "items": { "$ref": "#/definitions/AWS::Glue::Partition.Order" }, "type": "array" }, "StoredAsSubDirectories": { "type": "boolean" } }, "type": "object" }, "AWS::Glue::Table": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CatalogId": { "type": "string" }, "DatabaseName": { "type": "string" }, "TableInput": { "$ref": "#/definitions/AWS::Glue::Table.TableInput" } }, "required": [ "CatalogId", "DatabaseName", "TableInput" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::Table" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Table.Column": { "additionalProperties": false, "properties": { "Comment": { "type": "string" }, "Name": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "AWS::Glue::Table.Order": { "additionalProperties": false, "properties": { "Column": { "type": "string" }, "SortOrder": { "type": "number" } }, "required": [ "Column", "SortOrder" ], "type": "object" }, "AWS::Glue::Table.SerdeInfo": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Parameters": { "type": "object" }, "SerializationLibrary": { "type": "string" } }, "type": "object" }, "AWS::Glue::Table.SkewedInfo": { "additionalProperties": false, "properties": { "SkewedColumnNames": { "items": { "type": "string" }, "type": "array" }, "SkewedColumnValueLocationMaps": { "type": "object" }, "SkewedColumnValues": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::Glue::Table.StorageDescriptor": { "additionalProperties": false, "properties": { "BucketColumns": { "items": { "type": "string" }, "type": "array" }, "Columns": { "items": { "$ref": "#/definitions/AWS::Glue::Table.Column" }, "type": "array" }, "Compressed": { "type": "boolean" }, "InputFormat": { "type": "string" }, "Location": { "type": "string" }, "NumberOfBuckets": { "type": "number" }, "OutputFormat": { "type": "string" }, "Parameters": { "type": "object" }, "SerdeInfo": { "$ref": "#/definitions/AWS::Glue::Table.SerdeInfo" }, "SkewedInfo": { "$ref": "#/definitions/AWS::Glue::Table.SkewedInfo" }, "SortColumns": { "items": { "$ref": "#/definitions/AWS::Glue::Table.Order" }, "type": "array" }, "StoredAsSubDirectories": { "type": "boolean" } }, "type": "object" }, "AWS::Glue::Table.TableInput": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Name": { "type": "string" }, "Owner": { "type": "string" }, "Parameters": { "type": "object" }, "PartitionKeys": { "items": { "$ref": "#/definitions/AWS::Glue::Table.Column" }, "type": "array" }, "Retention": { "type": "number" }, "StorageDescriptor": { "$ref": "#/definitions/AWS::Glue::Table.StorageDescriptor" }, "TableType": { "type": "string" }, "ViewExpandedText": { "type": "string" }, "ViewOriginalText": { "type": "string" } }, "type": "object" }, "AWS::Glue::Trigger": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Actions": { "items": { "$ref": "#/definitions/AWS::Glue::Trigger.Action" }, "type": "array" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "Predicate": { "$ref": "#/definitions/AWS::Glue::Trigger.Predicate" }, "Schedule": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Actions", "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::Glue::Trigger" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Glue::Trigger.Action": { "additionalProperties": false, "properties": { "Arguments": { "type": "object" }, "JobName": { "type": "string" } }, "type": "object" }, "AWS::Glue::Trigger.Condition": { "additionalProperties": false, "properties": { "JobName": { "type": "string" }, "LogicalOperator": { "type": "string" }, "State": { "type": "string" } }, "type": "object" }, "AWS::Glue::Trigger.Predicate": { "additionalProperties": false, "properties": { "Conditions": { "items": { "$ref": "#/definitions/AWS::Glue::Trigger.Condition" }, "type": "array" }, "Logical": { "type": "string" } }, "type": "object" }, "AWS::GuardDuty::Detector": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Enable": { "type": "boolean" } }, "required": [ "Enable" ], "type": "object" }, "Type": { "enum": [ "AWS::GuardDuty::Detector" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::GuardDuty::IPSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Activate": { "type": "boolean" }, "DetectorId": { "type": "string" }, "Format": { "type": "string" }, "Location": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "Activate", "DetectorId", "Format", "Location" ], "type": "object" }, "Type": { "enum": [ "AWS::GuardDuty::IPSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::GuardDuty::Master": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DetectorId": { "type": "string" }, "InvitationId": { "type": "string" }, "MasterId": { "type": "string" } }, "required": [ "DetectorId", "InvitationId", "MasterId" ], "type": "object" }, "Type": { "enum": [ "AWS::GuardDuty::Master" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::GuardDuty::Member": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DetectorId": { "type": "string" }, "Email": { "type": "string" }, "MemberId": { "type": "string" }, "Message": { "type": "string" }, "Status": { "type": "string" } }, "required": [ "DetectorId", "Email", "MemberId" ], "type": "object" }, "Type": { "enum": [ "AWS::GuardDuty::Member" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::GuardDuty::ThreatIntelSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Activate": { "type": "boolean" }, "DetectorId": { "type": "string" }, "Format": { "type": "string" }, "Location": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "Activate", "DetectorId", "Format", "Location" ], "type": "object" }, "Type": { "enum": [ "AWS::GuardDuty::ThreatIntelSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IAM::AccessKey": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Serial": { "type": "number" }, "Status": { "type": "string" }, "UserName": { "type": "string" } }, "required": [ "UserName" ], "type": "object" }, "Type": { "enum": [ "AWS::IAM::AccessKey" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IAM::Group": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "GroupName": { "type": "string" }, "ManagedPolicyArns": { "items": { "type": "string" }, "type": "array" }, "Path": { "type": "string" }, "Policies": { "items": { "$ref": "#/definitions/AWS::IAM::Group.Policy" }, "type": "array" } }, "type": "object" }, "Type": { "enum": [ "AWS::IAM::Group" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::IAM::Group.Policy": { "additionalProperties": false, "properties": { "PolicyDocument": { "type": "object" }, "PolicyName": { "type": "string" } }, "required": [ "PolicyDocument", "PolicyName" ], "type": "object" }, "AWS::IAM::InstanceProfile": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "InstanceProfileName": { "type": "string" }, "Path": { "type": "string" }, "Roles": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Roles" ], "type": "object" }, "Type": { "enum": [ "AWS::IAM::InstanceProfile" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IAM::ManagedPolicy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Groups": { "items": { "type": "string" }, "type": "array" }, "ManagedPolicyName": { "type": "string" }, "Path": { "type": "string" }, "PolicyDocument": { "type": "object" }, "Roles": { "items": { "type": "string" }, "type": "array" }, "Users": { "items": { "type": "string" }, "type": "array" } }, "required": [ "PolicyDocument" ], "type": "object" }, "Type": { "enum": [ "AWS::IAM::ManagedPolicy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IAM::Policy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Groups": { "items": { "type": "string" }, "type": "array" }, "PolicyDocument": { "type": "object" }, "PolicyName": { "type": "string" }, "Roles": { "items": { "type": "string" }, "type": "array" }, "Users": { "items": { "type": "string" }, "type": "array" } }, "required": [ "PolicyDocument", "PolicyName" ], "type": "object" }, "Type": { "enum": [ "AWS::IAM::Policy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IAM::Role": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AssumeRolePolicyDocument": { "type": "object" }, "ManagedPolicyArns": { "items": { "type": "string" }, "type": "array" }, "Path": { "type": "string" }, "Policies": { "items": { "$ref": "#/definitions/AWS::IAM::Role.Policy" }, "type": "array" }, "RoleName": { "type": "string" } }, "required": [ "AssumeRolePolicyDocument" ], "type": "object" }, "Type": { "enum": [ "AWS::IAM::Role" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IAM::Role.Policy": { "additionalProperties": false, "properties": { "PolicyDocument": { "type": "object" }, "PolicyName": { "type": "string" } }, "required": [ "PolicyDocument", "PolicyName" ], "type": "object" }, "AWS::IAM::User": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Groups": { "items": { "type": "string" }, "type": "array" }, "LoginProfile": { "$ref": "#/definitions/AWS::IAM::User.LoginProfile" }, "ManagedPolicyArns": { "items": { "type": "string" }, "type": "array" }, "Path": { "type": "string" }, "Policies": { "items": { "$ref": "#/definitions/AWS::IAM::User.Policy" }, "type": "array" }, "UserName": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::IAM::User" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::IAM::User.LoginProfile": { "additionalProperties": false, "properties": { "Password": { "type": "string" }, "PasswordResetRequired": { "type": "boolean" } }, "required": [ "Password" ], "type": "object" }, "AWS::IAM::User.Policy": { "additionalProperties": false, "properties": { "PolicyDocument": { "type": "object" }, "PolicyName": { "type": "string" } }, "required": [ "PolicyDocument", "PolicyName" ], "type": "object" }, "AWS::IAM::UserToGroupAddition": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "GroupName": { "type": "string" }, "Users": { "items": { "type": "string" }, "type": "array" } }, "required": [ "GroupName", "Users" ], "type": "object" }, "Type": { "enum": [ "AWS::IAM::UserToGroupAddition" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Inspector::AssessmentTarget": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AssessmentTargetName": { "type": "string" }, "ResourceGroupArn": { "type": "string" } }, "required": [ "ResourceGroupArn" ], "type": "object" }, "Type": { "enum": [ "AWS::Inspector::AssessmentTarget" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Inspector::AssessmentTemplate": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AssessmentTargetArn": { "type": "string" }, "AssessmentTemplateName": { "type": "string" }, "DurationInSeconds": { "type": "number" }, "RulesPackageArns": { "items": { "type": "string" }, "type": "array" }, "UserAttributesForFindings": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "AssessmentTargetArn", "DurationInSeconds", "RulesPackageArns" ], "type": "object" }, "Type": { "enum": [ "AWS::Inspector::AssessmentTemplate" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Inspector::ResourceGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ResourceGroupTags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "ResourceGroupTags" ], "type": "object" }, "Type": { "enum": [ "AWS::Inspector::ResourceGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IoT::Certificate": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CertificateSigningRequest": { "type": "string" }, "Status": { "type": "string" } }, "required": [ "CertificateSigningRequest", "Status" ], "type": "object" }, "Type": { "enum": [ "AWS::IoT::Certificate" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IoT::Policy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PolicyDocument": { "type": "object" }, "PolicyName": { "type": "string" } }, "required": [ "PolicyDocument" ], "type": "object" }, "Type": { "enum": [ "AWS::IoT::Policy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IoT::PolicyPrincipalAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PolicyName": { "type": "string" }, "Principal": { "type": "string" } }, "required": [ "PolicyName", "Principal" ], "type": "object" }, "Type": { "enum": [ "AWS::IoT::PolicyPrincipalAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IoT::Thing": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AttributePayload": { "$ref": "#/definitions/AWS::IoT::Thing.AttributePayload" }, "ThingName": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::IoT::Thing" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::IoT::Thing.AttributePayload": { "additionalProperties": false, "properties": { "Attributes": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "type": "object" }, "AWS::IoT::ThingPrincipalAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Principal": { "type": "string" }, "ThingName": { "type": "string" } }, "required": [ "Principal", "ThingName" ], "type": "object" }, "Type": { "enum": [ "AWS::IoT::ThingPrincipalAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IoT::TopicRule": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "RuleName": { "type": "string" }, "TopicRulePayload": { "$ref": "#/definitions/AWS::IoT::TopicRule.TopicRulePayload" } }, "required": [ "TopicRulePayload" ], "type": "object" }, "Type": { "enum": [ "AWS::IoT::TopicRule" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::IoT::TopicRule.Action": { "additionalProperties": false, "properties": { "CloudwatchAlarm": { "$ref": "#/definitions/AWS::IoT::TopicRule.CloudwatchAlarmAction" }, "CloudwatchMetric": { "$ref": "#/definitions/AWS::IoT::TopicRule.CloudwatchMetricAction" }, "DynamoDB": { "$ref": "#/definitions/AWS::IoT::TopicRule.DynamoDBAction" }, "DynamoDBv2": { "$ref": "#/definitions/AWS::IoT::TopicRule.DynamoDBv2Action" }, "Elasticsearch": { "$ref": "#/definitions/AWS::IoT::TopicRule.ElasticsearchAction" }, "Firehose": { "$ref": "#/definitions/AWS::IoT::TopicRule.FirehoseAction" }, "Kinesis": { "$ref": "#/definitions/AWS::IoT::TopicRule.KinesisAction" }, "Lambda": { "$ref": "#/definitions/AWS::IoT::TopicRule.LambdaAction" }, "Republish": { "$ref": "#/definitions/AWS::IoT::TopicRule.RepublishAction" }, "S3": { "$ref": "#/definitions/AWS::IoT::TopicRule.S3Action" }, "Sns": { "$ref": "#/definitions/AWS::IoT::TopicRule.SnsAction" }, "Sqs": { "$ref": "#/definitions/AWS::IoT::TopicRule.SqsAction" } }, "type": "object" }, "AWS::IoT::TopicRule.CloudwatchAlarmAction": { "additionalProperties": false, "properties": { "AlarmName": { "type": "string" }, "RoleArn": { "type": "string" }, "StateReason": { "type": "string" }, "StateValue": { "type": "string" } }, "required": [ "AlarmName", "RoleArn", "StateReason", "StateValue" ], "type": "object" }, "AWS::IoT::TopicRule.CloudwatchMetricAction": { "additionalProperties": false, "properties": { "MetricName": { "type": "string" }, "MetricNamespace": { "type": "string" }, "MetricTimestamp": { "type": "string" }, "MetricUnit": { "type": "string" }, "MetricValue": { "type": "string" }, "RoleArn": { "type": "string" } }, "required": [ "MetricName", "MetricNamespace", "MetricUnit", "MetricValue", "RoleArn" ], "type": "object" }, "AWS::IoT::TopicRule.DynamoDBAction": { "additionalProperties": false, "properties": { "HashKeyField": { "type": "string" }, "HashKeyType": { "type": "string" }, "HashKeyValue": { "type": "string" }, "PayloadField": { "type": "string" }, "RangeKeyField": { "type": "string" }, "RangeKeyType": { "type": "string" }, "RangeKeyValue": { "type": "string" }, "RoleArn": { "type": "string" }, "TableName": { "type": "string" } }, "required": [ "HashKeyField", "HashKeyValue", "RoleArn", "TableName" ], "type": "object" }, "AWS::IoT::TopicRule.DynamoDBv2Action": { "additionalProperties": false, "properties": { "PutItem": { "$ref": "#/definitions/AWS::IoT::TopicRule.PutItemInput" }, "RoleArn": { "type": "string" } }, "type": "object" }, "AWS::IoT::TopicRule.ElasticsearchAction": { "additionalProperties": false, "properties": { "Endpoint": { "type": "string" }, "Id": { "type": "string" }, "Index": { "type": "string" }, "RoleArn": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Endpoint", "Id", "Index", "RoleArn", "Type" ], "type": "object" }, "AWS::IoT::TopicRule.FirehoseAction": { "additionalProperties": false, "properties": { "DeliveryStreamName": { "type": "string" }, "RoleArn": { "type": "string" }, "Separator": { "type": "string" } }, "required": [ "DeliveryStreamName", "RoleArn" ], "type": "object" }, "AWS::IoT::TopicRule.KinesisAction": { "additionalProperties": false, "properties": { "PartitionKey": { "type": "string" }, "RoleArn": { "type": "string" }, "StreamName": { "type": "string" } }, "required": [ "RoleArn", "StreamName" ], "type": "object" }, "AWS::IoT::TopicRule.LambdaAction": { "additionalProperties": false, "properties": { "FunctionArn": { "type": "string" } }, "type": "object" }, "AWS::IoT::TopicRule.PutItemInput": { "additionalProperties": false, "properties": { "TableName": { "type": "string" } }, "required": [ "TableName" ], "type": "object" }, "AWS::IoT::TopicRule.RepublishAction": { "additionalProperties": false, "properties": { "RoleArn": { "type": "string" }, "Topic": { "type": "string" } }, "required": [ "RoleArn", "Topic" ], "type": "object" }, "AWS::IoT::TopicRule.S3Action": { "additionalProperties": false, "properties": { "BucketName": { "type": "string" }, "Key": { "type": "string" }, "RoleArn": { "type": "string" } }, "required": [ "BucketName", "Key", "RoleArn" ], "type": "object" }, "AWS::IoT::TopicRule.SnsAction": { "additionalProperties": false, "properties": { "MessageFormat": { "type": "string" }, "RoleArn": { "type": "string" }, "TargetArn": { "type": "string" } }, "required": [ "RoleArn", "TargetArn" ], "type": "object" }, "AWS::IoT::TopicRule.SqsAction": { "additionalProperties": false, "properties": { "QueueUrl": { "type": "string" }, "RoleArn": { "type": "string" }, "UseBase64": { "type": "boolean" } }, "required": [ "QueueUrl", "RoleArn" ], "type": "object" }, "AWS::IoT::TopicRule.TopicRulePayload": { "additionalProperties": false, "properties": { "Actions": { "items": { "$ref": "#/definitions/AWS::IoT::TopicRule.Action" }, "type": "array" }, "AwsIotSqlVersion": { "type": "string" }, "Description": { "type": "string" }, "RuleDisabled": { "type": "boolean" }, "Sql": { "type": "string" } }, "required": [ "Actions", "RuleDisabled", "Sql" ], "type": "object" }, "AWS::KMS::Alias": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AliasName": { "type": "string" }, "TargetKeyId": { "type": "string" } }, "required": [ "AliasName", "TargetKeyId" ], "type": "object" }, "Type": { "enum": [ "AWS::KMS::Alias" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::KMS::Key": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "EnableKeyRotation": { "type": "boolean" }, "Enabled": { "type": "boolean" }, "KeyPolicy": { "type": "object" }, "KeyUsage": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "KeyPolicy" ], "type": "object" }, "Type": { "enum": [ "AWS::KMS::Key" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Kinesis::Stream": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "RetentionPeriodHours": { "type": "number" }, "ShardCount": { "type": "number" }, "StreamEncryption": { "$ref": "#/definitions/AWS::Kinesis::Stream.StreamEncryption" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "ShardCount" ], "type": "object" }, "Type": { "enum": [ "AWS::Kinesis::Stream" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Kinesis::Stream.StreamEncryption": { "additionalProperties": false, "properties": { "EncryptionType": { "type": "string" }, "KeyId": { "type": "string" } }, "required": [ "EncryptionType", "KeyId" ], "type": "object" }, "AWS::KinesisAnalytics::Application": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationCode": { "type": "string" }, "ApplicationDescription": { "type": "string" }, "ApplicationName": { "type": "string" }, "Inputs": { "items": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.Input" }, "type": "array" } }, "required": [ "Inputs" ], "type": "object" }, "Type": { "enum": [ "AWS::KinesisAnalytics::Application" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::KinesisAnalytics::Application.CSVMappingParameters": { "additionalProperties": false, "properties": { "RecordColumnDelimiter": { "type": "string" }, "RecordRowDelimiter": { "type": "string" } }, "required": [ "RecordColumnDelimiter", "RecordRowDelimiter" ], "type": "object" }, "AWS::KinesisAnalytics::Application.Input": { "additionalProperties": false, "properties": { "InputParallelism": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.InputParallelism" }, "InputProcessingConfiguration": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.InputProcessingConfiguration" }, "InputSchema": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.InputSchema" }, "KinesisFirehoseInput": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.KinesisFirehoseInput" }, "KinesisStreamsInput": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.KinesisStreamsInput" }, "NamePrefix": { "type": "string" } }, "required": [ "InputSchema", "NamePrefix" ], "type": "object" }, "AWS::KinesisAnalytics::Application.InputLambdaProcessor": { "additionalProperties": false, "properties": { "ResourceARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "ResourceARN", "RoleARN" ], "type": "object" }, "AWS::KinesisAnalytics::Application.InputParallelism": { "additionalProperties": false, "properties": { "Count": { "type": "number" } }, "type": "object" }, "AWS::KinesisAnalytics::Application.InputProcessingConfiguration": { "additionalProperties": false, "properties": { "InputLambdaProcessor": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.InputLambdaProcessor" } }, "type": "object" }, "AWS::KinesisAnalytics::Application.InputSchema": { "additionalProperties": false, "properties": { "RecordColumns": { "items": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.RecordColumn" }, "type": "array" }, "RecordEncoding": { "type": "string" }, "RecordFormat": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.RecordFormat" } }, "required": [ "RecordColumns", "RecordFormat" ], "type": "object" }, "AWS::KinesisAnalytics::Application.JSONMappingParameters": { "additionalProperties": false, "properties": { "RecordRowPath": { "type": "string" } }, "required": [ "RecordRowPath" ], "type": "object" }, "AWS::KinesisAnalytics::Application.KinesisFirehoseInput": { "additionalProperties": false, "properties": { "ResourceARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "ResourceARN", "RoleARN" ], "type": "object" }, "AWS::KinesisAnalytics::Application.KinesisStreamsInput": { "additionalProperties": false, "properties": { "ResourceARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "ResourceARN", "RoleARN" ], "type": "object" }, "AWS::KinesisAnalytics::Application.MappingParameters": { "additionalProperties": false, "properties": { "CSVMappingParameters": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.CSVMappingParameters" }, "JSONMappingParameters": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.JSONMappingParameters" } }, "type": "object" }, "AWS::KinesisAnalytics::Application.RecordColumn": { "additionalProperties": false, "properties": { "Mapping": { "type": "string" }, "Name": { "type": "string" }, "SqlType": { "type": "string" } }, "required": [ "Name", "SqlType" ], "type": "object" }, "AWS::KinesisAnalytics::Application.RecordFormat": { "additionalProperties": false, "properties": { "MappingParameters": { "$ref": "#/definitions/AWS::KinesisAnalytics::Application.MappingParameters" }, "RecordFormatType": { "type": "string" } }, "required": [ "RecordFormatType" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationOutput": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "Output": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationOutput.Output" } }, "required": [ "ApplicationName", "Output" ], "type": "object" }, "Type": { "enum": [ "AWS::KinesisAnalytics::ApplicationOutput" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationOutput.DestinationSchema": { "additionalProperties": false, "properties": { "RecordFormatType": { "type": "string" } }, "type": "object" }, "AWS::KinesisAnalytics::ApplicationOutput.KinesisFirehoseOutput": { "additionalProperties": false, "properties": { "ResourceARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "ResourceARN", "RoleARN" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationOutput.KinesisStreamsOutput": { "additionalProperties": false, "properties": { "ResourceARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "ResourceARN", "RoleARN" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationOutput.LambdaOutput": { "additionalProperties": false, "properties": { "ResourceARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "ResourceARN", "RoleARN" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationOutput.Output": { "additionalProperties": false, "properties": { "DestinationSchema": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationOutput.DestinationSchema" }, "KinesisFirehoseOutput": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationOutput.KinesisFirehoseOutput" }, "KinesisStreamsOutput": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationOutput.KinesisStreamsOutput" }, "LambdaOutput": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationOutput.LambdaOutput" }, "Name": { "type": "string" } }, "required": [ "DestinationSchema" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApplicationName": { "type": "string" }, "ReferenceDataSource": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceDataSource" } }, "required": [ "ApplicationName", "ReferenceDataSource" ], "type": "object" }, "Type": { "enum": [ "AWS::KinesisAnalytics::ApplicationReferenceDataSource" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.CSVMappingParameters": { "additionalProperties": false, "properties": { "RecordColumnDelimiter": { "type": "string" }, "RecordRowDelimiter": { "type": "string" } }, "required": [ "RecordColumnDelimiter", "RecordRowDelimiter" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.JSONMappingParameters": { "additionalProperties": false, "properties": { "RecordRowPath": { "type": "string" } }, "required": [ "RecordRowPath" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.MappingParameters": { "additionalProperties": false, "properties": { "CSVMappingParameters": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.CSVMappingParameters" }, "JSONMappingParameters": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.JSONMappingParameters" } }, "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordColumn": { "additionalProperties": false, "properties": { "Mapping": { "type": "string" }, "Name": { "type": "string" }, "SqlType": { "type": "string" } }, "required": [ "Name", "SqlType" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordFormat": { "additionalProperties": false, "properties": { "MappingParameters": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.MappingParameters" }, "RecordFormatType": { "type": "string" } }, "required": [ "RecordFormatType" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceDataSource": { "additionalProperties": false, "properties": { "ReferenceSchema": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceSchema" }, "S3ReferenceDataSource": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.S3ReferenceDataSource" }, "TableName": { "type": "string" } }, "required": [ "ReferenceSchema" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceSchema": { "additionalProperties": false, "properties": { "RecordColumns": { "items": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordColumn" }, "type": "array" }, "RecordEncoding": { "type": "string" }, "RecordFormat": { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordFormat" } }, "required": [ "RecordColumns", "RecordFormat" ], "type": "object" }, "AWS::KinesisAnalytics::ApplicationReferenceDataSource.S3ReferenceDataSource": { "additionalProperties": false, "properties": { "BucketARN": { "type": "string" }, "FileKey": { "type": "string" }, "ReferenceRoleARN": { "type": "string" } }, "required": [ "BucketARN", "FileKey", "ReferenceRoleARN" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DeliveryStreamName": { "type": "string" }, "DeliveryStreamType": { "type": "string" }, "ElasticsearchDestinationConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ElasticsearchDestinationConfiguration" }, "ExtendedS3DestinationConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ExtendedS3DestinationConfiguration" }, "KinesisStreamSourceConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.KinesisStreamSourceConfiguration" }, "RedshiftDestinationConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.RedshiftDestinationConfiguration" }, "S3DestinationConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration" } }, "type": "object" }, "Type": { "enum": [ "AWS::KinesisFirehose::DeliveryStream" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.BufferingHints": { "additionalProperties": false, "properties": { "IntervalInSeconds": { "type": "number" }, "SizeInMBs": { "type": "number" } }, "required": [ "IntervalInSeconds", "SizeInMBs" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.CloudWatchLoggingOptions": { "additionalProperties": false, "properties": { "Enabled": { "type": "boolean" }, "LogGroupName": { "type": "string" }, "LogStreamName": { "type": "string" } }, "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.CopyCommand": { "additionalProperties": false, "properties": { "CopyOptions": { "type": "string" }, "DataTableColumns": { "type": "string" }, "DataTableName": { "type": "string" } }, "required": [ "DataTableName" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.ElasticsearchBufferingHints": { "additionalProperties": false, "properties": { "IntervalInSeconds": { "type": "number" }, "SizeInMBs": { "type": "number" } }, "required": [ "IntervalInSeconds", "SizeInMBs" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.ElasticsearchDestinationConfiguration": { "additionalProperties": false, "properties": { "BufferingHints": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ElasticsearchBufferingHints" }, "CloudWatchLoggingOptions": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.CloudWatchLoggingOptions" }, "DomainARN": { "type": "string" }, "IndexName": { "type": "string" }, "IndexRotationPeriod": { "type": "string" }, "ProcessingConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ProcessingConfiguration" }, "RetryOptions": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ElasticsearchRetryOptions" }, "RoleARN": { "type": "string" }, "S3BackupMode": { "type": "string" }, "S3Configuration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration" }, "TypeName": { "type": "string" } }, "required": [ "BufferingHints", "DomainARN", "IndexName", "IndexRotationPeriod", "RetryOptions", "RoleARN", "S3BackupMode", "S3Configuration", "TypeName" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.ElasticsearchRetryOptions": { "additionalProperties": false, "properties": { "DurationInSeconds": { "type": "number" } }, "required": [ "DurationInSeconds" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration": { "additionalProperties": false, "properties": { "KMSEncryptionConfig": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.KMSEncryptionConfig" }, "NoEncryptionConfig": { "type": "string" } }, "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.ExtendedS3DestinationConfiguration": { "additionalProperties": false, "properties": { "BucketARN": { "type": "string" }, "BufferingHints": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.BufferingHints" }, "CloudWatchLoggingOptions": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.CloudWatchLoggingOptions" }, "CompressionFormat": { "type": "string" }, "EncryptionConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration" }, "Prefix": { "type": "string" }, "ProcessingConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ProcessingConfiguration" }, "RoleARN": { "type": "string" }, "S3BackupConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration" }, "S3BackupMode": { "type": "string" } }, "required": [ "BucketARN", "BufferingHints", "CompressionFormat", "Prefix", "RoleARN" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.KMSEncryptionConfig": { "additionalProperties": false, "properties": { "AWSKMSKeyARN": { "type": "string" } }, "required": [ "AWSKMSKeyARN" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.KinesisStreamSourceConfiguration": { "additionalProperties": false, "properties": { "KinesisStreamARN": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "KinesisStreamARN", "RoleARN" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.ProcessingConfiguration": { "additionalProperties": false, "properties": { "Enabled": { "type": "boolean" }, "Processors": { "items": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.Processor" }, "type": "array" } }, "required": [ "Enabled", "Processors" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.Processor": { "additionalProperties": false, "properties": { "Parameters": { "items": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ProcessorParameter" }, "type": "array" }, "Type": { "type": "string" } }, "required": [ "Parameters", "Type" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.ProcessorParameter": { "additionalProperties": false, "properties": { "ParameterName": { "type": "string" }, "ParameterValue": { "type": "string" } }, "required": [ "ParameterName", "ParameterValue" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.RedshiftDestinationConfiguration": { "additionalProperties": false, "properties": { "CloudWatchLoggingOptions": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.CloudWatchLoggingOptions" }, "ClusterJDBCURL": { "type": "string" }, "CopyCommand": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.CopyCommand" }, "Password": { "type": "string" }, "ProcessingConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.ProcessingConfiguration" }, "RoleARN": { "type": "string" }, "S3Configuration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration" }, "Username": { "type": "string" } }, "required": [ "ClusterJDBCURL", "CopyCommand", "Password", "RoleARN", "S3Configuration", "Username" ], "type": "object" }, "AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration": { "additionalProperties": false, "properties": { "BucketARN": { "type": "string" }, "BufferingHints": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.BufferingHints" }, "CloudWatchLoggingOptions": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.CloudWatchLoggingOptions" }, "CompressionFormat": { "type": "string" }, "EncryptionConfiguration": { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration" }, "Prefix": { "type": "string" }, "RoleARN": { "type": "string" } }, "required": [ "BucketARN", "BufferingHints", "CompressionFormat", "RoleARN" ], "type": "object" }, "AWS::Lambda::Alias": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "FunctionName": { "type": "string" }, "FunctionVersion": { "type": "string" }, "Name": { "type": "string" }, "RoutingConfig": { "$ref": "#/definitions/AWS::Lambda::Alias.AliasRoutingConfiguration" } }, "required": [ "FunctionName", "FunctionVersion", "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::Lambda::Alias" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Lambda::Alias.AliasRoutingConfiguration": { "additionalProperties": false, "properties": { "AdditionalVersionWeights": { "items": { "$ref": "#/definitions/AWS::Lambda::Alias.VersionWeight" }, "type": "array" } }, "required": [ "AdditionalVersionWeights" ], "type": "object" }, "AWS::Lambda::Alias.VersionWeight": { "additionalProperties": false, "properties": { "FunctionVersion": { "type": "string" }, "FunctionWeight": { "type": "number" } }, "required": [ "FunctionVersion", "FunctionWeight" ], "type": "object" }, "AWS::Lambda::EventSourceMapping": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "BatchSize": { "type": "number" }, "Enabled": { "type": "boolean" }, "EventSourceArn": { "type": "string" }, "FunctionName": { "type": "string" }, "StartingPosition": { "type": "string" } }, "required": [ "EventSourceArn", "FunctionName", "StartingPosition" ], "type": "object" }, "Type": { "enum": [ "AWS::Lambda::EventSourceMapping" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Lambda::Function": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Code": { "$ref": "#/definitions/AWS::Lambda::Function.Code" }, "DeadLetterConfig": { "$ref": "#/definitions/AWS::Lambda::Function.DeadLetterConfig" }, "Description": { "type": "string" }, "Environment": { "$ref": "#/definitions/AWS::Lambda::Function.Environment" }, "FunctionName": { "type": "string" }, "Handler": { "type": "string" }, "KmsKeyArn": { "type": "string" }, "MemorySize": { "type": "number" }, "ReservedConcurrentExecutions": { "type": "number" }, "Role": { "type": "string" }, "Runtime": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Timeout": { "type": "number" }, "TracingConfig": { "$ref": "#/definitions/AWS::Lambda::Function.TracingConfig" }, "VpcConfig": { "$ref": "#/definitions/AWS::Lambda::Function.VpcConfig" } }, "required": [ "Code", "Handler", "Role", "Runtime" ], "type": "object" }, "Type": { "enum": [ "AWS::Lambda::Function" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Lambda::Function.Code": { "additionalProperties": false, "properties": { "S3Bucket": { "type": "string" }, "S3Key": { "type": "string" }, "S3ObjectVersion": { "type": "string" }, "ZipFile": { "type": "string" } }, "type": "object" }, "AWS::Lambda::Function.DeadLetterConfig": { "additionalProperties": false, "properties": { "TargetArn": { "type": "string" } }, "type": "object" }, "AWS::Lambda::Function.Environment": { "additionalProperties": false, "properties": { "Variables": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "type": "object" }, "AWS::Lambda::Function.TracingConfig": { "additionalProperties": false, "properties": { "Mode": { "type": "string" } }, "type": "object" }, "AWS::Lambda::Function.VpcConfig": { "additionalProperties": false, "properties": { "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "SecurityGroupIds", "SubnetIds" ], "type": "object" }, "AWS::Lambda::Permission": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Action": { "type": "string" }, "EventSourceToken": { "type": "string" }, "FunctionName": { "type": "string" }, "Principal": { "type": "string" }, "SourceAccount": { "type": "string" }, "SourceArn": { "type": "string" } }, "required": [ "Action", "FunctionName", "Principal" ], "type": "object" }, "Type": { "enum": [ "AWS::Lambda::Permission" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Lambda::Version": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CodeSha256": { "type": "string" }, "Description": { "type": "string" }, "FunctionName": { "type": "string" } }, "required": [ "FunctionName" ], "type": "object" }, "Type": { "enum": [ "AWS::Lambda::Version" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Logs::Destination": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DestinationName": { "type": "string" }, "DestinationPolicy": { "type": "string" }, "RoleArn": { "type": "string" }, "TargetArn": { "type": "string" } }, "required": [ "DestinationName", "DestinationPolicy", "RoleArn", "TargetArn" ], "type": "object" }, "Type": { "enum": [ "AWS::Logs::Destination" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Logs::LogGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "LogGroupName": { "type": "string" }, "RetentionInDays": { "type": "number" } }, "type": "object" }, "Type": { "enum": [ "AWS::Logs::LogGroup" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Logs::LogStream": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "LogGroupName": { "type": "string" }, "LogStreamName": { "type": "string" } }, "required": [ "LogGroupName" ], "type": "object" }, "Type": { "enum": [ "AWS::Logs::LogStream" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Logs::MetricFilter": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "FilterPattern": { "type": "string" }, "LogGroupName": { "type": "string" }, "MetricTransformations": { "items": { "$ref": "#/definitions/AWS::Logs::MetricFilter.MetricTransformation" }, "type": "array" } }, "required": [ "FilterPattern", "LogGroupName", "MetricTransformations" ], "type": "object" }, "Type": { "enum": [ "AWS::Logs::MetricFilter" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Logs::MetricFilter.MetricTransformation": { "additionalProperties": false, "properties": { "MetricName": { "type": "string" }, "MetricNamespace": { "type": "string" }, "MetricValue": { "type": "string" } }, "required": [ "MetricName", "MetricNamespace", "MetricValue" ], "type": "object" }, "AWS::Logs::SubscriptionFilter": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DestinationArn": { "type": "string" }, "FilterPattern": { "type": "string" }, "LogGroupName": { "type": "string" }, "RoleArn": { "type": "string" } }, "required": [ "DestinationArn", "FilterPattern", "LogGroupName" ], "type": "object" }, "Type": { "enum": [ "AWS::Logs::SubscriptionFilter" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::OpsWorks::App": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AppSource": { "$ref": "#/definitions/AWS::OpsWorks::App.Source" }, "Attributes": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "DataSources": { "items": { "$ref": "#/definitions/AWS::OpsWorks::App.DataSource" }, "type": "array" }, "Description": { "type": "string" }, "Domains": { "items": { "type": "string" }, "type": "array" }, "EnableSsl": { "type": "boolean" }, "Environment": { "items": { "$ref": "#/definitions/AWS::OpsWorks::App.EnvironmentVariable" }, "type": "array" }, "Name": { "type": "string" }, "Shortname": { "type": "string" }, "SslConfiguration": { "$ref": "#/definitions/AWS::OpsWorks::App.SslConfiguration" }, "StackId": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Name", "StackId", "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::OpsWorks::App" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::OpsWorks::App.DataSource": { "additionalProperties": false, "properties": { "Arn": { "type": "string" }, "DatabaseName": { "type": "string" }, "Type": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::App.EnvironmentVariable": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Secure": { "type": "boolean" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::OpsWorks::App.Source": { "additionalProperties": false, "properties": { "Password": { "type": "string" }, "Revision": { "type": "string" }, "SshKey": { "type": "string" }, "Type": { "type": "string" }, "Url": { "type": "string" }, "Username": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::App.SslConfiguration": { "additionalProperties": false, "properties": { "Certificate": { "type": "string" }, "Chain": { "type": "string" }, "PrivateKey": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::ElasticLoadBalancerAttachment": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ElasticLoadBalancerName": { "type": "string" }, "LayerId": { "type": "string" } }, "required": [ "ElasticLoadBalancerName", "LayerId" ], "type": "object" }, "Type": { "enum": [ "AWS::OpsWorks::ElasticLoadBalancerAttachment" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::OpsWorks::Instance": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AgentVersion": { "type": "string" }, "AmiId": { "type": "string" }, "Architecture": { "type": "string" }, "AutoScalingType": { "type": "string" }, "AvailabilityZone": { "type": "string" }, "BlockDeviceMappings": { "items": { "$ref": "#/definitions/AWS::OpsWorks::Instance.BlockDeviceMapping" }, "type": "array" }, "EbsOptimized": { "type": "boolean" }, "ElasticIps": { "items": { "type": "string" }, "type": "array" }, "Hostname": { "type": "string" }, "InstallUpdatesOnBoot": { "type": "boolean" }, "InstanceType": { "type": "string" }, "LayerIds": { "items": { "type": "string" }, "type": "array" }, "Os": { "type": "string" }, "RootDeviceType": { "type": "string" }, "SshKeyName": { "type": "string" }, "StackId": { "type": "string" }, "SubnetId": { "type": "string" }, "Tenancy": { "type": "string" }, "TimeBasedAutoScaling": { "$ref": "#/definitions/AWS::OpsWorks::Instance.TimeBasedAutoScaling" }, "VirtualizationType": { "type": "string" }, "Volumes": { "items": { "type": "string" }, "type": "array" } }, "required": [ "InstanceType", "LayerIds", "StackId" ], "type": "object" }, "Type": { "enum": [ "AWS::OpsWorks::Instance" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::OpsWorks::Instance.BlockDeviceMapping": { "additionalProperties": false, "properties": { "DeviceName": { "type": "string" }, "Ebs": { "$ref": "#/definitions/AWS::OpsWorks::Instance.EbsBlockDevice" }, "NoDevice": { "type": "string" }, "VirtualName": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::Instance.EbsBlockDevice": { "additionalProperties": false, "properties": { "DeleteOnTermination": { "type": "boolean" }, "Iops": { "type": "number" }, "SnapshotId": { "type": "string" }, "VolumeSize": { "type": "number" }, "VolumeType": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::Instance.TimeBasedAutoScaling": { "additionalProperties": false, "properties": { "Friday": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Monday": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Saturday": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Sunday": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Thursday": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Tuesday": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Wednesday": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "type": "object" }, "AWS::OpsWorks::Layer": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Attributes": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "AutoAssignElasticIps": { "type": "boolean" }, "AutoAssignPublicIps": { "type": "boolean" }, "CustomInstanceProfileArn": { "type": "string" }, "CustomJson": { "type": "object" }, "CustomRecipes": { "$ref": "#/definitions/AWS::OpsWorks::Layer.Recipes" }, "CustomSecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "EnableAutoHealing": { "type": "boolean" }, "InstallUpdatesOnBoot": { "type": "boolean" }, "LifecycleEventConfiguration": { "$ref": "#/definitions/AWS::OpsWorks::Layer.LifecycleEventConfiguration" }, "LoadBasedAutoScaling": { "$ref": "#/definitions/AWS::OpsWorks::Layer.LoadBasedAutoScaling" }, "Name": { "type": "string" }, "Packages": { "items": { "type": "string" }, "type": "array" }, "Shortname": { "type": "string" }, "StackId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Type": { "type": "string" }, "UseEbsOptimizedInstances": { "type": "boolean" }, "VolumeConfigurations": { "items": { "$ref": "#/definitions/AWS::OpsWorks::Layer.VolumeConfiguration" }, "type": "array" } }, "required": [ "AutoAssignElasticIps", "AutoAssignPublicIps", "EnableAutoHealing", "Name", "Shortname", "StackId", "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::OpsWorks::Layer" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::OpsWorks::Layer.AutoScalingThresholds": { "additionalProperties": false, "properties": { "CpuThreshold": { "type": "number" }, "IgnoreMetricsTime": { "type": "number" }, "InstanceCount": { "type": "number" }, "LoadThreshold": { "type": "number" }, "MemoryThreshold": { "type": "number" }, "ThresholdsWaitTime": { "type": "number" } }, "type": "object" }, "AWS::OpsWorks::Layer.LifecycleEventConfiguration": { "additionalProperties": false, "properties": { "ShutdownEventConfiguration": { "$ref": "#/definitions/AWS::OpsWorks::Layer.ShutdownEventConfiguration" } }, "type": "object" }, "AWS::OpsWorks::Layer.LoadBasedAutoScaling": { "additionalProperties": false, "properties": { "DownScaling": { "$ref": "#/definitions/AWS::OpsWorks::Layer.AutoScalingThresholds" }, "Enable": { "type": "boolean" }, "UpScaling": { "$ref": "#/definitions/AWS::OpsWorks::Layer.AutoScalingThresholds" } }, "type": "object" }, "AWS::OpsWorks::Layer.Recipes": { "additionalProperties": false, "properties": { "Configure": { "items": { "type": "string" }, "type": "array" }, "Deploy": { "items": { "type": "string" }, "type": "array" }, "Setup": { "items": { "type": "string" }, "type": "array" }, "Shutdown": { "items": { "type": "string" }, "type": "array" }, "Undeploy": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::OpsWorks::Layer.ShutdownEventConfiguration": { "additionalProperties": false, "properties": { "DelayUntilElbConnectionsDrained": { "type": "boolean" }, "ExecutionTimeout": { "type": "number" } }, "type": "object" }, "AWS::OpsWorks::Layer.VolumeConfiguration": { "additionalProperties": false, "properties": { "Iops": { "type": "number" }, "MountPoint": { "type": "string" }, "NumberOfDisks": { "type": "number" }, "RaidLevel": { "type": "number" }, "Size": { "type": "number" }, "VolumeType": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::Stack": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AgentVersion": { "type": "string" }, "Attributes": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "ChefConfiguration": { "$ref": "#/definitions/AWS::OpsWorks::Stack.ChefConfiguration" }, "CloneAppIds": { "items": { "type": "string" }, "type": "array" }, "ClonePermissions": { "type": "boolean" }, "ConfigurationManager": { "$ref": "#/definitions/AWS::OpsWorks::Stack.StackConfigurationManager" }, "CustomCookbooksSource": { "$ref": "#/definitions/AWS::OpsWorks::Stack.Source" }, "CustomJson": { "type": "object" }, "DefaultAvailabilityZone": { "type": "string" }, "DefaultInstanceProfileArn": { "type": "string" }, "DefaultOs": { "type": "string" }, "DefaultRootDeviceType": { "type": "string" }, "DefaultSshKeyName": { "type": "string" }, "DefaultSubnetId": { "type": "string" }, "EcsClusterArn": { "type": "string" }, "ElasticIps": { "items": { "$ref": "#/definitions/AWS::OpsWorks::Stack.ElasticIp" }, "type": "array" }, "HostnameTheme": { "type": "string" }, "Name": { "type": "string" }, "RdsDbInstances": { "items": { "$ref": "#/definitions/AWS::OpsWorks::Stack.RdsDbInstance" }, "type": "array" }, "ServiceRoleArn": { "type": "string" }, "SourceStackId": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "UseCustomCookbooks": { "type": "boolean" }, "UseOpsworksSecurityGroups": { "type": "boolean" }, "VpcId": { "type": "string" } }, "required": [ "DefaultInstanceProfileArn", "Name", "ServiceRoleArn" ], "type": "object" }, "Type": { "enum": [ "AWS::OpsWorks::Stack" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::OpsWorks::Stack.ChefConfiguration": { "additionalProperties": false, "properties": { "BerkshelfVersion": { "type": "string" }, "ManageBerkshelf": { "type": "boolean" } }, "type": "object" }, "AWS::OpsWorks::Stack.ElasticIp": { "additionalProperties": false, "properties": { "Ip": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "Ip" ], "type": "object" }, "AWS::OpsWorks::Stack.RdsDbInstance": { "additionalProperties": false, "properties": { "DbPassword": { "type": "string" }, "DbUser": { "type": "string" }, "RdsDbInstanceArn": { "type": "string" } }, "required": [ "DbPassword", "DbUser", "RdsDbInstanceArn" ], "type": "object" }, "AWS::OpsWorks::Stack.Source": { "additionalProperties": false, "properties": { "Password": { "type": "string" }, "Revision": { "type": "string" }, "SshKey": { "type": "string" }, "Type": { "type": "string" }, "Url": { "type": "string" }, "Username": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::Stack.StackConfigurationManager": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Version": { "type": "string" } }, "type": "object" }, "AWS::OpsWorks::UserProfile": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllowSelfManagement": { "type": "boolean" }, "IamUserArn": { "type": "string" }, "SshPublicKey": { "type": "string" }, "SshUsername": { "type": "string" } }, "required": [ "IamUserArn" ], "type": "object" }, "Type": { "enum": [ "AWS::OpsWorks::UserProfile" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::OpsWorks::Volume": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Ec2VolumeId": { "type": "string" }, "MountPoint": { "type": "string" }, "Name": { "type": "string" }, "StackId": { "type": "string" } }, "required": [ "Ec2VolumeId", "StackId" ], "type": "object" }, "Type": { "enum": [ "AWS::OpsWorks::Volume" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::DBCluster": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AvailabilityZones": { "items": { "type": "string" }, "type": "array" }, "BackupRetentionPeriod": { "type": "number" }, "DBClusterIdentifier": { "type": "string" }, "DBClusterParameterGroupName": { "type": "string" }, "DBSubnetGroupName": { "type": "string" }, "DatabaseName": { "type": "string" }, "Engine": { "type": "string" }, "EngineVersion": { "type": "string" }, "KmsKeyId": { "type": "string" }, "MasterUserPassword": { "type": "string" }, "MasterUsername": { "type": "string" }, "Port": { "type": "number" }, "PreferredBackupWindow": { "type": "string" }, "PreferredMaintenanceWindow": { "type": "string" }, "ReplicationSourceIdentifier": { "type": "string" }, "SnapshotIdentifier": { "type": "string" }, "StorageEncrypted": { "type": "boolean" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcSecurityGroupIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Engine" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::DBCluster" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::DBClusterParameterGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Family": { "type": "string" }, "Parameters": { "type": "object" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "Description", "Family", "Parameters" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::DBClusterParameterGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::DBInstance": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllocatedStorage": { "type": "string" }, "AllowMajorVersionUpgrade": { "type": "boolean" }, "AutoMinorVersionUpgrade": { "type": "boolean" }, "AvailabilityZone": { "type": "string" }, "BackupRetentionPeriod": { "type": "string" }, "CharacterSetName": { "type": "string" }, "CopyTagsToSnapshot": { "type": "boolean" }, "DBClusterIdentifier": { "type": "string" }, "DBInstanceClass": { "type": "string" }, "DBInstanceIdentifier": { "type": "string" }, "DBName": { "type": "string" }, "DBParameterGroupName": { "type": "string" }, "DBSecurityGroups": { "items": { "type": "string" }, "type": "array" }, "DBSnapshotIdentifier": { "type": "string" }, "DBSubnetGroupName": { "type": "string" }, "Domain": { "type": "string" }, "DomainIAMRoleName": { "type": "string" }, "Engine": { "type": "string" }, "EngineVersion": { "type": "string" }, "Iops": { "type": "number" }, "KmsKeyId": { "type": "string" }, "LicenseModel": { "type": "string" }, "MasterUserPassword": { "type": "string" }, "MasterUsername": { "type": "string" }, "MonitoringInterval": { "type": "number" }, "MonitoringRoleArn": { "type": "string" }, "MultiAZ": { "type": "boolean" }, "OptionGroupName": { "type": "string" }, "Port": { "type": "string" }, "PreferredBackupWindow": { "type": "string" }, "PreferredMaintenanceWindow": { "type": "string" }, "PubliclyAccessible": { "type": "boolean" }, "SourceDBInstanceIdentifier": { "type": "string" }, "SourceRegion": { "type": "string" }, "StorageEncrypted": { "type": "boolean" }, "StorageType": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "Timezone": { "type": "string" }, "VPCSecurityGroups": { "items": { "type": "string" }, "type": "array" } }, "required": [ "DBInstanceClass" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::DBInstance" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::DBParameterGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Family": { "type": "string" }, "Parameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "Description", "Family" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::DBParameterGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::DBSecurityGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DBSecurityGroupIngress": { "items": { "$ref": "#/definitions/AWS::RDS::DBSecurityGroup.Ingress" }, "type": "array" }, "EC2VpcId": { "type": "string" }, "GroupDescription": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "DBSecurityGroupIngress", "GroupDescription" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::DBSecurityGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::DBSecurityGroup.Ingress": { "additionalProperties": false, "properties": { "CIDRIP": { "type": "string" }, "EC2SecurityGroupId": { "type": "string" }, "EC2SecurityGroupName": { "type": "string" }, "EC2SecurityGroupOwnerId": { "type": "string" } }, "type": "object" }, "AWS::RDS::DBSecurityGroupIngress": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CIDRIP": { "type": "string" }, "DBSecurityGroupName": { "type": "string" }, "EC2SecurityGroupId": { "type": "string" }, "EC2SecurityGroupName": { "type": "string" }, "EC2SecurityGroupOwnerId": { "type": "string" } }, "required": [ "DBSecurityGroupName" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::DBSecurityGroupIngress" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::DBSubnetGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DBSubnetGroupDescription": { "type": "string" }, "DBSubnetGroupName": { "type": "string" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "DBSubnetGroupDescription", "SubnetIds" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::DBSubnetGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::EventSubscription": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Enabled": { "type": "boolean" }, "EventCategories": { "items": { "type": "string" }, "type": "array" }, "SnsTopicArn": { "type": "string" }, "SourceIds": { "items": { "type": "string" }, "type": "array" }, "SourceType": { "type": "string" } }, "required": [ "SnsTopicArn" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::EventSubscription" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::OptionGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "EngineName": { "type": "string" }, "MajorEngineVersion": { "type": "string" }, "OptionConfigurations": { "items": { "$ref": "#/definitions/AWS::RDS::OptionGroup.OptionConfiguration" }, "type": "array" }, "OptionGroupDescription": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "EngineName", "MajorEngineVersion", "OptionConfigurations", "OptionGroupDescription" ], "type": "object" }, "Type": { "enum": [ "AWS::RDS::OptionGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::RDS::OptionGroup.OptionConfiguration": { "additionalProperties": false, "properties": { "DBSecurityGroupMemberships": { "items": { "type": "string" }, "type": "array" }, "OptionName": { "type": "string" }, "OptionSettings": { "$ref": "#/definitions/AWS::RDS::OptionGroup.OptionSetting" }, "OptionVersion": { "type": "string" }, "Port": { "type": "number" }, "VpcSecurityGroupMemberships": { "items": { "type": "string" }, "type": "array" } }, "required": [ "OptionName" ], "type": "object" }, "AWS::RDS::OptionGroup.OptionSetting": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" }, "AWS::Redshift::Cluster": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllowVersionUpgrade": { "type": "boolean" }, "AutomatedSnapshotRetentionPeriod": { "type": "number" }, "AvailabilityZone": { "type": "string" }, "ClusterIdentifier": { "type": "string" }, "ClusterParameterGroupName": { "type": "string" }, "ClusterSecurityGroups": { "items": { "type": "string" }, "type": "array" }, "ClusterSubnetGroupName": { "type": "string" }, "ClusterType": { "type": "string" }, "ClusterVersion": { "type": "string" }, "DBName": { "type": "string" }, "ElasticIp": { "type": "string" }, "Encrypted": { "type": "boolean" }, "HsmClientCertificateIdentifier": { "type": "string" }, "HsmConfigurationIdentifier": { "type": "string" }, "IamRoles": { "items": { "type": "string" }, "type": "array" }, "KmsKeyId": { "type": "string" }, "LoggingProperties": { "$ref": "#/definitions/AWS::Redshift::Cluster.LoggingProperties" }, "MasterUserPassword": { "type": "string" }, "MasterUsername": { "type": "string" }, "NodeType": { "type": "string" }, "NumberOfNodes": { "type": "number" }, "OwnerAccount": { "type": "string" }, "Port": { "type": "number" }, "PreferredMaintenanceWindow": { "type": "string" }, "PubliclyAccessible": { "type": "boolean" }, "SnapshotClusterIdentifier": { "type": "string" }, "SnapshotIdentifier": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VpcSecurityGroupIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "ClusterType", "DBName", "MasterUserPassword", "MasterUsername", "NodeType" ], "type": "object" }, "Type": { "enum": [ "AWS::Redshift::Cluster" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Redshift::Cluster.LoggingProperties": { "additionalProperties": false, "properties": { "BucketName": { "type": "string" }, "S3KeyPrefix": { "type": "string" } }, "required": [ "BucketName" ], "type": "object" }, "AWS::Redshift::ClusterParameterGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "ParameterGroupFamily": { "type": "string" }, "Parameters": { "items": { "$ref": "#/definitions/AWS::Redshift::ClusterParameterGroup.Parameter" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "Description", "ParameterGroupFamily" ], "type": "object" }, "Type": { "enum": [ "AWS::Redshift::ClusterParameterGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Redshift::ClusterParameterGroup.Parameter": { "additionalProperties": false, "properties": { "ParameterName": { "type": "string" }, "ParameterValue": { "type": "string" } }, "required": [ "ParameterName", "ParameterValue" ], "type": "object" }, "AWS::Redshift::ClusterSecurityGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "Description" ], "type": "object" }, "Type": { "enum": [ "AWS::Redshift::ClusterSecurityGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Redshift::ClusterSecurityGroupIngress": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CIDRIP": { "type": "string" }, "ClusterSecurityGroupName": { "type": "string" }, "EC2SecurityGroupName": { "type": "string" }, "EC2SecurityGroupOwnerId": { "type": "string" } }, "required": [ "ClusterSecurityGroupName" ], "type": "object" }, "Type": { "enum": [ "AWS::Redshift::ClusterSecurityGroupIngress" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Redshift::ClusterSubnetGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "Description", "SubnetIds" ], "type": "object" }, "Type": { "enum": [ "AWS::Redshift::ClusterSubnetGroup" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Route53::HealthCheck": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "HealthCheckConfig": { "$ref": "#/definitions/AWS::Route53::HealthCheck.HealthCheckConfig" }, "HealthCheckTags": { "items": { "$ref": "#/definitions/AWS::Route53::HealthCheck.HealthCheckTag" }, "type": "array" } }, "required": [ "HealthCheckConfig" ], "type": "object" }, "Type": { "enum": [ "AWS::Route53::HealthCheck" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Route53::HealthCheck.AlarmIdentifier": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Region": { "type": "string" } }, "required": [ "Name", "Region" ], "type": "object" }, "AWS::Route53::HealthCheck.HealthCheckConfig": { "additionalProperties": false, "properties": { "AlarmIdentifier": { "$ref": "#/definitions/AWS::Route53::HealthCheck.AlarmIdentifier" }, "ChildHealthChecks": { "items": { "type": "string" }, "type": "array" }, "EnableSNI": { "type": "boolean" }, "FailureThreshold": { "type": "number" }, "FullyQualifiedDomainName": { "type": "string" }, "HealthThreshold": { "type": "number" }, "IPAddress": { "type": "string" }, "InsufficientDataHealthStatus": { "type": "string" }, "Inverted": { "type": "boolean" }, "MeasureLatency": { "type": "boolean" }, "Port": { "type": "number" }, "Regions": { "items": { "type": "string" }, "type": "array" }, "RequestInterval": { "type": "number" }, "ResourcePath": { "type": "string" }, "SearchString": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Route53::HealthCheck.HealthCheckTag": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::Route53::HostedZone": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "HostedZoneConfig": { "$ref": "#/definitions/AWS::Route53::HostedZone.HostedZoneConfig" }, "HostedZoneTags": { "items": { "$ref": "#/definitions/AWS::Route53::HostedZone.HostedZoneTag" }, "type": "array" }, "Name": { "type": "string" }, "QueryLoggingConfig": { "$ref": "#/definitions/AWS::Route53::HostedZone.QueryLoggingConfig" }, "VPCs": { "items": { "$ref": "#/definitions/AWS::Route53::HostedZone.VPC" }, "type": "array" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::Route53::HostedZone" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Route53::HostedZone.HostedZoneConfig": { "additionalProperties": false, "properties": { "Comment": { "type": "string" } }, "type": "object" }, "AWS::Route53::HostedZone.HostedZoneTag": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::Route53::HostedZone.QueryLoggingConfig": { "additionalProperties": false, "properties": { "CloudWatchLogsLogGroupArn": { "type": "string" } }, "required": [ "CloudWatchLogsLogGroupArn" ], "type": "object" }, "AWS::Route53::HostedZone.VPC": { "additionalProperties": false, "properties": { "VPCId": { "type": "string" }, "VPCRegion": { "type": "string" } }, "required": [ "VPCId", "VPCRegion" ], "type": "object" }, "AWS::Route53::RecordSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AliasTarget": { "$ref": "#/definitions/AWS::Route53::RecordSet.AliasTarget" }, "Comment": { "type": "string" }, "Failover": { "type": "string" }, "GeoLocation": { "$ref": "#/definitions/AWS::Route53::RecordSet.GeoLocation" }, "HealthCheckId": { "type": "string" }, "HostedZoneId": { "type": "string" }, "HostedZoneName": { "type": "string" }, "Name": { "type": "string" }, "Region": { "type": "string" }, "ResourceRecords": { "items": { "type": "string" }, "type": "array" }, "SetIdentifier": { "type": "string" }, "TTL": { "type": "string" }, "Type": { "type": "string" }, "Weight": { "type": "number" } }, "required": [ "Name", "Type" ], "type": "object" }, "Type": { "enum": [ "AWS::Route53::RecordSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Route53::RecordSet.AliasTarget": { "additionalProperties": false, "properties": { "DNSName": { "type": "string" }, "EvaluateTargetHealth": { "type": "boolean" }, "HostedZoneId": { "type": "string" } }, "required": [ "DNSName", "HostedZoneId" ], "type": "object" }, "AWS::Route53::RecordSet.GeoLocation": { "additionalProperties": false, "properties": { "ContinentCode": { "type": "string" }, "CountryCode": { "type": "string" }, "SubdivisionCode": { "type": "string" } }, "type": "object" }, "AWS::Route53::RecordSetGroup": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Comment": { "type": "string" }, "HostedZoneId": { "type": "string" }, "HostedZoneName": { "type": "string" }, "RecordSets": { "items": { "$ref": "#/definitions/AWS::Route53::RecordSetGroup.RecordSet" }, "type": "array" } }, "type": "object" }, "Type": { "enum": [ "AWS::Route53::RecordSetGroup" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Route53::RecordSetGroup.AliasTarget": { "additionalProperties": false, "properties": { "DNSName": { "type": "string" }, "EvaluateTargetHealth": { "type": "boolean" }, "HostedZoneId": { "type": "string" } }, "required": [ "DNSName", "HostedZoneId" ], "type": "object" }, "AWS::Route53::RecordSetGroup.GeoLocation": { "additionalProperties": false, "properties": { "ContinentCode": { "type": "string" }, "CountryCode": { "type": "string" }, "SubdivisionCode": { "type": "string" } }, "type": "object" }, "AWS::Route53::RecordSetGroup.RecordSet": { "additionalProperties": false, "properties": { "AliasTarget": { "$ref": "#/definitions/AWS::Route53::RecordSetGroup.AliasTarget" }, "Comment": { "type": "string" }, "Failover": { "type": "string" }, "GeoLocation": { "$ref": "#/definitions/AWS::Route53::RecordSetGroup.GeoLocation" }, "HealthCheckId": { "type": "string" }, "HostedZoneId": { "type": "string" }, "HostedZoneName": { "type": "string" }, "Name": { "type": "string" }, "Region": { "type": "string" }, "ResourceRecords": { "items": { "type": "string" }, "type": "array" }, "SetIdentifier": { "type": "string" }, "TTL": { "type": "string" }, "Type": { "type": "string" }, "Weight": { "type": "number" } }, "required": [ "Name", "Type" ], "type": "object" }, "AWS::S3::Bucket": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AccelerateConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.AccelerateConfiguration" }, "AccessControl": { "type": "string" }, "AnalyticsConfigurations": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.AnalyticsConfiguration" }, "type": "array" }, "BucketEncryption": { "$ref": "#/definitions/AWS::S3::Bucket.BucketEncryption" }, "BucketName": { "type": "string" }, "CorsConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.CorsConfiguration" }, "InventoryConfigurations": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.InventoryConfiguration" }, "type": "array" }, "LifecycleConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.LifecycleConfiguration" }, "LoggingConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.LoggingConfiguration" }, "MetricsConfigurations": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.MetricsConfiguration" }, "type": "array" }, "NotificationConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.NotificationConfiguration" }, "ReplicationConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.ReplicationConfiguration" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" }, "VersioningConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.VersioningConfiguration" }, "WebsiteConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.WebsiteConfiguration" } }, "type": "object" }, "Type": { "enum": [ "AWS::S3::Bucket" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::S3::Bucket.AbortIncompleteMultipartUpload": { "additionalProperties": false, "properties": { "DaysAfterInitiation": { "type": "number" } }, "required": [ "DaysAfterInitiation" ], "type": "object" }, "AWS::S3::Bucket.AccelerateConfiguration": { "additionalProperties": false, "properties": { "AccelerationStatus": { "type": "string" } }, "required": [ "AccelerationStatus" ], "type": "object" }, "AWS::S3::Bucket.AccessControlTranslation": { "additionalProperties": false, "properties": { "Owner": { "type": "string" } }, "required": [ "Owner" ], "type": "object" }, "AWS::S3::Bucket.AnalyticsConfiguration": { "additionalProperties": false, "properties": { "Id": { "type": "string" }, "Prefix": { "type": "string" }, "StorageClassAnalysis": { "$ref": "#/definitions/AWS::S3::Bucket.StorageClassAnalysis" }, "TagFilters": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.TagFilter" }, "type": "array" } }, "required": [ "Id", "StorageClassAnalysis" ], "type": "object" }, "AWS::S3::Bucket.BucketEncryption": { "additionalProperties": false, "properties": { "ServerSideEncryptionConfiguration": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.ServerSideEncryptionRule" }, "type": "array" } }, "required": [ "ServerSideEncryptionConfiguration" ], "type": "object" }, "AWS::S3::Bucket.CorsConfiguration": { "additionalProperties": false, "properties": { "CorsRules": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.CorsRule" }, "type": "array" } }, "required": [ "CorsRules" ], "type": "object" }, "AWS::S3::Bucket.CorsRule": { "additionalProperties": false, "properties": { "AllowedHeaders": { "items": { "type": "string" }, "type": "array" }, "AllowedMethods": { "items": { "type": "string" }, "type": "array" }, "AllowedOrigins": { "items": { "type": "string" }, "type": "array" }, "ExposedHeaders": { "items": { "type": "string" }, "type": "array" }, "Id": { "type": "string" }, "MaxAge": { "type": "number" } }, "required": [ "AllowedMethods", "AllowedOrigins" ], "type": "object" }, "AWS::S3::Bucket.DataExport": { "additionalProperties": false, "properties": { "Destination": { "$ref": "#/definitions/AWS::S3::Bucket.Destination" }, "OutputSchemaVersion": { "type": "string" } }, "required": [ "Destination", "OutputSchemaVersion" ], "type": "object" }, "AWS::S3::Bucket.Destination": { "additionalProperties": false, "properties": { "BucketAccountId": { "type": "string" }, "BucketArn": { "type": "string" }, "Format": { "type": "string" }, "Prefix": { "type": "string" } }, "required": [ "BucketArn", "Format" ], "type": "object" }, "AWS::S3::Bucket.EncryptionConfiguration": { "additionalProperties": false, "properties": { "ReplicaKmsKeyID": { "type": "string" } }, "required": [ "ReplicaKmsKeyID" ], "type": "object" }, "AWS::S3::Bucket.FilterRule": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Name", "Value" ], "type": "object" }, "AWS::S3::Bucket.InventoryConfiguration": { "additionalProperties": false, "properties": { "Destination": { "$ref": "#/definitions/AWS::S3::Bucket.Destination" }, "Enabled": { "type": "boolean" }, "Id": { "type": "string" }, "IncludedObjectVersions": { "type": "string" }, "OptionalFields": { "items": { "type": "string" }, "type": "array" }, "Prefix": { "type": "string" }, "ScheduleFrequency": { "type": "string" } }, "required": [ "Destination", "Enabled", "Id", "IncludedObjectVersions", "ScheduleFrequency" ], "type": "object" }, "AWS::S3::Bucket.LambdaConfiguration": { "additionalProperties": false, "properties": { "Event": { "type": "string" }, "Filter": { "$ref": "#/definitions/AWS::S3::Bucket.NotificationFilter" }, "Function": { "type": "string" } }, "required": [ "Event", "Function" ], "type": "object" }, "AWS::S3::Bucket.LifecycleConfiguration": { "additionalProperties": false, "properties": { "Rules": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.Rule" }, "type": "array" } }, "required": [ "Rules" ], "type": "object" }, "AWS::S3::Bucket.LoggingConfiguration": { "additionalProperties": false, "properties": { "DestinationBucketName": { "type": "string" }, "LogFilePrefix": { "type": "string" } }, "type": "object" }, "AWS::S3::Bucket.MetricsConfiguration": { "additionalProperties": false, "properties": { "Id": { "type": "string" }, "Prefix": { "type": "string" }, "TagFilters": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.TagFilter" }, "type": "array" } }, "required": [ "Id" ], "type": "object" }, "AWS::S3::Bucket.NoncurrentVersionTransition": { "additionalProperties": false, "properties": { "StorageClass": { "type": "string" }, "TransitionInDays": { "type": "number" } }, "required": [ "StorageClass", "TransitionInDays" ], "type": "object" }, "AWS::S3::Bucket.NotificationConfiguration": { "additionalProperties": false, "properties": { "LambdaConfigurations": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.LambdaConfiguration" }, "type": "array" }, "QueueConfigurations": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.QueueConfiguration" }, "type": "array" }, "TopicConfigurations": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.TopicConfiguration" }, "type": "array" } }, "type": "object" }, "AWS::S3::Bucket.NotificationFilter": { "additionalProperties": false, "properties": { "S3Key": { "$ref": "#/definitions/AWS::S3::Bucket.S3KeyFilter" } }, "required": [ "S3Key" ], "type": "object" }, "AWS::S3::Bucket.QueueConfiguration": { "additionalProperties": false, "properties": { "Event": { "type": "string" }, "Filter": { "$ref": "#/definitions/AWS::S3::Bucket.NotificationFilter" }, "Queue": { "type": "string" } }, "required": [ "Event", "Queue" ], "type": "object" }, "AWS::S3::Bucket.RedirectAllRequestsTo": { "additionalProperties": false, "properties": { "HostName": { "type": "string" }, "Protocol": { "type": "string" } }, "required": [ "HostName" ], "type": "object" }, "AWS::S3::Bucket.RedirectRule": { "additionalProperties": false, "properties": { "HostName": { "type": "string" }, "HttpRedirectCode": { "type": "string" }, "Protocol": { "type": "string" }, "ReplaceKeyPrefixWith": { "type": "string" }, "ReplaceKeyWith": { "type": "string" } }, "type": "object" }, "AWS::S3::Bucket.ReplicationConfiguration": { "additionalProperties": false, "properties": { "Role": { "type": "string" }, "Rules": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.ReplicationRule" }, "type": "array" } }, "required": [ "Role", "Rules" ], "type": "object" }, "AWS::S3::Bucket.ReplicationDestination": { "additionalProperties": false, "properties": { "AccessControlTranslation": { "$ref": "#/definitions/AWS::S3::Bucket.AccessControlTranslation" }, "Account": { "type": "string" }, "Bucket": { "type": "string" }, "EncryptionConfiguration": { "$ref": "#/definitions/AWS::S3::Bucket.EncryptionConfiguration" }, "StorageClass": { "type": "string" } }, "required": [ "Bucket" ], "type": "object" }, "AWS::S3::Bucket.ReplicationRule": { "additionalProperties": false, "properties": { "Destination": { "$ref": "#/definitions/AWS::S3::Bucket.ReplicationDestination" }, "Id": { "type": "string" }, "Prefix": { "type": "string" }, "SourceSelectionCriteria": { "$ref": "#/definitions/AWS::S3::Bucket.SourceSelectionCriteria" }, "Status": { "type": "string" } }, "required": [ "Destination", "Prefix", "Status" ], "type": "object" }, "AWS::S3::Bucket.RoutingRule": { "additionalProperties": false, "properties": { "RedirectRule": { "$ref": "#/definitions/AWS::S3::Bucket.RedirectRule" }, "RoutingRuleCondition": { "$ref": "#/definitions/AWS::S3::Bucket.RoutingRuleCondition" } }, "required": [ "RedirectRule" ], "type": "object" }, "AWS::S3::Bucket.RoutingRuleCondition": { "additionalProperties": false, "properties": { "HttpErrorCodeReturnedEquals": { "type": "string" }, "KeyPrefixEquals": { "type": "string" } }, "type": "object" }, "AWS::S3::Bucket.Rule": { "additionalProperties": false, "properties": { "AbortIncompleteMultipartUpload": { "$ref": "#/definitions/AWS::S3::Bucket.AbortIncompleteMultipartUpload" }, "ExpirationDate": { "type": "string" }, "ExpirationInDays": { "type": "number" }, "Id": { "type": "string" }, "NoncurrentVersionExpirationInDays": { "type": "number" }, "NoncurrentVersionTransition": { "$ref": "#/definitions/AWS::S3::Bucket.NoncurrentVersionTransition" }, "NoncurrentVersionTransitions": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.NoncurrentVersionTransition" }, "type": "array" }, "Prefix": { "type": "string" }, "Status": { "type": "string" }, "TagFilters": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.TagFilter" }, "type": "array" }, "Transition": { "$ref": "#/definitions/AWS::S3::Bucket.Transition" }, "Transitions": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.Transition" }, "type": "array" } }, "required": [ "Status" ], "type": "object" }, "AWS::S3::Bucket.S3KeyFilter": { "additionalProperties": false, "properties": { "Rules": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.FilterRule" }, "type": "array" } }, "required": [ "Rules" ], "type": "object" }, "AWS::S3::Bucket.ServerSideEncryptionByDefault": { "additionalProperties": false, "properties": { "KMSMasterKeyID": { "type": "string" }, "SSEAlgorithm": { "type": "string" } }, "required": [ "SSEAlgorithm" ], "type": "object" }, "AWS::S3::Bucket.ServerSideEncryptionRule": { "additionalProperties": false, "properties": { "ServerSideEncryptionByDefault": { "$ref": "#/definitions/AWS::S3::Bucket.ServerSideEncryptionByDefault" } }, "type": "object" }, "AWS::S3::Bucket.SourceSelectionCriteria": { "additionalProperties": false, "properties": { "SseKmsEncryptedObjects": { "$ref": "#/definitions/AWS::S3::Bucket.SseKmsEncryptedObjects" } }, "required": [ "SseKmsEncryptedObjects" ], "type": "object" }, "AWS::S3::Bucket.SseKmsEncryptedObjects": { "additionalProperties": false, "properties": { "Status": { "type": "string" } }, "required": [ "Status" ], "type": "object" }, "AWS::S3::Bucket.StorageClassAnalysis": { "additionalProperties": false, "properties": { "DataExport": { "$ref": "#/definitions/AWS::S3::Bucket.DataExport" } }, "type": "object" }, "AWS::S3::Bucket.TagFilter": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Key", "Value" ], "type": "object" }, "AWS::S3::Bucket.TopicConfiguration": { "additionalProperties": false, "properties": { "Event": { "type": "string" }, "Filter": { "$ref": "#/definitions/AWS::S3::Bucket.NotificationFilter" }, "Topic": { "type": "string" } }, "required": [ "Event", "Topic" ], "type": "object" }, "AWS::S3::Bucket.Transition": { "additionalProperties": false, "properties": { "StorageClass": { "type": "string" }, "TransitionDate": { "type": "string" }, "TransitionInDays": { "type": "number" } }, "required": [ "StorageClass" ], "type": "object" }, "AWS::S3::Bucket.VersioningConfiguration": { "additionalProperties": false, "properties": { "Status": { "type": "string" } }, "required": [ "Status" ], "type": "object" }, "AWS::S3::Bucket.WebsiteConfiguration": { "additionalProperties": false, "properties": { "ErrorDocument": { "type": "string" }, "IndexDocument": { "type": "string" }, "RedirectAllRequestsTo": { "$ref": "#/definitions/AWS::S3::Bucket.RedirectAllRequestsTo" }, "RoutingRules": { "items": { "$ref": "#/definitions/AWS::S3::Bucket.RoutingRule" }, "type": "array" } }, "type": "object" }, "AWS::S3::BucketPolicy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "PolicyDocument": { "type": "object" } }, "required": [ "Bucket", "PolicyDocument" ], "type": "object" }, "Type": { "enum": [ "AWS::S3::BucketPolicy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SDB::Domain": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::SDB::Domain" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::SES::ConfigurationSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::SES::ConfigurationSet" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::SES::ConfigurationSetEventDestination": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ConfigurationSetName": { "type": "string" }, "EventDestination": { "$ref": "#/definitions/AWS::SES::ConfigurationSetEventDestination.EventDestination" } }, "required": [ "ConfigurationSetName", "EventDestination" ], "type": "object" }, "Type": { "enum": [ "AWS::SES::ConfigurationSetEventDestination" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SES::ConfigurationSetEventDestination.CloudWatchDestination": { "additionalProperties": false, "properties": { "DimensionConfigurations": { "items": { "$ref": "#/definitions/AWS::SES::ConfigurationSetEventDestination.DimensionConfiguration" }, "type": "array" } }, "type": "object" }, "AWS::SES::ConfigurationSetEventDestination.DimensionConfiguration": { "additionalProperties": false, "properties": { "DefaultDimensionValue": { "type": "string" }, "DimensionName": { "type": "string" }, "DimensionValueSource": { "type": "string" } }, "required": [ "DefaultDimensionValue", "DimensionName", "DimensionValueSource" ], "type": "object" }, "AWS::SES::ConfigurationSetEventDestination.EventDestination": { "additionalProperties": false, "properties": { "CloudWatchDestination": { "$ref": "#/definitions/AWS::SES::ConfigurationSetEventDestination.CloudWatchDestination" }, "Enabled": { "type": "boolean" }, "KinesisFirehoseDestination": { "$ref": "#/definitions/AWS::SES::ConfigurationSetEventDestination.KinesisFirehoseDestination" }, "MatchingEventTypes": { "items": { "type": "string" }, "type": "array" }, "Name": { "type": "string" } }, "required": [ "MatchingEventTypes" ], "type": "object" }, "AWS::SES::ConfigurationSetEventDestination.KinesisFirehoseDestination": { "additionalProperties": false, "properties": { "DeliveryStreamARN": { "type": "string" }, "IAMRoleARN": { "type": "string" } }, "required": [ "DeliveryStreamARN", "IAMRoleARN" ], "type": "object" }, "AWS::SES::ReceiptFilter": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Filter": { "$ref": "#/definitions/AWS::SES::ReceiptFilter.Filter" } }, "required": [ "Filter" ], "type": "object" }, "Type": { "enum": [ "AWS::SES::ReceiptFilter" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SES::ReceiptFilter.Filter": { "additionalProperties": false, "properties": { "IpFilter": { "$ref": "#/definitions/AWS::SES::ReceiptFilter.IpFilter" }, "Name": { "type": "string" } }, "required": [ "IpFilter" ], "type": "object" }, "AWS::SES::ReceiptFilter.IpFilter": { "additionalProperties": false, "properties": { "Cidr": { "type": "string" }, "Policy": { "type": "string" } }, "required": [ "Cidr", "Policy" ], "type": "object" }, "AWS::SES::ReceiptRule": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "After": { "type": "string" }, "Rule": { "$ref": "#/definitions/AWS::SES::ReceiptRule.Rule" }, "RuleSetName": { "type": "string" } }, "required": [ "Rule", "RuleSetName" ], "type": "object" }, "Type": { "enum": [ "AWS::SES::ReceiptRule" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SES::ReceiptRule.Action": { "additionalProperties": false, "properties": { "AddHeaderAction": { "$ref": "#/definitions/AWS::SES::ReceiptRule.AddHeaderAction" }, "BounceAction": { "$ref": "#/definitions/AWS::SES::ReceiptRule.BounceAction" }, "LambdaAction": { "$ref": "#/definitions/AWS::SES::ReceiptRule.LambdaAction" }, "S3Action": { "$ref": "#/definitions/AWS::SES::ReceiptRule.S3Action" }, "SNSAction": { "$ref": "#/definitions/AWS::SES::ReceiptRule.SNSAction" }, "StopAction": { "$ref": "#/definitions/AWS::SES::ReceiptRule.StopAction" }, "WorkmailAction": { "$ref": "#/definitions/AWS::SES::ReceiptRule.WorkmailAction" } }, "type": "object" }, "AWS::SES::ReceiptRule.AddHeaderAction": { "additionalProperties": false, "properties": { "HeaderName": { "type": "string" }, "HeaderValue": { "type": "string" } }, "required": [ "HeaderName", "HeaderValue" ], "type": "object" }, "AWS::SES::ReceiptRule.BounceAction": { "additionalProperties": false, "properties": { "Message": { "type": "string" }, "Sender": { "type": "string" }, "SmtpReplyCode": { "type": "string" }, "StatusCode": { "type": "string" }, "TopicArn": { "type": "string" } }, "required": [ "Message", "Sender", "SmtpReplyCode" ], "type": "object" }, "AWS::SES::ReceiptRule.LambdaAction": { "additionalProperties": false, "properties": { "FunctionArn": { "type": "string" }, "InvocationType": { "type": "string" }, "TopicArn": { "type": "string" } }, "required": [ "FunctionArn" ], "type": "object" }, "AWS::SES::ReceiptRule.Rule": { "additionalProperties": false, "properties": { "Actions": { "items": { "$ref": "#/definitions/AWS::SES::ReceiptRule.Action" }, "type": "array" }, "Enabled": { "type": "boolean" }, "Name": { "type": "string" }, "Recipients": { "items": { "type": "string" }, "type": "array" }, "ScanEnabled": { "type": "boolean" }, "TlsPolicy": { "type": "string" } }, "type": "object" }, "AWS::SES::ReceiptRule.S3Action": { "additionalProperties": false, "properties": { "BucketName": { "type": "string" }, "KmsKeyArn": { "type": "string" }, "ObjectKeyPrefix": { "type": "string" }, "TopicArn": { "type": "string" } }, "required": [ "BucketName" ], "type": "object" }, "AWS::SES::ReceiptRule.SNSAction": { "additionalProperties": false, "properties": { "Encoding": { "type": "string" }, "TopicArn": { "type": "string" } }, "type": "object" }, "AWS::SES::ReceiptRule.StopAction": { "additionalProperties": false, "properties": { "Scope": { "type": "string" }, "TopicArn": { "type": "string" } }, "required": [ "Scope" ], "type": "object" }, "AWS::SES::ReceiptRule.WorkmailAction": { "additionalProperties": false, "properties": { "OrganizationArn": { "type": "string" }, "TopicArn": { "type": "string" } }, "required": [ "OrganizationArn" ], "type": "object" }, "AWS::SES::ReceiptRuleSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "RuleSetName": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::SES::ReceiptRuleSet" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::SES::Template": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Template": { "$ref": "#/definitions/AWS::SES::Template.Template" } }, "type": "object" }, "Type": { "enum": [ "AWS::SES::Template" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::SES::Template.Template": { "additionalProperties": false, "properties": { "HtmlPart": { "type": "string" }, "SubjectPart": { "type": "string" }, "TemplateName": { "type": "string" }, "TextPart": { "type": "string" } }, "type": "object" }, "AWS::SNS::Subscription": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Endpoint": { "type": "string" }, "Protocol": { "type": "string" }, "TopicArn": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::SNS::Subscription" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::SNS::Topic": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DisplayName": { "type": "string" }, "Subscription": { "items": { "$ref": "#/definitions/AWS::SNS::Topic.Subscription" }, "type": "array" }, "TopicName": { "type": "string" } }, "type": "object" }, "Type": { "enum": [ "AWS::SNS::Topic" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::SNS::Topic.Subscription": { "additionalProperties": false, "properties": { "Endpoint": { "type": "string" }, "Protocol": { "type": "string" } }, "required": [ "Endpoint", "Protocol" ], "type": "object" }, "AWS::SNS::TopicPolicy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PolicyDocument": { "type": "object" }, "Topics": { "items": { "type": "string" }, "type": "array" } }, "required": [ "PolicyDocument", "Topics" ], "type": "object" }, "Type": { "enum": [ "AWS::SNS::TopicPolicy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SQS::Queue": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ContentBasedDeduplication": { "type": "boolean" }, "DelaySeconds": { "type": "number" }, "FifoQueue": { "type": "boolean" }, "KmsDataKeyReusePeriodSeconds": { "type": "number" }, "KmsMasterKeyId": { "type": "string" }, "MaximumMessageSize": { "type": "number" }, "MessageRetentionPeriod": { "type": "number" }, "QueueName": { "type": "string" }, "ReceiveMessageWaitTimeSeconds": { "type": "number" }, "RedrivePolicy": { "type": "object" }, "VisibilityTimeout": { "type": "number" } }, "type": "object" }, "Type": { "enum": [ "AWS::SQS::Queue" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::SQS::QueuePolicy": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PolicyDocument": { "type": "object" }, "Queues": { "items": { "type": "string" }, "type": "array" } }, "required": [ "PolicyDocument", "Queues" ], "type": "object" }, "Type": { "enum": [ "AWS::SQS::QueuePolicy" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SSM::Association": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AssociationName": { "type": "string" }, "DocumentVersion": { "type": "string" }, "InstanceId": { "type": "string" }, "Name": { "type": "string" }, "Parameters": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "$ref": "#/definitions/AWS::SSM::Association.ParameterValues" } }, "type": "object" }, "ScheduleExpression": { "type": "string" }, "Targets": { "items": { "$ref": "#/definitions/AWS::SSM::Association.Target" }, "type": "array" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::SSM::Association" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SSM::Association.ParameterValues": { "additionalProperties": false, "properties": { "ParameterValues": { "items": { "type": "string" }, "type": "array" } }, "required": [ "ParameterValues" ], "type": "object" }, "AWS::SSM::Association.Target": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Values": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Key", "Values" ], "type": "object" }, "AWS::SSM::Document": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Content": { "type": "object" }, "DocumentType": { "type": "string" }, "Tags": { "items": { "$ref": "#/definitions/Tag" }, "type": "array" } }, "required": [ "Content" ], "type": "object" }, "Type": { "enum": [ "AWS::SSM::Document" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SSM::MaintenanceWindowTask": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "LoggingInfo": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.LoggingInfo" }, "MaxConcurrency": { "type": "string" }, "MaxErrors": { "type": "string" }, "Name": { "type": "string" }, "Priority": { "type": "number" }, "ServiceRoleArn": { "type": "string" }, "Targets": { "items": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.Target" }, "type": "array" }, "TaskArn": { "type": "string" }, "TaskInvocationParameters": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.TaskInvocationParameters" }, "TaskParameters": { "type": "object" }, "TaskType": { "type": "string" }, "WindowId": { "type": "string" } }, "required": [ "MaxConcurrency", "MaxErrors", "Priority", "ServiceRoleArn", "Targets", "TaskArn", "TaskType" ], "type": "object" }, "Type": { "enum": [ "AWS::SSM::MaintenanceWindowTask" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SSM::MaintenanceWindowTask.LoggingInfo": { "additionalProperties": false, "properties": { "Region": { "type": "string" }, "S3Bucket": { "type": "string" }, "S3Prefix": { "type": "string" } }, "required": [ "Region", "S3Bucket" ], "type": "object" }, "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowAutomationParameters": { "additionalProperties": false, "properties": { "DocumentVersion": { "type": "string" }, "Parameters": { "type": "object" } }, "type": "object" }, "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowLambdaParameters": { "additionalProperties": false, "properties": { "ClientContext": { "type": "string" }, "Payload": { "type": "string" }, "Qualifier": { "type": "string" } }, "type": "object" }, "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowRunCommandParameters": { "additionalProperties": false, "properties": { "Comment": { "type": "string" }, "DocumentHash": { "type": "string" }, "DocumentHashType": { "type": "string" }, "NotificationConfig": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.NotificationConfig" }, "OutputS3BucketName": { "type": "string" }, "OutputS3KeyPrefix": { "type": "string" }, "Parameters": { "type": "object" }, "ServiceRoleArn": { "type": "string" }, "TimeoutSeconds": { "type": "number" } }, "type": "object" }, "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowStepFunctionsParameters": { "additionalProperties": false, "properties": { "Input": { "type": "string" }, "Name": { "type": "string" } }, "type": "object" }, "AWS::SSM::MaintenanceWindowTask.NotificationConfig": { "additionalProperties": false, "properties": { "NotificationArn": { "type": "string" }, "NotificationEvents": { "items": { "type": "string" }, "type": "array" }, "NotificationType": { "type": "string" } }, "required": [ "NotificationArn" ], "type": "object" }, "AWS::SSM::MaintenanceWindowTask.Target": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Values": { "items": { "type": "string" }, "type": "array" } }, "required": [ "Key" ], "type": "object" }, "AWS::SSM::MaintenanceWindowTask.TaskInvocationParameters": { "additionalProperties": false, "properties": { "MaintenanceWindowAutomationParameters": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.MaintenanceWindowAutomationParameters" }, "MaintenanceWindowLambdaParameters": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.MaintenanceWindowLambdaParameters" }, "MaintenanceWindowRunCommandParameters": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.MaintenanceWindowRunCommandParameters" }, "MaintenanceWindowStepFunctionsParameters": { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask.MaintenanceWindowStepFunctionsParameters" } }, "type": "object" }, "AWS::SSM::Parameter": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "AllowedPattern": { "type": "string" }, "Description": { "type": "string" }, "Name": { "type": "string" }, "Type": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Type", "Value" ], "type": "object" }, "Type": { "enum": [ "AWS::SSM::Parameter" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SSM::PatchBaseline": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ApprovalRules": { "$ref": "#/definitions/AWS::SSM::PatchBaseline.RuleGroup" }, "ApprovedPatches": { "items": { "type": "string" }, "type": "array" }, "ApprovedPatchesComplianceLevel": { "type": "string" }, "ApprovedPatchesEnableNonSecurity": { "type": "boolean" }, "Description": { "type": "string" }, "GlobalFilters": { "$ref": "#/definitions/AWS::SSM::PatchBaseline.PatchFilterGroup" }, "Name": { "type": "string" }, "OperatingSystem": { "type": "string" }, "PatchGroups": { "items": { "type": "string" }, "type": "array" }, "RejectedPatches": { "items": { "type": "string" }, "type": "array" }, "Sources": { "items": { "$ref": "#/definitions/AWS::SSM::PatchBaseline.PatchSource" }, "type": "array" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::SSM::PatchBaseline" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::SSM::PatchBaseline.PatchFilter": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Values": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::SSM::PatchBaseline.PatchFilterGroup": { "additionalProperties": false, "properties": { "PatchFilters": { "items": { "$ref": "#/definitions/AWS::SSM::PatchBaseline.PatchFilter" }, "type": "array" } }, "type": "object" }, "AWS::SSM::PatchBaseline.PatchSource": { "additionalProperties": false, "properties": { "Configuration": { "type": "string" }, "Name": { "type": "string" }, "Products": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "AWS::SSM::PatchBaseline.Rule": { "additionalProperties": false, "properties": { "ApproveAfterDays": { "type": "number" }, "ComplianceLevel": { "type": "string" }, "EnableNonSecurity": { "type": "boolean" }, "PatchFilterGroup": { "$ref": "#/definitions/AWS::SSM::PatchBaseline.PatchFilterGroup" } }, "type": "object" }, "AWS::SSM::PatchBaseline.RuleGroup": { "additionalProperties": false, "properties": { "PatchRules": { "items": { "$ref": "#/definitions/AWS::SSM::PatchBaseline.Rule" }, "type": "array" } }, "type": "object" }, "AWS::Serverless::Api": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CacheClusterEnabled": { "type": "boolean" }, "CacheClusterSize": { "type": "string" }, "DefinitionBody": { "type": "object" }, "DefinitionUri": { "anyOf": [ { "type": [ "string" ] }, { "$ref": "#/definitions/AWS::Serverless::Api.S3Location" } ] }, "Name": { "type": "string" }, "StageName": { "type": "string" }, "Variables": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "required": [ "StageName" ], "type": "object" }, "Type": { "enum": [ "AWS::Serverless::Api" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Serverless::Api.S3Location": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "Key": { "type": "string" }, "Version": { "type": "number" } }, "required": [ "Bucket", "Key", "Version" ], "type": "object" }, "AWS::Serverless::Function": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "CodeUri": { "anyOf": [ { "type": [ "string" ] }, { "$ref": "#/definitions/AWS::Serverless::Function.S3Location" } ] }, "DeadLetterQueue": { "$ref": "#/definitions/AWS::Serverless::Function.DeadLetterQueue" }, "Description": { "type": "string" }, "Environment": { "$ref": "#/definitions/AWS::Serverless::Function.FunctionEnvironment" }, "Events": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "$ref": "#/definitions/AWS::Serverless::Function.EventSource" } }, "type": "object" }, "FunctionName": { "type": "string" }, "Handler": { "type": "string" }, "KmsKeyArn": { "type": "string" }, "MemorySize": { "type": "number" }, "Policies": { "anyOf": [ { "type": [ "string" ] }, { "items": { "type": "string" }, "type": "array" }, { "$ref": "#/definitions/AWS::Serverless::Function.IAMPolicyDocument" }, { "items": { "$ref": "#/definitions/AWS::Serverless::Function.IAMPolicyDocument" }, "type": "array" } ] }, "Role": { "type": "string" }, "Runtime": { "type": "string" }, "Tags": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" }, "Timeout": { "type": "number" }, "Tracing": { "type": "string" }, "VpcConfig": { "$ref": "#/definitions/AWS::Serverless::Function.VpcConfig" } }, "required": [ "CodeUri", "Handler", "Runtime" ], "type": "object" }, "Type": { "enum": [ "AWS::Serverless::Function" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::Serverless::Function.AlexaSkillEvent": { "additionalProperties": false, "properties": { "Variables": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "type": "object" }, "AWS::Serverless::Function.ApiEvent": { "additionalProperties": false, "properties": { "Method": { "type": "string" }, "Path": { "type": "string" }, "RestApiId": { "type": "string" } }, "required": [ "Method", "Path" ], "type": "object" }, "AWS::Serverless::Function.CloudWatchEventEvent": { "additionalProperties": false, "properties": { "Input": { "type": "string" }, "InputPath": { "type": "string" }, "Pattern": { "type": "object" } }, "required": [ "Pattern" ], "type": "object" }, "AWS::Serverless::Function.DeadLetterQueue": { "additionalProperties": false, "properties": { "TargetArn": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "TargetArn", "Type" ], "type": "object" }, "AWS::Serverless::Function.DynamoDBEvent": { "additionalProperties": false, "properties": { "BatchSize": { "type": "number" }, "StartingPosition": { "type": "string" }, "Stream": { "type": "string" } }, "required": [ "BatchSize", "StartingPosition", "Stream" ], "type": "object" }, "AWS::Serverless::Function.EventSource": { "additionalProperties": false, "properties": { "Properties": { "anyOf": [ { "$ref": "#/definitions/AWS::Serverless::Function.S3Event" }, { "$ref": "#/definitions/AWS::Serverless::Function.SNSEvent" }, { "$ref": "#/definitions/AWS::Serverless::Function.KinesisEvent" }, { "$ref": "#/definitions/AWS::Serverless::Function.DynamoDBEvent" }, { "$ref": "#/definitions/AWS::Serverless::Function.ApiEvent" }, { "$ref": "#/definitions/AWS::Serverless::Function.ScheduleEvent" }, { "$ref": "#/definitions/AWS::Serverless::Function.CloudWatchEventEvent" }, { "$ref": "#/definitions/AWS::Serverless::Function.IoTRuleEvent" }, { "$ref": "#/definitions/AWS::Serverless::Function.AlexaSkillEvent" } ] }, "Type": { "type": "string" } }, "required": [ "Properties", "Type" ], "type": "object" }, "AWS::Serverless::Function.FunctionEnvironment": { "additionalProperties": false, "properties": { "Variables": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "string" } }, "type": "object" } }, "required": [ "Variables" ], "type": "object" }, "AWS::Serverless::Function.IAMPolicyDocument": { "additionalProperties": false, "properties": { "Statement": { "type": "object" } }, "required": [ "Statement" ], "type": "object" }, "AWS::Serverless::Function.IoTRuleEvent": { "additionalProperties": false, "properties": { "AwsIotSqlVersion": { "type": "string" }, "Sql": { "type": "string" } }, "required": [ "Sql" ], "type": "object" }, "AWS::Serverless::Function.KinesisEvent": { "additionalProperties": false, "properties": { "BatchSize": { "type": "number" }, "StartingPosition": { "type": "string" }, "Stream": { "type": "string" } }, "required": [ "StartingPosition", "Stream" ], "type": "object" }, "AWS::Serverless::Function.S3Event": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "Events": { "anyOf": [ { "type": [ "string" ] }, { "items": { "type": "string" }, "type": "array" } ] }, "Filter": { "$ref": "#/definitions/AWS::Serverless::Function.S3NotificationFilter" } }, "required": [ "Bucket", "Events" ], "type": "object" }, "AWS::Serverless::Function.S3Location": { "additionalProperties": false, "properties": { "Bucket": { "type": "string" }, "Key": { "type": "string" }, "Version": { "type": "number" } }, "required": [ "Bucket", "Key", "Version" ], "type": "object" }, "AWS::Serverless::Function.S3NotificationFilter": { "additionalProperties": false, "properties": { "S3Key": { "type": "string" } }, "required": [ "S3Key" ], "type": "object" }, "AWS::Serverless::Function.SNSEvent": { "additionalProperties": false, "properties": { "Topic": { "type": "string" } }, "required": [ "Topic" ], "type": "object" }, "AWS::Serverless::Function.ScheduleEvent": { "additionalProperties": false, "properties": { "Input": { "type": "string" }, "Schedule": { "type": "string" } }, "required": [ "Schedule" ], "type": "object" }, "AWS::Serverless::Function.VpcConfig": { "additionalProperties": false, "properties": { "SecurityGroupIds": { "items": { "type": "string" }, "type": "array" }, "SubnetIds": { "items": { "type": "string" }, "type": "array" } }, "required": [ "SecurityGroupIds", "SubnetIds" ], "type": "object" }, "AWS::Serverless::SimpleTable": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "PrimaryKey": { "$ref": "#/definitions/AWS::Serverless::SimpleTable.PrimaryKey" }, "ProvisionedThroughput": { "$ref": "#/definitions/AWS::Serverless::SimpleTable.ProvisionedThroughput" } }, "type": "object" }, "Type": { "enum": [ "AWS::Serverless::SimpleTable" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Serverless::SimpleTable.PrimaryKey": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::Serverless::SimpleTable.ProvisionedThroughput": { "additionalProperties": false, "properties": { "ReadCapacityUnits": { "type": "number" }, "WriteCapacityUnits": { "type": "number" } }, "required": [ "WriteCapacityUnits" ], "type": "object" }, "AWS::ServiceDiscovery::Instance": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "InstanceAttributes": { "type": "object" }, "InstanceId": { "type": "string" }, "ServiceId": { "type": "string" } }, "required": [ "InstanceAttributes", "ServiceId" ], "type": "object" }, "Type": { "enum": [ "AWS::ServiceDiscovery::Instance" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ServiceDiscovery::PrivateDnsNamespace": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Name": { "type": "string" }, "Vpc": { "type": "string" } }, "required": [ "Name", "Vpc" ], "type": "object" }, "Type": { "enum": [ "AWS::ServiceDiscovery::PrivateDnsNamespace" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ServiceDiscovery::PublicDnsNamespace": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::ServiceDiscovery::PublicDnsNamespace" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ServiceDiscovery::Service": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Description": { "type": "string" }, "DnsConfig": { "$ref": "#/definitions/AWS::ServiceDiscovery::Service.DnsConfig" }, "HealthCheckConfig": { "$ref": "#/definitions/AWS::ServiceDiscovery::Service.HealthCheckConfig" }, "Name": { "type": "string" } }, "required": [ "DnsConfig" ], "type": "object" }, "Type": { "enum": [ "AWS::ServiceDiscovery::Service" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::ServiceDiscovery::Service.DnsConfig": { "additionalProperties": false, "properties": { "DnsRecords": { "items": { "$ref": "#/definitions/AWS::ServiceDiscovery::Service.DnsRecord" }, "type": "array" }, "NamespaceId": { "type": "string" } }, "required": [ "DnsRecords", "NamespaceId" ], "type": "object" }, "AWS::ServiceDiscovery::Service.DnsRecord": { "additionalProperties": false, "properties": { "TTL": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "TTL", "Type" ], "type": "object" }, "AWS::ServiceDiscovery::Service.HealthCheckConfig": { "additionalProperties": false, "properties": { "FailureThreshold": { "type": "number" }, "ResourcePath": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::StepFunctions::Activity": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::StepFunctions::Activity" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::StepFunctions::StateMachine": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DefinitionString": { "type": "string" }, "RoleArn": { "type": "string" }, "StateMachineName": { "type": "string" } }, "required": [ "DefinitionString", "RoleArn" ], "type": "object" }, "Type": { "enum": [ "AWS::StepFunctions::StateMachine" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::ByteMatchSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ByteMatchTuples": { "items": { "$ref": "#/definitions/AWS::WAF::ByteMatchSet.ByteMatchTuple" }, "type": "array" }, "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAF::ByteMatchSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::ByteMatchSet.ByteMatchTuple": { "additionalProperties": false, "properties": { "FieldToMatch": { "$ref": "#/definitions/AWS::WAF::ByteMatchSet.FieldToMatch" }, "PositionalConstraint": { "type": "string" }, "TargetString": { "type": "string" }, "TargetStringBase64": { "type": "string" }, "TextTransformation": { "type": "string" } }, "required": [ "FieldToMatch", "PositionalConstraint", "TextTransformation" ], "type": "object" }, "AWS::WAF::ByteMatchSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAF::IPSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "IPSetDescriptors": { "items": { "$ref": "#/definitions/AWS::WAF::IPSet.IPSetDescriptor" }, "type": "array" }, "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAF::IPSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::IPSet.IPSetDescriptor": { "additionalProperties": false, "properties": { "Type": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Type", "Value" ], "type": "object" }, "AWS::WAF::Rule": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "MetricName": { "type": "string" }, "Name": { "type": "string" }, "Predicates": { "items": { "$ref": "#/definitions/AWS::WAF::Rule.Predicate" }, "type": "array" } }, "required": [ "MetricName", "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAF::Rule" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::Rule.Predicate": { "additionalProperties": false, "properties": { "DataId": { "type": "string" }, "Negated": { "type": "boolean" }, "Type": { "type": "string" } }, "required": [ "DataId", "Negated", "Type" ], "type": "object" }, "AWS::WAF::SizeConstraintSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "SizeConstraints": { "items": { "$ref": "#/definitions/AWS::WAF::SizeConstraintSet.SizeConstraint" }, "type": "array" } }, "required": [ "Name", "SizeConstraints" ], "type": "object" }, "Type": { "enum": [ "AWS::WAF::SizeConstraintSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::SizeConstraintSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAF::SizeConstraintSet.SizeConstraint": { "additionalProperties": false, "properties": { "ComparisonOperator": { "type": "string" }, "FieldToMatch": { "$ref": "#/definitions/AWS::WAF::SizeConstraintSet.FieldToMatch" }, "Size": { "type": "number" }, "TextTransformation": { "type": "string" } }, "required": [ "ComparisonOperator", "FieldToMatch", "Size", "TextTransformation" ], "type": "object" }, "AWS::WAF::SqlInjectionMatchSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "SqlInjectionMatchTuples": { "items": { "$ref": "#/definitions/AWS::WAF::SqlInjectionMatchSet.SqlInjectionMatchTuple" }, "type": "array" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAF::SqlInjectionMatchSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::SqlInjectionMatchSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAF::SqlInjectionMatchSet.SqlInjectionMatchTuple": { "additionalProperties": false, "properties": { "FieldToMatch": { "$ref": "#/definitions/AWS::WAF::SqlInjectionMatchSet.FieldToMatch" }, "TextTransformation": { "type": "string" } }, "required": [ "FieldToMatch", "TextTransformation" ], "type": "object" }, "AWS::WAF::WebACL": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DefaultAction": { "$ref": "#/definitions/AWS::WAF::WebACL.WafAction" }, "MetricName": { "type": "string" }, "Name": { "type": "string" }, "Rules": { "items": { "$ref": "#/definitions/AWS::WAF::WebACL.ActivatedRule" }, "type": "array" } }, "required": [ "DefaultAction", "MetricName", "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAF::WebACL" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::WebACL.ActivatedRule": { "additionalProperties": false, "properties": { "Action": { "$ref": "#/definitions/AWS::WAF::WebACL.WafAction" }, "Priority": { "type": "number" }, "RuleId": { "type": "string" } }, "required": [ "Action", "Priority", "RuleId" ], "type": "object" }, "AWS::WAF::WebACL.WafAction": { "additionalProperties": false, "properties": { "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAF::XssMatchSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "XssMatchTuples": { "items": { "$ref": "#/definitions/AWS::WAF::XssMatchSet.XssMatchTuple" }, "type": "array" } }, "required": [ "Name", "XssMatchTuples" ], "type": "object" }, "Type": { "enum": [ "AWS::WAF::XssMatchSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAF::XssMatchSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAF::XssMatchSet.XssMatchTuple": { "additionalProperties": false, "properties": { "FieldToMatch": { "$ref": "#/definitions/AWS::WAF::XssMatchSet.FieldToMatch" }, "TextTransformation": { "type": "string" } }, "required": [ "FieldToMatch", "TextTransformation" ], "type": "object" }, "AWS::WAFRegional::ByteMatchSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ByteMatchTuples": { "items": { "$ref": "#/definitions/AWS::WAFRegional::ByteMatchSet.ByteMatchTuple" }, "type": "array" }, "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::ByteMatchSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::ByteMatchSet.ByteMatchTuple": { "additionalProperties": false, "properties": { "FieldToMatch": { "$ref": "#/definitions/AWS::WAFRegional::ByteMatchSet.FieldToMatch" }, "PositionalConstraint": { "type": "string" }, "TargetString": { "type": "string" }, "TargetStringBase64": { "type": "string" }, "TextTransformation": { "type": "string" } }, "required": [ "FieldToMatch", "PositionalConstraint", "TextTransformation" ], "type": "object" }, "AWS::WAFRegional::ByteMatchSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAFRegional::IPSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "IPSetDescriptors": { "items": { "$ref": "#/definitions/AWS::WAFRegional::IPSet.IPSetDescriptor" }, "type": "array" }, "Name": { "type": "string" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::IPSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::IPSet.IPSetDescriptor": { "additionalProperties": false, "properties": { "Type": { "type": "string" }, "Value": { "type": "string" } }, "required": [ "Type", "Value" ], "type": "object" }, "AWS::WAFRegional::Rule": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "MetricName": { "type": "string" }, "Name": { "type": "string" }, "Predicates": { "items": { "$ref": "#/definitions/AWS::WAFRegional::Rule.Predicate" }, "type": "array" } }, "required": [ "MetricName", "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::Rule" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::Rule.Predicate": { "additionalProperties": false, "properties": { "DataId": { "type": "string" }, "Negated": { "type": "boolean" }, "Type": { "type": "string" } }, "required": [ "DataId", "Negated", "Type" ], "type": "object" }, "AWS::WAFRegional::SizeConstraintSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "SizeConstraints": { "items": { "$ref": "#/definitions/AWS::WAFRegional::SizeConstraintSet.SizeConstraint" }, "type": "array" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::SizeConstraintSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::SizeConstraintSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAFRegional::SizeConstraintSet.SizeConstraint": { "additionalProperties": false, "properties": { "ComparisonOperator": { "type": "string" }, "FieldToMatch": { "$ref": "#/definitions/AWS::WAFRegional::SizeConstraintSet.FieldToMatch" }, "Size": { "type": "number" }, "TextTransformation": { "type": "string" } }, "required": [ "ComparisonOperator", "FieldToMatch", "Size", "TextTransformation" ], "type": "object" }, "AWS::WAFRegional::SqlInjectionMatchSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "SqlInjectionMatchTuples": { "items": { "$ref": "#/definitions/AWS::WAFRegional::SqlInjectionMatchSet.SqlInjectionMatchTuple" }, "type": "array" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::SqlInjectionMatchSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::SqlInjectionMatchSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAFRegional::SqlInjectionMatchSet.SqlInjectionMatchTuple": { "additionalProperties": false, "properties": { "FieldToMatch": { "$ref": "#/definitions/AWS::WAFRegional::SqlInjectionMatchSet.FieldToMatch" }, "TextTransformation": { "type": "string" } }, "required": [ "FieldToMatch", "TextTransformation" ], "type": "object" }, "AWS::WAFRegional::WebACL": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "DefaultAction": { "$ref": "#/definitions/AWS::WAFRegional::WebACL.Action" }, "MetricName": { "type": "string" }, "Name": { "type": "string" }, "Rules": { "items": { "$ref": "#/definitions/AWS::WAFRegional::WebACL.Rule" }, "type": "array" } }, "required": [ "DefaultAction", "MetricName", "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::WebACL" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::WebACL.Action": { "additionalProperties": false, "properties": { "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAFRegional::WebACL.Rule": { "additionalProperties": false, "properties": { "Action": { "$ref": "#/definitions/AWS::WAFRegional::WebACL.Action" }, "Priority": { "type": "number" }, "RuleId": { "type": "string" } }, "required": [ "Action", "Priority", "RuleId" ], "type": "object" }, "AWS::WAFRegional::WebACLAssociation": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "ResourceArn": { "type": "string" }, "WebACLId": { "type": "string" } }, "required": [ "ResourceArn", "WebACLId" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::WebACLAssociation" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::XssMatchSet": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "Name": { "type": "string" }, "XssMatchTuples": { "items": { "$ref": "#/definitions/AWS::WAFRegional::XssMatchSet.XssMatchTuple" }, "type": "array" } }, "required": [ "Name" ], "type": "object" }, "Type": { "enum": [ "AWS::WAFRegional::XssMatchSet" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "AWS::WAFRegional::XssMatchSet.FieldToMatch": { "additionalProperties": false, "properties": { "Data": { "type": "string" }, "Type": { "type": "string" } }, "required": [ "Type" ], "type": "object" }, "AWS::WAFRegional::XssMatchSet.XssMatchTuple": { "additionalProperties": false, "properties": { "FieldToMatch": { "$ref": "#/definitions/AWS::WAFRegional::XssMatchSet.FieldToMatch" }, "TextTransformation": { "type": "string" } }, "required": [ "FieldToMatch", "TextTransformation" ], "type": "object" }, "AWS::WorkSpaces::Workspace": { "additionalProperties": false, "properties": { "DeletionPolicy": { "enum": [ "Delete", "Retain", "Snapshot" ], "type": "string" }, "DependsOn": { "anyOf": [ { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, { "items": { "pattern": "^[a-zA-Z0-9]+$", "type": "string" }, "type": "array" } ] }, "Metadata": { "type": "object" }, "Properties": { "additionalProperties": false, "properties": { "BundleId": { "type": "string" }, "DirectoryId": { "type": "string" }, "RootVolumeEncryptionEnabled": { "type": "boolean" }, "UserName": { "type": "string" }, "UserVolumeEncryptionEnabled": { "type": "boolean" }, "VolumeEncryptionKey": { "type": "string" } }, "required": [ "BundleId", "DirectoryId", "UserName" ], "type": "object" }, "Type": { "enum": [ "AWS::WorkSpaces::Workspace" ], "type": "string" } }, "required": [ "Type", "Properties" ], "type": "object" }, "Parameter": { "additionalProperties": false, "properties": { "AllowedPattern": { "type": "string" }, "AllowedValues": { "type": "array" }, "ConstraintDescription": { "type": "string" }, "Default": { "type": "string" }, "Description": { "type": "string" }, "MaxLength": { "type": "string" }, "MaxValue": { "type": "string" }, "MinLength": { "type": "string" }, "MinValue": { "type": "string" }, "NoEcho": { "type": [ "string", "boolean" ] }, "Type": { "enum": [ "String", "Number", "List\u003cNumber\u003e", "CommaDelimitedList", "AWS::EC2::AvailabilityZone::Name", "AWS::EC2::Image::Id", "AWS::EC2::Instance::Id", "AWS::EC2::KeyPair::KeyName", "AWS::EC2::SecurityGroup::GroupName", "AWS::EC2::SecurityGroup::Id", "AWS::EC2::Subnet::Id", "AWS::EC2::Volume::Id", "AWS::EC2::VPC::Id", "AWS::Route53::HostedZone::Id", "List\u003cAWS::EC2::AvailabilityZone::Name\u003e", "List\u003cAWS::EC2::Image::Id\u003e", "List\u003cAWS::EC2::Instance::Id\u003e", "List\u003cAWS::EC2::SecurityGroup::GroupName\u003e", "List\u003cAWS::EC2::SecurityGroup::Id\u003e", "List\u003cAWS::EC2::Subnet::Id\u003e", "List\u003cAWS::EC2::Volume::Id\u003e", "List\u003cAWS::EC2::VPC::Id\u003e", "List\u003cAWS::Route53::HostedZone::Id\u003e", "List\u003cString\u003e" ], "type": "string" } }, "required": [ "Type" ], "type": "object" }, "Tag": { "additionalProperties": false, "properties": { "Key": { "type": "string" }, "Value": { "type": "string" } }, "type": "object" } }, "properties": { "AWSTemplateFormatVersion": { "enum": [ "2010-09-09" ], "type": "string" }, "Conditions": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "object" } }, "type": "object" }, "Description": { "description": "Template description", "maxLength": 1024, "type": "string" }, "Mappings": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "object" } }, "type": "object" }, "Metadata": { "type": "object" }, "Outputs": { "additionalProperties": false, "maxProperties": 60, "minProperties": 1, "patternProperties": { "^[a-zA-Z0-9]+$": { "type": "object" } }, "type": "object" }, "Parameters": { "additionalProperties": false, "maxProperties": 50, "patternProperties": { "^[a-zA-Z0-9]+$": { "$ref": "#/definitions/Parameter" } }, "type": "object" }, "Resources": { "additionalProperties": false, "patternProperties": { "^[a-zA-Z0-9]+$": { "anyOf": [ { "$ref": "#/definitions/AWS::ApiGateway::Account" }, { "$ref": "#/definitions/AWS::ApiGateway::ApiKey" }, { "$ref": "#/definitions/AWS::ApiGateway::Authorizer" }, { "$ref": "#/definitions/AWS::ApiGateway::BasePathMapping" }, { "$ref": "#/definitions/AWS::ApiGateway::ClientCertificate" }, { "$ref": "#/definitions/AWS::ApiGateway::Deployment" }, { "$ref": "#/definitions/AWS::ApiGateway::DocumentationPart" }, { "$ref": "#/definitions/AWS::ApiGateway::DocumentationVersion" }, { "$ref": "#/definitions/AWS::ApiGateway::DomainName" }, { "$ref": "#/definitions/AWS::ApiGateway::GatewayResponse" }, { "$ref": "#/definitions/AWS::ApiGateway::Method" }, { "$ref": "#/definitions/AWS::ApiGateway::Model" }, { "$ref": "#/definitions/AWS::ApiGateway::RequestValidator" }, { "$ref": "#/definitions/AWS::ApiGateway::Resource" }, { "$ref": "#/definitions/AWS::ApiGateway::RestApi" }, { "$ref": "#/definitions/AWS::ApiGateway::Stage" }, { "$ref": "#/definitions/AWS::ApiGateway::UsagePlan" }, { "$ref": "#/definitions/AWS::ApiGateway::UsagePlanKey" }, { "$ref": "#/definitions/AWS::ApiGateway::VpcLink" }, { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalableTarget" }, { "$ref": "#/definitions/AWS::ApplicationAutoScaling::ScalingPolicy" }, { "$ref": "#/definitions/AWS::Athena::NamedQuery" }, { "$ref": "#/definitions/AWS::AutoScaling::AutoScalingGroup" }, { "$ref": "#/definitions/AWS::AutoScaling::LaunchConfiguration" }, { "$ref": "#/definitions/AWS::AutoScaling::LifecycleHook" }, { "$ref": "#/definitions/AWS::AutoScaling::ScalingPolicy" }, { "$ref": "#/definitions/AWS::AutoScaling::ScheduledAction" }, { "$ref": "#/definitions/AWS::Batch::ComputeEnvironment" }, { "$ref": "#/definitions/AWS::Batch::JobDefinition" }, { "$ref": "#/definitions/AWS::Batch::JobQueue" }, { "$ref": "#/definitions/AWS::CertificateManager::Certificate" }, { "$ref": "#/definitions/AWS::Cloud9::EnvironmentEC2" }, { "$ref": "#/definitions/AWS::CloudFormation::CustomResource" }, { "$ref": "#/definitions/AWS::CloudFormation::Stack" }, { "$ref": "#/definitions/AWS::CloudFormation::WaitCondition" }, { "$ref": "#/definitions/AWS::CloudFormation::WaitConditionHandle" }, { "$ref": "#/definitions/AWS::CloudFront::CloudFrontOriginAccessIdentity" }, { "$ref": "#/definitions/AWS::CloudFront::Distribution" }, { "$ref": "#/definitions/AWS::CloudFront::StreamingDistribution" }, { "$ref": "#/definitions/AWS::CloudTrail::Trail" }, { "$ref": "#/definitions/AWS::CloudWatch::Alarm" }, { "$ref": "#/definitions/AWS::CloudWatch::Dashboard" }, { "$ref": "#/definitions/AWS::CodeBuild::Project" }, { "$ref": "#/definitions/AWS::CodeCommit::Repository" }, { "$ref": "#/definitions/AWS::CodeDeploy::Application" }, { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentConfig" }, { "$ref": "#/definitions/AWS::CodeDeploy::DeploymentGroup" }, { "$ref": "#/definitions/AWS::CodePipeline::CustomActionType" }, { "$ref": "#/definitions/AWS::CodePipeline::Pipeline" }, { "$ref": "#/definitions/AWS::Cognito::IdentityPool" }, { "$ref": "#/definitions/AWS::Cognito::IdentityPoolRoleAttachment" }, { "$ref": "#/definitions/AWS::Cognito::UserPool" }, { "$ref": "#/definitions/AWS::Cognito::UserPoolClient" }, { "$ref": "#/definitions/AWS::Cognito::UserPoolGroup" }, { "$ref": "#/definitions/AWS::Cognito::UserPoolUser" }, { "$ref": "#/definitions/AWS::Cognito::UserPoolUserToGroupAttachment" }, { "$ref": "#/definitions/AWS::Config::ConfigRule" }, { "$ref": "#/definitions/AWS::Config::ConfigurationRecorder" }, { "$ref": "#/definitions/AWS::Config::DeliveryChannel" }, { "$ref": "#/definitions/AWS::DAX::Cluster" }, { "$ref": "#/definitions/AWS::DAX::ParameterGroup" }, { "$ref": "#/definitions/AWS::DAX::SubnetGroup" }, { "$ref": "#/definitions/AWS::DMS::Certificate" }, { "$ref": "#/definitions/AWS::DMS::Endpoint" }, { "$ref": "#/definitions/AWS::DMS::EventSubscription" }, { "$ref": "#/definitions/AWS::DMS::ReplicationInstance" }, { "$ref": "#/definitions/AWS::DMS::ReplicationSubnetGroup" }, { "$ref": "#/definitions/AWS::DMS::ReplicationTask" }, { "$ref": "#/definitions/AWS::DataPipeline::Pipeline" }, { "$ref": "#/definitions/AWS::DirectoryService::MicrosoftAD" }, { "$ref": "#/definitions/AWS::DirectoryService::SimpleAD" }, { "$ref": "#/definitions/AWS::DynamoDB::Table" }, { "$ref": "#/definitions/AWS::EC2::CustomerGateway" }, { "$ref": "#/definitions/AWS::EC2::DHCPOptions" }, { "$ref": "#/definitions/AWS::EC2::EIP" }, { "$ref": "#/definitions/AWS::EC2::EIPAssociation" }, { "$ref": "#/definitions/AWS::EC2::EgressOnlyInternetGateway" }, { "$ref": "#/definitions/AWS::EC2::FlowLog" }, { "$ref": "#/definitions/AWS::EC2::Host" }, { "$ref": "#/definitions/AWS::EC2::Instance" }, { "$ref": "#/definitions/AWS::EC2::InternetGateway" }, { "$ref": "#/definitions/AWS::EC2::NatGateway" }, { "$ref": "#/definitions/AWS::EC2::NetworkAcl" }, { "$ref": "#/definitions/AWS::EC2::NetworkAclEntry" }, { "$ref": "#/definitions/AWS::EC2::NetworkInterface" }, { "$ref": "#/definitions/AWS::EC2::NetworkInterfaceAttachment" }, { "$ref": "#/definitions/AWS::EC2::NetworkInterfacePermission" }, { "$ref": "#/definitions/AWS::EC2::PlacementGroup" }, { "$ref": "#/definitions/AWS::EC2::Route" }, { "$ref": "#/definitions/AWS::EC2::RouteTable" }, { "$ref": "#/definitions/AWS::EC2::SecurityGroup" }, { "$ref": "#/definitions/AWS::EC2::SecurityGroupEgress" }, { "$ref": "#/definitions/AWS::EC2::SecurityGroupIngress" }, { "$ref": "#/definitions/AWS::EC2::SpotFleet" }, { "$ref": "#/definitions/AWS::EC2::Subnet" }, { "$ref": "#/definitions/AWS::EC2::SubnetCidrBlock" }, { "$ref": "#/definitions/AWS::EC2::SubnetNetworkAclAssociation" }, { "$ref": "#/definitions/AWS::EC2::SubnetRouteTableAssociation" }, { "$ref": "#/definitions/AWS::EC2::TrunkInterfaceAssociation" }, { "$ref": "#/definitions/AWS::EC2::VPC" }, { "$ref": "#/definitions/AWS::EC2::VPCCidrBlock" }, { "$ref": "#/definitions/AWS::EC2::VPCDHCPOptionsAssociation" }, { "$ref": "#/definitions/AWS::EC2::VPCEndpoint" }, { "$ref": "#/definitions/AWS::EC2::VPCGatewayAttachment" }, { "$ref": "#/definitions/AWS::EC2::VPCPeeringConnection" }, { "$ref": "#/definitions/AWS::EC2::VPNConnection" }, { "$ref": "#/definitions/AWS::EC2::VPNConnectionRoute" }, { "$ref": "#/definitions/AWS::EC2::VPNGateway" }, { "$ref": "#/definitions/AWS::EC2::VPNGatewayRoutePropagation" }, { "$ref": "#/definitions/AWS::EC2::Volume" }, { "$ref": "#/definitions/AWS::EC2::VolumeAttachment" }, { "$ref": "#/definitions/AWS::ECR::Repository" }, { "$ref": "#/definitions/AWS::ECS::Cluster" }, { "$ref": "#/definitions/AWS::ECS::Service" }, { "$ref": "#/definitions/AWS::ECS::TaskDefinition" }, { "$ref": "#/definitions/AWS::EFS::FileSystem" }, { "$ref": "#/definitions/AWS::EFS::MountTarget" }, { "$ref": "#/definitions/AWS::EMR::Cluster" }, { "$ref": "#/definitions/AWS::EMR::InstanceFleetConfig" }, { "$ref": "#/definitions/AWS::EMR::InstanceGroupConfig" }, { "$ref": "#/definitions/AWS::EMR::SecurityConfiguration" }, { "$ref": "#/definitions/AWS::EMR::Step" }, { "$ref": "#/definitions/AWS::ElastiCache::CacheCluster" }, { "$ref": "#/definitions/AWS::ElastiCache::ParameterGroup" }, { "$ref": "#/definitions/AWS::ElastiCache::ReplicationGroup" }, { "$ref": "#/definitions/AWS::ElastiCache::SecurityGroup" }, { "$ref": "#/definitions/AWS::ElastiCache::SecurityGroupIngress" }, { "$ref": "#/definitions/AWS::ElastiCache::SubnetGroup" }, { "$ref": "#/definitions/AWS::ElasticBeanstalk::Application" }, { "$ref": "#/definitions/AWS::ElasticBeanstalk::ApplicationVersion" }, { "$ref": "#/definitions/AWS::ElasticBeanstalk::ConfigurationTemplate" }, { "$ref": "#/definitions/AWS::ElasticBeanstalk::Environment" }, { "$ref": "#/definitions/AWS::ElasticLoadBalancing::LoadBalancer" }, { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::Listener" }, { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::ListenerCertificate" }, { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::ListenerRule" }, { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::LoadBalancer" }, { "$ref": "#/definitions/AWS::ElasticLoadBalancingV2::TargetGroup" }, { "$ref": "#/definitions/AWS::Elasticsearch::Domain" }, { "$ref": "#/definitions/AWS::Events::Rule" }, { "$ref": "#/definitions/AWS::GameLift::Alias" }, { "$ref": "#/definitions/AWS::GameLift::Build" }, { "$ref": "#/definitions/AWS::GameLift::Fleet" }, { "$ref": "#/definitions/AWS::Glue::Classifier" }, { "$ref": "#/definitions/AWS::Glue::Connection" }, { "$ref": "#/definitions/AWS::Glue::Crawler" }, { "$ref": "#/definitions/AWS::Glue::Database" }, { "$ref": "#/definitions/AWS::Glue::DevEndpoint" }, { "$ref": "#/definitions/AWS::Glue::Job" }, { "$ref": "#/definitions/AWS::Glue::Partition" }, { "$ref": "#/definitions/AWS::Glue::Table" }, { "$ref": "#/definitions/AWS::Glue::Trigger" }, { "$ref": "#/definitions/AWS::GuardDuty::Detector" }, { "$ref": "#/definitions/AWS::GuardDuty::IPSet" }, { "$ref": "#/definitions/AWS::GuardDuty::Master" }, { "$ref": "#/definitions/AWS::GuardDuty::Member" }, { "$ref": "#/definitions/AWS::GuardDuty::ThreatIntelSet" }, { "$ref": "#/definitions/AWS::IAM::AccessKey" }, { "$ref": "#/definitions/AWS::IAM::Group" }, { "$ref": "#/definitions/AWS::IAM::InstanceProfile" }, { "$ref": "#/definitions/AWS::IAM::ManagedPolicy" }, { "$ref": "#/definitions/AWS::IAM::Policy" }, { "$ref": "#/definitions/AWS::IAM::Role" }, { "$ref": "#/definitions/AWS::IAM::User" }, { "$ref": "#/definitions/AWS::IAM::UserToGroupAddition" }, { "$ref": "#/definitions/AWS::Inspector::AssessmentTarget" }, { "$ref": "#/definitions/AWS::Inspector::AssessmentTemplate" }, { "$ref": "#/definitions/AWS::Inspector::ResourceGroup" }, { "$ref": "#/definitions/AWS::IoT::Certificate" }, { "$ref": "#/definitions/AWS::IoT::Policy" }, { "$ref": "#/definitions/AWS::IoT::PolicyPrincipalAttachment" }, { "$ref": "#/definitions/AWS::IoT::Thing" }, { "$ref": "#/definitions/AWS::IoT::ThingPrincipalAttachment" }, { "$ref": "#/definitions/AWS::IoT::TopicRule" }, { "$ref": "#/definitions/AWS::KMS::Alias" }, { "$ref": "#/definitions/AWS::KMS::Key" }, { "$ref": "#/definitions/AWS::Kinesis::Stream" }, { "$ref": "#/definitions/AWS::KinesisAnalytics::Application" }, { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationOutput" }, { "$ref": "#/definitions/AWS::KinesisAnalytics::ApplicationReferenceDataSource" }, { "$ref": "#/definitions/AWS::KinesisFirehose::DeliveryStream" }, { "$ref": "#/definitions/AWS::Lambda::Alias" }, { "$ref": "#/definitions/AWS::Lambda::EventSourceMapping" }, { "$ref": "#/definitions/AWS::Lambda::Function" }, { "$ref": "#/definitions/AWS::Lambda::Permission" }, { "$ref": "#/definitions/AWS::Lambda::Version" }, { "$ref": "#/definitions/AWS::Logs::Destination" }, { "$ref": "#/definitions/AWS::Logs::LogGroup" }, { "$ref": "#/definitions/AWS::Logs::LogStream" }, { "$ref": "#/definitions/AWS::Logs::MetricFilter" }, { "$ref": "#/definitions/AWS::Logs::SubscriptionFilter" }, { "$ref": "#/definitions/AWS::OpsWorks::App" }, { "$ref": "#/definitions/AWS::OpsWorks::ElasticLoadBalancerAttachment" }, { "$ref": "#/definitions/AWS::OpsWorks::Instance" }, { "$ref": "#/definitions/AWS::OpsWorks::Layer" }, { "$ref": "#/definitions/AWS::OpsWorks::Stack" }, { "$ref": "#/definitions/AWS::OpsWorks::UserProfile" }, { "$ref": "#/definitions/AWS::OpsWorks::Volume" }, { "$ref": "#/definitions/AWS::RDS::DBCluster" }, { "$ref": "#/definitions/AWS::RDS::DBClusterParameterGroup" }, { "$ref": "#/definitions/AWS::RDS::DBInstance" }, { "$ref": "#/definitions/AWS::RDS::DBParameterGroup" }, { "$ref": "#/definitions/AWS::RDS::DBSecurityGroup" }, { "$ref": "#/definitions/AWS::RDS::DBSecurityGroupIngress" }, { "$ref": "#/definitions/AWS::RDS::DBSubnetGroup" }, { "$ref": "#/definitions/AWS::RDS::EventSubscription" }, { "$ref": "#/definitions/AWS::RDS::OptionGroup" }, { "$ref": "#/definitions/AWS::Redshift::Cluster" }, { "$ref": "#/definitions/AWS::Redshift::ClusterParameterGroup" }, { "$ref": "#/definitions/AWS::Redshift::ClusterSecurityGroup" }, { "$ref": "#/definitions/AWS::Redshift::ClusterSecurityGroupIngress" }, { "$ref": "#/definitions/AWS::Redshift::ClusterSubnetGroup" }, { "$ref": "#/definitions/AWS::Route53::HealthCheck" }, { "$ref": "#/definitions/AWS::Route53::HostedZone" }, { "$ref": "#/definitions/AWS::Route53::RecordSet" }, { "$ref": "#/definitions/AWS::Route53::RecordSetGroup" }, { "$ref": "#/definitions/AWS::S3::Bucket" }, { "$ref": "#/definitions/AWS::S3::BucketPolicy" }, { "$ref": "#/definitions/AWS::SDB::Domain" }, { "$ref": "#/definitions/AWS::SES::ConfigurationSet" }, { "$ref": "#/definitions/AWS::SES::ConfigurationSetEventDestination" }, { "$ref": "#/definitions/AWS::SES::ReceiptFilter" }, { "$ref": "#/definitions/AWS::SES::ReceiptRule" }, { "$ref": "#/definitions/AWS::SES::ReceiptRuleSet" }, { "$ref": "#/definitions/AWS::SES::Template" }, { "$ref": "#/definitions/AWS::SNS::Subscription" }, { "$ref": "#/definitions/AWS::SNS::Topic" }, { "$ref": "#/definitions/AWS::SNS::TopicPolicy" }, { "$ref": "#/definitions/AWS::SQS::Queue" }, { "$ref": "#/definitions/AWS::SQS::QueuePolicy" }, { "$ref": "#/definitions/AWS::SSM::Association" }, { "$ref": "#/definitions/AWS::SSM::Document" }, { "$ref": "#/definitions/AWS::SSM::MaintenanceWindowTask" }, { "$ref": "#/definitions/AWS::SSM::Parameter" }, { "$ref": "#/definitions/AWS::SSM::PatchBaseline" }, { "$ref": "#/definitions/AWS::Serverless::Api" }, { "$ref": "#/definitions/AWS::Serverless::Function" }, { "$ref": "#/definitions/AWS::Serverless::SimpleTable" }, { "$ref": "#/definitions/AWS::ServiceDiscovery::Instance" }, { "$ref": "#/definitions/AWS::ServiceDiscovery::PrivateDnsNamespace" }, { "$ref": "#/definitions/AWS::ServiceDiscovery::PublicDnsNamespace" }, { "$ref": "#/definitions/AWS::ServiceDiscovery::Service" }, { "$ref": "#/definitions/AWS::StepFunctions::Activity" }, { "$ref": "#/definitions/AWS::StepFunctions::StateMachine" }, { "$ref": "#/definitions/AWS::WAF::ByteMatchSet" }, { "$ref": "#/definitions/AWS::WAF::IPSet" }, { "$ref": "#/definitions/AWS::WAF::Rule" }, { "$ref": "#/definitions/AWS::WAF::SizeConstraintSet" }, { "$ref": "#/definitions/AWS::WAF::SqlInjectionMatchSet" }, { "$ref": "#/definitions/AWS::WAF::WebACL" }, { "$ref": "#/definitions/AWS::WAF::XssMatchSet" }, { "$ref": "#/definitions/AWS::WAFRegional::ByteMatchSet" }, { "$ref": "#/definitions/AWS::WAFRegional::IPSet" }, { "$ref": "#/definitions/AWS::WAFRegional::Rule" }, { "$ref": "#/definitions/AWS::WAFRegional::SizeConstraintSet" }, { "$ref": "#/definitions/AWS::WAFRegional::SqlInjectionMatchSet" }, { "$ref": "#/definitions/AWS::WAFRegional::WebACL" }, { "$ref": "#/definitions/AWS::WAFRegional::WebACLAssociation" }, { "$ref": "#/definitions/AWS::WAFRegional::XssMatchSet" }, { "$ref": "#/definitions/AWS::WorkSpaces::Workspace" } ] } }, "type": "object" }, "Transform": { "enum": [ "AWS::Serverless-2016-10-31" ], "type": "string" } }, "required": [ "Transform", "Resources" ], "type": "object" }`
schema/sam.go
0.629433
0.406626
sam.go
starcoder
package fp2 const mul = ` // Mul sets z to the {{.Name}}-product of x,y, returns z func (z *{{.Name}}) Mul(x, y *{{.Name}}) *{{.Name}} { {{ template "mul" dict "all" . "V1" "x" "V2" "y"}} return z } // MulAssign sets z to the {{.Name}}-product of z,x returns z func (z *{{.Name}}) MulAssign(x *{{.Name}}) *{{.Name}} { {{ template "mul" dict "all" . "V1" "z" "V2" "x"}} return z } {{ define "mul" -}} // (a+bu)*(c+du) == (ac+({{.all.Fp2NonResidue}})*bd) + (ad+bc)u where u^2 == {{.all.Fp2NonResidue}} // Karatsuba: 3 fp multiplications instead of 4 // [1]: ac // [2]: bd // [3]: (a+b)*(c+d) // Then z.A0: [1] + ({{.all.Fp2NonResidue}})*[2] // Then z.A1: [3] - [2] - [1] var ac, bd, cplusd, aplusbcplusd fp.Element ac.Mul(&{{$.V1}}.A0, &{{$.V2}}.A0) // [1]: ac bd.Mul(&{{$.V1}}.A1, &{{$.V2}}.A1) // [2]: bd cplusd.Add(&{{$.V2}}.A0, &{{$.V2}}.A1) // c+d aplusbcplusd.Add(&{{$.V1}}.A0, &{{$.V1}}.A1) // a+b aplusbcplusd.MulAssign(&cplusd) // [3]: (a+b)*(c+d) z.A1.Add(&ac, &bd) // ad+bc, [2] + [1] z.A1.Sub(&aplusbcplusd, &z.A1) // z.A1: [3] - [2] - [1] {{- if eq $.all.Fp2NonResidue "-1" }} z.A0.Sub(&ac, &bd) // z.A0: [1] - [2] {{- else }} MulByNonResidue(&z.A0, &bd) z.A0.AddAssign(&ac) // z.A0: [1] + ({{.all.Fp2NonResidue}})*[2] {{- end -}} {{ end }} // Square sets z to the e2-product of x,x returns z func (z *{{.Name}}) Square(x *{{.Name}}) *{{.Name}} { // (a+bu)^2 == (a^2+({{.Fp2NonResidue}})*b^2) + (2ab)u where u^2 == {{.Fp2NonResidue}} // Complex method: 2 fp multiplications instead of 3 // [1]: ab // [2]: (a+b)*(a+({{.Fp2NonResidue}})*b) // Then z.A0: [2] - ({{.Fp2NonResidue}}+1)*[1] // Then z.A1: 2[1] {{- if eq .Fp2NonResidue "-1" }} // optimize for quadratic nonresidue -1 var aplusb fp.Element var result e2 aplusb.Add(&x.A0, &x.A1) // a+b result.A0.Sub(&x.A0, &x.A1) // a-b result.A0.MulAssign(&aplusb) // [2]: (a+b)*(a-b) result.A1.Mul(&x.A0, &x.A1).Double(&result.A1) // [1]: ab z.Set(&result) {{- else }} var ab, aplusb, ababetab fp.Element MulByNonResidue(&ababetab, &x.A1) ababetab.AddAssign(&x.A0) // a+({{.Fp2NonResidue}})*b aplusb.Add(&x.A0, &x.A1) // a+b ababetab.MulAssign(&aplusb) // [2]: (a+b)*(a+({{.Fp2NonResidue}})*b) ab.Mul(&x.A0, &x.A1) // [1]: ab z.A1.Double(&ab) // z.A1: 2*[1] {{- if eq .Fp2NonResidue "5"}} z.A0.Add(&ab, &z.A1).Double(&z.A0) // (5+1)*ab, optimize for quadratic nonresidue 5 {{- else}} MulByNonResidue(&z.A0, &ab).AddAssign(&ab) // ({{.Fp2NonResidue}}+1)*ab {{- end }} z.A0.Sub(&ababetab, &z.A0) // z.A0: [2] - ({{.Fp2NonResidue}}+1)[1] {{- end }} return z } // MulByNonSquare multiplies an element by (0,1) // TODO deprecate in favor of inlined MulByNonResidue in fp6 package func (z *{{.Name}}) MulByNonSquare(x *{{.Name}}) *{{.Name}} { a := x.A0 MulByNonResidue(&z.A0, &x.A1) z.A1 = a return z } // Inverse sets z to the {{.Name}}-inverse of x, returns z func (z *{{.Name}}) Inverse(x *{{.Name}}) *{{.Name}} { // Algorithm 8 from https://eprint.iacr.org/2010/354.pdf {{- if eq .Fp2NonResidue "-1" }} var a0, a1, t0, t1 fp.Element {{- else }} var a0, a1, t0, t1, t1beta fp.Element {{- end }} a0 = x.A0 // = is slightly faster than Set() a1 = x.A1 // = is slightly faster than Set() t0.Square(&a0) // step 1 t1.Square(&a1) // step 2 {{- if eq .Fp2NonResidue "-1" }} t0.Add(&t0, &t1) // step 3 {{- else }} MulByNonResidue(&t1beta, &t1) t0.SubAssign(&t1beta) // step 3 {{- end }} t1.Inverse(&t0) // step 4 z.A0.Mul(&a0, &t1) // step 5 z.A1.Neg(&a1).MulAssign(&t1) // step 6 return z } // MulByElement multiplies an element in {{.Name}} by an element in fp func (z *{{.Name}}) MulByElement(x *{{.Name}}, y *fp.Element) *{{.Name}} { var yCopy fp.Element yCopy.Set(y) z.A0.Mul(&x.A0, &yCopy) z.A1.Mul(&x.A1, &yCopy) return z } // Conjugate conjugates an element in {{.Name}} func (z *{{.Name}}) Conjugate(x *{{.Name}}) *{{.Name}} { z.A0.Set(&x.A0) z.A1.Neg(&x.A1) return z } // MulByNonResidue multiplies a fp.Element by {{.Fp2NonResidue}} // It would be nice to make this a method of fp.Element but fp.Element is outside this package func MulByNonResidue(out, in *fp.Element) *fp.Element { {{- template "fpMulByNonResidueBody" dict "all" . "out" "out" "in" "in" }} return out } // MulByNonResidueInv multiplies a fp.Element by {{.Fp2NonResidue}}^{-1} // It would be nice to make this a method of fp.Element but fp.Element is outside this package func MulByNonResidueInv(out, in *fp.Element) *fp.Element { {{- template "fpMulByNonResidueInvBody" dict "all" . "out" "out" "in" "in" }} return out } `
ecc/internal/tower/fp2/mul.go
0.711431
0.474083
mul.go
starcoder
package gmeasure import ( "fmt" "math" "sort" "time" "github.com/bsm/gomega/gmeasure/table" ) type MeasurementType uint const ( MeasurementTypeInvalid MeasurementType = iota MeasurementTypeNote MeasurementTypeDuration MeasurementTypeValue ) var letEnumSupport = newEnumSupport(map[uint]string{uint(MeasurementTypeInvalid): "INVALID LOG ENTRY TYPE", uint(MeasurementTypeNote): "Note", uint(MeasurementTypeDuration): "Duration", uint(MeasurementTypeValue): "Value"}) func (s MeasurementType) String() string { return letEnumSupport.String(uint(s)) } func (s *MeasurementType) UnmarshalJSON(b []byte) error { out, err := letEnumSupport.UnmarshJSON(b) *s = MeasurementType(out) return err } func (s MeasurementType) MarshalJSON() ([]byte, error) { return letEnumSupport.MarshJSON(uint(s)) } /* Measurement records all captured data for a given measurement. You generally don't make Measurements directly - but you can fetch them from Experiments using Get(). When using Ginkgo, you can register Measurements as Report Entries via AddReportEntry. This will emit all the captured data points when Ginkgo generates the report. */ type Measurement struct { // Type is the MeasurementType - one of MeasurementTypeNote, MeasurementTypeDuration, or MeasurementTypeValue Type MeasurementType // ExperimentName is the name of the experiment that this Measurement is associated with ExperimentName string // If Type is MeasurementTypeNote, Note is populated with the note text. Note string // If Type is MeasurementTypeDuration or MeasurementTypeValue, Name is the name of the recorded measurement Name string // Style captures the styling information (if any) for this Measurement Style string // Units capture the units (if any) for this Measurement. Units is set to "duration" if the Type is MeasurementTypeDuration Units string // PrecisionBundle captures the precision to use when rendering data for this Measurement. // If Type is MeasurementTypeDuration then PrecisionBundle.Duration is used to round any durations before presentation. // If Type is MeasurementTypeValue then PrecisionBundle.ValueFormat is used to format any values before presentation PrecisionBundle PrecisionBundle // If Type is MeasurementTypeDuration, Durations will contain all durations recorded for this measurement Durations []time.Duration // If Type is MeasurementTypeValue, Values will contain all float64s recorded for this measurement Values []float64 // If Type is MeasurementTypeDuration or MeasurementTypeValue then Annotations will include string annotations for all recorded Durations or Values. // If the user does not pass-in an Annotation() decoration for a particular value or duration, the corresponding entry in the Annotations slice will be the empty string "" Annotations []string } type Measurements []Measurement func (m Measurements) IdxWithName(name string) int { for idx, measurement := range m { if measurement.Name == name { return idx } } return -1 } func (m Measurement) report(enableStyling bool) string { out := "" style := m.Style if !enableStyling { style = "" } switch m.Type { case MeasurementTypeNote: out += fmt.Sprintf("%s - Note\n%s\n", m.ExperimentName, m.Note) if style != "" { out = style + out + "{{/}}" } return out case MeasurementTypeValue, MeasurementTypeDuration: out += fmt.Sprintf("%s - %s", m.ExperimentName, m.Name) if m.Units != "" { out += " [" + m.Units + "]" } if style != "" { out = style + out + "{{/}}" } out += "\n" out += m.Stats().String() + "\n" } t := table.NewTable() t.TableStyle.EnableTextStyling = enableStyling switch m.Type { case MeasurementTypeValue: t.AppendRow(table.R(table.C("Value", table.AlignTypeCenter), table.C("Annotation", table.AlignTypeCenter), table.Divider("="), style)) for idx := range m.Values { t.AppendRow(table.R( table.C(fmt.Sprintf(m.PrecisionBundle.ValueFormat, m.Values[idx]), table.AlignTypeRight), table.C(m.Annotations[idx], "{{gray}}", table.AlignTypeLeft), )) } case MeasurementTypeDuration: t.AppendRow(table.R(table.C("Duration", table.AlignTypeCenter), table.C("Annotation", table.AlignTypeCenter), table.Divider("="), style)) for idx := range m.Durations { t.AppendRow(table.R( table.C(m.Durations[idx].Round(m.PrecisionBundle.Duration).String(), style, table.AlignTypeRight), table.C(m.Annotations[idx], "{{gray}}", table.AlignTypeLeft), )) } } out += t.Render() return out } /* ColorableString generates a styled report that includes all the data points for this Measurement. It is called automatically by Ginkgo's reporting infrastructure when the Measurement is registered as a ReportEntry via AddReportEntry. */ func (m Measurement) ColorableString() string { return m.report(true) } /* String generates an unstyled report that includes all the data points for this Measurement. */ func (m Measurement) String() string { return m.report(false) } /* Stats returns a Stats struct summarizing the statistic of this measurement */ func (m Measurement) Stats() Stats { if m.Type == MeasurementTypeInvalid || m.Type == MeasurementTypeNote { return Stats{} } out := Stats{ ExperimentName: m.ExperimentName, MeasurementName: m.Name, Style: m.Style, Units: m.Units, PrecisionBundle: m.PrecisionBundle, } switch m.Type { case MeasurementTypeValue: out.Type = StatsTypeValue out.N = len(m.Values) if out.N == 0 { return out } indices, sum := make([]int, len(m.Values)), 0.0 for idx, v := range m.Values { indices[idx] = idx sum += v } sort.Slice(indices, func(i, j int) bool { return m.Values[indices[i]] < m.Values[indices[j]] }) out.ValueBundle = map[Stat]float64{ StatMin: m.Values[indices[0]], StatMax: m.Values[indices[out.N-1]], StatMean: sum / float64(out.N), StatStdDev: 0.0, } out.AnnotationBundle = map[Stat]string{ StatMin: m.Annotations[indices[0]], StatMax: m.Annotations[indices[out.N-1]], } if out.N%2 == 0 { out.ValueBundle[StatMedian] = (m.Values[indices[out.N/2]] + m.Values[indices[out.N/2-1]]) / 2.0 } else { out.ValueBundle[StatMedian] = m.Values[indices[(out.N-1)/2]] } for _, v := range m.Values { out.ValueBundle[StatStdDev] += (v - out.ValueBundle[StatMean]) * (v - out.ValueBundle[StatMean]) } out.ValueBundle[StatStdDev] = math.Sqrt(out.ValueBundle[StatStdDev] / float64(out.N)) case MeasurementTypeDuration: out.Type = StatsTypeDuration out.N = len(m.Durations) if out.N == 0 { return out } indices, sum := make([]int, len(m.Durations)), time.Duration(0) for idx, v := range m.Durations { indices[idx] = idx sum += v } sort.Slice(indices, func(i, j int) bool { return m.Durations[indices[i]] < m.Durations[indices[j]] }) out.DurationBundle = map[Stat]time.Duration{ StatMin: m.Durations[indices[0]], StatMax: m.Durations[indices[out.N-1]], StatMean: sum / time.Duration(out.N), } out.AnnotationBundle = map[Stat]string{ StatMin: m.Annotations[indices[0]], StatMax: m.Annotations[indices[out.N-1]], } if out.N%2 == 0 { out.DurationBundle[StatMedian] = (m.Durations[indices[out.N/2]] + m.Durations[indices[out.N/2-1]]) / 2 } else { out.DurationBundle[StatMedian] = m.Durations[indices[(out.N-1)/2]] } stdDev := 0.0 for _, v := range m.Durations { stdDev += float64(v-out.DurationBundle[StatMean]) * float64(v-out.DurationBundle[StatMean]) } out.DurationBundle[StatStdDev] = time.Duration(math.Sqrt(stdDev / float64(out.N))) } return out }
gmeasure/measurement.go
0.669421
0.506225
measurement.go
starcoder
package opencvl // Examples contains some example pipelines that are also usable for image transforms import ( "fmt" "image" "gocv.io/x/gocv" ) // BlurPipeline performs a gaussian blur, given the magnitude of the blur on the x and y axis func BlurPipeline(xblur, yblur int) Pipeline { p := NewPipeline() layer := NewOpenCVLayer(func(mat gocv.Mat, args ...interface{}) gocv.Mat { gocv.GaussianBlur(mat, &mat, image.Point{xblur, yblur}, 0, 0, gocv.BorderDefault) return mat }) p.AddLayer(layer) return p } // InvertPipeline inverts an image func InvertPipeline() Pipeline { p := NewPipeline() layer := NewOpenCVLayer(func(mat gocv.Mat, args ...interface{}) gocv.Mat { gocv.BitwiseNot(mat, &mat) return mat }) p.AddLayer(layer) return p } // HSLCorrectPipeline does an HSL color correction pipeline func HSLCorrectPipeline(hchange, schange, lchange float64) Pipeline { p := NewPipeline() layer := NewOpenCVLayer(func(mat gocv.Mat, args ...interface{}) gocv.Mat { gocv.CvtColor(mat, &mat, gocv.ColorBGRToHLS) mask := gocv.NewMatWithSizeFromScalar(gocv.NewScalar(hchange, lchange, schange, 0), mat.Rows(), mat.Cols(), mat.Type()) gocv.Add(mat, mask, &mat) gocv.CvtColor(mat, &mat, gocv.ColorHLSToBGR) return mat }) p.AddLayer(layer) return p } // TranslatePipeline translates an image func TranslatePipeline(xchange, ychange int) (Pipeline, error) { p := NewPipeline() var kernelSource = fmt.Sprintf(` __kernel void translate( __read_only image2d_t in, __write_only image2d_t out) { const int2 pos = (int2)(get_global_id(0), get_global_id(1)); const int2 dim = get_image_dim(in); float4 pixel = (float4)(0); if (pos.x < dim.x && pos.y < dim.y) { pixel = read_imagef(in, pos); pos.x += %d; pos.y += %d; if (pos.x < dim.x && pos.y < dim.y) { write_imagef(out, pos, pixel); } } }`, xchange, ychange) layer, err := NewOpenCLLayer(kernelSource, "translate", 0, 0) if err != nil { return NewPipeline(), err } p.AddLayer(layer) err = p.Build() if err != nil { return NewPipeline(), err } return p, nil } // RotatePipeline rotates an image func RotatePipeline(x, y int, rotation float64) Pipeline { p := NewPipeline() layer := NewOpenCVLayer(func(mat gocv.Mat, args ...interface{}) gocv.Mat { matrix := gocv.GetRotationMatrix2D(image.Point{x, y}, rotation, 1) gocv.WarpAffine(mat, &mat, matrix, image.Point{0, 0}) return mat }) p.AddLayer(layer) return p }
examples.go
0.83471
0.545104
examples.go
starcoder
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 // Galton box width const boxH = 37 // Galton box height. const pinsBaseW = 19 // Pins triangle base. const nMaxBalls = 55 // Number of balls. const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) type Ball struct{ x, y int } func newBall(x, y int) *Ball { if box[y][x] != empty { panic("Tried to create a new ball in a non-empty cell. Program terminated.") } b := Ball{x, y} box[y][x] = ball return &b } func (b *Ball) doStep() { if b.y <= 0 { return // Reached the bottom of the box. } cell := box[b.y-1][b.x] switch cell { case empty: box[b.y][b.x] = empty b.y-- box[b.y][b.x] = ball case pin: box[b.y][b.x] = empty b.y-- if box[b.y][b.x-1] == empty && box[b.y][b.x+1] == empty { b.x += rand.Intn(2)*2 - 1 box[b.y][b.x] = ball return } else if box[b.y][b.x-1] == empty { b.x++ } else { b.x-- } box[b.y][b.x] = ball default: // It's frozen - it always piles on other balls. } } type Cell = byte /* Galton box. Will be printed upside down. */ var box [boxH][boxW]Cell func initializeBox() { // Set ceiling and floor box[0][0] = corner box[0][boxW-1] = corner for i := 1; i < boxW-1; i++ { box[0][i] = floor } for i := 0; i < boxW; i++ { box[boxH-1][i] = box[0][i] } // Set walls for r := 1; r < boxH-1; r++ { box[r][0] = wall box[r][boxW-1] = wall } // Set rest to empty initially for i := 1; i < boxH-1; i++ { for j := 1; j < boxW-1; j++ { box[i][j] = empty } } // Set pins for nPins := 1; nPins <= pinsBaseW; nPins++ { for p := 0; p < nPins; p++ { box[boxH-2-nPins][centerH+1-nPins+p*2] = pin } } } func drawBox() { for r := boxH - 1; r >= 0; r-- { for c := 0; c < boxW; c++ { fmt.Printf("%c", box[r][c]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) initializeBox() var balls []*Ball for i := 0; i < nMaxBalls+boxH; i++ { fmt.Println("\nStep", i, ":") if i < nMaxBalls { balls = append(balls, newBall(centerH, boxH-2)) // add ball } drawBox() // Next step for the simulation. // Frozen balls are kept in balls slice for simplicity for _, b := range balls { b.doStep() } } }
lang/Go/galton-box-animation.go
0.659734
0.420005
galton-box-animation.go
starcoder
package diff import ( "context" ) // LCS between x and y. // This implementation converts the LCS problem into LIS sub problems without recursion. // The memory complexity is O(x.Occurrence(y)). // The time complexicy is O(x.Occurrence(y).Complexity()). // The time complexicy is similar with Myer's diff algorithm, but with more modulized steps, which allows further optimization easier. // https://en.wikipedia.org/wiki/Longest_common_subsequence_problem func (x Sequence) LCS(ctx context.Context, y Sequence) Sequence { left, right := x.Common(y) l, r, x, y := x[:left], x[len(x)-right:], x[left:len(x)-right], y[left:len(y)-right] return append(append(Sequence{}, l...), append(x.lcs(ctx, y), r...)...) } func (x Sequence) lcs(ctx context.Context, y Sequence) Sequence { x = x.Reduce(y) y = y.Reduce(x) o := x.Occurrence(y) p := make([]int, len(o)) n := o.Complexity() lis := NewLIS(len(o), func(i int) int { return o[i][p[i]] }) var longest int var longestI int for i := 0; i < n && ctx.Err() == nil; i++ { o.Permutate(p, i) l := lis.Length() if l > longest { longestI = i longest = l } } p = make([]int, len(o)) o.Permutate(p, longestI) s := lis.Get() lcs := make(Sequence, longest) for i := 0; i < longest; i++ { lcs[i] = x[s[i]] } return lcs } // Common returns the common prefix and suffix between x and y. // This function scales down the problem via the first property: // https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#First_property func (x Sequence) Common(y Sequence) (left, right int) { l := min(len(x), len(y)) for ; left < l && eq(x[left], y[left]); left++ { } lx, ly := len(x), len(y) l = min(lx-left, ly-left) for ; right < l && eq(x[lx-right-1], y[ly-right-1]); right++ { } return } // Reduce Comparables from x that doesn't exist in y func (x Sequence) Reduce(y Sequence) Sequence { rest := Sequence{} h := y.Histogram() for _, c := range x { if _, has := h[c.Hash()]; has { rest = append(rest, c) } } return rest } // Histogram of a Comparables type Histogram map[string][]int // Histogram of each Comparable func (x Sequence) Histogram() Histogram { h := Histogram{} for i, c := range x { if _, has := h[c.Hash()]; !has { h[c.Hash()] = []int{} } h[c.Hash()] = append(h[c.Hash()], i) } return h } // IsSubsequenceOf returns true if x is a subsequence of y func (x Sequence) IsSubsequenceOf(y Sequence) bool { for i, j := 0, 0; i < len(x); i++ { for { if j >= len(y) { return false } if eq(x[i], y[j]) { j++ break } j++ } } return true } // Occurrence histogram type Occurrence [][]int // Complexity to find the LCS in m func (o Occurrence) Complexity() int { if len(o) == 0 { return 0 } n := 1 for _, i := range o { n *= len(i) } return n } // Permutate p with i func (o Occurrence) Permutate(p []int, i int) { for j := 0; i > 0; j++ { p[j] = i % len(o[j]) i = i / len(o[j]) } } // Occurrence returns the position of each element of y in x. func (x Sequence) Occurrence(y Sequence) Occurrence { m := make(Occurrence, len(y)) h := x.Histogram() for i, c := range y { if indexes, has := h[c.Hash()]; has { m[i] = indexes } } return m } // LIS https://en.wikipedia.org/wiki/Longest_increasing_subsequence type LIS struct { p []int m []int len int x func(int) int } // NewLIS helper func NewLIS(len int, x func(int) int) *LIS { return &LIS{ p: make([]int, len), m: make([]int, len+1), len: len, x: x, } } // Length of LIS func (lis *LIS) Length() int { l := 0 for i := 0; i < lis.len; i++ { lo := 1 hi := l + 1 for lo < hi { mid := lo + (hi-lo)/2 if lis.x(lis.m[mid]) < lis.x(i) { lo = mid + 1 } else { hi = mid } } newL := lo lis.p[i] = lis.m[newL-1] lis.m[newL] = i if newL > l { l = newL } } return l } // Get the LIS func (lis *LIS) Get() []int { l := lis.Length() s := make([]int, l) k := lis.m[l] for i := l - 1; i >= 0; i-- { s[i] = lis.x(k) k = lis.p[k] } return s }
lib/diff/lcs.go
0.755366
0.495911
lcs.go
starcoder
package code import ( "fmt" "go/types" ) // CompatibleTypes isnt a strict comparison, it allows for pointer differences func CompatibleTypes(expected types.Type, actual types.Type) error { //fmt.Println("Comparing ", expected.String(), actual.String()) // Special case to deal with pointer mismatches { expectedPtr, expectedIsPtr := expected.(*types.Pointer) actualPtr, actualIsPtr := actual.(*types.Pointer) if expectedIsPtr && actualIsPtr { return CompatibleTypes(expectedPtr.Elem(), actualPtr.Elem()) } if expectedIsPtr && !actualIsPtr { return CompatibleTypes(expectedPtr.Elem(), actual) } if !expectedIsPtr && actualIsPtr { return CompatibleTypes(expected, actualPtr.Elem()) } } switch expected := expected.(type) { case *types.Slice: if actual, ok := actual.(*types.Slice); ok { return CompatibleTypes(expected.Elem(), actual.Elem()) } case *types.Array: if actual, ok := actual.(*types.Array); ok { if expected.Len() != actual.Len() { return fmt.Errorf("array length differs") } return CompatibleTypes(expected.Elem(), actual.Elem()) } case *types.Basic: if actual, ok := actual.(*types.Basic); ok { if actual.Kind() != expected.Kind() { return fmt.Errorf("basic kind differs, %s != %s", expected.Name(), actual.Name()) } return nil } case *types.Struct: if actual, ok := actual.(*types.Struct); ok { if expected.NumFields() != actual.NumFields() { return fmt.Errorf("number of struct fields differ") } for i := 0; i < expected.NumFields(); i++ { if expected.Field(i).Name() != actual.Field(i).Name() { return fmt.Errorf("struct field %d name differs, %s != %s", i, expected.Field(i).Name(), actual.Field(i).Name()) } if err := CompatibleTypes(expected.Field(i).Type(), actual.Field(i).Type()); err != nil { return err } } return nil } case *types.Tuple: if actual, ok := actual.(*types.Tuple); ok { if expected.Len() != actual.Len() { return fmt.Errorf("tuple length differs, %d != %d", expected.Len(), actual.Len()) } for i := 0; i < expected.Len(); i++ { if err := CompatibleTypes(expected.At(i).Type(), actual.At(i).Type()); err != nil { return err } } return nil } case *types.Signature: if actual, ok := actual.(*types.Signature); ok { if err := CompatibleTypes(expected.Params(), actual.Params()); err != nil { return err } if err := CompatibleTypes(expected.Results(), actual.Results()); err != nil { return err } return nil } case *types.Interface: if actual, ok := actual.(*types.Interface); ok { if expected.NumMethods() != actual.NumMethods() { return fmt.Errorf("interface method count differs, %d != %d", expected.NumMethods(), actual.NumMethods()) } for i := 0; i < expected.NumMethods(); i++ { if expected.Method(i).Name() != actual.Method(i).Name() { return fmt.Errorf("interface method %d name differs, %s != %s", i, expected.Method(i).Name(), actual.Method(i).Name()) } if err := CompatibleTypes(expected.Method(i).Type(), actual.Method(i).Type()); err != nil { return err } } return nil } case *types.Map: if actual, ok := actual.(*types.Map); ok { if err := CompatibleTypes(expected.Key(), actual.Key()); err != nil { return err } if err := CompatibleTypes(expected.Elem(), actual.Elem()); err != nil { return err } return nil } case *types.Chan: if actual, ok := actual.(*types.Chan); ok { return CompatibleTypes(expected.Elem(), actual.Elem()) } case *types.Named: if actual, ok := actual.(*types.Named); ok { if NormalizeVendor(expected.Obj().Pkg().Path()) != NormalizeVendor(actual.Obj().Pkg().Path()) { return fmt.Errorf( "package name of named type differs, %s != %s", NormalizeVendor(expected.Obj().Pkg().Path()), NormalizeVendor(actual.Obj().Pkg().Path()), ) } if expected.Obj().Name() != actual.Obj().Name() { return fmt.Errorf( "named type name differs, %s != %s", NormalizeVendor(expected.Obj().Name()), NormalizeVendor(actual.Obj().Name()), ) } return nil } // Before models are generated all missing references will be Invalid Basic references. // lets assume these are valid too. if actual, ok := actual.(*types.Basic); ok && actual.Kind() == types.Invalid { return nil } default: return fmt.Errorf("missing support for %T", expected) } return fmt.Errorf("type mismatch %T != %T", expected, actual) }
internal/code/compare.go
0.578448
0.588209
compare.go
starcoder
package mg import ( "context" "encoding/json" "fmt" "reflect" "time" ) // Fn represents a function that can be run with mg.Deps. Package, Name, and ID must combine to // uniquely identify a function, while ensuring the "same" function has identical values. These are // used as a map key to find and run (or not run) the function. type Fn interface { // Name should return the fully qualified name of the function. Usually // it's best to use runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name(). Name() string // ID should be an additional uniqueness qualifier in case the name is insufficiently unique. // This can be the case for functions that take arguments (mg.F json-encodes an array of the // args). ID() string // Run should run the function. Run(ctx context.Context) error } // F takes a function that is compatible as a mage target, and any args that need to be passed to // it, and wraps it in an mg.Fn that mg.Deps can run. Args must be passed in the same order as they // are declared by the function. Note that you do not need to and should not pass a context.Context // to F, even if the target takes a context. Compatible args are int, bool, string, and // time.Duration. func F(target interface{}, args ...interface{}) Fn { hasContext, isNamespace, err := checkF(target, args) if err != nil { panic(err) } id, err := json.Marshal(args) if err != nil { panic(fmt.Errorf("can't convert args into a mage-compatible id for mg.Deps: %s", err)) } return fn{ name: funcName(target), id: string(id), f: func(ctx context.Context) error { v := reflect.ValueOf(target) count := len(args) if hasContext { count++ } if isNamespace { count++ } vargs := make([]reflect.Value, count) x := 0 if isNamespace { vargs[0] = reflect.ValueOf(struct{}{}) x++ } if hasContext { vargs[x] = reflect.ValueOf(ctx) x++ } for y := range args { vargs[x+y] = reflect.ValueOf(args[y]) } ret := v.Call(vargs) if len(ret) > 0 { // we only allow functions with a single error return, so this should be safe. if ret[0].IsNil() { return nil } return ret[0].Interface().(error) } return nil }, } } type fn struct { name string id string f func(ctx context.Context) error } // Name returns the fully qualified name of the function. func (f fn) Name() string { return f.name } // ID returns a hash of the argument values passed in func (f fn) ID() string { return f.id } // Run runs the function. func (f fn) Run(ctx context.Context) error { return f.f(ctx) } func checkF(target interface{}, args []interface{}) (hasContext, isNamespace bool, _ error) { t := reflect.TypeOf(target) if t == nil || t.Kind() != reflect.Func { return false, false, fmt.Errorf("non-function passed to mg.F: %T. The mg.F function accepts function names, such as mg.F(TargetA, \"arg1\", \"arg2\")", target) } if t.NumOut() > 1 { return false, false, fmt.Errorf("target has too many return values, must be zero or just an error: %T", target) } if t.NumOut() == 1 && t.Out(0) != errType { return false, false, fmt.Errorf("target's return value is not an error") } // more inputs than slots is an error if not variadic if len(args) > t.NumIn() && !t.IsVariadic() { return false, false, fmt.Errorf("too many arguments for target, got %d for %T", len(args), target) } if t.NumIn() == 0 { return false, false, nil } x := 0 inputs := t.NumIn() if t.In(0).AssignableTo(emptyType) { // nameSpace func isNamespace = true x++ // callers must leave off the namespace value inputs-- } if t.NumIn() > x && t.In(x) == ctxType { // callers must leave off the context inputs-- // let the upper function know it should pass us a context. hasContext = true // skip checking the first argument in the below loop if it's a context, since first arg is // special. x++ } if t.IsVariadic() { if len(args) < inputs-1 { return false, false, fmt.Errorf("too few arguments for target, got %d for %T", len(args), target) } } else if len(args) != inputs { return false, false, fmt.Errorf("wrong number of arguments for target, got %d for %T", len(args), target) } for _, arg := range args { argT := t.In(x) if t.IsVariadic() && x == t.NumIn()-1 { // For the variadic argument, use the slice element type. argT = argT.Elem() } if !argTypes[argT] { return false, false, fmt.Errorf("argument %d (%s), is not a supported argument type", x, argT) } passedT := reflect.TypeOf(arg) if argT != passedT { return false, false, fmt.Errorf("argument %d expected to be %s, but is %s", x, argT, passedT) } if x < t.NumIn()-1 { x++ } } return hasContext, isNamespace, nil } // Here we define the types that are supported as arguments/returns var ( ctxType = reflect.TypeOf(func(context.Context) {}).In(0) errType = reflect.TypeOf(func() error { return nil }).Out(0) emptyType = reflect.TypeOf(struct{}{}) intType = reflect.TypeOf(int(0)) stringType = reflect.TypeOf(string("")) boolType = reflect.TypeOf(bool(false)) durType = reflect.TypeOf(time.Second) // don't put ctx in here, this is for non-context types argTypes = map[reflect.Type]bool{ intType: true, boolType: true, stringType: true, durType: true, } )
mg/fn.go
0.658198
0.418994
fn.go
starcoder
package chunks import ( "io" "github.com/attic-labs/noms/go/hash" ) // ChunkStore is the core storage abstraction in noms. We can put data // anyplace we have a ChunkStore implementation for. type ChunkStore interface { // Get the Chunk for the value of the hash in the store. If the hash is // absent from the store EmptyChunk is returned. Get(h hash.Hash) Chunk // GetMany gets the Chunks with |hashes| from the store. On return, // |foundChunks| will have been fully sent all chunks which have been // found. Any non-present chunks will silently be ignored. GetMany(hashes hash.HashSet, foundChunks chan *Chunk) // Returns true iff the value at the address |h| is contained in the // store Has(h hash.Hash) bool // Returns a new HashSet containing any members of |hashes| that are // absent from the store. HasMany(hashes hash.HashSet) (absent hash.HashSet) // Put caches c in the ChunkSource. Upon return, c must be visible to // subsequent Get and Has calls, but must not be persistent until a call // to Flush(). Put may be called concurrently with other calls to Put(), // Get(), GetMany(), Has() and HasMany(). Put(c Chunk) // Returns the NomsVersion with which this ChunkSource is compatible. Version() string // Rebase brings this ChunkStore into sync with the persistent storage's // current root. Rebase() // Root returns the root of the database as of the time the ChunkStore // was opened or the most recent call to Rebase. Root() hash.Hash // Commit atomically attempts to persist all novel Chunks and update the // persisted root hash from last to current (or keeps it the same). // If last doesn't match the root in persistent storage, returns false. Commit(current, last hash.Hash) bool // Stats may return some kind of struct that reports statistics about the // ChunkStore instance. The type is implementation-dependent, and impls // may return nil Stats() interface{} // Close tears down any resources in use by the implementation. After // Close(), the ChunkStore may not be used again. It is NOT SAFE to call // Close() concurrently with any other ChunkStore method; behavior is // undefined and probably crashy. io.Closer } // Factory allows the creation of namespaced ChunkStore instances. The details // of how namespaces are separated is left up to the particular implementation // of Factory and ChunkStore. type Factory interface { CreateStore(ns string) ChunkStore // CreateStoreFromCache allows caller to signal to the factory that it's // willing to tolerate an out-of-date ChunkStore. CreateStoreFromCache(ns string) ChunkStore // Shutter shuts down the factory. Subsequent calls to CreateStore() will fail. Shutter() }
go/chunks/chunk_store.go
0.601125
0.465752
chunk_store.go
starcoder
package bdd import ( "context" "fmt" "reflect" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/inklabs/rangedb" "github.com/inklabs/rangedb/rangedbtest" ) // Command defines a CQRS command. type Command interface { rangedb.AggregateMessage CommandType() string } // CommandDispatcher defines how a function can dispatch CQRS commands. type CommandDispatcher func(command Command) // TestCase contains the BDD test case. type TestCase struct { store rangedb.Store dispatch CommandDispatcher previousEvents []rangedb.Event command Command } // New constructs a BDD test case. func New(store rangedb.Store, commandDispatcher CommandDispatcher) *TestCase { return &TestCase{ store: store, dispatch: commandDispatcher, } } // Given loads events into the store. func (c *TestCase) Given(events ...rangedb.Event) *TestCase { c.previousEvents = events return c } // When executes a CQRS command. func (c *TestCase) When(command Command) *TestCase { c.command = command return c } // Then asserts the expectedEvents were raised. func (c *TestCase) Then(expectedEvents ...rangedb.Event) func(*testing.T) { return func(t *testing.T) { t.Helper() streamPreviousEventCounts := make(map[string]uint64) for _, event := range c.previousEvents { streamPreviousEventCounts[rangedb.GetEventStream(event)]++ rangedbtest.BlockingSaveEvents(t, c.store, &rangedb.EventRecord{Event: event}) } c.dispatch(c.command) if len(expectedEvents) == 0 { ctx := rangedbtest.TimeoutContext(t) allEvents, err := recordIteratorToSlice(c.store.Events(ctx, 0)) require.NoError(t, err) totalRaisedEvents := len(allEvents) - len(c.previousEvents) require.Equal(t, 0, totalRaisedEvents) return } streamExpectedEvents := make(map[string][]rangedb.Event) for _, event := range expectedEvents { stream := rangedb.GetEventStream(event) streamExpectedEvents[stream] = append(streamExpectedEvents[stream], event) } for stream, expectedEventsInStream := range streamExpectedEvents { streamSequenceNumber := streamPreviousEventCounts[stream] ctx := rangedbtest.TimeoutContext(t) actualEvents, err := recordIteratorToSlice(c.store.EventsByStream(ctx, streamSequenceNumber, stream)) assert.NoError(t, err) assert.Equal(t, expectedEventsInStream, actualEvents, "stream: %s", stream) } } } // ThenInspectEvents should be called after a CQRS command has executed to assert on specific events. func (c *TestCase) ThenInspectEvents(f func(t *testing.T, events []rangedb.Event)) func(t *testing.T) { return func(t *testing.T) { t.Helper() ctx := rangedbtest.TimeoutContext(t) streamPreviousEventCounts := make(map[string]uint64) for _, event := range c.previousEvents { streamPreviousEventCounts[rangedb.GetEventStream(event)]++ rangedbtest.BlockingSaveEvents(t, c.store, &rangedb.EventRecord{Event: event}) } c.dispatch(c.command) var events []rangedb.Event for _, stream := range getStreamsFromStore(c.store) { streamSequenceNumber := streamPreviousEventCounts[stream] actualEvents, err := recordIteratorToSlice(c.store.EventsByStream(ctx, streamSequenceNumber, stream)) require.NoError(t, err) events = append(events, actualEvents...) } f(t, events) } } func getStreamsFromStore(store rangedb.Store) []string { streams := make(map[string]struct{}) recordIterator := store.Events(context.Background(), 0) for recordIterator.Next() { if recordIterator.Err() != nil { break } stream := rangedb.GetStream(recordIterator.Record().AggregateType, recordIterator.Record().AggregateID) streams[stream] = struct{}{} } keys := make([]string, 0, len(streams)) for k := range streams { keys = append(keys, k) } return keys } func recordIteratorToSlice(recordIterator rangedb.RecordIterator) ([]rangedb.Event, error) { var events []rangedb.Event for recordIterator.Next() { if recordIterator.Err() != nil { return nil, recordIterator.Err() } value, err := eventAsValue(recordIterator.Record().Data) if err != nil { return nil, err } events = append(events, value) } return events, nil } func eventAsValue(inputEvent interface{}) (rangedb.Event, error) { var event rangedb.Event reflectedValue := reflect.ValueOf(inputEvent) if reflectedValue.Kind() == reflect.Ptr { event = reflectedValue.Elem().Interface().(rangedb.Event) } else { return nil, fmt.Errorf("unbound event type: %T", inputEvent) } return event, nil }
rangedbtest/bdd/bdd.go
0.747247
0.442155
bdd.go
starcoder
package main import ( "fmt" ) type node struct { data int left *node right *node } type binarySearchTree struct { root *node } func createNode(data int) *node { myNode := node{ data: data, left: nil, right: nil, } return &myNode } func showPreOrderElements(root *node) { if root != nil { fmt.Println(root.data) showPreOrderElements(root.left) showPreOrderElements(root.right) } } func showInorderElements(root *node) { if root != nil { showInorderElements(root.left) fmt.Println(root.data) showInorderElements(root.right) } } func showPostOrderElements(root *node) { if root != nil { showPostOrderElements(root.left) showPostOrderElements(root.right) fmt.Println(root.data) } } func insertElement(root *node, data int) *node { if root != nil { if data < root.data { root.left = insertElement(root.left, data) } else { root.right = insertElement(root.right, data) } } else { root = createNode(data) } return root } func length(root *node) int { if root == nil { return 0 } return length(root.left) + length(root.right) + 1 } //dont count rootNode (Check This Function) func height(root *node) int { if root != nil { lHeight := height(root.left) rHeight := height(root.right) if lHeight > rHeight { return lHeight + 1 } else { return rHeight + 1 } } else { return -1 } } func findElement(root *node, key int) int { if root == nil { return 0 } if root.data == key { return 1 } isLeft := findElement(root.left, key) isRight := findElement(root.right, key) if isLeft > isRight { return isLeft } return isRight } func minElement(root *node) int { if root == nil { return 0 } if root.left == nil { return root.data } return minElement(root.left) } func maxElement(root *node) int { if root == nil { return 0 } if root.right == nil { return root.data } return maxElement(root.right) } //Todo : Çöz func isBinarySearchTree(root *node) int { // 1- parent may have max 2 child // 2- left child should be smaller than parent node // 3- right child should be bigger than parent node return 1 } func sumTreeNodes(root *node) int { if root == nil { return 0 } return sumTreeNodes(root.left) + sumTreeNodes(root.right) + root.data } // Todo: İncele func showLeftChild(root *node) { if root != nil { if root.left != nil && root.right != nil { fmt.Println(root.data) } showLeftChild(root.left) showLeftChild(root.right) } else { return } } func main() { myNode := createNode(10) myBinarySearchTree := binarySearchTree{ root: myNode, } showPreOrderElements(myBinarySearchTree.root) myBinarySearchTree.root = insertElement(myBinarySearchTree.root, 8) myBinarySearchTree.root = insertElement(myBinarySearchTree.root, 12) myBinarySearchTree.root = insertElement(myBinarySearchTree.root, 13) myBinarySearchTree.root = insertElement(myBinarySearchTree.root, 25) myBinarySearchTree.root = insertElement(myBinarySearchTree.root, 22) myBinarySearchTree.root = insertElement(myBinarySearchTree.root, 4) myBinarySearchTree.root = insertElement(myBinarySearchTree.root, 5) //Total : 99 fmt.Println("ShowPreOrder : ") showPreOrderElements(myBinarySearchTree.root) fmt.Println("*****") lengthx := length(myBinarySearchTree.root) height := height(myBinarySearchTree.root) fmt.Println(lengthx) fmt.Println(height) fmt.Println("The Length is : ", length(myBinarySearchTree.root)) isFind := findElement(myBinarySearchTree.root, 12) fmt.Println("İsFind : ", isFind) maxElement := maxElement(myBinarySearchTree.root) minElement := minElement(myBinarySearchTree.root) fmt.Println("Max Element is ", maxElement) fmt.Println("Min Element is ", minElement) isSpecialTree := sumTreeNodes(myBinarySearchTree.root) fmt.Println("İs Special : ", isSpecialTree) showLeftChild(myBinarySearchTree.root) }
src/dataStructures/tree/binarySearchTree.go
0.545286
0.448487
binarySearchTree.go
starcoder
package primitives import ( "errors" "github.com/phoreproject/synapse/chainhash" "github.com/phoreproject/synapse/pb" ) // Block represents a single beacon chain block. type Block struct { BlockHeader BlockHeader BlockBody BlockBody } // Copy returns a copy of the block. func (b *Block) Copy() Block { return Block{ b.BlockHeader.Copy(), b.BlockBody.Copy(), } } // ToProto gets the protobuf representation of the block. func (b *Block) ToProto() *pb.Block { return &pb.Block{ Header: b.BlockHeader.ToProto(), Body: b.BlockBody.ToProto(), } } // BlockFromProto returns a block from the protobuf representation. func BlockFromProto(bl *pb.Block) (*Block, error) { header, err := BlockHeaderFromProto(bl.Header) if err != nil { return nil, err } body, err := BlockBodyFromProto(bl.Body) if err != nil { return nil, err } return &Block{ BlockHeader: *header, BlockBody: *body, }, nil } // BlockHeader is the header of the block. type BlockHeader struct { SlotNumber uint64 ParentRoot chainhash.Hash StateRoot chainhash.Hash ValidatorIndex uint32 RandaoReveal [48]byte Signature [48]byte } // Copy returns a copy of the block header. func (bh *BlockHeader) Copy() BlockHeader { return *bh } // ToProto converts to block header to protobuf form. func (bh *BlockHeader) ToProto() *pb.BlockHeader { return &pb.BlockHeader{ SlotNumber: bh.SlotNumber, ValidatorIndex: bh.ValidatorIndex, ParentRoot: bh.ParentRoot[:], StateRoot: bh.StateRoot[:], RandaoReveal: bh.RandaoReveal[:], Signature: bh.Signature[:], } } // BlockHeaderFromProto converts a protobuf representation of a block header to a block header. func BlockHeaderFromProto(header *pb.BlockHeader) (*BlockHeader, error) { if len(header.RandaoReveal) > 48 { return nil, errors.New("randaoReveal should be 48 bytes long") } if len(header.Signature) > 48 { return nil, errors.New("signature should be 48 bytes long") } newHeader := &BlockHeader{ SlotNumber: header.SlotNumber, ValidatorIndex: header.ValidatorIndex, } copy(newHeader.RandaoReveal[:], header.RandaoReveal) copy(newHeader.Signature[:], header.Signature) err := newHeader.StateRoot.SetBytes(header.StateRoot) if err != nil { return nil, err } err = newHeader.ParentRoot.SetBytes(header.ParentRoot) if err != nil { return nil, err } return newHeader, nil } // BlockBody contains the beacon actions that happened this block. type BlockBody struct { Attestations []Attestation ProposerSlashings []ProposerSlashing CasperSlashings []CasperSlashing Deposits []Deposit Exits []Exit Votes []AggregatedVote } // Copy returns a copy of the block body. func (bb *BlockBody) Copy() BlockBody { newAttestations := make([]Attestation, len(bb.Attestations)) newProposerSlashings := make([]ProposerSlashing, len(bb.ProposerSlashings)) newCasperSlashings := make([]CasperSlashing, len(bb.CasperSlashings)) newDeposits := make([]Deposit, len(bb.Deposits)) newExits := make([]Exit, len(bb.Exits)) newVotes := make([]AggregatedVote, len(bb.Votes)) for i := range bb.Attestations { newAttestations[i] = bb.Attestations[i].Copy() } for i := range bb.ProposerSlashings { newProposerSlashings[i] = bb.ProposerSlashings[i].Copy() } for i := range bb.CasperSlashings { newCasperSlashings[i] = bb.CasperSlashings[i].Copy() } for i := range bb.Deposits { newDeposits[i] = bb.Deposits[i].Copy() } for i := range bb.Exits { newExits[i] = bb.Exits[i].Copy() } for i := range bb.Votes { newVotes[i] = bb.Votes[i].Copy() } return BlockBody{ Attestations: newAttestations, ProposerSlashings: newProposerSlashings, CasperSlashings: newCasperSlashings, Deposits: newDeposits, Exits: newExits, Votes: newVotes, } } // ToProto converts the block body to protobuf form func (bb *BlockBody) ToProto() *pb.BlockBody { atts := make([]*pb.Attestation, len(bb.Attestations)) for i := range atts { atts[i] = bb.Attestations[i].ToProto() } ps := make([]*pb.ProposerSlashing, len(bb.ProposerSlashings)) for i := range ps { ps[i] = bb.ProposerSlashings[i].ToProto() } cs := make([]*pb.CasperSlashing, len(bb.CasperSlashings)) for i := range cs { cs[i] = bb.CasperSlashings[i].ToProto() } ds := make([]*pb.Deposit, len(bb.Deposits)) for i := range ds { ds[i] = bb.Deposits[i].ToProto() } ex := make([]*pb.Exit, len(bb.Exits)) for i := range ex { ex[i] = bb.Exits[i].ToProto() } vs := make([]*pb.AggregatedVote, len(bb.Votes)) for i := range vs { vs[i] = bb.Votes[i].ToProto() } return &pb.BlockBody{ Attestations: atts, ProposerSlashings: ps, CasperSlashings: cs, Deposits: ds, Exits: ex, Votes: vs, } } // BlockBodyFromProto converts a protobuf representation of a block body to a block body. func BlockBodyFromProto(body *pb.BlockBody) (*BlockBody, error) { atts := make([]Attestation, len(body.Attestations)) casperSlashings := make([]CasperSlashing, len(body.CasperSlashings)) proposerSlashings := make([]ProposerSlashing, len(body.ProposerSlashings)) deposits := make([]Deposit, len(body.Deposits)) exits := make([]Exit, len(body.Exits)) votes := make([]AggregatedVote, len(body.Votes)) for i := range atts { a, err := AttestationFromProto(body.Attestations[i]) if err != nil { return nil, err } atts[i] = *a } for i := range casperSlashings { cs, err := CasperSlashingFromProto(body.CasperSlashings[i]) if err != nil { return nil, err } casperSlashings[i] = *cs } for i := range proposerSlashings { ps, err := ProposerSlashingFromProto(body.ProposerSlashings[i]) if err != nil { return nil, err } proposerSlashings[i] = *ps } for i := range deposits { ds, err := DepositFromProto(body.Deposits[i]) if err != nil { return nil, err } deposits[i] = *ds } for i := range exits { ex, err := ExitFromProto(body.Exits[i]) if err != nil { return nil, err } exits[i] = *ex } for i := range votes { v, err := AggregatedVoteFromProto(body.Votes[i]) if err != nil { return nil, err } votes[i] = *v } return &BlockBody{ Attestations: atts, CasperSlashings: casperSlashings, ProposerSlashings: proposerSlashings, Deposits: deposits, Exits: exits, Votes: votes, }, nil }
primitives/block.go
0.748995
0.41404
block.go
starcoder
package inject import ( "fmt" "reflect" ) // Context that is passed to scopes. type Context interface{} type Singleton struct{} // Key used to uniquely identify a binding. type Key interface{} type Tag interface{} // Type used to identify a tagged type binding. type TaggedKey struct { Key Tag } /* Signature for provider functions. Provider functions are used to dynamically allocate an instance at run-time. */ type Provider func(Context, Container) interface{} /* Injector aggregates binding configuration and creates Containers based on that configuration. Binding configuration is defined by a Key that consists of a type and an optional tag. A child injector may be used to create bindings that are intended to be used only by part of the system. When a Container is created from a child injector, the bindings of the parent Injector are also available. Keys may only be bound once across an Injector and all of its descendant Injectors (children and their children). The Injector will panic if an attempt is made to rebind an already-bound Key. In order to look up a bound type, use the CreateContainer() method and call the appropriate methods on the returned Container. */ type Injector interface { // Binds a type to a Provider function. Bind(Key, Provider) // Binds a type to a single instance. BindInstance(Key, interface{}) // Binds a key to a Provider function, caching it within the specified scope. BindInScope(Key, Provider, Tag) // Binds a key to a single instance. BindInstanceInScope(Key, interface{}, Tag) // Binds a scope to a tag. BindScope(Scope, Tag) // Binds a tagged type to a Provider function. BindTagged(Key, Tag, Provider) // Binds a tagged type to a Provider function. BindTaggedInScope(Key, Tag, Provider, Tag) // Binds a tagged type to a single instance. BindTaggedInstance(Key, Tag, interface{}) // Binds a tagged type to a single instance. BindTaggedInstanceInScope(Key, Tag, interface{}, Tag) // Creates a child injector that can bind additional types not available from this Injector. CreateChildInjector() Injector // Creates a Container that can be used to retrieve instance objects from the Injector. CreateContainer() Container // Exposes a type to its parent injector. Expose(Key) // Exposes a type to its parent injector. ExposeAndRename(Key, Key) // Exposes a type to its parent injector. ExposeTaggedAndRename(Key, Tag, Key) // Exposes a type to its parent injector. ExposeAndRenameTagged(Key, Key, Tag) // Exposes a type to its parent injector. ExposeAndTag(Key, Tag) // Exposes a type to its parent injector. ExposeTaggedAndRenameTagged(Key, Tag, Key, Tag) // Exposes a tagged type to its parent injector. ExposeTagged(Key, Tag) // Wraps a Provider to cache in a given scope. Scope(key Key, provider Provider, scopeTag Tag) Provider // Gets the binding for a key, searching the current injector and all ancestor injectors. getBinding(Key) (binding, bool) /* Searches the parent injector for the key, continuing to search upward until the root injector is found. */ findAncestorBinding(Key) (binding, bool) } // The context holds all the keys used by a given object. type keyset map[Key]Key type binding struct { injector *injector provider Provider } // Bindings for each key in the injector. type bindings map[Key]binding type scopes map[Tag]Scope type injector struct { // The bindings present in this injector. bindings // Registered scopes (shared among all injectors) scopes // The parent injector. See getBinding(), findAncestorBinding(). parent *injector // A pointer to the keyset for this injector and all ancestor and descendant injectors. keyset } func CreateInjector() Injector { singleton := singletonscope{make(map[Key]interface{})} scopes := make(scopes) scopes[Singleton{}] = &singleton return &injector{ bindings: make(map[Key]binding), scopes: scopes, parent: nil, keyset: make(keyset), } } // Creates a child injector that can contain bindings not available to the parent injector. func (this *injector) CreateChildInjector() Injector { child := injector{ bindings: make(map[Key]binding), scopes: this.scopes, parent: this, keyset: this.keyset, } return &child } func (this injector) Bind(key Key, provider Provider) { if _, exists := this.bindings[key]; exists { panic(fmt.Sprintf("%s is already bound.", key)) } if _, exists := this.findAncestorBinding(key); exists { panic(fmt.Sprintf("%s is already bound in an ancestor injector.", key)) } this.keyset[key] = key this.bindings[key] = binding{&this, provider} } func (this injector) Scope(key Key, provider Provider, scopeTag Tag) Provider { var scopes = this.scopes if scope, exists := scopes[scopeTag]; exists { return scope.Scope(key, provider) } panic(fmt.Sprintf("Scope tag '%s' is not bound", scopeTag)) } func (this injector) BindInScope(key Key, provider Provider, scopeTag Tag) { this.Bind(key, this.Scope(key, provider, scopeTag)) } func (this injector) BindInstance(key Key, instance interface{}) { this.Bind(key, func(context Context, container Container) interface{} { return instance }) } func (this injector) BindInstanceInScope(key Key, value interface{}, scopeTag Tag) { this.BindInScope(key, func(context Context, container Container) interface{} { return value }, scopeTag) } func (this injector) BindTaggedInScope(bindingType Key, tag Tag, provider Provider, scopeTag Tag) { this.BindInScope(TaggedKey{bindingType, tag}, provider, scopeTag) } func (this injector) BindTagged(instanceType Key, tag Tag, provider Provider) { this.Bind(TaggedKey{instanceType, tag}, provider) } func (this injector) BindTaggedInstance(instanceType Key, tag Tag, instance interface{}) { this.BindInstance(TaggedKey{instanceType, tag}, instance) } func (this injector) BindTaggedInstanceInScope(bindingType Key, tag Tag, value interface{}, scopeTag Tag) { this.BindInstanceInScope(TaggedKey{bindingType, tag}, value, scopeTag) } // Creates a Container that is used to request values during object creation. func (this injector) CreateContainer() Container { return container{ &this, make(keyset), nil, make(map[*injector]*container), } } func (this injector) Expose(key Key) { this.ExposeAndRename(key, key) } func (this injector) ExposeTagged(key Key, tag Tag) { this.ExposeAndRename(TaggedKey{key, tag}, TaggedKey{key, tag}) } func (this injector) ExposeAndTag(key Key, tag Tag) { this.ExposeAndRename(key, TaggedKey{key, tag}) } func (this injector) ExposeTaggedAndRename(key Key, tag Tag, parentKey Key) { this.ExposeAndRename(TaggedKey{key, tag}, parentKey) } func (this injector) ExposeTaggedAndRenameTagged(key Key, tag Tag, parentKey Key, parentTag Tag) { this.ExposeAndRename(TaggedKey{key, tag}, TaggedKey{parentKey, parentTag}) } func (this injector) ExposeAndRenameTagged(key Key, parentKey Key, parentTag Tag) { this.ExposeAndRename(key, TaggedKey{parentKey, parentTag}) } func (this injector) ExposeAndRename(childKey Key, parentKey Key) { if this.parent == nil { panic(fmt.Sprintf("No parent injector available when exposing %s.", childKey)) } if _, exists := this.bindings[childKey]; !exists { panic(fmt.Sprintf("No binding for %s is present in the child injector.", childKey)) } if _, exists := this.findAncestorBinding(parentKey); exists { panic(fmt.Sprintf("A binding for %s already exists. It could come from another child injector or an ancestor injector.", parentKey)) } this.parent.bindings[parentKey] = this.bindings[childKey] } func (this injector) getBinding(key Key) (binding, bool) { binding, ok := this.bindings[key] return binding, ok } func (this injector) findAncestorBinding(key Key) (binding, bool) { parent := this.parent for parent != nil { if binding, ok := this.parent.getBinding(key); ok { return binding, ok } parent = parent.parent } return binding{}, false } /* Container provides access to the bindings configured in an Injector. All bindings are available as a Provider or as a value. A new Container should be used for each injected type. A Container will panic if a key is looked up more than once. This behavior is intended to detect and prevent cycles in depedencies. For example, suppose you have a type A that gets an instance of type B that in turn relies on type A again (A -> B -> A). The types would have a structure like this: type A struct { B } type B struct { A } func ConfigureInjector(injector inject.Injector) { injector.Bind(reflect.TypeOf(A(nil)), func (container Container) interface{} { return A { createB(container) } } injector.Bind(reflect.TypeOf(B(nil)), func (container Container) interface{} { return B { createA(container) } } } func createA(container inject.Container) { return A { B: container.GetInstanceForKey(reflect.TypeOf(A(nil))) } } func createB(container goos.Container) { return B { A: container.GetInstanceForKey(reflect.TypeOf(B(nil)) } } */ type Container interface { // Returns an instance of the type. GetInstance(Context, Key) interface{} // Returns an instance of the type tagged with the tag. GetTaggedInstance(Context, Key, Tag) interface{} // Returns a Provider that can return an instance of the type. GetProvider(Key) Provider // Returns a Provider that can return an instance of the type tagged with the tag. GetTaggedProvider(Key, Tag) Provider } type container struct { // The injector holding the bindings available to the container. injector *injector // The invocation keyset, holding all the previous requests to prevent duplicate requests. keyset // The parent container; used for exposed child bindings. parent *container // Child container for each injector children map[*injector]*container } func createChildProvider(parent *container, binding binding) Provider { var childContainer *container if bindingContainer, ok := parent.children[binding.injector]; ok { childContainer = bindingContainer } else { container := container{ binding.injector, make(keyset), parent, parent.children, } childContainer = &container parent.children[binding.injector] = childContainer } return func(context Context, container Container) interface{} { return binding.provider(context, childContainer) } } // Returns a Provider that can create an instance of the type bound to the key. func (this container) GetProvider(key Key) Provider { if _, exists := this.keyset[key]; exists { panic(fmt.Sprintf("Already looked up %s (%+v). Is there a cycle of dependencies?", key, reflect.TypeOf(key))) } this.keyset[key] = key if binding, ok := this.injector.bindings[key]; ok { if binding.injector == this.injector { return binding.provider } else { return createChildProvider(&this, binding) } } if binding, ok := this.injector.findAncestorBinding(key); ok { return createChildProvider(&this, binding) } panic(fmt.Sprintf("Unable to find %s in injector", key)) } // Returns a Provider that can create an instance of the instanceType tagged with tag. func (this container) GetTaggedProvider(instanceType Key, tag Tag) Provider { return this.GetProvider(TaggedKey{instanceType, tag}) } // Returns an instance of the type bound to the key. func (this container) GetInstance(context Context, key Key) interface{} { return this.GetProvider(key)(context, this) } // Returns an instance of the instanceType tagged with tag. func (this container) GetTaggedInstance(context Context, instanceType Key, tag Tag) interface{} { return this.GetInstance(context, TaggedKey{instanceType, tag}) } func (this TaggedKey) String() string { if this.Tag == nil { return fmt.Sprintf("%v<%s>", reflect.TypeOf(this.Key), reflect.TypeOf(this.Tag)) } return fmt.Sprintf("%v<%s(%v)>", reflect.TypeOf(this.Key), reflect.TypeOf(this.Tag), this.Tag) } type simplescope struct { name string values map[Context]map[Key]interface{} } type Scope interface { Scope(Key, Provider) Provider } type scopeKey struct { Context Key } type SimpleScope interface { Scope(Key, Provider) Provider Enter(Context) Exit(Context) } func (this *simplescope) Enter(context Context) { this.values[context] = make(map[Key]interface{}) } func (this *simplescope) Exit(context Context) { if _, exists := this.values[context]; exists { delete(this.values, context) } else { panic(fmt.Sprintf("Already out of context when existing scope %v", this)) } } func (this *simplescope) Scope(key Key, provider Provider) Provider { return func(context Context, container Container) interface{} { if scope, exists := this.values[context]; exists { if value, exists := scope[key]; exists { return value } value := provider(context, container) scope[key] = value return value } panic(fmt.Sprintf("Attempt to access %s outside of scope %s. %d scopes are active.", key, this.name, len(this.values))) } } func CreateSimpleScope() SimpleScope { scope := simplescope{name: "SimpleScope", values: make(map[Context]map[Key]interface{})} return &scope } func CreateSimpleScopeWithName(name string) SimpleScope { scope := simplescope{name: name, values: make(map[Context]map[Key]interface{})} return &scope } func (this injector) BindScope(scope Scope, scopeTag Tag) { if _, exists := this.scopes[scopeTag]; exists { panic(fmt.Sprintf("Scope is already bound for tag '%s'", scopeTag)) } this.scopes[scopeTag] = scope } type singletonscope struct { values map[Key]interface{} } func (this *singletonscope) Enter(context Context) { panic("You're always in singletonscope. Do not try to enter this scope.") } func (this *singletonscope) Exit(context Context) { panic("You're always in singletonscope. Do not try to exit this scope.") } func (this *singletonscope) Scope(key Key, provider Provider) Provider { return func(context Context, container Container) interface{} { if value, exists := this.values[key]; exists { return value } value := provider(context, container) this.values[key] = value return value } }
go/src/github.com/nicholasjackson/blackpuppy-api-mail/inject/inject.go
0.775732
0.490968
inject.go
starcoder
package model import ( "fmt" "math" "strings" "gonum.org/v1/gonum/mat" ) // State defines the interface for any state implementation. type State interface { IsTerminal() bool Vector() mat.Vector } // StateValue is a map of expected value for state. type StateValue map[State]float64 // Get ... func (sv StateValue) Get(at State) float64 { return sv[at] } // Clone ... func (sv StateValue) Clone() StateValue { cloned := make(StateValue, len(sv)) for s, v := range sv { cloned[s] = v } return cloned } // Print mimics Python's numpy matrix printing func (sv StateValue) Print(states []State, width int) (str string) { i := 0 str = "[[\t" for _, s := range states { v := sv[s] if v >= 0 { str += " " } else { str += "-" } if v == 0 { str += "0.\t\t" } else { str += fmt.Sprintf("%.6f\t", math.Abs(v)) } i++ if i == len(sv) { str += "]" } else if i%width == 0 { str += "]\n [\t" } } str += "]" return } // ToPolicy transforms the state value to policy for action func (sv StateValue) ToPolicy(actions map[Action]ActionFunc, states []State, width int) (map[State][]Action, string) { // Build policy policy := make(map[State][]Action, len(states)) for _, s := range states { if s.IsTerminal() { policy[s] = []Action{} } else { values := make(map[Action]float64, len(actions)) for a, f := range actions { next, _ := f(s, a) if next == s { values[a] = -math.MaxFloat64 } else { values[a] = sv[next] } } var highest float64 = -math.MaxFloat64 taken := make(map[float64][]Action) for a, v := range values { if v >= highest { highest = v if len(taken[highest]) > 0 { existing := taken[highest] existing = append(existing, a) taken[highest] = existing } else { taken[highest] = []Action{a} } } } policy[s] = taken[highest] } } // Create display i := 0 str := "[[\t" for _, s := range states { as := policy[s] if len(as) == 0 { str += fmt.Sprintf("%-12s\t", "-") } else { names := []string{} for _, a := range as { names = append(names, a.GetName()) } str += fmt.Sprintf("%-12s\t", strings.Join(names, ",")) } i++ if i == len(policy) { str += "]" } else if i%width == 0 { str += "]\n [\t" } } str += "]" return policy, str }
model/state.go
0.585931
0.451327
state.go
starcoder
package matrix import ( "errors" "fmt" ) // ScanDirection scan matrix driection type ScanDirection uint const ( // ROW for row first ROW ScanDirection = 1 // COLUMN for column first COLUMN ScanDirection = 2 ) // State value of matrix map[][] type State uint16 const ( // StateFalse 0xffff FALSE StateFalse State = 0xffff // ZERO 0x0 FALSE ZERO State = 0xeeee // StateTrue 0x0 TRUE StateTrue State = 0x0 // StateInit 0x9999 use for initial state StateInit State = 0x9999 // StateVersion 0x4444 StateVersion State = 0x4444 // StateFormat 0x7777 for persisted state StateFormat State = 0x7777 ) func (s State) String() string { return fmt.Sprintf("0x%X", uint16(s)) } var ( // ErrorOutRangeOfW x out of range of Width ErrorOutRangeOfW = errors.New("out of range of width") // ErrorOutRangeOfH y out of range of Height ErrorOutRangeOfH = errors.New("out of range of height") ) func StateSliceMatched(ss1, ss2 []State) bool { if len(ss1) != len(ss2) { return false } for idx := range ss1 { if (ss1[idx] ^ ss2[idx]) != 0 { return false } } return true } // New generate a matrix with map[][]bool func New(width, height int) *Matrix { mat := make([][]State, width) for w := 0; w < width; w++ { mat[w] = make([]State, height) } m := &Matrix{ mat: mat, width: width, height: height, } m.init() return m } // Matrix is a matrix data type // width:3 height: 4 for [3][4]int type Matrix struct { mat [][]State width int height int } // do some init work func (m *Matrix) init() { for w := 0; w < m.width; w++ { for h := 0; h < m.height; h++ { m.mat[w][h] = StateInit } } } // Print to stdout func (m *Matrix) print() { m.Iterate(ROW, func(x, y int, s State) { fmt.Printf("(%2d,%2d)%s ", x, y, s) if (x + 1) == m.width { fmt.Println() } }) } // Copy matrix into a new Matrix func (m *Matrix) Copy() *Matrix { newMat := make([][]State, m.width) for w := 0; w < m.width; w++ { newMat[w] = make([]State, m.height) copy(newMat[w], m.mat[w]) } newM := &Matrix{ width: m.width, height: m.height, mat: newMat, } return newM } // Width ... width func (m *Matrix) Width() int { return m.width } // Height ... height func (m *Matrix) Height() int { return m.height } // Set [w][h] as true func (m *Matrix) Set(w, h int, c State) error { if w >= m.width || w < 0 { return ErrorOutRangeOfW } if h >= m.height || h < 0 { return ErrorOutRangeOfH } m.mat[w][h] = c return nil } // Get state value from matrix with postion (x, y) func (m *Matrix) Get(w, h int) (State, error) { if w >= m.width || w < 0 { return ZERO, ErrorOutRangeOfW } if h >= m.height || h < 0 { return ZERO, ErrorOutRangeOfH } return m.mat[w][h], nil } // IterateFunc ... type IterateFunc func(int, int, State) // Iterate the Matrix with loop direction ROW major or COLUMN major func (m *Matrix) Iterate(dir ScanDirection, f IterateFunc) { // row direction first if dir == ROW { for h := 0; h < m.height; h++ { for w := 0; w < m.width; w++ { f(w, h, m.mat[w][h]) } } return } // column direction first if dir == COLUMN { for w := 0; w < m.width; w++ { for h := 0; h < m.height; h++ { f(w, h, m.mat[w][h]) } } return } } // XOR ... func XOR(s1, s2 State) State { if s1 != s2 { return StateTrue } return StateFalse }
matrix/matrix.go
0.586996
0.445771
matrix.go
starcoder
package eval import ( "reflect" "unsafe" "github.com/DataDog/datadog-agent/pkg/security/secl/ast" "github.com/pkg/errors" ) // RuleID - ID of a Rule type RuleID = string // Rule - Rule object identified by an `ID` containing a SECL `Expression` type Rule struct { ID RuleID Expression string Tags []string Opts *Opts Model Model evaluator *RuleEvaluator ast *ast.Rule } // RuleEvaluator - Evaluation part of a Rule type RuleEvaluator struct { Eval BoolEvalFnc EventTypes []EventType FieldValues map[Field][]FieldValue partialEvals map[Field]BoolEvalFnc } // PartialEval partially evaluation of the Rule with the given Field. func (r *RuleEvaluator) PartialEval(ctx *Context, field Field) (bool, error) { eval, ok := r.partialEvals[field] if !ok { return false, &ErrFieldNotFound{Field: field} } return eval(ctx), nil } func (r *RuleEvaluator) setPartial(field string, partialEval BoolEvalFnc) { if r.partialEvals == nil { r.partialEvals = make(map[string]BoolEvalFnc) } r.partialEvals[field] = partialEval } // GetFields - Returns all the Field that the RuleEvaluator handles func (r *RuleEvaluator) GetFields() []Field { fields := make([]Field, len(r.FieldValues)) i := 0 for key := range r.FieldValues { fields[i] = key i++ } return fields } // Eval - Evaluates func (r *Rule) Eval(ctx *Context) bool { return r.evaluator.Eval(ctx) } // GetFieldValues returns the values of the given field func (r *Rule) GetFieldValues(field Field) []FieldValue { return r.evaluator.FieldValues[field] } // PartialEval - Partial evaluation with the given Field func (r *Rule) PartialEval(ctx *Context, field Field) (bool, error) { return r.evaluator.PartialEval(ctx, field) } // GetPartialEval - Returns the Partial RuleEvaluator for the given Field func (r *Rule) GetPartialEval(field Field) BoolEvalFnc { return r.evaluator.partialEvals[field] } // GetFields - Returns all the Field of the Rule including field of the Macro used func (r *Rule) GetFields() []Field { fields := r.evaluator.GetFields() for _, macro := range r.Opts.Macros { fields = append(fields, macro.GetFields()...) } return fields } // GetEvaluator - Returns the RuleEvaluator of the Rule corresponding to the SECL `Expression` func (r *Rule) GetEvaluator() *RuleEvaluator { return r.evaluator } // GetEventTypes - Returns a list of all the event that the `Expression` handles func (r *Rule) GetEventTypes() []EventType { eventTypes := r.evaluator.EventTypes for _, macro := range r.Opts.Macros { eventTypes = append(eventTypes, macro.GetEventTypes()...) } return eventTypes } // GetAst - Returns the representation of the SECL `Expression` func (r *Rule) GetAst() *ast.Rule { return r.ast } // Parse - Transforms the SECL `Expression` into its AST representation func (r *Rule) Parse() error { astRule, err := ast.ParseRule(r.Expression) if err != nil { return err } r.ast = astRule return nil } func combineRegisters(combinations []Registers, regID RegisterID, values []unsafe.Pointer) []Registers { var combined []Registers if len(combinations) == 0 { for _, value := range values { registers := make(Registers) registers[regID] = &Register{ Value: value, } combined = append(combined, registers) } return combined } for _, combination := range combinations { for _, value := range values { regs := combination.Clone() regs[regID] = &Register{ Value: value, } combined = append(combined, regs) } } return combined } func handleRegisters(evalFnc BoolEvalFnc, registersInfo map[RegisterID]*registerInfo) BoolEvalFnc { return func(ctx *Context) bool { ctx.Registers = make(Registers) // start with the head of all register for id, info := range registersInfo { ctx.Registers[id] = &Register{ Value: info.iterator.Front(ctx), iterator: info.iterator, } } // capture all the values for each register registerValues := make(map[RegisterID][]unsafe.Pointer) for id, reg := range ctx.Registers { values := []unsafe.Pointer{} for reg.Value != nil { // short cut if we find a solution while constructing the combinations if evalFnc(ctx) { return true } values = append(values, reg.Value) reg.Value = reg.iterator.Next() } registerValues[id] = values // restore the head value reg.Value = reg.iterator.Front(ctx) } // no need to combine there is only one registers used if len(registersInfo) == 1 { return false } // generate all the combinations var combined []Registers for id, values := range registerValues { combined = combineRegisters(combined, id, values) } // eval the combinations for _, registers := range combined { ctx.Registers = registers if evalFnc(ctx) { return true } } return false } } func ruleToEvaluator(rule *ast.Rule, model Model, opts *Opts) (*RuleEvaluator, error) { macros := make(map[MacroID]*MacroEvaluator) for id, macro := range opts.Macros { macros[id] = macro.evaluator } state := newState(model, "", macros) eval, _, _, err := nodeToEvaluator(rule.BooleanExpression, opts, state) if err != nil { return nil, err } evalBool, ok := eval.(*BoolEvaluator) if !ok { return nil, NewTypeError(rule.Pos, reflect.Bool) } events, err := eventTypesFromFields(model, state) if err != nil { return nil, err } // direct value, no bool evaluator, wrap value if evalBool.EvalFnc == nil { evalBool.EvalFnc = func(ctx *Context) bool { return evalBool.Value } } // rule uses register replace the original eval function with the one handling registers if len(state.registersInfo) > 0 { evalBool.EvalFnc = handleRegisters(evalBool.EvalFnc, state.registersInfo) } return &RuleEvaluator{ Eval: evalBool.EvalFnc, EventTypes: events, FieldValues: state.fieldValues, }, nil } // GenEvaluator - Compile and generates the RuleEvaluator func (r *Rule) GenEvaluator(model Model, opts *Opts) error { r.Model = model r.Opts = opts evaluator, err := ruleToEvaluator(r.ast, model, opts) if err != nil { if err, ok := err.(*ErrAstToEval); ok { return errors.Wrapf(&ErrRuleParse{pos: err.Pos, expr: r.Expression}, "rule syntax error: %s", err) } return errors.Wrap(err, "rule compilation error") } r.evaluator = evaluator return nil } func (r *Rule) genMacroPartials() (map[Field]map[MacroID]*MacroEvaluator, error) { partials := make(map[Field]map[MacroID]*MacroEvaluator) for _, field := range r.GetFields() { for id, macro := range r.Opts.Macros { // NOTE(safchain) this is not working with nested macro. It will be removed once partial // will be generated another way evaluator, err := macroToEvaluator(macro.ast, r.Model, r.Opts, field) if err != nil { if err, ok := err.(*ErrAstToEval); ok { return nil, errors.Wrap(&ErrRuleParse{pos: err.Pos, expr: macro.Expression}, "macro syntax error") } return nil, errors.Wrap(err, "macro compilation error") } macroEvaluators, exists := partials[field] if !exists { macroEvaluators = make(map[MacroID]*MacroEvaluator) partials[field] = macroEvaluators } macroEvaluators[id] = evaluator } } return partials, nil } // GenPartials - Compiles and generates partial Evaluators func (r *Rule) GenPartials() error { macroPartials, err := r.genMacroPartials() if err != nil { return err } for _, field := range r.GetFields() { state := newState(r.Model, field, macroPartials[field]) pEval, _, _, err := nodeToEvaluator(r.ast.BooleanExpression, r.Opts, state) if err != nil { return errors.Wrapf(err, "couldn't generate partial for field %s and rule %s", field, r.ID) } pEvalBool, ok := pEval.(*BoolEvaluator) if !ok { return NewTypeError(r.ast.Pos, reflect.Bool) } if pEvalBool.EvalFnc == nil { pEvalBool.EvalFnc = func(ctx *Context) bool { return pEvalBool.Value } } // rule uses register replace the original eval function with the one handling registers if len(state.registersInfo) > 0 { // generate register map for the given field only registersInfo := make(map[RegisterID]*registerInfo) for regID, info := range state.registersInfo { if _, exists := info.subFields[field]; exists { registersInfo[regID] = info } } pEvalBool.EvalFnc = handleRegisters(pEvalBool.EvalFnc, registersInfo) } r.evaluator.setPartial(field, pEvalBool.EvalFnc) } return nil }
pkg/security/secl/eval/rule.go
0.782413
0.402157
rule.go
starcoder
package utils import ( "math" "strconv" pqueue "github.com/andela-sjames/priorityQueue" ) /** dijkstra function in it's base form takes a directed acyclic and uses a naive approach - a non Indexed Priority Queue (IPQ) to determine the shortest distance from the start of a graph to the end of the graph. It returns a slice of the shortest distance and a slice of the previous node traversed to get to the end of the graph. **/ func dijstra(g adjList, n int, s int, e int) ([]int, []int) { // g - adjacency list of a weighted graph // n - the number of nodes in the graph // s - the index of the starting node ( 0 <= s < n ) // e - the index of the end node ( 0 <= e < n ) visited := make([]bool, n) distance := make([]int, n) // keep track of the previous node we took // to get to the current node previous := make([]int, n) for i := range visited { visited[i] = false } for i := range distance { distance[i] = math.MaxInt64 } distance[s] = 0 // Set Min option to true for minheap minheap := pqueue.NewHeap(pqueue.Options{ Min: true, }) minheap.InsertPriority(string(s), 0) for minheap.Length() != 0 { stringAtIndex, min := minheap.Poll() integerAtIndex, _ := strconv.Atoi(stringAtIndex) // current node is integerAtIndex visited[integerAtIndex] = true // optimization to ignore stale index // (index, min_dis) pair if distance[integerAtIndex] < min { continue } // loop through all the neighbours of // the current node cn := g[integerAtIndex].head for cn != nil { if visited[cn.vertex] { continue } newdist := distance[integerAtIndex] + cn.weight if newdist < distance[cn.vertex] { previous[cn.vertex] = integerAtIndex distance[cn.vertex] = newdist minheap.InsertPriority(strconv.Itoa(cn.vertex), newdist) } if cn.next == nil { break } cn = cn.next } // Optimise here to stop early. if integerAtIndex == e { return distance, previous } } return distance, previous }
utils/dijkstra.go
0.735167
0.519704
dijkstra.go
starcoder
// This is a Go replica of https://github.com/google/or-tools/blob/master/ortools/linear_solver/samples/integer_programming_example.py // Small example to illustrate solving a MIP problem. package main import ( "fmt" "github.com/baobabsoluciones/ortoolslp" ) func main() { // Integer programming sample. // [START solver] // Create the mip solver with the desired backend solver := ortoolslp.NewSolver("IntegerProgrammingExample", ortoolslp.SolverCBC_MIXED_INTEGER_PROGRAMMING) // solver := ortoolslp.NewSolver("IntegerProgrammingExample", ortoolslp.SolverCLP_LINEAR_PROGRAMMING) // solver := ortoolslp.NewSolver("IntegerProgrammingExample", ortoolslp.SolverGLOP_LINEAR_PROGRAMMING) // solver := ortoolslp.NewSolver("IntegerProgrammingExample", ortoolslp.SolverGLPK_LINEAR_PROGRAMMING) // solver := ortoolslp.NewSolver("IntegerProgrammingExample", ortoolslp.SolverSCIP_MIXED_INTEGER_PROGRAMMING) // solver := ortoolslp.NewSolver("IntegerProgrammingExample", ortoolslp.SolverCPLEX_LINEAR_PROGRAMMING) // solver := ortoolslp.NewSolver("IntegerProgrammingExample", ortoolslp.SolverGUROBI_LINEAR_PROGRAMMING) // [END solver] // [START variables] // x, y, and z are non-negative integer variables. x := solver.IntVar(0.0, ortoolslp.SolverInfinity(), "x") y := solver.IntVar(0.0, ortoolslp.SolverInfinity(), "y") z := solver.IntVar(0.0, ortoolslp.SolverInfinity(), "z") // [END variables] // [START constraints] // 2*x + 7*y + 3*z <= 50 constraint0 := solver.Constraint(-ortoolslp.SolverInfinity(), float64(50)) constraint0.SetCoefficient(x, 2) constraint0.SetCoefficient(y, 7) constraint0.SetCoefficient(z, 3) // 3*x - 5*y + 7*z <= 45 constraint1 := solver.Constraint(-ortoolslp.SolverInfinity(), float64(45)) constraint1.SetCoefficient(x, 3) constraint1.SetCoefficient(y, -5) constraint1.SetCoefficient(z, 7) // 5*x + 2*y - 6*z <= 37 constraint2 := solver.Constraint(-ortoolslp.SolverInfinity(), float64(37)) constraint2.SetCoefficient(x, 5) constraint2.SetCoefficient(y, 2) constraint2.SetCoefficient(z, -6) // [END constraints] // [START objective] // Maximize 2*x + 2*y + 3*z objective := solver.Objective() objective.SetCoefficient(x, 2) objective.SetCoefficient(y, 2) objective.SetCoefficient(z, 3) objective.SetMaximization() // [END objective] // Solve the problem and print the solution. // [START print_solution] solver.Solve() // Print the objective value of the solution. fmt.Printf("Maximum objective function value = %f\n", solver.Objective().Value()) fmt.Println() // Print the value of each variable in the solution. fmt.Printf("%s = %f\n", x.Name(), x.Solution_value()) fmt.Printf("%s = %f\n", y.Name(), y.Solution_value()) fmt.Printf("%s = %f\n", z.Name(), z.Solution_value()) // [END print_solution] }
examples/MILP/integer_programming_example.go
0.855369
0.448849
integer_programming_example.go
starcoder
package nistec import ( "crypto/elliptic/internal/fiat" "crypto/subtle" "errors" ) var p384B, _ = new(fiat.P384Element).SetBytes([]byte{ 0xb3, 0x31, 0x2f, 0xa7, 0xe2, 0x3e, 0xe7, 0xe4, 0x98, 0x8e, 0x05, 0x6b, 0xe3, 0xf8, 0x2d, 0x19, 0x18, 0x1d, 0x9c, 0x6e, 0xfe, 0x81, 0x41, 0x12, 0x03, 0x14, 0x08, 0x8f, 0x50, 0x13, 0x87, 0x5a, 0xc6, 0x56, 0x39, 0x8d, 0x8a, 0x2e, 0xd1, 0x9d, 0x2a, 0x85, 0xc8, 0xed, 0xd3, 0xec, 0x2a, 0xef}) var p384G, _ = NewP384Point().SetBytes([]byte{0x4, 0xaa, 0x87, 0xca, 0x22, 0xbe, 0x8b, 0x05, 0x37, 0x8e, 0xb1, 0xc7, 0x1e, 0xf3, 0x20, 0xad, 0x74, 0x6e, 0x1d, 0x3b, 0x62, 0x8b, 0xa7, 0x9b, 0x98, 0x59, 0xf7, 0x41, 0xe0, 0x82, 0x54, 0x2a, 0x38, 0x55, 0x02, 0xf2, 0x5d, 0xbf, 0x55, 0x29, 0x6c, 0x3a, 0x54, 0x5e, 0x38, 0x72, 0x76, 0x0a, 0xb7, 0x36, 0x17, 0xde, 0x4a, 0x96, 0x26, 0x2c, 0x6f, 0x5d, 0x9e, 0x98, 0xbf, 0x92, 0x92, 0xdc, 0x29, 0xf8, 0xf4, 0x1d, 0xbd, 0x28, 0x9a, 0x14, 0x7c, 0xe9, 0xda, 0x31, 0x13, 0xb5, 0xf0, 0xb8, 0xc0, 0x0a, 0x60, 0xb1, 0xce, 0x1d, 0x7e, 0x81, 0x9d, 0x7a, 0x43, 0x1d, 0x7c, 0x90, 0xea, 0x0e, 0x5f}) const p384ElementLength = 48 // P384Point is a P-384 point. The zero value is NOT valid. type P384Point struct { // The point is represented in projective coordinates (X:Y:Z), // where x = X/Z and y = Y/Z. x, y, z *fiat.P384Element } // NewP384Point returns a new P384Point representing the point at infinity point. func NewP384Point() *P384Point { return &P384Point{ x: new(fiat.P384Element), y: new(fiat.P384Element).One(), z: new(fiat.P384Element), } } // NewP384Generator returns a new P384Point set to the canonical generator. func NewP384Generator() *P384Point { return (&P384Point{ x: new(fiat.P384Element), y: new(fiat.P384Element), z: new(fiat.P384Element), }).Set(p384G) } // Set sets p = q and returns p. func (p *P384Point) Set(q *P384Point) *P384Point { p.x.Set(q.x) p.y.Set(q.y) p.z.Set(q.z) return p } // SetBytes sets p to the compressed, uncompressed, or infinity value encoded in // b, as specified in SEC 1, Version 2.0, Section 2.3.4. If the point is not on // the curve, it returns nil and an error, and the receiver is unchanged. // Otherwise, it returns p. func (p *P384Point) SetBytes(b []byte) (*P384Point, error) { switch { // Point at infinity. case len(b) == 1 && b[0] == 0: return p.Set(NewP384Point()), nil // Uncompressed form. case len(b) == 1+2*p384ElementLength && b[0] == 4: x, err := new(fiat.P384Element).SetBytes(b[1 : 1+p384ElementLength]) if err != nil { return nil, err } y, err := new(fiat.P384Element).SetBytes(b[1+p384ElementLength:]) if err != nil { return nil, err } if err := p384CheckOnCurve(x, y); err != nil { return nil, err } p.x.Set(x) p.y.Set(y) p.z.One() return p, nil // Compressed form case len(b) == 1+p384ElementLength && b[0] == 0: return nil, errors.New("unimplemented") // TODO(filippo) default: return nil, errors.New("invalid P384 point encoding") } } func p384CheckOnCurve(x, y *fiat.P384Element) error { // x³ - 3x + b. x3 := new(fiat.P384Element).Square(x) x3.Mul(x3, x) threeX := new(fiat.P384Element).Add(x, x) threeX.Add(threeX, x) x3.Sub(x3, threeX) x3.Add(x3, p384B) // y² = x³ - 3x + b y2 := new(fiat.P384Element).Square(y) if x3.Equal(y2) != 1 { return errors.New("P384 point not on curve") } return nil } // Bytes returns the uncompressed or infinity encoding of p, as specified in // SEC 1, Version 2.0, Section 2.3.3. Note that the encoding of the point at // infinity is shorter than all other encodings. func (p *P384Point) Bytes() []byte { // This function is outlined to make the allocations inline in the caller // rather than happen on the heap. var out [133]byte return p.bytes(&out) } func (p *P384Point) bytes(out *[133]byte) []byte { if p.z.IsZero() == 1 { return append(out[:0], 0) } zinv := new(fiat.P384Element).Invert(p.z) xx := new(fiat.P384Element).Mul(p.x, zinv) yy := new(fiat.P384Element).Mul(p.y, zinv) buf := append(out[:0], 4) buf = append(buf, xx.Bytes()...) buf = append(buf, yy.Bytes()...) return buf } // Add sets q = p1 + p2, and returns q. The points may overlap. func (q *P384Point) Add(p1, p2 *P384Point) *P384Point { // Complete addition formula for a = -3 from "Complete addition formulas for // prime order elliptic curves" (https://eprint.iacr.org/2015/1060), §A.2. t0 := new(fiat.P384Element).Mul(p1.x, p2.x) // t0 := X1 * X2 t1 := new(fiat.P384Element).Mul(p1.y, p2.y) // t1 := Y1 * Y2 t2 := new(fiat.P384Element).Mul(p1.z, p2.z) // t2 := Z1 * Z2 t3 := new(fiat.P384Element).Add(p1.x, p1.y) // t3 := X1 + Y1 t4 := new(fiat.P384Element).Add(p2.x, p2.y) // t4 := X2 + Y2 t3.Mul(t3, t4) // t3 := t3 * t4 t4.Add(t0, t1) // t4 := t0 + t1 t3.Sub(t3, t4) // t3 := t3 - t4 t4.Add(p1.y, p1.z) // t4 := Y1 + Z1 x3 := new(fiat.P384Element).Add(p2.y, p2.z) // X3 := Y2 + Z2 t4.Mul(t4, x3) // t4 := t4 * X3 x3.Add(t1, t2) // X3 := t1 + t2 t4.Sub(t4, x3) // t4 := t4 - X3 x3.Add(p1.x, p1.z) // X3 := X1 + Z1 y3 := new(fiat.P384Element).Add(p2.x, p2.z) // Y3 := X2 + Z2 x3.Mul(x3, y3) // X3 := X3 * Y3 y3.Add(t0, t2) // Y3 := t0 + t2 y3.Sub(x3, y3) // Y3 := X3 - Y3 z3 := new(fiat.P384Element).Mul(p384B, t2) // Z3 := b * t2 x3.Sub(y3, z3) // X3 := Y3 - Z3 z3.Add(x3, x3) // Z3 := X3 + X3 x3.Add(x3, z3) // X3 := X3 + Z3 z3.Sub(t1, x3) // Z3 := t1 - X3 x3.Add(t1, x3) // X3 := t1 + X3 y3.Mul(p384B, y3) // Y3 := b * Y3 t1.Add(t2, t2) // t1 := t2 + t2 t2.Add(t1, t2) // t2 := t1 + t2 y3.Sub(y3, t2) // Y3 := Y3 - t2 y3.Sub(y3, t0) // Y3 := Y3 - t0 t1.Add(y3, y3) // t1 := Y3 + Y3 y3.Add(t1, y3) // Y3 := t1 + Y3 t1.Add(t0, t0) // t1 := t0 + t0 t0.Add(t1, t0) // t0 := t1 + t0 t0.Sub(t0, t2) // t0 := t0 - t2 t1.Mul(t4, y3) // t1 := t4 * Y3 t2.Mul(t0, y3) // t2 := t0 * Y3 y3.Mul(x3, z3) // Y3 := X3 * Z3 y3.Add(y3, t2) // Y3 := Y3 + t2 x3.Mul(t3, x3) // X3 := t3 * X3 x3.Sub(x3, t1) // X3 := X3 - t1 z3.Mul(t4, z3) // Z3 := t4 * Z3 t1.Mul(t3, t0) // t1 := t3 * t0 z3.Add(z3, t1) // Z3 := Z3 + t1 q.x.Set(x3) q.y.Set(y3) q.z.Set(z3) return q } // Double sets q = p + p, and returns q. The points may overlap. func (q *P384Point) Double(p *P384Point) *P384Point { // Complete addition formula for a = -3 from "Complete addition formulas for // prime order elliptic curves" (https://eprint.iacr.org/2015/1060), §A.2. t0 := new(fiat.P384Element).Square(p.x) // t0 := X ^ 2 t1 := new(fiat.P384Element).Square(p.y) // t1 := Y ^ 2 t2 := new(fiat.P384Element).Square(p.z) // t2 := Z ^ 2 t3 := new(fiat.P384Element).Mul(p.x, p.y) // t3 := X * Y t3.Add(t3, t3) // t3 := t3 + t3 z3 := new(fiat.P384Element).Mul(p.x, p.z) // Z3 := X * Z z3.Add(z3, z3) // Z3 := Z3 + Z3 y3 := new(fiat.P384Element).Mul(p384B, t2) // Y3 := b * t2 y3.Sub(y3, z3) // Y3 := Y3 - Z3 x3 := new(fiat.P384Element).Add(y3, y3) // X3 := Y3 + Y3 y3.Add(x3, y3) // Y3 := X3 + Y3 x3.Sub(t1, y3) // X3 := t1 - Y3 y3.Add(t1, y3) // Y3 := t1 + Y3 y3.Mul(x3, y3) // Y3 := X3 * Y3 x3.Mul(x3, t3) // X3 := X3 * t3 t3.Add(t2, t2) // t3 := t2 + t2 t2.Add(t2, t3) // t2 := t2 + t3 z3.Mul(p384B, z3) // Z3 := b * Z3 z3.Sub(z3, t2) // Z3 := Z3 - t2 z3.Sub(z3, t0) // Z3 := Z3 - t0 t3.Add(z3, z3) // t3 := Z3 + Z3 z3.Add(z3, t3) // Z3 := Z3 + t3 t3.Add(t0, t0) // t3 := t0 + t0 t0.Add(t3, t0) // t0 := t3 + t0 t0.Sub(t0, t2) // t0 := t0 - t2 t0.Mul(t0, z3) // t0 := t0 * Z3 y3.Add(y3, t0) // Y3 := Y3 + t0 t0.Mul(p.y, p.z) // t0 := Y * Z t0.Add(t0, t0) // t0 := t0 + t0 z3.Mul(t0, z3) // Z3 := t0 * Z3 x3.Sub(x3, z3) // X3 := X3 - Z3 z3.Mul(t0, t1) // Z3 := t0 * t1 z3.Add(z3, z3) // Z3 := Z3 + Z3 z3.Add(z3, z3) // Z3 := Z3 + Z3 q.x.Set(x3) q.y.Set(y3) q.z.Set(z3) return q } // Select sets q to p1 if cond == 1, and to p2 if cond == 0. func (q *P384Point) Select(p1, p2 *P384Point, cond int) *P384Point { q.x.Select(p1.x, p2.x, cond) q.y.Select(p1.y, p2.y, cond) q.z.Select(p1.z, p2.z, cond) return q } // ScalarMult sets p = scalar * q, and returns p. func (p *P384Point) ScalarMult(q *P384Point, scalar []byte) *P384Point { // table holds the first 16 multiples of q. The explicit newP384Point calls // get inlined, letting the allocations live on the stack. var table = [16]*P384Point{ NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), NewP384Point(), } for i := 1; i < 16; i++ { table[i].Add(table[i-1], q) } // Instead of doing the classic double-and-add chain, we do it with a // four-bit window: we double four times, and then add [0-15]P. t := NewP384Point() p.Set(NewP384Point()) for _, byte := range scalar { p.Double(p) p.Double(p) p.Double(p) p.Double(p) for i := uint8(0); i < 16; i++ { cond := subtle.ConstantTimeByteEq(byte>>4, i) t.Select(table[i], t, cond) } p.Add(p, t) p.Double(p) p.Double(p) p.Double(p) p.Double(p) for i := uint8(0); i < 16; i++ { cond := subtle.ConstantTimeByteEq(byte&0b1111, i) t.Select(table[i], t, cond) } p.Add(p, t) } return p }
src/crypto/elliptic/internal/nistec/p384.go
0.531209
0.464537
p384.go
starcoder
package pbinfo import ( "strings" "time" "github.com/docker/go-units" ) // ProblemDifficulty represents the difficulty of a problem. type ProblemDifficulty int const ( Unknown ProblemDifficulty = iota Easy Medium Difficult Contest difficultyEasyString = "easy" difficultyMediumString = "medium" difficultyDifficultString = "difficult" difficultyContestString = "contest" difficultyUnknownString = "unknown" ) func (p ProblemDifficulty) String() string { switch p { case Easy: return difficultyEasyString case Medium: return difficultyMediumString case Difficult: return difficultyDifficultString case Contest: return difficultyContestString default: return difficultyUnknownString } } var asciiReplacer = strings.NewReplacer("ă", "a", "â", "a", "î", "i", "ș", "s", "ț", "t") // ParseProblemDifficulty tries to determine the difficulty of a problem from the given string. // It normalizes the input by converting it to lowercase and converting letters with diacritics // to their closest ASCII equivalent, and then it compares the result with certain predefined values // associated with difficulty levels. If no matching value is found, the Unknown difficulty is returned. func ParseProblemDifficulty(input string) ProblemDifficulty { switch asciiReplacer.Replace(strings.ToLower(input)) { case difficultyEasyString, "usoara", "usor": return Easy case difficultyMediumString, "medie", "mediu": return Medium case difficultyDifficultString, "dificila", "dificil": return Difficult case difficultyContestString, "concurs": return Contest default: return Unknown } } // Problem represents a single PbInfo problem. type Problem struct { // The ID of the problem. ID int // The name of the problem. Name string // The person that published this problem. Publisher string // The grade the problem is targeted at. If 0, grade is unknown. Grade int // The input file. Is equal to "-" if input is from STDIN. Input string // The output file. It is empty if the output is to STDOUT. Output string // The maximum execution time of the solution. If 0, no time limit is given. MaxTime time.Duration // The maximum amount of both stack and heap memory used by the solution, in bytes. // If 0, no memory limit is given. MaxMemoryBytes int64 // The maximum amount of stack memory used by the solution, in bytes. // If 0, no memory limit is given. MaxStackBytes int64 // The source of the problem: the place where it was taken from. If empty, source is unknown. Source string // The authors of the problem. If empty/nil, the author is considered the poster. Authors []string // The difficulty of the problem. Difficulty ProblemDifficulty // The score of the latest uploaded solution. It is nil if no solution was uploaded before. Score *int } // ReadableMaxMemory returns the memory limit of the solution in a human-readable format. func (p *Problem) ReadableMaxMemory() string { return units.HumanSize(float64(p.MaxMemoryBytes)) } // ReadableMaxStack returns the stack memory limit of the solution in a human-readable format. func (p *Problem) ReadableMaxStack() string { return units.HumanSize(float64(p.MaxStackBytes)) } // TestCase holds the input and the expected output for a single test case of a problem. type TestCase struct { Input []byte Output []byte IsExample bool Score int }
pkg/pbinfo/problem.go
0.715921
0.434521
problem.go
starcoder
package compile import ( "github.com/danos/yang/parse" "github.com/danos/yang/schema" ) /* * To add extensions to the schema tree a simple pattern is followed. * The compiler turns a set of parse nodes into a schema node. As each * node is compiled, it is passed to the extensions which are given an * opportunity to wrap (decorate) the node with any extensions. If * the extensions are misused then an error may be returned instead. */ type Extensions interface { // Returns a function used to get the cardinality of any extension NodeCardinality(parse.NodeType) map[parse.NodeType]parse.Cardinality // Extend the complete model set, including the combined tree of // all the underlying models ExtendModelSet(schema.ModelSet) (schema.ModelSet, error) // Extend the schema tree used for RPC parameters and schema Models ExtendModel(parse.Node, schema.Model, schema.Tree) (schema.Model, error) // Extend the RPC node which includes input and output parameters // as trees ExtendRpc(parse.Node, schema.Rpc) (schema.Rpc, error) // Extend the Notification node ExtendNotification(parse.Node, schema.Notification) (schema.Notification, error) // Extend the schema tree used for RPC parameters and schema Models ExtendTree(parse.Node, schema.Tree) (schema.Tree, error) // Extend the various nodes within a schema Tree ExtendContainer(parse.Node, schema.Container) (schema.Container, error) ExtendList(parse.Node, schema.List) (schema.List, error) ExtendLeaf(parse.Node, schema.Leaf) (schema.Leaf, error) ExtendLeafList(parse.Node, schema.LeafList) (schema.LeafList, error) // Extend choice and case nodes ExtendChoice(parse.Node, schema.Choice) (schema.Choice, error) ExtendCase(parse.Node, schema.Case) (schema.Case, error) // Extend the type, given the parse node and the base type that this // type is derived from. The base time may be nil, when the type is // a built in type. ExtendType(p parse.Node, base schema.Type, t schema.Type) (schema.Type, error) // Extend must to allow for custom must optimisations ExtendMust(p parse.Node, m parse.Node) (string, error) ExtendOpdCommand(parse.Node, schema.OpdCommand) (schema.OpdCommand, error) ExtendOpdOption(parse.Node, schema.OpdOption) (schema.OpdOption, error) ExtendOpdArgument(parse.Node, schema.OpdArgument) (schema.OpdArgument, error) } func (comp *Compiler) extendModelSet(m schema.ModelSet) (schema.ModelSet, error) { if comp.extensions == nil { return m, nil } return comp.extensions.ExtendModelSet(m) } func (comp *Compiler) extendModel(p parse.Node, m schema.Model, t schema.Tree) schema.Model { if comp.extensions == nil { return m } m2, e := comp.extensions.ExtendModel(p, m, t) if e != nil { comp.error(p, e) return m } return m2 } func (comp *Compiler) extendRpc(p parse.Node, r schema.Rpc) schema.Rpc { if comp.extensions == nil { return r } r2, e := comp.extensions.ExtendRpc(p, r) if e != nil { comp.error(p, e) return r } return r2 } func (comp *Compiler) extendNotification(p parse.Node, n schema.Notification) schema.Notification { if comp.extensions == nil { return n } n2, e := comp.extensions.ExtendNotification(p, n) if e != nil { comp.error(p, e) return n } return n2 } func (comp *Compiler) extendTree(p parse.Node, t schema.Tree) schema.Tree { if comp.extensions == nil { return t } t2, e := comp.extensions.ExtendTree(p, t) if e != nil { comp.error(p, e) return t } return t2 } func (comp *Compiler) extendContainer( p parse.Node, c schema.Container, ) schema.Container { if comp.extensions == nil { return c } c2, e := comp.extensions.ExtendContainer(p, c) if e != nil { comp.error(p, e) return c } return c2 } func (comp *Compiler) extendList(p parse.Node, l schema.List) schema.List { if comp.extensions == nil { return l } l2, e := comp.extensions.ExtendList(p, l) if e != nil { comp.error(p, e) return l } return l2 } func (comp *Compiler) extendLeaf(p parse.Node, l schema.Leaf) schema.Leaf { if comp.extensions == nil { return l } l2, e := comp.extensions.ExtendLeaf(p, l) if e != nil { comp.error(p, e) return l } return l2 } func (comp *Compiler) extendLeafList(p parse.Node, l schema.LeafList) schema.LeafList { if comp.extensions == nil { return l } l2, e := comp.extensions.ExtendLeafList(p, l) if e != nil { comp.error(p, e) return l } return l2 } func (comp *Compiler) extendChoice(p parse.Node, c schema.Choice) schema.Choice { if comp.extensions == nil { return c } choiceExt, e := comp.extensions.ExtendChoice(p, c) if e != nil { comp.error(p, e) return c } return choiceExt } func (comp *Compiler) extendCase(p parse.Node, c schema.Case) schema.Case { if comp.extensions == nil { return c } caseExt, e := comp.extensions.ExtendCase(p, c) if e != nil { comp.error(p, e) return c } return caseExt } func (comp *Compiler) extendType( p parse.Node, base schema.Type, t schema.Type, ) schema.Type { if comp.extensions == nil { return t } t2, e := comp.extensions.ExtendType(p, base, t) if e != nil { comp.error(p, e) return t } return t2 } func (comp *Compiler) extendMust( p parse.Node, m parse.Node, ) string { if comp.extensions == nil { return "" } mustExt, e := comp.extensions.ExtendMust(p, m) if e != nil { comp.error(p, e) return "" } return mustExt } func (comp *Compiler) extendOpdCommand( p parse.Node, c schema.OpdCommand, ) schema.OpdCommand { if comp.extensions == nil { return c } c2, e := comp.extensions.ExtendOpdCommand(p, c) if e != nil { comp.error(p, e) return c } return c2 } func (comp *Compiler) extendOpdOption(p parse.Node, o schema.OpdOption) schema.OpdOption { if comp.extensions == nil { return o } o2, e := comp.extensions.ExtendOpdOption(p, o) if e != nil { comp.error(p, e) return o } return o2 } func (comp *Compiler) extendOpdArgument(p parse.Node, a schema.OpdArgument) schema.OpdArgument { if comp.extensions == nil { return a } a2, e := comp.extensions.ExtendOpdArgument(p, a) if e != nil { comp.error(p, e) return a } return a2 }
compile/extensions.go
0.719581
0.458227
extensions.go
starcoder
package zson import ( "errors" "fmt" "github.com/brimdata/zed" astzed "github.com/brimdata/zed/compiler/ast/zed" ) type Value interface { TypeOf() zed.Type SetType(zed.Type) } // Note that all of the types include a generic zed.Type as their type since // anything can have a zed.TypeNamed along with its normal type. type ( Primitive struct { Type zed.Type Text string } Record struct { Type zed.Type Fields []Value } Array struct { Type zed.Type Elements []Value } Set struct { Type zed.Type Elements []Value } Union struct { Type zed.Type Selector int Value Value } Enum struct { Type zed.Type Name string } Map struct { Type zed.Type Entries []Entry } Entry struct { Key Value Value Value } Null struct { Type zed.Type } TypeValue struct { Type zed.Type Value zed.Type } Error struct { Type zed.Type Value Value } ) func (p *Primitive) TypeOf() zed.Type { return p.Type } func (r *Record) TypeOf() zed.Type { return r.Type } func (a *Array) TypeOf() zed.Type { return a.Type } func (s *Set) TypeOf() zed.Type { return s.Type } func (u *Union) TypeOf() zed.Type { return u.Type } func (e *Enum) TypeOf() zed.Type { return e.Type } func (m *Map) TypeOf() zed.Type { return m.Type } func (n *Null) TypeOf() zed.Type { return n.Type } func (t *TypeValue) TypeOf() zed.Type { return t.Type } func (e *Error) TypeOf() zed.Type { return e.Type } func (p *Primitive) SetType(t zed.Type) { p.Type = t } func (r *Record) SetType(t zed.Type) { r.Type = t } func (a *Array) SetType(t zed.Type) { a.Type = t } func (s *Set) SetType(t zed.Type) { s.Type = t } func (u *Union) SetType(t zed.Type) { u.Type = t } func (e *Enum) SetType(t zed.Type) { e.Type = t } func (m *Map) SetType(t zed.Type) { m.Type = t } func (n *Null) SetType(t zed.Type) { n.Type = t } func (t *TypeValue) SetType(T zed.Type) { t.Type = T } func (e *Error) SetType(t zed.Type) { e.Type = t } // An Analyzer transforms an astzed.Value (which has decentralized type decorators) // to a typed Value, where every component of a nested Value is explicitly typed. // This is done via a semantic analysis where type state flows both down a the // nested value hierarchy (via type decorators) and back up via fully typed value // whose types are then usable as typedefs. The Analyzer tracks the ZSON typedef // semantics by updating its table of name-to-type bindings in accordance with the // left-to-right, depth-first semantics of ZSON typedefs. type Analyzer map[string]zed.Type func NewAnalyzer() Analyzer { return Analyzer(make(map[string]zed.Type)) } func (a Analyzer) ConvertValue(zctx *zed.Context, val astzed.Value) (Value, error) { return a.convertValue(zctx, val, nil) } func (a Analyzer) convertValue(zctx *zed.Context, val astzed.Value, parent zed.Type) (Value, error) { switch val := val.(type) { case *astzed.ImpliedValue: return a.convertAny(zctx, val.Of, parent) case *astzed.DefValue: v, err := a.convertAny(zctx, val.Of, parent) if err != nil { return nil, err } named, err := a.enterTypeDef(zctx, val.TypeName, v.TypeOf()) if err != nil { return nil, err } if named != nil { v.SetType(named) } return v, nil case *astzed.CastValue: switch valOf := val.Of.(type) { case *astzed.DefValue: // Enter the type def so val.Type can see it. if _, err := a.convertValue(zctx, valOf, nil); err != nil { return nil, err } case *astzed.CastValue: // Enter any nested type defs so val.Type can see them. if _, err := a.convertType(zctx, valOf.Type); err != nil { return nil, err } } cast, err := a.convertType(zctx, val.Type) if err != nil { return nil, err } if err := a.typeCheck(cast, parent); err != nil { return nil, err } var v Value if union, ok := zed.TypeUnder(cast).(*zed.TypeUnion); ok { v, err = a.convertValue(zctx, val.Of, nil) if err != nil { return nil, err } v, err = a.convertUnion(zctx, v, union, cast) } else { v, err = a.convertValue(zctx, val.Of, cast) } if err != nil { return nil, err } if union, ok := zed.TypeUnder(parent).(*zed.TypeUnion); ok { v, err = a.convertUnion(zctx, v, union, parent) } return v, err } return nil, fmt.Errorf("unknown value ast type: %T", val) } func (a Analyzer) typeCheck(cast, parent zed.Type) error { if parent == nil || cast == parent { return nil } if _, ok := zed.TypeUnder(parent).(*zed.TypeUnion); ok { // We let unions through this type check with no further checking // as any union incompability will be caught in convertAnyValue(). return nil } return fmt.Errorf("decorator conflict enclosing context %q and decorator cast %q", FormatType(parent), FormatType(cast)) } func (a Analyzer) enterTypeDef(zctx *zed.Context, name string, typ zed.Type) (*zed.TypeNamed, error) { var named *zed.TypeNamed if IsTypeName(name) { var err error if named, err = zctx.LookupTypeNamed(name, typ); err != nil { return nil, err } typ = named } a[name] = typ return named, nil } func (a Analyzer) convertAny(zctx *zed.Context, val astzed.Any, cast zed.Type) (Value, error) { // If we're casting something to a union, then the thing inside needs to // describe itself and we can convert the inner value to a union value when // we know its type (so we can code the selector). if union, ok := zed.TypeUnder(cast).(*zed.TypeUnion); ok { v, err := a.convertAny(zctx, val, nil) if err != nil { return nil, err } return a.convertUnion(zctx, v, union, cast) } switch val := val.(type) { case *astzed.Primitive: return a.convertPrimitive(zctx, val, cast) case *astzed.Record: return a.convertRecord(zctx, val, cast) case *astzed.Array: return a.convertArray(zctx, val, cast) case *astzed.Set: return a.convertSet(zctx, val, cast) case *astzed.Enum: return a.convertEnum(zctx, val, cast) case *astzed.Map: return a.convertMap(zctx, val, cast) case *astzed.TypeValue: return a.convertTypeValue(zctx, val, cast) case *astzed.Error: return a.convertError(zctx, val, cast) } return nil, fmt.Errorf("internal error: unknown ast type in Analyzer.convertAny(): %T", val) } func (a Analyzer) convertPrimitive(zctx *zed.Context, val *astzed.Primitive, cast zed.Type) (Value, error) { typ := zed.LookupPrimitive(val.Type) if typ == nil { return nil, fmt.Errorf("no such primitive type: %q", val.Type) } isNull := typ == zed.TypeNull if cast != nil { // The parser emits Enum values for identifiers but not for // string enum names. Check if the cast type is an enum, // and if so, convert the string to its enum counterpart. if v := stringToEnum(val, cast); v != nil { return v, nil } var err error typ, err = castType(typ, cast) if err != nil { return nil, err } } if isNull { return &Null{Type: typ}, nil } return &Primitive{Type: typ, Text: val.Text}, nil } func stringToEnum(val *astzed.Primitive, cast zed.Type) Value { if enum, ok := cast.(*zed.TypeEnum); ok { if val.Type == "string" { return &Enum{ Type: enum, Name: val.Text, } } } return nil } func castType(typ, cast zed.Type) (zed.Type, error) { typID, castID := typ.ID(), cast.ID() if typID == castID || typID == zed.IDNull || zed.IsInteger(typID) && zed.IsInteger(castID) || zed.IsFloat(typID) && zed.IsFloat(castID) { return cast, nil } return nil, fmt.Errorf("type mismatch: %q cannot be used as %q", FormatType(typ), FormatType(cast)) } func (a Analyzer) convertRecord(zctx *zed.Context, val *astzed.Record, cast zed.Type) (Value, error) { var fields []Value var err error if cast != nil { recType, ok := zed.TypeUnder(cast).(*zed.TypeRecord) if !ok { return nil, fmt.Errorf("record decorator not of type record: %T", cast) } if len(recType.Columns) != len(val.Fields) { return nil, fmt.Errorf("record decorator columns (%d) mismatched with value columns (%d)", len(recType.Columns), len(val.Fields)) } fields, err = a.convertFields(zctx, val.Fields, recType.Columns) } else { fields, err = a.convertFields(zctx, val.Fields, nil) if err != nil { return nil, err } cast, err = lookupRecordType(zctx, val.Fields, fields) } if err != nil { return nil, err } return &Record{ Type: cast, Fields: fields, }, nil } func (a Analyzer) convertFields(zctx *zed.Context, in []astzed.Field, cols []zed.Column) ([]Value, error) { fields := make([]Value, 0, len(in)) for k, f := range in { var cast zed.Type if cols != nil { cast = cols[k].Type } v, err := a.convertValue(zctx, f.Value, cast) if err != nil { return nil, err } fields = append(fields, v) } return fields, nil } func lookupRecordType(zctx *zed.Context, fields []astzed.Field, vals []Value) (*zed.TypeRecord, error) { columns := make([]zed.Column, 0, len(fields)) for k, f := range fields { columns = append(columns, zed.Column{f.Name, vals[k].TypeOf()}) } return zctx.LookupTypeRecord(columns) } // Figure out what the cast should be for the elements and for the union conversion if any. func arrayElemCast(cast zed.Type) (zed.Type, error) { if cast == nil { return nil, nil } if arrayType, ok := zed.TypeUnder(cast).(*zed.TypeArray); ok { return arrayType.Type, nil } return nil, errors.New("array decorator not of type array") } func (a Analyzer) convertArray(zctx *zed.Context, array *astzed.Array, cast zed.Type) (Value, error) { vals := make([]Value, 0, len(array.Elements)) typ, err := arrayElemCast(cast) if err != nil { return nil, err } for _, elem := range array.Elements { v, err := a.convertValue(zctx, elem, typ) if err != nil { return nil, err } vals = append(vals, v) } if cast != nil || len(vals) == 0 { // We had a cast so we know any type mistmatches we have been // caught below... if cast == nil { cast = zctx.LookupTypeArray(zed.TypeNull) } return &Array{ Type: cast, Elements: vals, }, nil } elems, inner, err := a.normalizeElems(zctx, vals) if err != nil { return nil, err } return &Array{ Type: zctx.LookupTypeArray(inner), Elements: elems, }, nil } func (a Analyzer) normalizeElems(zctx *zed.Context, vals []Value) ([]Value, zed.Type, error) { types := make([]zed.Type, len(vals)) for i, val := range vals { types[i] = val.TypeOf() } unique := types[:0] for _, typ := range zed.UniqueTypes(types) { if typ != zed.TypeNull { unique = append(unique, typ) } } if len(unique) == 1 { return vals, unique[0], nil } if len(unique) == 0 { return vals, zed.TypeNull, nil } union := zctx.LookupTypeUnion(unique) var unions []Value for _, v := range vals { union, err := a.convertUnion(zctx, v, union, union) if err != nil { return nil, nil, err } unions = append(unions, union) } return unions, union, nil } func (a Analyzer) convertSet(zctx *zed.Context, set *astzed.Set, cast zed.Type) (Value, error) { var elemType zed.Type if cast != nil { setType, ok := zed.TypeUnder(cast).(*zed.TypeSet) if !ok { return nil, fmt.Errorf("set decorator not of type set: %T", cast) } elemType = setType.Type } vals := make([]Value, 0, len(set.Elements)) for _, elem := range set.Elements { v, err := a.convertValue(zctx, elem, elemType) if err != nil { return nil, err } vals = append(vals, v) } if cast != nil || len(vals) == 0 { if cast == nil { cast = zctx.LookupTypeSet(zed.TypeNull) } return &Array{ Type: cast, Elements: vals, }, nil } elems, inner, err := a.normalizeElems(zctx, vals) if err != nil { return nil, err } return &Set{ Type: zctx.LookupTypeSet(inner), Elements: elems, }, nil } func (a Analyzer) convertUnion(zctx *zed.Context, v Value, union *zed.TypeUnion, cast zed.Type) (Value, error) { valType := v.TypeOf() if valType == zed.TypeNull { // Set selector to -1 to signal to the builder to encode a null. return &Union{ Type: cast, Selector: -1, Value: v, }, nil } for k, typ := range union.Types { if valType == typ { return &Union{ Type: cast, Selector: k, Value: v, }, nil } } return nil, fmt.Errorf("type %q is not in union type %q", FormatType(valType), FormatType(union)) } func (a Analyzer) convertEnum(zctx *zed.Context, val *astzed.Enum, cast zed.Type) (Value, error) { if cast == nil { return nil, fmt.Errorf("identifier %q must be enum and requires decorator", val.Name) } enum, ok := zed.TypeUnder(cast).(*zed.TypeEnum) if !ok { return nil, fmt.Errorf("identifier %q is enum and incompatible with type %q", val.Name, FormatType(cast)) } for _, s := range enum.Symbols { if s == val.Name { return &Enum{ Name: val.Name, Type: cast, }, nil } } return nil, fmt.Errorf("symbol %q not a member of type %q", val.Name, FormatType(enum)) } func (a Analyzer) convertMap(zctx *zed.Context, m *astzed.Map, cast zed.Type) (Value, error) { var keyType, valType zed.Type if cast != nil { typ, ok := zed.TypeUnder(cast).(*zed.TypeMap) if !ok { return nil, errors.New("map decorator not of type map") } keyType = typ.KeyType valType = typ.ValType } keys := make([]Value, 0, len(m.Entries)) vals := make([]Value, 0, len(m.Entries)) for _, e := range m.Entries { key, err := a.convertValue(zctx, e.Key, keyType) if err != nil { return nil, err } val, err := a.convertValue(zctx, e.Value, valType) if err != nil { return nil, err } keys = append(keys, key) vals = append(vals, val) } if cast == nil { // If there was no decorator, pull the types out of the first // entry we just analyed. if len(keys) == 0 { // empty set with no decorator keyType = zed.TypeNull valType = zed.TypeNull } else { var err error keys, keyType, err = a.normalizeElems(zctx, keys) if err != nil { return nil, err } vals, valType, err = a.normalizeElems(zctx, vals) if err != nil { return nil, err } } cast = zctx.LookupTypeMap(keyType, valType) } entries := make([]Entry, 0, len(keys)) for i := range keys { entries = append(entries, Entry{keys[i], vals[i]}) } return &Map{ Type: cast, Entries: entries, }, nil } func (a Analyzer) convertTypeValue(zctx *zed.Context, tv *astzed.TypeValue, cast zed.Type) (Value, error) { if cast != nil { if _, ok := zed.TypeUnder(cast).(*zed.TypeOfType); !ok { return nil, fmt.Errorf("cannot apply decorator (%q) to a type value", FormatType(cast)) } } typ, err := a.convertType(zctx, tv.Value) if err != nil { return nil, err } if cast == nil { cast = zed.TypeType } return &TypeValue{ Type: cast, Value: typ, }, nil } func (a Analyzer) convertError(zctx *zed.Context, val *astzed.Error, cast zed.Type) (Value, error) { var inner zed.Type if cast != nil { typ, ok := zed.TypeUnder(cast).(*zed.TypeError) if !ok { return nil, errors.New("error decorator not of type error") } inner = typ.Type } under, err := a.convertValue(zctx, val.Value, inner) if err != nil { return nil, err } if cast == nil { cast = zctx.LookupTypeError(under.TypeOf()) } return &Error{ Value: under, Type: cast, }, nil } func (a Analyzer) convertType(zctx *zed.Context, typ astzed.Type) (zed.Type, error) { switch t := typ.(type) { case *astzed.TypePrimitive: name := t.Name typ := zed.LookupPrimitive(name) if typ == nil { return nil, fmt.Errorf("no such primitive type: %q", name) } return typ, nil case *astzed.TypeDef: typ, err := a.convertType(zctx, t.Type) if err != nil { return nil, err } named, err := a.enterTypeDef(zctx, t.Name, typ) if err != nil { return nil, err } if named != nil { typ = named } return typ, nil case *astzed.TypeRecord: return a.convertTypeRecord(zctx, t) case *astzed.TypeArray: typ, err := a.convertType(zctx, t.Type) if err != nil { return nil, err } return zctx.LookupTypeArray(typ), nil case *astzed.TypeSet: typ, err := a.convertType(zctx, t.Type) if err != nil { return nil, err } return zctx.LookupTypeSet(typ), nil case *astzed.TypeMap: return a.convertTypeMap(zctx, t) case *astzed.TypeUnion: return a.convertTypeUnion(zctx, t) case *astzed.TypeEnum: return a.convertTypeEnum(zctx, t) case *astzed.TypeError: typ, err := a.convertType(zctx, t.Type) if err != nil { return nil, err } return zctx.LookupTypeError(typ), nil case *astzed.TypeName: typ, ok := a[t.Name] if !ok { // We avoid the nil-interface bug here by assigning to named // and then typ because assigning directly to typ will create // a nin-nil interface pointer for a nil result. named := zctx.LookupTypeDef(t.Name) if named == nil { return nil, fmt.Errorf("no such type name: %q", t.Name) } typ = named } return typ, nil } return nil, fmt.Errorf("unknown type in Analyzer.convertType: %T", typ) } func (a Analyzer) convertTypeRecord(zctx *zed.Context, typ *astzed.TypeRecord) (*zed.TypeRecord, error) { fields := typ.Fields columns := make([]zed.Column, 0, len(fields)) for _, f := range fields { typ, err := a.convertType(zctx, f.Type) if err != nil { return nil, err } columns = append(columns, zed.Column{f.Name, typ}) } return zctx.LookupTypeRecord(columns) } func (a Analyzer) convertTypeMap(zctx *zed.Context, tmap *astzed.TypeMap) (*zed.TypeMap, error) { keyType, err := a.convertType(zctx, tmap.KeyType) if err != nil { return nil, err } valType, err := a.convertType(zctx, tmap.ValType) if err != nil { return nil, err } return zctx.LookupTypeMap(keyType, valType), nil } func (a Analyzer) convertTypeUnion(zctx *zed.Context, union *astzed.TypeUnion) (*zed.TypeUnion, error) { var types []zed.Type for _, typ := range union.Types { typ, err := a.convertType(zctx, typ) if err != nil { return nil, err } types = append(types, typ) } return zctx.LookupTypeUnion(types), nil } func (a Analyzer) convertTypeEnum(zctx *zed.Context, enum *astzed.TypeEnum) (*zed.TypeEnum, error) { if len(enum.Symbols) == 0 { return nil, errors.New("enum body is empty") } return zctx.LookupTypeEnum(enum.Symbols), nil }
zson/analyzer.go
0.592431
0.614568
analyzer.go
starcoder
// Package consensus implements different Matrix consensus engines. package consensus import ( "math/big" "github.com/matrix/go-matrix/common" "github.com/matrix/go-matrix/core/state" "github.com/matrix/go-matrix/core/types" "github.com/matrix/go-matrix/params" "github.com/matrix/go-matrix/rpc" ) // ChainReader defines a small collection of methods needed to access the local // blockchain during header and/or uncle verification. type ChainReader interface { // Config retrieves the blockchain's chain configuration. Config() *params.ChainConfig // CurrentHeader retrieves the current header from the local chain. CurrentHeader() *types.Header // GetHeader retrieves a block header from the database by hash and number. GetHeader(hash common.Hash, number uint64) *types.Header // GetHeaderByNumber retrieves a block header from the database by number. GetHeaderByNumber(number uint64) *types.Header // GetHeaderByHash retrieves a block header from the database by its hash. GetHeaderByHash(hash common.Hash) *types.Header // GetBlock retrieves a block from the database by hash and number. GetBlock(hash common.Hash, number uint64) *types.Block } // Engine is an algorithm agnostic consensus engine. type Engine interface { // Author retrieves the Matrix address of the account that minted the given // block, which may be different from the header's coinbase if a consensus // engine is based on signatures. Author(header *types.Header) (common.Address, error) // VerifyHeader checks whether a header conforms to the consensus rules of a // given engine. Verifying the seal may be done optionally here, or explicitly // via the VerifySeal method. VerifyHeader(chain ChainReader, header *types.Header, seal bool) error // VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers // concurrently. The method returns a quit channel to abort the operations and // a results channel to retrieve the async verifications (the order is that of // the input slice). VerifyHeaders(chain ChainReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error) // VerifyUncles verifies that the given block's uncles conform to the consensus // rules of a given engine. VerifyUncles(chain ChainReader, block *types.Block) error // VerifySeal checks whether the crypto seal on a header is valid according to // the consensus rules of the given engine. VerifySeal(chain ChainReader, header *types.Header) error // Prepare initializes the consensus fields of a block header according to the // rules of a particular engine. The changes are executed inline. Prepare(chain ChainReader, header *types.Header) error // Finalize runs any post-transaction state modifications (e.g. block rewards) // and assembles the final block. // Note: The block header and state database might be updated to reflect any // consensus rules that happen at finalization (e.g. block rewards). Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error) // Seal generates a new block for the given input block with the local miner's // seal place on top. Seal(chain ChainReader, header *types.Header, stop <-chan struct{}, foundMsgCh chan *FoundMsg, diffList []*big.Int, isBroadcastNode bool) error // CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty // that a new block should have. CalcDifficulty(chain ChainReader, time uint64, parent *types.Header) *big.Int // APIs returns the RPC APIs this consensus engine provides. APIs(chain ChainReader) []rpc.API } // PoW is a consensus engine based on proof-of-work. type PoW interface { Engine // Hashrate returns the current mining hashrate of a PoW consensus engine. Hashrate() float64 } type FoundMsg struct { Header *types.Header Difficulty *big.Int } type DPOSEngine interface { VerifyBlock(header *types.Header) error //verify hash in current block VerifyHash(signHash common.Hash, signs []common.Signature) ([]common.Signature, error) //verify hash in given number block VerifyHashWithNumber(signHash common.Hash, signs []common.Signature, number uint64) ([]common.Signature, error) //VerifyHashWithStocks(signHash common.Hash, signs []common.Signature, stocks map[common.Address]uint16) ([]common.Signature, error) VerifyHashWithVerifiedSigns(signs []*common.VerifiedSign) ([]common.Signature, error) VerifyHashWithVerifiedSignsAndNumber(signs []*common.VerifiedSign, number uint64) ([]common.Signature, error) }
consensus/consensus.go
0.694095
0.490053
consensus.go
starcoder
package core import ( "github.com/nuberu/engine/math" ) type Camera struct { Object3 matrixWorldInverse math.Matrix4 projectionMatrix math.Matrix4 projectionMatrixInverse math.Matrix4 } func NewCamera() *Camera { cam := Camera{ Object3: *NewObject(), matrixWorldInverse: *math.NewDefaultMatrix4(), projectionMatrix: *math.NewDefaultMatrix4(), projectionMatrixInverse: *math.NewDefaultMatrix4(), } return &cam } func (camera *Camera) IsCamera() bool { return true } func (camera *Camera) GetMatrixWorldInverse() *math.Matrix4 { return &camera.matrixWorldInverse } func (camera *Camera) GetProjectionMatrix() *math.Matrix4 { return &camera.projectionMatrix } func (camera *Camera) GetProjectionMatrixInverse() *math.Matrix4 { return &camera.projectionMatrixInverse } func (camera *Camera) Copy(source *Camera, recursive bool) { camera.Object3.Copy(&source.Object3, recursive) camera.matrixWorldInverse.Copy(&source.matrixWorldInverse) camera.projectionMatrix.Copy(&source.projectionMatrix) camera.projectionMatrixInverse.Copy(&source.projectionMatrixInverse) } func (camera *Camera) Clone() *Camera { newCamera := new(Camera) newCamera.Copy(camera, true) return newCamera } func (camera *Camera) UpdateMatrixWorld(force bool) { camera.Object3.UpdateMatrixWorld(force) camera.matrixWorldInverse.SetInverseOf(camera.GetMatrixWorld(), false) } func (camera *Camera) GetWorldDirection(target *math.Vector3) *math.Vector3 { camera.UpdateMatrixWorld(true) e := camera.GetMatrixWorld().GetElements() target.Set(-e[8], -e[9], -e[10]) target.Normalize() return target } func Project(vec *math.Vector3, camera *Camera) { vec.ApplyMatrix4(camera.GetMatrixWorldInverse()) vec.ApplyMatrix4(camera.GetProjectionMatrix()) } func UnProject(vec *math.Vector3, camera *Camera) { matrix := math.NewDefaultMatrix4() matrix.SetIdentity() matrix.SetInverseOf(camera.GetProjectionMatrix(), false) vec.ApplyMatrix4(matrix) vec.ApplyMatrix4(camera.GetMatrixWorld()) }
core/camera.go
0.860808
0.560072
camera.go
starcoder
package anomalia // Detector is the default anomaly detector type Detector struct { threshold float64 timeSeries *TimeSeries } // NewDetector return an instance of the default detector. func NewDetector(ts *TimeSeries) *Detector { return &Detector{threshold: 2.0, timeSeries: ts} } // Threshold sets the threshold used by the detector. func (d *Detector) Threshold(threshold float64) *Detector { d.threshold = threshold return d } // GetScores runs the detector on the supplied time series. // It uses the Bitmap algorithm to calculate the score list and falls back // to the normal distribution algorithm in case of not enough data points in the time series. func (d *Detector) GetScores() *ScoreList { if scoreList := NewBitmap().Run(d.timeSeries); scoreList != nil { return scoreList } return NewWeightedSum().Run(d.timeSeries) } // GetAnomalies detects anomalies using the specified threshold on scores func (d *Detector) GetAnomalies(scoreList *ScoreList) []Anomaly { var ( zippedSeries = d.timeSeries.Zip() scores = scoreList.Zip() anomalies = make([]Anomaly, 0) intervals = make([]TimePeriod, 0) ) // Find all anomalies intervals var start, end float64 for _, timestamp := range scoreList.Timestamps { if scores[timestamp] > d.threshold { end = timestamp if start == 0 { start = timestamp } } else if (start != 0) && (end != 0) { intervals = append(intervals, TimePeriod{start, end}) start = 0 end = 0 } } // Locate the exact anomaly timestamp within each interval for _, interval := range intervals { intervalSeries := d.timeSeries.Crop(interval.Start, interval.Start) refinedScoreList := NewEma().Run(intervalSeries) maxRefinedScore := refinedScoreList.Max() // Get timestamp of the maximal score if index := indexOf(refinedScoreList.Scores, maxRefinedScore); index != -1 { maxRefinedTimestamp := refinedScoreList.Timestamps[index] // Create the anomaly anomaly := Anomaly{ Timestamp: maxRefinedTimestamp, Value: zippedSeries[maxRefinedTimestamp], StartTimestamp: interval.Start, EndTimestamp: interval.End, Score: maxRefinedScore, threshold: d.threshold, } anomalies = append(anomalies, anomaly) } } return anomalies }
detector.go
0.86592
0.645274
detector.go
starcoder
package metrics import ( "sync" "time" "github.com/rcrowley/go-metrics" ) type timer struct { mutex sync.Mutex sum int64 prev int64 count int64 mean float64 } // GetOrRegisterTimer returns an existing Timer or constructs and registers a // new StandardTimer. func getOrRegisterTimer(name string, r metrics.Registry) metrics.Timer { if nil == r { r = metrics.DefaultRegistry } return r.GetOrRegister(name, newTimer).(metrics.Timer) } func newTimer() metrics.Timer { t := &timer{} arbiter.Lock() defer arbiter.Unlock() arbiter.meters = append(arbiter.meters, t) if !arbiter.started { arbiter.started = true go arbiter.tick() } return t } // Count returns the number of events recorded. func (t *timer) Count() int64 { t.mutex.Lock() count := t.count t.mutex.Unlock() return count } // Max returns the maximum value in the sample. func (t *timer) Max() int64 { // Not implement return 0 } // Min returns the minimum value in the sample. func (t *timer) Min() int64 { // Not implement return 0 } // Mean returns the mean of the values in the sample. func (t *timer) Mean() float64 { return t.RateMean() } // Percentile returns an arbitrary percentile of the values in the sample. func (t *timer) Percentile(p float64) float64 { // Not implement return 0.0 } // Percentiles returns a slice of arbitrary percentiles of the values in the // sample. func (t *timer) Percentiles(ps []float64) []float64 { // Not implement return nil } // Rate1 returns the one-minute moving average rate of events per second. func (t *timer) Rate1() float64 { return t.RateMean() } // Rate5 returns the five-minute moving average rate of events per second. func (t *timer) Rate5() float64 { return t.RateMean() } // Rate15 returns the fifteen-minute moving average rate of events per second. func (t *timer) Rate15() float64 { return t.RateMean() } // RateMean returns the meter's mean rate of events per second. func (t *timer) RateMean() float64 { t.mutex.Lock() mean := t.mean t.mutex.Unlock() return mean } // Snapshot returns a read-only copy of the timer. func (t *timer) Snapshot() metrics.Timer { t.mutex.Lock() snap := &timerSnapshot{ sum: t.sum, count: t.count, mean: t.mean, } t.mutex.Unlock() return snap } // StdDev returns the standard deviation of the values in the sample. func (t *timer) StdDev() float64 { // Not implement return 0.0 } // Sum returns the sum in the sample. func (t *timer) Sum() int64 { t.mutex.Lock() sum := t.sum t.mutex.Unlock() return sum } // Record the duration of the execution of the given function. // record time as Millisecond func (t *timer) Time(f func()) { ts := time.Now() f() t.Update(time.Since(ts) / time.Millisecond) } // Record the duration of an event. Millisecond func (t *timer) Update(d time.Duration) { t.mutex.Lock() t.sum += int64(d) t.count += 1 t.mutex.Unlock() } // Record the duration of an event that started at a time and ends now. func (t *timer) UpdateSince(ts time.Time) { t.Update(time.Since(ts) / time.Millisecond) } // Variance returns the variance of the values in the sample. func (t *timer) Variance() float64 { // Not implement return 0.0 } func (t *timer) tick() { t.mutex.Lock() if t.count != 0 { sum := t.sum t.mean = float64(sum-t.prev) / float64(t.count) t.prev = sum t.count = 0 } t.mutex.Unlock() } // TimerSnapshot is a read-only copy of another Timer. type timerSnapshot struct { sum int64 count int64 mean float64 } // Count returns the number of events recorded at the time the snapshot was // taken. func (t *timerSnapshot) Count() int64 { return t.count } // Max returns the maximum value at the time the snapshot was taken. func (t *timerSnapshot) Max() int64 { return 0 } // Mean returns the mean value at the time the snapshot was taken. func (t *timerSnapshot) Mean() float64 { return t.mean } // Min returns the minimum value at the time the snapshot was taken. func (t *timerSnapshot) Min() int64 { return 0 } // Percentile returns an arbitrary percentile of sampled values at the time the // snapshot was taken. func (t *timerSnapshot) Percentile(p float64) float64 { return 0.0 } // Percentiles returns a slice of arbitrary percentiles of sampled values at // the time the snapshot was taken. func (t *timerSnapshot) Percentiles(ps []float64) []float64 { return nil } // Rate1 returns the one-minute moving average rate of events per second at the // time the snapshot was taken. func (t *timerSnapshot) Rate1() float64 { return t.mean } // Rate5 returns the five-minute moving average rate of events per second at // the time the snapshot was taken. func (t *timerSnapshot) Rate5() float64 { return t.mean } // Rate15 returns the fifteen-minute moving average rate of events per second // at the time the snapshot was taken. func (t *timerSnapshot) Rate15() float64 { return t.mean } // RateMean returns the meter's mean rate of events per second at the time the // snapshot was taken. func (t *timerSnapshot) RateMean() float64 { return t.mean } // Snapshot returns the snapshot. func (t *timerSnapshot) Snapshot() metrics.Timer { return t } // StdDev returns the standard deviation of the values at the time the snapshot // was taken. func (t *timerSnapshot) StdDev() float64 { return 0.0 } // Sum returns the sum at the time the snapshot was taken. func (t *timerSnapshot) Sum() int64 { return t.sum } // Time panics. func (*timerSnapshot) Time(func()) { panic("Time called on a TimerSnapshot") } // Update panics. func (*timerSnapshot) Update(time.Duration) { panic("Update called on a TimerSnapshot") } // UpdateSince panics. func (*timerSnapshot) UpdateSince(time.Time) { panic("UpdateSince called on a TimerSnapshot") } // Variance returns the variance of the values at the time the snapshot was // taken. func (t *timerSnapshot) Variance() float64 { return 0.0 }
metrics/timer.go
0.856827
0.525673
timer.go
starcoder
package dbnssystem import ( "errors" "math/big" ) var ( big1 = big.NewInt(1) big3 = big.NewInt(3) // ErrDBNSBase2And3 is returned if the integer can not represented by any linear combination 2^a3^b. ErrDBNSBase2And3 = errors.New("not represented by any linear combination 2^a3^b") // ErrPositiveInteger is returned if the integer is negative. ErrPositiveInteger = errors.New("not a negative integer") ) /* This algorithm comes from: A Tree-Based Approach for Computing Double-Base Chains: Algorithm 1. Tree-based DB-chain search. This implementation maybe be improved. ex: We write 841232 = 2^7*3^8+2^6*3^3-2^5*3^2-2^4. Use ExpansionBase2And will get the output is (2-exponent, 3-exponent, sign) = (7,8,1) & (6,3,1) & (5,2,-1) & (4,0,-1). Note that: This representations is not unique. */ type expansion23 struct { exponent2 int exponent3 int sign int } // Because we need to compute N/3 for some positive integers. We use a small trick transit it to multiply magicIntegerDivide3 for efficiency. // This idea can be found in book: Hacker's Delight" by <NAME>. // The deepOfBench means the max depth generating from a root number. More details can see paper: // A Tree-Based Approach for Computing Double-Base Chains: Algorithm 1. Tree-based DB-chain search.. type dbnsMentor struct { deepOfBranch int } func NewDBNS(deepOfBranch int) *dbnsMentor { return &dbnsMentor{ deepOfBranch: deepOfBranch, } } // Give a, b, discriminant to construct quadratic forms. func newexpansion23(exponent2, exponent3, s int) *expansion23 { return &expansion23{ exponent2: exponent2, exponent3: exponent3, sign: s, } } func (expan *expansion23) GetExp2() int { return expan.exponent2 } func (expan *expansion23) GetExp3() int { return expan.exponent3 } func (expan *expansion23) GetSign() int { return expan.sign } // This is a algorithm to get number % 3. The velocity of this function is faster than new(bigInt).mod(number, 3). func fastMod3(number *big.Int) int { numberOne, numberTwo := 0, 0 for i := 0; i < number.BitLen(); i = i + 2 { if number.Bit(i) != 0 { numberOne++ } } for i := 1; i < number.BitLen(); i = i + 2 { if number.Bit(i) != 0 { numberTwo++ } } result := 0 if numberOne > numberTwo { result = numberOne - numberTwo } else { result = numberTwo - numberOne result = result << 1 } return result % 3 } func (dbns *dbnsMentor) ExpansionBase2And3(number *big.Int) ([]*expansion23, error) { numberClone := new(big.Int).Set(number) exp2, exp3 := 0, 0 numberClone, exp2 = getMax2Factor(numberClone) numberClone, exp3 = getMax3Factor(numberClone) firstExpansion23 := newexpansion23(exp2, exp3, 0) result := []*expansion23{firstExpansion23} otherPart, err := get23ExpansionSpecialcase(numberClone, dbns.deepOfBranch) if err != nil { return nil, err } result = append(result, otherPart...) result = transDBNSForm(result) return result, nil } func get23ExpansionSpecialcase(numberwithout23Factor *big.Int, deepOfBranch int) ([]*expansion23, error) { result := make([]*expansion23, 0) for numberwithout23Factor.Cmp(big1) != 0 { value, tempExpansion23, err := getGivenDepth23Expansion(numberwithout23Factor, deepOfBranch) if err != nil { return nil, err } numberwithout23Factor = value result = append(result, tempExpansion23...) } return result, nil } func getGivenDepth23Expansion(number *big.Int, upperDepth int) (*big.Int, []*expansion23, error) { numberList := []*big.Int{number} minPosition, exp2, exp3 := 0, 0, 0 upperDepthMinus1 := uint(upperDepth - 1) var bStop bool minValue := new(big.Int).Set(number) if number.Sign() < 1 { return nil, nil, ErrPositiveInteger } number, exp2 = getMax2Factor(number) _, exp3 = getMax3Factor(number) totalSlice := []*expansion23{newexpansion23(exp2, exp3, 0)} for j := uint(0); j < upperDepthMinus1; j++ { index, upperBound := (1<<j)-1, (1<<(j+1))-1 for i := index; i < upperBound; i++ { bStop, totalSlice, numberList = bStopComputeDescendent(totalSlice, numberList, i) if bStop { return big1, totalSlice, nil } } } index, upperBound := (1<<upperDepthMinus1)-1, (1<<(upperDepthMinus1+1))-1 for i := index; i < upperBound; i++ { bStop, totalSlice, numberList = bStopComputeDescendent(totalSlice, numberList, i) if bStop { return big1, totalSlice, nil } // numberList[len(numberList)-2] := minus1 and numberList[len(numberList)-1] = plus1 minValue, minPosition = getMinValueAndPosition(minValue, numberList[len(numberList)-2], numberList[len(numberList)-1], minPosition, i) } return minValue, getRepresentation23Expansion(minPosition, totalSlice), nil } // For the newest branch, we find the minimal value to set it to be new startpoint. And use its location to trace the corresponding factors. func getMinValueAndPosition(nowMinValue, compareMinus1Value, comparePlus1Value *big.Int, minPosition, index int) (*big.Int, int) { position := ((index + 1) << 1) if nowMinValue.Cmp(compareMinus1Value) > 0 { nowMinValue = compareMinus1Value minPosition = position } if nowMinValue.Cmp(comparePlus1Value) > 0 { position++ minPosition = position nowMinValue = comparePlus1Value } return nowMinValue, minPosition } func bStopComputeDescendent(totalSlice []*expansion23, numberList []*big.Int, index int) (bool, []*expansion23, []*big.Int) { plus1, minus1, factor23 := computePlus1AndMinus123Factor(numberList[index]) totalSlice = append(totalSlice, factor23...) if minus1.Cmp(big1) == 0 { position := ((index + 1) << 1) return true, getRepresentation23Expansion(position, totalSlice), nil } if plus1.Cmp(big1) == 0 { position := ((index + 1) << 1) + 1 return true, getRepresentation23Expansion(position, totalSlice), nil } numberList = append(numberList, minus1) numberList = append(numberList, plus1) return false, totalSlice, numberList } // assume that gcd(number,6) = 1 func computePlus1AndMinus123Factor(number *big.Int) (*big.Int, *big.Int, []*expansion23) { result := make([]*expansion23, 0) exp2, exp3 := 0, 0 numberMinus1 := new(big.Int).Sub(number, big1) numberMinus1, exp2 = getMax2Factor(numberMinus1) numberMinus1, exp3 = getMax3Factor(numberMinus1) temp23FactorMinus1 := newexpansion23(exp2, exp3, -1) result = append(result, temp23FactorMinus1) numberPlus1 := new(big.Int).Add(number, big1) numberPlus1, exp2 = getMax2Factor(numberPlus1) numberPlus1, exp3 = getMax3Factor(numberPlus1) temp23FactorPlus1 := newexpansion23(exp2, exp3, 1) result = append(result, temp23FactorPlus1) return numberPlus1, numberMinus1, result } func getRepresentation23Expansion(position int, totalSlice []*expansion23) []*expansion23 { result := make([]*expansion23, 0) copyPosition := position - 1 for copyPosition > 0 { addSlice := []*expansion23{totalSlice[copyPosition]} result = append(addSlice, result...) copyPosition = (copyPosition - 1) >> 1 } return result } func getMax2Factor(number *big.Int) (*big.Int, int) { bitLength := number.BitLen() for i := 0; i < bitLength; i++ { if number.Bit(i) != 0 { number.Rsh(number, uint(i)) return number, i } } return big.NewInt(0), 0 } func getMax3Factor(number *big.Int) (*big.Int, int) { bitLength := number.BitLen() for i := 0; i < bitLength; i++ { residue := fastMod3(number) if residue == 0 { number.Div(number, big3) continue } return number, i } return nil, 0 } // example: The input of the struct is like: 841232 = 2^4(2^5(2^2*3^1(2^3(2^4+1)+1)−1)+1) // The output is 841232 = 2^18*3^1+2^14*3^1−2^11*3^1+2^9+2^4 func transDBNSForm(input []*expansion23) []*expansion23 { result := make([]*expansion23, len(input)) exp2, exp3 := 0, 0 length := len(input) - 1 for i := 0; i < length; i++ { exp2 += input[i].exponent2 exp3 += input[i].exponent3 temp := newexpansion23(exp2, exp3, -1*input[i+1].sign) result[length-i] = temp } exp2 += input[length].exponent2 exp3 += input[length].exponent3 result[0] = newexpansion23(exp2, exp3, 1) for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 { result[i], result[j] = result[j], result[i] } return result }
crypto/dbnssystem/dbns.go
0.663996
0.450359
dbns.go
starcoder
package badgerhold import ( "fmt" "math/big" "reflect" "time" ) // ErrTypeMismatch is the error thrown when two types cannot be compared type ErrTypeMismatch struct { Value interface{} Other interface{} } func (e *ErrTypeMismatch) Error() string { return fmt.Sprintf("%v (%T) cannot be compared with %v (%T)", e.Value, e.Value, e.Other, e.Other) } //Comparer compares a type against the encoded value in the store. The result should be 0 if current==other, // -1 if current < other, and +1 if current > other. // If a field in a struct doesn't specify a comparer, then the default comparison is used (convert to string and compare) // this interface is already handled for standard Go Types as well as more complex ones such as those in time and big // an error is returned if the type cannot be compared // The concrete type will always be passed in, not a pointer type Comparer interface { Compare(other interface{}) (int, error) } func (c *Criterion) compare(rowValue, criterionValue interface{}, currentRow interface{}) (int, error) { if rowValue == nil || criterionValue == nil { if rowValue == criterionValue { return 0, nil } return 0, &ErrTypeMismatch{rowValue, criterionValue} } if _, ok := criterionValue.(Field); ok { fVal := reflect.ValueOf(currentRow).Elem().FieldByName(string(criterionValue.(Field))) if !fVal.IsValid() { return 0, fmt.Errorf("The field %s does not exist in the type %s", criterionValue, reflect.TypeOf(currentRow)) } criterionValue = fVal.Interface() } value := rowValue for reflect.TypeOf(value).Kind() == reflect.Ptr { value = reflect.ValueOf(value).Elem().Interface() } other := criterionValue for reflect.TypeOf(other).Kind() == reflect.Ptr { other = reflect.ValueOf(other).Elem().Interface() } return compare(value, other) } func compare(value, other interface{}) (int, error) { switch t := value.(type) { case time.Time: tother, ok := other.(time.Time) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(time.Time).Equal(tother) { return 0, nil } if value.(time.Time).Before(tother) { return -1, nil } return 1, nil case big.Float: o, ok := other.(big.Float) if !ok { return 0, &ErrTypeMismatch{t, other} } v := value.(big.Float) return v.Cmp(&o), nil case big.Int: o, ok := other.(big.Int) if !ok { return 0, &ErrTypeMismatch{t, other} } v := value.(big.Int) return v.Cmp(&o), nil case big.Rat: o, ok := other.(big.Rat) if !ok { return 0, &ErrTypeMismatch{t, other} } v := value.(big.Rat) return v.Cmp(&o), nil case int: tother, ok := other.(int) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(int) == tother { return 0, nil } if value.(int) < tother { return -1, nil } return 1, nil case int8: tother, ok := other.(int8) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(int8) == tother { return 0, nil } if value.(int8) < tother { return -1, nil } return 1, nil case int16: tother, ok := other.(int16) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(int16) == tother { return 0, nil } if value.(int16) < tother { return -1, nil } return 1, nil case int32: tother, ok := other.(int32) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(int32) == tother { return 0, nil } if value.(int32) < tother { return -1, nil } return 1, nil case int64: tother, ok := other.(int64) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(int64) == tother { return 0, nil } if value.(int64) < tother { return -1, nil } return 1, nil case uint: tother, ok := other.(uint) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(uint) == tother { return 0, nil } if value.(uint) < tother { return -1, nil } return 1, nil case uint8: tother, ok := other.(uint8) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(uint8) == tother { return 0, nil } if value.(uint8) < tother { return -1, nil } return 1, nil case uint16: tother, ok := other.(uint16) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(uint16) == tother { return 0, nil } if value.(uint16) < tother { return -1, nil } return 1, nil case uint32: tother, ok := other.(uint32) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(uint32) == tother { return 0, nil } if value.(uint32) < tother { return -1, nil } return 1, nil case uint64: tother, ok := other.(uint64) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(uint64) == tother { return 0, nil } if value.(uint64) < tother { return -1, nil } return 1, nil case float32: tother, ok := other.(float32) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(float32) == tother { return 0, nil } if value.(float32) < tother { return -1, nil } return 1, nil case float64: tother, ok := other.(float64) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(float64) == tother { return 0, nil } if value.(float64) < tother { return -1, nil } return 1, nil case string: tother, ok := other.(string) if !ok { return 0, &ErrTypeMismatch{t, other} } if value.(string) == tother { return 0, nil } if value.(string) < tother { return -1, nil } return 1, nil case Comparer: return value.(Comparer).Compare(other) default: valS := fmt.Sprintf("%s", value) otherS := fmt.Sprintf("%s", other) if valS == otherS { return 0, nil } if valS < otherS { return -1, nil } return 1, nil } }
compare.go
0.668988
0.443721
compare.go
starcoder
package gohome import ( "github.com/PucklaMotzer09/mathgl/mgl32" ) // A tween that moves its parent to a certain position type TweenPosition2D struct { // The position to which the parent should move Destination mgl32.Vec2 // The time in which it should do this in seconds Time float32 // The type of this tween TweenType uint8 transform *TransformableObject2D velocity mgl32.Vec2 elapsedTime float32 } func (this *TweenPosition2D) Start(parent interface{}) { parent2D, ok := parent.(TweenableObject2D) if ok { this.transform = parent2D.GetTransform2D() } else { this.transform = nil } if this.transform != nil { this.velocity = this.Destination.Sub(this.transform.Position).Mul(1.0 / this.Time) } this.elapsedTime = 0.0 } func (this *TweenPosition2D) Update(delta_time float32) bool { if this.transform == nil { return true } this.elapsedTime += delta_time this.transform.Position = this.transform.Position.Add(this.velocity.Mul(delta_time)) if this.elapsedTime >= this.Time { return true } return false } func (this *TweenPosition2D) GetType() uint8 { return this.TweenType } func (this *TweenPosition2D) End() { if this.transform != nil { this.transform.Position = this.Destination } } func (this *TweenPosition2D) Reset() { if this.transform != nil { this.transform.Position = this.Destination.Sub(this.velocity.Mul(this.Time)) this.elapsedTime = 0.0 } } func (this *TweenPosition2D) Copy() Tween { return &TweenPosition2D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} } // A tween that rotates its parent to a certain rotation type TweenRotation2D struct { // The rotation to which it should rotate Destination float32 // The time in which it should do this Time float32 // The type of this tween TweenType uint8 transform *TransformableObject2D velocity float32 elapsedTime float32 } func (this *TweenRotation2D) Start(parent interface{}) { parent2D, ok := parent.(TweenableObject2D) if ok { this.transform = parent2D.GetTransform2D() } else { this.transform = nil } if this.transform != nil { this.velocity = (this.Destination - this.transform.Rotation) / this.Time } this.elapsedTime = 0.0 } func (this *TweenRotation2D) Update(delta_time float32) bool { if this.transform == nil { return true } this.elapsedTime += delta_time this.transform.Rotation += this.velocity * delta_time if this.elapsedTime >= this.Time { return true } return false } func (this *TweenRotation2D) GetType() uint8 { return this.TweenType } func (this *TweenRotation2D) End() { if this.transform != nil { this.transform.Rotation = this.Destination } } func (this *TweenRotation2D) Reset() { if this.transform != nil { this.transform.Rotation = this.Destination - this.velocity*this.Time this.elapsedTime = 0.0 } } func (this *TweenRotation2D) Copy() Tween { return &TweenRotation2D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} } // A tween that does nothing for a given amount of time type TweenWait struct { // The amount of time it should do nothing in seconds Time float32 // The type of this tween TweenType uint8 elapsedTime float32 } func (this *TweenWait) Start(parent interface{}) { this.elapsedTime = 0.0 } func (this *TweenWait) Update(delta_time float32) bool { this.elapsedTime += delta_time if this.elapsedTime >= this.Time { return true } return false } func (this *TweenWait) GetType() uint8 { return this.TweenType } func (this *TweenWait) End() { } func (this *TweenWait) Reset() { this.elapsedTime = 0.0 } func (this *TweenWait) Copy() Tween { return &TweenWait{Time: this.Time, TweenType: this.TweenType} } // An object which has a visibility type BlinkableObject interface { // Sets the object to be visible SetVisible() // Sets the object to be invisible SetInvisible() // Returns wether the object is visible IsVisible() bool } // A tween that lets its parent blink for given amount of times type TweenBlink struct { // The count of blinks Amount int // The time on blink needs in seconds Time float32 // The type of this tween TweenType uint8 timeForOneBlink float32 elapsedTime float32 oneBlinkElapsedTime float32 previousVisible bool parent BlinkableObject } func (this *TweenBlink) Start(parent interface{}) { this.elapsedTime = 0.0 this.timeForOneBlink = this.Time / float32(this.Amount) if parent != nil { this.parent = parent.(BlinkableObject) if this.parent != nil { this.previousVisible = this.parent.IsVisible() } } } func (this *TweenBlink) Update(delta_time float32) bool { if this.parent == nil { return true } this.elapsedTime += delta_time this.oneBlinkElapsedTime += delta_time if this.oneBlinkElapsedTime >= this.timeForOneBlink/2.0 { if this.parent.IsVisible() { this.parent.SetInvisible() } else { this.parent.SetVisible() } this.oneBlinkElapsedTime = 0.0 } if this.elapsedTime >= this.Time { return true } return false } func (this *TweenBlink) GetType() uint8 { return this.TweenType } func (this *TweenBlink) End() { if this.parent != nil { if this.previousVisible { this.parent.SetVisible() } else { this.parent.SetInvisible() } } } func (this *TweenBlink) Reset() { this.elapsedTime = 0.0 this.oneBlinkElapsedTime = 0.0 if this.parent != nil { if this.previousVisible { this.parent.SetVisible() } else { this.parent.SetInvisible() } } } func (this *TweenBlink) Copy() Tween { return &TweenBlink{Amount: this.Amount, Time: this.Time, TweenType: this.TweenType} } // A tween that scales its parent to a given value type TweenScale2D struct { // The scale the parent should reach Destination mgl32.Vec2 // The time needed for the tween in seconds Time float32 // The type of this tween TweenType uint8 elapsedTime float32 velocity mgl32.Vec2 transform *TransformableObject2D } func (this *TweenScale2D) Start(parent interface{}) { this.elapsedTime = 0.0 this.transform = nil if parent != nil { parent2D, ok := parent.(TweenableObject2D) if ok { this.transform = parent2D.GetTransform2D() } else { return } } else { return } this.velocity = this.Destination.Sub(this.transform.Scale).Mul(1.0 / this.Time) } func (this *TweenScale2D) Update(delta_time float32) bool { if this.transform == nil { return true } this.transform.Scale = this.transform.Scale.Add(this.velocity.Mul(delta_time)) this.elapsedTime += delta_time if this.elapsedTime >= this.Time { return true } return false } func (this *TweenScale2D) End() { if this.transform == nil { return } this.transform.Scale = this.Destination this.elapsedTime = 0.0 } func (this *TweenScale2D) GetType() uint8 { return this.TweenType } func (this *TweenScale2D) Reset() { if this.transform == nil { return } this.elapsedTime = 0.0 this.transform.Scale = this.Destination.Sub(this.velocity.Mul(this.Time)) } func (this *TweenScale2D) Copy() Tween { return &TweenScale2D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} } // A tween that changes the texture region of a Sprite2D like a sprite animation type TweenRegion2D struct { // The texture region the parent should have Destination TextureRegion // The time it should have this region Time float32 // The type of this tween TweenType uint8 startRegion TextureRegion startSize mgl32.Vec2 parent *Sprite2D elapsedTime float32 } func (this *TweenRegion2D) Start(parent interface{}) { this.elapsedTime = 0.0 if parent != nil { this.parent = parent.(*Sprite2D) if this.parent != nil { this.startRegion = this.parent.TextureRegion this.parent.TextureRegion = this.Destination if this.parent.Transform != nil { this.startSize = this.parent.Transform.Size this.parent.Transform.Size = [2]float32{this.Destination.Width(), this.Destination.Height()} } } } } func (this *TweenRegion2D) Update(delta_time float32) bool { if this.parent == nil { return true } this.elapsedTime += delta_time if this.elapsedTime >= this.Time { return true } return false } func (this *TweenRegion2D) End() { if this.parent == nil { return } this.elapsedTime = 0.0 } func (this *TweenRegion2D) GetType() uint8 { return this.TweenType } func (this *TweenRegion2D) Reset() { if this.parent == nil { return } this.elapsedTime = 0.0 this.parent.TextureRegion = this.startRegion if this.parent.Transform != nil { this.parent.Transform.Size = this.startSize } } func (this *TweenRegion2D) Copy() Tween { return &TweenRegion2D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} } // A tween that changes the texture of a Sprite2D type TweenTexture2D struct { // The texture the parent should have Destination Texture // The the parent should have the Texture Time float32 // The type of the tween TweenType uint8 elapsedTime float32 parent *Sprite2D startTexture Texture startSize mgl32.Vec2 } func (this *TweenTexture2D) Start(parent interface{}) { this.elapsedTime = 0.0 if parent != nil { this.parent = parent.(*Sprite2D) if this.parent != nil { this.startTexture = this.parent.Texture this.parent.Texture = this.Destination if this.parent.Transform != nil { this.startSize = this.parent.Transform.Size this.parent.Transform.Size = [2]float32{float32(this.Destination.GetWidth()), float32(this.Destination.GetHeight())} } } } } func (this *TweenTexture2D) Update(delta_time float32) bool { if this.parent == nil { return true } this.elapsedTime += delta_time if this.elapsedTime >= this.Time { return true } return false } func (this *TweenTexture2D) End() { if this.parent == nil { return } this.elapsedTime = 0.0 } func (this *TweenTexture2D) GetType() uint8 { return this.TweenType } func (this *TweenTexture2D) Reset() { if this.parent == nil { return } this.elapsedTime = 0.0 this.parent.Texture = this.startTexture if this.parent.Transform != nil { this.parent.Transform.Size = this.startSize } } func (this *TweenTexture2D) Copy() Tween { return &TweenTexture2D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} } // A tween that moves a 3D object to a certain position type TweenPosition3D struct { // The position the parent should reach Destination mgl32.Vec3 // The time it should need for the movement Time float32 // The type of the tween TweenType uint8 transform *TransformableObject3D velocity mgl32.Vec3 elapsedTime float32 } func (this *TweenPosition3D) Start(parent interface{}) { if parent != nil { parent3D, ok := parent.(TweenableObject3D) if ok { this.transform = parent3D.GetTransform3D() } else { this.transform = nil } } if this.transform != nil { this.velocity = this.Destination.Sub(this.transform.Position).Mul(1.0 / this.Time) } this.elapsedTime = 0.0 } func (this *TweenPosition3D) Update(delta_time float32) bool { if this.transform == nil { return true } this.elapsedTime += delta_time this.transform.Position = this.transform.Position.Add(this.velocity.Mul(delta_time)) if this.elapsedTime >= this.Time { return true } return false } func (this *TweenPosition3D) GetType() uint8 { return this.TweenType } func (this *TweenPosition3D) End() { if this.transform != nil { this.transform.Position = this.Destination } } func (this *TweenPosition3D) Reset() { if this.transform != nil { this.transform.Position = this.Destination.Sub(this.velocity.Mul(this.Time)) this.elapsedTime = 0.0 } } func (this *TweenPosition3D) Copy() Tween { return &TweenPosition3D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} } // A tween that rotates a 3D object type TweenRotation3D struct { // The rotation that should be reached Destination mgl32.Quat // The time needed for the rotation Time float32 // The type of this tween TweenType uint8 transform *TransformableObject3D start mgl32.Quat elapsedTime float32 } func (this *TweenRotation3D) Start(parent interface{}) { parent3D, ok := parent.(TweenableObject3D) if ok { this.transform = parent3D.GetTransform3D() } else { this.transform = nil } this.elapsedTime = 0.0 if this.transform != nil { this.start = this.transform.Rotation } } func (this *TweenRotation3D) Update(delta_time float32) bool { if this.transform == nil { return true } this.elapsedTime += delta_time this.transform.Rotation = mgl32.QuatSlerp(this.start, this.Destination, this.elapsedTime/this.Time) if this.elapsedTime >= this.Time { return true } return false } func (this *TweenRotation3D) GetType() uint8 { return this.TweenType } func (this *TweenRotation3D) End() { if this.transform != nil { this.transform.Rotation = this.Destination } } func (this *TweenRotation3D) Reset() { if this.transform != nil { this.transform.Rotation = this.start } this.elapsedTime = 0.0 } func (this *TweenRotation3D) Copy() Tween { return &TweenRotation3D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} } // A tween that scales a 3D object to a certain value type TweenScale3D struct { // The scale that should be reached Destination mgl32.Vec3 // The time needed for the transformation Time float32 // The type of the tween TweenType uint8 elapsedTime float32 velocity mgl32.Vec3 transform *TransformableObject3D } func (this *TweenScale3D) Start(parent interface{}) { this.elapsedTime = 0.0 this.transform = nil if parent != nil { parent3D, ok := parent.(TweenableObject3D) if ok { this.transform = parent3D.GetTransform3D() } else { return } } else { return } this.velocity = this.Destination.Sub(this.transform.Scale).Mul(1.0 / this.Time) } func (this *TweenScale3D) Update(delta_time float32) bool { if this.transform == nil { return true } this.transform.Scale = this.transform.Scale.Add(this.velocity.Mul(delta_time)) this.elapsedTime += delta_time if this.elapsedTime >= this.Time { return true } return false } func (this *TweenScale3D) End() { if this.transform == nil { return } this.transform.Scale = this.Destination this.elapsedTime = 0.0 } func (this *TweenScale3D) GetType() uint8 { return this.TweenType } func (this *TweenScale3D) Reset() { if this.transform == nil { return } this.elapsedTime = 0.0 this.transform.Scale = this.Destination.Sub(this.velocity.Mul(this.Time)) } func (this *TweenScale3D) Copy() Tween { return &TweenScale3D{Destination: this.Destination, Time: this.Time, TweenType: this.TweenType} }
src/gohome/tweens.go
0.71423
0.586345
tweens.go
starcoder
package ordinarykriging import ( "math" ) // matrixTranspose The matrix is reversed, and the horizontal matrix becomes the vertical matrix // 矩阵颠倒,横向矩阵变成纵向矩阵 func matrixTranspose(X []float64, n, m int) []float64 { Z := make([]float64, m*n) for i := 0; i < n; i++ { for j := 0; j < m; j++ { Z[j*n+i] = X[i*m+j] } } return Z } // matrixMultiply naive matrix multiplication // 矩阵相乘, 横向矩阵乘纵向矩阵 func matrixMultiply(X, Y []float64, n, m, p int) []float64 { Z := make([]float64, n*p) for i := 0; i < n; i++ { for j := 0; j < p; j++ { Z[i*p+j] = 0 for k := 0; k < m; k++ { Z[i*p+j] += X[i*m+k] * Y[k*p+j] } } } return Z } // matrixAdd // 矩阵相加 func matrixAdd(X, Y []float64, n, m int) []float64 { Z := make([]float64, n*m) for i := 0; i < n; i++ { for j := 0; j < m; j++ { Z[i*m+j] = X[i*m+j] + Y[i*m+j] } } return Z } // matrixDiag matrix algebra func matrixDiag(c float64, n int) []float64 { Z := make([]float64, n*n) for i := 0; i < n; i++ { Z[i*n+i] = c } return Z } // matrixChol cholesky decomposition // Cholesky 分解 func matrixChol(X []float64, n int) bool { p := make([]float64, n) for i := 0; i < n; i++ { p[i] = X[i*n+i] } for i := 0; i < n; i++ { for j := 0; j < i; j++ { p[i] -= X[i*n+j] * X[i*n+j] } if p[i] <= 0 { return false } p[i] = math.Sqrt(p[i]) for j := i + 1; j < n; j++ { for k := 0; k < i; k++ { X[j*n+i] -= X[j*n+k] * X[i*n+k] X[j*n+i] /= p[i] } } } for i := 0; i < n; i++ { X[i*n+i] = p[i] } return true } // matrixChol2inv inversion of cholesky decomposition // cholesky 分解的求逆 func matrixChol2inv(X []float64, n int) { var i, j, k int var sum float64 for i = 0; i < n; i++ { X[i*n+i] = 1 / X[i*n+i] for j = i + 1; j < n; j++ { sum = 0 for k = i; k < j; k++ { sum -= X[j*n+k] * X[k*n+i] } X[j*n+i] = sum / X[j*n+j] } } for i = 0; i < n; i++ { for j = i + 1; j < n; j++ { X[i*n+j] = 0 } } for i = 0; i < n; i++ { X[i*n+i] *= X[i*n+i] for k = i + 1; k < n; k++ { X[i*n+i] += X[k*n+i] * X[k*n+i] } for j = i + 1; j < n; j++ { for k = j; k < n; k++ { X[i*n+j] += X[k*n+i] * X[k*n+j] } } } for i = 0; i < n; i++ { for j = 0; j < i; j++ { X[i*n+j] = X[j*n+i] } } }
ordinarykriging/matrix.go
0.564339
0.553988
matrix.go
starcoder
package vmath import ( "fmt" "github.com/maja42/vmath/math32" ) // Rectf represents a 2D, axis-aligned rectangle. type Rectf struct { Min Vec2f Max Vec2f } // RectfFromCorners creates a new rectangle given two opposite corners. // If necessary, coordinates are swapped to create a normalized rectangle. func RectfFromCorners(c1, c2 Vec2f) Rectf { if c1[0] > c2[0] { c1[0], c2[0] = c2[0], c1[0] } if c1[1] > c2[1] { c1[1], c2[1] = c2[1], c1[1] } return Rectf{c1, c2} } // RectfFromPosSize creates a new rectangle with the given size and position. // Negative dimensions are inverted to create a normalized rectangle. func RectfFromPosSize(pos, size Vec2f) Rectf { if size[0] < 0 { size[0] = -size[0] pos[0] -= size[0] } if size[1] < 0 { size[1] = -size[1] pos[1] -= size[1] } return Rectf{ pos, pos.Add(size), } } // RectfFromEdges creates a new rectangle with the given edge positions. // If necessary, edges are swapped to create a normalized rectangle. func RectfFromEdges(left, right, bottom, top float32) Rectf { return RectfFromCorners(Vec2f{left, bottom}, Vec2f{right, top}) } // Normalize ensures that the Min position is smaller than the Max position in every dimension. func (r Rectf) Normalize() Rectf { if r.Min[0] > r.Max[0] { r.Min[0], r.Max[0] = r.Max[0], r.Min[0] } if r.Min[1] > r.Max[1] { r.Min[1], r.Max[1] = r.Max[1], r.Min[1] } return r } func (r Rectf) String() string { return fmt.Sprintf("Rectf([%f x %f]-[%f x %f])", r.Min[0], r.Min[1], r.Max[0], r.Max[1]) } // Recti returns an integer representation of the rectangle. // Decimals are truncated. func (r Rectf) Recti() Recti { return Recti{ r.Min.Vec2i(), r.Max.Vec2i(), } } // Round returns an integer representation of the rectangle. // Decimals are rounded. func (r Rectf) Round() Recti { return Recti{ r.Min.Round(), r.Max.Round(), } } // Size returns the rectangle's dimensions. func (r Rectf) Size() Vec2f { return r.Max.Sub(r.Min) } // Area returns the rectangle's area. func (r Rectf) Area() float32 { size := r.Max.Sub(r.Min) return size[0] * size[1] } // Left returns the rectangle's left position (smaller X). func (r Rectf) Left() float32 { return r.Min[0] } // Right returns the rectangle's right position (bigger X). func (r Rectf) Right() float32 { return r.Max[0] } // Bottom returns the rectangle's bottom position (smaller Y). func (r Rectf) Bottom() float32 { return r.Min[1] } // Top returns the rectangle's top position (bigger Y). func (r Rectf) Top() float32 { return r.Max[1] } // SetPos changes the rectangle position by modifying min, but keeps the rectangle's size. func (r Rectf) SetPos(pos Vec2f) { size := r.Size() r.Min = pos r.Max = r.Min.Add(size) } // SetSize changes the rectangle size by keeping the min-position. func (r Rectf) SetSize(size Vec2f) { r.Max = r.Min.Add(size) } // Add moves the rectangle with the given vector by adding it to the min- and max- components. func (r Rectf) Add(v Vec2f) Rectf { return Rectf{ Min: r.Min.Add(v), Max: r.Max.Add(v), } } // Sub moves the rectangle with the given vector by subtracting it to the min- and max- components. func (r Rectf) Sub(v Vec2f) Rectf { return Rectf{ Min: r.Min.Sub(v), Max: r.Max.Sub(v), } } // Intersects checks if this rectangle intersects another rectangle. // Touching rectangles where floats are exactly equal are not considered to intersect. func (r Rectf) Intersects(other Rectf) bool { return r.Min[0] <= other.Max[0] && r.Max[0] >= other.Min[0] && r.Max[1] >= other.Min[1] && r.Min[1] <= other.Max[1] } // ContainsPoint checks if a given point resides within the rectangle. // If the point is on an edge, it is also considered to be contained within the rectangle. func (r Rectf) ContainsPoint(point Vec2f) bool { return point[0] >= r.Min[0] && point[0] <= r.Max[0] && point[1] >= r.Min[1] && point[1] <= r.Max[1] } // ContainsRectf checks if this rectangle completely contains another rectangle. func (r Rectf) ContainsRectf(other Rectf) bool { return r.Min[0] <= other.Min[0] && r.Max[0] >= other.Max[0] && r.Min[1] <= other.Min[1] && r.Max[1] >= other.Max[1] } // Merge returns a rectangle that contains both smaller rectangles. func (r Rectf) Merge(other Rectf) Rectf { min := Vec2f{ math32.Min(r.Min[0], other.Min[0]), math32.Min(r.Min[1], other.Min[1]), } max := Vec2f{ math32.Max(r.Max[0], other.Max[0]), math32.Max(r.Max[1], other.Max[1]), } return Rectf{min, max} } // SquarePointDistance returns the squared distance between the rectangle and a point. // If the point is contained within the rectangle, 0 is returned. // Otherwise, the squared distance between the point and the nearest edge or corner is returned. func (r Rectf) SquarePointDistance(pos Vec2f) float32 { // Source: "Nearest Neighbor Queries" by <NAME>, <NAME> and <NAME>, ACM SIGMOD, pages 71-79, 1995. sum := float32(0.0) for dim, val := range pos { if val < r.Min[dim] { // below/left of edge d := val - r.Min[dim] sum += d * d } else if val > r.Max[dim] { // above/right of edge d := val - r.Max[dim] sum += d * d } else { sum += 0 } } return sum } // PointDistance returns the distance between the rectangle and a point. // If the point is contained within the rectangle, 0 is returned. // Otherwise, the distance between the point and the nearest edge or corner is returned. func (r Rectf) PointDistance(pos Vec2f) float32 { return math32.Sqrt(r.SquarePointDistance(pos)) }
rectf.go
0.940592
0.640938
rectf.go
starcoder
package models import ( "encoding/json" "fmt" "strings" ) // ConceptMapEquivalence is documented here http://hl7.org/fhir/ValueSet/concept-map-equivalence type ConceptMapEquivalence int const ( ConceptMapEquivalenceRelatedto ConceptMapEquivalence = iota ConceptMapEquivalenceEquivalent ConceptMapEquivalenceEqual ConceptMapEquivalenceWider ConceptMapEquivalenceSubsumes ConceptMapEquivalenceNarrower ConceptMapEquivalenceSpecializes ConceptMapEquivalenceInexact ConceptMapEquivalenceUnmatched ConceptMapEquivalenceDisjoint ) func (code ConceptMapEquivalence) MarshalJSON() ([]byte, error) { return json.Marshal(code.Code()) } func (code *ConceptMapEquivalence) UnmarshalJSON(json []byte) error { s := strings.Trim(string(json), "\"") switch s { case "relatedto": *code = ConceptMapEquivalenceRelatedto case "equivalent": *code = ConceptMapEquivalenceEquivalent case "equal": *code = ConceptMapEquivalenceEqual case "wider": *code = ConceptMapEquivalenceWider case "subsumes": *code = ConceptMapEquivalenceSubsumes case "narrower": *code = ConceptMapEquivalenceNarrower case "specializes": *code = ConceptMapEquivalenceSpecializes case "inexact": *code = ConceptMapEquivalenceInexact case "unmatched": *code = ConceptMapEquivalenceUnmatched case "disjoint": *code = ConceptMapEquivalenceDisjoint default: return fmt.Errorf("unknown ConceptMapEquivalence code `%s`", s) } return nil } func (code ConceptMapEquivalence) String() string { return code.Code() } func (code ConceptMapEquivalence) Code() string { switch code { case ConceptMapEquivalenceRelatedto: return "relatedto" case ConceptMapEquivalenceEquivalent: return "equivalent" case ConceptMapEquivalenceEqual: return "equal" case ConceptMapEquivalenceWider: return "wider" case ConceptMapEquivalenceSubsumes: return "subsumes" case ConceptMapEquivalenceNarrower: return "narrower" case ConceptMapEquivalenceSpecializes: return "specializes" case ConceptMapEquivalenceInexact: return "inexact" case ConceptMapEquivalenceUnmatched: return "unmatched" case ConceptMapEquivalenceDisjoint: return "disjoint" } return "<unknown>" } func (code ConceptMapEquivalence) Display() string { switch code { case ConceptMapEquivalenceRelatedto: return "Related To" case ConceptMapEquivalenceEquivalent: return "Equivalent" case ConceptMapEquivalenceEqual: return "Equal" case ConceptMapEquivalenceWider: return "Wider" case ConceptMapEquivalenceSubsumes: return "Subsumes" case ConceptMapEquivalenceNarrower: return "Narrower" case ConceptMapEquivalenceSpecializes: return "Specializes" case ConceptMapEquivalenceInexact: return "Inexact" case ConceptMapEquivalenceUnmatched: return "Unmatched" case ConceptMapEquivalenceDisjoint: return "Disjoint" } return "<unknown>" } func (code ConceptMapEquivalence) Definition() string { switch code { case ConceptMapEquivalenceRelatedto: return "The concepts are related to each other, and have at least some overlap in meaning, but the exact relationship is not known." case ConceptMapEquivalenceEquivalent: return "The definitions of the concepts mean the same thing (including when structural implications of meaning are considered) (i.e. extensionally identical)." case ConceptMapEquivalenceEqual: return "The definitions of the concepts are exactly the same (i.e. only grammatical differences) and structural implications of meaning are identical or irrelevant (i.e. intentionally identical)." case ConceptMapEquivalenceWider: return "The target mapping is wider in meaning than the source concept." case ConceptMapEquivalenceSubsumes: return "The target mapping subsumes the meaning of the source concept (e.g. the source is-a target)." case ConceptMapEquivalenceNarrower: return "The target mapping is narrower in meaning than the source concept. The sense in which the mapping is narrower SHALL be described in the comments in this case, and applications should be careful when attempting to use these mappings operationally." case ConceptMapEquivalenceSpecializes: return "The target mapping specializes the meaning of the source concept (e.g. the target is-a source)." case ConceptMapEquivalenceInexact: return "The target mapping overlaps with the source concept, but both source and target cover additional meaning, or the definitions are imprecise and it is uncertain whether they have the same boundaries to their meaning. The sense in which the mapping is inexact SHALL be described in the comments in this case, and applications should be careful when attempting to use these mappings operationally." case ConceptMapEquivalenceUnmatched: return "There is no match for this concept in the target code system." case ConceptMapEquivalenceDisjoint: return "This is an explicit assertion that there is no mapping between the source and target concept." } return "<unknown>" }
models/conceptMapEquivalence.gen.go
0.705379
0.411052
conceptMapEquivalence.gen.go
starcoder
package integration import ( "testing" "github.com/CyCoreSystems/ari" "github.com/pkg/errors" tmock "github.com/stretchr/testify/mock" ) func TestApplicationList(t *testing.T, s Server) { runTest("emptyList", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Application.On("List", (*ari.Key)(nil)).Return([]*ari.Key{}, nil) if _, err := cl.Application().List(nil); err != nil { t.Errorf("Unexpected error in remote List call: %v", err) } }) runTest("nonEmptyList", t, s, func(t *testing.T, m *mock, cl ari.Client) { h1 := ari.NewKey(ari.ApplicationKey, "1") h2 := ari.NewKey(ari.ApplicationKey, "2") m.Application.On("List", (*ari.Key)(nil)).Return([]*ari.Key{h1, h2}, nil) items, err := cl.Application().List(nil) if err != nil { t.Errorf("Unexpected error in remote List call: %v", err) } if len(items) != 2 { t.Errorf("Expected items to be length 2, got %d", len(items)) } else { if items[0].ID != "1" { t.Errorf("Expected item 0 to be '1', got %s", items[0].ID) } if items[1].ID != "2" { t.Errorf("Expected item 1 to be '2', got %s", items[1].ID) } } }) } func TestApplicationData(t *testing.T, s Server) { key := ari.NewKey(ari.ApplicationKey, "1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { ad := &ari.ApplicationData{} ad.Name = "app1" m.Application.On("Data", tmock.Anything).Return(ad, nil) res, err := cl.Application().Data(key) if err != nil { t.Errorf("Unexpected error in remote Data call: %v", err) } if res == nil || res.Name != ad.Name { t.Errorf("Expected application data name %s, got %s", ad, res) } m.Shutdown() m.Application.AssertCalled(t, "Data", key) }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("unknown error") m.Application.On("Data", key).Return(nil, expected) res, err := cl.Application().Data(key) if err == nil || errors.Cause(err).Error() != expected.Error() { t.Errorf("Expected error '%v', got '%v'", expected, err) } if res != nil { t.Errorf("Expected application data result to be empty, got %s", res) } m.Shutdown() m.Application.AssertCalled(t, "Data", key) }) } func TestApplicationSubscribe(t *testing.T, s Server) { key := ari.NewKey(ari.ApplicationKey, "1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Application.On("Subscribe", key, "2").Return(nil) if err := cl.Application().Subscribe(key, "2"); err != nil { t.Errorf("Unexpected error in remote Subscribe call: %v", err) } m.Shutdown() m.Application.AssertCalled(t, "Subscribe", key, "2") }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("unknown error") m.Application.On("Subscribe", key, "2").Return(expected) if err := cl.Application().Subscribe(key, "2"); err == nil || errors.Cause(err).Error() != expected.Error() { t.Errorf("Expected error '%v', got '%v'", expected, err) } m.Shutdown() m.Application.AssertCalled(t, "Subscribe", key, "2") }) } func TestApplicationUnsubscribe(t *testing.T, s Server) { key := ari.NewKey(ari.ApplicationKey, "1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Application.On("Unsubscribe", key, "2").Return(nil) if err := cl.Application().Unsubscribe(key, "2"); err != nil { t.Errorf("Unexpected error in remote Unsubscribe call: %T", err) } m.Shutdown() m.Application.AssertCalled(t, "Unsubscribe", key, "2") }) runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := errors.New("unknown error") m.Application.On("Unsubscribe", key, "2").Return(expected) if err := cl.Application().Unsubscribe(key, "2"); err == nil || errors.Cause(err).Error() != expected.Error() { t.Errorf("Expected error '%v', got '%v'", expected, err) } m.Application.AssertCalled(t, "Unsubscribe", key, "2") }) } func TestApplicationGet(t *testing.T, s Server) { key := ari.NewKey(ari.ApplicationKey, "1") runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) { ad := &ari.ApplicationData{} ad.Name = "app1" m.Application.On("Data", tmock.Anything).Return(ad, nil) if h := cl.Application().Get(key); h == nil { t.Errorf("Unexpected nil-handle") } m.Shutdown() m.Application.AssertCalled(t, "Data", key) }) }
internal/integration/application.go
0.550124
0.432663
application.go
starcoder
package pulse import ( "fmt" "sort" "strings" "time" "github.com/insolar/insolar/longbits" "github.com/insolar/insolar/network/consensus/common/cryptkit" ) var _ DataReader = &Data{} type Data struct { PulseNumber Number DataExt } type DataHolder interface { GetPulseNumber() Number GetPulseData() Data GetPulseDataDigest() cryptkit.DigestHolder } type DataExt struct { // ByteSize=44 PulseEpoch Epoch NextPulseDelta uint16 PrevPulseDelta uint16 // Unix millis when the pulse was generated by a Pulsar. MUST be zero otherwise. Timestamp uint32 PulseEntropy longbits.Bits256 } type DataReader interface { GetPulseNumber() Number GetStartOfEpoch() Number GetPulseEntropy() longbits.Bits256 GetNextPulseNumber() (Number, bool) GetPrevPulseNumber() (Number, bool) GetTimestamp() int64 IsExpectedPulse() bool IsFromEphemeral() bool AsPulseData() Data } func NewFirstPulsarData(delta uint16, entropy longbits.Bits256) Data { return newPulsarData(OfNow(), delta, entropy) } func NewPulsarData(pn Number, deltaNext uint16, deltaPrev uint16, entropy longbits.Bits256) Data { r := newPulsarData(pn, deltaNext, entropy) r.PrevPulseDelta = deltaPrev return r } func NewFirstEphemeralData() Data { return newEphemeralData(MinTimePulse) } type EntropyFunc func() longbits.Bits256 func (r Data) String() string { buf := strings.Builder{} buf.WriteString(fmt.Sprint(r.PulseNumber)) ep := r.PulseEpoch if uint32(ep) != uint32(r.PulseNumber) && ep != 0 { buf.WriteString(fmt.Sprintf("(%v)", ep)) } if r.NextPulseDelta == r.PrevPulseDelta { buf.WriteString(fmt.Sprintf("±%d", r.NextPulseDelta)) } else { if r.PrevPulseDelta > 0 { buf.WriteString(fmt.Sprintf("-%d", r.PrevPulseDelta)) } if r.NextPulseDelta > 0 { buf.WriteString(fmt.Sprintf("+%d", r.NextPulseDelta)) } } return buf.String() } func newPulsarData(pn Number, delta uint16, entropy longbits.Bits256) Data { if delta == 0 { panic("delta cant be zero") } return Data{ PulseNumber: pn, DataExt: DataExt{ PulseEpoch: pn.AsEpoch(), PulseEntropy: entropy, Timestamp: uint32(time.Now().Unix()), NextPulseDelta: delta, PrevPulseDelta: 0, }, } } func newEphemeralData(pn Number) Data { s := Data{ PulseNumber: pn, DataExt: DataExt{ PulseEpoch: EphemeralPulseEpoch, Timestamp: 0, NextPulseDelta: 1, PrevPulseDelta: 0, }, } fixedPulseEntropy(&s.PulseEntropy, s.PulseNumber) return s } /* This function has a fixed implementation and MUST remain unchanged as some elements of Consensus rely on identical behavior of this functions. */ func fixedPulseEntropy(v *longbits.Bits256, pn Number) { longbits.FillBitsWithStaticNoise(uint32(pn), (*v)[:]) } func (r Data) EnsurePulseData() { switch { case r.isExpected(): panic("next delta can't be zero") case !r.PulseNumber.IsTimePulse(): panic("incorrect pulse number") case !r.HasValidEpoch(): panic("incorrect pulse epoch") default: r.PulseNumber.Prev(r.PrevPulseDelta) } } func (r Data) HasValidEpoch() bool { switch isValid, isSpecial := r.PulseEpoch.Classify(); { case !isValid: return false case isSpecial: return true default: return r.PulseEpoch <= Epoch(r.PulseNumber) } } func (r Data) HasValidTimeEpoch() bool { return r.PulseEpoch <= Epoch(r.PulseNumber) && r.PulseEpoch.IsTimeEpoch() } func (r Data) isExpected() bool { return r.NextPulseDelta == 0 } func (r Data) isFirst() bool { return r.PrevPulseDelta == 0 } func (r Data) IsValidPulseData() bool { switch { case r.isExpected(): case !r.PulseNumber.IsTimePulse(): case !r.HasValidEpoch(): default: return true } return false } func (r Data) IsEmpty() bool { return r.PulseNumber.IsUnknown() } func (r Data) IsEmptyCompatibleWith(epoch Epoch) bool { return r.PulseNumber.IsUnknown() && r.PulseEpoch.IsCompatible(epoch) } func (r Data) IsValidExpectedPulseData() bool { return r.isExpected() && r.PulseNumber.IsTimePulse() && r.HasValidEpoch() } func (r Data) IsValidExpectedPulsarData() bool { return r.isExpected() && r.PulseNumber.IsTimePulse() && r.HasValidTimeEpoch() } func (r Data) EnsurePulsarData() { if !r.PulseEpoch.IsTimeEpoch() { panic("incorrect pulse epoch by pulsar") } r.EnsurePulseData() } func (r Data) IsValidPulsarData() bool { if !r.PulseEpoch.IsTimeEpoch() { return false } return r.IsValidPulseData() } func (r Data) EnsureEphemeralData() { if !r.PulseEpoch.IsEphemeral() { panic("incorrect pulse epoch") } r.EnsurePulseData() } func (r Data) IsValidEphemeralData() bool { if !r.PulseEpoch.IsEphemeral() { return false } return r.IsValidPulseData() } func (r Data) IsFromPulsar() bool { return r.PulseEpoch.IsTimeEpoch() && r.PulseNumber.IsTimePulse() } func (r Data) IsFromEphemeral() bool { return r.PulseEpoch.IsEphemeral() && r.PulseNumber.IsTimePulse() } func (r Data) GetStartOfEpoch() Number { switch { case !r.PulseNumber.IsTimePulse(): return Unknown case r.HasValidTimeEpoch(): return OfUint32(uint32(r.PulseEpoch)) } return r.PulseNumber } func (r Data) GetPulseEntropy() longbits.Bits256 { return r.PulseEntropy } func (r Data) CreateNextPulse(entropyGen EntropyFunc) Data { switch { case r.PulseEpoch.IsEphemeral(): return r.createNextEphemeralPulse() case r.PulseEpoch.IsTimeEpoch(): return r.createNextPulsarPulse(r.NextPulseDelta, entropyGen) case r.PulseEpoch.IsArticulation(): panic("articulation pulse") default: panic("unknown pulse type") } } func (r Data) IsValidNext(n Data) bool { switch { case r.NextPulseDelta != n.PrevPulseDelta || r.isExpected() || n.isExpected(): case !r.PulseNumber.IsTimePulse(): case r.PulseNumber+Number(r.NextPulseDelta) != n.PulseNumber: case !r.PulseEpoch.IsCompatible(n.PulseEpoch): default: return true } return false } func (r Data) IsValidPrev(p Data) bool { switch { case p.NextPulseDelta != r.PrevPulseDelta || r.isFirst(): case !r.PulseNumber.IsTimePulse(): case p.PulseNumber+Number(p.NextPulseDelta) != r.PulseNumber: case !r.PulseEpoch.IsCompatible(p.PulseEpoch): default: return true } return false } func (r Data) GetNextPulseNumber() (Number, bool) { if r.isExpected() { return r.PulseNumber, false } return r.PulseNumber.TryNext(r.NextPulseDelta) } func (r Data) GetPrevPulseNumber() (Number, bool) { if r.isFirst() { return r.PulseNumber, false } return r.PulseNumber.TryPrev(r.PrevPulseDelta) } func (r Data) NextPulseNumber() Number { if r.isExpected() { panic("illegal state") } return r.PulseNumber.Next(r.NextPulseDelta) } func (r Data) PrevPulseNumber() Number { if r.isFirst() { panic("illegal state") } return r.PulseNumber.Prev(r.PrevPulseDelta) } func (r Data) CreateNextExpected() Data { s := Data{ PulseNumber: r.NextPulseNumber(), DataExt: DataExt{ PulseEpoch: r.PulseEpoch, PrevPulseDelta: r.NextPulseDelta, NextPulseDelta: 0, }, } if r.PulseEpoch.IsTimeEpoch() { s.PulseEpoch = s.PulseNumber.AsEpoch() } return s } func (r Data) CreateNextEphemeralPulse() Data { if !r.IsFromEphemeral() { panic("prev is not ephemeral") } return r.createNextEphemeralPulse() } func (r Data) createNextEphemeralPulse() Data { s := newEphemeralData(r.NextPulseNumber()) s.PrevPulseDelta = r.NextPulseDelta return s } func (r Data) CreateNextPulsarPulse(delta uint16, entropyGen EntropyFunc) Data { if !r.PulseEpoch.IsTimeEpoch() { panic("not time pulse") } return r.createNextPulsarPulse(delta, entropyGen) } func (r Data) createNextPulsarPulse(delta uint16, entropyGen EntropyFunc) Data { s := newPulsarData(r.NextPulseNumber(), delta, entropyGen()) s.PrevPulseDelta = r.NextPulseDelta return s } func (r Data) GetPulseNumber() Number { return r.PulseNumber } func (r Data) GetNextPulseDelta() uint16 { return r.NextPulseDelta } func (r Data) GetPrevPulseDelta() uint16 { return r.PrevPulseDelta } func (r Data) GetTimestamp() int64 { return int64(r.Timestamp) } func (r Data) IsExpectedPulse() bool { return r.isExpected() && r.PulseNumber.IsTimePulse() } func (r Data) IsFirstPulse() bool { return r.isFirst() && r.PulseNumber.IsTimePulse() } func (r Data) AsPulseData() Data { return r } func (r Data) AsRange() Range { r.EnsurePulseData() return onePulseRange{r} } func SortData(data []Data) { sort.Sort(DataSorter{data}) } type DataSorter struct { Data []Data } func (d DataSorter) Len() int { return len(d.Data) } func (d DataSorter) Less(i, j int) bool { return d.Data[i].PulseNumber < d.Data[j].PulseNumber } func (d DataSorter) Swap(i, j int) { d.Data[i], d.Data[j] = d.Data[j], d.Data[i] }
pulse/pulse_data.go
0.689515
0.538559
pulse_data.go
starcoder
package refutil import ( "fmt" "reflect" ) // IsKindComplex returns true if the given Kind is a complex value. func IsKindComplex(k reflect.Kind) bool { return reflect.Complex64 == k || k == reflect.Complex128 } // IsKindFloat returns true if the given Kind is a float value. func IsKindFloat(k reflect.Kind) bool { return reflect.Float32 == k || k == reflect.Float64 } // IsKindInt returns true if the given Kind is a int value. func IsKindInt(k reflect.Kind) bool { return reflect.Int <= k && k <= reflect.Int64 } // IsKindUint returns true if the given Kind is a uint value. func IsKindUint(k reflect.Kind) bool { return reflect.Uint <= k && k <= reflect.Uintptr } // IsKindNumeric returns true if the given Kind is a numeric value. func IsKindNumeric(k reflect.Kind) bool { return (reflect.Int <= k && k <= reflect.Uint64) || (reflect.Float32 <= k && k <= reflect.Complex128) } // IsKindNillable will return true if the Kind is a chan, func, interface, map, // pointer, or slice value, false otherwise. func IsKindNillable(k reflect.Kind) bool { return (reflect.Chan <= k && k <= reflect.Slice) || k == reflect.UnsafePointer } // IsKindLength will return true if the Kind has a length. func IsKindLength(k reflect.Kind) bool { return reflect.Array == k || reflect.Chan == k || reflect.Map == k || reflect.Slice == k || reflect.String == k } // IndirectVal is like Indirect but faster when the caller is using working with // a reflect.Value. func IndirectVal(val reflect.Value) reflect.Value { var last uintptr for { if val.Kind() != reflect.Ptr { return val } ptr := val.Pointer() if ptr == last { return val } last, val = ptr, val.Elem() } } // Indirect will perform recursive indirection on the given value. It should // never panic and will return a value unless indirection is impossible due to // infinite recursion in cases like `type Element *Element`. func Indirect(value interface{}) interface{} { for { val := reflect.ValueOf(value) if val.Kind() != reflect.Ptr { // Value is not a pointer. return value } res := reflect.Indirect(val) if !res.IsValid() || !res.CanInterface() { // Invalid value or can't be returned as interface{}. return value } // Test for a circular type. if res.Kind() == reflect.Ptr && val.Pointer() == res.Pointer() { return value } // Next round. value = res.Interface() } } // Recover will attempt to execute f, if f return a non-nil error it will be // returned. If f panics this function will attempt to recover() and return a // error instead. func Recover(f func() error) (err error) { defer func() { if r := recover(); r != nil { switch T := r.(type) { case error: err = T default: err = fmt.Errorf("panic: %v", r) } } }() err = f() return }
vendor/github.com/cstockton/go-conv/internal/refutil/refutil.go
0.805211
0.563798
refutil.go
starcoder
package timeseries import ( "errors" "strings" "github.com/grokify/mogo/time/timeutil" ) func (ts *TimeSeries) TimeSeriesMonthYOY() TimeSeries { return ts.TimeSeriesMonthXOX(-1, 0, 0, "YoY") } func (ts *TimeSeries) TimeSeriesMonthQOQ() TimeSeries { return ts.TimeSeriesMonthXOX(0, -3, 0, "QoQ") } func (ts *TimeSeries) TimeSeriesMonthMOM() TimeSeries { return ts.TimeSeriesMonthXOX(0, -1, 0, "MoM") } func (ts *TimeSeries) TimeSeriesMonthXOX(years, months, days int, suffix string) TimeSeries { tsm := ts.ToMonth(true) tsXOX := NewTimeSeries(tsm.SeriesName) suffix = strings.TrimSpace(suffix) if len(suffix) > 0 { if len(tsm.SeriesName) > 0 { tsXOX.SeriesName += " " + suffix } else { tsXOX.SeriesName = suffix } } tsXOX.IsFloat = true tsXOX.Interval = tsm.Interval times := tsm.TimeSlice(true) times.SortReverse() for _, dt := range times { dtThis := dt dtPast := dt.AddDate(years, months, days) tiThis, err := tsm.Get(dtThis) if err != nil { panic("cannot find this time") } tiPast, err := ts.Get(dtPast) if err != nil { continue } tsXOX.AddFloat64(dtThis, (tiThis.Float64()-tiPast.Float64())/tiPast.Float64()) } return tsXOX } func (ts *TimeSeries) TimeSeriesYearYOY(suffix string) (TimeSeries, error) { if ts.Interval != timeutil.Year { return TimeSeries{}, errors.New("interval year is required") } // tsm := ts.ToMonth(true) tsYOY := NewTimeSeries(ts.SeriesName) suffix = strings.TrimSpace(suffix) if len(suffix) > 0 { if len(ts.SeriesName) > 0 { tsYOY.SeriesName += " " + suffix } else { tsYOY.SeriesName = suffix } } tsYOY.IsFloat = true tsYOY.Interval = ts.Interval times := ts.TimeSlice(true) times.SortReverse() for _, dt := range times { dtThis := dt dtPast := dt.AddDate(-1, 0, 0) tiThis, err := ts.Get(dtThis) if err != nil { panic("cannot find this time") } tiPast, err := ts.Get(dtPast) if err != nil { continue } tsYOY.AddFloat64(dtThis, (tiThis.Float64()-tiPast.Float64())/tiPast.Float64()) } return tsYOY, nil }
data/timeseries/time_series_month_xox.go
0.684686
0.437824
time_series_month_xox.go
starcoder
package h21 // Row of data table. type Row struct { ID string Description string Comment string } // Table of data. type Table struct { ID string Name string Row []Row } // TableLookup provides valid values for field types. var TableLookup = map[string]Table{ `0001`: {ID: `0001`, Name: `SEX`, Row: []Row{ {ID: `F`, Description: `Female`}, {ID: `M`, Description: `Male`}, {ID: `O`, Description: `Other`}, {ID: `U`, Description: `Unknown`}}}, `0002`: {ID: `0002`, Name: `MARITAL STATUS`, Row: []Row{ {ID: `A`, Description: `Separated`}, {ID: `D`, Description: `Divorced`}, {ID: `M`, Description: `Married`}, {ID: `S`, Description: `Single`}, {ID: `W`, Description: `Widowed`}}}, `0003`: {ID: `0003`, Name: `EVENT TYPE CODE`, Row: []Row{ {ID: `A01`, Description: `Admit a patient`}, {ID: `A02`, Description: `Transfer a Patient`}, {ID: `A03`, Description: `Discharge a Patient`}, {ID: `A04`, Description: `Register a Patient`}, {ID: `A05`, Description: `Pre-admit a Patient`}, {ID: `A06`, Description: `Transfer an outpatient to inpatient`}, {ID: `A07`, Description: `Transfer an Inpatient to Outpatient`}, {ID: `A08`, Description: `Update patient information`}, {ID: `A09`, Description: `Patient departing`}, {ID: `A10`, Description: `Patient arriving`}, {ID: `A11`, Description: `Cancel admit`}, {ID: `A12`, Description: `Cancel transfer`}, {ID: `A13`, Description: `Cancel discharge`}, {ID: `A14`, Description: `Pending admit`}, {ID: `A15`, Description: `Pending transfer`}, {ID: `A16`, Description: `Pending discharge`}, {ID: `A17`, Description: `Swap Patients`}, {ID: `A18`, Description: `Merge patient information`}, {ID: `A19`, Description: `Patient query`}, {ID: `A20`, Description: `Bed status updates`}, {ID: `A21`, Description: `Leave of Absence - Out (leaving)`}, {ID: `A22`, Description: `Leave of Absence - In (returning)`}, {ID: `A23`, Description: `Delete a Patient Record`}, {ID: `A24`, Description: `Link Patient Records`}, {ID: `O01`, Description: `Order message`}, {ID: `O02`, Description: `Order response`}, {ID: `P01`, Description: `Add and update patient account`}, {ID: `P02`, Description: `Purge Patient Accounts`}, {ID: `P03`, Description: `Post detail financial transaction`}, {ID: `P04`, Description: `Generate bills and A/R statements`}, {ID: `Q01`, Description: `Immediate access`}, {ID: `Q02`, Description: `Deferred Access`}, {ID: `R01`, Description: `Unsolicited transmission of requested Observ.`}, {ID: `R03`, Description: `Display oriented results, query/unsol. update`}}}, `0004`: {ID: `0004`, Name: `PATIENT CLASS`, Row: []Row{ {ID: `E`, Description: `Emergency`}, {ID: `I`, Description: `Inpatient`}, {ID: `O`, Description: `Outpatient`}, {ID: `P`, Description: `Preadmit`}}}, `0005`: {ID: `0005`, Name: `ETHNIC GROUP`, Row: []Row{ {ID: `B`, Description: `Black`}, {ID: `C`, Description: `Caucasian`}, {ID: `H`, Description: `Hispanic`}, {ID: `R`, Description: `Oriental`}}}, `0006`: {ID: `0006`, Name: `RELIGION`, Row: []Row{ {ID: `A`, Description: `Atheist`}, {ID: `B`, Description: `Baptist`}, {ID: `C`, Description: `Catholic`}, {ID: `E`, Description: `Episcopalian`}, {ID: `J`, Description: `Judaism`}, {ID: `L`, Description: `Lutheran`}, {ID: `M`, Description: `Church of Latter Day Saints (Mormon)`}, {ID: `N`, Description: `Hindu`}, {ID: `P`, Description: `Protestant`}}}, `0007`: {ID: `0007`, Name: `ADMISSION TYPE`, Row: []Row{ {ID: `A`, Description: `Accident`}, {ID: `E`, Description: `Emergency`}, {ID: `L`, Description: `Labor and Delivery`}, {ID: `R`, Description: `Routine`}}}, `0008`: {ID: `0008`, Name: `ACKNOWLEDGMENT CODE`, Row: []Row{ {ID: `AA`, Description: `Application Accept`}, {ID: `AE`, Description: `Application Error`}, {ID: `AR`, Description: `Application Reject`}}}, `0009`: {ID: `0009`, Name: `AMBULATORY STATUS`, Row: []Row{ {ID: `A0`, Description: `No functional limitations`}, {ID: `A1`, Description: `Ambulates with assistive device`}, {ID: `A2`, Description: `Wheelchair/stretcher bound`}, {ID: `A3`, Description: `Comatose; non-responsive`}, {ID: `A4`, Description: `Disoriented`}, {ID: `A5`, Description: `Vision impaired`}, {ID: `A7`, Description: `Speech impaired`}, {ID: `A8`, Description: `Non-English Speaking`}, {ID: `A9`, Description: `Functional level unknown`}, {ID: `B1`, Description: `Oxygen Therapy`}, {ID: `B2`, Description: `Special Equipment (tunes, IV's, Catheters)`}, {ID: `B3`, Description: `Amputee`}, {ID: `B4`, Description: `Mastectomy`}, {ID: `B5`, Description: `Paraplegic`}, {ID: `B6`, Description: `Pregnant`}}}, `0010`: {ID: `0010`, Name: `PHYSICIAN ID`, Row: []Row{}}, `0017`: {ID: `0017`, Name: `TRANSACTION TYPE`, Row: []Row{}}, `0018`: {ID: `0018`, Name: `PATIENT TYPE`, Row: []Row{}}, `0019`: {ID: `0019`, Name: `ANESTHESIA CODE`, Row: []Row{}}, `0021`: {ID: `0021`, Name: `BAD DEBT AGENCY CODE`, Row: []Row{}}, `0022`: {ID: `0022`, Name: `BILLING STATUS`, Row: []Row{}}, `0023`: {ID: `0023`, Name: `ADMIT SOURCE`, Row: []Row{}}, `0024`: {ID: `0024`, Name: `FEE SCHEDULE`, Row: []Row{}}, `0032`: {ID: `0032`, Name: `CHARGE/PRICE INDICATOR`, Row: []Row{}}, `0036`: {ID: `0036`, Name: `UNITS OF MEASURE - ISO528,1977`, Row: []Row{ {ID: `BT`, Description: `Bottle`}, {ID: `EA`, Description: `Each`}, {ID: `GM`, Description: `Grams`}, {ID: `KG`, Description: `Kilograms`}, {ID: `MEQ`, Description: `Milliequivalent`}, {ID: `MG`, Description: `Milligrams`}, {ID: `OZ`, Description: `Ounces`}, {ID: `SC`, Description: `Square centimeters`}, {ID: `TB`, Description: `Tablet`}, {ID: `VL`, Description: `Vial`}}}, `0038`: {ID: `0038`, Name: `ORDER STATUS`, Row: []Row{ {ID: `CA`, Description: `Order was canceled`}, {ID: `CM`, Description: `Order is completed`}, {ID: `DC`, Description: `Order was discontinued`}, {ID: `ER`, Description: `Error, order not found`}, {ID: `HD`, Description: `Order is on hold`}, {ID: `IP`, Description: `In process, unspecified`}, {ID: `SC`, Description: `In process, scheduled`}}}, `0042`: {ID: `0042`, Name: `INS. COMPANY PLAN CODE`, Row: []Row{}}, `0043`: {ID: `0043`, Name: `CONDITION`, Row: []Row{}}, `0044`: {ID: `0044`, Name: `CONTRACT CODE`, Row: []Row{}}, `0045`: {ID: `0045`, Name: `COURTESY CODE`, Row: []Row{}}, `0046`: {ID: `0046`, Name: `CREDIT RATING`, Row: []Row{}}, `0047`: {ID: `0047`, Name: `DANGER CODE`, Row: []Row{}}, `0048`: {ID: `0048`, Name: `WHAT SUBJECT FILTER`, Row: []Row{ {ID: `ADV`, Description: `Advice/Diagnosis`}, {ID: `ANU`, Description: `Nursing Unit Look up`}, {ID: `APN`, Description: `Patient name look up`}, {ID: `CAN`, Description: `Cancel. Used to cancel a query`}, {ID: `DEM`, Description: `Demographics`}, {ID: `MRI`, Description: `Most recent inpatient`}, {ID: `MRO`, Description: `Most recent outpatient`}, {ID: `OTH`, Description: `Other`}, {ID: `PRO`, Description: `Procedure`}, {ID: `RES`, Description: `Result`}, {ID: `STA`, Description: `Status`}}}, `0049`: {ID: `0049`, Name: `DEPARTMENT CODE`, Row: []Row{}}, `0050`: {ID: `0050`, Name: `ACCIDENT CODE`, Row: []Row{}}, `0051`: {ID: `0051`, Name: `DIAGNOSIS CODE`, Row: []Row{}}, `0052`: {ID: `0052`, Name: `DIAGNOSIS TYPE`, Row: []Row{}}, `0053`: {ID: `0053`, Name: `DIAGNOSIS CODING METHOD`, Row: []Row{ {ID: `I9`, Description: `ICD9`}}}, `0055`: {ID: `0055`, Name: `DRG CODE`, Row: []Row{}}, `0056`: {ID: `0056`, Name: `DRG GROUPER REVIEW CODE`, Row: []Row{}}, `0059`: {ID: `0059`, Name: `CONSENT CODE`, Row: []Row{}}, `0062`: {ID: `0062`, Name: `EVENT REASON`, Row: []Row{ {ID: `01`, Description: `Patient Request`}, {ID: `02`, Description: `Physician Order`}}}, `0063`: {ID: `0063`, Name: `RELATIONSHIP`, Row: []Row{}}, `0064`: {ID: `0064`, Name: `FINANCIAL CLASS`, Row: []Row{}}, `0065`: {ID: `0065`, Name: `ACTION CODE`, Row: []Row{ {ID: `A`, Description: `Add ordered tests to the existing specimen`}, {ID: `C`, Description: `Cancel order for battery or tests named`}, {ID: `G`, Description: `Generated order`}, {ID: `L`, Description: `Lab to obtain specimen from patient.`}, {ID: `O`, Description: `Specimen obtained by service other than Lab`}, {ID: `P`, Description: `Pending specimen-Order sent prior to delivery`}, {ID: `S`, Description: `Schedule the tests specified below`}}}, `0066`: {ID: `0066`, Name: `EMPLOYMENT STATUS`, Row: []Row{}}, `0068`: {ID: `0068`, Name: `GUARANTOR TYPE`, Row: []Row{}}, `0069`: {ID: `0069`, Name: `HOSPITAL SERVICE`, Row: []Row{}}, `0070`: {ID: `0070`, Name: `SOURCE OF SPECIMEN`, Row: []Row{ {ID: `BLD`, Description: `Blood`}, {ID: `BON`, Description: `Bone`}, {ID: `BRN`, Description: `Burn`}, {ID: `CNJT`, Description: `Conjunctiva`}, {ID: `CSF`, Description: `Cerebral spinal fluid`}, {ID: `CVX`, Description: `Cervix`}, {ID: `EAR`, Description: `Ear`}, {ID: `FIB`, Description: `Fibroblood`}, {ID: `HAR`, Description: `Hair`}, {ID: `MN`, Description: `Amniotic Fluid`}, {ID: `NOS`, Description: `Nose`}, {ID: `OTH`, Description: `Other`}, {ID: `PLAS`, Description: `Plasma`}, {ID: `PRT`, Description: `Peritoneal Fluid`}, {ID: `RBC`, Description: `Erythrocytes`}, {ID: `SAL`, Description: `Saliva`}, {ID: `SEM`, Description: `Seminal Fluid`}, {ID: `SER`, Description: `Serum`}, {ID: `SKN`, Description: `Skin`}, {ID: `SNV`, Description: `Synovial Fluid`}, {ID: `STL`, Description: `Stool`}, {ID: `SWT`, Description: `Sweat`}, {ID: `THRT`, Description: `Throat`}, {ID: `TIS`, Description: `Tissue`}, {ID: `UMB`, Description: `Umbilical Blood`}, {ID: `UR`, Description: `Urine`}, {ID: `URTH`, Description: `Urethra`}, {ID: `WBC`, Description: `Leukocytes`}, {ID: `WND`, Description: `Wound`}}}, `0072`: {ID: `0072`, Name: `INS. PLAN ID`, Row: []Row{}}, `0073`: {ID: `0073`, Name: `INTEREST RATE CODE`, Row: []Row{}}, `0074`: {ID: `0074`, Name: `DIAGNOSTIC SERVICE SECTION ID`, Row: []Row{ {ID: `BG`, Description: `Blood gases`}, {ID: `CH`, Description: `Chemistry`}, {ID: `CP`, Description: `Cytopathology`}, {ID: `CT`, Description: `CAT scan`}, {ID: `CUS`, Description: `Cardiac Ultrasound`}, {ID: `EC`, Description: `Electrocardiac (e.g., EKG, EEC, Holter)`}, {ID: `HM`, Description: `Hematology`}, {ID: `IMM`, Description: `Immunology`}, {ID: `MB`, Description: `Microbiology`}, {ID: `MCB`, Description: `Mycobacteriology`}, {ID: `MYC`, Description: `Mycology`}, {ID: `NMR`, Description: `Nuclear magnetic resonance`}, {ID: `NMS`, Description: `Nuclear medicine scan`}, {ID: `NRS`, Description: `Nursing service measures`}, {ID: `OT`, Description: `Occupational Therapy`}, {ID: `OTH`, Description: `Other`}, {ID: `OUS`, Description: `OB Ultrasound`}, {ID: `PHR`, Description: `Pharmacy`}, {ID: `PT`, Description: `Physical Therapy`}, {ID: `RC`, Description: `Respiratory Care`}, {ID: `RT`, Description: `Radiation Therapy`}, {ID: `RUS`, Description: `Radiology ultrasound`}, {ID: `SP`, Description: `Surgical Pathology`}, {ID: `SR`, Description: `Serology`}, {ID: `TX`, Description: `Toxicology`}, {ID: `VUS`, Description: `Vascular Ultrasound`}, {ID: `XRC`, Description: `Cineradiography`}}}, `0076`: {ID: `0076`, Name: `MESSAGE TYPE`, Row: []Row{ {ID: `ACK`, Description: `General Acknowledgment CNT II`}, {ID: `ARD`, Description: `Ancillary RPT (display) ANR VII`}, {ID: `BAR`, Description: `Add/change billing account BLN VI`}, {ID: `DSR`, Description: `Display response QRY V`}, {ID: `MCF`, Description: `Delayed acknowledgment CNT II`}, {ID: `ORF`, Description: `Observ. Result/record resp. ANR VII`}, {ID: `ORM`, Description: `Order ORD IV`}, {ID: `ORR`, Description: `Order response message ORD IV`}, {ID: `ORU`, Description: `Observ. result/unsolicited ANR VII`}, {ID: `OSQ`, Description: `Order status query ORD IV`}, {ID: `UDM`, Description: `Unsolicited display QRY V`}}}, `0078`: {ID: `0078`, Name: `ABNORMAL FLAGS`, Row: []Row{ {ID: `<`, Description: `Below absolute low-off instrument scale`}, {ID: `A`, Description: `Abnormal (applies to non-numeric results)`}, {ID: `AA`, Description: `Very abnormal`}, {ID: `D`, Description: `Significant change down`}, {ID: `H`, Description: `Above high normal`}, {ID: `HH`, Description: `Above upper panic limits`}, {ID: `I`, Description: `Interval`}, {ID: `LL`, Description: `Below lower panic limits`}, {ID: `MS`, Description: `Moderately sensitive`}, {ID: `R`, Description: `Resists`}, {ID: `S`, Description: `Sensitive`}, {ID: `U`, Description: `Significant change up`}, {ID: `VS`, Description: `Very sensitive`}}}, `0079`: {ID: `0079`, Name: `LOCATION`, Row: []Row{}}, `0080`: {ID: `0080`, Name: `NATURE OF ABNORMAL TESTING`, Row: []Row{ {ID: `A`, Description: `An aged based population`}, {ID: `N`, Description: `None - generic normal range`}, {ID: `R`, Description: `A race based population`}, {ID: `S`, Description: `A sexed based population`}}}, `0081`: {ID: `0081`, Name: `NOTICE OF ADMISSION`, Row: []Row{}}, `0083`: {ID: `0083`, Name: `OUTLIER TYPE`, Row: []Row{}}, `0084`: {ID: `0084`, Name: `PERFORMED BY CODE`, Row: []Row{}}, `0085`: {ID: `0085`, Name: `OBSERVATION RESULT STATUS`, Row: []Row{ {ID: `D`, Description: `Delete previously transmitted observation`}, {ID: `F`, Description: `Complete/final results (entered and verified)`}, {ID: `I`, Description: `Specimen in lab--results pending`}, {ID: `R`, Description: `Results entered - not verified`}, {ID: `S`, Description: `Partial results`}}}, `0086`: {ID: `0086`, Name: `INS. PLAN TYPE`, Row: []Row{}}, `0087`: {ID: `0087`, Name: `PRE-ADMIT TESTING`, Row: []Row{}}, `0088`: {ID: `0088`, Name: `PROCEDURE CODE`, Row: []Row{}}, `0089`: {ID: `0089`, Name: `PROCEDURE CODING METHOD`, Row: []Row{}}, `0090`: {ID: `0090`, Name: `PROCEDURE TYPE`, Row: []Row{}}, `0091`: {ID: `0091`, Name: `QUERY PRIORITY`, Row: []Row{ {ID: `D`, Description: `Deferred`}, {ID: `I`, Description: `Immediate`}}}, `0092`: {ID: `0092`, Name: `RE-ADMISSION INDICATOR`, Row: []Row{}}, `0093`: {ID: `0093`, Name: `RELEASE OF INFORMATION`, Row: []Row{}}, `0094`: {ID: `0094`, Name: `REPORT OF ELIGIBILITY`, Row: []Row{}}, `0096`: {ID: `0096`, Name: `FINANCIAL TRANSACTION CODE`, Row: []Row{}}, `0098`: {ID: `0098`, Name: `TYPE OF AGREEMENT CODE`, Row: []Row{}}, `0099`: {ID: `0099`, Name: `VIP INDICATOR`, Row: []Row{}}, `0100`: {ID: `0100`, Name: `WHEN TO CHARGE`, Row: []Row{ {ID: `D`, Description: `On discharge`}, {ID: `O`, Description: `On receipt of order`}, {ID: `R`, Description: `At time service is completed`}, {ID: `S`, Description: `At time service is started`}}}, `0102`: {ID: `0102`, Name: `DELAYED ACKNOWLEDGMENT TYPE`, Row: []Row{ {ID: `D`, Description: `Message Received, stored for later processing`}}}, `0103`: {ID: `0103`, Name: `PROCESSING ID`, Row: []Row{ {ID: `D`, Description: `Debugging`}, {ID: `P`, Description: `Production`}, {ID: `T`, Description: `Training`}}}, `0104`: {ID: `0104`, Name: `VERSION CONTROL TABLE`, Row: []Row{ {ID: `2.0`, Description: `Release 2.0 September 1988`}, {ID: `2.0D`, Description: `Demo 2.0 October 1988`}, {ID: `2.1`, Description: `Release 2.1 March 1990`}}}, `0105`: {ID: `0105`, Name: `SOURCE OF COMMENT`, Row: []Row{ {ID: `L`, Description: `Ancillary department is source of comment`}, {ID: `P`, Description: `Orderer is source of comment`}}}, `0106`: {ID: `0106`, Name: `QUERY FORMAT CODE`, Row: []Row{ {ID: `R`, Description: `Response in Record-oriented format`}}}, `0107`: {ID: `0107`, Name: `DEFERRED RESPONSE TYPE`, Row: []Row{ {ID: `L`, Description: `Later than the DATE/TIME specified`}}}, `0108`: {ID: `0108`, Name: `QUERY RESULTS LEVEL`, Row: []Row{ {ID: `O`, Description: `Order plus order status`}, {ID: `S`, Description: `Status only`}, {ID: `T`, Description: `Full Results`}}}, `0109`: {ID: `0109`, Name: `REPORT PRIORITY`, Row: []Row{ {ID: `R`, Description: `Routine`}, {ID: `S`, Description: `Stat`}}}, `0110`: {ID: `0110`, Name: `TRANSFER TO BAD DEBT CODE`, Row: []Row{}}, `0111`: {ID: `0111`, Name: `DELETE ACCOUNT CODE`, Row: []Row{}}, `0112`: {ID: `0112`, Name: `DISCHARGED DISPOSITION`, Row: []Row{}}, `0113`: {ID: `0113`, Name: `DISCHARGED TO LOCATION`, Row: []Row{}}, `0114`: {ID: `0114`, Name: `DIET TYPE`, Row: []Row{}}, `0115`: {ID: `0115`, Name: `SERVICING FACILITY`, Row: []Row{}}, `0116`: {ID: `0116`, Name: `BED STATUS`, Row: []Row{ {ID: `C`, Description: `Closed`}, {ID: `H`, Description: `Housekeeping`}, {ID: `O`, Description: `Occupied`}}}, `0117`: {ID: `0117`, Name: `ACCOUNT STATUS`, Row: []Row{}}, `0118`: {ID: `0118`, Name: `MAJOR DIAGNOSTIC CATEGORY`, Row: []Row{}}, `0119`: {ID: `0119`, Name: `ORDER CONTROL`, Row: []Row{ {ID: `CA`, Description: `Cancel order request`}, {ID: `CH`, Description: `Child order`}, {ID: `CN`, Description: `Combined result`}, {ID: `DC`, Description: `Discontinue order request`}, {ID: `DE`, Description: `Data Errors`}, {ID: `DR`, Description: `Discontinued as requested`}, {ID: `HD`, Description: `Hold order request`}, {ID: `HR`, Description: `On hold as requested`}, {ID: `NA`, Description: `Number assigned T`}, {ID: `NW`, Description: `New order T`}, {ID: `OD`, Description: `Order discontinued`}, {ID: `OK`, Description: `Order accepted and OK`}, {ID: `OR`, Description: `Released as requested`}, {ID: `PA`, Description: `Parent order`}, {ID: `RE`, Description: `Observations to follow`}, {ID: `RO`, Description: `Replacement order`}, {ID: `RP`, Description: `Order replace request`}, {ID: `RR`, Description: `Request received`}, {ID: `RU`, Description: `Replaced unsolicited`}, {ID: `SN`, Description: `Send filler number F I`}, {ID: `SS`, Description: `Send order status request`}, {ID: `UD`, Description: `Unable to discontinue`}, {ID: `UH`, Description: `Unable to put on hold`}, {ID: `UR`, Description: `Unable to release`}, {ID: `UX`, Description: `Unable to change`}, {ID: `XR`, Description: `Changed as requested`}, {ID: `XX`, Description: `Order changed, unsolicited`}}}, `0121`: {ID: `0121`, Name: `RESPONSE FLAG`, Row: []Row{ {ID: `E`, Description: `Report exceptions only.`}, {ID: `F`, Description: `Same as D, plus confirmations explicitly.`}, {ID: `N`, Description: `Only the MSA segment is returned.`}}}, `0122`: {ID: `0122`, Name: `CHARGE TYPE`, Row: []Row{ {ID: `CH`, Description: `Charge`}, {ID: `CO`, Description: `Contract`}, {ID: `CR`, Description: `Credit`}, {ID: `DP`, Description: `Department`}, {ID: `GR`, Description: `Grant`}, {ID: `NC`, Description: `No Charge`}, {ID: `PC`, Description: `Professional`}, {ID: `RS`, Description: `Research`}}}, `0123`: {ID: `0123`, Name: `RESULT STATUS - OBR`, Row: []Row{ {ID: `C`, Description: `Correction of previously transmitted results`}, {ID: `F`, Description: `Final results - results stored & verified`}, {ID: `I`, Description: `Specimen in lab, not yet processed.`}, {ID: `P`, Description: `Preliminary results`}, {ID: `R`, Description: `Results stored - not yet verified`}, {ID: `S`, Description: `Procedure scheduled, not done`}, {ID: `Y`, Description: `No order on record for this test`}, {ID: `Z`, Description: `No record of this patient`}}}, `0124`: {ID: `0124`, Name: `TRANSPORTATION MODE`, Row: []Row{ {ID: `PORT`, Description: `The examining device goes to Patient's Loc.`}, {ID: `WALK`, Description: `Patient walks to diagnostic service`}, {ID: `WHLC`, Description: `Wheelchair`}}}, `0125`: {ID: `0125`, Name: `VALUE TYPE`, Row: []Row{ {ID: `AD`, Description: `Address`}, {ID: `CK`, Description: `Composite ID with check digit`}, {ID: `FT`, Description: `Formatted Text`}, {ID: `PN`, Description: `Person name`}, {ID: `ST`, Description: `String data. Used to transmit numerics.`}, {ID: `TM`, Description: `Time`}, {ID: `TS`, Description: `Time stamp`}, {ID: `TX`, Description: `Text`}}}, `0126`: {ID: `0126`, Name: `QUANTITY LIMITED REQUEST`, Row: []Row{ {ID: `CH`, Description: `Characters`}, {ID: `LI`, Description: `Lines`}, {ID: `PG`, Description: `Pages`}, {ID: `ZO`, Description: `Locally defined`}}}, } // TableValueLookup may be used to validate a specific value. var TableValueLookup = map[string]map[string]bool{ `0001`: { `F`: true, `M`: true, `O`: true, `U`: true}, `0002`: { `A`: true, `D`: true, `M`: true, `S`: true, `W`: true}, `0003`: { `A01`: true, `A02`: true, `A03`: true, `A04`: true, `A05`: true, `A06`: true, `A07`: true, `A08`: true, `A09`: true, `A10`: true, `A11`: true, `A12`: true, `A13`: true, `A14`: true, `A15`: true, `A16`: true, `A17`: true, `A18`: true, `A19`: true, `A20`: true, `A21`: true, `A22`: true, `A23`: true, `A24`: true, `O01`: true, `O02`: true, `P01`: true, `P02`: true, `P03`: true, `P04`: true, `Q01`: true, `Q02`: true, `R01`: true, `R03`: true}, `0004`: { `E`: true, `I`: true, `O`: true, `P`: true}, `0005`: { `B`: true, `C`: true, `H`: true, `R`: true}, `0006`: { `A`: true, `B`: true, `C`: true, `E`: true, `J`: true, `L`: true, `M`: true, `N`: true, `P`: true}, `0007`: { `A`: true, `E`: true, `L`: true, `R`: true}, `0008`: { `AA`: true, `AE`: true, `AR`: true}, `0009`: { `A0`: true, `A1`: true, `A2`: true, `A3`: true, `A4`: true, `A5`: true, `A7`: true, `A8`: true, `A9`: true, `B1`: true, `B2`: true, `B3`: true, `B4`: true, `B5`: true, `B6`: true}, `0010`: {}, `0017`: {}, `0018`: {}, `0019`: {}, `0021`: {}, `0022`: {}, `0023`: {}, `0024`: {}, `0032`: {}, `0036`: { `BT`: true, `EA`: true, `GM`: true, `KG`: true, `MEQ`: true, `MG`: true, `OZ`: true, `SC`: true, `TB`: true, `VL`: true}, `0038`: { `CA`: true, `CM`: true, `DC`: true, `ER`: true, `HD`: true, `IP`: true, `SC`: true}, `0042`: {}, `0043`: {}, `0044`: {}, `0045`: {}, `0046`: {}, `0047`: {}, `0048`: { `ADV`: true, `ANU`: true, `APN`: true, `CAN`: true, `DEM`: true, `MRI`: true, `MRO`: true, `OTH`: true, `PRO`: true, `RES`: true, `STA`: true}, `0049`: {}, `0050`: {}, `0051`: {}, `0052`: {}, `0053`: { `I9`: true}, `0055`: {}, `0056`: {}, `0059`: {}, `0062`: { `01`: true, `02`: true}, `0063`: {}, `0064`: {}, `0065`: { `A`: true, `C`: true, `G`: true, `L`: true, `O`: true, `P`: true, `S`: true}, `0066`: {}, `0068`: {}, `0069`: {}, `0070`: { `BLD`: true, `BON`: true, `BRN`: true, `CNJT`: true, `CSF`: true, `CVX`: true, `EAR`: true, `FIB`: true, `HAR`: true, `MN`: true, `NOS`: true, `OTH`: true, `PLAS`: true, `PRT`: true, `RBC`: true, `SAL`: true, `SEM`: true, `SER`: true, `SKN`: true, `SNV`: true, `STL`: true, `SWT`: true, `THRT`: true, `TIS`: true, `UMB`: true, `UR`: true, `URTH`: true, `WBC`: true, `WND`: true}, `0072`: {}, `0073`: {}, `0074`: { `BG`: true, `CH`: true, `CP`: true, `CT`: true, `CUS`: true, `EC`: true, `HM`: true, `IMM`: true, `MB`: true, `MCB`: true, `MYC`: true, `NMR`: true, `NMS`: true, `NRS`: true, `OT`: true, `OTH`: true, `OUS`: true, `PHR`: true, `PT`: true, `RC`: true, `RT`: true, `RUS`: true, `SP`: true, `SR`: true, `TX`: true, `VUS`: true, `XRC`: true}, `0076`: { `ACK`: true, `ARD`: true, `BAR`: true, `DSR`: true, `MCF`: true, `ORF`: true, `ORM`: true, `ORR`: true, `ORU`: true, `OSQ`: true, `UDM`: true}, `0078`: { `<`: true, `A`: true, `AA`: true, `D`: true, `H`: true, `HH`: true, `I`: true, `LL`: true, `MS`: true, `R`: true, `S`: true, `U`: true, `VS`: true}, `0079`: {}, `0080`: { `A`: true, `N`: true, `R`: true, `S`: true}, `0081`: {}, `0083`: {}, `0084`: {}, `0085`: { `D`: true, `F`: true, `I`: true, `R`: true, `S`: true}, `0086`: {}, `0087`: {}, `0088`: {}, `0089`: {}, `0090`: {}, `0091`: { `D`: true, `I`: true}, `0092`: {}, `0093`: {}, `0094`: {}, `0096`: {}, `0098`: {}, `0099`: {}, `0100`: { `D`: true, `O`: true, `R`: true, `S`: true}, `0102`: { `D`: true}, `0103`: { `D`: true, `P`: true, `T`: true}, `0104`: { `2.0`: true, `2.0D`: true, `2.1`: true}, `0105`: { `L`: true, `P`: true}, `0106`: { `R`: true}, `0107`: { `L`: true}, `0108`: { `O`: true, `S`: true, `T`: true}, `0109`: { `R`: true, `S`: true}, `0110`: {}, `0111`: {}, `0112`: {}, `0113`: {}, `0114`: {}, `0115`: {}, `0116`: { `C`: true, `H`: true, `O`: true}, `0117`: {}, `0118`: {}, `0119`: { `CA`: true, `CH`: true, `CN`: true, `DC`: true, `DE`: true, `DR`: true, `HD`: true, `HR`: true, `NA`: true, `NW`: true, `OD`: true, `OK`: true, `OR`: true, `PA`: true, `RE`: true, `RO`: true, `RP`: true, `RR`: true, `RU`: true, `SN`: true, `SS`: true, `UD`: true, `UH`: true, `UR`: true, `UX`: true, `XR`: true, `XX`: true}, `0121`: { `E`: true, `F`: true, `N`: true}, `0122`: { `CH`: true, `CO`: true, `CR`: true, `DP`: true, `GR`: true, `NC`: true, `PC`: true, `RS`: true}, `0123`: { `C`: true, `F`: true, `I`: true, `P`: true, `R`: true, `S`: true, `Y`: true, `Z`: true}, `0124`: { `PORT`: true, `WALK`: true, `WHLC`: true}, `0125`: { `AD`: true, `CK`: true, `FT`: true, `PN`: true, `ST`: true, `TM`: true, `TS`: true, `TX`: true}, `0126`: { `CH`: true, `LI`: true, `PG`: true, `ZO`: true}, }
h21/table.go
0.665737
0.848972
table.go
starcoder
package pterm import ( "strings" ) // DefaultParagraph contains the default values for a ParagraphPrinter. var DefaultParagraph = ParagraphPrinter{ MaxWidth: GetTerminalWidth(), } // ParagraphPrinter can print paragraphs to a fixed line width. // The text will split between words, so that words will stick together. // It's like in a book. type ParagraphPrinter struct { MaxWidth int } // WithMaxWidth returns a new ParagraphPrinter with a specific MaxWidth func (p ParagraphPrinter) WithMaxWidth(width int) *ParagraphPrinter { p.MaxWidth = width return &p } // Sprint formats using the default formats for its operands and returns the resulting string. // Spaces are added between operands when neither is a string. func (p ParagraphPrinter) Sprint(a ...interface{}) string { words := strings.Fields(strings.TrimSpace(Sprint(a...))) if len(words) == 0 { return "" } wrapped := words[0] spaceLeft := p.MaxWidth - len(wrapped) for _, word := range words[1:] { if len(word)+1 > spaceLeft { wrapped += "\n" + word spaceLeft = p.MaxWidth - len(word) } else { wrapped += " " + word spaceLeft -= 1 + len(word) } } return wrapped } // Sprintln formats using the default formats for its operands and returns the resulting string. // Spaces are always added between operands and a newline is appended. func (p ParagraphPrinter) Sprintln(a ...interface{}) string { return Sprintln(p.Sprint(a...)) } // Sprintf formats according to a format specifier and returns the resulting string. func (p ParagraphPrinter) Sprintf(format string, a ...interface{}) string { return p.Sprint(Sprintf(format, a...)) } // Print formats using the default formats for its operands and writes to standard output. // Spaces are added between operands when neither is a string. // It returns the number of bytes written and any write error encountered. func (p *ParagraphPrinter) Print(a ...interface{}) *TextPrinter { Print(p.Sprint(a...)) tp := TextPrinter(p) return &tp } // Println formats using the default formats for its operands and writes to standard output. // Spaces are always added between operands and a newline is appended. // It returns the number of bytes written and any write error encountered. func (p *ParagraphPrinter) Println(a ...interface{}) *TextPrinter { Println(p.Sprint(a...)) tp := TextPrinter(p) return &tp } // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. func (p *ParagraphPrinter) Printf(format string, a ...interface{}) *TextPrinter { Print(p.Sprintf(format, a...)) tp := TextPrinter(p) return &tp }
paragraph_printer.go
0.633637
0.532972
paragraph_printer.go
starcoder
package main import ( "context" "fmt" "github.com/google/go-cmp/cmp" "github.com/sourcegraph/sourcegraph/lib/errors" ) // buildQueries returns a channel that is fed all of the test functions that should be invoked // as part of the test. This function depends on the flags provided by the user to alter the // behavior of the testing functions. func buildQueries() <-chan queryFunc { fns := make(chan queryFunc) go func() { defer close(fns) for _, testCase := range testCases { // Definition returns defintion fns <- makeTestFunc("def -> def", queryDefinitions, testCase.Definition, []Location{testCase.Definition}) // References return definition for _, reference := range testCase.References { fns <- makeTestFunc("refs -> def", queryDefinitions, reference, []Location{testCase.Definition}) } // Definition returns references fns <- makeTestFunc("def -> refs", queryReferences, testCase.Definition, testCase.References) // References return references if queryReferencesOfReferences { for _, reference := range testCase.References { fns <- makeTestFunc("refs -> refs", queryReferences, reference, testCase.References) } } } }() return fns } type testFunc func(ctx context.Context, location Location) ([]Location, error) // makeTestFunc returns a test function that invokes the given function f with the given // source, then compares the result against the set of expected locations. This function // depends on the flags provided by the user to alter the behavior of the testing // functions. func makeTestFunc(name string, f testFunc, source Location, expectedLocations []Location) func(ctx context.Context) error { return func(ctx context.Context) error { locations, err := f(ctx, source) if err != nil { return err } if checkQueryResult { sortLocations(locations) if allowDirtyInstance { // We allow other upload records to exist on the instance, so we might have // additional locations. Here, we trim down the set of returned locations // to only include the expected values, and check only that the instance gave // us a superset of the expected output. filteredLocations := locations[:0] outer: for _, location := range locations { for _, expectedLocation := range expectedLocations { if expectedLocation == location { filteredLocations = append(filteredLocations, location) continue outer } } } locations = filteredLocations } if diff := cmp.Diff(expectedLocations, locations); diff != "" { collectRepositoryToResults := func(locations []Location) map[string]int { repositoryToResults := map[string]int{} for _, location := range locations { if _, ok := repositoryToResults[location.Repo]; !ok { repositoryToResults[location.Repo] = 0 } repositoryToResults[location.Repo] += 1 } return repositoryToResults } e := "" e += fmt.Sprintf("%s: unexpected results\n\n", name) e += fmt.Sprintf("started at location:\n\n %+v\n\n", source) e += "results by repository:\n\n" allRepos := map[string]struct{}{} for _, location := range append(locations, expectedLocations...) { allRepos[location.Repo] = struct{}{} } repositoryToGottenResults := collectRepositoryToResults(locations) repositoryToWantedResults := collectRepositoryToResults(expectedLocations) for repo := range allRepos { e += fmt.Sprintf(" - %s: want %d locations, got %d locations\n", repo, repositoryToWantedResults[repo], repositoryToGottenResults[repo]) } e += "\n" e += "raw diff (-want +got):\n\n" + diff return errors.Errorf(e) } } return nil } }
dev/codeintel-qa/cmd/query/queries.go
0.826151
0.451145
queries.go
starcoder
package lshensemble import ( "errors" "fmt" "sync" "time" cmap "github.com/orcaman/concurrent-map" ) type param struct { k int l int } // Partition represents a domain size partition in the LSH Ensemble index. type Partition struct { Lower int `json:"lower"` Upper int `json:"upper"` } // Lsh interface is implemented by LshForst and LshForestArray. type Lsh interface { // Add addes a new key into the index, it won't be searchable // until the next time Index() is called since the add. Add(key interface{}, sig []uint64) // Index makes all keys added so far searchable. Index() // Query searches the index given a minhash signature, and // the LSH parameters k and l. Result keys will be written to // the channel out. // Closing channel done will cancels the query execution. Query(sig []uint64, k, l int, out chan<- interface{}, done <-chan struct{}) // OptimalKL computes the optimal LSH parameters k and l given // x, the index domain size, q, the query domain size, and t, // the containment threshold. The resulting false positive (fp) // and false negative (fn) probabilities are returned as well. OptimalKL(x, q int, t float64) (optK, optL int, fp, fn float64) } // LshEnsemble represents an LSH Ensemble index. type LshEnsemble struct { Partitions []Partition lshes []Lsh maxK int numHash int paramCache cmap.ConcurrentMap } // NewLshEnsemble initializes a new index consists of MinHash LSH implemented using LshForest. // numHash is the number of hash functions in MinHash. // maxK is the maximum value for the MinHash parameter K - the number of hash functions per "band". // initSize is the initial size of underlying hash tables to allocate. func NewLshEnsemble(parts []Partition, numHash, maxK, initSize int) *LshEnsemble { lshes := make([]Lsh, len(parts)) for i := range lshes { lshes[i] = NewLshForest(maxK, numHash/maxK, initSize) } return &LshEnsemble{ lshes: lshes, Partitions: parts, maxK: maxK, numHash: numHash, paramCache: cmap.New(), } } // NewLshEnsemblePlus initializes a new index consists of MinHash LSH implemented using LshForestArray. // numHash is the number of hash functions in MinHash. // maxK is the maximum value for the MinHash parameter K - the number of hash functions per "band". // initSize is the initial size of underlying hash tables to allocate. func NewLshEnsemblePlus(parts []Partition, numHash, maxK, initSize int) *LshEnsemble { lshes := make([]Lsh, len(parts)) for i := range lshes { lshes[i] = NewLshForestArray(maxK, numHash, initSize) } return &LshEnsemble{ lshes: lshes, Partitions: parts, maxK: maxK, numHash: numHash, paramCache: cmap.New(), } } // Add a new domain to the index given its partition ID - the index of the partition. // The added domain won't be searchable until the Index() function is called. func (e *LshEnsemble) Add(key interface{}, sig []uint64, partInd int) { e.lshes[partInd].Add(key, sig) } // Prepare adds a new domain to the index given its size, and partition will // be selected automatically. It could be more efficient to use Add(). // The added domain won't be searchable until the Index() function is called. func (e *LshEnsemble) Prepare(key interface{}, sig []uint64, size int) error { for i := range e.Partitions { if size >= e.Partitions[i].Lower && size <= e.Partitions[i].Upper { e.Add(key, sig, i) break } } return errors.New("No matching partition found") } // Index makes all added domains searchable. func (e *LshEnsemble) Index() { for i := range e.lshes { e.lshes[i].Index() } } // Query returns the candidate domain keys in a channel. // This function is given the MinHash signature of the query domain, sig, the domain size, // the containment threshold, and a cancellation channel. // Closing channel done will cancel the query execution. // The query signature must be generated using the same seed as the signatures of the indexed domains, // and have the same number of hash functions. func (e *LshEnsemble) Query(sig []uint64, size int, threshold float64, done <-chan struct{}) <-chan interface{} { params := e.computeParams(size, threshold) return e.queryWithParam(sig, params, done) } // QueryTimed is similar to Query, returns the candidate domain keys in a slice as well as the running time. func (e *LshEnsemble) QueryTimed(sig []uint64, size int, threshold float64) (result []interface{}, dur time.Duration) { // Compute the optimal k and l for each partition params := e.computeParams(size, threshold) result = make([]interface{}, 0) done := make(chan struct{}) defer close(done) start := time.Now() for key := range e.queryWithParam(sig, params, done) { result = append(result, key) } dur = time.Since(start) return result, dur } func (e *LshEnsemble) queryWithParam(sig []uint64, params []param, done <-chan struct{}) <-chan interface{} { // Collect candidates from all partitions keyChan := make(chan interface{}) var wg sync.WaitGroup wg.Add(len(e.lshes)) for i := range e.lshes { go func(lsh Lsh, k, l int) { lsh.Query(sig, k, l, keyChan, done) wg.Done() }(e.lshes[i], params[i].k, params[i].l) } go func() { wg.Wait() close(keyChan) }() return keyChan } // Compute the optimal k and l for each partition func (e *LshEnsemble) computeParams(size int, threshold float64) []param { params := make([]param, len(e.Partitions)) for i, p := range e.Partitions { x := p.Upper key := cacheKey(x, size, threshold) if cached, exist := e.paramCache.Get(key); exist { params[i] = cached.(param) } else { optK, optL, _, _ := e.lshes[i].OptimalKL(x, size, threshold) computed := param{optK, optL} e.paramCache.Set(key, computed) params[i] = computed } } return params } // Make a cache key with threshold precision to 2 decimal points func cacheKey(x, q int, t float64) string { return fmt.Sprintf("%.8x %.8x %.2f", x, q, t) }
lshensemble.go
0.721154
0.403508
lshensemble.go
starcoder
package flight import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "os" ) type Passengers struct { Kind string `json:kind` AdultCount int `json:adultCount` ChildCount int `json:childCount` InfantInLapCount int `json:infantInLapCount` InfantInSeatCount int `json:infantInSeatCount` SeniorCount int `json:seniorCount` } type PermittedDepartureTime struct { Kind string `json:kind` EarliestTime string `json:earliestTime` LatestTime string `json:latestTime` } type RequestSlice struct { Kind string `json:kind` Origin string `json:origin` Destination string `json:destination` Date string `json:date` MaxStops int `json:maxStops` MaxConnectionDuration int `json:maxConnectionDuration` PreferredCabin string `json:preferredCabin` PermittedDepartureTime *PermittedDepartureTime `json:permittedDepartureTime` PermittedCarrier []string `json:permittedCarrier` ProhibitedCarrier []string `json:prohibitedCarrier` } type Request struct { Passengers *Passengers `json:passengers` Slice []*RequestSlice `json:slice` MaxPrice string `json:maxPrice` SaleCountry string `json:saleCountry` Refundable string `json:refundable` } type City struct { Kind string `json:kind` Code string `json:code` Name string `json:name` Country string `json:country` } type Airport struct { Kind string `json:kind` Name string `json:name` Code string `json:code` City string `json:city` } type Tax struct { Kind string `json:kind` Name string `json:name` ID string `json:id` ChargeType string `json:chargeType` Code string `json:code` Country string `json:country` SalePrice string `json:salePrice` } type Aircraft struct { Kind string `json:kind` Name string `json:name` Code string `json:code` } type Carrier struct { Kind string `json:kind` Name string `json:name` Code string `json:code` } type TripData struct { Kind string `json:kind` Airport []*Airport `json:airport` City []*City `json:city` Aircraft []*Aircraft `json:aircraft` Tax []*Tax `json:tax` Carrier []*Carrier `json:carrier` } type TripOption struct { Kind string `json:kind` ID string `json:id` SaleTotal string `json:saleTotal` } type Fare struct { Kind string `json:kind` ID string `json:id` Carrier *Carrier `json:carrier` Origin string `json:origin` Destination string `json:destination` BasisCode string `json:basisCode` Private bool `json:private` } type Price struct { Kind string `json:kind` Fares Fare `json:fare` } type BagDescriptor struct { Kind string `json:kind` CommercialName string `json:commercialName` Count int `json:count` Description []string `json:description` Subcode string `json:subcode` } type FreeBaggageOption struct { Kind string `json:kind` Descriptor *BagDescriptor `json:bagDescriptor` } type SegmentPrice struct { Kind string `json:kind` FareID string `json:fareId` SegmentID string `json:segmentId` FreeBaggageOptions []*FreeBaggageOption `json:freeBaggageOption` Kilos int `json:kilos` KilosPerPiece int `json:kilosPerPiece` Pieces int `json:pieces` Pounds int `json:pounds` } type Trips struct { Kind string `json:kind` RequestId string `json:requestId` Data *TripData `json:data` Options *TripOption `json:tripOption` Pricing []*Price `json:pricing` SegmentPricing []*SegmentPrice `json:segmentPricing` BaseFareTotal string `json:baseFareTotal` SaleFareTotal string `json:saleFareTotal` SaleTaxTotal string `json:saleTaxTotal` SaleTotal string `json:saleTotal` Passengers *Passengers `json:passengers` Tax *Tax `json:tax` FareCalculation string `json:fareCalculation` LatestTicketingTime string `json:latestTicketingTime` PTC string `json:ptc` Refundable bool `json:refundable` } type Flight struct { Carrier string `json:carrier` Number string `json:number` } type Leg struct { Kind string `json:kind` Duration int `json:duration` ID string `json:id` ArrivalTime string `json:arrivalTime` DepartureTime string `json:departureTime` Origin string `json:origin` Destination string `json:destination` OriginTerminal string `json:originTerminal` DestinationTerminal string `json:destinationTerminal` OperatingDisclosure string `json:operatingDisclosure` OnTimePerformance int `json:onTimePerformance` Mileage int `json:mileage` Meal string `json:meal` Secure bool `json:secure` ConnectionDuration int `json:connectionDuration` ChangePlane bool `json:changePlane` } type Segment struct { Kind string `json:kind` Duration string `json:duration` Flight *Flight `json:flight` ID string `json:id` Cabin string `json:cabin` BookingCode string `json:bookingCode` BookingCodeCount int `json:bookingCodeCount` MarriedSegmentGroup string `json:marriedSegmentGroup` SubjectToGovernmentApproval bool `json:subjectToGovernmentApproval` Legs []*Leg `json:leg` ConnectionDuration int `json:connectionDuration` } type ResponseSlice struct { Kind string `json:kind` Duration string `json:duration` Segment []*Segment `json:segment` } type Response struct { Kind string `json:kind` Trips Trips `json:trips` Slice []*ResponseSlice `json:slice` } type GoFlyer interface { GetFlight(Request) (Response, error) } type MockFlight struct { } func (flight MockFlight) GetFlight(apiRequest Request) (Response, error) { response := Response{} file, e := ioutil.ReadFile("test_response.json") if e != nil { fmt.Printf("File error: %v\n", e) os.Exit(1) } err := json.Unmarshal(file, &response) return response, err } type GoFlight struct { ApiKey string } func (flight *GoFlight) GetFlight(apiRequest Request) (Response, error) { url := fmt.Sprintf("https://www.googleapis.com/qpxExpress/v1/trips/search?key=%s", flight.ApiKey) fmt.Println("URL:>", url) jsonData, err := json.Marshal(apiRequest) req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() var response Response body, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(body, &response) return response, err }
main.go
0.545044
0.533944
main.go
starcoder
package math4g // Mat32 is a 3x2 matrix is represented as float[6]. type Mat32 [6]Scala // NewMat32 creates Mat32 instance func NewMat32(a, b, c, d, e, f Scala) Mat32 { return Mat32{a, b, c, d, e, f} } // IdentityMatrix makes the transform to identity matrix. func IdentityMat32() Mat32 { return NewMat32(1.0, 0.0, 0.0, 1.0, 0.0, 0.0) } // TranslateMatrix makes the transform to translation matrix matrix. func TranslateMat32(tx, ty Scala) Mat32 { return NewMat32(1.0, 0.0, 0.0, 1.0, tx, ty) } // ScaleMatrix makes the transform to scale matrix. func ScaleMat32(sx, sy Scala) Mat32 { return NewMat32(sx, 0.0, 0.0, sy, 0.0, 0.0) } // RotateMatrix makes the transform to rotate matrix. Angle is specified in radians. func RotateMat32(a Scala) Mat32 { sin, cos := Sincos(a) return NewMat32(Scala(cos), Scala(sin), Scala(-sin), Scala(cos), 0.0, 0.0) } // SkewXMatrix makes the transform to skew-x matrix. Angle is specified in radians. func SkewXMat32(a Scala) Mat32 { return NewMat32(1.0, 0.0, Tan(a), 1.0, 0.0, 0.0) } // SkewYMatrix makes the transform to skew-y matrix. Angle is specified in radians. func SkewYMat32(a Scala) Mat32 { return NewMat32(1.0, Tan(a), 0.0, 1.0, 0.0, 0.0) } // Multiply makes the transform to the result of multiplication of two transforms, of A = A*B. func (t Mat32) Multiply(s Mat32) Mat32 { t0 := t[0]*s[0] + t[1]*s[2] t2 := t[2]*s[0] + t[3]*s[2] t4 := t[4]*s[0] + t[5]*s[2] + s[4] t[1] = t[0]*s[1] + t[1]*s[3] t[3] = t[2]*s[1] + t[3]*s[3] t[5] = t[4]*s[1] + t[5]*s[3] + s[5] t[0] = t0 t[2] = t2 t[4] = t4 return t } // PreMultiply makes the transform to the result of multiplication of two transforms, of A = B*A. func (t Mat32) PreMultiply(s Mat32) Mat32 { return s.Multiply(t) } // InlinePreMultiply makes the transform to the result of multiplication of two transforms, of A = B*A. func (s *Mat32) InlinePreMultiply(t *Mat32) { s0 := t[0]*s[0] + t[1]*s[2] s2 := t[2]*s[0] + t[3]*s[2] s4 := t[4]*s[0] + t[5]*s[2] + s[4] s[1] = t[0]*s[1] + t[1]*s[3] s[3] = t[2]*s[1] + t[3]*s[3] s[5] = t[4]*s[1] + t[5]*s[3] + s[5] s[0] = s0 s[2] = s2 s[4] = s4 } // Inverse makes the destination to inverse of specified transform. // Returns 1 if the inverse could be calculated, else 0. func (t Mat32) Inverse() Mat32 { det := t[0]*t[3] - t[2]*t[1] if det > -1e-6 && det < 1e-6 { return IdentityMat32() } invdet := 1.0 / det return Mat32{ t[3] * invdet, -t[1] * invdet, -t[2] * invdet, t[0] * invdet, (t[2]*t[5] - t[3]*t[4]) * invdet, (t[1]*t[4] - t[0]*t[5]) * invdet, } } // TransformPoint transforms a point by given Transform. func (t Mat32) TransformPoint(sx, sy Scala) (dx, dy Scala) { dx = sx*t[0] + sy*t[2] + t[4] dy = sx*t[1] + sy*t[3] + t[5] return } // Transform transforms a pointer that is represented by vector by given Matrix. func (t *Mat32) Transform(v Vec2) Vec2 { return Vec2{ v[0]*t[0] + v[1]*t[2] + t[4], v[0]*t[1] + v[1]*t[3] + t[5], } } // ToMat3x4 makes 3x4 matrix. func (t Mat32) ToMat34() []Scala { return []Scala{ t[0], t[1], 0.0, 0.0, t[2], t[3], 0.0, 0.0, t[4], t[5], 1.0, 0.0, } } func (t Mat32) getAverageScale() Scala { sx := Sqrt(t[0]*t[0] + t[2]*t[2]) sy := Sqrt(t[1]*t[1] + t[3]*t[3]) return (sx + sy) * 0.5 }
mat32.go
0.879781
0.808635
mat32.go
starcoder
package onshape import ( "encoding/json" ) // BTMassPropertiesBulkInfo struct for BTMassPropertiesBulkInfo type BTMassPropertiesBulkInfo struct { Bodies *map[string]BTMassPropertiesInfoNull `json:"bodies,omitempty"` MicroversionId *string `json:"microversionId,omitempty"` } // NewBTMassPropertiesBulkInfo instantiates a new BTMassPropertiesBulkInfo 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 NewBTMassPropertiesBulkInfo() *BTMassPropertiesBulkInfo { this := BTMassPropertiesBulkInfo{} return &this } // NewBTMassPropertiesBulkInfoWithDefaults instantiates a new BTMassPropertiesBulkInfo 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 NewBTMassPropertiesBulkInfoWithDefaults() *BTMassPropertiesBulkInfo { this := BTMassPropertiesBulkInfo{} return &this } // GetBodies returns the Bodies field value if set, zero value otherwise. func (o *BTMassPropertiesBulkInfo) GetBodies() map[string]BTMassPropertiesInfoNull { if o == nil || o.Bodies == nil { var ret map[string]BTMassPropertiesInfoNull return ret } return *o.Bodies } // GetBodiesOk returns a tuple with the Bodies field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTMassPropertiesBulkInfo) GetBodiesOk() (*map[string]BTMassPropertiesInfoNull, bool) { if o == nil || o.Bodies == nil { return nil, false } return o.Bodies, true } // HasBodies returns a boolean if a field has been set. func (o *BTMassPropertiesBulkInfo) HasBodies() bool { if o != nil && o.Bodies != nil { return true } return false } // SetBodies gets a reference to the given map[string]BTMassPropertiesInfoNull and assigns it to the Bodies field. func (o *BTMassPropertiesBulkInfo) SetBodies(v map[string]BTMassPropertiesInfoNull) { o.Bodies = &v } // GetMicroversionId returns the MicroversionId field value if set, zero value otherwise. func (o *BTMassPropertiesBulkInfo) GetMicroversionId() string { if o == nil || o.MicroversionId == nil { var ret string return ret } return *o.MicroversionId } // GetMicroversionIdOk returns a tuple with the MicroversionId field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTMassPropertiesBulkInfo) GetMicroversionIdOk() (*string, bool) { if o == nil || o.MicroversionId == nil { return nil, false } return o.MicroversionId, true } // HasMicroversionId returns a boolean if a field has been set. func (o *BTMassPropertiesBulkInfo) HasMicroversionId() bool { if o != nil && o.MicroversionId != nil { return true } return false } // SetMicroversionId gets a reference to the given string and assigns it to the MicroversionId field. func (o *BTMassPropertiesBulkInfo) SetMicroversionId(v string) { o.MicroversionId = &v } func (o BTMassPropertiesBulkInfo) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Bodies != nil { toSerialize["bodies"] = o.Bodies } if o.MicroversionId != nil { toSerialize["microversionId"] = o.MicroversionId } return json.Marshal(toSerialize) } type NullableBTMassPropertiesBulkInfo struct { value *BTMassPropertiesBulkInfo isSet bool } func (v NullableBTMassPropertiesBulkInfo) Get() *BTMassPropertiesBulkInfo { return v.value } func (v *NullableBTMassPropertiesBulkInfo) Set(val *BTMassPropertiesBulkInfo) { v.value = val v.isSet = true } func (v NullableBTMassPropertiesBulkInfo) IsSet() bool { return v.isSet } func (v *NullableBTMassPropertiesBulkInfo) Unset() { v.value = nil v.isSet = false } func NewNullableBTMassPropertiesBulkInfo(val *BTMassPropertiesBulkInfo) *NullableBTMassPropertiesBulkInfo { return &NullableBTMassPropertiesBulkInfo{value: val, isSet: true} } func (v NullableBTMassPropertiesBulkInfo) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBTMassPropertiesBulkInfo) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
onshape/model_bt_mass_properties_bulk_info.go
0.693992
0.403302
model_bt_mass_properties_bulk_info.go
starcoder
package main import ( "fmt" "io" "text/template" ) const checkNativeiterable = `func checkNativeIterable(t *Dense, dims int, dt Dtype) error { // checks: if !t.IsNativelyAccessible() { return errors.Errorf("Cannot convert *Dense to *mat.Dense. Data is inaccessible") } if t.Shape().Dims() != dims { return errors.Errorf("Cannot convert *Dense to native iterator. Expected number of dimension: %d, T has got %d dimensions (Shape: %v)", dims, t.Dims(), t.Shape()) } if t.F() || t.RequiresIterator() { return errors.Errorf("Not yet implemented: native matrix for colmajor or unpacked matrices") } if t.Dtype() != dt { return errors.Errorf("Conversion to native iterable only works on %v. Got %v", dt, t.Dtype()) } return nil } ` const nativeIterRaw = `// Vector{{short .}} converts a *Dense into a []{{asType .}} // If the *Dense does not represent a vector of the wanted type, it will return an error. func Vector{{short .}}(t *Dense) (retVal []{{asType .}}, err error) { if err = checkNativeIterable(t, 1, {{reflectKind .}}); err != nil { return nil, err } return t.{{sliceOf .}}, nil } // Matrix{{short .}} converts a *Dense into a [][]{{asType .}} // If the *Dense does not represent a matrix of the wanted type, it will return an error. func Matrix{{short .}}(t *Dense) (retVal [][]{{asType .}}, err error) { if err = checkNativeIterable(t, 2, {{reflectKind .}}); err != nil { return nil, err } data := t.{{sliceOf .}} shape := t.Shape() strides := t.Strides() rows := shape[0] cols := shape[1] rowStride := strides[0] retVal = make([][]{{asType .}}, rows) for i := range retVal { start := i * rowStride hdr := &reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(&data[start])), Len: cols, Cap: cols, } retVal[i] = *(*[]{{asType .}})(unsafe.Pointer(hdr)) } return } // Tensor3{{short .}} converts a *Dense into a [][][]{{asType .}}. // If the *Dense does not represent a 3-tensor of the wanted type, it will return an error. func Tensor3{{short .}}(t *Dense) (retVal [][][]{{asType .}}, err error) { if err = checkNativeIterable(t, 3, {{reflectKind .}}); err != nil { return nil, err } data := t.{{sliceOf .}} shape := t.Shape() strides := t.Strides() layers := shape[0] rows := shape[1] cols := shape[2] layerStride := strides[0] rowStride := strides[1] retVal = make([][][]{{asType .}}, layers) for i := range retVal { retVal[i] = make([][]{{asType .}}, rows) for j := range retVal[i] { start := i*layerStride + j*rowStride hdr := &reflect.SliceHeader{ Data: uintptr(unsafe.Pointer(&data[start])), Len: cols, Cap: cols, } retVal[i][j] = *(*[]{{asType .}})(unsafe.Pointer(hdr)) } } return } ` const nativeIterTestRaw = `func Test_Vector{{short .}}(t *testing.T) { assert := assert.New(t) var T *Dense {{if isRangeable . -}} T = New(WithBacking(Range({{reflectKind .}}, 0, 6)), WithShape(6)) {{else -}} T = New(Of({{reflectKind .}}), WithShape(6)) {{end -}} it, err := Vector{{short .}}(T) if err != nil { t.Fatal(err) } assert.Equal(6, len(it)) } func Test_Matrix{{short .}}(t *testing.T) { assert := assert.New(t) var T *Dense {{if isRangeable . -}} T = New(WithBacking(Range({{reflectKind .}}, 0, 6)), WithShape(2, 3)) {{else -}} T = New(Of({{reflectKind .}}), WithShape(2, 3)) {{end -}} it, err := Matrix{{short .}}(T) if err != nil { t.Fatal(err) } assert.Equal(2, len(it)) assert.Equal(3, len(it[0])) } func Test_Tensor3{{short .}}(t *testing.T) { assert := assert.New(t) var T *Dense {{if isRangeable . -}} T = New(WithBacking(Range({{reflectKind .}}, 0, 24)), WithShape(2, 3, 4)) {{else -}} T = New(Of({{reflectKind .}}), WithShape(2, 3, 4)) {{end -}} it, err := Tensor3{{short .}}(T) if err != nil { t.Fatal(err) } assert.Equal(2, len(it)) assert.Equal(3, len(it[0])) assert.Equal(4, len(it[0][0])) } ` var ( NativeIter *template.Template NativeIterTest *template.Template ) func init() { NativeIter = template.Must(template.New("NativeIter").Funcs(funcs).Parse(nativeIterRaw)) NativeIterTest = template.Must(template.New("NativeIterTest").Funcs(funcs).Parse(nativeIterTestRaw)) } func generateNativeIterators(f io.Writer, ak Kinds) { fmt.Fprintf(f, importUnqualifiedTensor) fmt.Fprintf(f, "%v\n", checkNativeiterable) ks := filter(ak.Kinds, isSpecialized) for _, k := range ks { fmt.Fprintf(f, "/* Native Iterables for %v */\n\n", k) NativeIter.Execute(f, k) fmt.Fprint(f, "\n\n") } } func generateNativeIteratorTests(f io.Writer, ak Kinds) { fmt.Fprintf(f, importUnqualifiedTensor) ks := filter(ak.Kinds, isSpecialized) for _, k := range ks { NativeIterTest.Execute(f, k) fmt.Fprint(f, "\n\n") } }
genlib2/native_iterator.go
0.667364
0.487185
native_iterator.go
starcoder
package gJson import ( "encoding/json" "reflect" "strconv" "unicode/utf8" ) // EncodeKeyVal writes the provide key/value to the encoder, with a leading // comma if `isFirst` is `false`. // The pair is not written if `canElide` is `true` and the value provided is a // zero value, is a JSONEncoder that did returned `false`, or a `Marshaler` that // panic'd or did not write anything. func (e *Encoder) EncodeKeyVal(k string, v interface{}, isFirst, canElide bool) bool { var pos = e.b.Len() // fmt.Printf("Encoding: %s, %#v\n\n", k, v) if !isFirst { e.writeByte(',') } e.EncodeString(k, false) e.writeByte(':') if e.Encode(v, canElide) == false { e.b.Truncate(pos) return false } return true } func (e *Encoder) Encode(data interface{}, canElide bool) bool { if data == nil { return e.EncodeNull(canElide) } switch d := data.(type) { case string: return e.EncodeString(d, canElide) case bool: return e.EncodeBool(d, canElide) case int: return e.EncodeInt(int64(d), canElide) case int64: return e.EncodeInt(int64(d), canElide) case int32: return e.EncodeInt(int64(d), canElide) case int16: return e.EncodeInt(int64(d), canElide) case int8: return e.EncodeInt(int64(d), canElide) case uint: return e.EncodeUint(uint64(d), canElide) case uint64: return e.EncodeUint(uint64(d), canElide) case uint32: return e.EncodeUint(uint64(d), canElide) case uint16: return e.EncodeUint(uint64(d), canElide) case uint8: return e.EncodeUint(uint64(d), canElide) case float32: return e.EncodeFloat32(d, canElide) case float64: return e.EncodeFloat64(d, canElide) default: v := reflect.ValueOf(data) kind := v.Kind() if canElide { if de, ok := data.(Zeroable); ok && de.IsZero() { return false } switch kind { case reflect.Array, reflect.Slice, reflect.Map: if v.Len() == 0 { return false } case reflect.Interface, reflect.Ptr: if v.IsNil() { return false } } if v.CanAddr() { if de, ok := v.Addr().Interface().(Zeroable); ok && de.IsZero() { return false } } } if je, ok := data.(JSONEncodable); ok { if je.JSONEncode(e) { return true } return e.EncodeNull(canElide) } switch kind { case reflect.Slice, reflect.Array: return e.EncodeArray(data, canElide) } } return e.marshalFallback(data, canElide) } func (e *Encoder) marshalFallback(d interface{}, canElide bool) bool { // fmt.Printf("Marshal fallback on: %#v\n\n", d) if b, err := json.Marshal(d); err == nil && len(b) > 0 { e.write(b) return true } return e.EncodeNull(canElide) } func (e *Encoder) EncodeNull(canElide bool) bool { if canElide { return false } e.writeString("null") return true } /* func (e *Encoder) EncodeStruct(s interface{}, canElide bool) bool { } */ func (e *Encoder) EncodeArray(s interface{}, canElide bool) bool { v := reflect.ValueOf(s) switch v.Kind() { case reflect.Slice, reflect.Array: default: // Can't be encoded as an Array return false } ln := v.Len() if canElide && ln == 0 { return false } e.WriteRawByte('[') for i := 0; i < ln; i += 1 { if i != 0 { e.WriteRawByte(',') } item := v.Index(i) if item.IsNil() { e.EncodeNull(false) continue } itf := item.Interface() if enc, ok := itf.(JSONEncodable); ok { if !enc.JSONEncode(e) { e.EncodeNull(false) } } else { e.Encode(itf, false) } } e.WriteRawByte(']') return true } func (e *Encoder) EncodeBool(b bool, canElide bool) bool { if b { e.writeString("true") } else { if canElide { return false } e.writeString("false") } return true } func (e *Encoder) EncodeInt(i int64, canElide bool) bool { if i < 0 { e.writeByte('-') return e.EncodeUint(uint64(-i), canElide) } return e.EncodeUint(uint64(i), canElide) } func (e *Encoder) EncodeUint(i uint64, canElide bool) bool { if canElide && i == 0 { return false } if i < 10 { e.writeByte(byte(i) | 48) return true } var start = e.b.Len() for i != 0 { e.writeByte(byte(i%10) | 48) i = i / 10 } var end = e.b.Len() - 1 var b = e.b.Bytes() for start < end { b[start], b[end] = b[end], b[start] start = start + 1 end = end - 1 } return true } func (e *Encoder) EncodeFloat32(f float32, canElide bool) bool { if canElide && f == 0 { return false } e.writeString(strconv.FormatFloat(float64(f), 'g', -1, 32)) return true } func (e *Encoder) EncodeFloat64(f float64, canElide bool) bool { if canElide && f == 0 { return false } e.writeString(strconv.FormatFloat(f, 'g', -1, 64)) return true } func (e *Encoder) EncodeString(s string, canElide bool) bool { if canElide && s == "" { return false } e.writeByte('"') i, start := 0, 0 var c byte for i < len(s) { if c = s[i]; c < utf8.RuneSelf { // Single-byte characters if escCheck[c] == 1 { // No escape i = i + 1 } else { // Needs escape if start < i { e.writeString(s[start:i]) } if c < 0x20 { e.writeString(escapedCtrl[c]) } else { e.writeString(escaped[c]) } i = i + 1 start = i } } else { // Multi-byte characters r, size := utf8.DecodeRuneInString(s[i:]) if r == utf8.RuneError { if start < i { e.writeString(s[start:i]) } e.writeString(_REPLACEMENT) i = i + 1 start = i } else if r == '\u2028' || r == '\u2029' { // These fail in JSONP; http://stackoverflow.com/a/9168133/1106925 if start < i { e.writeString(s[start:i]) } e.writeString(escaped[byte(r&0xFF)]) i = i + size start = i } else { i = i + size } } } e.writeString(s[start:]) e.writeByte('"') return true } const _REPLACEMENT = `\ufffd` var escCheck = [0x80]byte{ // 0-31 (< 0x20) 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 32-33 (OK) 1, 1, // 34 ('"') 0, // 35-37 (OK) 1, 1, 1, // 38 ('&') 0, // 39-59 (OK) 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 60 ('<') 0, // 61 (OK) 1, // 62 ('>') 0, // 63-91 (OK) 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 92 ('\\') 0, // 93-127 (OK) 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, } var escapedCtrl = [0x20]string{ `\u0000`, `\u0001`, `\u0002`, `\u0003`, `\u0004`, `\u0005`, `\u0006`, `\u0007`, `\b`, `\t`, `\n`, `\u0011`, `\f`, `\r`, `\u0014`, `\u0015`, `\u0016`, `\u0017`, `\u0018`, `\u0019`, `\u0020`, `\u0021`, `\u0022`, `\u0023`, `\u0024`, `\u0025`, `\u0026`, `\u0027`, `\u0028`, `\u0029`, `\u0030`, `\u0031`, } var escaped = map[byte]string{ 0x28: `\u2028`, 0x29: `\u2029`, '"': `\"`, // \u0034 '<': `\u0060`, '>': `\u0062`, '\\': `\\`, // \u0092 }
gJson/primitives.go
0.64579
0.433862
primitives.go
starcoder
package iso20022 // Account between an investor(s) and a fund manager or a fund. The account can contain holdings in any investment fund or investment fund class managed (or distributed) by the fund manager, within the same fund family. type InvestmentAccount21 struct { // Unique and unambiguous identification for the account between the account owner and the account servicer. AccountIdentification *AccountIdentification1 `xml:"AcctId"` // Name of the account. It provides an additional means of identification, and is designated by the account servicer in agreement with the account owner. AccountName *Max35Text `xml:"AcctNm,omitempty"` // Supplementary registration information applying to a specific block of units for dealing and reporting purposes. The supplementary registration information may be used when all the units are registered, for example, to a funds supermarket, but holdings for each investor have to reconciled individually. AccountDesignation *Max35Text `xml:"AcctDsgnt,omitempty"` // Party that legally owns the account. OwnerIdentification []*PartyIdentification2Choice `xml:"OwnrId,omitempty"` // Party that manages the account on behalf of the account owner, that is manages the registration and booking of entries on the account, calculates balances on the account and provides information about the account. AccountServicer *PartyIdentification2Choice `xml:"AcctSvcr,omitempty"` // Counterparties eligibility as defined by article 24 of the EU MiFID Directive applicable to transactions executed by investment firms for eligible counterparties. OrderOriginatorEligibility *OrderOriginatorEligibility1Code `xml:"OrdrOrgtrElgblty,omitempty"` // Sub-accounts that are grouped in a master or omnibus account. SubAccountDetails *SubAccount1 `xml:"SubAcctDtls,omitempty"` } func (i *InvestmentAccount21) AddAccountIdentification() *AccountIdentification1 { i.AccountIdentification = new(AccountIdentification1) return i.AccountIdentification } func (i *InvestmentAccount21) SetAccountName(value string) { i.AccountName = (*Max35Text)(&value) } func (i *InvestmentAccount21) SetAccountDesignation(value string) { i.AccountDesignation = (*Max35Text)(&value) } func (i *InvestmentAccount21) AddOwnerIdentification() *PartyIdentification2Choice { newValue := new (PartyIdentification2Choice) i.OwnerIdentification = append(i.OwnerIdentification, newValue) return newValue } func (i *InvestmentAccount21) AddAccountServicer() *PartyIdentification2Choice { i.AccountServicer = new(PartyIdentification2Choice) return i.AccountServicer } func (i *InvestmentAccount21) SetOrderOriginatorEligibility(value string) { i.OrderOriginatorEligibility = (*OrderOriginatorEligibility1Code)(&value) } func (i *InvestmentAccount21) AddSubAccountDetails() *SubAccount1 { i.SubAccountDetails = new(SubAccount1) return i.SubAccountDetails }
InvestmentAccount21.go
0.713631
0.440229
InvestmentAccount21.go
starcoder
// Package consumer contains interfaces that receive and process consumerdata. package consumer import ( "context" "github.com/open-telemetry/opentelemetry-collector/internal/data" "github.com/open-telemetry/opentelemetry-collector/translator/internaldata" ) // NewInternalToOCTraceConverter creates new internalToOCTraceConverter that takes TraceConsumer and // implements ConsumeTrace interface. func NewInternalToOCTraceConverter(tc TraceConsumer) TraceConsumerV2 { return &internalToOCTraceConverter{tc} } // internalToOCTraceConverter is a internal to oc translation shim that takes TraceConsumer and // implements ConsumeTrace interface. type internalToOCTraceConverter struct { traceConsumer TraceConsumer } // ConsumeTrace takes new-style data.TraceData method, converts it to OC and uses old-style ConsumeTraceData method // to process the trace data. func (tc *internalToOCTraceConverter) ConsumeTrace(ctx context.Context, td data.TraceData) error { ocTraces := internaldata.TraceDataToOC(td) for i := range ocTraces { err := tc.traceConsumer.ConsumeTraceData(ctx, ocTraces[i]) if err != nil { return err } } return nil } var _ TraceConsumerV2 = (*internalToOCTraceConverter)(nil) // NewInternalToOCMetricsConverter creates new internalToOCMetricsConverter that takes MetricsConsumer and // implements ConsumeTrace interface. func NewInternalToOCMetricsConverter(tc MetricsConsumer) MetricsConsumerV2 { return &internalToOCMetricsConverter{tc} } // internalToOCMetricsConverter is a internal to oc translation shim that takes MetricsConsumer and // implements ConsumeMetrics interface. type internalToOCMetricsConverter struct { metricsConsumer MetricsConsumer } // ConsumeMetrics takes new-style data.MetricData method, converts it to OC and uses old-style ConsumeMetricsData method // to process the metrics data. func (tc *internalToOCMetricsConverter) ConsumeMetrics(ctx context.Context, td data.MetricData) error { ocMetrics := internaldata.MetricDataToOC(td) for i := range ocMetrics { err := tc.metricsConsumer.ConsumeMetricsData(ctx, ocMetrics[i]) if err != nil { return err } } return nil } var _ MetricsConsumerV2 = (*internalToOCMetricsConverter)(nil)
consumer/converter.go
0.664867
0.40751
converter.go
starcoder
RISC-V CPU Emulation Notes: We use uint64 for integer registers. The upper 32-bits is ignored for xlen == 32. For RV32e (16 integer registers) an out of range register (>=16) will generate an exception. We use uint64 for float registers. For CPUs that have only 32-bit float support the upper 32-bits are ignored. For CPUs that have 32/64-bit float support the full 64-bits is used. A 32-bit value written to the float register will set the upper 32-bits to all ones for NaN boxing. */ //----------------------------------------------------------------------------- package rv import ( "math" "sync" "github.com/deadsy/riscv/csr" "github.com/deadsy/riscv/mem" ) //----------------------------------------------------------------------------- // rv32i func emu_LUI(m *RV, ins uint) error { imm, rd := decodeU(ins) m.wrX(rd, uint64(imm<<12)) m.PC += 4 return nil } func emu_AUIPC(m *RV, ins uint) error { imm, rd := decodeU(ins) m.wrX(rd, uint64(int(m.PC)+(imm<<12))) m.PC += 4 return nil } func emu_JAL(m *RV, ins uint) error { imm, rd := decodeJ(ins) m.wrX(rd, m.PC+4) m.PC = uint64(int(m.PC) + int(imm)) return nil } func emu_JALR(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) t := m.PC + 4 m.PC = uint64((int(m.rdX(rs1)) + imm) & ^1) m.wrX(rd, t) return nil } func emu_BEQ(m *RV, ins uint) error { imm, rs2, rs1 := decodeB(ins) if m.rdX(rs1) == m.rdX(rs2) { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 4 } return nil } func emu_BNE(m *RV, ins uint) error { imm, rs2, rs1 := decodeB(ins) if m.rdX(rs1) != m.rdX(rs2) { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 4 } return nil } func emu_BLT(m *RV, ins uint) error { imm, rs2, rs1 := decodeB(ins) var lt bool if m.xlen == 32 { lt = int32(m.rdX(rs1)) < int32(m.rdX(rs2)) } else { lt = int64(m.rdX(rs1)) < int64(m.rdX(rs2)) } if lt { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 4 } return nil } func emu_BGE(m *RV, ins uint) error { imm, rs2, rs1 := decodeB(ins) var ge bool if m.xlen == 32 { ge = int32(m.rdX(rs1)) >= int32(m.rdX(rs2)) } else { ge = int64(m.rdX(rs1)) >= int64(m.rdX(rs2)) } if ge { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 4 } return nil } func emu_BLTU(m *RV, ins uint) error { imm, rs2, rs1 := decodeB(ins) if m.rdX(rs1) < m.rdX(rs2) { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 4 } return nil } func emu_BGEU(m *RV, ins uint) error { imm, rs2, rs1 := decodeB(ins) if m.rdX(rs1) >= m.rdX(rs2) { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 4 } return nil } func emu_LB(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) val, err := m.Mem.Rd8(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int8(val))) m.PC += 4 return nil } func emu_LH(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) val, err := m.Mem.Rd16(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int16(val))) m.PC += 4 return nil } func emu_LW(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) val, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(val))) m.PC += 4 return nil } func emu_LBU(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) val, err := m.Mem.Rd8(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(val)) m.PC += 4 return nil } func emu_LHU(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) val, err := m.Mem.Rd16(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(val)) m.PC += 4 return nil } func emu_SB(m *RV, ins uint) error { imm, rs2, rs1 := decodeS(ins) adr := uint(int(m.rdX(rs1)) + imm) err := m.Mem.Wr8(adr, uint8(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.PC += 4 return nil } func emu_SH(m *RV, ins uint) error { imm, rs2, rs1 := decodeS(ins) adr := uint(int(m.rdX(rs1)) + imm) err := m.Mem.Wr16(adr, uint16(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.PC += 4 return nil } func emu_SW(m *RV, ins uint) error { imm, rs2, rs1 := decodeS(ins) adr := uint(int(m.rdX(rs1)) + imm) err := m.Mem.Wr32(adr, uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.PC += 4 return nil } func emu_ADDI(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) m.wrX(rd, uint64(int(m.rdX(rs1))+imm)) m.PC += 4 return nil } func emu_SLTI(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) var lt bool if m.xlen == 32 { lt = int32(m.rdX(rs1)) < int32(imm) } else { lt = int64(m.rdX(rs1)) < int64(imm) } var result uint64 if lt { result = 1 } m.wrX(rd, result) m.PC += 4 return nil } func emu_SLTIU(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) var lt bool if m.xlen == 32 { lt = uint32(m.rdX(rs1)) < uint32(imm) } else { lt = m.rdX(rs1) < uint64(imm) } var result uint64 if lt { result = 1 } m.wrX(rd, result) m.PC += 4 return nil } func emu_XORI(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) m.wrX(rd, m.rdX(rs1)^uint64(imm)) m.PC += 4 return nil } func emu_ORI(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) m.wrX(rd, m.rdX(rs1)|uint64(imm)) m.PC += 4 return nil } func emu_ANDI(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) m.wrX(rd, m.rdX(rs1)&uint64(imm)) m.PC += 4 return nil } // rv32i/rv64i func emu_SLLI(m *RV, ins uint) error { shamt, rs1, rd := decodeIc(ins) if m.xlen == 32 && shamt > 31 { return m.errIllegal(ins) } m.wrX(rd, m.rdX(rs1)<<shamt) m.PC += 4 return nil } // rv32i/rv64i func emu_SRLI(m *RV, ins uint) error { shamt, rs1, rd := decodeIc(ins) if m.xlen == 32 && shamt > 31 { return m.errIllegal(ins) } m.wrX(rd, m.rdX(rs1)>>shamt) m.PC += 4 return nil } // rv32i/rv64i func emu_SRAI(m *RV, ins uint) error { shamt, rs1, rd := decodeIc(ins) if m.xlen == 32 && shamt > 31 { return m.errIllegal(ins) } if m.xlen == 32 { m.wrX(rd, uint64(int32(m.rdX(rs1))>>shamt)) } else { m.wrX(rd, uint64(int64(m.rdX(rs1))>>shamt)) } m.PC += 4 return nil } func emu_ADD(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, m.rdX(rs1)+m.rdX(rs2)) m.PC += 4 return nil } func emu_SUB(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, m.rdX(rs1)-m.rdX(rs2)) m.PC += 4 return nil } func emu_SLL(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var shamt uint64 if m.xlen == 32 { shamt = m.rdX(rs2) & 31 } else { shamt = m.rdX(rs2) & 63 } m.wrX(rd, m.rdX(rs1)<<shamt) m.PC += 4 return nil } func emu_SLT(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var lt bool if m.xlen == 32 { lt = int32(m.rdX(rs1)) < int32(m.rdX(rs2)) } else { lt = int64(m.rdX(rs1)) < int64(m.rdX(rs2)) } var result uint64 if lt { result = 1 } m.wrX(rd, result) m.PC += 4 return nil } func emu_SLTU(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var result uint64 if m.rdX(rs1) < m.rdX(rs2) { result = 1 } m.wrX(rd, result) m.PC += 4 return nil } func emu_XOR(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, m.rdX(rs1)^m.rdX(rs2)) m.PC += 4 return nil } func emu_SRL(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) shamt := m.rdX(rs2) & 63 m.wrX(rd, m.rdX(rs1)>>shamt) m.PC += 4 return nil } func emu_SRA(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var x uint64 if m.xlen == 32 { shamt := m.rdX(rs2) & 31 x = uint64(int32(m.rdX(rs1)) >> shamt) } else { shamt := m.rdX(rs2) & 63 x = uint64(int64(m.rdX(rs1)) >> shamt) } m.wrX(rd, x) m.PC += 4 return nil } func emu_OR(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, m.rdX(rs1)|m.rdX(rs2)) m.PC += 4 return nil } func emu_AND(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, m.rdX(rs1)&m.rdX(rs2)) m.PC += 4 return nil } func emu_FENCE(m *RV, ins uint) error { // no-op for a sw emulator m.PC += 4 return nil } func emu_FENCE_I(m *RV, ins uint) error { // no-op for a sw emulator m.PC += 4 return nil } func emu_ECALL(m *RV, ins uint) error { m.PC = m.CSR.ECALL(m.PC, 0) return nil } func emu_EBREAK(m *RV, ins uint) error { m.PC = m.CSR.Exception(m.PC, uint(csr.ExBreakpoint), uint(m.PC), false) return nil } func emu_CSRRW(m *RV, ins uint) error { csr, rs1, rd := decodeIb(ins) var t uint64 var err error if rd != 0 { t, err = m.CSR.Rd(csr) if err != nil { return m.errCSR(err, ins) } } err = m.CSR.Wr(csr, m.rdX(rs1)) if err != nil { return m.errCSR(err, ins) } m.wrX(rd, t) m.PC += 4 return nil } func emu_CSRRS(m *RV, ins uint) error { csr, rs1, rd := decodeIb(ins) t, err := m.CSR.Rd(csr) if err != nil { return m.errCSR(err, ins) } if rs1 != 0 { err := m.CSR.Wr(csr, t|m.rdX(rs1)) if err != nil { return m.errCSR(err, ins) } } m.wrX(rd, t) m.PC += 4 return nil } func emu_CSRRC(m *RV, ins uint) error { csr, rs1, rd := decodeIb(ins) t, err := m.CSR.Rd(csr) if err != nil { return m.errCSR(err, ins) } if rs1 != 0 { err := m.CSR.Wr(csr, t & ^m.rdX(rs1)) if err != nil { return m.errCSR(err, ins) } } m.wrX(rd, t) m.PC += 4 return nil } func emu_CSRRWI(m *RV, ins uint) error { csr, zimm, rd := decodeIb(ins) if rd != 0 { t, err := m.CSR.Rd(csr) if err != nil { return m.errCSR(err, ins) } m.wrX(rd, t) } err := m.CSR.Wr(csr, uint64(zimm)) if err != nil { return m.errCSR(err, ins) } m.PC += 4 return nil } func emu_CSRRSI(m *RV, ins uint) error { csr, zimm, rd := decodeIb(ins) t, err := m.CSR.Rd(csr) if err != nil { return m.errCSR(err, ins) } err = m.CSR.Wr(csr, t|uint64(zimm)) if err != nil { return m.errCSR(err, ins) } m.wrX(rd, t) m.PC += 4 return nil } func emu_CSRRCI(m *RV, ins uint) error { csr, zimm, rd := decodeIb(ins) t, err := m.CSR.Rd(csr) if err != nil { return m.errCSR(err, ins) } err = m.CSR.Wr(csr, t & ^uint64(zimm)) if err != nil { return m.errCSR(err, ins) } m.wrX(rd, t) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv32i privileged func emu_URET(m *RV, ins uint) error { m.PC = uint64(m.CSR.URET()) return nil } func emu_SRET(m *RV, ins uint) error { m.PC = uint64(m.CSR.SRET()) return nil } func emu_MRET(m *RV, ins uint) error { m.PC = uint64(m.CSR.MRET()) return nil } func emu_WFI(m *RV, ins uint) error { return m.errTodo() } func emu_SFENCE_VMA(m *RV, ins uint) error { m.PC += 4 return nil } func emu_HFENCE_BVMA(m *RV, ins uint) error { m.PC += 4 return nil } func emu_HFENCE_GVMA(m *RV, ins uint) error { m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv32m func emu_MUL(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, m.rdX(rs1)*m.rdX(rs2)) m.PC += 4 return nil } func emu_MULH(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var x uint64 if m.xlen == 32 { a := int64(int32(m.rdX(rs1))) b := int64(int32(m.rdX(rs2))) c := (a * b) >> 32 x = uint64(c) } else { x = uint64(mulhss(int64(m.rdX(rs1)), int64(m.rdX(rs2)))) } m.wrX(rd, x) m.PC += 4 return nil } func emu_MULHSU(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var x uint64 if m.xlen == 32 { a := int64(int32(m.rdX(rs1))) b := int64(m.rdX(rs2)) c := (a * b) >> 32 x = uint64(c) } else { x = uint64(mulhsu(int64(m.rdX(rs1)), m.rdX(rs2))) } m.wrX(rd, x) m.PC += 4 return nil } func emu_MULHU(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var x uint64 if m.xlen == 32 { a := uint64(m.rdX(rs1)) b := uint64(m.rdX(rs2)) c := (a * b) >> 32 x = uint64(c) } else { x = mulhuu(m.rdX(rs1), m.rdX(rs2)) } m.wrX(rd, x) m.PC += 4 return nil } func emu_DIV(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var x uint64 if m.xlen == 32 { result := int32(-1) a := int32(m.rdX(rs1)) b := int32(m.rdX(rs2)) if b != 0 { result = a / b } x = uint64(result) } else { result := int64(-1) a := int64(m.rdX(rs1)) b := int64(m.rdX(rs2)) if b != 0 { result = a / b } x = uint64(result) } m.wrX(rd, x) m.PC += 4 return nil } func emu_DIVU(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) result := uint64((1 << 64) - 1) if m.rdX(rs2) != 0 { result = m.rdX(rs1) / m.rdX(rs2) } m.wrX(rd, result) m.PC += 4 return nil } func emu_REM(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) var x uint64 if m.xlen == 32 { result := int32(m.rdX(rs1)) b := int32(m.rdX(rs2)) if b != 0 { result %= b } x = uint64(result) } else { result := int64(m.rdX(rs1)) b := int64(m.rdX(rs2)) if b != 0 { result %= b } x = uint64(result) } m.wrX(rd, x) m.PC += 4 return nil } func emu_REMU(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) result := m.rdX(rs1) if m.rdX(rs2) != 0 { result %= m.rdX(rs2) } m.wrX(rd, result) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv32a func emu_LR_W(m *RV, ins uint) error { return m.errTodo() } func emu_SC_W(m *RV, ins uint) error { return m.errTodo() /* rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) err = m.Mem.Wr32(adr, uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.amo.Unlock() m.PC += 4 return nil */ } func emu_AMOSWAP_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOADD_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, t+uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOXOR_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, t^uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOAND_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, t&uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOOR_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, t|uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMIN_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, uint32(minInt32(int32(t), int32(m.rdX(rs2))))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMAX_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, uint32(maxInt32(int32(t), int32(m.rdX(rs2))))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMINU_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, uint32(minUint32(t, uint32(m.rdX(rs2))))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMAXU_W(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr32(adr, uint32(maxUint32(t, uint32(m.rdX(rs2))))) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(t))) m.amo.Unlock() m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv32f func emu_FLW(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) x, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FSW(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } imm, rs2, rs1 := decodeS(ins) adr := uint(int(m.rdX(rs1)) + imm) err := m.Mem.Wr32(adr, m.rdFS(rs2)) if err != nil { return m.errMemory(err) } m.PC += 4 return nil } func emu_FMADD_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_s(m.rdFS(rs1), m.rdFS(rs2), m.rdFS(rs3), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FMSUB_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_s(m.rdFS(rs1), m.rdFS(rs2), neg32(m.rdFS(rs3)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FNMSUB_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_s(neg32(m.rdFS(rs1)), m.rdFS(rs2), m.rdFS(rs3), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FNMADD_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_s(neg32(m.rdFS(rs1)), m.rdFS(rs2), neg32(m.rdFS(rs3)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FADD_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fadd_s(m.rdFS(rs1), m.rdFS(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FSUB_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fsub_s(m.rdFS(rs1), m.rdFS(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FMUL_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fmul_s(m.rdFS(rs1), m.rdFS(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FDIV_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fdiv_s(m.rdFS(rs1), m.rdFS(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FSQRT_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fsqrt_s(m.rdFS(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FSGNJ_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) sign := m.rdFS(rs2) & f32SignMask m.wrFS(rd, sign|(m.rdFS(rs1)&mask30to0)) m.PC += 4 return nil } func emu_FSGNJN_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) sign := ^m.rdFS(rs2) & f32SignMask m.wrFS(rd, sign|(m.rdFS(rs1)&mask30to0)) m.PC += 4 return nil } func emu_FSGNJX_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) sign := (m.rdFS(rs1) ^ m.rdFS(rs2)) & f32SignMask m.wrFS(rd, sign|(m.rdFS(rs1)&mask30to0)) m.PC += 4 return nil } func emu_FMIN_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrFS(rd, fmin_s(m.rdFS(rs1), m.rdFS(rs2), m.CSR)) m.PC += 4 return nil } func emu_FMAX_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrFS(rd, fmax_s(m.rdFS(rs1), m.rdFS(rs2), m.CSR)) m.PC += 4 return nil } func emu_FCVT_W_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_w_s(m.rdFS(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, uint64(int64(x))) m.PC += 4 return nil } func emu_FCVT_WU_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_wu_s(m.rdFS(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, uint64(int64(int32(x)))) m.PC += 4 return nil } func emu_FMV_X_W(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(int32(m.rdFS(rs1)))) m.PC += 4 return nil } func emu_FEQ_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(feq_s(m.rdFS(rs1), m.rdFS(rs2), m.CSR))) m.PC += 4 return nil } func emu_FLT_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(flt_s(m.rdFS(rs1), m.rdFS(rs2), m.CSR))) m.PC += 4 return nil } func emu_FLE_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(fle_s(m.rdFS(rs1), m.rdFS(rs2), m.CSR))) m.PC += 4 return nil } func emu_FCLASS_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(fclass_s(m.rdFS(rs1)))) m.PC += 4 return nil } func emu_FCVT_S_W(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_s_w(int32(m.rdX(rs1)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FCVT_S_WU(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_s_wu(uint32(m.rdX(rs1)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FMV_W_X(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, _, rd := decodeR(ins) m.wrFS(rd, uint32(m.rdX(rs1))) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv32d func emu_FLD(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) x, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FSD(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } imm, rs2, rs1 := decodeS(ins) adr := uint(int(m.rdX(rs1)) + imm) err := m.Mem.Wr64(adr, m.rdFD(rs2)) if err != nil { return m.errMemory(err) } m.PC += 4 return nil } func emu_FMADD_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_d(m.rdFD(rs1), m.rdFD(rs2), m.rdFD(rs3), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FMSUB_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_d(m.rdFD(rs1), m.rdFD(rs2), neg64(m.rdFD(rs3)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FNMSUB_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_d(neg64(m.rdFD(rs1)), m.rdFD(rs2), m.rdFD(rs3), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FNMADD_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs3, rs2, rs1, rm, rd := decodeR4(ins) x, err := fmadd_d(neg64(m.rdFD(rs1)), m.rdFD(rs2), neg64(m.rdFD(rs3)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FADD_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fadd_d(m.rdFD(rs1), m.rdFD(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FSUB_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fsub_d(m.rdFD(rs1), m.rdFD(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FMUL_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fmul_d(m.rdFD(rs1), m.rdFD(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FDIV_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, rm, rd := decodeR(ins) x, err := fdiv_d(m.rdFD(rs1), m.rdFD(rs2), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FSQRT_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fsqrt_d(m.rdFD(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FSGNJ_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) sign := m.rdFD(rs2) & f64SignMask m.wrFD(rd, sign|(m.rdFD(rs1)&mask62to0)) m.PC += 4 return nil } func emu_FSGNJN_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) sign := ^m.rdFD(rs2) & f64SignMask m.wrFD(rd, sign|(m.rdFD(rs1)&mask62to0)) m.PC += 4 return nil } func emu_FSGNJX_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) sign := (m.rdFD(rs1) ^ m.rdFD(rs2)) & f64SignMask m.wrFD(rd, sign|(m.rdFD(rs1)&mask62to0)) m.PC += 4 return nil } func emu_FMIN_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrFD(rd, fmin_d(m.rdFD(rs1), m.rdFD(rs2), m.CSR)) m.PC += 4 return nil } func emu_FMAX_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrFD(rd, fmax_d(m.rdFD(rs1), m.rdFD(rs2), m.CSR)) m.PC += 4 return nil } func emu_FCVT_S_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_s_d(m.rdFD(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FCVT_D_S(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, _, rd := decodeR(ins) m.wrFD(rd, fcvt_d_s(m.rdFS(rs1), m.CSR)) m.PC += 4 return nil } func emu_FEQ_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(feq_d(m.rdFD(rs1), m.rdFD(rs2), m.CSR))) m.PC += 4 return nil } func emu_FLT_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(flt_d(m.rdFD(rs1), m.rdFD(rs2), m.CSR))) m.PC += 4 return nil } func emu_FLE_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(fle_d(m.rdFD(rs1), m.rdFD(rs2), m.CSR))) m.PC += 4 return nil } func emu_FCLASS_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(fclass_d(m.rdFD(rs1)))) m.PC += 4 return nil } func emu_FCVT_W_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_w_d(m.rdFD(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, uint64(int64(x))) m.PC += 4 return nil } func emu_FCVT_WU_D(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_wu_d(m.rdFD(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, uint64(int64(int32(x)))) m.PC += 4 return nil } func emu_FCVT_D_W(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_d_w(int32(m.rdX(rs1)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FCVT_D_WU(m *RV, ins uint) error { if m.CSR.IsFloatOff() { return m.errIllegal(ins) } _, rs1, rm, rd := decodeR(ins) x, err := fcvt_d_wu(uint32(m.rdX(rs1)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv32c func emu_C_ILLEGAL(m *RV, ins uint) error { return m.errIllegal(ins) } func emu_C_ADDI4SPN(m *RV, ins uint) error { uimm, rd := decodeCIW(ins) m.wrX(rd, m.rdX(RegSp)+uint64(uimm)) m.PC += 2 return nil } func emu_C_LW(m *RV, ins uint) error { uimm, rs1, rd := decodeCS(ins) adr := uint(m.rdX(rs1)) + uimm val, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(val))) m.PC += 2 return nil } func emu_C_SW(m *RV, ins uint) error { uimm, rs1, rs2 := decodeCS(ins) adr := uint(m.rdX(rs1)) + uimm err := m.Mem.Wr32(adr, uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.PC += 2 return nil } func emu_C_NOP(m *RV, ins uint) error { m.PC += 2 return nil } func emu_C_ADDI(m *RV, ins uint) error { imm, rd := decodeCIa(ins) if rd != 0 { m.wrX(rd, uint64(int(m.rdX(rd))+imm)) } m.PC += 2 return nil } func emu_C_LI(m *RV, ins uint) error { imm, rd := decodeCIa(ins) m.wrX(rd, uint64(imm)) m.PC += 2 return nil } func emu_C_ADDI16SP(m *RV, ins uint) error { imm := decodeCIb(ins) m.wrX(RegSp, uint64(int(m.rdX(RegSp))+imm)) m.PC += 2 return nil } func emu_C_LUI(m *RV, ins uint) error { imm, rd := decodeCIf(ins) if imm == 0 { return m.errIllegal(ins) } if rd != 0 && rd != 2 { m.wrX(rd, uint64(imm<<12)) } m.PC += 2 return nil } func emu_C_SRLI(m *RV, ins uint) error { shamt, rd := decodeCIc(ins) if m.xlen == 32 && shamt > 31 { return m.errIllegal(ins) } m.wrX(rd, m.rdX(rd)>>shamt) m.PC += 2 return nil } func emu_C_SRAI(m *RV, ins uint) error { shamt, rd := decodeCIc(ins) var x uint64 if m.xlen == 32 { if shamt > 31 { return m.errIllegal(ins) } x = uint64(int32(m.rdX(rd)) >> shamt) } else { x = uint64(int64(m.rdX(rd)) >> shamt) } m.wrX(rd, x) m.PC += 2 return nil } func emu_C_ANDI(m *RV, ins uint) error { imm, rd := decodeCIe(ins) m.wrX(rd, uint64(int(m.rdX(rd))&imm)) m.PC += 2 return nil } func emu_C_SUB(m *RV, ins uint) error { rd, rs := decodeCRa(ins) m.wrX(rd, m.rdX(rd)-m.rdX(rs)) m.PC += 2 return nil } func emu_C_XOR(m *RV, ins uint) error { rd, rs := decodeCRa(ins) m.wrX(rd, m.rdX(rd)^m.rdX(rs)) m.PC += 2 return nil } func emu_C_OR(m *RV, ins uint) error { rd, rs := decodeCRa(ins) m.wrX(rd, m.rdX(rd)|m.rdX(rs)) m.PC += 2 return nil } func emu_C_AND(m *RV, ins uint) error { rd, rs := decodeCRa(ins) m.wrX(rd, m.rdX(rd)&m.rdX(rs)) m.PC += 2 return nil } func emu_C_J(m *RV, ins uint) error { imm := decodeCJ(ins) m.PC = uint64(int(m.PC) + imm) return nil } func emu_C_BEQZ(m *RV, ins uint) error { imm, rs := decodeCB(ins) if m.rdX(rs) == 0 { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 2 } return nil } func emu_C_BNEZ(m *RV, ins uint) error { imm, rs := decodeCB(ins) if m.rdX(rs) != 0 { m.PC = uint64(int(m.PC) + imm) } else { m.PC += 2 } return nil } func emu_C_SLLI(m *RV, ins uint) error { shamt, rd := decodeCId(ins) if rd != 0 && shamt != 0 { m.wrX(rd, m.rdX(rd)<<shamt) } m.PC += 2 return nil } func emu_C_SLLI64(m *RV, ins uint) error { return m.errTodo() } func emu_C_LWSP(m *RV, ins uint) error { uimm, rd := decodeCSSa(ins) if rd == 0 { return m.errIllegal(ins) } adr := uint(m.rdX(RegSp)) + uimm val, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(int32(val))) m.PC += 2 return nil } func emu_C_JR(m *RV, ins uint) error { rs1, _ := decodeCR(ins) if rs1 == 0 { return m.errIllegal(ins) } m.PC = m.rdX(rs1) return nil } func emu_C_MV(m *RV, ins uint) error { rd, rs := decodeCR(ins) if rs != 0 { m.wrX(rd, m.rdX(rs)) } m.PC += 2 return nil } func emu_C_EBREAK(m *RV, ins uint) error { m.PC = m.CSR.Exception(m.PC, uint(csr.ExBreakpoint), uint(m.PC), false) return nil } func emu_C_JALR(m *RV, ins uint) error { rs1, _ := decodeCR(ins) if rs1 == 0 { return m.errIllegal(ins) } t := m.PC + 2 m.PC = m.rdX(rs1) m.wrX(RegRa, t) return nil } func emu_C_ADD(m *RV, ins uint) error { rd, rs := decodeCR(ins) m.wrX(rd, m.rdX(rd)+m.rdX(rs)) m.PC += 2 return nil } func emu_C_SWSP(m *RV, ins uint) error { uimm, rs2 := decodeCSSb(ins) adr := uint(m.rdX(RegSp)) + uimm err := m.Mem.Wr32(adr, uint32(m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.PC += 2 return nil } //----------------------------------------------------------------------------- // rv32c-only func emu_C_JAL(m *RV, ins uint) error { imm := decodeCJ(ins) m.wrX(RegRa, m.PC+2) m.PC = uint64(int(m.PC) + imm) return nil } //----------------------------------------------------------------------------- // rv32fc func emu_C_FLW(m *RV, ins uint) error { return m.errTodo() } func emu_C_FLWSP(m *RV, ins uint) error { return m.errTodo() } func emu_C_FSW(m *RV, ins uint) error { return m.errTodo() } func emu_C_FSWSP(m *RV, ins uint) error { return m.errTodo() } //----------------------------------------------------------------------------- // rv32dc func emu_C_FLD(m *RV, ins uint) error { return m.errTodo() } func emu_C_FLDSP(m *RV, ins uint) error { return m.errTodo() } func emu_C_FSD(m *RV, ins uint) error { return m.errTodo() } func emu_C_FSDSP(m *RV, ins uint) error { return m.errTodo() } //----------------------------------------------------------------------------- // rv64i func emu_LWU(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) val, err := m.Mem.Rd32(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, uint64(val)) m.PC += 4 return nil } func emu_LD(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) adr := uint(int(m.rdX(rs1)) + imm) val, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, val) m.PC += 4 return nil } func emu_SD(m *RV, ins uint) error { imm, rs2, rs1 := decodeS(ins) adr := uint(int(m.rdX(rs1)) + imm) err := m.Mem.Wr64(adr, m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.PC += 4 return nil } func emu_ADDIW(m *RV, ins uint) error { imm, rs1, rd := decodeIa(ins) m.wrX(rd, uint64(int32(int(m.rdX(rs1))+imm))) m.PC += 4 return nil } func emu_SLLIW(m *RV, ins uint) error { shamt, rs1, rd := decodeIc(ins) if shamt&32 != 0 { return m.errIllegal(ins) } m.wrX(rd, uint64(int32(m.rdX(rs1))<<shamt)) m.PC += 4 return nil } func emu_SRLIW(m *RV, ins uint) error { shamt, rs1, rd := decodeIc(ins) if shamt&32 != 0 { return m.errIllegal(ins) } m.wrX(rd, uint64(int32(uint32(m.rdX(rs1))>>shamt))) m.PC += 4 return nil } func emu_SRAIW(m *RV, ins uint) error { shamt, rs1, rd := decodeIc(ins) if shamt&32 != 0 { return m.errIllegal(ins) } m.wrX(rd, uint64(int32(m.rdX(rs1))>>shamt)) m.PC += 4 return nil } func emu_ADDW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(int32(m.rdX(rs1)+m.rdX(rs2)))) m.PC += 4 return nil } func emu_SUBW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.wrX(rd, uint64(int32(m.rdX(rs1)-m.rdX(rs2)))) m.PC += 4 return nil } func emu_SLLW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) shamt := m.rdX(rs2) & 31 m.wrX(rd, uint64(int32(m.rdX(rs1)<<shamt))) m.PC += 4 return nil } func emu_SRLW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) shamt := m.rdX(rs2) & 31 m.wrX(rd, uint64(int32(uint32(m.rdX(rs1))>>shamt))) m.PC += 4 return nil } func emu_SRAW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) shamt := m.rdX(rs2) & 31 m.wrX(rd, uint64(int32(m.rdX(rs1))>>shamt)) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv64m func emu_MULW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) result := int32(m.rdX(rs1) * m.rdX(rs2)) m.wrX(rd, uint64(result)) m.PC += 4 return nil } func emu_DIVW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) result := int32(m.rdX(rs1)) divisor := int32(m.rdX(rs2)) if divisor == -1 && result == math.MinInt32 { // overflow } else if divisor == 0 { result = -1 } else { result /= divisor } m.wrX(rd, uint64(result)) m.PC += 4 return nil } func emu_DIVUW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) dividend := uint32(m.rdX(rs1)) divisor := uint32(m.rdX(rs2)) result := int32(-1) if divisor != 0 { result = int32(dividend / divisor) } m.wrX(rd, uint64(result)) m.PC += 4 return nil } func emu_REMW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) result := int32(m.rdX(rs1)) divisor := int32(m.rdX(rs2)) if divisor == -1 && result == math.MinInt32 { // overflow result = 0 } else if divisor == 0 { // nop } else { result %= divisor } m.wrX(rd, uint64(result)) m.PC += 4 return nil } func emu_REMUW(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) dividend := uint32(m.rdX(rs1)) divisor := uint32(m.rdX(rs2)) result := int32(dividend) if divisor != 0 { result = int32(dividend % divisor) } m.wrX(rd, uint64(result)) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv64a func emu_LR_D(m *RV, ins uint) error { return m.errTodo() } func emu_SC_D(m *RV, ins uint) error { return m.errTodo() } func emu_AMOSWAP_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOADD_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, t+m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOXOR_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, t^m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOAND_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, t&m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOOR_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, t|m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMIN_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, uint64(minInt64(int64(t), int64(m.rdX(rs2))))) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMAX_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, uint64(maxInt64(int64(t), int64(m.rdX(rs2))))) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMINU_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, minUint64(t, m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } func emu_AMOMAXU_D(m *RV, ins uint) error { rs2, rs1, _, rd := decodeR(ins) m.amo.Lock() adr := uint(m.rdX(rs1)) t, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } err = m.Mem.Wr64(adr, maxUint64(t, m.rdX(rs2))) if err != nil { return m.errMemory(err) } m.wrX(rd, t) m.amo.Unlock() m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv64f func emu_FCVT_L_S(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_l_s(m.rdFS(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, uint64(x)) m.PC += 4 return nil } func emu_FCVT_LU_S(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_lu_s(m.rdFS(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, x) m.PC += 4 return nil } func emu_FCVT_S_L(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_s_l(int64(m.rdX(rs1)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } func emu_FCVT_S_LU(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_s_lu(m.rdX(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFS(rd, x) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv64d func emu_FCVT_L_D(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_l_d(m.rdFD(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, uint64(x)) m.PC += 4 return nil } func emu_FCVT_LU_D(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_lu_d(m.rdFD(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrX(rd, x) m.PC += 4 return nil } func emu_FMV_X_D(m *RV, ins uint) error { _, rs1, _, rd := decodeR(ins) m.wrX(rd, m.rdFD(rs1)) m.PC += 4 return nil } func emu_FCVT_D_L(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_d_l(int64(m.rdX(rs1)), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FCVT_D_LU(m *RV, ins uint) error { _, rs1, rm, rd := decodeR(ins) x, err := fcvt_d_lu(m.rdX(rs1), rm, m.CSR) if err != nil { return m.errIllegal(ins) } m.wrFD(rd, x) m.PC += 4 return nil } func emu_FMV_D_X(m *RV, ins uint) error { _, rs1, _, rd := decodeR(ins) m.wrFD(rd, m.rdX(rs1)) m.PC += 4 return nil } //----------------------------------------------------------------------------- // rv64c func emu_C_ADDIW(m *RV, ins uint) error { imm, rd := decodeCIa(ins) if rd != 0 { m.wrX(rd, uint64(int32(int(m.rdX(rd))+imm))) } else { return m.errIllegal(ins) } m.PC += 2 return nil } func emu_C_LDSP(m *RV, ins uint) error { uimm, rd := decodeCIg(ins) adr := uint(m.rdX(RegSp)) + uimm val, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } if rd != 0 { m.wrX(rd, val) } else { return m.errIllegal(ins) } m.PC += 2 return nil } func emu_C_SDSP(m *RV, ins uint) error { uimm, rs2 := decodeCSSc(ins) adr := uint(m.rdX(RegSp)) + uimm err := m.Mem.Wr64(adr, m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.PC += 2 return nil } func emu_C_LD(m *RV, ins uint) error { uimm, rs1, rd := decodeCSa(ins) adr := uint(m.rdX(rs1)) + uimm val, err := m.Mem.Rd64(adr) if err != nil { return m.errMemory(err) } m.wrX(rd, val) m.PC += 2 return nil } func emu_C_SD(m *RV, ins uint) error { uimm, rs1, rs2 := decodeCSa(ins) adr := uint(m.rdX(rs1)) + uimm err := m.Mem.Wr64(adr, m.rdX(rs2)) if err != nil { return m.errMemory(err) } m.PC += 2 return nil } func emu_C_SUBW(m *RV, ins uint) error { return m.errTodo() } func emu_C_ADDW(m *RV, ins uint) error { return m.errTodo() } //----------------------------------------------------------------------------- // Integer Register Access // wrX writes an integer register func (m *RV) wrX(i uint, val uint64) { if i == 0 { // no writes to zero return } if m.xlen == 32 { val = uint64(uint32(val)) } m.x[i] = val } // rdX reads an integer register func (m *RV) rdX(i uint) uint64 { if i == 0 { // always reads as zero return 0 } if m.xlen == 32 { return uint64(uint32(m.x[i])) } return m.x[i] } //----------------------------------------------------------------------------- // Float Register Access // wrFS writes a 32-bit float register. func (m *RV) wrFS(i uint, val uint32) { m.f[i] = uint64(val) | upper32 } // rdFS reads a 32-bit float register. func (m *RV) rdFS(i uint) uint32 { return uint32(m.f[i]) } // wrFD writes a 64-bit float register. func (m *RV) wrFD(i uint, val uint64) { m.f[i] = val } // rdFD reads a 64-bit float register. func (m *RV) rdFD(i uint) uint64 { return m.f[i] } //----------------------------------------------------------------------------- func maxInt32(a, b int32) int32 { if a > b { return a } return b } func minInt32(a, b int32) int32 { if a < b { return a } return b } func maxUint32(a, b uint32) uint32 { if a > b { return a } return b } func minUint32(a, b uint32) uint32 { if a < b { return a } return b } func maxInt64(a, b int64) int64 { if a > b { return a } return b } func minInt64(a, b int64) int64 { if a < b { return a } return b } func maxUint64(a, b uint64) uint64 { if a > b { return a } return b } func minUint64(a, b uint64) uint64 { if a < b { return a } return b } //----------------------------------------------------------------------------- // RV is a RISC-V CPU. type RV struct { x [32]uint64 // integer registers f [32]uint64 // float registers PC uint64 // program counter isa *ISA // ISA implemented for the CPU Mem *mem.Memory // memory of the target system CSR *csr.State // CSR state amo sync.Mutex // lock for atomic operations lastPC uint64 // stuck PC detection xlen uint // bit length of integer registers err *errBuffer // buffer of handled/un-handled emulation errors } // Reset the CPU. func (m *RV) Reset() { m.PC = m.Mem.Entry m.CSR.Reset() m.err.reset() m.lastPC = 0 } // NewRV64 returns a 64-bit RISC-V CPU. func NewRV64(isa *ISA, mem *mem.Memory, csr *csr.State) *RV { m := RV{ xlen: 64, isa: isa, Mem: mem, CSR: csr, err: newErrBuffer(32), } m.Reset() return &m } // NewRV32 returns a 32-bit RISC-V CPU. func NewRV32(isa *ISA, mem *mem.Memory, csr *csr.State) *RV { m := RV{ xlen: 32, isa: isa, Mem: mem, CSR: csr, err: newErrBuffer(32), } m.Reset() return &m } //----------------------------------------------------------------------------- func (m *RV) errHandler(err error) error { e := err.(*Error) // record the error m.err.write(e) // handle the error switch e.Type { case ErrIllegal, ErrCSR: m.PC = m.CSR.Exception(m.PC, uint(csr.ExInsIllegal), e.ins, false) return nil case ErrMemory: em := e.err.(*mem.Error) if em.Type&(mem.ErrBreak|mem.ErrEmpty) == 0 { m.PC = m.CSR.Exception(m.PC, uint(em.Ex), em.Addr, false) return nil } } return err } //----------------------------------------------------------------------------- // Run the CPU for a single instruction. func (m *RV) Run() error { // read the next instruction ins, err := m.Mem.RdIns(uint(m.PC)) if err != nil { return m.errHandler(m.errMemory(err)) } // check for break points err = m.Mem.GetBreak() if err != nil { return m.errMemory(err) } // lookup and emulate the instruction im := m.isa.lookup(ins) if im == nil { return m.errHandler(m.errIllegal(ins)) } err = im.defn.emu(m, ins) if err != nil { return m.errHandler(err) } // Update the CSR registers m.CSR.IncInstructions() m.CSR.IncClockCycles(2) // check for breaks points err = m.Mem.GetBreak() if err != nil { return m.errMemory(err) } // stuck PC detection if m.PC == m.lastPC { return m.errStuckPC() } m.lastPC = m.PC return nil } //----------------------------------------------------------------------------- // IntRegs returns a display string for the integer registers. func (m *RV) IntRegs() string { reg := make([]uint, 32) for i := range reg { reg[i] = uint(m.rdX(uint(i))) } return intRegString(reg, uint(m.PC), m.xlen) } // FloatRegs returns a display string for the float registers. func (m *RV) FloatRegs() string { return floatRegString(m.f[:]) } // Disassemble the instruction at the address. func (m *RV) Disassemble(addr uint) *Disassembly { return m.isa.Disassemble(m.Mem, addr) } //-----------------------------------------------------------------------------
rv/emu.go
0.740456
0.421373
emu.go
starcoder
package scene import ( "math" "github.com/carlosroman/aun-otra-ray-tracer/go/internal/object" "github.com/carlosroman/aun-otra-ray-tracer/go/internal/ray" ) const ( epsilon = 0.00000001 ) type Computation struct { t float64 //Intersect obj object.Object point ray.Vector overPoint ray.Vector eyev ray.Vector normalv ray.Vector reflectv ray.Vector underPoint ray.Vector inside bool n1 float64 n2 float64 } func (c Computation) Intersect() float64 { return c.t } func (c Computation) Object() object.Object { return c.obj } func (c Computation) Point() ray.Vector { return c.point } func (c Computation) Eyev() ray.Vector { return c.eyev } func (c Computation) Normalv() ray.Vector { return c.normalv } func (c Computation) Reflectv() ray.Vector { return c.reflectv } func (c Computation) Inside() bool { return c.inside } func (c Computation) OverPoint() ray.Vector { return c.overPoint } func (c Computation) UnderPoint() ray.Vector { return c.underPoint } func (c Computation) N1() float64 { return c.n1 } func (c Computation) N2() float64 { return c.n2 } func contains(objs []object.Object, obj object.Object) (found bool, idx int) { for i := range objs { if objs[i] == obj { return true, i } } return false, 0 } func PrepareComputations(i object.Intersection, r ray.Ray, xs ...object.Intersection) (comps Computation) { comps.t = i.T comps.obj = i.Obj comps.point = r.PointAt(comps.t) comps.eyev = r.Direction().Negate() comps.normalv = object.NormalAt(i, comps.point) comps.reflectv = r.Direction().Reflect(comps.normalv) if ray.Dot(comps.normalv, comps.eyev) < 0 { comps.inside = true comps.normalv = comps.normalv.Negate() } normalvMultiplyByEpsilon := comps.normalv.Multiply(epsilon) comps.overPoint = comps.point.Add(normalvMultiplyByEpsilon) comps.underPoint = comps.point.Subtract(normalvMultiplyByEpsilon) var containers []object.Object comps.n1 = 1.0 comps.n2 = 1.0 for idx := range xs { if i == xs[idx] { if len(containers) > 0 { comps.n1 = containers[len(containers)-1].Material().RefractiveIndex } } if found, at := contains(containers, xs[idx].Obj); found { containers = append(containers[:at], containers[at+1:]...) } else { containers = append(containers, xs[idx].Obj) } if i == xs[idx] { if len(containers) > 0 { comps.n2 = containers[len(containers)-1].Material().RefractiveIndex } break } } return comps } func Schlick(comps Computation) float64 { cos := ray.Dot(comps.eyev, comps.normalv) if comps.n1 > comps.n2 { n := comps.n1 / comps.n2 sin2t := math.Pow(n, 2) * (1.0 - math.Pow(cos, 2)) if sin2t > 1.0 { return 1.0 } cos = math.Sqrt(1.0 - sin2t) } r0 := math.Pow((comps.n1-comps.n2)/(comps.n1+comps.n2), 2) return r0 + (1-r0)*math.Pow(1-cos, 5) }
go/internal/scene/computation.go
0.755907
0.531453
computation.go
starcoder