id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
11,200
paulmach/go.geo
bound.go
ToMysqlIntersectsCondition
func (b *Bound) ToMysqlIntersectsCondition(column string) string { return fmt.Sprintf("INTERSECTS(%s, GEOMFROMTEXT('%s'))", column, b.String()) }
go
func (b *Bound) ToMysqlIntersectsCondition(column string) string { return fmt.Sprintf("INTERSECTS(%s, GEOMFROMTEXT('%s'))", column, b.String()) }
[ "func", "(", "b", "*", "Bound", ")", "ToMysqlIntersectsCondition", "(", "column", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "column", ",", "b", ".", "String", "(", ")", ")", "\n", "}" ]
// ToMysqlIntersectsCondition returns a condition defining the intersection // of the column and the bound. To be used in a MySQL query.
[ "ToMysqlIntersectsCondition", "returns", "a", "condition", "defining", "the", "intersection", "of", "the", "column", "and", "the", "bound", ".", "To", "be", "used", "in", "a", "MySQL", "query", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/bound.go#L395-L397
11,201
paulmach/go.geo
surface.go
GradientAt
func (s *Surface) GradientAt(point *Point) *Point { if !s.bound.Contains(point) { return NewPoint(0, 0) } xi, yi, deltaX, deltaY := s.gridCoordinate(point) xi1 := xi + 1 if limit := s.Width - 1; xi1 > limit { xi = limit - 1 xi1 = limit deltaX = 1.0 } yi1 := yi + 1 if limit := s.Height - 1; yi1 > limit { yi = limit - 1 yi1 = limit deltaY = 1.0 } u1 := s.Grid[xi][yi]*(1-deltaX) + s.Grid[xi1][yi]*deltaX u2 := s.Grid[xi][yi1]*(1-deltaX) + s.Grid[xi1][yi1]*deltaX w1 := (1 - deltaY) * (s.Grid[xi1][yi] - s.Grid[xi][yi]) w2 := deltaY * (s.Grid[xi1][yi1] - s.Grid[xi][yi1]) return NewPoint((w1+w2)/s.gridBoxWidth(), (u2-u1)/s.gridBoxHeight()) }
go
func (s *Surface) GradientAt(point *Point) *Point { if !s.bound.Contains(point) { return NewPoint(0, 0) } xi, yi, deltaX, deltaY := s.gridCoordinate(point) xi1 := xi + 1 if limit := s.Width - 1; xi1 > limit { xi = limit - 1 xi1 = limit deltaX = 1.0 } yi1 := yi + 1 if limit := s.Height - 1; yi1 > limit { yi = limit - 1 yi1 = limit deltaY = 1.0 } u1 := s.Grid[xi][yi]*(1-deltaX) + s.Grid[xi1][yi]*deltaX u2 := s.Grid[xi][yi1]*(1-deltaX) + s.Grid[xi1][yi1]*deltaX w1 := (1 - deltaY) * (s.Grid[xi1][yi] - s.Grid[xi][yi]) w2 := deltaY * (s.Grid[xi1][yi1] - s.Grid[xi][yi1]) return NewPoint((w1+w2)/s.gridBoxWidth(), (u2-u1)/s.gridBoxHeight()) }
[ "func", "(", "s", "*", "Surface", ")", "GradientAt", "(", "point", "*", "Point", ")", "*", "Point", "{", "if", "!", "s", ".", "bound", ".", "Contains", "(", "point", ")", "{", "return", "NewPoint", "(", "0", ",", "0", ")", "\n", "}", "\n\n", "xi", ",", "yi", ",", "deltaX", ",", "deltaY", ":=", "s", ".", "gridCoordinate", "(", "point", ")", "\n\n", "xi1", ":=", "xi", "+", "1", "\n", "if", "limit", ":=", "s", ".", "Width", "-", "1", ";", "xi1", ">", "limit", "{", "xi", "=", "limit", "-", "1", "\n", "xi1", "=", "limit", "\n", "deltaX", "=", "1.0", "\n", "}", "\n\n", "yi1", ":=", "yi", "+", "1", "\n", "if", "limit", ":=", "s", ".", "Height", "-", "1", ";", "yi1", ">", "limit", "{", "yi", "=", "limit", "-", "1", "\n", "yi1", "=", "limit", "\n", "deltaY", "=", "1.0", "\n", "}", "\n\n", "u1", ":=", "s", ".", "Grid", "[", "xi", "]", "[", "yi", "]", "*", "(", "1", "-", "deltaX", ")", "+", "s", ".", "Grid", "[", "xi1", "]", "[", "yi", "]", "*", "deltaX", "\n", "u2", ":=", "s", ".", "Grid", "[", "xi", "]", "[", "yi1", "]", "*", "(", "1", "-", "deltaX", ")", "+", "s", ".", "Grid", "[", "xi1", "]", "[", "yi1", "]", "*", "deltaX", "\n\n", "w1", ":=", "(", "1", "-", "deltaY", ")", "*", "(", "s", ".", "Grid", "[", "xi1", "]", "[", "yi", "]", "-", "s", ".", "Grid", "[", "xi", "]", "[", "yi", "]", ")", "\n", "w2", ":=", "deltaY", "*", "(", "s", ".", "Grid", "[", "xi1", "]", "[", "yi1", "]", "-", "s", ".", "Grid", "[", "xi", "]", "[", "yi1", "]", ")", "\n\n", "return", "NewPoint", "(", "(", "w1", "+", "w2", ")", "/", "s", ".", "gridBoxWidth", "(", ")", ",", "(", "u2", "-", "u1", ")", "/", "s", ".", "gridBoxHeight", "(", ")", ")", "\n", "}" ]
// GradientAt returns the surface gradient at the given point. // Bilinearlly interpolates the grid cell to find the gradient.
[ "GradientAt", "returns", "the", "surface", "gradient", "at", "the", "given", "point", ".", "Bilinearlly", "interpolates", "the", "grid", "cell", "to", "find", "the", "gradient", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/surface.go#L89-L117
11,202
paulmach/go.geo
surface.go
gridBoxWidth
func (s Surface) gridBoxWidth() float64 { return s.bound.Width() / float64(s.Width-1) }
go
func (s Surface) gridBoxWidth() float64 { return s.bound.Width() / float64(s.Width-1) }
[ "func", "(", "s", "Surface", ")", "gridBoxWidth", "(", ")", "float64", "{", "return", "s", ".", "bound", ".", "Width", "(", ")", "/", "float64", "(", "s", ".", "Width", "-", "1", ")", "\n", "}" ]
// gridBoxWidth returns the width of a grid element in the units of s.Bound.
[ "gridBoxWidth", "returns", "the", "width", "of", "a", "grid", "element", "in", "the", "units", "of", "s", ".", "Bound", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/surface.go#L154-L156
11,203
paulmach/go.geo
surface.go
gridBoxHeight
func (s Surface) gridBoxHeight() float64 { return s.bound.Height() / float64(s.Height-1) }
go
func (s Surface) gridBoxHeight() float64 { return s.bound.Height() / float64(s.Height-1) }
[ "func", "(", "s", "Surface", ")", "gridBoxHeight", "(", ")", "float64", "{", "return", "s", ".", "bound", ".", "Height", "(", ")", "/", "float64", "(", "s", ".", "Height", "-", "1", ")", "\n", "}" ]
// gridBoxHeight returns the height of a grid element in the units of s.Bound.
[ "gridBoxHeight", "returns", "the", "height", "of", "a", "grid", "element", "in", "the", "units", "of", "s", ".", "Bound", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/surface.go#L159-L161
11,204
paulmach/go.geo
clustering/combiner.go
ClusterCombiners
func ClusterCombiners(combiners []Combiner, threshold float64) []Combiner { if len(combiners) < 2 { return combiners } s := &state{ Distances: initializeCombinerDistances(combiners, threshold), DistanceFunc: func(a, b int) float64 { return combiners[a].DistanceFromCombiner(combiners[b]) }, } // successively merge for i := 1; i < len(combiners); i++ { lower, higher, dist := s.MinDistance() if dist > threshold { break } // merge these two combiners[lower] = combiners[lower].Combine(combiners[higher]) s.ResetDistances(lower, higher) combiners[higher] = nil } last := len(combiners) - 1 for i := range combiners { if combiners[i] == nil { combiners[i] = combiners[last] last-- } } return combiners[:last+1] }
go
func ClusterCombiners(combiners []Combiner, threshold float64) []Combiner { if len(combiners) < 2 { return combiners } s := &state{ Distances: initializeCombinerDistances(combiners, threshold), DistanceFunc: func(a, b int) float64 { return combiners[a].DistanceFromCombiner(combiners[b]) }, } // successively merge for i := 1; i < len(combiners); i++ { lower, higher, dist := s.MinDistance() if dist > threshold { break } // merge these two combiners[lower] = combiners[lower].Combine(combiners[higher]) s.ResetDistances(lower, higher) combiners[higher] = nil } last := len(combiners) - 1 for i := range combiners { if combiners[i] == nil { combiners[i] = combiners[last] last-- } } return combiners[:last+1] }
[ "func", "ClusterCombiners", "(", "combiners", "[", "]", "Combiner", ",", "threshold", "float64", ")", "[", "]", "Combiner", "{", "if", "len", "(", "combiners", ")", "<", "2", "{", "return", "combiners", "\n", "}", "\n\n", "s", ":=", "&", "state", "{", "Distances", ":", "initializeCombinerDistances", "(", "combiners", ",", "threshold", ")", ",", "DistanceFunc", ":", "func", "(", "a", ",", "b", "int", ")", "float64", "{", "return", "combiners", "[", "a", "]", ".", "DistanceFromCombiner", "(", "combiners", "[", "b", "]", ")", "\n", "}", ",", "}", "\n\n", "// successively merge", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "combiners", ")", ";", "i", "++", "{", "lower", ",", "higher", ",", "dist", ":=", "s", ".", "MinDistance", "(", ")", "\n", "if", "dist", ">", "threshold", "{", "break", "\n", "}", "\n\n", "// merge these two", "combiners", "[", "lower", "]", "=", "combiners", "[", "lower", "]", ".", "Combine", "(", "combiners", "[", "higher", "]", ")", "\n", "s", ".", "ResetDistances", "(", "lower", ",", "higher", ")", "\n", "combiners", "[", "higher", "]", "=", "nil", "\n", "}", "\n\n", "last", ":=", "len", "(", "combiners", ")", "-", "1", "\n", "for", "i", ":=", "range", "combiners", "{", "if", "combiners", "[", "i", "]", "==", "nil", "{", "combiners", "[", "i", "]", "=", "combiners", "[", "last", "]", "\n", "last", "--", "\n", "}", "\n", "}", "\n\n", "return", "combiners", "[", ":", "last", "+", "1", "]", "\n", "}" ]
// ClusterCombiners will do a simple hierarchical of the combiners. // It will modify the input slice as things will be combined into each other.
[ "ClusterCombiners", "will", "do", "a", "simple", "hierarchical", "of", "the", "combiners", ".", "It", "will", "modify", "the", "input", "slice", "as", "things", "will", "be", "combined", "into", "each", "other", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/combiner.go#L13-L47
11,205
paulmach/go.geo
clustering/distance_set.go
newDistanceSet
func newDistanceSet() *distanceSet { return &distanceSet{ MinDistance: math.MaxFloat64, Distances: make(map[int]float64, 500), // adding 500 was a 20% performance win } }
go
func newDistanceSet() *distanceSet { return &distanceSet{ MinDistance: math.MaxFloat64, Distances: make(map[int]float64, 500), // adding 500 was a 20% performance win } }
[ "func", "newDistanceSet", "(", ")", "*", "distanceSet", "{", "return", "&", "distanceSet", "{", "MinDistance", ":", "math", ".", "MaxFloat64", ",", "Distances", ":", "make", "(", "map", "[", "int", "]", "float64", ",", "500", ")", ",", "// adding 500 was a 20% performance win", "}", "\n", "}" ]
// newDistanceSet creates a new distance set.
[ "newDistanceSet", "creates", "a", "new", "distance", "set", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/distance_set.go#L15-L20
11,206
paulmach/go.geo
clustering/distance_set.go
Set
func (ds *distanceSet) Set(index int, distance float64) bool { if d, ok := ds.Distances[index]; ok && index == ds.MinIndex && distance > d { // minimum index is being made greater, need to reset ds.Distances[index] = distance ds.reset() return true } ds.Distances[index] = distance if distance < ds.MinDistance { ds.MinDistance = distance ds.MinIndex = index return true } return false }
go
func (ds *distanceSet) Set(index int, distance float64) bool { if d, ok := ds.Distances[index]; ok && index == ds.MinIndex && distance > d { // minimum index is being made greater, need to reset ds.Distances[index] = distance ds.reset() return true } ds.Distances[index] = distance if distance < ds.MinDistance { ds.MinDistance = distance ds.MinIndex = index return true } return false }
[ "func", "(", "ds", "*", "distanceSet", ")", "Set", "(", "index", "int", ",", "distance", "float64", ")", "bool", "{", "if", "d", ",", "ok", ":=", "ds", ".", "Distances", "[", "index", "]", ";", "ok", "&&", "index", "==", "ds", ".", "MinIndex", "&&", "distance", ">", "d", "{", "// minimum index is being made greater, need to reset", "ds", ".", "Distances", "[", "index", "]", "=", "distance", "\n", "ds", ".", "reset", "(", ")", "\n", "return", "true", "\n", "}", "\n\n", "ds", ".", "Distances", "[", "index", "]", "=", "distance", "\n", "if", "distance", "<", "ds", ".", "MinDistance", "{", "ds", ".", "MinDistance", "=", "distance", "\n", "ds", ".", "MinIndex", "=", "index", "\n", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Set sets the distance for a given index // and updates the denormalized min distance if necessary. // Returns true if the minimum has been updated.
[ "Set", "sets", "the", "distance", "for", "a", "given", "index", "and", "updates", "the", "denormalized", "min", "distance", "if", "necessary", ".", "Returns", "true", "if", "the", "minimum", "has", "been", "updated", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/distance_set.go#L25-L41
11,207
paulmach/go.geo
clustering/distance_set.go
Delete
func (ds *distanceSet) Delete(index int) bool { delete(ds.Distances, index) if index == ds.MinIndex { ds.reset() return true } return false }
go
func (ds *distanceSet) Delete(index int) bool { delete(ds.Distances, index) if index == ds.MinIndex { ds.reset() return true } return false }
[ "func", "(", "ds", "*", "distanceSet", ")", "Delete", "(", "index", "int", ")", "bool", "{", "delete", "(", "ds", ".", "Distances", ",", "index", ")", "\n", "if", "index", "==", "ds", ".", "MinIndex", "{", "ds", ".", "reset", "(", ")", "\n", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Delete removes a values for an index and resets denormalized minimum. // Returns true if the minimum has been updated.
[ "Delete", "removes", "a", "values", "for", "an", "index", "and", "resets", "denormalized", "minimum", ".", "Returns", "true", "if", "the", "minimum", "has", "been", "updated", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/distance_set.go#L45-L53
11,208
paulmach/go.geo
clustering/distance_set.go
reset
func (ds *distanceSet) reset() { minDist := math.MaxFloat64 minIndex := 0 for i, d := range ds.Distances { if d < minDist { minDist = d minIndex = i } } ds.MinIndex = minIndex ds.MinDistance = minDist }
go
func (ds *distanceSet) reset() { minDist := math.MaxFloat64 minIndex := 0 for i, d := range ds.Distances { if d < minDist { minDist = d minIndex = i } } ds.MinIndex = minIndex ds.MinDistance = minDist }
[ "func", "(", "ds", "*", "distanceSet", ")", "reset", "(", ")", "{", "minDist", ":=", "math", ".", "MaxFloat64", "\n", "minIndex", ":=", "0", "\n", "for", "i", ",", "d", ":=", "range", "ds", ".", "Distances", "{", "if", "d", "<", "minDist", "{", "minDist", "=", "d", "\n", "minIndex", "=", "i", "\n", "}", "\n", "}", "\n\n", "ds", ".", "MinIndex", "=", "minIndex", "\n", "ds", ".", "MinDistance", "=", "minDist", "\n", "}" ]
// reset refinds the denormalized minimum. Can be used if manually updating values. // not part of the official api.
[ "reset", "refinds", "the", "denormalized", "minimum", ".", "Can", "be", "used", "if", "manually", "updating", "values", ".", "not", "part", "of", "the", "official", "api", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/distance_set.go#L57-L69
11,209
paulmach/go.geo
line.go
NewLine
func NewLine(a, b *Point) *Line { return &Line{*a.Clone(), *b.Clone()} }
go
func NewLine(a, b *Point) *Line { return &Line{*a.Clone(), *b.Clone()} }
[ "func", "NewLine", "(", "a", ",", "b", "*", "Point", ")", "*", "Line", "{", "return", "&", "Line", "{", "*", "a", ".", "Clone", "(", ")", ",", "*", "b", ".", "Clone", "(", ")", "}", "\n", "}" ]
// NewLine creates a new line by cloning the provided points.
[ "NewLine", "creates", "a", "new", "line", "by", "cloning", "the", "provided", "points", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L16-L18
11,210
paulmach/go.geo
line.go
Transform
func (l *Line) Transform(projector Projector) *Line { projector(&l.a) projector(&l.b) return l }
go
func (l *Line) Transform(projector Projector) *Line { projector(&l.a) projector(&l.b) return l }
[ "func", "(", "l", "*", "Line", ")", "Transform", "(", "projector", "Projector", ")", "*", "Line", "{", "projector", "(", "&", "l", ".", "a", ")", "\n", "projector", "(", "&", "l", ".", "b", ")", "\n\n", "return", "l", "\n", "}" ]
// Transform applies a given projection or inverse projection to the current line. // Modifies the line.
[ "Transform", "applies", "a", "given", "projection", "or", "inverse", "projection", "to", "the", "current", "line", ".", "Modifies", "the", "line", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L22-L27
11,211
paulmach/go.geo
line.go
DistanceFrom
func (l *Line) DistanceFrom(point *Point) float64 { // yes duplicate code, but saw a 15% performance increase by removing the function call // return math.Sqrt(l.SquaredDistanceFrom(point)) x := l.a[0] y := l.a[1] dx := l.b[0] - x dy := l.b[1] - y if dx != 0 || dy != 0 { t := ((point[0]-x)*dx + (point[1]-y)*dy) / (dx*dx + dy*dy) if t > 1 { x = l.b[0] y = l.b[1] } else if t > 0 { x += dx * t y += dy * t } } dx = point[0] - x dy = point[1] - y return math.Sqrt(dx*dx + dy*dy) }
go
func (l *Line) DistanceFrom(point *Point) float64 { // yes duplicate code, but saw a 15% performance increase by removing the function call // return math.Sqrt(l.SquaredDistanceFrom(point)) x := l.a[0] y := l.a[1] dx := l.b[0] - x dy := l.b[1] - y if dx != 0 || dy != 0 { t := ((point[0]-x)*dx + (point[1]-y)*dy) / (dx*dx + dy*dy) if t > 1 { x = l.b[0] y = l.b[1] } else if t > 0 { x += dx * t y += dy * t } } dx = point[0] - x dy = point[1] - y return math.Sqrt(dx*dx + dy*dy) }
[ "func", "(", "l", "*", "Line", ")", "DistanceFrom", "(", "point", "*", "Point", ")", "float64", "{", "// yes duplicate code, but saw a 15% performance increase by removing the function call", "// return math.Sqrt(l.SquaredDistanceFrom(point))", "x", ":=", "l", ".", "a", "[", "0", "]", "\n", "y", ":=", "l", ".", "a", "[", "1", "]", "\n", "dx", ":=", "l", ".", "b", "[", "0", "]", "-", "x", "\n", "dy", ":=", "l", ".", "b", "[", "1", "]", "-", "y", "\n\n", "if", "dx", "!=", "0", "||", "dy", "!=", "0", "{", "t", ":=", "(", "(", "point", "[", "0", "]", "-", "x", ")", "*", "dx", "+", "(", "point", "[", "1", "]", "-", "y", ")", "*", "dy", ")", "/", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", "\n\n", "if", "t", ">", "1", "{", "x", "=", "l", ".", "b", "[", "0", "]", "\n", "y", "=", "l", ".", "b", "[", "1", "]", "\n", "}", "else", "if", "t", ">", "0", "{", "x", "+=", "dx", "*", "t", "\n", "y", "+=", "dy", "*", "t", "\n", "}", "\n", "}", "\n\n", "dx", "=", "point", "[", "0", "]", "-", "x", "\n", "dy", "=", "point", "[", "1", "]", "-", "y", "\n\n", "return", "math", ".", "Sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", "\n", "}" ]
// DistanceFrom does NOT use spherical geometry. It finds the distance from // the line using standard Euclidean geometry, using the units the points are in.
[ "DistanceFrom", "does", "NOT", "use", "spherical", "geometry", ".", "It", "finds", "the", "distance", "from", "the", "line", "using", "standard", "Euclidean", "geometry", "using", "the", "units", "the", "points", "are", "in", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L31-L55
11,212
paulmach/go.geo
line.go
SquaredDistanceFrom
func (l *Line) SquaredDistanceFrom(point *Point) float64 { x := l.a[0] y := l.a[1] dx := l.b[0] - x dy := l.b[1] - y if dx != 0 || dy != 0 { t := ((point[0]-x)*dx + (point[1]-y)*dy) / (dx*dx + dy*dy) if t > 1 { x = l.b[0] y = l.b[1] } else if t > 0 { x += dx * t y += dy * t } } dx = point[0] - x dy = point[1] - y return dx*dx + dy*dy }
go
func (l *Line) SquaredDistanceFrom(point *Point) float64 { x := l.a[0] y := l.a[1] dx := l.b[0] - x dy := l.b[1] - y if dx != 0 || dy != 0 { t := ((point[0]-x)*dx + (point[1]-y)*dy) / (dx*dx + dy*dy) if t > 1 { x = l.b[0] y = l.b[1] } else if t > 0 { x += dx * t y += dy * t } } dx = point[0] - x dy = point[1] - y return dx*dx + dy*dy }
[ "func", "(", "l", "*", "Line", ")", "SquaredDistanceFrom", "(", "point", "*", "Point", ")", "float64", "{", "x", ":=", "l", ".", "a", "[", "0", "]", "\n", "y", ":=", "l", ".", "a", "[", "1", "]", "\n", "dx", ":=", "l", ".", "b", "[", "0", "]", "-", "x", "\n", "dy", ":=", "l", ".", "b", "[", "1", "]", "-", "y", "\n\n", "if", "dx", "!=", "0", "||", "dy", "!=", "0", "{", "t", ":=", "(", "(", "point", "[", "0", "]", "-", "x", ")", "*", "dx", "+", "(", "point", "[", "1", "]", "-", "y", ")", "*", "dy", ")", "/", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", "\n\n", "if", "t", ">", "1", "{", "x", "=", "l", ".", "b", "[", "0", "]", "\n", "y", "=", "l", ".", "b", "[", "1", "]", "\n", "}", "else", "if", "t", ">", "0", "{", "x", "+=", "dx", "*", "t", "\n", "y", "+=", "dy", "*", "t", "\n", "}", "\n", "}", "\n\n", "dx", "=", "point", "[", "0", "]", "-", "x", "\n", "dy", "=", "point", "[", "1", "]", "-", "y", "\n\n", "return", "dx", "*", "dx", "+", "dy", "*", "dy", "\n", "}" ]
// SquaredDistanceFrom does NOT use spherical geometry. It finds the squared distance from // the line using standard Euclidean geometry, using the units the points are in.
[ "SquaredDistanceFrom", "does", "NOT", "use", "spherical", "geometry", ".", "It", "finds", "the", "squared", "distance", "from", "the", "line", "using", "standard", "Euclidean", "geometry", "using", "the", "units", "the", "points", "are", "in", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L59-L81
11,213
paulmach/go.geo
line.go
GeoDistance
func (l *Line) GeoDistance(haversine ...bool) float64 { return l.a.GeoDistanceFrom(&l.b, yesHaversine(haversine)) }
go
func (l *Line) GeoDistance(haversine ...bool) float64 { return l.a.GeoDistanceFrom(&l.b, yesHaversine(haversine)) }
[ "func", "(", "l", "*", "Line", ")", "GeoDistance", "(", "haversine", "...", "bool", ")", "float64", "{", "return", "l", ".", "a", ".", "GeoDistanceFrom", "(", "&", "l", ".", "b", ",", "yesHaversine", "(", "haversine", ")", ")", "\n", "}" ]
// GeoDistance computes the distance of the line, ie. its length, using spherical geometry.
[ "GeoDistance", "computes", "the", "distance", "of", "the", "line", "ie", ".", "its", "length", "using", "spherical", "geometry", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L95-L97
11,214
paulmach/go.geo
line.go
Measure
func (l *Line) Measure(point *Point) float64 { projFactor := l.Project(point) if projFactor <= 0.0 { return 0.0 } if projFactor <= 1.0 { return projFactor * l.Distance() } // projFactor is > 1 return l.Distance() }
go
func (l *Line) Measure(point *Point) float64 { projFactor := l.Project(point) if projFactor <= 0.0 { return 0.0 } if projFactor <= 1.0 { return projFactor * l.Distance() } // projFactor is > 1 return l.Distance() }
[ "func", "(", "l", "*", "Line", ")", "Measure", "(", "point", "*", "Point", ")", "float64", "{", "projFactor", ":=", "l", ".", "Project", "(", "point", ")", "\n", "if", "projFactor", "<=", "0.0", "{", "return", "0.0", "\n", "}", "\n", "if", "projFactor", "<=", "1.0", "{", "return", "projFactor", "*", "l", ".", "Distance", "(", ")", "\n", "}", "\n", "// projFactor is > 1", "return", "l", ".", "Distance", "(", ")", "\n", "}" ]
// Measure returns the distance along the line to the point nearest the given point. // Treats the line as a line segment such that if the nearest point is an endpoint of the line, // the function will return 0 or 1 as appropriate.
[ "Measure", "returns", "the", "distance", "along", "the", "line", "to", "the", "point", "nearest", "the", "given", "point", ".", "Treats", "the", "line", "as", "a", "line", "segment", "such", "that", "if", "the", "nearest", "point", "is", "an", "endpoint", "of", "the", "line", "the", "function", "will", "return", "0", "or", "1", "as", "appropriate", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L130-L140
11,215
paulmach/go.geo
line.go
Interpolate
func (l *Line) Interpolate(percent float64) *Point { return &Point{ l.a[0] + percent*(l.b[0]-l.a[0]), l.a[1] + percent*(l.b[1]-l.a[1]), } }
go
func (l *Line) Interpolate(percent float64) *Point { return &Point{ l.a[0] + percent*(l.b[0]-l.a[0]), l.a[1] + percent*(l.b[1]-l.a[1]), } }
[ "func", "(", "l", "*", "Line", ")", "Interpolate", "(", "percent", "float64", ")", "*", "Point", "{", "return", "&", "Point", "{", "l", ".", "a", "[", "0", "]", "+", "percent", "*", "(", "l", ".", "b", "[", "0", "]", "-", "l", ".", "a", "[", "0", "]", ")", ",", "l", ".", "a", "[", "1", "]", "+", "percent", "*", "(", "l", ".", "b", "[", "1", "]", "-", "l", ".", "a", "[", "1", "]", ")", ",", "}", "\n", "}" ]
// Interpolate performs a simple linear interpolation, from A to B. // This function is the opposite of Project.
[ "Interpolate", "performs", "a", "simple", "linear", "interpolation", "from", "A", "to", "B", ".", "This", "function", "is", "the", "opposite", "of", "Project", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L144-L149
11,216
paulmach/go.geo
line.go
Side
func (l *Line) Side(p *Point) int { val := (l.b[0]-l.a[0])*(p[1]-l.b[1]) - (l.b[1]-l.a[1])*(p[0]-l.b[0]) if val < 0 { return 1 // right } else if val > 0 { return -1 // left } return 0 // collinear }
go
func (l *Line) Side(p *Point) int { val := (l.b[0]-l.a[0])*(p[1]-l.b[1]) - (l.b[1]-l.a[1])*(p[0]-l.b[0]) if val < 0 { return 1 // right } else if val > 0 { return -1 // left } return 0 // collinear }
[ "func", "(", "l", "*", "Line", ")", "Side", "(", "p", "*", "Point", ")", "int", "{", "val", ":=", "(", "l", ".", "b", "[", "0", "]", "-", "l", ".", "a", "[", "0", "]", ")", "*", "(", "p", "[", "1", "]", "-", "l", ".", "b", "[", "1", "]", ")", "-", "(", "l", ".", "b", "[", "1", "]", "-", "l", ".", "a", "[", "1", "]", ")", "*", "(", "p", "[", "0", "]", "-", "l", ".", "b", "[", "0", "]", ")", "\n\n", "if", "val", "<", "0", "{", "return", "1", "// right", "\n", "}", "else", "if", "val", ">", "0", "{", "return", "-", "1", "// left", "\n", "}", "\n\n", "return", "0", "// collinear", "\n", "}" ]
// Side returns 1 if the point is on the right side, -1 if on the left side, and 0 if collinear.
[ "Side", "returns", "1", "if", "the", "point", "is", "on", "the", "right", "side", "-", "1", "if", "on", "the", "left", "side", "and", "0", "if", "collinear", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L152-L162
11,217
paulmach/go.geo
line.go
Midpoint
func (l *Line) Midpoint() *Point { return &Point{(l.a[0] + l.b[0]) / 2, (l.a[1] + l.b[1]) / 2} }
go
func (l *Line) Midpoint() *Point { return &Point{(l.a[0] + l.b[0]) / 2, (l.a[1] + l.b[1]) / 2} }
[ "func", "(", "l", "*", "Line", ")", "Midpoint", "(", ")", "*", "Point", "{", "return", "&", "Point", "{", "(", "l", ".", "a", "[", "0", "]", "+", "l", ".", "b", "[", "0", "]", ")", "/", "2", ",", "(", "l", ".", "a", "[", "1", "]", "+", "l", ".", "b", "[", "1", "]", ")", "/", "2", "}", "\n", "}" ]
// Midpoint returns the Euclidean midpoint of the line.
[ "Midpoint", "returns", "the", "Euclidean", "midpoint", "of", "the", "line", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L229-L231
11,218
paulmach/go.geo
line.go
GeoMidpoint
func (l *Line) GeoMidpoint() *Point { p := &Point{} dLng := deg2rad(l.b.Lng() - l.a.Lng()) aLatRad := deg2rad(l.a.Lat()) bLatRad := deg2rad(l.b.Lat()) x := math.Cos(bLatRad) * math.Cos(dLng) y := math.Cos(bLatRad) * math.Sin(dLng) p.SetLat(math.Atan2(math.Sin(aLatRad)+math.Sin(bLatRad), math.Sqrt((math.Cos(aLatRad)+x)*(math.Cos(aLatRad)+x)+y*y))) p.SetLng(deg2rad(l.a.Lng()) + math.Atan2(y, math.Cos(aLatRad)+x)) // convert back to degrees p.SetLat(rad2deg(p.Lat())) p.SetLng(rad2deg(p.Lng())) return p }
go
func (l *Line) GeoMidpoint() *Point { p := &Point{} dLng := deg2rad(l.b.Lng() - l.a.Lng()) aLatRad := deg2rad(l.a.Lat()) bLatRad := deg2rad(l.b.Lat()) x := math.Cos(bLatRad) * math.Cos(dLng) y := math.Cos(bLatRad) * math.Sin(dLng) p.SetLat(math.Atan2(math.Sin(aLatRad)+math.Sin(bLatRad), math.Sqrt((math.Cos(aLatRad)+x)*(math.Cos(aLatRad)+x)+y*y))) p.SetLng(deg2rad(l.a.Lng()) + math.Atan2(y, math.Cos(aLatRad)+x)) // convert back to degrees p.SetLat(rad2deg(p.Lat())) p.SetLng(rad2deg(p.Lng())) return p }
[ "func", "(", "l", "*", "Line", ")", "GeoMidpoint", "(", ")", "*", "Point", "{", "p", ":=", "&", "Point", "{", "}", "\n\n", "dLng", ":=", "deg2rad", "(", "l", ".", "b", ".", "Lng", "(", ")", "-", "l", ".", "a", ".", "Lng", "(", ")", ")", "\n\n", "aLatRad", ":=", "deg2rad", "(", "l", ".", "a", ".", "Lat", "(", ")", ")", "\n", "bLatRad", ":=", "deg2rad", "(", "l", ".", "b", ".", "Lat", "(", ")", ")", "\n\n", "x", ":=", "math", ".", "Cos", "(", "bLatRad", ")", "*", "math", ".", "Cos", "(", "dLng", ")", "\n", "y", ":=", "math", ".", "Cos", "(", "bLatRad", ")", "*", "math", ".", "Sin", "(", "dLng", ")", "\n\n", "p", ".", "SetLat", "(", "math", ".", "Atan2", "(", "math", ".", "Sin", "(", "aLatRad", ")", "+", "math", ".", "Sin", "(", "bLatRad", ")", ",", "math", ".", "Sqrt", "(", "(", "math", ".", "Cos", "(", "aLatRad", ")", "+", "x", ")", "*", "(", "math", ".", "Cos", "(", "aLatRad", ")", "+", "x", ")", "+", "y", "*", "y", ")", ")", ")", "\n", "p", ".", "SetLng", "(", "deg2rad", "(", "l", ".", "a", ".", "Lng", "(", ")", ")", "+", "math", ".", "Atan2", "(", "y", ",", "math", ".", "Cos", "(", "aLatRad", ")", "+", "x", ")", ")", "\n\n", "// convert back to degrees", "p", ".", "SetLat", "(", "rad2deg", "(", "p", ".", "Lat", "(", ")", ")", ")", "\n", "p", ".", "SetLng", "(", "rad2deg", "(", "p", ".", "Lng", "(", ")", ")", ")", "\n\n", "return", "p", "\n", "}" ]
// GeoMidpoint returns the half-way point along a great circle path between the two points.
[ "GeoMidpoint", "returns", "the", "half", "-", "way", "point", "along", "a", "great", "circle", "path", "between", "the", "two", "points", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L234-L253
11,219
paulmach/go.geo
line.go
Bound
func (l *Line) Bound() *Bound { return NewBound(math.Max(l.a[0], l.b[0]), math.Min(l.a[0], l.b[0]), math.Max(l.a[1], l.b[1]), math.Min(l.a[1], l.b[1])) }
go
func (l *Line) Bound() *Bound { return NewBound(math.Max(l.a[0], l.b[0]), math.Min(l.a[0], l.b[0]), math.Max(l.a[1], l.b[1]), math.Min(l.a[1], l.b[1])) }
[ "func", "(", "l", "*", "Line", ")", "Bound", "(", ")", "*", "Bound", "{", "return", "NewBound", "(", "math", ".", "Max", "(", "l", ".", "a", "[", "0", "]", ",", "l", ".", "b", "[", "0", "]", ")", ",", "math", ".", "Min", "(", "l", ".", "a", "[", "0", "]", ",", "l", ".", "b", "[", "0", "]", ")", ",", "math", ".", "Max", "(", "l", ".", "a", "[", "1", "]", ",", "l", ".", "b", "[", "1", "]", ")", ",", "math", ".", "Min", "(", "l", ".", "a", "[", "1", "]", ",", "l", ".", "b", "[", "1", "]", ")", ")", "\n", "}" ]
// Bound returns a bound around the line. Simply uses rectangular coordinates.
[ "Bound", "returns", "a", "bound", "around", "the", "line", ".", "Simply", "uses", "rectangular", "coordinates", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L256-L259
11,220
paulmach/go.geo
line.go
Reverse
func (l *Line) Reverse() *Line { l.a, l.b = l.b, l.a return l }
go
func (l *Line) Reverse() *Line { l.a, l.b = l.b, l.a return l }
[ "func", "(", "l", "*", "Line", ")", "Reverse", "(", ")", "*", "Line", "{", "l", ".", "a", ",", "l", ".", "b", "=", "l", ".", "b", ",", "l", ".", "a", "\n", "return", "l", "\n", "}" ]
// Reverse swaps the start and end of the line.
[ "Reverse", "swaps", "the", "start", "and", "end", "of", "the", "line", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L262-L265
11,221
paulmach/go.geo
line.go
Equals
func (l *Line) Equals(line *Line) bool { return (l.a.Equals(&line.a) && l.b.Equals(&line.b)) || (l.a.Equals(&line.b) && l.b.Equals(&line.a)) }
go
func (l *Line) Equals(line *Line) bool { return (l.a.Equals(&line.a) && l.b.Equals(&line.b)) || (l.a.Equals(&line.b) && l.b.Equals(&line.a)) }
[ "func", "(", "l", "*", "Line", ")", "Equals", "(", "line", "*", "Line", ")", "bool", "{", "return", "(", "l", ".", "a", ".", "Equals", "(", "&", "line", ".", "a", ")", "&&", "l", ".", "b", ".", "Equals", "(", "&", "line", ".", "b", ")", ")", "||", "(", "l", ".", "a", ".", "Equals", "(", "&", "line", ".", "b", ")", "&&", "l", ".", "b", ".", "Equals", "(", "&", "line", ".", "a", ")", ")", "\n", "}" ]
// Equals returns the line equality and is irrespective of direction, // i.e. true if one is the reverse of the other.
[ "Equals", "returns", "the", "line", "equality", "and", "is", "irrespective", "of", "direction", "i", ".", "e", ".", "true", "if", "one", "is", "the", "reverse", "of", "the", "other", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L269-L271
11,222
paulmach/go.geo
line.go
ToGeoJSON
func (l *Line) ToGeoJSON() *geojson.Feature { return geojson.NewLineStringFeature([][]float64{ {l.a[0], l.a[1]}, {l.b[0], l.b[1]}, }) }
go
func (l *Line) ToGeoJSON() *geojson.Feature { return geojson.NewLineStringFeature([][]float64{ {l.a[0], l.a[1]}, {l.b[0], l.b[1]}, }) }
[ "func", "(", "l", "*", "Line", ")", "ToGeoJSON", "(", ")", "*", "geojson", ".", "Feature", "{", "return", "geojson", ".", "NewLineStringFeature", "(", "[", "]", "[", "]", "float64", "{", "{", "l", ".", "a", "[", "0", "]", ",", "l", ".", "a", "[", "1", "]", "}", ",", "{", "l", ".", "b", "[", "0", "]", ",", "l", ".", "b", "[", "1", "]", "}", ",", "}", ")", "\n", "}" ]
// ToGeoJSON creates a new geojson feature with a linestring geometry // containing the two points.
[ "ToGeoJSON", "creates", "a", "new", "geojson", "feature", "with", "a", "linestring", "geometry", "containing", "the", "two", "points", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/line.go#L290-L295
11,223
paulmach/go.geo
reducers/douglas_peucker.go
Reduce
func (r DouglasPeuckerReducer) Reduce(path *geo.Path) *geo.Path { return DouglasPeucker(path, r.Threshold) }
go
func (r DouglasPeuckerReducer) Reduce(path *geo.Path) *geo.Path { return DouglasPeucker(path, r.Threshold) }
[ "func", "(", "r", "DouglasPeuckerReducer", ")", "Reduce", "(", "path", "*", "geo", ".", "Path", ")", "*", "geo", ".", "Path", "{", "return", "DouglasPeucker", "(", "path", ",", "r", ".", "Threshold", ")", "\n", "}" ]
// Reduce runs the DouglasPeucker using the threshold of the DouglasPeuckerReducer.
[ "Reduce", "runs", "the", "DouglasPeucker", "using", "the", "threshold", "of", "the", "DouglasPeuckerReducer", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/douglas_peucker.go#L21-L23
11,224
paulmach/go.geo
reducers/douglas_peucker.go
DouglasPeucker
func DouglasPeucker(path *geo.Path, threshold float64) *geo.Path { if path.Length() <= 2 { return path.Clone() } mask := make([]byte, path.Length()) mask[0] = 1 mask[path.Length()-1] = 1 points := path.Points() found := dpWorker(points, threshold, mask) newPoints := make([]geo.Point, 0, found) for i, v := range mask { if v == 1 { newPoints = append(newPoints, points[i]) } } return (&geo.Path{}).SetPoints(newPoints) }
go
func DouglasPeucker(path *geo.Path, threshold float64) *geo.Path { if path.Length() <= 2 { return path.Clone() } mask := make([]byte, path.Length()) mask[0] = 1 mask[path.Length()-1] = 1 points := path.Points() found := dpWorker(points, threshold, mask) newPoints := make([]geo.Point, 0, found) for i, v := range mask { if v == 1 { newPoints = append(newPoints, points[i]) } } return (&geo.Path{}).SetPoints(newPoints) }
[ "func", "DouglasPeucker", "(", "path", "*", "geo", ".", "Path", ",", "threshold", "float64", ")", "*", "geo", ".", "Path", "{", "if", "path", ".", "Length", "(", ")", "<=", "2", "{", "return", "path", ".", "Clone", "(", ")", "\n", "}", "\n\n", "mask", ":=", "make", "(", "[", "]", "byte", ",", "path", ".", "Length", "(", ")", ")", "\n", "mask", "[", "0", "]", "=", "1", "\n", "mask", "[", "path", ".", "Length", "(", ")", "-", "1", "]", "=", "1", "\n\n", "points", ":=", "path", ".", "Points", "(", ")", "\n\n", "found", ":=", "dpWorker", "(", "points", ",", "threshold", ",", "mask", ")", "\n", "newPoints", ":=", "make", "(", "[", "]", "geo", ".", "Point", ",", "0", ",", "found", ")", "\n\n", "for", "i", ",", "v", ":=", "range", "mask", "{", "if", "v", "==", "1", "{", "newPoints", "=", "append", "(", "newPoints", ",", "points", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n\n", "return", "(", "&", "geo", ".", "Path", "{", "}", ")", ".", "SetPoints", "(", "newPoints", ")", "\n", "}" ]
// DouglasPeucker simplifies the path using the Douglas Peucker method. // Returns a new path and DOES NOT modify the original.
[ "DouglasPeucker", "simplifies", "the", "path", "using", "the", "Douglas", "Peucker", "method", ".", "Returns", "a", "new", "path", "and", "DOES", "NOT", "modify", "the", "original", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/douglas_peucker.go#L37-L58
11,225
paulmach/go.geo
reducers/douglas_peucker.go
DouglasPeuckerIndexMap
func DouglasPeuckerIndexMap(path *geo.Path, threshold float64) (reduced *geo.Path, indexMap []int) { if path.Length() == 0 { return path.Clone(), []int{} } if path.Length() == 1 { return path.Clone(), []int{0} } if path.Length() == 2 { return path.Clone(), []int{0, 1} } mask := make([]byte, path.Length()) mask[0] = 1 mask[path.Length()-1] = 1 originalPoints := path.Points() found := dpWorker(originalPoints, threshold, mask) points := make([]geo.Point, 0, found) for i, v := range mask { if v == 1 { points = append(points, originalPoints[i]) indexMap = append(indexMap, i) } } reduced = &geo.Path{} return reduced.SetPoints(points), indexMap }
go
func DouglasPeuckerIndexMap(path *geo.Path, threshold float64) (reduced *geo.Path, indexMap []int) { if path.Length() == 0 { return path.Clone(), []int{} } if path.Length() == 1 { return path.Clone(), []int{0} } if path.Length() == 2 { return path.Clone(), []int{0, 1} } mask := make([]byte, path.Length()) mask[0] = 1 mask[path.Length()-1] = 1 originalPoints := path.Points() found := dpWorker(originalPoints, threshold, mask) points := make([]geo.Point, 0, found) for i, v := range mask { if v == 1 { points = append(points, originalPoints[i]) indexMap = append(indexMap, i) } } reduced = &geo.Path{} return reduced.SetPoints(points), indexMap }
[ "func", "DouglasPeuckerIndexMap", "(", "path", "*", "geo", ".", "Path", ",", "threshold", "float64", ")", "(", "reduced", "*", "geo", ".", "Path", ",", "indexMap", "[", "]", "int", ")", "{", "if", "path", ".", "Length", "(", ")", "==", "0", "{", "return", "path", ".", "Clone", "(", ")", ",", "[", "]", "int", "{", "}", "\n", "}", "\n\n", "if", "path", ".", "Length", "(", ")", "==", "1", "{", "return", "path", ".", "Clone", "(", ")", ",", "[", "]", "int", "{", "0", "}", "\n", "}", "\n\n", "if", "path", ".", "Length", "(", ")", "==", "2", "{", "return", "path", ".", "Clone", "(", ")", ",", "[", "]", "int", "{", "0", ",", "1", "}", "\n", "}", "\n\n", "mask", ":=", "make", "(", "[", "]", "byte", ",", "path", ".", "Length", "(", ")", ")", "\n", "mask", "[", "0", "]", "=", "1", "\n", "mask", "[", "path", ".", "Length", "(", ")", "-", "1", "]", "=", "1", "\n\n", "originalPoints", ":=", "path", ".", "Points", "(", ")", "\n\n", "found", ":=", "dpWorker", "(", "originalPoints", ",", "threshold", ",", "mask", ")", "\n\n", "points", ":=", "make", "(", "[", "]", "geo", ".", "Point", ",", "0", ",", "found", ")", "\n", "for", "i", ",", "v", ":=", "range", "mask", "{", "if", "v", "==", "1", "{", "points", "=", "append", "(", "points", ",", "originalPoints", "[", "i", "]", ")", "\n", "indexMap", "=", "append", "(", "indexMap", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "reduced", "=", "&", "geo", ".", "Path", "{", "}", "\n", "return", "reduced", ".", "SetPoints", "(", "points", ")", ",", "indexMap", "\n", "}" ]
// DouglasPeuckerIndexMap is similar to DouglasPeucker but returns an array that maps // each new path index to its original path index. // Returns a new path and DOES NOT modify the original.
[ "DouglasPeuckerIndexMap", "is", "similar", "to", "DouglasPeucker", "but", "returns", "an", "array", "that", "maps", "each", "new", "path", "index", "to", "its", "original", "path", "index", ".", "Returns", "a", "new", "path", "and", "DOES", "NOT", "modify", "the", "original", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/douglas_peucker.go#L63-L94
11,226
paulmach/go.geo
reducers/douglas_peucker.go
DouglasPeuckerGeoIndexMap
func DouglasPeuckerGeoIndexMap(path *geo.Path, meters float64) (reduced *geo.Path, indexMap []int) { if path.Length() == 0 { return path.Clone(), []int{} } if path.Length() == 1 { return path.Clone(), []int{0} } if path.Length() == 2 { return path.Clone(), []int{0, 1} } mask := make([]byte, path.Length()) mask[0] = 1 mask[path.Length()-1] = 1 factor := geo.MercatorScaleFactor(path.Bound().Center().Lat()) originalPoints := path.Clone().Transform(geo.Mercator.Project).Points() found := dpWorker(originalPoints, meters*factor, mask) points := make([]geo.Point, 0, found) for i, v := range mask { if v == 1 { points = append(points, originalPoints[i]) indexMap = append(indexMap, i) } } reduced = &geo.Path{} reduced.SetPoints(points) reduced.Transform(geo.Mercator.Inverse) return reduced, indexMap }
go
func DouglasPeuckerGeoIndexMap(path *geo.Path, meters float64) (reduced *geo.Path, indexMap []int) { if path.Length() == 0 { return path.Clone(), []int{} } if path.Length() == 1 { return path.Clone(), []int{0} } if path.Length() == 2 { return path.Clone(), []int{0, 1} } mask := make([]byte, path.Length()) mask[0] = 1 mask[path.Length()-1] = 1 factor := geo.MercatorScaleFactor(path.Bound().Center().Lat()) originalPoints := path.Clone().Transform(geo.Mercator.Project).Points() found := dpWorker(originalPoints, meters*factor, mask) points := make([]geo.Point, 0, found) for i, v := range mask { if v == 1 { points = append(points, originalPoints[i]) indexMap = append(indexMap, i) } } reduced = &geo.Path{} reduced.SetPoints(points) reduced.Transform(geo.Mercator.Inverse) return reduced, indexMap }
[ "func", "DouglasPeuckerGeoIndexMap", "(", "path", "*", "geo", ".", "Path", ",", "meters", "float64", ")", "(", "reduced", "*", "geo", ".", "Path", ",", "indexMap", "[", "]", "int", ")", "{", "if", "path", ".", "Length", "(", ")", "==", "0", "{", "return", "path", ".", "Clone", "(", ")", ",", "[", "]", "int", "{", "}", "\n", "}", "\n\n", "if", "path", ".", "Length", "(", ")", "==", "1", "{", "return", "path", ".", "Clone", "(", ")", ",", "[", "]", "int", "{", "0", "}", "\n", "}", "\n\n", "if", "path", ".", "Length", "(", ")", "==", "2", "{", "return", "path", ".", "Clone", "(", ")", ",", "[", "]", "int", "{", "0", ",", "1", "}", "\n", "}", "\n\n", "mask", ":=", "make", "(", "[", "]", "byte", ",", "path", ".", "Length", "(", ")", ")", "\n", "mask", "[", "0", "]", "=", "1", "\n", "mask", "[", "path", ".", "Length", "(", ")", "-", "1", "]", "=", "1", "\n\n", "factor", ":=", "geo", ".", "MercatorScaleFactor", "(", "path", ".", "Bound", "(", ")", ".", "Center", "(", ")", ".", "Lat", "(", ")", ")", "\n", "originalPoints", ":=", "path", ".", "Clone", "(", ")", ".", "Transform", "(", "geo", ".", "Mercator", ".", "Project", ")", ".", "Points", "(", ")", "\n", "found", ":=", "dpWorker", "(", "originalPoints", ",", "meters", "*", "factor", ",", "mask", ")", "\n\n", "points", ":=", "make", "(", "[", "]", "geo", ".", "Point", ",", "0", ",", "found", ")", "\n", "for", "i", ",", "v", ":=", "range", "mask", "{", "if", "v", "==", "1", "{", "points", "=", "append", "(", "points", ",", "originalPoints", "[", "i", "]", ")", "\n", "indexMap", "=", "append", "(", "indexMap", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "reduced", "=", "&", "geo", ".", "Path", "{", "}", "\n", "reduced", ".", "SetPoints", "(", "points", ")", "\n", "reduced", ".", "Transform", "(", "geo", ".", "Mercator", ".", "Inverse", ")", "\n", "return", "reduced", ",", "indexMap", "\n", "}" ]
// DouglasPeuckerGeoIndexMap is similar to GeoReduce but returns an array that maps // each new path index to its original path index. // Returns a new path and DOES NOT modify the original.
[ "DouglasPeuckerGeoIndexMap", "is", "similar", "to", "GeoReduce", "but", "returns", "an", "array", "that", "maps", "each", "new", "path", "index", "to", "its", "original", "path", "index", ".", "Returns", "a", "new", "path", "and", "DOES", "NOT", "modify", "the", "original", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/douglas_peucker.go#L99-L132
11,227
paulmach/go.geo
path_resample.go
Resample
func (p *Path) Resample(totalPoints int) *Path { if totalPoints <= 0 { p.PointSet = make([]Point, 0) return p } if p.resampleEdgeCases(totalPoints) { return p } // precomputes the total distance and intermediate distances total, dists := precomputeDistances(p.PointSet) p.resample(dists, total, totalPoints) return p }
go
func (p *Path) Resample(totalPoints int) *Path { if totalPoints <= 0 { p.PointSet = make([]Point, 0) return p } if p.resampleEdgeCases(totalPoints) { return p } // precomputes the total distance and intermediate distances total, dists := precomputeDistances(p.PointSet) p.resample(dists, total, totalPoints) return p }
[ "func", "(", "p", "*", "Path", ")", "Resample", "(", "totalPoints", "int", ")", "*", "Path", "{", "if", "totalPoints", "<=", "0", "{", "p", ".", "PointSet", "=", "make", "(", "[", "]", "Point", ",", "0", ")", "\n", "return", "p", "\n", "}", "\n\n", "if", "p", ".", "resampleEdgeCases", "(", "totalPoints", ")", "{", "return", "p", "\n", "}", "\n\n", "// precomputes the total distance and intermediate distances", "total", ",", "dists", ":=", "precomputeDistances", "(", "p", ".", "PointSet", ")", "\n", "p", ".", "resample", "(", "dists", ",", "total", ",", "totalPoints", ")", "\n", "return", "p", "\n", "}" ]
// Resample converts the path into totalPoints-1 evenly spaced segments. // Assumes euclidean geometry.
[ "Resample", "converts", "the", "path", "into", "totalPoints", "-", "1", "evenly", "spaced", "segments", ".", "Assumes", "euclidean", "geometry", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/path_resample.go#L5-L19
11,228
paulmach/go.geo
path_resample.go
ResampleWithInterval
func (p *Path) ResampleWithInterval(dist float64) *Path { if dist <= 0 { p.PointSet = make([]Point, 0) return p } // precomputes the total distance and intermediate distances total, dists := precomputeDistances(p.PointSet) totalPoints := int(total/dist) + 1 if p.resampleEdgeCases(totalPoints) { return p } p.resample(dists, total, totalPoints) return p }
go
func (p *Path) ResampleWithInterval(dist float64) *Path { if dist <= 0 { p.PointSet = make([]Point, 0) return p } // precomputes the total distance and intermediate distances total, dists := precomputeDistances(p.PointSet) totalPoints := int(total/dist) + 1 if p.resampleEdgeCases(totalPoints) { return p } p.resample(dists, total, totalPoints) return p }
[ "func", "(", "p", "*", "Path", ")", "ResampleWithInterval", "(", "dist", "float64", ")", "*", "Path", "{", "if", "dist", "<=", "0", "{", "p", ".", "PointSet", "=", "make", "(", "[", "]", "Point", ",", "0", ")", "\n", "return", "p", "\n", "}", "\n\n", "// precomputes the total distance and intermediate distances", "total", ",", "dists", ":=", "precomputeDistances", "(", "p", ".", "PointSet", ")", "\n\n", "totalPoints", ":=", "int", "(", "total", "/", "dist", ")", "+", "1", "\n", "if", "p", ".", "resampleEdgeCases", "(", "totalPoints", ")", "{", "return", "p", "\n", "}", "\n\n", "p", ".", "resample", "(", "dists", ",", "total", ",", "totalPoints", ")", "\n", "return", "p", "\n", "}" ]
// ResampleWithInterval coverts the path into evenly spaced points of // about the given distance. The total distance is computed using euclidean // geometry and then divided by the given distance to get the number of segments.
[ "ResampleWithInterval", "coverts", "the", "path", "into", "evenly", "spaced", "points", "of", "about", "the", "given", "distance", ".", "The", "total", "distance", "is", "computed", "using", "euclidean", "geometry", "and", "then", "divided", "by", "the", "given", "distance", "to", "get", "the", "number", "of", "segments", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/path_resample.go#L24-L40
11,229
paulmach/go.geo
path_resample.go
resampleEdgeCases
func (p *Path) resampleEdgeCases(totalPoints int) bool { // degenerate case if len(p.PointSet) <= 1 { return true } // if all the points are the same, treat as special case. equal := true for _, point := range p.PointSet { if !p.PointSet[0].Equals(&point) { equal = false break } } if equal { if totalPoints > p.Length() { // extend to be requested length for p.Length() != totalPoints { p.PointSet = append(p.PointSet, p.PointSet[0]) } return true } // contract to be requested length p.PointSet = p.PointSet[:totalPoints] return true } return false }
go
func (p *Path) resampleEdgeCases(totalPoints int) bool { // degenerate case if len(p.PointSet) <= 1 { return true } // if all the points are the same, treat as special case. equal := true for _, point := range p.PointSet { if !p.PointSet[0].Equals(&point) { equal = false break } } if equal { if totalPoints > p.Length() { // extend to be requested length for p.Length() != totalPoints { p.PointSet = append(p.PointSet, p.PointSet[0]) } return true } // contract to be requested length p.PointSet = p.PointSet[:totalPoints] return true } return false }
[ "func", "(", "p", "*", "Path", ")", "resampleEdgeCases", "(", "totalPoints", "int", ")", "bool", "{", "// degenerate case", "if", "len", "(", "p", ".", "PointSet", ")", "<=", "1", "{", "return", "true", "\n", "}", "\n\n", "// if all the points are the same, treat as special case.", "equal", ":=", "true", "\n", "for", "_", ",", "point", ":=", "range", "p", ".", "PointSet", "{", "if", "!", "p", ".", "PointSet", "[", "0", "]", ".", "Equals", "(", "&", "point", ")", "{", "equal", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "equal", "{", "if", "totalPoints", ">", "p", ".", "Length", "(", ")", "{", "// extend to be requested length", "for", "p", ".", "Length", "(", ")", "!=", "totalPoints", "{", "p", ".", "PointSet", "=", "append", "(", "p", ".", "PointSet", ",", "p", ".", "PointSet", "[", "0", "]", ")", "\n", "}", "\n\n", "return", "true", "\n", "}", "\n\n", "// contract to be requested length", "p", ".", "PointSet", "=", "p", ".", "PointSet", "[", ":", "totalPoints", "]", "\n", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// resampleEdgeCases is used to handle edge case for // resampling like not enough points and the path is all the same point. // will return nil if there are no edge cases. If return true if // one of these edge cases was found and handled.
[ "resampleEdgeCases", "is", "used", "to", "handle", "edge", "case", "for", "resampling", "like", "not", "enough", "points", "and", "the", "path", "is", "all", "the", "same", "point", ".", "will", "return", "nil", "if", "there", "are", "no", "edge", "cases", ".", "If", "return", "true", "if", "one", "of", "these", "edge", "cases", "was", "found", "and", "handled", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/path_resample.go#L119-L150
11,230
paulmach/go.geo
clustering/sort.go
Less
func (s Sortable) Less(i, j int) bool { return len(s[i].Pointers) > len(s[j].Pointers) }
go
func (s Sortable) Less(i, j int) bool { return len(s[i].Pointers) > len(s[j].Pointers) }
[ "func", "(", "s", "Sortable", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "len", "(", "s", "[", "i", "]", ".", "Pointers", ")", ">", "len", "(", "s", "[", "j", "]", ".", "Pointers", ")", "\n\n", "}" ]
// Less returns truee if i > j, so bigger will be first. // This is to implement the sort interface.
[ "Less", "returns", "truee", "if", "i", ">", "j", "so", "bigger", "will", "be", "first", ".", "This", "is", "to", "implement", "the", "sort", "interface", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/sort.go#L25-L28
11,231
paulmach/go.geo
clustering/sort.go
Swap
func (s Sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
go
func (s Sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
[ "func", "(", "s", "Sortable", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "s", "[", "i", "]", ",", "s", "[", "j", "]", "=", "s", "[", "j", "]", ",", "s", "[", "i", "]", "\n", "}" ]
// Swap interchanges two elements. // This is to implement the sort interface.
[ "Swap", "interchanges", "two", "elements", ".", "This", "is", "to", "implement", "the", "sort", "interface", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/sort.go#L32-L34
11,232
paulmach/go.geo
reducers/radial.go
Reduce
func (r RadialReducer) Reduce(path *geo.Path) *geo.Path { return Radial(path, r.Threshold) }
go
func (r RadialReducer) Reduce(path *geo.Path) *geo.Path { return Radial(path, r.Threshold) }
[ "func", "(", "r", "RadialReducer", ")", "Reduce", "(", "path", "*", "geo", ".", "Path", ")", "*", "geo", ".", "Path", "{", "return", "Radial", "(", "path", ",", "r", ".", "Threshold", ")", "\n", "}" ]
// Reduce runs the Radial reduction using the threshold of the RadialReducer.
[ "Reduce", "runs", "the", "Radial", "reduction", "using", "the", "threshold", "of", "the", "RadialReducer", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/radial.go#L23-L25
11,233
paulmach/go.geo
reducers/radial.go
Reduce
func (r RadialGeoReducer) Reduce(path *geo.Path) *geo.Path { return RadialGeo(path, r.Threshold) }
go
func (r RadialGeoReducer) Reduce(path *geo.Path) *geo.Path { return RadialGeo(path, r.Threshold) }
[ "func", "(", "r", "RadialGeoReducer", ")", "Reduce", "(", "path", "*", "geo", ".", "Path", ")", "*", "geo", ".", "Path", "{", "return", "RadialGeo", "(", "path", ",", "r", ".", "Threshold", ")", "\n", "}" ]
// Reduce runs the RadialGeo reduction using the threshold of the RadialGeoReducer. // The threshold is expected to be in meters.
[ "Reduce", "runs", "the", "RadialGeo", "reduction", "using", "the", "threshold", "of", "the", "RadialGeoReducer", ".", "The", "threshold", "is", "expected", "to", "be", "in", "meters", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/radial.go#L49-L51
11,234
paulmach/go.geo
reducers/radial.go
Radial
func Radial(path *geo.Path, meters float64) *geo.Path { p, _ := radialCore(path, meters*meters, squaredDistance, false) return p }
go
func Radial(path *geo.Path, meters float64) *geo.Path { p, _ := radialCore(path, meters*meters, squaredDistance, false) return p }
[ "func", "Radial", "(", "path", "*", "geo", ".", "Path", ",", "meters", "float64", ")", "*", "geo", ".", "Path", "{", "p", ",", "_", ":=", "radialCore", "(", "path", ",", "meters", "*", "meters", ",", "squaredDistance", ",", "false", ")", "\n", "return", "p", "\n", "}" ]
// Radial peforms a radial distance polyline simplification using a standard euclidean distance. // Returns a new path and DOES NOT modify the original.
[ "Radial", "peforms", "a", "radial", "distance", "polyline", "simplification", "using", "a", "standard", "euclidean", "distance", ".", "Returns", "a", "new", "path", "and", "DOES", "NOT", "modify", "the", "original", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/radial.go#L61-L64
11,235
paulmach/go.geo
reducers/radial.go
RadialIndexMap
func RadialIndexMap(path *geo.Path, meters float64) (*geo.Path, []int) { return radialCore(path, meters*meters, squaredDistance, true) }
go
func RadialIndexMap(path *geo.Path, meters float64) (*geo.Path, []int) { return radialCore(path, meters*meters, squaredDistance, true) }
[ "func", "RadialIndexMap", "(", "path", "*", "geo", ".", "Path", ",", "meters", "float64", ")", "(", "*", "geo", ".", "Path", ",", "[", "]", "int", ")", "{", "return", "radialCore", "(", "path", ",", "meters", "*", "meters", ",", "squaredDistance", ",", "true", ")", "\n", "}" ]
// RadialIndexMap is similar to Radial but returns an array that maps // each new path index to its original path index. // Returns a new path and DOES NOT modify the original.
[ "RadialIndexMap", "is", "similar", "to", "Radial", "but", "returns", "an", "array", "that", "maps", "each", "new", "path", "index", "to", "its", "original", "path", "index", ".", "Returns", "a", "new", "path", "and", "DOES", "NOT", "modify", "the", "original", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/radial.go#L69-L71
11,236
paulmach/go.geo
reducers/radial.go
RadialGeoIndexMap
func RadialGeoIndexMap(path *geo.Path, meters float64) (*geo.Path, []int) { return radialCore(path, meters, geoDistance, true) }
go
func RadialGeoIndexMap(path *geo.Path, meters float64) (*geo.Path, []int) { return radialCore(path, meters, geoDistance, true) }
[ "func", "RadialGeoIndexMap", "(", "path", "*", "geo", ".", "Path", ",", "meters", "float64", ")", "(", "*", "geo", ".", "Path", ",", "[", "]", "int", ")", "{", "return", "radialCore", "(", "path", ",", "meters", ",", "geoDistance", ",", "true", ")", "\n", "}" ]
// RadialGeoIndexMap is similar to RadialGeo but returns an array that maps // each new path index to its original path index. // Returns a new path and DOES NOT modify the original.
[ "RadialGeoIndexMap", "is", "similar", "to", "RadialGeo", "but", "returns", "an", "array", "that", "maps", "each", "new", "path", "index", "to", "its", "original", "path", "index", ".", "Returns", "a", "new", "path", "and", "DOES", "NOT", "modify", "the", "original", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/radial.go#L84-L86
11,237
paulmach/go.geo
clustering/set.go
ResetDistances
func (s *state) ResetDistances(into, from int) { // since the center of into changed, need to update the distance to anything linked to this one. for k := range s.Distances[into].Distances { if k == into { continue } dist := s.DistanceFunc(into, k) s.Distances[into].Set(k, dist) s.Distances[k].Set(into, dist) } // we are merging from into into. // so any links with from need to be links with into. // any links into from need to be deleted // we no longer need the distance info of from for k := range s.Distances[from].Distances { if k == from || k == into { continue } dist := s.DistanceFunc(into, k) s.Distances[into].Set(k, dist) s.Distances[k].Set(into, dist) s.Distances[k].Delete(from) } s.Distances[from] = nil s.Distances[into].Delete(from) }
go
func (s *state) ResetDistances(into, from int) { // since the center of into changed, need to update the distance to anything linked to this one. for k := range s.Distances[into].Distances { if k == into { continue } dist := s.DistanceFunc(into, k) s.Distances[into].Set(k, dist) s.Distances[k].Set(into, dist) } // we are merging from into into. // so any links with from need to be links with into. // any links into from need to be deleted // we no longer need the distance info of from for k := range s.Distances[from].Distances { if k == from || k == into { continue } dist := s.DistanceFunc(into, k) s.Distances[into].Set(k, dist) s.Distances[k].Set(into, dist) s.Distances[k].Delete(from) } s.Distances[from] = nil s.Distances[into].Delete(from) }
[ "func", "(", "s", "*", "state", ")", "ResetDistances", "(", "into", ",", "from", "int", ")", "{", "// since the center of into changed, need to update the distance to anything linked to this one.", "for", "k", ":=", "range", "s", ".", "Distances", "[", "into", "]", ".", "Distances", "{", "if", "k", "==", "into", "{", "continue", "\n", "}", "\n\n", "dist", ":=", "s", ".", "DistanceFunc", "(", "into", ",", "k", ")", "\n\n", "s", ".", "Distances", "[", "into", "]", ".", "Set", "(", "k", ",", "dist", ")", "\n", "s", ".", "Distances", "[", "k", "]", ".", "Set", "(", "into", ",", "dist", ")", "\n", "}", "\n\n", "// we are merging from into into.", "// so any links with from need to be links with into.", "// any links into from need to be deleted", "// we no longer need the distance info of from", "for", "k", ":=", "range", "s", ".", "Distances", "[", "from", "]", ".", "Distances", "{", "if", "k", "==", "from", "||", "k", "==", "into", "{", "continue", "\n", "}", "\n\n", "dist", ":=", "s", ".", "DistanceFunc", "(", "into", ",", "k", ")", "\n\n", "s", ".", "Distances", "[", "into", "]", ".", "Set", "(", "k", ",", "dist", ")", "\n", "s", ".", "Distances", "[", "k", "]", ".", "Set", "(", "into", ",", "dist", ")", "\n\n", "s", ".", "Distances", "[", "k", "]", ".", "Delete", "(", "from", ")", "\n", "}", "\n\n", "s", ".", "Distances", "[", "from", "]", "=", "nil", "\n", "s", ".", "Distances", "[", "into", "]", ".", "Delete", "(", "from", ")", "\n", "}" ]
// ResetDistances makes sure the distance map is up to date given the recent merge of clusters.
[ "ResetDistances", "makes", "sure", "the", "distance", "map", "is", "up", "to", "date", "given", "the", "recent", "merge", "of", "clusters", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/set.go#L13-L45
11,238
paulmach/go.geo
clustering/set.go
MinDistance
func (s *state) MinDistance() (a, b int, dist float64) { dist = math.MaxFloat64 for i, ds := range s.Distances { if ds == nil { continue } if ds.MinDistance < dist { dist = ds.MinDistance a = i b = ds.MinIndex } } return }
go
func (s *state) MinDistance() (a, b int, dist float64) { dist = math.MaxFloat64 for i, ds := range s.Distances { if ds == nil { continue } if ds.MinDistance < dist { dist = ds.MinDistance a = i b = ds.MinIndex } } return }
[ "func", "(", "s", "*", "state", ")", "MinDistance", "(", ")", "(", "a", ",", "b", "int", ",", "dist", "float64", ")", "{", "dist", "=", "math", ".", "MaxFloat64", "\n\n", "for", "i", ",", "ds", ":=", "range", "s", ".", "Distances", "{", "if", "ds", "==", "nil", "{", "continue", "\n", "}", "\n\n", "if", "ds", ".", "MinDistance", "<", "dist", "{", "dist", "=", "ds", ".", "MinDistance", "\n\n", "a", "=", "i", "\n", "b", "=", "ds", ".", "MinIndex", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// MinDistance returns the link with minimum distance. // a is the index stored on the DistanceSet, b is the index of the smallest values.
[ "MinDistance", "returns", "the", "link", "with", "minimum", "distance", ".", "a", "is", "the", "index", "stored", "on", "the", "DistanceSet", "b", "is", "the", "index", "of", "the", "smallest", "values", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/set.go#L49-L66
11,239
paulmach/go.geo
reducers/merge.go
MergeIndexMaps
func MergeIndexMaps(map1, map2 []int) []int { result := make([]int, len(map2)) for i, v := range map2 { result[i] = map1[v] } return result }
go
func MergeIndexMaps(map1, map2 []int) []int { result := make([]int, len(map2)) for i, v := range map2 { result[i] = map1[v] } return result }
[ "func", "MergeIndexMaps", "(", "map1", ",", "map2", "[", "]", "int", ")", "[", "]", "int", "{", "result", ":=", "make", "(", "[", "]", "int", ",", "len", "(", "map2", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "map2", "{", "result", "[", "i", "]", "=", "map1", "[", "v", "]", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// MergeIndexMaps merges two index maps for use when chaining reducers. // For example, to radially reduce and then DP, merge the index maps with this function // to get a map from the original to the final path.
[ "MergeIndexMaps", "merges", "two", "index", "maps", "for", "use", "when", "chaining", "reducers", ".", "For", "example", "to", "radially", "reduce", "and", "then", "DP", "merge", "the", "index", "maps", "with", "this", "function", "to", "get", "a", "map", "from", "the", "original", "to", "the", "final", "path", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/reducers/merge.go#L6-L13
11,240
paulmach/go.geo
clustering/clustering.go
ClusterPointers
func ClusterPointers(pointers []geo.Pointer, distancer ClusterDistancer, threshold float64) []*Cluster { clusters := make([]*Cluster, 0, len(pointers)) for _, p := range pointers { clusters = append(clusters, NewCluster(p)) } return cluster(clusters, distancer, threshold) }
go
func ClusterPointers(pointers []geo.Pointer, distancer ClusterDistancer, threshold float64) []*Cluster { clusters := make([]*Cluster, 0, len(pointers)) for _, p := range pointers { clusters = append(clusters, NewCluster(p)) } return cluster(clusters, distancer, threshold) }
[ "func", "ClusterPointers", "(", "pointers", "[", "]", "geo", ".", "Pointer", ",", "distancer", "ClusterDistancer", ",", "threshold", "float64", ")", "[", "]", "*", "Cluster", "{", "clusters", ":=", "make", "(", "[", "]", "*", "Cluster", ",", "0", ",", "len", "(", "pointers", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "pointers", "{", "clusters", "=", "append", "(", "clusters", ",", "NewCluster", "(", "p", ")", ")", "\n", "}", "\n\n", "return", "cluster", "(", "clusters", ",", "distancer", ",", "threshold", ")", "\n", "}" ]
// ClusterPointers will take a set of Pointers and cluster them using // the distancer and threshold.
[ "ClusterPointers", "will", "take", "a", "set", "of", "Pointers", "and", "cluster", "them", "using", "the", "distancer", "and", "threshold", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/clustering.go#L11-L18
11,241
paulmach/go.geo
clustering/clustering.go
ClusterClusters
func ClusterClusters(clusters []*Cluster, distancer ClusterDistancer, threshold float64) []*Cluster { copiedClusters := make([]*Cluster, len(clusters), len(clusters)) copy(copiedClusters, clusters) return cluster(copiedClusters, distancer, threshold) }
go
func ClusterClusters(clusters []*Cluster, distancer ClusterDistancer, threshold float64) []*Cluster { copiedClusters := make([]*Cluster, len(clusters), len(clusters)) copy(copiedClusters, clusters) return cluster(copiedClusters, distancer, threshold) }
[ "func", "ClusterClusters", "(", "clusters", "[", "]", "*", "Cluster", ",", "distancer", "ClusterDistancer", ",", "threshold", "float64", ")", "[", "]", "*", "Cluster", "{", "copiedClusters", ":=", "make", "(", "[", "]", "*", "Cluster", ",", "len", "(", "clusters", ")", ",", "len", "(", "clusters", ")", ")", "\n", "copy", "(", "copiedClusters", ",", "clusters", ")", "\n\n", "return", "cluster", "(", "copiedClusters", ",", "distancer", ",", "threshold", ")", "\n", "}" ]
// ClusterClusters can be used if you've already created cluster objects // using a prefilterer of something else. Original clusters will be copied // so the original set will be unchanged.
[ "ClusterClusters", "can", "be", "used", "if", "you", "ve", "already", "created", "cluster", "objects", "using", "a", "prefilterer", "of", "something", "else", ".", "Original", "clusters", "will", "be", "copied", "so", "the", "original", "set", "will", "be", "unchanged", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/clustering.go#L23-L28
11,242
paulmach/go.geo
clustering/clustering.go
cluster
func cluster(clusters []*Cluster, distancer ClusterDistancer, threshold float64) []*Cluster { if len(clusters) < 2 { return clusters } count := 0 for _, cluster := range clusters { count += len(cluster.Pointers) } clusters, found := clusterClusters( clusters, // Default initialization, TODO: better bucketing/prefiltering will greatly increase performance. initClusterDistances(clusters, distancer, threshold), distancer, threshold, ) result := make([]*Cluster, 0, found) for _, cluster := range clusters { if cluster != nil { result = append(result, cluster) } } return result }
go
func cluster(clusters []*Cluster, distancer ClusterDistancer, threshold float64) []*Cluster { if len(clusters) < 2 { return clusters } count := 0 for _, cluster := range clusters { count += len(cluster.Pointers) } clusters, found := clusterClusters( clusters, // Default initialization, TODO: better bucketing/prefiltering will greatly increase performance. initClusterDistances(clusters, distancer, threshold), distancer, threshold, ) result := make([]*Cluster, 0, found) for _, cluster := range clusters { if cluster != nil { result = append(result, cluster) } } return result }
[ "func", "cluster", "(", "clusters", "[", "]", "*", "Cluster", ",", "distancer", "ClusterDistancer", ",", "threshold", "float64", ")", "[", "]", "*", "Cluster", "{", "if", "len", "(", "clusters", ")", "<", "2", "{", "return", "clusters", "\n", "}", "\n\n", "count", ":=", "0", "\n", "for", "_", ",", "cluster", ":=", "range", "clusters", "{", "count", "+=", "len", "(", "cluster", ".", "Pointers", ")", "\n", "}", "\n\n", "clusters", ",", "found", ":=", "clusterClusters", "(", "clusters", ",", "// Default initialization, TODO: better bucketing/prefiltering will greatly increase performance.", "initClusterDistances", "(", "clusters", ",", "distancer", ",", "threshold", ")", ",", "distancer", ",", "threshold", ",", ")", "\n\n", "result", ":=", "make", "(", "[", "]", "*", "Cluster", ",", "0", ",", "found", ")", "\n", "for", "_", ",", "cluster", ":=", "range", "clusters", "{", "if", "cluster", "!=", "nil", "{", "result", "=", "append", "(", "result", ",", "cluster", ")", "\n", "}", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// cluster will modify the passed in clusters, centroid and list of pointers, // so a copy must have been made before reaching this function.
[ "cluster", "will", "modify", "the", "passed", "in", "clusters", "centroid", "and", "list", "of", "pointers", "so", "a", "copy", "must", "have", "been", "made", "before", "reaching", "this", "function", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/clustering.go#L32-L58
11,243
paulmach/go.geo
clustering/clustering.go
ClusterGeoPointers
func ClusterGeoPointers(pointers []geo.Pointer, threshold float64) []*Cluster { clusters := make([]*Cluster, 0, len(pointers)) for _, p := range pointers { clusters = append(clusters, NewCluster(p)) } if len(clusters) < 2 { return clusters } // performs the actual clustering return geocluster(clusters, threshold) }
go
func ClusterGeoPointers(pointers []geo.Pointer, threshold float64) []*Cluster { clusters := make([]*Cluster, 0, len(pointers)) for _, p := range pointers { clusters = append(clusters, NewCluster(p)) } if len(clusters) < 2 { return clusters } // performs the actual clustering return geocluster(clusters, threshold) }
[ "func", "ClusterGeoPointers", "(", "pointers", "[", "]", "geo", ".", "Pointer", ",", "threshold", "float64", ")", "[", "]", "*", "Cluster", "{", "clusters", ":=", "make", "(", "[", "]", "*", "Cluster", ",", "0", ",", "len", "(", "pointers", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "pointers", "{", "clusters", "=", "append", "(", "clusters", ",", "NewCluster", "(", "p", ")", ")", "\n", "}", "\n\n", "if", "len", "(", "clusters", ")", "<", "2", "{", "return", "clusters", "\n", "}", "\n\n", "// performs the actual clustering", "return", "geocluster", "(", "clusters", ",", "threshold", ")", "\n", "}" ]
// ClusterGeoPointers will take a set of Pointers and cluster them. // It will project the points using mercator, scale the threshold, cluster, and project back. // Performace is about 40% than simply using a geo distancer. // This may not make sense for all geo datasets.
[ "ClusterGeoPointers", "will", "take", "a", "set", "of", "Pointers", "and", "cluster", "them", ".", "It", "will", "project", "the", "points", "using", "mercator", "scale", "the", "threshold", "cluster", "and", "project", "back", ".", "Performace", "is", "about", "40%", "than", "simply", "using", "a", "geo", "distancer", ".", "This", "may", "not", "make", "sense", "for", "all", "geo", "datasets", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/clustering.go#L64-L76
11,244
paulmach/go.geo
clustering/clustering.go
ClusterGeoClusters
func ClusterGeoClusters(clusters []*Cluster, threshold float64) []*Cluster { if len(clusters) < 2 { return clusters } copiedClusters := make([]*Cluster, len(clusters), len(clusters)) for i, cluster := range clusters { copiedClusters[i] = NewClusterWithCentroid(cluster.Centroid, cluster.Pointers...) } return geocluster(copiedClusters, threshold) }
go
func ClusterGeoClusters(clusters []*Cluster, threshold float64) []*Cluster { if len(clusters) < 2 { return clusters } copiedClusters := make([]*Cluster, len(clusters), len(clusters)) for i, cluster := range clusters { copiedClusters[i] = NewClusterWithCentroid(cluster.Centroid, cluster.Pointers...) } return geocluster(copiedClusters, threshold) }
[ "func", "ClusterGeoClusters", "(", "clusters", "[", "]", "*", "Cluster", ",", "threshold", "float64", ")", "[", "]", "*", "Cluster", "{", "if", "len", "(", "clusters", ")", "<", "2", "{", "return", "clusters", "\n", "}", "\n\n", "copiedClusters", ":=", "make", "(", "[", "]", "*", "Cluster", ",", "len", "(", "clusters", ")", ",", "len", "(", "clusters", ")", ")", "\n", "for", "i", ",", "cluster", ":=", "range", "clusters", "{", "copiedClusters", "[", "i", "]", "=", "NewClusterWithCentroid", "(", "cluster", ".", "Centroid", ",", "cluster", ".", "Pointers", "...", ")", "\n", "}", "\n\n", "return", "geocluster", "(", "copiedClusters", ",", "threshold", ")", "\n", "}" ]
// ClusterGeoClusters can be used if you've already created clusters objects // using a prefilterer of something else.
[ "ClusterGeoClusters", "can", "be", "used", "if", "you", "ve", "already", "created", "clusters", "objects", "using", "a", "prefilterer", "of", "something", "else", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/clustering.go#L80-L91
11,245
paulmach/go.geo
clustering/clustering.go
geocluster
func geocluster(clusters []*Cluster, threshold float64) []*Cluster { if len(clusters) < 2 { return clusters } bound := geo.NewBoundFromPoints(clusters[0].Centroid, clusters[0].Centroid) for _, cluster := range clusters { bound.Extend(cluster.Centroid) geo.Mercator.Project(cluster.Centroid) } factor := geo.MercatorScaleFactor(bound.Center().Lat()) scaledThreshold := threshold * threshold * factor * factor clusteredClusters, found := clusterClusters( clusters, // Default initialization, TODO: better bucketing/prefiltering will greatly increase performance. // can use the bound above to help with this. initClusterDistances(clusters, CentroidSquaredDistance{}, scaledThreshold), CentroidSquaredDistance{}, scaledThreshold, ) result := make([]*Cluster, 0, found) for _, cluster := range clusteredClusters { if cluster != nil { geo.Mercator.Inverse(cluster.Centroid) result = append(result, cluster) } } return result }
go
func geocluster(clusters []*Cluster, threshold float64) []*Cluster { if len(clusters) < 2 { return clusters } bound := geo.NewBoundFromPoints(clusters[0].Centroid, clusters[0].Centroid) for _, cluster := range clusters { bound.Extend(cluster.Centroid) geo.Mercator.Project(cluster.Centroid) } factor := geo.MercatorScaleFactor(bound.Center().Lat()) scaledThreshold := threshold * threshold * factor * factor clusteredClusters, found := clusterClusters( clusters, // Default initialization, TODO: better bucketing/prefiltering will greatly increase performance. // can use the bound above to help with this. initClusterDistances(clusters, CentroidSquaredDistance{}, scaledThreshold), CentroidSquaredDistance{}, scaledThreshold, ) result := make([]*Cluster, 0, found) for _, cluster := range clusteredClusters { if cluster != nil { geo.Mercator.Inverse(cluster.Centroid) result = append(result, cluster) } } return result }
[ "func", "geocluster", "(", "clusters", "[", "]", "*", "Cluster", ",", "threshold", "float64", ")", "[", "]", "*", "Cluster", "{", "if", "len", "(", "clusters", ")", "<", "2", "{", "return", "clusters", "\n", "}", "\n\n", "bound", ":=", "geo", ".", "NewBoundFromPoints", "(", "clusters", "[", "0", "]", ".", "Centroid", ",", "clusters", "[", "0", "]", ".", "Centroid", ")", "\n", "for", "_", ",", "cluster", ":=", "range", "clusters", "{", "bound", ".", "Extend", "(", "cluster", ".", "Centroid", ")", "\n", "geo", ".", "Mercator", ".", "Project", "(", "cluster", ".", "Centroid", ")", "\n", "}", "\n\n", "factor", ":=", "geo", ".", "MercatorScaleFactor", "(", "bound", ".", "Center", "(", ")", ".", "Lat", "(", ")", ")", "\n", "scaledThreshold", ":=", "threshold", "*", "threshold", "*", "factor", "*", "factor", "\n\n", "clusteredClusters", ",", "found", ":=", "clusterClusters", "(", "clusters", ",", "// Default initialization, TODO: better bucketing/prefiltering will greatly increase performance.", "// can use the bound above to help with this.", "initClusterDistances", "(", "clusters", ",", "CentroidSquaredDistance", "{", "}", ",", "scaledThreshold", ")", ",", "CentroidSquaredDistance", "{", "}", ",", "scaledThreshold", ",", ")", "\n\n", "result", ":=", "make", "(", "[", "]", "*", "Cluster", ",", "0", ",", "found", ")", "\n", "for", "_", ",", "cluster", ":=", "range", "clusteredClusters", "{", "if", "cluster", "!=", "nil", "{", "geo", ".", "Mercator", ".", "Inverse", "(", "cluster", ".", "Centroid", ")", "\n", "result", "=", "append", "(", "result", ",", "cluster", ")", "\n", "}", "\n", "}", "\n\n", "return", "result", "\n", "}" ]
// will modify the passed in clusters, centroid and list of pathers, // so a copy must have been made before reaching this function.
[ "will", "modify", "the", "passed", "in", "clusters", "centroid", "and", "list", "of", "pathers", "so", "a", "copy", "must", "have", "been", "made", "before", "reaching", "this", "function", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/clustering/clustering.go#L95-L127
11,246
paulmach/go.geo
point.go
NewPointFromQuadkeyString
func NewPointFromQuadkeyString(key string) *Point { i, _ := strconv.ParseInt(key, 4, 64) return NewPointFromQuadkey(i, len(key)) }
go
func NewPointFromQuadkeyString(key string) *Point { i, _ := strconv.ParseInt(key, 4, 64) return NewPointFromQuadkey(i, len(key)) }
[ "func", "NewPointFromQuadkeyString", "(", "key", "string", ")", "*", "Point", "{", "i", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "key", ",", "4", ",", "64", ")", "\n", "return", "NewPointFromQuadkey", "(", "i", ",", "len", "(", "key", ")", ")", "\n", "}" ]
// NewPointFromQuadkeyString creates a new point from a quadkey string.
[ "NewPointFromQuadkeyString", "creates", "a", "new", "point", "from", "a", "quadkey", "string", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L49-L52
11,247
paulmach/go.geo
point.go
NewPointFromGeoHash
func NewPointFromGeoHash(hash string) *Point { west, east, south, north := geoHash2ranges(hash) return NewPoint((west+east)/2.0, (north+south)/2.0) }
go
func NewPointFromGeoHash(hash string) *Point { west, east, south, north := geoHash2ranges(hash) return NewPoint((west+east)/2.0, (north+south)/2.0) }
[ "func", "NewPointFromGeoHash", "(", "hash", "string", ")", "*", "Point", "{", "west", ",", "east", ",", "south", ",", "north", ":=", "geoHash2ranges", "(", "hash", ")", "\n", "return", "NewPoint", "(", "(", "west", "+", "east", ")", "/", "2.0", ",", "(", "north", "+", "south", ")", "/", "2.0", ")", "\n", "}" ]
// NewPointFromGeoHash creates a new point at the center of the geohash range.
[ "NewPointFromGeoHash", "creates", "a", "new", "point", "at", "the", "center", "of", "the", "geohash", "range", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L55-L58
11,248
paulmach/go.geo
point.go
NewPointFromGeoHashInt64
func NewPointFromGeoHashInt64(hash int64, bits int) *Point { west, east, south, north := geoHashInt2ranges(hash, bits) return NewPoint((west+east)/2.0, (north+south)/2.0) }
go
func NewPointFromGeoHashInt64(hash int64, bits int) *Point { west, east, south, north := geoHashInt2ranges(hash, bits) return NewPoint((west+east)/2.0, (north+south)/2.0) }
[ "func", "NewPointFromGeoHashInt64", "(", "hash", "int64", ",", "bits", "int", ")", "*", "Point", "{", "west", ",", "east", ",", "south", ",", "north", ":=", "geoHashInt2ranges", "(", "hash", ",", "bits", ")", "\n", "return", "NewPoint", "(", "(", "west", "+", "east", ")", "/", "2.0", ",", "(", "north", "+", "south", ")", "/", "2.0", ")", "\n", "}" ]
// NewPointFromGeoHashInt64 creates a new point at the center of the // integer version of a geohash range. bits indicates the precision of the hash.
[ "NewPointFromGeoHashInt64", "creates", "a", "new", "point", "at", "the", "center", "of", "the", "integer", "version", "of", "a", "geohash", "range", ".", "bits", "indicates", "the", "precision", "of", "the", "hash", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L62-L65
11,249
paulmach/go.geo
point.go
DistanceFrom
func (p *Point) DistanceFrom(point *Point) float64 { d0 := (point[0] - p[0]) d1 := (point[1] - p[1]) return math.Sqrt(d0*d0 + d1*d1) }
go
func (p *Point) DistanceFrom(point *Point) float64 { d0 := (point[0] - p[0]) d1 := (point[1] - p[1]) return math.Sqrt(d0*d0 + d1*d1) }
[ "func", "(", "p", "*", "Point", ")", "DistanceFrom", "(", "point", "*", "Point", ")", "float64", "{", "d0", ":=", "(", "point", "[", "0", "]", "-", "p", "[", "0", "]", ")", "\n", "d1", ":=", "(", "point", "[", "1", "]", "-", "p", "[", "1", "]", ")", "\n", "return", "math", ".", "Sqrt", "(", "d0", "*", "d0", "+", "d1", "*", "d1", ")", "\n", "}" ]
// DistanceFrom returns the Euclidean distance between the points.
[ "DistanceFrom", "returns", "the", "Euclidean", "distance", "between", "the", "points", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L79-L83
11,250
paulmach/go.geo
point.go
SquaredDistanceFrom
func (p *Point) SquaredDistanceFrom(point *Point) float64 { d0 := (point[0] - p[0]) d1 := (point[1] - p[1]) return d0*d0 + d1*d1 }
go
func (p *Point) SquaredDistanceFrom(point *Point) float64 { d0 := (point[0] - p[0]) d1 := (point[1] - p[1]) return d0*d0 + d1*d1 }
[ "func", "(", "p", "*", "Point", ")", "SquaredDistanceFrom", "(", "point", "*", "Point", ")", "float64", "{", "d0", ":=", "(", "point", "[", "0", "]", "-", "p", "[", "0", "]", ")", "\n", "d1", ":=", "(", "point", "[", "1", "]", "-", "p", "[", "1", "]", ")", "\n", "return", "d0", "*", "d0", "+", "d1", "*", "d1", "\n", "}" ]
// SquaredDistanceFrom returns the squared Euclidean distance between the points. // This avoids a sqrt computation.
[ "SquaredDistanceFrom", "returns", "the", "squared", "Euclidean", "distance", "between", "the", "points", ".", "This", "avoids", "a", "sqrt", "computation", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L87-L91
11,251
paulmach/go.geo
point.go
GeoDistanceFrom
func (p *Point) GeoDistanceFrom(point *Point, haversine ...bool) float64 { dLat := deg2rad(point.Lat() - p.Lat()) dLng := math.Abs(deg2rad(point.Lng() - p.Lng())) if yesHaversine(haversine) { // yes trig functions dLat2Sin := math.Sin(dLat / 2) dLng2Sin := math.Sin(dLng / 2) a := dLat2Sin*dLat2Sin + math.Cos(deg2rad(p.Lat()))*math.Cos(deg2rad(point.Lat()))*dLng2Sin*dLng2Sin return 2.0 * EarthRadius * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) } if dLng > math.Pi { dLng = 2*math.Pi - dLng } // fast way using pythagorean theorem on an equirectangular projection x := dLng * math.Cos(deg2rad((p.Lat()+point.Lat())/2.0)) return math.Sqrt(dLat*dLat+x*x) * EarthRadius }
go
func (p *Point) GeoDistanceFrom(point *Point, haversine ...bool) float64 { dLat := deg2rad(point.Lat() - p.Lat()) dLng := math.Abs(deg2rad(point.Lng() - p.Lng())) if yesHaversine(haversine) { // yes trig functions dLat2Sin := math.Sin(dLat / 2) dLng2Sin := math.Sin(dLng / 2) a := dLat2Sin*dLat2Sin + math.Cos(deg2rad(p.Lat()))*math.Cos(deg2rad(point.Lat()))*dLng2Sin*dLng2Sin return 2.0 * EarthRadius * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) } if dLng > math.Pi { dLng = 2*math.Pi - dLng } // fast way using pythagorean theorem on an equirectangular projection x := dLng * math.Cos(deg2rad((p.Lat()+point.Lat())/2.0)) return math.Sqrt(dLat*dLat+x*x) * EarthRadius }
[ "func", "(", "p", "*", "Point", ")", "GeoDistanceFrom", "(", "point", "*", "Point", ",", "haversine", "...", "bool", ")", "float64", "{", "dLat", ":=", "deg2rad", "(", "point", ".", "Lat", "(", ")", "-", "p", ".", "Lat", "(", ")", ")", "\n", "dLng", ":=", "math", ".", "Abs", "(", "deg2rad", "(", "point", ".", "Lng", "(", ")", "-", "p", ".", "Lng", "(", ")", ")", ")", "\n\n", "if", "yesHaversine", "(", "haversine", ")", "{", "// yes trig functions", "dLat2Sin", ":=", "math", ".", "Sin", "(", "dLat", "/", "2", ")", "\n", "dLng2Sin", ":=", "math", ".", "Sin", "(", "dLng", "/", "2", ")", "\n", "a", ":=", "dLat2Sin", "*", "dLat2Sin", "+", "math", ".", "Cos", "(", "deg2rad", "(", "p", ".", "Lat", "(", ")", ")", ")", "*", "math", ".", "Cos", "(", "deg2rad", "(", "point", ".", "Lat", "(", ")", ")", ")", "*", "dLng2Sin", "*", "dLng2Sin", "\n\n", "return", "2.0", "*", "EarthRadius", "*", "math", ".", "Atan2", "(", "math", ".", "Sqrt", "(", "a", ")", ",", "math", ".", "Sqrt", "(", "1", "-", "a", ")", ")", "\n", "}", "\n\n", "if", "dLng", ">", "math", ".", "Pi", "{", "dLng", "=", "2", "*", "math", ".", "Pi", "-", "dLng", "\n", "}", "\n\n", "// fast way using pythagorean theorem on an equirectangular projection", "x", ":=", "dLng", "*", "math", ".", "Cos", "(", "deg2rad", "(", "(", "p", ".", "Lat", "(", ")", "+", "point", ".", "Lat", "(", ")", ")", "/", "2.0", ")", ")", "\n", "return", "math", ".", "Sqrt", "(", "dLat", "*", "dLat", "+", "x", "*", "x", ")", "*", "EarthRadius", "\n", "}" ]
// GeoDistanceFrom returns the geodesic distance in meters.
[ "GeoDistanceFrom", "returns", "the", "geodesic", "distance", "in", "meters", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L94-L114
11,252
paulmach/go.geo
point.go
BearingTo
func (p *Point) BearingTo(point *Point) float64 { dLng := deg2rad(point.Lng() - p.Lng()) pLatRad := deg2rad(p.Lat()) pointLatRad := deg2rad(point.Lat()) y := math.Sin(dLng) * math.Cos(pointLatRad) x := math.Cos(pLatRad)*math.Sin(pointLatRad) - math.Sin(pLatRad)*math.Cos(pointLatRad)*math.Cos(dLng) return rad2deg(math.Atan2(y, x)) }
go
func (p *Point) BearingTo(point *Point) float64 { dLng := deg2rad(point.Lng() - p.Lng()) pLatRad := deg2rad(p.Lat()) pointLatRad := deg2rad(point.Lat()) y := math.Sin(dLng) * math.Cos(pointLatRad) x := math.Cos(pLatRad)*math.Sin(pointLatRad) - math.Sin(pLatRad)*math.Cos(pointLatRad)*math.Cos(dLng) return rad2deg(math.Atan2(y, x)) }
[ "func", "(", "p", "*", "Point", ")", "BearingTo", "(", "point", "*", "Point", ")", "float64", "{", "dLng", ":=", "deg2rad", "(", "point", ".", "Lng", "(", ")", "-", "p", ".", "Lng", "(", ")", ")", "\n\n", "pLatRad", ":=", "deg2rad", "(", "p", ".", "Lat", "(", ")", ")", "\n", "pointLatRad", ":=", "deg2rad", "(", "point", ".", "Lat", "(", ")", ")", "\n\n", "y", ":=", "math", ".", "Sin", "(", "dLng", ")", "*", "math", ".", "Cos", "(", "pointLatRad", ")", "\n", "x", ":=", "math", ".", "Cos", "(", "pLatRad", ")", "*", "math", ".", "Sin", "(", "pointLatRad", ")", "-", "math", ".", "Sin", "(", "pLatRad", ")", "*", "math", ".", "Cos", "(", "pointLatRad", ")", "*", "math", ".", "Cos", "(", "dLng", ")", "\n\n", "return", "rad2deg", "(", "math", ".", "Atan2", "(", "y", ",", "x", ")", ")", "\n", "}" ]
// BearingTo computes the direction one must start traveling on earth // to be heading to the given point.
[ "BearingTo", "computes", "the", "direction", "one", "must", "start", "traveling", "on", "earth", "to", "be", "heading", "to", "the", "given", "point", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L118-L128
11,253
paulmach/go.geo
point.go
GeoHashInt64
func (p *Point) GeoHashInt64(bits int) (hash int64) { // This code was inspired by https://github.com/broady/gogeohash latMin, latMax := -90.0, 90.0 lngMin, lngMax := -180.0, 180.0 for i := 0; i < bits; i++ { hash <<= 1 // interleave bits if i%2 == 0 { mid := (lngMin + lngMax) / 2.0 if p[0] > mid { lngMin = mid hash |= 1 } else { lngMax = mid } } else { mid := (latMin + latMax) / 2.0 if p[1] > mid { latMin = mid hash |= 1 } else { latMax = mid } } } return }
go
func (p *Point) GeoHashInt64(bits int) (hash int64) { // This code was inspired by https://github.com/broady/gogeohash latMin, latMax := -90.0, 90.0 lngMin, lngMax := -180.0, 180.0 for i := 0; i < bits; i++ { hash <<= 1 // interleave bits if i%2 == 0 { mid := (lngMin + lngMax) / 2.0 if p[0] > mid { lngMin = mid hash |= 1 } else { lngMax = mid } } else { mid := (latMin + latMax) / 2.0 if p[1] > mid { latMin = mid hash |= 1 } else { latMax = mid } } } return }
[ "func", "(", "p", "*", "Point", ")", "GeoHashInt64", "(", "bits", "int", ")", "(", "hash", "int64", ")", "{", "// This code was inspired by https://github.com/broady/gogeohash", "latMin", ",", "latMax", ":=", "-", "90.0", ",", "90.0", "\n", "lngMin", ",", "lngMax", ":=", "-", "180.0", ",", "180.0", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "bits", ";", "i", "++", "{", "hash", "<<=", "1", "\n\n", "// interleave bits", "if", "i", "%", "2", "==", "0", "{", "mid", ":=", "(", "lngMin", "+", "lngMax", ")", "/", "2.0", "\n", "if", "p", "[", "0", "]", ">", "mid", "{", "lngMin", "=", "mid", "\n", "hash", "|=", "1", "\n", "}", "else", "{", "lngMax", "=", "mid", "\n", "}", "\n", "}", "else", "{", "mid", ":=", "(", "latMin", "+", "latMax", ")", "/", "2.0", "\n", "if", "p", "[", "1", "]", ">", "mid", "{", "latMin", "=", "mid", "\n", "hash", "|=", "1", "\n", "}", "else", "{", "latMax", "=", "mid", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// GeoHashInt64 returns the integer version of the geohash // down to the given number of bits. // The main usecase for this function is to be able to do integer based ordering of points. // In that case the number of bits should be the same for all encodings.
[ "GeoHashInt64", "returns", "the", "integer", "version", "of", "the", "geohash", "down", "to", "the", "given", "number", "of", "bits", ".", "The", "main", "usecase", "for", "this", "function", "is", "to", "be", "able", "to", "do", "integer", "based", "ordering", "of", "points", ".", "In", "that", "case", "the", "number", "of", "bits", "should", "be", "the", "same", "for", "all", "encodings", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L184-L214
11,254
paulmach/go.geo
point.go
Add
func (p *Point) Add(point *Point) *Point { p[0] += point[0] p[1] += point[1] return p }
go
func (p *Point) Add(point *Point) *Point { p[0] += point[0] p[1] += point[1] return p }
[ "func", "(", "p", "*", "Point", ")", "Add", "(", "point", "*", "Point", ")", "*", "Point", "{", "p", "[", "0", "]", "+=", "point", "[", "0", "]", "\n", "p", "[", "1", "]", "+=", "point", "[", "1", "]", "\n\n", "return", "p", "\n", "}" ]
// Add a point to the given point.
[ "Add", "a", "point", "to", "the", "given", "point", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L217-L222
11,255
paulmach/go.geo
point.go
Subtract
func (p *Point) Subtract(point *Point) *Point { p[0] -= point[0] p[1] -= point[1] return p }
go
func (p *Point) Subtract(point *Point) *Point { p[0] -= point[0] p[1] -= point[1] return p }
[ "func", "(", "p", "*", "Point", ")", "Subtract", "(", "point", "*", "Point", ")", "*", "Point", "{", "p", "[", "0", "]", "-=", "point", "[", "0", "]", "\n", "p", "[", "1", "]", "-=", "point", "[", "1", "]", "\n\n", "return", "p", "\n", "}" ]
// Subtract a point from the given point.
[ "Subtract", "a", "point", "from", "the", "given", "point", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L225-L230
11,256
paulmach/go.geo
point.go
Scale
func (p *Point) Scale(factor float64) *Point { p[0] *= factor p[1] *= factor return p }
go
func (p *Point) Scale(factor float64) *Point { p[0] *= factor p[1] *= factor return p }
[ "func", "(", "p", "*", "Point", ")", "Scale", "(", "factor", "float64", ")", "*", "Point", "{", "p", "[", "0", "]", "*=", "factor", "\n", "p", "[", "1", "]", "*=", "factor", "\n\n", "return", "p", "\n", "}" ]
// Scale each component of the point.
[ "Scale", "each", "component", "of", "the", "point", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L251-L256
11,257
paulmach/go.geo
point.go
Equals
func (p *Point) Equals(point *Point) bool { if p[0] == point[0] && p[1] == point[1] { return true } return false }
go
func (p *Point) Equals(point *Point) bool { if p[0] == point[0] && p[1] == point[1] { return true } return false }
[ "func", "(", "p", "*", "Point", ")", "Equals", "(", "point", "*", "Point", ")", "bool", "{", "if", "p", "[", "0", "]", "==", "point", "[", "0", "]", "&&", "p", "[", "1", "]", "==", "point", "[", "1", "]", "{", "return", "true", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Equals checks if the point represents the same point or vector.
[ "Equals", "checks", "if", "the", "point", "represents", "the", "same", "point", "or", "vector", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L274-L280
11,258
paulmach/go.geo
point.go
ToGeoJSON
func (p Point) ToGeoJSON() *geojson.Feature { return geojson.NewPointFeature([]float64{p[0], p[1]}) }
go
func (p Point) ToGeoJSON() *geojson.Feature { return geojson.NewPointFeature([]float64{p[0], p[1]}) }
[ "func", "(", "p", "Point", ")", "ToGeoJSON", "(", ")", "*", "geojson", ".", "Feature", "{", "return", "geojson", ".", "NewPointFeature", "(", "[", "]", "float64", "{", "p", "[", "0", "]", ",", "p", "[", "1", "]", "}", ")", "\n", "}" ]
// ToGeoJSON creates a new geojson feature with a point geometry.
[ "ToGeoJSON", "creates", "a", "new", "geojson", "feature", "with", "a", "point", "geometry", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L327-L329
11,259
paulmach/go.geo
point.go
Round
func (p *Point) Round(factor ...int) *Point { f := 1.0e5 if len(factor) != 0 { f = float64(factor[0]) } for idx, val := range p { x := val * f p[idx] = math.Floor(x+0.5) / f } return p }
go
func (p *Point) Round(factor ...int) *Point { f := 1.0e5 if len(factor) != 0 { f = float64(factor[0]) } for idx, val := range p { x := val * f p[idx] = math.Floor(x+0.5) / f } return p }
[ "func", "(", "p", "*", "Point", ")", "Round", "(", "factor", "...", "int", ")", "*", "Point", "{", "f", ":=", "1.0e5", "\n", "if", "len", "(", "factor", ")", "!=", "0", "{", "f", "=", "float64", "(", "factor", "[", "0", "]", ")", "\n", "}", "\n\n", "for", "idx", ",", "val", ":=", "range", "p", "{", "x", ":=", "val", "*", "f", "\n", "p", "[", "idx", "]", "=", "math", ".", "Floor", "(", "x", "+", "0.5", ")", "/", "f", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// Round returns a point which coordinates are rounded // Factor defaults to 1.0e5
[ "Round", "returns", "a", "point", "which", "coordinates", "are", "rounded", "Factor", "defaults", "to", "1", ".", "0e5" ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/point.go#L344-L356
11,260
paulmach/go.geo
wkb.go
NewPointFromWKB
func NewPointFromWKB(wkb []byte) *Point { p := &Point{} if err := p.unmarshalWKB(wkb); err != nil { return nil } return p }
go
func NewPointFromWKB(wkb []byte) *Point { p := &Point{} if err := p.unmarshalWKB(wkb); err != nil { return nil } return p }
[ "func", "NewPointFromWKB", "(", "wkb", "[", "]", "byte", ")", "*", "Point", "{", "p", ":=", "&", "Point", "{", "}", "\n", "if", "err", ":=", "p", ".", "unmarshalWKB", "(", "wkb", ")", ";", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// NewPointFromWKB will take raw WKB and set the data for a new point. // The WKB data must be of type Point. Will return nil if invalid WKB point.
[ "NewPointFromWKB", "will", "take", "raw", "WKB", "and", "set", "the", "data", "for", "a", "new", "point", ".", "The", "WKB", "data", "must", "be", "of", "type", "Point", ".", "Will", "return", "nil", "if", "invalid", "WKB", "point", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/wkb.go#L25-L32
11,261
paulmach/go.geo
wkb.go
NewLineFromWKB
func NewLineFromWKB(wkb []byte) *Line { l := &Line{} if err := l.unmarshalWKB(wkb); err != nil { return nil } return l }
go
func NewLineFromWKB(wkb []byte) *Line { l := &Line{} if err := l.unmarshalWKB(wkb); err != nil { return nil } return l }
[ "func", "NewLineFromWKB", "(", "wkb", "[", "]", "byte", ")", "*", "Line", "{", "l", ":=", "&", "Line", "{", "}", "\n", "if", "err", ":=", "l", ".", "unmarshalWKB", "(", "wkb", ")", ";", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "l", "\n", "}" ]
// NewLineFromWKB will take raw WKB and set the data for a new line. // The WKB data must of type LineString and only contain 2 points. // Will return nil if invalid WKB.
[ "NewLineFromWKB", "will", "take", "raw", "WKB", "and", "set", "the", "data", "for", "a", "new", "line", ".", "The", "WKB", "data", "must", "of", "type", "LineString", "and", "only", "contain", "2", "points", ".", "Will", "return", "nil", "if", "invalid", "WKB", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/wkb.go#L37-L44
11,262
paulmach/go.geo
wkb.go
NewPointSetFromWKB
func NewPointSetFromWKB(wkb []byte) *PointSet { ps := &PointSet{} if err := ps.unmarshalWKB(wkb); err != nil { return nil } return ps }
go
func NewPointSetFromWKB(wkb []byte) *PointSet { ps := &PointSet{} if err := ps.unmarshalWKB(wkb); err != nil { return nil } return ps }
[ "func", "NewPointSetFromWKB", "(", "wkb", "[", "]", "byte", ")", "*", "PointSet", "{", "ps", ":=", "&", "PointSet", "{", "}", "\n", "if", "err", ":=", "ps", ".", "unmarshalWKB", "(", "wkb", ")", ";", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "ps", "\n", "}" ]
// NewPointSetFromWKB will take raw WKB and set the data for a new point set. // The WKB data must be of type LineString, Polygon or MultiPoint. // Will return nil if invalid WKB.
[ "NewPointSetFromWKB", "will", "take", "raw", "WKB", "and", "set", "the", "data", "for", "a", "new", "point", "set", ".", "The", "WKB", "data", "must", "be", "of", "type", "LineString", "Polygon", "or", "MultiPoint", ".", "Will", "return", "nil", "if", "invalid", "WKB", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/wkb.go#L49-L56
11,263
paulmach/go.geo
wkb.go
NewPathFromWKB
func NewPathFromWKB(wkb []byte) *Path { p := NewPath() if err := p.PointSet.unmarshalWKB(wkb); err != nil { return nil } return p }
go
func NewPathFromWKB(wkb []byte) *Path { p := NewPath() if err := p.PointSet.unmarshalWKB(wkb); err != nil { return nil } return p }
[ "func", "NewPathFromWKB", "(", "wkb", "[", "]", "byte", ")", "*", "Path", "{", "p", ":=", "NewPath", "(", ")", "\n", "if", "err", ":=", "p", ".", "PointSet", ".", "unmarshalWKB", "(", "wkb", ")", ";", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// NewPathFromWKB will take raw WKB and set the data for a new path. // The WKB data must be of type LineString, Polygon or MultiPoint. // Will return nil if invalid WKB.
[ "NewPathFromWKB", "will", "take", "raw", "WKB", "and", "set", "the", "data", "for", "a", "new", "path", ".", "The", "WKB", "data", "must", "be", "of", "type", "LineString", "Polygon", "or", "MultiPoint", ".", "Will", "return", "nil", "if", "invalid", "WKB", "." ]
22b514266d334aa8d88c792452195cbb2f670319
https://github.com/paulmach/go.geo/blob/22b514266d334aa8d88c792452195cbb2f670319/wkb.go#L61-L68
11,264
cloudfoundry/inigo
helpers/portauthority/portauthority.go
ClaimPorts
func (p *portAllocator) ClaimPorts(numPorts int) (uint16, error) { port := p.nextPort if p.endingPort < port+uint16(numPorts-1) { return 0, errors.New("insufficient ports available") } p.nextPort = p.nextPort + uint16(numPorts) return uint16(port), nil }
go
func (p *portAllocator) ClaimPorts(numPorts int) (uint16, error) { port := p.nextPort if p.endingPort < port+uint16(numPorts-1) { return 0, errors.New("insufficient ports available") } p.nextPort = p.nextPort + uint16(numPorts) return uint16(port), nil }
[ "func", "(", "p", "*", "portAllocator", ")", "ClaimPorts", "(", "numPorts", "int", ")", "(", "uint16", ",", "error", ")", "{", "port", ":=", "p", ".", "nextPort", "\n", "if", "p", ".", "endingPort", "<", "port", "+", "uint16", "(", "numPorts", "-", "1", ")", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ".", "nextPort", "=", "p", ".", "nextPort", "+", "uint16", "(", "numPorts", ")", "\n", "return", "uint16", "(", "port", ")", ",", "nil", "\n", "}" ]
// ClaimPorts returns a new uint16 port to be used for testing processes. // // No guarantees are made that something is not already listening on that port. // If running multiple processes, you should initialize the portAllocator with different ranges. // If ports are also allocated by another method, the portAllocator should be // provided with a range that skips those other ports. // // numPorts indicates the number of ports that will be claimed. The first claimed // port is returned, and the next numPorts-1 ports sequentially after that are yours // to use. // // returns a non-nil error if there are not enough ports in the range compared to // the number requested.
[ "ClaimPorts", "returns", "a", "new", "uint16", "port", "to", "be", "used", "for", "testing", "processes", ".", "No", "guarantees", "are", "made", "that", "something", "is", "not", "already", "listening", "on", "that", "port", ".", "If", "running", "multiple", "processes", "you", "should", "initialize", "the", "portAllocator", "with", "different", "ranges", ".", "If", "ports", "are", "also", "allocated", "by", "another", "method", "the", "portAllocator", "should", "be", "provided", "with", "a", "range", "that", "skips", "those", "other", "ports", ".", "numPorts", "indicates", "the", "number", "of", "ports", "that", "will", "be", "claimed", ".", "The", "first", "claimed", "port", "is", "returned", "and", "the", "next", "numPorts", "-", "1", "ports", "sequentially", "after", "that", "are", "yours", "to", "use", ".", "returns", "a", "non", "-", "nil", "error", "if", "there", "are", "not", "enough", "ports", "in", "the", "range", "compared", "to", "the", "number", "requested", "." ]
414d9ec47804264460f9347dcbcdcbc5124990b3
https://github.com/cloudfoundry/inigo/blob/414d9ec47804264460f9347dcbcdcbc5124990b3/helpers/portauthority/portauthority.go#L42-L50
11,265
rancher/rancher-compose
rancher/volume.go
InspectTemplate
func (v *Volume) InspectTemplate(ctx context.Context) (*client.VolumeTemplate, error) { volumes, err := v.context.Client.VolumeTemplate.List(&client.ListOpts{ Filters: map[string]interface{}{ "name": v.name, "stackId": v.context.Stack.Id, }, }) if err != nil { return nil, err } if len(volumes.Data) > 0 { return &volumes.Data[0], nil } return nil, nil }
go
func (v *Volume) InspectTemplate(ctx context.Context) (*client.VolumeTemplate, error) { volumes, err := v.context.Client.VolumeTemplate.List(&client.ListOpts{ Filters: map[string]interface{}{ "name": v.name, "stackId": v.context.Stack.Id, }, }) if err != nil { return nil, err } if len(volumes.Data) > 0 { return &volumes.Data[0], nil } return nil, nil }
[ "func", "(", "v", "*", "Volume", ")", "InspectTemplate", "(", "ctx", "context", ".", "Context", ")", "(", "*", "client", ".", "VolumeTemplate", ",", "error", ")", "{", "volumes", ",", "err", ":=", "v", ".", "context", ".", "Client", ".", "VolumeTemplate", ".", "List", "(", "&", "client", ".", "ListOpts", "{", "Filters", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "v", ".", "name", ",", "\"", "\"", ":", "v", ".", "context", ".", "Stack", ".", "Id", ",", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "volumes", ".", "Data", ")", ">", "0", "{", "return", "&", "volumes", ".", "Data", "[", "0", "]", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// InspectTemplate looks up a volume template
[ "InspectTemplate", "looks", "up", "a", "volume", "template" ]
88b67b0c10b69c6f0da66d208a3eea7351864dca
https://github.com/rancher/rancher-compose/blob/88b67b0c10b69c6f0da66d208a3eea7351864dca/rancher/volume.go#L73-L89
11,266
rancher/rancher-compose
rancher/volume.go
InspectExternal
func (v *Volume) InspectExternal(ctx context.Context) (*client.Volume, error) { volumes, err := v.context.Client.Volume.List(&client.ListOpts{ Filters: map[string]interface{}{ "name": v.name, }, }) if err != nil { return nil, err } if len(volumes.Data) > 0 { return &volumes.Data[0], nil } return nil, nil }
go
func (v *Volume) InspectExternal(ctx context.Context) (*client.Volume, error) { volumes, err := v.context.Client.Volume.List(&client.ListOpts{ Filters: map[string]interface{}{ "name": v.name, }, }) if err != nil { return nil, err } if len(volumes.Data) > 0 { return &volumes.Data[0], nil } return nil, nil }
[ "func", "(", "v", "*", "Volume", ")", "InspectExternal", "(", "ctx", "context", ".", "Context", ")", "(", "*", "client", ".", "Volume", ",", "error", ")", "{", "volumes", ",", "err", ":=", "v", ".", "context", ".", "Client", ".", "Volume", ".", "List", "(", "&", "client", ".", "ListOpts", "{", "Filters", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "v", ".", "name", ",", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "volumes", ".", "Data", ")", ">", "0", "{", "return", "&", "volumes", ".", "Data", "[", "0", "]", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "nil", "\n", "}" ]
// InspectExternal looks up a volume
[ "InspectExternal", "looks", "up", "a", "volume" ]
88b67b0c10b69c6f0da66d208a3eea7351864dca
https://github.com/rancher/rancher-compose/blob/88b67b0c10b69c6f0da66d208a3eea7351864dca/rancher/volume.go#L92-L107
11,267
rancher/rancher-compose
app/app.go
StopCommand
func StopCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "stop", ShortName: "down", Usage: "Stop services", Action: app.WithProject(factory, app.ProjectStop), Flags: []cli.Flag{ cli.IntFlag{ Name: "timeout,t", Usage: "Specify a shutdown timeout in seconds.", Value: 10, }, }, } }
go
func StopCommand(factory app.ProjectFactory) cli.Command { return cli.Command{ Name: "stop", ShortName: "down", Usage: "Stop services", Action: app.WithProject(factory, app.ProjectStop), Flags: []cli.Flag{ cli.IntFlag{ Name: "timeout,t", Usage: "Specify a shutdown timeout in seconds.", Value: 10, }, }, } }
[ "func", "StopCommand", "(", "factory", "app", ".", "ProjectFactory", ")", "cli", ".", "Command", "{", "return", "cli", ".", "Command", "{", "Name", ":", "\"", "\"", ",", "ShortName", ":", "\"", "\"", ",", "Usage", ":", "\"", "\"", ",", "Action", ":", "app", ".", "WithProject", "(", "factory", ",", "app", ".", "ProjectStop", ")", ",", "Flags", ":", "[", "]", "cli", ".", "Flag", "{", "cli", ".", "IntFlag", "{", "Name", ":", "\"", "\"", ",", "Usage", ":", "\"", "\"", ",", "Value", ":", "10", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// StopCommand defines the libcompose stop subcommand.
[ "StopCommand", "defines", "the", "libcompose", "stop", "subcommand", "." ]
88b67b0c10b69c6f0da66d208a3eea7351864dca
https://github.com/rancher/rancher-compose/blob/88b67b0c10b69c6f0da66d208a3eea7351864dca/app/app.go#L250-L264
11,268
rancher/rancher-compose
lookup/file.go
ResolvePath
func (f *FileResourceLookup) ResolvePath(path, inFile string) string { vs := strings.SplitN(path, ":", 2) if len(vs) == 2 && !filepath.IsAbs(vs[0]) { log.Warnf("Rancher Compose will not resolve relative path %s", vs[0]) } return path }
go
func (f *FileResourceLookup) ResolvePath(path, inFile string) string { vs := strings.SplitN(path, ":", 2) if len(vs) == 2 && !filepath.IsAbs(vs[0]) { log.Warnf("Rancher Compose will not resolve relative path %s", vs[0]) } return path }
[ "func", "(", "f", "*", "FileResourceLookup", ")", "ResolvePath", "(", "path", ",", "inFile", "string", ")", "string", "{", "vs", ":=", "strings", ".", "SplitN", "(", "path", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "vs", ")", "==", "2", "&&", "!", "filepath", ".", "IsAbs", "(", "vs", "[", "0", "]", ")", "{", "log", ".", "Warnf", "(", "\"", "\"", ",", "vs", "[", "0", "]", ")", "\n", "}", "\n", "return", "path", "\n", "}" ]
// Give a warning rather than resolve relative paths
[ "Give", "a", "warning", "rather", "than", "resolve", "relative", "paths" ]
88b67b0c10b69c6f0da66d208a3eea7351864dca
https://github.com/rancher/rancher-compose/blob/88b67b0c10b69c6f0da66d208a3eea7351864dca/lookup/file.go#L16-L22
11,269
qor/validations
validations.go
NewError
func NewError(resource interface{}, column, err string) error { return &Error{Resource: resource, Column: column, Message: err} }
go
func NewError(resource interface{}, column, err string) error { return &Error{Resource: resource, Column: column, Message: err} }
[ "func", "NewError", "(", "resource", "interface", "{", "}", ",", "column", ",", "err", "string", ")", "error", "{", "return", "&", "Error", "{", "Resource", ":", "resource", ",", "Column", ":", "column", ",", "Message", ":", "err", "}", "\n", "}" ]
// NewError generate a new error for a model's field
[ "NewError", "generate", "a", "new", "error", "for", "a", "model", "s", "field" ]
f364bca61b46bd48a5e32552a37758864fdf005d
https://github.com/qor/validations/blob/f364bca61b46bd48a5e32552a37758864fdf005d/validations.go#L10-L12
11,270
qor/validations
validations.go
Label
func (err Error) Label() string { scope := gorm.Scope{Value: err.Resource} return fmt.Sprintf("%v_%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue(), err.Column) }
go
func (err Error) Label() string { scope := gorm.Scope{Value: err.Resource} return fmt.Sprintf("%v_%v_%v", scope.GetModelStruct().ModelType.Name(), scope.PrimaryKeyValue(), err.Column) }
[ "func", "(", "err", "Error", ")", "Label", "(", ")", "string", "{", "scope", ":=", "gorm", ".", "Scope", "{", "Value", ":", "err", ".", "Resource", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scope", ".", "GetModelStruct", "(", ")", ".", "ModelType", ".", "Name", "(", ")", ",", "scope", ".", "PrimaryKeyValue", "(", ")", ",", "err", ".", "Column", ")", "\n", "}" ]
// Label is a label including model type, primary key and column name
[ "Label", "is", "a", "label", "including", "model", "type", "primary", "key", "and", "column", "name" ]
f364bca61b46bd48a5e32552a37758864fdf005d
https://github.com/qor/validations/blob/f364bca61b46bd48a5e32552a37758864fdf005d/validations.go#L22-L25
11,271
optiopay/kafka
broker.go
NewBrokerConf
func NewBrokerConf(clientID string) BrokerConf { return BrokerConf{ ClientID: clientID, DialTimeout: 10 * time.Second, DialRetryLimit: 10, DialRetryWait: 500 * time.Millisecond, AllowTopicCreation: false, LeaderRetryLimit: 10, LeaderRetryWait: 500 * time.Millisecond, RetryErrLimit: 10, RetryErrWait: time.Millisecond * 500, ReadTimeout: 30 * time.Second, Logger: &nullLogger{}, } }
go
func NewBrokerConf(clientID string) BrokerConf { return BrokerConf{ ClientID: clientID, DialTimeout: 10 * time.Second, DialRetryLimit: 10, DialRetryWait: 500 * time.Millisecond, AllowTopicCreation: false, LeaderRetryLimit: 10, LeaderRetryWait: 500 * time.Millisecond, RetryErrLimit: 10, RetryErrWait: time.Millisecond * 500, ReadTimeout: 30 * time.Second, Logger: &nullLogger{}, } }
[ "func", "NewBrokerConf", "(", "clientID", "string", ")", "BrokerConf", "{", "return", "BrokerConf", "{", "ClientID", ":", "clientID", ",", "DialTimeout", ":", "10", "*", "time", ".", "Second", ",", "DialRetryLimit", ":", "10", ",", "DialRetryWait", ":", "500", "*", "time", ".", "Millisecond", ",", "AllowTopicCreation", ":", "false", ",", "LeaderRetryLimit", ":", "10", ",", "LeaderRetryWait", ":", "500", "*", "time", ".", "Millisecond", ",", "RetryErrLimit", ":", "10", ",", "RetryErrWait", ":", "time", ".", "Millisecond", "*", "500", ",", "ReadTimeout", ":", "30", "*", "time", ".", "Second", ",", "Logger", ":", "&", "nullLogger", "{", "}", ",", "}", "\n", "}" ]
// NewBrokerConf returns the default broker configuration.
[ "NewBrokerConf", "returns", "the", "default", "broker", "configuration", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L189-L203
11,272
optiopay/kafka
broker.go
Dial
func Dial(nodeAddresses []string, conf BrokerConf) (*Broker, error) { if len(nodeAddresses) == 0 { return nil, errors.New("no addresses provided") } broker := &Broker{ conf: conf, conns: make(map[int32]*connection), nodeAddresses: nodeAddresses, } for i := 0; i < conf.DialRetryLimit; i++ { if i > 0 { conf.Logger.Debug("cannot fetch metadata from any connection", "retry", i, "sleep", conf.DialRetryWait) time.Sleep(conf.DialRetryWait) } err := broker.refreshMetadata() if err == nil { return broker, nil } conf.Logger.Error("Got an error trying to fetch metadata", "error", err) } return nil, fmt.Errorf("cannot connect to: %s. TLS authentication: %t", nodeAddresses, conf.useTLS()) }
go
func Dial(nodeAddresses []string, conf BrokerConf) (*Broker, error) { if len(nodeAddresses) == 0 { return nil, errors.New("no addresses provided") } broker := &Broker{ conf: conf, conns: make(map[int32]*connection), nodeAddresses: nodeAddresses, } for i := 0; i < conf.DialRetryLimit; i++ { if i > 0 { conf.Logger.Debug("cannot fetch metadata from any connection", "retry", i, "sleep", conf.DialRetryWait) time.Sleep(conf.DialRetryWait) } err := broker.refreshMetadata() if err == nil { return broker, nil } conf.Logger.Error("Got an error trying to fetch metadata", "error", err) } return nil, fmt.Errorf("cannot connect to: %s. TLS authentication: %t", nodeAddresses, conf.useTLS()) }
[ "func", "Dial", "(", "nodeAddresses", "[", "]", "string", ",", "conf", "BrokerConf", ")", "(", "*", "Broker", ",", "error", ")", "{", "if", "len", "(", "nodeAddresses", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "broker", ":=", "&", "Broker", "{", "conf", ":", "conf", ",", "conns", ":", "make", "(", "map", "[", "int32", "]", "*", "connection", ")", ",", "nodeAddresses", ":", "nodeAddresses", ",", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "conf", ".", "DialRetryLimit", ";", "i", "++", "{", "if", "i", ">", "0", "{", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "i", ",", "\"", "\"", ",", "conf", ".", "DialRetryWait", ")", "\n", "time", ".", "Sleep", "(", "conf", ".", "DialRetryWait", ")", "\n", "}", "\n\n", "err", ":=", "broker", ".", "refreshMetadata", "(", ")", "\n\n", "if", "err", "==", "nil", "{", "return", "broker", ",", "nil", "\n", "}", "\n\n", "conf", ".", "Logger", ".", "Error", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "nodeAddresses", ",", "conf", ".", "useTLS", "(", ")", ")", "\n", "}" ]
// Dial connects to any node from a given list of kafka addresses and after // successful metadata fetch, returns broker. // // The returned broker is not initially connected to any kafka node.
[ "Dial", "connects", "to", "any", "node", "from", "a", "given", "list", "of", "kafka", "addresses", "and", "after", "successful", "metadata", "fetch", "returns", "broker", ".", "The", "returned", "broker", "is", "not", "initially", "connected", "to", "any", "kafka", "node", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L220-L248
11,273
optiopay/kafka
broker.go
Close
func (b *Broker) Close() { b.mu.Lock() defer b.mu.Unlock() for nodeID, conn := range b.conns { if err := conn.Close(); err != nil { b.conf.Logger.Info("cannot close node connection", "nodeID", nodeID, "error", err) } } }
go
func (b *Broker) Close() { b.mu.Lock() defer b.mu.Unlock() for nodeID, conn := range b.conns { if err := conn.Close(); err != nil { b.conf.Logger.Info("cannot close node connection", "nodeID", nodeID, "error", err) } } }
[ "func", "(", "b", "*", "Broker", ")", "Close", "(", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "nodeID", ",", "conn", ":=", "range", "b", ".", "conns", "{", "if", "err", ":=", "conn", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "b", ".", "conf", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "\"", "\"", ",", "nodeID", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Close closes the broker and all active kafka nodes connections.
[ "Close", "closes", "the", "broker", "and", "all", "active", "kafka", "nodes", "connections", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L260-L270
11,274
optiopay/kafka
broker.go
Metadata
func (b *Broker) Metadata() (*proto.MetadataResp, error) { b.mu.Lock() defer b.mu.Unlock() return b.fetchMetadata() }
go
func (b *Broker) Metadata() (*proto.MetadataResp, error) { b.mu.Lock() defer b.mu.Unlock() return b.fetchMetadata() }
[ "func", "(", "b", "*", "Broker", ")", "Metadata", "(", ")", "(", "*", "proto", ".", "MetadataResp", ",", "error", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "b", ".", "fetchMetadata", "(", ")", "\n", "}" ]
// Metadata requests metadata information from any node.
[ "Metadata", "requests", "metadata", "information", "from", "any", "node", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L273-L277
11,275
optiopay/kafka
broker.go
CreateTopic
func (b *Broker) CreateTopic(topics []proto.TopicInfo, timeout time.Duration, validateOnly bool) (*proto.CreateTopicsResp, error) { b.mu.Lock() defer b.mu.Unlock() var resp *proto.CreateTopicsResp err := b.callOnClusterController(func(c *connection) error { var err error req := proto.CreateTopicsReq{ Timeout: timeout, CreateTopicsRequests: topics, ValidateOnly: validateOnly, } resp, err = c.CreateTopic(&req) return err }) return resp, err }
go
func (b *Broker) CreateTopic(topics []proto.TopicInfo, timeout time.Duration, validateOnly bool) (*proto.CreateTopicsResp, error) { b.mu.Lock() defer b.mu.Unlock() var resp *proto.CreateTopicsResp err := b.callOnClusterController(func(c *connection) error { var err error req := proto.CreateTopicsReq{ Timeout: timeout, CreateTopicsRequests: topics, ValidateOnly: validateOnly, } resp, err = c.CreateTopic(&req) return err }) return resp, err }
[ "func", "(", "b", "*", "Broker", ")", "CreateTopic", "(", "topics", "[", "]", "proto", ".", "TopicInfo", ",", "timeout", "time", ".", "Duration", ",", "validateOnly", "bool", ")", "(", "*", "proto", ".", "CreateTopicsResp", ",", "error", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "var", "resp", "*", "proto", ".", "CreateTopicsResp", "\n", "err", ":=", "b", ".", "callOnClusterController", "(", "func", "(", "c", "*", "connection", ")", "error", "{", "var", "err", "error", "\n", "req", ":=", "proto", ".", "CreateTopicsReq", "{", "Timeout", ":", "timeout", ",", "CreateTopicsRequests", ":", "topics", ",", "ValidateOnly", ":", "validateOnly", ",", "}", "\n", "resp", ",", "err", "=", "c", ".", "CreateTopic", "(", "&", "req", ")", "\n", "return", "err", "\n", "}", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// CreateTopic request topic creation
[ "CreateTopic", "request", "topic", "creation" ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L280-L295
11,276
optiopay/kafka
broker.go
refreshMetadata
func (b *Broker) refreshMetadata() error { meta, err := b.fetchMetadata() if err == nil { b.cacheMetadata(meta) } return err }
go
func (b *Broker) refreshMetadata() error { meta, err := b.fetchMetadata() if err == nil { b.cacheMetadata(meta) } return err }
[ "func", "(", "b", "*", "Broker", ")", "refreshMetadata", "(", ")", "error", "{", "meta", ",", "err", ":=", "b", ".", "fetchMetadata", "(", ")", "\n", "if", "err", "==", "nil", "{", "b", ".", "cacheMetadata", "(", "meta", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// refreshMetadata is requesting metadata information from any node and refresh // internal cached representation. // Because it's changing internal state, this method requires lock protection, // but it does not acquire nor release lock itself.
[ "refreshMetadata", "is", "requesting", "metadata", "information", "from", "any", "node", "and", "refresh", "internal", "cached", "representation", ".", "Because", "it", "s", "changing", "internal", "state", "this", "method", "requires", "lock", "protection", "but", "it", "does", "not", "acquire", "nor", "release", "lock", "itself", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L301-L307
11,277
optiopay/kafka
broker.go
muRefreshMetadata
func (b *Broker) muRefreshMetadata() error { b.mu.Lock() err := b.refreshMetadata() b.mu.Unlock() return err }
go
func (b *Broker) muRefreshMetadata() error { b.mu.Lock() err := b.refreshMetadata() b.mu.Unlock() return err }
[ "func", "(", "b", "*", "Broker", ")", "muRefreshMetadata", "(", ")", "error", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "err", ":=", "b", ".", "refreshMetadata", "(", ")", "\n", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// muRefreshMetadata calls refreshMetadata, but protects it with broker's lock.
[ "muRefreshMetadata", "calls", "refreshMetadata", "but", "protects", "it", "with", "broker", "s", "lock", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L310-L315
11,278
optiopay/kafka
broker.go
cacheMetadata
func (b *Broker) cacheMetadata(resp *proto.MetadataResp) { if !b.metadata.created.IsZero() { b.conf.Logger.Debug("rewriting old metadata", "age", time.Now().Sub(b.metadata.created)) } b.metadata = clusterMetadata{ created: time.Now(), nodes: make(map[int32]string), endpoints: make(map[topicPartition]int32), partitions: make(map[string]int32), } b.metadata.controllerId = resp.ControllerID for _, node := range resp.Brokers { addr := fmt.Sprintf("%s:%d", node.Host, node.Port) b.metadata.nodes[node.NodeID] = addr } for _, topic := range resp.Topics { for _, part := range topic.Partitions { dest := topicPartition{topic.Name, part.ID} b.metadata.endpoints[dest] = part.Leader } b.metadata.partitions[topic.Name] = int32(len(topic.Partitions)) } b.conf.Logger.Debug("new metadata cached") }
go
func (b *Broker) cacheMetadata(resp *proto.MetadataResp) { if !b.metadata.created.IsZero() { b.conf.Logger.Debug("rewriting old metadata", "age", time.Now().Sub(b.metadata.created)) } b.metadata = clusterMetadata{ created: time.Now(), nodes: make(map[int32]string), endpoints: make(map[topicPartition]int32), partitions: make(map[string]int32), } b.metadata.controllerId = resp.ControllerID for _, node := range resp.Brokers { addr := fmt.Sprintf("%s:%d", node.Host, node.Port) b.metadata.nodes[node.NodeID] = addr } for _, topic := range resp.Topics { for _, part := range topic.Partitions { dest := topicPartition{topic.Name, part.ID} b.metadata.endpoints[dest] = part.Leader } b.metadata.partitions[topic.Name] = int32(len(topic.Partitions)) } b.conf.Logger.Debug("new metadata cached") }
[ "func", "(", "b", "*", "Broker", ")", "cacheMetadata", "(", "resp", "*", "proto", ".", "MetadataResp", ")", "{", "if", "!", "b", ".", "metadata", ".", "created", ".", "IsZero", "(", ")", "{", "b", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "time", ".", "Now", "(", ")", ".", "Sub", "(", "b", ".", "metadata", ".", "created", ")", ")", "\n", "}", "\n", "b", ".", "metadata", "=", "clusterMetadata", "{", "created", ":", "time", ".", "Now", "(", ")", ",", "nodes", ":", "make", "(", "map", "[", "int32", "]", "string", ")", ",", "endpoints", ":", "make", "(", "map", "[", "topicPartition", "]", "int32", ")", ",", "partitions", ":", "make", "(", "map", "[", "string", "]", "int32", ")", ",", "}", "\n", "b", ".", "metadata", ".", "controllerId", "=", "resp", ".", "ControllerID", "\n", "for", "_", ",", "node", ":=", "range", "resp", ".", "Brokers", "{", "addr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "node", ".", "Host", ",", "node", ".", "Port", ")", "\n", "b", ".", "metadata", ".", "nodes", "[", "node", ".", "NodeID", "]", "=", "addr", "\n", "}", "\n", "for", "_", ",", "topic", ":=", "range", "resp", ".", "Topics", "{", "for", "_", ",", "part", ":=", "range", "topic", ".", "Partitions", "{", "dest", ":=", "topicPartition", "{", "topic", ".", "Name", ",", "part", ".", "ID", "}", "\n", "b", ".", "metadata", ".", "endpoints", "[", "dest", "]", "=", "part", ".", "Leader", "\n", "}", "\n", "b", ".", "metadata", ".", "partitions", "[", "topic", ".", "Name", "]", "=", "int32", "(", "len", "(", "topic", ".", "Partitions", ")", ")", "\n", "}", "\n", "b", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "}" ]
// cacheMetadata creates new internal metadata representation using data from // given response. It's call has to be protected with lock. // // Do not call with partial metadata response, this assumes we have the full // set of metadata in the response
[ "cacheMetadata", "creates", "new", "internal", "metadata", "representation", "using", "data", "from", "given", "response", ".", "It", "s", "call", "has", "to", "be", "protected", "with", "lock", ".", "Do", "not", "call", "with", "partial", "metadata", "response", "this", "assumes", "we", "have", "the", "full", "set", "of", "metadata", "in", "the", "response" ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L499-L523
11,279
optiopay/kafka
broker.go
PartitionCount
func (b *Broker) PartitionCount(topic string) (int32, error) { b.mu.Lock() defer b.mu.Unlock() count, ok := b.metadata.partitions[topic] if ok { return count, nil } return 0, fmt.Errorf("topic %s not found in metadata", topic) }
go
func (b *Broker) PartitionCount(topic string) (int32, error) { b.mu.Lock() defer b.mu.Unlock() count, ok := b.metadata.partitions[topic] if ok { return count, nil } return 0, fmt.Errorf("topic %s not found in metadata", topic) }
[ "func", "(", "b", "*", "Broker", ")", "PartitionCount", "(", "topic", "string", ")", "(", "int32", ",", "error", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "count", ",", "ok", ":=", "b", ".", "metadata", ".", "partitions", "[", "topic", "]", "\n", "if", "ok", "{", "return", "count", ",", "nil", "\n", "}", "\n\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "topic", ")", "\n", "}" ]
// PartitionCount returns how many partitions a given topic has. If a topic // is not known, 0 and an error are returned.
[ "PartitionCount", "returns", "how", "many", "partitions", "a", "given", "topic", "has", ".", "If", "a", "topic", "is", "not", "known", "0", "and", "an", "error", "are", "returned", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L527-L537
11,280
optiopay/kafka
broker.go
muCloseDeadConnection
func (b *Broker) muCloseDeadConnection(conn *connection) { b.mu.Lock() defer b.mu.Unlock() for nid, c := range b.conns { if c == conn { b.conf.Logger.Debug("closing dead connection", "nodeID", nid) delete(b.conns, nid) _ = c.Close() if err := b.refreshMetadata(); err != nil { b.conf.Logger.Debug("cannot refresh metadata", "error", err) } return } } }
go
func (b *Broker) muCloseDeadConnection(conn *connection) { b.mu.Lock() defer b.mu.Unlock() for nid, c := range b.conns { if c == conn { b.conf.Logger.Debug("closing dead connection", "nodeID", nid) delete(b.conns, nid) _ = c.Close() if err := b.refreshMetadata(); err != nil { b.conf.Logger.Debug("cannot refresh metadata", "error", err) } return } } }
[ "func", "(", "b", "*", "Broker", ")", "muCloseDeadConnection", "(", "conn", "*", "connection", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "for", "nid", ",", "c", ":=", "range", "b", ".", "conns", "{", "if", "c", "==", "conn", "{", "b", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "nid", ")", "\n", "delete", "(", "b", ".", "conns", ",", "nid", ")", "\n", "_", "=", "c", ".", "Close", "(", ")", "\n", "if", "err", ":=", "b", ".", "refreshMetadata", "(", ")", ";", "err", "!=", "nil", "{", "b", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// muCloseDeadConnection is closing and removing any reference to given // connection. Because we remove dead connection, additional request to refresh // metadata is made // // muCloseDeadConnection call it protected with broker's lock.
[ "muCloseDeadConnection", "is", "closing", "and", "removing", "any", "reference", "to", "given", "connection", ".", "Because", "we", "remove", "dead", "connection", "additional", "request", "to", "refresh", "metadata", "is", "made", "muCloseDeadConnection", "call", "it", "protected", "with", "broker", "s", "lock", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L754-L771
11,281
optiopay/kafka
broker.go
offset
func (b *Broker) offset(topic string, partition int32, timems int64) (offset int64, err error) { for retry := 0; retry < b.conf.RetryErrLimit; retry++ { if retry != 0 { time.Sleep(b.conf.RetryErrWait) err = b.muRefreshMetadata() if err != nil { continue } } var conn *connection conn, err = b.muLeaderConnection(topic, partition) if err != nil { return 0, err } var resp *proto.OffsetResp resp, err = conn.Offset(&proto.OffsetReq{ RequestHeader: proto.RequestHeader{ClientID: b.conf.ClientID}, ReplicaID: -1, // any client Topics: []proto.OffsetReqTopic{ { Name: topic, Partitions: []proto.OffsetReqPartition{ { ID: partition, TimeMs: timems, MaxOffsets: 2, }, }, }, }, }) if err != nil { if _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE { // Connection is broken, so should be closed, but the error is // still valid and should be returned so that retry mechanism have // chance to react. b.conf.Logger.Debug("connection died while sending message", "topic", topic, "partition", partition, "error", err) b.muCloseDeadConnection(conn) } continue } for _, t := range resp.Topics { if t.Name != topic { b.conf.Logger.Debug("unexpected topic information", "expected", topic, "got", t.Name) continue } for _, part := range t.Partitions { if part.ID != partition { b.conf.Logger.Debug("unexpected partition information", "topic", t.Name, "expected", partition, "got", part.ID) continue } if err = part.Err; err == nil { if len(part.Offsets) == 0 { return 0, nil } else { return part.Offsets[0], nil } } } } } return 0, errors.New("incomplete fetch response") }
go
func (b *Broker) offset(topic string, partition int32, timems int64) (offset int64, err error) { for retry := 0; retry < b.conf.RetryErrLimit; retry++ { if retry != 0 { time.Sleep(b.conf.RetryErrWait) err = b.muRefreshMetadata() if err != nil { continue } } var conn *connection conn, err = b.muLeaderConnection(topic, partition) if err != nil { return 0, err } var resp *proto.OffsetResp resp, err = conn.Offset(&proto.OffsetReq{ RequestHeader: proto.RequestHeader{ClientID: b.conf.ClientID}, ReplicaID: -1, // any client Topics: []proto.OffsetReqTopic{ { Name: topic, Partitions: []proto.OffsetReqPartition{ { ID: partition, TimeMs: timems, MaxOffsets: 2, }, }, }, }, }) if err != nil { if _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE { // Connection is broken, so should be closed, but the error is // still valid and should be returned so that retry mechanism have // chance to react. b.conf.Logger.Debug("connection died while sending message", "topic", topic, "partition", partition, "error", err) b.muCloseDeadConnection(conn) } continue } for _, t := range resp.Topics { if t.Name != topic { b.conf.Logger.Debug("unexpected topic information", "expected", topic, "got", t.Name) continue } for _, part := range t.Partitions { if part.ID != partition { b.conf.Logger.Debug("unexpected partition information", "topic", t.Name, "expected", partition, "got", part.ID) continue } if err = part.Err; err == nil { if len(part.Offsets) == 0 { return 0, nil } else { return part.Offsets[0], nil } } } } } return 0, errors.New("incomplete fetch response") }
[ "func", "(", "b", "*", "Broker", ")", "offset", "(", "topic", "string", ",", "partition", "int32", ",", "timems", "int64", ")", "(", "offset", "int64", ",", "err", "error", ")", "{", "for", "retry", ":=", "0", ";", "retry", "<", "b", ".", "conf", ".", "RetryErrLimit", ";", "retry", "++", "{", "if", "retry", "!=", "0", "{", "time", ".", "Sleep", "(", "b", ".", "conf", ".", "RetryErrWait", ")", "\n", "err", "=", "b", ".", "muRefreshMetadata", "(", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "}", "\n", "var", "conn", "*", "connection", "\n", "conn", ",", "err", "=", "b", ".", "muLeaderConnection", "(", "topic", ",", "partition", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "var", "resp", "*", "proto", ".", "OffsetResp", "\n", "resp", ",", "err", "=", "conn", ".", "Offset", "(", "&", "proto", ".", "OffsetReq", "{", "RequestHeader", ":", "proto", ".", "RequestHeader", "{", "ClientID", ":", "b", ".", "conf", ".", "ClientID", "}", ",", "ReplicaID", ":", "-", "1", ",", "// any client", "Topics", ":", "[", "]", "proto", ".", "OffsetReqTopic", "{", "{", "Name", ":", "topic", ",", "Partitions", ":", "[", "]", "proto", ".", "OffsetReqPartition", "{", "{", "ID", ":", "partition", ",", "TimeMs", ":", "timems", ",", "MaxOffsets", ":", "2", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "||", "err", "==", "io", ".", "EOF", "||", "err", "==", "syscall", ".", "EPIPE", "{", "// Connection is broken, so should be closed, but the error is", "// still valid and should be returned so that retry mechanism have", "// chance to react.", "b", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "partition", ",", "\"", "\"", ",", "err", ")", "\n", "b", ".", "muCloseDeadConnection", "(", "conn", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "resp", ".", "Topics", "{", "if", "t", ".", "Name", "!=", "topic", "{", "b", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "t", ".", "Name", ")", "\n", "continue", "\n", "}", "\n", "for", "_", ",", "part", ":=", "range", "t", ".", "Partitions", "{", "if", "part", ".", "ID", "!=", "partition", "{", "b", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "t", ".", "Name", ",", "\"", "\"", ",", "partition", ",", "\"", "\"", ",", "part", ".", "ID", ")", "\n", "continue", "\n", "}", "\n", "if", "err", "=", "part", ".", "Err", ";", "err", "==", "nil", "{", "if", "len", "(", "part", ".", "Offsets", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "else", "{", "return", "part", ".", "Offsets", "[", "0", "]", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// offset will return offset value for given partition. Use timems to specify // which offset value should be returned.
[ "offset", "will", "return", "offset", "value", "for", "given", "partition", ".", "Use", "timems", "to", "specify", "which", "offset", "value", "should", "be", "returned", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L775-L845
11,282
optiopay/kafka
broker.go
OffsetEarliest
func (b *Broker) OffsetEarliest(topic string, partition int32) (offset int64, err error) { return b.offset(topic, partition, -2) }
go
func (b *Broker) OffsetEarliest(topic string, partition int32) (offset int64, err error) { return b.offset(topic, partition, -2) }
[ "func", "(", "b", "*", "Broker", ")", "OffsetEarliest", "(", "topic", "string", ",", "partition", "int32", ")", "(", "offset", "int64", ",", "err", "error", ")", "{", "return", "b", ".", "offset", "(", "topic", ",", "partition", ",", "-", "2", ")", "\n", "}" ]
// OffsetEarliest returns the oldest offset available on the given partition.
[ "OffsetEarliest", "returns", "the", "oldest", "offset", "available", "on", "the", "given", "partition", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L848-L850
11,283
optiopay/kafka
broker.go
NewProducerConf
func NewProducerConf() ProducerConf { return ProducerConf{ Compression: proto.CompressionNone, RequiredAcks: proto.RequiredAcksAll, RequestTimeout: 5 * time.Second, RetryLimit: 10, RetryWait: 200 * time.Millisecond, Logger: nil, } }
go
func NewProducerConf() ProducerConf { return ProducerConf{ Compression: proto.CompressionNone, RequiredAcks: proto.RequiredAcksAll, RequestTimeout: 5 * time.Second, RetryLimit: 10, RetryWait: 200 * time.Millisecond, Logger: nil, } }
[ "func", "NewProducerConf", "(", ")", "ProducerConf", "{", "return", "ProducerConf", "{", "Compression", ":", "proto", ".", "CompressionNone", ",", "RequiredAcks", ":", "proto", ".", "RequiredAcksAll", ",", "RequestTimeout", ":", "5", "*", "time", ".", "Second", ",", "RetryLimit", ":", "10", ",", "RetryWait", ":", "200", "*", "time", ".", "Millisecond", ",", "Logger", ":", "nil", ",", "}", "\n", "}" ]
// NewProducerConf returns a default producer configuration.
[ "NewProducerConf", "returns", "a", "default", "producer", "configuration", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L886-L895
11,284
optiopay/kafka
broker.go
Producer
func (b *Broker) Producer(conf ProducerConf) Producer { if conf.Logger == nil { conf.Logger = b.conf.Logger } return &producer{ conf: conf, broker: b, } }
go
func (b *Broker) Producer(conf ProducerConf) Producer { if conf.Logger == nil { conf.Logger = b.conf.Logger } return &producer{ conf: conf, broker: b, } }
[ "func", "(", "b", "*", "Broker", ")", "Producer", "(", "conf", "ProducerConf", ")", "Producer", "{", "if", "conf", ".", "Logger", "==", "nil", "{", "conf", ".", "Logger", "=", "b", ".", "conf", ".", "Logger", "\n", "}", "\n", "return", "&", "producer", "{", "conf", ":", "conf", ",", "broker", ":", "b", ",", "}", "\n", "}" ]
// Producer returns new producer instance, bound to the broker.
[ "Producer", "returns", "new", "producer", "instance", "bound", "to", "the", "broker", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L904-L912
11,285
optiopay/kafka
broker.go
Produce
func (p *producer) Produce(topic string, partition int32, messages ...*proto.Message) (offset int64, err error) { for retry := 0; retry < p.conf.RetryLimit; retry++ { if retry != 0 { time.Sleep(p.conf.RetryWait) } offset, err = p.produce(topic, partition, messages...) switch err { case nil: for i, msg := range messages { msg.Offset = int64(i) + offset } if retry != 0 { p.conf.Logger.Debug("Produced message after retry", "retry", retry, "topic", topic) } return offset, err case io.EOF, syscall.EPIPE: // p.produce call is closing connection when this error shows up, // but it's also returning it so that retry loop can count this // case // we cannot handle this error here, because there is no direct // access to connection default: if err := p.broker.muRefreshMetadata(); err != nil { p.conf.Logger.Debug("cannot refresh metadata", "error", err) } } p.conf.Logger.Debug("Cannot produce messages", "retry", retry, "topic", topic, "error", err) } p.conf.Logger.Debug("Abort to produce after retrying messages", "retry", p.conf.RetryLimit, "topic", topic) return 0, err }
go
func (p *producer) Produce(topic string, partition int32, messages ...*proto.Message) (offset int64, err error) { for retry := 0; retry < p.conf.RetryLimit; retry++ { if retry != 0 { time.Sleep(p.conf.RetryWait) } offset, err = p.produce(topic, partition, messages...) switch err { case nil: for i, msg := range messages { msg.Offset = int64(i) + offset } if retry != 0 { p.conf.Logger.Debug("Produced message after retry", "retry", retry, "topic", topic) } return offset, err case io.EOF, syscall.EPIPE: // p.produce call is closing connection when this error shows up, // but it's also returning it so that retry loop can count this // case // we cannot handle this error here, because there is no direct // access to connection default: if err := p.broker.muRefreshMetadata(); err != nil { p.conf.Logger.Debug("cannot refresh metadata", "error", err) } } p.conf.Logger.Debug("Cannot produce messages", "retry", retry, "topic", topic, "error", err) } p.conf.Logger.Debug("Abort to produce after retrying messages", "retry", p.conf.RetryLimit, "topic", topic) return 0, err }
[ "func", "(", "p", "*", "producer", ")", "Produce", "(", "topic", "string", ",", "partition", "int32", ",", "messages", "...", "*", "proto", ".", "Message", ")", "(", "offset", "int64", ",", "err", "error", ")", "{", "for", "retry", ":=", "0", ";", "retry", "<", "p", ".", "conf", ".", "RetryLimit", ";", "retry", "++", "{", "if", "retry", "!=", "0", "{", "time", ".", "Sleep", "(", "p", ".", "conf", ".", "RetryWait", ")", "\n", "}", "\n\n", "offset", ",", "err", "=", "p", ".", "produce", "(", "topic", ",", "partition", ",", "messages", "...", ")", "\n\n", "switch", "err", "{", "case", "nil", ":", "for", "i", ",", "msg", ":=", "range", "messages", "{", "msg", ".", "Offset", "=", "int64", "(", "i", ")", "+", "offset", "\n", "}", "\n", "if", "retry", "!=", "0", "{", "p", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "retry", ",", "\"", "\"", ",", "topic", ")", "\n", "}", "\n", "return", "offset", ",", "err", "\n", "case", "io", ".", "EOF", ",", "syscall", ".", "EPIPE", ":", "// p.produce call is closing connection when this error shows up,", "// but it's also returning it so that retry loop can count this", "// case", "// we cannot handle this error here, because there is no direct", "// access to connection", "default", ":", "if", "err", ":=", "p", ".", "broker", ".", "muRefreshMetadata", "(", ")", ";", "err", "!=", "nil", "{", "p", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "p", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "retry", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "p", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "p", ".", "conf", ".", "RetryLimit", ",", "\"", "\"", ",", "topic", ")", "\n", "return", "0", ",", "err", "\n\n", "}" ]
// Produce writes messages to the given destination. Writes within the call are // atomic, meaning either all or none of them are written to kafka. Produce // has a configurable amount of retries which may be attempted when common // errors are encountered. This behaviour can be configured with the // RetryLimit and RetryWait attributes. // // Upon a successful call, the message's Offset field is updated.
[ "Produce", "writes", "messages", "to", "the", "given", "destination", ".", "Writes", "within", "the", "call", "are", "atomic", "meaning", "either", "all", "or", "none", "of", "them", "are", "written", "to", "kafka", ".", "Produce", "has", "a", "configurable", "amount", "of", "retries", "which", "may", "be", "attempted", "when", "common", "errors", "are", "encountered", ".", "This", "behaviour", "can", "be", "configured", "with", "the", "RetryLimit", "and", "RetryWait", "attributes", ".", "Upon", "a", "successful", "call", "the", "message", "s", "Offset", "field", "is", "updated", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L921-L962
11,286
optiopay/kafka
broker.go
produce
func (p *producer) produce(topic string, partition int32, messages ...*proto.Message) (offset int64, err error) { conn, err := p.broker.muLeaderConnection(topic, partition) if err != nil { return 0, err } req := proto.ProduceReq{ RequestHeader: proto.RequestHeader{ClientID: p.broker.conf.ClientID}, Compression: p.conf.Compression, RequiredAcks: p.conf.RequiredAcks, Timeout: p.conf.RequestTimeout, Topics: []proto.ProduceReqTopic{ { Name: topic, Partitions: []proto.ProduceReqPartition{ { ID: partition, Messages: messages, }, }, }, }, } resp, err := conn.Produce(&req) if err != nil { if _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE { // Connection is broken, so should be closed, but the error is // still valid and should be returned so that retry mechanism have // chance to react. p.conf.Logger.Debug("connection died while sending message", "topic", topic, "partition", partition, "error", err) p.broker.muCloseDeadConnection(conn) } return 0, err } if req.RequiredAcks == proto.RequiredAcksNone { return 0, err } // we expect single partition response found := false for _, t := range resp.Topics { if t.Name != topic { p.conf.Logger.Debug("unexpected topic information received", "expected", topic, "got", t.Name) continue } for _, part := range t.Partitions { if part.ID != partition { p.conf.Logger.Debug("unexpected partition information received", "topic", t.Name, "expected", partition, "got", part.ID) continue } found = true offset = part.Offset err = part.Err } } if !found { return 0, errors.New("incomplete produce response") } return offset, err }
go
func (p *producer) produce(topic string, partition int32, messages ...*proto.Message) (offset int64, err error) { conn, err := p.broker.muLeaderConnection(topic, partition) if err != nil { return 0, err } req := proto.ProduceReq{ RequestHeader: proto.RequestHeader{ClientID: p.broker.conf.ClientID}, Compression: p.conf.Compression, RequiredAcks: p.conf.RequiredAcks, Timeout: p.conf.RequestTimeout, Topics: []proto.ProduceReqTopic{ { Name: topic, Partitions: []proto.ProduceReqPartition{ { ID: partition, Messages: messages, }, }, }, }, } resp, err := conn.Produce(&req) if err != nil { if _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE { // Connection is broken, so should be closed, but the error is // still valid and should be returned so that retry mechanism have // chance to react. p.conf.Logger.Debug("connection died while sending message", "topic", topic, "partition", partition, "error", err) p.broker.muCloseDeadConnection(conn) } return 0, err } if req.RequiredAcks == proto.RequiredAcksNone { return 0, err } // we expect single partition response found := false for _, t := range resp.Topics { if t.Name != topic { p.conf.Logger.Debug("unexpected topic information received", "expected", topic, "got", t.Name) continue } for _, part := range t.Partitions { if part.ID != partition { p.conf.Logger.Debug("unexpected partition information received", "topic", t.Name, "expected", partition, "got", part.ID) continue } found = true offset = part.Offset err = part.Err } } if !found { return 0, errors.New("incomplete produce response") } return offset, err }
[ "func", "(", "p", "*", "producer", ")", "produce", "(", "topic", "string", ",", "partition", "int32", ",", "messages", "...", "*", "proto", ".", "Message", ")", "(", "offset", "int64", ",", "err", "error", ")", "{", "conn", ",", "err", ":=", "p", ".", "broker", ".", "muLeaderConnection", "(", "topic", ",", "partition", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "req", ":=", "proto", ".", "ProduceReq", "{", "RequestHeader", ":", "proto", ".", "RequestHeader", "{", "ClientID", ":", "p", ".", "broker", ".", "conf", ".", "ClientID", "}", ",", "Compression", ":", "p", ".", "conf", ".", "Compression", ",", "RequiredAcks", ":", "p", ".", "conf", ".", "RequiredAcks", ",", "Timeout", ":", "p", ".", "conf", ".", "RequestTimeout", ",", "Topics", ":", "[", "]", "proto", ".", "ProduceReqTopic", "{", "{", "Name", ":", "topic", ",", "Partitions", ":", "[", "]", "proto", ".", "ProduceReqPartition", "{", "{", "ID", ":", "partition", ",", "Messages", ":", "messages", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", "\n\n", "resp", ",", "err", ":=", "conn", ".", "Produce", "(", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "||", "err", "==", "io", ".", "EOF", "||", "err", "==", "syscall", ".", "EPIPE", "{", "// Connection is broken, so should be closed, but the error is", "// still valid and should be returned so that retry mechanism have", "// chance to react.", "p", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "partition", ",", "\"", "\"", ",", "err", ")", "\n", "p", ".", "broker", ".", "muCloseDeadConnection", "(", "conn", ")", "\n", "}", "\n", "return", "0", ",", "err", "\n", "}", "\n\n", "if", "req", ".", "RequiredAcks", "==", "proto", ".", "RequiredAcksNone", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "// we expect single partition response", "found", ":=", "false", "\n", "for", "_", ",", "t", ":=", "range", "resp", ".", "Topics", "{", "if", "t", ".", "Name", "!=", "topic", "{", "p", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "t", ".", "Name", ")", "\n", "continue", "\n", "}", "\n", "for", "_", ",", "part", ":=", "range", "t", ".", "Partitions", "{", "if", "part", ".", "ID", "!=", "partition", "{", "p", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "t", ".", "Name", ",", "\"", "\"", ",", "partition", ",", "\"", "\"", ",", "part", ".", "ID", ")", "\n", "continue", "\n", "}", "\n", "found", "=", "true", "\n", "offset", "=", "part", ".", "Offset", "\n", "err", "=", "part", ".", "Err", "\n", "}", "\n", "}", "\n\n", "if", "!", "found", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "offset", ",", "err", "\n", "}" ]
// produce send produce request to leader for given destination.
[ "produce", "send", "produce", "request", "to", "leader", "for", "given", "destination", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L965-L1035
11,287
optiopay/kafka
broker.go
NewConsumerConf
func NewConsumerConf(topic string, partition int32) ConsumerConf { return ConsumerConf{ Topic: topic, Partition: partition, RequestTimeout: time.Millisecond * 50, RetryLimit: -1, RetryWait: time.Millisecond * 50, RetryErrLimit: 10, RetryErrWait: time.Millisecond * 500, MinFetchSize: 1, MaxFetchSize: 2000000, StartOffset: StartOffsetOldest, Logger: nil, } }
go
func NewConsumerConf(topic string, partition int32) ConsumerConf { return ConsumerConf{ Topic: topic, Partition: partition, RequestTimeout: time.Millisecond * 50, RetryLimit: -1, RetryWait: time.Millisecond * 50, RetryErrLimit: 10, RetryErrWait: time.Millisecond * 500, MinFetchSize: 1, MaxFetchSize: 2000000, StartOffset: StartOffsetOldest, Logger: nil, } }
[ "func", "NewConsumerConf", "(", "topic", "string", ",", "partition", "int32", ")", "ConsumerConf", "{", "return", "ConsumerConf", "{", "Topic", ":", "topic", ",", "Partition", ":", "partition", ",", "RequestTimeout", ":", "time", ".", "Millisecond", "*", "50", ",", "RetryLimit", ":", "-", "1", ",", "RetryWait", ":", "time", ".", "Millisecond", "*", "50", ",", "RetryErrLimit", ":", "10", ",", "RetryErrWait", ":", "time", ".", "Millisecond", "*", "500", ",", "MinFetchSize", ":", "1", ",", "MaxFetchSize", ":", "2000000", ",", "StartOffset", ":", "StartOffsetOldest", ",", "Logger", ":", "nil", ",", "}", "\n", "}" ]
// NewConsumerConf returns the default consumer configuration.
[ "NewConsumerConf", "returns", "the", "default", "consumer", "configuration", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1099-L1113
11,288
optiopay/kafka
broker.go
Consumer
func (b *Broker) Consumer(conf ConsumerConf) (Consumer, error) { return b.consumer(conf) }
go
func (b *Broker) Consumer(conf ConsumerConf) (Consumer, error) { return b.consumer(conf) }
[ "func", "(", "b", "*", "Broker", ")", "Consumer", "(", "conf", "ConsumerConf", ")", "(", "Consumer", ",", "error", ")", "{", "return", "b", ".", "consumer", "(", "conf", ")", "\n", "}" ]
// Consumer creates a new consumer instance, bound to the broker.
[ "Consumer", "creates", "a", "new", "consumer", "instance", "bound", "to", "the", "broker", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1128-L1130
11,289
optiopay/kafka
broker.go
BatchConsumer
func (b *Broker) BatchConsumer(conf ConsumerConf) (BatchConsumer, error) { return b.consumer(conf) }
go
func (b *Broker) BatchConsumer(conf ConsumerConf) (BatchConsumer, error) { return b.consumer(conf) }
[ "func", "(", "b", "*", "Broker", ")", "BatchConsumer", "(", "conf", "ConsumerConf", ")", "(", "BatchConsumer", ",", "error", ")", "{", "return", "b", ".", "consumer", "(", "conf", ")", "\n", "}" ]
// BatchConsumer creates a new BatchConsumer instance, bound to the broker.
[ "BatchConsumer", "creates", "a", "new", "BatchConsumer", "instance", "bound", "to", "the", "broker", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1133-L1135
11,290
optiopay/kafka
broker.go
consume
func (c *consumer) consume() ([]*proto.Message, error) { var msgbuf []*proto.Message var retry int for len(msgbuf) == 0 { var err error msgbuf, err = c.fetch() if err != nil { return nil, err } if len(msgbuf) == 0 { if c.conf.RetryWait > 0 { time.Sleep(c.conf.RetryWait) } retry++ if c.conf.RetryLimit != -1 && retry > c.conf.RetryLimit { return nil, ErrNoData } } } return msgbuf, nil }
go
func (c *consumer) consume() ([]*proto.Message, error) { var msgbuf []*proto.Message var retry int for len(msgbuf) == 0 { var err error msgbuf, err = c.fetch() if err != nil { return nil, err } if len(msgbuf) == 0 { if c.conf.RetryWait > 0 { time.Sleep(c.conf.RetryWait) } retry++ if c.conf.RetryLimit != -1 && retry > c.conf.RetryLimit { return nil, ErrNoData } } } return msgbuf, nil }
[ "func", "(", "c", "*", "consumer", ")", "consume", "(", ")", "(", "[", "]", "*", "proto", ".", "Message", ",", "error", ")", "{", "var", "msgbuf", "[", "]", "*", "proto", ".", "Message", "\n", "var", "retry", "int", "\n", "for", "len", "(", "msgbuf", ")", "==", "0", "{", "var", "err", "error", "\n", "msgbuf", ",", "err", "=", "c", ".", "fetch", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "msgbuf", ")", "==", "0", "{", "if", "c", ".", "conf", ".", "RetryWait", ">", "0", "{", "time", ".", "Sleep", "(", "c", ".", "conf", ".", "RetryWait", ")", "\n", "}", "\n", "retry", "++", "\n", "if", "c", ".", "conf", ".", "RetryLimit", "!=", "-", "1", "&&", "retry", ">", "c", ".", "conf", ".", "RetryLimit", "{", "return", "nil", ",", "ErrNoData", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "msgbuf", ",", "nil", "\n", "}" ]
// consume is returning a batch of messages from consumed partition. // Consumer can retry fetching messages even if responses return no new // data. Retry behaviour can be configured through RetryLimit and RetryWait // consumer parameters. // // consume can retry sending request on common errors. This behaviour can // be configured with RetryErrLimit and RetryErrWait consumer configuration // attributes.
[ "consume", "is", "returning", "a", "batch", "of", "messages", "from", "consumed", "partition", ".", "Consumer", "can", "retry", "fetching", "messages", "even", "if", "responses", "return", "no", "new", "data", ".", "Retry", "behaviour", "can", "be", "configured", "through", "RetryLimit", "and", "RetryWait", "consumer", "parameters", ".", "consume", "can", "retry", "sending", "request", "on", "common", "errors", ".", "This", "behaviour", "can", "be", "configured", "with", "RetryErrLimit", "and", "RetryErrWait", "consumer", "configuration", "attributes", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1182-L1203
11,291
optiopay/kafka
broker.go
NewOffsetCoordinatorConf
func NewOffsetCoordinatorConf(consumerGroup string) OffsetCoordinatorConf { return OffsetCoordinatorConf{ ConsumerGroup: consumerGroup, RetryErrLimit: 10, RetryErrWait: time.Millisecond * 500, Logger: nil, } }
go
func NewOffsetCoordinatorConf(consumerGroup string) OffsetCoordinatorConf { return OffsetCoordinatorConf{ ConsumerGroup: consumerGroup, RetryErrLimit: 10, RetryErrWait: time.Millisecond * 500, Logger: nil, } }
[ "func", "NewOffsetCoordinatorConf", "(", "consumerGroup", "string", ")", "OffsetCoordinatorConf", "{", "return", "OffsetCoordinatorConf", "{", "ConsumerGroup", ":", "consumerGroup", ",", "RetryErrLimit", ":", "10", ",", "RetryErrWait", ":", "time", ".", "Millisecond", "*", "500", ",", "Logger", ":", "nil", ",", "}", "\n", "}" ]
// NewOffsetCoordinatorConf returns default OffsetCoordinator configuration.
[ "NewOffsetCoordinatorConf", "returns", "default", "OffsetCoordinator", "configuration", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1379-L1386
11,292
optiopay/kafka
broker.go
OffsetCoordinator
func (b *Broker) OffsetCoordinator(conf OffsetCoordinatorConf) (OffsetCoordinator, error) { conn, err := b.muCoordinatorConnection(conf.ConsumerGroup) if err != nil { return nil, err } if conf.Logger == nil { conf.Logger = b.conf.Logger } c := &offsetCoordinator{ broker: b, conf: conf, conn: conn, } return c, nil }
go
func (b *Broker) OffsetCoordinator(conf OffsetCoordinatorConf) (OffsetCoordinator, error) { conn, err := b.muCoordinatorConnection(conf.ConsumerGroup) if err != nil { return nil, err } if conf.Logger == nil { conf.Logger = b.conf.Logger } c := &offsetCoordinator{ broker: b, conf: conf, conn: conn, } return c, nil }
[ "func", "(", "b", "*", "Broker", ")", "OffsetCoordinator", "(", "conf", "OffsetCoordinatorConf", ")", "(", "OffsetCoordinator", ",", "error", ")", "{", "conn", ",", "err", ":=", "b", ".", "muCoordinatorConnection", "(", "conf", ".", "ConsumerGroup", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "conf", ".", "Logger", "==", "nil", "{", "conf", ".", "Logger", "=", "b", ".", "conf", ".", "Logger", "\n", "}", "\n", "c", ":=", "&", "offsetCoordinator", "{", "broker", ":", "b", ",", "conf", ":", "conf", ",", "conn", ":", "conn", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// OffsetCoordinator returns offset management coordinator for single consumer // group, bound to broker.
[ "OffsetCoordinator", "returns", "offset", "management", "coordinator", "for", "single", "consumer", "group", "bound", "to", "broker", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1398-L1412
11,293
optiopay/kafka
broker.go
Commit
func (c *offsetCoordinator) Commit(topic string, partition int32, offset int64) error { return c.commit(topic, partition, offset, "") }
go
func (c *offsetCoordinator) Commit(topic string, partition int32, offset int64) error { return c.commit(topic, partition, offset, "") }
[ "func", "(", "c", "*", "offsetCoordinator", ")", "Commit", "(", "topic", "string", ",", "partition", "int32", ",", "offset", "int64", ")", "error", "{", "return", "c", ".", "commit", "(", "topic", ",", "partition", ",", "offset", ",", "\"", "\"", ")", "\n", "}" ]
// Commit is saving offset information for given topic and partition. // // Commit can retry saving offset information on common errors. This behaviour // can be configured with with RetryErrLimit and RetryErrWait coordinator // configuration attributes.
[ "Commit", "is", "saving", "offset", "information", "for", "given", "topic", "and", "partition", ".", "Commit", "can", "retry", "saving", "offset", "information", "on", "common", "errors", ".", "This", "behaviour", "can", "be", "configured", "with", "with", "RetryErrLimit", "and", "RetryErrWait", "coordinator", "configuration", "attributes", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1419-L1421
11,294
optiopay/kafka
broker.go
CommitFull
func (c *offsetCoordinator) CommitFull(topic string, partition int32, offset int64, metadata string) error { return c.commit(topic, partition, offset, metadata) }
go
func (c *offsetCoordinator) CommitFull(topic string, partition int32, offset int64, metadata string) error { return c.commit(topic, partition, offset, metadata) }
[ "func", "(", "c", "*", "offsetCoordinator", ")", "CommitFull", "(", "topic", "string", ",", "partition", "int32", ",", "offset", "int64", ",", "metadata", "string", ")", "error", "{", "return", "c", ".", "commit", "(", "topic", ",", "partition", ",", "offset", ",", "metadata", ")", "\n", "}" ]
// Commit works exactly like Commit method, but store extra metadata string // together with offset information.
[ "Commit", "works", "exactly", "like", "Commit", "method", "but", "store", "extra", "metadata", "string", "together", "with", "offset", "information", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1425-L1427
11,295
optiopay/kafka
broker.go
commit
func (c *offsetCoordinator) commit(topic string, partition int32, offset int64, metadata string) (resErr error) { c.mu.Lock() defer c.mu.Unlock() for retry := 0; retry < c.conf.RetryErrLimit; retry++ { if retry != 0 { c.mu.Unlock() time.Sleep(c.conf.RetryErrWait) c.mu.Lock() } // connection can be set to nil if previously reference connection died if c.conn == nil { conn, err := c.broker.muCoordinatorConnection(c.conf.ConsumerGroup) if err != nil { resErr = err c.conf.Logger.Debug("cannot connect to coordinator", "consumGrp", c.conf.ConsumerGroup, "error", err) continue } c.conn = conn } resp, err := c.conn.OffsetCommit(&proto.OffsetCommitReq{ RequestHeader: proto.RequestHeader{ClientID: c.broker.conf.ClientID}, ConsumerGroup: c.conf.ConsumerGroup, Topics: []proto.OffsetCommitReqTopic{ { Name: topic, Partitions: []proto.OffsetCommitReqPartition{ {ID: partition, Offset: offset, TimeStamp: time.Now(), Metadata: metadata}, }, }, }, }) resErr = err if _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE { c.conf.Logger.Debug("connection died while commiting", "topic", topic, "partition", partition, "consumGrp", c.conf.ConsumerGroup) c.broker.muCloseDeadConnection(c.conn) c.conn = nil } else if err == nil { for _, t := range resp.Topics { if t.Name != topic { c.conf.Logger.Debug("unexpected topic information received", "got", t.Name, "expected", topic) continue } for _, part := range t.Partitions { if part.ID != partition { c.conf.Logger.Debug("unexpected partition information received", "topic", topic, "got", part.ID, "expected", partition) continue } return part.Err } } return errors.New("response does not contain commit information") } } return resErr }
go
func (c *offsetCoordinator) commit(topic string, partition int32, offset int64, metadata string) (resErr error) { c.mu.Lock() defer c.mu.Unlock() for retry := 0; retry < c.conf.RetryErrLimit; retry++ { if retry != 0 { c.mu.Unlock() time.Sleep(c.conf.RetryErrWait) c.mu.Lock() } // connection can be set to nil if previously reference connection died if c.conn == nil { conn, err := c.broker.muCoordinatorConnection(c.conf.ConsumerGroup) if err != nil { resErr = err c.conf.Logger.Debug("cannot connect to coordinator", "consumGrp", c.conf.ConsumerGroup, "error", err) continue } c.conn = conn } resp, err := c.conn.OffsetCommit(&proto.OffsetCommitReq{ RequestHeader: proto.RequestHeader{ClientID: c.broker.conf.ClientID}, ConsumerGroup: c.conf.ConsumerGroup, Topics: []proto.OffsetCommitReqTopic{ { Name: topic, Partitions: []proto.OffsetCommitReqPartition{ {ID: partition, Offset: offset, TimeStamp: time.Now(), Metadata: metadata}, }, }, }, }) resErr = err if _, ok := err.(*net.OpError); ok || err == io.EOF || err == syscall.EPIPE { c.conf.Logger.Debug("connection died while commiting", "topic", topic, "partition", partition, "consumGrp", c.conf.ConsumerGroup) c.broker.muCloseDeadConnection(c.conn) c.conn = nil } else if err == nil { for _, t := range resp.Topics { if t.Name != topic { c.conf.Logger.Debug("unexpected topic information received", "got", t.Name, "expected", topic) continue } for _, part := range t.Partitions { if part.ID != partition { c.conf.Logger.Debug("unexpected partition information received", "topic", topic, "got", part.ID, "expected", partition) continue } return part.Err } } return errors.New("response does not contain commit information") } } return resErr }
[ "func", "(", "c", "*", "offsetCoordinator", ")", "commit", "(", "topic", "string", ",", "partition", "int32", ",", "offset", "int64", ",", "metadata", "string", ")", "(", "resErr", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "for", "retry", ":=", "0", ";", "retry", "<", "c", ".", "conf", ".", "RetryErrLimit", ";", "retry", "++", "{", "if", "retry", "!=", "0", "{", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "time", ".", "Sleep", "(", "c", ".", "conf", ".", "RetryErrWait", ")", "\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "}", "\n\n", "// connection can be set to nil if previously reference connection died", "if", "c", ".", "conn", "==", "nil", "{", "conn", ",", "err", ":=", "c", ".", "broker", ".", "muCoordinatorConnection", "(", "c", ".", "conf", ".", "ConsumerGroup", ")", "\n", "if", "err", "!=", "nil", "{", "resErr", "=", "err", "\n", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "c", ".", "conf", ".", "ConsumerGroup", ",", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "c", ".", "conn", "=", "conn", "\n", "}", "\n\n", "resp", ",", "err", ":=", "c", ".", "conn", ".", "OffsetCommit", "(", "&", "proto", ".", "OffsetCommitReq", "{", "RequestHeader", ":", "proto", ".", "RequestHeader", "{", "ClientID", ":", "c", ".", "broker", ".", "conf", ".", "ClientID", "}", ",", "ConsumerGroup", ":", "c", ".", "conf", ".", "ConsumerGroup", ",", "Topics", ":", "[", "]", "proto", ".", "OffsetCommitReqTopic", "{", "{", "Name", ":", "topic", ",", "Partitions", ":", "[", "]", "proto", ".", "OffsetCommitReqPartition", "{", "{", "ID", ":", "partition", ",", "Offset", ":", "offset", ",", "TimeStamp", ":", "time", ".", "Now", "(", ")", ",", "Metadata", ":", "metadata", "}", ",", "}", ",", "}", ",", "}", ",", "}", ")", "\n", "resErr", "=", "err", "\n\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "||", "err", "==", "io", ".", "EOF", "||", "err", "==", "syscall", ".", "EPIPE", "{", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "partition", ",", "\"", "\"", ",", "c", ".", "conf", ".", "ConsumerGroup", ")", "\n", "c", ".", "broker", ".", "muCloseDeadConnection", "(", "c", ".", "conn", ")", "\n", "c", ".", "conn", "=", "nil", "\n", "}", "else", "if", "err", "==", "nil", "{", "for", "_", ",", "t", ":=", "range", "resp", ".", "Topics", "{", "if", "t", ".", "Name", "!=", "topic", "{", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "t", ".", "Name", ",", "\"", "\"", ",", "topic", ")", "\n", "continue", "\n\n", "}", "\n", "for", "_", ",", "part", ":=", "range", "t", ".", "Partitions", "{", "if", "part", ".", "ID", "!=", "partition", "{", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "part", ".", "ID", ",", "\"", "\"", ",", "partition", ")", "\n", "continue", "\n", "}", "\n", "return", "part", ".", "Err", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "resErr", "\n", "}" ]
// commit is saving offset and metadata information. Provides limited error // handling configurable through OffsetCoordinatorConf.
[ "commit", "is", "saving", "offset", "and", "metadata", "information", ".", "Provides", "limited", "error", "handling", "configurable", "through", "OffsetCoordinatorConf", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1431-L1500
11,296
optiopay/kafka
broker.go
Offset
func (c *offsetCoordinator) Offset(topic string, partition int32) (offset int64, metadata string, resErr error) { c.mu.Lock() defer c.mu.Unlock() for retry := 0; retry < c.conf.RetryErrLimit; retry++ { if retry != 0 { c.mu.Unlock() time.Sleep(c.conf.RetryErrWait) c.mu.Lock() } // connection can be set to nil if previously reference connection died if c.conn == nil { conn, err := c.broker.muCoordinatorConnection(c.conf.ConsumerGroup) if err != nil { c.conf.Logger.Debug("cannot connect to coordinator", "consumGrp", c.conf.ConsumerGroup, "error", err) resErr = err continue } c.conn = conn } resp, err := c.conn.OffsetFetch(&proto.OffsetFetchReq{ ConsumerGroup: c.conf.ConsumerGroup, Topics: []proto.OffsetFetchReqTopic{ { Name: topic, Partitions: []int32{partition}, }, }, }) resErr = err switch err { case io.EOF, syscall.EPIPE: c.conf.Logger.Debug("connection died while fetching offset", "topic", topic, "partition", partition, "consumGrp", c.conf.ConsumerGroup) c.broker.muCloseDeadConnection(c.conn) c.conn = nil case nil: for _, t := range resp.Topics { if t.Name != topic { c.conf.Logger.Debug("unexpected topic information received", "got", t.Name, "expected", topic) continue } for _, part := range t.Partitions { if part.ID != partition { c.conf.Logger.Debug("unexpected partition information received", "topic", topic, "expected", partition, "get", part.ID) continue } if part.Err != nil { return 0, "", part.Err } return part.Offset, part.Metadata, nil } } return 0, "", errors.New("response does not contain offset information") } } return 0, "", resErr }
go
func (c *offsetCoordinator) Offset(topic string, partition int32) (offset int64, metadata string, resErr error) { c.mu.Lock() defer c.mu.Unlock() for retry := 0; retry < c.conf.RetryErrLimit; retry++ { if retry != 0 { c.mu.Unlock() time.Sleep(c.conf.RetryErrWait) c.mu.Lock() } // connection can be set to nil if previously reference connection died if c.conn == nil { conn, err := c.broker.muCoordinatorConnection(c.conf.ConsumerGroup) if err != nil { c.conf.Logger.Debug("cannot connect to coordinator", "consumGrp", c.conf.ConsumerGroup, "error", err) resErr = err continue } c.conn = conn } resp, err := c.conn.OffsetFetch(&proto.OffsetFetchReq{ ConsumerGroup: c.conf.ConsumerGroup, Topics: []proto.OffsetFetchReqTopic{ { Name: topic, Partitions: []int32{partition}, }, }, }) resErr = err switch err { case io.EOF, syscall.EPIPE: c.conf.Logger.Debug("connection died while fetching offset", "topic", topic, "partition", partition, "consumGrp", c.conf.ConsumerGroup) c.broker.muCloseDeadConnection(c.conn) c.conn = nil case nil: for _, t := range resp.Topics { if t.Name != topic { c.conf.Logger.Debug("unexpected topic information received", "got", t.Name, "expected", topic) continue } for _, part := range t.Partitions { if part.ID != partition { c.conf.Logger.Debug("unexpected partition information received", "topic", topic, "expected", partition, "get", part.ID) continue } if part.Err != nil { return 0, "", part.Err } return part.Offset, part.Metadata, nil } } return 0, "", errors.New("response does not contain offset information") } } return 0, "", resErr }
[ "func", "(", "c", "*", "offsetCoordinator", ")", "Offset", "(", "topic", "string", ",", "partition", "int32", ")", "(", "offset", "int64", ",", "metadata", "string", ",", "resErr", "error", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "for", "retry", ":=", "0", ";", "retry", "<", "c", ".", "conf", ".", "RetryErrLimit", ";", "retry", "++", "{", "if", "retry", "!=", "0", "{", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "time", ".", "Sleep", "(", "c", ".", "conf", ".", "RetryErrWait", ")", "\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "}", "\n\n", "// connection can be set to nil if previously reference connection died", "if", "c", ".", "conn", "==", "nil", "{", "conn", ",", "err", ":=", "c", ".", "broker", ".", "muCoordinatorConnection", "(", "c", ".", "conf", ".", "ConsumerGroup", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "c", ".", "conf", ".", "ConsumerGroup", ",", "\"", "\"", ",", "err", ")", "\n", "resErr", "=", "err", "\n", "continue", "\n", "}", "\n", "c", ".", "conn", "=", "conn", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "conn", ".", "OffsetFetch", "(", "&", "proto", ".", "OffsetFetchReq", "{", "ConsumerGroup", ":", "c", ".", "conf", ".", "ConsumerGroup", ",", "Topics", ":", "[", "]", "proto", ".", "OffsetFetchReqTopic", "{", "{", "Name", ":", "topic", ",", "Partitions", ":", "[", "]", "int32", "{", "partition", "}", ",", "}", ",", "}", ",", "}", ")", "\n", "resErr", "=", "err", "\n\n", "switch", "err", "{", "case", "io", ".", "EOF", ",", "syscall", ".", "EPIPE", ":", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "partition", ",", "\"", "\"", ",", "c", ".", "conf", ".", "ConsumerGroup", ")", "\n", "c", ".", "broker", ".", "muCloseDeadConnection", "(", "c", ".", "conn", ")", "\n", "c", ".", "conn", "=", "nil", "\n", "case", "nil", ":", "for", "_", ",", "t", ":=", "range", "resp", ".", "Topics", "{", "if", "t", ".", "Name", "!=", "topic", "{", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "t", ".", "Name", ",", "\"", "\"", ",", "topic", ")", "\n", "continue", "\n", "}", "\n", "for", "_", ",", "part", ":=", "range", "t", ".", "Partitions", "{", "if", "part", ".", "ID", "!=", "partition", "{", "c", ".", "conf", ".", "Logger", ".", "Debug", "(", "\"", "\"", ",", "\"", "\"", ",", "topic", ",", "\"", "\"", ",", "partition", ",", "\"", "\"", ",", "part", ".", "ID", ")", "\n", "continue", "\n", "}", "\n", "if", "part", ".", "Err", "!=", "nil", "{", "return", "0", ",", "\"", "\"", ",", "part", ".", "Err", "\n", "}", "\n", "return", "part", ".", "Offset", ",", "part", ".", "Metadata", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "0", ",", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "0", ",", "\"", "\"", ",", "resErr", "\n", "}" ]
// Offset is returning last offset and metadata information committed for given // topic and partition. // Offset can retry sending request on common errors. This behaviour can be // configured with with RetryErrLimit and RetryErrWait coordinator // configuration attributes.
[ "Offset", "is", "returning", "last", "offset", "and", "metadata", "information", "committed", "for", "given", "topic", "and", "partition", ".", "Offset", "can", "retry", "sending", "request", "on", "common", "errors", ".", "This", "behaviour", "can", "be", "configured", "with", "with", "RetryErrLimit", "and", "RetryErrWait", "coordinator", "configuration", "attributes", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/broker.go#L1507-L1576
11,297
optiopay/kafka
connection.go
newTCPConnection
func newTCPConnection(address string, timeout, readTimeout time.Duration) (*connection, error) { var fetchVersions = true for { dialer := net.Dialer{ Timeout: timeout, KeepAlive: 30 * time.Second, } conn, err := dialer.Dial("tcp", address) if err != nil { return nil, err } c := &connection{ stop: make(chan struct{}), nextID: make(chan int32), rw: conn, respc: make(map[int32]chan []byte), logger: &nullLogger{}, readTimeout: readTimeout, apiVersions: make(map[int16]proto.SupportedVersion), } go c.nextIDLoop() go c.readRespLoop() if fetchVersions { if c.cacheApiVersions() != nil { fetchVersions = false //required for errorchk _ = c.Close() continue } } return c, nil } }
go
func newTCPConnection(address string, timeout, readTimeout time.Duration) (*connection, error) { var fetchVersions = true for { dialer := net.Dialer{ Timeout: timeout, KeepAlive: 30 * time.Second, } conn, err := dialer.Dial("tcp", address) if err != nil { return nil, err } c := &connection{ stop: make(chan struct{}), nextID: make(chan int32), rw: conn, respc: make(map[int32]chan []byte), logger: &nullLogger{}, readTimeout: readTimeout, apiVersions: make(map[int16]proto.SupportedVersion), } go c.nextIDLoop() go c.readRespLoop() if fetchVersions { if c.cacheApiVersions() != nil { fetchVersions = false //required for errorchk _ = c.Close() continue } } return c, nil } }
[ "func", "newTCPConnection", "(", "address", "string", ",", "timeout", ",", "readTimeout", "time", ".", "Duration", ")", "(", "*", "connection", ",", "error", ")", "{", "var", "fetchVersions", "=", "true", "\n", "for", "{", "dialer", ":=", "net", ".", "Dialer", "{", "Timeout", ":", "timeout", ",", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "}", "\n", "conn", ",", "err", ":=", "dialer", ".", "Dial", "(", "\"", "\"", ",", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ":=", "&", "connection", "{", "stop", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "nextID", ":", "make", "(", "chan", "int32", ")", ",", "rw", ":", "conn", ",", "respc", ":", "make", "(", "map", "[", "int32", "]", "chan", "[", "]", "byte", ")", ",", "logger", ":", "&", "nullLogger", "{", "}", ",", "readTimeout", ":", "readTimeout", ",", "apiVersions", ":", "make", "(", "map", "[", "int16", "]", "proto", ".", "SupportedVersion", ")", ",", "}", "\n", "go", "c", ".", "nextIDLoop", "(", ")", "\n", "go", "c", ".", "readRespLoop", "(", ")", "\n\n", "if", "fetchVersions", "{", "if", "c", ".", "cacheApiVersions", "(", ")", "!=", "nil", "{", "fetchVersions", "=", "false", "\n", "//required for errorchk", "_", "=", "c", ".", "Close", "(", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "return", "c", ",", "nil", "\n", "}", "\n\n", "}" ]
// newConnection returns new, initialized connection or error
[ "newConnection", "returns", "new", "initialized", "connection", "or", "error" ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L87-L121
11,298
optiopay/kafka
connection.go
getBestVersion
func (c *connection) getBestVersion(apiKey int16) int16 { if requested, ok := c.apiVersions[apiKey]; ok { supported := proto.SupportedByDriver[apiKey] if min(supported.MaxVersion, requested.MaxVersion) >= max(supported.MinVersion, requested.MinVersion) { return min(supported.MaxVersion, requested.MaxVersion) } } return 0 }
go
func (c *connection) getBestVersion(apiKey int16) int16 { if requested, ok := c.apiVersions[apiKey]; ok { supported := proto.SupportedByDriver[apiKey] if min(supported.MaxVersion, requested.MaxVersion) >= max(supported.MinVersion, requested.MinVersion) { return min(supported.MaxVersion, requested.MaxVersion) } } return 0 }
[ "func", "(", "c", "*", "connection", ")", "getBestVersion", "(", "apiKey", "int16", ")", "int16", "{", "if", "requested", ",", "ok", ":=", "c", ".", "apiVersions", "[", "apiKey", "]", ";", "ok", "{", "supported", ":=", "proto", ".", "SupportedByDriver", "[", "apiKey", "]", "\n", "if", "min", "(", "supported", ".", "MaxVersion", ",", "requested", ".", "MaxVersion", ")", ">=", "max", "(", "supported", ".", "MinVersion", ",", "requested", ".", "MinVersion", ")", "{", "return", "min", "(", "supported", ".", "MaxVersion", ",", "requested", ".", "MaxVersion", ")", "\n", "}", "\n", "}", "\n", "return", "0", "\n", "}" ]
//getBestVersion returns version for passed apiKey which best fit server and client requirements
[ "getBestVersion", "returns", "version", "for", "passed", "apiKey", "which", "best", "fit", "server", "and", "client", "requirements" ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L137-L145
11,299
optiopay/kafka
connection.go
nextIDLoop
func (c *connection) nextIDLoop() { var id int32 = 1 for { select { case <-c.stop: close(c.nextID) return case c.nextID <- id: id++ if id == math.MaxInt32 { id = 1 } } } }
go
func (c *connection) nextIDLoop() { var id int32 = 1 for { select { case <-c.stop: close(c.nextID) return case c.nextID <- id: id++ if id == math.MaxInt32 { id = 1 } } } }
[ "func", "(", "c", "*", "connection", ")", "nextIDLoop", "(", ")", "{", "var", "id", "int32", "=", "1", "\n", "for", "{", "select", "{", "case", "<-", "c", ".", "stop", ":", "close", "(", "c", ".", "nextID", ")", "\n", "return", "\n", "case", "c", ".", "nextID", "<-", "id", ":", "id", "++", "\n", "if", "id", "==", "math", ".", "MaxInt32", "{", "id", "=", "1", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// nextIDLoop generates correlation IDs, making sure they are always in order // and within the scope of request-response mapping array.
[ "nextIDLoop", "generates", "correlation", "IDs", "making", "sure", "they", "are", "always", "in", "order", "and", "within", "the", "scope", "of", "request", "-", "response", "mapping", "array", "." ]
6c126522640ec5e8e232d0e219160b30a92814f8
https://github.com/optiopay/kafka/blob/6c126522640ec5e8e232d0e219160b30a92814f8/connection.go#L163-L177