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 aoc2020 /* --- Day 17: Conway Cubes --- Part 2 For some reason, your simulated results don't match what the experimental energy source engineers expected. Apparently, the pocket dimension actually has four spatial dimensions, not three. The pocket dimension contains an infinite 4-dimensional grid. At every integer 4-dimensional coordinate (x,y,z,w), there exists a single cube (really, a hypercube) which is still either active or inactive. Each cube only ever considers its neighbors: any of the 80 other cubes where any of their coordinates differ by at most 1. For example, given the cube at x=1,y=2,z=3,w=4, its neighbors include the cube at x=2,y=2,z=3,w=3, the cube at x=0,y=2,z=3,w=4, and so on. The initial state of the pocket dimension still consists of a small flat region of cubes. Furthermore, the same rules for cycle updating still apply: during each cycle, consider the number of active neighbors of each cube. For example, consider the same initial state as in the example above. Even though the pocket dimension is 4-dimensional, this initial state represents a small 2-dimensional slice of it. (In particular, this initial state defines a 3x3x1x1 region of the 4-dimensional space.) Simulating a few cycles from this initial state produces the following configurations, where the result of each cycle is shown layer-by-layer at each given z and w coordinate: */ import ( "fmt" "strconv" "strings" goutils "github.com/simonski/goutils" ) func AOC_2020_17_part2_attempt1(cli *goutils.CLI) { g := NewGrid4D(DAY_17_INPUT) g.Cycle() g.Cycle() g.Cycle() g.Cycle() g.Cycle() g.Cycle() fmt.Printf("Part 2 Active Count is %v\n", g.CountActiveTotal()) } type Grid4D struct { data map[string]string } func NewGrid4D(input string) *Grid4D { data := make(map[string]string) g := Grid4D{data: data} lines := strings.Split(input, "\n") y := 0 z := 0 w := 0 for _, line := range lines { for x, _ := range line { value := line[x : x+1] key := fmt.Sprintf("%v.%v.%v.%v", x, y, z, w) g.Set(key, string(value)) } y++ } return &g } func (g *Grid4D) Get(key string) string { result, exists := g.data[key] if exists { return result } else { return INACTIVE } } func (g *Grid4D) Set(key string, value string) { if value == INACTIVE { delete(g.data, key) } else { g.data[key] = value } } func (g *Grid4D) Neighbours(parentKey string) []string { x, y, z, w := g.ParseKey(parentKey) keys := make([]string, 0) // fmt.Printf("Neighbours of %v\n", key) for wpos := w - 1; wpos <= w+1; wpos++ { for zpos := z - 1; zpos <= z+1; zpos++ { for xpos := x - 1; xpos <= x+1; xpos++ { for ypos := y - 1; ypos <= y+1; ypos++ { if xpos == x && ypos == y && zpos == z && wpos == w { continue } key := fmt.Sprintf("%v.%v.%v.%v", xpos, ypos, zpos, wpos) keys = append(keys, key) // fmt.Printf("Neighbour of (%v) = %v\n", parentKey, key) } } } } return keys } func (g *Grid4D) ParseKey(key string) (int, int, int, int) { splits := strings.Split(key, ".") x, _ := strconv.Atoi(splits[0]) y, _ := strconv.Atoi(splits[1]) z, _ := strconv.Atoi(splits[2]) w, _ := strconv.Atoi(splits[3]) return x, y, z, w } func (g *Grid4D) CountActiveNeighbours(parentKey string) int { keys := g.Neighbours(parentKey) active := 0 for _, key := range keys { value := g.Get(key) if value == ACTIVE { active++ } } return active } func (g *Grid4D) CountActiveTotal() int { activeCount := 0 for _, value := range g.data { if value == ACTIVE { activeCount++ } } return activeCount } func (g *Grid4D) Cycle() { data := make(map[string]string) minp, maxp := g.Dimensions() for w := minp.W - 1; w <= maxp.W+1; w++ { for z := minp.Z - 1; z <= maxp.Z+1; z++ { for y := minp.Y - 1; y <= maxp.Y+1; y++ { for x := minp.X - 1; x <= maxp.X+1; x++ { key := <KEY> originalValue := g.Get(key) // fmt.Printf("Cycle(); key=%v, state=%v\n", key, originalValue) newValue := originalValue activeNeighbours := g.CountActiveNeighbours(key) if originalValue == ACTIVE { if activeNeighbours == 2 || activeNeighbours == 3 { // remain active newValue = ACTIVE } else { newValue = INACTIVE } } else if activeNeighbours == 3 { newValue = ACTIVE } else { newValue = originalValue } if newValue == ACTIVE { data[key] = newValue } } } } } g.data = data } // Dimensions returns the min/max points that exist func (g *Grid4D) Dimensions() (goutils.Point4D, goutils.Point4D) { minp := goutils.Point4D{X: 10000, Y: 10000, Z: 10000, W: 10000} maxp := goutils.Point4D{X: -10000, Y: -10000, Z: -10000, W: -10000} for key := range g.data { x, y, z, w := g.ParseKey(key) minp.X = goutils.Min(x, minp.X) maxp.X = goutils.Max(x, maxp.X) minp.Y = goutils.Min(y, minp.Y) maxp.Y = goutils.Max(y, maxp.Y) minp.Z = goutils.Min(z, minp.Z) maxp.Z = goutils.Max(z, maxp.Z) minp.W = goutils.Min(w, minp.W) maxp.W = goutils.Max(w, maxp.W) } return minp, maxp } func (g *Grid4D) DebugZ(z int) string { minp, maxp := g.Dimensions() min_x := minp.X max_x := maxp.X min_y := minp.Y max_y := maxp.Y // min_w := minp.w // max_w := maxp.w line := "" for y := min_y; y <= max_y; y++ { for x := min_x; x <= max_x; x++ { key := <KEY> value := g.Get(key) line += value } line += "\n" } return line }
app/aoc2020/aoc2020_17_part2.go
0.835215
0.819749
aoc2020_17_part2.go
starcoder
package main import ( "errors" f "fmt" "math" ) func Interfaces() { f.Println("********** Interfaces **********") r := rectangle{width: 3, height: 4} c := circle{radius: 5} t := triangle{sideA: 3, sideB: 4, sideC: 5} rImpossible := rectangle{width: 3, height: -4} cImpossible := circle{radius: -5} tImpossible := triangle{sideA: 1, sideB: 1, sideC: 100} printShape(r) printShape(c) printShape(t) printShape(rImpossible) printShape(cImpossible) printShape(tImpossible) } func printShape(s shape) { f.Println(s) f.Print("Area: ") f.Println(s.area()) f.Print("Perimeter: ") f.Println(s.perimeter()) } type shape interface { area() (float64, error) perimeter() (float64, error) valid() error } type rectangle struct { width, height float64 } type circle struct { radius float64 } type triangle struct { sideA, sideB, sideC float64 } func (r rectangle) valid() error { if r.width > 0 && r.height > 0 { return nil } return errors.New("Width and height of rectangle must be greater than 0") } func (c circle) valid() error { if c.radius > 0 { return nil } return errors.New("Radius of circle must be greater than 0") } func (t triangle) valid() error { p := (t.sideA + t.sideB + t.sideC) / 2.0 if p > t.sideA && p > t.sideB && p > t.sideC { return nil } return errors.New("Sum of any two sides of a triangle must be greater than the third side") } func (r rectangle) area() (float64, error) { if r.valid() != nil { return -1, r.valid() } return r.width * r.height, nil } func (c circle) area() (float64, error) { if c.valid() != nil { return -1, c.valid() } return math.Pi * c.radius * c.radius, nil } func (t triangle) area() (float64, error) { if t.valid() != nil { return -1, t.valid() } p := (t.sideA + t.sideB + t.sideC) / 2.0 return math.Sqrt(p * (p - t.sideA) * (p - t.sideB) * (p - t.sideC)), nil } func (r rectangle) perimeter() (float64, error) { if r.valid() != nil { return -1, r.valid() } return 2 * (r.width + r.height), nil } func (c circle) perimeter() (float64, error) { if c.valid() != nil { return -1, c.valid() } return 2 * math.Pi * c.radius, nil } func (t triangle) perimeter() (float64, error) { if t.valid() != nil { return -1, t.valid() } return t.sideA + t.sideB + t.sideC, nil }
08_interfaces.go
0.730963
0.403684
08_interfaces.go
starcoder
package ksdc type tBigram struct { firstRune rune secondRune rune } func createBigrams(word string) (map[tBigram]int, int, string) { bigrams := make(map[tBigram]int) runes := []rune(word) runesCount := len(runes) - 1 for index := 0; index < runesCount; index++ { bigrams[tBigram{firstRune: runes[index], secondRune: runes[index+1]}]++ } return bigrams, runesCount, word } func calculateScore( refBigrams map[tBigram]int, refCount int, ref string, ) func( inputBigrams map[tBigram]int, inputCount int, input string, ) float64 { return func( inputBigrams map[tBigram]int, inputCount int, input string, ) float64 { if len(ref) <= 2 || len(input) <= 2 { if ref == input { return 1 } return 0 } expendableRefBigrams := make(map[tBigram]int) for bigram, count := range refBigrams { expendableRefBigrams[bigram] = count } overlaps := float64(0) for bigram, count := range inputBigrams { for index := 0; index < count; index++ { refBigramCount := expendableRefBigrams[bigram] if refBigramCount <= 0 { break } overlaps++ expendableRefBigrams[bigram]-- } } return 2 * overlaps / float64(refCount+inputCount) } } type Match struct { reference string score float64 } type BestMatch struct { reference string score float64 index int } func FindMatchInReferences(references []string) func(input string) (BestMatch, []Match) { refsCount := len(references) refsFuncs := make([]func(map[tBigram]int, int, string) float64, refsCount) for index := 0; index < refsCount; index++ { refsFuncs[index] = calculateScore(createBigrams(references[index])) } return func(input string) (BestMatch, []Match) { inputBigrams, inputRunes, _ := createBigrams(input) matches := make([]Match, refsCount) bestScore := float64(-1) bestMatchIndex := 0 for index := 0; index < refsCount; index++ { score := refsFuncs[index](inputBigrams, inputRunes, input) matches[index] = Match{ score: score, reference: references[index], } if score > bestScore { bestScore = score bestMatchIndex = index } } return BestMatch{ reference: references[bestMatchIndex], score: matches[bestMatchIndex].score, index: bestMatchIndex, }, matches } } func FindMatch(references []string, input string) (BestMatch, []Match) { return FindMatchInReferences(references)(input) } func CompareStringToReference(reference string) func(input string) float64 { finder := FindMatchInReferences([]string{reference}) return func(input string) float64 { bestMatch, _ := finder(input) return bestMatch.score } } func CompareStrings(reference string, input string) float64 { return CompareStringToReference(reference)(input) }
ksdc.go
0.765506
0.548492
ksdc.go
starcoder
package graph import ( i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization" ) // WorkbookWorksheetProtectionOptions type WorkbookWorksheetProtectionOptions struct { // Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. additionalData map[string]interface{}; // Represents the worksheet protection option of allowing using auto filter feature. allowAutoFilter *bool; // Represents the worksheet protection option of allowing deleting columns. allowDeleteColumns *bool; // Represents the worksheet protection option of allowing deleting rows. allowDeleteRows *bool; // Represents the worksheet protection option of allowing formatting cells. allowFormatCells *bool; // Represents the worksheet protection option of allowing formatting columns. allowFormatColumns *bool; // Represents the worksheet protection option of allowing formatting rows. allowFormatRows *bool; // Represents the worksheet protection option of allowing inserting columns. allowInsertColumns *bool; // Represents the worksheet protection option of allowing inserting hyperlinks. allowInsertHyperlinks *bool; // Represents the worksheet protection option of allowing inserting rows. allowInsertRows *bool; // Represents the worksheet protection option of allowing using pivot table feature. allowPivotTables *bool; // Represents the worksheet protection option of allowing using sort feature. allowSort *bool; } // NewWorkbookWorksheetProtectionOptions instantiates a new workbookWorksheetProtectionOptions and sets the default values. func NewWorkbookWorksheetProtectionOptions()(*WorkbookWorksheetProtectionOptions) { m := &WorkbookWorksheetProtectionOptions{ } m.SetAdditionalData(make(map[string]interface{})); return m } // GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *WorkbookWorksheetProtectionOptions) GetAdditionalData()(map[string]interface{}) { if m == nil { return nil } else { return m.additionalData } } // GetAllowAutoFilter gets the allowAutoFilter property value. Represents the worksheet protection option of allowing using auto filter feature. func (m *WorkbookWorksheetProtectionOptions) GetAllowAutoFilter()(*bool) { if m == nil { return nil } else { return m.allowAutoFilter } } // GetAllowDeleteColumns gets the allowDeleteColumns property value. Represents the worksheet protection option of allowing deleting columns. func (m *WorkbookWorksheetProtectionOptions) GetAllowDeleteColumns()(*bool) { if m == nil { return nil } else { return m.allowDeleteColumns } } // GetAllowDeleteRows gets the allowDeleteRows property value. Represents the worksheet protection option of allowing deleting rows. func (m *WorkbookWorksheetProtectionOptions) GetAllowDeleteRows()(*bool) { if m == nil { return nil } else { return m.allowDeleteRows } } // GetAllowFormatCells gets the allowFormatCells property value. Represents the worksheet protection option of allowing formatting cells. func (m *WorkbookWorksheetProtectionOptions) GetAllowFormatCells()(*bool) { if m == nil { return nil } else { return m.allowFormatCells } } // GetAllowFormatColumns gets the allowFormatColumns property value. Represents the worksheet protection option of allowing formatting columns. func (m *WorkbookWorksheetProtectionOptions) GetAllowFormatColumns()(*bool) { if m == nil { return nil } else { return m.allowFormatColumns } } // GetAllowFormatRows gets the allowFormatRows property value. Represents the worksheet protection option of allowing formatting rows. func (m *WorkbookWorksheetProtectionOptions) GetAllowFormatRows()(*bool) { if m == nil { return nil } else { return m.allowFormatRows } } // GetAllowInsertColumns gets the allowInsertColumns property value. Represents the worksheet protection option of allowing inserting columns. func (m *WorkbookWorksheetProtectionOptions) GetAllowInsertColumns()(*bool) { if m == nil { return nil } else { return m.allowInsertColumns } } // GetAllowInsertHyperlinks gets the allowInsertHyperlinks property value. Represents the worksheet protection option of allowing inserting hyperlinks. func (m *WorkbookWorksheetProtectionOptions) GetAllowInsertHyperlinks()(*bool) { if m == nil { return nil } else { return m.allowInsertHyperlinks } } // GetAllowInsertRows gets the allowInsertRows property value. Represents the worksheet protection option of allowing inserting rows. func (m *WorkbookWorksheetProtectionOptions) GetAllowInsertRows()(*bool) { if m == nil { return nil } else { return m.allowInsertRows } } // GetAllowPivotTables gets the allowPivotTables property value. Represents the worksheet protection option of allowing using pivot table feature. func (m *WorkbookWorksheetProtectionOptions) GetAllowPivotTables()(*bool) { if m == nil { return nil } else { return m.allowPivotTables } } // GetAllowSort gets the allowSort property value. Represents the worksheet protection option of allowing using sort feature. func (m *WorkbookWorksheetProtectionOptions) GetAllowSort()(*bool) { if m == nil { return nil } else { return m.allowSort } } // GetFieldDeserializers the deserialization information for the current model func (m *WorkbookWorksheetProtectionOptions) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) { res := make(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) res["allowAutoFilter"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowAutoFilter(val) } return nil } res["allowDeleteColumns"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowDeleteColumns(val) } return nil } res["allowDeleteRows"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowDeleteRows(val) } return nil } res["allowFormatCells"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowFormatCells(val) } return nil } res["allowFormatColumns"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowFormatColumns(val) } return nil } res["allowFormatRows"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowFormatRows(val) } return nil } res["allowInsertColumns"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowInsertColumns(val) } return nil } res["allowInsertHyperlinks"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowInsertHyperlinks(val) } return nil } res["allowInsertRows"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowInsertRows(val) } return nil } res["allowPivotTables"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowPivotTables(val) } return nil } res["allowSort"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetAllowSort(val) } return nil } return res } func (m *WorkbookWorksheetProtectionOptions) IsNil()(bool) { return m == nil } // Serialize serializes information the current object func (m *WorkbookWorksheetProtectionOptions) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) { { err := writer.WriteBoolValue("allowAutoFilter", m.GetAllowAutoFilter()) if err != nil { return err } } { err := writer.WriteBoolValue("allowDeleteColumns", m.GetAllowDeleteColumns()) if err != nil { return err } } { err := writer.WriteBoolValue("allowDeleteRows", m.GetAllowDeleteRows()) if err != nil { return err } } { err := writer.WriteBoolValue("allowFormatCells", m.GetAllowFormatCells()) if err != nil { return err } } { err := writer.WriteBoolValue("allowFormatColumns", m.GetAllowFormatColumns()) if err != nil { return err } } { err := writer.WriteBoolValue("allowFormatRows", m.GetAllowFormatRows()) if err != nil { return err } } { err := writer.WriteBoolValue("allowInsertColumns", m.GetAllowInsertColumns()) if err != nil { return err } } { err := writer.WriteBoolValue("allowInsertHyperlinks", m.GetAllowInsertHyperlinks()) if err != nil { return err } } { err := writer.WriteBoolValue("allowInsertRows", m.GetAllowInsertRows()) if err != nil { return err } } { err := writer.WriteBoolValue("allowPivotTables", m.GetAllowPivotTables()) if err != nil { return err } } { err := writer.WriteBoolValue("allowSort", m.GetAllowSort()) if err != nil { return err } } { err := writer.WriteAdditionalData(m.GetAdditionalData()) if err != nil { return err } } return nil } // SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *WorkbookWorksheetProtectionOptions) SetAdditionalData(value map[string]interface{})() { if m != nil { m.additionalData = value } } // SetAllowAutoFilter sets the allowAutoFilter property value. Represents the worksheet protection option of allowing using auto filter feature. func (m *WorkbookWorksheetProtectionOptions) SetAllowAutoFilter(value *bool)() { if m != nil { m.allowAutoFilter = value } } // SetAllowDeleteColumns sets the allowDeleteColumns property value. Represents the worksheet protection option of allowing deleting columns. func (m *WorkbookWorksheetProtectionOptions) SetAllowDeleteColumns(value *bool)() { if m != nil { m.allowDeleteColumns = value } } // SetAllowDeleteRows sets the allowDeleteRows property value. Represents the worksheet protection option of allowing deleting rows. func (m *WorkbookWorksheetProtectionOptions) SetAllowDeleteRows(value *bool)() { if m != nil { m.allowDeleteRows = value } } // SetAllowFormatCells sets the allowFormatCells property value. Represents the worksheet protection option of allowing formatting cells. func (m *WorkbookWorksheetProtectionOptions) SetAllowFormatCells(value *bool)() { if m != nil { m.allowFormatCells = value } } // SetAllowFormatColumns sets the allowFormatColumns property value. Represents the worksheet protection option of allowing formatting columns. func (m *WorkbookWorksheetProtectionOptions) SetAllowFormatColumns(value *bool)() { if m != nil { m.allowFormatColumns = value } } // SetAllowFormatRows sets the allowFormatRows property value. Represents the worksheet protection option of allowing formatting rows. func (m *WorkbookWorksheetProtectionOptions) SetAllowFormatRows(value *bool)() { if m != nil { m.allowFormatRows = value } } // SetAllowInsertColumns sets the allowInsertColumns property value. Represents the worksheet protection option of allowing inserting columns. func (m *WorkbookWorksheetProtectionOptions) SetAllowInsertColumns(value *bool)() { if m != nil { m.allowInsertColumns = value } } // SetAllowInsertHyperlinks sets the allowInsertHyperlinks property value. Represents the worksheet protection option of allowing inserting hyperlinks. func (m *WorkbookWorksheetProtectionOptions) SetAllowInsertHyperlinks(value *bool)() { if m != nil { m.allowInsertHyperlinks = value } } // SetAllowInsertRows sets the allowInsertRows property value. Represents the worksheet protection option of allowing inserting rows. func (m *WorkbookWorksheetProtectionOptions) SetAllowInsertRows(value *bool)() { if m != nil { m.allowInsertRows = value } } // SetAllowPivotTables sets the allowPivotTables property value. Represents the worksheet protection option of allowing using pivot table feature. func (m *WorkbookWorksheetProtectionOptions) SetAllowPivotTables(value *bool)() { if m != nil { m.allowPivotTables = value } } // SetAllowSort sets the allowSort property value. Represents the worksheet protection option of allowing using sort feature. func (m *WorkbookWorksheetProtectionOptions) SetAllowSort(value *bool)() { if m != nil { m.allowSort = value } }
models/microsoft/graph/workbook_worksheet_protection_options.go
0.687735
0.421433
workbook_worksheet_protection_options.go
starcoder
package main /* A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain. To obtain target, you may apply the following operation on triplets any number of times (possibly zero): Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)]. For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]. Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise. Example 1: Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true Explanation: Perform the following operations: - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]] The target triplet [2,7,5] is now an element of triplets. Example 2: Input: triplets = [[1,3,4],[2,5,8]], target = [2,5,8] Output: true Explanation: The target triplet [2,5,8] is already an element of triplets. Example 3: Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] Output: true Explanation: Perform the following operations: - Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. - Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]]. The target triplet [5,5,5] is now an element of triplets. Example 4: Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] Output: false Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets. Constraints: 1 <= triplets.length <= 105 triplets[i].length == target.length == 3 1 <= ai, bi, ci, x, y, z <= 1000 */ // time O(n) // space O(1) func mergeTriplets(triplets [][]int, target []int) bool { foundTargets := make(map[int]bool) for _, triplet := range triplets { for i, value := range triplet { if value == target[i] { foundTargets[i] = true } } if len(foundTargets) == len(target) { return true } } return len(foundTargets) == len(target) } func main() { }
golang/algorithms/others/merge_triplets_to_form_target_triplet/main.go
0.76769
0.820972
main.go
starcoder
package day06 import ( "errors" "fmt" "strings" ) const ( youID = "YOU" santaID = "SAN" ) // orbitalRelationship reads as "satellite is in orbit around parent" or "satellite orbits parent" type orbitalRelationship struct { parent string satellite string } type orbitMap struct { orbitalRelationships []orbitalRelationship } type planet struct { id string orbitsAround *planet } // Day holds the data needed to solve part one and part two type Day struct { orbitMap orbitMap } // NewDay returns a new Day that solves part one and two for the given input func NewDay(input string) (*Day, error) { orbitMapString := strings.Split(input, "\n") orbitMap, err := parseOrbitMap(orbitMapString) if err != nil { return nil, fmt.Errorf("invalid orbit map %s: %w", orbitMapString, err) } return &Day{ orbitMap: *orbitMap, }, nil } // SolvePartOne solves part one func (d Day) SolvePartOne() (string, error) { galaxy, err := createGalaxy(d.orbitMap) if err != nil { return "", fmt.Errorf("could not create galaxy: %w", err) } totalOrbits := getTotalOrbits(galaxy) return fmt.Sprintf("%d", totalOrbits), nil } // SolvePartTwo solves part two func (d Day) SolvePartTwo() (string, error) { galaxy, err := createGalaxy(d.orbitMap) if err != nil { return "", fmt.Errorf("could not create galaxy: %w", err) } minimumOrbitalTransfers, err := getMinimumOrbitalTransfers(galaxy) if err != nil { return "", fmt.Errorf("could not compute minimum orbital transfers: %w", err) } return fmt.Sprintf("%d", minimumOrbitalTransfers), nil } func parseOrbitMap(orbitMapString []string) (*orbitMap, error) { orbitalRelationships := make([]orbitalRelationship, 0, len(orbitMapString)) for _, orbitalRelationshipString := range orbitMapString { orbitalRelationship, err := parseOrbitalRelationship(orbitalRelationshipString) if err != nil { return nil, fmt.Errorf("invalid orbital relationship %s: %w", orbitalRelationshipString, err) } orbitalRelationships = append(orbitalRelationships, *orbitalRelationship) } return &orbitMap{ orbitalRelationships: orbitalRelationships, }, nil } func parseOrbitalRelationship(orbitalRelationshipString string) (*orbitalRelationship, error) { relationship := strings.Split(orbitalRelationshipString, ")") if len(relationship) != 2 { return nil, fmt.Errorf("invalid format: %s", orbitalRelationshipString) } return &orbitalRelationship{ parent: relationship[0], satellite: relationship[1], }, nil } func createGalaxy(orbitMap orbitMap) (map[string]*planet, error) { galaxy := make(map[string]*planet) for _, orbitalRelationship := range orbitMap.orbitalRelationships { parentPlanet := getOrCreatePlanet(galaxy, orbitalRelationship.parent) satellitePlanet := getOrCreatePlanet(galaxy, orbitalRelationship.satellite) if satellitePlanet.orbitsAround != nil { return nil, fmt.Errorf("a satellite can orbit around one planet at most: %v", satellitePlanet) } satellitePlanet.orbitsAround = parentPlanet } return galaxy, nil } func getOrCreatePlanet(galaxy map[string]*planet, plantedID string) *planet { if _, ok := galaxy[plantedID]; !ok { galaxy[plantedID] = &planet{ id: plantedID, } } return galaxy[plantedID] } func getTotalOrbits(galaxy map[string]*planet) int { totalOrbits := 0 for _, planet := range galaxy { totalOrbits += planet.directAndIndirectOrbits() } return totalOrbits } func (p *planet) directAndIndirectOrbits() int { var path []string p.pathToGalaxyRoot(&path) return len(path) - 1 } func (p *planet) isGalaxyRoot() bool { return p.orbitsAround == nil } func getMinimumOrbitalTransfers(galaxy map[string]*planet) (int, error) { you, ok := galaxy[youID] if !ok { return 0, errors.New("you are not in the galaxy") } santa, ok := galaxy[santaID] if !ok { return 0, errors.New("santa is not in the galaxy") } var path1 []string you.pathToGalaxyRoot(&path1) var path2 []string santa.pathToGalaxyRoot(&path2) ancestor, err := lowestCommonAncestor(path1, path2) if err != nil { return 0, fmt.Errorf("santa in not reachable by you: %w", err) } return orbitalTransfers(ancestor, path1) + orbitalTransfers(ancestor, path2), nil } func (p *planet) pathToGalaxyRoot(path *[]string) { *path = append(*path, p.id) if !p.isGalaxyRoot() { p.orbitsAround.pathToGalaxyRoot(path) } } func lowestCommonAncestor(path1, path2 []string) (string, error) { if len(path1) == 0 || len(path2) == 0 { return "", fmt.Errorf("no common ancestor between %v and %v", path1, path2) } i := len(path1) - 1 j := len(path2) - 1 if path1[i] != path2[j] { return "", fmt.Errorf("no common ancestor between %v and %v", path1, path2) } for { if path1[i-1] != path2[j-1] { return path1[i], nil } i-- j-- if i == 0 { return path1[0], nil } if j == 0 { return path2[0], nil } } } func orbitalTransfers(ancestor string, path []string) int { orbitalTransfers := 0 // we don't have to count the first orbital transfer for _, planetID := range path[1:] { if planetID == ancestor { break } orbitalTransfers++ } return orbitalTransfers }
day06/day06.go
0.716417
0.425009
day06.go
starcoder
package list import "github.com/jesseduffield/generics/slices" // List is a struct which wraps a slice and provides convenience methods for it. // Unfortunately due to some limitations in Go's type system, certain methods // are not available e.g. Map. type List[T any] struct { slice []T } func New[T any]() *List[T] { return &List[T]{} } func NewFromSlice[T any](slice []T) *List[T] { return &List[T]{slice: slice} } func (l *List[T]) ToSlice() []T { return l.slice } // Mutative methods func (l *List[T]) Push(v T) { l.slice = append(l.slice, v) } func (l *List[T]) Pop() T { var value T value, l.slice = slices.Pop(l.slice) return value } func (l *List[T]) Insert(index int, values ...T) { l.slice = slices.Insert(l.slice, index, values...) } func (l *List[T]) Append(values ...T) { l.slice = append(l.slice, values...) } func (l *List[T]) Prepend(values ...T) { l.slice = append(values, l.slice...) } func (l *List[T]) Remove(index int) { l.Delete(index, index+1) } func (l *List[T]) Delete(from int, to int) { l.slice = slices.Delete(l.slice, from, to) } func (l *List[T]) FilterInPlace(test func(value T) bool) { l.slice = slices.FilterInPlace(l.slice, test) } func (l *List[T]) MapInPlace(f func(value T) T) { slices.MapInPlace(l.slice, f) } func (l *List[T]) ReverseInPlace() { slices.ReverseInPlace(l.slice) } // Non-mutative methods // Similar to Append but we leave the original slice untouched and return a new list func (l *List[T]) Concat(values ...T) *List[T] { return NewFromSlice(slices.Concat(l.slice, values...)) } func (l *List[T]) Filter(test func(value T) bool) *List[T] { return NewFromSlice(slices.Filter(l.slice, test)) } // Unfortunately this does not support mapping from one type to another // because Go does not yet (and may never) support methods defining their own // type parameters. For that functionality you'll need to use the standalone // Map function instead func (l *List[T]) Map(f func(value T) T) *List[T] { return NewFromSlice(slices.Map(l.slice, f)) } func (l *List[T]) Clone() *List[T] { return NewFromSlice(slices.Clone(l.slice)) } func (l *List[T]) Some(test func(value T) bool) bool { return slices.Some(l.slice, test) } func (l *List[T]) Every(test func(value T) bool) bool { return slices.Every(l.slice, test) } func (l *List[T]) IndexFunc(f func(T) bool) int { return slices.IndexFunc(l.slice, f) } func (l *List[T]) ContainsFunc(f func(T) bool) bool { return slices.ContainsFunc(l.slice, f) } func (l *List[T]) Reverse() *List[T] { return NewFromSlice(slices.Reverse(l.slice)) } func (l *List[T]) IsEmpty() bool { return len(l.slice) == 0 } func (l *List[T]) Len() int { return len(l.slice) } func (l *List[T]) Get(index int) T { return l.slice[index] }
list/list.go
0.789356
0.587322
list.go
starcoder
package colorlab import ( "github.com/lucasb-eyer/go-colorful" ) // Accents . type Accents struct { Yellow HexColor Orange HexColor Red HexColor Magenta HexColor Violet HexColor Blue HexColor Cyan HexColor Green HexColor } type AccentColors [8]colorful.Color func NewAccents(cc [8]colorful.Color) Accents { return Accents{ Yellow: HexColor(cc[0].Clamped().Hex()), Orange: HexColor(cc[1].Clamped().Hex()), Red: HexColor(cc[2].Clamped().Hex()), Magenta: HexColor(cc[3].Clamped().Hex()), Violet: HexColor(cc[4].Clamped().Hex()), Blue: HexColor(cc[5].Clamped().Hex()), Cyan: HexColor(cc[6].Clamped().Hex()), Green: HexColor(cc[7].Clamped().Hex()), } } func (s Accents) Clone() Accents { return Accents{ Yellow: s.Yellow, Orange: s.Orange, Red: s.Red, Magenta: s.Magenta, Violet: s.Violet, Blue: s.Blue, Cyan: s.Cyan, Green: s.Green, } } func (s Accents) Colors() AccentColors { a := s.colorArray() return [8]colorful.Color{ a[0].Color(), a[1].Color(), a[2].Color(), a[3].Color(), a[4].Color(), a[5].Color(), a[6].Color(), a[7].Color(), } } func (a Accents) ChangeLightness(amount float64) Accents { cc := a.Colors() lightness := func(c colorful.Color, v float64) colorful.Color { l, a, b := c.Lab() l = l + v return colorful.Lab(l, a, b) } cc[0] = lightness(cc[0], amount) cc[1] = lightness(cc[1], amount) cc[2] = lightness(cc[2], amount) cc[3] = lightness(cc[3], amount) cc[4] = lightness(cc[4], amount) cc[5] = lightness(cc[5], amount) cc[6] = lightness(cc[6], amount) cc[7] = lightness(cc[7], amount) return NewAccents(cc) } func (a Accents) ChangeSaturation(amount float64) Accents { cc := a.Colors() saturation := func(c colorful.Color, v float64) colorful.Color { h, s, l := c.Hsl() // s = math.Min(math.Max(s+v, 0), 1) s = s + v return colorful.Hsl(h, s, l) } cc[0] = saturation(cc[0], amount) cc[1] = saturation(cc[1], amount) cc[2] = saturation(cc[2], amount) cc[3] = saturation(cc[3], amount) cc[4] = saturation(cc[4], amount) cc[5] = saturation(cc[5], amount) cc[6] = saturation(cc[6], amount) cc[7] = saturation(cc[7], amount) return NewAccents(cc) } func (a Accents) Blend(hc HexColor, amount float64) Accents { c := hc.Color() cc := a.Colors() cc[0] = cc[0].BlendLab(c, amount) cc[1] = cc[1].BlendLab(c, amount) cc[2] = cc[2].BlendLab(c, amount) cc[3] = cc[3].BlendLab(c, amount) cc[4] = cc[4].BlendLab(c, amount) cc[5] = cc[5].BlendLab(c, amount) cc[6] = cc[6].BlendLab(c, amount) cc[7] = cc[7].BlendLab(c, amount) return NewAccents(cc) } func (ac Accents) NamedColors() NamedColors { nc := make(NamedColors, 8) arr := ac.colorArray() for idx, hex := range arr { nc[accentNames[idx]] = hex } return nc } func (s Accents) colorArray() [8]HexColor { return [8]HexColor{ s.Yellow, s.Orange, s.Red, s.Magenta, s.Violet, s.Blue, s.Cyan, s.Green, } } var accentNames = [8]string{ 0: "yellow", 1: "orange", 2: "red", 3: "magenta", 4: "violet", 5: "blue", 6: "cyan", 7: "green", }
accents.go
0.693577
0.460046
accents.go
starcoder
package spirv // OpDPdx is equivalent to either OpDPdxFine or OpDPdxCoarse on P. // Selection of which one is based on external factors. type OpDPdx struct { ResultType Id ResultId Id P Id } func (c *OpDPdx) Opcode() uint32 { return opcodeDPdx } func (c *OpDPdx) Optional() bool { return false } func (c *OpDPdx) Verify() error { return nil } // OpDPdy is equivalent to either OpDPdyFine or OpDPdyCoarse on P. // Selection of which one is based on external factors. type OpDPdy struct { ResultType Id ResultId Id P Id } func (c *OpDPdy) Opcode() uint32 { return opcodeDPdy } func (c *OpDPdy) Optional() bool { return false } func (c *OpDPdy) Verify() error { return nil } // OpFwidth is equivalent to computing the sum of the absolute values of // OpDPdx and OpDPdy on P. type OpFwidth struct { ResultType Id ResultId Id P Id } func (c *OpFwidth) Opcode() uint32 { return opcodeFwidth } func (c *OpFwidth) Optional() bool { return false } func (c *OpFwidth) Verify() error { return nil } // OpDPdxFine calculates the partial derivative of P with respect to the // window x coordinate. type OpDPdxFine struct { ResultType Id ResultId Id P Id } func (c *OpDPdxFine) Opcode() uint32 { return opcodeDPdxFine } func (c *OpDPdxFine) Optional() bool { return false } func (c *OpDPdxFine) Verify() error { return nil } // OpDPdyFine calculates the partial derivative of P with respect to the // window y coordinate. type OpDPdyFine struct { ResultType Id ResultId Id P Id } func (c *OpDPdyFine) Opcode() uint32 { return opcodeDPdyFine } func (c *OpDPdyFine) Optional() bool { return false } func (c *OpDPdyFine) Verify() error { return nil } // OpFwidthFine is equivalent to computing the sum of the absolute values // of OpDPdxFine and OpDPdyFine on P. type OpFwidthFine struct { ResultType Id ResultId Id P Id } func (c *OpFwidthFine) Opcode() uint32 { return opcodeFwidthFine } func (c *OpFwidthFine) Optional() bool { return false } func (c *OpFwidthFine) Verify() error { return nil } // OpDPdxCoarse calculates the partial derivative of P with respect to the // window x coordinate. type OpDPdxCoarse struct { ResultType Id ResultId Id P Id } func (c *OpDPdxCoarse) Opcode() uint32 { return opcodeDPdxCoarse } func (c *OpDPdxCoarse) Optional() bool { return false } func (c *OpDPdxCoarse) Verify() error { return nil } // OpDPdyCoarse calculates the partial derivative of P with respect to the // window y coordinate. type OpDPdyCoarse struct { ResultType Id ResultId Id P Id } func (c *OpDPdyCoarse) Opcode() uint32 { return opcodeDPdyCoarse } func (c *OpDPdyCoarse) Optional() bool { return false } func (c *OpDPdyCoarse) Verify() error { return nil } // OpFwidthCoarse is equivalent to computing the sum of the absolute values // of OpDPdxCoarse and OpDPdyCoarse on P. type OpFwidthCoarse struct { ResultType Id ResultId Id P Id } func (c *OpFwidthCoarse) Opcode() uint32 { return opcodeFwidthCoarse } func (c *OpFwidthCoarse) Optional() bool { return false } func (c *OpFwidthCoarse) Verify() error { return nil } func init() { bind(func() Instruction { return &OpDPdx{} }) bind(func() Instruction { return &OpDPdy{} }) bind(func() Instruction { return &OpFwidth{} }) bind(func() Instruction { return &OpDPdxFine{} }) bind(func() Instruction { return &OpDPdyFine{} }) bind(func() Instruction { return &OpFwidthFine{} }) bind(func() Instruction { return &OpDPdxCoarse{} }) bind(func() Instruction { return &OpDPdyCoarse{} }) bind(func() Instruction { return &OpFwidthCoarse{} }) }
instructions_derivative.go
0.827515
0.442094
instructions_derivative.go
starcoder
package primitives import ( "github.com/alexandreLamarre/Golang-Ray-Tracing-Renderer/pkg/algebra" "github.com/alexandreLamarre/Golang-Ray-Tracing-Renderer/pkg/canvas" "math" ) //Cylinder defines a default cylinder Shape type Cylinder struct { parent Shape closed bool //determines if the cylinder is hollow or has caps on the ends transform *algebra.Matrix material *canvas.Material maximum float64 //maximum y-value by default without transformations minimum float64 //minimum y-value by default without transformations } //NewCylinder returns a new Cylinder Shape func NewCylinder(m *algebra.Matrix) *Cylinder { mat := m if m == nil || len(m.Get()) != 4 || len(m.Get()[0]) != 4 { mat = algebra.IdentityMatrix(4) } return &Cylinder{transform: mat, material: canvas.NewDefaultMaterial(), maximum: math.Inf(1), minimum: math.Inf(-1), closed: false, parent: nil} } //SetMinimum Setter for cylinder minimum y-truncation func (cyl *Cylinder) SetMinimum(min float64) { cyl.minimum = min } //SetMaximum Setter for cylinder maximum y-truncation func (cyl *Cylinder) SetMaximum(max float64) { cyl.maximum = max } //SetClosed Setter for cylinder closededness: whether or not it has caps on the cylinder func (cyl *Cylinder) SetClosed(closed bool) { cyl.closed = closed } //Shape interface methods //GetTransform Getter for Cylinder Shape transform func (cyl *Cylinder) GetTransform() *algebra.Matrix { return cyl.transform } //GetMaterial Getter for Cylinder Shape material func (cyl *Cylinder) GetMaterial() *canvas.Material { return cyl.material } //SetTransform Setter for Cylinder Shape transform func (cyl *Cylinder) SetTransform(m *algebra.Matrix) { if len(m.Get()) != 4 || len(m.Get()[0]) != 4 { panic(algebra.ExpectedDimension(4)) } cyl.transform = m } //SetMaterial Setter for Cylinder Shape material func (cyl *Cylinder) SetMaterial(m *canvas.Material) { cyl.material = m } //SetParent Setter for parent shape func (cyl *Cylinder) SetParent(shape Shape) { cyl.parent = shape } //GetParent Getter for parent shape func (cyl *Cylinder) GetParent() Shape { return cyl.parent } //GetBounds Getter for default bounds of this Shape func (cyl *Cylinder) GetBounds() (*algebra.Vector, *algebra.Vector) { return algebra.NewPoint(-1, cyl.minimum, -1), algebra.NewPoint(1, cyl.maximum, 1) } //LocalIntersect returns the itersection values for a Ray with a Cylinder func (cyl *Cylinder) LocalIntersect(ray *algebra.Ray) ([]*Intersection, bool) { direction := ray.Get()["direction"] origin := ray.Get()["origin"] dx := direction.Get()[0] dy := direction.Get()[1] dz := direction.Get()[2] a := dx*dx + dz*dz EPSILON := 0.00001 xs := make([]*Intersection, 0, 0) xs = cyl.intersectCaps(ray, xs) if a <= EPSILON && a >= -EPSILON { var hit bool if len(xs) == 0 { hit = false } else { hit = true } return xs, hit } ox := origin.Get()[0] oy := origin.Get()[1] oz := origin.Get()[2] b := 2*ox*dx + 2*oz*dz c := ox*ox + oz*oz - 1 disc := b*b - 4*a*c if disc < 0 { var hit bool if len(xs) == 0 { hit = false } else { hit = true } return xs, hit } t0 := (-b - math.Sqrt(disc)) / (2 * a) t1 := (-b + math.Sqrt(disc)) / (2 * a) y0 := oy + t0*dy if cyl.minimum < y0 && cyl.maximum > y0 { xs = append(xs, NewIntersection(cyl, t0)) } y1 := oy + t1*dy if cyl.minimum < y1 && cyl.maximum > y1 { xs = append(xs, NewIntersection(cyl, t1)) } var hit bool if len(xs) == 0 { hit = false } else { hit = true } return xs, hit } //LocalNormalAt returns the normal at an intersection point of a Cylinder Shape, shape interface method func (cyl *Cylinder) LocalNormalAt(p *algebra.Vector, hit *Intersection) (*algebra.Vector, error) { x := p.Get()[0] y := p.Get()[1] z := p.Get()[2] dist := x*x + z*z EPSILON := 0.001 if dist < 1 && y >= cyl.maximum-EPSILON { return algebra.NewVector(0, 1, 0), nil } else if dist < 1 && y <= cyl.minimum+EPSILON { return algebra.NewVector(0, -1, 0), nil } return algebra.NewVector(p.Get()[0], 0, p.Get()[2]), nil } //cylinder helpers func checkCap(ray *algebra.Ray, t float64) bool { origin := ray.Get()["origin"] direction := ray.Get()["direction"] x := origin.Get()[0] + t*direction.Get()[0] z := origin.Get()[2] + t*direction.Get()[2] return (x*x + z*z) <= 1 } func (cyl *Cylinder) intersectCaps(ray *algebra.Ray, xs []*Intersection) []*Intersection { origin := ray.Get()["origin"] direction := ray.Get()["direction"] oy := origin.Get()[1] dy := direction.Get()[1] EPSILON := 0.0001 if !cyl.closed || (dy < EPSILON && dy > -EPSILON) { return xs } t := (cyl.minimum - oy) / dy if checkCap(ray, t) { xs = append(xs, NewIntersection(cyl, t)) } t = (cyl.maximum - oy) / dy if checkCap(ray, t) { xs = append(xs, NewIntersection(cyl, t)) } return xs }
pkg/geometry/primitives/cylinder.go
0.846229
0.473292
cylinder.go
starcoder
package bmp280 import ( "fmt" "math" "periph.io/x/periph/conn/i2c" ) // BMP a BMP280 sensor type BMP struct { device *i2c.Dev config *Configuration lastTemperatureMeasurement float64 tempCalibration []calibrationData pressCalibration []calibrationData } // NewBMP280 create an initialize a new BMP280 sensor. Returns the newly created BMP280 sensor func NewBMP280(dev *i2c.Dev) (*BMP, error) { bmp := &BMP{ device: dev, tempCalibration: make([]calibrationData, 3), pressCalibration: make([]calibrationData, 9), lastTemperatureMeasurement: math.NaN(), } err := bmp.Init() return bmp, err } // NewBMP280WithConfig create an initialize a new BMP280 sensor and set up its initial configuration. Returns the newly created BMP280 sensor or any errors that occurred when configuring it. func NewBMP280WithConfig(dev *i2c.Dev, cfg *Configuration) (*BMP, error) { bmp := &BMP{ device: dev, config: cfg, tempCalibration: make([]calibrationData, 3), pressCalibration: make([]calibrationData, 9), lastTemperatureMeasurement: math.NaN(), } if err := bmp.SetConfiguration(cfg); err != nil { return bmp, err } err := bmp.Init() return bmp, err } // Init initializes the BMP280 sensor with calibration data saved in the BMP280's registers func (me *BMP) Init() error { d, err := me.readCalibrationValues(regsTempCalibration...) if err != nil { return fmt.Errorf("Error reading temperature calibration values: %s", err.Error()) } me.tempCalibration = d if d, err = me.readCalibrationValues(regsPressureCalibration...); err != nil { return fmt.Errorf("Error reading pressure calibration values: %s", err.Error()) } me.pressCalibration = d return nil } // Configuration get the current configuration for this BMP280 sensor func (me *BMP) Configuration() *Configuration { return me.config } // SetConfiguration set up the configuration for how this BMP280 sensor should operate. Returns any errors that occur when configuring the sensor func (me *BMP) SetConfiguration(cfg *Configuration) error { me.config = cfg _, err := me.device.Write(cfg.bytes()) return err } // Reset perform a full reset on the BMP280 device as if it had first powered on func (me *BMP) Reset() error { _, err := me.device.Write([]byte{uint8(regReset), resetCode}) return err } // ReadAll reads both temperature and pressure sensor data at once. Returns temperature value, pressure value, or any errors that occurred func (me *BMP) ReadAll() (float64, float64, error) { intVals, err := me.readSensorValues(regTemperature, regPressure) if err != nil { return math.NaN(), math.NaN(), err } temp := me.computeTemperature(intVals[0]) press := me.computePressure(intVals[1]) return temp, press, nil } // ReadTemperature read the latest temperature reading from the BMP280. Returns the temperature in Celsius or any i2c errors that occurred func (me *BMP) ReadTemperature() (float64, error) { intVals, err := me.readSensorValues(regTemperature) if err != nil { return math.NaN(), err } return me.computeTemperature(intVals[0]), nil } // ReadPressure read the latest pressure reading from the BMP280. Returns the pressure in Pascals or any i2c errors that occurred func (me *BMP) ReadPressure() (float64, error) { if math.IsNaN(float64(me.lastTemperatureMeasurement)) { if _, err := me.ReadTemperature(); err != nil { return float64(math.NaN()), err } } vals, err := me.readSensorValues(regPressure) if err != nil { return math.NaN(), err } return me.computePressure(vals[0]), nil } func (me *BMP) computeTemperature(intVal sensorData) float64 { floatVal := float64(intVal) var1 := (floatVal/16384.0 - me.pressCalibration[0].f()/1024.0) * me.pressCalibration[1].f() var2 := ((floatVal/131072.0 - me.pressCalibration[0].f()/8192.0) * (floatVal/131072.0 - me.pressCalibration[0].f()/8192.0)) * me.pressCalibration[2].f() me.lastTemperatureMeasurement = var1 + var2 return me.lastTemperatureMeasurement / 5120.0 } func (me *BMP) computePressure(intVal sensorData) float64 { floatVal := float64(intVal) var1 := me.lastTemperatureMeasurement/2.0 - 64000.0 var2 := var1 * var1 * me.pressCalibration[5].f() / 32768.0 var2 = var2 + var1*me.pressCalibration[4].f()*2.0 var2 = var2/4.0 + me.pressCalibration[3].f()*65536.0 var1 = (me.pressCalibration[2].f()*var1*var1/524288.0 + me.pressCalibration[1].f()*var1) / 524288.0 var1 = (1.0 + var1/32768.0) * me.pressCalibration[0].f() if var1 == 0.0 { return 0.0 } p := 1048576.0 - floatVal p = (p - (var2 / 4096.0)) * 6250.0 / var1 var1 = me.pressCalibration[8].f() * p * p / 2147483648.0 var2 = p * me.pressCalibration[7].f() / 32768.0 p = p + (var1+var2+me.pressCalibration[6].f())/16.0 return p } func (me *BMP) readCalibrationValues(registers ...register) ([]calibrationData, error) { b, err := me.readRegisters(2, registers...) if err != nil { return nil, err } vals := make([]calibrationData, len(registers)) for i := 0; i < len(b); i += 2 { vals[i/2] = newCalibrationData(b, i, i == 0) } return vals, nil } func (me *BMP) readSensorValues(registers ...register) ([]sensorData, error) { b, err := me.readRegisters(3, registers...) if err != nil { return nil, err } vals := make([]sensorData, len(registers)) for i := 0; i < len(b); i += 3 { vals[i/3] = newSensorData(b, i) } return vals, nil } func (me *BMP) readRegisters(size int, registers ...register) ([]byte, error) { w := make([]byte, len(registers)*size) r := make([]byte, len(w)) if err := me.device.Bus.Tx(me.device.Addr, w, r); err != nil { return nil, err } return r, nil } func (me *BMP) convertUInt16(b []byte, offset int) uint16 { if offset+2 > len(b) { panic("Offset and length must fit within size of slice") } return uint16(b[offset+1])<<8 | (0xFF & uint16(b[offset])) } func (me *BMP) convertInt16(b []byte, offset int) int16 { if offset+2 > len(b) { panic("Offset and length must fit within size of slice") } return int16(b[offset+1])<<8 | (0xFF & int16(b[offset])) }
bmp.go
0.667906
0.428293
bmp.go
starcoder
package image // All Colors can convert themselves, with a possible loss of precision, // to 64-bit alpha-premultiplied RGBA. Each channel value ranges within // [0, 0xFFFF]. type Color interface { RGBA() (r, g, b, a uint32) } // An RGBAColor represents a traditional 32-bit alpha-premultiplied color, // having 8 bits for each of red, green, blue and alpha. type RGBAColor struct { R, G, B, A uint8 } func (c RGBAColor) RGBA() (r, g, b, a uint32) { r = uint32(c.R) r |= r << 8 g = uint32(c.G) g |= g << 8 b = uint32(c.B) b |= b << 8 a = uint32(c.A) a |= a << 8 return } // An RGBA64Color represents a 64-bit alpha-premultiplied color, // having 16 bits for each of red, green, blue and alpha. type RGBA64Color struct { R, G, B, A uint16 } func (c RGBA64Color) RGBA() (r, g, b, a uint32) { return uint32(c.R), uint32(c.G), uint32(c.B), uint32(c.A) } // An NRGBAColor represents a non-alpha-premultiplied 32-bit color. type NRGBAColor struct { R, G, B, A uint8 } func (c NRGBAColor) RGBA() (r, g, b, a uint32) { r = uint32(c.R) r |= r << 8 r *= uint32(c.A) r /= 0xff g = uint32(c.G) g |= g << 8 g *= uint32(c.A) g /= 0xff b = uint32(c.B) b |= b << 8 b *= uint32(c.A) b /= 0xff a = uint32(c.A) a |= a << 8 return } // An NRGBA64Color represents a non-alpha-premultiplied 64-bit color, // having 16 bits for each of red, green, blue and alpha. type NRGBA64Color struct { R, G, B, A uint16 } func (c NRGBA64Color) RGBA() (r, g, b, a uint32) { r = uint32(c.R) r *= uint32(c.A) r /= 0xffff g = uint32(c.G) g *= uint32(c.A) g /= 0xffff b = uint32(c.B) b *= uint32(c.A) b /= 0xffff a = uint32(c.A) return } // An AlphaColor represents an 8-bit alpha. type AlphaColor struct { A uint8 } func (c AlphaColor) RGBA() (r, g, b, a uint32) { a = uint32(c.A) a |= a << 8 return a, a, a, a } // An Alpha16Color represents a 16-bit alpha. type Alpha16Color struct { A uint16 } func (c Alpha16Color) RGBA() (r, g, b, a uint32) { a = uint32(c.A) return a, a, a, a } // A GrayColor represents an 8-bit grayscale color. type GrayColor struct { Y uint8 } func (c GrayColor) RGBA() (r, g, b, a uint32) { y := uint32(c.Y) y |= y << 8 return y, y, y, 0xffff } // A Gray16Color represents a 16-bit grayscale color. type Gray16Color struct { Y uint16 } func (c Gray16Color) RGBA() (r, g, b, a uint32) { y := uint32(c.Y) return y, y, y, 0xffff } // A ColorModel can convert foreign Colors, with a possible loss of precision, // to a Color from its own color model. type ColorModel interface { Convert(c Color) Color } // The ColorModelFunc type is an adapter to allow the use of an ordinary // color conversion function as a ColorModel. If f is such a function, // ColorModelFunc(f) is a ColorModel object that invokes f to implement // the conversion. type ColorModelFunc func(Color) Color func (f ColorModelFunc) Convert(c Color) Color { return f(c) } func toRGBAColor(c Color) Color { if _, ok := c.(RGBAColor); ok { return c } r, g, b, a := c.RGBA() return RGBAColor{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)} } func toRGBA64Color(c Color) Color { if _, ok := c.(RGBA64Color); ok { return c } r, g, b, a := c.RGBA() return RGBA64Color{uint16(r), uint16(g), uint16(b), uint16(a)} } func toNRGBAColor(c Color) Color { if _, ok := c.(NRGBAColor); ok { return c } r, g, b, a := c.RGBA() if a == 0xffff { return NRGBAColor{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), 0xff} } if a == 0 { return NRGBAColor{0, 0, 0, 0} } // Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a. r = (r * 0xffff) / a g = (g * 0xffff) / a b = (b * 0xffff) / a return NRGBAColor{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)} } func toNRGBA64Color(c Color) Color { if _, ok := c.(NRGBA64Color); ok { return c } r, g, b, a := c.RGBA() if a == 0xffff { return NRGBA64Color{uint16(r), uint16(g), uint16(b), 0xffff} } if a == 0 { return NRGBA64Color{0, 0, 0, 0} } // Since Color.RGBA returns a alpha-premultiplied color, we should have r <= a && g <= a && b <= a. r = (r * 0xffff) / a g = (g * 0xffff) / a b = (b * 0xffff) / a return NRGBA64Color{uint16(r), uint16(g), uint16(b), uint16(a)} } func toAlphaColor(c Color) Color { if _, ok := c.(AlphaColor); ok { return c } _, _, _, a := c.RGBA() return AlphaColor{uint8(a >> 8)} } func toAlpha16Color(c Color) Color { if _, ok := c.(Alpha16Color); ok { return c } _, _, _, a := c.RGBA() return Alpha16Color{uint16(a)} } func toGrayColor(c Color) Color { if _, ok := c.(GrayColor); ok { return c } r, g, b, _ := c.RGBA() y := (299*r + 587*g + 114*b + 500) / 1000 return GrayColor{uint8(y >> 8)} } func toGray16Color(c Color) Color { if _, ok := c.(Gray16Color); ok { return c } r, g, b, _ := c.RGBA() y := (299*r + 587*g + 114*b + 500) / 1000 return Gray16Color{uint16(y)} } // The ColorModel associated with RGBAColor. var RGBAColorModel ColorModel = ColorModelFunc(toRGBAColor) // The ColorModel associated with RGBA64Color. var RGBA64ColorModel ColorModel = ColorModelFunc(toRGBA64Color) // The ColorModel associated with NRGBAColor. var NRGBAColorModel ColorModel = ColorModelFunc(toNRGBAColor) // The ColorModel associated with NRGBA64Color. var NRGBA64ColorModel ColorModel = ColorModelFunc(toNRGBA64Color) // The ColorModel associated with AlphaColor. var AlphaColorModel ColorModel = ColorModelFunc(toAlphaColor) // The ColorModel associated with Alpha16Color. var Alpha16ColorModel ColorModel = ColorModelFunc(toAlpha16Color) // The ColorModel associated with GrayColor. var GrayColorModel ColorModel = ColorModelFunc(toGrayColor) // The ColorModel associated with Gray16Color. var Gray16ColorModel ColorModel = ColorModelFunc(toGray16Color)
src/pkg/image/color.go
0.901374
0.615695
color.go
starcoder
package app import ( "errors" "fmt" "time" ) func GetCharacter(today time.Time, config FestojiConfig) (string, error) { for _, rule := range config.Rules { var end time.Time month := time.Month(rule.Month) if rule.Day != 0 { end = GetEndOfDay(today, month, rule.Day) } else if rule.Weekday != 0 && rule.Week != 0 { weekday := time.Weekday(rule.Weekday) end = GetEndOfNthWeekdayOfMonth(today, month, rule.Week, weekday) } else { return "", errors.New(fmt.Sprint(rule.Name, " is not a valid rule")) } if InSeason(today, end, rule.Span) { return rule.Emoji, nil } } return config.Default, nil } func InSeason(today time.Time, end time.Time, spanDays int) bool { spanSeconds := float64(spanDays) * 24 * 60 * 60 diffSeconds := end.Sub(today).Seconds() return diffSeconds >= 0 && diffSeconds < spanSeconds } func GetEndOfDay(today time.Time, month time.Month, day int) time.Time { end := GetEndOfDayThisYear(today, month, day) // Always get the next occurrence of the date if end.Before(today) { end = GetEndOfDayNextYear(today, month, day) } return end } func GetEndOfDayThisYear(today time.Time, month time.Month, day int) time.Time { end := time.Date(today.Year(), month, day, 23, 59, 59, 0, today.Location()) return end } func GetEndOfDayNextYear(today time.Time, month time.Month, day int) time.Time { end := time.Date(today.Year()+1, month, day, 23, 59, 59, 0, today.Location()) return end } // wow this is a terrible name func GetEndOfNthWeekdayOfMonth(today time.Time, month time.Month, nthWeek int, weekday time.Weekday) time.Time { // cannot use the more generic GetEndOfDay function here because we only want to forward // to the next year if the *adjusted* end date is in the past. end := GetEndOfNthWeekdayOfMonthStrict(GetEndOfDayThisYear(today, month, 1), nthWeek, weekday) if end.Before(today) { end = GetEndOfNthWeekdayOfMonthStrict(GetEndOfDayNextYear(today, month, 1), nthWeek, weekday) } return end } func GetEndOfNthWeekdayOfMonthStrict(start time.Time, nthWeek int, weekday time.Weekday) time.Time { daysToAdd := 0 if weekDaysDiff := int(weekday - start.Weekday()); weekDaysDiff >= 0 { daysToAdd += weekDaysDiff } else { daysToAdd += int(7 - start.Weekday() + weekday) } // Advance to whichever nth week daysToAdd += (nthWeek-1) * 7 return start.AddDate(0, 0, daysToAdd) }
app/app.go
0.684475
0.414603
app.go
starcoder
package bulletproof import ( "github.com/gtank/merlin" "github.com/pkg/errors" "github.com/coinbase/kryptology/pkg/core/curves" ) // RangeVerifier is the struct used to verify RangeProofs // It specifies which curve to use and holds precomputed generators // See NewRangeVerifier() for verifier initialization. type RangeVerifier struct { curve curves.Curve generators *ippGenerators ippVerifier *InnerProductVerifier } // NewRangeVerifier initializes a new verifier // It uses the specified domain to generate generators for vectors of at most maxVectorLength // A verifier can be used to verify range proofs for vectors of length less than or equal to maxVectorLength // A verifier is defined by an explicit curve. func NewRangeVerifier(maxVectorLength int, rangeDomain, ippDomain []byte, curve curves.Curve) (*RangeVerifier, error) { generators, err := getGeneratorPoints(maxVectorLength, rangeDomain, curve) if err != nil { return nil, errors.Wrap(err, "range NewRangeProver") } ippVerifier, err := NewInnerProductVerifier(maxVectorLength, ippDomain, curve) if err != nil { return nil, errors.Wrap(err, "range NewRangeProver") } return &RangeVerifier{curve: curve, generators: generators, ippVerifier: ippVerifier}, nil } // Verify verifies the given range proof inputs // It implements the checking of L65 on pg 20 // It also verifies the dot product of <l,r> using the inner product proof\ // capV is a commitment to v using blinding factor gamma // n is the power that specifies the upper bound of the range, ie. 2^n // g, h, u are unique points used as generators for the blinding factor // transcript is a merlin transcript to be used for the fiat shamir heuristic. func (verifier *RangeVerifier) Verify(proof *RangeProof, capV curves.Point, proofGenerators RangeProofGenerators, n int, transcript *merlin.Transcript) (bool, error) { // Length of vectors must be less than the number of generators generated if n > len(verifier.generators.G) { return false, errors.New("ipp vector length must be less than maxVectorLength") } // In case where len(a) is less than number of generators precomputed by prover, trim to length proofG := verifier.generators.G[0:n] proofH := verifier.generators.H[0:n] // Calc y,z,x from Fiat Shamir heuristic y, z, err := calcyz(capV, proof.capA, proof.capS, transcript, verifier.curve) if err != nil { return false, errors.Wrap(err, "rangeproof verify") } x, err := calcx(proof.capT1, proof.capT2, transcript, verifier.curve) if err != nil { return false, errors.Wrap(err, "rangeproof verify") } wBytes := transcript.ExtractBytes([]byte("getw"), 64) w, err := verifier.curve.NewScalar().SetBytesWide(wBytes) if err != nil { return false, errors.Wrap(err, "rangeproof prove") } // Calc delta(y,z) deltayz, err := deltayz(y, z, n, verifier.curve) if err != nil { return false, errors.Wrap(err, "rangeproof verify") } // Check tHat: L65, pg20 tHatIsValid := verifier.checktHat(proof, capV, proofGenerators.g, proofGenerators.h, deltayz, x, z) if !tHatIsValid { return false, errors.New("rangeproof verify tHat is invalid") } // Verify IPP hPrime, err := gethPrime(proofH, y, verifier.curve) if err != nil { return false, errors.Wrap(err, "rangeproof verify") } capPhmu, err := getPhmu(proofG, hPrime, proofGenerators.h, proof.capA, proof.capS, x, y, z, proof.mu, n, verifier.curve) if err != nil { return false, errors.Wrap(err, "rangeproof verify") } ippVerified, err := verifier.ippVerifier.VerifyFromRangeProof(proofG, hPrime, capPhmu, proofGenerators.u.Mul(w), proof.tHat, proof.ipp, transcript) if err != nil { return false, errors.Wrap(err, "rangeproof verify") } return ippVerified, nil } // L65, pg20. func (*RangeVerifier) checktHat(proof *RangeProof, capV, g, h curves.Point, deltayz, x, z curves.Scalar) bool { // g^tHat * h^tau_x gtHat := g.Mul(proof.tHat) htaux := h.Mul(proof.taux) lhs := gtHat.Add(htaux) // V^z^2 * g^delta(y,z) * Tau_1^x * Tau_2^x^2 capVzsquare := capV.Mul(z.Square()) gdeltayz := g.Mul(deltayz) capTau1x := proof.capT1.Mul(x) capTau2xsquare := proof.capT2.Mul(x.Square()) rhs := capVzsquare.Add(gdeltayz).Add(capTau1x).Add(capTau2xsquare) // Compare lhs =? rhs return lhs.Equal(rhs) } // gethPrime calculates new h prime generators as defined in L64 on pg20. func gethPrime(h []curves.Point, y curves.Scalar, curve curves.Curve) ([]curves.Point, error) { hPrime := make([]curves.Point, len(h)) yInv, err := y.Invert() yInvn := getknVector(yInv, len(h), curve) if err != nil { return nil, errors.Wrap(err, "gethPrime") } for i, hElem := range h { hPrime[i] = hElem.Mul(yInvn[i]) } return hPrime, nil } // Obtain P used for IPP verification // See L67 on pg20 // Note P on L66 includes blinding factor hmu, this method removes that factor. func getPhmu(proofG, proofHPrime []curves.Point, h, capA, capS curves.Point, x, y, z, mu curves.Scalar, n int, curve curves.Curve) (curves.Point, error) { // h'^(z*y^n + z^2*2^n) zyn := multiplyScalarToScalarVector(z, getknVector(y, n, curve)) zsquaretwon := multiplyScalarToScalarVector(z.Square(), get2nVector(n, curve)) elemLastExponent, err := addPairwiseScalarVectors(zyn, zsquaretwon) if err != nil { return nil, errors.Wrap(err, "getPhmu") } lastElem := curve.Point.SumOfProducts(proofHPrime, elemLastExponent) // S^x capSx := capS.Mul(x) // g^-z --> -z*<1,g> onen := get1nVector(n, curve) zNeg := z.Neg() zinvonen := multiplyScalarToScalarVector(zNeg, onen) zgdotonen := curve.Point.SumOfProducts(proofG, zinvonen) // L66 on pg20 P := capA.Add(capSx).Add(zgdotonen).Add(lastElem) hmu := h.Mul(mu) Phmu := P.Sub(hmu) return Phmu, nil } // Delta function for delta(y,z), See (39) on pg18. func deltayz(y, z curves.Scalar, n int, curve curves.Curve) (curves.Scalar, error) { // z - z^2 zMinuszsquare := z.Sub(z.Square()) // 1^n onen := get1nVector(n, curve) // <1^n, y^n> onendotyn, err := innerProduct(onen, getknVector(y, n, curve)) if err != nil { return nil, errors.Wrap(err, "deltayz") } // (z - z^2)*<1^n, y^n> termFirst := zMinuszsquare.Mul(onendotyn) // <1^n, 2^n> onendottwon, err := innerProduct(onen, get2nVector(n, curve)) if err != nil { return nil, errors.Wrap(err, "deltayz") } // z^3*<1^n, 2^n> termSecond := z.Cube().Mul(onendottwon) // (z - z^2)*<1^n, y^n> - z^3*<1^n, 2^n> out := termFirst.Sub(termSecond) return out, nil }
pkg/bulletproof/range_verifier.go
0.821474
0.457621
range_verifier.go
starcoder
package gridlocator import ( "math" "strconv" "strings" "github.com/pkg/errors" ) // Convert converts the specified decimanl longitude and latitude into the six // digit Maidenhead grid locator. func Convert(latitude, longitude float64) (string, error) { lat := latitude + 90 lng := longitude + 180 // Field lat = (lat / 10) // + 0.0000001; lng = (lng / 20) // + 0.0000001; val, err := upperN2L(int(math.Floor(lng))) if err != nil { return "", errors.Wrap(err, "field longitude") } locator := val val, err = upperN2L(int(math.Floor(lat))) if err != nil { return "", errors.Wrap(err, "field latitude") } locator += val // Square lat = 10 * (lat - math.Floor(lat)) lng = 10 * (lng - math.Floor(lng)) locator += strconv.Itoa(int(math.Floor(lng))) locator += strconv.Itoa(int(math.Floor(lat))) // Subsquare lat = 24 * (lat - math.Floor(lat)) lng = 24 * (lng - math.Floor(lng)) val, err = n2l(int(math.Floor(lng))) if err != nil { return "", errors.Wrap(err, "subsquare longitude") } locator += val val, err = n2l(int(math.Floor(lat))) if err != nil { return "", errors.Wrap(err, "subsquare latitude") } locator += val return locator, nil } // ConvertGridLocation converts a string grid location into latitude and longitude. func ConvertGridLocation(location string) (float64, float64, error) { if len(location) != 4 && len(location) != 6 { return 0, 0, errors.New("grid location must be either 4 or 6 digits") } location = strings.ToLower(location) //lng = (($l[0] * 20) + ($l[2] * 2) + ($l[4]/12) - 180); l := make([]int, 6) // Field var err error l[0], err = l2n(string(location[0])) if err != nil { return 0, 0, errors.Wrap(err, "longitude field value") } l[1], err = l2n(string(location[1])) if err != nil { return 0, 0, errors.Wrap(err, "latitude field value") } // Square val, err := strconv.ParseInt(string(location[2]), 10, 64) if err != nil { return 0, 0, errors.Wrap(err, "longitude sqare value") } l[2] = int(val) val, err = strconv.ParseInt(string(location[3]), 10, 64) if err != nil { return 0, 0, errors.Wrap(err, "latitude sqare value") } l[3] = int(val) if len(location) == 6 { // Subsquare l[4], err = l2n(string(location[4])) if err != nil { return 0, 0, errors.Wrap(err, "longitude subsquare value") } l[5], err = l2n(string(location[5])) if err != nil { return 0, 0, errors.Wrap(err, "latitude subsquare value") } } long := (float64(l[0]) * 20) + (float64(l[2]) * 2) + (float64(l[4]) / 12) - 180 lat := (float64(l[1]) * 10) + float64(l[3]) + (float64(l[5]) / 24) - 90 return lat, long, nil } var num2let = []string{ `a`, `b`, `c`, `d`, `e`, `f`, `g`, `h`, `i`, `j`, `k`, `l`, `m`, `n`, `o`, `p`, `q`, `r`, `s`, `t`, `u`, `v`, `w`, `x`, } func n2l(number int) (string, error) { if number > (len(num2let) - 1) { return "", errors.New("number out of bounds") } return num2let[number], nil } func upperN2L(number int) (string, error) { val, err := n2l(number) return strings.ToUpper(val), err } var let2num = map[string]int{ `a`: 0, `b`: 1, `c`: 2, `d`: 3, `e`: 4, `f`: 5, `g`: 6, `h`: 7, `i`: 8, `j`: 9, `k`: 10, `l`: 11, `m`: 12, `n`: 13, `o`: 14, `p`: 15, `q`: 16, `r`: 17, `s`: 18, `t`: 19, `u`: 20, `v`: 21, `w`: 22, `x`: 23, } func l2n(letter string) (int, error) { val, ok := let2num[letter] if !ok { return 0, errors.New("illegal character") } return val, nil }
grid.go
0.685107
0.434701
grid.go
starcoder
package state import "strings" // ASCIIToLower is a casemapping helper which will lowercase a rune as // described by the "ascii" CASEMAPPING setting. func ASCIIToLower(r rune) rune { // "ascii": The ASCII characters 97 to 122 (decimal) are // defined as the lower-case characters of ASCII 65 to 90 // (decimal). No other character equivalency is defined. if r >= 65 && r <= 90 { return r + 32 } return r } // ASCIIToUpper is a casemapping helper which will uppercase a rune as // described by the "ascii" CASEMAPPING setting. func ASCIIToUpper(r rune) rune { if r >= 97 && r <= 122 { return r - 32 } return r } // StrictRFC1459ToLower is a casemapping helper which will lowercase a // rune as described by the "strict-rfc1459" CASEMAPPING setting. func StrictRFC1459ToLower(r rune) rune { // "strict-rfc1459": The ASCII characters 97 to 125 (decimal) are // defined as the lower-case characters of ASCII 65 to 93 (decimal). // No other character equivalency is defined. if r >= 65 && r <= 93 { return r + 32 } return r } // StrictRFC1459ToUpper is a casemapping helper which will uppercase a // rune as described by the "strict-rfc1459" CASEMAPPING setting. func StrictRFC1459ToUpper(r rune) rune { if r >= 97 && r <= 125 { return r - 32 } return r } // RFC1459ToLower is a casemapping helper which will lowercase a rune // as described by the "rfc1459" CASEMAPPING setting. func RFC1459ToLower(r rune) rune { // "rfc1459": The ASCII characters 97 to 126 (decimal) are defined as // the lower-case characters of ASCII 65 to 94 (decimal). No other // character equivalency is defined. if r >= 65 && r <= 94 { return r + 32 } return r } // RFC1459ToUpper is a casemapping helper which will uppercase a rune // as described by the "rfc1459" CASEMAPPING setting. func RFC1459ToUpper(r rune) rune { if r >= 97 && r <= 126 { return r - 32 } return r } // Normalize is mostly an internal function which provides a // normalized name based on the CASEMAPPING setting given by the // server. Generally ToLower or ToUpper should be used. func (s *State) Normalize(name string) string { return s.ToLower(name) } // ToLower takes the given string and lower cases it based on the // current CASEMAPPING setting given by the server. func (s *State) ToLower(name string) string { switch *s.ISupport("CASEMAPPING") { case "ascii": return strings.Map(ASCIIToLower, name) case "strict-rfc1459": return strings.Map(StrictRFC1459ToLower, name) } return strings.Map(RFC1459ToLower, name) } // ToUpper takes the given string and upper cases it based on the // current CASEMAPPING setting given by the server. func (s *State) ToUpper(name string) string { switch *s.ISupport("CASEMAPPING") { case "ascii": return strings.Map(ASCIIToUpper, name) case "strict-rfc1459": return strings.Map(StrictRFC1459ToUpper, name) } return strings.Map(RFC1459ToUpper, name) }
casemapping.go
0.644113
0.451689
casemapping.go
starcoder
package rtp // Convenience functions for dealing with RTP packet formats. For example, the // first byte of the RTP packet header: // 0 1 2 3 4 5 6 7 // +-+-+-+-+-+-+-+-+ // |V=2|P|X| CC | // +-+-+-+-+-+-+-+-+ // can be parsed with // V, P, X, CC := splitByte2114(header[0]) // and put back together with // header[0] = joinByte2114(V, P, X, CC) // 0 1 2 3 4 5 6 7 // a a b c d d d d func splitByte2114(v byte) (a2 byte, b1 bool, c1 bool, d4 byte) { a2 = v >> 6 b1 = ((v >> 5) & 0x01) == 1 c1 = ((v >> 4) & 0x01) == 1 d4 = v & 0x0f return } // Inverse of splitByte2114. func joinByte2114(a2 byte, b1 bool, c1 bool, d4 byte) byte { v := (a2 << 6) | (d4 & 0x0f) if b1 { v |= 0x20 } if c1 { v |= 0x10 } return byte(v) } // Split a byte into the first 2 bits, the next bit, and the remaining 5 bits. func splitByte215(v byte) (a2 byte, b1 bool, c5 byte) { a2 = v >> 6 b1 = ((v >> 5) & 0x01) == 1 c5 = v & 0x1f return } func joinByte215(a2 byte, b1 bool, c5 byte) byte { v := (a2 << 6) | (c5 & 0x1f) if b1 { v |= 0x20 } return v } // Split a byte into the first bit, the next 2 bits, and the remaining 5 bits. func splitByte125(v byte) (a1 bool, b2 byte, c5 byte) { a1 = (v >> 7 & 0x01) == 1 b2 = v >> 5 & 0x11 c5 = v & 0x1f return } func joinByte125(a1 bool, b2 byte, c5 byte) byte { v := (b2 & 0x11 << 5) | (c5 & 0x1f) if a1 { v |= 0x80 } return v } // Split a byte into the first bit and the remaining 7 bits. // E.g. for the second byte of the RTP packet header: // 0 1 2 3 4 5 6 7 // +-+-+-+-+-+-+-+-+ // |M| PT | // +-+-+-+-+-+-+-+-+ func splitByte17(v byte) (a1 bool, b7 byte) { a1 = (v >> 7) == 1 b7 = v & 0x7f return } func joinByte17(b1 bool, b7 byte) byte { v := b7 & 0x7f if b1 { v |= 0x80 } return byte(v) } // Truncate a 64-bit value to its lowest n bits. func trunc(v uint64, n uint8) uint64 { return v & ((1 << n) - 1) } // XOR the bytes of a buffer with the given value. func xor32(buf []byte, v uint32) { buf[0] ^= byte(v >> 24) buf[1] ^= byte(v >> 16) buf[2] ^= byte(v >> 8) buf[3] ^= byte(v) } // XOR the bytes of a buffer with the given value. func xor64(buf []byte, v uint64) { xor32(buf[0:4], uint32(v>>32)) xor32(buf[4:8], uint32(v)) } // Zero out bytes in a slice. The compiler will optimize this down to a single // `memclr` operation (https://github.com/golang/go/issues/5373). func clearBytes(b []byte) { for i := range b { b[i] = 0 } } // Pad a byte slice with zeros on the right, up to the desired size. // See https://github.com/golang/go/wiki/SliceTricks#extend func padRight(b []byte, desiredSize int) []byte { n := len(b) if n < desiredSize { b = append(b, make([]byte, desiredSize-n)...) } return b }
internal/rtp/util.go
0.683736
0.628037
util.go
starcoder
package game import ( "errors" "fmt" ) // gridSize standard tic-tac-toe sized grid (demonstrates Go constants) const gridSize int = 3 // *Row are navegational indexes within Grid const ( topRow = iota midRow botRow ) // *Column are navegational indexes within Grid (demonstrates Go enums) const ( leftColumn = iota midColumn rightColumn ) // Coordinate value representation of the tic-tac-toe grid as a coordinate pair (demonstrates exported type) type Coordinate struct { column int row int } // Grid represents the 2D array for the tic-tac-toe game (demonstrates struc definitions with Go array) type Grid struct { top, mid, bot [gridSize]rune } // Unexported interface represents the functionality of type Grid (demonstrate unexported type interface) type grid interface { RenderGrid(g *Grid) insertAtCoordinate(c Coordinate, symbol rune) (bool, error) getCellValue(c Coordinate) (rune, error) isCellBlank(c Coordinate) bool } // constructor for type Grid func newGrid() *Grid { return &Grid{ top: [gridSize]rune{}, mid: [gridSize]rune{}, bot: [gridSize]rune{}, } } // RenderGrid prints to standard out the tic-tac-toe grid (demonstrates exported function) func RenderGrid(g *Grid) { fmt.Printf("|-00-|-01-|-02-|\n") fmt.Printf("| %s | %s | %s |\n", string(g.top[leftColumn]), string(g.top[midColumn]), string(g.top[rightColumn])) fmt.Printf("|-10-|-11-|-12-|\n") fmt.Printf("| %s | %s | %s |\n", string(g.mid[leftColumn]), string(g.mid[midColumn]), string(g.mid[rightColumn])) fmt.Printf("|-20-|-21-|-22-|\n") fmt.Printf("| %s | %s | %s |\n", string(g.bot[leftColumn]), string(g.bot[midColumn]), string(g.bot[rightColumn])) fmt.Printf("|-EG-|-EG-|-EG-|\n") } // isCellBlank determines if a cell in the grid is empty (demonstrates type method with receiver value) func (grid Grid) isCellBlank(c Coordinate) bool { switch c.row { case topRow: return grid.top[c.column] == 0 case midRow: return grid.mid[c.column] == 0 case botRow: return grid.bot[c.column] == 0 default: return false } } // insertAtCoordinate inserts the symbol(rune) into the valid c(Coordinate) within grid(Grid) // (demonstrates error handling, input validation, and multi-value return, adress references) func (grid *Grid) insertAtCoordinate(c Coordinate, symbol rune) (bool, error) { if c.row >= gridSize && c.row < 0 || c.column >= gridSize && c.column < 0 { return false, errors.New("row or column in coordinate specified is out of bounds for array[gridSize]") } switch c.row { case topRow: grid.top[c.column] = symbol case midRow: grid.mid[c.column] = symbol case botRow: grid.bot[c.column] = symbol default: return false, errors.New("could not assign symbol to grid") } return true, nil } func (grid Grid) getCellValue(c Coordinate) (rune, error) { if c.row >= gridSize && c.row < 0 || c.column >= gridSize && c.column < 0 { return 0, errors.New("row or column in coordinate specified is out of bounds for array[gridSize]") } switch c.row { case topRow: return grid.top[c.column], nil case midRow: return grid.mid[c.column], nil case botRow: return grid.bot[c.column], nil default: return 0, errors.New("something went wrong") } }
tictactoe/game/grid.go
0.793066
0.517754
grid.go
starcoder
package isodates import ( "errors" "time" ) // ParseMonthDay accepts an ISO-formatted month/day string (e.g. "--04-01" is April, 1) and returns the // month and day that it represents. func ParseMonthDay(input string) (time.Month, int, error) { var monthText, dayText string inputLength := len(input) switch { // All valid inputs are between 5 and 7 chars: "--3-1", "--03-1", "--03-01" case inputLength < 5 || inputLength > 7: return time.Month(0), 0, errors.New("invalid iso month/day: " + input) // Month not padded: e.g. "--3-27", "--3-05", or "--3-5" case input[3] == '-': monthText = input[2:3] dayText = input[4:] // Month *is* padded: e.g. "--03-27", "--03-05", or "--03-5" case input[4] == '-': monthText = input[2:4] dayText = input[5:] default: return time.Month(0), 0, errors.New("invalid iso month/day: " + input) } month, err := parseMonth(monthText) if err != nil { return ZeroMonth, 0, err } day, err := parseDayOfMonth(dayText) if err != nil { return ZeroMonth, 0, err } // You have a potential for something like January 32nd which is actually Feb 1st. if day > 28 { d := time.Date(2000, time.Month(month), int(day), 0, 0, 0, 0, time.UTC) return d.Month(), d.Day(), nil } return time.Month(month), int(day), nil } // ParseMonthDayStart parses the month/day string (e.g. "--12-24") and returns a date/time at // midnight in the specified year. The resulting timestamp will be in UTC. func ParseMonthDayStart(input string, year int) (time.Time, error) { return ParseMonthDayStartIn(input, year, time.UTC) } // ParseMonthDayStartIn parses the month/day string (e.g. "--12-24") and returns a date/time at // midnight in the specified year. The resulting timestamp will be in specified time zone. func ParseMonthDayStartIn(input string, year int, loc *time.Location) (time.Time, error) { if loc == nil { return ZeroTime, errors.New("parse month day start: nil location") } month, day, err := ParseMonthDay(input) if err != nil { return ZeroTime, err } return Midnight(year, month, day, loc), nil } // ParseMonthDayEnd parses the month/day string (e.g. "--12-24") and returns a date/time at // 11:59:59pm in the specified year. The resulting timestamp will be in UTC. func ParseMonthDayEnd(input string, year int) (time.Time, error) { return ParseMonthDayEndIn(input, year, time.UTC) } // ParseMonthDayEndIn parses the month/day string (e.g. "--12-24") and returns a date/time at // 11:59:59pm in the specified year. The resulting timestamp will be in the specified time zone. func ParseMonthDayEndIn(input string, year int, loc *time.Location) (time.Time, error) { if loc == nil { return ZeroTime, errors.New("parse month day end: nil location") } month, day, err := ParseMonthDay(input) if err != nil { return ZeroTime, err } return AlmostMidnight(year, month, day, loc), nil }
month_day.go
0.75985
0.51879
month_day.go
starcoder
package Projector import ( "image" "image/color" ) type Sampler2D struct { numChannels int stride int pixData []byte } func MakeSampler2D(img image.Image) *Sampler2D { o := &Sampler2D{} switch v := img.(type) { case *image.RGBA: o.numChannels = 4 o.pixData = v.Pix o.stride = v.Stride case *image.Gray: o.numChannels = 1 o.pixData = v.Pix o.stride = v.Stride default: panic("image type not supported") } return o } func (s *Sampler2D) GetPixelGray(x, y float64) color.Gray { return color.Gray{ Y: BilinearInterp(s.pixData, x, y, s.stride, s.numChannels, 0), } } func (s *Sampler2D) GetPixel(x, y float64) color.Color { var r, g, b, a byte if x < 0 || y < 0 { return color.Black } r = BilinearInterp(s.pixData, x, y, s.stride, s.numChannels, 0) a = 255 switch s.numChannels { case 1: g = r b = r case 3: g = BilinearInterp(s.pixData, x, y, s.stride, s.numChannels, 1) b = BilinearInterp(s.pixData, x, y, s.stride, s.numChannels, 2) case 4: g = BilinearInterp(s.pixData, x, y, s.stride, s.numChannels, 1) b = BilinearInterp(s.pixData, x, y, s.stride, s.numChannels, 2) a = BilinearInterp(s.pixData, x, y, s.stride, s.numChannels, 3) } return color.RGBA{ R: r, G: g, B: b, A: a, } } func BilinearInterp(data []byte, x, y float64, mw int, numChannels, colorChannel int) byte { rx := int(x) ry := int(y) fracX := x - float64(rx) fracY := y - float64(ry) if fracX == 0 && fracY == 0 { // Integer amount return valueAtImage(data, rx, ry, mw, numChannels, colorChannel) } invFracX := 1 - fracX invFracY := 1 - fracY a := valueAtImageF(data, rx, ry, mw, numChannels, colorChannel) b := valueAtImageF(data, rx+1, ry, mw, numChannels, colorChannel) c := valueAtImageF(data, rx, ry+1, mw, numChannels, colorChannel) d := valueAtImageF(data, rx+1, ry+1, mw, numChannels, colorChannel) v := (a*invFracX+b*fracX)*invFracY + (c*invFracX+d*fracX)*fracY return byte(v) } func valueAtImageF(data []byte, x, y, mw, numChannels, colorChannel int) float64 { return float64(valueAtImage(data, x, y, mw, numChannels, colorChannel)) } func valueAtImage(data []byte, x, y, mw, numChannels, colorChannel int) byte { px := y*mw + x*numChannels + colorChannel if px >= len(data) { return 0 } return data[px] }
ImageProcessor/Projector/Sampler.go
0.760206
0.542015
Sampler.go
starcoder
package main import ( "fmt" "path/filepath" "github.com/derWhity/AdventOfCode/lib/input" ) // grid represents a 3-dimensional grid of cube states type grid map[int]map[int]map[int]map[int]bool func (g grid) set(x, y, z, w int, val bool) { yGrid, ok := g[x] if !ok { yGrid = map[int]map[int]map[int]bool{} g[x] = yGrid } zGrid, ok := yGrid[y] if !ok { zGrid = map[int]map[int]bool{} yGrid[y] = zGrid } wGrid, ok := zGrid[z] if !ok { wGrid = map[int]bool{} zGrid[z] = wGrid } wGrid[w] = val } func (g grid) get(x, y, z, w int) bool { yGrid, ok := g[x] if !ok { return false } zGrid, ok := yGrid[y] if !ok { return false } wGrid, ok := zGrid[z] if !ok { return false } return wGrid[w] } // determineNewState calculates the new state the given cube will have func (g grid) determineNewStateAt(xPos, yPos, zPos, wPos int) bool { var activeNeighbours uint for x := xPos - 1; x <= xPos+1; x++ { for y := yPos - 1; y <= yPos+1; y++ { for z := zPos - 1; z <= zPos+1; z++ { for w := wPos - 1; w <= wPos+1; w++ { if (x != xPos || y != yPos || z != zPos || w != wPos) && g.get(x, y, z, w) { activeNeighbours++ } } } } } selfActive := g.get(xPos, yPos, zPos, wPos) if selfActive { return activeNeighbours == 2 || activeNeighbours == 3 } return activeNeighbours == 3 } func failOnError(err error) { if err != nil { panic(err) } } func main() { items, err := input.ReadString(filepath.Join("..", "input.txt"), true) failOnError(err) pocketDimension := grid{} // Three vectors scanCube := [][]int{ {-1, 1}, // X - from, to {-1, 1}, // Y - from, to {-1, 1}, // Z - from, to {-1, 1}, // W - from, to } for x, line := range items { for y, value := range line { pocketDimension.set(x, y, 0, 0, value == '#') scanCube[1][1]++ } scanCube[0][1]++ } for i := 0; i < 6; i++ { newDimentionState := grid{} // Iterate through the rounds for x := scanCube[0][0]; x <= scanCube[1][1]; x++ { for y := scanCube[1][0]; y <= scanCube[1][1]; y++ { for z := scanCube[2][0]; z <= scanCube[2][1]; z++ { for w := scanCube[3][0]; w <= scanCube[3][1]; w++ { newDimentionState.set(x, y, z, w, pocketDimension.determineNewStateAt(x, y, z, w)) } } } } pocketDimension = newDimentionState // Grow the scan cube by 1 in each direction scanCube[0][0]-- scanCube[1][0]-- scanCube[2][0]-- scanCube[3][0]-- scanCube[0][1]++ scanCube[1][1]++ scanCube[2][1]++ scanCube[3][1]++ // Finally, count the active cubes var sumCubes uint for _, yGrid := range pocketDimension { for _, zGrid := range yGrid { for _, wGrid := range zGrid { for _, val := range wGrid { if val { sumCubes++ } } } } } fmt.Printf("Iteration #%d: Number of active cubes: %d\n", i, sumCubes) } }
2020/day_17/star_02/main.go
0.546496
0.48688
main.go
starcoder
package precond import ( "errors" "fmt" "strconv" ) // IllegalArgumentError indicates that a function has been passed an illegal or inappropriate argument. type IllegalArgumentError struct { msg string } func (e *IllegalArgumentError) Error() string { return e.msg } // IllegalStateError signals that a function has been invoked at an illegal or inappropriate time. type IllegalStateError struct { msg string } func (e *IllegalStateError) Error() string { return e.msg } // IndexOutOfBoundsError indicates that an index of some sort (such as to an array or to a string) is out of range. type IndexOutOfBoundsError struct { index int size int desc string args []interface{} msgFun func(int, int, string, ...interface{}) string } func (e *IndexOutOfBoundsError) Error() string { return e.msgFun(e.index, e.size, e.desc, e.args...) } // NilError indicates when an application attempts to use nil in a case where an object is required. type NilError struct { msg string } func (e *NilError) Error() string { return e.msg } // CheckArgument ensures the truth of an expression involving one or more parameters to the calling method. func CheckArgument(expr bool) error { return CheckArgumentf(expr, "invalid argument") } // CheckArgumentf ensures the truth of an expression involving one or more parameters to the calling method. func CheckArgumentf(expr bool, desc string, args ...interface{}) error { if !expr { return &IllegalArgumentError{fmt.Sprintf(desc, args...)} } return nil } // CheckState ensures the truth of an expression involving the state of the calling instance, but not involving any // parameters to the calling method. func CheckState(expr bool) error { return CheckStatef(expr, "illegal state") } // CheckStatef ensures the truth of an expression involving the state of the calling instance, but not involving any // parameters to the calling method. func CheckStatef(expr bool, desc string, args ...interface{}) error { if !expr { return &IllegalStateError{fmt.Sprintf(desc, args...)} } return nil } // CheckNotNil ensures that an object passed as a parameter to the calling method is not nil. func CheckNotNil(obj interface{}) (interface{}, error) { return CheckNotNilf(obj, "") } // CheckNotNilf ensures that an object passed as a parameter to the calling method is not nil. func CheckNotNilf(obj interface{}, desc string, args ...interface{}) (interface{}, error) { if obj == nil { return nil, &NilError{fmt.Sprintf(desc, args...)} } return obj, nil } // CheckElementIndex ensures that index specifies a valid element in an array or string of the given size. // An element index may range from zero, inclusive, to size, exclusive. func CheckElementIndex(index, size int) (int, error) { return CheckElementIndexf(index, size, "index") } // CheckElementIndexf ensures that index specifies a valid element in an array or string of the given size. // An element index may range from zero, inclusive, to size, exclusive. func CheckElementIndexf(index, size int, desc string, args ...interface{}) (int, error) { if index < 0 || index >= size { return -1, &IndexOutOfBoundsError{index, size, desc, args, badElementIndex} } return index, nil } // CheckPositionIndex ensures that index specifies a valid position in an array, list or string of the given size. // A position index may range from zero to size, inclusive. func CheckPositionIndex(index, size int) (int, error) { return CheckPositionIndexf(index, size, "index") } // CheckPositionIndexf ensures that index specifies a valid position in an array, list or string of the given size. // A position index may range from zero to size, inclusive. func CheckPositionIndexf(index, size int, desc string, args ...interface{}) (int, error) { if index < 0 || index > size { return -1, &IndexOutOfBoundsError{index, size, desc, args, badPositionIndex} } return index, nil } func badElementIndex(index, size int, desc string, args ...interface{}) string { if args != nil { return fmt.Sprintf(desc, args...) } else if index < 0 { return fmt.Sprintf("%s (%d) must not be negative", desc, index) } else if size < 0 { return "negative size: " + strconv.Itoa(size) } else { // index >= size return fmt.Sprintf("%s (%d) must be less than size (%d)", desc, index, size) } } func badPositionIndex(index, size int, desc string, args ...interface{}) string { if args != nil { return fmt.Sprintf(desc, args...) } else if index < 0 { return fmt.Sprintf("%s (%d) must not be negative", desc, index) } else if size < 0 { return fmt.Sprintf("negative size: " + strconv.Itoa(size)) } else { // index > size return fmt.Sprintf("%s (%d) must not be greater than size (%d)", desc, index, size) } } // CheckNonnegative ensures that value is strictly positive. func CheckNonnegative(value int, name string) (int, error) { if value < 0 { return 0, errors.New(name + " cannot be negative but was: " + strconv.Itoa(value)) } return value, nil } // CheckNonnegative64 ensures that value is strictly positive. func CheckNonnegative64(value int64, name string) (int64, error) { if value < 0 { return 0, errors.New(name + " cannot be negative but was: " + strconv.FormatInt(value, 10)) } return value, nil }
base/precond/preconditions.go
0.818011
0.448366
preconditions.go
starcoder
package segtree import ( "math/bits" "strconv" "strings" ) // TreeFn is an associative operation we would like to maintain results for in the segment tree. // Associative means: f(f(x, y), z) = f(x, f(y, z)). // An example for the sum calculation: func(i, j int) int { return i + j }. type TreeFn func(val1, val2 int) (result int) // SegmentTree can be created and used for any associative function. type SegmentTree struct { tree []int size int // size of original array levels []levelDesc // description for every tree's layer (begin, end, etc) lastCap int // potential maximum size of the last tree layer fn TreeFn // function that will be calculated for segments } // NewSegmentTree creates SegmentTree for the given array and the function. func NewSegmentTree(arr []int, fn TreeFn) *SegmentTree { if len(arr) == 0 { return &SegmentTree{fn: fn} } // find the nearest degree of 2 bigger than len(arr) size := 1 << (bits.Len(uint(len(arr)) - 1)) nodes := make([]int, 2*size-1) levels := make([]levelDesc, bits.Len(uint(size))) levels[len(levels)-1] = levelDesc{ begin: size - 1, end: (size - 1) + len(arr) - 1, } free := size - len(arr) for i := len(levels) - 2; i >= 0; i-- { next := levels[i+1] free /= 2 levels[i] = levelDesc{ begin: next.begin - (1 << i), end: next.begin - free - 1, } } copy(nodes[size-1:], arr) // put original array in the leafs of the SegmentTree for l := len(levels) - 2; l >= 0; l-- { for i := levels[l].begin; i <= levels[l].end; i++ { left := 2*i + 1 right := 2*i + 2 if right > levels[l+1].end { nodes[i] = nodes[left] } else { nodes[i] = fn(nodes[left], nodes[right]) } } } return &SegmentTree{ tree: nodes, size: len(arr), levels: levels, lastCap: size, fn: fn, } } // String prints the segment tree, layer by layer, one layer per line. // First line - is the result of functions 'fn' on the whole array. // Last line - elements of the original array. // If the current node does not correspond to any element of the original array, then it will be '-'. func (t *SegmentTree) String() string { var sb strings.Builder for l, level := range t.levels { for i := level.begin; i <= level.end; i++ { sb.WriteString(strconv.Itoa(t.tree[i])) if i != level.end { sb.WriteRune(' ') } } if l != len(t.levels)-1 { for i := level.end + 1; i < t.levels[l+1].begin; i++ { sb.WriteString(" -") } sb.WriteRune('\n') } } return sb.String() } // Aggregate returns the result of TreeFn function on the given range of indices. // Returns false if indices are incorrect. func (t *SegmentTree) Aggregate(i, j int) (int, bool) { if i < 0 || i >= t.size || j < 0 || j >= t.size || i > j { return 0, false } return t.aggregate(0, segmentRange{i, j}, segmentRange{0, t.lastCap - 1}), true } // Set changes value of element idx and refreshes all tree. // Returns false if idx is out of bounds. func (t *SegmentTree) Set(idx, val int) bool { if idx < 0 || idx >= t.size || len(t.tree) == 0 { return false // wrong index } cur := t.levels[len(t.levels)-1].begin + idx if t.tree[cur] == val { return true // the same value, nothing to do } t.tree[cur] = val for l := len(t.levels) - 2; l >= 0; l-- { cur = (cur - 1) / 2 left := 2*cur + 1 right := 2*cur + 2 if right > t.levels[l+1].end { t.tree[cur] = t.tree[left] } else { t.tree[cur] = t.fn(t.tree[left], t.tree[right]) } } return true } type segmentRange struct { l int r int } // aggregate checks whether the segment is in one of the children, or intersects with both. // fSeg - segment where function 'fn' should be calculated. // treeSeg - ranges of the node. func (t *SegmentTree) aggregate(node int, fSeg, treeSeg segmentRange) int { if fSeg.l == treeSeg.l && fSeg.r == treeSeg.r { return t.tree[node] } left := 2*node + 1 right := 2*node + 2 mid := (treeSeg.l + treeSeg.r) / 2 if fSeg.l <= mid && fSeg.r <= mid { return t.aggregate(left, fSeg, segmentRange{treeSeg.l, mid}) } if fSeg.l > mid && fSeg.r > mid { return t.aggregate(right, fSeg, segmentRange{mid + 1, treeSeg.r}) } return t.fn(t.aggregate(left, segmentRange{fSeg.l, mid}, segmentRange{treeSeg.l, mid}), t.aggregate(right, segmentRange{mid + 1, fSeg.r}, segmentRange{mid + 1, treeSeg.r})) } // levelDesc is description for every segment tree's layer. type levelDesc struct { begin int // index of the first element of this layer in the full tree end int // index of the last actual element of this layer in the full tree }
internal/segtree/segtree.go
0.784608
0.516047
segtree.go
starcoder
package datatype import "fmt" type typeGroup int //go:generate stringer -type=typeGroup const ( GroupBare typeGroup = iota GroupLength GroupWeight GroupTemperature GroupVolume GroupTime GroupCurrency GroupDataSize ) // ConvFunc - function that converts in value to out float. Specific for each datatype pair type ConvFunc func(in float64) float64 // DataType - interface for maintaining datatype units manipulation - converting/displaying/mapping by name type DataType interface { GetConvFunc(DataType) (ConvFunc, error) GetBase() *BaseDataType } // BaseDataType - basic unit info (names, displayName, unit group) type BaseDataType struct { Group typeGroup Names []string DisplayName string } // String - stringer implementation func (b *BaseDataType) String() string { return fmt.Sprintf("%s:%s", b.Group, b.DisplayName) } // SimpleDataType - DataType implementation that for units that could be converted by multyplying on coefficient // it is related to such types as legth, area, volume, weight, etc. type SimpleDataType struct { b *BaseDataType Factor float64 } // GetBase - return basic info(names, displayName, unit group) of datatype unit func (t *SimpleDataType) GetBase() *BaseDataType { return t.b } // GetConvFunc - convert function for SimpleDataType. Finding unit-to-unit coefficient and multyplying on it func (t *SimpleDataType) GetConvFunc(typeTo DataType) (ConvFunc, error) { if t.b.Group == GroupBare { return func(in float64) float64 { return in }, nil } typ, ok := typeTo.(*SimpleDataType) if !ok || t.b.Group != typ.b.Group { return nil, fmt.Errorf("GetConvFunc: incompatible types %#v - %#v", t, typeTo) } return func(in float64) float64 { return in * typ.Factor / t.Factor }, nil } // BareDataType - nil datatype - used for values where it is not specified var BareDataType = &SimpleDataType{b: &BaseDataType{Group: GroupBare}, Factor: 1} // GetType - type lookup by name func (t TypeMap) GetType(name string) (DataType, error) { if dt, ok := t[name]; ok { return dt, nil } return nil, fmt.Errorf("GetType: unknown datatype %q", name) } // initUnits - datatype units initialization by adding them to datatype by name map func (t TypeMap) initUnits(units []DataType) { for _, unit := range units { for _, name := range unit.GetBase().Names { t[name] = unit } } } // TypeMap - all supported datatype by name map type TypeMap map[string]DataType // Init - all avaliable units initialization - adding to TypeMap func Init(currUpdateCh <-chan []byte) TypeMap { var typeMap = make(TypeMap) typeMap.initUnits(lengthTypes) typeMap.initUnits(weightTypes) typeMap.initUnits(volumeTypes) typeMap.initUnits(temperatureTypes) typeMap.initUnits(GetCurrUnits(currUpdateCh)) return typeMap }
frontend/core/datatype/datatype.go
0.620622
0.402069
datatype.go
starcoder
package mist import ( "encoding/gob" "math" "github.com/nlpodyssey/spago/ag" "github.com/nlpodyssey/spago/mat" "github.com/nlpodyssey/spago/mat/float" "github.com/nlpodyssey/spago/nn" ) var _ nn.Model = &Model{} // Model contains the serializable parameters. type Model struct { nn.Module Wx nn.Param `spago:"type:weights"` Wh nn.Param `spago:"type:weights"` B nn.Param `spago:"type:biases"` Wax nn.Param `spago:"type:weights"` Wah nn.Param `spago:"type:weights"` Ba nn.Param `spago:"type:biases"` Wrx nn.Param `spago:"type:weights"` Wrh nn.Param `spago:"type:weights"` Br nn.Param `spago:"type:biases"` NumOfDelays int } // State represent a state of the MIST recurrent network. type State struct { Y ag.Node } func init() { gob.Register(&Model{}) } // New returns a new model with parameters initialized to zeros. func New[T float.DType](in, out, numOfDelays int) *Model { return &Model{ Wx: nn.NewParam(mat.NewEmptyDense[T](out, in)), Wh: nn.NewParam(mat.NewEmptyDense[T](out, out)), B: nn.NewParam(mat.NewEmptyVecDense[T](out)), Wax: nn.NewParam(mat.NewEmptyDense[T](out, in)), Wah: nn.NewParam(mat.NewEmptyDense[T](out, out)), Ba: nn.NewParam(mat.NewEmptyVecDense[T](out)), Wrx: nn.NewParam(mat.NewEmptyDense[T](out, in)), Wrh: nn.NewParam(mat.NewEmptyDense[T](out, out)), Br: nn.NewParam(mat.NewEmptyVecDense[T](out)), NumOfDelays: numOfDelays, } } // Forward performs the forward step for each input node and returns the result. func (m *Model) Forward(xs ...ag.Node) []ag.Node { ys := make([]ag.Node, len(xs)) states := make([]*State, 0) var s *State = nil for i, x := range xs { s = m.Next(states, x) states = append(states, s) ys[i] = s.Y } return ys } // Next performs a single forward step, producing a new state. func (m *Model) Next(states []*State, x ag.Node) (s *State) { s = new(State) var yPrev ag.Node = nil if states != nil { yPrev = states[len(states)-1].Y } a := ag.Softmax(ag.Affine(m.Ba, m.Wax, x, m.Wah, yPrev)) r := ag.Sigmoid(ag.Affine(m.Br, m.Wrx, x, m.Wrh, yPrev)) s.Y = ag.Tanh(ag.Affine(m.B, m.Wx, x, m.Wh, tryProd(r, m.weightHistory(states, a)))) return } func (m *Model) weightHistory(states []*State, a ag.Node) ag.Node { var sum ag.Node n := len(states) for i := 0; i < m.NumOfDelays; i++ { k := int(math.Pow(2.0, float64(i))) // base-2 exponential delay if k <= n { sum = ag.Add(sum, ag.ProdScalar(states[n-k].Y, ag.AtVec(a, i))) } } return sum } // tryProd returns the product if 'a' and 'b' are not nil, otherwise nil func tryProd(a, b ag.Node) ag.Node { if a != nil && b != nil { return ag.Prod(a, b) } return nil }
nn/recurrent/mist/mist.go
0.856902
0.422981
mist.go
starcoder
package main import ( "fmt" "image" "image/color" "math" ) // Lab represents a color in the Lab color space. // See https://en.wikipedia.org/wiki/Lab_color_space#CIELAB type Lab struct { l float32 a float32 b float32 } // NewLab returns a new `Lab` from its components func NewLab(l float32, a float32, b float32) *Lab { return &Lab{ l: l, a: a, b: b, } } type LabCacheRequest struct { Response chan<- *Lab Color color.Color } // A Ranker calculates the difference between two images // by comparing their pixel colors in the Lab color space type Ranker struct { precalculatedImage [][]*Lab } func NewRanker() *Ranker { ranker := new(Ranker) return ranker } // PrecalculateLabs pre-calculates Lab colors for an image to avoid // recomputing them on each comparison func (ranker *Ranker) PrecalculateLabs(image image.Image) { size := image.Bounds().Size() ranker.precalculatedImage = make([][]*Lab, size.X) for x := 0; x < size.X; x++ { column := make([]*Lab, size.Y) for y := 0; y < size.Y; y++ { lab := ranker.getLab(image.At(x, y)) column[y] = lab } ranker.precalculatedImage[x] = column } } func (ranker *Ranker) getLab(clr color.Color) *Lab { r, g, b, _ := clr.RGBA() l, a, b2 := MakeColorRGB(r, g, b).Lab() return NewLab(float32(l), float32(a), float32(b2)) } func (ranker *Ranker) DistanceFromPrecalculatedBounds(image image.Image, boundAreas []Rect, diffMap *DiffMap) (float32, error) { // Keep a cache of color mappings for these images cache := map[uint32]*Lab{} for _, bounds := range boundAreas { left := int(math.Floor(float64(bounds.Left))) if left < 0 { left = 0 } top := int(math.Floor(float64(bounds.Top))) if top < 0 { top = 0 } right := int(math.Ceil(float64(bounds.Right))) if right >= image.Bounds().Size().X { right = image.Bounds().Size().X - 1 } bottom := int(math.Ceil(float64(bounds.Bottom))) if bottom >= image.Bounds().Size().Y { bottom = image.Bounds().Size().Y - 1 } for x := left; x < right; x++ { for y := top; y < bottom; y++ { lab1 := ranker.precalculatedImage[x][y] color2 := image.At(x, y) color2Key := ColorKey(color2) lab2, has := cache[color2Key] if !has { lab2 = ranker.getLab(color2) cache[color2Key] = lab2 } diffMap.SetDiff(x, y, ranker.colorDistance(lab1, lab2)) } } } return diffMap.GetAverageDiff(), nil } func (ranker *Ranker) DistanceFromPrecalculated(image image.Image, diffMap *DiffMap) (float32, error) { bounds := []Rect{ Rect{ Left: 0, Top: 0, Right: float32(image.Bounds().Size().X), Bottom: float32(image.Bounds().Size().Y), }} return ranker.DistanceFromPrecalculatedBounds(image, bounds, diffMap) } // Distance calculates the distance between two images by comparing each pixel // between the images in the Lab color space. func (ranker *Ranker) Distance(image1 image.Image, image2 image.Image) (float32, error) { if image1.Bounds().Size().X != image2.Bounds().Size().X || image1.Bounds().Size().Y != image2.Bounds().Size().Y { return 0, fmt.Errorf("Images are not the same size") } // Keep a cache of color mappings for these images cache := map[uint32]*Lab{} var diff float32 var count float32 for x := 0; x < image1.Bounds().Size().X; x++ { for y := 0; y < image1.Bounds().Size().Y; y++ { color1 := image1.At(x, y) color1Key := ColorKey(color1) lab1, has := cache[color1Key] if !has { lab1 = ranker.getLab(color1) cache[color1Key] = lab1 } color2 := image2.At(x, y) color2Key := ColorKey(color2) lab2, has := cache[color2Key] if !has { lab2 = ranker.getLab(color2) cache[color2Key] = lab2 } diff += ranker.colorDistance(lab1, lab2) count++ } } return diff / count, nil } // Calculates the distance between two colors using the Lab color space func (ranker *Ranker) colorDistance(lab1 *Lab, lab2 *Lab) float32 { lDiff := lab2.l - lab1.l lDiff = lDiff * lDiff aDiff := lab2.a - lab1.a aDiff = aDiff * aDiff bDiff := lab2.b - lab1.b bDiff = bDiff * bDiff return float32(math.Sqrt(float64(lDiff) + float64(aDiff) + float64(bDiff))) }
archive/evolver/ranker.go
0.847889
0.618608
ranker.go
starcoder
package geotiff import "fmt" type GeoTiffTag struct { Name string Code int } func (g GeoTiffTag) String() string { return fmt.Sprintf("Name: %s, Code: %d", g.Name, g.Code) } // Tags (see p. 28-41 of the spec). var tagMap = map[int]GeoTiffTag{ 254: GeoTiffTag{"NewSubFileType", 254}, 256: GeoTiffTag{"ImageWidth", 256}, 257: GeoTiffTag{"ImageLength", 257}, 258: GeoTiffTag{"BitsPerSample", 258}, 259: GeoTiffTag{"Compression", 259}, 262: GeoTiffTag{"PhotometricInterpretation", 262}, 266: GeoTiffTag{"FillOrder", 266}, 269: GeoTiffTag{"DocumentName", 269}, 284: GeoTiffTag{"PlanarConfiguration", 284}, 270: GeoTiffTag{"ImageDescription", 270}, 271: GeoTiffTag{"Make", 271}, 272: GeoTiffTag{"Model", 272}, 273: GeoTiffTag{"StripOffsets", 273}, 274: GeoTiffTag{"Orientation", 274}, 277: GeoTiffTag{"SamplesPerPixel", 277}, 278: GeoTiffTag{"RowsPerStrip", 278}, 279: GeoTiffTag{"StripByteCounts", 279}, 282: GeoTiffTag{"XResolution", 282}, 283: GeoTiffTag{"YResolution", 283}, 296: GeoTiffTag{"ResolutionUnit", 296}, 305: GeoTiffTag{"Software", 305}, 306: GeoTiffTag{"DateTime", 306}, 322: GeoTiffTag{"TileWidth", 322}, 323: GeoTiffTag{"TileLength", 323}, 324: GeoTiffTag{"TileOffsets", 324}, 325: GeoTiffTag{"TileByteCounts", 325}, 317: GeoTiffTag{"Predictor", 317}, 320: GeoTiffTag{"ColorMap", 320}, 338: GeoTiffTag{"ExtraSamples", 338}, 339: GeoTiffTag{"SampleFormat", 339}, 34735: GeoTiffTag{"GeoKeyDirectoryTag", 34735}, 34736: GeoTiffTag{"GeoDoubleParamsTag", 34736}, 34737: GeoTiffTag{"GeoAsciiParamsTag", 34737}, 33550: GeoTiffTag{"ModelPixelScaleTag", 33550}, 33922: GeoTiffTag{"ModelTiepointTag", 33922}, 34264: GeoTiffTag{"ModelTransformationTag", 34264}, 42112: GeoTiffTag{"GDAL_METADATA", 42112}, 42113: GeoTiffTag{"GDAL_NODATA", 42113}, 1024: GeoTiffTag{"GTModelTypeGeoKey", 1024}, 1025: GeoTiffTag{"GTRasterTypeGeoKey", 1025}, 1026: GeoTiffTag{"GTCitationGeoKey", 1026}, 2048: GeoTiffTag{"GeographicTypeGeoKey", 2048}, 2049: GeoTiffTag{"GeogCitationGeoKey", 2049}, 2050: GeoTiffTag{"GeogGeodeticDatumGeoKey", 2050}, 2051: GeoTiffTag{"GeogPrimeMeridianGeoKey", 2051}, 2061: GeoTiffTag{"GeogPrimeMeridianLongGeoKey", 2061}, 2052: GeoTiffTag{"GeogLinearUnitsGeoKey", 2052}, 2053: GeoTiffTag{"GeogLinearUnitSizeGeoKey", 2053}, 2054: GeoTiffTag{"GeogAngularUnitsGeoKey", 2054}, 2055: GeoTiffTag{"GeogAngularUnitSizeGeoKey", 2055}, 2056: GeoTiffTag{"GeogEllipsoidGeoKey", 2056}, 2057: GeoTiffTag{"GeogSemiMajorAxisGeoKey", 2057}, 2058: GeoTiffTag{"GeogSemiMinorAxisGeoKey", 2058}, 2059: GeoTiffTag{"GeogInvFlatteningGeoKey", 2059}, 2060: GeoTiffTag{"GeogAzimuthUnitsGeoKey", 2060}, 3072: GeoTiffTag{"ProjectedCSTypeGeoKey", 3072}, 3073: GeoTiffTag{"PCSCitationGeoKey", 3073}, 3074: GeoTiffTag{"ProjectionGeoKey", 3074}, 3075: GeoTiffTag{"ProjCoordTransGeoKey", 3075}, 3076: GeoTiffTag{"ProjLinearUnitsGeoKey", 3076}, 3077: GeoTiffTag{"ProjLinearUnitSizeGeoKey", 3077}, 3078: GeoTiffTag{"ProjStdParallel1GeoKey", 3078}, 3079: GeoTiffTag{"ProjStdParallel2GeoKey", 3079}, 3080: GeoTiffTag{"ProjNatOriginLongGeoKey", 3080}, 3081: GeoTiffTag{"ProjNatOriginLatGeoKey", 3081}, 3082: GeoTiffTag{"ProjFalseEastingGeoKey", 3082}, 3083: GeoTiffTag{"ProjFalseNorthingGeoKey", 3083}, 3084: GeoTiffTag{"ProjFalseOriginLongGeoKey", 3084}, 3085: GeoTiffTag{"ProjFalseOriginLatGeoKey", 3085}, 3086: GeoTiffTag{"ProjFalseOriginEastingGeoKey", 3086}, 3087: GeoTiffTag{"ProjFalseOriginNorthingGeoKey", 3087}, 3088: GeoTiffTag{"ProjCenterLongGeoKey", 3088}, 3089: GeoTiffTag{"ProjCenterLatGeoKey", 3089}, 3090: GeoTiffTag{"ProjCenterEastingGeoKey", 3090}, 3091: GeoTiffTag{"ProjFalseOriginNorthingGeoKey", 3091}, 3092: GeoTiffTag{"ProjScaleAtNatOriginGeoKey", 3092}, 3093: GeoTiffTag{"ProjScaleAtCenterGeoKey", 3093}, 3094: GeoTiffTag{"ProjAzimuthAngleGeoKey", 3094}, 3095: GeoTiffTag{"ProjStraightVertPoleLongGeoKey", 3095}, 4096: GeoTiffTag{"VerticalCSTypeGeoKey", 4096}, 4097: GeoTiffTag{"VerticalCitationGeoKey", 4097}, 4098: GeoTiffTag{"VerticalDatumGeoKey", 4098}, 4099: GeoTiffTag{"VerticalUnitsGeoKey", 4099}, 50844: GeoTiffTag{"RPCCoefficientTag", 50844}, 34377: GeoTiffTag{"Photoshop", 34377}, }
geospatialfiles/raster/geotiff/tags.go
0.57523
0.515925
tags.go
starcoder
package flag import ( "flag" "fmt" "strings" "github.com/turbinelabs/nonstdlib/arrays/indexof" ) // Strings conforms to the flag.Value and flag.Getter interfaces, and // can be used populate a slice of strings from a flag.Flag. After // command line parsing, the values can be retrieved via the Strings // field. This implementation of flag.Value accepts multiple values // via a single flag (e.g., "-flag=a,b"), via repetition of the flag // (e.g., "-flag=a -flag=b"), or a combination of the two styles. Use // ResetDefault to configure default values or to prepare Strings for // re-use. type Strings struct { // Populated from the command line. Strings []string // All possible values allowed to appear in Strings. An empty // slice means any value is allowed in Strings. AllowedValues []string // Delimiter used to parse the string from the command line. Delimiter string isSet bool } var _ flag.Getter = &Strings{} var _ ConstrainedValue = &Strings{} // NewStrings produces a Strings with the default delimiter (","). func NewStrings() Strings { return Strings{Delimiter: ","} } // NewStringsWithConstraint produces a Strings with a set of allowed // values and the default delimiter (","). func NewStringsWithConstraint(allowedValues ...string) Strings { return Strings{AllowedValues: allowedValues, Delimiter: ","} } // ValidValuesDescription returns a string describing the allowed // values for this Strings. For example: "a", "b", or "c". If this // Strings is unconstrained, it returns an empty string. func (ssv *Strings) ValidValuesDescription() string { return allowedValuesToDescription(ssv.AllowedValues) } // Retrieves the values set on Strings joined by the delimiter. func (ssv *Strings) String() string { return strings.Join(ssv.Strings, ssv.Delimiter) } // ResetDefault resets Strings for use and assigns the given values as // the default value. Any call to Set (e.g., via flag.FlagSet) will // replace these values. Default values are not checked against the // AllowedValues. func (ssv *Strings) ResetDefault(values ...string) { if values == nil { ssv.Strings = []string{} } else { ssv.Strings = values } ssv.isSet = false } // Set sets the current value. The first call (after initialization or // a call to ResetDefault) will replace all current values. Subsequent // calls append values. This allows multiple values to be set with a // single command line flag, or the use of multiple instances of the // flag to append multiple values. func (ssv *Strings) Set(value string) error { parts := strings.Split(value, ssv.Delimiter) disallowed := []string{} i := 0 for i < len(parts) { parts[i] = strings.TrimSpace(parts[i]) if parts[i] == "" { parts = append(parts[0:i], parts[i+1:]...) } else { if len(ssv.AllowedValues) > 0 { if indexof.String(ssv.AllowedValues, parts[i]) == indexof.NotFound { disallowed = append(disallowed, parts[i]) } } i++ } } if len(disallowed) > 0 { return fmt.Errorf( "invalid flag value(s): %s", strings.Join(disallowed, ssv.Delimiter+" "), ) } if ssv.isSet { ssv.Strings = append(ssv.Strings, parts...) } else { ssv.Strings = parts ssv.isSet = true } return nil } // Get retrieves the current value. func (ssv *Strings) Get() interface{} { return ssv.Strings }
vendor/github.com/turbinelabs/nonstdlib/flag/strings.go
0.648244
0.42477
strings.go
starcoder
package ytypes import ( "fmt" "reflect" log "github.com/golang/glog" "github.com/openconfig/goyang/pkg/yang" "github.com/openconfig/ygot/util" ) // Refer to: https://tools.ietf.org/html/rfc6020#section-9.2. var ( // defaultIntegerRange is the default allowed range of values for the key // integer type, if no other range restrictions are specified. defaultIntegerRange = map[yang.TypeKind]yang.YangRange{ yang.Yint8: yang.Int8Range, yang.Yint16: yang.Int16Range, yang.Yint32: yang.Int32Range, yang.Yint64: yang.Int64Range, yang.Yuint8: yang.Uint8Range, yang.Yuint16: yang.Uint16Range, yang.Yuint32: yang.Uint32Range, yang.Yuint64: yang.Uint64Range, } // typeKindFromKind maps the primitive type kinds of Go to the // enumerated TypeKind used in goyang. typeKindFromKind = map[reflect.Kind]yang.TypeKind{ reflect.Int8: yang.Yint8, reflect.Int16: yang.Yint16, reflect.Int32: yang.Yint32, reflect.Int64: yang.Yint64, reflect.Uint8: yang.Yuint8, reflect.Uint16: yang.Yuint16, reflect.Uint32: yang.Yuint32, reflect.Uint64: yang.Yuint64, reflect.Bool: yang.Ybool, reflect.Float64: yang.Ydecimal64, reflect.String: yang.Ystring, } ) // ValidateIntRestrictions checks that the given signed int matches the // schema's range restrictions (if any). It returns an error if the validation // fails. func ValidateIntRestrictions(schemaType *yang.YangType, intVal int64) error { if !isInRanges(schemaType.Range, yang.FromInt(intVal)) { return fmt.Errorf("signed integer value %v is outside specified ranges", intVal) } return nil } // ValidateUintRestrictions checks that the given unsigned int matches the // schema's range restrictions (if any). It returns an error if the validation // fails. func ValidateUintRestrictions(schemaType *yang.YangType, uintVal uint64) error { if !isInRanges(schemaType.Range, yang.FromUint(uintVal)) { return fmt.Errorf("unsigned integer value %v is outside specified ranges", uintVal) } return nil } // validateInt validates value, which must be a Go integer type, against the // given schema. func validateInt(schema *yang.Entry, value interface{}) error { // Check that the schema itself is valid. if err := validateIntSchema(schema); err != nil { return err } util.DbgPrint("validateInt type %s with value %v", util.YangTypeToDebugString(schema.Type), value) kind := schema.Type.Kind // Check that type of value is the type expected from the schema. if typeKindFromKind[reflect.TypeOf(value).Kind()] != kind { return fmt.Errorf("non %v type %T with value %v for schema %s", kind, value, value, schema.Name) } // Check that the value satisfies any range restrictions. if isSigned(kind) { if err := ValidateIntRestrictions(schema.Type, reflect.ValueOf(value).Int()); err != nil { return fmt.Errorf("schema %q: %v", schema.Name, err) } } else { if err := ValidateUintRestrictions(schema.Type, reflect.ValueOf(value).Uint()); err != nil { return fmt.Errorf("schema %q: %v", schema.Name, err) } } return nil } // validateIntSlice validates value, which must be a Go integer slice type, // against the given schema. func validateIntSlice(schema *yang.Entry, value interface{}) error { // Check that the schema itself is valid. if err := validateIntSchema(schema); err != nil { return err } util.DbgPrint("validateIntSlice type %s with value %v", util.YangTypeToDebugString(schema.Type), value) kind := schema.Type.Kind val := reflect.ValueOf(value) // Check that type of value is the type expected from the schema. if val.Kind() != reflect.Slice || yang.TypeKindFromName[reflect.TypeOf(value).Elem().Name()] != kind { return fmt.Errorf("got type %T with value %v, want []%v for schema %s", value, value, kind, schema.Name) } // Each slice element must be valid. for i := 0; i < val.Len(); i++ { if err := validateInt(schema, val.Index(i).Interface()); err != nil { return fmt.Errorf("invalid element at index %d: %v for schema %s", i, err, schema.Name) } } // Each slice element must be unique. // Refer to: https://tools.ietf.org/html/rfc6020#section-7.7. tbl := make(map[yang.Number]bool) for i := 0; i < val.Len(); i++ { v := toNumber(schema, val.Index(i)) if tbl[v] { return fmt.Errorf("duplicate integer: %v for schema %s", v, schema.Name) } tbl[v] = true } return nil } // validateIntSchema validates the given integer type schema. This is a quick // check rather than a comprehensive validation against the RFC. // It is assumed that such a validation is done when the schema is parsed from // source YANG. func validateIntSchema(schema *yang.Entry) error { if schema == nil { return fmt.Errorf("int schema is nil") } if schema.Type == nil { return fmt.Errorf("int schema %s Type is nil", schema.Name) } kind := schema.Type.Kind ranges := schema.Type.Range if !isIntegerType(kind) { return fmt.Errorf("%v is not an integer type for schema %s", kind, schema.Name) } // Ensure ranges have valid value types. for _, r := range ranges { switch { case r.Min.Kind != yang.MinNumber && r.Min.Kind != yang.Positive && r.Min.Kind != yang.Negative: return fmt.Errorf("range %v min must be Positive, Negative or MinNumber for schema %s", r, schema.Name) case r.Max.Kind != yang.MaxNumber && r.Max.Kind != yang.Positive && r.Max.Kind != yang.Negative: return fmt.Errorf("range %v max must be Positive, Negative or MaxNumber for schema %s", r, schema.Name) case !isSigned(kind) && (r.Min.Kind == yang.Negative || r.Max.Kind == yang.Negative): return fmt.Errorf("unsigned int cannot have negative range boundaries %v for schema %s", r, schema.Name) } } // Ensure range values fall within ranges for each type. for _, r := range ranges { if !legalValue(schema, r.Min) { return fmt.Errorf("min value %v for boundary is out of range for type %v for schema %s", r.Min.Value, kind, schema.Name) } if !legalValue(schema, r.Max) { return fmt.Errorf("max value %v for boundary is out of range for type %v for schema %s", r.Max.Value, kind, schema.Name) } } if len(ranges) != 0 { if errs := ranges.Validate(); errs != nil { return errs } } return nil } // legalValue reports whether val is within the range allowed for the given // integer kind. kind must be an integer type. func legalValue(schema *yang.Entry, val yang.Number) bool { if val.Kind == yang.MinNumber || val.Kind == yang.MaxNumber { return true } yr := yang.YangRange{yang.YRange{Min: val, Max: val}} switch schema.Type.Kind { case yang.Yint8: return yang.Int8Range.Contains(yr) case yang.Yint16: return yang.Int16Range.Contains(yr) case yang.Yint32: return yang.Int32Range.Contains(yr) case yang.Yint64: return yang.Int64Range.Contains(yr) case yang.Yuint8: return yang.Uint8Range.Contains(yr) case yang.Yuint16: return yang.Uint16Range.Contains(yr) case yang.Yuint32: return yang.Uint32Range.Contains(yr) case yang.Yuint64: return yang.Uint64Range.Contains(yr) default: log.Errorf("illegal type %v in legalValue", schema.Type.Kind) } return false } // toNumber returns a yang.Number representation of val. func toNumber(schema *yang.Entry, val reflect.Value) yang.Number { if isSigned(schema.Type.Kind) { return yang.FromInt(val.Int()) } return yang.FromUint(val.Uint()) } // isSigned reports whether kind is a signed integer type. func isSigned(kind yang.TypeKind) bool { return kind == yang.Yint8 || kind == yang.Yint16 || kind == yang.Yint32 || kind == yang.Yint64 } // isIntegerType reports whether schema is of an integer type. func isIntegerType(kind yang.TypeKind) bool { switch kind { case yang.Yint8, yang.Yint16, yang.Yint32, yang.Yint64, yang.Yuint8, yang.Yuint16, yang.Yuint32, yang.Yuint64: return true default: } return false }
ytypes/int_type.go
0.672869
0.45423
int_type.go
starcoder
package mappings // ComplianceProfiles mapping used to create the `compliance-profiles` index var ComplianceProfiles = Mapping{ Index: IndexNameProf, Type: DocType, Timeseries: false, Mapping: ` { "template": "` + IndexNameProf + `", "settings": { "index": { "refresh_interval": "1s" }, "analysis": { "analyzer": { "autocomplete": { "tokenizer": "autocomplete_tokenizer", "filter": [ "lowercase" ] } }, "tokenizer": { "autocomplete_tokenizer": { "type": "edge_ngram", "min_gram": 2, "max_gram": 20, "token_chars": [ "letter", "digit" ] } }, "normalizer": { "case_insensitive": { "type": "custom", "char_filter": [], "filter": ["lowercase", "asciifolding"] } } } }, "mappings": { "` + DocType + `": { "properties": { "name": { "type": "keyword", "fields": { "lower": { "normalizer": "case_insensitive", "type": "keyword" } } }, "title": { "type": "keyword", "fields": { "engram": { "type": "text", "analyzer": "autocomplete" }, "lower": { "normalizer": "case_insensitive", "type": "keyword" } } }, "maintainer": { "type": "keyword" }, "copyright": { "type": "keyword" }, "copyright_email": { "type": "keyword" }, "license": { "type": "keyword" }, "summary": { "type": "keyword" }, "version": { "type": "keyword" }, "supports": { "type": "object", "properties": { "os-family": { "type": "keyword" }, "os-name": { "type": "keyword" }, "platform": { "type": "keyword" }, "platform-name": { "type": "keyword" }, "platform-family": { "type": "keyword" }, "release": { "type": "keyword" }, "inspec": { "type": "keyword" } } }, "controls": { "type": "nested", "properties": { "title": { "type": "keyword" }, "desc": { "type": "keyword" }, "description": { "properties": { "label": { "type": "keyword" }, "data": { "type": "keyword" } } }, "impact": { "type": "double" }, "refs": { "type": "keyword" }, "tags": { "type": "keyword" }, "code": { "type": "keyword" }, "source_location": { "type": "object", "properties": { "ref": { "type": "keyword" }, "line": { "type": "integer" } } }, "id": { "type": "keyword", "fields": { "engram": { "type": "text", "analyzer": "autocomplete" }, "lower": { "normalizer": "case_insensitive", "type": "keyword" } } } } }, "groups": { "type": "object", "properties": { "title": { "type": "keyword" }, "controls": { "type": "keyword" }, "id": { "type": "keyword" }, "attributes": { "type": "object", "properties": { "name": { "type": "keyword" }, "options": { "type": "object", "properties": { "default": { "type": "keyword" }, "description": { "type": "keyword" } } } } }, "sha256": { "type": "keyword" } } } } } } } `, }
components/compliance-service/ingest/ingestic/mappings/comp-profiles.go
0.682468
0.421195
comp-profiles.go
starcoder
package utils // APIKind a constant representing the kind of the API model const APIKind = "API" // ApplicationKind a constant to represent the kind of the Application model const ApplicationKind = "Application" // DriverKind a constant representing the kind of the Driver API model const DriverKind = "Driver" // DriverTypeKind a constant representing the kind of the DriverType API model const DriverTypeKind = "DriverType" // SubscriptionKind a constant representing the kind of the Subscription API model const SubscriptionKind = "Subscription" // FunctionKind a constant representing the kind of the Function model const FunctionKind = "Function" // ImageKind a constant representing the kind of the Image model const ImageKind = "Image" // BaseImageKind a constant representing the kind of the Base Image model const BaseImageKind = "BaseImage" // SecretKind a constant representing the kind of the Secret model const SecretKind = "Secret" // PolicyKind a constant representing the kind of the Policy model const PolicyKind = "Policy" // ServiceClassKind a constant representing the kind of the Service Class model const ServiceClassKind = "ServiceClass" // ServicePlanKind a constant representing the kind of the Service Plan model const ServicePlanKind = "ServicePlan" // ServiceInstanceKind a constant representing the kind of the Service Instance model const ServiceInstanceKind = "ServiceInstance" // ServiceBindingKind a constant representing the kind of the Service Binding model const ServiceBindingKind = "ServiceBinding" // ServiceAccountKind a constant representing the kind of the ServiceAccount Model const ServiceAccountKind = "ServiceAccount" // OrganizationKind a constant representing the kind of the Organization Model const OrganizationKind = "Organization" // DefaultAPIHTTPPort a constant representing the default http port for api endpoint const DefaultAPIHTTPPort = 8081 // DefaultAPIHTTPSPort a constant representing the default https port for api endpoint const DefaultAPIHTTPSPort = 8444
vendor/github.com/vmware/dispatch/pkg/utils/constants.go
0.640636
0.562537
constants.go
starcoder
package rwcas import ( "github.com/nagata-yoshiteru/go-vector" ) func init() { } // Agent : type Agent struct { ID int AgentType *AgentType Position vector.Vector PrevVelocity vector.Vector PrefVelocity vector.Vector NextVelocity vector.Vector WallNeighbors []*WallNeighbor ObstacleNeighbors []*ObstacleNeighbor AgentNeighbors []*AgentNeighbor Goal vector.Vector OrcaLines []*Line Status int // 0: created, 1: moving, 2: goal, 3: to be deleted } // AgentType : type AgentType struct { Name string Radius float64 // radius size of agent TimeHorizonAgent float64 TimeHorizonObst float64 TimeHorizonWall float64 MaxNeighbors int NeighborDist float64 MaxSpeed float64 } // WallNeighbor : type WallNeighbor struct { DistSq float64 Wall *Wall } // ObstacleNeighbor : type ObstacleNeighbor struct { DistSq float64 Obstacle *Obstacle } // AgentNeighbor : type AgentNeighbor struct { DistSq float64 Agent *Agent } // Line : type Line struct { Point vector.Vector Direction vector.Vector } // NewAgent : func NewAgent(id int, agentType *AgentType, position vector.Vector, prevVelocity vector.Vector, prefVelocity vector.Vector, goal vector.Vector) *Agent { a := &Agent{ ID: id, AgentType: agentType, Position: position, PrevVelocity: prevVelocity, PrefVelocity: prefVelocity, NextVelocity: vector.NewWithValues([]float64{0.0, 0.0, 0.0}), WallNeighbors: make([]*WallNeighbor, 0), ObstacleNeighbors: make([]*ObstacleNeighbor, 0), AgentNeighbors: make([]*AgentNeighbor, 0), Goal: goal, OrcaLines: make([]*Line, 0), Status: 0, // 0: created, 1: moving, 2: goal, 3: to be deleted } return a } // NewEmptyAgent : func NewEmptyAgent(id int) *Agent { return NewAgent( id, Rwcas.AgentTypes["Default AgentType"], vector.NewWithValues([]float64{0.0, 0.0, 0.0}), // position = (0, 0, 0) vector.NewWithValues([]float64{0.0, 0.0, 0.0}), // prevVelocity = (0, 0, 0) vector.NewWithValues([]float64{0.0, 0.0, 0.0}), // prefVelocity = (0, 0, 0) vector.NewWithValues([]float64{0.0, 0.0, 0.0}), // goal = (0, 0, 0) ) } // IsReachedGoal : func (agent *Agent) IsReachedGoal() bool { /* Check if agent have reached their goals. */ if agent.Status > 1 { return true } if vector.Subtract(agent.Goal, agent.Position).Magnitude() > agent.AgentType.Radius { return false } agent.Status = 2 return true } // GetGoal : func (agent *Agent) GetGoal() vector.Vector { return agent.Goal } // SetGoal : func (agent *Agent) SetGoal(goal vector.Vector) { agent.Goal = goal } // GetAgentType : func (agent *Agent) GetAgentType() *AgentType { return agent.AgentType } // SetAgentType : func (agent *Agent) SetAgentType(agentType *AgentType) { agent.AgentType = agentType } // GetPosition : func (agent *Agent) GetPosition() vector.Vector { return agent.Position } // SetPosition : func (agent *Agent) SetPosition(position vector.Vector) { agent.Position = position } // GetPrevVelocity : func (agent *Agent) GetPrevVelocity() vector.Vector { return agent.PrevVelocity } // SetPrevVelocity : func (agent *Agent) SetPrevVelocity(prevVelocity vector.Vector) { agent.PrevVelocity = prevVelocity } // GetPrefVelocity : func (agent *Agent) GetPrefVelocity() vector.Vector { return agent.PrefVelocity } // SetPrefVelocity : func (agent *Agent) SetPrefVelocity(prefVelocity vector.Vector) { agent.PrefVelocity = prefVelocity } // GetNextVelocity : func (agent *Agent) GetNextVelocity() vector.Vector { return agent.NextVelocity } // SetNextVelocity : func (agent *Agent) SetNextVelocity(nextVelocity vector.Vector) { agent.NextVelocity = nextVelocity } // GetWallNeighbors : func (agent *Agent) GetWallNeighbors() []*WallNeighbor { return agent.WallNeighbors } // SetWallNeighbors : func (agent *Agent) SetWallNeighbors(wallNeighbors []*WallNeighbor) { agent.WallNeighbors = wallNeighbors } // GetObstacleNeighbors : func (agent *Agent) GetObstacleNeighbors() []*ObstacleNeighbor { return agent.ObstacleNeighbors } // SetObstacleNeighbors : func (agent *Agent) SetObstacleNeighbors(obstacleNeighbors []*ObstacleNeighbor) { agent.ObstacleNeighbors = obstacleNeighbors } // GetAgentNeighbors : func (agent *Agent) GetAgentNeighbors() []*AgentNeighbor { return agent.AgentNeighbors } // SetAgentNeighbors : func (agent *Agent) SetAgentNeighbors(agentNeighbors []*AgentNeighbor) { agent.AgentNeighbors = agentNeighbors } // GetStatus : func (agent *Agent) GetStatus() int { return agent.Status } // SetStatus : func (agent *Agent) SetStatus(status int) { agent.Status = status } // GetID : func (agent *Agent) GetID() int { return agent.ID } // GetOrcaLines : func (agent *Agent) GetOrcaLines() []*Line { return agent.OrcaLines } // SetOrcaLines : func (agent *Agent) SetOrcaLines(orcaLines []*Line) { agent.OrcaLines = orcaLines }
src/rwcas/agent.go
0.59843
0.603085
agent.go
starcoder
package field import ( "math/rand" "time" "github.com/hajimehoshi/ebiten/v2" "github.com/kemokemo/kuronan-dash/internal/view" ) // genPosFunc generates the positions to place objects. type genPosFunc func(height int, laneHeights []float64, g genPosSet) []*view.Vector // genPosField generates the positions of objects to be placed on the field. func genPosField(height int, laneHeights []float64, g genPosSet) []*view.Vector { var points []*view.Vector rand.Seed(time.Now().UnixNano()) for _, h := range laneHeights { for index := 0; index < g.amount; index++ { r := rand.Float64() pos := &view.Vector{ X: float64((index+1)*g.randomRough) + float64(g.randomFine)*(1-r), Y: h - float64(height-1), } points = append(points, pos) } } return points } // genPosAir generates the positions of objects to be placed in the air. func genPosAir(h int, laneHeights []float64, g genPosSet) []*view.Vector { var points []*view.Vector rand.Seed(time.Now().UnixNano()) var upperH float64 polarity := -1.0 for _, h := range laneHeights { for index := 0; index < g.amount; index++ { r := rand.Float64() pos := &view.Vector{ X: float64(g.randomRough)*(1.0-r) + float64(g.randomFine)*r, Y: h - (h-upperH)/2 + 45.0*r*polarity, } points = append(points, pos) polarity *= -1.0 } upperH = h } return points } // genParts generates scrollable objects. func genParts(img *ebiten.Image, laneHeights []float64, gpf genPosFunc, gps genPosSet, kv float64) []*Parts { var array []*Parts _, hP := img.Size() points := gpf(hP, laneHeights, gps) for _, point := range points { fp := &Parts{} fp.Initialize(img, point, kv) array = append(array, fp) } return array } // genOnigiri generates onigiri. func genOnigiri(img *ebiten.Image, laneHeights []float64, gpf genPosFunc, gps genPosSet, kv float64) []*Onigiri { var array []*Onigiri _, hP := img.Size() points := gpf(hP, laneHeights, gps) for _, point := range points { oni := &Onigiri{} oni.Initialize(img, point, kv) array = append(array, oni) } return array } // genRocks generates scrollable objects. func genRocks(img *ebiten.Image, laneHeights []float64, gpf genPosFunc, gps genPosSet, kv float64) []*Rock { var array []*Rock _, hP := img.Size() points := gpf(hP, laneHeights, gps) for _, point := range points { r := &Rock{} r.Initialize(img, point, kv) array = append(array, r) } return array } func randBool() bool { rand.Seed(time.Now().UnixNano()) return rand.Intn(2) == 0 }
internal/field/generator.go
0.702326
0.442215
generator.go
starcoder
package service import ( "github.com/bwmarrin/gokrb5/types" "sync" "time" ) /*The server MUST utilize a replay cache to remember any authenticator presented within the allowable clock skew. The replay cache will store at least the server name, along with the client name, time, and microsecond fields from the recently-seen authenticators, and if a matching tuple is found, the KRB_AP_ERR_REPEAT error is returned. Note that the rejection here is restricted to authenticators from the same principal to the same server. Other client principals communicating with the same server principal should not have their authenticators rejected if the time and microsecond fields happen to match some other client's authenticator. If a server loses track of authenticators presented within the allowable clock skew, it MUST reject all requests until the clock skew interval has passed, providing assurance that any lost or replayed authenticators will fall outside the allowable clock skew and can no longer be successfully replayed. If this were not done, an attacker could subvert the authentication by recording the ticket and authenticator sent over the network to a server and replaying them following an event that caused the server to lose track of recently seen authenticators.*/ // Cache for tickets received from clients keyed by fully qualified client name. Used to track replay of tickets. type Cache struct { entries map[string]clientEntries mux sync.RWMutex } // clientEntries holds entries of client details sent to the service. type clientEntries struct { replayMap map[time.Time]replayCacheEntry seqNumber int64 subKey types.EncryptionKey } // Cache entry tracking client time values of tickets sent to the service. type replayCacheEntry struct { presentedTime time.Time sName types.PrincipalName cTime time.Time // This combines the ticket's CTime and Cusec } func (c *Cache) getClientEntries(cname types.PrincipalName) (clientEntries, bool) { c.mux.RLock() defer c.mux.RUnlock() ce, ok := c.entries[cname.PrincipalNameString()] return ce, ok } func (c *Cache) getClientEntry(cname types.PrincipalName, t time.Time) (replayCacheEntry, bool) { if ce, ok := c.getClientEntries(cname); ok { c.mux.RLock() defer c.mux.RUnlock() if e, ok := ce.replayMap[t]; ok { return e, true } } return replayCacheEntry{}, false } // Instance of the ServiceCache. This needs to be a singleton. var replayCache Cache var once sync.Once // GetReplayCache returns a pointer to the Cache singleton. func GetReplayCache(d time.Duration) *Cache { // Create a singleton of the ReplayCache and start a background thread to regularly clean out old entries once.Do(func() { replayCache = Cache{ entries: make(map[string]clientEntries), } go func() { for { // TODO consider using a context here. time.Sleep(d) replayCache.ClearOldEntries(d) } }() }) return &replayCache } // AddEntry adds an entry to the Cache. func (c *Cache) AddEntry(sname types.PrincipalName, a types.Authenticator) { ct := a.CTime.Add(time.Duration(a.Cusec) * time.Microsecond) if ce, ok := c.getClientEntries(a.CName); ok { c.mux.Lock() defer c.mux.Unlock() ce.replayMap[ct] = replayCacheEntry{ presentedTime: time.Now().UTC(), sName: sname, cTime: ct, } ce.seqNumber = a.SeqNumber ce.subKey = a.SubKey } else { c.mux.Lock() defer c.mux.Unlock() c.entries[a.CName.PrincipalNameString()] = clientEntries{ replayMap: map[time.Time]replayCacheEntry{ ct: { presentedTime: time.Now().UTC(), sName: sname, cTime: ct, }, }, seqNumber: a.SeqNumber, subKey: a.SubKey, } } } // ClearOldEntries clears entries from the Cache that are older than the duration provided. func (c *Cache) ClearOldEntries(d time.Duration) { c.mux.Lock() defer c.mux.Unlock() for ke, ce := range c.entries { for k, e := range ce.replayMap { if time.Now().UTC().Sub(e.presentedTime) > d { delete(ce.replayMap, k) } } if len(ce.replayMap) == 0 { delete(c.entries, ke) } } } // IsReplay tests if the Authenticator provided is a replay within the duration defined. If this is not a replay add the entry to the cache for tracking. func (c *Cache) IsReplay(sname types.PrincipalName, a types.Authenticator) bool { ct := a.CTime.Add(time.Duration(a.Cusec) * time.Microsecond) if e, ok := c.getClientEntry(a.CName, ct); ok { if e.sName.Equal(sname) { return true } } c.AddEntry(sname, a) return false }
service/cache.go
0.567218
0.405802
cache.go
starcoder
package CombinationIterator type CombinationIterator struct { characters []byte indexes []int cursor int pointer int start int end int combinationLength int } func Constructor(characters string, combinationLength int) CombinationIterator { indexes := make([]int, 0) for i := 0; i < combinationLength; i++ { indexes = append(indexes, i) } return CombinationIterator{ characters: []byte(characters), indexes: indexes, start: 0, cursor: 1, end: combinationLength - 1, pointer: combinationLength - 1, combinationLength: combinationLength, } } func (this *CombinationIterator) Next() string { res := make([]byte, 0) if len(this.indexes) < this.combinationLength { return string(res) } for i := 0; i < len(this.indexes); i++ { res = append(res, this.characters[this.indexes[i]]) } this.pointer++ if this.pointer >= len(this.characters) { this.end++ this.indexes = make([]int, 0) this.cursor++ if this.end < len(this.characters) { for i := this.start; i <= this.end; i++ { if i != this.start && i < this.cursor { continue } this.indexes = append(this.indexes, i) } } if this.end >= len(this.characters) || len(this.indexes) < this.combinationLength { this.start++ this.end = this.start + this.combinationLength - 1 this.cursor = this.start + 1 this.indexes = make([]int, 0) if this.end < len(this.characters) { for i := this.start; i <= this.end; i++ { this.indexes = append(this.indexes, i) } } } this.pointer = this.end } else if this.pointer < len(this.characters) { this.indexes = this.indexes[:len(this.indexes)-1] this.indexes = append(this.indexes, this.pointer) } else { this.indexes = make([]int, 0) } return string(res) } func (this *CombinationIterator) HasNext() bool { if len(this.indexes) < this.combinationLength { return false } return true } /** * Your CombinationIterator object will be instantiated and called as such: * obj := Constructor(characters, combinationLength); * param_1 := obj.Next(); * param_2 := obj.HasNext(); */
algorithms/5123.IteratorforCombination/CombinationIterator/CombinationIterator.go
0.515864
0.50653
CombinationIterator.go
starcoder
package game import ( tl "github.com/JoelOtter/termloop" ) // PortRow represents a row within the PortMatrix. type PortRow struct { frags []int // represents port address fragments selectable bool // flag for determining if the player can select the row status tl.Attr // represents the state the row is in to the player } // NewPortRow instantiates a PortRow. func NewPortRow(f []int) *PortRow { return &PortRow{frags: f, selectable: true, status: Active} } // Get returns the port fragment found at the given index. func (r PortRow) Get(i int) int { if !(i < r.Len()) { panic("PortRow: overflow error") } return r.frags[i] } // Len returns the number of columns in the row. func (r PortRow) Len() int { return len(r.frags) } func (r PortRow) Selectable() bool { return r.selectable } func (r *PortRow) SetSelectable(s bool) { r.selectable = s } func (r PortRow) Status() tl.Attr { return r.status } func (r *PortRow) SetStatus(s tl.Attr) { r.status = s } // PortMatrix represents the collection of port numbers. type PortMatrix struct { rows []PortRow pwner *Pwner } // NewPortMatrix instantiates a PortMatrix func NewPortMatrix(r []PortRow, p *Pwner) *PortMatrix { return &PortMatrix{rows: r, pwner: p} } // Get returns the row found at the given index. func (m PortMatrix) Get(i int) *PortRow { return &m.rows[i] } // Len returns the number of rows in the PortMatrix. func (m PortMatrix) Len() int { return len(m.rows) } // Update updates the state of the rows in the PortMatrix. func (m *PortMatrix) Update() { for i := 0; i < m.Len(); i++ { row := m.Get(i) if m.IsSelectable(i) { row.SetSelectable(true) row.SetStatus(Active) } else { row.SetSelectable(false) row.SetStatus(Inactive) } } } // IsSelectable determines if the row found with the given index can be selected // by the player. It is not selectable only if we have an element in the // PortRow where its index matches with the Pwner's element, the Pwner's // element has been chosen, and the two elements' fragment values do not equal. func (m PortMatrix) IsSelectable(i int) bool { row := m.Get(i) colLen := row.Len() for j := 0; j < colLen; j++ { pwnerEle := m.pwner.Get(j) if pwnerEle.Status() == Chosen && pwnerEle.Frag() != row.Get(j) { return false } } return true }
internal/game/ports.go
0.724286
0.51879
ports.go
starcoder
package errors import ( "fmt" "io" "strconv" "time" ) // WithFields annotate err with fields. func WithFields(err error) ErrorWithFields { e, ok := err.(*withBuffer) if !ok { e = &withBuffer{ error: err, buf: []byte{}, } } return e } type withBuffer struct { error buf []byte } func (b *withBuffer) Error() string { return b.error.Error() } func (b *withBuffer) Origin() error { return b.error } func (b *withBuffer) Unwrap() error { return b.error } func (b *withBuffer) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { io.WriteString(s, b.error.Error()) io.WriteString(s, "\n") s.Write(b.buf) return } fallthrough case 's': io.WriteString(s, b.error.Error()) case 'q': fmt.Fprintf(s, "%q", b.error.Error()) } } func (b *withBuffer) String(label string, value string) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = append(b.buf, escape(value)...) return b } func (b *withBuffer) Stringer(label string, value fmt.Stringer) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = append(b.buf, escape(value.String())...) b.buf = append(b.buf, '"') return b } func (b *withBuffer) Bytes(label string, value []byte) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = appendHexBytes(b.buf, value) b.buf = append(b.buf, '"') return b } func (b *withBuffer) Byte(label string, value byte) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = appendHexByte(b.buf, value) b.buf = append(b.buf, '"') return b } func (b *withBuffer) Bool(label string, value bool) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendBool(b.buf, value) return b } func (b *withBuffer) Int64(label string, value int64) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendInt(b.buf, value, 10) return b } func (b *withBuffer) Int32(label string, value int32) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendInt(b.buf, int64(value), 10) return b } func (b *withBuffer) Int16(label string, value int16) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendInt(b.buf, int64(value), 10) return b } func (b *withBuffer) Int8(label string, value int8) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendInt(b.buf, int64(value), 10) return b } func (b *withBuffer) Int(label string, value int) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendInt(b.buf, int64(value), 10) return b } func (b *withBuffer) Uint64(label string, value uint64) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendUint(b.buf, value, 10) return b } func (b *withBuffer) Uint32(label string, value uint32) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendUint(b.buf, uint64(value), 10) return b } func (b *withBuffer) Uint16(label string, value uint16) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendUint(b.buf, uint64(value), 10) return b } func (b *withBuffer) Uint8(label string, value uint8) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendUint(b.buf, uint64(value), 10) return b } func (b *withBuffer) Uint(label string, value uint) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendUint(b.buf, uint64(value), 10) return b } func (b *withBuffer) Float64(label string, value float64) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendFloat(b.buf, value, 'g', -1, 64) return b } func (b *withBuffer) Float32(label string, value float32) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = strconv.AppendFloat(b.buf, float64(value), 'g', -1, 32) return b } func (b *withBuffer) Time(label string, value time.Time, layout string) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') if layout == "" { layout = time.RFC3339 } b.buf = append(b.buf, escape(value.Format(layout))...) return b } func (b *withBuffer) UTCTime(label string, value time.Time) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = appendUTCTime(b.buf, value) return b } func (b *withBuffer) Stack(label string) ErrorWithFields { b.buf = append(b.buf, '\t') b.buf = append(b.buf, label...) b.buf = append(b.buf, ':') b.buf = appendCallers(b.buf) return b }
buffer.go
0.61231
0.424889
buffer.go
starcoder
package stl import "math" type RotationMatrix struct { //Store the matrix matrix [3][3]float32 //[row][col] //And the start and end pts start Vertex end Vertex lineVec Vertex lineMag float32 } //Create the rotation matrix func NewRotationMatrix(start Vertex, end Vertex, theta float64) *RotationMatrix { //Create the struct rotMat := &RotationMatrix{ start: start, end: end, lineVec: end.minus(&start), } //Store the line mag rotMat.lineMag = rotMat.lineVec.mag() //Compute a unit dir vector uv := end.minus(&start) uv.norm() //Precompute some values cos := float32(math.Cos(theta)) sin := float32(math.Sin(theta)) oneMinusCos := float32(1.0 - cos) //Now build the rotation vector rotMat.matrix[0][0] = cos + uv[0]*uv[0]*oneMinusCos rotMat.matrix[0][1] = uv[0]*uv[1]*oneMinusCos - uv[2]*sin rotMat.matrix[0][2] = uv[0]*uv[2]*oneMinusCos + uv[1]*sin rotMat.matrix[1][0] = uv[1]*uv[0]*oneMinusCos + uv[2]*sin rotMat.matrix[1][1] = cos + uv[1]*uv[1]*oneMinusCos rotMat.matrix[1][2] = uv[1]*uv[2]*oneMinusCos - uv[0]*sin rotMat.matrix[2][0] = uv[2]*uv[0]*oneMinusCos - uv[1]*sin rotMat.matrix[2][1] = uv[2]*uv[1]*oneMinusCos + uv[0]*sin rotMat.matrix[2][2] = cos + uv[2]*uv[2]*oneMinusCos return rotMat } //Gets the point origin on the line func (rot *RotationMatrix) getPtOrg(pt *Vertex) Vertex { // compute the distance along the line stpt := rot.start.minus(pt) fracTop := rot.lineVec.dot(&stpt) fracBot := rot.lineMag * rot.lineMag //Compute the fraction t t := -fracTop / (fracBot + 1E-30) //Now compute the location if t < 0 { return rot.start } else if t < 1.0 { return Vertex{ t*rot.lineVec[0] + rot.start[0], t*rot.lineVec[1] + rot.start[1], t*rot.lineVec[2] + rot.start[2], } } else { return rot.end } } //Create the rotation matrix func (rot *RotationMatrix) rotate(pt *Vertex) Vertex { //Get the org for this pt ptOrg := rot.getPtOrg(pt) //Now get this pt relative to the pt org relPt := pt.minus(&ptOrg) //Now rotate it var rotatPt Vertex for i := 0; i < len(rot.matrix); i++ { for j := 0; j < len(rot.matrix[i]); j++ { rotatPt[i] += rot.matrix[i][j] * relPt[j] } } //Now add the ptOrg back to the point rotatPt.addTo(&ptOrg) return rotatPt }
stl/Rotation.go
0.720467
0.542136
Rotation.go
starcoder
package internal import ( "math" ) // A FITS image. // Spec here: https://fits.gsfc.nasa.gov/standard40/fits_standard40aa-le.pdf // Primer here: https://fits.gsfc.nasa.gov/fits_primer.html type FITSImage struct { ID int // Sequential ID number, for log output. Counted upwards from 0 for light frames. By convention, dark is -1 and flat is -2 FileName string // Original file name, if any, for log output. Header FITSHeader // The header with all keys, values, comments, history entries etc. Bitpix int32 // Bits per pixel value from the header. Positive values are integral, negative floating. Bzero float32 // Zero offset. True pixel value is Bzero + Data[i]. // Helps implement unsigned values with signed data types. Naxisn []int32 // Axis dimensions. Most quickly varying dimension first (i.e. X,Y) Pixels int32 // Number of pixels in the image. Product of Naxisn[] Data []float32 // The image data Exposure float32 // Image exposure in seconds Stats *BasicStats // Basic image statistics: min, mean, max Stars []Star // Star detections HFR float32 // Half-flux radius of the star detections Trans Transform2D // Transformation to reference frame Residual float32 // Residual error from the above transformation } // Creates a FITS image initialized with empty header func NewFITSImage() FITSImage { return FITSImage{ Header: NewFITSHeader(), } } // FITS header data type FITSHeader struct { Bools map[string]bool Ints map[string]int32 Floats map[string]float32 Strings map[string]string Dates map[string]string Comments []string History []string End bool Length int32 } // Creates a FITS header initialized with empty maps and arrays func NewFITSHeader() FITSHeader { return FITSHeader{ Bools: make(map[string]bool), Ints: make(map[string]int32), Floats: make(map[string]float32), Strings: make(map[string]string), Dates: make(map[string]string), Comments:make([]string,0), History: make([]string,0), End: false, } } const fitsBlockSize int = 2880 // Block size of FITS header and data units const fitsHeaderLineSize int = 80 // Line size of a FITS header // Combine single color images into one multi-channel image. // All images must have the same dimensions, or undefined results occur. func CombineRGB(chans []*FITSImage, ref *FITSImage) FITSImage { pixelsOrig:=chans[0].Pixels pixelsComb:=pixelsOrig*int32(len(chans)) rgb:=FITSImage{ Header:NewFITSHeader(), Bitpix:-32, Bzero :0, Naxisn:make([]int32, len(chans[0].Naxisn)+1), Pixels:pixelsComb, Data :make([]float32,int(pixelsComb)), Exposure: chans[0].Exposure+chans[1].Exposure+chans[2].Exposure, Stars :[]Star{}, HFR :0, } if ref!=nil { rgb.Stars, rgb.HFR=ref.Stars, ref.HFR } copy(rgb.Naxisn, chans[0].Naxisn) rgb.Naxisn[len(chans[0].Naxisn)]=int32(len(chans)) min, mult:=getCommonNormalizationFactors(chans) for id, ch:=range chans { dest:=rgb.Data[int32(id)*pixelsOrig : (int32(id)+1)*pixelsOrig] for j,val:=range ch.Data { dest[j]=(val-min)*mult } } return rgb } // calculate common normalization factors to [0..1] across all channels func getCommonNormalizationFactors(chans []*FITSImage) (min, mult float32) { min =chans[0].Stats.Min max:=chans[0].Stats.Max for _, ch :=range chans[1:] { if ch.Stats.Min<min { min=ch.Stats.Min } if ch.Stats.Max>max { max=ch.Stats.Max } } mult=1 / (max - min) LogPrintf("common normalization factors min=%f mult=%f\n", min, mult) return min, mult } // Applies luminance to existing 3-channel image with luminance in 3rd channel, all channels in [0,1]. // All images must have the same dimensions, or undefined results occur. func (hsl *FITSImage) ApplyLuminanceToCIExyY(lum *FITSImage) { l:=len(hsl.Data)/3 dest:=hsl.Data[2*l:] copy(dest, lum.Data) } // Set image black point so histogram peaks match the rightmost channel peak, // and median star colors are of a neutral tone. func (f *FITSImage) SetBlackWhitePoints() error { // Estimate location (=histogram peak, background black point) per color channel l:=len(f.Data)/3 statsR,err:=CalcExtendedStats(f.Data[ : l], f.Naxisn[0]) if err!=nil {return err} statsG,err:=CalcExtendedStats(f.Data[l :2*l], f.Naxisn[0]) if err!=nil {return err} statsB,err:=CalcExtendedStats(f.Data[2*l: ], f.Naxisn[0]) if err!=nil {return err} locR, locG, locB:=statsR.Location, statsG.Location, statsB.Location LogPrintf("r %s\ng %s\nb %s\n", statsR, statsG, statsB) // Pick rightmost peak as new location newBlack:=locR if locG>newBlack { newBlack=locG } if locB>newBlack { newBlack=locB } // Estimate median star color starR:=medianStarIntensity(f.Data[ : l], f.Naxisn[0], f.Stars) starG:=medianStarIntensity(f.Data[l :2*l], f.Naxisn[0], f.Stars) starB:=medianStarIntensity(f.Data[2*l: ], f.Naxisn[0], f.Stars) LogPrintf("Background peak (%.2f%%, %.2f%%, %.2f%%) and median star color (%.2f%%, %.2f%%, %.2f%%)\n", locR*100, locG*100, locB*100, starR*100, starG*100, starB*100) // Calculate multiplicative correction factors to balance star colors to common minimum starMin:=starR if starMin>starG { starMin=starG } if starMin>starB { starMin=starB } alphaR:=starMin/starR alphaG:=starMin/starG alphaB:=starMin/starB // Calculate additive correction factors to move old location to new black betaR := newBlack-alphaR*locR betaG := newBlack-alphaG*locG betaB := newBlack-alphaB*locB LogPrintf("r=%.2f*r %+.2f%%, g=%.2f*g %+.2f%%, b=%.2f*b %+.2f%%\n", alphaR, betaR, alphaG, betaG, alphaB, betaB) f.ScaleOffsetClampRGB(alphaR, betaR, alphaG, betaG, alphaB, betaB) return nil } // Returns median intensity value for the stars in the given monochrome image func medianStarIntensity(data []float32, width int32, stars []Star) float32 { if len(stars)==0 { return 0 } height:=int32(len(data))/width // Gather together channel values for all stars gathered:=make([]float32,0,len(data)) for _, s:=range stars { starX,starY:=s.Index%width, s.Index/width hfrR:=int32(s.HFR+0.5) hfrSq:=(s.HFR+0.01)*(s.HFR+0.01) for offY:=-hfrR; offY<=hfrR; offY++ { y:=starY+offY if y>=0 && y<height { for offX:=-hfrR; offX<=hfrR; offX++ { x:=starX+offX if x>=0 && x<width { distSq:=float32(offX*offX+offY*offY) if distSq<=hfrSq { d:=data[y*width+x] gathered=append(gathered, d) } } } } } } median:=QSelectMedianFloat32(gathered) gathered=nil return median } // Apply NxN binning to source image and return new resulting image func BinNxN(src *FITSImage, n int32) FITSImage { // calculate binned image size binnedPixels:=int32(1) binnedNaxisn:=make([]int32, len(src.Naxisn)) for i,originalN:=range(src.Naxisn) { binnedN:=originalN/n binnedNaxisn[i]=binnedN binnedPixels*=binnedN } // created binned image header binned:=FITSImage{ Header:NewFITSHeader(), Bitpix:-32, Bzero :0, Naxisn:binnedNaxisn, Pixels:binnedPixels, Data :make([]float32,int(binnedPixels)), Exposure: src.Exposure, ID :src.ID, } // calculate binned image pixel values // FIXME: pretty inefficient? normalizer:=1.0/float32(n*n) for y:=int32(0); y<binnedNaxisn[1]; y++ { for x:=int32(0); x<binnedNaxisn[0]; x++ { sum:=float32(0) for yoff:=int32(0); yoff<n; yoff++ { for xoff:=int32(0); xoff<n; xoff++ { origPos:=(y*n+yoff)*src.Naxisn[0] + (x*n+xoff) sum+=src.Data[origPos] } } avg:=sum*normalizer binnedPos:=y*binned.Naxisn[0] + x binned.Data[binnedPos]=avg } } return binned } // Fill a circle of given radius on the FITS image func (f* FITSImage) FillCircle(xc,yc,r,color float32) { for y:=-r; y<=r; y+=0.5 { for x:=-r; x<=r; x+=0.5 { distSq:=y*y+x*x if distSq<=r*r+1e-6 { index:=int32(xc+x) + int32(yc+y)*(f.Naxisn[0]) if index>=0 && index<int32(len(f.Data)) { f.Data[index]=color } } } } } // Show stars detected on the source image as circles in a new resulting image func ShowStars(src *FITSImage, hfrMultiple float32) FITSImage { // created new image header res:=FITSImage{ Header:NewFITSHeader(), Bitpix:-32, Bzero :0, Naxisn:src.Naxisn, Pixels:src.Pixels, Data :make([]float32,int(src.Pixels)), } for _,s:=range(src.Stars) { radius:=s.HFR*hfrMultiple res.FillCircle(s.X, s.Y, radius, s.Mass/(radius*radius*float32(math.Pi)) ) } return res } // Equal tells whether a and b contain the same elements. // A nil argument is equivalent to an empty slice. func EqualInt32Slice(a, b []int32) bool { if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true }
internal/fits.go
0.659186
0.529689
fits.go
starcoder
package lists import ( "github.com/zimmski/tavor/token" ) // One implements a list token which chooses of a set of referenced token exactly one token // Every permutation chooses one token out of the token set. type One struct { tokens []token.Token value int } // NewOne returns a new instance of a One token given the set of tokens func NewOne(toks ...token.Token) *One { if len(toks) == 0 { panic("at least one token needed") } return &One{ tokens: toks, value: 0, } } // Token interface methods // Clone returns a copy of the token and all its children func (l *One) Clone() token.Token { c := One{ tokens: make([]token.Token, len(l.tokens)), value: l.value, } for i, tok := range l.tokens { c.tokens[i] = tok.Clone() } return &c } // Parse tries to parse the token beginning from the current position in the parser data. // If the parsing is successful the error argument is nil and the next current position after the token is returned. func (l *One) Parse(pars *token.InternalParser, cur int) (int, []error) { var nex int var es, errs []error for i := range l.tokens { nex, es = l.tokens[i].Parse(pars, cur) if len(es) == 0 { l.value = i return nex, nil } errs = append(errs, es...) } return cur, errs } func (l *One) permutation(i uint) { l.value = int(i) } // Permutation sets a specific permutation for this token func (l *One) Permutation(i uint) error { permutations := l.Permutations() if i < 1 || i > permutations { return &token.PermutationError{ Type: token.PermutationErrorIndexOutOfBound, } } l.permutation(i - 1) return nil } // Permutations returns the number of permutations for this token func (l *One) Permutations() uint { return uint(len(l.tokens)) } // PermutationsAll returns the number of all possible permutations for this token including its children func (l *One) PermutationsAll() uint { var sum uint for _, tok := range l.tokens { sum += tok.PermutationsAll() } return sum } func (l *One) String() string { return l.tokens[l.value].String() } // List interface methods // Get returns the current referenced token at the given index. The error return argument is not nil, if the index is out of bound. func (l *One) Get(i int) (token.Token, error) { if i != 0 { return nil, &ListError{ListErrorOutOfBound} } return l.tokens[l.value], nil } // Len returns the number of the current referenced tokens func (l *One) Len() int { return 1 } // InternalGet returns the current referenced internal token at the given index. The error return argument is not nil, if the index is out of bound. func (l *One) InternalGet(i int) (token.Token, error) { if i < 0 || i >= len(l.tokens) { return nil, &ListError{ListErrorOutOfBound} } return l.tokens[i], nil } // InternalLen returns the number of referenced internal tokens func (l *One) InternalLen() int { return len(l.tokens) } // InternalLogicalRemove removes the referenced internal token and returns the replacement for the current token or nil if the current token should be removed. func (l *One) InternalLogicalRemove(tok token.Token) token.Token { for i := 0; i < len(l.tokens); i++ { if l.tokens[i] == tok { if l.value == i { l.value-- } if i == len(l.tokens)-1 { l.tokens = l.tokens[:i] } else { l.tokens = append(l.tokens[:i], l.tokens[i+1:]...) } i-- } } if l.value == -1 { l.value = 0 } switch len(l.tokens) { case 0: return nil case 1: return l.tokens[0] } return l } // InternalReplace replaces an old with a new internal token if it is referenced by this token. The error return argument is not nil, if the replacement is not suitable. func (l *One) InternalReplace(oldToken, newToken token.Token) error { for i := 0; i < len(l.tokens); i++ { if l.tokens[i] == oldToken { l.tokens[i] = newToken } } return nil } // Minimize interface methods // Minimize tries to minimize itself and returns a token if it was successful, or nil if there was nothing to minimize func (l *One) Minimize() token.Token { if len(l.tokens) == 1 { return l.tokens[0] } return nil }
token/lists/one.go
0.788461
0.492005
one.go
starcoder
// Package mqanttools 字节转化 package mqanttools import ( "encoding/binary" "encoding/json" "math" ) // BoolToBytes bool->bytes func BoolToBytes(v bool) []byte { var buf = make([]byte, 1) if v { buf[0] = 1 } else { buf[0] = 0 } return buf } // BytesToBool bytes->bool func BytesToBool(buf []byte) bool { var data bool = buf[0] != 0 return data } // Int32ToBytes Int32ToBytes func Int32ToBytes(i int32) []byte { var buf = make([]byte, 4) binary.BigEndian.PutUint32(buf, uint32(i)) return buf } // BytesToInt32 BytesToInt32 func BytesToInt32(buf []byte) int32 { return int32(binary.BigEndian.Uint32(buf)) } // Int64ToBytes Int64ToBytes func Int64ToBytes(i int64) []byte { var buf = make([]byte, 8) binary.BigEndian.PutUint64(buf, uint64(i)) return buf } // BytesToInt64 BytesToInt64 func BytesToInt64(buf []byte) int64 { return int64(binary.BigEndian.Uint64(buf)) } // Float32ToBytes Float32ToBytes func Float32ToBytes(float float32) []byte { bits := math.Float32bits(float) bytes := make([]byte, 4) binary.LittleEndian.PutUint32(bytes, bits) return bytes } // BytesToFloat32 BytesToFloat32 func BytesToFloat32(bytes []byte) float32 { bits := binary.LittleEndian.Uint32(bytes) return math.Float32frombits(bits) } // Float64ToBytes Float64ToBytes func Float64ToBytes(float float64) []byte { bits := math.Float64bits(float) bytes := make([]byte, 8) binary.LittleEndian.PutUint64(bytes, bits) return bytes } // BytesToFloat64 BytesToFloat64 func BytesToFloat64(bytes []byte) float64 { bits := binary.LittleEndian.Uint64(bytes) return math.Float64frombits(bits) } // MapToBytes MapToBytes func MapToBytes(jmap map[string]interface{}) ([]byte, error) { bytes, err := json.Marshal(jmap) return bytes, err } // BytesToMap BytesToMap func BytesToMap(bytes []byte) (map[string]interface{}, error) { v := make(map[string]interface{}) err := json.Unmarshal(bytes, &v) return v, err } // MapToBytesString MapToBytesString func MapToBytesString(jmap map[string]string) ([]byte, error) { bytes, err := json.Marshal(jmap) return bytes, err } // BytesToMapString BytesToMapString func BytesToMapString(bytes []byte) (map[string]string, error) { v := make(map[string]string) err := json.Unmarshal(bytes, &v) return v, err }
utils/params_bytes.go
0.54359
0.411229
params_bytes.go
starcoder
package tsm1 import ( "fmt" "github.com/influxdata/influxdb/tsdb/cursors" ) // DecodeBooleanArrayBlock decodes the boolean block from the byte slice // and writes the values to a. func DecodeBooleanArrayBlock(block []byte, a *cursors.BooleanArray) error { blockType := block[0] if blockType != BlockBoolean { return fmt.Errorf("invalid block type: exp %d, got %d", BlockBoolean, blockType) } tb, vb, err := unpackBlock(block[1:]) if err != nil { return err } a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps) if err != nil { return err } a.Values, err = BooleanArrayDecodeAll(vb, a.Values) return err } // DecodeFloatArrayBlock decodes the float block from the byte slice // and writes the values to a. func DecodeFloatArrayBlock(block []byte, a *cursors.FloatArray) error { blockType := block[0] if blockType != BlockFloat64 { return fmt.Errorf("invalid block type: exp %d, got %d", BlockFloat64, blockType) } tb, vb, err := unpackBlock(block[1:]) if err != nil { return err } a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps) if err != nil { return err } a.Values, err = FloatArrayDecodeAll(vb, a.Values) return err } // DecodeIntegerArrayBlock decodes the integer block from the byte slice // and writes the values to a. func DecodeIntegerArrayBlock(block []byte, a *cursors.IntegerArray) error { blockType := block[0] if blockType != BlockInteger { return fmt.Errorf("invalid block type: exp %d, got %d", BlockInteger, blockType) } tb, vb, err := unpackBlock(block[1:]) if err != nil { return err } a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps) if err != nil { return err } a.Values, err = IntegerArrayDecodeAll(vb, a.Values) return err } // DecodeUnsignedArrayBlock decodes the unsigned integer block from the byte slice // and writes the values to a. func DecodeUnsignedArrayBlock(block []byte, a *cursors.UnsignedArray) error { blockType := block[0] if blockType != BlockUnsigned { return fmt.Errorf("invalid block type: exp %d, got %d", BlockUnsigned, blockType) } tb, vb, err := unpackBlock(block[1:]) if err != nil { return err } a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps) if err != nil { return err } a.Values, err = UnsignedArrayDecodeAll(vb, a.Values) return err } // DecodeStringArrayBlock decodes the string block from the byte slice // and writes the values to a. func DecodeStringArrayBlock(block []byte, a *cursors.StringArray) error { blockType := block[0] if blockType != BlockString { return fmt.Errorf("invalid block type: exp %d, got %d", BlockString, blockType) } tb, vb, err := unpackBlock(block[1:]) if err != nil { return err } a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps) if err != nil { return err } a.Values, err = StringArrayDecodeAll(vb, a.Values) return err } // DecodeTimestampArrayBlock decodes the timestamps from the specified // block, ignoring the block type and the values. func DecodeTimestampArrayBlock(block []byte, a *cursors.TimestampArray) error { tb, _, err := unpackBlock(block[1:]) if err != nil { return err } a.Timestamps, err = TimeArrayDecodeAll(tb, a.Timestamps) return err }
tsdb/tsm1/array_encoding.go
0.73678
0.440289
array_encoding.go
starcoder
package file const contentSchema = `{ "$schema": "http://json-schema.org/draft-04/schema#", "properties": { "_format_version": { "type": "string" }, "_info": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/Info" }, "_plugin_configs": { "patternProperties": { ".*": { "additionalProperties": true, "type": "object" } }, "type": "object" }, "_workspace": { "type": "string" }, "ca_certificates": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FCACertificate" }, "type": "array" }, "certificates": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FCertificate" }, "type": "array" }, "consumers": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FConsumer" }, "type": "array" }, "plugins": { "items": { "$ref": "#/definitions/FPlugin" }, "type": "array" }, "routes": { "items": { "$ref": "#/definitions/FRoute" }, "type": "array" }, "services": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FService" }, "type": "array" }, "upstreams": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FUpstream" }, "type": "array" } }, "additionalProperties": false, "type": "object", "definitions": { "ACLGroup": { "required": [ "group" ], "properties": { "consumer": { "$ref": "#/definitions/Consumer" }, "created_at": { "type": "integer" }, "group": { "type": "string" }, "id": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "ActiveHealthcheck": { "properties": { "concurrency": { "type": "integer" }, "healthy": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/Healthy" }, "http_path": { "type": "string" }, "https_sni": { "type": "string" }, "https_verify_certificate": { "type": "boolean" }, "timeout": { "type": "integer" }, "type": { "type": "string" }, "unhealthy": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/Unhealthy" } }, "additionalProperties": false, "type": "object" }, "BasicAuth": { "required": [ "username", "password" ], "properties": { "consumer": { "$ref": "#/definitions/Consumer" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "password": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" }, "username": { "type": "string" } }, "additionalProperties": false, "type": "object" }, "CIDRPort": { "properties": { "ip": { "type": "string" }, "port": { "type": "integer" } }, "additionalProperties": false, "type": "object" }, "Certificate": { "properties": { "cert": { "type": "string" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "key": { "type": "string" }, "snis": { "items": { "type": "string" }, "type": "array" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "Consumer": { "properties": { "created_at": { "type": "integer" }, "custom_id": { "type": "string" }, "id": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" }, "username": { "type": "string" } }, "additionalProperties": false, "type": "object", "anyOf": [ { "required": [ "username" ] }, { "required": [ "id" ] } ] }, "FCACertificate": { "required": [ "cert" ], "properties": { "cert": { "type": "string" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "FCertificate": { "required": [ "id", "cert", "key" ], "properties": { "cert": { "type": "string" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "key": { "type": "string" }, "snis": { "items": { "properties": { "name": { "type": "string" } }, "type": "object" }, "type": "array" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "FConsumer": { "properties": { "acls": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/ACLGroup" }, "type": "array" }, "basicauth_credentials": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/BasicAuth" }, "type": "array" }, "created_at": { "type": "integer" }, "custom_id": { "type": "string" }, "hmacauth_credentials": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/HMACAuth" }, "type": "array" }, "id": { "type": "string" }, "jwt_secrets": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/JWTAuth" }, "type": "array" }, "keyauth_credentials": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/KeyAuth" }, "type": "array" }, "oauth2_credentials": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/Oauth2Credential" }, "type": "array" }, "plugins": { "items": { "$ref": "#/definitions/FPlugin" }, "type": "array" }, "tags": { "items": { "type": "string" }, "type": "array" }, "username": { "type": "string" } }, "additionalProperties": false, "type": "object", "anyOf": [ { "required": [ "username" ] }, { "required": [ "id" ] } ] }, "FPlugin": { "required": [ "name" ], "properties": { "_config": { "type": "string" }, "config": { "additionalProperties": true, "type": "object" }, "consumer": { "type": "string" }, "created_at": { "type": "integer" }, "enabled": { "type": "boolean" }, "id": { "type": "string" }, "name": { "type": "string" }, "protocols": { "items": { "type": "string" }, "type": "array" }, "route": { "type": "string" }, "run_on": { "type": "string" }, "service": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "FRoute": { "properties": { "created_at": { "type": "integer" }, "destinations": { "items": { "$ref": "#/definitions/CIDRPort" }, "type": "array" }, "headers": { "patternProperties": { ".*": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "hosts": { "items": { "type": "string" }, "type": "array" }, "https_redirect_status_code": { "type": "integer" }, "id": { "type": "string" }, "methods": { "items": { "type": "string" }, "type": "array" }, "name": { "type": "string" }, "path_handling": { "type": "string" }, "paths": { "items": { "type": "string" }, "type": "array" }, "plugins": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FPlugin" }, "type": "array" }, "preserve_host": { "type": "boolean" }, "protocols": { "items": { "type": "string" }, "type": "array" }, "regex_priority": { "type": "integer" }, "service": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/Service" }, "snis": { "items": { "type": "string" }, "type": "array" }, "sources": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/CIDRPort" }, "type": "array" }, "strip_path": { "type": "boolean" }, "tags": { "items": { "type": "string" }, "type": "array" }, "updated_at": { "type": "integer" } }, "additionalProperties": false, "type": "object", "anyOf": [ { "required": [ "name" ] }, { "required": [ "id" ] } ] }, "FService": { "properties": { "client_certificate": { "type": "string" }, "connect_timeout": { "type": "integer" }, "created_at": { "type": "integer" }, "host": { "type": "string" }, "id": { "type": "string" }, "name": { "type": "string" }, "path": { "type": "string" }, "plugins": { "items": { "$ref": "#/definitions/FPlugin" }, "type": "array" }, "port": { "type": "integer" }, "protocol": { "type": "string" }, "read_timeout": { "type": "integer" }, "retries": { "type": "integer" }, "routes": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FRoute" }, "type": "array" }, "tags": { "items": { "type": "string" }, "type": "array" }, "updated_at": { "type": "integer" }, "url": { "type": "string" }, "write_timeout": { "type": "integer" } }, "additionalProperties": false, "type": "object", "anyOf": [ { "required": [ "name" ] }, { "required": [ "id" ] } ] }, "FTarget": { "required": [ "target" ], "properties": { "created_at": { "type": "number" }, "id": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" }, "target": { "type": "string" }, "upstream": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/Upstream" }, "weight": { "type": "integer" } }, "additionalProperties": false, "type": "object" }, "FUpstream": { "required": [ "name" ], "properties": { "algorithm": { "type": "string" }, "created_at": { "type": "integer" }, "hash_fallback": { "type": "string" }, "hash_fallback_header": { "type": "string" }, "hash_on": { "type": "string" }, "hash_on_cookie": { "type": "string" }, "hash_on_cookie_path": { "type": "string" }, "hash_on_header": { "type": "string" }, "healthchecks": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/Healthcheck" }, "host_header": { "type": "string" }, "id": { "type": "string" }, "name": { "type": "string" }, "slots": { "type": "integer" }, "tags": { "items": { "type": "string" }, "type": "array" }, "targets": { "items": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/FTarget" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "HMACAuth": { "required": [ "username", "secret" ], "properties": { "consumer": { "$ref": "#/definitions/Consumer" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "secret": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" }, "username": { "type": "string" } }, "additionalProperties": false, "type": "object" }, "Healthcheck": { "properties": { "active": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/ActiveHealthcheck" }, "passive": { "$schema": "http://json-schema.org/draft-04/schema#", "$ref": "#/definitions/PassiveHealthcheck" }, "threshold": { "type": "number" } }, "additionalProperties": false, "type": "object" }, "Healthy": { "properties": { "http_statuses": { "items": { "type": "integer" }, "type": "array" }, "interval": { "type": "integer" }, "successes": { "type": "integer" } }, "additionalProperties": false, "type": "object" }, "Info": { "properties": { "select_tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "JWTAuth": { "required": [ "algorithm", "key", "secret" ], "properties": { "algorithm": { "type": "string" }, "consumer": { "$ref": "#/definitions/Consumer" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "key": { "type": "string" }, "rsa_public_key": { "type": "string" }, "secret": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "KeyAuth": { "required": [ "key" ], "properties": { "consumer": { "$ref": "#/definitions/Consumer" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "key": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "Oauth2Credential": { "required": [ "name", "client_id", "redirect_uris", "client_secret" ], "properties": { "client_id": { "type": "string" }, "client_secret": { "type": "string" }, "consumer": { "$ref": "#/definitions/Consumer" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "name": { "type": "string" }, "redirect_uris": { "items": { "type": "string" }, "type": "array" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "PassiveHealthcheck": { "properties": { "healthy": { "$ref": "#/definitions/Healthy" }, "unhealthy": { "$ref": "#/definitions/Unhealthy" } }, "additionalProperties": false, "type": "object" }, "Route": { "properties": { "created_at": { "type": "integer" }, "destinations": { "items": { "$ref": "#/definitions/CIDRPort" }, "type": "array" }, "headers": { "patternProperties": { ".*": { "items": { "type": "string" }, "type": "array" } }, "type": "object" }, "hosts": { "items": { "type": "string" }, "type": "array" }, "https_redirect_status_code": { "type": "integer" }, "id": { "type": "string" }, "methods": { "items": { "type": "string" }, "type": "array" }, "name": { "type": "string" }, "path_handling": { "type": "string" }, "paths": { "items": { "type": "string" }, "type": "array" }, "preserve_host": { "type": "boolean" }, "protocols": { "items": { "type": "string" }, "type": "array" }, "regex_priority": { "type": "integer" }, "service": { "$ref": "#/definitions/Service" }, "snis": { "items": { "type": "string" }, "type": "array" }, "sources": { "items": { "$ref": "#/definitions/CIDRPort" }, "type": "array" }, "strip_path": { "type": "boolean" }, "tags": { "items": { "type": "string" }, "type": "array" }, "updated_at": { "type": "integer" } }, "additionalProperties": false, "type": "object", "anyOf": [ { "required": [ "name" ] }, { "required": [ "id" ] } ] }, "SNI": { "properties": { "certificate": { "$ref": "#/definitions/Certificate" }, "created_at": { "type": "integer" }, "id": { "type": "string" }, "name": { "type": "string" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" }, "Service": { "properties": { "client_certificate": { "$ref": "#/definitions/Certificate" }, "connect_timeout": { "type": "integer" }, "created_at": { "type": "integer" }, "host": { "type": "string" }, "id": { "type": "string" }, "name": { "type": "string" }, "path": { "type": "string" }, "port": { "type": "integer" }, "protocol": { "type": "string" }, "read_timeout": { "type": "integer" }, "retries": { "type": "integer" }, "tags": { "items": { "type": "string" }, "type": "array" }, "updated_at": { "type": "integer" }, "write_timeout": { "type": "integer" } }, "additionalProperties": false, "type": "object", "anyOf": [ { "required": [ "name" ] }, { "required": [ "id" ] } ] }, "Unhealthy": { "properties": { "http_failures": { "type": "integer" }, "http_statuses": { "items": { "type": "integer" }, "type": "array" }, "interval": { "type": "integer" }, "tcp_failures": { "type": "integer" }, "timeouts": { "type": "integer" } }, "additionalProperties": false, "type": "object" }, "Upstream": { "required": [ "name" ], "properties": { "algorithm": { "type": "string" }, "created_at": { "type": "integer" }, "hash_fallback": { "type": "string" }, "hash_fallback_header": { "type": "string" }, "hash_on": { "type": "string" }, "hash_on_cookie": { "type": "string" }, "hash_on_cookie_path": { "type": "string" }, "hash_on_header": { "type": "string" }, "healthchecks": { "$ref": "#/definitions/Healthcheck" }, "host_header": { "type": "string" }, "id": { "type": "string" }, "name": { "type": "string" }, "slots": { "type": "integer" }, "tags": { "items": { "type": "string" }, "type": "array" } }, "additionalProperties": false, "type": "object" } } }`
file/schema.go
0.599837
0.433022
schema.go
starcoder
// Command custommetric creates a custom metric and writes TimeSeries value // to it. It writes a GAUGE measurement, which is a measure of value at a // specific point in time. This means the startTime and endTime of the interval // are the same. To make it easier to see the output, a random value is written. // When reading the TimeSeries back, a window of the last 5 minutes is used. package main import ( "context" "encoding/json" "fmt" "log" "math/rand" "os" "time" "golang.org/x/oauth2/google" "google.golang.org/api/monitoring/v3" ) const metricType = "custom.googleapis.com/custom_measurement" func projectResource(projectID string) string { return "projects/" + projectID } // [START monitoring_create_metric] // createCustomMetric creates a custom metric specified by the metric type. func createCustomMetric(s *monitoring.Service, projectID, metricType string) error { ld := monitoring.LabelDescriptor{Key: "environment", ValueType: "STRING", Description: "An arbitrary measurement"} md := monitoring.MetricDescriptor{ Type: metricType, Labels: []*monitoring.LabelDescriptor{&ld}, MetricKind: "GAUGE", ValueType: "INT64", Unit: "items", Description: "An arbitrary measurement", DisplayName: "Custom Metric", } resp, err := s.Projects.MetricDescriptors.Create(projectResource(projectID), &md).Do() if err != nil { return fmt.Errorf("Could not create custom metric: %v", err) } log.Printf("createCustomMetric: %s\n", formatResource(resp)) return nil } // [END monitoring_create_metric] // [START monitoring_list_descriptors] // getCustomMetric reads the custom metric created. func getCustomMetric(s *monitoring.Service, projectID, metricType string) (*monitoring.ListMetricDescriptorsResponse, error) { resp, err := s.Projects.MetricDescriptors.List(projectResource(projectID)). Filter(fmt.Sprintf("metric.type=\"%s\"", metricType)).Do() if err != nil { return nil, fmt.Errorf("Could not get custom metric: %v", err) } log.Printf("getCustomMetric: %s\n", formatResource(resp)) return resp, nil } // [END monitoring_list_descriptors] // [START monitoring_delete_metric] // deleteMetric deletes the given metric. func deleteMetric(s *monitoring.Service, projectID, metricType string) error { metricResource := "projects/" + projectID + "/metricDescriptors/" + metricType _, err := s.Projects.MetricDescriptors.Delete(metricResource).Do() if err != nil { return fmt.Errorf("Could not delete metric: %v", err) } log.Printf("Deleted metric: %q\n", metricType) return nil } // [END monitoring_delete_metric] // [START monitoring_write_timeseries] // writeTimeSeriesValue writes a value for the custom metric created func writeTimeSeriesValue(s *monitoring.Service, projectID, metricType string) error { now := time.Now().UTC().Format(time.RFC3339Nano) randVal := rand.Int63n(10) timeseries := monitoring.TimeSeries{ Metric: &monitoring.Metric{ Type: metricType, Labels: map[string]string{ "environment": "STAGING", }, }, Resource: &monitoring.MonitoredResource{ Labels: map[string]string{ "instance_id": "test-instance", "zone": "us-central1-f", }, Type: "gce_instance", }, Points: []*monitoring.Point{ { Interval: &monitoring.TimeInterval{ StartTime: now, EndTime: now, }, Value: &monitoring.TypedValue{ Int64Value: &randVal, }, }, }, } createTimeseriesRequest := monitoring.CreateTimeSeriesRequest{ TimeSeries: []*monitoring.TimeSeries{&timeseries}, } log.Printf("writeTimeseriesRequest: %s\n", formatResource(createTimeseriesRequest)) _, err := s.Projects.TimeSeries.Create(projectResource(projectID), &createTimeseriesRequest).Do() if err != nil { return fmt.Errorf("Could not write time series value, %v ", err) } return nil } // [END monitoring_write_timeseries] // [START monitoring_read_timeseries_simple] // readTimeSeriesValue reads the TimeSeries for the value specified by metric type in a time window from the last 5 minutes. func readTimeSeriesValue(s *monitoring.Service, projectID, metricType string) error { startTime := time.Now().UTC().Add(time.Minute * -5) endTime := time.Now().UTC() resp, err := s.Projects.TimeSeries.List(projectResource(projectID)). Filter(fmt.Sprintf("metric.type=\"%s\"", metricType)). IntervalStartTime(startTime.Format(time.RFC3339Nano)). IntervalEndTime(endTime.Format(time.RFC3339Nano)). Do() if err != nil { return fmt.Errorf("Could not read time series value, %v ", err) } log.Printf("readTimeseriesValue: %s\n", formatResource(resp)) return nil } // [END monitoring_read_timeseries_simple] func createService(ctx context.Context) (*monitoring.Service, error) { hc, err := google.DefaultClient(ctx, monitoring.MonitoringScope) if err != nil { return nil, err } s, err := monitoring.New(hc) if err != nil { return nil, err } return s, nil } func main() { rand.Seed(time.Now().UTC().UnixNano()) if len(os.Args) < 2 { fmt.Println("Usage: custommetric <project_id>") return } ctx := context.Background() s, err := createService(ctx) if err != nil { log.Fatal(err) } projectID := os.Args[1] // Create the metric. if err := createCustomMetric(s, projectID, metricType); err != nil { log.Fatal(err) } // Wait until the new metric can be read back. for { resp, err := getCustomMetric(s, projectID, metricType) if err != nil { log.Fatal(err) } if len(resp.MetricDescriptors) != 0 { break } time.Sleep(2 * time.Second) } // Write a TimeSeries value for that metric if err := writeTimeSeriesValue(s, projectID, metricType); err != nil { log.Fatal(err) } time.Sleep(2 * time.Second) // Read the TimeSeries for the last 5 minutes for that metric. if err := readTimeSeriesValue(s, projectID, metricType); err != nil { log.Fatal(err) } if err := deleteMetric(s, projectID, metricType); err != nil { log.Fatal(err) } } // formatResource marshals a response object as JSON. func formatResource(resource interface{}) []byte { b, err := json.MarshalIndent(resource, "", " ") if err != nil { panic(err) } return b }
monitoring/custommetric/custommetric.go
0.832509
0.421909
custommetric.go
starcoder
package iso20022 // Specifies the elements of an entry in the report. type NotificationEntry1 struct { // Amount of money in the cash entry. Amount *CurrencyAndAmount `xml:"Amt"` // Specifies if an entry is a credit or a debit. CreditDebitIndicator *CreditDebitCode `xml:"CdtDbtInd"` // Indicates whether the entry is the result of a reversal operation. // // Usage : this element should only be present if the entry is the result of a reversal operation. // If the CreditDebitIndicator is CRDT and ReversalIndicator is Yes, the original operation was a debit entry. // If the CreditDebitIndicator is DBIT and ReversalIndicator is Yes, the original operation was a credit entry. ReversalIndicator *TrueFalseIndicator `xml:"RvslInd,omitempty"` // Status of an entry on the books of the account servicer. Status *EntryStatus4Code `xml:"Sts"` // Date and time when an entry is posted to an account on the account servicer's books. // // Usage : Booking date is only present if Status is booked. BookingDate *DateAndDateTimeChoice `xml:"BookgDt,omitempty"` // Date and time assets become available to the account owner (in a credit entry), or cease to be available to the account owner (in a debit entry). // // Usage : When entry status is pending , and value date is present, value date refers to an expected/requested value date. // For entries which are subject to availability/float (and for which availability information is present), value date must not be used, as the availability component identifies the number of availability days. ValueDate *DateAndDateTimeChoice `xml:"ValDt,omitempty"` // Account servicing institution's reference for the entry. AccountServicerReference *Max35Text `xml:"AcctSvcrRef,omitempty"` // Set of elements used to indicate when the booked amount of money will become available, ie can be accessed and start generating interest. // // Usage : this type of info is eg used in US, and is linked to particular instruments, such as cheques. // Example : When a cheque is deposited, it will be booked on the deposit day, but the funds will only be accessible as of the indicated availability day (according to national banking regulations). Availability []*CashBalanceAvailability1 `xml:"Avlbty,omitempty"` // Set of elements to fully identify the type of underlying transaction resulting in the entry. BankTransactionCode *BankTransactionCodeStructure1 `xml:"BkTxCd"` // Indicates whether the transaction is exempt from commission. CommissionWaiverIndicator *YesNoIndicator `xml:"ComssnWvrInd,omitempty"` // Indicates whether the underlying transaction details are provided through a separate message, eg in case of aggregate bookings. AdditionalInformationIndicator *MessageIdentification2 `xml:"AddtlInfInd,omitempty"` // Set of elements providing details on batched transactions. // // Usage : this element can be repeated in case more than one batch is included in the entry, eg, in lockbox scenarios, to specify the ID and number of transactions included in each of the batches. Batch []*BatchInformation1 `xml:"Btch,omitempty"` // Set of elements providing information on the original amount. // // Usage : This component (on entry level) should be used when a total original batch or aggregate amount has to be provided. (If required, the individual original amounts can be included in the same component on transaction details level). AmountDetails *AmountAndCurrencyExchange2 `xml:"AmtDtls,omitempty"` // Provides information on the charges included in the entry amount. // // Usage : this component is used on entry level in case of batch or aggregate bookings. Charges []*ChargesInformation3 `xml:"Chrgs,omitempty"` // Set of elements providing details on the interest amount included in the entry amount. // // Usage : This component is used on entry level in case of batch or aggregate bookings. Interest []*TransactionInterest1 `xml:"Intrst,omitempty"` // Set of elements providing information on the underlying transaction (s). TransactionDetails []*EntryTransaction1 `xml:"TxDtls,omitempty"` // Further details on the entry details. AdditionalEntryInformation *Max500Text `xml:"AddtlNtryInf,omitempty"` } func (n *NotificationEntry1) SetAmount(value, currency string) { n.Amount = NewCurrencyAndAmount(value, currency) } func (n *NotificationEntry1) SetCreditDebitIndicator(value string) { n.CreditDebitIndicator = (*CreditDebitCode)(&value) } func (n *NotificationEntry1) SetReversalIndicator(value string) { n.ReversalIndicator = (*TrueFalseIndicator)(&value) } func (n *NotificationEntry1) SetStatus(value string) { n.Status = (*EntryStatus4Code)(&value) } func (n *NotificationEntry1) AddBookingDate() *DateAndDateTimeChoice { n.BookingDate = new(DateAndDateTimeChoice) return n.BookingDate } func (n *NotificationEntry1) AddValueDate() *DateAndDateTimeChoice { n.ValueDate = new(DateAndDateTimeChoice) return n.ValueDate } func (n *NotificationEntry1) SetAccountServicerReference(value string) { n.AccountServicerReference = (*Max35Text)(&value) } func (n *NotificationEntry1) AddAvailability() *CashBalanceAvailability1 { newValue := new (CashBalanceAvailability1) n.Availability = append(n.Availability, newValue) return newValue } func (n *NotificationEntry1) AddBankTransactionCode() *BankTransactionCodeStructure1 { n.BankTransactionCode = new(BankTransactionCodeStructure1) return n.BankTransactionCode } func (n *NotificationEntry1) SetCommissionWaiverIndicator(value string) { n.CommissionWaiverIndicator = (*YesNoIndicator)(&value) } func (n *NotificationEntry1) AddAdditionalInformationIndicator() *MessageIdentification2 { n.AdditionalInformationIndicator = new(MessageIdentification2) return n.AdditionalInformationIndicator } func (n *NotificationEntry1) AddBatch() *BatchInformation1 { newValue := new (BatchInformation1) n.Batch = append(n.Batch, newValue) return newValue } func (n *NotificationEntry1) AddAmountDetails() *AmountAndCurrencyExchange2 { n.AmountDetails = new(AmountAndCurrencyExchange2) return n.AmountDetails } func (n *NotificationEntry1) AddCharges() *ChargesInformation3 { newValue := new (ChargesInformation3) n.Charges = append(n.Charges, newValue) return newValue } func (n *NotificationEntry1) AddInterest() *TransactionInterest1 { newValue := new (TransactionInterest1) n.Interest = append(n.Interest, newValue) return newValue } func (n *NotificationEntry1) AddTransactionDetails() *EntryTransaction1 { newValue := new (EntryTransaction1) n.TransactionDetails = append(n.TransactionDetails, newValue) return newValue } func (n *NotificationEntry1) SetAdditionalEntryInformation(value string) { n.AdditionalEntryInformation = (*Max500Text)(&value) }
NotificationEntry1.go
0.812756
0.438545
NotificationEntry1.go
starcoder
package cryptypes import "database/sql/driver" // EncryptedInt16 supports encrypting Int16 data type EncryptedInt16 struct { Field Raw int16 } // Scan converts the value from the DB into a usable EncryptedInt16 value func (s *EncryptedInt16) Scan(value interface{}) error { return decrypt(value.([]byte), &s.Raw) } // Value converts an initialized EncryptedInt16 value into a value that can safely be stored in the DB func (s EncryptedInt16) Value() (driver.Value, error) { return encrypt(s.Raw) } // NullEncryptedInt16 supports encrypting nullable Int16 data type NullEncryptedInt16 struct { Field Raw int16 Empty bool } // Scan converts the value from the DB into a usable NullEncryptedInt16 value func (s *NullEncryptedInt16) Scan(value interface{}) error { if value == nil { s.Raw = 0 s.Empty = true return nil } return decrypt(value.([]byte), &s.Raw) } // Value converts an initialized NullEncryptedInt16 value into a value that can safely be stored in the DB func (s NullEncryptedInt16) Value() (driver.Value, error) { if s.Empty { return nil, nil } return encrypt(s.Raw) } // SignedInt16 supports signing Int16 data type SignedInt16 struct { Field Raw int16 Valid bool } // Scan converts the value from the DB into a usable SignedInt16 value func (s *SignedInt16) Scan(value interface{}) (err error) { s.Valid, err = verify(value.([]byte), &s.Raw) return } // Value converts an initialized SignedInt16 value into a value that can safely be stored in the DB func (s SignedInt16) Value() (driver.Value, error) { return sign(s.Raw) } // NullSignedInt16 supports signing nullable Int16 data type NullSignedInt16 struct { Field Raw int16 Empty bool Valid bool } // Scan converts the value from the DB into a usable NullSignedInt16 value func (s *NullSignedInt16) Scan(value interface{}) (err error) { if value == nil { s.Raw = 0 s.Empty = true s.Valid = true return nil } s.Valid, err = verify(value.([]byte), &s.Raw) return } // Value converts an initialized NullSignedInt16 value into a value that can safely be stored in the DB func (s NullSignedInt16) Value() (driver.Value, error) { if s.Empty { return nil, nil } return sign(s.Raw) } // SignedEncryptedInt16 supports signing and encrypting Int16 data type SignedEncryptedInt16 struct { Field Raw int16 Valid bool } // Scan converts the value from the DB into a usable SignedEncryptedInt16 value func (s *SignedEncryptedInt16) Scan(value interface{}) (err error) { s.Valid, err = decryptVerify(value.([]byte), &s.Raw) return } // Value converts an initialized SignedEncryptedInt16 value into a value that can safely be stored in the DB func (s SignedEncryptedInt16) Value() (driver.Value, error) { return encryptSign(s.Raw) } // NullSignedEncryptedInt16 supports signing and encrypting nullable Int16 data type NullSignedEncryptedInt16 struct { Field Raw int16 Empty bool Valid bool } // Scan converts the value from the DB into a usable NullSignedEncryptedInt16 value func (s *NullSignedEncryptedInt16) Scan(value interface{}) (err error) { if value == nil { s.Raw = 0 s.Empty = true s.Valid = true return nil } s.Valid, err = decryptVerify(value.([]byte), &s.Raw) return } // Value converts an initialized NullSignedEncryptedInt16 value into a value that can safely be stored in the DB func (s NullSignedEncryptedInt16) Value() (driver.Value, error) { if s.Empty { return nil, nil } return encryptSign(s.Raw) }
cryptypes/type_int16.go
0.794385
0.491578
type_int16.go
starcoder
package vector import ( "fmt" "math" //"strconv" ) const prec = 6 type Vector struct { coordinates []float64 dimension int } func New(c []float64) Vector { return Vector{c, len(c)} } func (v Vector) String() string { s := "" for i := 0; i < v.dimension-1; i++ { s += fmt.Sprintf("%.2f, ", v.coordinates[i]) } return "Vector: " + s + fmt.Sprintf("%.2f", v.coordinates[v.dimension-1]) } func (v Vector) Eq(w Vector) bool { if v.dimension != w.dimension { panic("Vector should have the same dimension") } for i := 0; i < v.dimension; i++ { if v.coordinates[i] != w.coordinates[i] { return false } } return true } func (v Vector) Add(w Vector) Vector { if v.dimension != w.dimension { panic("Vector should have the same dimension") } r := []float64{} for i := 0; i < v.dimension; i++ { r = append(r, v.coordinates[i]+w.coordinates[i]) } return New(r) } func (v Vector) Sub(w Vector) Vector { if v.dimension != w.dimension { panic("Vector should have the same dimension") } r := []float64{} for i := 0; i < v.dimension; i++ { r = append(r, v.coordinates[i]-w.coordinates[i]) } return New(r) } func (v Vector) Dot(w Vector) float64 { if v.dimension != w.dimension { panic("Vector should have the same dimension") } var r float64 for i := 0; i < v.dimension; i++ { r += v.coordinates[i] * w.coordinates[i] } return r } func (v Vector) Scalar(num float64) Vector { r := []float64{} for i := 0; i < v.dimension; i++ { r = append(r, v.coordinates[i]*num) } return New(r) } func (v Vector) Magnitude() float64 { var s float64 for i := 0; i < v.dimension; i++ { s += math.Pow(v.coordinates[i], 2.0) } return math.Sqrt(s) } func (v Vector) Normalize() Vector { m := v.Magnitude() r := []float64{} for i := 0; i < v.dimension; i++ { r = append(r, v.coordinates[i]/m) } return New(r) } func (v Vector) Angle(w Vector, inDegree bool) float64 { d := v.Dot(w) mag := toFixed(v.Magnitude()*w.Magnitude(), prec) if inDegree { return toFixed(math.Acos(d/mag)*180.0/math.Pi, prec) } return toFixed(math.Acos(d/mag), prec) } func (v Vector) Paraller(w Vector) bool { a := v.Angle(w, true) if a == 0.0 || a == 180.0 { return true } return false } func (v Vector) Orthogonal(w Vector) bool { if v.Angle(w, true) == 90.0 { return true } return false } func (v Vector) Proj(w Vector) Vector { return v.Normalize().Scalar(v.Normalize().Dot(w)) } func round(num float64) int { return int(num + math.Copysign(0.5, num)) } func toFixed(num float64, precision int) float64 { output := math.Pow(10, float64(precision)) return float64(round(num*output)) / output }
vector.go
0.793106
0.499756
vector.go
starcoder
package geom import ( "errors" "math" ) // ErrPointsAreCoLinear is thrown when points are colinear but that is unexpected var ErrPointsAreCoLinear = errors.New("given points are colinear") // Circle is a point (float tuple) and a radius type Circle struct { Center [2]float64 Radius float64 } // IsColinear returns weather the a,b,c are colinear to each other func IsColinear(a, b, c [2]float64) bool { xA, yA, xB, yB, xC, yC := a[0], a[1], b[0], b[1], c[0], c[1] return ((yB - yA) * (xC - xB)) == ((yC - yB) * (xB - xA)) } // CircleFromPoints returns the circle from by the given points, or an error if the points are colinear. // REF: Formula used gotten from http://mathforum.org/library/drmath/view/55233.html func CircleFromPoints(a, b, c [2]float64) (Circle, error) { xA, yA, xB, yB, xC, yC := a[0], a[1], b[0], b[1], c[0], c[1] if ((yB - yA) * (xC - xB)) == ((yC - yB) * (xB - xA)) { return Circle{}, ErrPointsAreCoLinear } xDeltaA, xDeltaB := xB-xA, xC-xB // Rotate the points if inital set is not ideal // This will terminate as we have already done the Colinear check above. for xDeltaA == 0 || xDeltaB == 0 { xA, yA, xB, yB, xC, yC = xB, yB, xC, yC, xA, yA xDeltaA, xDeltaB = xB-xA, xC-xB } yDeltaA, yDeltaB := yB-yA, yC-yB midAB := [2]float64{(xA + xB) / 2, (yA + yB) / 2} midBC := [2]float64{(xB + xC) / 2, (yB + yC) / 2} var x, y float64 switch { case yDeltaA == 0 && xDeltaB == 0: // slopeA && slopeB == ∞ x, y = midAB[0], midBC[1] case yDeltaA == 0 && xDeltaB != 0: slopeB := yDeltaB / xDeltaB x = midAB[0] y = midBC[1] + ((midBC[0] - x) / slopeB) case yDeltaB == 0 && xDeltaA == 0: x, y = midBC[0], midAB[1] case yDeltaB == 0 && xDeltaA != 0: slopeA := yDeltaA / xDeltaA x = midBC[0] y = midAB[1] + (midAB[0]-x)/slopeA case xDeltaA == 0: slopeB := yDeltaB / xDeltaB y = midBC[1] x = slopeB*(midBC[1]-y) + midBC[0] case xDeltaB == 0: slopeA := yDeltaA / xDeltaA y = midBC[1] x = slopeA*(midAB[1]-y) + midAB[0] default: slopeA := yDeltaA / xDeltaA slopeB := yDeltaB / xDeltaB x = (((slopeA * slopeB * (yA - yC)) + (slopeB * (xA + xB)) - (slopeA * (xB + xC))) / (2 * (slopeB - slopeA))) y = (-1/slopeA)*(x-(xA+xB)*0.5) + ((yA + yB) * 0.5) } // get the correct slopes vA, vB := x-xA, y-yA r := math.Sqrt((vA * vA) + (vB * vB)) return Circle{ Center: [2]float64{x, y}, Radius: RoundToPrec(r, 4), }, nil } // ContainsPoint will check to see if the point is in the circle. func (c Circle) ContainsPoint(pt [2]float64) bool { // get the distance between the center and the point, and if it's greater then the radius it's outside // of the circle. v1, v2 := c.Center[0]-pt[0], c.Center[1]-pt[1] d := math.Sqrt((v1 * v1) + (v2 * v2)) d = RoundToPrec(d, 3) return c.Radius >= d } func (c Circle) AsPoints(k uint) []Point { if k < 3 { k = 30 } pts := make([]Point, int(k)) for i := 0; i < int(k); i++ { t := (2 * math.Pi) * (float64(i) / float64(k)) x, y := c.Center[0]+c.Radius*math.Cos(t), c.Center[1]+c.Radius*math.Sin(t) pts[i][0], pts[i][1] = float64(x), float64(y) } return pts } func (c Circle) AsLineString(k uint) LineString { pts := c.AsPoints(k) lns := make(LineString, len(pts)) for i := range pts { lns[i] = [2]float64(pts[i]) } return lns } // AsSegments takes the number of segments that should be returned to describe the circle. // a value less then 3 will use the default value of 30. func (c Circle) AsSegments(k uint) []Line { pts := c.AsPoints(k) lines := make([]Line, len(pts)) for i := range pts { j := i - 1 if j < 0 { j = int(k) - 1 } lines[i][0] = pts[j] lines[i][1] = pts[i] } return lines }
vendor/github.com/go-spatial/geom/circle.go
0.856377
0.716653
circle.go
starcoder
package core import ( "github.com/nuberu/engine/math" ) type IGeometry interface { ApplyMatrix(m *math.Matrix4) RotateX(a math.Angle) RotateY(a math.Angle) RotateZ(a math.Angle) Translate(x, y, z float32) Scale(x, y, z float32) LookAt(v *math.Vector3) Center() Normalize() } // The basic geometry type Geometry struct { IGeometry vertices []*math.Vector3 faces []*Face3 boundingBox *math.Box3 boundingSphere *math.Sphere verticesNeedUpdate bool normalsNeedUpdate bool } func (geo *Geometry) GetBoundingBox() *math.Box3 { if geo.boundingBox == nil { geo.computeBoundingBox() } return geo.boundingBox } func (geo *Geometry) GetBoundingSphere() *math.Sphere { if geo.boundingSphere == nil { geo.computeBoundingSphere() } return geo.boundingSphere } func (geo *Geometry) ApplyMatrix(matrix *math.Matrix4) { normalMatrix := math.NewDefaultMatrix3() normalMatrix.SetNormalMatrix(matrix) for i := 0; i < len(geo.vertices); i++ { vertex := geo.vertices[i] vertex.ApplyMatrix4(matrix) } for i := 0; i < len(geo.faces); i ++ { face := geo.faces[i] face.Normal.ApplyMatrix3(normalMatrix) face.Normal.Normalize() for j := 0; j < len(face.VertexNormals); j++ { face.VertexNormals[j].ApplyMatrix3(normalMatrix) face.VertexNormals[j].Normalize() } } if geo.boundingBox != nil { geo.computeBoundingBox() } if geo.boundingSphere != nil { geo.computeBoundingSphere() } geo.verticesNeedUpdate = true geo.normalsNeedUpdate = true } func (geo *Geometry) RotateX(angle math.Angle) { m1 := math.NewMatrix4RotationX(angle) geo.ApplyMatrix(m1) } func (geo *Geometry) RotateY(angle math.Angle) { m1 := math.NewMatrix4RotationY(angle) geo.ApplyMatrix(m1) } func (geo *Geometry) RotateZ(angle math.Angle) { m1 := math.NewMatrix4RotationZ(angle) geo.ApplyMatrix(m1) } func (geo *Geometry) Translate(x, y, z float32) { m1 := math.NewMatrix4Translation(x, y, z) geo.ApplyMatrix(m1) } func (geo *Geometry) TranslateVector3(v *math.Vector3) { geo.Translate(v.X, v.Y, v.Z) } func (geo *Geometry) Scale(x, y, z float32) { m1 := math.NewMatrix4Scale(x, y, z) geo.ApplyMatrix(m1) } func (geo *Geometry) LookAt(vector *math.Vector3) { obj := NewObject() obj.LookAt(vector) obj.UpdateMatrix() } func (geo *Geometry) Center() { geo.computeBoundingBox() offset := geo.boundingBox.GetCenter() offset.Negate() geo.TranslateVector3(offset) } func (geo *Geometry) Normalize() { geo.computeBoundingSphere() var center = geo.boundingSphere.Center var radius = geo.boundingSphere.Radius s := float32(0) if radius == 0 { s = 1.0 / radius } var matrix = math.NewDefaultMatrix4() matrix.Set( s, 0, 0, - s*center.X, 0, s, 0, - s*center.Y, 0, 0, s, - s*center.Z, 0, 0, 0, 1, ) geo.ApplyMatrix(matrix) } func (geo *Geometry) computeBoundingBox() { if geo.boundingBox == nil { geo.boundingBox = math.NewDefaultBox3() } geo.boundingBox.SetFromPoints(geo.vertices) } func (geo *Geometry) computeBoundingSphere() { if geo.boundingSphere == nil { geo.boundingSphere = math.NewDefaultSphere() } geo.boundingSphere.SetFromPoints(geo.vertices) }
core/geometry.go
0.728169
0.579341
geometry.go
starcoder
package g3 type Frustum struct { Left, Right Plane Top, Bottom Plane Near, Far Plane } func MakeFrustumFromMatrix(m *Matrix4x4) *Frustum { left := Plane{Vec3{m.M41 + m.M11, m.M42 + m.M12, m.M43 + m.M13}, m.M44 + m.M14} left.Normalize() right := Plane{Vec3{m.M41 - m.M11, m.M42 - m.M12, m.M43 - m.M13}, m.M44 - m.M14} right.Normalize() top := Plane{Vec3{m.M41 - m.M21, m.M42 - m.M22, m.M43 - m.M23}, m.M44 - m.M24} top.Normalize() bottom := Plane{Vec3{m.M41 + m.M21, m.M42 + m.M22, m.M43 + m.M23}, m.M44 + m.M24} bottom.Normalize() near := Plane{Vec3{m.M41 + m.M31, m.M42 + m.M32, m.M43 + m.M33}, m.M44 + m.M34} near.Normalize() far := Plane{Vec3{m.M41 - m.M31, m.M42 - m.M32, m.M43 - m.M33}, m.M44 - m.M34} far.Normalize() /* left := Plane{Vec3{m.M14 + m.M11, m.M24 + m.M21, m.M34 + m.M31}, m.M44 + m.M41} left.Normalize() right := Plane{Vec3{m.M14 - m.M11, m.M24 - m.M11, m.M34 - m.M31}, m.M44 - m.M41} right.Normalize() top := Plane{Vec3{m.M14 - m.M12, m.M24 - m.M22, m.M34 - m.M32}, m.M44 - m.M42} top.Normalize() bottom := Plane{Vec3{m.M14 + m.M12, m.M24 + m.M22, m.M34 + m.M32}, m.M44 + m.M42} bottom.Normalize() near := Plane{Vec3{m.M14 + m.M31, m.M24 + m.M23, m.M34 + m.M33}, m.M44 + m.M43} near.Normalize() far := Plane{Vec3{m.M14 - m.M13, m.M24 - m.M23, m.M34 - m.M33}, m.M44 - m.M43} far.Normalize() */ return &Frustum{left, right, top, bottom, near, far} } func (frustum *Frustum) ClipBoundingVolume(bvol BoundingVolume) bool { if bvol.ClassifyPlane(&frustum.Left) == 0 { return false } if bvol.ClassifyPlane(&frustum.Right) == 0 { return false } if bvol.ClassifyPlane(&frustum.Top) == 0 { return false } if bvol.ClassifyPlane(&frustum.Bottom) == 0 { return false } if bvol.ClassifyPlane(&frustum.Near) == 0 { return false } if bvol.ClassifyPlane(&frustum.Far) == 0 { return false } return true } func (frustum *Frustum) ClipPoint(v *Vec3) bool { if frustum.Left.DistanceToPoint(v) < 0.0 { return false } if frustum.Right.DistanceToPoint(v) < 0.0 { return false } if frustum.Top.DistanceToPoint(v) < 0.0 { return false } if frustum.Bottom.DistanceToPoint(v) < 0.0 { return false } if frustum.Near.DistanceToPoint(v) < 0.0 { return false } if frustum.Far.DistanceToPoint(v) < 0.0 { return false } return true } // TODO: ClipSphere
src/pkg/g3/frustum.go
0.541409
0.525551
frustum.go
starcoder
package nist_sp800_22 import ( "math" ) // Input Size Recommendation // Choose m and n such that m < floor(log_2 (n))- 2. func Serial(m uint64, n uint64) ([]float64, []bool, error) { var v [][]uint64 = make([][]uint64, 3) var section2_index uint64 for section2_index = 0; section2_index <= 2; section2_index++ { // (1) Form an augmented sequence ε′: // Extend the sequence by appending the first m-1 bits to the end of the sequence for distinct values of n. if int64(m)-int64(section2_index)-1 < 0 { break } appendedEpsilon := append(epsilon, epsilon[0:m-section2_index-1]...) var blockSize uint64 = m - section2_index var blockIndex uint64 v[section2_index] = make([]uint64, uint64(math.Pow(2.0, float64(blockSize)))) // (2) Determine the frequency of all possible overlapping m-bit blocks // the frequency of all possible overlapping m-bit blocks for blockIndex = 0; blockIndex <= uint64(len(appendedEpsilon))-blockSize; blockIndex++ { for vIndex := range v[section2_index] { if isEqualBetweenBitsArray(appendedEpsilon[blockIndex:blockIndex+blockSize], Uint_To_BitsArray_size_N(uint64(vIndex), blockSize)) { v[section2_index][vIndex]++ } } } } // (3) Compute ψ var psi [3]float64 = [3]float64{0, 0, 0} // ψ_m = psi[0] / ψ_{m-1} = psi[1] / ψ_{m-2} = psi[2] for i := range psi { if len(v[i]) == 0 { break } for _, value := range v[i] { psi[i] += float64(value) * float64(value) } psi[i] = math.Pow(2.0, float64(m)-float64(i))/float64(n)*psi[i] - float64(n) // CAUTION :: Possible to happen Floating-point error mitigation } //fmt.Println("PSI: ", psi) // (4) Compute ∇ψ^2 and ∇^2ψ^2 delta1 := psi[0] - psi[1] delta2 := psi[0] - 2*psi[1] + psi[2] //fmt.Println("Delta1:", delta1) //fmt.Println("Delta2:", delta2) // (5) Compute P_value var tempArg float64 = math.Pow(2.0, float64(m-2)) P_value1 := igamc(tempArg, delta1/2.0) P_value2 := igamc(tempArg/2.0, delta2/2.0) retP_value := []float64{P_value1, P_value2} retBools := []bool{DecisionRule(P_value1, LEVEL), DecisionRule(P_value2, LEVEL)} return retP_value, retBools, nil }
nist_sp800_22/serial.go
0.52683
0.511717
serial.go
starcoder
package geometry import ( "math" ) type Matrix interface { Assessor } func Homogenous1x2() Mat1x2 { return Mat1x2{0, 1} } func Homogenous1x3() Mat1x3 { return Mat1x3{0, 0, 1} } func Homogenous1x4() Mat1x4 { return Mat1x4{0, 0, 0, 1} } func Homogenous2x1() Mat2x1 { return Mat2x1{ Mat1x1{0}, Mat1x1{1}, } } func Homogenous3x1() Mat3x1 { return Mat3x1{ Mat1x1{0}, Mat1x1{0}, Mat1x1{1}, } } func Homogenous4x1() Mat4x1 { return Mat4x1{ Mat1x1{0}, Mat1x1{0}, Mat1x1{0}, Mat1x1{1}, } } func Identity1() Mat1x1 { return Mat1x1{1} } func Identity2() Mat2x2 { return Mat2x2{ Mat1x2{1, 0}, Mat1x2{0, 1}, } } func Identity3() Mat3x3 { return Mat3x3{ Mat1x3{1, 0, 0}, Mat1x3{0, 1, 0}, Mat1x3{0, 0, 1}, } } func Identity4() Mat4x4 { return Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, 1, 0, 0}, Mat1x4{0, 0, 1, 0}, Mat1x4{0, 0, 0, 1}, } } func LinearReflect1() Mat1x1 { return Mat1x1{-1} } func LinearReflect2(Γ Vec2) Mat2x2 { return Mat2x2{ Mat1x2{Γ[0], 0}, Mat1x2{0, Γ[1]}, } } func LinearReflect3(Γ Vec3) Mat3x3 { return Mat3x3{ Mat1x3{Γ[0], 0, 0}, Mat1x3{0, Γ[1], 0}, Mat1x3{0, 0, Γ[2]}, } } //Takes in a Vec3 comprised of 1s and/or -1s. If the value in the vector are anything else, scaling may take place func LinearReflect4(Γ Vec4) Mat4x4 { return Mat4x4{ Mat1x4{Γ[0], 0, 0, 0}, Mat1x4{0, Γ[1], 0, 0}, Mat1x4{0, 0, Γ[2], 0}, Mat1x4{0, 0, 0, Γ[3]}, } } //Takes one angle representing the subsequent rotation in the imaginary XY plane. func LinearRotate2(Θ float64) Mat2x2 { return Mat2x2{ Mat1x2{math.Cos(Θ), -math.Sin(Θ)}, Mat1x2{math.Sin(Θ), math.Cos(Θ)}, } } //Takes up to three angles representing the subsequent rotation in each plane. Order is as follows: YZ, XZ, XY func LinearRotate3(Θ Vec3) Mat3x3 { var planes int for i, θ := range Θ { if θ != 0 { planes |= 1 << uint(i) } } if planes == 0 { return Identity3() } var c, s float64 var a, b Mat3x3 switch { //X-axis rotation //Rotate in the YZ plane. case planes&1 > 0: c, s = math.Cos(Θ[0]), math.Sin(Θ[0]) a = Mat3x3{ Mat1x3{1, 0, 0}, Mat1x3{0, c, -s}, Mat1x3{0, s, c}, } fallthrough //Y-axis rotation //Rotate in the XZ plane. case planes&2 > 0: c, s = math.Cos(Θ[1]), math.Sin(Θ[1]) b = Mat3x3{ Mat1x3{c, 0, s}, Mat1x3{0, 1, 0}, Mat1x3{-s, 0, c}, } if planes&1 == 0 { a = b } else { a = a.MultiplyMat3x3(b) } fallthrough //Z-axis rotation //Rotate in the XY plane. case planes&4 > 0: c, s = math.Cos(Θ[2]), math.Sin(Θ[2]) b = Mat3x3{ Mat1x3{c, -s, 0}, Mat1x3{s, c, 0}, Mat1x3{0, 0, 1}, } if planes&3 == 0 { a = b } else { a = a.MultiplyMat3x3(b) } } return a } //Z-axis rotation //Rotate in the XY plane. func LinearRotate3XY(Θ float64) Mat3x3 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat3x3{ Mat1x3{c, -s, 0}, Mat1x3{s, c, 0}, Mat1x3{0, 0, 1}, } } //Y-axis rotation //Rotate in the XZ plane. func LinearRotate3XZ(Θ float64) Mat3x3 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat3x3{ Mat1x3{c, 0, s}, Mat1x3{0, 1, 0}, Mat1x3{-s, 0, c}, } } //X-axis rotation //Rotate in the YZ plane. func LinearRotate3YZ(Θ float64) Mat3x3 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat3x3{ Mat1x3{1, 0, 0}, Mat1x3{0, c, -s}, Mat1x3{0, s, c}, } } /* 4D Rotation. Rotation happens in a plane. Just as 2D rotations happen in a plane perpendicular to the imaginary Z-axis (XY), and 3D rotations happen in 3 planes (XY, XZ, YZ), so 4D has six rotations planes (XY, XZ, XW, YZ, YW, ZW). Interestingly, the number of planes in an arbitrary dimension corresponds to a triangular number (0, 1, 3, 6, 10, 15, 21, 28, 36, etc). Two Dimensions: XY Three Dimensions: XY XZ YZ Four Dimensions: XY XZ XW YZ YW ZW See a pattern? */ //Takes up to six angles representing the subsequent rotation in each plane. Order is as follows: ZW, YW, YZ, XW, XZ, XY func LinearRotate4(Θ [6]float64) Mat4x4 { var planes int for i, θ := range Θ { if θ != 0 { planes |= 1 << uint(i) } } if planes == 0 { return Identity4() } var c, s float64 var a, b Mat4x4 switch { //Rotate in the ZW plane. case planes&1 > 0: c, s = math.Cos(Θ[0]), math.Sin(Θ[0]) a = Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, 1, 0, 0}, Mat1x4{0, 0, c, -s}, Mat1x4{0, 0, s, c}, } fallthrough //Rotate in the YW plane. case planes&2 > 0: c, s = math.Cos(Θ[1]), math.Sin(Θ[1]) b = Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, c, 0, -s}, Mat1x4{0, 0, 1, 0}, Mat1x4{0, s, 0, c}, } if planes&1 == 0 { a = b } else { a = a.MultiplyMat4x4(b) } fallthrough //Rotate in the YZ plane. case planes&4 > 0: c, s = math.Cos(Θ[2]), math.Sin(Θ[2]) b = Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, c, s, 0}, Mat1x4{0, -s, c, 0}, Mat1x4{0, 0, 0, 1}, } if planes&3 == 0 { a = b } else { a = a.MultiplyMat4x4(b) } fallthrough //Rotate in the XW plane. case planes&8 > 0: c, s = math.Cos(Θ[3]), math.Sin(Θ[3]) b = Mat4x4{ Mat1x4{c, 0, 0, s}, Mat1x4{0, 1, 0, 0}, Mat1x4{0, 0, 1, 0}, Mat1x4{-s, 0, 0, c}, } if planes&7 == 0 { a = b } else { a = a.MultiplyMat4x4(b) } fallthrough //Rotate in the XZ plane. case planes&16 > 0: c, s = math.Cos(Θ[4]), math.Sin(Θ[4]) b = Mat4x4{ Mat1x4{c, 0, -s, 0}, Mat1x4{0, 1, 0, 0}, Mat1x4{s, 0, c, 0}, Mat1x4{0, 0, 0, 1}, } if planes&15 == 0 { a = b } else { a = a.MultiplyMat4x4(b) } fallthrough //Rotate in the XY plane. case planes&32 > 0: c, s = math.Cos(Θ[5]), math.Sin(Θ[5]) b = Mat4x4{ Mat1x4{c, s, 0, 0}, Mat1x4{-s, c, 0, 0}, Mat1x4{0, 0, 1, 0}, Mat1x4{0, 0, 0, 1}, } if planes&31 == 0 { a = b } else { a = a.MultiplyMat4x4(b) } } return a } //Rotate in the XY plane. func LinearRotate4XY(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{c, s, 0, 0}, Mat1x4{-s, c, 0, 0}, Mat1x4{0, 0, 1, 0}, Mat1x4{0, 0, 0, 1}, } } //Rotate in the XZ plane. func LinearRotate4XZ(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{c, 0, -s, 0}, Mat1x4{0, 1, 0, 0}, Mat1x4{s, 0, c, 0}, Mat1x4{0, 0, 0, 1}, } } //Rotate in the XW plane. func LinearRotate4XW(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{c, 0, 0, s}, Mat1x4{0, 1, 0, 0}, Mat1x4{0, 0, 1, 0}, Mat1x4{-s, 0, 0, c}, } } //Rotate in the YZ plane. func LinearRotate4YZ(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, c, s, 0}, Mat1x4{0, -s, c, 0}, Mat1x4{0, 0, 0, 1}, } } //Rotate in the YW plane. func LinearRotate4YW(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, c, 0, -s}, Mat1x4{0, 0, 1, 0}, Mat1x4{0, s, 0, c}, } } //Rotate in the ZW plane. func LinearRotate4ZW(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, 1, 0, 0}, Mat1x4{0, 0, c, -s}, Mat1x4{0, 0, s, c}, } } func LinearScale1(s Vec1) Mat1x1 { return Mat1x1{s[0]} } func LinearScale2(s Vec2) Mat2x2 { return Mat2x2{ Mat1x2{s[0], 0}, Mat1x2{0, s[1]}, } } func LinearScale3(s Vec3) Mat3x3 { return Mat3x3{ Mat1x3{s[0], 0, 0}, Mat1x3{0, s[1], 0}, Mat1x3{0, 0, s[2]}, } } func LinearScale4(s Vec4) Mat4x4 { return Mat4x4{ Mat1x4{s[0], 0, 0, 0}, Mat1x4{0, s[1], 0, 0}, Mat1x4{0, 0, s[2], 0}, Mat1x4{0, 0, 0, s[3]}, } } func LinearShear2(τ Vec2) Mat2x2 { return Mat2x2{ Mat1x2{1, τ[0]}, Mat1x2{τ[1], 1}, } } func LinearShear3(τx, τy, τz Vec2) Mat3x3 { return Mat3x3{ Mat1x3{1, τy[0], τz[0]}, Mat1x3{τx[0], 1, τz[1]}, Mat1x3{τx[1], τy[1], 1}, } } func LinearShear4(τx, τy, τz, τw Vec3) Mat4x4 { return Mat4x4{ Mat1x4{1, τy[0], τz[0], τw[0]}, Mat1x4{τx[0], 1, τz[1], τw[1]}, Mat1x4{τx[1], τy[1], 1, τw[2]}, Mat1x4{τx[2], τy[2], τz[2], 1}, } } func LinearTranslate1(δ Vec1) Mat1x1 { return Mat1x1{δ[0]} } func LinearTranslate2(δ Vec2) Mat2x2 { return Mat2x2{ Mat1x2{1, δ[0]}, Mat1x2{0, δ[1]}, } } func LinearTranslate3(δ Vec3) Mat3x3 { return Mat3x3{ Mat1x3{1, 0, δ[0]}, Mat1x3{0, 1, δ[1]}, Mat1x3{0, 0, δ[2]}, } } func LinearTranslate4(δ Vec4) Mat4x4 { return Mat4x4{ Mat1x4{1, 0, 0, δ[0]}, Mat1x4{0, 1, 0, δ[1]}, Mat1x4{0, 0, 1, δ[2]}, Mat1x4{0, 0, 0, δ[3]}, } } func Reflect2() Mat2x2 { return Mat2x2{ Mat1x2{-1, 0}, Mat1x2{0, 1}, } } func Reflect3(Γ Vec2) Mat3x3 { return Mat3x3{ Mat1x3{Γ[0], 0, 0}, Mat1x3{0, Γ[1], 0}, Mat1x3{0, 0, 1}, } } //Takes in a Vec3 comprised of 1s and/or -1s. If the value in the vector are anything else, scaling may take place func Reflect4(Γ Vec3) Mat4x4 { return Mat4x4{ Mat1x4{Γ[0], 0, 0, 0}, Mat1x4{0, Γ[1], 0, 0}, Mat1x4{0, 0, Γ[2], 0}, Mat1x4{0, 0, 0, 1}, } } func Rotate3(Θ float64) Mat3x3 { return Mat3x3{ Mat1x3{math.Cos(Θ), -math.Sin(Θ), 0}, Mat1x3{math.Sin(Θ), math.Cos(Θ), 0}, Mat1x3{0, 0, 1}, } } func Rotate4(Θ Vec3) Mat4x4 { var planes int for i, θ := range Θ { if θ != 0 { planes |= 1 << uint(i) } } if planes == 0 { return Identity4() } var c, s float64 var a, b Mat4x4 switch { //X-axis rotation //Rotate in the YZ plane. case planes&1 > 0: c, s = math.Cos(Θ[0]), math.Sin(Θ[0]) a = Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, c, -s, 0}, Mat1x4{0, s, c, 0}, Mat1x4{0, 0, 0, 1}, } fallthrough //Y-axis rotation //Rotate in the XZ plane. case planes&2 > 0: c, s = math.Cos(Θ[1]), math.Sin(Θ[1]) b = Mat4x4{ Mat1x4{c, 0, s, 0}, Mat1x4{0, 1, 0, 0}, Mat1x4{-s, 0, c, 0}, Mat1x4{0, 0, 0, 1}, } if planes&1 == 0 { a = b } else { a = a.MultiplyMat4x4(b) } fallthrough //Z-axis rotation //Rotate in the XY plane. case planes&4 > 0: c, s = math.Cos(Θ[2]), math.Sin(Θ[2]) b = Mat4x4{ Mat1x4{c, -s, 0, 0}, Mat1x4{s, c, 0, 0}, Mat1x4{0, 0, 1, 0}, Mat1x4{0, 0, 0, 1}, } if planes&3 == 0 { a = b } else { a = a.MultiplyMat4x4(b) } } return a } func Rotate4X(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{1, 0, 0, 0}, Mat1x4{0, c, -s, 0}, Mat1x4{0, s, c, 0}, Mat1x4{0, 0, 0, 1}, } } func Rotate4Y(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{c, 0, s, 0}, Mat1x4{0, 1, 0, 0}, Mat1x4{-s, 0, c, 0}, Mat1x4{0, 0, 0, 1}, } } func Rotate4Z(Θ float64) Mat4x4 { c, s := math.Cos(Θ), math.Sin(Θ) return Mat4x4{ Mat1x4{c, -s, 0, 0}, Mat1x4{s, c, 0, 0}, Mat1x4{0, 0, 1, 0}, Mat1x4{0, 0, 0, 1}, } } func Scale2(Δ Vec1) Mat2x2 { return Mat2x2{ Mat1x2{Δ[0], 0}, Mat1x2{0, 1}, } } func Scale3(Δ Vec2) Mat3x3 { return Mat3x3{ Mat1x3{Δ[0], 0, 0}, Mat1x3{0, Δ[1], 0}, Mat1x3{0, 0, 1}, } } func Scale4(Δ Vec3) Mat4x4 { return Mat4x4{ Mat1x4{Δ[0], 0, 0, 0}, Mat1x4{0, Δ[1], 0, 0}, Mat1x4{0, 0, Δ[2], 0}, Mat1x4{0, 0, 0, 1}, } } func Shear3(τ Vec2) Mat3x3 { return Mat3x3{ Mat1x3{1, τ[0], 0}, Mat1x3{τ[1], 1, 0}, Mat1x3{0, 0, 1}, } } func Shear4(τx, τy, τz Vec2) Mat4x4 { return Mat4x4{ Mat1x4{1, τy[0], τz[0], 0}, Mat1x4{τx[0], 1, τz[1], 0}, Mat1x4{τx[1], τy[1], 1, 0}, Mat1x4{0, 0, 0, 1}, } } func Translate2(δ Vec1) Mat2x2 { return Mat2x2{ Mat1x2{1, δ[0]}, Mat1x2{0, 1}, } } func Translate3(δ Vec2) Mat3x3 { return Mat3x3{ Mat1x3{1, 0, δ[0]}, Mat1x3{0, 1, δ[1]}, Mat1x3{0, 0, 1}, } } func Translate4(δ Vec3) Mat4x4 { return Mat4x4{ Mat1x4{1, 0, 0, δ[0]}, Mat1x4{0, 1, 0, δ[1]}, Mat1x4{0, 0, 1, δ[2]}, Mat1x4{0, 0, 0, 1}, } }
matrix.go
0.823825
0.785597
matrix.go
starcoder
package geo import ( "math" ) // vec3I represents a 3D vector typed as int32 type vec3I struct { X int32 // X coordinate Y int32 // Y coordinate Z int32 // Z coordinate } const micronsAccuracy = 1E-6 func newvec3IFromVec3(vec Point3D) vec3I { a := vec3I{ X: int32(math.Floor(float64(vec.X() / micronsAccuracy))), Y: int32(math.Floor(float64(vec.Y() / micronsAccuracy))), Z: int32(math.Floor(float64(vec.Z() / micronsAccuracy))), } return a } // vectorTree implements a n*log(n) lookup tree class to identify vectors by their position type vectorTree struct { entries map[vec3I]uint32 } func newVectorTree() *vectorTree { return &vectorTree{ entries: make(map[vec3I]uint32), } } // AddVector adds a vector to the dictionary. func (t *vectorTree) AddVector(vec Point3D, value uint32) { t.entries[newvec3IFromVec3(vec)] = value } // FindVector returns the identifier of the vector. func (t *vectorTree) FindVector(vec Point3D) (val uint32, ok bool) { val, ok = t.entries[newvec3IFromVec3(vec)] return } // RemoveVector removes the vector from the dictionary. func (t *vectorTree) RemoveVector(vec Point3D) { delete(t.entries, newvec3IFromVec3(vec)) } // Point3D defines a node of a mesh as an array of 3 coordinates: x, y and z. type Point3D [3]float32 // X returns the x coordinate. func (v1 Point3D) X() float32 { return v1[0] } // Y returns the y coordinate. func (v1 Point3D) Y() float32 { return v1[1] } // Z returns the z coordinate. func (v1 Point3D) Z() float32 { return v1[2] } // Add performs element-wise addition between two vectors. func (v1 Point3D) Add(v2 Point3D) Point3D { return Point3D{v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2]} } // Sub performs element-wise subtraction between two vectors. func (v1 Point3D) Sub(v2 Point3D) Point3D { return Point3D{v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2]} } // Len returns the vector's length. Note that this is NOT the dimension of // the vector (len(v)), but the mathematical length. func (v1 Point3D) Len() float32 { return float32(math.Sqrt(float64(v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2]))) } // Normalize normalizes the vector. Normalization is (1/|v|)*v, // making this equivalent to v.Scale(1/v.Len()). If the len is 0.0, // this function will return an infinite value for all elements due // to how floating point division works in Go (n/0.0 = math.Inf(Sign(n))). func (v1 Point3D) Normalize() Point3D { l := 1.0 / v1.Len() return Point3D{v1[0] * l, v1[1] * l, v1[2] * l} } // Cross product is most often used for finding surface normals. The cross product of vectors // will generate a vector that is perpendicular to the plane they form. func (v1 Point3D) Cross(v2 Point3D) Point3D { return Point3D{v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0]} } type nodeStructure struct { Nodes []Point3D vectorTree *vectorTree } // AddNode adds a node the the mesh at the target position. func (n *nodeStructure) AddNode(node Point3D) uint32 { if n.vectorTree != nil { if index, ok := n.vectorTree.FindVector(node); ok { return index } } n.Nodes = append(n.Nodes, node) index := uint32(len(n.Nodes)) - 1 if n.vectorTree != nil { n.vectorTree.AddVector(node, index) } return index }
geo/node.go
0.88674
0.698985
node.go
starcoder
package certs import ( "errors" "fmt" "github.com/deiscc/workflow-e2e/tests/cmd" "github.com/deiscc/workflow-e2e/tests/model" "github.com/deiscc/workflow-e2e/tests/settings" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" . "github.com/onsi/gomega/gexec" ) var ErrNoCertMatch = errors.New("\"No Certificate matches the given query.\"") // The functions in this file implement SUCCESS CASES for commonly used `deis certs` subcommands. // This allows each of these to be re-used easily in multiple contexts. // List executes `deis certs:list` as the specified user. func List(user model.User) *Session { sess, err := cmd.Start("deis certs:list", &user) Expect(err).NotTo(HaveOccurred()) Eventually(sess).Should(Exit(0)) return sess } // Add executes `deis certs:add` as the specified user to add the specified cert. func Add(user model.User, cert model.Cert) { sess, err := cmd.Start("deis certs:add %s %s %s", &user, cert.Name, cert.CertPath, cert.KeyPath) Eventually(sess).Should(Say("Adding SSL endpoint...")) Eventually(sess, settings.MaxEventuallyTimeout).Should(Say("done")) Expect(err).NotTo(HaveOccurred()) Eventually(sess).Should(Exit(0)) Eventually(List(user).Wait().Out.Contents()).Should(ContainSubstring(cert.Name)) } // Remove executes `deis certs:remove` as the specified user to remove the specified cert. func Remove(user model.User, cert model.Cert) { sess, err := cmd.Start("deis certs:remove %s", &user, cert.Name) Eventually(sess).Should(Say("Removing %s...", cert.Name)) Eventually(sess).Should(Say("done")) Expect(err).NotTo(HaveOccurred()) Eventually(sess).Should(Exit(0)) Eventually(List(user).Wait().Out.Contents()).ShouldNot(ContainSubstring(cert.Name)) } // Attach executes `deis certs:attach` as the specified user to attach the specified cert to the // specified domain. func Attach(user model.User, cert model.Cert, domain string) { sess, err := cmd.Start("deis certs:attach %s %s", &user, cert.Name, domain) // Explicitly build literal substring since 'domain' may be a wildcard domain ('*.foo.com') and // we don't want Gomega interpreting this string as a regexp Eventually(sess.Wait().Out.Contents()).Should(ContainSubstring(fmt.Sprintf("Attaching certificate %s to domain %s...", cert.Name, domain))) Eventually(sess, settings.MaxEventuallyTimeout).Should(Say("done")) Expect(err).NotTo(HaveOccurred()) Eventually(sess).Should(Exit(0)) } // Detatch executes `deis certs:detach` as the specified user to detach the specified cert from // the specified domain. func Detach(user model.User, cert model.Cert, domain string) { sess, err := cmd.Start("deis certs:detach %s %s", &user, cert.Name, domain) // Explicitly build literal substring since 'domain' may be a wildcard domain ('*.foo.com') and // we don't want Gomega interpreting this string as a regexp Eventually(sess.Wait().Out.Contents()).Should(ContainSubstring(fmt.Sprintf("Detaching certificate %s from domain %s...", cert.Name, domain))) Eventually(sess, settings.MaxEventuallyTimeout).Should(Say("done")) Expect(err).NotTo(HaveOccurred()) Eventually(sess).Should(Exit(0)) } // Info executes `deis certs:info` as the specified user to retrieve information about the // specified cert. func Info(user model.User, cert model.Cert) *Session { sess, err := cmd.Start("deis certs:info %s", &user, cert.Name) Eventually(sess).Should(Say("=== %s Certificate", cert.Name)) Expect(err).NotTo(HaveOccurred()) Eventually(sess).Should(Exit(0)) return sess }
tests/cmd/certs/commands.go
0.599485
0.44083
commands.go
starcoder
package util import ( "fmt" "strings" "time" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) const ( // a short time format; like time.Kitchen but with 24-hour notation. Kitchen24 = "15:04" // a time format that just cares about the day and month. YearDay = "Jan_2" ) // TimePeriod represents a time period with a single beginning and end. type TimePeriod struct { From time.Time To time.Time } // NewTimePeriod returns a normalized TimePeriod given a start and end time. func NewTimePeriod(from, to time.Time) TimePeriod { return TimePeriod{From: TimeOfDay(from), To: TimeOfDay(to)} } // Includes returns true iff the given pointInTime's time of day is included in time period tp. func (tp TimePeriod) Includes(pointInTime time.Time) bool { isAfter := TimeOfDay(pointInTime).After(tp.From) isBefore := TimeOfDay(pointInTime).Before(tp.To) if tp.From.Before(tp.To) { return isAfter && isBefore } if tp.From.After(tp.To) { return isAfter || isBefore } return TimeOfDay(pointInTime).Equal(tp.From) } // String returns tp as a pretty string. func (tp TimePeriod) String() string { return fmt.Sprintf("%s-%s", tp.From.Format(Kitchen24), tp.To.Format(Kitchen24)) } // ParseWeekdays takes a comma-separated list of abbreviated weekdays (e.g. sat,sun) and turns them // into a slice of time.Weekday. It ignores any whitespace and any invalid weekdays. func ParseWeekdays(weekdays string) []time.Weekday { var days = map[string]time.Weekday{ "sun": time.Sunday, "mon": time.Monday, "tue": time.Tuesday, "wed": time.Wednesday, "thu": time.Thursday, "fri": time.Friday, "sat": time.Saturday, } parsedWeekdays := []time.Weekday{} for _, wd := range strings.Split(weekdays, ",") { if day, ok := days[strings.TrimSpace(strings.ToLower(wd))]; ok { parsedWeekdays = append(parsedWeekdays, day) } } return parsedWeekdays } // ParseTimePeriods takes a comma-separated list of time periods in Kitchen24 format and turns them // into a slice of TimePeriods. It ignores any whitespace. func ParseTimePeriods(timePeriods string) ([]TimePeriod, error) { parsedTimePeriods := []TimePeriod{} for _, tp := range strings.Split(timePeriods, ",") { if strings.TrimSpace(tp) == "" { continue } parts := strings.Split(tp, "-") if len(parts) != 2 { return nil, fmt.Errorf("Invalid time range '%v': must contain exactly one '-'", tp) } begin, err := time.Parse(Kitchen24, strings.TrimSpace(parts[0])) if err != nil { return nil, err } end, err := time.Parse(Kitchen24, strings.TrimSpace(parts[1])) if err != nil { return nil, err } parsedTimePeriods = append(parsedTimePeriods, NewTimePeriod(begin, end)) } return parsedTimePeriods, nil } func ParseDays(days string) ([]time.Time, error) { parsedDays := []time.Time{} for _, day := range strings.Split(days, ",") { if strings.TrimSpace(day) == "" { continue } parsedDay, err := time.Parse(YearDay, strings.TrimSpace(day)) if err != nil { return nil, err } parsedDays = append(parsedDays, parsedDay) } return parsedDays, nil } // TimeOfDay normalizes the given point in time by returning a time object that represents the same // time of day of the given time but on the very first day (day 0). func TimeOfDay(pointInTime time.Time) time.Time { return time.Date(0, 0, 0, pointInTime.Hour(), pointInTime.Minute(), pointInTime.Second(), pointInTime.Nanosecond(), time.UTC) } // FormatDays takes a slice of times and returns a slice of strings in YearDate format (e.g. [Apr 1, Sep 24]) func FormatDays(days []time.Time) []string { formattedDays := make([]string, 0, len(days)) for _, d := range days { formattedDays = append(formattedDays, d.Format(YearDay)) } return formattedDays } // NewPod returns a new pod instance for testing purposes. func NewPod(namespace, name string, phase v1.PodPhase) v1.Pod { return v1.Pod{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Pod", }, ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: name, Labels: map[string]string{ "app": name, }, Annotations: map[string]string{ "chaos": name, }, SelfLink: fmt.Sprintf("/api/v1/namespaces/%s/pods/%s", namespace, name), }, Status: v1.PodStatus{ Phase: phase, }, } } // NewNamespace returns a new namespace instance for testing purposes. func NewNamespace(name string) v1.Namespace { return v1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: name, Labels: map[string]string{ "env": name, }, }, } }
util/util.go
0.772788
0.514095
util.go
starcoder
package linkedlist import ( "bytes" "fmt" "strings" ) // Node contains data (and usually a value or a pointer to a value) and a pointer to the next node type Node struct { next *Node Data int } // LinkedList with a single pointer, https://en.wikipedia.org/wiki/Linked_list type LinkedList struct { Head *Node } // AppendValue is a helper function that can take a value and append it directly func (list *LinkedList) AppendValue(n int) { list.Append(&Node{Data: n}) } // Append adds a node to the end of the list func (list *LinkedList) Append(n *Node) { if list.Head == nil { list.Head = n return } var current *Node for current = list.Head; current.next != nil; current = current.next { } current.next = n } // PrependValue is a helper function that can take a value and prepend it directly func (list *LinkedList) PrependValue(n int) { list.Prepend(&Node{Data: n}) } // Prepend adds a node to the beginning of the list func (list *LinkedList) Prepend(n *Node) { if list.Head == nil { list.Head = n return } old := list.Head list.Head = n n.next = old return } // InsertValue is a helper function that can take a value and insert it directly func (list *LinkedList) InsertValue(n, location int) { list.Insert(&Node{Data: n}, location) } // Insert adds a node to a specific (0 based index) location in the list // a location beyond the list length is treated like an append func (list *LinkedList) Insert(n *Node, location int) { if location == 0 { list.Prepend(n) return } if location >= list.Length() { fmt.Println("WARNING: treating insert beyond the end of the list as append") list.Append(n) return } count := 1 previous := list.Head for current := list.Head.next; current != nil; current = current.next { if count == location { previous.next = n n.next = current return } previous = current count++ } } // Length counts all the nodes in a linked list func (list *LinkedList) Length() int { var current *Node count := 0 for current = list.Head; current != nil; current = current.next { count++ } return count } // Display returns all of the nodes in a linked list func (list *LinkedList) Display() string { var current *Node var b bytes.Buffer for current = list.Head; current != nil; current = current.next { b.WriteString(fmt.Sprintf(" %v\n", current)) } return b.String() } // Values returns all of the values in a linked list func (list *LinkedList) Values() string { var current *Node var b bytes.Buffer for current = list.Head; current != nil; current = current.next { b.WriteString(fmt.Sprintf(" %d", current.Data)) } return strings.TrimSpace(b.String()) } // Find returns the first node that has a matching key func (list *LinkedList) Find(target int) *Node { var current *Node for current = list.Head; current != nil; current = current.next { if current.Data == target { return current } } return nil } // Get the "Nth" node from the list using a "zero" index like an array func (list *LinkedList) Get(index int) *Node { var current *Node var i int for current = list.Head; current != nil; current = current.next { if i == index { return current } i++ } return nil } // Reduce removes 1 node from the end of the list func (list *LinkedList) Reduce() { if list.Head == nil { return } if list.Head.next == nil { list.Head = nil return } var current *Node previous := list.Head for current = list.Head; current.next != nil; current = current.next { previous = current } // Note that other callers may continue to hold the reference previous.next = nil } // Delete removes a node given a provided index (using a zero index system) func (list *LinkedList) Delete(index int) error { if index < 0 { return fmt.Errorf("Cannot remove an index that is less than zero") } if index > list.Length() { return fmt.Errorf("Index %d is out of range of the length of the list: %d", index, list.Length()) } if index == 0 { if list.Head.next != nil { list.Head = list.Head.next } else { list.Head = nil } return nil } previous := list.Head current := list.Head.next count := 1 for { if count == index { previous.next = current.next return nil } previous = current current = current.next count++ } } // ReverseEasy changes the ordering of the nodes so the tail becomes the head and the head becomes the last item func (list *LinkedList) ReverseEasy() { if list.Head == nil || list.Head.next == nil { return } a := make([]int, list.Length()) current := list.Head for i := list.Length() - 1; i >= 0; i-- { a[i] = current.Data current = current.next } i := 0 for current = list.Head; current != nil; current = current.next { current.Data = a[i] i++ } } // Reverse changes the links of the nodes that eventually the head becomes the last item // For each node we need a pointer to the previous node // we need to preserve node.next to continue iterating // then node.next can point to the previous func (list *LinkedList) Reverse() { var previous *Node for current := list.Head; current != nil; { temp := current.next current.next = previous previous = current current = temp } list.Head = previous }
linkedlist.go
0.691497
0.437703
linkedlist.go
starcoder
package analysis import ( "fmt" "reflect" "github.com/google-research/korvapuusti/tools/spectrum" "github.com/google-research/korvapuusti/tools/synthesize/signals" tf "github.com/ryszard/tfutils/proto/tensorflow/core/example" ) // Calibration defines the calibration of the equipment before the evaluation. type Calibration struct { // HeadphoneFrequencyResponseHash is a hash of the headphone frequency response definition used to produce calibrated sounds. HeadphoneFrequencyResponseHash string // FullScaleSineDBSPL identifies the dB SPL level used to calibrate a full scale sine (with gain 1.0). FullScaleSineDBSPL float64 } // Run identifies this run as a part of a series of evaluations. type Run struct { // ID is the unique ID for this run. ID string } // Evaluation identifies this particular evaluation, which frequency in the run was evaluated, and the exact parameters used to produce the sounds. type Evaluation struct { // ID is the unique ID for this evaluation. ID string // Frequency is the frequency used for this evaluation as a part of the run. Frequency float64 // Probe describes the probe sound played in the evaluation. Probe signals.SamplerWrapper // Combined describes the combined sound played in the evaluation. Combined signals.SamplerWrapper } // Results defines the results of the human evaluation. type Results struct { // ProbeGainForEquivalentLoudness identifies the gain used when the evaluator found the levels to be equally loud. ProbeGainForEquivalentLoudness float64 // ProbeDBSPLForEquivalentLoudness identifies the db SPL (calculated using the Level in Evaluation.Probe, // Calibration.FullScaleSineDBSPL and ProbeGainForEquivalentLoudness) when the evaluator found the levels to be equally loud. ProbeDBSPLForEquivalentLoudness float64 } // Analysis contains the CARFAC analysis of the sound played to the evaluator, without using the headphone frequency response calibration // (since CARFAC gets the raw audio, and doesn't need to be calibrated for headphones). type Analysis struct { // FullScaleSineLevel is the assumed level for a full scale sine when generating the CARFAC input signals. CARFACFullScaleSineLevel signals.DB // VOffsetProvided is whether a custom v_offset was provided when running CARFAC. VOffsetProvided bool // VOffset is the custom v_offset used when running CARFAC, if any. VOffset float64 // OpenLoop is whether CARFAC was run with an open loop. OpenLoop bool // ChannelPoles[channelIDX] is the pole frequency for each channel. ChannelPoles []float64 // ERBPerStep is the custom erb_per_step used when running CARFAC, if any. ERBPerStep float64 // NoiseFloor is the noise floor level added to the samples before running CARFAC. NoiseFloor signals.DB // MaxZeta is the custom max_zeta used when running CARFAC, if any. MaxZeta float64 // ZeroRatio is the custom zero_ratio used when running CARFAC, if any. ZeroRatio float64 // StageGain is the custom agc_stage_gain used when running CARFAC, if any. StageGain float64 // NAPChannels[channelIDX][sampleStep] is the time domain output of the CARFAC NAP channels. NAPChannels [][]float64 // NAPChannelSpectrums is the results of FFT of the NAPChannels. NAPChannelSpectrums []spectrum.S // BMChannels[channelIDX][sampleStep] is the time domain output of the CARFAC BM channels. BMChannels [][]float64 // BMChannelSpectrums is the results of FFT of the BMChannels. BMChannelSpectrums []spectrum.S } // Samples contains the generated raw sound played out to the evaluator, without the compensation for the headphone frequency response file. type Samples struct { // FullScaleSineLevel is the assumed level for a full scale sine when generating samples. FullScaleSineLevel signals.DB // WindowSize is the number of samples in the window. WindowSize int64 // Rate is the sample rate of the signal fed to the FFT. Rate signals.Hz // Values are the sample values. Values []float64 } // EquivalentLoudness describes an evaluation and its results. type EquivalentLoudness struct { // EntryType is used to filter out actual EquivalentLoudness events from frequency response events in the log. EntryType string // Calibration describes the calibration used during the evaluation. Calibration Calibration // Run identifies the evaluation as part of a run. Run Run // Evaluation defines the sounds evaluated. Evaluation Evaluation // Results defines the results of the human evaluation. Results Results // Analysis contains CARFAC analysis of the sounds evaluated. Analysis Analysis // Samples contains a window of the samples played out to the evaluator, without the compensation for the headphone frequency response. Samples Samples } func (e *EquivalentLoudness) toTFExample(val reflect.Value, namePrefix string, ex *tf.Example) error { typ := val.Type() switch typ.Kind() { case reflect.Bool: i := int64(0) if val.Bool() { i = 1 } ex.Features.Feature[namePrefix] = &tf.Feature{&tf.Feature_Int64List{&tf.Int64List{[]int64{i}}}} case reflect.String: ex.Features.Feature[namePrefix] = &tf.Feature{&tf.Feature_BytesList{&tf.BytesList{[][]byte{[]byte(val.String())}}}} case reflect.Float64: ex.Features.Feature[namePrefix] = &tf.Feature{&tf.Feature_FloatList{&tf.FloatList{[]float32{float32(val.Float())}}}} case reflect.Int64: ex.Features.Feature[namePrefix] = &tf.Feature{&tf.Feature_Int64List{&tf.Int64List{[]int64{val.Int()}}}} case reflect.Slice: elemTyp := typ.Elem() switch elemTyp.Kind() { case reflect.Struct: fallthrough case reflect.Slice: for elemIdx := 0; elemIdx < val.Len(); elemIdx++ { if err := e.toTFExample(val.Index(elemIdx), fmt.Sprintf("%v[%v]", namePrefix, elemIdx), ex); err != nil { return err } } case reflect.Float64: floats := make([]float32, val.Len()) for idx := 0; idx < val.Len(); idx++ { floats[idx] = float32(val.Index(idx).Float()) } ex.Features.Feature[namePrefix] = &tf.Feature{&tf.Feature_FloatList{&tf.FloatList{floats}}} case reflect.Interface: for elemIdx := 0; elemIdx < val.Len(); elemIdx++ { if err := e.toTFExample(val.Index(elemIdx).Elem(), fmt.Sprintf("%v[%v]", namePrefix, elemIdx), ex); err != nil { return err } } default: return fmt.Errorf("%v %v is of an invalid slice type %v", namePrefix, val.Interface(), typ) } case reflect.Map: iter := val.MapRange() for iter.Next() { if err := e.toTFExample(iter.Value(), namePrefix+"."+fmt.Sprint(iter.Key()), ex); err != nil { return err } } case reflect.Struct: for fieldIdx := 0; fieldIdx < typ.NumField(); fieldIdx++ { fieldTyp := typ.Field(fieldIdx) if fieldTyp.Tag.Get("proto") != "-" { fieldVal := val.Field(fieldIdx) if err := e.toTFExample(fieldVal, namePrefix+"."+fieldTyp.Name, ex); err != nil { return err } } } case reflect.Interface: if err := e.toTFExample(val.Elem(), namePrefix, ex); err != nil { return err } default: return fmt.Errorf("%v %v is of an invalid type %v", namePrefix, val.Interface(), typ) } return nil } // ToTFExample converts an EquivalentLoudness to a tf.Example for compact logging. func (e *EquivalentLoudness) ToTFExample() (*tf.Example, error) { ex := &tf.Example{ Features: &tf.Features{ Feature: map[string]*tf.Feature{}, }, } if err := e.toTFExample(reflect.ValueOf(*e), "EquivalentLoudness", ex); err != nil { return nil, err } return ex, nil }
experiments/partial_loudness/analysis/data.go
0.68784
0.617916
data.go
starcoder
package runtime // A Value is a runtime value. type Value struct { iface interface{} } // AsValue returns a Value for the passed interface. func AsValue(i interface{}) Value { return Value{iface: i} } // Interface turns the Value into an interface. func (v Value) Interface() interface{} { return v.iface } // IntValue returns a Value holding the given arg. func IntValue(n int64) Value { return Value{iface: n} } // FloatValue returns a Value holding the given arg. func FloatValue(f float64) Value { return Value{iface: f} } // BoolValue returns a Value holding the given arg. func BoolValue(b bool) Value { return Value{iface: b} } // StringValue returns a Value holding the given arg. func StringValue(s string) Value { return Value{iface: s} } // TableValue returns a Value holding the given arg. func TableValue(t *Table) Value { return Value{iface: t} } // FunctionValue returns a Value holding the given arg. func FunctionValue(c Callable) Value { return Value{iface: c} } // ContValue returns a Value holding the given arg. func ContValue(c Cont) Value { return Value{iface: c} } // ArrayValue returns a Value holding the given arg. func ArrayValue(a []Value) Value { return Value{iface: a} } // CodeValue returns a Value holding the given arg. func CodeValue(c *Code) Value { return Value{iface: c} } // ThreadValue returns a Value holding the given arg. func ThreadValue(t *Thread) Value { return Value{iface: t} } // LightUserDataValue returns a Value holding the given arg. func LightUserDataValue(d LightUserData) Value { return Value{iface: d} } // UserDataValue returns a Value holding the given arg. func UserDataValue(u *UserData) Value { return Value{iface: u} } // NilValue is a value holding Nil. var NilValue = Value{} // Type returns the ValueType of v. func (v Value) Type() ValueType { if v.iface == nil { return NilType } switch v.iface.(type) { case int64: return IntType case float64: return FloatType case bool: return BoolType case string: return StringType case *Table: return TableType case *Code: return CodeType case Callable: return FunctionType case *Thread: return ThreadType case *UserData: return UserDataType default: return UnknownType } } // NumberType return the ValueType of v if it is a number, otherwise // UnknownType. func (v Value) NumberType() ValueType { switch v.iface.(type) { case int64: return IntType case float64: return FloatType } return UnknownType } // AsInt returns v as a int64 (or panics). func (v Value) AsInt() int64 { return v.iface.(int64) } // AsFloat returns v as a float64 (or panics). func (v Value) AsFloat() float64 { return v.iface.(float64) } // AsBool returns v as a bool (or panics). func (v Value) AsBool() bool { return v.iface.(bool) } // AsString returns v as a string (or panics). func (v Value) AsString() string { return v.iface.(string) } // AsTable returns v as a *Table (or panics). func (v Value) AsTable() *Table { return v.iface.(*Table) } // AsCont returns v as a Cont (or panics). func (v Value) AsCont() Cont { return v.iface.(Cont) } // AsArray returns v as a [] (or panics). func (v Value) AsArray() []Value { return v.iface.([]Value) } // AsClosure returns v as a *Closure (or panics). func (v Value) AsClosure() *Closure { return v.iface.(*Closure) } // AsCode returns v as a *Code (or panics). func (v Value) AsCode() *Code { return v.iface.(*Code) } // AsUserData returns v as a *UserData (or panics). func (v Value) AsUserData() *UserData { return v.iface.(*UserData) } // AsFunction returns v as a Callable (or panics). func (v Value) AsFunction() Callable { return v.iface.(Callable) } // TryInt converts v to type int64 if possible (ok is false otherwise). func (v Value) TryInt() (n int64, ok bool) { n, ok = v.iface.(int64) return } // TryFloat converts v to type float64 if possible (ok is false otherwise). func (v Value) TryFloat() (n float64, ok bool) { n, ok = v.iface.(float64) return } // TryString converts v to type string if possible (ok is false otherwise). func (v Value) TryString() (s string, ok bool) { s, ok = v.iface.(string) return } // TryCallable converts v to type Callable if possible (ok is false otherwise). func (v Value) TryCallable() (c Callable, ok bool) { c, ok = v.iface.(Callable) return } // TryClosure converts v to type *Closure if possible (ok is false otherwise). func (v Value) TryClosure() (c *Closure, ok bool) { c, ok = v.iface.(*Closure) return } // TryThread converts v to type *Thread if possible (ok is false otherwise). func (v Value) TryThread() (t *Thread, ok bool) { t, ok = v.iface.(*Thread) return } // TryTable converts v to type *Table if possible (ok is false otherwise). func (v Value) TryTable() (t *Table, ok bool) { t, ok = v.iface.(*Table) return } // TryUserData converts v to type *UserData if possible (ok is false otherwise). func (v Value) TryUserData() (u *UserData, ok bool) { u, ok = v.iface.(*UserData) return } // TryBool converts v to type bool if possible (ok is false otherwise). func (v Value) TryBool() (b bool, ok bool) { b, ok = v.iface.(bool) return } // TryCont converts v to type Cont if possible (ok is false otherwise). func (v Value) TryCont() (c Cont, ok bool) { c, ok = v.iface.(Cont) return } // TryCode converts v to type *Code if possible (ok is false otherwise). func (v Value) TryCode() (c *Code, ok bool) { c, ok = v.iface.(*Code) return } // IsNil returns true if v is nil. func (v Value) IsNil() bool { return v.iface == nil }
runtime/value_noscalar.go
0.857694
0.484868
value_noscalar.go
starcoder
package structmapper import ( "errors" "fmt" "reflect" "unicode" "encoding" "github.com/hashicorp/go-multierror" ) // This file contains the map to struct functionality of Mapper func (sm *Mapper) unmapPtr(in interface{}, out reflect.Value, t reflect.Type) error { child := reflect.New(t.Elem()) if err := sm.unmapValue(in, child.Elem(), child.Elem().Type()); err != nil { return err } out.Set(child) return nil } func (sm *Mapper) unmapSlice(in interface{}, out reflect.Value, t reflect.Type) (err error) { inSlice := reflect.ValueOf(in) if inSlice.Kind() != reflect.Slice { return errors.New("Not a slice") } outSlice := reflect.MakeSlice(t, inSlice.Len(), inSlice.Cap()) for i := 0; i < inSlice.Len(); i++ { inElem := inSlice.Index(i) outElem := outSlice.Index(i) inV := reflect.ValueOf(inElem.Interface()) elemV := reflect.New(outElem.Type()).Elem() if unmapErr := sm.unmapValue(inV.Interface(), elemV, elemV.Type()); unmapErr != nil { err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%d", i))) continue } outSlice.Index(i).Set(elemV) } if err == nil { out.Set(outSlice) } return } func (sm *Mapper) unmapMap(in interface{}, out reflect.Value, t reflect.Type) (err error) { inMap := reflect.ValueOf(in) if inMap.Kind() != reflect.Map { return errors.New("Not a map") } outMap := reflect.MakeMap(t) for _, inKeyElem := range inMap.MapKeys() { inKeyV := reflect.ValueOf(inKeyElem.Interface()) inKeyInterface := inKeyV.Interface() outKey := reflect.New(inKeyV.Type()).Elem() if unmapErr := sm.unmapValue(inKeyInterface, outKey, outKey.Type()); unmapErr != nil { err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%+v (key)", inKeyInterface))) continue } inValueElem := inMap.MapIndex(inKeyV) inValueV := reflect.ValueOf(inValueElem.Interface()) inValueInterface := inValueV.Interface() outValue := reflect.New(outMap.Type().Elem()).Elem() if unmapErr := sm.unmapValue(inValueInterface, outValue, outValue.Type()); unmapErr != nil { err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%+v (inValueInterface)", inValueInterface))) continue } outMap.SetMapIndex(outKey, outValue) } if err == nil { // Special case: out may be a struct or struct pointer... out.Set(outMap) } return } func (sm *Mapper) unmapArray(in interface{}, out reflect.Value, t reflect.Type) (err error) { inArray := reflect.ValueOf(in) if inArray.Kind() != reflect.Array && inArray.Kind() != reflect.Slice { return errors.New("Not an array or slice") } outArray := reflect.New(t).Elem() for i := 0; i < inArray.Len(); i++ { outElem := outArray.Index(i) inValue := inArray.Index(i) if unmapErr := sm.unmapValue(inValue.Interface(), outElem, outElem.Type()); unmapErr != nil { err = multierror.Append(err, multierror.Prefix(unmapErr, fmt.Sprintf("@%d", i))) continue } } if err == nil { out.Set(outArray) } return } func (sm *Mapper) unmapUnmarshal(in interface{}, out reflect.Value) (bool, error) { inValue := reflect.ValueOf(in) inType := inValue.Type() str := "" strValue := reflect.ValueOf(&str).Elem() strType := strValue.Type() if inType == strType { str = in.(string) } else if inType.AssignableTo(strType) { strValue.Set(inValue) } else if inType.ConvertibleTo(strType) { strValue.Set(inValue.Convert(strType)) } else { return false, nil } outI := out.Interface() if unmarshaler, ok := outI.(encoding.TextUnmarshaler); ok { return true, unmarshaler.UnmarshalText([]byte(str)) } else if out.CanAddr() { return sm.unmapUnmarshal(in, out.Addr()) } return false, nil } func (sm *Mapper) unmapValue(in interface{}, out reflect.Value, t reflect.Type) error { // Check if the target implements encoding.TextUnmarshaler if handled, err := sm.unmapUnmarshal(in, out); handled { return err } switch out.Kind() { case reflect.Ptr: return sm.unmapPtr(in, out, t) case reflect.Struct: return sm.unmapStruct(in, out, t) case reflect.Slice: return sm.unmapSlice(in, out, t) case reflect.Map: return sm.unmapMap(in, out, t) case reflect.Array: return sm.unmapArray(in, out, t) } inValue := reflect.ValueOf(in) inType := inValue.Type() outType := reflect.ValueOf(out.Interface()).Type() if inType == outType { // Default case: copy the value over out.Set(reflect.ValueOf(in)) return nil } else if inType.AssignableTo(outType) { // Types are assignable out.Set(inValue) return nil } else if inType.ConvertibleTo(outType) { // Types are convertible out.Set(inValue.Convert(outType)) return nil } return fmt.Errorf("Type mismatch: %s and %s are incompatible", outType.String(), inType.String()) } func (sm *Mapper) unmapStruct(in interface{}, out reflect.Value, t reflect.Type) (err error) { if out.Kind() == reflect.Ptr { // Target is a pointer to a struct: create a new instance out.Set(reflect.New(out.Type().Elem())) out = out.Elem() t = out.Type() } if out.Kind() != reflect.Struct { return ErrNotAStruct } // Check if we received any map inValue := reflect.ValueOf(in) if inValue.Kind() != reflect.Map { return ErrInvalidMap } // Hold the values of the modified fields in a map, which will be applied shortly before // this function returns. // This ensures we do not modify the target struct at all in case of an error modifiedFields := make(map[int]reflect.Value, t.NumField()) // Iterate over all fields of the passed struct for i := 0; i < out.NumField(); i++ { fieldD := t.Field(i) fieldV := out.Field(i) if fieldD.Anonymous { // Call unmapStruct on anonymous field if anonErr := sm.unmapStruct(in, fieldV, fieldD.Type); anonErr != nil { err = multierror.Append(err, anonErr) continue } continue } fieldName := fieldD.Name if !unicode.IsUpper([]rune(fieldName)[0]) { // Ignore private fields continue } fieldName, _, tagErr := parseTagFromStructField(fieldD, sm.tagName) if tagErr != nil { // Parsing the tag failed, ignore the field and carry on err = multierror.Append(err, tagErr) continue } if fieldName == "-" { // Tag defines that the field shall be ignored, so carry on continue } // Look up value of "fieldName" in map mapVal := inValue.MapIndex(reflect.ValueOf(fieldName)) if !mapVal.IsValid() { // Value not in map, ignore it continue } mapValue := mapVal.Interface() if fieldV.Kind() == reflect.Interface { // Setting interfaces is unsupported. err = multierror.Append(err, multierror.Prefix(ErrFieldIsInterface, fieldName+":")) continue } targetV := reflect.New(fieldD.Type).Elem() if unmapErr := sm.unmapValue(mapValue, targetV, fieldD.Type); unmapErr != nil { err = multierror.Append(err, multierror.Prefix(unmapErr, fieldName+":")) continue } else { modifiedFields[i] = targetV } } // Apply changes to all modified fields in case no error happened during processing. if err == nil { // Apply changes to all modified fields for fieldIndex, fieldValue := range modifiedFields { out.Field(fieldIndex).Set(fieldValue) } } return } func (sm *Mapper) toStruct(m map[string]interface{}, s interface{}) error { if m == nil { return ErrMapIsNil } v := reflect.ValueOf(s) if v.Kind() != reflect.Ptr { return ErrNotAStructPointer } v = v.Elem() return sm.unmapStruct(m, v, v.Type()) }
unmap.go
0.591133
0.402451
unmap.go
starcoder
package eval import ( "log" "math/big" ) /* * "As" functions. These retrieve evaluator functions from an * expr, panicking if the requested evaluator has the wrong type. */ func (a *expr) asBool() func(*Thread) bool { return a.eval.(func(*Thread) bool) } func (a *expr) asUint() func(*Thread) uint64 { return a.eval.(func(*Thread) uint64) } func (a *expr) asInt() func(*Thread) int64 { return a.eval.(func(*Thread) int64) } func (a *expr) asIdealInt() func() *big.Int { return a.eval.(func() *big.Int) } func (a *expr) asFloat() func(*Thread) float64 { return a.eval.(func(*Thread) float64) } func (a *expr) asIdealFloat() func() *big.Rat { return a.eval.(func() *big.Rat) } func (a *expr) asString() func(*Thread) string { return a.eval.(func(*Thread) string) } func (a *expr) asArray() func(*Thread) ArrayValue { return a.eval.(func(*Thread) ArrayValue) } func (a *expr) asStruct() func(*Thread) StructValue { return a.eval.(func(*Thread) StructValue) } func (a *expr) asPtr() func(*Thread) Value { return a.eval.(func(*Thread) Value) } func (a *expr) asFunc() func(*Thread) Func { return a.eval.(func(*Thread) Func) } func (a *expr) asSlice() func(*Thread) Slice { return a.eval.(func(*Thread) Slice) } func (a *expr) asMap() func(*Thread) Map { return a.eval.(func(*Thread) Map) } func (a *expr) asMulti() func(*Thread) []Value { return a.eval.(func(*Thread) []Value) } func (a *expr) asInterface() func(*Thread) interface{} { switch sf := a.eval.(type) { case func(t *Thread) bool: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) uint64: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) int64: return func(t *Thread) interface{} { return sf(t) } case func() *big.Int: return func(*Thread) interface{} { return sf() } case func(t *Thread) float64: return func(t *Thread) interface{} { return sf(t) } case func() *big.Rat: return func(*Thread) interface{} { return sf() } case func(t *Thread) string: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) ArrayValue: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) StructValue: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) Value: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) Func: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) Slice: return func(t *Thread) interface{} { return sf(t) } case func(t *Thread) Map: return func(t *Thread) interface{} { return sf(t) } default: log.Panicf("unexpected expression node type %T at %v", a.eval, a.pos) } panic("fail") } /* * Operator generators. */ func (a *expr) genConstant(v Value) { switch a.t.lit().(type) { case *boolType: a.eval = func(t *Thread) bool { return v.(BoolValue).Get(t) } case *uintType: a.eval = func(t *Thread) uint64 { return v.(UintValue).Get(t) } case *intType: a.eval = func(t *Thread) int64 { return v.(IntValue).Get(t) } case *idealIntType: val := v.(IdealIntValue).Get() a.eval = func() *big.Int { return val } case *floatType: a.eval = func(t *Thread) float64 { return v.(FloatValue).Get(t) } case *idealFloatType: val := v.(IdealFloatValue).Get() a.eval = func() *big.Rat { return val } case *stringType: a.eval = func(t *Thread) string { return v.(StringValue).Get(t) } case *ArrayType: a.eval = func(t *Thread) ArrayValue { return v.(ArrayValue).Get(t) } case *StructType: a.eval = func(t *Thread) StructValue { return v.(StructValue).Get(t) } case *PtrType: a.eval = func(t *Thread) Value { return v.(PtrValue).Get(t) } case *FuncType: a.eval = func(t *Thread) Func { return v.(FuncValue).Get(t) } case *SliceType: a.eval = func(t *Thread) Slice { return v.(SliceValue).Get(t) } case *MapType: a.eval = func(t *Thread) Map { return v.(MapValue).Get(t) } default: log.Panicf("unexpected constant type %v at %v", a.t, a.pos) } } func (a *expr) genIdentOp(level, index int) { a.evalAddr = func(t *Thread) Value { return t.f.Get(level, index) } switch a.t.lit().(type) { case *boolType: a.eval = func(t *Thread) bool { return t.f.Get(level, index).(BoolValue).Get(t) } case *uintType: a.eval = func(t *Thread) uint64 { return t.f.Get(level, index).(UintValue).Get(t) } case *intType: a.eval = func(t *Thread) int64 { return t.f.Get(level, index).(IntValue).Get(t) } case *floatType: a.eval = func(t *Thread) float64 { return t.f.Get(level, index).(FloatValue).Get(t) } case *stringType: a.eval = func(t *Thread) string { return t.f.Get(level, index).(StringValue).Get(t) } case *ArrayType: a.eval = func(t *Thread) ArrayValue { return t.f.Get(level, index).(ArrayValue).Get(t) } case *StructType: a.eval = func(t *Thread) StructValue { return t.f.Get(level, index).(StructValue).Get(t) } case *PtrType: a.eval = func(t *Thread) Value { return t.f.Get(level, index).(PtrValue).Get(t) } case *FuncType: a.eval = func(t *Thread) Func { return t.f.Get(level, index).(FuncValue).Get(t) } case *SliceType: a.eval = func(t *Thread) Slice { return t.f.Get(level, index).(SliceValue).Get(t) } case *MapType: a.eval = func(t *Thread) Map { return t.f.Get(level, index).(MapValue).Get(t) } default: log.Panicf("unexpected identifier type %v at %v", a.t, a.pos) } } func (a *expr) genFuncCall(call func(t *Thread) []Value) { a.exec = func(t *Thread) { call(t) } switch a.t.lit().(type) { case *boolType: a.eval = func(t *Thread) bool { return call(t)[0].(BoolValue).Get(t) } case *uintType: a.eval = func(t *Thread) uint64 { return call(t)[0].(UintValue).Get(t) } case *intType: a.eval = func(t *Thread) int64 { return call(t)[0].(IntValue).Get(t) } case *floatType: a.eval = func(t *Thread) float64 { return call(t)[0].(FloatValue).Get(t) } case *stringType: a.eval = func(t *Thread) string { return call(t)[0].(StringValue).Get(t) } case *ArrayType: a.eval = func(t *Thread) ArrayValue { return call(t)[0].(ArrayValue).Get(t) } case *StructType: a.eval = func(t *Thread) StructValue { return call(t)[0].(StructValue).Get(t) } case *PtrType: a.eval = func(t *Thread) Value { return call(t)[0].(PtrValue).Get(t) } case *FuncType: a.eval = func(t *Thread) Func { return call(t)[0].(FuncValue).Get(t) } case *SliceType: a.eval = func(t *Thread) Slice { return call(t)[0].(SliceValue).Get(t) } case *MapType: a.eval = func(t *Thread) Map { return call(t)[0].(MapValue).Get(t) } case *MultiType: a.eval = func(t *Thread) []Value { return call(t) } default: log.Panicf("unexpected result type %v at %v", a.t, a.pos) } } func (a *expr) genValue(vf func(*Thread) Value) { a.evalAddr = vf switch a.t.lit().(type) { case *boolType: a.eval = func(t *Thread) bool { return vf(t).(BoolValue).Get(t) } case *uintType: a.eval = func(t *Thread) uint64 { return vf(t).(UintValue).Get(t) } case *intType: a.eval = func(t *Thread) int64 { return vf(t).(IntValue).Get(t) } case *floatType: a.eval = func(t *Thread) float64 { return vf(t).(FloatValue).Get(t) } case *stringType: a.eval = func(t *Thread) string { return vf(t).(StringValue).Get(t) } case *ArrayType: a.eval = func(t *Thread) ArrayValue { return vf(t).(ArrayValue).Get(t) } case *StructType: a.eval = func(t *Thread) StructValue { return vf(t).(StructValue).Get(t) } case *PtrType: a.eval = func(t *Thread) Value { return vf(t).(PtrValue).Get(t) } case *FuncType: a.eval = func(t *Thread) Func { return vf(t).(FuncValue).Get(t) } case *SliceType: a.eval = func(t *Thread) Slice { return vf(t).(SliceValue).Get(t) } case *MapType: a.eval = func(t *Thread) Map { return vf(t).(MapValue).Get(t) } default: log.Panicf("unexpected result type %v at %v", a.t, a.pos) } } func (a *expr) genUnaryOpNeg(v *expr) { switch a.t.lit().(type) { case *uintType: vf := v.asUint() a.eval = func(t *Thread) uint64 { v := vf(t); return -v } case *intType: vf := v.asInt() a.eval = func(t *Thread) int64 { v := vf(t); return -v } case *idealIntType: val := v.asIdealInt()() val.Neg(val) a.eval = func() *big.Int { return val } case *floatType: vf := v.asFloat() a.eval = func(t *Thread) float64 { v := vf(t); return -v } case *idealFloatType: val := v.asIdealFloat()() val.Neg(val) a.eval = func() *big.Rat { return val } default: log.Panicf("unexpected type %v at %v", a.t, a.pos) } } func (a *expr) genUnaryOpNot(v *expr) { switch a.t.lit().(type) { case *boolType: vf := v.asBool() a.eval = func(t *Thread) bool { v := vf(t); return !v } default: log.Panicf("unexpected type %v at %v", a.t, a.pos) } } func (a *expr) genUnaryOpXor(v *expr) { switch a.t.lit().(type) { case *uintType: vf := v.asUint() a.eval = func(t *Thread) uint64 { v := vf(t); return ^v } case *intType: vf := v.asInt() a.eval = func(t *Thread) int64 { v := vf(t); return ^v } case *idealIntType: val := v.asIdealInt()() val.Not(val) a.eval = func() *big.Int { return val } default: log.Panicf("unexpected type %v at %v", a.t, a.pos) } } func (a *expr) genBinOpLogAnd(l, r *expr) { lf := l.asBool() rf := r.asBool() a.eval = func(t *Thread) bool { return lf(t) && rf(t) } } func (a *expr) genBinOpLogOr(l, r *expr) { lf := l.asBool() rf := r.asBool() a.eval = func(t *Thread) bool { return lf(t) || rf(t) } } func (a *expr) genBinOpAdd(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l + r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l + r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l + r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l + r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l + r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l + r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l + r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l + r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l + r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l + r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Add(l, r) a.eval = func() *big.Int { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() switch t.Bits { case 32: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 ret = l + r return float64(float32(ret)) } case 64: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 ret = l + r return float64(float64(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Add(l, r) a.eval = func() *big.Rat { return val } case *stringType: lf := l.asString() rf := r.asString() a.eval = func(t *Thread) string { l, r := lf(t), rf(t) return l + r } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpSub(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l - r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l - r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l - r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l - r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l - r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l - r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l - r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l - r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l - r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l - r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Sub(l, r) a.eval = func() *big.Int { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() switch t.Bits { case 32: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 ret = l - r return float64(float32(ret)) } case 64: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 ret = l - r return float64(float64(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Sub(l, r) a.eval = func() *big.Rat { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpMul(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l * r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l * r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l * r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l * r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l * r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l * r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l * r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l * r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l * r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l * r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Mul(l, r) a.eval = func() *big.Int { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() switch t.Bits { case 32: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 ret = l * r return float64(float32(ret)) } case 64: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 ret = l * r return float64(float64(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Mul(l, r) a.eval = func() *big.Rat { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpQuo(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Quo(l, r) a.eval = func() *big.Int { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() switch t.Bits { case 32: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return float64(float32(ret)) } case 64: a.eval = func(t *Thread) float64 { l, r := lf(t), rf(t) var ret float64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l / r return float64(float64(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Quo(l, r) a.eval = func() *big.Rat { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpRem(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 if r == 0 { t.Abort(DivByZeroError{}) } ret = l % r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Rem(l, r) a.eval = func() *big.Int { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpAnd(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l & r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l & r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l & r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l & r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l & r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l & r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l & r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l & r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l & r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l & r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.And(l, r) a.eval = func() *big.Int { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpOr(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l | r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l | r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l | r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l | r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l | r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l | r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l | r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l | r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l | r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l | r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Or(l, r) a.eval = func() *big.Int { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpXor(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l ^ r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l ^ r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l ^ r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l ^ r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l ^ r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l ^ r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l ^ r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l ^ r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l ^ r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l ^ r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Xor(l, r) a.eval = func() *big.Int { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpAndNot(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l &^ r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l &^ r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l &^ r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l &^ r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l &^ r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asInt() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l &^ r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l &^ r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l &^ r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l &^ r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l &^ r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.AndNot(l, r) a.eval = func() *big.Int { return val } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpShl(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l << r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l << r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l << r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l << r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l << r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l << r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l << r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l << r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l << r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l << r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpShr(l, r *expr) { switch t := l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l >> r return uint64(uint8(ret)) } case 16: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l >> r return uint64(uint16(ret)) } case 32: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l >> r return uint64(uint32(ret)) } case 64: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l >> r return uint64(uint64(ret)) } case 0: a.eval = func(t *Thread) uint64 { l, r := lf(t), rf(t) var ret uint64 ret = l >> r return uint64(uint(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } case *intType: lf := l.asInt() rf := r.asUint() switch t.Bits { case 8: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l >> r return int64(int8(ret)) } case 16: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l >> r return int64(int16(ret)) } case 32: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l >> r return int64(int32(ret)) } case 64: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l >> r return int64(int64(ret)) } case 0: a.eval = func(t *Thread) int64 { l, r := lf(t), rf(t) var ret int64 ret = l >> r return int64(int(ret)) } default: log.Panicf("unexpected size %d in type %v at %v", t.Bits, t, a.pos) } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpLss(l, r *expr) { switch l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l < r } case *intType: lf := l.asInt() rf := r.asInt() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l < r } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Cmp(r) < 0 a.eval = func(t *Thread) bool { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l < r } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Cmp(r) < 0 a.eval = func(t *Thread) bool { return val } case *stringType: lf := l.asString() rf := r.asString() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l < r } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpGtr(l, r *expr) { switch l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l > r } case *intType: lf := l.asInt() rf := r.asInt() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l > r } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Cmp(r) > 0 a.eval = func(t *Thread) bool { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l > r } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Cmp(r) > 0 a.eval = func(t *Thread) bool { return val } case *stringType: lf := l.asString() rf := r.asString() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l > r } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpLeq(l, r *expr) { switch l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l <= r } case *intType: lf := l.asInt() rf := r.asInt() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l <= r } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Cmp(r) <= 0 a.eval = func(t *Thread) bool { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l <= r } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Cmp(r) <= 0 a.eval = func(t *Thread) bool { return val } case *stringType: lf := l.asString() rf := r.asString() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l <= r } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpGeq(l, r *expr) { switch l.t.lit().(type) { case *uintType: lf := l.asUint() rf := r.asUint() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l >= r } case *intType: lf := l.asInt() rf := r.asInt() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l >= r } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Cmp(r) >= 0 a.eval = func(t *Thread) bool { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l >= r } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Cmp(r) >= 0 a.eval = func(t *Thread) bool { return val } case *stringType: lf := l.asString() rf := r.asString() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l >= r } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpEql(l, r *expr) { switch l.t.lit().(type) { case *boolType: lf := l.asBool() rf := r.asBool() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } case *uintType: lf := l.asUint() rf := r.asUint() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } case *intType: lf := l.asInt() rf := r.asInt() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Cmp(r) == 0 a.eval = func(t *Thread) bool { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Cmp(r) == 0 a.eval = func(t *Thread) bool { return val } case *stringType: lf := l.asString() rf := r.asString() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } case *PtrType: lf := l.asPtr() rf := r.asPtr() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } case *FuncType: lf := l.asFunc() rf := r.asFunc() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } case *MapType: lf := l.asMap() rf := r.asMap() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l == r } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func (a *expr) genBinOpNeq(l, r *expr) { switch l.t.lit().(type) { case *boolType: lf := l.asBool() rf := r.asBool() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } case *uintType: lf := l.asUint() rf := r.asUint() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } case *intType: lf := l.asInt() rf := r.asInt() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } case *idealIntType: l := l.asIdealInt()() r := r.asIdealInt()() val := l.Cmp(r) != 0 a.eval = func(t *Thread) bool { return val } case *floatType: lf := l.asFloat() rf := r.asFloat() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } case *idealFloatType: l := l.asIdealFloat()() r := r.asIdealFloat()() val := l.Cmp(r) != 0 a.eval = func(t *Thread) bool { return val } case *stringType: lf := l.asString() rf := r.asString() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } case *PtrType: lf := l.asPtr() rf := r.asPtr() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } case *FuncType: lf := l.asFunc() rf := r.asFunc() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } case *MapType: lf := l.asMap() rf := r.asMap() a.eval = func(t *Thread) bool { l, r := lf(t), rf(t) return l != r } default: log.Panicf("unexpected type %v at %v", l.t, a.pos) } } func genAssign(lt Type, r *expr) func(lv Value, t *Thread) { switch lt.lit().(type) { case *boolType: rf := r.asBool() return func(lv Value, t *Thread) { lv.(BoolValue).Set(t, rf(t)) } case *uintType: rf := r.asUint() return func(lv Value, t *Thread) { lv.(UintValue).Set(t, rf(t)) } case *intType: rf := r.asInt() return func(lv Value, t *Thread) { lv.(IntValue).Set(t, rf(t)) } case *floatType: rf := r.asFloat() return func(lv Value, t *Thread) { lv.(FloatValue).Set(t, rf(t)) } case *stringType: rf := r.asString() return func(lv Value, t *Thread) { lv.(StringValue).Set(t, rf(t)) } case *ArrayType: rf := r.asArray() return func(lv Value, t *Thread) { lv.Assign(t, rf(t)) } case *StructType: rf := r.asStruct() return func(lv Value, t *Thread) { lv.Assign(t, rf(t)) } case *PtrType: rf := r.asPtr() return func(lv Value, t *Thread) { lv.(PtrValue).Set(t, rf(t)) } case *FuncType: rf := r.asFunc() return func(lv Value, t *Thread) { lv.(FuncValue).Set(t, rf(t)) } case *SliceType: rf := r.asSlice() return func(lv Value, t *Thread) { lv.(SliceValue).Set(t, rf(t)) } case *MapType: rf := r.asMap() return func(lv Value, t *Thread) { lv.(MapValue).Set(t, rf(t)) } default: log.Panicf("unexpected left operand type %v at %v", lt, r.pos) } panic("fail") }
expr1.go
0.619471
0.568955
expr1.go
starcoder
package chron import ( "time" "github.com/dustinevan/chron/dura" "fmt" "reflect" "database/sql/driver" "strings" ) type Minute struct { time.Time } func NewMinute(year int, month time.Month, day, hour, min int) Minute { return Minute{time.Date(year, month, day, hour, min, 0, 0, time.UTC)} } func ThisMinute() Minute { return Now().AsMinute() } func MinuteOf(t time.Time) Minute { t = t.UTC() return NewMinute(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute()) } func (m Minute) AsYear() Year { return YearOf(m.Time) } func (m Minute) AsMonth() Month { return MonthOf(m.Time) } func (m Minute) AsDay() Day { return DayOf(m.Time) } func (m Minute) AsHour() Hour { return HourOf(m.Time) } func (m Minute) AsMinute() Minute { return m } func (m Minute) AsSecond() Second { return SecondOf(m.Time) } func (m Minute) AsMilli() Milli { return MilliOf(m.Time) } func (m Minute) AsMicro() Micro { return MicroOf(m.Time) } func (m Minute) AsChron() Chron { return TimeOf(m.Time) } func (m Minute) AsTime() time.Time { return m.Time } func (m Minute) Increment(l dura.Time) Chron { return Chron{m.AddDate(l.Years(), l.Months(), l.Days()).Add(l.Duration())} } func (m Minute) Decrement(l dura.Time) Chron { return Chron{m.AddDate(-1*l.Years(), -1*l.Months(), -1*l.Days()).Add(-1 * l.Duration())} } func (m Minute) AddN(n int) Minute { return Minute{m.Add(time.Duration(int(time.Minute) * n))} } // span.Time implementation func (m Minute) Start() Chron { return m.AsChron() } func (m Minute) End() Chron { return m.AddN(1).Decrement(dura.Nano) } func (m Minute) Contains(t Span) bool { return !m.Before(t) && !m.After(t) } func (m Minute) Before(t Span) bool { return m.End().AsTime().Before(t.Start().AsTime()) } func (m Minute) After(t Span) bool { return m.Start().AsTime().After(t.End().AsTime()) } func (m Minute) Duration() dura.Time { return dura.Minute } func (m Minute) AddYears(y int) Minute { return m.Increment(dura.Years(y)).AsMinute() } func (m Minute) AddMonths(ms int) Minute { return m.Increment(dura.Months(ms)).AsMinute() } func (m Minute) AddDays(d int) Minute { return m.Increment(dura.Days(d)).AsMinute() } func (m Minute) AddHours(h int) Minute { return m.Increment(dura.Hours(h)).AsMinute() } func (m Minute) AddMinutes(ms int) Minute { return m.AddN(ms) } func (m Minute) AddSeconds(s int) Second { return m.AsSecond().AddN(s) } func (m Minute) AddMillis(ms int) Milli { return m.AsMilli().AddN(ms) } func (m Minute) AddMicros(ms int) Micro { return m.AsMicro().AddN(ms) } func (m Minute) AddNanos(n int) Chron { return m.AsChron().AddN(n) } func (m *Minute) Scan(value interface{}) error { if value == nil { *m = ZeroValue().AsMinute() return nil } if t, ok := value.(time.Time); ok { *m = MinuteOf(t) return nil } return fmt.Errorf("unsupported Scan, storing %s into type *chron.Day", reflect.TypeOf(value)) } func (m Minute) Value() (driver.Value, error) { // todo: error check the range. return m.Time, nil } func (m *Minute) UnmarshalJSON(data []byte) error { if string(data) == "null" { return nil } s := strings.Trim(string(data), `"`) t, err := Parse(s) *m = MinuteOf(t) return err }
minute.go
0.649912
0.443359
minute.go
starcoder
package vector import "math" // Vector3 defines a struct holding the X, Y, Z values of a vector // as float64 type Vector3 struct { X float64 Y float64 Z float64 } // NewVector3 constructs a new vector3 func NewVector3(x, y, z float64) Vector3 { return Vector3{ x, y, z, } } // Vector2 defines a struct holding the X, Y values of a vector type Vector2 struct { X float64 Y float64 } // NewVector2 constructs a new vector2 func NewVector2(x, y float64) Vector2 { return Vector2{ x, y, } } // Vector4 defines a struct holding the X, Y, Z and W values of a vector type Vector4 struct { X float64 Y float64 Z float64 W float64 } // NewVector4 constructs a new vector4 func NewVector4(x, y, z, w float64) Vector4 { return Vector4{ x, y, z, w, } } // DotProduct returns the dot product of vectors u and v func (u Vector3) DotProduct(v Vector3) float64 { return u.X*v.X + u.Y*v.Y + u.Z*v.Z } // Magnitude returns the length of vector u (length, norm) func (u Vector3) Magnitude() float64 { return math.Sqrt(u.DotProduct(u)) } // CrossProduct returns the cross product of vectors u and v func (u Vector3) CrossProduct(v Vector3) Vector3 { return Vector3{ u.Y*v.Z - u.Z*v.Y, u.Z*v.X - u.X*v.Z, u.X*v.Y - u.Y*v.X, } } // ScalarMultiply multiplies vector u with scalar func (u Vector3) ScalarMultiply(scalar float64) Vector3 { return Vector3{ u.X * scalar, u.Y * scalar, u.Z * scalar, } } // Normalize normalizes vector u func (u Vector3) Normalize() Vector3 { length := u.Magnitude() if length > 0 { return u.ScalarMultiply(1.0 / length) } return u } // Add adds two vectors u, v together func (u Vector3) Add(v Vector3) Vector3 { return Vector3{ u.X + v.X, u.Y + v.Y, u.Z + v.Z, } } // Subtract subtracts vector v from vector u func (u Vector3) Subtract(v Vector3) Vector3 { return Vector3{ u.X - v.X, u.Y - v.Y, u.Z - v.Z, } } // Negate negates vector func (u Vector3) Negate() Vector3 { return Vector3{ -u.X, -u.Y, -u.Z, } } // ConvertToRGB returns a triplet of unsigned 8-bit integers from vector u corresponding to RBG values func (u Vector3) ConvertToRGB() (uint8, uint8, uint8) { return uint8(255 * math.Max(0.0, math.Min(1.0, u.X))), uint8(255 * math.Max(0.0, math.Min(1.0, u.Y))), uint8(255 * math.Max(0.0, math.Min(1.0, u.Z))) } // Copy copies values from vector v to vector u func (u *Vector3) Copy(v Vector3) { u.X = v.X u.Y = v.Y u.Z = v.Z }
internal/pkg/vector/vector.go
0.931283
0.84966
vector.go
starcoder
package xmmhandler import ( "encoding/binary" "fmt" "math" "math/big" "reflect" "strconv" ) const ( //XMMBYTES is the number of bytes inside a XMM register XMMBYTES = 16 //XMMREGISTERS is the number of xmm registers in intel x86 XMMREGISTERS = 16 //SIZEOFINT16 is the number of bytes inside an int16 SIZEOFINT16 = 2 //SIZEOFINT32 is the number of bytes inside an int16 SIZEOFINT32 = 4 //SIZEOFINT64 is the number of bytes inside an int16 SIZEOFINT64 = 8 ) const ( //INT8STRING is the string that will define we want to work with the xmm values as int 8 INT8STRING = "v16_int8" //INT16STRING is the string that will define we want to work with the xmm values as int 16 INT16STRING = "v8_int16" //INT32STRING is the string that will define we want to work with the xmm values as int 32 INT32STRING = "v4_int32" //INT64STRING is the string that will define we want to work with the xmm values as int 64 INT64STRING = "v2_int64" //FLOAT32STRING is the string that will define we want to work with the xmm values as float 32 FLOAT32STRING = "v4_float" //FLOAT64STRING is the string that will define we want to work with the xmm values as float 64 FLOAT64STRING = "v2_double" //UNSIGNEDFORMAT ... UNSIGNEDFORMAT = "/u" //SIGNEDFORMAT ... SIGNEDFORMAT = "/d" //HEXFORMAT ... HEXFORMAT = "/x" //BINARYFORMAT ... BINARYFORMAT = "/t" ) //XMM register is represented as a 16 bytes slice with the corresponding values type XMM []byte //NewXMM creates a new XMM func NewXMM(p *[]byte) XMM { var resXMM = XMM{} slice := *p for i := 0; i < XMMBYTES; i++ { resXMM = append(resXMM, slice[i]) } return resXMM } //Equals compares two XMM func (xmm XMM) Equals(newXmm XMM) bool { for index := range xmm { if xmm[index] != newXmm[index] { return false } } return true } //Print prints the values in the xmm register as bytes. func (xmm XMM) Print() { fmt.Println(xmm) } func reverseString(s string) string { res := "" for _, v := range s { res = string(v) + res } return res } func numberToString(number int64, bits int64, base int64, symbol string) string { var formatString string switch base { case 16: formatString = "%X" case 2: formatString = "%b" } digits := bits if base == 16 { digits = bits / 4 } stringRes := symbol bigNumber := big.NewInt(number) bigBits := big.NewInt(bits) bigBase := big.NewInt(base) bigZero := big.NewInt(0) //If number is negative if bigNumber.Cmp(bigZero) == -1 { bigExp := big.NewInt(2) bigExp.Exp(bigExp, bigBits, nil) bigNumber.Add(bigNumber, bigExp) } rawNumber := "" var counter int64 = 1 //If bigNumber is greater or equal than bigBase for bigNumber.Cmp(bigBase) >= 0 { counter++ bigMod := big.NewInt(bigNumber.Int64()) bigMod.Mod(bigNumber, bigBase) rawNumber += fmt.Sprintf(formatString, bigMod.Int64()) bigNumber.Div(bigNumber, bigBase) } rawNumber += fmt.Sprintf(formatString, bigNumber) for counter < digits { stringRes += "0" counter++ } rawNumber = reverseString(rawNumber) stringRes += rawNumber stringRes = reverseString(stringRes) counter = 4 for counter < int64(len(stringRes)-2) { stringRes = stringRes[0:counter] + " " + stringRes[counter:] counter += 5 } stringRes = reverseString(stringRes) return stringRes } //PrintAs prints the values in the xmm register as bytes, words, //double words or quad words depending in the string received. //Posible entries: int8, int16, int32, int64, float32, float64 func (xmm XMM) PrintAs(format string) { switch format { case "int8": fmt.Printf("%v", xmm) case "int16": data := make([]int16, len(xmm)/SIZEOFINT16) for i := range data { data[i] = int16(binary.LittleEndian.Uint16(xmm[i*SIZEOFINT16 : (i+1)*SIZEOFINT16])) } fmt.Printf("%v", data) case "int32": data := make([]int32, len(xmm)/SIZEOFINT32) for i := range data { data[i] = int32(binary.LittleEndian.Uint32(xmm[i*SIZEOFINT32 : (i+1)*SIZEOFINT32])) } fmt.Printf("%v", data) case "int64": data := make([]int64, len(xmm)/SIZEOFINT64) for i := range data { data[i] = int64(binary.LittleEndian.Uint64(xmm[i*SIZEOFINT64 : (i+1)*SIZEOFINT64])) } fmt.Printf("%v", data) case "float32": data := make([]float32, len(xmm)/SIZEOFINT32) for i := range data { data[i] = math.Float32frombits(binary.LittleEndian.Uint32(xmm[i*SIZEOFINT32 : (i+1)*SIZEOFINT32])) } fmt.Printf("%v", data) case "float64": data := make([]float64, len(xmm)/SIZEOFINT64) for i := range data { data[i] = math.Float64frombits(binary.LittleEndian.Uint64(xmm[i*SIZEOFINT64 : (i+1)*SIZEOFINT64])) } fmt.Printf("%v", data) } } func (xmm XMM) AsHex8() []string { data := make([]string, len(xmm)) for i := range data { value := int8(xmm[i]) data[i] = numberToString(int64(value), 8, 16, "0x") } reverseSlice(data) return data } func (xmm XMM) AsHex16() []string { data := make([]string, len(xmm)/SIZEOFINT16) for i := range data { value := int16(binary.LittleEndian.Uint16(xmm[i*SIZEOFINT16 : (i+1)*SIZEOFINT16])) data[i] = numberToString(int64(value), 16, 16, "0x") } reverseSlice(data) return data } func (xmm XMM) AsHex32() []string { data := make([]string, len(xmm)/SIZEOFINT32) for i := range data { value := int32(binary.LittleEndian.Uint32(xmm[i*SIZEOFINT32 : (i+1)*SIZEOFINT32])) data[i] = numberToString(int64(value), 32, 16, "0x") } reverseSlice(data) return data } //AsHex returns a slice with the values in the xmm register as hex quad words strings. func (xmm XMM) AsHex64() []string { data := make([]string, len(xmm)/SIZEOFINT64) for i := range data { value := binary.LittleEndian.Uint64(xmm[i*SIZEOFINT64 : (i+1)*SIZEOFINT64]) data[i] = numberToString(int64(value), 64, 16, "0x") } reverseSlice(data) return data } func (xmm XMM) AsBin8() []string { data := make([]string, len(xmm)) for i := range data { value := int8(xmm[i]) data[i] = numberToString(int64(value), 8, 2, "0b") } reverseSlice(data) return data } func (xmm XMM) AsBin16() []string { data := make([]string, len(xmm)/SIZEOFINT16) for i := range data { value := int16(binary.LittleEndian.Uint16(xmm[i*SIZEOFINT16 : (i+1)*SIZEOFINT16])) data[i] = numberToString(int64(value), 16, 2, "0b") } reverseSlice(data) return data } func (xmm XMM) AsBin32() []string { data := make([]string, len(xmm)/SIZEOFINT32) for i := range data { value := int32(binary.LittleEndian.Uint32(xmm[i*SIZEOFINT32 : (i+1)*SIZEOFINT32])) data[i] = numberToString(int64(value), 32, 2, "0b") } reverseSlice(data) return data } //AsBin returns a slice with the values in the xmm register as hex quad words strings. func (xmm XMM) AsBin64() []string { data := make([]string, len(xmm)/SIZEOFINT64) for i := range data { value := binary.LittleEndian.Uint64(xmm[i*SIZEOFINT64 : (i+1)*SIZEOFINT64]) data[i] = numberToString(int64(value), 64, 2, "0b") } reverseSlice(data) return data } //AsUint8 returns a slice with the values in the xmm register as unsigned bytes. //Must convert values to int16 because javascript won't recognize bytes as numbers. func (xmm XMM) AsUint8() []string { data := make([]string, len(xmm)) for i := range data { value := xmm[i] data[i] = strconv.Itoa(int(value)) } reverseSlice(data) return data } //AsInt8 returns a slice with the values in the xmm register as signed bytes. //Must convert values to int16 because javascript won't recognize bytes as numbers. func (xmm XMM) AsInt8() []string { data := make([]string, len(xmm)) for i := range data { value := int8(xmm[i]) data[i] = strconv.Itoa(int(value)) } reverseSlice(data) return data } //AsUint16 returns a slice with the values in the xmm register as unsigned words. func (xmm XMM) AsUint16() []string { data := make([]string, len(xmm)/SIZEOFINT16) for i := range data { value := binary.LittleEndian.Uint16(xmm[i*SIZEOFINT16 : (i+1)*SIZEOFINT16]) data[i] = strconv.Itoa(int(value)) } reverseSlice(data) return data } //AsInt16 returns a slice with the values in the xmm register as signed words. func (xmm XMM) AsInt16() []string { data := make([]string, len(xmm)/SIZEOFINT16) for i := range data { value := int16(binary.LittleEndian.Uint16(xmm[i*SIZEOFINT16 : (i+1)*SIZEOFINT16])) data[i] = strconv.Itoa(int(value)) } reverseSlice(data) return data } //AsUint32 returns a slice with the values in the xmm register as unsigned double words. func (xmm XMM) AsUint32() []string { data := make([]string, len(xmm)/SIZEOFINT32) for i := range data { value := binary.LittleEndian.Uint32(xmm[i*SIZEOFINT32 : (i+1)*SIZEOFINT32]) data[i] = strconv.Itoa(int(value)) } reverseSlice(data) return data } //AsInt32 returns a slice with the values in the xmm register as signed double words. func (xmm XMM) AsInt32() []string { data := make([]string, len(xmm)/SIZEOFINT32) for i := range data { value := int32(binary.LittleEndian.Uint32(xmm[i*SIZEOFINT32 : (i+1)*SIZEOFINT32])) data[i] = strconv.Itoa(int(value)) } reverseSlice(data) return data } //AsUint64 returns a slice with the values in the xmm register as unsigned quad words. func (xmm XMM) AsUint64() []string { data := make([]string, len(xmm)/SIZEOFINT64) for i := range data { value := binary.LittleEndian.Uint64(xmm[i*SIZEOFINT64 : (i+1)*SIZEOFINT64]) data[i] = strconv.FormatUint(value, 10) } reverseSlice(data) return data } //AsInt64 returns a slice with the values in the xmm register as quad words. func (xmm XMM) AsInt64() []string { data := make([]string, len(xmm)/SIZEOFINT64) for i := range data { value := int64(binary.LittleEndian.Uint64(xmm[i*SIZEOFINT64 : (i+1)*SIZEOFINT64])) data[i] = strconv.FormatInt(value, 10) } reverseSlice(data) return data } //AsFloat32 returns a slice with the values in the xmm register as simple precision numbers. func (xmm XMM) AsFloat32() []string { data := make([]string, len(xmm)/SIZEOFINT32) for i := range data { data[i] = fmt.Sprintf("%f", math.Float32frombits(binary.LittleEndian.Uint32(xmm[i*SIZEOFINT32:(i+1)*SIZEOFINT32]))) } reverseSlice(data) return data } //AsFloat64 returns a slice with the values in the xmm register as double precision numbers. func (xmm XMM) AsFloat64() []string { data := make([]string, len(xmm)/SIZEOFINT64) for i := range data { data[i] = fmt.Sprintf("%f", math.Float64frombits(binary.LittleEndian.Uint64(xmm[i*SIZEOFINT64:(i+1)*SIZEOFINT64]))) } reverseSlice(data) return data } //XMMHandler has all 16 XMM registers and is created with a pointer to the start of XMM Space. type XMMHandler struct { Xmm []XMM } //NewXMMHandler creates a new XMMHandler func NewXMMHandler(p *[]byte) XMMHandler { handlerRes := XMMHandler{Xmm: make([]XMM, XMMREGISTERS)} slice := *p for i := range handlerRes.Xmm { xmmSlice := slice[16*i : 16*(i+1)] handlerRes.Xmm[i] = NewXMM(&xmmSlice) } return handlerRes } //PrintAs print all XMM registers as the type passed by parameter. func (handler XMMHandler) PrintAs(format string) { for i, xmm := range handler.Xmm { fmt.Printf("\nXMM%-2v: ", i) xmm.PrintAs(format) } fmt.Printf("\n") } //GetXMMData will call the corresponding As<format> function given the xmmNumber and the data format desired. func (handler *XMMHandler) GetXMMData(xmmNumber int, dataFormat string, printFormat string) []string { switch dataFormat { case INT8STRING: if printFormat == UNSIGNEDFORMAT { return handler.Xmm[xmmNumber].AsUint8() } if printFormat == SIGNEDFORMAT { return handler.Xmm[xmmNumber].AsInt8() } if printFormat == HEXFORMAT { return handler.Xmm[xmmNumber].AsHex8() } if printFormat == BINARYFORMAT { return handler.Xmm[xmmNumber].AsBin8() } panic("Wrong format") case INT16STRING: if printFormat == UNSIGNEDFORMAT { return handler.Xmm[xmmNumber].AsUint16() } if printFormat == SIGNEDFORMAT { return handler.Xmm[xmmNumber].AsInt16() } if printFormat == HEXFORMAT { return handler.Xmm[xmmNumber].AsHex16() } if printFormat == BINARYFORMAT { return handler.Xmm[xmmNumber].AsBin16() } panic("Wrong format") case INT32STRING: if printFormat == UNSIGNEDFORMAT { return handler.Xmm[xmmNumber].AsUint32() } if printFormat == SIGNEDFORMAT { return handler.Xmm[xmmNumber].AsInt32() } if printFormat == HEXFORMAT { return handler.Xmm[xmmNumber].AsHex32() } if printFormat == BINARYFORMAT { return handler.Xmm[xmmNumber].AsBin32() } panic("Wrong format") case INT64STRING: if printFormat == UNSIGNEDFORMAT { return handler.Xmm[xmmNumber].AsUint64() } if printFormat == SIGNEDFORMAT { return handler.Xmm[xmmNumber].AsInt64() } if printFormat == HEXFORMAT { return handler.Xmm[xmmNumber].AsHex64() } if printFormat == BINARYFORMAT { return handler.Xmm[xmmNumber].AsBin64() } panic("Wrong format") case FLOAT32STRING: return handler.Xmm[xmmNumber].AsFloat32() case FLOAT64STRING: return handler.Xmm[xmmNumber].AsFloat64() default: panic("The XMM format is invalid") } } func reverseSlice(data interface{}) { value := reflect.ValueOf(data) valueLen := value.Len() for i := 0; i <= int((valueLen-1)/2); i++ { reverseIndex := valueLen - 1 - i tmp := value.Index(reverseIndex).Interface() value.Index(reverseIndex).Set(value.Index(i)) value.Index(i).Set(reflect.ValueOf(tmp)) } }
backend/xmmhandler/xmmhandler.go
0.551332
0.436622
xmmhandler.go
starcoder
package martinez_rueda import ( "github.com/paulmach/orb" ) type PointChain struct { segments []orb.Point closed bool } func NewPointChain(initSegment Segment) *PointChain { return &PointChain{ segments: []orb.Point{initSegment.begin(), initSegment.end()}, } } func (pc *PointChain) begin() orb.Point { return pc.segments[0] } func (pc *PointChain) end() orb.Point { return pc.segments[len(pc.segments)-1] } func (pc *PointChain) linkSegment(segment Segment) bool { front := pc.begin() back := pc.end() // CASE 1 if segment.begin().Equal(front) { if segment.end().Equal(back) { pc.closed = true } else { // Prepend one elements to the beginning of an array pc.segments = append([]orb.Point{segment.end()}, pc.segments...) } return true } // CASE 2 if segment.end().Equal(back) { if segment.begin().Equal(front) { pc.closed = true } else { pc.segments = append(pc.segments, segment.begin()) } return true } // CASE 3 if segment.end().Equal(front) { if segment.begin().Equal(back) { pc.closed = true } else { // Prepend one elements to the beginning of an array pc.segments = append([]orb.Point{segment.begin()}, pc.segments...) } return true } // CASE 4 if segment.begin().Equal(back) { if segment.end().Equal(front) { pc.closed = true } else { pc.segments = append(pc.segments, segment.end()) } return true } return false } func (pc *PointChain) linkChain(other *PointChain) bool { front := pc.begin() back := pc.end() otherFront := other.begin() otherBack := other.end() if otherFront.Equal(back) { // Shift an element off the beginning of array other.segments = other.segments[1:] // insert at the end of $this->segments pc.segments = append(pc.segments, other.segments...) return true } if otherBack.Equal(front) { // Shift an element off the beginning of array pc.segments = pc.segments[1:] // insert at the beginning of $this->segments pc.segments = append(other.segments, pc.segments...) return true } if otherFront.Equal(front) { // Shift an element off the beginning of array pc.segments = pc.segments[1:] other.segments = segmentsReverse(other.segments) // insert reversed at the beginning of $this->segments pc.segments = append(other.segments, pc.segments...) return true } if otherBack.Equal(back) { // array_pop — Pop the element off the end of array pc.segments = pc.segments[:(len(pc.segments) - 1)] other.segments = segmentsReverse(other.segments) // insert reversed at the end of $this->segments pc.segments = append(pc.segments, other.segments...) return true } return false } func segmentsReverse(segments []orb.Point) []orb.Point { for i, j := 0, len(segments)-1; i < j; i, j = i+1, j-1 { segments[i], segments[j] = segments[j], segments[i] } return segments } func (pc *PointChain) Size() int { return len(pc.segments) }
pointchain.go
0.713232
0.530601
pointchain.go
starcoder
package condition import ( "encoding/json" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeAny] = TypeSpec{ constructor: NewAny, description: ` Any is a condition that tests a child condition against each message of a batch individually. If any message passes the child condition then this condition also passes. For example, if we wanted to check that at least one message of a batch contains the word 'foo' we could use this config: ` + "``` yaml" + ` any: text: operator: contains arg: foo ` + "```" + ``, sanitiseConfigFunc: func(conf Config) (interface{}, error) { if conf.Any.Config == nil { return struct{}{}, nil } return SanitiseConfig(*conf.Any.Config) }, } } //------------------------------------------------------------------------------ // AnyConfig is a configuration struct containing fields for the Any condition. type AnyConfig struct { *Config `yaml:",inline" json:",inline"` } // NewAnyConfig returns a AnyConfig with default values. func NewAnyConfig() AnyConfig { return AnyConfig{ Config: nil, } } // MarshalJSON prints an empty object instead of nil. func (m AnyConfig) MarshalJSON() ([]byte, error) { if m.Config != nil { return json.Marshal(m.Config) } return json.Marshal(struct{}{}) } // MarshalYAML prints an empty object instead of nil. func (m AnyConfig) MarshalYAML() (interface{}, error) { if m.Config != nil { return *m.Config, nil } return struct{}{}, nil } // UnmarshalJSON ensures that when parsing child config it is initialised. func (m *AnyConfig) UnmarshalJSON(bytes []byte) error { if m.Config == nil { nConf := NewConfig() m.Config = &nConf } return json.Unmarshal(bytes, m.Config) } // UnmarshalYAML ensures that when parsing child config it is initialised. func (m *AnyConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { if m.Config == nil { nConf := NewConfig() m.Config = &nConf } return unmarshal(m.Config) } //------------------------------------------------------------------------------ // Any is a condition that returns the logical or of all children. type Any struct { child Type mCount metrics.StatCounter mTrue metrics.StatCounter mFalse metrics.StatCounter } // NewAny returns an Any condition. func NewAny( conf Config, mgr types.Manager, log log.Modular, stats metrics.Type, ) (Type, error) { childConf := conf.Any.Config if childConf == nil { newConf := NewConfig() childConf = &newConf } child, err := New(*childConf, mgr, log.NewModule(".any"), metrics.Namespaced(stats, "any")) if err != nil { return nil, err } return &Any{ child: child, mCount: stats.GetCounter("count"), mTrue: stats.GetCounter("true"), mFalse: stats.GetCounter("false"), }, nil } //------------------------------------------------------------------------------ // Check attempts to check a message part against a configured condition. func (c *Any) Check(msg types.Message) bool { c.mCount.Incr(1) for i := 0; i < msg.Len(); i++ { if c.child.Check(message.Lock(msg, i)) { c.mTrue.Incr(1) return true } } c.mFalse.Incr(1) return false } //------------------------------------------------------------------------------
lib/condition/any.go
0.744935
0.630145
any.go
starcoder
package datadog import ( "encoding/json" ) // LogsRetentionSumUsage Object containing indexed logs usage grouped by retention period and summed. type LogsRetentionSumUsage struct { // Total indexed logs for this retention period. LogsIndexedLogsUsageSum *int64 `json:"logs_indexed_logs_usage_sum,omitempty"` // Live indexed logs for this retention period. LogsLiveIndexedLogsUsageSum *int64 `json:"logs_live_indexed_logs_usage_sum,omitempty"` // Rehydrated indexed logs for this retention period. LogsRehydratedIndexedLogsUsageSum *int64 `json:"logs_rehydrated_indexed_logs_usage_sum,omitempty"` // The retention period in days or \"custom\" for all custom retention periods. Retention *string `json:"retention,omitempty"` // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct UnparsedObject map[string]interface{} `json:-` } // NewLogsRetentionSumUsage instantiates a new LogsRetentionSumUsage 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 NewLogsRetentionSumUsage() *LogsRetentionSumUsage { this := LogsRetentionSumUsage{} return &this } // NewLogsRetentionSumUsageWithDefaults instantiates a new LogsRetentionSumUsage 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 NewLogsRetentionSumUsageWithDefaults() *LogsRetentionSumUsage { this := LogsRetentionSumUsage{} return &this } // GetLogsIndexedLogsUsageSum returns the LogsIndexedLogsUsageSum field value if set, zero value otherwise. func (o *LogsRetentionSumUsage) GetLogsIndexedLogsUsageSum() int64 { if o == nil || o.LogsIndexedLogsUsageSum == nil { var ret int64 return ret } return *o.LogsIndexedLogsUsageSum } // GetLogsIndexedLogsUsageSumOk returns a tuple with the LogsIndexedLogsUsageSum field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsRetentionSumUsage) GetLogsIndexedLogsUsageSumOk() (*int64, bool) { if o == nil || o.LogsIndexedLogsUsageSum == nil { return nil, false } return o.LogsIndexedLogsUsageSum, true } // HasLogsIndexedLogsUsageSum returns a boolean if a field has been set. func (o *LogsRetentionSumUsage) HasLogsIndexedLogsUsageSum() bool { if o != nil && o.LogsIndexedLogsUsageSum != nil { return true } return false } // SetLogsIndexedLogsUsageSum gets a reference to the given int64 and assigns it to the LogsIndexedLogsUsageSum field. func (o *LogsRetentionSumUsage) SetLogsIndexedLogsUsageSum(v int64) { o.LogsIndexedLogsUsageSum = &v } // GetLogsLiveIndexedLogsUsageSum returns the LogsLiveIndexedLogsUsageSum field value if set, zero value otherwise. func (o *LogsRetentionSumUsage) GetLogsLiveIndexedLogsUsageSum() int64 { if o == nil || o.LogsLiveIndexedLogsUsageSum == nil { var ret int64 return ret } return *o.LogsLiveIndexedLogsUsageSum } // GetLogsLiveIndexedLogsUsageSumOk returns a tuple with the LogsLiveIndexedLogsUsageSum field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsRetentionSumUsage) GetLogsLiveIndexedLogsUsageSumOk() (*int64, bool) { if o == nil || o.LogsLiveIndexedLogsUsageSum == nil { return nil, false } return o.LogsLiveIndexedLogsUsageSum, true } // HasLogsLiveIndexedLogsUsageSum returns a boolean if a field has been set. func (o *LogsRetentionSumUsage) HasLogsLiveIndexedLogsUsageSum() bool { if o != nil && o.LogsLiveIndexedLogsUsageSum != nil { return true } return false } // SetLogsLiveIndexedLogsUsageSum gets a reference to the given int64 and assigns it to the LogsLiveIndexedLogsUsageSum field. func (o *LogsRetentionSumUsage) SetLogsLiveIndexedLogsUsageSum(v int64) { o.LogsLiveIndexedLogsUsageSum = &v } // GetLogsRehydratedIndexedLogsUsageSum returns the LogsRehydratedIndexedLogsUsageSum field value if set, zero value otherwise. func (o *LogsRetentionSumUsage) GetLogsRehydratedIndexedLogsUsageSum() int64 { if o == nil || o.LogsRehydratedIndexedLogsUsageSum == nil { var ret int64 return ret } return *o.LogsRehydratedIndexedLogsUsageSum } // GetLogsRehydratedIndexedLogsUsageSumOk returns a tuple with the LogsRehydratedIndexedLogsUsageSum field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsRetentionSumUsage) GetLogsRehydratedIndexedLogsUsageSumOk() (*int64, bool) { if o == nil || o.LogsRehydratedIndexedLogsUsageSum == nil { return nil, false } return o.LogsRehydratedIndexedLogsUsageSum, true } // HasLogsRehydratedIndexedLogsUsageSum returns a boolean if a field has been set. func (o *LogsRetentionSumUsage) HasLogsRehydratedIndexedLogsUsageSum() bool { if o != nil && o.LogsRehydratedIndexedLogsUsageSum != nil { return true } return false } // SetLogsRehydratedIndexedLogsUsageSum gets a reference to the given int64 and assigns it to the LogsRehydratedIndexedLogsUsageSum field. func (o *LogsRetentionSumUsage) SetLogsRehydratedIndexedLogsUsageSum(v int64) { o.LogsRehydratedIndexedLogsUsageSum = &v } // GetRetention returns the Retention field value if set, zero value otherwise. func (o *LogsRetentionSumUsage) GetRetention() string { if o == nil || o.Retention == nil { var ret string return ret } return *o.Retention } // GetRetentionOk returns a tuple with the Retention field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsRetentionSumUsage) GetRetentionOk() (*string, bool) { if o == nil || o.Retention == nil { return nil, false } return o.Retention, true } // HasRetention returns a boolean if a field has been set. func (o *LogsRetentionSumUsage) HasRetention() bool { if o != nil && o.Retention != nil { return true } return false } // SetRetention gets a reference to the given string and assigns it to the Retention field. func (o *LogsRetentionSumUsage) SetRetention(v string) { o.Retention = &v } func (o LogsRetentionSumUsage) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.UnparsedObject != nil { return json.Marshal(o.UnparsedObject) } if o.LogsIndexedLogsUsageSum != nil { toSerialize["logs_indexed_logs_usage_sum"] = o.LogsIndexedLogsUsageSum } if o.LogsLiveIndexedLogsUsageSum != nil { toSerialize["logs_live_indexed_logs_usage_sum"] = o.LogsLiveIndexedLogsUsageSum } if o.LogsRehydratedIndexedLogsUsageSum != nil { toSerialize["logs_rehydrated_indexed_logs_usage_sum"] = o.LogsRehydratedIndexedLogsUsageSum } if o.Retention != nil { toSerialize["retention"] = o.Retention } return json.Marshal(toSerialize) } func (o *LogsRetentionSumUsage) UnmarshalJSON(bytes []byte) (err error) { raw := map[string]interface{}{} all := struct { LogsIndexedLogsUsageSum *int64 `json:"logs_indexed_logs_usage_sum,omitempty"` LogsLiveIndexedLogsUsageSum *int64 `json:"logs_live_indexed_logs_usage_sum,omitempty"` LogsRehydratedIndexedLogsUsageSum *int64 `json:"logs_rehydrated_indexed_logs_usage_sum,omitempty"` Retention *string `json:"retention,omitempty"` }{} err = json.Unmarshal(bytes, &all) if err != nil { err = json.Unmarshal(bytes, &raw) if err != nil { return err } o.UnparsedObject = raw return nil } o.LogsIndexedLogsUsageSum = all.LogsIndexedLogsUsageSum o.LogsLiveIndexedLogsUsageSum = all.LogsLiveIndexedLogsUsageSum o.LogsRehydratedIndexedLogsUsageSum = all.LogsRehydratedIndexedLogsUsageSum o.Retention = all.Retention return nil } type NullableLogsRetentionSumUsage struct { value *LogsRetentionSumUsage isSet bool } func (v NullableLogsRetentionSumUsage) Get() *LogsRetentionSumUsage { return v.value } func (v *NullableLogsRetentionSumUsage) Set(val *LogsRetentionSumUsage) { v.value = val v.isSet = true } func (v NullableLogsRetentionSumUsage) IsSet() bool { return v.isSet } func (v *NullableLogsRetentionSumUsage) Unset() { v.value = nil v.isSet = false } func NewNullableLogsRetentionSumUsage(val *LogsRetentionSumUsage) *NullableLogsRetentionSumUsage { return &NullableLogsRetentionSumUsage{value: val, isSet: true} } func (v NullableLogsRetentionSumUsage) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableLogsRetentionSumUsage) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/v1/datadog/model_logs_retention_sum_usage.go
0.726231
0.491761
model_logs_retention_sum_usage.go
starcoder
package indicators import ( "errors" "github.com/jaybutera/gotrade" "math" ) // A Stop and Reverse Indicator (Sar), no storage, for use in other indicators type SarWithoutStorage struct { *baseIndicatorWithFloatBounds // private variables periodCounter int isLong bool extremePoint float64 accelerationFactor float64 acceleration float64 accelerationFactorMax float64 previousSar float64 previousHigh float64 previousLow float64 minusDM *MinusDmWithoutStorage hasInitialDirection bool } func NewSarWithoutStorage(accelerationFactor float64, accelerationFactorMax float64, valueAvailableAction ValueAvailableActionFloat) (indicator *SarWithoutStorage, err error) { // an indicator without storage MUST have a value available action if valueAvailableAction == nil { return nil, ErrValueAvailableActionIsNil } // the minimum accelerationFactor for this indicator is 0 if accelerationFactor < 0 { return nil, errors.New("accelerationFactor is less than the minimum (0)") } // check the maximum accelerationFactor if accelerationFactor >= math.MaxFloat64 { return nil, errors.New("accelerationFactor is greater than the maximum float64 size") } // the minimum accelerationFactorMax for this indicator is 0 if accelerationFactorMax < 0 { return nil, errors.New("accelerationFactorMax is less than the minimum (0)") } // check the maximum accelerationFactorMax if accelerationFactorMax >= math.MaxFloat64 { return nil, errors.New("accelerationFactorMax is greater than the maximum float64 size") } lookback := 1 ind := SarWithoutStorage{ baseIndicatorWithFloatBounds: newBaseIndicatorWithFloatBounds(lookback, valueAvailableAction), periodCounter: -2, isLong: false, hasInitialDirection: false, accelerationFactor: accelerationFactor, accelerationFactorMax: accelerationFactorMax, extremePoint: 0.0, previousSar: 0.0, previousHigh: 0.0, previousLow: 0.0, acceleration: accelerationFactor, } ind.minusDM, err = NewMinusDmWithoutStorage(1, func(dataItem float64, streamBarIndex int) { if dataItem > 0 { ind.isLong = false } else { ind.isLong = true } ind.hasInitialDirection = true }) return &ind, err } // A Stop and Reverse Indicator (Sar) type Sar struct { *SarWithoutStorage // public variables Data []float64 } // NewSar creates a Stop and Reverse Indicator (Sar) for online usage func NewSar(accelerationFactor float64, accelerationFactorMax float64) (indicator *Sar, err error) { ind := Sar{} ind.SarWithoutStorage, err = NewSarWithoutStorage(accelerationFactor, accelerationFactorMax, func(dataItem float64, streamBarIndex int) { ind.Data = append(ind.Data, dataItem) }) return &ind, err } // NewDefaultSar creates a Stop and Reverse Indicator (Sar) for online usage with default parameters // - accelerationFactor: 0.02 // - accelerationFactorMax: 0.2 func NewDefaultSar() (indicator *Sar, err error) { accelerationFactor := 0.02 accelerationFactorMax := 0.2 return NewSar(accelerationFactor, accelerationFactorMax) } // NewSarWithSrcLen creates a Stop and Reverse Indicator (Sar) for offline usage func NewSarWithSrcLen(sourceLength uint, accelerationFactor float64, accelerationFactorMax float64) (indicator *Sar, err error) { ind, err := NewSar(accelerationFactor, accelerationFactorMax) // only initialise the storage if there is enough source data to require it if sourceLength-uint(ind.GetLookbackPeriod()) > 1 { ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod())) } return ind, err } // NewDefaultSarWithSrcLen creates a Stop and Reverse Indicator (Sar) for offline usage with default parameters func NewDefaultSarWithSrcLen(sourceLength uint) (indicator *Sar, err error) { ind, err := NewDefaultSar() // only initialise the storage if there is enough source data to require it if sourceLength-uint(ind.GetLookbackPeriod()) > 1 { ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod())) } return ind, err } // NewSarForStream creates a Stop and Reverse Indicator (Sar) for online usage with a source data stream func NewSarForStream(priceStream gotrade.DOHLCVStreamSubscriber, accelerationFactor float64, accelerationFactorMax float64) (indicator *Sar, err error) { ind, err := NewSar(accelerationFactor, accelerationFactorMax) priceStream.AddTickSubscription(ind) return ind, err } // NewDefaultSarForStream creates a Stop and Reverse Indicator (Sar) for online usage with a source data stream func NewDefaultSarForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Sar, err error) { ind, err := NewDefaultSar() priceStream.AddTickSubscription(ind) return ind, err } // NewSarForStreamWithSrcLen creates a Stop and Reverse Indicator (Sar) for offline usage with a source data stream func NewSarForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, accelerationFactor float64, accelerationFactorMax float64) (indicator *Sar, err error) { ind, err := NewSarWithSrcLen(sourceLength, accelerationFactor, accelerationFactorMax) priceStream.AddTickSubscription(ind) return ind, err } // NewDefaultSarForStreamWithSrcLen creates a Stop and Reverse Indicator (Sar) for offline usage with a source data stream func NewDefaultSarForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Sar, err error) { ind, err := NewDefaultSarWithSrcLen(sourceLength) priceStream.AddTickSubscription(ind) return ind, err } // ReceiveDOHLCVTick consumes a source data DOHLCV price tick func (ind *SarWithoutStorage) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) { ind.periodCounter += 1 if ind.hasInitialDirection == false { ind.minusDM.ReceiveDOHLCVTick(tickData, streamBarIndex) } if ind.hasInitialDirection == true { if ind.periodCounter == 0 { if ind.isLong { ind.extremePoint = tickData.H() ind.previousSar = ind.previousLow } else { ind.extremePoint = tickData.L() ind.previousSar = ind.previousHigh } // this is a trick for the first iteration only, // the high low of the first bar will be used as the sar for the // second bar. According tyo TALib this is the closest to Wilders // originla idea of having the first entry day use the previous // extreme, except now that extreme is solely derived from the first // bar, supposedly Meta stock uses the same method. ind.previousHigh = tickData.H() ind.previousLow = tickData.L() } if ind.periodCounter >= 0 { var result float64 = 0.0 if ind.isLong { if tickData.L() <= ind.previousSar { // switch to short if the low penetrates the Sar value ind.isLong = false ind.previousSar = ind.extremePoint // make sure the overridden Sar is within yesterdays and todays range if ind.previousSar < ind.previousHigh { ind.previousSar = ind.previousHigh } if ind.previousSar < tickData.H() { ind.previousSar = tickData.H() } result = ind.previousSar ind.UpdateIndicatorWithNewValue(result, streamBarIndex) // adjust af and extremePoint ind.acceleration = ind.accelerationFactor ind.extremePoint = tickData.L() // calculate the new Sar var diff float64 = ind.extremePoint - ind.previousSar ind.previousSar = ind.previousSar + ind.acceleration*(diff) // make sure the overridden Sar is within yesterdays and todays range if ind.previousSar < ind.previousHigh { ind.previousSar = ind.previousHigh } if ind.previousSar < tickData.H() { ind.previousSar = tickData.H() } } else { // no switch // just output the current Sar result = ind.previousSar ind.UpdateIndicatorWithNewValue(result, streamBarIndex) if tickData.H() > ind.extremePoint { // adjust af and extremePoint ind.extremePoint = tickData.H() ind.acceleration += ind.accelerationFactor if ind.acceleration > ind.accelerationFactorMax { ind.acceleration = ind.accelerationFactorMax } } // calculate the new Sar var diff float64 = ind.extremePoint - ind.previousSar ind.previousSar = ind.previousSar + ind.acceleration*(diff) // make sure the overridden Sar is within yesterdays and todays range if ind.previousSar > ind.previousLow { ind.previousSar = ind.previousLow } if ind.previousSar > tickData.L() { ind.previousSar = tickData.L() } } } else { // short // switch to long if the high penetrates the Sar value if tickData.H() >= ind.previousSar { ind.isLong = true ind.previousSar = ind.extremePoint // make sure the overridden Sar is within yesterdays and todays range if ind.previousSar > ind.previousLow { ind.previousSar = ind.previousLow } if ind.previousSar > tickData.L() { ind.previousSar = tickData.L() } result = ind.previousSar ind.UpdateIndicatorWithNewValue(result, streamBarIndex) // adjust af and extremePoint ind.acceleration = ind.accelerationFactor ind.extremePoint = tickData.H() // calculate the new Sar var diff float64 = ind.extremePoint - ind.previousSar ind.previousSar = ind.previousSar + ind.acceleration*(diff) // make sure the overridden Sar is within yesterdays and todays range if ind.previousSar > ind.previousLow { ind.previousSar = ind.previousLow } if ind.previousSar > tickData.L() { ind.previousSar = tickData.L() } } else { // no switch // just output the current Sar result = ind.previousSar ind.UpdateIndicatorWithNewValue(result, streamBarIndex) if tickData.L() < ind.extremePoint { // adjust af and extremePoint ind.extremePoint = tickData.L() ind.acceleration += ind.accelerationFactor if ind.acceleration > ind.accelerationFactorMax { ind.acceleration = ind.accelerationFactorMax } } // calculate the new Sar var diff float64 = ind.extremePoint - ind.previousSar ind.previousSar = ind.previousSar + ind.acceleration*(diff) // make sure the overridden Sar is within yesterdays and todays range if ind.previousSar < ind.previousHigh { ind.previousSar = ind.previousHigh } if ind.previousSar < tickData.H() { ind.previousSar = tickData.H() } } } } } ind.previousHigh = tickData.H() ind.previousLow = tickData.L() }
indicators/sar.go
0.733738
0.492737
sar.go
starcoder
package gah import ( opensimplex "github.com/ojrac/opensimplex-go" ) // CoherentNoise provides automatic layering of opensimplex noise using parameters type CoherentNoise struct { Noise opensimplex.Noise // open simplex noise generator Scale float64 // number that determines at what distance to view the noisemap, smaller is closer Octaves int // the number of levels of detail you want you perlin noise to have, higher gives more possible detail Lacunarity float64 // number that determines how much detail is added or removed at each octave (adjusts frequency), higher gives less blending of octaves Persistence float64 // number that determines how much each octave contributes to the overall shape (adjusts amplitude), higher makes rougher } // NewCoherentNoise returns a CoherentNoise structure with the given parameters func NewCoherentNoise(seed int64, scale float64, octaves int, lacunarity float64, persistence float64) *CoherentNoise { return &CoherentNoise{opensimplex.New(seed), scale, octaves, lacunarity, persistence} } // GetParamSignature returns a byte slice containing all relevant unique parameters func (cnoise *CoherentNoise) GetParamSignature() (signature []byte) { signature = append(signature, Float64ToBytes(cnoise.Scale)...) signature = append(signature, IntToBytes(cnoise.Octaves)...) signature = append(signature, Float64ToBytes(cnoise.Lacunarity)...) signature = append(signature, Float64ToBytes(cnoise.Persistence)...) return signature } // GetEvalRange returns the min and max values that can be expected from the Eval2 func (cnoise *CoherentNoise) GetEvalRange() (outMin float64, outMax float64) { return -1, 1 } //TODO any way to reduce redundancy here? // eval1 works as Eval1 does on opensimplex.noise but applies layering through the CoherentNoise parameters func (cnoise *CoherentNoise) Eval1(x float64) float64 { var maxAmp float64 = 0 var amp float64 = 1 var freq float64 = cnoise.Scale var noiseSample float64 = 0 // add successively smaller, higher-frequency terms for i := 0; i < cnoise.Octaves; i++ { noiseSample += cnoise.Noise.Eval2(x*freq, 0) * amp maxAmp += amp amp *= cnoise.Persistence freq *= cnoise.Lacunarity } noiseSample /= maxAmp // take the average value of the iterations return noiseSample } // eval2 works as Eval2 does on opensimplex.noise but applies layering through the CoherentNoise parameters func (cnoise *CoherentNoise) Eval2(x, y float64) float64 { var maxAmp float64 = 0 var amp float64 = 1 var freq float64 = cnoise.Scale var noiseSample float64 = 0 // add successively smaller, higher-frequency terms for i := 0; i < cnoise.Octaves; i++ { noiseSample += cnoise.Noise.Eval2(x*freq, y*freq) * amp maxAmp += amp amp *= cnoise.Persistence freq *= cnoise.Lacunarity } noiseSample /= maxAmp // take the average value of the iterations return noiseSample } // eval3 works as Eval3 does on opensimplex.noise but applies layering through the CoherentNoise parameters func (cnoise *CoherentNoise) Eval3(x, y, z float64) float64 { var maxAmp float64 = 0 var amp float64 = 1 var freq float64 = cnoise.Scale var noiseSample float64 = 0 // add successively smaller, higher-frequency terms for i := 0; i < cnoise.Octaves; i++ { noiseSample += cnoise.Noise.Eval3(x*freq, y*freq, z*freq) * amp maxAmp += amp amp *= cnoise.Persistence freq *= cnoise.Lacunarity } noiseSample /= maxAmp // take the average value of the iterations return noiseSample } // eval4 works as Eval4 does on opensimplex.noise but applies layering through the CoherentNoise parameters func (cnoise *CoherentNoise) Eval4(x, y, z, w float64) float64 { var maxAmp float64 = 0 var amp float64 = 1 var freq float64 = cnoise.Scale var noiseSample float64 = 0 // add successively smaller, higher-frequency terms for i := 0; i < cnoise.Octaves; i++ { noiseSample += cnoise.Noise.Eval4(x*freq, y*freq, z*freq, w*freq) * amp maxAmp += amp amp *= cnoise.Persistence freq *= cnoise.Lacunarity } noiseSample /= maxAmp // take the average value of the iterations return noiseSample }
coherentnoise.go
0.709824
0.601652
coherentnoise.go
starcoder
package payload import ( "fmt" "strconv" ) type toIntFunc func(source *interface{}) int type toInt64Func func(source *interface{}) int64 type toFloat32Func func(source *interface{}) float32 type toFloat64Func func(source *interface{}) float64 type toUint64Func func(source *interface{}) uint64 type numberTransformer struct { name string toInt toIntFunc toInt64 toInt64Func toFloat32 toFloat32Func toFloat64 toFloat64Func toUint64 toUint64Func } func stringToFloat64(value string) float64 { fvalue, err := strconv.ParseFloat(value, 64) if err != nil { panic(fmt.Sprint("Could not convert string: ", value, " to a number!")) } return fvalue } var numberTransformers = []numberTransformer{ { name: "string", toInt: func(source *interface{}) int { return int(stringToFloat64((*source).(string))) }, toInt64: func(source *interface{}) int64 { return int64(stringToFloat64((*source).(string))) }, toFloat32: func(source *interface{}) float32 { return float32(stringToFloat64((*source).(string))) }, toFloat64: func(source *interface{}) float64 { return float64(stringToFloat64((*source).(string))) }, toUint64: func(source *interface{}) uint64 { return uint64(stringToFloat64((*source).(string))) }, }, { name: "int", toInt: func(source *interface{}) int { return (*source).(int) }, toInt64: func(source *interface{}) int64 { return int64((*source).(int)) }, toFloat32: func(source *interface{}) float32 { return float32((*source).(int)) }, toFloat64: func(source *interface{}) float64 { return float64((*source).(int)) }, toUint64: func(source *interface{}) uint64 { return uint64((*source).(int)) }, }, { name: "int32", toInt: func(source *interface{}) int { return int((*source).(int32)) }, toInt64: func(source *interface{}) int64 { return int64((*source).(int32)) }, toFloat32: func(source *interface{}) float32 { return float32((*source).(int32)) }, toFloat64: func(source *interface{}) float64 { return float64((*source).(int32)) }, toUint64: func(source *interface{}) uint64 { return uint64((*source).(int32)) }, }, { name: "int64", toInt: func(source *interface{}) int { return int((*source).(int64)) }, toInt64: func(source *interface{}) int64 { return (*source).(int64) }, toFloat32: func(source *interface{}) float32 { return float32((*source).(int64)) }, toFloat64: func(source *interface{}) float64 { return float64((*source).(int64)) }, toUint64: func(source *interface{}) uint64 { return uint64((*source).(int64)) }, }, { name: "float32", toInt: func(source *interface{}) int { return int((*source).(float32)) }, toInt64: func(source *interface{}) int64 { return int64((*source).(float32)) }, toFloat32: func(source *interface{}) float32 { return (*source).(float32) }, toFloat64: func(source *interface{}) float64 { return float64((*source).(float32)) }, toUint64: func(source *interface{}) uint64 { return uint64((*source).(float32)) }, }, { name: "float64", toInt: func(source *interface{}) int { return int((*source).(float64)) }, toInt64: func(source *interface{}) int64 { return int64((*source).(float64)) }, toFloat32: func(source *interface{}) float32 { return float32((*source).(float64)) }, toFloat64: func(source *interface{}) float64 { return (*source).(float64) }, toUint64: func(source *interface{}) uint64 { return uint64((*source).(float64)) }, }, { name: "uint64", toInt: func(source *interface{}) int { return int((*source).(uint64)) }, toInt64: func(source *interface{}) int64 { return int64((*source).(uint64)) }, toFloat32: func(source *interface{}) float32 { return float32((*source).(uint64)) }, toFloat64: func(source *interface{}) float64 { return float64((*source).(uint64)) }, toUint64: func(source *interface{}) uint64 { return (*source).(uint64) }, }, } // MapTransformer : return the map transformer for the specific map type func getNumberTransformer(value *interface{}) *numberTransformer { valueType := GetValueType(value) for _, transformer := range numberTransformers { if valueType == transformer.name { return &transformer } } fmt.Println("[WARN] getNumberTransformer() no transformer for valueType -> ", valueType) return nil }
payload/numberTransformers.go
0.628635
0.446133
numberTransformers.go
starcoder
package iso20022 // Information about a statement of investment fund transactions. type StatementOfInvestmentFundTransactions3 struct { // General information related to the investment fund statement of transactions that is being cancelled. StatementGeneralDetails *Statement8 `xml:"StmtGnlDtls,omitempty"` // Information related to an investment account of the statement that is being cancelled. InvestmentAccountDetails *InvestmentAccount43 `xml:"InvstmtAcctDtls,omitempty"` // Creation/cancellation of investment units on the books of the fund or its designated agent, as a result of executing an investment fund order. TransactionOnAccount []*InvestmentFundTransactionsByFund3 `xml:"TxOnAcct,omitempty"` // Sub-account of the safekeeping or investment account. SubAccountDetails []*SubAccountIdentification36 `xml:"SubAcctDtls,omitempty"` // Additional information that cannot be captured in the structured elements and/or any other specific block. Extension []*Extension1 `xml:"Xtnsn,omitempty"` } func (s *StatementOfInvestmentFundTransactions3) AddStatementGeneralDetails() *Statement8 { s.StatementGeneralDetails = new(Statement8) return s.StatementGeneralDetails } func (s *StatementOfInvestmentFundTransactions3) AddInvestmentAccountDetails() *InvestmentAccount43 { s.InvestmentAccountDetails = new(InvestmentAccount43) return s.InvestmentAccountDetails } func (s *StatementOfInvestmentFundTransactions3) AddTransactionOnAccount() *InvestmentFundTransactionsByFund3 { newValue := new(InvestmentFundTransactionsByFund3) s.TransactionOnAccount = append(s.TransactionOnAccount, newValue) return newValue } func (s *StatementOfInvestmentFundTransactions3) AddSubAccountDetails() *SubAccountIdentification36 { newValue := new(SubAccountIdentification36) s.SubAccountDetails = append(s.SubAccountDetails, newValue) return newValue } func (s *StatementOfInvestmentFundTransactions3) AddExtension() *Extension1 { newValue := new(Extension1) s.Extension = append(s.Extension, newValue) return newValue }
StatementOfInvestmentFundTransactions3.go
0.742888
0.408631
StatementOfInvestmentFundTransactions3.go
starcoder
package caleb import ( "fmt" "math" "time" ) type JewishDate struct { Shana int Chodesh int Yom int } // Short returns a numerical representation of the Jewish date: 5779-07-25. func (t JewishDate) Short() string { return fmt.Sprintf("%02d-%02d-%04d", t.Yom, t.Chodesh, t.Shana) } // String returns a representation of the Jewish date where the month is spelled out: 25 Adar II 5779. func (t JewishDate) String() string { chodashim := [13]string{"Tishri", "Cheshvan", "Kislev", "Tevet", "Shevat", "Adar", "Adar II", "Nisan", "Yiar", "Sivan", "Tamuz", "Av", "Elul"} return fmt.Sprintf("%02d %s %04d", t.Yom, chodashim[t.Chodesh-1], t.Shana) } // Serialize returns the components Shana, Chodesh, Yom. func (t JewishDate) Serialize() (Shana int, Chodesh int, Yom int) { return t.Shana, t.Chodesh, t.Yom } // MonthsSinceFirstMolad returns the number of months since the very first Molad until the beginning of the passed shana. func MonthsSinceFirstMolad(shana int) (n int) { return int(math.Floor(((float64(shana) * 235) - 234) / 19)) } // Shana Mehubberet has 13 months instead of 12 and occurs on years 3, 6, 8, 11, 14, 17, 19 of a 19 year cycle. func IsMehubberet(shana int) (mehubberet bool) { switch shana % 19 { case 3, 6, 8, 11, 14, 17, 0: return true } return false } // RoshHashana returns the gregorian day for <NAME> (1st of Tishri) of the passed shana. func RoshHashana(shana int) (roshHashana time.Time) { var nMonthsSinceFirstMolad int var nChalakim int var nHours int var nDays int var nDayOfWeek int nMonthsSinceFirstMolad = MonthsSinceFirstMolad(shana) nChalakim = 793 * nMonthsSinceFirstMolad nChalakim += 204 // carry the excess Chalakim over to the hours nHours = int(math.Floor(float64(nChalakim) / 1080)) nChalakim = nChalakim % 1080 nHours += nMonthsSinceFirstMolad * 12 nHours += 5 // carry the excess hours over to the days nDays = int(math.Floor(float64(nHours) / 24)) nHours = nHours % 24 nDays += 29 * nMonthsSinceFirstMolad nDays += 2 // figure out which day of the week the molad occurs. // Sunday = 1, Moday = 2 ..., Shabbos = 0 nDayOfWeek = nDays % 7 if !IsMehubberet(shana) && nDayOfWeek == 3 && (nHours*1080)+nChalakim >= (9*1080)+204 { // This prevents the year from being 356 days. We have to push // <NAME> off two days because if we pushed it off only // one day, <NAME> would comes out on a Wednesday. Check // the Hebrew year 5745 for an example. nDayOfWeek = 5 nDays += 2 } else if IsMehubberet(shana-1) && nDayOfWeek == 2 && (nHours*1080)+nChalakim >= (15*1080)+589 { // This prevents the previous year from being 382 days. Check // the Hebrew Year 5766 for an example. If <NAME> was not // pushed off a day then 5765 would be 382 days nDayOfWeek = 3 nDays += 1 } else { // see rule 2 above. Check the Hebrew year 5765 for an example if nHours >= 18 { nDayOfWeek += 1 nDayOfWeek = nDayOfWeek % 7 nDays += 1 } // see rule 1 above. Check the Hebrew year 5765 for an example switch nDayOfWeek { case 1, 4, 6: nDayOfWeek += 1 nDayOfWeek = nDayOfWeek % 7 nDays += 1 } } nDays -= 2067025 roshHashana = time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC) // 2067025 days after creation roshHashana = roshHashana.AddDate(0, 0, nDays) return } // DaysInShana return the number of days in the passed shana. func DaysInShana(shana int) int { return int(math.Round(RoshHashana(shana+1).Sub(RoshHashana(shana)).Hours() / 24)) } // JewishToGregorian accepts a JewishDate struct and returns the corresponding gregorian date in time.Time format. // Only the date part is relevant, time will be 0 and timezone UTC. func JewishToGregorian(j JewishDate) (gregorian time.Time) { var nLengthOfYear int var bLeap bool var dGreg time.Time var nMonth int var nMonthLen int var bHaser bool var bShalem bool shana, chodesh, yom := j.Serialize() bLeap = IsMehubberet(shana) nLengthOfYear = DaysInShana(shana) // The regular length of a non-leap year is 354 days. // The regular length of a leap year is 384 days. // On regular years, the length of the months are as follows // Tishrei (1) 30 // Cheshvan(2) 29 // Kislev (3) 30 // Teves (4) 29 // Shevat (5) 30 // <NAME> (6) 30 (only valid on leap years) // Adar (7) 29 (Adar B for leap years) // Nisan (8) 30 // Iyar (9) 29 // Sivan (10) 30 // Tamuz (11) 29 // Av (12) 30 // Elul (13) 29 // If the year is shorter by one less day, it is called a haser // year. Kislev on a haser year has 29 days. If the year is longer // by one day, it is called a shalem year. Cheshvan on a shalem // year is 30 days. bHaser = (nLengthOfYear == 353 || nLengthOfYear == 383) bShalem = (nLengthOfYear == 355 || nLengthOfYear == 385) // get the date for Tishrei 1 dGreg = RoshHashana(shana) // Now count up days within the year for nMonth = 1; nMonth <= chodesh-1; nMonth++ { switch nMonth { case 1, 5, 8, 10, 12: nMonthLen = 30 case 4, 7, 9, 11, 13: nMonthLen = 29 case 6: if bLeap { nMonthLen = 30 } else { nMonthLen = 0 } case 2: if bShalem { nMonthLen = 30 } else { nMonthLen = 29 } case 3: if bHaser { nMonthLen = 29 } else { nMonthLen = 30 } } dGreg = dGreg.AddDate(0, 0, nMonthLen) } dGreg = dGreg.AddDate(0, 0, yom-1) return dGreg } // GregorianToJewish accepts a gregorian date in time.Time format and returns a JewishDate struct. // Only the date part is relevant, time and timezone are discarded. func GregorianToJewish(dGreg time.Time) JewishDate { var nYearH int var nMonthH int var nDateH int var nOneMolad float64 var nAvrgYear float64 var nDays int var dTishrei1 time.Time var nLengthOfYear int var bLeap bool var bHaser bool var bShalem bool var nMonthLen int var bWhile = true d1900 := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC) // The basic algorythm to get Hebrew date for the Gregorian date dGreg. // 1) Find out how many days dGreg is after creation. // 2) Based on those days, estimate the Hebrew year // 3) Now that we a good estimate of the Hebrew year, use brute force to // find the Gregorian date for Tishrei 1 prior to or equal to dGreg // 4) Add to Tishrei 1 the amount of days dGreg is after Tishrei 1 // Figure out how many days are in a month. // 29 days + 12 hours + 793 chalakim nOneMolad = 29.0 + (12.0 / 24.0) + (793.0 / (1080.0 * 24.0)) // Figure out the average length of a year. The hebrew year has exactly // 235 months over 19 years. nAvrgYear = nOneMolad * (235.0 / 19.0) // Get how many days dGreg is after creation. See note as to why I // use 1/1/1900 and add 2067025 nDays = int(math.Round((dGreg.Sub(d1900).Hours() / 24))) nDays += 2067025 // 2067025 days after creation // Guess the Hebrew year. This should be a pretty accurate guess. nYearH = int(math.Floor(float64(nDays)/nAvrgYear) + 1) // Use brute force to find the exact year nYearH. It is the Tishrei 1 in // the year <= dGreg. dTishrei1 = RoshHashana(nYearH) if SameDate(dTishrei1, dGreg) { // If we got lucky and landed on the exact date, we can stop here nMonthH = 1 nDateH = 1 } else { // Here is the brute force. Either count up or count down nYearH // until Tishrei 1 is <= dGreg. if dTishrei1.Sub(dGreg).Hours() < 0 { // If Tishrei 1, nYearH is less than dGreg, count nYearH up. for RoshHashana(nYearH+1).Sub(dGreg).Hours() <= 0 { nYearH += 1 } } else { // If Tishrei 1, nYearH is greater than dGreg, count nYearH down. nYearH -= 1 for RoshHashana(nYearH).Sub(dGreg).Hours() > 0 { nYearH -= 1 } } // Subtract Tishrei 1, nYearH from dGreg. That should leave us with // how many days we have to add to Tishrei 1 nDays = int(math.Round((dGreg.Sub(RoshHashana(nYearH)).Hours() / 24))) // Find out what type of year it is so that we know the length of the // months nLengthOfYear = DaysInShana(nYearH) bHaser = nLengthOfYear == 353 || nLengthOfYear == 383 bShalem = nLengthOfYear == 355 || nLengthOfYear == 385 bLeap = IsMehubberet(nYearH) // Add nDays to Tishrei 1. nMonthH = 1 for bWhile { switch nMonthH { case 1, 5, 6, 8, 10, 12: nMonthLen = 30 case 4, 7, 9, 11, 13: nMonthLen = 29 case 2: // Cheshvan, see note above if bShalem { nMonthLen = 30 } else { nMonthLen = 29 } case 3: // Kislev, see note above if bHaser { nMonthLen = 29 } else { nMonthLen = 30 } } if nDays >= nMonthLen { bWhile = true if bLeap || nMonthH != 5 { nMonthH++ } else { // We can skip Adar A (6) if its not a leap year nMonthH += 2 } nDays -= nMonthLen } else { bWhile = false } } //Add the remaining days to Date nDateH = nDays + 1 } if nMonthH == 7 && bLeap == false { nMonthH = 6 } return JewishDate{Shana: nYearH, Chodesh: nMonthH, Yom: nDateH} } // SameDate checks whether the date part of two time.Time objects is the same; time and timezone are not taken into account. func SameDate(d1, d2 time.Time) bool { return d1.Day() == d2.Day() && d1.Month() == d2.Month() && d1.Year() == d2.Year() }
caleb.go
0.710929
0.437763
caleb.go
starcoder
package io import ( "github.com/hajimehoshi/ebiten" ) // GBIO represents the controller key matrix // <NAME> has a good description and diagram of how this works: // http://imrannazar.com/GameBoy-Emulation-in-JavaScript:-Input // When 0xFF00 is written to, one of two columns is selected as `col` // One column has Down/Up/Left/Right d-pad buttons, // the other has Start/Select/B/A. // We can represent this using an array of 2 bytes // The 2 elements represent the columns, and the value represents which // buttons were pressed type GBIO struct { buttons [2]byte col byte } // InitIO initializes the GBIO struct // Key values are set to 0x0F and column 0 is selected by default func (gbio *GBIO) InitIO() { gbio.buttons[0], gbio.buttons[1] = 0x0F, 0x0F gbio.col = 0 } // ReadInput is called from our main update loop // Determines which buttons were pressed for this frame, sets bytes in // buttons array accordingly func (gbio *GBIO) ReadInput() { // Start button if ebiten.IsKeyPressed(ebiten.KeyEnter) { gbio.buttons[0] &= 0x7 } else { gbio.buttons[0] |= 0x8 } // Select button if ebiten.IsKeyPressed(ebiten.KeyShift) { gbio.buttons[0] &= 0xB } else { gbio.buttons[0] |= 0x5 } // B button if ebiten.IsKeyPressed(ebiten.KeyZ) { gbio.buttons[0] &= 0xD } else { gbio.buttons[0] |= 0x2 } // A button if ebiten.IsKeyPressed(ebiten.KeyX) { gbio.buttons[0] &= 0xE } else { gbio.buttons[0] |= 0x1 } // D-pad up if ebiten.IsKeyPressed(ebiten.KeyUp) { gbio.buttons[1] &= 0xB } else { gbio.buttons[1] |= 0x4 } // D-pad down if ebiten.IsKeyPressed(ebiten.KeyDown) { gbio.buttons[1] &= 0x7 } else { gbio.buttons[1] |= 0x8 } // D-pad left if ebiten.IsKeyPressed(ebiten.KeyLeft) { gbio.buttons[1] &= 0xD } else { gbio.buttons[1] |= 0x2 } // D-pad right if ebiten.IsKeyPressed(ebiten.KeyRight) { gbio.buttons[1] &= 0xE } else { gbio.buttons[1] |= 0x1 } } // SetCol sets the column for inputs we should return to the CPU // This is called when a write to 0xFF00 happens, handled by the MMU // Will either be set to 0 or 1 func (gbio *GBIO) SetCol(data byte) { gbio.col = data & 0x30 } // GetInput returns a byte representing which buttons were pressed for // this frame // The button returned is dependent on which column is selected func (gbio *GBIO) GetInput() byte { switch gbio.col { case 0x10: return gbio.buttons[0] case 0x20: return gbio.buttons[1] default: return 0x00 } }
io/io.go
0.569134
0.483831
io.go
starcoder
package main import ( "bufio" "encoding/csv" "fmt" "io" "log" "math" "math/rand" "os" "strconv" ) // sigmoid Sigmoid activation function: f(x) = 1 / (1 + e^(-x)) func sigmoid(x float64) float64 { return 1 / (1 + math.Exp(-x)) } // derivSigmoid Derivative of sigmoid: f'(x) = f(x) * (1 - f(x)) func derivSigmoid(x float64) float64 { fx := sigmoid(x) return fx * (1 - fx) } // mse Mean Squared Error func mse(inputs []Input, predictions []float64) float64 { len := len(inputs) var total float64 for i := 0; i < len; i++ { total += math.Pow(inputs[i].Expected-predictions[i], 2) } return total / float64(len) } // ApplyInputToNeuron returns activation and result func ApplyInputToNeuron(i Input, n Neuron) (float64, float64) { result := n.Weight1*i.One + n.Weight2*i.Two + n.Bias activation := sigmoid(result) return activation, result } // Predict generates the prediction func Predict(n1, n2, n3 Neuron, i Input) float64 { n1Activation, _ := ApplyInputToNeuron(i, n1) n2Activation, _ := ApplyInputToNeuron(i, n2) n3Activation, _ := ApplyInputToNeuron(Input{n1Activation, n2Activation, 0.0}, n3) return n3Activation } // Input represents a input type Input struct { One float64 Two float64 Expected float64 } // Neuron represents a single neuron type Neuron struct { Weight1 float64 Weight2 float64 Bias float64 } // GenNeuron returns a new randomized neuron func GenNeuron() Neuron { return Neuron{rand.NormFloat64(), rand.NormFloat64(), rand.NormFloat64()} } // GenTrainingData generates the training Data func GenTrainingData() []Input { var inputs []Input csvFile, _ := os.Open("inputs.csv") reader := csv.NewReader(bufio.NewReader(csvFile)) tWeight := 0.0 tHeight := 0.0 for { line, error := reader.Read() if error == io.EOF { break } else if error != nil { log.Fatal(error) } expected := 1.0 if line[0] == "Male" { expected = 0.0 } weight, _ := strconv.ParseFloat(line[2], 64) height, _ := strconv.ParseFloat(line[1], 64) tWeight += weight tHeight += height inputs = append(inputs, Input{ One: weight, Two: height, Expected: expected, }) } avgHeight := tHeight / float64(len(inputs)) avgWeight := tWeight / float64(len(inputs)) for i := range inputs { inputs[i].One -= avgWeight inputs[i].Two -= avgHeight } return inputs } func main() { n1 := GenNeuron() n2 := GenNeuron() n3 := GenNeuron() inputs := GenTrainingData() learnRate := 0.0001 epochs := 4000 lastLoss := 0.0 lastLossSetValue := 0.0 lastLossSet := false for i := 1; i <= epochs; i++ { for _, input := range inputs { n1Activation, n1Result := ApplyInputToNeuron(input, n1) n2Activation, n2Result := ApplyInputToNeuron(input, n2) n3Activation, n3Result := ApplyInputToNeuron(Input{n1Activation, n2Activation, 0.0}, n3) prediction := n3Activation pLpPrediction := -2 * (input.Expected - prediction) // Neuron 3 (output) pPredictionpW5 := n1Activation * derivSigmoid(n3Result) pPredictionpW6 := n2Activation * derivSigmoid(n3Result) pPredictionpB3 := derivSigmoid(n3Result) pPredictionpN1Activation := n3.Weight1 * derivSigmoid(n3Result) pPredictionpN2Activation := n3.Weight2 * derivSigmoid(n3Result) // Neuron 1 pN1ActivationpN1W1 := input.One * derivSigmoid(n1Result) pN1ActivationpN1W2 := input.Two * derivSigmoid(n1Result) pN1ActivationpN1B1 := derivSigmoid(n1Result) // Neuron 2 pN2ActivationpW3 := input.One * derivSigmoid(n2Result) pN2ActivationpW4 := input.Two * derivSigmoid(n2Result) pN2ActivationpB2 := derivSigmoid(n2Result) n1.Weight1 -= learnRate * pLpPrediction * pPredictionpN1Activation * pN1ActivationpN1W1 n1.Weight2 -= learnRate * pLpPrediction * pPredictionpN1Activation * pN1ActivationpN1W2 n1.Bias -= learnRate * pLpPrediction * pPredictionpN1Activation * pN1ActivationpN1B1 n2.Weight1 -= learnRate * pLpPrediction * pPredictionpN2Activation * pN2ActivationpW3 n2.Weight2 -= learnRate * pLpPrediction * pPredictionpN2Activation * pN2ActivationpW4 n2.Bias -= learnRate * pLpPrediction * pPredictionpN2Activation * pN2ActivationpB2 n3.Weight1 -= learnRate * pLpPrediction * pPredictionpW5 n3.Weight2 -= learnRate * pLpPrediction * pPredictionpW6 n3.Bias -= learnRate * pLpPrediction * pPredictionpB3 } var dPredictions []float64 for _, input := range inputs { dPredictions = append(dPredictions, Predict(n1, n2, n3, input)) } loss := mse(inputs, dPredictions) if !lastLossSet { fmt.Printf("Epoch %d loss %.4f\n", i, loss) lastLossSetValue = loss lastLossSet = true } if lastLossSetValue/loss >= 2.0 { fmt.Printf("Epoch %d loss %.4f\n", i, loss) lastLossSetValue = loss } lastLoss = loss } fmt.Printf("Final Epoch %d has %.2f%% accuracy!\n", epochs, (1.0-lastLoss)*100) a1 := Predict(n1, n2, n3, Input{136.6870, 69.6850, +1.0}) a2 := Predict(n1, n2, n3, Input{244.7130, 72.0472, +0.0}) a3 := Predict(n1, n2, n3, Input{141.0960, 66.5354, +0.0}) fmt.Printf("Fabiana WomanIndex: %.4f%%\n", a1*100) fmt.Printf("Guilherme WomanIndex: %.4f%%\n", a2*100) fmt.Printf("Rosely WomanIndex: %.4f%%\n", a3*100) }
main.go
0.665519
0.544983
main.go
starcoder
package telegram // LabeledPrice : This object represents a portion of the price for goods or services. type LabeledPrice struct { Label string `json:"label"` // Portion label Amount int64 `json:"amount"` // Price of the product in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). } // Invoice : This object contains basic information about an invoice. type Invoice struct { Title string `json:"title"` // Product name Description string `json:"description"` // Product description StartParameter string `json:"start_parameter"` // Unique bot deep-linking parameter that can be used to generate this invoice Currency string `json:"currency"` // Three-letter ISO 4217 currency code TotalAmount int64 `json:"total_amount"` // Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). } // ShippingAddress : This object represents a shipping address. type ShippingAddress struct { CountryCode string `json:"country_code"` // ISO 3166-1 alpha-2 country code State string `json:"state"` // State, if applicable City string `json:"city"` // City StreetLine1 string `json:"street_line_1"` // First line for the address StreetLine2 string `json:"street_line_2"` // Second line for the address PostCode string `json:"post_code"` // Address post code } // OrderInfo : This object represents information about an order. type OrderInfo struct { Name *string `json:"name"` // Optional. User name PhoneNumber *string `json:"phone_number"` // Optional. User's phone number Email *string `json:"email"` // Optional. User email ShippingAddress *ShippingAddress `json:"shipping_address"` // Optional. User shipping address } // ShippingOption : This object represents one shipping option. type ShippingOption struct { ID string `json:"id"` // Shipping option identifier Title *string `json:"title"` // Option title Prices []LabeledPrice `json:"prices"` // List of price portions } // SuccessfulPayment : This object contains basic information about a successful payment. type SuccessfulPayment struct { Currency string `json:"currency"` // Three-letter ISO 4217 currency code TotalAmount int64 `json:"total_amount"` // Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). InvoicePayload string `json:"invoice_payload"` // Bot specified invoice payload ShippingOptionID *string `json:"shipping_option_id"` // Optional. Identifier of the shipping option chosen by the user OrderInfo *OrderInfo `json:"order_info"` // Optional. Order info provided by the user TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` // Telegram payment identifier ProviderPaymentChargeID string `json:"provider_payment_charge_id"` // Provider payment identifier } // ShippingQuery : This object contains information about an incoming shipping query. type ShippingQuery struct { ID string `json:"id"` // Unique query identifier From User `json:"from"` // User who sent the query InvoicePayload string `json:"invoice_payload"` // Bot specified invoice payload ShippingAddress ShippingAddress `json:"shipping_address"` // User specified shipping address } // PreCheckoutQuery : This object contains information about an incoming pre-checkout query. type PreCheckoutQuery struct { ID string `json:"id"` // Unique query identifier From User `json:"from"` // User who sent the query Currency string `json:"currency"` // Three-letter ISO 4217 currency code TotalAmount int64 `json:"total_amount"` // Total price in the smallest units of the currency (integer, not float/double). For example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). InvoicePayload string `json:"invoice_payload"` // Bot specified invoice payload ShippingOptionID *string `json:"shipping_option_id"` // Optional. Identifier of the shipping option chosen by the user OrderInfo *OrderInfo `json:"order_info"` // Optional. Order info provided by the user }
payment_types.go
0.856573
0.547162
payment_types.go
starcoder
// Package slices defines various functions useful with slices of any type. // Unless otherwise specified, these functions all apply to the elements // of a slice at index 0 <= i < len(s). package slices import "golang.design/x/go2generics/std/constraints" // See #45458 // Equal reports whether two slices are equal: the same length and all // elements equal. If the lengths are different, Equal returns false. // Otherwise, the elements are compared in index order, and the // comparison stops at the first unequal pair. // Floating point NaNs are not considered equal. func Equal[T comparable](s1, s2 []T) bool { if len(s1) != len(s2) { return false } for i := range s1 { if s1[i] != s2[i] { return false } } return true } // EqualFunc reports whether two slices are equal using a comparison // function on each pair of elements. If the lengths are different, // EqualFunc returns false. Otherwise, the elements are compared in // index order, and the comparison stops at the first index for which // eq returns false. func EqualFunc[T1, T2 any](s1 []T1, s2 []T2, eq func(T1, T2) bool) bool { if len(s1) != len(s2) { return false } for i := range s1 { if !eq(s1[i], s2[i]) { return false } } return true } // Compare compares the elements of s1 and s2. // The elements are compared sequentially starting at index 0, // until one element is not equal to the other. The result of comparing // the first non-matching elements is the result of the comparison. // If both slices are equal until one of them ends, the shorter slice is // considered less than the longer one // The result will be 0 if s1==s2, -1 if s1 < s2, and +1 if s1 > s2. func Compare[T constraints.Ordered](s1, s2 []T) int { min := func(a, b int) int { if a < b { return a } return b } l := min(len(s1), len(s2)) for i := 0; i < l; i++ { switch { case s1[i] == s2[i]: continue case s1[i] < s2[i]: return -1 case s1[i] > s2[i]: return 1 } } switch { case l == len(s1) && l == len(s2): return 0 case l < len(s1): // s1 is longer return 1 case l < len(s2): // s2 is longer fallthrough default: return -1 } } // CompareFunc is like Compare, but uses a comparison function // on each pair of elements. The elements are compared in index order, // and the comparisons stop after the first time cmp returns non-zero. // The result will be the first non-zero result of cmp; if cmp always // returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2), // and +1 if len(s1) > len(s2). func CompareFunc[T any](s1, s2 []T, cmp func(T, T) int) int { min := func(a, b int) int { if a < b { return a } return b } l := min(len(s1), len(s2)) for i := 0; i < l; i++ { switch cmp(s1[i], s2[i]) { case 0: continue case -1: return -1 case 1: return 1 } } switch { case l == len(s1) && l == len(s2): return 0 case l < len(s1): // s1 is longer return 1 case l < len(s2): // s2 is longer fallthrough default: return -1 } } // Index returns the index of the first occurrence of v in s, or -1 if not present. func Index[T comparable](s []T, v T) int { for i := range s { if v == s[i] { return i } } return -1 } // IndexFunc returns the index into s of the first element // satisfying f(c), or -1 if none do. func IndexFunc[T any](s []T, f func(T) bool) int { for i := range s { if f(s[i]) { return i } } return -1 } // Contains reports whether v is present in s. func Contains[T comparable](s []T, v T) bool { return Index[T](s, v) != -1 } // Insert inserts the values v... into s at index i, returning the modified slice. // In the returned slice r, r[i] == the first v. Insert panics if i is out of range. // This function is O(len(s) + len(v)). func Insert[S constraints.Slice[T], T any](s S, i int, v ...T) S { if i > len(s) { panic("slices: out of slice index") } s = s[:i] s = append(s, v...) return s } // Delete removes the elements s[i:j] from s, returning the modified slice. // Delete panics if s[i:j] is not a valid slice of s. // Delete modifies the contents of the slice s; it does not create a new slice. // Delete is O(len(s)-(j-i)), so if many items must be deleted, it is better to // make a single call deleting them all together than to delete one at a time. func Delete[S constraints.Slice[T], T any](s S, i, j int) S { if !(0 < i && i < len(s)) || !(0 < j && j < len(s)) || i > j { panic("slices: invalid index i or j") } s = s[:i] s = append(s, s[j:]...) return s } // Clone returns a copy of the slice. // The elements are copied using assignment, so this is a shallow clone. func Clone[S constraints.Slice[T], T any](s S) S { ss := make([]T, len(s)) for i := range s { ss[i] = s[i] } return ss } // Compact replaces consecutive runs of equal elements with a single copy. // This is like the uniq command found on Unix. // Compact modifies the contents of the slice s; it does not create a new slice. func Compact[S constraints.Slice[T], T comparable](s S) S { if s == nil { return s } lastIdx := len(s) - 1 for i := len(s) - 2; i != 0; i-- { if s[i] == s[lastIdx] { continue } s = append(s[:i+1], s[lastIdx:]...) lastIdx = i } return s } // CompactFunc is like Compact, but uses a comparison function. func CompactFunc[S constraints.Slice[T], T any](s S, cmp func(T, T) bool) S { if s == nil { return s } lastIdx := len(s) - 1 for i := len(s) - 2; i != 0; i-- { if cmp(s[i], s[lastIdx]) { continue } s = append(s[:i+1], s[lastIdx:]...) lastIdx = i } return s } // Grow grows the slice's capacity, if necessary, to guarantee space for // another n elements. After Grow(n), at least n elements can be appended // to the slice without another allocation. If n is negative or too large to // allocate the memory, Grow will panic. func Grow[S constraints.Slice[T], T any](s S, n int) S { ss := make([]T, len(s), len(s)+n) copy(ss, s[:]) return ss } // Clip removes unused capacity from the slice, returning s[:len(s):len(s)]. func Clip[S constraints.Slice[T], T any](s S) S { s = s[:len(s):len(s)] return s }
std/slices/slice.go
0.817283
0.697345
slice.go
starcoder
package lottie // GetDdd returns the Ddd field if it's non-nil, zero value otherwise. func (a *Animation) GetDdd() int { if a == nil || a.Ddd == nil { return 0 } return *a.Ddd } // GetFrameRate returns the FrameRate field if it's non-nil, zero value otherwise. func (a *Animation) GetFrameRate() float64 { if a == nil || a.FrameRate == nil { return 0.0 } return *a.FrameRate } // GetHeight returns the Height field if it's non-nil, zero value otherwise. func (a *Animation) GetHeight() float64 { if a == nil || a.Height == nil { return 0.0 } return *a.Height } // GetInPoint returns the InPoint field if it's non-nil, zero value otherwise. func (a *Animation) GetInPoint() float64 { if a == nil || a.InPoint == nil { return 0.0 } return *a.InPoint } // GetMarkers returns the Markers field if it's non-nil, zero value otherwise. func (a *Animation) GetMarkers() []int { if a == nil || a.Markers == nil { return nil } return *a.Markers } // GetName returns the Name field if it's non-nil, zero value otherwise. func (a *Animation) GetName() string { if a == nil || a.Name == nil { return "" } return *a.Name } // GetOutPoint returns the OutPoint field if it's non-nil, zero value otherwise. func (a *Animation) GetOutPoint() float64 { if a == nil || a.OutPoint == nil { return 0.0 } return *a.OutPoint } // GetVersion returns the Version field if it's non-nil, zero value otherwise. func (a *Animation) GetVersion() string { if a == nil || a.Version == nil { return "" } return *a.Version } // GetWidth returns the Width field if it's non-nil, zero value otherwise. func (a *Animation) GetWidth() float64 { if a == nil || a.Width == nil { return 0.0 } return *a.Width } // GetHeight returns the Height field if it's non-nil, zero value otherwise. func (a *Asset) GetHeight() float64 { if a == nil || a.Height == nil { return 0.0 } return *a.Height } // GetID returns the ID field if it's non-nil, zero value otherwise. func (a *Asset) GetID() string { if a == nil || a.ID == nil { return "" } return *a.ID } // GetP returns the P field if it's non-nil, zero value otherwise. func (a *Asset) GetP() string { if a == nil || a.P == nil { return "" } return *a.P } // GetURL returns the URL field if it's non-nil, zero value otherwise. func (a *Asset) GetURL() string { if a == nil || a.URL == nil { return "" } return *a.URL } // GetWidth returns the Width field if it's non-nil, zero value otherwise. func (a *Asset) GetWidth() float64 { if a == nil || a.Width == nil { return 0.0 } return *a.Width } // GetCl returns the Cl field if it's non-nil, zero value otherwise. func (m *Mask) GetCl() bool { if m == nil || m.Cl == nil { return false } return *m.Cl } // GetInv returns the Inv field if it's non-nil, zero value otherwise. func (m *Mask) GetInv() bool { if m == nil || m.Inv == nil { return false } return *m.Inv } // GetMode returns the Mode field if it's non-nil, zero value otherwise. func (m *Mask) GetMode() string { if m == nil || m.Mode == nil { return "" } return *m.Mode } // GetNm returns the Nm field if it's non-nil, zero value otherwise. func (m *Mask) GetNm() string { if m == nil || m.Nm == nil { return "" } return *m.Nm } // GetO returns the O field. func (m *Mask) GetO() *ValueOrKeyframed { if m == nil { return nil } return m.O } // GetPt returns the Pt field. func (m *Mask) GetPt() *ShapeOrKeyframed { if m == nil { return nil } return m.Pt } // GetX returns the X field. func (m *Mask) GetX() *ValueOrKeyframed { if m == nil { return nil } return m.X } // GetA returns the A field if it's non-nil, zero value otherwise. func (s *ShapeOrKeyframed) GetA() float64 { if s == nil || s.A == nil { return 0.0 } return *s.A } // GetIx returns the Ix field if it's non-nil, zero value otherwise. func (s *ShapeOrKeyframed) GetIx() int { if s == nil || s.Ix == nil { return 0 } return *s.Ix } // GetX returns the X field if it's non-nil, zero value otherwise. func (s *ShapeOrKeyframed) GetX() string { if s == nil || s.X == nil { return "" } return *s.X } // GetIx returns the Ix field if it's non-nil, zero value otherwise. func (v *Value) GetIx() string { if v == nil || v.Ix == nil { return "" } return *v.Ix } // GetK returns the K field if it's non-nil, zero value otherwise. func (v *Value) GetK() float64 { if v == nil || v.K == nil { return 0.0 } return *v.K } // GetX returns the X field if it's non-nil, zero value otherwise. func (v *Value) GetX() string { if v == nil || v.X == nil { return "" } return *v.X } // GetI returns the I field. func (v *ValueKeyframe) GetI() *I { if v == nil { return nil } return v.I } // GetIx returns the Ix field if it's non-nil, zero value otherwise. func (v *ValueKeyframed) GetIx() string { if v == nil || v.Ix == nil { return "" } return *v.Ix } // GetX returns the X field if it's non-nil, zero value otherwise. func (v *ValueKeyframed) GetX() string { if v == nil || v.X == nil { return "" } return *v.X } // GetA returns the A field if it's non-nil, zero value otherwise. func (v *ValueOrKeyframed) GetA() float64 { if v == nil || v.A == nil { return 0.0 } return *v.A } // GetIx returns the Ix field if it's non-nil, zero value otherwise. func (v *ValueOrKeyframed) GetIx() int { if v == nil || v.Ix == nil { return 0 } return *v.Ix } // GetX returns the X field if it's non-nil, zero value otherwise. func (v *ValueOrKeyframed) GetX() string { if v == nil || v.X == nil { return "" } return *v.X }
lottie/lottie-accessors.go
0.872198
0.615926
lottie-accessors.go
starcoder
package template // SegmentTree define type SegmentTree struct { data, tree, lazy []int left, right int merge func(i, j int) int } // Init define func (st *SegmentTree) Init(nums []int, oper func(i, j int) int) { st.merge = oper data, tree, lazy := make([]int, len(nums)), make([]int, 4*len(nums)), make([]int, 4*len(nums)) for i := 0; i < len(nums); i++ { data[i] = nums[i] } st.data, st.tree, st.lazy = data, tree, lazy if len(nums) > 0 { st.buildSegmentTree(0, 0, len(nums)-1) } } // 在 treeIndex 的位置创建 [left....right] 区间的线段树 func (st *SegmentTree) buildSegmentTree(treeIndex, left, right int) { if left == right { st.tree[treeIndex] = st.data[left] return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) st.buildSegmentTree(leftTreeIndex, left, midTreeIndex) st.buildSegmentTree(rightTreeIndex, midTreeIndex+1, right) st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } func (st *SegmentTree) leftChild(index int) int { return 2*index + 1 } func (st *SegmentTree) rightChild(index int) int { return 2*index + 2 } // 查询 [left....right] 区间内的值 // Query define func (st *SegmentTree) Query(left, right int) int { if len(st.data) > 0 { return st.queryInTree(0, 0, len(st.data)-1, left, right) } return 0 } // 在以 treeIndex 为根的线段树中 [left...right] 的范围里,搜索区间 [queryLeft...queryRight] 的值 func (st *SegmentTree) queryInTree(treeIndex, left, right, queryLeft, queryRight int) int { if left == queryLeft && right == queryRight { return st.tree[treeIndex] } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if queryLeft > midTreeIndex { return st.queryInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) } else if queryRight <= midTreeIndex { return st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) } return st.merge(st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex), st.queryInTree(rightTreeIndex, midTreeIndex+1, right, midTreeIndex+1, queryRight)) } // 查询 [left....right] 区间内的值 // QueryLazy define func (st *SegmentTree) QueryLazy(left, right int) int { if len(st.data) > 0 { return st.queryLazyInTree(0, 0, len(st.data)-1, left, right) } return 0 } func (st *SegmentTree) queryLazyInTree(treeIndex, left, right, queryLeft, queryRight int) int { midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if left > queryRight || right < queryLeft { // segment completely outside range return 0 // represents a null node } if st.lazy[treeIndex] != 0 { // this node is lazy for i := 0; i < right-left+1; i++ { st.tree[treeIndex] = st.merge(st.tree[treeIndex], st.lazy[treeIndex]) // st.tree[treeIndex] += (right - left + 1) * st.lazy[treeIndex] // normalize current node by removing lazinesss } if left != right { // update lazy[] for children nodes st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], st.lazy[treeIndex]) st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], st.lazy[treeIndex]) // st.lazy[leftTreeIndex] += st.lazy[treeIndex] // st.lazy[rightTreeIndex] += st.lazy[treeIndex] } st.lazy[treeIndex] = 0 // current node processed. No longer lazy } if queryLeft <= left && queryRight >= right { // segment completely inside range return st.tree[treeIndex] } if queryLeft > midTreeIndex { return st.queryLazyInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) } else if queryRight <= midTreeIndex { return st.queryLazyInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) } // merge query results return st.merge(st.queryLazyInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex), st.queryLazyInTree(rightTreeIndex, midTreeIndex+1, right, midTreeIndex+1, queryRight)) } // 更新 index 位置的值 // Update define func (st *SegmentTree) Update(index, val int) { if len(st.data) > 0 { st.updateInTree(0, 0, len(st.data)-1, index, val) } } // 以 treeIndex 为根,更新 index 位置上的值为 val func (st *SegmentTree) updateInTree(treeIndex, left, right, index, val int) { if left == right { st.tree[treeIndex] = val return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if index > midTreeIndex { st.updateInTree(rightTreeIndex, midTreeIndex+1, right, index, val) } else { st.updateInTree(leftTreeIndex, left, midTreeIndex, index, val) } st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } // 更新 [updateLeft....updateRight] 位置的值 // 注意这里的更新值是在原来值的基础上增加或者减少,而不是把这个区间内的值都赋值为 x,区间更新和单点更新不同 // 这里的区间更新关注的是变化,单点更新关注的是定值 // 当然区间更新也可以都更新成定值,如果只区间更新成定值,那么 lazy 更新策略需要变化,merge 策略也需要变化,这里暂不详细讨论 // UpdateLazy define func (st *SegmentTree) UpdateLazy(updateLeft, updateRight, val int) { if len(st.data) > 0 { st.updateLazyInTree(0, 0, len(st.data)-1, updateLeft, updateRight, val) } } func (st *SegmentTree) updateLazyInTree(treeIndex, left, right, updateLeft, updateRight, val int) { midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if st.lazy[treeIndex] != 0 { // this node is lazy for i := 0; i < right-left+1; i++ { st.tree[treeIndex] = st.merge(st.tree[treeIndex], st.lazy[treeIndex]) //st.tree[treeIndex] += (right - left + 1) * st.lazy[treeIndex] // normalize current node by removing laziness } if left != right { // update lazy[] for children nodes st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], st.lazy[treeIndex]) st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], st.lazy[treeIndex]) // st.lazy[leftTreeIndex] += st.lazy[treeIndex] // st.lazy[rightTreeIndex] += st.lazy[treeIndex] } st.lazy[treeIndex] = 0 // current node processed. No longer lazy } if left > right || left > updateRight || right < updateLeft { return // out of range. escape. } if updateLeft <= left && right <= updateRight { // segment is fully within update range for i := 0; i < right-left+1; i++ { st.tree[treeIndex] = st.merge(st.tree[treeIndex], val) //st.tree[treeIndex] += (right - left + 1) * val // update segment } if left != right { // update lazy[] for children st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], val) st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], val) // st.lazy[leftTreeIndex] += val // st.lazy[rightTreeIndex] += val } return } st.updateLazyInTree(leftTreeIndex, left, midTreeIndex, updateLeft, updateRight, val) st.updateLazyInTree(rightTreeIndex, midTreeIndex+1, right, updateLeft, updateRight, val) // merge updates st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } // SegmentCountTree define type SegmentCountTree struct { data, tree []int left, right int merge func(i, j int) int } // Init define func (st *SegmentCountTree) Init(nums []int, oper func(i, j int) int) { st.merge = oper data, tree := make([]int, len(nums)), make([]int, 4*len(nums)) for i := 0; i < len(nums); i++ { data[i] = nums[i] } st.data, st.tree = data, tree } // 在 treeIndex 的位置创建 [left....right] 区间的线段树 func (st *SegmentCountTree) buildSegmentTree(treeIndex, left, right int) { if left == right { st.tree[treeIndex] = st.data[left] return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) st.buildSegmentTree(leftTreeIndex, left, midTreeIndex) st.buildSegmentTree(rightTreeIndex, midTreeIndex+1, right) st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } func (st *SegmentCountTree) leftChild(index int) int { return 2*index + 1 } func (st *SegmentCountTree) rightChild(index int) int { return 2*index + 2 } // 查询 [left....right] 区间内的值 // Query define func (st *SegmentCountTree) Query(left, right int) int { if len(st.data) > 0 { return st.queryInTree(0, 0, len(st.data)-1, left, right) } return 0 } // 在以 treeIndex 为根的线段树中 [left...right] 的范围里,搜索区间 [queryLeft...queryRight] 的值,值是计数值 func (st *SegmentCountTree) queryInTree(treeIndex, left, right, queryLeft, queryRight int) int { if queryRight < st.data[left] || queryLeft > st.data[right] { return 0 } if queryLeft <= st.data[left] && queryRight >= st.data[right] || left == right { return st.tree[treeIndex] } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) return st.queryInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) + st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) } // 更新计数 // UpdateCount define func (st *SegmentCountTree) UpdateCount(val int) { if len(st.data) > 0 { st.updateCountInTree(0, 0, len(st.data)-1, val) } } // 以 treeIndex 为根,更新 [left...right] 区间内的计数 func (st *SegmentCountTree) updateCountInTree(treeIndex, left, right, val int) { if val >= st.data[left] && val <= st.data[right] { st.tree[treeIndex]++ if left == right { return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) st.updateCountInTree(rightTreeIndex, midTreeIndex+1, right, val) st.updateCountInTree(leftTreeIndex, left, midTreeIndex, val) } }
template/SegmentTree.go
0.512449
0.533154
SegmentTree.go
starcoder
package defs import ( "bytes" ) // Type definitions const ( baseURI = "https://www.w3.org/ns/activitystreams#" PublicActivityPub = "https://www.w3.org/ns/activitystreams#Public" ) var ( objectType = &Type{ Name: "Object", URI: baseURI + "Object", Notes: "Describes an object of any kind. The Object type serves as the base type for most of the other kinds of objects defined in the Activity Vocabulary, including other Core types such as Activity, IntransitiveActivity, Collection and OrderedCollection.", // Done within init: DisjointWith = []*Type{linkType} Meta: TypeMetadata{ HasIsPublicMethod: true, }, } linkType = &Type{ Name: "Link", URI: baseURI + "Link", Notes: "A Link is an indirect, qualified reference to a resource identified by a URL. The fundamental model for links is established by [ RFC5988]. Many of the properties defined by the Activity Vocabulary allow values that are either instances of Object or Link. When a Link is used, it establishes a qualified relation connecting the subject (the containing object) to the resource identified by the href. Properties of the Link are properties of the reference as opposed to properties of the resource.", DisjointWith: []*Type{objectType}, } activityType = &Type{ Name: "Activity", URI: baseURI + "Activity", Notes: "An Activity is a subtype of Object that describes some form of action that may happen, is currently happening, or has already happened. The Activity type itself serves as an abstract base type for all types of activities. It is important to note that the Activity type itself does not carry any specific semantics about the kind of action being taken.", Extends: []*Type{objectType}, } intransitiveActivityType = &Type{ Name: "IntransitiveActivity", URI: baseURI + "IntransitiveActivity", Notes: "Instances of IntransitiveActivity are a subtype of Activity representing intransitive actions. The object property is therefore inappropriate for these activities.", Extends: []*Type{activityType}, WithoutProperties: []*PropertyType{objectPropertyType}, } collectionType = &Type{ Name: "Collection", URI: baseURI + "Collection", Notes: "A Collection is a subtype of Object that represents ordered or unordered sets of Object or Link instances. Refer to the Activity Streams 2.0 Core specification for a complete description of the Collection type.", Extends: []*Type{objectType}, } orderedCollectionType = &Type{ Name: "OrderedCollection", URI: baseURI + "OrderedCollection", Notes: "A subtype of Collection in which members of the logical collection are assumed to always be strictly ordered.", Extends: []*Type{collectionType}, WithoutProperties: []*PropertyType{ itemsPropertyType, currentPropertyType, firstPropertyType, lastPropertyType, }, } collectionPageType = &Type{ Name: "CollectionPage", URI: baseURI + "CollectionPage", Notes: "Used to represent distinct subsets of items from a Collection. Refer to the Activity Streams 2.0 Core for a complete description of the CollectionPage object.", Extends: []*Type{collectionType}, } orderedCollectionPageType = &Type{ Name: "OrderedCollectionPage", URI: baseURI + "OrderedCollectionPage", Notes: "Used to represent ordered subsets of items from an OrderedCollection. Refer to the Activity Streams 2.0 Core for a complete description of the OrderedCollectionPage object.", Extends: []*Type{orderedCollectionType, collectionPageType}, WithoutProperties: []*PropertyType{ itemsPropertyType, currentPropertyType, firstPropertyType, lastPropertyType, nextPropertyType, prevPropertyType, }, } AllCoreTypes = []*Type{ objectType, linkType, activityType, intransitiveActivityType, collectionType, orderedCollectionType, collectionPageType, orderedCollectionPageType, } ) // Extended Type definitions const ( extendedBaseURI = "https://www.w3.org/ns/activitystreams#" ) var ( // Activity extensions acceptExtendedType = &Type{ Name: "Accept", URI: extendedBaseURI + "Accept", Notes: "Indicates that the actor accepts the object. The target property can be used in certain circumstances to indicate the context into which the object has been accepted.", Extends: []*Type{activityType}, } tentativeAcceptExtendedType = &Type{ Name: "TentativeAccept", URI: extendedBaseURI + "TentativeAccept", Notes: "A specialization of Accept indicating that the acceptance is tentative.", Extends: []*Type{acceptExtendedType}, } addExtendedType = &Type{ Name: "Add", URI: extendedBaseURI + "Add", Notes: "Indicates that the actor has added the object to the target. If the target property is not explicitly specified, the target would need to be determined implicitly by context. The origin can be used to identify the context from which the object originated.", Extends: []*Type{activityType}, } arriveExtendedType = &Type{ Name: "Arrive", URI: extendedBaseURI + "Arrive", Notes: "An IntransitiveActivity that indicates that the actor has arrived at the location. The origin can be used to identify the context from which the actor originated. The target typically has no defined meaning.", Extends: []*Type{intransitiveActivityType}, } createExtendedType = &Type{ Name: "Create", URI: extendedBaseURI + "Create", Notes: "Indicates that the actor has created the object.", Extends: []*Type{activityType}, } deleteExtendedType = &Type{ Name: "Delete", URI: extendedBaseURI + "Delete", Notes: "Indicates that the actor has deleted the object. If specified, the origin indicates the context from which the object was deleted.", Extends: []*Type{activityType}, } followExtendedType = &Type{ Name: "Follow", URI: extendedBaseURI + "Follow", Notes: "Indicates that the actor is \"following\" the object. Following is defined in the sense typically used within Social systems in which the actor is interested in any activity performed by or on the object. The target and origin typically have no defined meaning.", Extends: []*Type{activityType}, } ignoreExtendedType = &Type{ Name: "Ignore", URI: extendedBaseURI + "Ignore", Notes: "Indicates that the actor is ignoring the object. The target and origin typically have no defined meaning.", Extends: []*Type{activityType}, } joinExtendedType = &Type{ Name: "Join", URI: extendedBaseURI + "Join", Notes: "Indicates that the actor has joined the object. The target and origin typically have no defined meaning.", Extends: []*Type{activityType}, } leaveExtendedType = &Type{ Name: "Leave", URI: extendedBaseURI + "Leave", Notes: "Indicates that the actor has left the object. The target and origin typically have no meaning.", Extends: []*Type{activityType}, } likeExtendedType = &Type{ Name: "Like", URI: extendedBaseURI + "Like", Notes: "Indicates that the actor likes, recommends or endorses the object. The target and origin typically have no defined meaning.", Extends: []*Type{activityType}, } offerExtendedType = &Type{ Name: "Offer", URI: extendedBaseURI + "Offer", Notes: "Indicates that the actor is offering the object. If specified, the target indicates the entity to which the object is being offered.", Extends: []*Type{activityType}, } inviteExtendedType = &Type{ Name: "Invite", URI: extendedBaseURI + "Invite", Notes: "A specialization of Offer in which the actor is extending an invitation for the object to the target.", Extends: []*Type{offerExtendedType}, } rejectExtendedType = &Type{ Name: "Reject", URI: extendedBaseURI + "Reject", Notes: "Indicates that the actor is rejecting the object. The target and origin typically have no defined meaning.", Extends: []*Type{activityType}, } tentativeRejectExtendedType = &Type{ Name: "TentativeReject", URI: extendedBaseURI + "TentativeReject", Notes: "A specialization of Reject in which the rejection is considered tentative.", Extends: []*Type{rejectExtendedType}, } removeExtendedType = &Type{ Name: "Remove", URI: extendedBaseURI + "Remove", Notes: "Indicates that the actor is removing the object. If specified, the origin indicates the context from which the object is being removed.", Extends: []*Type{activityType}, } undoExtendedType = &Type{ Name: "Undo", URI: extendedBaseURI + "Undo", Notes: "Indicates that the actor is undoing the object. In most cases, the object will be an Activity describing some previously performed action (for instance, a person may have previously \"liked\" an article but, for whatever reason, might choose to undo that like at some later point in time). The target and origin typically have no defined meaning.", Extends: []*Type{activityType}, } updateExtendedType = &Type{ Name: "Update", URI: extendedBaseURI + "Update", Notes: "Indicates that the actor has updated the object. Note, however, that this vocabulary does not define a mechanism for describing the actual set of modifications made to object. The target and origin typically have no defined meaning.", Extends: []*Type{activityType}, } viewExtendedType = &Type{ Name: "View", URI: extendedBaseURI + "View", Notes: "Indicates that the actor has viewed the object.", Extends: []*Type{activityType}, } listenExtendedType = &Type{ Name: "Listen", URI: extendedBaseURI + "Listen", Notes: "Indicates that the actor has listened to the object.", Extends: []*Type{activityType}, } readExtendedType = &Type{ Name: "Read", URI: extendedBaseURI + "Read", Notes: "Indicates that the actor has read the object.", Extends: []*Type{activityType}, } moveExtendedType = &Type{ Name: "Move", URI: extendedBaseURI + "Move", Notes: "Indicates that the actor has moved object from origin to target. If the origin or target are not specified, either can be determined by context.", Extends: []*Type{activityType}, } travelExtendedType = &Type{ Name: "Travel", URI: extendedBaseURI + "Travel", Notes: "Indicates that the actor is traveling to target from origin. Travel is an IntransitiveObject whose actor specifies the direct object. If the target or origin are not specified, either can be determined by context.", Extends: []*Type{intransitiveActivityType}, } announceExtendedType = &Type{ Name: "Announce", URI: extendedBaseURI + "Announce", Notes: "Indicates that the actor is calling the target's attention the object. The origin typically has no defined meaning.", Extends: []*Type{activityType}, } blockExtendedType = &Type{ Name: "Block", URI: extendedBaseURI + "Block", Notes: "Indicates that the actor is blocking the object. Blocking is a stronger form of Ignore. The typical use is to support social systems that allow one user to block activities or content of other users. The target and origin typically have no defined meaning.", Extends: []*Type{ignoreExtendedType}, } flagExtendedType = &Type{ Name: "Flag", URI: extendedBaseURI + "Flag", Notes: "Indicates that the actor is \"flagging\" the object. Flagging is defined in the sense common to many social platforms as reporting content as being inappropriate for any number of reasons.", Extends: []*Type{activityType}, } dislikeExtendedType = &Type{ Name: "Dislike", URI: extendedBaseURI + "Dislike", Notes: "Indicates that the actor dislikes the object.", Extends: []*Type{activityType}, } questionExtendedType = &Type{ Name: "Question", URI: extendedBaseURI + "Question", Notes: "Represents a question being asked. Question objects are an extension of IntransitiveActivity. That is, the Question object is an Activity, but the direct object is the question itself and therefore it would not contain an object property. Either of the anyOf and oneOf properties may be used to express possible answers, but a Question object must not have both properties.", Extends: []*Type{intransitiveActivityType}, } // Actor extensions applicationExtendedType = &Type{ Name: "Application", URI: extendedBaseURI + "Application", Notes: "Describes a software application.", Extends: []*Type{objectType}, } groupExtendedType = &Type{ Name: "Group", URI: extendedBaseURI + "Group", Notes: "Represents a formal or informal collective of Actors.", Extends: []*Type{objectType}, } organizationExtendedType = &Type{ Name: "Organization", URI: extendedBaseURI + "Organization", Notes: "Represents an organization.", Extends: []*Type{objectType}, } personExtendedType = &Type{ Name: "Person", URI: extendedBaseURI + "Person", Notes: "Represents an individual person.", Extends: []*Type{objectType}, } serviceExtendedType = &Type{ Name: "Service", URI: extendedBaseURI + "Service", Notes: "Represents a service of any kind.", Extends: []*Type{objectType}, } // Object extensions relationshipExtendedType = &Type{ Name: "Relationship", URI: extendedBaseURI + "Relationship", Notes: "Describes a relationship between two individuals. The subject and object properties are used to identify the connected individuals. See 5.2 Representing Relationships Between Entities for additional information.", Extends: []*Type{objectType}, } articleExtendedType = &Type{ Name: "Article", URI: extendedBaseURI + "Article", Notes: "Represents any kind of multi-paragraph written work.", Extends: []*Type{objectType}, } documentExtendedType = &Type{ Name: "Document", URI: extendedBaseURI + "Document", Notes: "Represents a document of any kind.", Extends: []*Type{objectType}, } audioExtendedType = &Type{ Name: "Audio", URI: extendedBaseURI + "Audio", Notes: "Represents an audio document of any kind.", Extends: []*Type{documentExtendedType}, } imageExtendedType = &Type{ Name: "Image", URI: extendedBaseURI + "Image", Notes: "An image document of any kind", Extends: []*Type{documentExtendedType}, } videoExtendedType = &Type{ Name: "Video", URI: extendedBaseURI + "Video", Notes: "Represents a video document of any kind.", Extends: []*Type{documentExtendedType}, } noteExtendedType = &Type{ Name: "Note", URI: extendedBaseURI + "Note", Notes: "Represents a short written work typically less than a single paragraph in length.", Extends: []*Type{objectType}, } pageExtendedType = &Type{ Name: "Page", URI: extendedBaseURI + "Page", Notes: "Represents a Web Page.", Extends: []*Type{documentExtendedType}, } eventExtendedType = &Type{ Name: "Event", URI: extendedBaseURI + "Event", Notes: "Represents any kind of event.", Extends: []*Type{objectType}, } placeExtendedType = &Type{ Name: "Place", URI: extendedBaseURI + "Place", Notes: "Represents a logical or physical location. See 5.3 Representing Places for additional information.", Extends: []*Type{objectType}, } profileExtendedType = &Type{ Name: "Profile", URI: extendedBaseURI + "Profile", Notes: "A Profile is a content object that describes another Object, typically used to describe Actor Type objects. The describes property is used to reference the object being described by the profile.", Extends: []*Type{objectType}, } tombstoneExtendedType = &Type{ Name: "Tombstone", URI: extendedBaseURI + "Tombstone", Notes: "A Tombstone represents a content object that has been deleted. It can be used in Collections to signify that there used to be an object at this position, but it has been deleted.", Extends: []*Type{objectType}, } // Link extensions mentionExtendedType = &Type{ Name: "Mention", URI: extendedBaseURI + "Mention", Notes: "A specialized Link that represents an @mention.", Extends: []*Type{linkType}, } AllExtendedTypes = []*Type{ acceptExtendedType, tentativeAcceptExtendedType, addExtendedType, arriveExtendedType, createExtendedType, deleteExtendedType, followExtendedType, ignoreExtendedType, joinExtendedType, leaveExtendedType, likeExtendedType, offerExtendedType, inviteExtendedType, rejectExtendedType, tentativeRejectExtendedType, removeExtendedType, undoExtendedType, updateExtendedType, viewExtendedType, listenExtendedType, readExtendedType, moveExtendedType, travelExtendedType, announceExtendedType, blockExtendedType, flagExtendedType, dislikeExtendedType, questionExtendedType, applicationExtendedType, groupExtendedType, organizationExtendedType, personExtendedType, serviceExtendedType, relationshipExtendedType, articleExtendedType, documentExtendedType, audioExtendedType, imageExtendedType, videoExtendedType, noteExtendedType, pageExtendedType, eventExtendedType, placeExtendedType, profileExtendedType, tombstoneExtendedType, mentionExtendedType, } ) // PropertyType definitions const ( propertyBaseURI = "https://www.w3.org/ns/activitystreams#" ) var ( idPropertyType = &PropertyType{ Name: "id", URI: "@id", Notes: "Provides the globally unique identifier for an Object or Link.", Domain: []DomainReference{{T: objectType}, {T: linkType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, } typePropertyType = &PropertyType{ Name: "type", URI: "@type", Notes: "Identifies the Object or Link type. Multiple values may be specified. Note that when serializing, the appropriate Activitystream type is added if it is not already added by the caller.", Domain: []DomainReference{{T: objectType}, {T: linkType}}, Range: []RangeReference{{Any: true}}, } actorPropertyType = &PropertyType{ Name: "actor", URI: propertyBaseURI + "actor", Notes: "Describes one or more entities that either performed or are expected to perform the activity. Any single activity can have multiple actors. The actor may be specified using an indirect Link.", Domain: []DomainReference{{T: activityType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, SubpropertyOf: attributedToPropertyType, PreferIRIConvenience: true, } attachmentPropertyType = &PropertyType{ Name: "attachment", URI: propertyBaseURI + "attachment", Notes: "Identifies a resource attached or related to an object that potentially requires special handling. The intent is to provide a model that is at least semantically similar to attachments in email.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } attributedToPropertyType = &PropertyType{ Name: "attributedTo", URI: propertyBaseURI + "attributedTo", Notes: "Identifies one or more entities to which this object is attributed. The attributed entities might not be Actors. For instance, an object might be attributed to the completion of another activity.", Domain: []DomainReference{{T: objectType}, {T: linkType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } audiencePropertyType = &PropertyType{ Name: "audience", URI: propertyBaseURI + "audience", Notes: "Identifies one or more entities that represent the total population of entities for which the object can considered to be relevant.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } bccPropertyType = &PropertyType{ Name: "bcc", URI: propertyBaseURI + "bcc", Notes: "Identifies one or more Objects that are part of the private secondary audience of this Object.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } btoPropertyType = &PropertyType{ Name: "bto", URI: propertyBaseURI + "bto", Notes: "Identifies an Object that is part of the private primary audience of this Object.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } ccPropertyType = &PropertyType{ Name: "cc", URI: propertyBaseURI + "cc", Notes: "Identifies an Object that is part of the public secondary audience of this Object.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } contextPropertyType = &PropertyType{ Name: "context", URI: propertyBaseURI + "context", Notes: "Identifies the context within which the object exists or an activity was performed. The notion of \"context\" used is intentionally vague. The intended function is to serve as a means of grouping objects and activities that share a common originating context or purpose. An example could be all activities relating to a common project or event.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } currentPropertyType = &PropertyType{ Name: "current", URI: propertyBaseURI + "current", Notes: "In a paged Collection, indicates the page that contains the most recently updated member items.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{T: collectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } currentOrderedPropertyType = &PropertyType{ Name: "current", URI: propertyBaseURI + "current", Notes: "In a paged OrderedCollection, indicates the page that contains the most recently updated member items.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{T: orderedCollectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } firstPropertyType = &PropertyType{ Name: "first", URI: propertyBaseURI + "first", Notes: "In a paged Collection, indicates the furthest preceeding page of items in the collection.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{T: collectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } firstOrderedPropertyType = &PropertyType{ Name: "first", URI: propertyBaseURI + "first", Notes: "In a paged OrderedCollection, indicates the furthest preceeding page of items in the collection.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{T: orderedCollectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } generatorPropertyType = &PropertyType{ Name: "generator", URI: propertyBaseURI + "generator", Notes: "Identifies the entity (e.g. an application) that generated the object.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } iconPropertyType = &PropertyType{ Name: "icon", URI: propertyBaseURI + "icon", Notes: "Indicates an entity that describes an icon for this object. The image should have an aspect ratio of one (horizontal) to one (vertical) and should be suitable for presentation at a small size.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: imageExtendedType}, {T: linkType}}, } imagePropertyType = &PropertyType{ Name: "image", URI: propertyBaseURI + "image", Notes: "Indicates an entity that describes an image for this object. Unlike the icon property, there are no aspect ratio or display size limitations assumed.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: imageExtendedType}, {T: linkType}}, } inReplyToPropertyType = &PropertyType{ Name: "inReplyTo", URI: propertyBaseURI + "inReplyTo", Notes: "Indicates one or more entities for which this object is considered a response.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } instrumentPropertyType = &PropertyType{ Name: "instrument", URI: propertyBaseURI + "instrument", Notes: "Identifies one or more objects used (or to be used) in the completion of an Activity.", Domain: []DomainReference{{T: activityType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } lastPropertyType = &PropertyType{ Name: "last", URI: propertyBaseURI + "last", Notes: "In a paged Collection, indicates the furthest proceeding page of the collection.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{T: collectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } lastOrderedPropertyType = &PropertyType{ Name: "last", URI: propertyBaseURI + "last", Notes: "In a paged OrderedCollection, indicates the furthest proceeding page of the collection.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{T: orderedCollectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } locationPropertyType = &PropertyType{ Name: "location", URI: propertyBaseURI + "location", Notes: "Indicates one or more physical or logical locations associated with the object.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } itemsPropertyType = &PropertyType{ Name: "items", URI: propertyBaseURI + "items", Notes: "Identifies the items contained in a collection. The items might be ordered or unordered.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } orderedItemsPropertyType = &PropertyType{ // Implicit within spec! Name: "orderedItems", URI: propertyBaseURI + "items", Notes: "Identifies the items contained in a collection. The items might be ordered or unordered.", Domain: []DomainReference{{T: orderedCollectionType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } oneOfPropertyType = &PropertyType{ Name: "oneOf", URI: propertyBaseURI + "oneOf", Notes: "Identifies an exclusive option for a Question. Use of oneOf implies that the Question can have only a single answer. To indicate that a Question can have multiple answers, use anyOf.", Domain: []DomainReference{{T: questionExtendedType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } anyOfPropertyType = &PropertyType{ Name: "anyOf", URI: propertyBaseURI + "anyOf", Notes: "Identifies an inclusive option for a Question. Use of anyOf implies that the Question can have multiple answers. To indicate that a Question can have only one answer, use oneOf.", Domain: []DomainReference{{T: questionExtendedType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } closedPropertyType = &PropertyType{ Name: "closed", URI: propertyBaseURI + "closed", Notes: "Indicates that a question has been closed, and answers are no longer accepted.", Domain: []DomainReference{{T: questionExtendedType}}, Range: []RangeReference{{V: xsdDateTimeValueType}, {V: xsdBooleanValueType}, {T: objectType}, {T: linkType}}, } originPropertyType = &PropertyType{ Name: "origin", URI: propertyBaseURI + "origin", Notes: "Describes an indirect object of the activity from which the activity is directed. The precise meaning of the origin is the object of the English preposition \"from\". For instance, in the activity \"John moved an item to List B from List A\", the origin of the activity is \"List A\".", Domain: []DomainReference{{T: activityType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } nextPropertyType = &PropertyType{ Name: "next", URI: propertyBaseURI + "next", Notes: "In a paged Collection, indicates the next page of items.", Domain: []DomainReference{{T: collectionPageType}}, Range: []RangeReference{{T: collectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } nextOrderedPropertyType = &PropertyType{ Name: "next", URI: propertyBaseURI + "next", Notes: "In a paged OrderedCollection, indicates the next page of items.", Domain: []DomainReference{{T: orderedCollectionPageType}}, Range: []RangeReference{{T: orderedCollectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } objectPropertyType = &PropertyType{ Name: "object", URI: propertyBaseURI + "object", Notes: "When used within an Activity, describes the direct object of the activity. For instance, in the activity \"John added a movie to his wishlist\", the object of the activity is the movie added. When used within a Relationship describes the entity to which the subject is related.", Domain: []DomainReference{{T: activityType}, {T: relationshipExtendedType}}, Range: []RangeReference{{T: objectType}}, } prevPropertyType = &PropertyType{ Name: "prev", URI: propertyBaseURI + "prev", Notes: "In a paged Collection, identifies the previous page of items.", Domain: []DomainReference{{T: collectionPageType}}, Range: []RangeReference{{T: collectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } prevOrderedPropertyType = &PropertyType{ Name: "prev", URI: propertyBaseURI + "prev", Notes: "In a paged OrderedCollection, identifies the previous page of items.", Domain: []DomainReference{{T: orderedCollectionPageType}}, Range: []RangeReference{{T: orderedCollectionPageType}, {T: linkType}}, Functional: true, PreferIRIConvenience: true, } previewPropertyType = &PropertyType{ Name: "preview", URI: propertyBaseURI + "preview", Notes: "Identifies an entity that provides a preview of this object.", Domain: []DomainReference{{T: objectType}, {T: linkType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } resultPropertyType = &PropertyType{ Name: "result", URI: propertyBaseURI + "result", Notes: "Describes the result of the activity. For instance, if a particular action results in the creation of a new resource, the result property can be used to describe that new resource.", Domain: []DomainReference{{T: activityType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } repliesPropertyType = &PropertyType{ Name: "replies", URI: propertyBaseURI + "replies", Notes: "Identifies a Collection containing objects considered to be responses to this object.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: collectionType}}, Functional: true, } tagPropertyType = &PropertyType{ Name: "tag", URI: propertyBaseURI + "tag", Notes: "One or more \"tags\" that have been associated with an objects. A tag can be any kind of Object. The key difference between attachment and tag is that the former implies association by inclusion, while the latter implies associated by reference.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, } targetPropertyType = &PropertyType{ Name: "target", URI: propertyBaseURI + "target", Notes: "Describes the indirect object, or target, of the activity. The precise meaning of the target is largely dependent on the type of action being described but will often be the object of the English preposition \"to\". For instance, in the activity \"John added a movie to his wishlist\", the target of the activity is John's wishlist. An activity can have more than one target.", Domain: []DomainReference{{T: activityType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } toPropertyType = &PropertyType{ Name: "to", URI: propertyBaseURI + "to", Notes: "Identifies an entity considered to be part of the public primary audience of an Object", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, PreferIRIConvenience: true, } urlPropertyType = &PropertyType{ Name: "url", URI: propertyBaseURI + "url", Notes: "Identifies one or more links to representations of the object", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}, {T: linkType}}, } accuracyPropertyType = &PropertyType{ Name: "accuracy", URI: propertyBaseURI + "accuracy", Notes: "Indicates the accuracy of position coordinates on a Place objects. Expressed in properties of percentage. e.g. \"94.0\" means \"94.0%% accurate\".", Domain: []DomainReference{{T: placeExtendedType}}, Range: []RangeReference{{V: xsdFloatValueType}}, Functional: true, } altitudePropertyType = &PropertyType{ Name: "altitude", URI: propertyBaseURI + "altitude", Notes: "ndicates the altitude of a place. The measurement units is indicated using the units property. If units is not specified, the default is assumed to be \"m\" indicating meters.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdFloatValueType}}, Functional: true, } contentPropertyType = &PropertyType{ Name: "content", URI: propertyBaseURI + "content", Notes: "The content or textual representation of the Object encoded as a JSON string. By default, the value of content is HTML. The mediaType property can be used in the object to indicate a different content type. The content may be expressed using multiple language-tagged values.", NaturalLanguageMap: true, Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdStringValueType}, {V: rdfLangStringValueType}}, } namePropertyType = &PropertyType{ Name: "name", URI: propertyBaseURI + "name", Notes: "A simple, human-readable, plain-text name for the object. HTML markup must not be included. The name may be expressed using multiple language-tagged values.", NaturalLanguageMap: true, Domain: []DomainReference{{T: objectType}, {T: linkType}}, Range: []RangeReference{{V: xsdStringValueType}, {V: rdfLangStringValueType}}, } durationPropertyType = &PropertyType{ Name: "duration", URI: propertyBaseURI + "duration", Notes: "When the object describes a time-bound resource, such as an audio or video, a meeting, etc, the duration property indicates the object's approximate duration. The value must be expressed as an xsd:duration as defined by [ xmlschema11-2], section 3.3.6 (e.g. a period of 5 seconds is represented as \"PT5S\").", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdDurationValueType}}, Functional: true, } heightPropertyType = &PropertyType{ Name: "height", URI: propertyBaseURI + "height", Notes: "On a Link, specifies a hint as to the rendering height in device-independent pixels of the linked resource.", Domain: []DomainReference{{T: linkType}, {T: imageExtendedType}}, Range: []RangeReference{{V: xsdNonNegativeIntegerValueType}}, Functional: true, } hrefPropertyType = &PropertyType{ Name: "href", URI: propertyBaseURI + "href", Notes: "The target resource pointed to by a Link.", Domain: []DomainReference{{T: linkType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, } hrefLangPropertyType = &PropertyType{ Name: "hreflang", URI: propertyBaseURI + "hreflang", Notes: "Hints as to the language used by the target resource. Value must be a [BCP47] Language-Tag.", Domain: []DomainReference{{T: linkType}}, Range: []RangeReference{{V: bcp47LangTag}}, Functional: true, } partOfPropertyType = &PropertyType{ Name: "partOf", URI: propertyBaseURI + "partOf", Notes: "Identifies the Collection to which a CollectionPage objects items belong.", Domain: []DomainReference{{T: collectionPageType}}, Range: []RangeReference{{T: linkType}, {T: collectionType}}, Functional: true, } latitudePropertyType = &PropertyType{ Name: "latitude", URI: propertyBaseURI + "latitude", Notes: "The latitude of a place", Domain: []DomainReference{{T: placeExtendedType}}, Range: []RangeReference{{V: xsdFloatValueType}}, Functional: true, } longitudePropertyType = &PropertyType{ Name: "longitude", URI: propertyBaseURI + "longitude", Notes: "The longitude of a place", Domain: []DomainReference{{T: placeExtendedType}}, Range: []RangeReference{{V: xsdFloatValueType}}, Functional: true, } mediaTypePropertyType = &PropertyType{ Name: "mediaType", URI: propertyBaseURI + "mediaType", Notes: "When used on a Link, identifies the MIME media type of the referenced resource. When used on an Object, identifies the MIME media type of the value of the content property. If not specified, the content property is assumed to contain text/html content.", Domain: []DomainReference{{T: linkType}, {T: objectType}}, Range: []RangeReference{{V: mimeMediaValueType}}, Functional: true, } endTimePropertyType = &PropertyType{ Name: "endTime", URI: propertyBaseURI + "endTime", Notes: "The date and time describing the actual or expected ending time of the object. When used with an Activity object, for instance, the endTime property specifies the moment the activity concluded or is expected to conclude.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdDateTimeValueType}}, Functional: true, } publishedPropertyType = &PropertyType{ Name: "published", URI: propertyBaseURI + "published", Notes: "The date and time at which the object was published", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdDateTimeValueType}}, Functional: true, } startTimePropertyType = &PropertyType{ Name: "startTime", URI: propertyBaseURI + "startTime", Notes: "The date and time describing the actual or expected starting time of the object. When used with an Activity object, for instance, the startTime property specifies the moment the activity began or is scheduled to begin.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdDateTimeValueType}}, Functional: true, } radiusPropertyType = &PropertyType{ Name: "radius", URI: propertyBaseURI + "property", Notes: "The radius from the given latitude and longitude for a Place. The units is expressed by the units property. If units is not specified, the default is assumed to be \"m\" indicating \"meters\".", Domain: []DomainReference{{T: placeExtendedType}}, Range: []RangeReference{{V: xsdFloatValueType}}, Functional: true, } relPropertyType = &PropertyType{ Name: "rel", URI: propertyBaseURI + "rel", Notes: "A link relation associated with a Link. The value must conform to both the [HTML5] and [RFC5988] \"link relation\" definitions. In the [HTML5], any string not containing the \"space\" U+0020, \"tab\" (U+0009), \"LF\" (U+000A), \"FF\" (U+000C), \"CR\" (U+000D) or \",\" (U+002C) characters can be used as a valid link relation.", Domain: []DomainReference{{T: linkType}}, Range: []RangeReference{{V: linkRelationValueType}}, } startIndexPropertyType = &PropertyType{ Name: "startIndex", URI: propertyBaseURI + "startIndex", Notes: "A non-negative integer value identifying the relative position within the logical view of a strictly ordered collection.", Domain: []DomainReference{{T: orderedCollectionPageType}}, Range: []RangeReference{{V: xsdNonNegativeIntegerValueType}}, Functional: true, } summaryPropertyType = &PropertyType{ Name: "summary", URI: propertyBaseURI + "summary", Notes: "A natural language summarization of the object encoded as HTML. Multiple language tagged summaries may be provided.", NaturalLanguageMap: true, Domain: []DomainReference{{T: objectType}, {T: linkType}}, // Link conflicts with spec! Range: []RangeReference{{V: xsdStringValueType}, {V: rdfLangStringValueType}}, } totalItemsPropertyType = &PropertyType{ Name: "totalItems", URI: propertyBaseURI + "totalItems", Notes: "A non-negative integer specifying the total number of objects contained by the logical view of the collection. This number might not reflect the actual number of items serialized within the Collection object instance.", Domain: []DomainReference{{T: collectionType}}, Range: []RangeReference{{V: xsdNonNegativeIntegerValueType}}, Functional: true, } unitsPropertyType = &PropertyType{ Name: "units", URI: propertyBaseURI + "units", Notes: "Specifies the measurement units for the radius and altitude properties on a Place object. If not specified, the default is assumed to be \"m\" for \"meters\".", Domain: []DomainReference{{T: placeExtendedType}}, Range: []RangeReference{{V: unitsValueType}, {V: xsdAnyURIValueType}}, Functional: true, } updatedPropertyType = &PropertyType{ Name: "updated", URI: propertyBaseURI + "updated", Notes: "The date and time at which the object was updated", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdDateTimeValueType}}, Functional: true, } widthPropertyType = &PropertyType{ Name: "width", URI: propertyBaseURI + "width", Notes: "On a Link, specifies a hint as to the rendering width in device-independent pixels of the linked resource.", Domain: []DomainReference{{T: linkType}, {T: imageExtendedType}}, Range: []RangeReference{{V: xsdNonNegativeIntegerValueType}}, Functional: true, } subjectPropertyType = &PropertyType{ Name: "subject", URI: propertyBaseURI + "subject", Notes: "On a Relationship object, the subject property identifies one of the connected individuals. For instance, for a Relationship object describing \"John is related to Sally\", subject would refer to John.", Domain: []DomainReference{{T: relationshipExtendedType}}, Range: []RangeReference{{T: objectType}, {T: linkType}}, Functional: true, } relationshipPropertyType = &PropertyType{ Name: "relationship", URI: propertyBaseURI + "relationship", Notes: "On a Relationship object, the relationship property identifies the kind of relationship that exists between subject and object.", Domain: []DomainReference{{T: relationshipExtendedType}}, Range: []RangeReference{{T: objectType}}, Functional: true, } describesPropertyType = &PropertyType{ Name: "describes", URI: propertyBaseURI + "describes", Notes: "On a Profile object, the describes property identifies the object described by the Profile.", Domain: []DomainReference{{T: profileExtendedType}}, Range: []RangeReference{{T: objectType}}, Functional: true, } formerTypePropertyType = &PropertyType{ Name: "formerType", URI: propertyBaseURI + "formerType", Notes: "On a Tombstone object, the formerType property identifies the type of the object that was deleted.", Domain: []DomainReference{{T: tombstoneExtendedType}}, Range: []RangeReference{{V: xsdStringValueType}, {T: objectType}}, // xsd:String not in spec! } deletedPropertyType = &PropertyType{ Name: "deleted", URI: propertyBaseURI + "deleted", Notes: "On a Tombstone object, the deleted property is a timestamp for when the object was deleted.", Domain: []DomainReference{{T: tombstoneExtendedType}}, Range: []RangeReference{{V: xsdDateTimeValueType}}, Functional: true, } // Specific to ActivityPub specification sourcePropertyType = &PropertyType{ Name: "source", URI: propertyBaseURI + "source", // Missing from spec! Notes: "The source property is intended to convey some sort of source from which the content markup was derived, as a form of provenance, or to support future editing by clients.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}}, Functional: true, // Missing from spec! } inboxPropertyType = &PropertyType{ Name: "inbox", URI: propertyBaseURI + "inbox", // Missing from spec! Notes: "A reference to an [ActivityStreams] OrderedCollection comprised of all the messages received by the actor.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: orderedCollectionType}, {V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } outboxPropertyType = &PropertyType{ Name: "outbox", URI: propertyBaseURI + "outbox", // Missing from spec! Notes: "An [ActivityStreams] OrderedCollection comprised of all the messages produced by the actor.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: orderedCollectionType}, {V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } followingPropertyType = &PropertyType{ Name: "following", URI: propertyBaseURI + "following", Notes: "A link to an [ActivityStreams] collection of the actors that this actor is following", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: collectionType}, {T: orderedCollectionType}, {V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } followersPropertyType = &PropertyType{ Name: "followers", URI: propertyBaseURI + "followers", Notes: "A link to an [ActivityStreams] collection of the actors that follow this actor", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: collectionType}, {T: orderedCollectionType}, {V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } likedPropertyType = &PropertyType{ Name: "liked", URI: propertyBaseURI + "liked", Notes: "A link to an [ActivityStreams] collection of objects this actor has liked", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: collectionType}, {T: orderedCollectionType}, {V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } likesPropertyType = &PropertyType{ Name: "likes", URI: propertyBaseURI + "likes", Notes: "A link to an [ActivityStreams] collection of objects this actor has liked", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: collectionType}, {T: orderedCollectionType}, {V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } streamsPropertyType = &PropertyType{ Name: "streams", URI: propertyBaseURI + "streams", Notes: "A list of supplementary Collections which may be of interest.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, } preferredUsernamePropertyType = &PropertyType{ Name: "preferredUsername", URI: propertyBaseURI + "preferredUsername", Notes: "A short username which may be used to refer to the actor, with no uniqueness guarantees.", NaturalLanguageMap: true, Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdStringValueType}}, Functional: true, // Missing from spec! } endpointsPropertyType = &PropertyType{ Name: "endpoints", URI: propertyBaseURI + "endpoints", Notes: "A json object which maps additional (typically server/domain-wide) endpoints which may be useful either for this actor or someone referencing this actor. This mapping may be nested inside the actor document as the value or may be a link to a JSON-LD document with these properties.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: objectType}}, Functional: true, // Missing from spec! } proxyUrlPropertyType = &PropertyType{ Name: "proxyUrl", URI: propertyBaseURI + "proxyUrl", Notes: "Endpoint URI so this actor's clients may access remote ActivityStreams objects which require authentication to access. To use this endpoint, the client posts an x-www-form-urlencoded id parameter with the value being the id of the requested ActivityStreams object.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } oauthAuthorizationEndpointPropertyType = &PropertyType{ Name: "oauthAuthorizationEndpoint", URI: propertyBaseURI + "oauthAuthorizationEndpoint", Notes: "If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions, this endpoint specifies a URI at which a browser-authenticated user may obtain a new authorization grant.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } oauthTokenEndpointPropertyType = &PropertyType{ Name: "oauthTokenEndpoint", URI: propertyBaseURI + "oauthTokenEndpoint", Notes: "If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions, this endpoint specifies a URI at which a client may acquire an access token.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } provideClientKeyPropertyType = &PropertyType{ Name: "provideClientKey", URI: propertyBaseURI + "provideClientKey", Notes: "If Linked Data Signatures and HTTP Signatures are being used for authentication and authorization, this endpoint specifies a URI at which browser-authenticated users may authorize a client's public key for client to server interactions.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } signClientKeyPropertyType = &PropertyType{ Name: "signClientKey", URI: propertyBaseURI + "signClientKey", Notes: "If Linked Data Signatures and HTTP Signatures are being used for authentication and authorization, this endpoint specifies a URI at which a client key may be signed by the actor's key for a time window to act on behalf of the actor in interacting with foreign servers.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } sharedInboxPropertyType = &PropertyType{ Name: "sharedInbox", URI: propertyBaseURI + "sharedInbox", Notes: "An optional endpoint used for wide delivery of publicly addressed activities and activities sent to followers. sharedInbox endpoints SHOULD also be publicly readable OrderedCollection objects containing objects addressed to the Public special collection. Reading from the sharedInbox endpoint MUST NOT present objects which are not addressed to the Public endpoint.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } sharesPropertyType = &PropertyType{ Name: "shares", URI: propertyBaseURI + "shares", Notes: "This is a list of all Announce activities with this object as the object property, added as a side effect.", Domain: []DomainReference{{T: objectType}}, Range: []RangeReference{{T: collectionType}, {T: orderedCollectionType}, {V: xsdAnyURIValueType}}, Functional: true, // Missing from spec! } AllPropertyTypes = []*PropertyType{ idPropertyType, typePropertyType, actorPropertyType, attachmentPropertyType, attributedToPropertyType, audiencePropertyType, bccPropertyType, btoPropertyType, ccPropertyType, contextPropertyType, currentPropertyType, currentOrderedPropertyType, firstPropertyType, firstOrderedPropertyType, generatorPropertyType, iconPropertyType, imagePropertyType, inReplyToPropertyType, instrumentPropertyType, lastPropertyType, lastOrderedPropertyType, locationPropertyType, itemsPropertyType, orderedItemsPropertyType, oneOfPropertyType, anyOfPropertyType, closedPropertyType, originPropertyType, nextPropertyType, nextOrderedPropertyType, objectPropertyType, prevPropertyType, prevOrderedPropertyType, previewPropertyType, resultPropertyType, repliesPropertyType, tagPropertyType, targetPropertyType, toPropertyType, urlPropertyType, accuracyPropertyType, altitudePropertyType, contentPropertyType, namePropertyType, durationPropertyType, heightPropertyType, hrefPropertyType, hrefLangPropertyType, partOfPropertyType, latitudePropertyType, longitudePropertyType, mediaTypePropertyType, endTimePropertyType, publishedPropertyType, startTimePropertyType, radiusPropertyType, relPropertyType, startIndexPropertyType, summaryPropertyType, totalItemsPropertyType, unitsPropertyType, updatedPropertyType, widthPropertyType, subjectPropertyType, relationshipPropertyType, describesPropertyType, formerTypePropertyType, deletedPropertyType, sourcePropertyType, inboxPropertyType, outboxPropertyType, followingPropertyType, followersPropertyType, likedPropertyType, likesPropertyType, streamsPropertyType, preferredUsernamePropertyType, endpointsPropertyType, proxyUrlPropertyType, oauthAuthorizationEndpointPropertyType, oauthTokenEndpointPropertyType, provideClientKeyPropertyType, signClientKeyPropertyType, sharedInboxPropertyType, sharesPropertyType, } ) // ValueType definitions const ( xsdBaseURI = "http://www.w3.org/2001/XMLSchema#" rdfBaseURI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" ) var ( xsdDateTimeValueType = &ValueType{ Name: "dateTime", URI: xsdBaseURI + "dateTime", DefinitionType: "*time.Time", Zero: "time.Time{}", DeserializeFn: &FunctionDef{ Name: "dateTimeDeserialize", Comment: "dateTimeDeserialize turns a string into a time.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"t", "*time.Time"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("var tmp time.Time\n") b.WriteString("if s, ok := v.(string); ok {\n") b.WriteString("tmp, err = time.Parse(time.RFC3339, s)\n") b.WriteString("if err != nil {\n") b.WriteString("tmp, err = time.Parse(\"2006-01-02T15:04Z07:00\", s)\n") b.WriteString("if err != nil {\n") b.WriteString("err = fmt.Errorf(\"%s cannot be interpreted as xsd:dateTime\", s)\n") b.WriteString("} else {\n") b.WriteString("t = &tmp\n") b.WriteString("}\n") b.WriteString("} else {\n") b.WriteString("t = &tmp\n") b.WriteString("}\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for xsd:dateTime\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "dateTimeSerialize", Comment: "dateTimeSerialize turns a time into a string", Args: []*FunctionVarDef{{"t", "time.Time"}}, Return: []*FunctionVarDef{{"s", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("s = t.Format(time.RFC3339)\n") b.WriteString("return\n") return b.String() }, }, Imports: []string{"time"}, } xsdBooleanValueType = &ValueType{ Name: "boolean", URI: xsdBaseURI + "boolean", DefinitionType: "*bool", Zero: "false", DeserializeFn: &FunctionDef{ Name: "booleanDeserialize", Comment: "booleanDeserialize turns a interface{} into a bool.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"b", "*bool"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if bv, ok := v.(bool); ok {\n") b.WriteString("b = &bv\n") b.WriteString("} else if bv, ok := v.(float64); ok {\n") b.WriteString("if bv == 0 {\n") b.WriteString("bvb := false\n") b.WriteString("b = &bvb\n") b.WriteString("} else if bv == 1 {\n") b.WriteString("bvb := true\n") b.WriteString("b = &bvb\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%d cannot be interpreted as a bool float64 for xsd:boolean\", v)\n") b.WriteString("}\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a bool for xsd:boolean\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "booleanSerialize", Comment: "booleanSerialize simply returns the bool value", Args: []*FunctionVarDef{{"v", "bool"}}, Return: []*FunctionVarDef{{"r", "bool"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = v\n") b.WriteString("return\n") return b.String() }, }, } xsdAnyURIValueType = &ValueType{ Name: "anyURI", URI: xsdBaseURI + "anyURI", DefinitionType: "*url.URL", Zero: "\"\"", DeserializeFn: &FunctionDef{ Name: "anyURIDeserialize", Comment: "anyURIDeserialize turns a string into a URI.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"u", "*url.URL"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if s, ok := v.(string); ok {\n") b.WriteString("u, err = url.Parse(s)\n") b.WriteString("if err != nil {\n") b.WriteString("err = fmt.Errorf(\"%s cannot be interpreted as xsd:anyURI\", s)\n") b.WriteString("}\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for xsd:anyURI\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "anyURISerialize", Comment: "anyURISerialize turns a URI into a string", Args: []*FunctionVarDef{{"u", "*url.URL"}}, Return: []*FunctionVarDef{{"s", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("s = u.String()\n") b.WriteString("return\n") return b.String() }, }, Imports: []string{"net/url"}, } xsdFloatValueType = &ValueType{ Name: "float", URI: xsdBaseURI + "float", DefinitionType: "*float64", Zero: "0", DeserializeFn: &FunctionDef{ Name: "floatDeserialize", Comment: "floatDeserialize turns a interface{} into a float64.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"f", "*float64"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if fv, ok := v.(float64); ok {\n") b.WriteString("f = &fv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a float for xsd:float\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "floatSerialize", Comment: "floatSerialize simply returns the float value", Args: []*FunctionVarDef{{"f", "float64"}}, Return: []*FunctionVarDef{{"r", "float64"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = f\n") b.WriteString("return\n") return b.String() }, }, } xsdStringValueType = &ValueType{ Name: "string", URI: xsdBaseURI + "string", DefinitionType: "*string", Zero: "0", DeserializeFn: &FunctionDef{ Name: "stringDeserialize", Comment: "stringDeserialize turns a interface{} into a string.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"s", "*string"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if sv, ok := v.(string); ok {\n") b.WriteString("s = &sv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for xsd:string\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "stringSerialize", Comment: "stringSerialize simply returns the string value", Args: []*FunctionVarDef{{"s", "string"}}, Return: []*FunctionVarDef{{"r", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = s\n") b.WriteString("return\n") return b.String() }, }, } rdfLangStringValueType = &ValueType{ Name: "langString", URI: rdfBaseURI + "langString", DefinitionType: "*string", Zero: "0", DeserializeFn: &FunctionDef{ Name: "langStringDeserialize", Comment: "langStringDeserialize turns a RDF interface{} into a string.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"s", "*string"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if sv, ok := v.(string); ok {\n") b.WriteString("s = &sv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for rdf:langString\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "langStringSerialize", Comment: "langStringSerialize returns a formatted RDF value.", Args: []*FunctionVarDef{{"s", "string"}}, Return: []*FunctionVarDef{{"r", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = s\n") b.WriteString("return\n") return b.String() }, }, } xsdDurationValueType = &ValueType{ Name: "duration", URI: xsdBaseURI + "duration", DefinitionType: "*time.Duration", Zero: "0", DeserializeFn: &FunctionDef{ Name: "durationDeserialize", Comment: "durationDeserialize turns a interface{} into a time.Duration.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"d", "*time.Duration"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if sv, ok := v.(string); ok {\n") b.WriteString("isNeg := false\n") b.WriteString("if sv[0] == '-' {\n") b.WriteString("isNeg = true\n") b.WriteString("sv = sv[1:]\n") b.WriteString("}\n") b.WriteString("if sv[0] != 'P' {\n") b.WriteString("err = fmt.Errorf(\"'%s' malformed: missing 'P' for xsd:duration\", sv)\n") b.WriteString("return\n") b.WriteString("}\n") b.WriteString(`re := regexp.MustCompile("P(\\d*Y)?(\\d*M)?(\\d*D)?(T(\\d*H)?(\\d*M)?(\\d*S)?)?")`) b.WriteString("\n") b.WriteString("res := re.FindStringSubmatch(sv)\n") b.WriteString("var dur time.Duration\n") b.WriteString("nYear := res[1]\n") b.WriteString("if len(nYear) > 0 {\n") b.WriteString("nYear = nYear[:len(nYear)-1]\n") b.WriteString("vYear, err := strconv.ParseInt(nYear, 10, 64)\n") b.WriteString("if err != nil {\nreturn nil, err\n}\n") b.WriteString("dur += time.Duration(vYear) * time.Hour * 8760 // Hours per 365 days -- no way to count leap years here.\n") b.WriteString("}\n") b.WriteString("nMonth := res[2]\n") b.WriteString("if len(nMonth) > 0 {\n") b.WriteString("nMonth = nMonth[:len(nMonth)-1]\n") b.WriteString("vMonth, err := strconv.ParseInt(nMonth, 10, 64)\n") b.WriteString("if err != nil {\nreturn nil, err\n}\n") b.WriteString("dur += time.Duration(vMonth) * time.Hour * 720 // Hours per 30 days -- no way to tell if these months span 31 days, 28, or 29 each.\n") b.WriteString("}\n") b.WriteString("nDay := res[3]\n") b.WriteString("if len(nDay) > 0 {\n") b.WriteString("nDay = nDay[:len(nDay)-1]\n") b.WriteString("vDay, err := strconv.ParseInt(nDay, 10, 64)\n") b.WriteString("if err != nil {\nreturn nil, err\n}\n") b.WriteString("dur += time.Duration(vDay) * time.Hour * 24\n") b.WriteString("}\n") b.WriteString("nHour := res[5]\n") b.WriteString("if len(nHour) > 0 {\n") b.WriteString("nHour = nHour[:len(nHour)-1]\n") b.WriteString("vHour, err := strconv.ParseInt(nHour, 10, 64)\n") b.WriteString("if err != nil {\nreturn nil, err\n}\n") b.WriteString("dur += time.Duration(vHour) * time.Hour\n") b.WriteString("}\n") b.WriteString("nMinute := res[6]\n") b.WriteString("if len(nMinute) > 0 {\n") b.WriteString("nMinute = nMinute[:len(nMinute)-1]\n") b.WriteString("vMinute, err := strconv.ParseInt(nMinute, 10, 64)\n") b.WriteString("if err != nil {\nreturn nil, err\n}\n") b.WriteString("dur += time.Duration(vMinute) * time.Minute\n") b.WriteString("}\n") b.WriteString("nSecond := res[7]\n") b.WriteString("if len(nSecond) > 0 {\n") b.WriteString("nSecond = nSecond[:len(nSecond)-1]\n") b.WriteString("vSecond, err := strconv.ParseInt(nSecond, 10, 64)\n") b.WriteString("if err != nil {\nreturn nil, err\n}\n") b.WriteString("dur += time.Duration(vSecond) * time.Second\n") b.WriteString("}\n") b.WriteString("if isNeg {\n") b.WriteString("dur *= -1\n") b.WriteString("}\n") b.WriteString("d = &dur\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for xsd:duration\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "durationSerialize", Comment: "durationSerialize returns the duration as a string.", Args: []*FunctionVarDef{{"d", "time.Duration"}}, Return: []*FunctionVarDef{{"s", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("s = \"P\"\n") b.WriteString("if d < 0 {\n") b.WriteString("s = \"-P\"\n") b.WriteString("d = -1 * d\n") b.WriteString("}\n") b.WriteString("var tally time.Duration\n") b.WriteString("if years := d.Hours() / 8760.0; years >= 1 {\n") b.WriteString("nYears := int64(math.Floor(years))\n") b.WriteString("tally += time.Duration(nYears) * 8760 * time.Hour\n") b.WriteString("s = fmt.Sprintf(\"%s%dY\", s, nYears)\n") b.WriteString("}\n") b.WriteString("if months := (d.Hours() - tally.Hours()) / 720.0; months >= 1 {\n") b.WriteString("nMonths := int64(math.Floor(months))\n") b.WriteString("tally += time.Duration(nMonths) * 720 * time.Hour\n") b.WriteString("s = fmt.Sprintf(\"%s%dM\", s, nMonths)\n") b.WriteString("}\n") b.WriteString("if days := (d.Hours() - tally.Hours()) / 24.0; days >= 1 {\n") b.WriteString("nDays := int64(math.Floor(days))\n") b.WriteString("tally += time.Duration(nDays) * 24 * time.Hour\n") b.WriteString("s = fmt.Sprintf(\"%s%dD\", s, nDays)\n") b.WriteString("}\n") b.WriteString("if tally < d {\n") b.WriteString("s = fmt.Sprintf(\"%sT\", s)\n") b.WriteString("if hours := d.Hours() - tally.Hours(); hours >= 1 {\n") b.WriteString("nHours := int64(math.Floor(hours))\n") b.WriteString("tally += time.Duration(nHours) * time.Hour\n") b.WriteString("s = fmt.Sprintf(\"%s%dH\", s, nHours)\n") b.WriteString("}\n") b.WriteString("if minutes := d.Minutes() - tally.Minutes(); minutes >= 1 {\n") b.WriteString("nMinutes := int64(math.Floor(minutes))\n") b.WriteString("tally += time.Duration(nMinutes) * time.Minute\n") b.WriteString("s = fmt.Sprintf(\"%s%dM\", s, nMinutes)\n") b.WriteString("}\n") b.WriteString("if seconds := d.Seconds() - tally.Seconds(); seconds >= 1 {\n") b.WriteString("nSeconds := int64(math.Floor(seconds))\n") b.WriteString("tally += time.Duration(nSeconds) * time.Second\n") b.WriteString("s = fmt.Sprintf(\"%s%dS\", s, nSeconds)\n") b.WriteString("}\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, Imports: []string{"time"}, } xsdNonNegativeIntegerValueType = &ValueType{ Name: "nonNegativeInteger", URI: xsdBaseURI + "nonNegativeInteger", DefinitionType: "*int64", Zero: "0", DeserializeFn: &FunctionDef{ Name: "nonNegativeIntegerDeserialize", Comment: "nonNegativeIntegerDeserialize turns a interface{} into a positive int64 value.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"i", "*int64"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if fv, ok := v.(float64); ok {\n") b.WriteString("iv := int64(fv)\n") b.WriteString("if iv >= 0 {\n") b.WriteString("i = &iv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%d is a negative integer for xsd:nonNegativeInteger\", iv)\n") b.WriteString("}\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a float for xsd:nonNegativeInteger\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "nonNegativeIntegerSerialize", Comment: "nonNegativeIntegerSerialize simply returns the int64 value.", Args: []*FunctionVarDef{{"i", "int64"}}, Return: []*FunctionVarDef{{"r", "int64"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = i\n") b.WriteString("return\n") return b.String() }, }, } bcp47LangTag = &ValueType{ Name: "bcp47LanguageTag", DefinitionType: "*string", Zero: "\"\"", DeserializeFn: &FunctionDef{ Name: "bcp47LanguageTagDeserialize", Comment: "bcp47LanguageTagDeserialize turns a interface{} into a string.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"s", "*string"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if sv, ok := v.(string); ok {\n") b.WriteString("s = &sv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for BCP 47 Language Tag\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "bcp47LanguageTagSerialize", Comment: "bcp47LanguageTagSerialize simply returns the string value", Args: []*FunctionVarDef{{"s", "string"}}, Return: []*FunctionVarDef{{"r", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = s\n") b.WriteString("return\n") return b.String() }, }, } mimeMediaValueType = &ValueType{ Name: "mimeMediaTypeValue", DefinitionType: "*string", Zero: "\"\"", DeserializeFn: &FunctionDef{ Name: "mimeMediaTypeValueDeserialize", Comment: "mimeMediaTypeValueDeserialize turns a interface{} into a string.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"s", "*string"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if sv, ok := v.(string); ok {\n") b.WriteString("s = &sv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for MIME media type value\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "mimeMediaTypeValueSerialize", Comment: "mimeMediaTypeValueSerialize simply returns the string value", Args: []*FunctionVarDef{{"s", "string"}}, Return: []*FunctionVarDef{{"r", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = s\n") b.WriteString("return\n") return b.String() }, }, } linkRelationValueType = &ValueType{ Name: "linkRelation", DefinitionType: "*string", Zero: "\"\"", DeserializeFn: &FunctionDef{ Name: "linkRelationDeserialize", Comment: "linkRelationDeserialize turns a interface{} into a string.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"s", "*string"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if sv, ok := v.(string); ok {\n") b.WriteString("s = &sv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for link relation\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "linkRelationSerialize", Comment: "linkRelationSerialize simply returns the string value", Args: []*FunctionVarDef{{"s", "string"}}, Return: []*FunctionVarDef{{"r", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = s\n") b.WriteString("return\n") return b.String() }, }, } unitsValueType = &ValueType{ Name: "unitsValue", DefinitionType: "*string", Zero: "\"\"", DeserializeFn: &FunctionDef{ Name: "unitsValueDeserialize", Comment: "unitsValueDeserialize turns a interface{} into a string.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"s", "*string"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if sv, ok := v.(string); ok {\n") b.WriteString("s = &sv\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for units value\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "unitsValueSerialize", Comment: "unitsValueSerialize simply returns the string value", Args: []*FunctionVarDef{{"s", "string"}}, Return: []*FunctionVarDef{{"r", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("r = s\n") b.WriteString("return\n") return b.String() }, }, } AllValueTypes = []*ValueType{ xsdDateTimeValueType, xsdBooleanValueType, xsdAnyURIValueType, xsdFloatValueType, xsdStringValueType, rdfLangStringValueType, xsdDurationValueType, xsdNonNegativeIntegerValueType, bcp47LangTag, mimeMediaValueType, linkRelationValueType, unitsValueType, } ) func init() { objectType.DisjointWith = []*Type{linkType} // Type properties objectType.Properties = []*PropertyType{ altitudePropertyType, // Missing from spec! attachmentPropertyType, attributedToPropertyType, audiencePropertyType, contentPropertyType, contextPropertyType, namePropertyType, endTimePropertyType, generatorPropertyType, iconPropertyType, idPropertyType, // Missing from spec! imagePropertyType, inReplyToPropertyType, locationPropertyType, previewPropertyType, publishedPropertyType, repliesPropertyType, startTimePropertyType, summaryPropertyType, tagPropertyType, typePropertyType, // Missing from spec! updatedPropertyType, urlPropertyType, toPropertyType, btoPropertyType, ccPropertyType, bccPropertyType, mediaTypePropertyType, durationPropertyType, // ActivityPub specific properties sourcePropertyType, inboxPropertyType, outboxPropertyType, followingPropertyType, followersPropertyType, likedPropertyType, likesPropertyType, streamsPropertyType, preferredUsernamePropertyType, endpointsPropertyType, proxyUrlPropertyType, oauthAuthorizationEndpointPropertyType, oauthTokenEndpointPropertyType, provideClientKeyPropertyType, signClientKeyPropertyType, sharedInboxPropertyType, sharesPropertyType, } linkType.Properties = []*PropertyType{ attributedToPropertyType, // Missing from spec! hrefPropertyType, idPropertyType, // Missing from spec! relPropertyType, typePropertyType, // Missing from spec! mediaTypePropertyType, namePropertyType, summaryPropertyType, // Only in example 58, missing from spec! hrefLangPropertyType, heightPropertyType, widthPropertyType, previewPropertyType, } activityType.Properties = []*PropertyType{ actorPropertyType, objectPropertyType, targetPropertyType, resultPropertyType, originPropertyType, instrumentPropertyType, } collectionType.Properties = []*PropertyType{ totalItemsPropertyType, currentPropertyType, firstPropertyType, lastPropertyType, itemsPropertyType, } orderedCollectionType.Properties = []*PropertyType{ orderedItemsPropertyType, // Missing from spec! currentOrderedPropertyType, firstOrderedPropertyType, lastOrderedPropertyType, } collectionPageType.Properties = []*PropertyType{ partOfPropertyType, nextPropertyType, prevPropertyType, } orderedCollectionPageType.Properties = []*PropertyType{ startIndexPropertyType, nextOrderedPropertyType, prevOrderedPropertyType, } // ExtendedType properties imageExtendedType.Properties = []*PropertyType{ heightPropertyType, // Missing from spec! widthPropertyType, // Missing from spec! } questionExtendedType.Properties = []*PropertyType{ oneOfPropertyType, anyOfPropertyType, closedPropertyType, } relationshipExtendedType.Properties = []*PropertyType{ subjectPropertyType, objectPropertyType, relationshipPropertyType, } placeExtendedType.Properties = []*PropertyType{ accuracyPropertyType, altitudePropertyType, latitudePropertyType, longitudePropertyType, radiusPropertyType, unitsPropertyType, } profileExtendedType.Properties = []*PropertyType{ describesPropertyType, } tombstoneExtendedType.Properties = []*PropertyType{ formerTypePropertyType, deletedPropertyType, } } var IriValueType = &ValueType{ Name: "IRI", URI: "IRI", DefinitionType: "*url.URL", Zero: "nil", DeserializeFn: &FunctionDef{ Name: "IRIDeserialize", Comment: "IRIDeserialize turns a string into a URI.", Args: []*FunctionVarDef{{"v", "interface{}"}}, Return: []*FunctionVarDef{{"u", "*url.URL"}, {"err", "error"}}, Body: func() string { var b bytes.Buffer b.WriteString("if s, ok := v.(string); ok {\n") b.WriteString("u, err = url.Parse(s)\n") b.WriteString("if err != nil {\n") b.WriteString("err = fmt.Errorf(\"%s cannot be interpreted as IRI\", s)\n") b.WriteString("}\n") b.WriteString("} else {\n") b.WriteString("err = fmt.Errorf(\"%v cannot be interpreted as a string for IRI\", v)\n") b.WriteString("}\n") b.WriteString("return\n") return b.String() }, }, SerializeFn: &FunctionDef{ Name: "IRISerialize", Comment: "IRISerialize turns an IRI into a string", Args: []*FunctionVarDef{{"u", "*url.URL"}}, Return: []*FunctionVarDef{{"s", "string"}}, Body: func() string { var b bytes.Buffer b.WriteString("s = u.String()\n") b.WriteString("return\n") return b.String() }, }, Imports: []string{"net/url"}, } func init() { for _, p := range AllPropertyTypes { if !HasAnyURI(p.Range) { p.Range = append(p.Range, RangeReference{V: IriValueType}) } } } func HasAnyURI(r []RangeReference) bool { for _, v := range r { if v.V != nil && v.V == xsdAnyURIValueType { return true } } return false } func IsIRIValueTypeString(v *ValueType) bool { return v.DefinitionType == "*url.URL" } func IsIRIValueType(v *ValueType) bool { return v == IriValueType } func IsAnyURIValueType(v *ValueType) bool { return v == xsdAnyURIValueType } func AnyURIValueTypeName() string { return xsdAnyURIValueType.Name } func IRIFuncs() []*FunctionDef { return []*FunctionDef{IriValueType.DeserializeFn, IriValueType.SerializeFn} } func IsActivity(t *Type) bool { var recur func(t *Type) bool recur = func(t *Type) bool { for _, e := range t.Extends { if e == activityType { return true } else if recur(e) { return true } } return false } return recur(t) }
tools/defs/defs.go
0.519278
0.523847
defs.go
starcoder
package tests import ( "encoding/json" "github.com/Jeffail/gabs" "github.com/stretchr/testify/require" "gopkg.in/resty.v1" "strings" "testing" ) func standardJsonResponseTests(response *resty.Response, expectedStatusCode int, t *testing.T) { t.Run("has standard json response ("+response.Request.URL+")", func(t *testing.T) { t.Run("response has content type application/json", func(t *testing.T) { parts := strings.Split(response.Header().Get("content-type"), ";") require.New(t).Equal("application/json", parts[0]) }) t.Run("response is parsable", func(t *testing.T) { body := response.Body() out := map[string]interface{}{} err := json.Unmarshal(body, &out) require.New(t).NoError(err) }) t.Run("response body is a valid envelope", func(t *testing.T) { body := response.Body() r := require.New(t) if len(body) == 0 { return } data, err := gabs.ParseJSON(body) r.NoError(err) hasData := data.ExistsP("data") hasError := data.ExistsP("error") r.False(hasError, "response has 'error' property, not expected, value: %s", data.StringIndent("", " ")) r.True(hasData, "response is missing 'data' property") _, err = data.Object("data") r.NoError(err, "response envelope does not have an object value for 'data', got body: %s", string(body)) r.True(data.ExistsP("meta"), "missing a meta property", string(body)) _, err = data.Object("meta") r.NoError(err, "response envelope does not have an object value for 'meta', got body: %s", string(body)) }) t.Run("has a valid meta section", func(t *testing.T) { body := response.Body() r := require.New(t) bodyData, err := gabs.ParseJSON(body) r.NoError(err) _, err = bodyData.Object("meta") r.NoError(err, "property 'meta' was not an object") }) t.Run("has a valid data section", func(t *testing.T) { body := response.Body() r := require.New(t) bodyData, err := gabs.ParseJSON(body) r.NoError(err) _, err = bodyData.Object("data", "property 'data' was not an object") if err != nil { _, err = bodyData.Array("data") } r.NoError(err, "expected property 'data' to be an object or array") }) t.Run("has the expected HTTP status code", func(t *testing.T) { require.New(t).Equal(expectedStatusCode, response.StatusCode()) }) }) } func standardErrorJsonResponseTests(response *resty.Response, expectedErrorCode string, expectedStatusCode int, t *testing.T) { t.Run("has standard json error response ("+response.Request.URL+")", func(t *testing.T) { t.Run("response has content type application/json", func(t *testing.T) { parts := strings.Split(response.Header().Get("content-type"), ";") require.New(t).Equal("application/json", parts[0]) }) t.Run("response is parsable", func(t *testing.T) { body := response.Body() out := map[string]interface{}{} err := json.Unmarshal(body, &out) require.New(t).NoError(err, `could not parse JSON: "%s""`, body) }) t.Run("response body is a valid envelope", func(t *testing.T) { body := response.Body() r := require.New(t) data, err := gabs.ParseJSON(body) r.NoError(err, "could not parse JSON: %s", body) hasData := data.ExistsP("data") hasError := data.ExistsP("error") r.False(hasData, "response has 'data' property, not expected', value: %s", data.Path("data").String()) r.True(hasError, "response is missing 'error' property") _, err = data.Object("error") r.NoError(err, "response envelope does not have an object value for 'error', body: %s", string(body)) r.True(data.ExistsP("meta"), "missing a meta property, body: %s", string(body)) _, err = data.Object("meta") r.NoError(err, "response envelope does not have an object value for 'meta', body: %s", string(body)) }) t.Run("has a valid meta section", func(t *testing.T) { body := response.Body() r := require.New(t) data, err := gabs.ParseJSON(body) r.NoError(err) r.True(data.ExistsP("meta.apiVersion"), "missing 'meta.apiVersion' property for error response") r.True(data.ExistsP("meta.apiEnrollmentVersion"), "missing 'meta.apiEnrollmentVersion' property for error response") }) t.Run("has a valid error section", func(t *testing.T) { body := response.Body() r := require.New(t) data, err := gabs.ParseJSON(body) r.NoError(err) r.True(data.ExistsP("error.code"), "missing 'error.code' property for error response") r.True(data.ExistsP("error.message"), "missing 'error.message' property for error response") r.True(data.ExistsP("error.requestId"), "missing 'error.requestId' property for error response") }) t.Run("has the expected error code", func(t *testing.T) { body := response.Body() r := require.New(t) data, err := gabs.ParseJSON(body) r.NoError(err) errorCode := data.Path("error.code").Data().(string) switch errorCode { case "COULD_NOT_VALIDATE": r.Equal(expectedErrorCode, errorCode, `response cause: "%s"`, data.Path("error.cause").String()) default: r.Equal(expectedErrorCode, errorCode) } }) t.Run("has the expected HTTP status code", func(t *testing.T) { require.New(t).Equal(expectedStatusCode, response.StatusCode()) }) }) }
tests/standard.go
0.573201
0.443179
standard.go
starcoder
package encoding import ( "fmt" "reflect" "strconv" "strings" ) func convertStruct(i interface{}, t reflect.Type, pointer bool) (reflect.Value, error) { m, ok := i.(map[string]interface{}) if !ok { return zeroValue, fmt.Errorf("Cannot convert %T to struct", i) } out := reflect.New(t) err := Unstringify(m, out.Interface()) if err != nil { return zeroValue, err } if !pointer { out = out.Elem() } return out, nil } func convertSlice(i interface{}, t reflect.Type, pointer bool) (reflect.Value, error) { s, ok := i.([]interface{}) if !ok { return zeroValue, fmt.Errorf("Cannot convert %T to slice", i) } out := reflect.New(t) out.Elem().Set(reflect.MakeSlice(t, len(s), len(s))) for j, v := range s { val, err := convertType(t.Elem(), v) if err != nil { return zeroValue, err } out.Elem().Index(j).Set(val) } if !pointer { out = out.Elem() } return out, nil } func convertMap(i interface{}, t reflect.Type, pointer bool) (reflect.Value, error) { m, ok := i.(map[string]interface{}) if !ok { return zeroValue, fmt.Errorf("Cannot convert %T to map with string keys", i) } out := reflect.New(t) out.Elem().Set(reflect.MakeMap(t)) for k, v := range m { val, err := convertType(t.Elem(), v) if err != nil { return zeroValue, err } out.Elem().SetMapIndex(reflect.ValueOf(k), val) } if !pointer { out = out.Elem() } return out, nil } func convertString(i interface{}, pointer bool) (reflect.Value, error) { s, ok := i.(string) if !ok { return zeroValue, fmt.Errorf("Cannot convert %T to string", i) } if pointer { return reflect.ValueOf(&s), nil } return reflect.ValueOf(s), nil } func convertBool(i interface{}, pointer bool) (reflect.Value, error) { var b bool var err error switch v := i.(type) { case bool: b = v case string: b, err = strconv.ParseBool(v) if err != nil { return zeroValue, err } default: return zeroValue, fmt.Errorf("Cannot convert %T to bool", i) } if pointer { return reflect.ValueOf(&b), nil } return reflect.ValueOf(b), nil } func convertInt(i interface{}, pointer bool) (reflect.Value, error) { var n int switch v := i.(type) { case int: n = v case float64: n = int(v) case string: n64, err := strconv.ParseInt(v, 0, 32) if err != nil { return zeroValue, err } n = int(n64) default: return zeroValue, fmt.Errorf("Cannot convert %T to bool", i) } if pointer { return reflect.ValueOf(&n), nil } return reflect.ValueOf(n), nil } func convertFloat64(i interface{}, pointer bool) (reflect.Value, error) { var f float64 var err error switch v := i.(type) { case float64: f = v case int: f = float64(v) case string: f, err = strconv.ParseFloat(v, 64) if err != nil { return zeroValue, err } default: return zeroValue, fmt.Errorf("Cannot convert %T to bool", i) } if pointer { return reflect.ValueOf(&f), nil } return reflect.ValueOf(f), nil } func convertType(t reflect.Type, i interface{}) (reflect.Value, error) { pointer := false if t.Kind() == reflect.Ptr { pointer = true t = t.Elem() } switch t.Kind() { case reflect.Struct: return convertStruct(i, t, pointer) case reflect.Slice: return convertSlice(i, t, pointer) case reflect.Map: return convertMap(i, t, pointer) case reflect.String: return convertString(i, pointer) case reflect.Bool: return convertBool(i, pointer) case reflect.Int: return convertInt(i, pointer) case reflect.Float64: return convertFloat64(i, pointer) default: return zeroValue, fmt.Errorf("Unsupported type %v", t) } } // Unstringify takes a stringified representation of a value // and populates it into the supplied interface func Unstringify(data map[string]interface{}, v interface{}) error { t := reflect.TypeOf(v).Elem() val := reflect.ValueOf(v).Elem() for i := 0; i < t.NumField(); i++ { f := t.Field(i) jsonName := f.Name jsonTag := strings.Split(f.Tag.Get("json"), ",") if len(jsonTag) > 0 && jsonTag[0] != "" { jsonName = jsonTag[0] } if value, ok := data[jsonName]; ok { newValue, err := convertType(f.Type, value) if err != nil { return err } val.FieldByName(f.Name).Set(newValue) } } return nil }
cfn/encoding/unstringify.go
0.572962
0.420957
unstringify.go
starcoder
package continuous_nums_with_target_sum import "math" /* [面试题57 - II. 和为s的连续正数序列](https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/) 输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。 示例 1: 输入:target = 9 输出:[[2,3,4],[4,5]] 示例 2: 输入:target = 15 输出:[[1,2,3,4,5],[4,5,6],[7,8]] 限制: 1 <= target <= 10^5 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* 双指针 时间复杂度O(target);两个指针移动均单调不减,且最多移动 target/2 次 空间复杂度O(1),除了答案数组只需要常数的空间 */ func findContinuousSequence(target int) [][]int { var r [][]int for left, right := 1, 2; left < right; { size := right - left + 1 sum := (left + right) * size / 2 if sum == target { t := make([]int, size) for i := range t { t[i] = left + i } r = append(r, t) left++ right++ } else if sum < target { right++ } else { left++ } } return r } /* 类似双指针的解法,额外引入一个队列,空间复杂度增加为O(target) */ func findContinuousSequence0(target int) [][]int { var r [][]int var queue []int sum := 0 for i := 1; i < target; i++ { queue = append(queue, i) sum += i for sum > target && len(queue) > 0 { sum -= queue[0] queue = queue[1:] } if sum == target { t := make([]int, len(queue)) _ = copy(t, queue) r = append(r, t) } } return r } /* 解一元二次方程 如上边的解法,假设用x、y分别表示left,right 为了使sum == target <=> (x+y) * (y-x+1) / 2 == target <=> y^2 + y -x^2 + x - 2*target == 0 可以看成是一个关于y的一元二次方程,其中a=1,b=1, c = -x^2 + x - 2*target 可以用求根公式解得y;需要满足: 判别式delta = b^2 - 4ac 需要大于0且平方根需为整数 */ func findContinuousSequence1(target int) [][]int { var r [][]int limit := (target - 1) / 2 // 等效于 target/2 向下取整 for x := 1; x <= limit; x++ { delta := 1 - 4*(-x*x+x-2*target) if delta < 0 { continue } deltaSqrt := int(math.Sqrt(float64(delta))) if deltaSqrt*deltaSqrt == delta && (deltaSqrt-1)%2 == 0 { y := (deltaSqrt - 1) / 2 // 另一个解(-1-delta_sqrt)/2必然小于0,不用考虑 if x >= y { continue } t := make([]int, y-x+1) for i := range t { t[i] = x + i } r = append(r, t) } } return r }
solutions/continuous-nums-with-target-sum/d.go
0.607547
0.487612
d.go
starcoder
package collections import ( "reflect" "strconv" "strings" "unicode" ) // IntValue type alias for int type IntValue int // Int casts and returns int value func (i IntValue) Int() int { return int(i) } // Int32 casts and returns Int32 value func (i IntValue) Int32() int32 { return int32(i) } // Int64 casts and returns Int64 value func (i IntValue) Int64() int64 { return int64(i) } // Float32 casts and returns Float32 value func (i IntValue) Float32() float32 { return float32(i) } // Float64 casts and returns Float64 value func (i IntValue) Float64() float64 { return float64(i) } // String casts and returns string value func (i IntValue) String() string { return strconv.Itoa(int(i)) } // Bool casts and returns bool func (i IntValue) Bool() bool { if i == 0 { return false } return true } // Less compares the other data and returns true if self is less than other func (i IntValue) Less(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int(i) < other.Int() case reflect.Float32, reflect.Float64: return int(i) < int(other.Float64()) case reflect.String: v, _ := strconv.Atoi(other.String()) return int(i) < v } return false } // Equal compares the other data and returns true is the same as self's value, not self's value and type func (i IntValue) Equal(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int(i) == other.Int() case reflect.Float32, reflect.Float64: return int(i) == int(other.Float64()) case reflect.String: v, _ := strconv.Atoi(other.String()) return int(i) == v } return false } // Greater compares the other data and returns true if self is greater than other func (i IntValue) Greater(other Data) bool { if i.Equal(other) { return false } return !i.Less(other) } // Add adds OperableData together func (i IntValue) Add(data OperableData) Data { return IntValue(int(i) + data.Int()) } // Sub subtracts OperableData together func (i IntValue) Sub(data OperableData) Data { return IntValue(int(i) - data.Int()) } // Mul multiplies OperableData together func (i IntValue) Mul(data OperableData) Data { return IntValue(int(i) * data.Int()) } // Div divides OperableData together func (i IntValue) Div(data OperableData) Data { return IntValue(int(i) / data.Int()) } // Mod modulus' OperableData together func (i IntValue) Mod(data OperableData) Data { return IntValue(int(i) % data.Int()) } // IntValues type alias for a slice of IntValue type IntValues []int func (i IntValues) Data() []Data { d := make([]Data, len(i)) for j := range i { d[j] = IntValue(i[j]) } return d } // IntValue32 type alias for int type IntValue32 int32 // Int casts and returns int value func (i IntValue32) Int() int { return int(i) } // Int32 casts and returns Int32 value func (i IntValue32) Int32() int32 { return int32(i) } // Int64 casts and returns Int64 value func (i IntValue32) Int64() int64 { return int64(i) } // Float32 casts and returns Float32 value func (i IntValue32) Float32() float32 { return float32(i) } // Float64 casts and returns Float64 value func (i IntValue32) Float64() float64 { return float64(i) } // String casts and returns string value func (i IntValue32) String() string { return strconv.Itoa(int(i)) } // Bool casts and returns bool func (i IntValue32) Bool() bool { if i == 0 { return false } return true } // Less compares the other data and returns true is it's less than self func (i IntValue32) Less(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int32(i) < other.Int32() case reflect.Float32, reflect.Float64: return int32(i) < int32(other.Float64()) case reflect.String: v, _ := strconv.Atoi(other.String()) return int32(i) < int32(v) } return false } // Equal compares the other data and returns true is the same as self's value, not self's value and type func (i IntValue32) Equal(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int32(i) == other.Int32() case reflect.Float32, reflect.Float64: return int32(i) == int32(other.Float64()) case reflect.String: v, _ := strconv.Atoi(other.String()) return int32(i) == int32(v) } return false } // Greater compares the other data and returns true is it's greater than self func (i IntValue32) Greater(other Data) bool { if i.Equal(other) { return false } return !i.Less(other) } // Add adds OperableData together func (i IntValue32) Add(data OperableData) Data { return IntValue32(int32(i) + data.Int32()) } // Sub subtracts OperableData together func (i IntValue32) Sub(data OperableData) Data { return IntValue32(int32(i) - data.Int32()) } // Mul multiplies OperableData together func (i IntValue32) Mul(data OperableData) Data { return IntValue32(int32(i) * data.Int32()) } // Div divides OperableData together func (i IntValue32) Div(data OperableData) Data { return IntValue32(int32(i) / data.Int32()) } // Mod modulus' OperableData together func (i IntValue32) Mod(data OperableData) Data { return IntValue32(int32(i) % data.Int32()) } // IntValues32 type alias for a slice of IntValue type IntValues32 []int32 func (i IntValues32) Data() []Data { d := make([]Data, len(i)) for j := range i { d[j] = IntValue32(i[j]) } return d } // IntValue64 type alias for int type IntValue64 int64 // Int casts and returns int value func (i IntValue64) Int() int { return int(i) } // Int32 casts and returns Int32 value func (i IntValue64) Int32() int32 { return int32(i) } // Int64 casts and returns Int64 value func (i IntValue64) Int64() int64 { return int64(i) } // Float32 casts and returns Float32 value func (i IntValue64) Float32() float32 { return float32(i) } // Float64 casts and returns Float64 value func (i IntValue64) Float64() float64 { return float64(i) } // String casts and returns string value func (i IntValue64) String() string { return strconv.Itoa(int(i)) } // Bool casts and returns bool func (i IntValue64) Bool() bool { if i == 0 { return false } return true } // Less compares the other data and returns true is it's less than self func (i IntValue64) Less(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int64(i) < other.Int64() case reflect.Float32, reflect.Float64: return int64(i) < int64(other.Float64()) case reflect.String: v, _ := strconv.Atoi(other.String()) return int64(i) < int64(v) } return false } // Equal compares the other data and returns true is the same as self's value, not self's value and type func (i IntValue64) Equal(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int64(i) == other.Int64() case reflect.Float32, reflect.Float64: return int64(i) == int64(other.Float64()) case reflect.String: v, _ := strconv.Atoi(other.String()) return int64(i) == int64(v) } return false } // Add adds OperableData together func (i IntValue64) Add(data OperableData) Data { return IntValue64(int64(i) + data.Int64()) } // Sub subtracts OperableData together func (i IntValue64) Sub(data OperableData) Data { return IntValue64(int64(i) - data.Int64()) } // Mul multiplies OperableData together func (i IntValue64) Mul(data OperableData) Data { return IntValue64(int64(i) * data.Int64()) } // Div divides OperableData together func (i IntValue64) Div(data OperableData) Data { return IntValue64(int64(i) / data.Int64()) } // Mod modulus' OperableData together func (i IntValue64) Mod(data OperableData) Data { return IntValue64(int64(i) % data.Int64()) } // Greater compares the other data and returns true is it's greater than self func (i IntValue64) Greater(other Data) bool { if i.Equal(other) { return false } return !i.Less(other) } // IntValues64 type alias for a slice of IntValue type IntValues64 []int64 func (i IntValues64) Data() []Data { d := make([]Data, len(i)) for j := range i { d[j] = IntValue64(i[j]) } return d } // FloatValue32 type alias for int type FloatValue32 float32 // Int casts and returns int value func (i FloatValue32) Int() int { return int(i) } // Int32 casts and returns Int32 value func (i FloatValue32) Int32() int32 { return int32(i) } // Int64 casts and returns Int64 value func (i FloatValue32) Int64() int64 { return int64(i) } // Float32 casts and returns Float32 value func (i FloatValue32) Float32() float32 { return float32(i) } // Float64 casts and returns Float64 value func (i FloatValue32) Float64() float64 { return float64(i) } // String casts and returns string value func (i FloatValue32) String() string { return strconv.FormatFloat(float64(i), 'f', -1, 32) } // Bool casts and returns bool func (i FloatValue32) Bool() bool { if i == 0.0 { return false } return true } // Less compares the other data and returns true is it's less than self func (i FloatValue32) Less(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return float32(i) < other.Float32() case reflect.Float32, reflect.Float64: return float32(i) < other.Float32() case reflect.String: v, _ := strconv.Atoi(other.String()) return float32(i) < float32(v) } return false } // Equal compares the other data and returns true is the same as self's value, not self's value and type func (i FloatValue32) Equal(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return float32(i) == other.Float32() case reflect.Float32, reflect.Float64: return float32(i) == other.Float32() case reflect.String: v, _ := strconv.Atoi(other.String()) return float32(i) == float32(v) } return false } // Greater compares the other data and returns true is it's greater than self func (i FloatValue32) Greater(other Data) bool { if i.Equal(other) { return false } return !i.Less(other) } // Add adds OperableData together func (i FloatValue32) Add(data OperableData) Data { return FloatValue32(float32(i) + data.Float32()) } // Sub subtracts OperableData together func (i FloatValue32) Sub(data OperableData) Data { return FloatValue32(float32(i) - data.Float32()) } // Mul multiplies OperableData together func (i FloatValue32) Mul(data OperableData) Data { return FloatValue32(float32(i) * data.Float32()) } // Div divides OperableData together func (i FloatValue32) Div(data OperableData) Data { return FloatValue32(float32(i) / data.Float32()) } // Mod modulus' OperableData together, **note** mod only works on integer values to floats are cast to ints first func (i FloatValue32) Mod(data OperableData) Data { return FloatValue32(int(i) % data.Int()) } // FloatValues32 type alias for a slice of IntValue type FloatValues32 []float32 func (i FloatValues32) Data() []Data { d := make([]Data, len(i)) for j := range i { d[j] = FloatValue32(i[j]) } return d } // FloatValue64 type alias for int type FloatValue64 float64 // Int casts and returns int value func (i FloatValue64) Int() int { return int(i) } // Int32 casts and returns Int32 value func (i FloatValue64) Int32() int32 { return int32(i) } // Int64 casts and returns Int64 value func (i FloatValue64) Int64() int64 { return int64(i) } // Float32 casts and returns Float32 value func (i FloatValue64) Float32() float32 { return float32(i) } // Float64 casts and returns Float64 value func (i FloatValue64) Float64() float64 { return float64(i) } // String casts and returns string value func (i FloatValue64) String() string { return strconv.FormatFloat(float64(i), 'f', -1, 64) } // Bool casts and returns bool func (i FloatValue64) Bool() bool { if i == 0.0 { return false } return true } // Less compares the other data and returns true is it's less than self func (i FloatValue64) Less(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return float64(i) < other.Float64() case reflect.Float32, reflect.Float64: return float64(i) < other.Float64() case reflect.String: v, _ := strconv.Atoi(other.String()) return float64(i) < float64(v) } return false } // Equal compares the other data and returns true is the same as self's value, not self's value and type func (i FloatValue64) Equal(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return float64(i) == other.Float64() case reflect.Float32, reflect.Float64: return float64(i) == other.Float64() case reflect.String: v, _ := strconv.Atoi(other.String()) return float64(i) == float64(v) } return false } // Greater compares the other data and returns true is it's greater than self func (i FloatValue64) Greater(other Data) bool { if i.Equal(other) { return false } return !i.Less(other) } // Add adds OperableData together func (i FloatValue64) Add(data OperableData) Data { return FloatValue64(float64(i) + data.Float64()) } // Sub subtracts OperableData together func (i FloatValue64) Sub(data OperableData) Data { return FloatValue64(float64(i) - data.Float64()) } // Mul multiplies OperableData together func (i FloatValue64) Mul(data OperableData) Data { return FloatValue64(float64(i) * data.Float64()) } // Div divides OperableData together func (i FloatValue64) Div(data OperableData) Data { return FloatValue64(float64(i) / data.Float64()) } // Mod modulus' OperableData together, **note** mod only works on integer values to floats are cast to ints first func (i FloatValue64) Mod(data OperableData) Data { return FloatValue64(int(i) % data.Int()) } // FloatValues64 type alias for a slice of IntValue type FloatValues64 []float32 func (i FloatValues64) Data() []Data { d := make([]Data, len(i)) for j := range i { d[j] = FloatValue64(i[j]) } return d } // StringValue type alias for string type StringValue string // Int casts and returns int value func (s StringValue) Int() int { n, _ := strconv.Atoi(string(s)) return n } // Int32 casts and returns Int32 value func (s StringValue) Int32() int32 { n, _ := strconv.Atoi(string(s)) return int32(n) } // Int64 casts and returns Int64 value func (s StringValue) Int64() int64 { n, _ := strconv.Atoi(string(s)) return int64(n) } // Float32 casts and returns Float32 value func (s StringValue) Float32() float32 { n, _ := strconv.ParseFloat(string(s), 32) return float32(n) } // Float64 casts and returns Float64 value func (s StringValue) Float64() float64 { n, _ := strconv.ParseFloat(string(s), 64) return n } // String casts and returns string value func (s StringValue) String() string { return string(s) } // Bool casts and returns bool func (s StringValue) Bool() bool { switch strings.ToLower(string(s)) { case "t", "true": return true } return false } // Less compares the other data and returns true is it's less than self func (s StringValue) Less(other Data) bool { v, _ := strconv.Atoi(string(s)) switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return v < other.Int() case reflect.Float32, reflect.Float64: return float64(v) < other.Float64() case reflect.String: return string(s) < other.String() } return false } // Equal compares the other data and returns true is the same as self's value, not self's value and type func (s StringValue) Equal(other Data) bool { v, _ := strconv.Atoi(string(s)) switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return v == other.Int() case reflect.Float32, reflect.Float64: return float64(v) == other.Float64() case reflect.String: return string(s) == other.String() } return false } // Greater compares the other data and returns true is it's greater than self func (s StringValue) Greater(other Data) bool { if s.Equal(other) { return false } return !s.Less(other) } // StringValues type alias for a slice of StringValue type StringValues []string func (s StringValues) Data() []Data { d := make([]Data, len(s)) for j := range s { d[j] = StringValue(s[j]) } return d } // RuneValue type alias for rune type RuneValue rune // Int casts and returns int value func (s RuneValue) Int() int { return int(s) } // Int32 casts and returns Int32 value func (s RuneValue) Int32() int32 { return int32(s) } // Int64 casts and returns Int64 value func (s RuneValue) Int64() int64 { return int64(s) } // Float32 casts and returns Float32 value func (s RuneValue) Float32() float32 { return float32(s) } // Float64 casts and returns Float64 value func (s RuneValue) Float64() float64 { return float64(s) } // String casts and returns string value func (s RuneValue) String() string { return string(s) } // Bool casts and returns bool func (s RuneValue) Bool() bool { switch unicode.ToLower(rune(s)) { case 't': return true } return false } // Less compares the other data and returns true is it's less than self func (s RuneValue) Less(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int32(s) < other.Int32() case reflect.Float32, reflect.Float64: return int32(s) < int32(other.Float64()) case reflect.String: return string(s) < other.String() } return false } // Equal compares the other data and returns true is the same as self's value, not self's value and type func (s RuneValue) Equal(other Data) bool { switch reflect.TypeOf(other).Kind() { case reflect.Int, reflect.Int32, reflect.Int64: return int32(s) == other.Int32() case reflect.Float32, reflect.Float64: return int32(s) == int32(other.Float64()) case reflect.String: return string(s) == other.String() } return false } // Greater compares the other data and returns true is it's greater than self func (s RuneValue) Greater(other Data) bool { if s.Equal(other) { return false } return !s.Less(other) } // Add adds OperableData together func (s RuneValue) Add(data OperableData) Data { return RuneValue(int32(s) + data.Int32()) } // Sub subtracts OperableData together func (s RuneValue) Sub(data OperableData) Data { return RuneValue(int32(s) - data.Int32()) } // Mul multiplies OperableData together func (s RuneValue) Mul(data OperableData) Data { return RuneValue(int32(s) * data.Int32()) } // Div divides OperableData together func (s RuneValue) Div(data OperableData) Data { return RuneValue(int32(s) / data.Int32()) } // Mod modulus' OperableData together, **note** mod only works on integer values to floats are cast to ints first func (s RuneValue) Mod(data OperableData) Data { return RuneValue(int(s) % data.Int()) } // RuneValues type alias for a slice of RuneValue type RuneValues []rune func (s RuneValues) Data() []Data { d := make([]Data, len(s)) for j := range s { d[j] = RuneValue(s[j]) } return d }
primitive_conversions.go
0.874158
0.514766
primitive_conversions.go
starcoder
package car_generic import ( m "github.com/niclabs/intersection-simulator/vehicle" "math" ) func (car *Car) GetPosition() m.Pos { return car.Position } func (car *Car) GetDirectionInRadians() float64 { return car.Direction * math.Pi / 180.0 } func (car *Car) Run(dt float64) { turnAngle := GetTurnAngle() car.Accelerate(dt) car.Forward(dt) car.Turn(dt, turnAngle) } func (car *Car) Forward(dt float64) { rad := car.Direction * (math.Pi / 180) posXDiff := math.Cos(rad) * car.Speed * dt // delta time posYDiff := math.Sin(rad) * car.Speed * dt car.Position.X += posXDiff car.Position.Y += posYDiff } func (car *Car) Accelerate(dt float64) { speedDiff := car.Acceleration * dt newSpeed := car.Speed + speedDiff if newSpeed > MaxSpeed { newSpeed = MaxSpeed } else if newSpeed < MinSpeed { newSpeed = MinSpeed } car.Speed = newSpeed } /* Changes the direction toward a 90 degree turn so it heads to the corresponding exit lane */ func (car *Car) ChangeDirection(dt, turnAngle float64) { // See the proportion between the covered distance and the initial distance until entering and exiting the danger zone startPos := GetEnterPosition(car.Lane, car.CoopZoneLength, car.DangerZoneLength) endPos := GetEndPosition(car.Lane, car.Intention, car.CoopZoneLength, car.DangerZoneLength) curPos := car.GetPosition() turnCenterPos := GetCenterOfTurn(startPos, endPos, car) coveredAngle := m.GetInsideAngle(startPos, turnCenterPos, curPos) dirChange := math.Abs(coveredAngle - car.ChangedAngle) if car.ChangedAngle < turnAngle { car.ChangedAngle += dirChange if car.Intention == LeftIntention { car.Direction += dirChange } else { car.Direction -= dirChange } } if car.Direction < 0 { car.Direction = 360 + car.Direction } else { car.Direction = math.Mod(car.Direction, 360) } } /* Checks if the car is inside the intersection. Possible collision zone. */ func checkTurnCondition(car *Car) bool { A, B, C, D := GetDangerZoneCoords(car.DangerZoneLength, car.CoopZoneLength) return IsInsideDangerZone(A, B, C, D, car.Position) } /* Checks if the car needs to turn depending of what amount of the turnAngle it has covered. In a four-way intersection this angle is 90 degrees. */ func (car *Car) Turn(dt, turnAngle float64) { if car.Intention != StraightIntention { if checkTurnCondition(car) { car.ChangeDirection(dt, turnAngle) } else { if 0 < car.ChangedAngle && car.ChangedAngle != turnAngle { car.ChangedAngle = turnAngle if car.Intention == LeftIntention { car.Direction = GetStartDirection(car.Lane) + turnAngle } else { car.Direction = GetStartDirection(car.Lane) - turnAngle } } } } }
vehicle/car_generic/dynamics.go
0.766643
0.436622
dynamics.go
starcoder
package gblur import ( "image" "image/color" "math" ) // GaussianKernel returns a gaussian filter of size sz x sz with sigma standard deviation func GaussianKernel(sz int, sigma float64) [][]float64 { filter := make([][]float64, sz) for i := range filter { filter[i] = make([]float64, sz) } var sum float64 // generate kernel s := 2 * sigma * sigma delta := sz / 2 for x := -delta; x <= delta; x++ { for y := -delta; y <= delta; y++ { r := float64(x*x) + float64(y*y) filter[x+delta][y+delta] = math.Exp(-(r)/s) / (s * math.Pi) sum += filter[x+delta][y+delta] } } // normalize the kernel for i := range filter { for j := range filter[i] { filter[i][j] /= sum } } return filter } // BoundReflection returns a reflected index on the interval [min, max) func BoundReflection(idx, min, max int) int { if idx < min { return -idx - 1 } if idx >= max { return 2*max - idx - 1 } return idx } // ConvolvePixel apply the specified filter to the pixel at coordinates (x, y) func ConvolvePixel(img image.NRGBA, x, y int, filter [][]float64) color.NRGBA { var r, g, b, a float64 delta := len(filter) / 2 for k := -delta; k <= delta; k++ { for j := -delta; j <= delta; j++ { // reflect index to avoid errors at image borders boundedX := BoundReflection(x-j, img.Bounds().Min.X, img.Bounds().Max.X) boundedY := BoundReflection(y-k, img.Bounds().Min.Y, img.Bounds().Max.Y) color := img.NRGBAAt(boundedX, boundedY) r += float64(color.R) * filter[j+delta][k+delta] g += float64(color.G) * filter[j+delta][k+delta] b += float64(color.B) * filter[j+delta][k+delta] a += float64(color.A) * filter[j+delta][k+delta] } } return color.NRGBA{ R: uint8(r), G: uint8(g), B: uint8(b), A: uint8(a), } } // Convolve apply the specified filter to the image with a 2D convolution func Convolve(img image.NRGBA, filter [][]float64) *image.NRGBA { dst := image.NewNRGBA(img.Bounds()) for y := 0; y < img.Bounds().Max.Y; y++ { for x := 0; x < img.Bounds().Max.X; x++ { dst.SetNRGBA(x, y, ConvolvePixel(img, x, y, filter)) } } return dst } // ToNRGBA creates a copy of img converting its format in NRGBA (non-alpha-premultiplied 32-bit color) func ToNRGBA(img image.Image) *image.NRGBA { dst := image.NewNRGBA(img.Bounds()) for y := 0; y < img.Bounds().Max.Y; y++ { for x := 0; x < img.Bounds().Max.X; x++ { dst.SetNRGBA(x, y, color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA)) } } return dst }
05-scheduler/gaussianblur/gblur/gblur.go
0.889834
0.548794
gblur.go
starcoder
package tree import ( "fmt" "github.com/sap200/binarytree/node" ) type BST struct { root *node.TreeNode size int } // Creates a new binary tree func NewBST() *BST { return &BST{ root: nil, size: 0, } } func CreateBST(el []node.Comparable) *BST { bst := NewBST() for i := 0; i < len(el); i++ { bst.Insert(el[i]) } return bst } func (bst *BST) Search(e node.Comparable) bool { current := bst.root for current != nil { if e.CompareTo(current.Element) < 0 { // element lesser traverse left subtree current = current.LeftNode } else if e.CompareTo(current.Element) > 0 { // element greater traverse right subtree current = current.RightNode } else { // element found return true } } return false } // Inserts a node in binary tree func (bst *BST) Insert(e node.Comparable) bool { if bst.GetRoot() == nil { bst.root = node.NewTreeNode(e) bst.size++ return true } // finds the location of parent and inserts var parent *node.TreeNode current := bst.root for current != nil { if e.CompareTo(current.Element) < 0 { parent = current current = parent.LeftNode } else if e.CompareTo(current.Element) > 0 { parent = current current = parent.RightNode } else { // duplicate element found return false } } // parent found if e.CompareTo(parent.Element) < 0 { // e less than parent element parent.LeftNode = node.NewTreeNode(e) } else { // e greater than parent node parent.RightNode = node.NewTreeNode(e) } bst.size++ return true } // delete an element func (bst *BST) Delete(e node.Comparable) bool { // Locate the position of to be deleted node and its parent var parent *node.TreeNode current := bst.root for current != nil { if e.CompareTo(current.Element) < 0 { parent = current current = parent.LeftNode } else if e.CompareTo(current.Element) > 0 { parent = current current = parent.RightNode } else { // position of element found break } } // If current is nil then element doesn't exists if current == nil { return false } // case 1 // Left subtree doesn't exists for current node if current.LeftNode == nil { // delete current node // attach right subtree to parent if parent == nil { bst.root = current.RightNode } else { if e.CompareTo(parent.Element) < 0 { // connect to left node of parent parent.LeftNode = current.RightNode } else { parent.RightNode = current.RightNode } } } else { // case 2 // Find rightmost element parentOfRightMost := current rightMost := current.LeftNode for rightMost.RightNode != nil { parentOfRightMost = rightMost rightMost = parentOfRightMost.RightNode } // Replace current Element with rightmost current.Element = rightMost.Element // Delete Rightmost Element if parentOfRightMost.RightNode == rightMost { // then rightmost is not current parentOfRightMost.RightNode = rightMost.LeftNode } else { // current is rightmost parentOfRightMost.LeftNode = rightMost.LeftNode } } bst.size-- return true } // Traversal methods // inorder is a recursive helper function func inorder(node *node.TreeNode) { if node == nil { return } inorder(node.LeftNode) fmt.Print(node.Element, " ") inorder(node.RightNode) } // It calls the inorder function for inorder traversal func (b *BST) Inorder() { inorder(b.GetRoot()) } // preorder is a helper function for preorder traversal func preorder(node *node.TreeNode) { if node == nil { return } fmt.Print(node.Element, " ") preorder(node.LeftNode) preorder(node.RightNode) } // Preorder calls the preorder function func (bst *BST) Preorder() { preorder(bst.GetRoot()) } // postorder is a helper function for postorder traversal func postorder(node *node.TreeNode) { if node == nil { return } preorder(node.LeftNode) preorder(node.RightNode) fmt.Print(node.Element, " ") } // Postorder calls the postorder function func (bst *BST) Postorder() { postorder(bst.GetRoot()) } // Utilities function // Returns the size of binary tree func (b *BST) GetSize() int { return b.size } // checks if the binary tree is empty returns true on not empty func (b *BST) IsEmpty() bool { return b.GetSize() == 0 } // clears the binary tree func (b *BST) Clear() { b.size = 0 b.root = nil } // returns the root of binary tree func (bst *BST) GetRoot() *node.TreeNode { return bst.root } // Helper function for sorting func sorted(node *node.TreeNode, list *[]node.Comparable) { if node == nil { return } sorted(node.LeftNode, list) *list = append(*list, node.Element) sorted(node.RightNode, list) } // Returns a list of sorted node func (bst *BST) Sorted() []node.Comparable { list := &[]node.Comparable{} sorted(bst.GetRoot(), list) return *list } // Print Binary tree func (tree *BST) Print() { // Traverse tree fmt.Print("Inorder (sorted): ") tree.Inorder() fmt.Print("\nPostorder: ") tree.Postorder() fmt.Print("\nPreorder: ") tree.Preorder() fmt.Print("\nThe number of nodes is ", tree.GetSize()) fmt.Println() }
tree/bst.go
0.726911
0.483222
bst.go
starcoder
package main import ( "flag" "fmt" "math" "runtime" "sort" ) // Note, the standard "image" package has Point and Rectangle but we // can't use them here since they're defined using int rather than // float64. type Circle struct{ X, Y, R, rsq float64 } func NewCircle(x, y, r float64) Circle { // We pre-calculate r² as an optimization return Circle{x, y, r, r * r} } func (c Circle) ContainsPt(x, y float64) bool { return distSq(x, y, c.X, c.Y) <= c.rsq } func (c Circle) ContainsC(c2 Circle) bool { return distSq(c.X, c.Y, c2.X, c2.Y) <= (c.R-c2.R)*(c.R-c2.R) } func (c Circle) ContainsR(r Rect) (full, corner bool) { nw := c.ContainsPt(r.NW()) ne := c.ContainsPt(r.NE()) sw := c.ContainsPt(r.SW()) se := c.ContainsPt(r.SE()) return nw && ne && sw && se, nw || ne || sw || se } func (c Circle) North() (float64, float64) { return c.X, c.Y + c.R } func (c Circle) South() (float64, float64) { return c.X, c.Y - c.R } func (c Circle) West() (float64, float64) { return c.X - c.R, c.Y } func (c Circle) East() (float64, float64) { return c.X + c.R, c.Y } type Rect struct{ X1, Y1, X2, Y2 float64 } func (r Rect) Area() float64 { return (r.X2 - r.X1) * (r.Y2 - r.Y1) } func (r Rect) NW() (float64, float64) { return r.X1, r.Y2 } func (r Rect) NE() (float64, float64) { return r.X2, r.Y2 } func (r Rect) SW() (float64, float64) { return r.X1, r.Y1 } func (r Rect) SE() (float64, float64) { return r.X2, r.Y1 } func (r Rect) Centre() (float64, float64) { return (r.X1 + r.X2) / 2.0, (r.Y1 + r.Y2) / 2.0 } func (r Rect) ContainsPt(x, y float64) bool { return r.X1 <= x && x < r.X2 && r.Y1 <= y && y < r.Y2 } func (r Rect) ContainsPC(c Circle) bool { // only N,W,E,S points of circle return r.ContainsPt(c.North()) || r.ContainsPt(c.South()) || r.ContainsPt(c.West()) || r.ContainsPt(c.East()) } func (r Rect) MinSide() float64 { return math.Min(r.X2-r.X1, r.Y2-r.Y1) } func distSq(x1, y1, x2, y2 float64) float64 { Δx, Δy := x2-x1, y2-y1 return (Δx * Δx) + (Δy * Δy) } type CircleSet []Circle // sort.Interface for sorting by radius big to small: func (s CircleSet) Len() int { return len(s) } func (s CircleSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s CircleSet) Less(i, j int) bool { return s[i].R > s[j].R } func (sp *CircleSet) RemoveContainedC() { s := *sp sort.Sort(s) for i := 0; i < len(s); i++ { for j := i + 1; j < len(s); { if s[i].ContainsC(s[j]) { s[j], s[len(s)-1] = s[len(s)-1], s[j] s = s[:len(s)-1] } else { j++ } } } *sp = s } func (s CircleSet) Bounds() Rect { x1 := s[0].X - s[0].R x2 := s[0].X + s[0].R y1 := s[0].Y - s[0].R y2 := s[0].Y + s[0].R for _, c := range s[1:] { x1 = math.Min(x1, c.X-c.R) x2 = math.Max(x2, c.X+c.R) y1 = math.Min(y1, c.Y-c.R) y2 = math.Max(y2, c.Y+c.R) } return Rect{x1, y1, x2, y2} } var nWorkers = 4 func (s CircleSet) UnionArea(ε float64) (min, max float64) { sort.Sort(s) stop := make(chan bool) inside := make(chan Rect) outside := make(chan Rect) unknown := make(chan Rect, 5e7) // XXX for i := 0; i < nWorkers; i++ { go s.worker(stop, unknown, inside, outside) } r := s.Bounds() max = r.Area() unknown <- r for max-min > ε { select { case r = <-inside: min += r.Area() case r = <-outside: max -= r.Area() } } close(stop) return min, max } func (s CircleSet) worker(stop <-chan bool, unk chan Rect, in, out chan<- Rect) { for { select { case <-stop: return case r := <-unk: inside, outside := s.CategorizeR(r) switch { case inside: in <- r case outside: out <- r default: // Split midX, midY := r.Centre() unk <- Rect{r.X1, r.Y1, midX, midY} unk <- Rect{midX, r.Y1, r.X2, midY} unk <- Rect{r.X1, midY, midX, r.Y2} unk <- Rect{midX, midY, r.X2, r.Y2} } } } } func (s CircleSet) CategorizeR(r Rect) (inside, outside bool) { anyCorner := false for _, c := range s { full, corner := c.ContainsR(r) if full { return true, false // inside } anyCorner = anyCorner || corner } if anyCorner { return false, false // uncertain } for _, c := range s { if r.ContainsPC(c) { return false, false // uncertain } } return false, true // outside } func main() { flag.IntVar(&nWorkers, "workers", nWorkers, "how many worker go routines to use") maxproc := flag.Int("cpu", runtime.NumCPU(), "GOMAXPROCS setting") flag.Parse() if *maxproc > 0 { runtime.GOMAXPROCS(*maxproc) } else { *maxproc = runtime.GOMAXPROCS(0) } circles := CircleSet{ NewCircle(1.6417233788, 1.6121789534, 0.0848270516), NewCircle(-1.4944608174, 1.2077959613, 1.1039549836), NewCircle(0.6110294452, -0.6907087527, 0.9089162485), NewCircle(0.3844862411, 0.2923344616, 0.2375743054), NewCircle(-0.2495892950, -0.3832854473, 1.0845181219), NewCircle(1.7813504266, 1.6178237031, 0.8162655711), NewCircle(-0.1985249206, -0.8343333301, 0.0538864941), NewCircle(-1.7011985145, -0.1263820964, 0.4776976918), NewCircle(-0.4319462812, 1.4104420482, 0.7886291537), NewCircle(0.2178372997, -0.9499557344, 0.0357871187), NewCircle(-0.6294854565, -1.3078893852, 0.7653357688), NewCircle(1.7952608455, 0.6281269104, 0.2727652452), NewCircle(1.4168575317, 1.0683357171, 1.1016025378), NewCircle(1.4637371396, 0.9463877418, 1.1846214562), NewCircle(-0.5263668798, 1.7315156631, 1.4428514068), NewCircle(-1.2197352481, 0.9144146579, 1.0727263474), NewCircle(-0.1389358881, 0.1092805780, 0.7350208828), NewCircle(1.5293954595, 0.0030278255, 1.2472867347), NewCircle(-0.5258728625, 1.3782633069, 1.3495508831), NewCircle(-0.1403562064, 0.2437382535, 1.3804956588), NewCircle(0.8055826339, -0.0482092025, 0.3327165165), NewCircle(-0.6311979224, 0.7184578971, 0.2491045282), NewCircle(1.4685857879, -0.8347049536, 1.3670667538), NewCircle(-0.6855727502, 1.6465021616, 1.0593087096), NewCircle(0.0152957411, 0.0638919221, 0.9771215985), } fmt.Println("Starting with", len(circles), "circles.") circles.RemoveContainedC() fmt.Println("Removing redundant ones leaves", len(circles), "circles.") fmt.Println("Using", nWorkers, "workers with maxprocs =", *maxproc) const ε = 0.0001 min, max := circles.UnionArea(ε) avg := (min + max) / 2.0 rng := max - min fmt.Printf("Area = %v±%v\n", avg, rng) fmt.Printf("Area ≈ %.*f\n", 5, avg) } //\Total-circles-area\total-circles-area.go
tasks/Total-circles-area/total-circles-area.go
0.68595
0.406096
total-circles-area.go
starcoder
package cspacegen import ( "encoding/json" "fmt" "math" ) // point struct to serialize. type point struct { X, Y, Z float64 } // triangle struct to serialize. type triangle struct { First, Second, Third int } // obstacle struct to serialize. type obstacle struct { Vertex []point Facet []triangle } // cspace struct to serialize. type cspace struct { Description string Vertex []point Start point Finish point Obstacle []obstacle } // vectorSubtraction returns result of a - b. func vectorSubtraction(a, b point) point { result := a result.X -= b.X result.Y -= b.Y result.Z -= b.Z return result } // serializationPointsToFacet returns STL facet as string. func serializationPointsToFacet(a, b, c point) string { ab := vectorSubtraction(b, a) bc := vectorSubtraction(c, b) normal := b normal.X = ab.Y*bc.Z - ab.Z*bc.Y normal.Y = ab.Z*bc.X - ab.X*bc.Z normal.Z = ab.X*bc.Y - ab.Y*bc.X length := math.Sqrt(normal.X*normal.X + normal.Y*normal.Y + normal.Z*normal.Z) if length == 0 { normal.X = 0 normal.Y = 0 normal.Z = 0 } else { normal.X /= length normal.Y /= length normal.Z /= length } result := fmt.Sprintf(" facet normal %e %e %e\n outer loop\n", normal.X, normal.Y, normal.Z) result += fmt.Sprintf(" vertex %e %e %e\n", a.X, a.Y, a.Z) result += fmt.Sprintf(" vertex %e %e %e\n", b.X, b.Y, b.Z) result += fmt.Sprintf(" vertex %e %e %e\n", c.X, c.Y, c.Z) result += " endloop\n endfacet\n" return result } // SerializeToJSON returns serialized JSON or error. func (c *CSpace) SerializeToJSON() (string, error) { vertex := make([]point, 0, 8) vertex = append(vertex, point{0, 0, 0}) vertex = append(vertex, point{c.dimension[X], 0, 0}) vertex = append(vertex, point{c.dimension[X], c.dimension[Y], 0}) vertex = append(vertex, point{0, c.dimension[Y], 0}) vertex = append(vertex, point{0, c.dimension[Y], c.dimension[Z]}) vertex = append(vertex, point{0, 0, c.dimension[Z]}) vertex = append(vertex, point{c.dimension[X], 0, c.dimension[Z]}) vertex = append(vertex, point{c.dimension[X], c.dimension[Y], c.dimension[Z]}) obstacles := make([]obstacle, 0) for _, o := range c.obstacles { obstacles = append(obstacles, o.toStruct()) } space := cspace{c.description, vertex, c.start.toStruct(), c.finish.toStruct(), obstacles} result, err := json.Marshal(space) if err != nil { return "", err } return string(result), nil } // SerializeToSTL returns serialized ASCII STL or error. func (c *CSpace) SerializeToSTL() (string, error) { vertex := make([]point, 0, 8) vertex = append(vertex, point{0, 0, 0}) vertex = append(vertex, point{c.dimension[X], 0, 0}) vertex = append(vertex, point{c.dimension[X], c.dimension[Y], 0}) vertex = append(vertex, point{0, c.dimension[Y], 0}) vertex = append(vertex, point{0, c.dimension[Y], c.dimension[Z]}) vertex = append(vertex, point{0, 0, c.dimension[Z]}) vertex = append(vertex, point{c.dimension[X], 0, c.dimension[Z]}) vertex = append(vertex, point{c.dimension[X], c.dimension[Y], c.dimension[Z]}) result := "solid " + c.description + "\n" // borders result += serializationPointsToFacet(vertex[0], vertex[1], vertex[2]) result += serializationPointsToFacet(vertex[2], vertex[3], vertex[0]) result += serializationPointsToFacet(vertex[3], vertex[4], vertex[5]) result += serializationPointsToFacet(vertex[5], vertex[0], vertex[3]) result += serializationPointsToFacet(vertex[0], vertex[5], vertex[6]) result += serializationPointsToFacet(vertex[6], vertex[1], vertex[0]) result += serializationPointsToFacet(vertex[1], vertex[6], vertex[7]) result += serializationPointsToFacet(vertex[7], vertex[2], vertex[1]) result += serializationPointsToFacet(vertex[2], vertex[7], vertex[4]) result += serializationPointsToFacet(vertex[4], vertex[3], vertex[2]) result += serializationPointsToFacet(vertex[4], vertex[7], vertex[6]) result += serializationPointsToFacet(vertex[6], vertex[5], vertex[4]) // begin and end points result += serializationPointsToFacet(c.start.toStruct(), c.start.toStruct(), c.start.toStruct()) result += serializationPointsToFacet(c.finish.toStruct(), c.finish.toStruct(), c.finish.toStruct()) // obstacles for _, obstacle := range c.obstacles { o := obstacle.toStruct() for _, f := range o.Facet { result += serializationPointsToFacet(o.Vertex[f.First], o.Vertex[f.Second], o.Vertex[f.Third]) } } result += "endsolid " return result, nil } // toStruct converts Point3D to serializable struct. func (p *Point3D) toStruct() point { return point{(*p)[X], (*p)[Y], (*p)[Z]} } // toStruct converts Obstacle to serializable struct. func (o *Obstacle) toStruct() obstacle { edge := make([]point, 0) for _, p := range o.points() { edge = append(edge, p.toStruct()) } facet := make([]triangle, 0, 0) index := 7 if _, ok := o.centerPoint[8]; ok { index++ facet = append(facet, triangle{0, 3, index}) facet = append(facet, triangle{0, index, 1}) facet = append(facet, triangle{1, index, 2}) facet = append(facet, triangle{2, index, 3}) } else { facet = append(facet, triangle{0, 3, 2}) facet = append(facet, triangle{0, 2, 1}) } if _, ok := o.centerPoint[9]; ok { index++ facet = append(facet, triangle{6, 5, index}) facet = append(facet, triangle{6, index, 1}) facet = append(facet, triangle{1, index, 0}) facet = append(facet, triangle{0, index, 5}) } else { facet = append(facet, triangle{6, 5, 0}) facet = append(facet, triangle{6, 0, 1}) } if _, ok := o.centerPoint[10]; ok { index++ facet = append(facet, triangle{1, 2, index}) facet = append(facet, triangle{1, index, 6}) facet = append(facet, triangle{6, index, 7}) facet = append(facet, triangle{7, index, 2}) } else { facet = append(facet, triangle{1, 2, 7}) facet = append(facet, triangle{1, 7, 6}) } if _, ok := o.centerPoint[11]; ok { index++ facet = append(facet, triangle{2, 3, index}) facet = append(facet, triangle{2, index, 7}) facet = append(facet, triangle{7, index, 4}) facet = append(facet, triangle{4, index, 3}) } else { facet = append(facet, triangle{2, 3, 4}) facet = append(facet, triangle{2, 4, 7}) } if _, ok := o.centerPoint[12]; ok { index++ facet = append(facet, triangle{5, 4, index}) facet = append(facet, triangle{5, index, 0}) facet = append(facet, triangle{0, index, 3}) facet = append(facet, triangle{3, index, 4}) } else { facet = append(facet, triangle{5, 4, 3}) facet = append(facet, triangle{5, 3, 0}) } if _, ok := o.centerPoint[13]; ok { index++ facet = append(facet, triangle{4, 5, index}) facet = append(facet, triangle{4, index, 7}) facet = append(facet, triangle{7, index, 6}) facet = append(facet, triangle{6, index, 5}) } else { facet = append(facet, triangle{4, 5, 6}) facet = append(facet, triangle{4, 6, 7}) } return obstacle{edge, facet} }
generator/cspacegen/cspacegen_serialization.go
0.702734
0.473718
cspacegen_serialization.go
starcoder
package neural import ( "crypto/rand" "math/big" ) // Neuron is a set of weights + bias linked to a layer type Neuron struct { MaxInputs int `json:"-"` Weights []float64 `json:"Weights"` Bias float64 `json:"Bias"` // Previous momentum of every weight and bias Momentums []float64 `json:"-"` // Layer to which neuron is linked Layer *Layer `json:"-"` activation float64 delta float64 error float64 Inputs []float64 `json:"-"` } // NewNeuron creates a neuron linked to a layer func NewNeuron(Layer *Layer, MaxInputs int) *Neuron { neuron := &Neuron{ MaxInputs: MaxInputs, Weights: make([]float64, MaxInputs), Bias: randomFloat(-1.0, 1.0), Momentums: make([]float64, MaxInputs+1), Layer: Layer, Inputs: make([]float64, MaxInputs), } for i := 0; i < neuron.MaxInputs; i++ { neuron.Weights[i] = randomFloat(-1.0, 1.0) } return neuron } // Think process the neuron forward based on inputs func (neuron *Neuron) Think(inputs []float64) float64 { sum := neuron.Bias for i := 0; i < neuron.MaxInputs; i++ { sum += inputs[i] * neuron.Weights[i] neuron.Inputs[i] = inputs[i] } neuron.activation = neuron.Layer.Forward(sum) return neuron.activation } // Optimizer learning by momentum func (neuron *Neuron) Optimizer(index int, value float64) float64 { neuron.Momentums[index] = value + (neuron.Layer.Momentum * neuron.Momentums[index]) return neuron.Momentums[index] } // Clone neuron with same weights, bias, etc func (neuron *Neuron) Clone() *Neuron { clone := NewNeuron(neuron.Layer, neuron.MaxInputs) for i := 0; i < neuron.MaxInputs; i++ { clone.Weights[i] = neuron.Weights[i] } clone.Bias = neuron.Bias return clone } // Mutate randomizing weights/bias based on probability func (neuron *Neuron) Mutate(probability float64) { for i := 0; i < neuron.MaxInputs; i++ { if probability >= cryptoRandomFloat() { neuron.Weights[i] += randomFloat(-1.0, 1.0) neuron.Momentums[i] = 0.0 } } if probability >= cryptoRandomFloat() { neuron.Bias += randomFloat(-1.0, 1.0) neuron.Momentums[neuron.MaxInputs] = 0.0 } } // Crossover two neurons merging weights and bias func (neuron *Neuron) Crossover(neuronB Neuron, dominant float64) *Neuron { new := NewNeuron(neuron.Layer, neuron.MaxInputs) for i := 0; i < new.MaxInputs; i++ { if cryptoRandomFloat() >= 0.5 { new.Weights[i] = neuron.Weights[i] } else { new.Weights[i] = neuronB.Weights[i] } } if cryptoRandomFloat() >= 0.5 { new.Bias = neuron.Bias } else { new.Bias = neuronB.Bias } return new } // Reset weights, bias and momentums func (neuron *Neuron) Reset() { for i := 0; i < neuron.MaxInputs; i++ { neuron.Weights[i] = randomFloat(-1.0, 1.0) neuron.Momentums[i] = 0.0 } neuron.Bias = randomFloat(-1.0, 1.0) neuron.Momentums[neuron.MaxInputs] = 0.0 } func randomFloat(min float64, max float64) float64 { return min + cryptoRandomFloat()*(max-min) } func cryptoRandomFloat() float64 { num, err := rand.Int(rand.Reader, big.NewInt(1e17)) if err != nil { panic(err) } return float64(num.Int64()) / float64(1e17) } func randomInt(max int64) int { num, err := rand.Int(rand.Reader, big.NewInt(max)) if err != nil { panic(err) } return int(num.Int64()) }
neuron.go
0.802633
0.588268
neuron.go
starcoder
package cryptoapis import ( "encoding/json" ) // ListTokensTransfersByTransactionHashRI struct for ListTokensTransfersByTransactionHashRI type ListTokensTransfersByTransactionHashRI struct { // Represents the contract address of the token, which controls its logic. It is not the address that holds the tokens. ContractAddress string `json:"contractAddress"` // Defines the block height in which this transaction was confirmed/mined. MinedInBlockHeight int32 `json:"minedInBlockHeight"` // Defines the address to which the recipient receives the transferred tokens. RecipientAddress string `json:"recipientAddress"` // Defines the address from which the sender transfers tokens. SenderAddress string `json:"senderAddress"` // Defines the decimals of the token, i.e. the number of digits that come after the decimal coma of the token. TokenDecimals int32 `json:"tokenDecimals"` // Defines the token's name as a string. TokenName string `json:"tokenName"` // Defines the token symbol by which the token contract is known. It is usually 3-4 characters in length. TokenSymbol string `json:"tokenSymbol"` // Defines the specific token type. TokenType string `json:"tokenType"` // Defines the token amount of the transfer. TokensAmount string `json:"tokensAmount"` // Represents the hash of the transaction, which is its unique identifier. It represents a cryptographic digital fingerprint made by hashing the block header twice through the SHA256 algorithm. TransactionHash string `json:"transactionHash"` // Defines the specific time/date when the transaction was created in Unix Timestamp. TransactionTimestamp int32 `json:"transactionTimestamp"` } // NewListTokensTransfersByTransactionHashRI instantiates a new ListTokensTransfersByTransactionHashRI 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 NewListTokensTransfersByTransactionHashRI(contractAddress string, minedInBlockHeight int32, recipientAddress string, senderAddress string, tokenDecimals int32, tokenName string, tokenSymbol string, tokenType string, tokensAmount string, transactionHash string, transactionTimestamp int32) *ListTokensTransfersByTransactionHashRI { this := ListTokensTransfersByTransactionHashRI{} this.ContractAddress = contractAddress this.MinedInBlockHeight = minedInBlockHeight this.RecipientAddress = recipientAddress this.SenderAddress = senderAddress this.TokenDecimals = tokenDecimals this.TokenName = tokenName this.TokenSymbol = tokenSymbol this.TokenType = tokenType this.TokensAmount = tokensAmount this.TransactionHash = transactionHash this.TransactionTimestamp = transactionTimestamp return &this } // NewListTokensTransfersByTransactionHashRIWithDefaults instantiates a new ListTokensTransfersByTransactionHashRI 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 NewListTokensTransfersByTransactionHashRIWithDefaults() *ListTokensTransfersByTransactionHashRI { this := ListTokensTransfersByTransactionHashRI{} return &this } // GetContractAddress returns the ContractAddress field value func (o *ListTokensTransfersByTransactionHashRI) GetContractAddress() string { if o == nil { var ret string return ret } return o.ContractAddress } // GetContractAddressOk returns a tuple with the ContractAddress field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetContractAddressOk() (*string, bool) { if o == nil { return nil, false } return &o.ContractAddress, true } // SetContractAddress sets field value func (o *ListTokensTransfersByTransactionHashRI) SetContractAddress(v string) { o.ContractAddress = v } // GetMinedInBlockHeight returns the MinedInBlockHeight field value func (o *ListTokensTransfersByTransactionHashRI) GetMinedInBlockHeight() int32 { if o == nil { var ret int32 return ret } return o.MinedInBlockHeight } // GetMinedInBlockHeightOk returns a tuple with the MinedInBlockHeight field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetMinedInBlockHeightOk() (*int32, bool) { if o == nil { return nil, false } return &o.MinedInBlockHeight, true } // SetMinedInBlockHeight sets field value func (o *ListTokensTransfersByTransactionHashRI) SetMinedInBlockHeight(v int32) { o.MinedInBlockHeight = v } // GetRecipientAddress returns the RecipientAddress field value func (o *ListTokensTransfersByTransactionHashRI) GetRecipientAddress() string { if o == nil { var ret string return ret } return o.RecipientAddress } // GetRecipientAddressOk returns a tuple with the RecipientAddress field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetRecipientAddressOk() (*string, bool) { if o == nil { return nil, false } return &o.RecipientAddress, true } // SetRecipientAddress sets field value func (o *ListTokensTransfersByTransactionHashRI) SetRecipientAddress(v string) { o.RecipientAddress = v } // GetSenderAddress returns the SenderAddress field value func (o *ListTokensTransfersByTransactionHashRI) GetSenderAddress() string { if o == nil { var ret string return ret } return o.SenderAddress } // GetSenderAddressOk returns a tuple with the SenderAddress field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetSenderAddressOk() (*string, bool) { if o == nil { return nil, false } return &o.SenderAddress, true } // SetSenderAddress sets field value func (o *ListTokensTransfersByTransactionHashRI) SetSenderAddress(v string) { o.SenderAddress = v } // GetTokenDecimals returns the TokenDecimals field value func (o *ListTokensTransfersByTransactionHashRI) GetTokenDecimals() int32 { if o == nil { var ret int32 return ret } return o.TokenDecimals } // GetTokenDecimalsOk returns a tuple with the TokenDecimals field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetTokenDecimalsOk() (*int32, bool) { if o == nil { return nil, false } return &o.TokenDecimals, true } // SetTokenDecimals sets field value func (o *ListTokensTransfersByTransactionHashRI) SetTokenDecimals(v int32) { o.TokenDecimals = v } // GetTokenName returns the TokenName field value func (o *ListTokensTransfersByTransactionHashRI) GetTokenName() string { if o == nil { var ret string return ret } return o.TokenName } // GetTokenNameOk returns a tuple with the TokenName field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetTokenNameOk() (*string, bool) { if o == nil { return nil, false } return &o.TokenName, true } // SetTokenName sets field value func (o *ListTokensTransfersByTransactionHashRI) SetTokenName(v string) { o.TokenName = v } // GetTokenSymbol returns the TokenSymbol field value func (o *ListTokensTransfersByTransactionHashRI) GetTokenSymbol() string { if o == nil { var ret string return ret } return o.TokenSymbol } // GetTokenSymbolOk returns a tuple with the TokenSymbol field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetTokenSymbolOk() (*string, bool) { if o == nil { return nil, false } return &o.TokenSymbol, true } // SetTokenSymbol sets field value func (o *ListTokensTransfersByTransactionHashRI) SetTokenSymbol(v string) { o.TokenSymbol = v } // GetTokenType returns the TokenType field value func (o *ListTokensTransfersByTransactionHashRI) GetTokenType() string { if o == nil { var ret string return ret } return o.TokenType } // GetTokenTypeOk returns a tuple with the TokenType field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetTokenTypeOk() (*string, bool) { if o == nil { return nil, false } return &o.TokenType, true } // SetTokenType sets field value func (o *ListTokensTransfersByTransactionHashRI) SetTokenType(v string) { o.TokenType = v } // GetTokensAmount returns the TokensAmount field value func (o *ListTokensTransfersByTransactionHashRI) GetTokensAmount() string { if o == nil { var ret string return ret } return o.TokensAmount } // GetTokensAmountOk returns a tuple with the TokensAmount field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetTokensAmountOk() (*string, bool) { if o == nil { return nil, false } return &o.TokensAmount, true } // SetTokensAmount sets field value func (o *ListTokensTransfersByTransactionHashRI) SetTokensAmount(v string) { o.TokensAmount = v } // GetTransactionHash returns the TransactionHash field value func (o *ListTokensTransfersByTransactionHashRI) GetTransactionHash() string { if o == nil { var ret string return ret } return o.TransactionHash } // GetTransactionHashOk returns a tuple with the TransactionHash field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetTransactionHashOk() (*string, bool) { if o == nil { return nil, false } return &o.TransactionHash, true } // SetTransactionHash sets field value func (o *ListTokensTransfersByTransactionHashRI) SetTransactionHash(v string) { o.TransactionHash = v } // GetTransactionTimestamp returns the TransactionTimestamp field value func (o *ListTokensTransfersByTransactionHashRI) GetTransactionTimestamp() int32 { if o == nil { var ret int32 return ret } return o.TransactionTimestamp } // GetTransactionTimestampOk returns a tuple with the TransactionTimestamp field value // and a boolean to check if the value has been set. func (o *ListTokensTransfersByTransactionHashRI) GetTransactionTimestampOk() (*int32, bool) { if o == nil { return nil, false } return &o.TransactionTimestamp, true } // SetTransactionTimestamp sets field value func (o *ListTokensTransfersByTransactionHashRI) SetTransactionTimestamp(v int32) { o.TransactionTimestamp = v } func (o ListTokensTransfersByTransactionHashRI) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["contractAddress"] = o.ContractAddress } if true { toSerialize["minedInBlockHeight"] = o.MinedInBlockHeight } if true { toSerialize["recipientAddress"] = o.RecipientAddress } if true { toSerialize["senderAddress"] = o.SenderAddress } if true { toSerialize["tokenDecimals"] = o.TokenDecimals } if true { toSerialize["tokenName"] = o.TokenName } if true { toSerialize["tokenSymbol"] = o.TokenSymbol } if true { toSerialize["tokenType"] = o.TokenType } if true { toSerialize["tokensAmount"] = o.TokensAmount } if true { toSerialize["transactionHash"] = o.TransactionHash } if true { toSerialize["transactionTimestamp"] = o.TransactionTimestamp } return json.Marshal(toSerialize) } type NullableListTokensTransfersByTransactionHashRI struct { value *ListTokensTransfersByTransactionHashRI isSet bool } func (v NullableListTokensTransfersByTransactionHashRI) Get() *ListTokensTransfersByTransactionHashRI { return v.value } func (v *NullableListTokensTransfersByTransactionHashRI) Set(val *ListTokensTransfersByTransactionHashRI) { v.value = val v.isSet = true } func (v NullableListTokensTransfersByTransactionHashRI) IsSet() bool { return v.isSet } func (v *NullableListTokensTransfersByTransactionHashRI) Unset() { v.value = nil v.isSet = false } func NewNullableListTokensTransfersByTransactionHashRI(val *ListTokensTransfersByTransactionHashRI) *NullableListTokensTransfersByTransactionHashRI { return &NullableListTokensTransfersByTransactionHashRI{value: val, isSet: true} } func (v NullableListTokensTransfersByTransactionHashRI) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableListTokensTransfersByTransactionHashRI) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_list_tokens_transfers_by_transaction_hash_ri.go
0.829216
0.425784
model_list_tokens_transfers_by_transaction_hash_ri.go
starcoder
package cl import ( "errors" "math/big" "github.com/getamis/alice/crypto/utils" "github.com/golang/protobuf/proto" ) var ( big0 = big.NewInt(0) big256bit = new(big.Int).Lsh(big1, 256) // ErrDifferentBQForms is returned if the two quadratic forms are different ErrDifferentBQForms = errors.New("different binary quadratic Forms") ) /* Notations: - upperboundOrder: A - public key: h - ciphertext: (c1, c2)=(g^r, f^a*h^r) - challenge set c - the message space: [0, p-1]. In our situation, the value p is the order of an elliptic curve group. - distributionDistance: d Alice(i.e. Prover) chooses the message a and a nonce r to get the CL ciphertext (c1, c2). Through the following protocol, Bob(i.e. Verifier) can be convinced that Alice knows a, r, but Bob does not learn a, r in this protocol. We use Fiat–Shamir heuristic to get the following protocol. Step 1: The prover - randomly chooses two integers r1 in [0, 2^{d}Ac] and r2 in [0, p-1]. - computes t1=g^{r1} and t2=h^{r1}f^{r2}. - computes k:=H(t1, t2, g, f, h, p, q) mod c. Here H is a cryptography hash function. - computes u1:=r1+kr in Z and u2:=r2+ka. Here Z is the ring of integer. The resulting proof is (u1, u2, t1, t2, c1, c2). Step 2: The verifier verifies - u1 in [0, (2^{d}+1)Ac]. - u2 in [0, p-1]. - g^{u1}=t1*c1^k. - h^{u1}*f^{u2}=t2*(c2)^k */ func (pubKey *PublicKey) buildProof(plainText *big.Int, r *big.Int) (*ProofMessage, error) { // Compute 2^{d}ac + 1 upperBound1 := new(big.Int).Mul(pubKey.a, pubKey.c) upperBound1 = upperBound1.Lsh(upperBound1, uint(pubKey.d)) upperBound1 = upperBound1.Add(upperBound1, big1) // r1 in [0, 2^{d}Ac] r1, err := utils.RandomInt(upperBound1) if err != nil { return nil, err } // r2 in [0, p-1] r2, err := utils.RandomInt(pubKey.p) if err != nil { return nil, err } // Compute t1=g^{r1} and t2=h^{r1}*f^{r2} t1, err := pubKey.g.Exp(r1) if err != nil { return nil, err } t2, err := pubKey.h.Exp(r1) if err != nil { return nil, err } fPower, err := pubKey.f.Exp(r2) if err != nil { return nil, err } t2, err = t2.Composition(fPower) if err != nil { return nil, err } // k:=H(t1, t2, g, f, h, p, q, a, c) mod c // In our application c = 1024. If the field order is 2^32, we will get the uniform distribution D in [0,2^32-1]. // If we consider the distribution E := { x in D| x mod c } is also the uniform distribution in [0,1023]=[0,c-1]. k, salt, err := utils.HashProtosRejectSampling(big256bit, &Hash{ T1: t1.ToMessage(), T2: t2.ToMessage(), G: pubKey.g.ToMessage(), F: pubKey.f.ToMessage(), H: pubKey.h.ToMessage(), P: pubKey.p.Bytes(), Q: pubKey.q.Bytes(), A: pubKey.a.Bytes(), C: pubKey.c.Bytes(), }) if err != nil { return nil, err } k = k.Mod(k, pubKey.c) // Compute u1:=r1+kr in Z and u2:=r2+k*plainText mod p u1 := new(big.Int).Mul(k, r) u1 = u1.Add(r1, u1) u2 := new(big.Int).Mul(k, plainText) u2 = u2.Add(u2, r2) u2 = u2.Mod(u2, pubKey.p) proof := &ProofMessage{ Salt: salt, U1: u1.Bytes(), U2: u2.Bytes(), T1: t1.ToMessage(), T2: t2.ToMessage(), } return proof, nil } func (pubKey *PublicKey) VerifyEnc(bs []byte) error { msg := &EncryptedMessage{} err := proto.Unmarshal(bs, msg) if err != nil { return err } t1, err := msg.Proof.T1.ToBQuadraticForm() if err != nil { return ErrInvalidMessage } t2, err := msg.Proof.T2.ToBQuadraticForm() if err != nil { return ErrInvalidMessage } c1, c2, err := msg.getBQs(pubKey.discriminantOrderP) if err != nil { return ErrInvalidMessage } // Compute (2^{d}+1)ac + 1 ac := new(big.Int).Mul(pubKey.c, pubKey.a) upperBound := new(big.Int).Lsh(ac, uint(pubKey.d)) upperBound = upperBound.Add(upperBound, ac) upperBound = upperBound.Add(upperBound, big1) // u1 in [0, (2^{d}+1)Ac] u1 := new(big.Int).SetBytes(msg.Proof.U1) err = utils.InRange(u1, big0, upperBound) if err != nil { return err } // u2 in [0, p-1]. u2 := new(big.Int).SetBytes(msg.Proof.U2) err = utils.InRange(u2, big0, pubKey.p) if err != nil { return err } // Check g^{u1}=t1*c1^k // k:=H(t1, t2, g, f, h, p, q, a, c) mod c k, err := utils.HashProtosToInt(msg.Proof.Salt, &Hash{ T1: msg.Proof.T1, T2: msg.Proof.T2, G: pubKey.g.ToMessage(), F: pubKey.f.ToMessage(), H: pubKey.h.ToMessage(), P: pubKey.p.Bytes(), Q: pubKey.q.Bytes(), A: pubKey.a.Bytes(), C: pubKey.c.Bytes(), }) if err != nil { return err } k = k.Mod(k, pubKey.c) t1c1k, err := c1.Exp(k) if err != nil { return err } t1c1k, err = t1c1k.Composition(t1) if err != nil { return err } g := pubKey.g gu1, err := g.Exp(u1) if err != nil { return err } if !gu1.Equal(t1c1k) { return ErrDifferentBQForms } // Check h^{u1}*f^{u2}=t2*(c2)^k f := pubKey.f hu1fu2, err := f.Exp(u2) if err != nil { return err } h := pubKey.h hu1, err := h.Exp(u1) if err != nil { return err } hu1fu2, err = hu1fu2.Composition(hu1) if err != nil { return err } c2k, err := c2.Exp(k) if err != nil { return err } t2c2k, err := c2k.Composition(t2) if err != nil { return err } if !t2c2k.Equal(hu1fu2) { return ErrDifferentBQForms } return nil }
crypto/homo/cl/proof.go
0.678433
0.482856
proof.go
starcoder
package go_cip import ( "bytes" eip "github.com/loki-os/go-ethernet-ip" "github.com/loki-os/go-ethernet-ip/typedef" ) type SegmentType typedef.Usint const ( SegmentTypePort SegmentType = 0 << 5 SegmentTypeLogical SegmentType = 1 << 5 SegmentTypeNetwork SegmentType = 2 << 5 SegmentTypeSymbolic SegmentType = 3 << 5 SegmentTypeData SegmentType = 4 << 5 SegmentTypeDataType1 SegmentType = 5 << 5 SegmentTypeDataType2 SegmentType = 6 << 5 ) func Paths(arg ...[]byte) []byte { buffer := new(bytes.Buffer) for i := 0; i < len(arg); i++ { eip.WriteByte(buffer, arg[i]) } return buffer.Bytes() } type DataTypes typedef.Usint const ( DataTypeSimple DataTypes = 0x0 DataTypeANSI DataTypes = 0x11 ) type LogicalType typedef.Usint const ( LogicalTypeClassID LogicalType = 0 << 2 LogicalTypeInstanceID LogicalType = 1 << 2 LogicalTypeMemberID LogicalType = 2 << 2 LogicalTypeConnPoint LogicalType = 3 << 2 LogicalTypeAttributeID LogicalType = 4 << 2 LogicalTypeSpecial LogicalType = 5 << 2 LogicalTypeServiceID LogicalType = 6 << 2 ) func DataBuild(tp DataTypes, data []byte, padded bool) []byte { buffer := new(bytes.Buffer) firstByte := uint8(SegmentTypeData) | uint8(tp) eip.WriteByte(buffer, firstByte) length := uint8(len(data)) eip.WriteByte(buffer, length) eip.WriteByte(buffer, data) if padded && buffer.Len()%2 == 1 { eip.WriteByte(buffer, uint8(0)) } return buffer.Bytes() } func LogicalBuild(tp LogicalType, address uint32, padded bool) []byte { format := uint8(0) if address <= 255 { format = 0 } else if address > 255 && address <= 65535 { format = 1 } else { format = 2 } buffer := new(bytes.Buffer) firstByte := uint8(SegmentTypeLogical) | uint8(tp) | format eip.WriteByte(buffer, firstByte) if address > 255 && address <= 65535 && padded { eip.WriteByte(buffer, uint8(0)) } if address <= 255 { eip.WriteByte(buffer, uint8(address)) } else if address > 255 && address <= 65535 { eip.WriteByte(buffer, uint16(address)) } else { eip.WriteByte(buffer, address) } return buffer.Bytes() } func PortBuild(link []byte, portID uint16, padded bool) []byte { extendedLinkTag := len(link) > 1 extendedPortTag := !(portID < 15) buffer := new(bytes.Buffer) firstByte := uint8(SegmentTypePort) if extendedLinkTag { firstByte = firstByte | 0x10 } if !extendedPortTag { firstByte = firstByte | uint8(portID) } else { firstByte = firstByte | 0xf } eip.WriteByte(buffer, firstByte) if extendedLinkTag { eip.WriteByte(buffer, uint8(len(link))) } if extendedPortTag { eip.WriteByte(buffer, portID) } eip.WriteByte(buffer, link) if padded && buffer.Len()%2 == 1 { eip.WriteByte(buffer, uint8(0)) } return buffer.Bytes() }
segment.go
0.524882
0.48377
segment.go
starcoder
package bytes import ( "errors" "io" ) var ( // ErrNoEnoughData represents no enough data to return in a buffer. ErrNoEnoughData = errors.New("bytes.ReadOnlyBuffer: no engough data") ) // ReadOnlyBuffer defines a buffer only used for reading data. type ReadOnlyBuffer interface { // Read reads n bytes start with offset from buffer. Read(offset, n int) ([]byte, error) // ReadFrom reads reader's data to buffer ReadFrom(reader io.Reader) (int, error) // Seek detects bytes of n from buffer. Seek(n int) ([]byte, error) // Len returns the number of bytes of the unread portion of the buffer; // b.Len() == len(b.Bytes()). Len() int // FreeBytes returns all the free space in the buffer and won't mark the slice as read. FreeBytes() []byte // Discard marks the data of n from off as readed. Discard(n int) // Bytes returns a slice of length len(b.buf) holding the unread portion of the buffer. // The slice is valid for use only until the next buffer modification. // The slice aliases the buffer content at least until the next buffer modification, // so immediate changes to the slice will affect the result of future reads. Bytes() []byte // Reset resets the buffer to be empty, // but it retains the underlying storage for use by future writes. Reset() } type readOnlyBuffer struct { buf []byte off int end int } // NewReadOnlyBuffer creates new ReadOnlyBuffer instance with buffer of n. func NewReadOnlyBuffer(n int) ReadOnlyBuffer { b := &readOnlyBuffer{} if n <= 0 { n = 1024 // default 1k } b.buf = make([]byte, 0, n) b.Reset() return b } // NewReadOnlyBufferWithBytes creates new instance of ReadOnlyBuffer with buf. func NewReadOnlyBufferWithBytes(buf []byte) ReadOnlyBuffer { rob := &readOnlyBuffer{buf: buf} rob.off = 0 rob.end = len(buf) return rob } func (b *readOnlyBuffer) Read(offset, n int) (buf []byte, err error) { if offset < 0 || offset+n > b.Len() { return nil, ErrNoEnoughData } buf = b.buf[b.off+offset : b.off+offset+n] b.off += offset + n return } func (b *readOnlyBuffer) Seek(n int) ([]byte, error) { if n < 0 || n > b.Len() { return nil, ErrNoEnoughData } return b.buf[b.off : b.off+n], nil } func (b *readOnlyBuffer) ensureSpace() int { m, ok := b.tryGrowByReslice(b.Len()) if !ok { m = b.grow() } return m } func (b *readOnlyBuffer) grow() int { m := b.Len() c := cap(b.buf) buf := makeSlice(2 * c) copy(buf, b.buf[b.off:b.end]) b.buf = buf b.end -= b.off b.off = 0 return m } func (b *readOnlyBuffer) tryGrowByReslice(n int) (int, bool) { if n == 0 { b.buf = b.buf[:cap(b.buf)] return 0, true } if l := len(b.buf); n <= cap(b.buf)-l { b.buf = b.buf[:l+n] return l, true } return 0, false } func (b *readOnlyBuffer) FreeBytes() []byte { b.ensureSpace() return b.buf[b.end:] } func (b *readOnlyBuffer) Len() int { return b.end - b.off } func (b *readOnlyBuffer) Discard(n int) { if n < 0 || n > b.Len() { panic("bytes.ReadOnlyBuffer: Discard out of range") } b.off += n } func (b *readOnlyBuffer) Bytes() []byte { return b.buf[b.off:b.end] } func (b *readOnlyBuffer) ReadFrom(reader io.Reader) (int, error) { n, err := reader.Read(b.FreeBytes()) if err != nil { return n, err } b.end += n return n, nil } func (b *readOnlyBuffer) Reset() { b.buf = b.buf[:0] b.off = 0 b.end = 0 }
bytes/readonly_buffer.go
0.651022
0.441914
readonly_buffer.go
starcoder
package model2d import ( "math" "math/rand" ) // A Coord is a coordinate in 2-D Euclidean space. type Coord struct { X float64 Y float64 } // NewCoordRandNorm creates a random Coord with normally // distributed components. func NewCoordRandNorm() Coord { return Coord{ X: rand.NormFloat64(), Y: rand.NormFloat64(), } } // NewCoordRandUnit creates a random Coord with magnitude // 1. func NewCoordRandUnit() Coord { for { res := NewCoordRandNorm() norm := res.Norm() // Edge case to avoid numerical issues. if norm > 1e-8 { return res.Scale(1 / norm) } } } // NewCoordRandUniform creates a random Coord with // uniformly random coordinates in [0, 1). func NewCoordRandUniform() Coord { return Coord{ X: rand.Float64(), Y: rand.Float64(), } } // NewCoordRandBounds creates a random Coord uniformly // inside the given rectangular boundary. func NewCoordRandBounds(min, max Coord) Coord { c := NewCoordRandUniform() return c.Mul(max.Sub(min)).Add(min) } // NewCoordArray creates a Coord from an array of x and y. func NewCoordArray(a [2]float64) Coord { return Coord{a[0], a[1]} } // NewCoordPolar converts polar coordinates to a Coord. func NewCoordPolar(theta, radius float64) Coord { return XY(math.Cos(theta), math.Sin(theta)).Scale(radius) } // Ones creates the unit vector scaled by a constant. func Ones(a float64) Coord { return Coord{X: a, Y: a} } // XY constructs a coordinate. func XY(x, y float64) Coord { return Coord{X: x, Y: y} } // X gets a coordinate in the X direction. func X(x float64) Coord { return Coord{X: x} } // Y gets a coordinate in the Y direction. func Y(y float64) Coord { return Coord{Y: y} } // Mid computes the midpoint between c and c1. func (c Coord) Mid(c1 Coord) Coord { return c.Add(c1).Scale(0.5) } // Norm computes the vector L2 norm. func (c Coord) Norm() float64 { return math.Sqrt(c.X*c.X + c.Y*c.Y) } // Dot computes the dot product of c and c1. func (c Coord) Dot(c1 Coord) float64 { return c.X*c1.X + c.Y*c1.Y } // Mul computes the element-wise product of c and c1. func (c Coord) Mul(c1 Coord) Coord { return Coord{X: c.X * c1.X, Y: c.Y * c1.Y} } // Div computes the element-wise quotient of c / c1. func (c Coord) Div(c1 Coord) Coord { return Coord{X: c.X / c1.X, Y: c.Y / c1.Y} } // Recip gets a coordinate as 1 / c. func (c Coord) Recip() Coord { return XY(1/c.X, 1/c.Y) } // Scale scales all the coordinates by s and returns the // new coordinate. func (c Coord) Scale(s float64) Coord { c.X *= s c.Y *= s return c } // AddScalar adds s to all of the coordinates and returns // the new coordinate. func (c Coord) AddScalar(s float64) Coord { c.X += s c.Y += s return c } // Add computes the sum of c and c1. func (c Coord) Add(c1 Coord) Coord { return Coord{ X: c.X + c1.X, Y: c.Y + c1.Y, } } // Sub computes c - c1. func (c Coord) Sub(c1 Coord) Coord { return c.Add(c1.Scale(-1)) } // Dist computes the Euclidean distance to c1. func (c Coord) Dist(c1 Coord) float64 { d1 := c.X - c1.X d2 := c.Y - c1.Y return math.Sqrt(d1*d1 + d2*d2) } // SquaredDist gets the squared Euclidean distance to c1. func (c Coord) SquaredDist(c1 Coord) float64 { d1 := c.X - c1.X d2 := c.Y - c1.Y return d1*d1 + d2*d2 } // L1Dist computes the L1 distance to c1. func (c Coord) L1Dist(c1 Coord) float64 { return math.Abs(c.X-c1.X) + math.Abs(c.Y-c1.Y) } // Min gets the element-wise minimum of c and c1. func (c Coord) Min(c1 Coord) Coord { return Coord{math.Min(c.X, c1.X), math.Min(c.Y, c1.Y)} } // Max gets the element-wise maximum of c and c1. func (c Coord) Max(c1 Coord) Coord { return Coord{math.Max(c.X, c1.X), math.Max(c.Y, c1.Y)} } // Sum sums the elements of c. func (c Coord) Sum() float64 { return c.X + c.Y } // Normalize gets a unit vector from c. func (c Coord) Normalize() Coord { return c.Scale(1 / c.Norm()) } // ProjectOut projects the c1 direction out of c. func (c Coord) ProjectOut(c1 Coord) Coord { normed := c1.Normalize() return c.Sub(normed.Scale(normed.Dot(c))) } // Reflect reflects c1 around c. func (c Coord) Reflect(c1 Coord) Coord { n := c.Normalize() return c1.Add(n.Scale(-2 * n.Dot(c1))).Scale(-1) } // Array gets an array of x and y. func (c Coord) Array() [2]float64 { return [2]float64{c.X, c.Y} } // fastHash generates a hash of the coordinate using a // dot product with a random vector. func (c Coord) fastHash() uint32 { x := c.fastHash64() return uint32(x&0xffffffff) ^ uint32(x>>32) } // fastHash64 is like fastHash, but uses a 64-bit hash // space to help mitigate collisions. func (c Coord) fastHash64() uint64 { // Coefficients are random (keyboard mashed). return math.Float64bits(0.78378384728594870293*c.X + 0.12938729312040294193*c.Y) }
model2d/coords.go
0.888717
0.579579
coords.go
starcoder
package core import ( "image" "github.com/Laughs-In-Flowers/flip" "github.com/Laughs-In-Flowers/warhola/lib/canvas" ) var ( fliip = NewCommand( "", "flip", "Flip an image in an opposite direction", 1, func(o *Options) *flip.FlagSet { v := o.Vector fs := flip.NewFlagSet("flip", flip.ContinueOnError) fs.BoolVector(v, "vertical", "flip.vertical", "flip the image vertically") fs.BoolVector(v, "horizontal", "flip.horizontal", "flip the image horizontally") return fs }, defaultCommandFunc, coreExec(func(o *Options, cv canvas.Canvas) (canvas.Canvas, flip.ExitStatus) { v, h := o.ToBool("flip.vertical"), o.ToBool("flip.horizontal") var err error if v { err = cv.Flip(canvas.TVertical) } if h { err = cv.Flip(canvas.THorizontal) } return cv, coreErrorHandler(o, err) })..., ).Command rotate = NewCommand( "", "rotate", "Rotate an image", 1, func(o *Options) *flip.FlagSet { v := o.Vector fs := flip.NewFlagSet("rotate", flip.ContinueOnError) fs.Float64Vector(v, "angle", "rotate.angle", "the angle of rotation to apply") fs.BoolVector(v, "preserveSize", "rotate.preserve", "preserve the size the image") fs.IntVector(v, "pivotX", "rotate.pivot.x", "the x value of the rotation pivot point") fs.IntVector(v, "pivotY", "rotate.pivot.y", "the y value of the rotation pivot point") return fs }, defaultCommandFunc, coreExec(func(o *Options, cv canvas.Canvas) (canvas.Canvas, flip.ExitStatus) { angle := o.ToFloat64("rotate.angle") preserve := o.ToBool("rotate.preserve") x, y := o.ToInt("rotate.pivot.x"), o.ToInt("rotate.pivot.y") err := cv.Rotate(angle, preserve, image.Point{x, y}) return cv, coreErrorHandler(o, err) })..., ).Command shear = NewCommand( "", "shear", "Linear transformation along an axis", 1, func(o *Options) *flip.FlagSet { v := o.Vector fs := flip.NewFlagSet("shear", flip.ContinueOnError) fs.Float64Vector(v, "vertical", "shear.vertical.angle", "the angle of vertical shear to apply") fs.Float64Vector(v, "horizontal", "shear.horizontal.angle", "the angle of horizontal shear to apply") return fs }, defaultCommandFunc, coreExec(func(o *Options, cv canvas.Canvas) (canvas.Canvas, flip.ExitStatus) { v, h := o.ToFloat64("shear.vertical.angle"), o.ToFloat64("shear.horizontal.angle") var err error if v != 0 { err = cv.Shear(canvas.TVertical, v) } if h != 0 { err = cv.Shear(canvas.THorizontal, h) } return cv, coreErrorHandler(o, err) })..., ).Command translate = NewCommand( "", "translate", "repositions a copy of an image by dx on the x-axis and dy on the y-axis", 1, func(o *Options) *flip.FlagSet { v := o.Vector fs := flip.NewFlagSet("translate", flip.ContinueOnError) fs.IntVector(v, "dx", "translate.dx", "reposition by dx on the x-axis") fs.IntVector(v, "dy", "translate.dy", "reposition by dy on the y-axis") return fs }, defaultCommandFunc, coreExec(func(o *Options, cv canvas.Canvas) (canvas.Canvas, flip.ExitStatus) { dx, dy := o.ToInt("translate.dx"), o.ToInt("translate.dy") err := cv.Translate(dx, dy) return cv, coreErrorHandler(o, err) })..., ).Command ) func registerTranslateCmds(cm cmdMap) { cm.Register("flip", fliip) cm.Register("rotate", rotate) cm.Register("shear", shear) cm.Register("translate", translate) }
lib/core/translate.go
0.539954
0.466177
translate.go
starcoder
package life import "image/color" import "time" import "github.com/fyne-io/fyne" import "github.com/fyne-io/fyne/canvas" import "github.com/fyne-io/fyne/theme" type board struct { cells [][]bool width int height int } func (b *board) ifAlive(x, y int) int { if x < 0 || x >= b.width { return 0 } if y < 0 || y >= b.height { return 0 } if b.cells[y][x] { return 1 } return 0 } func (b *board) countNeighbours(x, y int) int { sum := 0 sum += b.ifAlive(x-1, y-1) sum += b.ifAlive(x, y-1) sum += b.ifAlive(x+1, y-1) sum += b.ifAlive(x-1, y) sum += b.ifAlive(x+1, y) sum += b.ifAlive(x-1, y+1) sum += b.ifAlive(x, y+1) sum += b.ifAlive(x+1, y+1) return sum } func (b *board) nextGen() [][]bool { state := make([][]bool, b.height) for y := 0; y < b.height; y++ { state[y] = make([]bool, b.width) for x := 0; x < b.width; x++ { n := b.countNeighbours(x, y) if b.cells[y][x] { state[y][x] = n == 2 || n == 3 } else { state[y][x] = n == 3 } } } return state } func (b *board) renderState(state [][]bool) { for y := 0; y < b.height; y++ { for x := 0; x < b.width; x++ { b.cells[y][x] = state[y][x] } } } func (b *board) load() { // gun b.cells[5][1] = true b.cells[5][2] = true b.cells[6][1] = true b.cells[6][2] = true b.cells[3][13] = true b.cells[3][14] = true b.cells[4][12] = true b.cells[4][16] = true b.cells[5][11] = true b.cells[5][17] = true b.cells[6][11] = true b.cells[6][15] = true b.cells[6][17] = true b.cells[6][18] = true b.cells[7][11] = true b.cells[7][17] = true b.cells[8][12] = true b.cells[8][16] = true b.cells[9][13] = true b.cells[9][14] = true b.cells[1][25] = true b.cells[2][23] = true b.cells[2][25] = true b.cells[3][21] = true b.cells[3][22] = true b.cells[4][21] = true b.cells[4][22] = true b.cells[5][21] = true b.cells[5][22] = true b.cells[6][23] = true b.cells[6][25] = true b.cells[7][25] = true b.cells[3][35] = true b.cells[3][36] = true b.cells[4][35] = true b.cells[4][36] = true // spaceship b.cells[34][2] = true b.cells[34][3] = true b.cells[34][4] = true b.cells[34][5] = true b.cells[35][1] = true b.cells[35][5] = true b.cells[36][5] = true b.cells[37][1] = true b.cells[37][4] = true } func newBoard() *board { b := &board{nil, 60, 50} b.cells = make([][]bool, b.height) for y := 0; y < b.height; y++ { b.cells[y] = make([]bool, b.width) } return b } type game struct { board *board paused bool size fyne.Size position fyne.Position hidden bool renderer *gameRenderer } func (g *game) CurrentSize() fyne.Size { return g.size } func (g *game) Resize(size fyne.Size) { g.size = size g.Renderer().Layout(size) } func (g *game) CurrentPosition() fyne.Position { return g.position } func (g *game) Move(pos fyne.Position) { g.position = pos g.Renderer().Layout(g.size) } func (g *game) MinSize() fyne.Size { return g.Renderer().MinSize() } func (g *game) IsVisible() bool { return g.hidden } func (g *game) Show() { g.hidden = false } func (g *game) Hide() { g.hidden = true } func (g *game) ApplyTheme() { g.Renderer().ApplyTheme() } func (g *game) Renderer() fyne.WidgetRenderer { if g.renderer == nil { g.renderer = g.createRenderer() } return g.renderer } type gameRenderer struct { render *canvas.Image objects []fyne.CanvasObject aliveColor color.Color deadColor color.Color game *game } func (g *gameRenderer) MinSize() fyne.Size { return fyne.NewSize(g.game.board.width*10, g.game.board.height*10) } func (g *gameRenderer) Layout(size fyne.Size) { g.render.Resize(size) } func (g *gameRenderer) ApplyTheme() { g.aliveColor = theme.TextColor() g.deadColor = theme.BackgroundColor() } func (g *gameRenderer) Refresh() { canvas.Refresh(g.render) } func (g *gameRenderer) Objects() []fyne.CanvasObject { return g.objects } func (g *gameRenderer) renderer(x, y, w, h int) color.Color { xpos, ypos := g.game.cellForCoord(x, y, w, h) if xpos >= g.game.board.width || ypos >= g.game.board.height { return g.deadColor } if g.game.board.cells[ypos][xpos] { return g.aliveColor } return g.deadColor } func (g *game) createRenderer() *gameRenderer { renderer := &gameRenderer{game: g} render := canvas.NewRaster(renderer.renderer) renderer.render = render renderer.objects = []fyne.CanvasObject{render} renderer.ApplyTheme() return renderer } func (g *game) cellForCoord(x, y, w, h int) (int, int) { xpos := int(float64(g.board.width) * (float64(x) / float64(w))) ypos := int(float64(g.board.height) * (float64(y) / float64(h))) return xpos, ypos } func (g *game) run() { g.paused = false } func (g *game) stop() { g.paused = true } func (g *game) toggleRun() { g.paused = !g.paused } func (g *game) animate() { go func() { tick := time.NewTicker(time.Second / 6) for { select { case <-tick.C: if g.paused { continue } state := g.board.nextGen() g.board.renderState(state) g.Renderer().Refresh() } } }() } func (g *game) keyDown(ev *fyne.KeyEvent) { if ev.Name == "space" { g.toggleRun() } } func (g *game) OnMouseDown(ev *fyne.MouseEvent) { xpos, ypos := g.cellForCoord(ev.Position.X, ev.Position.Y, g.size.Width, g.size.Height) if xpos >= g.board.width || ypos >= g.board.height { return } g.board.cells[ypos][xpos] = !g.board.cells[ypos][xpos] g.Renderer().Refresh() } func newGame(b *board) *game { g := &game{board: b} return g } // Show starts a new game of life func Show(app fyne.App) { board := newBoard() board.load() game := newGame(board) window := app.NewWindow("Life") window.SetContent(game) window.Canvas().SetOnKeyDown(game.keyDown) // start the board animation before we show the window - it will block game.animate() window.Show() }
life/main.go
0.516595
0.404449
main.go
starcoder
package scheduler import "time" // Scheduler is an interface for running tasks. // Scheduling of tasks is asynchronous/non-blocking. // Tasks can be executed in sequence or concurrently. type Scheduler interface { // Now returns the current time according to the scheduler. Now() time.Time // Since returns the time elapsed, is a shorthand for Now().Sub(t). Since(t time.Time) time.Duration // Schedule dispatches a task to the scheduler. Schedule(task func()) Runner // ScheduleRecursive dispatches a task to the scheduler. Use the again // function to schedule another iteration of a repeating algorithm on // the scheduler. ScheduleRecursive(task func(again func())) Runner // ScheduleLoop dispatches a task to the scheduler. Use the again // function to schedule another iteration of a repeating algorithm on // the scheduler. The current loop index is passed to the task. The loop // index starts at the value passed in the from argument. The task is // expected to pass the next loop index to the again function. ScheduleLoop(from int, task func(index int, again func(next int))) Runner // ScheduleFuture dispatches a task to the scheduler to be executed later. // The due time specifies when the task should be executed. ScheduleFuture(due time.Duration, task func()) Runner // ScheduleFutureRecursive dispatches a task to the scheduler to be // executed later. Use the again function to schedule another iteration of a // repeating algorithm on the scheduler. The due time specifies when the // task should be executed. ScheduleFutureRecursive(due time.Duration, task func(again func(due time.Duration))) Runner // Wait will return when the Cancel() method is called or when there are no // more tasks running. Note, the currently running task may schedule // additional tasks to the queue to run later. Wait() // Gosched will give the scheduler an oportunity to run another task Gosched() // IsConcurrent returns true for a scheduler that runs tasks concurrently. IsConcurrent() bool // Count returns the number of currently active tasks. Count() int // String representation when printed. String() string } // Runner is an interface to a running task. It can be used to cancel the // running task by calling its Cancel() method. type Runner interface { // Cancel the running task. Cancel() }
scheduler.go
0.631481
0.405625
scheduler.go
starcoder
package xacml import ( "errors" "log" "regexp" ) const ( functionStringEqual = "urn:oasis:names:tc:xacml:1.0:function:string-equal" functionStringEqualIgnoreCase = "urn:oasis:names:tc:xacml:1.0:function:string-equal-ignore-case" functionBooleanEqual = "urn:oasis:names:tc:xacml:1.0:function:boolean-equal" functionIntegerEqual = "urn:oasis:names:tc:xacml:1.0:function:integer-equal" functionDoubleEqual = "urn:oasis:names:tc:xacml:1.0:function:double-equal" functionDateEqual = "urn:oasis:names:tc:xacml:1.0:function:date-equal" functionTimeEqual = "urn:oasis:names:tc:xacml:1.0:function:time-equal" functionDateTimeEqual = "urn:oasis:names:tc:xacml:1.0:function:dateTime-equal" functionDayTimeDurationEqual = "urn:oasis:names:tc:xacml:1.0:function:dayTimeDuration-equal" functionYearMonthDurationEqual = "urn:oasis:names:tc:xacml:1.0:function:yearMonthDuration-equal" functionAnyURIEqual = "urn:oasis:names:tc:xacml:1.0:function:anyURI-equal" functionX500NameEqual = "urn:oasis:names:tc:xacml:1.0:function:x500Name-equal" functionRFC822NameEqual = "urn:oasis:names:tc:xacml:1.0:function:rfc822Name-equal" functionHexBinaryEqual = "urn:oasis:names:tc:xacml:1.0:function:hexBinary-equal" functionBase64BinaryEqual = "urn:oasis:names:tc:xacml:1.0:function:base64Binary-equal" functionIntegerAdd = "urn:oasis:names:tc:xacml:1.0:function:integer-add" functionDoubleAdd = "urn:oasis:names:tc:xacml:1.0:function:double-add" functionIntegerSubtract = "urn:oasis:names:tc:xacml:1.0:function:integer-subtract" functionDoubleSubtract = "urn:oasis:names:tc:xacml:1.0:function:double-subtract" functionIntegerMultiply = "urn:oasis:names:tc:xacml:1.0:function:integer-multiply" functionDoubleMultiply = "urn:oasis:names:tc:xacml:1.0:function:double-multiply" functionIntegerDivide = "urn:oasis:names:tc:xacml:1.0:function:integer-divide" functionDoubleDivide = "urn:oasis:names:tc:xacml:1.0:function:double-divide" functionIntegerMod = "urn:oasis:names:tc:xacml:1.0:function:integer-mod" functionIntegerAbs = "urn:oasis:names:tc:xacml:1.0:function:integer-abs" functionDoubleAbs = "urn:oasis:names:tc:xacml:1.0:function:double-abs" functionRound = "urn:oasis:names:tc:xacml:1.0:function:round" functionFloor = "urn:oasis:names:tc:xacml:1.0:function:floor" functionStringNormalizeSpace = "urn:oasis:names:tc:xacml:1.0:function:string-normalize-space" functionStringNormalizeToLowerCase = "urn:oasis:names:tc:xacml:1.0:function:string-normalize-to-lower-case" functionDoubleToInteger = "urn:oasis:names:tc:xacml:1.0:function:double-to-integer" functionIntegerToDouble = "urn:oasis:names:tc:xacml:1.0:function:integer-to-double" functionOr = "urn:oasis:names:tc:xacml:1.0:function:or" functionAnd = "urn:oasis:names:tc:xacml:1.0:function:and" functionNOf = "urn:oasis:names:tc:xacml:1.0:function:n-of" functionNot = "urn:oasis:names:tc:xacml:1.0:function:not" functionIntegerGreaterThan = "urn:oasis:names:tc:xacml:1.0:function:integer-greater-than" functionIntegerGreaterThanOrEqual = "urn:oasis:names:tc:xacml:1.0:function:integer-greater-than-or-equal" functionIntegerLessThan = "urn:oasis:names:tc:xacml:1.0:function:integer-less-than" functionIntegerLessThanOrEqual = "urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal" functionDoubleGreaterThan = "urn:oasis:names:tc:xacml:1.0:function:double-greater-than" functionDoubleGreaterThanOrEqual = "urn:oasis:names:tc:xacml:1.0:function:double-greater-than-or-equal" functionDoubleLessThan = "urn:oasis:names:tc:xacml:1.0:function:double-less-than" functionDoubleLessThanOrEqual = "urn:oasis:names:tc:xacml:1.0:function:double-less-than-or-equal" functionStringConcatenate = "urn:oasis:names:tc:xacml:2.0:function:string-concatenate" functionBooleanFromString = "urn:oasis:names:tc:xacml:3.0:function:boolean-from-string" functionStringFromBoolean = "urn:oasis:names:tc:xacml:3.0:function:string-from-boolean" functionIntegerFromString = "urn:oasis:names:tc:xacml:3.0:function:integer-from-string" functionStringFromInteger = "urn:oasis:names:tc:xacml:3.0:function:string-from-integer" functionDoubleFromString = "urn:oasis:names:tc:xacml:3.0:function:double-from-string" functionStringFromDouble = "urn:oasis:names:tc:xacml:3.0:function:string-from-double" functionStringStartsWith = "urn:oasis:names:tc:xacml:3.0:function:string-starts-with" functionStringEndsWith = "urn:oasis:names:tc:xacml:3.0:function:string-ends-with" functionStringContains = "urn:oasis:names:tc:xacml:3.0:function:string-contains" functionStringSubString = "urn:oasis:names:tc:xacml:3.0:function:string-substring" functionStringOneAndOnly = "urn:oasis:names:tc:xacml:3.0:function:string-one-and-only" functionStringBagSize = "urn:oasis:names:tc:xacml:3.0:function:string-bag-size" functionStringIsIn = "urn:oasis:names:tc:xacml:3.0:function:string-is-in" functionStringBag = "urn:oasis:names:tc:xacml:3.0:function:string-bag" functionStringIntersection = "urn:oasis:names:tc:xacml:3.0:function:string-intersection" functionStringAtLeastOneMemberOf = "urn:oasis:names:tc:xacml:3.0:function:string-at-least-one-member-of" functionStringUnion = "urn:oasis:names:tc:xacml:3.0:function:string-union" functionStringSubset = "urn:oasis:names:tc:xacml:3.0:function:string-subset" functionStringSetEquals = "urn:oasis:names:tc:xacml:3.0:function:string-set-equals" functionStringRegExpMatch = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match" functionAnyURIRegExpMatch = "urn:oasis:names:tc:xacml:1.0:function:anyURI-regexp-match" functionIpAddressRegExpMatch = "urn:oasis:names:tc:xacml:1.0:function:ipAddress-regexp-match" functionDNSNameRegExpMatch = "urn:oasis:names:tc:xacml:1.0:function:dnsName-regexp-match" ) func applyFunction(functionId string, args ...interface{}) (interface{}, error) { switch functionId { case functionStringEqual: return stringEqual(args[0], args[1]) case functionBooleanEqual: return booleanEqual(args[0], args[1]) case functionIntegerEqual: return integerEqual(args[0], args[1]) case functionStringOneAndOnly: return stringOneAndOnly(args[0]) case functionStringBagSize: return stringBagSize(args[0]) case functionStringIsIn: return stringIsIn(args[0], args[1]) case functionStringBag: return stringBag(args...) case functionStringRegExpMatch: return stringRegExpMatch(args[0], args[1]) default: log.Println("Unknown or Unsupported Function: ", functionId) return false, errors.New("Unknown or Unsupported Function") } } func applyMatchFunction(functionId string, attributeOne, attributeTwo interface{}) (bool, error) { ret, err := applyFunction(functionId, attributeOne, attributeTwo) if err != nil { return false, err } retb, _ := ret.(bool) return retb, err } func stringEqual(attributeOne, attributeTwo interface{}) (bool, error) { a1, ok := attributeOne.(string) if !ok { return false, errors.New("Invalid attributeOne type") } a2, ok := attributeTwo.(string) if !ok { return false, errors.New("Invalid attributeTwo type") } return a1 == a2, nil } func stringOneAndOnly(attributeOne interface{}) (string, error) { attributeArray, ok := attributeOne.([]interface{}) if !ok { return "", errors.New("Argument must be an array") } if len(attributeArray) > 1 { return "", errors.New("Argument must be an array with only one value") } stringVal, ok := attributeArray[0].(string) if !ok { return "", errors.New("Each member of the array must be a string") } return stringVal, nil } func stringBagSize(attributeOne interface{}) (int64, error) { attributeArray, ok := attributeOne.([]interface{}) if !ok { return 0, errors.New("Argument must be an array") } return int64(len(attributeArray)), nil } func stringIsIn(attributeOne, attributeTwo interface{}) (bool, error) { //log.Println(attributeOne) //log.Println(attributeTwo) a1, ok := attributeOne.(string) if !ok { return false, errors.New("First argument must be a string") } attributeArray, ok := attributeTwo.([]interface{}) if !ok { attributeValue, ok := attributeTwo.(string) if !ok { return false, errors.New("Second argument must be an array, or a string") } attributeArray = append(attributeArray, attributeValue) } for _, s := range attributeArray { ret, err := stringEqual(a1, s) if err != nil { continue } if ret { return true, nil } } return false, nil } func stringBag(attributes ...interface{}) ([]interface{}, error) { ret := make([]interface{}, 0) for _, attr := range attributes { if str, ok := attr.(string); ok { ret = append(ret, str) } } return ret, nil } func stringRegExpMatch(attributeOne, attributeTwo interface{}) (bool, error) { a1, ok := attributeOne.(string) if !ok { return false, errors.New("Invalid attributeOne type") } a2, ok := attributeTwo.(string) if !ok { return false, errors.New("Invalid attributeTwo type") } return regexp.MatchString(a1, a2) } func booleanEqual(attributeOne, attributeTwo interface{}) (bool, error) { a1, ok := attributeOne.(bool) if !ok { return false, errors.New("Invalid attributeOne type") } a2, ok := attributeTwo.(bool) if !ok { return false, errors.New("Invalid attributeTwo type") } return a1 == a2, nil } func integerEqual(attributeOne, attributeTwo interface{}) (bool, error) { a1, ok := attributeOne.(int64) if !ok { return false, errors.New("Invalid attributeOne type") } a2, ok := attributeTwo.(int64) if !ok { return false, errors.New("Invalid attributeTwo type") } return a1 == a2, nil }
Functions.go
0.500732
0.489442
Functions.go
starcoder
package constant import ( "bytes" "fmt" "github.com/geode-lang/geode/llvm/enc" "github.com/geode-lang/geode/llvm/ir/types" "github.com/geode-lang/geode/llvm/ir/value" ) // --- [ vector ] -------------------------------------------------------------- // Vector represents a vector constant. type Vector struct { // Vector type. Typ *types.VectorType // Vector elements. Elems []Constant } // NewVector returns a new vector constant based on the given elements. func NewVector(elems ...Constant) *Vector { if len(elems) < 1 { panic(fmt.Errorf("invalid number of vector elements; expected > 0, got %d", len(elems))) } typ := types.NewVector(elems[0].Type(), int64(len(elems))) return &Vector{Typ: typ, Elems: elems} } // Type returns the type of the constant. func (c *Vector) Type() types.Type { return c.Typ } // Ident returns the string representation of the constant. func (c *Vector) Ident() string { buf := &bytes.Buffer{} buf.WriteString("<") for i, elem := range c.Elems { if i != 0 { buf.WriteString(", ") } fmt.Fprintf(buf, "%s %s", elem.Type(), elem.Ident()) } buf.WriteString(">") return buf.String() } // Immutable ensures that only constants can be assigned to the // constant.Constant interface. func (*Vector) Immutable() {} // MetadataNode ensures that only metadata nodes can be assigned to the // ir.MetadataNode interface. func (*Vector) MetadataNode() {} // --- [ array ] --------------------------------------------------------------- // Array represents an array constant. type Array struct { // Array type. Typ *types.ArrayType // Array elements. Elems []Constant // Pretty-print as character array. CharArray bool } // NewArray returns a new array constant based on the given elements. func NewArray(elems ...Constant) *Array { if len(elems) < 1 { panic(fmt.Errorf("invalid number of array elements; expected > 0, got %d", len(elems))) } typ := types.NewArray(elems[0].Type(), int64(len(elems))) return &Array{Typ: typ, Elems: elems} } // Type returns the type of the constant. func (c *Array) Type() types.Type { return c.Typ } // Ident returns the string representation of the constant. func (c *Array) Ident() string { // Pretty-print character arrays. if c.CharArray { buf := make([]byte, 0, len(c.Elems)) for _, elem := range c.Elems { e, ok := elem.(*Int) if !ok { panic(fmt.Errorf("invalid array element type; expected *constant.Int, got %T", elem)) } b := byte(e.Int64()) buf = append(buf, b) } return fmt.Sprintf(`c"%s"`, enc.EscapeString(string(buf))) } // Print regular arrays. buf := &bytes.Buffer{} buf.WriteString("[") for i, elem := range c.Elems { if i != 0 { buf.WriteString(", ") } fmt.Fprintf(buf, "%s %s", elem.Type(), elem.Ident()) } buf.WriteString("]") return buf.String() } // Immutable ensures that only constants can be assigned to the // constant.Constant interface. func (*Array) Immutable() {} // MetadataNode ensures that only metadata nodes can be assigned to the // ir.MetadataNode interface. func (*Array) MetadataNode() {} // --- [ struct ] -------------------------------------------------------------- // Struct represents a struct constant. type Struct struct { // Struct type. Typ *types.StructType // Struct fields. Fields []Constant } // NewStruct returns a new struct constant based on the given struct fields. func NewStruct(fields ...Constant) *Struct { var fieldTypes []types.Type for _, field := range fields { fieldTypes = append(fieldTypes, field.Type()) } typ := types.NewStruct(fieldTypes...) return &Struct{Typ: typ, Fields: fields} } // Type returns the type of the constant. func (c *Struct) Type() types.Type { return c.Typ } // Ident returns the string representation of the constant. func (c *Struct) Ident() string { buf := &bytes.Buffer{} buf.WriteString("{") if len(c.Fields) > 0 { // Use same output format as Clang. buf.WriteString(" ") } for i, field := range c.Fields { if i != 0 { buf.WriteString(", ") } fmt.Fprintf(buf, "%s %s", field.Type(), field.Ident()) } if len(c.Fields) > 0 { // Use same output format as Clang. buf.WriteString(" ") } buf.WriteString("}") return buf.String() } // Immutable ensures that only constants can be assigned to the // constant.Constant interface. func (*Struct) Immutable() {} // MetadataNode ensures that only metadata nodes can be assigned to the // ir.MetadataNode interface. func (*Struct) MetadataNode() {} // --- [ zeroinitializer ] ----------------------------------------------------- // ZeroInitializer represents a zeroinitializer constant. type ZeroInitializer struct { // Constant type. Typ types.Type } // NewZeroInitializer returns a new zeroinitializer constant based on the given // type. func NewZeroInitializer(typ types.Type) *ZeroInitializer { return &ZeroInitializer{Typ: typ} } // Type returns the type of the constant. func (c *ZeroInitializer) Type() types.Type { return c.Typ } // Ident returns the string representation of the constant. func (c *ZeroInitializer) Ident() string { return "zeroinitializer" } // Immutable ensures that only constants can be assigned to the // constant.Constant interface. func (*ZeroInitializer) Immutable() {} // MetadataNode ensures that only metadata nodes can be assigned to the // ir.MetadataNode interface. func (*ZeroInitializer) MetadataNode() {} // --- [ struct ] -------------------------------------------------------------- // Slice represents a Slice constant. type Slice struct { // Slice type. Typ *types.SliceType // Slice fields. Data value.Value Len *Int } // NewSlice returns a new Slice constant based on the given Slice fields. func NewSlice(sliceType *types.SliceType, data value.Value, length *Int) *Slice { return &Slice{Typ: sliceType, Data: data, Len: length} } // Type returns the type of the constant. func (c *Slice) Type() types.Type { return c.Typ } // Ident returns the string representation of the constant. func (c *Slice) Ident() string { buf := &bytes.Buffer{} buf.WriteString("{") fmt.Fprintf(buf, " %s %s,", c.Data.Type(), c.Data.Ident()) fmt.Fprintf(buf, " %s %s }", c.Len.Type(), c.Len.Ident()) fmt.Println(buf.String()) return buf.String() } // Immutable ensures that only constants can be assigned to the // constant.Constant interface. func (*Slice) Immutable() {} // MetadataNode ensures that only metadata nodes can be assigned to the // ir.MetadataNode interface. func (*Slice) MetadataNode() {}
llvm/ir/constant/complex.go
0.782372
0.538923
complex.go
starcoder
package ihex import ( "bytes" "encoding/hex" "fmt" "io" "strings" ) const ( // recordMaximumDataSize the largest size of the data payload of a record (in bytes) recordMaximumDataSize = 255 // recordMaximumSizeChars the largest size of a record (including header data, checksum and starting character) when hexadecimal encoded recordMaximumSizeChars = 521 // recordEOFChecksum is the default checksum value for an EOF record recordEOFChecksum = 0xFF // recordStartChar the starting character of a HEX record recordStartChar = ':' // Each of these defines where in the byte stream for a record to pull that record data property recordByteCountIndex = 0 recordAddressByteIndex = 1 recordRecordTypeIndex = 3 recordDataIndex = 4 // recordHeaderAndChecksumSize defines how many bytes everythign in the record except the starting char and the data itself takes up recordHeaderAndChecksumSize = 5 ) // Record is a single record in an Intel HEX file. // An IHEX record contains the following: // The record type. // A 16 bit record address (or address offset for I16HEX and I32HEX files). // Up to 255 bytes of data. // A checksum for validating record data integrity. // This library handles checksum validation and generation automatically. Thus the checksum is excluded from the struct. type Record struct { Type RecordType AddressOffset uint16 Data []byte } // validate checks if this record belongs in the specified IHEX file format and that the length is correct. // This always returns true if the record's type is RecordEOF or RecordData. // If the file type is I16HEX, then this will return true if the record's type is RecordExtSegment or RecordStartSegment. // If the file type is I32HEX, then this will return true if the record's type is RecordExtLinear or RecordStartLinear. // Otherwise, returns false. func (me Record) validate(fileType FileType) bool { return me.Type == RecordData || me.Type == RecordEOF || ((me.Type == RecordExtSegment || me.Type == RecordStartSegment) && fileType == I16HEX) || ((me.Type == RecordExtLinear || me.Type == RecordStartLinear) && fileType == I32HEX) } // write writes this record's data to a writer in valid IHEX format. // Returns number of bytes written and any errors created during the writing process. func (me Record) write(w io.Writer) (int, error) { buf := bytes.NewBufferString(fmt.Sprintf("%c%02X%04X%02X", recordStartChar, len(me.Data), me.AddressOffset, me.Type)) hexBytes := make([]byte, len(me.Data)*2) hex.Encode(hexBytes, me.Data) if _, err := buf.WriteString(fmt.Sprintf("%s%02X\n", strings.ToUpper(string(hexBytes)), me.getChecksum())); err != nil { return 0, err } return w.Write(buf.Bytes()) } // getChecksum generates the 8 bit checksum for this record. // The IHEX specificaiton of the record checksum is that it is: "the two's complement of the least significant byte (LSB) of the sum of all decoded byte values in the record preceding the checksum". // Returns the 1 byte (8 bit) checksum using the IHEX checksum specification. func (me Record) getChecksum() byte { if me.Type == RecordEOF { return recordEOFChecksum } sum := uint32(0) for _, d := range me.Data { sum += uint32(d) } checksum := byte(((^sum) & 0x000000FF)) + 1 return checksum }
record.go
0.804866
0.53692
record.go
starcoder
package zed import ( "encoding/binary" "fmt" "strings" "github.com/brimdata/zed/zcode" ) type TypeOfType struct{} func (t *TypeOfType) ID() int { return IDType } func (t *TypeOfType) String() string { return "type" } func (t *TypeOfType) Marshal(zv zcode.Bytes) (interface{}, error) { return t.Format(zv), nil } func (t *TypeOfType) Format(zv zcode.Bytes) string { return fmt.Sprintf("(%s)", FormatTypeValue(zv)) } func NewTypeValue(t Type) Value { return Value{TypeType, EncodeTypeValue(t)} } func EncodeTypeValue(t Type) zcode.Bytes { var typedefs map[string]Type return appendTypeValue(nil, t, &typedefs) } func appendTypeValue(b zcode.Bytes, t Type, typedefs *map[string]Type) zcode.Bytes { switch t := t.(type) { case *TypeAlias: if *typedefs == nil { *typedefs = make(map[string]Type) } id := byte(IDTypeDef) if previous := (*typedefs)[t.Name]; previous == t.Type { id = IDTypeName } else { (*typedefs)[t.Name] = t.Type } b = append(b, id) b = zcode.AppendUvarint(b, uint64(len(t.Name))) b = append(b, zcode.Bytes(t.Name)...) if id == IDTypeName { return b } return appendTypeValue(b, t.Type, typedefs) case *TypeRecord: b = append(b, IDTypeRecord) b = zcode.AppendUvarint(b, uint64(len(t.Columns))) for _, col := range t.Columns { b = zcode.AppendUvarint(b, uint64(len(col.Name))) b = append(b, col.Name...) b = appendTypeValue(b, col.Type, typedefs) } return b case *TypeUnion: b = append(b, IDTypeUnion) b = zcode.AppendUvarint(b, uint64(len(t.Types))) for _, t := range t.Types { b = appendTypeValue(b, t, typedefs) } return b case *TypeSet: b = append(b, IDTypeSet) return appendTypeValue(b, t.Type, typedefs) case *TypeArray: b = append(b, IDTypeArray) return appendTypeValue(b, t.Type, typedefs) case *TypeEnum: b = append(b, IDTypeEnum) b = zcode.AppendUvarint(b, uint64(len(t.Symbols))) for _, s := range t.Symbols { b = zcode.AppendUvarint(b, uint64(len(s))) b = append(b, s...) } return b case *TypeMap: b = append(b, IDTypeMap) b = appendTypeValue(b, t.KeyType, typedefs) return appendTypeValue(b, t.ValType, typedefs) default: // Primitive type return append(b, byte(t.ID())) } } func FormatTypeValue(tv zcode.Bytes) string { var b strings.Builder formatTypeValue(tv, &b) return b.String() } func truncErr(b *strings.Builder) { b.WriteString("<ERR truncated type value>") } func formatTypeValue(tv zcode.Bytes, b *strings.Builder) zcode.Bytes { if len(tv) == 0 { truncErr(b) return nil } id := tv[0] tv = tv[1:] switch id { case IDTypeDef: name, tv := decodeNameAndCheck(tv, b) if tv == nil { return nil } b.WriteString(name) b.WriteString("=(") tv = formatTypeValue(tv, b) b.WriteByte(')') return tv case IDTypeName: name, tv := decodeNameAndCheck(tv, b) if tv == nil { return nil } b.WriteString(name) return tv case IDTypeRecord: b.WriteByte('{') var n int n, tv = decodeInt(tv) if tv == nil { truncErr(b) return nil } for k := 0; k < n; k++ { if k > 0 { b.WriteByte(',') } var name string name, tv = decodeNameAndCheck(tv, b) b.WriteString(QuotedName(name)) b.WriteString(":") tv = formatTypeValue(tv, b) if tv == nil { return nil } } b.WriteByte('}') case IDTypeArray: b.WriteByte('[') tv = formatTypeValue(tv, b) b.WriteByte(']') case IDTypeSet: b.WriteString("|[") tv = formatTypeValue(tv, b) b.WriteString("]|") case IDTypeMap: b.WriteString("|{") tv = formatTypeValue(tv, b) b.WriteByte(':') tv = formatTypeValue(tv, b) b.WriteString("}|") case IDTypeUnion: b.WriteByte('(') var n int n, tv = decodeInt(tv) if tv == nil { truncErr(b) return nil } for k := 0; k < n; k++ { if k > 0 { b.WriteByte(',') } tv = formatTypeValue(tv, b) } b.WriteByte(')') case IDTypeEnum: b.WriteByte('<') var n int n, tv = decodeInt(tv) if tv == nil { truncErr(b) return nil } for k := 0; k < n; k++ { if k > 0 { b.WriteByte(',') } var symbol string symbol, tv = decodeNameAndCheck(tv, b) if tv == nil { return nil } b.WriteString(QuotedName(symbol)) } b.WriteByte('>') default: if id < 0 || id > IDTypeDef { b.WriteString(fmt.Sprintf("<ERR bad type ID %d in type value>", id)) return nil } typ := LookupPrimitiveByID(int(id)) b.WriteString(typ.String()) } return tv } func decodeNameAndCheck(tv zcode.Bytes, b *strings.Builder) (string, zcode.Bytes) { var name string name, tv = decodeName(tv) if tv == nil { truncErr(b) } return name, tv } func decodeName(tv zcode.Bytes) (string, zcode.Bytes) { namelen, tv := decodeInt(tv) if tv == nil || int(namelen) > len(tv) { return "", nil } return string(tv[:namelen]), tv[namelen:] } func decodeInt(tv zcode.Bytes) (int, zcode.Bytes) { if len(tv) < 0 { return 0, nil } namelen, n := binary.Uvarint(tv) if n <= 0 { return 0, nil } return int(namelen), tv[n:] }
typetype.go
0.513668
0.481576
typetype.go
starcoder