code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1 value |
|---|---|---|---|---|---|
package r3
import (
"math"
"sort"
)
// Point represent a point in 3D space through cartesian coordinates.
type Point struct {
X, Y, Z float64
}
// Vector represent a vector in 3D space .
type Vector struct {
X, Y, Z float64
}
// Plane represent a plane in 3D space .
type Plane struct {
orig Point
normal Vector
}
// Dot computes the dot product between this and the given vector.
func (v Vector) Dot(v2 Vector) float64 {
return v.X*v2.X + v.Y*v2.Y + v.Z*v2.Z
}
// Cross computes the cross product between this and the given vector.
func (v Vector) Cross(v2 Vector) Vector {
return Vector{
v.Y*v2.Z - v.Z*v2.Y,
v.Z*v2.X - v.X*v2.Z,
v.X*v2.Y - v.Y*v2.X,
}
}
// Length returns the length of the vector.
func (v Vector) Length() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y + v.Z*v.Z)
}
// Normalised returns a copy of this vector that is scaled to length 1.
func (v Vector) Normalised() Vector {
return v.Scale(1 / v.Length())
}
// Scale returns a copy of this vector that has its length multiplied by the given value.
func (v Vector) Scale(s float64) Vector {
return Vector{v.X * s, v.Y * s, v.Z * s}
}
// VectorTo returns the vector from this point to the given point.
func (p Point) VectorTo(p2 Point) Vector {
return Vector{p2.X - p.X, p2.Y - p.Y, p2.Z - p.Z}
}
// Add returns the point that results by displacing this point by the given vector.
func (p Point) Add(v Vector) Point {
return Point{p.X + v.X, p.Y + v.Y, p.Z + v.Z}
}
// ProjectPointOnPlane returns the point in the given plane that is closes to the given point.
func ProjectPointOnPlane(point Point, plane Plane) Point {
dist := plane.orig.VectorTo(point).Dot(plane.normal)
vecToPlane := plane.normal.Scale(-dist)
return point.Add(vecToPlane)
}
// PlaneFromPoints returns the plane defined by the given three points.
func PlaneFromPoints(p1, p2, p3 Point) Plane {
dir1 := p1.VectorTo(p2)
dir2 := p1.VectorTo(p3)
pNormal := dir1.Cross(dir2).Normalised()
return Plane{p1, pNormal}
}
// Spherical returns the spherical coordinates of the given point.
func (p Point) Spherical() SphericalCoordinate {
x, y, z := p.X, p.Y, p.Z
r := math.Sqrt(x*x + y*y + z*z)
theta := math.Acos(z / r)
phi := math.Atan2(y, x)
return SphericalCoordinate{r, theta, phi}
}
// SphericalCoordinate represents a point in 3D space using spherical coordinates.
type SphericalCoordinate struct {
R, Theta, Phi float64
}
// UnitSphereCoordinates represents a point in 3D space on the unit sphere.
type UnitSphereCoordinates struct {
theta, phi float64
}
// Centroid3D computes the centroid of the given points.
func Centroid3D(points []Point) Point {
x, y, z := 0.0, 0.0, 0.0
for _, p := range points {
x += p.X
y += p.Y
z += p.Z
}
x /= float64(len(points))
y /= float64(len(points))
z /= float64(len(points))
return Point{x, y, z}
}
// WeightedCentroid computes the centroid of the given points, but the contribution of each point is scaled by its weight.
// The weights represent relative weights and will be scaled by the overall sum of weights.
func WeightedCentroid(points []Point, weights []float64) Point {
x, y, z := 0.0, 0.0, 0.0
wSum := 0.0
for i, p := range points {
w := weights[i]
wSum += w
x += p.X * w
y += p.Y * w
z += p.Z * w
}
x /= wSum
y /= wSum
z /= wSum
return Point{x, y, z}
}
// Distance computes the distance between the two given points.
func Distance(p1 Point, p2 Point) float64 {
dx := p1.X - p2.X
dy := p1.Y - p2.Y
dz := p1.Z - p2.Z
return math.Sqrt(dx*dx + dy*dy + dz*dz)
}
// CounterClockwise3D sorts the given points clockwise around the given normal.
func CounterClockwise3D(v []Point, normal Vector) sort.Interface {
cc := counterClockwise3D{}
cc.v = v
cc.center = Centroid3D(v)
cc.normal = normal.Normalised()
return cc
}
type counterClockwise3D struct {
v []Point
normal Vector
center Point
}
func (v counterClockwise3D) Len() int { return len(v.v) }
func (v counterClockwise3D) Swap(i, j int) { v.v[i], v.v[j] = v.v[j], v.v[i] }
func (v counterClockwise3D) Less(i, j int) bool {
v1 := v.center.VectorTo(v.v[i])
v2 := v.center.VectorTo(v.v[j])
vc := v1.Cross(v2)
n := v.normal.Dot(vc)
return n < 0
}
// IsCCW returns whether point a is clockwise to point b relative to the given normal.
func IsCCW(a, b Point, center Point, normal Vector) bool {
v1 := center.VectorTo(a)
v2 := center.VectorTo(b)
vc := v1.Cross(v2)
n := normal.Dot(vc)
return n > 0
} | r3/r3.go | 0.91529 | 0.807271 | r3.go | starcoder |
package doboz
import (
"encoding/binary"
)
type Compressor struct {
dict Dictionary
}
// Returns the maximum compressed size of any block of data with the specified size
// This function should be used to determine the size of the compression destination buffer
func GetMaxCompressedSize(size int) int {
// The header + the original uncompressed data
return getHeaderSize(MaxInt) + size
}
func getHeaderSize(maxCompressedSize int) int {
return 1 + 2*getSizeCodedSize(maxCompressedSize)
}
func getSizeCodedSize(size int) int {
if size <= 255 {
return 1
}
if size <= 65535 {
return 2
}
/*if (size <= MaxUint) {
return 4
}
return 8*/
return 4
}
// Compresses a block of data
// The source and destination buffers must not overlap and their size must be greater than 0
// This operation is memory safe
// On success, returns RESULT_OK and outputs the compressed size
func (c *Compressor) Compress(source []byte, destination []byte) (Result, int) {
if len(source) == 0 {
return RESULT_ERROR_BUFFER_TOO_SMALL, 0
}
maxCompressedSize := GetMaxCompressedSize(len(source))
if len(destination) < maxCompressedSize {
return RESULT_ERROR_BUFFER_TOO_SMALL, 0
}
inputBuffer := source
outputBuffer := destination
// Compute the maximum output end pointer
// We use this to determine whether we should store the data instead of compressing it
maxOutputEnd := maxCompressedSize
// Allocate the header
outputIterator := getHeaderSize(maxCompressedSize)
// Initialize the dictionary
c.dict.SetBuffer(inputBuffer)
// Initialize the control word which contains the literal/match bits
// The highest bit of a control word is a guard bit, which marks the end of the bit list
// The guard bit simplifies and speeds up the decoding process, and it
const controlWordBitCount int = WORD_SIZE*8 - 1
const controlWordGuardBit uint = uint(1) << controlWordBitCount
controlWord := controlWordGuardBit
controlWordBit := 0
// Since we do not know the contents of the control words in advance, we allocate space for them and subsequently fill them with data as soon as we can
// This is necessary because the decoder must encounter a control word *before* the literals and matches it refers to
// We begin the compressed data with a control word
controlWordPointer := outputIterator
outputIterator += WORD_SIZE
// The match located at the current inputIterator position
var match Match
// The match located at the next inputIterator position
// Initialize it to 'no match', because we are at the beginning of the inputIterator buffer
// A match with a length of 0 means that there is no match
var nextMatch Match
nextMatch.Length = 0
// The dictionary matching look-ahead is 1 character, so set the dictionary position to 1
// We don't have to worry about getting matches beyond the inputIterator, because the dictionary ignores such requests
c.dict.Skip()
// At each position, we select the best match to encode from a list of match candidates provided by the match finder
var matchCandidates [MAX_MATCH_CANDIDATE_COUNT]Match
var matchCandidateCount int
// Iterate while there is still data left
for c.dict.Position()-1 < len(source) {
// Check whether the output is too large
// During each iteration, we may output up to 8 bytes (2 words), and the compressed stream ends with 4 dummy bytes
if outputIterator+2*WORD_SIZE+TRAILING_DUMMY_SIZE > maxOutputEnd {
// Stop the compression and instead store
return c.store(source, destination)
}
// Check whether the control word must be flushed
if controlWordBit == controlWordBitCount {
// Flush current control word
FastWrite(outputBuffer[controlWordPointer:], controlWord, WORD_SIZE)
// New control word
controlWord = controlWordGuardBit
controlWordBit = 0
controlWordPointer = outputIterator
outputIterator += WORD_SIZE
}
// The current match is the previous 'next' match
match = nextMatch
// Find the best match at the next position
// The dictionary position is automatically incremented
matchCandidateCount = c.dict.FindMatches(matchCandidates[:])
nextMatch = c.getBestMatch(matchCandidates[:matchCandidateCount])
// If we have a match, do not immediately use it, because we may miss an even better match (lazy evaluation)
// If encoding a literal and the next match has a higher compression ratio than encoding the current match, discard the current match
if match.Length > 0 && (1+nextMatch.Length)*c.getMatchCodedSize(match) > match.Length*(1+c.getMatchCodedSize(nextMatch)) {
match.Length = 0
}
// Check whether we must encode a literal or a match
if match.Length == 0 {
// Encode a literal (0 control word flag)
// In order to efficiently decode literals in runs, the literal bit (0) must differ from the guard bit (1)
// The current dictionary position is now two characters ahead of the literal to encode
FastWrite(outputBuffer[outputIterator:], uint(inputBuffer[c.dict.Position()-2]), 1)
outputIterator++
} else {
// Encode a match (1 control word flag)
controlWord |= uint(1 << controlWordBit)
outputIterator += c.encodeMatch(match, outputBuffer[outputIterator:])
// Skip the matched characters
for i := 0; i < match.Length-2; i++ {
c.dict.Skip()
}
matchCandidateCount = c.dict.FindMatches(matchCandidates[:])
nextMatch = c.getBestMatch(matchCandidates[:matchCandidateCount])
}
// Next control word bit
controlWordBit++
}
// Flush the control word
FastWrite(outputBuffer[controlWordPointer:], controlWord, WORD_SIZE)
// Output trailing safety dummy bytes
// This reduces the number of necessary buffer checks during decoding
FastWrite(outputBuffer[outputIterator:], 0, TRAILING_DUMMY_SIZE)
outputIterator += TRAILING_DUMMY_SIZE
// Done, compute the compressed size
compressedSize := outputIterator
// Encode the header
var header Header
header.Version = VERSION
header.IsStored = false
header.UncompressedSize = uint64(len(source))
header.CompressedSize = uint64(compressedSize)
c.encodeHeader(header, maxCompressedSize, outputBuffer)
// Return the compressed size
return RESULT_OK, compressedSize
}
// Store the source
func (c *Compressor) store(source []byte, destination []byte) (Result, int) {
outputBuffer := destination
outputIterator := 0
// Encode the header
maxCompressedSize := GetMaxCompressedSize(len(source))
headerSize := getHeaderSize(maxCompressedSize)
compressedSize := headerSize + len(source)
var header Header
header.Version = VERSION
header.IsStored = true
header.UncompressedSize = uint64(len(source))
header.CompressedSize = uint64(compressedSize)
c.encodeHeader(header, maxCompressedSize, destination)
outputIterator += headerSize
// Store the data
copy(outputBuffer[outputIterator:], source)
return RESULT_OK, compressedSize
}
func (c *Compressor) getBestMatch(matchCandidates []Match) (bestMatch Match) {
bestMatch.Length = 0
// Select the longest match which can be coded efficiently (coded size is less than the length)
for _, matchCandidate := range matchCandidates {
if matchCandidate.Length > c.getMatchCodedSize(matchCandidate) {
bestMatch = matchCandidate
break
}
}
return
}
func (c *Compressor) encodeMatch(match Match, destination []byte) int {
var word uint
var size int
lengthCode := uint(match.Length - MIN_MATCH_LENGTH)
offsetCode := uint(match.Offset)
if lengthCode == 0 && offsetCode < 64 {
word = offsetCode << 2 // 00
size = 1
} else if lengthCode == 0 && offsetCode < 16384 {
word = (offsetCode << 2) | 1 // 01
size = 2
} else if lengthCode < 16 && offsetCode < 1024 {
word = (offsetCode << 6) | (lengthCode << 2) | 2 // 10
size = 2
} else if lengthCode < 32 && offsetCode < 65536 {
word = (offsetCode << 8) | (lengthCode << 3) | 3 // 11
size = 3
} else {
word = (offsetCode << 11) | (lengthCode << 3) | 7 // 111
size = 4
}
if destination != nil {
FastWrite(destination, word, size)
}
return size
}
func (c *Compressor) getMatchCodedSize(match Match) int {
return c.encodeMatch(match, nil)
}
func (c *Compressor) encodeHeader(header Header, maxCompressedSize int, destination []byte) {
// Encode the attribute byte
attributes := uint(header.Version)
sizeCodedSize := uint(getSizeCodedSize(maxCompressedSize))
attributes |= (sizeCodedSize - 1) << 3
if header.IsStored {
attributes |= 128
}
destination[0] = byte(attributes)
destination = destination[1:]
// Encode the uncompressed and compressed sizes
switch sizeCodedSize {
case 1:
destination[0] = byte(header.UncompressedSize)
destination[sizeCodedSize] = byte(header.CompressedSize)
case 2:
binary.LittleEndian.PutUint16(destination, uint16(header.UncompressedSize))
binary.LittleEndian.PutUint16(destination[2:], uint16(header.CompressedSize))
case 4:
binary.LittleEndian.PutUint32(destination, uint32(header.UncompressedSize))
binary.LittleEndian.PutUint32(destination[4:], uint32(header.CompressedSize))
case 8:
binary.LittleEndian.PutUint64(destination, header.UncompressedSize)
binary.LittleEndian.PutUint64(destination[8:], header.CompressedSize)
}
} | compressor.go | 0.846831 | 0.541773 | compressor.go | starcoder |
package types
import (
"fmt"
"github.com/tendermint/go-wire/data"
)
// Result is a common result object for ABCI calls.
// CONTRACT: a zero Result is OK.
type Result struct {
Code CodeType `json:"code"`
Data data.Bytes `json:"data"`
Log string `json:"log"` // Can be non-deterministic
}
func NewResult(code CodeType, data []byte, log string) Result {
return Result{
Code: code,
Data: data,
Log: log,
}
}
func (res Result) IsOK() bool {
return res.Code == CodeType_OK
}
func (res Result) IsErr() bool {
return res.Code != CodeType_OK
}
func (res Result) IsSameCode(compare Result) bool {
return res.Code == compare.Code
}
func (res Result) Error() string {
return fmt.Sprintf("ABCI{code:%v, data:%X, log:%v}", res.Code, res.Data, res.Log)
}
func (res Result) String() string {
return fmt.Sprintf("ABCI{code:%v, data:%X, log:%v}", res.Code, res.Data, res.Log)
}
func (res Result) PrependLog(log string) Result {
return Result{
Code: res.Code,
Data: res.Data,
Log: log + ";" + res.Log,
}
}
func (res Result) AppendLog(log string) Result {
return Result{
Code: res.Code,
Data: res.Data,
Log: res.Log + ";" + log,
}
}
func (res Result) SetLog(log string) Result {
return Result{
Code: res.Code,
Data: res.Data,
Log: log,
}
}
func (res Result) SetData(data []byte) Result {
return Result{
Code: res.Code,
Data: data,
Log: res.Log,
}
}
//----------------------------------------
// NOTE: if data == nil and log == "", same as zero Result.
func NewResultOK(data []byte, log string) Result {
return Result{
Code: CodeType_OK,
Data: data,
Log: log,
}
}
func NewError(code CodeType, log string) Result {
return Result{
Code: code,
Log: log,
}
}
//----------------------------------------
// Convenience methods for turning the
// pb type into one using data.Bytes
// Convert ResponseCheckTx to standard Result
func (r *ResponseCheckTx) Result() Result {
return Result{
Code: r.Code,
Data: r.Data,
Log: r.Log,
}
}
// Convert ResponseDeliverTx to standard Result
func (r *ResponseDeliverTx) Result() Result {
return Result{
Code: r.Code,
Data: r.Data,
Log: r.Log,
}
}
type ResultQuery struct {
Code CodeType `json:"code"`
Index int64 `json:"index"`
Key data.Bytes `json:"key"`
Value data.Bytes `json:"value"`
Proof data.Bytes `json:"proof"`
Height uint64 `json:"height"`
Log string `json:"log"`
}
func (r *ResponseQuery) Result() *ResultQuery {
return &ResultQuery{
Code: r.Code,
Index: r.Index,
Key: r.Key,
Value: r.Value,
Proof: r.Proof,
Height: r.Height,
Log: r.Log,
}
} | vendor/github.com/tendermint/abci/types/result.go | 0.72487 | 0.45647 | result.go | starcoder |
package dst
// Gamma distribution, helper functions, log versions.
func pgamma_raw_ln(x, shape float64) float64 {
// Here, assume that (x, shape) are not NA & shape > 0 .
var res, sum float64
if x <= 0 {
return negInf
}
if x >= posInf {
return 0
}
if x < 1 {
res = pgamma_smallx_ln(x, shape)
} else if x <= shape-1 && x < 0.8*(shape+50) {
// incl. large shape compared to x
sum = log(pd_upper_series(x, shape)) // = x/shape + o(x/shape)
d := dpois_wrap_ln(shape, x)
// res = log_p ? sum + d : sum * d
res = sum + d
} else if shape-1 < x && shape < 0.8*(x+50) {
// incl. large x compared to shape
d := dpois_wrap_ln(shape, x)
if shape < 1 {
if x*eps64 > 1-shape {
// sum = R_D__1
sum = 0
} else {
f := pd_lower_cf(shape, x-(shape-1)) * x / shape
// = [shape/(x - shape+1) + o(shape/(x-shape+1))] * x/shape = 1 + o(1)
// sum = log_p ? log (f) : f
sum = log(f)
}
} else {
sum = pd_lower_series(x, shape-1) // = (shape-1)/x + o((shape-1)/x)
// sum = log_p ? log1p (sum) : 1 + sum
sum = log1p(sum)
}
// res = log_p ? R_Log1_Exp (d + sum) : 1 - d * sum
res = log1Exp(d + sum)
} else { /* x >= 1 and x fairly near shape. */
res = ppois_asymp(shape-1, x, true)
}
return res
}
// Abramowitz and Stegun 6.5.29 [right]
func pgamma_smallx_ln(x, shape float64) float64 {
var term, f2 float64
sum := 0.0
c := shape
n := 0.0
// Relative to 6.5.29 all terms have been multiplied by shape
// and the first, thus being 1, is omitted.
term = 1e32 // just to enter the while loop
for abs(term) > eps64*abs(sum) {
n++
c *= -x / n
term = c / (shape + n)
sum += term
}
f1 := log1p(sum)
if shape > 1 {
f2 = dpois_raw_ln(shape, x)
f2 = f2 + x
} else {
f2 = shape*log(x) - lgamma1p(shape)
}
return f1 + f2
}
func dpois_wrap_ln(x_plus_1, lambda float64) float64 {
if isInf(lambda, 0) {
return negInf
}
if x_plus_1 > 1 {
return dpois_raw_ln(x_plus_1-1, lambda)
}
if lambda > abs(x_plus_1-1)*M_cutoff {
return -lambda - lgammafn(x_plus_1)
}
d := dpois_raw_ln(x_plus_1, lambda)
return d + log(x_plus_1/lambda)
}
func dpois_raw_ln(x, lambda float64) float64 {
// x >= 0 ; integer for dpois(), but not e.g. for pgamma()!
// lambda >= 0
if lambda == 0 {
if x == 0 {
return 0
} else {
return negInf
}
}
if isInf(lambda, 0) {
return negInf
}
if x < 0 {
return negInf
}
if x <= lambda*min64 {
return -lambda
}
if lambda < x*min64 {
return -lambda + x*log(lambda) - lgammafn(x+1)
}
return -0.5*log((π+π)*x) + (-stirlerr(x) - bd0(x, lambda))
} | dst/gamma_aux_ln.go | 0.692954 | 0.625238 | gamma_aux_ln.go | starcoder |
package iso20022
// Chain of parties involved in the settlement of a transaction, including receipts and deliveries, book transfers, treasury deals, or other activities, resulting in the movement of a security or amount of money from one account to another.
type SettlementParties32 struct {
// First party in the settlement chain. In a plain vanilla settlement, it is the central securities depository where the counterparty requests to receive the financial instrument or from where the counterparty delivers the financial instruments.
Depository *PartyIdentification63 `xml:"Dpstry"`
// Party that, in a settlement chain, interacts with the depository. This may also be known as the “local agent”, “sub-custodian”, “receiving agent” or “delivering agent”.
Party1 *PartyIdentificationAndAccount95 `xml:"Pty1,omitempty"`
// Party that, in a settlement chain, interacts with party 1. This may also be known as the “investment manager” or “custodian”.
Party2 *PartyIdentificationAndAccount95 `xml:"Pty2,omitempty"`
// Party that, in a settlement chain, interacts with party 2.
Party3 *PartyIdentificationAndAccount95 `xml:"Pty3,omitempty"`
// Party that, in a settlement chain, interacts with party 3.
Party4 *PartyIdentificationAndAccount95 `xml:"Pty4,omitempty"`
// Party that, in a settlement chain, interacts with party 4.
Party5 *PartyIdentificationAndAccount95 `xml:"Pty5,omitempty"`
}
func (s *SettlementParties32) AddDepository() *PartyIdentification63 {
s.Depository = new(PartyIdentification63)
return s.Depository
}
func (s *SettlementParties32) AddParty1() *PartyIdentificationAndAccount95 {
s.Party1 = new(PartyIdentificationAndAccount95)
return s.Party1
}
func (s *SettlementParties32) AddParty2() *PartyIdentificationAndAccount95 {
s.Party2 = new(PartyIdentificationAndAccount95)
return s.Party2
}
func (s *SettlementParties32) AddParty3() *PartyIdentificationAndAccount95 {
s.Party3 = new(PartyIdentificationAndAccount95)
return s.Party3
}
func (s *SettlementParties32) AddParty4() *PartyIdentificationAndAccount95 {
s.Party4 = new(PartyIdentificationAndAccount95)
return s.Party4
}
func (s *SettlementParties32) AddParty5() *PartyIdentificationAndAccount95 {
s.Party5 = new(PartyIdentificationAndAccount95)
return s.Party5
} | SettlementParties32.go | 0.694199 | 0.518363 | SettlementParties32.go | starcoder |
package slice
// IncludesString func
// Returns true if the input contains the one or more of the values
func IncludesString(input []string, values ...string) bool {
for _, value := range values {
idx := IndexOfString(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesInt func
// Returns true if the input contains the one or more of the values
func IncludesInt(input []int, values ...int) bool {
for _, value := range values {
idx := IndexOfInt(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesInt8 func
// Returns true if the input contains the one or more of the values
func IncludesInt8(input []int8, values ...int8) bool {
for _, value := range values {
idx := IndexOfInt8(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesInt16 func
// Returns true if the input contains the one or more of the values
func IncludesInt16(input []int16, values ...int16) bool {
for _, value := range values {
idx := IndexOfInt16(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesInt32 func
// Returns true if the input contains the one or more of the values
func IncludesInt32(input []int32, values ...int32) bool {
for _, value := range values {
idx := IndexOfInt32(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesInt64 func
// Returns true if the input contains the one or more of the values
func IncludesInt64(input []int64, values ...int64) bool {
for _, value := range values {
idx := IndexOfInt64(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesUint func
// Returns true if the input contains the one or more of the values
func IncludesUint(input []uint, values ...uint) bool {
for _, value := range values {
idx := IndexOfUint(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesUint8 func
// Returns true if the input contains the one or more of the values
func IncludesUint8(input []uint8, values ...uint8) bool {
for _, value := range values {
idx := IndexOfUint8(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesUint16 func
// Returns true if the input contains the one or more of the values
func IncludesUint16(input []uint16, values ...uint16) bool {
for _, value := range values {
idx := IndexOfUint16(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesUint32 func
// Returns true if the input contains the one or more of the values
func IncludesUint32(input []uint32, values ...uint32) bool {
for _, value := range values {
idx := IndexOfUint32(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesFloat32 func
// Returns true if the input contains the one or more of the values
func IncludesFloat32(input []float32, values ...float32) bool {
for _, value := range values {
idx := IndexOfFloat32(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesFloat64 func
// Returns true if the input contains the one or more of the values
func IncludesFloat64(input []float64, values ...float64) bool {
for _, value := range values {
idx := IndexOfFloat64(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesComplex64 func
// Returns true if the input contains the one or more of the values
func IncludesComplex64(input []complex64, values ...complex64) bool {
for _, value := range values {
idx := IndexOfComplex64(value, input)
if idx > -1 {
return true
}
}
return false
}
// IncludesComplex128 func
// Returns true if the input contains the one or more of the values
func IncludesComplex128(input []complex128, values ...complex128) bool {
for _, value := range values {
idx := IndexOfComplex128(value, input)
if idx > -1 {
return true
}
}
return false
} | slice/includes.go | 0.823577 | 0.483039 | includes.go | starcoder |
package groups
import (
"math/big"
"fmt"
"github.com/xlab-si/emmy/crypto/common"
)
// QRRSA presents QR_N - group of quadratic residues modulo N where N is a product
// of two primes. This group is in general NOT cyclic (it is only when (P-1)/2 and (Q-1)/2 are primes,
// see QRSpecialRSA). The group QR_N is isomorphic to QR_P x QR_Q.
type QRRSA struct {
N *big.Int // N = P * Q
P *big.Int
Q *big.Int
Order *big.Int // Order = (P-1)/2 * (Q-1)/2
}
func NewQRRSA(P, Q *big.Int) (*QRRSA, error) {
if !P.ProbablyPrime(20) || !Q.ProbablyPrime(20) {
return nil, fmt.Errorf("P and Q must be primes")
}
pMin := new(big.Int).Sub(P, big.NewInt(1))
pMinHalf := new(big.Int).Div(pMin, big.NewInt(2))
qMin := new(big.Int).Sub(Q, big.NewInt(1))
qMinHalf := new(big.Int).Div(qMin, big.NewInt(2))
order := new(big.Int).Mul(pMinHalf, qMinHalf)
return &QRRSA{
N: new(big.Int).Mul(P, Q),
P: P,
Q: Q,
Order: order,
}, nil
}
func NewQRRSAPublic(N *big.Int) *QRRSA {
return &QRRSA{
N: N,
}
}
// Add computes x + y (mod N)
func (group *QRRSA) Add(x, y *big.Int) *big.Int {
r := new(big.Int)
r.Add(x, y)
return r.Mod(r, group.N)
}
// Mul computes x * y in QR_N. This means x * y mod N.
func (group *QRRSA) Mul(x, y *big.Int) *big.Int {
r := new(big.Int)
r.Mul(x, y)
return r.Mod(r, group.N)
}
// Inv computes inverse of x in QR_N. This means xInv such that x * xInv = 1 mod N.
func (group *QRRSA) Inv(x *big.Int) *big.Int {
return new(big.Int).ModInverse(x, group.N)
}
// Exp computes base^exponent in QR_N. This means base^exponent mod rsa.N.
func (group *QRRSA) Exp(base, exponent *big.Int) *big.Int {
expAbs := new(big.Int).Abs(exponent)
if expAbs.Cmp(exponent) == 0 {
return new(big.Int).Exp(base, exponent, group.N)
} else {
t := new(big.Int).Exp(base, expAbs, group.N)
return group.Inv(t)
}
}
// IsElementInGroup returns true if a is in QR_N and false otherwise.
func (group *QRRSA) IsElementInGroup(a *big.Int) (bool, error) {
if group.P == nil {
return false,
fmt.Errorf("IsElementInGroup not available for QRRSA with only public parameters")
}
factors := []*big.Int{group.P, group.Q}
for _, p := range factors {
isQR, err := common.IsQuadraticResidue(a, p)
if err != nil {
return false, err
}
if !isQR {
return false, nil
}
}
return true, nil
} | crypto/groups/qr_rsa.go | 0.760651 | 0.439326 | qr_rsa.go | starcoder |
package rbtree
// First returns the leftmost node in t, which is the first in-order node.
// If t is empty, it will return nil.
func (t *Tree) First() *Node {
if t.root == nil {
return nil
}
n := t.root
for n.left != nil {
n = n.left
}
return n
}
// Last returns the rightmost node in t, which is the last in-order node.
// If t is empty, it will return nil.
func (t *Tree) Last() *Node {
if t.root == nil {
return nil
}
n := t.root
for n.right != nil {
n = n.right
}
return n
}
// Next looks up the successor of n. If n is the last node, it returns nil.
func (t *Tree) Next(n *Node) *Node {
// right subtree is not empty
if n.right != nil {
x := n.right
for x.left != nil {
x = x.left
}
return x
}
// Right subtree is empty, backward to first non-right edge
x := n
for x.p != nil && x.p.right == x {
x = x.p
}
if x.p == nil {
return nil
}
return x.p
}
// Prev looks up the presuccessor of n. If n is the first node, it returns nil.
func (t *Tree) Prev(n *Node) *Node {
// Left subtree is not empty
if n.left != nil {
x := n.left
for x.right != nil {
x = x.right
}
return x
}
// Left subtree is empty, backward to first non-left edge
x := n
for x.p != nil && x.p.left == x {
x = x.p
}
if x.p == nil {
return nil
}
return x.p
}
// PostorderFirst looks up the first post-order node in t.
func (t *Tree) PostorderFirst() *Node {
if t.root == nil {
return nil
}
return t.PostorderFirstNode(t.root)
}
// PostorderNext looks up the post-order successor of n.
func (t *Tree) PostorderNext(n *Node) *Node {
if n.p != nil && n == n.p.left && n.p.right != nil {
x := n.p.right
return t.PostorderFirstNode(x)
}
if n.p == nil {
return nil
}
return n.p
}
// PostorderFirstNode looks up the first post-order node in subtree whose root is x. This node is the left-first deepest node.
func (t *Tree) PostorderFirstNode(x *Node) *Node {
for {
if x.left != nil {
x = x.left
} else if x.right != nil {
x = x.right
} else {
return x
}
}
}
// PreorderFirst returns the first pre-order node of t, which obviously is the root of t.
func (t *Tree) PreorderFirst() *Node { return t.root }
// PreorderNext returns the pre-order successor of x.
func (t *Tree) PreorderNext(x *Node) *Node {
if x.left != nil {
return x.left
} else if x.right != nil {
return x.right
}
for x.p != nil {
if x == x.p.left && x.p.right != nil {
return x.p.right
}
x = x.p
}
return nil
}
// PreorderLastNode looks up the last pre-order node in subtree whose root is x.
func (t *Tree) PreorderLastNode(x *Node) *Node {
for {
if x.right != nil {
x = x.right
} else if x.left != nil {
x = x.left
} else {
return x
}
}
} | rbtree/iter.go | 0.834407 | 0.538437 | iter.go | starcoder |
package assert
import (
"fmt"
"path/filepath"
"reflect"
"runtime"
"testing"
)
// Assert wraps a testing.TB for convenient asserting calls.
type Assert struct {
t testing.TB
}
// ObjectsAreEqual checks two interfaces with reflect.DeepEqual.
func ObjectsAreEqual(expected, actual interface{}) bool {
if expected == nil || actual == nil {
return expected == actual
}
return reflect.DeepEqual(expected, actual)
}
// IsNil checks an interface{} with the reflect package.
func IsNil(object interface{}) bool {
if object == nil {
return true
}
value := reflect.ValueOf(object)
kind := value.Kind()
if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
return true
}
return false
}
// errorSingle fails and prints the single object
// along with the message.
func errorSingle(t testing.TB, msg string, obj interface{}) {
//t.Errorf("%s: %v", msg, obj)
_, file, line, _ := runtime.Caller(2)
fmt.Printf("\033[31m\t%s:%d: %s\n\n\t\t%#v\033[39m\n\n", filepath.Base(file), line, msg, obj)
t.Fail()
}
// errorCompare fails and prints both the compared objects
// along with the message.
func errorCompare(t testing.TB, msg string, expected, actual interface{}) {
_, file, line, _ := runtime.Caller(2)
fmt.Printf("\033[31m\t%s:%d: %s\n\n\t\tgot: %#v\n\033[32m\t\texp: %#v\033[39m\n\n", filepath.Base(file), line, msg, actual, expected)
t.Fail()
}
func (a *Assert) True(cond bool, msg string) {
if !cond {
errorSingle(a.t, msg, cond)
}
}
func (a *Assert) Equal(expected, actual interface{}, msg string) {
if !ObjectsAreEqual(expected, actual) {
errorCompare(a.t, msg, expected, actual)
}
}
func (a *Assert) NotEqual(expected, actual interface{}, msg string) {
if ObjectsAreEqual(expected, actual) {
errorCompare(a.t, msg, expected, actual)
}
}
func (a *Assert) NoError(err error, msg string) {
if err != nil {
errorSingle(a.t, msg, err)
}
}
func (a *Assert) Nil(obj interface{}, msg string) {
if !IsNil(obj) {
errorSingle(a.t, msg, obj)
}
}
func (a *Assert) NotNil(obj interface{}, msg string) {
if IsNil(obj) {
errorSingle(a.t, msg, obj)
}
}
// NewAssert provides an Assert instance.
func NewAssert(t testing.TB) *Assert {
return &Assert{t}
} | assert/assert.go | 0.719186 | 0.469642 | assert.go | starcoder |
package model
import (
"github.com/bdlm/errors"
"github.com/bdlm/std"
)
/*
Cur implements std.Iterator.
Cur reads the key and value at the current cursor postion into pK and pV
respectively. Cur will return false if no iteration has begun, including
following calls to Reset.
*/
func (mdl *Model) Cur(pK, pV *interface{}) bool {
if mdl.pos < 0 || mdl.pos >= len(mdl.data) {
return false
}
*pK = mdl.pos
if std.ModelTypeHash == mdl.GetType() {
*pK = mdl.idxHash[mdl.pos]
}
if tmp, ok := mdl.data[mdl.pos].(*Value); ok && nil != tmp {
*pV = tmp
} else {
*pV = &Value{mdl.data[mdl.pos]}
}
return true
}
/*
Next implements std.Iterator.
Next moves the cursor forward one position before reading the key and value
at the cursor position into pK and pV respectively. If data is available at
that position and was written to pK and pV then Next returns true, else
false to signify the end of the data and resets the cursor postion to the
beginning of the data set (-1).
*/
func (mdl *Model) Next(pK, pV *interface{}) bool {
mdl.mux.Lock()
mdl.pos++
// at the end of the data, reset.
if len(mdl.data) <= mdl.pos {
mdl.pos = -1
mdl.mux.Unlock()
return false
}
*pK = mdl.pos
if std.ModelTypeHash == mdl.GetType() {
*pK = mdl.idxHash[mdl.pos]
}
if tmp, ok := mdl.data[mdl.pos].(*Value); ok && nil != tmp {
*pV = tmp
} else {
*pV = &Value{mdl.data[mdl.pos]}
}
mdl.mux.Unlock()
return true
}
/*
Prev implements std.Iterator.
Prev moves the cursor backward one position before reading the key and value
at the cursor position into pK and pV respectively. If data is available at
that position and was written to pK and pV then Prev returns true, else
false to signify the beginning of the data.
*/
func (mdl *Model) Prev(pK, pV *interface{}) bool {
mdl.mux.Lock()
mdl.pos--
// at the beginning of the data, stop.
if mdl.pos < 0 {
mdl.mux.Unlock()
return false
}
*pK = mdl.pos
if std.ModelTypeHash == mdl.GetType() {
*pK = mdl.idxHash[mdl.pos]
}
if tmp, ok := mdl.data[mdl.pos].(*Value); ok && nil != tmp {
*pV = tmp
} else {
*pV = &Value{mdl.data[mdl.pos]}
}
mdl.mux.Unlock()
return true
}
/*
Reset implements std.Iterator.
Reset sets the iterator cursor position.
*/
func (mdl *Model) Reset() {
mdl.pos = -1
}
/*
Seek implements std.Iterator.
Seek sets the iterator cursor position.
*/
func (mdl *Model) Seek(pos interface{}) error {
// List model
if std.ModelTypeList == mdl.GetType() {
idx := pos.(int)
if idx >= len(mdl.data) {
return errors.New(InvalidIndex, "the specified position '%d' is beyond the end of the data", idx)
} else if idx < 0 {
return errors.New(InvalidIndex, "invalid index '%d'", idx)
}
mdl.pos = idx - 1
return nil
}
// Hash model
hashKey := pos.(string)
if idx, ok := mdl.hashIdx[hashKey]; ok {
mdl.pos = idx - 1
}
return errors.New(InvalidIndex, "the specified position '%s' does not exist", hashKey)
} | model.iterator.go | 0.583559 | 0.518546 | model.iterator.go | starcoder |
package filter
import "github.com/nerdynick/ccloud-go-sdk/telemetry/labels"
type Filter interface {
And(filters ...Filter) CompoundFilter
AndEqualTo(field labels.Label, value string) CompoundFilter
AndNotEqualTo(field labels.Label, value string) CompoundFilter
AndGreaterThan(field labels.Label, value string) CompoundFilter
AndNotGreaterThan(field labels.Label, value string) CompoundFilter
AndGreaterThanOrEqualTo(field labels.Label, value string) CompoundFilter
AndNotGreaterThanOrEqualTo(field labels.Label, value string) CompoundFilter
Or(filters ...Filter) CompoundFilter
OrEqualTo(field labels.Label, value string) CompoundFilter
OrNotEqualTo(field labels.Label, value string) CompoundFilter
OrGreaterThan(field labels.Label, value string) CompoundFilter
OrNotGreaterThan(field labels.Label, value string) CompoundFilter
OrGreaterThanOrEqualTo(field labels.Label, value string) CompoundFilter
OrNotGreaterThanOrEqualTo(field labels.Label, value string) CompoundFilter
}
func NotAnyOf(filters ...Filter) UnaryFilter {
return Not(Or(filters...))
}
func AnyOf(filters ...Filter) CompoundFilter {
return Or(filters...)
}
func OneOf(filters ...Filter) CompoundFilter {
return Or(filters...)
}
func Or(filters ...Filter) CompoundFilter {
return CompoundFilter{
Op: OpOr,
Filters: filters,
}
}
func AllOf(filters ...Filter) CompoundFilter {
return And(filters...)
}
func And(filters ...Filter) CompoundFilter {
return CompoundFilter{
Op: OpAnd,
Filters: filters,
}
}
func Not(filter Filter) UnaryFilter {
return UnaryFilter{
Op: OpNot,
SubFilter: filter,
}
}
func NotEqualTo(field labels.Label, value string) UnaryFilter {
return Not(EqualTo(field, value))
}
func EqualTo(field labels.Label, value string) FieldFilter {
return FieldFilter{
Op: OpEq,
Field: field,
Value: value,
}
}
func NotGreaterThan(field labels.Label, value string) UnaryFilter {
return Not(GreaterThan(field, value))
}
func GreaterThan(field labels.Label, value string) FieldFilter {
return FieldFilter{
Op: OpGt,
Field: field,
Value: value,
}
}
func NotGreaterThanOrEqualTo(field labels.Label, value string) UnaryFilter {
return Not(GreaterThanOrEqualTo(field, value))
}
func GreaterThanOrEqualTo(field labels.Label, value string) FieldFilter {
return FieldFilter{
Op: OpGte,
Field: field,
Value: value,
}
} | telemetry/query/filter/filter.go | 0.779532 | 0.637835 | filter.go | starcoder |
package lookup
import "fmt"
// Lookup ...
func Lookup(sortedDict []string, target string) (bool, error) {
if 0 == len(sortedDict) {
return false, fmt.Errorf("dict can not be empty")
}
if 0 == len(target) {
return false, fmt.Errorf("target can not be empty")
}
left, right := 0, len(sortedDict)-1
for left <= right {
middle := left + (right-left)>>1
if target == sortedDict[middle] {
return true, nil
} else if target > sortedDict[middle] {
left = middle + 1
} else {
right = middle - 1
}
}
return false, fmt.Errorf("can no find target:%q in dict", target)
}
// Lookup1 ...
func Lookup1(sortedDict []string, target string, left, right int) bool {
if left > right {
return false
}
middle := left + (right-left)>>1
if target == sortedDict[middle] {
return true
} else if target > sortedDict[middle] {
return Lookup1(sortedDict, target, middle+1, right)
} else {
return Lookup1(sortedDict, target, left, middle-1)
}
}
// Bsearch lookup the first value in the a, return the index of target
func Bsearch(a []int, value int) int {
low := 0
high := len(a) - 1
for low <= high {
mid := low + ((high - low) >> 1)
if a[mid] > value {
high = mid - 1
} else if a[mid] < value {
low = mid + 1
} else {
if mid == 0 || a[mid-1] != value {
return mid
}
high = mid - 1
}
}
return -1
}
// bsearch1 lookup the last value is equal to value in the a, return the index of target
func bsearch1(a []int, value int) int {
length := len(a)
low, high := 0, length-1
for low <= high {
mid := low + (high-low)>>1
if value == a[mid] {
if mid == length-1 || a[mid+1] != value {
return mid
}
low = mid + 1
} else if value > a[mid] {
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}
// bsearch2 lookup the first value which is equal or greater than target in the a, return the index of target
func bsearch2(a []int, value int) int {
length := len(a)
low, high := 0, length-1
for low <= high {
mid := low + ((high - low) >> 1)
if value <= a[mid] {
if mid == 0 || a[mid-1] < value {
return mid
}
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// bsearch3 lookup the last value which is equal or less than target in the a, return the index of target
func bsearch3(a []int, value int) int {
length := len(a)
low, high := 0, length-1
for low <= high {
mid := low + (high-low)>>1
if a[mid] <= value {
if mid == length-1 || a[mid+1] > value {
return mid
}
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}
// bsearch4 lookup the specified value in the circular array, return the index of target
func bsearch4(a []int, value int) int {
length := len(a)
low, high := 0, length-1
for low <= high {
mid := low + (high-low)>>1
if value == a[mid] {
return mid
}
// a[low:mid+1] is ordered
if a[low] <= a[mid] {
// value is in ordered area
if a[low] <= value && value < a[mid] {
high = mid - 1
} else {
low = mid + 1
}
} else { // a[mid:high+1] is ordered
// value is in ordered area
if a[mid] < value && value <= a[high] {
low = mid + 1
} else {
high = mid - 1
}
}
}
return -1
}
// bsearch5 lookup the first value which is greater than value in the a, return the index of value
func bsearch5(a []int, value int) int {
length := len(a)
low, high := 0, length-1
for low <= high {
mid := low + ((high - low) >> 1)
if value >= a[mid] {
if mid == length-1 {
return -1
}
if a[mid+1] > value {
return mid + 1
}
low = mid + 1
} else {
if 0 == mid || a[mid-1] < value {
return mid
}
high = mid - 1
}
}
return -1
} | pkg/dichotomy/lookup/lookup.go | 0.712732 | 0.574872 | lookup.go | starcoder |
package main
import (
"fmt"
"sync"
)
/*
We can change our pipeline to run two instances of `sq`, each reading from the same input
channel. We introduce a new function, merge, to fan in the results:
*/
func main() {
in := gen(2, 3)
// Distribute the `sq` work across 2 goroutines that both read from `in`:
c1 := sq(in)
c2 := sq(in)
// Consume the merged output from `c1` and `c2`:
for n := range merge(c1, c2) {
fmt.Println(n)
}
}
/*
The `merge` function converts a list of channels to a single channel by starting a goroutine for
each inbound channel that copies the values to the sole outbound channel. Once all the output
goroutines have been started, `merge` starts one more goroutine to close the outbound channel
after all sends on that channel are done.
Sends on a closed channel panic! Therefore it’s important to ensure all sends are done before
calling `close`. The `sync.WaitGroup` type provides a simple way to arrange this synchronization:
*/
func merge(cs ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan int)
/* Start an output goroutine for each input channel in `cs`
`output` copies values from `c` to `out` until `c` is closed,
then calls `wg.Done`: */
output := func(c <-chan int) {
for n := range c {
out <- n
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
/* Start a goroutine to close out once all the output goroutines are done.
This must start after the `wg.Add` call: */
go func() {
wg.Wait()
close(out)
}()
return out
}
/* FROM: ../square-numbers/main.go */
/*
The first stage, `gen`, is a function that converts a list of integers to a channel that emits the
integers in the list. The `gen` function starts a goroutine that sends the integers on the channel
and closes the channel when all the values have been sent:
*/
func gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}
/*
The second stage, `sq`, receives integers from a channel and returns a channel that emits the square
of each received integer. After the inbound channel is closed and this stage has sent all the values
downstream, it closes the outbound channel:
*/
func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
} | go/pipelines-and-cancellations/pipeline/fan-out-fan-in/main.go | 0.697815 | 0.480357 | main.go | starcoder |
package dotplotter
import (
"image"
"image/color"
"image/draw"
"image/png"
"os"
"path/filepath"
)
// DefaultColor exports default RGB values for common colors.
func DefaultColor(c string) color.RGBA {
m := map[string]color.RGBA{
"white": color.RGBA{255, 255, 255, 255},
"black": color.RGBA{0, 0, 0, 255},
"red": color.RGBA{255, 0, 0, 255},
"orange": color.RGBA{255, 128, 0, 255},
"yellow": color.RGBA{255, 255, 0, 255},
"green": color.RGBA{0, 192, 0, 255},
"blue": color.RGBA{0, 0, 255, 255},
"purple": color.RGBA{128, 0, 255, 255},
}
r, ok := m[c]
if !ok {
return color.RGBA{}
}
return r
}
// modelRectangle holds the corners of a canvas in model-space.
type modelRectangle struct {
tl, br [2]float64
}
// canvas holds an image reference, a description of the model space, and constants to scale between pixel- and model-space.
type canvas struct {
img *image.RGBA
modelRect modelRectangle
xscale, yscale float64
}
// NewCanvas generates a canvas and calculates constants to scale between pixel- and model-space.
func NewCanvas(w, h int, xmin, xmax, ymin, ymax float64) canvas {
m := image.NewRGBA(image.Rect(0, 0, w, h))
draw.Draw(m, m.Bounds(), &image.Uniform{DefaultColor("white")}, image.ZP, draw.Src)
mr := modelRectangle{[2]float64{xmin, ymin}, [2]float64{xmax, ymax}}
xrange := xmax - xmin
yrange := ymax - ymin
xscale := float64(w) / xrange
yscale := float64(h) / yrange
return canvas{m, mr, xscale, yscale}
}
// ExportToPNG writes a canvas to file.
func (C *canvas) ExportToPNG(filename string) {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
fn := filepath.Join(wd, filename)
f, err := os.Create(fn)
if err != nil {
panic(err)
}
defer f.Close()
err = png.Encode(f, C.img)
if err != nil {
panic(err)
}
}
// DrawCircleAt draws a circle on a canvas. x/y are in model-space, r is in pixel-space.
func (C *canvas) DrawCircleAt(x, y float64, r int, fillColor color.RGBA) {
X, Y := int((x-C.modelRect.tl[0])*C.xscale), int((y-C.modelRect.tl[1])*C.yscale)
c := circle{image.Point{X, C.img.Bounds().Max.Y - Y}, r}
draw.DrawMask(C.img, C.img.Bounds(), &image.Uniform{fillColor}, image.ZP, &c, image.ZP, draw.Over)
}
// Circle logic from the Go blog:
// https://blog.golang.org/go-imagedraw-package
type circle struct {
o image.Point
r int
}
func (c *circle) ColorModel() color.Model {
return color.AlphaModel
}
func (c *circle) Bounds() image.Rectangle {
return image.Rect(c.o.X-c.r, c.o.Y-c.r, c.o.X+c.r, c.o.Y+c.r)
}
func (c *circle) At(x, y int) color.Color {
xx, yy, rr := float64(x-c.o.X)+0.5, float64(y-c.o.Y)+0.5, float64(c.r)
if xx*xx+yy*yy < rr*rr {
return color.Alpha{255}
}
return color.Alpha{0}
} | dotplotter.go | 0.795975 | 0.480296 | dotplotter.go | starcoder |
package widgets
import (
"fmt"
"github.com/ricoberger/kubetop/pkg/api"
ui "github.com/gizak/termui/v3"
w "github.com/gizak/termui/v3/widgets"
)
// ListType is our custom type for the different list types (e.g. sort and filter)
type ListType string
const (
// ListTypeSort represents the the sorting list.
ListTypeSort ListType = "Sort by ..."
// ListTypeFilterNamespace represents the namespace filter.
ListTypeFilterNamespace ListType = "Filter by Namespace ..."
// ListTypeFilterNode represents the node filter.
ListTypeFilterNode ListType = "Filter by Node ..."
// ListTypeFilterStatus represents the status filter.
ListTypeFilterStatus ListType = "Filter by Status ..."
// ListTypeFilterEventType represents the event type filter.
ListTypeFilterEventType ListType = "Filter by Event Type ..."
// ListTypeView represents the list for switching to an other view.
ListTypeView = "Select View ..."
)
// ListWidget represents the ui widget component for a list.
type ListWidget struct {
*w.List
apiClient *api.Client
filterNamespaces []string
filterNodes []string
filterStatuses []string
filterEventTypes []string
sortNodes []api.Sort
sortPods []api.Sort
sortEvents []api.Sort
views []ViewType
}
// NewListWidget returns a new list widget.
func NewListWidget(apiClient *api.Client) *ListWidget {
list := w.NewList()
list.TextStyle = ui.NewStyle(ui.ColorYellow)
list.WrapText = false
return &ListWidget{
list,
apiClient,
[]string{},
[]string{},
[]string{"-", "Running", "Waiting", "Terminated"},
[]string{"-", "Normal", "Warning"},
[]api.Sort{api.SortCPUASC, api.SortCPUDESC, api.SortMemoryASC, api.SortMemoryDESC, api.SortName, api.SortPodsASC, api.SortPodsDESC},
[]api.Sort{api.SortCPUASC, api.SortCPUDESC, api.SortMemoryASC, api.SortMemoryDESC, api.SortName, api.SortNamespace, api.SortRestartsASC, api.SortRestartsDESC, api.SortStatus},
[]api.Sort{api.SortName, api.SortNamespace, api.SortTimeASC, api.SortTimeDESC},
[]ViewType{ViewTypePods, ViewTypeNodes, ViewTypeEvents},
}
}
// Hide hides the list.
func (l *ListWidget) Hide() {
l.SetRect(0, 0, 0, 0)
}
// Selected determines the selected sortorder or filter.
func (l *ListWidget) Selected(viewType ViewType, listType ListType, sortorder api.Sort, filter api.Filter) (ViewType, api.Sort, api.Filter) {
if viewType == ViewTypeNodes {
if listType == ListTypeSort {
sortorder = l.sortNodes[l.SelectedRow]
}
} else if viewType == ViewTypePods {
if listType == ListTypeSort {
sortorder = l.sortPods[l.SelectedRow]
} else if listType == ListTypeFilterNamespace {
if l.filterNamespaces[l.SelectedRow] == "-" {
filter.Namespace = ""
} else {
filter.Namespace = l.filterNamespaces[l.SelectedRow]
}
} else if listType == ListTypeFilterNode {
if l.filterNodes[l.SelectedRow] == "-" {
filter.Node = ""
} else {
filter.Node = l.filterNodes[l.SelectedRow]
}
} else if listType == ListTypeFilterStatus {
switch l.filterStatuses[l.SelectedRow] {
case "-":
filter.Status = 10
case "Running":
filter.Status = 2
case "Waiting":
filter.Status = 1
case "Terminated":
filter.Status = 0
}
}
} else if viewType == ViewTypeEvents {
if listType == ListTypeSort {
sortorder = l.sortEvents[l.SelectedRow]
} else if listType == ListTypeFilterNamespace {
if l.filterNamespaces[l.SelectedRow] == "-" {
filter.Namespace = ""
} else {
filter.Namespace = l.filterNamespaces[l.SelectedRow]
}
} else if listType == ListTypeFilterNode {
if l.filterNodes[l.SelectedRow] == "-" {
filter.Node = ""
} else {
filter.Node = l.filterNodes[l.SelectedRow]
}
} else if listType == ListTypeFilterEventType {
if l.filterEventTypes[l.SelectedRow] == "-" {
filter.EventType = ""
} else {
filter.EventType = l.filterEventTypes[l.SelectedRow]
}
}
}
if listType == ListTypeView {
viewType = l.views[l.SelectedRow]
}
l.SetRect(0, 0, 0, 0)
return viewType, sortorder, filter
}
// Show shows a list with the specified sort options or filters.
func (l *ListWidget) Show(viewType ViewType, listType ListType, termWidth, termHeight int) bool {
var showList bool
l.Title = string(listType)
l.Rows = []string{}
if viewType == ViewTypeNodes {
// For the node view we only render the sort list.
if listType == ListTypeSort {
showList = true
for index, item := range l.sortNodes {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, item))
}
}
} else if viewType == ViewTypePods {
// For the pods view we render the sort list and the filters for namespace, node and status.
// The namespaces and nodes are selected from the Kubernetes API first.
if listType == ListTypeSort {
showList = true
for index, item := range l.sortPods {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, item))
}
} else if listType == ListTypeFilterNamespace {
showList = true
l.filterNamespaces, _ = l.apiClient.GetNamespaces()
for index, namespace := range l.filterNamespaces {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, namespace))
}
} else if listType == ListTypeFilterNode {
showList = true
l.filterNodes, _ = l.apiClient.GetNodes()
for index, node := range l.filterNodes {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, node))
}
} else if listType == ListTypeFilterStatus {
showList = true
for index, status := range l.filterStatuses {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, status))
}
}
} else if viewType == ViewTypeEvents {
// For the events view we render the sort list and the filters for namespace, node and event type.
// The namespaces and nodes are selected from the Kubernetes API first.
if listType == ListTypeSort {
showList = true
for index, item := range l.sortEvents {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, item))
}
} else if listType == ListTypeFilterNamespace {
showList = true
l.filterNamespaces, _ = l.apiClient.GetNamespaces()
for index, namespace := range l.filterNamespaces {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, namespace))
}
} else if listType == ListTypeFilterNode {
showList = true
l.filterNodes, _ = l.apiClient.GetNodes()
for index, node := range l.filterNodes {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, node))
}
} else if listType == ListTypeFilterEventType {
showList = true
for index, eventType := range l.filterEventTypes {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, eventType))
}
}
}
if listType == ListTypeView {
showList = true
for index, viewType := range l.views {
l.Rows = append(l.Rows, fmt.Sprintf("[%d] %s", index, viewType))
}
}
if showList {
l.SelectedRow = 0
l.SetRect(termWidth/2-25, termHeight/2-10, termWidth/2+25, termHeight/2+10)
} else {
l.SetRect(0, 0, 0, 0)
}
return showList
} | pkg/term/widgets/list.go | 0.588653 | 0.484319 | list.go | starcoder |
package ch
const (
Infinity = float64(^uint(0) >> 1)
// Infinity = Infinity
)
// shortestPathsWithMaxCost Internal implementation of Dijkstra's algorithm to compute witness paths
func (graph *Graph) shortestPathsWithMaxCost(source int64, maxcost float64, previousOrderPos int64) {
// Heap to store traveled distance
pqComparator := &distanceHeap{}
pqComparator.Push(graph.Vertices[source])
// Instead of inializing distances to Infinity every single shortestPathsWithMaxCost(...) call we can do following
// Set dist[source] -> 0 (as usual)
graph.Vertices[source].distance.distance = 0
// Set order position to previously contracted (excluded from graph) vertex
graph.Vertices[source].distance.previousOrderPos = previousOrderPos
// Set source to identifier of vertex for which shortestPathsWithMaxCost(...) has been called
graph.Vertices[source].distance.previousSourceID = source
for pqComparator.Len() != 0 {
vertex := pqComparator.Pop()
// Do not consider any vertex has been excluded earlier
if vertex.contracted {
continue
}
// Once a vertex is settled with a shortest path score greater than max cost, search stops.
if vertex.distance.distance > maxcost {
return
}
// Edge relaxation
vertexList := vertex.outIncidentEdges
for i := range vertexList {
temp := vertexList[i].vertexID
cost := vertexList[i].weight
tempPtr := graph.Vertices[temp]
// Do not consider any vertex has been excluded earlier
if tempPtr.contracted {
continue
}
alt := vertex.distance.distance + cost
if tempPtr.distance.distance > alt || // usual condition for Dijkstra's algorithm
vertex.distance.previousOrderPos != tempPtr.distance.previousOrderPos || // Optional condition: if previous shortestPathsWithMaxCost(...) call has changed shortest path tree
vertex.distance.previousSourceID != tempPtr.distance.previousSourceID { // Optional condition: if previous shortestPathsWithMaxCost(...) call has changed shortest path tree
// Update new shortest distance
tempPtr.distance.distance = vertex.distance.distance + cost
tempPtr.distance.previousOrderPos = previousOrderPos
tempPtr.distance.previousSourceID = source
pqComparator.Push(tempPtr)
}
}
}
} | dijkstra_local.go | 0.649801 | 0.470189 | dijkstra_local.go | starcoder |
package kzg
import (
"go.dedis.ch/kyber/v3"
)
// Commit commits to vector vect[0], ...., vect[D-1]
// it is [f(s)]1 where f is polynomial in evaluation (Lagrange) form,
// i.e. with f(rou[i]) = vect[i], i = 0..D-1
// vect[k] == nil equivalent to 0
func (sd *TrustedSetup) Commit(vect []kyber.Scalar) kyber.Point {
ret := sd.Suite.G1().Point().Null()
elem := sd.Suite.G1().Point()
for i, e := range vect {
if e == nil {
continue
}
elem.Mul(e, sd.LagrangeBasis[i])
ret.Add(ret, elem)
}
return ret
}
// Prove returns pi = [(f(s)-vect<index>)/(s-rou<index>)]1
// This is the proof sent to verifier
func (sd *TrustedSetup) Prove(vect []kyber.Scalar, i int) kyber.Point {
ret := sd.Suite.G1().Point().Null()
e := sd.Suite.G1().Point()
qij := sd.Suite.G1().Scalar()
for j := range sd.Domain {
sd.qPoly(vect, i, j, vect[i], qij)
e.Mul(qij, sd.LagrangeBasis[j])
ret.Add(ret, e)
}
return ret
}
func (sd *TrustedSetup) qPoly(vect []kyber.Scalar, i, m int, y kyber.Scalar, ret kyber.Scalar) {
numer := sd.Suite.G1().Scalar()
if i != m {
sd.diff(vect[m], y, numer)
if numer.Equal(sd.ZeroG1) {
ret.Zero()
return
}
ret.Mul(numer, sd.invsub(m, i))
return
}
// i == m
ret.Zero()
t := sd.Suite.G1().Scalar()
t1 := sd.Suite.G1().Scalar()
for j := range vect {
if j == m || vect[j] == nil {
continue
}
t.Mul(vect[j], sd.ta(m, j, t1))
ret.Add(ret, t)
}
if vect[m] != nil {
t.Mul(vect[m], sd.tk(m, t1))
ret.Sub(ret, t)
}
}
func (sd *TrustedSetup) diff(vi, vj kyber.Scalar, ret kyber.Scalar) {
switch {
case vi == nil && vj == nil:
ret.Zero()
return
case vi != nil && vj == nil:
ret.Set(vi)
case vi == nil && vj != nil:
ret.Neg(vj)
default:
ret.Sub(vi, vj)
}
}
// Verify verifies KZG proof that polynomial f committed with C has f(rou<atIndex>) = v
// c is commitment to the polynomial
// pi is commitment to the value point (proof)
// value is the value of the polynomial
// adIndex is index of the root of unity where polynomial is expected to have value = v
func (sd *TrustedSetup) Verify(c, pi kyber.Point, v kyber.Scalar, atIndex int) bool {
p1 := sd.Suite.Pair(pi, sd.Diff2[atIndex])
e := sd.Suite.G1().Point().Mul(v, nil)
e.Sub(c, e)
p2 := sd.Suite.Pair(e, sd.Suite.G2().Point().Base())
return p1.Equal(p2)
}
// VerifyVector calculates proofs and verifies all elements in the vector against commitment C
func (sd *TrustedSetup) VerifyVector(vect []kyber.Scalar, c kyber.Point) bool {
pi := make([]kyber.Point, sd.D)
for i := range vect {
pi[i] = sd.Prove(vect, i)
}
for i := range pi {
v := vect[i]
if v == nil {
v = sd.ZeroG1
}
if !sd.Verify(c, pi[i], v, i) {
return false
}
}
return true
}
// CommitAll return commit to the whole vector and to each of values of it
// Generate commitment to the vector and proofs to all values.
// Expensive. Usually used only in tests
func (sd *TrustedSetup) CommitAll(vect []kyber.Scalar) (kyber.Point, []kyber.Point) {
retC := sd.Commit(vect)
retPi := make([]kyber.Point, sd.D)
for i := range vect {
if vect[i] == nil {
continue
}
retPi[i] = sd.Prove(vect, i)
}
return retC, retPi
} | kzg/fun.go | 0.549399 | 0.420719 | fun.go | starcoder |
package main
import (
"math"
"math/rand"
"time"
)
type Point struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
type Vector struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
func MakePoint(x float64, y float64) *Point {
return &Point{RoundToPlaces(x, 1), RoundToPlaces(y, 1)}
}
func Round(f float64) float64 {
return math.Floor(f + 0.5)
}
func RoundToPlaces(f float64, places int) float64 {
shift := math.Pow(10, float64(places))
return Round(f*shift) / shift
}
func RoundPoint(p *Point) *Point {
return &Point{RoundToPlaces(p.X, 1), RoundToPlaces(p.Y, 1)}
}
func RoundVector(v *Vector) *Vector {
return &Vector{RoundToPlaces(v.X, 1), RoundToPlaces(v.Y, 1)}
}
// Converts an angle in degrees between 0 and 359.
func AngleToVector(angle float64) *Vector {
// Convert to radians.
r := angle * 0.01745
return UnitVector(&Vector{X: math.Sin(r), Y: -math.Cos(r)})
}
func AngleAndSpeedToVector(angle float64, speed float64) *Vector {
return MultiplyVector(AngleToVector(angle), speed)
}
func Magnitude(vector *Vector) float64 {
return math.Sqrt(vector.X*vector.X + vector.Y*vector.Y)
}
func UnitVector(vector *Vector) *Vector {
return &Vector{
X: (vector.X / Magnitude(vector)),
Y: (vector.Y / Magnitude(vector)),
}
}
func MultiplyVector(vector *Vector, f float64) *Vector {
return &Vector{
X: vector.X * f,
Y: vector.Y * f,
}
}
func AddVectors(vector1 *Vector, vector2 *Vector) *Vector {
return &Vector{
X: vector1.X + vector2.X,
Y: vector1.Y + vector2.Y,
}
}
func AddVectorToPoint(vector *Vector, point *Point) *Point {
return &Point{
X: point.X + vector.X,
Y: point.Y + vector.Y,
}
}
func MakeTimestamp() uint64 {
return uint64(time.Now().UnixNano() / int64(time.Millisecond))
}
func Random(min int, max int) int {
d := max - min + 1
return min + rand.Intn(d)
}
func RandomFloat(min float64, max float64) float64 {
d := max - min + 1
return min + rand.Float64()*d
}
func RandomAngle() float64 {
return float64(Random(0, 359))
}
func DistanceBetweenPoints(p1 *Point, p2 *Point) float64 {
dx := p1.X - p2.X
dy := p1.Y - p2.Y
return math.Sqrt(float64(dx*dx + dy*dy))
}
func CalculateCenter(points []*Point) *Point {
var sx float64 = 0
var sy float64 = 0
for _, p := range points {
sx += p.X
sy += p.Y
}
return &Point{
X: sx / float64(len(points)),
Y: sy / float64(len(points)),
}
}
func IsColliding(p1 *Point, r1 float64, p2 *Point, r2 float64) bool {
return DistanceBetweenPoints(p1, p2) < (r1 + r2)
} | hyperspace-app/server/maths.go | 0.891702 | 0.801897 | maths.go | starcoder |
package coords64
import (
"fmt"
"gotopo/geom"
)
type coords64 struct {
data []float64
dimensions uint8
}
var _ geom.ReadWriteCoords = NewCoords64() // Verify that *coords64 implements ReadWriteCoords
func NewCoords64() geom.ReadWriteCoords {
return NewCoords64WithDimensions(geom.DEFAULT_NUM_DIMENSIONS)
}
func NewCoords64WithCapacity(capacity uint32) geom.ReadWriteCoords {
return NewCoords64WithCapacityAndDimensions(capacity, geom.DEFAULT_NUM_DIMENSIONS)
}
func NewCoords64WithDimensions(dimensions uint8) geom.ReadWriteCoords {
return NewCoords64WithCapacityAndDimensions(0, dimensions)
}
func NewCoords64WithCapacityAndDimensions(capacity uint32, dimensions uint8) geom.ReadWriteCoords {
sliceCapacity := capacity * uint32(dimensions)
if sliceCapacity < uint32(dimensions) {
return &coords64{
data:[]float64{},
dimensions:dimensions}
} else {
return &coords64{
data:make([]float64, 0, sliceCapacity),
dimensions:dimensions}
}
}
func NewCoords64FromSlice(dimensions uint8, data []float64) geom.ReadWriteCoords {
if len(data) % int(dimensions) != 0 {
panic(fmt.Sprintf("The number of eleements in the data array must be divisible by the number of dimensions." +
" Array size '%d'. Dimensions: '%d'", len(data), dimensions))
}
return &coords64{
data:data,
dimensions:dimensions}
}
func (this coords64) NumDim() uint8 {
return this.dimensions
}
func (this coords64) NumCoords() uint32 {
return uint32(len(this.data)) / uint32(this.dimensions)
}
func (this coords64) IsEmpty() bool {
return len(this.data) == 0
}
func (this coords64) Get(coordIdx uint32) geom.Point {
if coordIdx >= this.NumCoords() {
panic(fmt.Sprintf("Out of bounds error: There are only %d coordinates, attempted to access %d", this.NumCoords(), coordIdx))
}
return point64{this, coordIdx * uint32(this.dimensions)}
}
func (this *coords64) Set(coordIdx uint32, newValue geom.Point) {
if newValue.NumDim() != this.dimensions {
panic(fmt.Sprintf("Number of dimensions in coordinate(%d) do not match those in this coords object (%d)",
newValue.NumDim(), this.dimensions))
}
setIdx := coordIdx * uint32(this.dimensions)
if setIdx > uint32(len(this.data)) - uint32(this.dimensions) {
panic(fmt.Sprintf("Insert index is out of bounds. Legal bounds are: 0 -> %d but was %d", this.NumCoords(), coordIdx))
}
for i := uint8(0); i < newValue.NumDim(); i++ {
this.data[setIdx + uint32(i)] = newValue.Ord(i)
}
}
func (this *coords64) Add(newValue geom.Point) {
if newValue.NumDim() != this.dimensions {
panic(fmt.Sprintf("Number of dimensions in coordinate(%d) do not match those in this coords object (%d)",
newValue.NumDim(), this.dimensions))
}
this.data = append(this.data, newValue.ToArray()...)
}
func (this *coords64) Insert(idx uint32, newValue geom.Point) {
this.InsertRaw(idx, newValue.ToArray())
}
func (this *coords64) InsertRaw(idx uint32, ordinals []float64) {
mod := len(ordinals) % int(this.dimensions)
if mod != 0 {
panic(fmt.Sprintf("The number of ordinals provided for insert must be exactly divisible by the number of " +
"dimensions but ordinals: %d is not divisible by %d, there is a remainder of: %d", len(ordinals), this.dimensions, mod))
}
insertIdx := idx * uint32(this.dimensions)
if insertIdx > uint32(len(this.data)) {
panic(fmt.Sprintf("Insert index is out of bounds. Legal bounds are: 0 -> %d but was %d", this.NumCoords(), idx))
}
this.data = append(this.data, ordinals...)
copy(this.data[insertIdx + uint32(this.dimensions):], this.data[insertIdx:])
for i, o := range ordinals {
this.data[insertIdx + uint32(i)] = o
}
}
func (this coords64) Factory() geom.CoordsFactory {
return CoordsFactory64{this.dimensions}
} | src/gotopo/geom/coords64/coords64.go | 0.71403 | 0.514583 | coords64.go | starcoder |
package circuit
import (
"gkr-mimc/common"
"gkr-mimc/polynomial"
"sync"
"github.com/consensys/gurvy/bn256/fr"
)
// Wire represent a single connexion between a gate,
// its output and its inputs
type Wire struct {
L, R, O int
Gate Gate
}
// Layer describes how a layer feeds its inputs
type Layer struct {
Wires []Wire
BGInputs, BGOutputs int
Gates []Gate
}
// NewLayer construct a new layer from a list of wires
func NewLayer(wires []Wire) Layer {
return Layer{
Wires: wires,
Gates: Gates(wires),
BGInputs: BGInputs(wires),
BGOutputs: BGOutputs(wires),
}
}
// GetStaticTable returns the prefolded static tables
// They are returned in the same order as l.Gates
func (l *Layer) GetStaticTable(q []fr.Element) []polynomial.BookKeepingTable {
// Computes the gates to ensure we return the bookeeping tables in a deterministic order
gates := l.Gates
res := make([]polynomial.BookKeepingTable, len(gates))
// Usefull integer constants
gO, gL := (1 << (2 * l.BGInputs)), 1<<l.BGInputs
var one fr.Element
one.SetOne()
for i, gate := range l.Gates {
// The tab is filled with zeroes
tab := make([]fr.Element, (1<<l.BGOutputs)*(1<<(2*l.BGInputs)))
for _, w := range l.Wires {
if w.Gate.ID() == gate.ID() {
k := gO*w.O + gL*w.L + w.R
tab[k].Add(&tab[k], &one)
}
}
// Prefold the bookkeeping table before returning
bkt := polynomial.NewBookKeepingTable(tab)
for _, r := range q {
bkt.Fold(r)
}
res[i] = bkt
}
return res
}
// Evaluate returns the assignment of the next layer
// It can be multi-threaded
func (l *Layer) Evaluate(inputs [][]fr.Element, nCore int) [][]fr.Element {
res := make([][]fr.Element, len(inputs))
semaphore := common.NewSemaphore(nCore)
defer semaphore.Close()
var wg sync.WaitGroup
wg.Add(len(inputs))
// Multi-thread the evaluation
for i := range inputs {
go func(i int) {
semaphore.Acquire()
inps := inputs[i]
GInputs := 1 << l.BGInputs
GOutputs := 1 << l.BGOutputs
N := len(inps) / GInputs
subRes := make([]fr.Element, N*GOutputs)
var tmp fr.Element
for _, w := range l.Wires {
// Precompute the indices
wON := w.O * N
wLN := w.L * N
wRN := w.R * N
for h := 0; h < N; h++ {
// Runs the gate evaluator
w.Gate.Eval(&tmp, &inps[wLN+h], &inps[wRN*N+h])
subRes[wON+h].Add(&subRes[wON+h], &tmp)
}
}
res[i] = subRes
semaphore.Release()
wg.Done()
}(i)
}
wg.Wait()
return res
}
// BGOutputs return the log-size of the input layer of the layer
func BGOutputs(wires []Wire) int {
res := 0
for _, wire := range wires {
if res < wire.O {
res = wire.O
}
}
return common.Log2Ceil(res + 1)
}
// BGInputs return the log-size of the input layer of the layer
func BGInputs(wires []Wire) int {
res := 0
for _, wire := range wires {
if res < wire.L {
res = wire.L
}
if res < wire.R {
res = wire.R
}
}
return common.Log2Ceil(res + 1)
}
// Gates returns a deduplicated list of gates used by this layer
func Gates(wires []Wire) []Gate {
gates := make(map[string]Gate)
res := []Gate{}
for _, wire := range wires {
if _, ok := gates[wire.Gate.ID()]; !ok {
res = append(res, wire.Gate)
}
}
return res
} | circuit/layers.go | 0.66628 | 0.422981 | layers.go | starcoder |
package path
import (
"fmt"
"math"
"strings"
"github.com/dustismo/heavyfishdesign/dynmap"
)
const (
DefaultPrecision = 3 // how many decimal places do we want to consider
)
type Point struct {
X float64
Y float64
// t value on a curve. (This is optional,
// and we ignore 0 values for this)
t float64
}
type Path interface {
Segments() []Segment
AddSegments(seg ...Segment)
Clone() Path
}
type Segment interface {
// SetStart(p Point) Segment
Start() Point
End() Point
SvgString(numDecimals int) string
UniqueString(numDecimals int) string
Clone() Segment
}
type MoveSegment struct {
StartPoint Point
EndPoint Point
}
type LineSegment struct {
StartPoint Point
EndPoint Point
}
type CurveSegment struct {
StartPoint Point
ControlPointStart Point
EndPoint Point
ControlPointEnd Point
}
func NewPath() Path {
p := &PathImpl{}
return p
}
// creates a new Path from the passed in segments without adding a
// move at the beginning.
func NewPathFromSegmentsWithoutMove(segments []Segment) Path {
segs := []Segment{}
segs = append(segs, segments...)
segs = FixHeadMove(segs)
return &PathImpl{
segments: segs,
}
}
func NewPathFromSegments(segments []Segment) Path {
segs := []Segment{}
if len(segments) > 0 {
if !IsMove(segments[0]) {
// didn't start with a move so we need to move to the start
segs = append(segs, MoveSegment{
StartPoint: NewPoint(0, 0),
EndPoint: segments[0].Start(),
})
}
}
segs = append(segs, segments...)
segs = FixHeadMove(segs)
return &PathImpl{
segments: segs,
}
}
// creates a line segment based on start point, length and angle
// where a positive horizontal line is 0 degrees
func NewLineSegmentAngle(start Point, length, angle float64) LineSegment {
y := (length * math.Sin(DegreesToRadians(angle))) + start.Y
x := (length * math.Cos(DegreesToRadians(angle))) + start.X
return LineSegment{
StartPoint: start,
EndPoint: NewPoint(x, y),
}
}
func SetSegmentStart(segment Segment, start Point) (Segment, error) {
switch s := segment.(type) {
case MoveSegment:
s.StartPoint = start
return s, nil
case LineSegment:
s.StartPoint = start
return s, nil
case CurveSegment:
s.StartPoint = start
return s, nil
}
return segment, fmt.Errorf("Unable to set segment start %+v", segment)
}
func SvgString(path Path, numDecimals int) string {
str := []string{}
for _, s := range path.Segments() {
str = append(str, s.SvgString(numDecimals))
}
return strings.Join(str, " ")
}
type PathImpl struct {
segments []Segment
}
func (p *PathImpl) SvgString(decimals int) string {
return ""
}
func (p *PathImpl) Segments() []Segment {
return p.segments
}
func (p *PathImpl) AddSegments(seg ...Segment) {
// update the startpoint
p.segments = append(p.segments, seg...)
}
func (p *PathImpl) Clone() Path {
segs := []Segment{}
for _, s := range p.segments {
segs = append(segs, s.Clone())
}
return &PathImpl{
segments: segs,
}
}
func (m MoveSegment) Start() Point {
return m.StartPoint
}
func (m MoveSegment) SetStart(p Point) Segment {
m.StartPoint = p
return m
}
func (m MoveSegment) End() Point {
return m.EndPoint
}
func (m MoveSegment) Clone() Segment {
return MoveSegment{
StartPoint: m.StartPoint.Clone(),
EndPoint: m.EndPoint.Clone(),
}
}
func (m MoveSegment) SvgString(numDecimals int) string {
return fmt.Sprintf(precisionStr("M %.3f %.3f", numDecimals), m.End().X, m.End().Y)
}
func (m MoveSegment) UniqueString(numDecimals int) string {
return fmt.Sprintf(precisionStr("MOVE (%.3f, %.3f) (%.3f, %.3f)", numDecimals),
m.Start().X,
m.Start().Y,
m.End().X,
m.End().Y,
)
}
func (l LineSegment) Start() Point {
return l.StartPoint
}
func (l LineSegment) SetStart(p Point) Segment {
l.StartPoint = p
return l
}
func (l LineSegment) End() Point {
return l.EndPoint
}
func (l LineSegment) Slope() float64 {
a := l.Start()
b := l.End()
return (b.Y - a.Y) / (b.X - a.X)
}
// returns true if this line is vertical
func (l LineSegment) IsVerticalPrecision(precision int) bool {
a := l.Start()
b := l.End()
return PrecisionEquals(a.X, b.X, precision)
}
func (l LineSegment) IsHorizontalPrecision(precision int) bool {
a := l.Start()
b := l.End()
return PrecisionEquals(a.Y, b.Y, precision)
}
func (l LineSegment) YIntercept() float64 {
a := l.Start()
return a.Y - l.Slope()*a.X
}
// gets the value of Y for the given X
func (l LineSegment) EvalX(x float64) float64 {
return l.Slope()*x + l.YIntercept()
}
func (l LineSegment) Length() float64 {
return Distance(l.Start(), l.End())
}
// Finds the point at the specified distance from the start point in
//the direction of the end point..
func (l LineSegment) PointAtDistance(distance float64) Point {
neg := 1.0
if l.IsVerticalPrecision(DefaultPrecision) {
if l.Start().Y > l.End().Y {
neg = -1.0
}
return NewPoint(
l.Start().X,
l.Start().Y+(neg*distance),
)
}
if l.IsHorizontalPrecision(DefaultPrecision) {
if l.Start().X > l.End().X {
neg = -1.0
}
return NewPoint(
l.Start().X+(neg*distance),
l.Start().Y,
)
}
// todo: does this work when start is after end?
m := l.Slope()
x := distance*math.Cos(math.Atan(m)) + l.Start().X
y := distance*math.Sin(math.Atan(m)) + l.Start().Y
return NewPoint(x, y)
}
// the angle of the line in degrees. where a positive horizontal line is 0
func (l LineSegment) Angle() float64 {
xDiff := l.End().X - l.Start().X
yDiff := l.End().Y - l.Start().Y
return (180 / math.Pi) * math.Atan2(yDiff, xDiff)
}
func (l LineSegment) Clone() Segment {
return LineSegment{
StartPoint: l.StartPoint.Clone(),
EndPoint: l.EndPoint.Clone(),
}
}
func (l LineSegment) SvgString(numDecimals int) string {
return fmt.Sprintf(precisionStr("L %.3f %.3f", numDecimals), l.End().X, l.End().Y)
}
func (l LineSegment) UniqueString(numDecimals int) string {
return fmt.Sprintf(precisionStr("LINE (%.3f, %.3f) (%.3f, %.3f)", numDecimals),
l.Start().X,
l.Start().Y,
l.End().X,
l.End().Y,
)
}
func (c CurveSegment) Start() Point {
return c.StartPoint
}
func (c CurveSegment) SetStart(p Point) Segment {
c.StartPoint = p
return c
}
func (c CurveSegment) End() Point {
return c.EndPoint
}
func (c CurveSegment) Clone() Segment {
return CurveSegment{
StartPoint: c.StartPoint.Clone(),
ControlPointStart: c.ControlPointStart.Clone(),
EndPoint: c.EndPoint.Clone(),
ControlPointEnd: c.ControlPointEnd.Clone(),
}
}
func (c CurveSegment) SvgString(numDecimals int) string {
return fmt.Sprintf(precisionStr("C %.3f %.3f %.3f %.3f %.3f %.3f", numDecimals),
c.ControlPointStart.X,
c.ControlPointStart.Y,
c.ControlPointEnd.X,
c.ControlPointEnd.Y,
c.End().X,
c.End().Y)
}
func (c CurveSegment) UniqueString(numDecimals int) string {
return fmt.Sprintf(precisionStr("CURVE (%.3f, %.3f) (%.3f, %.3f) (%.3f, %.3f) (%.3f, %.3f)", numDecimals),
c.Start().X,
c.Start().Y,
c.ControlPointStart.X,
c.ControlPointStart.Y,
c.ControlPointEnd.X,
c.ControlPointEnd.Y,
c.End().X,
c.End().Y,
)
}
func (c CurveSegment) ControlStart() Point {
return c.ControlPointStart
}
func (c CurveSegment) ControlEnd() Point {
return c.ControlPointEnd
}
// Creates a new point, will convert -0.0 to 0.0
func NewPoint(x float64, y float64) Point {
if x == -0.0 {
x = 0
}
if y == -0.0 {
y = 0
}
return Point{
x, y, -1,
}
}
// creates a new point, with the values rounded to 3 decimal places
func NewPointRounded(x float64, y float64) Point {
x = math.Round(x*1000) / 1000
y = math.Round(y*1000) / 1000
return NewPoint(x, y)
}
func (p Point) StringRounded() string {
x := math.Round(p.X*1000) / 1000
y := math.Round(p.Y*1000) / 1000
if x == -0.0 {
x = 0
}
if y == -0.0 {
y = 0
}
return fmt.Sprintf("(%.3f,%.3f)", x, y)
}
func (p Point) StringPrecision(numDecimals int) string {
return fmt.Sprintf(precisionStr("(X: %.3f, Y: %.3f)", numDecimals), p.X, p.Y)
}
func (p Point) String() string {
return fmt.Sprintf("(%.16f,%.16f)", p.X, p.Y)
}
// checks if the points are equal
// this check for exact equality (the floats must be the same)
func (p Point) Equals(other Point) bool {
return p.X == other.X && p.Y == other.Y
}
// checks if the points are equal based to the requested number of
// decimal places
func (p Point) EqualsPrecision(other Point, numDecimals int) bool {
if numDecimals < 0 {
return p.Equals(other)
}
return p.StringPrecision(numDecimals) == other.StringPrecision(numDecimals)
}
func (p Point) Clone() Point {
return NewPoint(p.X, p.Y)
}
func (p Point) ToDynMap() *dynmap.DynMap {
mp := dynmap.New()
mp.Put("x", p.X)
mp.Put("y", p.Y)
return mp
}
func precisionStr(str string, numDecimals int) string {
return strings.ReplaceAll(str, "3", fmt.Sprintf("%d", numDecimals))
} | path/path.go | 0.749546 | 0.463809 | path.go | starcoder |
package memory
import (
"github.com/blackchip-org/pac8/pkg/util/bits"
"github.com/blackchip-org/pac8/pkg/util/state"
)
// Memory is a chunk of 8-bit values accessed by a 16-bit address.
type Memory interface {
// Load returns the value from the address at addr.
Load(addr uint16) uint8
// Store puts the value of v at the address at addr.
Store(addr uint16, v uint8)
// Length is the number of 8-bit values in this memory.
Length() int
Save(*state.Encoder)
Restore(*state.Decoder)
}
// Block is a chunck of memory found at a specific address.
type Block struct {
// Mem is the memory for this block
Mem Memory
// Addr is the address that Mem.Load(0) represents.
Addr uint16
}
// NewBlock creates a new Block of memory at the address of addr.
func NewBlock(addr uint16, mem Memory) Block {
return Block{Mem: mem, Addr: addr}
}
type ram struct {
bytes []uint8
}
// NewRAM creates a chunk of memory with a length of len that can be
// read and written to.
func NewRAM(len int) Memory {
return &ram{bytes: make([]uint8, len, len)}
}
func (r ram) Load(address uint16) uint8 {
return r.bytes[address]
}
func (r ram) Store(address uint16, value uint8) {
r.bytes[address] = value
}
func (r ram) Length() int {
return len(r.bytes)
}
func (r ram) Save(enc *state.Encoder) {
enc.Encode(r.bytes)
}
func (r ram) Restore(dec *state.Decoder) {
dec.Decode(&r.bytes)
}
type rom struct {
bytes []uint8
}
// NewROM creates a chunk of read-only memory that accesses data.
func NewROM(data []uint8) Memory {
return rom{bytes: data}
}
func (r rom) Load(address uint16) uint8 {
if int(address) >= len(r.bytes) {
return 0
}
return r.bytes[address]
}
func (r rom) Store(address uint16, value uint8) {}
func (r rom) Length() int {
return len(r.bytes)
}
func (r rom) Save(enc *state.Encoder) {}
func (r rom) Restore(dec *state.Decoder) {}
type null struct {
length int
}
// NewNull creates a chunk of memory with a length of len that always returns
// zero when read. Writes are ignored.
func NewNull(len int) Memory {
return null{length: len}
}
func (n null) Load(address uint16) uint8 {
return 0
}
func (n null) Store(address uint16, value uint8) {}
func (n null) Length() int {
return n.length
}
func (n null) Save(enc *state.Encoder) {}
func (n null) Restore(dec *state.Decoder) {}
type pageMap struct {
mem Memory
offset uint16
}
type pageMapped struct {
blocks []Block
pages [256]pageMap
}
// NewPageMapped creates a memory that combines multiple memory blocks
// into a single addressable memory mapped at the page level. Each block
// must have a length that is divisible by a page and addressed at a
// page boundary. Unmapped pages return zero when read and are ignored
// when written.
func NewPageMapped(blocks []Block) Memory {
pm := &pageMapped{}
for i := 0; i < 256; i++ {
pm.pages[i] = pageMap{mem: NewNull(0x100), offset: 0}
}
for _, block := range blocks {
if block.Addr%0x100 != 0 {
panic("memory block must start on page boundary")
}
if block.Mem.Length()%0x100 != 0 {
panic("memory block length must be a multiple of a page")
}
for offset := 0; offset < block.Mem.Length(); offset += 256 {
page := (block.Addr + uint16(offset)) / 256
pm.pages[page] = pageMap{mem: block.Mem, offset: uint16(offset)}
}
}
pm.blocks = blocks
return pm
}
func (m pageMapped) Load(address uint16) uint8 {
pageN, index := bits.Split(address)
page := m.pages[pageN]
return page.mem.Load(page.offset + uint16(index))
}
func (m pageMapped) Store(address uint16, value uint8) {
pageN, index := bits.Split(address)
page := m.pages[pageN]
page.mem.Store(page.offset+uint16(index), value)
}
func (m pageMapped) Length() int {
return 0x10000
}
func (m pageMapped) Save(enc *state.Encoder) {
for _, b := range m.blocks {
b.Mem.Save(enc)
}
}
func (m pageMapped) Restore(dec *state.Decoder) {
for _, b := range m.blocks {
b.Mem.Restore(dec)
}
}
type BlockMapper struct {
Blocks []Block
}
func NewBlockMapper() *BlockMapper {
return &BlockMapper{
Blocks: make([]Block, 0, 0),
}
}
func (b *BlockMapper) Map(addr uint16, mem Memory) {
if addr%0x100 != 0 {
panic("memory block must start on page boundary")
}
if mem.Length()%0x100 != 0 {
panic("memory block length must be a multiple of a page")
}
b.Blocks = append(b.Blocks, NewBlock(addr, mem))
} | pkg/memory/memory.go | 0.769946 | 0.466177 | memory.go | starcoder |
package os
import (
"fmt"
"math"
"os"
"regexp"
"strconv"
"github.com/emc-advanced-dev/pkg/errors"
)
type DiskSize interface {
ToPartedFormat() string
ToBytes() Bytes
}
type Bytes int64
func (s Bytes) ToPartedFormat() string {
return fmt.Sprintf("%dB", uint64(s))
}
func (s Bytes) ToBytes() Bytes {
return s
}
// ToMegaBytes returns lowest whole number of size_MB so that size_MB >= (size_B / 1024^2)
func (s Bytes) ToMegaBytes() MegaBytes {
return MegaBytes(int(math.Ceil(float64(s) / float64(MegaBytes(1).ToBytes()))))
}
type MegaBytes int64
func (s MegaBytes) ToPartedFormat() string {
return fmt.Sprintf("%dMiB", uint64(s))
}
func (s MegaBytes) ToBytes() Bytes {
return Bytes(s << 20)
}
type GigaBytes int64
func (s GigaBytes) ToPartedFormat() string {
return fmt.Sprintf("%dGiB", uint64(s))
}
func (s GigaBytes) ToBytes() Bytes {
return Bytes(s << 30)
}
type Sectors int64
const SectorSize = 512
func (s Sectors) ToPartedFormat() string {
return fmt.Sprintf("%ds", uint64(s))
}
func (s Sectors) ToBytes() Bytes {
return Bytes(s * SectorSize)
}
func ToSectors(b DiskSize) (Sectors, error) {
inBytes := b.ToBytes()
if inBytes%SectorSize != 0 {
return 0, errors.New("can't convert to sectors", nil)
}
return Sectors(inBytes / SectorSize), nil
}
type BlockDevice string
func (b BlockDevice) Name() string {
return string(b)
}
type Partitioner interface {
MakeTable() error
MakePart(partType string, start, size DiskSize) error
}
type Resource interface {
Acquire() (BlockDevice, error)
Release() error
}
type Part interface {
Resource
Size() DiskSize
Offset() DiskSize
Get() BlockDevice
}
func IsExists(f string) bool {
_, err := os.Stat(f)
return !os.IsNotExist(err)
}
// ParseSize parses disk size string (e.g. "10GB" or "150MB") into MegaBytes
// If no unit string is provided, megabytes are assumed
func ParseSize(sizeStr string) (MegaBytes, error) {
r, _ := regexp.Compile("^([0-9]+)(m|mb|M|MB|g|gb|G|GB)?$")
match := r.FindStringSubmatch(sizeStr)
if len(match) != 3 {
return -1, fmt.Errorf("%s: unrecognized size", sizeStr)
}
size, _ := strconv.ParseInt(match[1], 10, 64)
unit := match[2]
switch unit {
case "g", "gb", "G", "GB":
size *= 1024
}
if size == 0 {
return -1, fmt.Errorf("%s: size must be larger than zero", sizeStr)
}
return MegaBytes(size), nil
} | pkg/os/device.go | 0.690246 | 0.421254 | device.go | starcoder |
package common
const (
// MeasurementsHeadCluster is the cluster row identifier in the measurement file.
MeasurementsHeadCluster = "cluster"
// MeasurementsHeadProvider is the provider row identifier in the measurement file.
MeasurementsHeadProvider = "provider"
// MeasurementsHeadSeed is the seed row identifier in the measurement file.
MeasurementsHeadSeed = "seed"
// MeasurementsHeadTimestamp is the timestamp row identifier in the measurement file.
MeasurementsHeadTimestamp = "timestamp"
// MeasurementsHeadStatusCode is the status code row identifier in the measurement file.
MeasurementsHeadStatusCode = "status_code"
// MeasurementsHeadResponseTime is the response time row identifier in the measurement file.
MeasurementsHeadResponseTime = "response_time_ms"
// ReportOutputFormatText is the identifier for the report output format text.
ReportOutputFormatText = "text"
// ReportOutputFormatJSON is the identifier for the report output format json.
ReportOutputFormatJSON = "json"
// CliFlagLogLevel is the cli flag to specify the log level.
CliFlagLogLevel = "log-level"
// CliFlagReportOutput is the cli flag which passes the report file destination.
CliFlagReportOutput = "report"
// CliFlagReportFormat is the cli flag which passes the report output format.
CliFlagReportFormat = "format"
// CliFlagHelpTextReportFile is the help text for the cli flag which passes the report file destination.
CliFlagHelpTextReportFile = "path to the report file"
// CliFlagHelpTextReportFormat is the help text for the cli flag which passes the report output format.
CliFlagHelpTextReportFormat = "output format of the report: text|json"
// CliFlagHelpLogLevel is the help text for the cli flag which specify the log level.
CliFlagHelpLogLevel = "log level: error|info|debug"
// LogDebugAddPrefix is a prefix for controller add operations debug log outputs.
LogDebugAddPrefix = "[ADD]"
// LogDebugUpdatePrefix is a prefix for controller update operations debug log outputs.
LogDebugUpdatePrefix = "[UPDATE]"
// DefaultLogLevel define the default log level.
DefaultLogLevel = "info"
// RequestTimeOut is the timeout for a health check to the ApiServer.
RequestTimeOut int = 5000
) | pkg/shoot-telemetry/common/definitions.go | 0.585812 | 0.401805 | definitions.go | starcoder |
package cmd
import (
"fmt"
"strconv"
"strings"
"github.com/jaredbancroft/aoc2020/pkg/helpers"
"github.com/spf13/cobra"
)
// day15Cmd represents the day15 command
var day15Cmd = &cobra.Command{
Use: "day15",
Short: "Advent of Code 2020 - Day15: Rambunctious Recitation",
Long: `
Advent of Code 2020
--- Day 15: Rambunctious Recitation ---
You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm,
all direct flights have been cancelled, but a route is available to get around the storm. You take it.
While you wait for your flight, you decide to check in with the Elves back at the North Pole. They're
playing a memory game and are ever so excited to explain the rules!
In this game, the players take turns saying numbers. They begin by taking turns reading from a list of
starting numbers (your puzzle input). Then, each turn consists of considering the most recently spoken number:
If that was the first time the number has been spoken, the current player says 0.
Otherwise, the number had been spoken before; the current player announces how many turns apart the number
is from when it was previously spoken.
So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number
is new) or an age (if the last number is a repeat).
For example, suppose the starting numbers are 0,3,6:
Turn 1: The 1st number spoken is a starting number, 0.
Turn 2: The 2nd number spoken is a starting number, 3.
Turn 3: The 3rd number spoken is a starting number, 6.
Turn 4: Now, consider the last number spoken, 6. Since that was the first time the number had been spoken, the 4th number spoken is 0.
Turn 5: Next, again consider the last number spoken, 0. Since it had been spoken before, the next number to speak is the difference between the turn number when it was last spoken (the previous turn, 4) and the turn number of the time it was most recently spoken before then (turn 1). Thus, the 5th number spoken is 4 - 1, 3.
Turn 6: The last number spoken, 3 had also been spoken before, most recently on turns 5 and 2. So, the 6th number spoken is 5 - 2, 3.
Turn 7: Since 3 was just spoken twice in a row, and the last two turns are 1 turn apart, the 7th number spoken is 1.
Turn 8: Since 1 is new, the 8th number spoken is 0.
Turn 9: 0 was last spoken on turns 8 and 4, so the 9th number spoken is the difference between them, 4.
Turn 10: 4 is new, so the 10th number spoken is 0.
(The game ends when the Elves get sick of playing or dinner is ready, whichever comes first.)
Their question for you is: what will be the 2020th number spoken? In the example above, the 2020th number spoken will be 436.
Here are a few more examples:
Given the starting numbers 1,3,2, the 2020th number spoken is 1.
Given the starting numbers 2,1,3, the 2020th number spoken is 10.
Given the starting numbers 1,2,3, the 2020th number spoken is 27.
Given the starting numbers 2,3,1, the 2020th number spoken is 78.
Given the starting numbers 3,2,1, the 2020th number spoken is 438.
Given the starting numbers 3,1,2, the 2020th number spoken is 1836.
Given your starting numbers, what will be the 2020th number spoken?`,
RunE: func(cmd *cobra.Command, args []string) error {
puzzle, err := helpers.ReadStringFile(input)
if err != nil {
return err
}
tracker, prev := parseTracker(puzzle[0])
turn := len(tracker)
var spoken int
for {
turn++
if x, ok := tracker[prev]; ok {
if len(x) > 1 {
spoken = x[len(x)-1] - x[len(x)-2]
tracker[spoken] = append(tracker[spoken], turn)
} else {
spoken = 0
tracker[spoken] = append(tracker[spoken], turn)
}
prev = spoken
}
if turn == 30000000 {
fmt.Println(spoken)
break
}
}
return nil
},
}
func parseTracker(numString string) (map[int][]int, int) {
tracker := make(map[int][]int)
nums := strings.Split(numString, ",")
var i int
for i, num := range nums {
numInt, _ := strconv.Atoi(num)
tracker[numInt] = []int{i + 1}
}
return tracker, i + 1
}
func init() {
rootCmd.AddCommand(day15Cmd)
} | cmd/day15.go | 0.58522 | 0.656438 | day15.go | starcoder |
package ast
import (
"akdjr/monkey/token"
"bytes"
"strings"
)
// Node represents a node in the AST. TokenLiteral() returns the literal value of the token that the node is associated with
type Node interface {
TokenLiteral() string
String() string
}
// Statement represents a statment in the AST. Statements do not produce values
type Statement interface {
Node
statementNode()
}
// Expression represents an expression in the AST. Expressions produce a value
type Expression interface {
Node
expressionNode()
}
// Program is a node that will be the root of the AST. It is represented as a series of statements
type Program struct {
Statements []Statement
}
func (p *Program) TokenLiteral() string {
if len(p.Statements) > 0 {
return p.Statements[0].TokenLiteral()
}
return ""
}
func (p *Program) String() string {
var out bytes.Buffer
for _, s := range p.Statements {
out.WriteString(s.String())
}
return out.String()
}
// LetStatement represeents a let statement of the format "let <identifier> = <expression>;"
type LetStatement struct {
Token token.Token
Name *Identifier
Value Expression
}
func (ls *LetStatement) statementNode() {}
func (ls *LetStatement) TokenLiteral() string { return ls.Token.Literal }
func (ls *LetStatement) String() string {
var out bytes.Buffer
out.WriteString(ls.TokenLiteral() + " ")
out.WriteString(ls.Name.String())
out.WriteString(" = ")
if ls.Value != nil {
out.WriteString(ls.Value.String())
}
out.WriteString(";")
return out.String()
}
// Identifier represents an expression that holds an identifier
type Identifier struct {
Token token.Token
Value string
}
func (i *Identifier) expressionNode() {}
func (i *Identifier) TokenLiteral() string { return i.Token.Literal }
func (i *Identifier) String() string { return i.Value }
// ReturnStatement represents a return statement of the format "return <expression>;"
type ReturnStatement struct {
Token token.Token
ReturnValue Expression
}
func (rs *ReturnStatement) statementNode() {}
func (rs *ReturnStatement) TokenLiteral() string { return rs.Token.Literal }
func (rs *ReturnStatement) String() string {
var out bytes.Buffer
out.WriteString(rs.TokenLiteral() + " ")
if rs.ReturnValue != nil {
out.WriteString(rs.ReturnValue.String())
}
out.WriteString(";")
return out.String()
}
// ExpressionStatement represents an expression statement of the form <expression>; ex. x + 10;
type ExpressionStatement struct {
Token token.Token
Expression Expression
}
func (es *ExpressionStatement) statementNode() {}
func (es *ExpressionStatement) TokenLiteral() string { return es.Token.Literal }
func (es *ExpressionStatement) String() string {
if es.Expression != nil {
return es.Expression.String()
}
return ""
}
// IntegerLiteral represents a 64 integer expression. ex 5
type IntegerLiteral struct {
Token token.Token
Value int64
}
func (il *IntegerLiteral) expressionNode() {}
func (il *IntegerLiteral) TokenLiteral() string { return il.Token.Literal }
func (il *IntegerLiteral) String() string { return il.Token.Literal }
// PrefixExpression represents a prefix operator expression, ex. -5 <prefix-operator><expression>
type PrefixExpression struct {
Token token.Token // the prefix token, ex !
Operator string
Right Expression
}
func (pe *PrefixExpression) expressionNode() {}
func (pe *PrefixExpression) TokenLiteral() string { return pe.Token.Literal }
func (pe *PrefixExpression) String() string {
var out bytes.Buffer
out.WriteString("(")
out.WriteString(pe.Operator)
out.WriteString(pe.Right.String())
out.WriteString(")")
return out.String()
}
// InfixExpression represents an infix operator expression, ex 5 + 5, <left-expression><prefix-operator><right-expression>
type InfixExpression struct {
Token token.Token // operator token, ex. +
Left Expression
Operator string
Right Expression
}
func (ie *InfixExpression) expressionNode() {}
func (ie *InfixExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *InfixExpression) String() string {
var out bytes.Buffer
out.WriteString("(")
out.WriteString(ie.Left.String())
out.WriteString(" " + ie.Operator + " ")
out.WriteString(ie.Right.String())
out.WriteString(")")
return out.String()
}
// Boolean represents a boolean literal, true/false
type Boolean struct {
Token token.Token
Value bool
}
func (b *Boolean) expressionNode() {}
func (b *Boolean) TokenLiteral() string { return b.Token.Literal }
func (b *Boolean) String() string { return b.Token.Literal }
// BlockStatement represents a block of statements of the form { <statements>; }
type BlockStatement struct {
Token token.Token // the { token
Statements []Statement
}
func (bs *BlockStatement) statementNode() {}
func (bs *BlockStatement) TokenLiteral() string { return bs.Token.Literal }
func (bs *BlockStatement) String() string {
var out bytes.Buffer
for _, stmt := range bs.Statements {
out.WriteString(stmt.String())
}
return out.String()
}
// IfExpression represents an if-else conditional. It is an expression as it can produce a value such that it can be used similarily to the ternary operator. ex: let value = if <condition> { <consequence> } else { <alternative> }.
type IfExpression struct {
Token token.Token // the if token
Condition Expression
Consequence *BlockStatement
Alternative *BlockStatement
}
func (ie *IfExpression) expressionNode() {}
func (ie *IfExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *IfExpression) String() string {
var out bytes.Buffer
out.WriteString("if ")
out.WriteString(ie.Condition.String())
out.WriteString(" ")
out.WriteString(ie.Consequence.String())
if ie.Alternative != nil {
out.WriteString("else")
out.WriteString(ie.Alternative.String())
}
return out.String()
}
// FunctionLiteral represents a function literal. it is an expression and as such can be assigned or passed around or treated as any other expression. of the format fn(<identifier list>) { <block statements> }
type FunctionLiteral struct {
Token token.Token // fn token
Parameters []*Identifier
Body *BlockStatement
}
func (fl *FunctionLiteral) expressionNode() {}
func (fl *FunctionLiteral) TokenLiteral() string { return fl.Token.Literal }
func (fl *FunctionLiteral) String() string {
var out bytes.Buffer
params := []string{}
for _, p := range fl.Parameters {
params = append(params, p.String())
}
out.WriteString(fl.TokenLiteral())
out.WriteString("(")
out.WriteString(strings.Join(params, ","))
out.WriteString(") ")
out.WriteString(fl.Body.String())
return out.String()
}
// CallExpression represents a call expression. This consist of an expression tha will evaluate to a function (either an identifier or a function literal - a function identifier is an expression that will resolve to a function literal) and an array of expressions as parameters.
type CallExpression struct {
Token token.Token // the '(' token
Function Expression // Identifier or FunctionLiteral
Arguments []Expression
}
func (ce *CallExpression) expressionNode() {}
func (ce *CallExpression) TokenLiteral() string { return ce.Token.Literal }
func (ce *CallExpression) String() string {
var out bytes.Buffer
args := []string{}
for _, a := range ce.Arguments {
args = append(args, a.String())
}
out.WriteString(ce.Function.String())
out.WriteString("(")
out.WriteString(strings.Join(args, ", "))
out.WriteString(")")
return out.String()
} | ast/ast.go | 0.808597 | 0.420362 | ast.go | starcoder |
package terms
import (
"algex/factor"
"math/big"
"sort"
"strings"
)
// term is a product of a coefficient and a set of non-numerical factors.
type term struct {
coeff *big.Rat
fact []factor.Value
}
// Exp is a an expression or sum of terms.
type Exp struct {
terms map[string]term
}
// NewExp creates a new expression.
func NewExp(ts ...[]factor.Value) *Exp {
e := &Exp{
terms: make(map[string]term),
}
for _, t := range ts {
n, fs, s := factor.Segment(t...)
if n == nil {
continue
}
e.insert(n, fs, s)
}
return e
}
// String represents an expression of terms as a string.
func (e *Exp) String() string {
if e == nil {
return "0"
} else if len(e.terms) == 0 {
return "0"
}
var s []string
for x := range e.terms {
s = append(s, x)
}
// TODO: might want to prefer a non-ascii sorted expression.
sort.Strings(s)
for i, x := range s {
f := e.terms[x]
v := []factor.Value{factor.R(f.coeff)}
t := factor.Prod(append(v, f.fact...)...)
if i != 0 && t[0] != '-' {
s[i] = "+" + t
} else {
s[i] = t
}
}
return strings.Join(s, "")
}
// insert merges a coefficient, a product of factors to an expression
// indexed by s.
func (e *Exp) insert(n *big.Rat, fs []factor.Value, s string) {
old, ok := e.terms[s]
if !ok {
e.terms[s] = term{
coeff: n,
fact: fs,
}
return
}
// Combine with existing term.
old.coeff = n.Add(n, e.terms[s].coeff)
if old.coeff.Cmp(&big.Rat{}) == 0 {
delete(e.terms, s)
return
}
e.terms[s] = old
}
// Add adds together expressions. With only one argument, Add is a
// simple duplicate function.
func Add(as ...*Exp) *Exp {
e := &Exp{
terms: make(map[string]term),
}
for _, a := range as {
for s, t := range a.terms {
m := &big.Rat{}
e.insert(m.Set(t.coeff), t.fact, s)
}
}
return e
}
// Sub subtracts b from a into a new expression.
func Sub(a, b *Exp) *Exp {
e := &Exp{
terms: make(map[string]term),
}
for s, t := range a.terms {
m := &big.Rat{}
e.insert(m.Set(t.coeff), t.fact, s)
}
for s, t := range b.terms {
m := big.NewRat(-1, 1)
e.insert(m.Mul(m, t.coeff), t.fact, s)
}
return e
}
var zero = []factor.Value{factor.R(&big.Rat{})}
// Mod takes a numerical integer factor and eliminates obvious
// multiples of it from an expression. No attempt is made to
// simplify non-integer fractions.
func (e *Exp) Mod(x factor.Value) *Exp {
if !x.IsNum() || !x.Num().IsInt() {
return e
}
z := &big.Int{} // Zero
a := &Exp{terms: make(map[string]term)}
for s, v := range e.terms {
if !v.coeff.IsInt() {
a.terms[s] = v
continue
}
t := big.NewInt(1)
u := big.NewInt(1)
_, d := t.DivMod(v.coeff.Num(), x.Num().Num(), u)
if d.Cmp(z) == 0 {
// Drop this term since it is a multiple of x.
continue
}
r := &big.Rat{}
r.SetInt(u)
a.terms[s] = term{
coeff: r,
fact: v.fact,
}
}
return a
}
// Mul computes the product of a series of expressions.
func Mul(as ...*Exp) *Exp {
var e *Exp
for i, a := range as {
if i == 0 {
e = Add(a)
continue
}
f := &Exp{
terms: make(map[string]term),
}
for _, p := range a.terms {
for _, q := range e.terms {
x := []factor.Value{factor.R(p.coeff), factor.R(q.coeff)}
n, fs, s := factor.Segment(append(x, append(p.fact, q.fact...)...)...)
f.insert(n, fs, s)
}
}
e = f
}
return e
}
// Substitute replaces each occurrence of b in an expression with the expression c.
func Substitute(e *Exp, b []factor.Value, c *Exp) *Exp {
s := [][]factor.Value{}
for _, t := range c.terms {
s = append(s, append([]factor.Value{factor.R(t.coeff)}, t.fact...))
}
for {
again := false
f := &Exp{
terms: make(map[string]term),
}
for _, x := range e.terms {
a := append([]factor.Value{factor.R(x.coeff)}, x.fact...)
hit, y := factor.Replace(a, b, zero, 1)
if hit == 0 {
n, fs, tag := factor.Segment(y...)
f.insert(n, fs, tag)
// If nothing substituted, then only insert once.
continue
}
if len(s) == 0 {
// If we are substituting 0 then we won't need anything.
continue
}
again = true
for _, t := range s {
_, y := factor.Replace(a, b, t, 1)
n, fs, tag := factor.Segment(y...)
f.insert(n, fs, tag)
}
}
e = f
if !again {
break
}
}
return e
}
// Contains investigates an expression for the presence of a term, b.
func (e *Exp) Contains(b []factor.Value) bool {
for _, x := range e.terms {
a := append([]factor.Value{factor.R(x.coeff)}, x.fact...)
if hit, _ := factor.Replace(a, b, zero, 1); hit != 0 {
return true
}
}
return false
}
// AsNumber ignores all terms that contain symbols, and just returns
// the value of the constant term. The boolean is true only when there
// are no non-constant terms.
func (e *Exp) AsNumber() (*big.Rat, bool) {
ok := e == nil
if !ok {
for _, t := range e.terms {
if len(t.fact) == 0 {
return t.coeff, true
}
}
}
return zero[0].Num(), ok
} | src/algex/terms/terms.go | 0.504394 | 0.42913 | terms.go | starcoder |
package contracts
import (
"context"
"testing"
"github.com/adamluzsi/frameless"
"github.com/adamluzsi/frameless/extid"
"github.com/adamluzsi/testcase"
"github.com/stretchr/testify/require"
)
type FixtureFactory struct {
T interface{}
Subject func(testing.TB) frameless.FixtureFactory
Context func(testing.TB) context.Context
}
func (c FixtureFactory) String() string {
return "FixtureFactory"
}
func (c FixtureFactory) Test(t *testing.T) { c.Spec(testcase.NewSpec(t)) }
func (c FixtureFactory) Benchmark(b *testing.B) { b.Skip() }
func (c FixtureFactory) Spec(s *testcase.Spec) {
s.Parallel()
factoryLet(s, c.Subject)
s.Describe(`.Fixture`, func(s *testcase.Spec) {
subject := func(t *testcase.T) interface{} {
return factoryGet(t).Fixture(c.T, c.Context(t))
}
s.Then(`each created fixture value is uniq`, func(t *testcase.T) {
var results []interface{}
for i := 0; i < 42; i++ {
result := subject(t)
require.NotContains(t, results, result)
results = append(results, result)
}
})
s.When(`struct has Resource external ID`, func(s *testcase.Spec) {
if _, _, hasExtIDField := extid.LookupStructField(c.T); !hasExtIDField {
return
}
s.Then(`it should leave it empty without any value for the fixtures`, func(t *testcase.T) {
fixture := subject(t)
extID, has := extid.Lookup(fixture)
require.False(t, has)
require.Empty(t, extID)
})
})
s.Describe(`.RegisterType`, func(s *testcase.Spec) {
type T struct{ V int }
expectedT := s.Let(`expectedT`, func(t *testcase.T) interface{} {
return T{V: t.Random.Int()}
})
s.Before(func(t *testcase.T) {
factoryGet(t).RegisterType(T{}, func(context.Context) interface{} {
return expectedT.Get(t).(T)
})
})
s.Then(`constructor passed with .RegisterType is used to construct the custom type`, func(t *testcase.T) {
actualT, ok := factoryGet(t).Fixture(T{}, c.Context(t)).(T)
require.True(t, ok)
require.Equal(t, expectedT.Get(t).(T), actualT)
})
})
})
} | contracts/FixtureFactory.go | 0.626238 | 0.454109 | FixtureFactory.go | starcoder |
package goutils
import (
"fmt"
"strings"
)
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
type BSTNode struct {
Value string
Data string
Left *BSTNode
Right *BSTNode
bal int
}
func (n *BSTNode) Insert(value, data string) bool {
switch {
case value == n.Value:
n.Data = data
return false
case value < n.Value:
if n.Left == nil {
n.Left = &BSTNode{Value: value, Data: data}
if n.Right == nil {
n.bal = -1
} else {
n.bal = 0
}
} else {
if n.Left.Insert(value, data) {
if n.Left.bal < -1 || n.Left.bal > 1 {
n.rebalance(n.Left)
} else {
n.bal--
}
}
}
case value > n.Value:
if n.Right == nil {
n.Right = &BSTNode{Value: value, Data: data}
if n.Left == nil {
n.bal = 1
} else {
n.bal = 0
}
} else {
if n.Right.Insert(value, data) {
if n.Right.bal < -1 || n.Right.bal > 1 {
n.rebalance(n.Right)
} else {
n.bal++
}
}
}
}
if n.bal != 0 {
return true
}
return false
}
func (n *BSTNode) rotateLeft(c *BSTNode) {
r := c.Right
c.Right = r.Left
r.Left = c
if c == n.Left {
n.Left = r
} else {
n.Right = r
}
c.bal = 0
r.bal = 0
}
func (n *BSTNode) rotateRight(c *BSTNode) {
l := c.Left
c.Left = l.Right
l.Right = c
if c == n.Left {
n.Left = l
} else {
n.Right = l
}
c.bal = 0
l.bal = 0
}
func (n *BSTNode) rotateRightLeft(c *BSTNode) {
c.Right.Left.bal = 1
c.rotateRight(c.Right)
c.Right.bal = 1
n.rotateLeft(c)
}
func (n *BSTNode) rotateLeftRight(c *BSTNode) {
c.Left.Right.bal = -1
c.rotateLeft(c.Left)
c.Left.bal = -1
n.rotateRight(c)
}
func (n *BSTNode) rebalance(c *BSTNode) {
switch {
case c.bal == -2 && c.Left.bal == -1:
n.rotateRight(c)
case c.bal == 2 && c.Right.bal == 1:
n.rotateLeft(c)
case c.bal == -2 && c.Left.bal == 1:
n.rotateLeftRight(c)
case c.bal == 2 && c.Right.bal == -1:
n.rotateRightLeft(c)
}
}
func (n *BSTNode) Find(s string) (string, bool) {
if n == nil {
return "", false
}
switch {
case s == n.Value:
return n.Data, true
case s < n.Value:
return n.Left.Find(s)
default:
return n.Right.Find(s)
}
}
func (n *BSTNode) Dump(i int, lr string) {
if n == nil {
return
}
indent := ""
if i > 0 {
indent = strings.Repeat(" ", (i-1)*4) + "+" + lr + "--"
}
fmt.Printf("%s%s[%d]\n", indent, n.Value, n.bal)
n.Left.Dump(i+1, "L")
n.Right.Dump(i+1, "R")
}
type BinarySearchTree struct {
Root *BSTNode
}
func (t *BinarySearchTree) Insert(value, data string) {
if t.Root == nil {
t.Root = &BSTNode{Value: value, Data: data}
return
}
t.Root.Insert(value, data)
if t.Root.bal < -1 || t.Root.bal > 1 {
t.rebalance()
}
}
func (t *BinarySearchTree) rebalance() {
fakeParent := &BSTNode{Left: t.Root, Value: "fakeParent"}
fakeParent.rebalance(t.Root)
t.Root = fakeParent.Left
}
func (t *BinarySearchTree) Find(s string) (string, bool) {
if t.Root == nil {
return "", false
}
return t.Root.Find(s)
}
func (t *BinarySearchTree) Traverse(n *BSTNode, f func(*BSTNode)) {
if n == nil {
return
}
t.Traverse(n.Left, f)
f(n)
t.Traverse(n.Right, f)
}
func (t *BinarySearchTree) Dump() {
t.Root.Dump(0, "")
} | bst.go | 0.559771 | 0.442335 | bst.go | starcoder |
package modbus
var NormalEndian normalEndian
type normalEndian struct{}
func (normalEndian) Uint16(b []byte) uint16 {
_ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
return uint16(b[1]) | uint16(b[0])<<8
}
func (normalEndian) PutUint16(b []byte, v uint16) {
_ = b[1] // early bounds check to guarantee safety of writes below
b[1] = byte(v)
b[0] = byte(v >> 8)
}
func (normalEndian) Uint32(b []byte) uint32 {
_ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
return uint32(b[1]) | uint32(b[0])<<8 | uint32(b[3])<<16 | uint32(b[2])<<24
}
func (normalEndian) PutUint32(b []byte, v uint32) {
_ = b[3] // early bounds check to guarantee safety of writes below
b[1] = byte(v)
b[0] = byte(v >> 8)
b[3] = byte(v >> 16)
b[2] = byte(v >> 24)
}
func (normalEndian) Uint64(b []byte) uint64 {
_ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
return uint64(b[1]) | uint64(b[0])<<8 | uint64(b[3])<<16 | uint64(b[2])<<24 |
uint64(b[5])<<32 | uint64(b[4])<<40 | uint64(b[7])<<48 | uint64(b[6])<<56
}
func (normalEndian) PutUint64(b []byte, v uint64) {
_ = b[7] // early bounds check to guarantee safety of writes below
b[1] = byte(v)
b[0] = byte(v >> 8)
b[3] = byte(v >> 16)
b[2] = byte(v >> 24)
b[5] = byte(v >> 32)
b[4] = byte(v >> 40)
b[7] = byte(v >> 48)
b[6] = byte(v >> 56)
}
func (normalEndian) String() string { return "NormalEndian" }
func (normalEndian) GoString() string { return "modbus.NormalEndian" }
var InverseEndian inverseEndian
type inverseEndian struct{}
func (inverseEndian) Uint16(b []byte) uint16 {
_ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
return uint16(b[1]) | uint16(b[0])<<8
}
func (inverseEndian) PutUint16(b []byte, v uint16) {
_ = b[1] // early bounds check to guarantee safety of writes below
b[1] = byte(v)
b[0] = byte(v >> 8)
}
func (inverseEndian) Uint32(b []byte) uint32 {
_ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24
}
func (inverseEndian) PutUint32(b []byte, v uint32) {
_ = b[3] // early bounds check to guarantee safety of writes below
b[3] = byte(v)
b[2] = byte(v >> 8)
b[1] = byte(v >> 16)
b[0] = byte(v >> 24)
}
func (inverseEndian) Uint64(b []byte) uint64 {
_ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |
uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56
}
func (inverseEndian) PutUint64(b []byte, v uint64) {
_ = b[7] // early bounds check to guarantee safety of writes below
b[7] = byte(v)
b[6] = byte(v >> 8)
b[5] = byte(v >> 16)
b[4] = byte(v >> 24)
b[3] = byte(v >> 32)
b[2] = byte(v >> 40)
b[1] = byte(v >> 48)
b[0] = byte(v >> 56)
}
func (inverseEndian) String() string { return "InverseEndian" }
func (inverseEndian) GoString() string { return "modbus.InverseEndian" } | collector/modbus/endian.go | 0.53437 | 0.415847 | endian.go | starcoder |
package spdx
// Snippet2_1 is a Snippet section of an SPDX Document for version 2.1 of the spec.
type Snippet2_1 struct {
// 5.1: Snippet SPDX Identifier: "SPDXRef-[idstring]"
// Cardinality: mandatory, one
SPDXIdentifier ElementID
// 5.2: Snippet from File SPDX Identifier
// Cardinality: mandatory, one
SnippetFromFileSPDXIdentifier DocElementID
// 5.3: Snippet Byte Range: [start byte]:[end byte]
// Cardinality: mandatory, one
ByteRangeStart int
ByteRangeEnd int
// 5.4: Snippet Line Range: [start line]:[end line]
// Cardinality: optional, one
LineRangeStart int
LineRangeEnd int
// 5.5: Snippet Concluded License: SPDX License Expression, "NONE" or "NOASSERTION"
// Cardinality: mandatory, one
LicenseConcluded string
// 5.6: License Information in Snippet: SPDX License Expression, "NONE" or "NOASSERTION"
// Cardinality: optional, one or many
LicenseInfoInSnippet []string
// 5.7: Snippet Comments on License
// Cardinality: optional, one
LicenseComments string
// 5.8: Snippet Copyright Text: copyright notice(s) text, "NONE" or "NOASSERTION"
// Cardinality: mandatory, one
CopyrightText string
// 5.9: Snippet Comment
// Cardinality: optional, one
Comment string
// 5.10: Snippet Name
// Cardinality: optional, one
Name string
}
// Snippet2_2 is a Snippet section of an SPDX Document for version 2.2 of the spec.
type Snippet2_2 struct {
// 5.1: Snippet SPDX Identifier: "SPDXRef-[idstring]"
// Cardinality: mandatory, one
SPDXIdentifier ElementID
// 5.2: Snippet from File SPDX Identifier
// Cardinality: mandatory, one
SnippetFromFileSPDXIdentifier DocElementID
// 5.3: Snippet Byte Range: [start byte]:[end byte]
// Cardinality: mandatory, one
ByteRangeStart int
ByteRangeEnd int
// 5.4: Snippet Line Range: [start line]:[end line]
// Cardinality: optional, one
LineRangeStart int
LineRangeEnd int
// 5.5: Snippet Concluded License: SPDX License Expression, "NONE" or "NOASSERTION"
// Cardinality: mandatory, one
LicenseConcluded string
// 5.6: License Information in Snippet: SPDX License Expression, "NONE" or "NOASSERTION"
// Cardinality: optional, one or many
LicenseInfoInSnippet []string
// 5.7: Snippet Comments on License
// Cardinality: optional, one
LicenseComments string
// 5.8: Snippet Copyright Text: copyright notice(s) text, "NONE" or "NOASSERTION"
// Cardinality: mandatory, one
CopyrightText string
// 5.9: Snippet Comment
// Cardinality: optional, one
Comment string
// 5.10: Snippet Name
// Cardinality: optional, one
Name string
// 5.11: Snippet Attribution Text
// Cardinality: optional, one or many
AttributionTexts []string
} | spdx/snippet.go | 0.591841 | 0.472744 | snippet.go | starcoder |
package schema
// ChangesetSpecSchemaJSON is the content of the file "changeset_spec.schema.json".
const ChangesetSpecSchemaJSON = `{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ChangesetSpec",
"description": "A changeset specification, which describes a changeset to be created or an existing changeset to be tracked.",
"type": "object",
"oneOf": [
{
"properties": {
"baseRepository": {
"type": "string",
"description": "The GraphQL ID of the repository that contains the existing changeset on the code host.",
"examples": ["UmVwb3NpdG9yeTo5Cg=="]
},
"externalID": {
"type": "string",
"description": "The ID that uniquely identifies the existing changeset on the code host",
"examples": ["3912", "12"]
}
},
"required": ["baseRepository", "externalID"],
"additionalProperties": false
},
{
"properties": {
"baseRepository": {
"type": "string",
"description": "The GraphQL ID of the repository that this changeset spec is proposing to change.",
"examples": ["UmVwb3NpdG9yeTo5Cg=="]
},
"baseRef": {
"type": "string",
"description": "The full name of the Git ref in the base repository that this changeset is based on (and is proposing to be merged into). This ref must exist on the base repository.",
"pattern": "^refs\\/heads\\/\\S+$",
"examples": ["refs/heads/master"]
},
"baseRev": {
"type": "string",
"description": "The base revision this changeset is based on. It is the latest commit in baseRef at the time when the changeset spec was created.",
"examples": ["4095572721c6234cd72013fd49dff4fb48f0f8a4"]
},
"headRepository": {
"type": "string",
"description": "The GraphQL ID of the repository that contains the branch with this changeset's changes. Fork repositories and cross-repository changesets are not yet supported. Therefore, headRepository must be equal to baseRepository.",
"examples": ["UmVwb3NpdG9yeTo5Cg=="]
},
"headRef": {
"type": "string",
"description": "The full name of the Git ref that holds the changes proposed by this changeset. This ref will be created or updated with the commits.",
"pattern": "^refs\\/heads\\/\\S+$",
"examples": ["refs/heads/fix-foo"]
},
"title": { "type": "string", "description": "The title of the changeset on the code host." },
"body": { "type": "string", "description": "The body (description) of the changeset on the code host." },
"commits": {
"type": "array",
"description": "The Git commits with the proposed changes. These commits are pushed to the head ref.",
"minItems": 1,
"maxItems": 1,
"items": {
"title": "GitCommitDescription",
"type": "object",
"description": "The Git commit to create with the changes.",
"additionalProperties": false,
"required": ["message", "diff", "authorName", "authorEmail"],
"properties": {
"message": {
"type": "string",
"description": "The Git commit message."
},
"diff": {
"type": "string",
"description": "The commit diff (in unified diff format)."
},
"authorName": {
"type": "string",
"description": "The Git commit author name."
},
"authorEmail": {
"type": "string",
"format": "email",
"description": "The Git commit author email."
}
}
}
},
"published": {
"oneOf": [{ "type": "boolean" }, { "type": "string", "pattern": "^draft$" }],
"description": "Whether to publish the changeset. An unpublished changeset can be previewed on Sourcegraph by any person who can view the campaign, but its commit, branch, and pull request aren't created on the code host. A published changeset results in a commit, branch, and pull request being created on the code host."
}
},
"required": [
"baseRepository",
"baseRef",
"baseRev",
"headRepository",
"headRef",
"title",
"body",
"commits",
"published"
],
"additionalProperties": false
}
]
}
` | schema/changeset_spec_stringdata.go | 0.765593 | 0.445469 | changeset_spec_stringdata.go | starcoder |
package types
import (
"fmt"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
)
type (
// Commission defines a commission parameters for a given validator.
Commission struct {
CommissionRates
UpdateTime time.Time `json:"update_time"` // the last time the commission rate was changed
}
// CommissionRates defines the initial commission rates to be used for creating a
// validator.
CommissionRates struct {
Rate sdk.Dec `json:"rate"` // the commission rate charged to delegators, as a fraction
MaxRate sdk.Dec `json:"max_rate"` // maximum commission rate which validator can ever charge, as a fraction
MaxChangeRate sdk.Dec `json:"max_change_rate"` // maximum daily increase of the validator commission, as a fraction
}
)
// NewCommissionRates returns an initialized validator commission rates.
func NewCommissionRates(rate, maxRate, maxChangeRate sdk.Dec) CommissionRates {
return CommissionRates{
Rate: rate,
MaxRate: maxRate,
MaxChangeRate: maxChangeRate,
}
}
// NewCommission returns an initialized validator commission.
func NewCommission(rate, maxRate, maxChangeRate sdk.Dec) Commission {
return Commission{
CommissionRates: NewCommissionRates(rate, maxRate, maxChangeRate),
UpdateTime: time.Unix(0, 0).UTC(),
}
}
// NewCommission returns an initialized validator commission with a specified
// update time which should be the current block BFT time.
func NewCommissionWithTime(rate, maxRate, maxChangeRate sdk.Dec, updatedAt time.Time) Commission {
return Commission{
CommissionRates: NewCommissionRates(rate, maxRate, maxChangeRate),
UpdateTime: updatedAt,
}
}
// Equal checks if the given Commission object is equal to the receiving
// Commission object.
func (c Commission) Equal(c2 Commission) bool {
return c.Rate.Equal(c2.Rate) &&
c.MaxRate.Equal(c2.MaxRate) &&
c.MaxChangeRate.Equal(c2.MaxChangeRate) &&
c.UpdateTime.Equal(c2.UpdateTime)
}
// String implements the Stringer interface for a Commission.
func (c Commission) String() string {
return fmt.Sprintf("rate: %s, maxRate: %s, maxChangeRate: %s, updateTime: %s",
c.Rate, c.MaxRate, c.MaxChangeRate, c.UpdateTime,
)
}
// Validate performs basic sanity validation checks of initial commission
// parameters. If validation fails, an SDK error is returned.
func (c CommissionRates) Validate() sdk.Error {
switch {
case c.MaxRate.LT(sdk.ZeroDec()):
// max rate cannot be negative
return ErrCommissionNegative(DefaultCodespace)
case c.MaxRate.GT(sdk.OneDec()):
// max rate cannot be greater than 1
return ErrCommissionHuge(DefaultCodespace)
case c.Rate.LT(sdk.ZeroDec()):
// rate cannot be negative
return ErrCommissionNegative(DefaultCodespace)
case c.Rate.GT(c.MaxRate):
// rate cannot be greater than the max rate
return ErrCommissionGTMaxRate(DefaultCodespace)
case c.MaxChangeRate.LT(sdk.ZeroDec()):
// change rate cannot be negative
return ErrCommissionChangeRateNegative(DefaultCodespace)
case c.MaxChangeRate.GT(c.MaxRate):
// change rate cannot be greater than the max rate
return ErrCommissionChangeRateGTMaxRate(DefaultCodespace)
}
return nil
}
// ValidateNewRate performs basic sanity validation checks of a new commission
// rate. If validation fails, an SDK error is returned.
func (c Commission) ValidateNewRate(newRate sdk.Dec, blockTime time.Time) sdk.Error {
switch {
case blockTime.Sub(c.UpdateTime).Hours() < 24:
// new rate cannot be changed more than once within 24 hours
return ErrCommissionUpdateTime(DefaultCodespace)
case newRate.LT(sdk.ZeroDec()):
// new rate cannot be negative
return ErrCommissionNegative(DefaultCodespace)
case newRate.GT(c.MaxRate):
// new rate cannot be greater than the max rate
return ErrCommissionGTMaxRate(DefaultCodespace)
case newRate.Sub(c.Rate).GT(c.MaxChangeRate):
// new rate % points change cannot be greater than the max change rate
return ErrCommissionGTMaxChangeRate(DefaultCodespace)
}
return nil
} | x/staking/types/commission.go | 0.82011 | 0.530054 | commission.go | starcoder |
package strings
import (
"errors"
"io"
"unicode/utf8"
"unsafe"
)
// A Builder is used to efficiently build a string using Write methods.
// It minimizes memory copying. The zero value is ready to use.
type Builder struct {
buf []byte
}
// String returns the accumulated string.
func (b *Builder) String() string {
return *(*string)(unsafe.Pointer(&b.buf))
}
// Len returns the number of accumulated bytes; b.Len() == len(b.String()).
func (b *Builder) Len() int { return len(b.buf) }
// Reset resets the Builder to be empty.
func (b *Builder) Reset() { b.buf = nil }
const maxInt = int(^uint(0) >> 1)
// grow copies the buffer to a new, larger buffer so that there are at least n
// bytes of capacity beyond len(b.buf).
func (b *Builder) grow(n int) {
buf := make([]byte, len(b.buf), 2*cap(b.buf)+n)
copy(buf, b.buf)
b.buf = buf
}
// Grow grows b's capacity, if necessary, to guarantee space for
// another n bytes. After Grow(n), at least n bytes can be written to b
// without another allocation. If n is negative, Grow panics.
func (b *Builder) Grow(n int) {
if n < 0 {
panic("strings.Builder.Grow: negative count")
}
if cap(b.buf)-len(b.buf) < n {
b.grow(n)
}
}
// Write appends the contents of p to b's buffer.
// Write always returns len(p), nil.
func (b *Builder) Write(p []byte) (int, error) {
b.buf = append(b.buf, p...)
return len(p), nil
}
// WriteByte appends the byte c to b's buffer.
// The returned error is always nil.
func (b *Builder) WriteByte(c byte) error {
b.buf = append(b.buf, c)
return nil
}
// WriteRune appends the UTF-8 encoding of Unicode code point r to b's buffer.
// It returns the length of r and a nil error.
func (b *Builder) WriteRune(r rune) (int, error) {
if r < utf8.RuneSelf {
b.buf = append(b.buf, byte(r))
return 1, nil
}
l := len(b.buf)
if cap(b.buf)-l < utf8.UTFMax {
b.grow(utf8.UTFMax)
}
n := utf8.EncodeRune(b.buf[l:l+utf8.UTFMax], r)
b.buf = b.buf[:l+n]
return n, nil
}
// WriteString appends the contents of s to b's buffer.
// It returns the length of s and a nil error.
func (b *Builder) WriteString(s string) (int, error) {
b.buf = append(b.buf, s...)
return len(s), nil
}
// minRead is the minimum slice passed to a Read call by Builder.ReadFrom.
// It is the same as bytes.MinRead.
const minRead = 512
// errNegativeRead is the panic value if the reader passed to Builder.ReadFrom
// returns a negative count.
var errNegativeRead = errors.New("strings.Builder: reader returned negative count from Read")
// ReadFrom reads data from r until EOF and appends it to b's buffer.
// The return value n is the number of bytes read.
// Any error except io.EOF encountered during the read is also returned.
func (b *Builder) ReadFrom(r io.Reader) (n int64, err error) {
for {
l := len(b.buf)
if cap(b.buf)-l < minRead {
b.grow(minRead)
}
m, e := r.Read(b.buf[l:cap(b.buf)])
if m < 0 {
panic(errNegativeRead)
}
b.buf = b.buf[:l+m]
n += int64(m)
if e == io.EOF {
return n, nil
}
if e != nil {
return n, e
}
}
} | src/strings/builder.go | 0.698124 | 0.426919 | builder.go | starcoder |
package iso20022
// Chain of parties involved in the settlement of a transaction, including receipts and deliveries, book transfers, treasury deals, or other activities, resulting in the movement of a security or amount of money from one account to another.
type SettlementParties23 struct {
// First party in the settlement chain. In a plain vanilla settlement, it is the Central Securities Depository where the counterparty requests to receive the financial instrument or from where the counterparty delivers the financial instruments.
Depository *PartyIdentification55 `xml:"Dpstry,omitempty"`
// Party that, in a settlement chain interacts with the depository.
Party1 *PartyIdentificationAndAccount34 `xml:"Pty1,omitempty"`
// Party that, in a settlement chain interacts with the party 1.
Party2 *PartyIdentificationAndAccount34 `xml:"Pty2,omitempty"`
// Party that, in a settlement chain interacts with the party 2.
Party3 *PartyIdentificationAndAccount34 `xml:"Pty3,omitempty"`
// Party that, in a settlement chain interacts with the party 3.
Party4 *PartyIdentificationAndAccount34 `xml:"Pty4,omitempty"`
// Party that, in a settlement chain interacts with the party 4.
Party5 *PartyIdentificationAndAccount34 `xml:"Pty5,omitempty"`
}
func (s *SettlementParties23) AddDepository() *PartyIdentification55 {
s.Depository = new(PartyIdentification55)
return s.Depository
}
func (s *SettlementParties23) AddParty1() *PartyIdentificationAndAccount34 {
s.Party1 = new(PartyIdentificationAndAccount34)
return s.Party1
}
func (s *SettlementParties23) AddParty2() *PartyIdentificationAndAccount34 {
s.Party2 = new(PartyIdentificationAndAccount34)
return s.Party2
}
func (s *SettlementParties23) AddParty3() *PartyIdentificationAndAccount34 {
s.Party3 = new(PartyIdentificationAndAccount34)
return s.Party3
}
func (s *SettlementParties23) AddParty4() *PartyIdentificationAndAccount34 {
s.Party4 = new(PartyIdentificationAndAccount34)
return s.Party4
}
func (s *SettlementParties23) AddParty5() *PartyIdentificationAndAccount34 {
s.Party5 = new(PartyIdentificationAndAccount34)
return s.Party5
} | SettlementParties23.go | 0.680985 | 0.528716 | SettlementParties23.go | starcoder |
package asciitable
import (
"bytes"
"fmt"
"strings"
"text/tabwriter"
)
// column represents a column in the table. Contains the maximum width of the
// column as well as the title.
type column struct {
width int
title string
}
// Table holds tabular values in a rows and columns format.
type Table struct {
columns []column
rows [][]string
}
// MakeTable creates a new instance of the table with given column names.
func MakeTable(headers []string) Table {
t := MakeHeadlessTable(len(headers))
for i := range t.columns {
t.columns[i].title = headers[i]
t.columns[i].width = len(headers[i])
}
return t
}
// MakeTable creates a new instance of the table without any column names.
// The number of columns is required.
func MakeHeadlessTable(columnCount int) Table {
return Table{
columns: make([]column, columnCount),
rows: make([][]string, 0),
}
}
// AddRow adds a row of cells to the table.
func (t *Table) AddRow(row []string) {
limit := min(len(row), len(t.columns))
for i := 0; i < limit; i++ {
cellWidth := len(row[i])
t.columns[i].width = max(cellWidth, t.columns[i].width)
}
t.rows = append(t.rows, row[:limit])
}
// AsBuffer returns a *bytes.Buffer with the printed output of the table.
func (t *Table) AsBuffer() *bytes.Buffer {
var buffer bytes.Buffer
writer := tabwriter.NewWriter(&buffer, 5, 0, 1, ' ', 0)
template := strings.Repeat("%v\t", len(t.columns))
// Header and separator.
if !t.IsHeadless() {
var colh []interface{}
var cols []interface{}
for _, col := range t.columns {
colh = append(colh, col.title)
cols = append(cols, strings.Repeat("-", col.width))
}
fmt.Fprintf(writer, template+"\n", colh...)
fmt.Fprintf(writer, template+"\n", cols...)
}
// Body.
for _, row := range t.rows {
var rowi []interface{}
for _, cell := range row {
rowi = append(rowi, cell)
}
fmt.Fprintf(writer, template+"\n", rowi...)
}
writer.Flush()
return &buffer
}
// IsHeadless returns true if none of the table title cells contains any text.
func (t *Table) IsHeadless() bool {
total := 0
for i := range t.columns {
total += len(t.columns[i].title)
}
return total == 0
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
} | lib/asciitable/table.go | 0.642993 | 0.418637 | table.go | starcoder |
package clui
import (
"fmt"
xs "github.com/huandu/xstrings"
term "github.com/nsf/termbox-go"
"sync/atomic"
)
// BarData is info about one bar in the chart. Every
// bar can be customized by setting its own colors and
// rune to draw the bar. Use ColorDefault for Fg and Bg,
// and 0 for Ch to draw with BarChart defaults
type BarData struct {
Value float64
Title string
Fg term.Attribute
Bg term.Attribute
Ch rune
}
// BarDataCell is used in callback to user to draw with
// customized colors and runes
type BarDataCell struct {
// Title of the bar
Item string
// order number of the bar
ID int
// value of the bar that is currently drawn
Value float64
// maximum value of the bar
BarMax float64
// value of the highest bar
TotalMax float64
// Default attributes and rune to draw the bar
Fg term.Attribute
Bg term.Attribute
Ch rune
}
/*
BarChart is a chart that represents grouped data with
rectangular bars. It can be monochrome - defaut behavior.
One can assign individual color to each bar and even use
custom drawn bars to display multicolored bars depending
on bar value.
All bars have the same width: either constant BarSize - in
case of AutoSize is false, or automatically calculated but
cannot be less than BarSize. Bars that do not fit the chart
area are not displayed.
BarChart displays vertical axis with values on the chart left
if ValueWidth greater than 0, horizontal axis with bar titles
if ShowTitles is true (to enable displaying marks on horizontal
axis, set ShowMarks to true), and chart legend on the right if
LegendWidth is greater than 3.
If LegendWidth is greater than half of the chart it is not
displayed. The same is applied to ValueWidth
*/
type BarChart struct {
BaseControl
data []BarData
autosize bool
gap int32
barWidth int32
legendWidth int32
valueWidth int32
showMarks bool
showTitles bool
onDrawCell func(*BarDataCell)
}
/*
NewBarChart creates a new bar chart.
view - is a View that manages the control
parent - is container that keeps the control. The same View can be a view and a parent at the same time.
w and h - are minimal size of the control.
scale - the way of scaling the control when the parent is resized. Use DoNotScale constant if the
control should keep its original size.
*/
func CreateBarChart(parent Control, w, h int, scale int) *BarChart {
c := new(BarChart)
c.BaseControl = NewBaseControl()
if w == AutoSize {
w = 10
}
if h == AutoSize {
h = 5
}
c.parent = parent
c.SetSize(w, h)
c.SetConstraints(w, h)
c.tabSkip = true
c.showTitles = true
c.barWidth = 3
c.data = make([]BarData, 0)
c.SetScale(scale)
if parent != nil {
parent.AddChild(c)
}
return c
}
// Repaint draws the control on its View surface
func (b *BarChart) Draw() {
if b.hidden {
return
}
b.mtx.RLock()
defer b.mtx.RUnlock()
PushAttributes()
defer PopAttributes()
fg, bg := RealColor(b.fg, b.Style(), ColorBarChartText), RealColor(b.bg, b.Style(), ColorBarChartBack)
SetTextColor(fg)
SetBackColor(bg)
FillRect(b.x, b.y, b.width, b.height, ' ')
if len(b.data) == 0 {
return
}
b.drawRulers()
b.drawValues()
b.drawLegend()
b.drawBars()
}
func (b *BarChart) barHeight() int {
if b.showTitles {
return b.height - 2
}
return b.height
}
func (b *BarChart) drawBars() {
if len(b.data) == 0 {
return
}
start, width := b.calculateBarArea()
if width < 2 {
return
}
barW := b.calculateBarWidth()
if barW == 0 {
return
}
coeff, max := b.calculateMultiplier()
if coeff == 0.0 {
return
}
PushAttributes()
defer PopAttributes()
h := b.barHeight()
pos := start
parts := []rune(SysObject(ObjBarChart))
fg, bg := TextColor(), BackColor()
for idx, d := range b.data {
if pos+barW > start+width {
break
}
fColor, bColor := d.Fg, d.Bg
ch := d.Ch
if fColor == ColorDefault {
fColor = fg
}
if bColor == ColorDefault {
bColor = bg
}
if ch == 0 {
ch = parts[0]
}
barH := int(d.Value * coeff)
if b.onDrawCell == nil {
SetTextColor(fColor)
SetBackColor(bColor)
FillRect(b.x+pos, b.y+h-barH, barW, barH, ch)
} else {
cellDef := BarDataCell{Item: d.Title, ID: idx,
Value: 0, BarMax: d.Value, TotalMax: max,
Fg: fColor, Bg: bColor, Ch: ch}
for dy := 0; dy < barH; dy++ {
req := cellDef
req.Value = max * float64(dy+1) / float64(h)
b.onDrawCell(&req)
SetTextColor(req.Fg)
SetBackColor(req.Bg)
for dx := 0; dx < barW; dx++ {
PutChar(b.x+pos+dx, b.y+h-1-dy, req.Ch)
}
}
}
if b.showTitles {
SetTextColor(fg)
SetBackColor(bg)
if b.showMarks {
c := parts[7]
PutChar(b.x+pos+barW/2, b.y+h, c)
}
var s string
shift := 0
if xs.Len(d.Title) > barW {
s = CutText(d.Title, barW)
} else {
shift, s = AlignText(d.Title, barW, AlignCenter)
}
DrawRawText(b.x+pos+shift, b.y+h+1, s)
}
pos += barW + int(b.BarGap())
}
}
func (b *BarChart) drawLegend() {
pos, width := b.calculateBarArea()
if pos+width >= b.width-3 {
return
}
PushAttributes()
defer PopAttributes()
fg, bg := RealColor(b.fg, b.Style(), ColorBarChartText), RealColor(b.bg, b.Style(), ColorBarChartBack)
parts := []rune(SysObject(ObjBarChart))
defRune := parts[0]
for idx, d := range b.data {
if idx >= b.height {
break
}
c := d.Ch
if c == 0 {
c = defRune
}
SetTextColor(d.Fg)
SetBackColor(d.Bg)
PutChar(b.x+pos+width, b.y+idx, c)
s := CutText(fmt.Sprintf(" - %v", d.Title), int(b.LegendWidth()))
SetTextColor(fg)
SetBackColor(bg)
DrawRawText(b.x+pos+width+1, b.y+idx, s)
}
}
func (b *BarChart) drawValues() {
valVal := int(b.ValueWidth())
if valVal <= 0 {
return
}
pos, _ := b.calculateBarArea()
if pos == 0 {
return
}
h := b.barHeight()
coeff, max := b.calculateMultiplier()
if max == coeff {
return
}
dy := 0
format := fmt.Sprintf("%%%v.2f", valVal)
for dy < h-1 {
v := float64(h-dy) / float64(h) * max
s := fmt.Sprintf(format, v)
s = CutText(s, valVal)
DrawRawText(b.x, b.y+dy, s)
dy += 2
}
}
func (b *BarChart) drawRulers() {
if int(b.ValueWidth()) <= 0 && int(b.LegendWidth()) <= 0 && !b.showTitles {
return
}
pos, vWidth := b.calculateBarArea()
parts := []rune(SysObject(ObjBarChart))
h := b.barHeight()
if pos > 0 {
pos--
vWidth++
}
// horizontal and vertical lines, corner
cH, cV, cC := parts[1], parts[2], parts[5]
if pos > 0 {
for dy := 0; dy < h; dy++ {
PutChar(b.x+pos, b.y+dy, cV)
}
}
if b.showTitles {
for dx := 0; dx < vWidth; dx++ {
PutChar(b.x+pos+dx, b.y+h, cH)
}
}
if pos > 0 && b.showTitles {
PutChar(b.x+pos, b.y+h, cC)
}
}
func (b *BarChart) calculateBarArea() (int, int) {
w := b.width
pos := 0
valVal := int(b.ValueWidth())
if valVal < w/2 {
w = w - valVal - 1
pos = valVal + 1
}
legVal := int(b.LegendWidth())
if legVal < w/2 {
w -= legVal
}
return pos, w
}
func (b *BarChart) calculateBarWidth() int {
if len(b.data) == 0 {
return 0
}
if !b.autosize {
return int(b.MinBarWidth())
}
w := b.width
legVal := int(b.LegendWidth())
valVal := int(b.ValueWidth())
if valVal < w/2 {
w = w - valVal - 1
}
if legVal < w/2 {
w -= legVal
}
dataCount := len(b.data)
gapVal := int(b.BarGap())
barVal := int(b.MinBarWidth())
minSize := dataCount*barVal + (dataCount-1)*gapVal
if minSize >= w {
return barVal
}
sz := (w - (dataCount-1)*gapVal) / dataCount
if sz == 0 {
sz = 1
}
return sz
}
func (b *BarChart) calculateMultiplier() (float64, float64) {
if len(b.data) == 0 {
return 0, 0
}
h := b.barHeight()
if h <= 1 {
return 0, 0
}
max := b.data[0].Value
for _, val := range b.data {
if val.Value > max {
max = val.Value
}
}
if max == 0 {
return 0, 0
}
return float64(h) / max, max
}
// AddData appends a new bar to a chart
func (b *BarChart) AddData(val BarData) {
b.mtx.Lock()
defer b.mtx.Unlock()
b.data = append(b.data, val)
}
// ClearData removes all bar from chart
func (b *BarChart) ClearData() {
b.mtx.Lock()
defer b.mtx.Unlock()
b.data = make([]BarData, 0)
}
// SetData assign a new bar list to a chart
func (b *BarChart) SetData(data []BarData) {
b.mtx.Lock()
defer b.mtx.Unlock()
b.data = make([]BarData, len(data))
copy(b.data, data)
}
// AutoSize returns whether automatic bar width
// calculation is on. If AutoSize is false then all
// bars have width BarWidth. If AutoSize is true then
// bar width is the maximum of three values: BarWidth,
// calculated width that makes all bars fit the
// bar chart area, and 1
func (b *BarChart) AutoSize() bool {
return b.autosize
}
// SetAutoSize enables or disables automatic bar
// width calculation
func (b *BarChart) SetAutoSize(auto bool) {
b.mtx.Lock()
defer b.mtx.Unlock()
b.autosize = auto
}
// Gap returns width of visual gap between two adjacent bars
func (b *BarChart) BarGap() int32 {
return atomic.LoadInt32(&b.gap)
}
// SetGap sets the space width between two adjacent bars
func (b *BarChart) SetBarGap(gap int32) {
atomic.StoreInt32(&b.gap, gap)
}
// MinBarWidth returns current minimal bar width
func (b *BarChart) MinBarWidth() int32 {
return atomic.LoadInt32(&b.barWidth)
}
// SetMinBarWidth changes the minimal bar width
func (b *BarChart) SetMinBarWidth(size int32) {
atomic.StoreInt32(&b.barWidth, size)
}
// ValueWidth returns the width of the area at the left of
// chart used to draw values. Set it to 0 to turn off the
// value panel
func (b *BarChart) ValueWidth() int32 {
return atomic.LoadInt32(&b.valueWidth)
}
// SetValueWidth changes width of the value panel on the left
func (b *BarChart) SetValueWidth(width int32) {
atomic.StoreInt32(&b.valueWidth, width)
}
// ShowTitles returns if chart displays horizontal axis and
// bar titles under it
func (b *BarChart) ShowTitles() bool {
return b.showTitles
}
// SetShowTitles turns on and off horizontal axis and bar titles
func (b *BarChart) SetShowTitles(show bool) {
b.mtx.Lock()
defer b.mtx.Unlock()
b.showTitles = show
}
// LegendWidth returns width of chart legend displayed at the
// right side of the chart. Set it to 0 to disable legend
func (b *BarChart) LegendWidth() int32 {
return atomic.LoadInt32(&b.legendWidth)
}
// SetLegendWidth sets new legend panel width
func (b *BarChart) SetLegendWidth(width int32) {
atomic.StoreInt32(&b.legendWidth, width)
}
// OnDrawCell sets callback that allows to draw multicolored
// bars. BarChart sends the current attrubutes and rune that
// it is going to use to display as well as the current value
// of the bar. A user can change the values of BarDataCell
// depending on some external data or calculations - only
// changing colors and rune makes sense. Changing anything else
// does not affect the chart
func (b *BarChart) OnDrawCell(fn func(*BarDataCell)) {
b.mtx.Lock()
defer b.mtx.Unlock()
b.onDrawCell = fn
}
// ShowMarks returns if horizontal axis has mark under each
// bar. To show marks, ShowTitles must be enabled.
func (b *BarChart) ShowMarks() bool {
return b.showMarks
}
// SetShowMarks turns on and off marks under horizontal axis
func (b *BarChart) SetShowMarks(show bool) {
b.mtx.Lock()
defer b.mtx.Unlock()
b.showMarks = show
} | barchart.go | 0.622345 | 0.48688 | barchart.go | starcoder |
package onshape
import (
"encoding/json"
)
// BTPProcedureDeclarationBase266 struct for BTPProcedureDeclarationBase266
type BTPProcedureDeclarationBase266 struct {
BTPTopLevelNode286
BtType *string `json:"btType,omitempty"`
Arguments *[]BTPArgumentDeclaration232 `json:"arguments,omitempty"`
Body *BTPStatementBlock271 `json:"body,omitempty"`
Precondition *BTPStatement269 `json:"precondition,omitempty"`
ReturnType *BTPTypeName290 `json:"returnType,omitempty"`
SpaceAfterArglist *BTPSpace10 `json:"spaceAfterArglist,omitempty"`
SpaceInEmptyList *BTPSpace10 `json:"spaceInEmptyList,omitempty"`
}
// NewBTPProcedureDeclarationBase266 instantiates a new BTPProcedureDeclarationBase266 object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewBTPProcedureDeclarationBase266() *BTPProcedureDeclarationBase266 {
this := BTPProcedureDeclarationBase266{}
return &this
}
// NewBTPProcedureDeclarationBase266WithDefaults instantiates a new BTPProcedureDeclarationBase266 object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewBTPProcedureDeclarationBase266WithDefaults() *BTPProcedureDeclarationBase266 {
this := BTPProcedureDeclarationBase266{}
return &this
}
// GetBtType returns the BtType field value if set, zero value otherwise.
func (o *BTPProcedureDeclarationBase266) GetBtType() string {
if o == nil || o.BtType == nil {
var ret string
return ret
}
return *o.BtType
}
// GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPProcedureDeclarationBase266) GetBtTypeOk() (*string, bool) {
if o == nil || o.BtType == nil {
return nil, false
}
return o.BtType, true
}
// HasBtType returns a boolean if a field has been set.
func (o *BTPProcedureDeclarationBase266) HasBtType() bool {
if o != nil && o.BtType != nil {
return true
}
return false
}
// SetBtType gets a reference to the given string and assigns it to the BtType field.
func (o *BTPProcedureDeclarationBase266) SetBtType(v string) {
o.BtType = &v
}
// GetArguments returns the Arguments field value if set, zero value otherwise.
func (o *BTPProcedureDeclarationBase266) GetArguments() []BTPArgumentDeclaration232 {
if o == nil || o.Arguments == nil {
var ret []BTPArgumentDeclaration232
return ret
}
return *o.Arguments
}
// GetArgumentsOk returns a tuple with the Arguments field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPProcedureDeclarationBase266) GetArgumentsOk() (*[]BTPArgumentDeclaration232, bool) {
if o == nil || o.Arguments == nil {
return nil, false
}
return o.Arguments, true
}
// HasArguments returns a boolean if a field has been set.
func (o *BTPProcedureDeclarationBase266) HasArguments() bool {
if o != nil && o.Arguments != nil {
return true
}
return false
}
// SetArguments gets a reference to the given []BTPArgumentDeclaration232 and assigns it to the Arguments field.
func (o *BTPProcedureDeclarationBase266) SetArguments(v []BTPArgumentDeclaration232) {
o.Arguments = &v
}
// GetBody returns the Body field value if set, zero value otherwise.
func (o *BTPProcedureDeclarationBase266) GetBody() BTPStatementBlock271 {
if o == nil || o.Body == nil {
var ret BTPStatementBlock271
return ret
}
return *o.Body
}
// GetBodyOk returns a tuple with the Body field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPProcedureDeclarationBase266) GetBodyOk() (*BTPStatementBlock271, bool) {
if o == nil || o.Body == nil {
return nil, false
}
return o.Body, true
}
// HasBody returns a boolean if a field has been set.
func (o *BTPProcedureDeclarationBase266) HasBody() bool {
if o != nil && o.Body != nil {
return true
}
return false
}
// SetBody gets a reference to the given BTPStatementBlock271 and assigns it to the Body field.
func (o *BTPProcedureDeclarationBase266) SetBody(v BTPStatementBlock271) {
o.Body = &v
}
// GetPrecondition returns the Precondition field value if set, zero value otherwise.
func (o *BTPProcedureDeclarationBase266) GetPrecondition() BTPStatement269 {
if o == nil || o.Precondition == nil {
var ret BTPStatement269
return ret
}
return *o.Precondition
}
// GetPreconditionOk returns a tuple with the Precondition field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPProcedureDeclarationBase266) GetPreconditionOk() (*BTPStatement269, bool) {
if o == nil || o.Precondition == nil {
return nil, false
}
return o.Precondition, true
}
// HasPrecondition returns a boolean if a field has been set.
func (o *BTPProcedureDeclarationBase266) HasPrecondition() bool {
if o != nil && o.Precondition != nil {
return true
}
return false
}
// SetPrecondition gets a reference to the given BTPStatement269 and assigns it to the Precondition field.
func (o *BTPProcedureDeclarationBase266) SetPrecondition(v BTPStatement269) {
o.Precondition = &v
}
// GetReturnType returns the ReturnType field value if set, zero value otherwise.
func (o *BTPProcedureDeclarationBase266) GetReturnType() BTPTypeName290 {
if o == nil || o.ReturnType == nil {
var ret BTPTypeName290
return ret
}
return *o.ReturnType
}
// GetReturnTypeOk returns a tuple with the ReturnType field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPProcedureDeclarationBase266) GetReturnTypeOk() (*BTPTypeName290, bool) {
if o == nil || o.ReturnType == nil {
return nil, false
}
return o.ReturnType, true
}
// HasReturnType returns a boolean if a field has been set.
func (o *BTPProcedureDeclarationBase266) HasReturnType() bool {
if o != nil && o.ReturnType != nil {
return true
}
return false
}
// SetReturnType gets a reference to the given BTPTypeName290 and assigns it to the ReturnType field.
func (o *BTPProcedureDeclarationBase266) SetReturnType(v BTPTypeName290) {
o.ReturnType = &v
}
// GetSpaceAfterArglist returns the SpaceAfterArglist field value if set, zero value otherwise.
func (o *BTPProcedureDeclarationBase266) GetSpaceAfterArglist() BTPSpace10 {
if o == nil || o.SpaceAfterArglist == nil {
var ret BTPSpace10
return ret
}
return *o.SpaceAfterArglist
}
// GetSpaceAfterArglistOk returns a tuple with the SpaceAfterArglist field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPProcedureDeclarationBase266) GetSpaceAfterArglistOk() (*BTPSpace10, bool) {
if o == nil || o.SpaceAfterArglist == nil {
return nil, false
}
return o.SpaceAfterArglist, true
}
// HasSpaceAfterArglist returns a boolean if a field has been set.
func (o *BTPProcedureDeclarationBase266) HasSpaceAfterArglist() bool {
if o != nil && o.SpaceAfterArglist != nil {
return true
}
return false
}
// SetSpaceAfterArglist gets a reference to the given BTPSpace10 and assigns it to the SpaceAfterArglist field.
func (o *BTPProcedureDeclarationBase266) SetSpaceAfterArglist(v BTPSpace10) {
o.SpaceAfterArglist = &v
}
// GetSpaceInEmptyList returns the SpaceInEmptyList field value if set, zero value otherwise.
func (o *BTPProcedureDeclarationBase266) GetSpaceInEmptyList() BTPSpace10 {
if o == nil || o.SpaceInEmptyList == nil {
var ret BTPSpace10
return ret
}
return *o.SpaceInEmptyList
}
// GetSpaceInEmptyListOk returns a tuple with the SpaceInEmptyList field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPProcedureDeclarationBase266) GetSpaceInEmptyListOk() (*BTPSpace10, bool) {
if o == nil || o.SpaceInEmptyList == nil {
return nil, false
}
return o.SpaceInEmptyList, true
}
// HasSpaceInEmptyList returns a boolean if a field has been set.
func (o *BTPProcedureDeclarationBase266) HasSpaceInEmptyList() bool {
if o != nil && o.SpaceInEmptyList != nil {
return true
}
return false
}
// SetSpaceInEmptyList gets a reference to the given BTPSpace10 and assigns it to the SpaceInEmptyList field.
func (o *BTPProcedureDeclarationBase266) SetSpaceInEmptyList(v BTPSpace10) {
o.SpaceInEmptyList = &v
}
func (o BTPProcedureDeclarationBase266) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
serializedBTPTopLevelNode286, errBTPTopLevelNode286 := json.Marshal(o.BTPTopLevelNode286)
if errBTPTopLevelNode286 != nil {
return []byte{}, errBTPTopLevelNode286
}
errBTPTopLevelNode286 = json.Unmarshal([]byte(serializedBTPTopLevelNode286), &toSerialize)
if errBTPTopLevelNode286 != nil {
return []byte{}, errBTPTopLevelNode286
}
if o.BtType != nil {
toSerialize["btType"] = o.BtType
}
if o.Arguments != nil {
toSerialize["arguments"] = o.Arguments
}
if o.Body != nil {
toSerialize["body"] = o.Body
}
if o.Precondition != nil {
toSerialize["precondition"] = o.Precondition
}
if o.ReturnType != nil {
toSerialize["returnType"] = o.ReturnType
}
if o.SpaceAfterArglist != nil {
toSerialize["spaceAfterArglist"] = o.SpaceAfterArglist
}
if o.SpaceInEmptyList != nil {
toSerialize["spaceInEmptyList"] = o.SpaceInEmptyList
}
return json.Marshal(toSerialize)
}
type NullableBTPProcedureDeclarationBase266 struct {
value *BTPProcedureDeclarationBase266
isSet bool
}
func (v NullableBTPProcedureDeclarationBase266) Get() *BTPProcedureDeclarationBase266 {
return v.value
}
func (v *NullableBTPProcedureDeclarationBase266) Set(val *BTPProcedureDeclarationBase266) {
v.value = val
v.isSet = true
}
func (v NullableBTPProcedureDeclarationBase266) IsSet() bool {
return v.isSet
}
func (v *NullableBTPProcedureDeclarationBase266) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableBTPProcedureDeclarationBase266(val *BTPProcedureDeclarationBase266) *NullableBTPProcedureDeclarationBase266 {
return &NullableBTPProcedureDeclarationBase266{value: val, isSet: true}
}
func (v NullableBTPProcedureDeclarationBase266) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableBTPProcedureDeclarationBase266) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | onshape/model_btp_procedure_declaration_base_266.go | 0.746324 | 0.515681 | model_btp_procedure_declaration_base_266.go | starcoder |
package test
import (
"fmt"
"image"
"image/png"
"os"
"path/filepath"
"testing"
"time"
"github.com/jesseduffield/fyne"
"github.com/jesseduffield/fyne/driver/desktop"
"github.com/jesseduffield/fyne/internal/cache"
"github.com/jesseduffield/fyne/internal/driver"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// AssertCanvasTappableAt asserts that the canvas is tappable at the given position.
func AssertCanvasTappableAt(t *testing.T, c fyne.Canvas, pos fyne.Position) bool {
if o, _ := findTappable(c, pos); o == nil {
t.Errorf("No tappable found at %#v", pos)
return false
}
return true
}
// AssertImageMatches asserts that the given image is the same as the one stored in the master file.
// The master filename is relative to the `testdata` directory which is relative to the test.
// The test `t` fails if the given image is not equal to the loaded master image.
// In this case the given image is written into a file in `testdata/failed/<masterFilename>` (relative to the test).
// This path is also reported, thus the file can be used as new master.
func AssertImageMatches(t *testing.T, masterFilename string, img image.Image, msgAndArgs ...interface{}) bool {
wd, err := os.Getwd()
require.NoError(t, err)
masterPath := filepath.Join(wd, "testdata", masterFilename)
failedPath := filepath.Join(wd, "testdata/failed", masterFilename)
_, err = os.Stat(masterPath)
if os.IsNotExist(err) {
require.NoError(t, writeImage(failedPath, img))
t.Errorf("Master not found at %s. Image written to %s might be used as master.", masterPath, failedPath)
return false
}
file, err := os.Open(masterPath)
require.NoError(t, err)
defer file.Close()
raw, _, err := image.Decode(file)
require.NoError(t, err)
masterPix := pixelsForImage(t, raw) // let's just compare the pixels directly
capturePix := pixelsForImage(t, img)
var msg string
if len(msgAndArgs) > 0 {
msg = fmt.Sprintf(msgAndArgs[0].(string)+"\n", msgAndArgs[1:]...)
}
if !assert.Equal(t, masterPix, capturePix, "%sImage did not match master. Actual image written to file://%s.", msg, failedPath) {
require.NoError(t, writeImage(failedPath, img))
return false
}
return true
}
// Drag drags at an absolute position on the canvas.
// deltaX/Y is the dragging distance: <0 for dragging up/left, >0 for dragging down/right.
func Drag(c fyne.Canvas, pos fyne.Position, deltaX, deltaY int) {
matches := func(object fyne.CanvasObject) bool {
if _, ok := object.(fyne.Draggable); ok {
return true
}
return false
}
o, p, _ := driver.FindObjectAtPositionMatching(pos, matches, c.Overlays().Top(), c.Content())
if o == nil {
return
}
e := &fyne.DragEvent{
PointEvent: fyne.PointEvent{Position: p},
DraggedX: deltaX,
DraggedY: deltaY,
}
o.(fyne.Draggable).Dragged(e)
o.(fyne.Draggable).DragEnd()
}
// MoveMouse simulates a mouse movement to the given position.
func MoveMouse(c fyne.Canvas, pos fyne.Position) {
if fyne.CurrentDevice().IsMobile() {
return
}
tc, _ := c.(*testCanvas)
var oldHovered, hovered desktop.Hoverable
if tc != nil {
oldHovered = tc.hovered
}
matches := func(object fyne.CanvasObject) bool {
if _, ok := object.(desktop.Hoverable); ok {
return true
}
return false
}
o, p, _ := driver.FindObjectAtPositionMatching(pos, matches, c.Overlays().Top(), c.Content())
if o != nil {
hovered = o.(desktop.Hoverable)
me := &desktop.MouseEvent{
PointEvent: fyne.PointEvent{
AbsolutePosition: pos,
Position: p,
},
}
if hovered == oldHovered {
hovered.MouseMoved(me)
} else {
if oldHovered != nil {
oldHovered.MouseOut()
}
hovered.MouseIn(me)
}
} else if oldHovered != nil {
oldHovered.MouseOut()
}
if tc != nil {
tc.hovered = hovered
}
}
// Scroll scrolls at an absolute position on the canvas.
// deltaX/Y is the scrolling distance: <0 for scrolling up/left, >0 for scrolling down/right.
func Scroll(c fyne.Canvas, pos fyne.Position, deltaX, deltaY int) {
matches := func(object fyne.CanvasObject) bool {
if _, ok := object.(fyne.Scrollable); ok {
return true
}
return false
}
o, _, _ := driver.FindObjectAtPositionMatching(pos, matches, c.Overlays().Top(), c.Content())
if o == nil {
return
}
e := &fyne.ScrollEvent{DeltaX: deltaX, DeltaY: deltaY}
o.(fyne.Scrollable).Scrolled(e)
}
// Tap simulates a left mouse click on the specified object.
func Tap(obj fyne.Tappable) {
TapAt(obj, fyne.NewPos(1, 1))
}
// TapAt simulates a left mouse click on the passed object at a specified place within it.
func TapAt(obj fyne.Tappable, pos fyne.Position) {
ev, c := prepareTap(obj, pos)
tap(c, obj, ev)
}
// TapCanvas taps at an absolute position on the canvas.
func TapCanvas(c fyne.Canvas, pos fyne.Position) {
if o, p := findTappable(c, pos); o != nil {
tap(c, o.(fyne.Tappable), &fyne.PointEvent{AbsolutePosition: pos, Position: p})
}
}
// TapSecondary simulates a right mouse click on the specified object.
func TapSecondary(obj fyne.SecondaryTappable) {
TapSecondaryAt(obj, fyne.NewPos(1, 1))
}
// TapSecondaryAt simulates a right mouse click on the passed object at a specified place within it.
func TapSecondaryAt(obj fyne.SecondaryTappable, pos fyne.Position) {
ev, c := prepareTap(obj, pos)
handleFocusOnTap(c, obj)
obj.TappedSecondary(ev)
}
// Type performs a series of key events to simulate typing of a value into the specified object.
// The focusable object will be focused before typing begins.
// The chars parameter will be input one rune at a time to the focused object.
func Type(obj fyne.Focusable, chars string) {
obj.FocusGained()
typeChars([]rune(chars), obj.TypedRune)
}
// TypeOnCanvas is like the Type function but it passes the key events to the canvas object
// rather than a focusable widget.
func TypeOnCanvas(c fyne.Canvas, chars string) {
typeChars([]rune(chars), c.OnTypedRune())
}
// ApplyTheme sets the given theme and waits for it to be applied to the current app.
func ApplyTheme(t *testing.T, theme fyne.Theme) {
require.IsType(t, &testApp{}, fyne.CurrentApp())
a := fyne.CurrentApp().(*testApp)
a.Settings().SetTheme(theme)
for a.lastAppliedTheme() != theme {
time.Sleep(1 * time.Millisecond)
}
}
// WidgetRenderer allows test scripts to gain access to the current renderer for a widget.
// This can be used for verifying correctness of rendered components for a widget in unit tests.
func WidgetRenderer(wid fyne.Widget) fyne.WidgetRenderer {
return cache.Renderer(wid)
}
// WithTestTheme runs a function with the testTheme temporarily set.
func WithTestTheme(t *testing.T, f func()) {
settings := fyne.CurrentApp().Settings()
current := settings.Theme()
ApplyTheme(t, NewTheme())
defer ApplyTheme(t, current)
f()
}
func findTappable(c fyne.Canvas, pos fyne.Position) (o fyne.CanvasObject, p fyne.Position) {
matches := func(object fyne.CanvasObject) bool {
if _, ok := object.(fyne.Tappable); ok {
return true
}
return false
}
o, p, _ = driver.FindObjectAtPositionMatching(pos, matches, c.Overlays().Top(), c.Content())
return
}
func prepareTap(obj interface{}, pos fyne.Position) (*fyne.PointEvent, fyne.Canvas) {
d := fyne.CurrentApp().Driver()
ev := &fyne.PointEvent{Position: pos}
var c fyne.Canvas
if co, ok := obj.(fyne.CanvasObject); ok {
c = d.CanvasForObject(co)
ev.AbsolutePosition = d.AbsolutePositionForObject(co).Add(pos)
}
return ev, c
}
func tap(c fyne.Canvas, obj fyne.Tappable, ev *fyne.PointEvent) {
handleFocusOnTap(c, obj)
obj.Tapped(ev)
}
func handleFocusOnTap(c fyne.Canvas, obj interface{}) {
if c == nil {
return
}
unfocus := true
if focus, ok := obj.(fyne.Focusable); ok {
if dis, ok := obj.(fyne.Disableable); !ok || !dis.Disabled() {
unfocus = false
if focus != c.Focused() {
c.Focus(focus)
}
}
}
if unfocus {
c.Unfocus()
}
}
func pixelsForImage(t *testing.T, img image.Image) []uint8 {
var pix []uint8
if data, ok := img.(*image.RGBA); ok {
pix = data.Pix
} else if data, ok := img.(*image.NRGBA); ok {
pix = data.Pix
}
if pix == nil {
t.Error("Master image is unsupported type")
}
return pix
}
func typeChars(chars []rune, keyDown func(rune)) {
for _, char := range chars {
keyDown(char)
}
}
func writeImage(path string, img image.Image) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
f, err := os.Create(path)
if err != nil {
return err
}
if err = png.Encode(f, img); err != nil {
f.Close()
return err
}
return f.Close()
} | test/util.go | 0.671901 | 0.448064 | util.go | starcoder |
// Package sortutil provides utilities supplementing the standard 'sort' package.
package sortutil
import "sort"
// ByteSlice attaches the methods of sort.Interface to []byte, sorting in increasing order.
type ByteSlice []byte
func (s ByteSlice) Len() int { return len(s) }
func (s ByteSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s ByteSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s ByteSlice) Sort() {
sort.Sort(s)
}
// SearchBytes searches for x in a sorted slice of bytes and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchBytes(a []byte, x byte) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Float32Slice attaches the methods of sort.Interface to []float32, sorting in increasing order.
type Float32Slice []float32
func (s Float32Slice) Len() int { return len(s) }
func (s Float32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Float32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Float32Slice) Sort() {
sort.Sort(s)
}
// SearchFloat32s searches for x in a sorted slice of float32 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchFloat32s(a []float32, x float32) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Int8Slice attaches the methods of sort.Interface to []int8, sorting in increasing order.
type Int8Slice []int8
func (s Int8Slice) Len() int { return len(s) }
func (s Int8Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Int8Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Int8Slice) Sort() {
sort.Sort(s)
}
// SearchInt8s searches for x in a sorted slice of int8 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchInt8s(a []int8, x int8) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Int16Slice attaches the methods of sort.Interface to []int16, sorting in increasing order.
type Int16Slice []int16
func (s Int16Slice) Len() int { return len(s) }
func (s Int16Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Int16Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Int16Slice) Sort() {
sort.Sort(s)
}
// SearchInt16s searches for x in a sorted slice of int16 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchInt16s(a []int16, x int16) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Int32Slice attaches the methods of sort.Interface to []int32, sorting in increasing order.
type Int32Slice []int32
func (s Int32Slice) Len() int { return len(s) }
func (s Int32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Int32Slice) Sort() {
sort.Sort(s)
}
// SearchInt32s searches for x in a sorted slice of int32 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchInt32s(a []int32, x int32) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Int64Slice attaches the methods of sort.Interface to []int64, sorting in increasing order.
type Int64Slice []int64
func (s Int64Slice) Len() int { return len(s) }
func (s Int64Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Int64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Int64Slice) Sort() {
sort.Sort(s)
}
// SearchInt64s searches for x in a sorted slice of int64 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchInt64s(a []int64, x int64) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// UintSlice attaches the methods of sort.Interface to []uint, sorting in increasing order.
type UintSlice []uint
func (s UintSlice) Len() int { return len(s) }
func (s UintSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s UintSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s UintSlice) Sort() {
sort.Sort(s)
}
// SearchUints searches for x in a sorted slice of uints and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchUints(a []uint, x uint) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Uint16Slice attaches the methods of sort.Interface to []uint16, sorting in increasing order.
type Uint16Slice []uint16
func (s Uint16Slice) Len() int { return len(s) }
func (s Uint16Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Uint16Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Uint16Slice) Sort() {
sort.Sort(s)
}
// SearchUint16s searches for x in a sorted slice of uint16 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchUint16s(a []uint16, x uint16) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Uint32Slice attaches the methods of sort.Interface to []uint32, sorting in increasing order.
type Uint32Slice []uint32
func (s Uint32Slice) Len() int { return len(s) }
func (s Uint32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Uint32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Uint32Slice) Sort() {
sort.Sort(s)
}
// SearchUint32s searches for x in a sorted slice of uint32 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchUint32s(a []uint32, x uint32) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// Uint64Slice attaches the methods of sort.Interface to []uint64, sorting in increasing order.
type Uint64Slice []uint64
func (s Uint64Slice) Len() int { return len(s) }
func (s Uint64Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s Uint64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s Uint64Slice) Sort() {
sort.Sort(s)
}
// SearchUint64s searches for x in a sorted slice of uint64 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchUint64s(a []uint64, x uint64) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// RuneSlice attaches the methods of sort.Interface to []rune, sorting in increasing order.
type RuneSlice []rune
func (s RuneSlice) Len() int { return len(s) }
func (s RuneSlice) Less(i, j int) bool { return s[i] < s[j] }
func (s RuneSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s RuneSlice) Sort() {
sort.Sort(s)
}
// SearchRunes searches for x in a sorted slice of uint64 and returns the index
// as specified by sort.Search. The slice must be sorted in ascending order.
func SearchRunes(a []rune, x rune) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
} | third_party/github.com/cznic/sortutil/sortutil.go | 0.838944 | 0.553807 | sortutil.go | starcoder |
package ledgerstate
import (
"math"
)
// TransactionBalancesValid is an internal utility function that checks if the sum of the balance changes equals to 0.
func TransactionBalancesValid(inputs Outputs, outputs Outputs) (valid bool) {
consumedCoins := make(map[Color]uint64)
for _, input := range inputs {
input.Balances().ForEach(func(color Color, balance uint64) bool {
consumedCoins[color], valid = SafeAddUint64(consumedCoins[color], balance)
return valid
})
if !valid {
return
}
}
recoloredCoins := uint64(0)
for _, output := range outputs {
output.Balances().ForEach(func(color Color, balance uint64) bool {
switch color {
case ColorIOTA, ColorMint:
recoloredCoins, valid = SafeAddUint64(recoloredCoins, balance)
default:
consumedCoins[color], valid = SafeSubUint64(consumedCoins[color], balance)
}
return valid
})
if !valid {
return
}
}
unspentCoins := uint64(0)
for _, remainingBalance := range consumedCoins {
if unspentCoins, valid = SafeAddUint64(unspentCoins, remainingBalance); !valid {
return
}
}
return unspentCoins == recoloredCoins
}
// UnlockBlocksValid is an internal utility function that checks if the UnlockBlocks are matching the referenced Inputs.
func UnlockBlocksValid(inputs Outputs, transaction *Transaction) (valid bool) {
unlockBlocks := transaction.UnlockBlocks()
for i, input := range inputs {
currentUnlockBlock := unlockBlocks[i]
if currentUnlockBlock.Type() == ReferenceUnlockBlockType {
currentUnlockBlock = unlockBlocks[unlockBlocks[i].(*ReferenceUnlockBlock).ReferencedIndex()]
}
unlockValid, unlockErr := input.UnlockValid(transaction, currentUnlockBlock)
if !unlockValid || unlockErr != nil {
return false
}
}
return true
}
// SafeAddUint64 adds two uint64 values. It returns the result and a valid flag that indicates whether the addition is
// valid without causing an overflow.
func SafeAddUint64(a uint64, b uint64) (result uint64, valid bool) {
valid = math.MaxUint64-a >= b
result = a + b
return
}
// SafeSubUint64 subtracts two uint64 values. It returns the result and a valid flag that indicates whether the
// subtraction is valid without causing an overflow.
func SafeSubUint64(a uint64, b uint64) (result uint64, valid bool) {
valid = b <= a
result = a - b
return
} | packages/ledgerstate/utils.go | 0.752831 | 0.53206 | utils.go | starcoder |
package iso20022
// List of elements which specify the opening of a non deliverable trade.
type OpeningData2 struct {
// Date at which the trading parties execute a treasury trade.
TradeDate *ISODate `xml:"TradDt"`
// Refers to the identification of a notification assigned by the trading side.
NotificationIdentification *Max35Text `xml:"NtfctnId"`
// Reference common to the parties of a trade.
CommonReference *Max35Text `xml:"CmonRef,omitempty"`
// Refers to the identification of a previous event in the life of a non deliverable forward trade.
RelatedReference *Max35Text `xml:"RltdRef,omitempty"`
// Describes the reason for the cancellation or the amendment.
AmendOrCancelReason *Max35Text `xml:"AmdOrCclRsn,omitempty"`
// Specifies the amounts of the non deliverable trade which is reported.
TradeAmounts *AmountsAndValueDate1 `xml:"TradAmts"`
// Exchange rate between two currencies. The rate is agreed by the trading parties during the negotiation process.
AgreedRate *AgreedRate1 `xml:"AgrdRate"`
// Set of parameters used to calculate the valuation rate to be applied to a non-deliverable agreement.
ValuationConditions *NonDeliverableForwardValuationConditions2 `xml:"ValtnConds"`
}
func (o *OpeningData2) SetTradeDate(value string) {
o.TradeDate = (*ISODate)(&value)
}
func (o *OpeningData2) SetNotificationIdentification(value string) {
o.NotificationIdentification = (*Max35Text)(&value)
}
func (o *OpeningData2) SetCommonReference(value string) {
o.CommonReference = (*Max35Text)(&value)
}
func (o *OpeningData2) SetRelatedReference(value string) {
o.RelatedReference = (*Max35Text)(&value)
}
func (o *OpeningData2) SetAmendOrCancelReason(value string) {
o.AmendOrCancelReason = (*Max35Text)(&value)
}
func (o *OpeningData2) AddTradeAmounts() *AmountsAndValueDate1 {
o.TradeAmounts = new(AmountsAndValueDate1)
return o.TradeAmounts
}
func (o *OpeningData2) AddAgreedRate() *AgreedRate1 {
o.AgreedRate = new(AgreedRate1)
return o.AgreedRate
}
func (o *OpeningData2) AddValuationConditions() *NonDeliverableForwardValuationConditions2 {
o.ValuationConditions = new(NonDeliverableForwardValuationConditions2)
return o.ValuationConditions
} | OpeningData2.go | 0.813313 | 0.529203 | OpeningData2.go | starcoder |
package main
import (
"math"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/mathgl/mgl32"
)
// CameraData Maps camera state
type CameraData struct {
Camera mgl32.Mat4
CameraUniform int32
PositionEye mgl32.Vec3
PositionTarget mgl32.Vec3
InertiaDrag float64
InertiaTurn float64
}
// InstanceCamera Stores camera state
var InstanceCamera CameraData
func (cameraData *CameraData) getEyeX() (position float32) {
return cameraData.PositionEye[0]
}
func (cameraData *CameraData) getEyeY() (position float32) {
return cameraData.PositionEye[1]
}
func (cameraData *CameraData) getEyeZ() (position float32) {
return cameraData.PositionEye[2]
}
func (cameraData *CameraData) getTargetX() (position float32) {
return cameraData.PositionTarget[0]
}
func (cameraData *CameraData) getTargetY() (position float32) {
return cameraData.PositionTarget[1]
}
func (cameraData *CameraData) getTargetZ() (position float32) {
return cameraData.PositionTarget[2]
}
func (cameraData *CameraData) moveEyeX(increment float32) {
cameraData.PositionEye[0] += increment
}
func (cameraData *CameraData) moveEyeY(increment float32) {
cameraData.PositionEye[1] += increment
}
func (cameraData *CameraData) moveEyeZ(increment float32) {
cameraData.PositionEye[2] += increment
}
func (cameraData *CameraData) moveTargetX(increment float32) {
cameraData.PositionTarget[0] += increment
}
func (cameraData *CameraData) moveTargetY(increment float32) {
cameraData.PositionTarget[1] += increment
}
func (cameraData *CameraData) moveTargetZ(increment float32) {
cameraData.PositionTarget[2] += increment
}
func (cameraData *CameraData) defaultEye() {
cameraData.PositionEye = ConfigCameraDefaultEye
}
func (cameraData *CameraData) defaultTarget() {
cameraData.PositionTarget = ConfigCameraDefaultTarget
}
func (cameraData *CameraData) defaultInertia() {
cameraData.InertiaDrag = 0.0
cameraData.InertiaTurn = 0.0
}
func getCamera() (*CameraData) {
return &InstanceCamera
}
func createCamera(program uint32) {
camera := getCamera()
camera.CameraUniform = gl.GetUniformLocation(program, gl.Str("cameraUniform\x00"))
// Default inertia (none)
camera.defaultInertia()
// Default camera position
camera.defaultEye()
camera.defaultTarget()
}
func produceInertia(inertia *float64, increment float64, celerity float64) {
*inertia += increment * celerity
// Cap inertia to maximum value
if *inertia > celerity {
*inertia = celerity
} else if *inertia < -1.0 * celerity {
*inertia = -1.0 * celerity
}
}
func consumeInertia(inertia *float64) (float64) {
if *inertia > 0 {
*inertia += ConfigCameraInertiaConsumeForward
} else if *inertia < 0 {
*inertia += ConfigCameraInertiaConsumeBackward
}
return *inertia
}
func processEventCameraEye() {
var (
celerity float64
rotationX float64
rotationY float64
inertiaDrag float64
inertiaTurn float64
)
camera := getCamera()
keyState := getEventKeyState()
timeFactor := normalizedTimeFactor()
// Decrease speed if diagonal move
if keyState.MoveTurbo == true {
celerity = ConfigCameraMoveCelerityTurbo
} else {
celerity = ConfigCameraMoveCelerityCruise
}
if (keyState.MoveUp == true || keyState.MoveDown == true) && (keyState.MoveLeft == true || keyState.MoveRight == true) {
celerity /= math.Sqrt(2.0)
}
// Acquire rotation around axis
rotationX = float64(camera.getTargetX())
rotationY = float64(camera.getTargetY())
// Process camera move position (keyboard)
if keyState.MoveUp == true {
produceInertia(&(camera.InertiaDrag), ConfigCameraInertiaProduceForward, celerity)
}
if keyState.MoveDown == true {
produceInertia(&(camera.InertiaDrag), ConfigCameraInertiaProduceBackward, celerity)
}
if keyState.MoveLeft == true {
produceInertia(&(camera.InertiaTurn), ConfigCameraInertiaProduceForward, celerity)
}
if keyState.MoveRight == true {
produceInertia(&(camera.InertiaTurn), ConfigCameraInertiaProduceBackward, celerity)
}
// Apply new position with inertia
inertiaDrag = consumeInertia(&(camera.InertiaDrag))
inertiaTurn = consumeInertia(&(camera.InertiaTurn))
camera.moveEyeX(timeFactor * float32(inertiaDrag * -1.0 * math.Sin(rotationY) + inertiaTurn * math.Cos(rotationY)))
camera.moveEyeZ(timeFactor * float32(inertiaDrag * math.Cos(rotationY) + inertiaTurn * math.Sin(rotationY)))
camera.moveEyeY(timeFactor * float32(inertiaDrag * math.Sin(rotationX)))
// Translation: walk
camera.Camera = camera.Camera.Mul4(mgl32.Translate3D(camera.getEyeX(), camera.getEyeY(), camera.getEyeZ()))
}
func processEventCameraTarget() {
camera := getCamera()
keyState := getEventKeyState()
timeFactor := normalizedTimeFactor()
camera.moveTargetX(timeFactor * keyState.WatchY * float32(math.Pi) * ConfigCameraTargetAmortizeFactor)
camera.moveTargetY(timeFactor * keyState.WatchX * float32(math.Pi) * 2 * ConfigCameraTargetAmortizeFactor)
// Rotation: view
camera.Camera = camera.Camera.Mul4(mgl32.HomogRotate3D(camera.getTargetX(), mgl32.Vec3{1, 0, 0}))
camera.Camera = camera.Camera.Mul4(mgl32.HomogRotate3D(camera.getTargetY(), mgl32.Vec3{0, 1, 0}))
camera.Camera = camera.Camera.Mul4(mgl32.HomogRotate3D(camera.getTargetZ(), mgl32.Vec3{0, 0, 1}))
}
func updateCamera() {
camera := getCamera()
camera.Camera = mgl32.Ident4()
processEventCameraTarget()
processEventCameraEye()
}
func resetCamera() {
camera := getCamera()
// Reset camera modifiers
resetMouseCursor()
// Reset camera itself
camera.defaultInertia()
camera.defaultEye()
camera.defaultTarget()
}
func bindCamera() {
camera := getCamera()
gl.UniformMatrix4fv(camera.CameraUniform, 1, false, &(camera.Camera[0]))
} | camera.go | 0.849878 | 0.545104 | camera.go | starcoder |
package easing
import (
"math"
)
// must map [0.0, 1.0] to [0.0, 1.0]
type EasingFun func(float64) float64
type Easing struct {
In, Out EasingFun
}
var (
Linear = Easing{
In: linearIn,
Out: linearOut,
}
QuadIn = Easing{
In: quadInIn,
Out: quadInOut,
}
QuadOut = Easing{
In: quadOutIn,
Out: quadOutOut,
}
QuadInOut = Easing{
In: quadInOutIn,
Out: quadInOutOut,
}
QuadOutIn = Easing{
In: quadOutInIn,
Out: quadOutInOut,
}
ExpIn = Easing{
In: expInIn,
Out: expInOut,
}
ExpOut = Easing{
In: expOutIn,
Out: expOutOut,
}
ExpInOut = Easing{
In: expInOutIn,
Out: expInOutOut,
}
ExpOutIn = Easing{
In: expOutInIn,
Out: expOutInOut,
}
)
// y = x
func linearIn(x float64) float64 {
return x
}
// y = -x + 1
func linearOut(x float64) float64 {
return 1.0 - x
}
// y = x²
func quadInIn(x float64) float64 {
return x * x
}
// y = -x² - 2x + 1
func quadInOut(x float64) float64 {
return 1.0 + x*(x-2.0)
}
// y = -x² + 2x
func quadOutIn(x float64) float64 {
return x * (2.0 - x)
}
// y = -x² + 1
func quadOutOut(x float64) float64 {
return 1.0 - x*x
}
// y([0 - 0.5[) = 2x²
// y([0.5 - 1]) = 2 * (-x² + 2x) - 1
func quadInOutIn(x float64) float64 {
if x < 0.5 {
return 2 * x * x
}
return 2.0*x*(2.0-x) - 1.0
}
// y([0 - 0.5[) = 1 - 2x²
// y([0.5 - 1[) = 2 * (x² - 2x) + 2
func quadInOutOut(x float64) float64 {
if x < 0.5 {
return 1.0 - 2.0*x*x
}
return 2.0 * (x*(x-2.0) + 1.0)
}
// y([0 - 0.5[) = -2 * (x² - x)
// y([0.5 - 1]) = 2 * (x² - x) + 1
func quadOutInIn(x float64) float64 {
if x < 0.5 {
return 2.0 * x * (1.0 - x)
}
return 2.0*x*(x-1.0) + 1
}
// y([0 - 0.5[) = 2 * (x² - x) + 1
// y([0.5 - 1]) = -2 * (x² - x)
func quadOutInOut(x float64) float64 {
if x < 0.5 {
return 2.0*x*(x-1.0) + 1
}
return 2.0 * x * (1.0 - x)
}
// y(x) = 1024 ^ (x - 1)
func expInIn(x float64) float64 {
return math.Pow(1024.0, x-1.0)
}
// y(x) = 1024 ^ (-x)
func expInOut(x float64) float64 {
return math.Pow(1024.0, -x)
}
// y(x) = 1 - 1024 ^ (-x)
func expOutIn(x float64) float64 {
return 1.0 - math.Pow(1024.0, -x)
}
// y(x) = 1 - 1024 ^ (x - 1)
func expOutOut(x float64) float64 {
return 1.0 - math.Pow(1024.0, x-1.0)
}
// y([0 - 0.5[) = (1024 ^ (2 * (x - 0.5))) / 2
// y([0.5 - 1]) = 1 - (1024 ^ (2 * (0.5 - x))) / 2
func expInOutIn(x float64) float64 {
if x < 0.5 {
return 0.5 * math.Pow(1048576.0, x-0.5)
}
return 1.0 - 0.5*math.Pow(1048576.0, 0.5-x)
}
// y([0 - 0.5[) = 1 - (1024 ^ (2 * (x - 0.5))) / 2
// y([0.5 - 1]) = (1024 ^ (2 * (0.5 - x))) / 2
func expInOutOut(x float64) float64 {
if x < 0.5 {
return 1.0 - 0.5*math.Pow(1048576.0, x-0.5)
}
return 0.5 * math.Pow(1048576.0, 0.5-x)
}
// y([0 - 0.5[) = 0.5 - 0.5 * 1048576 ^ (-x)
// y([0.5 - 1]) = 0.5 + 0.5 * 1048576 ^ (x-1)
func expOutInIn(x float64) float64 {
if x < 0.5 {
return 0.5 - 0.5*math.Pow(1048576.0, -x)
}
return 0.5 + 0.5*math.Pow(1048576.0, x-1.0)
}
// y([0 - 0.5[) = 0.5 + 0.5 * 1048576 ^ (-x)
// y([0.5 - 1]) = 0.5 - 0.5 * 1048576 ^ (x-1)
func expOutInOut(x float64) float64 {
if x < 0.5 {
return 0.5 + 0.5*math.Pow(1048576.0, -x)
}
return 0.5 - 0.5*math.Pow(1048576.0, x-1)
} | easing/easing.go | 0.739422 | 0.70117 | easing.go | starcoder |
package engo
const (
// AxisMax is the maximum value a joystick or keypress axis will reach
AxisMax float32 = 1
// AxisNeutral is the value an axis returns if there has been to state change.
AxisNeutral float32 = 0
// AxisMin is the minimum value a joystick or keypress axis will reach
AxisMin float32 = -1
)
// NewInputManager holds onto anything input related for engo
func NewInputManager() *InputManager {
return &InputManager{
Touches: make(map[int]Point),
axes: make(map[string]Axis),
buttons: make(map[string]Button),
keys: NewKeyManager(),
}
}
// InputManager contains information about all forms of input.
type InputManager struct {
// Mouse is InputManager's reference to the mouse. It is recommended to use the
// Axis and Button system if at all possible.
Mouse Mouse
// Modifier represents a special key pressed along with another key
Modifier Modifier
// Touches is the touches on the screen. There can be up to 5 recorded in Android,
// and up to 4 on iOS. GLFW can also keep track of the touches. The latest touch is also
// recorded in the Mouse so that touches readily work with the common.MouseSystem
Touches map[int]Point
axes map[string]Axis
buttons map[string]Button
keys *KeyManager
}
func (im *InputManager) update() {
im.keys.update()
}
// RegisterAxis registers a new axis which can be used to retrieve inputs which are spectrums.
func (im *InputManager) RegisterAxis(name string, pairs ...AxisPair) {
im.axes[name] = Axis{
Name: name,
Pairs: pairs,
}
}
// RegisterButton registers a new button input.
func (im *InputManager) RegisterButton(name string, keys ...Key) {
im.buttons[name] = Button{
Triggers: keys,
Name: name,
}
}
// Axis retrieves an Axis with a specified name.
func (im *InputManager) Axis(name string) Axis {
return im.axes[name]
}
// Button retrieves a Button with a specified name.
func (im *InputManager) Button(name string) Button {
return im.buttons[name]
}
// Mouse represents the mouse
type Mouse struct {
X, Y float32
ScrollX, ScrollY float32
Action Action
Button MouseButton
Modifer Modifier
} | input.go | 0.697094 | 0.45423 | input.go | starcoder |
package tort
import (
"fmt"
"reflect"
)
// SliceAssertions are tests around slice values.
type SliceAssertions struct {
Assertions
name string
slice []interface{}
}
// Slice identifies a slice variable value and returns test functions for its values. If the value
// isn't a slice, generates a fatal error.
func (assert Assertions) Slice(value interface{}) SliceAssertions {
assert.t.Helper()
if reflect.TypeOf(value).Kind() != reflect.Slice {
assert.Fatal("%v is not a slice", value)
}
// Have to jump through a few hoops to convert any incoming slice into somethign we can test
v := reflect.ValueOf(value)
var slice []interface{}
for idx := 0; idx < v.Len(); idx++ {
element := v.Index(idx)
slice = append(slice, element.Interface())
}
return SliceAssertions{
Assertions: assert,
name: "slice",
slice: slice,
}
}
// Slice identifies a slice field on a struct. If the field isn't present, or isn't a slice,
// generates an error.
func (assert StructAssertions) Slice(field string) SliceAssertions {
assert.t.Helper()
name := fmt.Sprintf("%s.%s", assert.Type(), field)
property := assert.Field(field)
if property.Kind() != reflect.Slice {
assert.Fatal("field %s is not a slice", name)
}
var slice []interface{}
for idx := 0; idx < property.Len(); idx++ {
slice = append(slice, property.Interface())
}
return SliceAssertions{
Assertions: assert.Assertions,
name: name,
slice: slice,
}
}
// Empty generates an error if the length of the slice is not zero.
func (assert SliceAssertions) Empty() {
assert.t.Helper()
if len(assert.slice) != 0 {
assert.Failed(`%s is not an empty slice; has %d elements`, assert.name, len(assert.slice))
}
}
// Length generates an error if the length of the slice doesn't equal the value supplied.
func (assert SliceAssertions) Length(expected int) {
assert.t.Helper()
if len(assert.slice) != expected {
assert.Failed(`expected %s to have %d elements; has %d instead`, assert.name, expected, len(assert.slice))
}
}
// MoreThan generates an error if the length of the slice doesn't exceed the value supplied.
func (assert SliceAssertions) MoreThan(expected int) {
assert.t.Helper()
if len(assert.slice) <= expected {
assert.Failed(`expected %s to have more than %d elements but it has %d elements`, assert.name, expected, len(assert.slice))
}
}
// FewerThan generates an error if the length of the slice equals or exceeds the value supplied.
func (assert SliceAssertions) FewerThan(expected int) {
assert.t.Helper()
if len(assert.slice) >= expected {
assert.Failed(`expected %s to have fewer than %d elementsbut it has %d elements`, assert.name, expected, len(assert.slice))
}
}
// Element looks up the element from the slice array.
func (assert SliceAssertions) Element(idx int) reflect.Value {
assert.t.Helper()
if idx < 0 || idx > len(assert.slice) {
assert.Fatal("index %d out of range", idx)
}
item := assert.slice[idx]
return reflect.ValueOf(item)
} | slices.go | 0.828454 | 0.767211 | slices.go | starcoder |
package hashing
import (
"crypto/sha256"
"fmt"
"hash"
"golang.org/x/crypto/blake2b"
)
type Digest []byte
type Hasher interface {
Salted([]byte, ...[]byte) Digest
Do(...[]byte) Digest
Len() uint16
}
// XorHasher implements the Hasher interface and computes a 2 bit hash
// function. Handy for testing hash tree implementations.
type XorHasher struct{}
func NewXorHasher() Hasher {
return new(XorHasher)
}
// Salted function adds a seed to the input data before hashing it.
func (x XorHasher) Salted(salt []byte, data ...[]byte) Digest {
data = append(data, salt)
return x.Do(data...)
}
// Do function hashes input data using the XOR hash function.
func (x XorHasher) Do(data ...[]byte) Digest {
var result byte
for _, elem := range data {
var sum byte
for _, b := range elem {
sum = sum ^ b
}
result = result ^ sum
}
return []byte{result}
}
// Len function returns the size of the resulting hash.
func (s XorHasher) Len() uint16 { return uint16(8) }
type KeyHasher struct {
underlying hash.Hash
}
// NewBlake2bHasher implements the Hasher interface and computes a 256 bit hash
// function using the Blake2 hashing algorithm.
func NewBlake2bHasher() Hasher {
hasher, err := blake2b.New256(nil)
if err != nil {
panic(fmt.Sprintf("Error creating BLAKE2b hasher %v", err))
}
return &KeyHasher{underlying: hasher}
}
// NewSha256Hasher implements the Hasher interface and computes a 256 bit hash
// function using the SHA256 hashing algorithm.
func NewSha256Hasher() Hasher {
return &KeyHasher{underlying: sha256.New()}
}
// Salted function adds a seed to the input data before hashing it.
func (s *KeyHasher) Salted(salt []byte, data ...[]byte) Digest {
data = append(data, salt)
return s.Do(data...)
}
// Do function hashes input data using the hashing function given by the KeyHasher.
func (s *KeyHasher) Do(data ...[]byte) Digest {
s.underlying.Reset()
for i := 0; i < len(data); i++ {
_, _ = s.underlying.Write(data[i])
}
return s.underlying.Sum(nil)[:]
}
// Len function returns the size of the resulting hash.
func (s KeyHasher) Len() uint16 { return uint16(256) }
// PearsonHasher implements the Hasher interface and computes a 8 bit hash
// function. Handy for testing hash tree implementations.
type PearsonHasher struct{}
func NewPearsonHasher() Hasher {
return new(PearsonHasher)
}
// Salted function adds a seed to the input data before hashing it.
func (h *PearsonHasher) Salted(salt []byte, data ...[]byte) Digest {
data = append(data, salt)
return h.Do(data...)
}
// Do function hashes input data using the Pearson hash function.
func (p *PearsonHasher) Do(data ...[]byte) Digest {
lookupTable := [...]uint8{
// 0-255 shuffled in any (random) order suffices
0x62, 0x06, 0x55, 0x96, 0x24, 0x17, 0x70, 0xa4, 0x87, 0xcf, 0xa9, 0x05, 0x1a, 0x40, 0xa5, 0xdb, // 1
0x3d, 0x14, 0x44, 0x59, 0x82, 0x3f, 0x34, 0x66, 0x18, 0xe5, 0x84, 0xf5, 0x50, 0xd8, 0xc3, 0x73, // 2
0x5a, 0xa8, 0x9c, 0xcb, 0xb1, 0x78, 0x02, 0xbe, 0xbc, 0x07, 0x64, 0xb9, 0xae, 0xf3, 0xa2, 0x0a, // 3
0xed, 0x12, 0xfd, 0xe1, 0x08, 0xd0, 0xac, 0xf4, 0xff, 0x7e, 0x65, 0x4f, 0x91, 0xeb, 0xe4, 0x79, // 4
0x7b, 0xfb, 0x43, 0xfa, 0xa1, 0x00, 0x6b, 0x61, 0xf1, 0x6f, 0xb5, 0x52, 0xf9, 0x21, 0x45, 0x37, // 5
0x3b, 0x99, 0x1d, 0x09, 0xd5, 0xa7, 0x54, 0x5d, 0x1e, 0x2e, 0x5e, 0x4b, 0x97, 0x72, 0x49, 0xde, // 6
0xc5, 0x60, 0xd2, 0x2d, 0x10, 0xe3, 0xf8, 0xca, 0x33, 0x98, 0xfc, 0x7d, 0x51, 0xce, 0xd7, 0xba, // 7
0x27, 0x9e, 0xb2, 0xbb, 0x83, 0x88, 0x01, 0x31, 0x32, 0x11, 0x8d, 0x5b, 0x2f, 0x81, 0x3c, 0x63, // 8
0x9a, 0x23, 0x56, 0xab, 0x69, 0x22, 0x26, 0xc8, 0x93, 0x3a, 0x4d, 0x76, 0xad, 0xf6, 0x4c, 0xfe, // 9
0x85, 0xe8, 0xc4, 0x90, 0xc6, 0x7c, 0x35, 0x04, 0x6c, 0x4a, 0xdf, 0xea, 0x86, 0xe6, 0x9d, 0x8b, // 10
0xbd, 0xcd, 0xc7, 0x80, 0xb0, 0x13, 0xd3, 0xec, 0x7f, 0xc0, 0xe7, 0x46, 0xe9, 0x58, 0x92, 0x2c, // 11
0xb7, 0xc9, 0x16, 0x53, 0x0d, 0xd6, 0x74, 0x6d, 0x9f, 0x20, 0x5f, 0xe2, 0x8c, 0xdc, 0x39, 0x0c, // 12
0xdd, 0x1f, 0xd1, 0xb6, 0x8f, 0x5c, 0x95, 0xb8, 0x94, 0x3e, 0x71, 0x41, 0x25, 0x1b, 0x6a, 0xa6, // 13
0x03, 0x0e, 0xcc, 0x48, 0x15, 0x29, 0x38, 0x42, 0x1c, 0xc1, 0x28, 0xd9, 0x19, 0x36, 0xb3, 0x75, // 14
0xee, 0x57, 0xf0, 0x9b, 0xb4, 0xaa, 0xf2, 0xd4, 0xbf, 0xa3, 0x4e, 0xda, 0x89, 0xc2, 0xaf, 0x6e, // 15
0x2b, 0x77, 0xe0, 0x47, 0x7a, 0x8e, 0x2a, 0xa0, 0x68, 0x30, 0xf7, 0x67, 0x0f, 0x0b, 0x8a, 0xef, // 16
}
ih := make([]byte, 0)
for _, k := range data {
h := uint8(0)
for _, v := range k {
h = lookupTable[h^v]
}
ih = append(ih, h)
}
r := uint8(0)
for _, v := range ih {
r = lookupTable[r^v]
}
return Digest{r}
}
// Len function returns the size of the resulting hash.
func (p PearsonHasher) Len() uint16 { return uint16(8) }
// FakeHasher implements the Hasher interface and computes a hash
// function depending on the caller.
// Here, 'Salted' function does nothing but act as a passthrough to 'Do' function.
// Handy for testing hash tree implementations.
type FakeHasher struct {
underlying Hasher
}
// Salted function directly hashes data, similarly to Do function.
func (h *FakeHasher) Salted(salt []byte, data ...[]byte) Digest {
return h.underlying.Do(data...)
}
// Do function hashes input data using the hashing function given by the KeyHasher.
func (h *FakeHasher) Do(data ...[]byte) Digest {
return h.underlying.Do(data...)
}
// Len function returns the size of the resulting hash.
func (h FakeHasher) Len() uint16 {
return h.underlying.Len()
}
func NewFakeXorHasher() Hasher {
return &FakeHasher{NewXorHasher()}
}
func NewFakeSha256Hasher() Hasher {
return &FakeHasher{NewSha256Hasher()}
}
func NewFakePearsonHasher() Hasher {
return &FakeHasher{NewPearsonHasher()}
} | crypto/hashing/hash.go | 0.737442 | 0.491761 | hash.go | starcoder |
package util
// Pow2 returns the first power-of-two value >= to n.
// This can be used to create suitable texture dimensions.
func Pow2(n int) int {
x := uint32(n - 1)
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
return int(x + 1)
}
// Min returns a iff a < b. otherwise returns b.
func Min(a, b int) int {
if a < b {
return a
}
return b
}
// Max returns a iff a > b. otherwise returns b.
func Max(a, b int) int {
if a > b {
return a
}
return b
}
// Clampi returns v, clamped to the range [min, max].
func Clampi(v, min, max int) int {
if v < min {
return min
}
if v > max {
return max
}
return v
}
// Mat4 defines a 4x4 matrix.
type Mat4 [16]float32
// Copy returns a copy of m.
func (m *Mat4) Copy() *Mat4 {
var n Mat4
copy(n[:], (*m)[:])
return &n
}
// Identity sets m to the identity matrix.
func (m *Mat4) Identity() {
mm := *m
mm[0] = 1
mm[1] = 0
mm[2] = 0
mm[3] = 0
mm[4] = 0
mm[5] = 1
mm[6] = 0
mm[7] = 0
mm[8] = 0
mm[9] = 0
mm[10] = 1
mm[11] = 0
mm[12] = 0
mm[13] = 0
mm[14] = 0
mm[15] = 1
*m = mm
}
// Mul sets ma to the multiplication of ma with mb.
func (ma *Mat4) Mul(mb *Mat4) {
a, b := *ma, *mb
a0 := a[0]
a1 := a[1]
a2 := a[2]
a3 := a[3]
a4 := a[4]
a5 := a[5]
a6 := a[6]
a7 := a[7]
a8 := a[8]
a9 := a[9]
a10 := a[10]
a11 := a[11]
a12 := a[12]
a13 := a[13]
a14 := a[14]
a15 := a[15]
a[0] = a0*b[0] + a4*b[1] + a8*b[2] + a12*b[3]
a[1] = a1*b[0] + a5*b[1] + a9*b[2] + a13*b[3]
a[2] = a2*b[0] + a6*b[1] + a10*b[2] + a14*b[3]
a[3] = a3*b[0] + a7*b[1] + a11*b[2] + a15*b[3]
a[4] = a0*b[4] + a4*b[5] + a8*b[6] + a12*b[7]
a[5] = a1*b[4] + a5*b[5] + a9*b[6] + a13*b[7]
a[6] = a2*b[4] + a6*b[5] + a10*b[6] + a14*b[7]
a[7] = a3*b[4] + a7*b[5] + a11*b[6] + a15*b[7]
a[8] = a0*b[8] + a4*b[9] + a8*b[10] + a12*b[11]
a[9] = a1*b[8] + a5*b[9] + a9*b[10] + a13*b[11]
a[10] = a2*b[8] + a6*b[9] + a10*b[10] + a14*b[11]
a[11] = a3*b[8] + a7*b[9] + a11*b[10] + a15*b[11]
a[12] = a0*b[12] + a4*b[13] + a8*b[14] + a12*b[15]
a[13] = a1*b[12] + a5*b[13] + a9*b[14] + a13*b[15]
a[14] = a2*b[12] + a6*b[13] + a10*b[14] + a14*b[15]
a[15] = a3*b[12] + a7*b[13] + a11*b[14] + a15*b[15]
*ma = a
}
// Mat4Ortho returns the orthographic projection for the given viewport.
func Mat4Ortho(left, right, top, bottom, znear, zfar float32) *Mat4 {
var s Mat4
s.Identity()
rml := right - left
rpl := right + left
tmb := top - bottom
tpb := top + bottom
fmn := zfar - znear
fpn := zfar + znear
s[0] = 2.0 / rml
s[5] = 2.0 / tmb
s[10] = -2.0 / fmn
s[12] = -rpl / rml
s[13] = -tpb / tmb
s[14] = -fpn / fmn
s[15] = 1.0
return &s
}
// Mat4Scale returns the scale matrix for dimensions x/y/z.
func Mat4Scale(x, y, z float32) *Mat4 {
var s Mat4
s.Identity()
s[0] = x
s[5] = y
s[10] = z
s[15] = 1
return &s
}
// Translate returns the translation matrix for coordinates x/y/z.
func Mat4Translate(x, y, z float32) *Mat4 {
var s Mat4
s[0] = 1
s[5] = 1
s[10] = 1
s[12] = x
s[13] = y
s[14] = z
s[15] = 1
return &s
} | util/util.go | 0.842604 | 0.604282 | util.go | starcoder |
package inspect
import (
"fmt"
"math"
"unsafe"
)
// The BlockOrder type represents the order of an allocation returned by the buddy allocator.
type BlockOrder uint64
const (
// Order0 is a constant representing allocations of order 0.
Order0 = BlockOrder(iota)
// Order1 is a constant representing allocations of order 1.
Order1
// Order2 is a constant representing allocations of order 2.
Order2
// Order3 is a constant representing allocations of order 3.
Order3
// Order4 is a constant representing allocations of order 4.
Order4
// Order5 is a constant representing allocations of order 5.
Order5
// Order6 is a constant representing allocations of order 6.
Order6
// Order7 is a constant representing allocations of order 7.
Order7
)
// nOrders contains the number of allocation orders.
const nOrders = uint(8)
var orderSize = []BlockOrder{16, 32, 64, 128, 256, 512, 1024, 2048}
// Size returns the usable size of an allocation for the given order.
func (o BlockOrder) Size() uint64 {
return uint64(orderSize[o])
}
func (o BlockOrder) String() string {
switch o {
case Order0:
return "0 [16 bytes]"
case Order1:
return "1 [32 bytes]"
case Order2:
return "2 [64 bytes]"
case Order3:
return "3 [128 bytes]"
case Order4:
return "4 [256 bytes]"
case Order5:
return "5 [512 bytes]"
case Order6:
return "6 [1024 bytes]"
case Order7:
return "7 [2048 bytes]"
}
return "INVALID"
}
// The BlockType type represents the type of a block returned by the buddy allocator.
type BlockType uint64
const (
// FreeBlockType is the type value for blocks of type FreeBlock.
FreeBlockType = BlockType(iota)
// ReservedBlockType is the type value for blocks of type ReservedBlock.
ReservedBlockType
// HeaderBlockType is the type value for blocks of type HeaderBlock.
HeaderBlockType
// NodeValueBlockType is the type value for blocks of type NodeValueBlock.
NodeValueBlockType
// IntValueBlockType is the type value for blocks of type IntValueBlock.
IntValueBlockType
// UintValueBlockType is the type value for blocks of type UintValueBlock.
UintValueBlockType
// DoubleValueBlockType is the type value for blocks of type DoubleValueBlock.
DoubleValueBlockType
// PropertyBlockType is the type value for blocks of type PropertyBlock.
PropertyBlockType
// ExtentBlockType is the type value for blocks of type ExtentBlock.
ExtentBlockType
// NameBlockType is the type value for blocks of type NameBlock.
NameBlockType
// TombstoneBlockType is the type value for blocks of type TombstoneBlock.
TombstoneBlockType
// ArrayBlockType is the type value for blocks of type ArrayBlock.
ArrayBlockType
// LinkBlockType is the type value for blocks of type LinkBlock.
LinkBlockType
)
func (t BlockType) String() string {
switch t {
case FreeBlockType:
return "FreeBlockType"
case ReservedBlockType:
return "ReservedBlockType"
case HeaderBlockType:
return "HeaderBlockType"
case NodeValueBlockType:
return "NodeValueBlockType"
case IntValueBlockType:
return "IntValueBlockType"
case UintValueBlockType:
return "UintValueBlockType"
case DoubleValueBlockType:
return "DoubleValueBlockType"
case PropertyBlockType:
return "PropertyBlockType"
case ExtentBlockType:
return "ExtentBlockType"
case NameBlockType:
return "NameBlockType"
case TombstoneBlockType:
return "TombstoneBlockType"
case ArrayBlockType:
return "ArrayBlockType"
case LinkBlockType:
return "LinkBlockType"
}
return "INVALID"
}
// Block is an opaque type representing any region returned by the buddy allocator.
type Block struct {
header uint64
payload uint64
}
// AsBlock converts the Block to a Block.
func (b *Block) AsBlock() *Block {
return (*Block)(unsafe.Pointer(b))
}
// AsFreeBlock converts the Block to a FreeBlock.
func (b *Block) AsFreeBlock() *FreeBlock {
return (*FreeBlock)(unsafe.Pointer(b))
}
// AsReservedBlock converts the Block to a ReservedBlock.
func (b *Block) AsReservedBlock() *ReservedBlock {
return (*ReservedBlock)(unsafe.Pointer(b))
}
// AsHeaderBlock converts the Block to a HeaderBlock.
func (b *Block) AsHeaderBlock() *HeaderBlock {
return (*HeaderBlock)(unsafe.Pointer(b))
}
// AsNodeValueBlock converts the Block to a NodeValueBlock.
func (b *Block) AsNodeValueBlock() *NodeValueBlock {
return (*NodeValueBlock)(unsafe.Pointer(b))
}
// AsIntValueBlock converts the Block to a IntValueBlock.
func (b *Block) AsIntValueBlock() *IntValueBlock {
return (*IntValueBlock)(unsafe.Pointer(b))
}
// AsUintValueBlock converts the Block to a UintValueBlock.
func (b *Block) AsUintValueBlock() *UintValueBlock {
return (*UintValueBlock)(unsafe.Pointer(b))
}
// AsDoubleValueBlock converts the Block to a DoubleValueBlock.
func (b *Block) AsDoubleValueBlock() *DoubleValueBlock {
return (*DoubleValueBlock)(unsafe.Pointer(b))
}
// AsPropertyBlock converts the Block to a PropertyBlock.
func (b *Block) AsPropertyBlock() *PropertyBlock {
return (*PropertyBlock)(unsafe.Pointer(b))
}
// AsExtentBlock converts the Block to a ExtentBlock.
func (b *Block) AsExtentBlock() *ExtentBlock {
return (*ExtentBlock)(unsafe.Pointer(b))
}
// AsNameBlock converts the Block to a NameBlock.
func (b *Block) AsNameBlock() *NameBlock {
return (*NameBlock)(unsafe.Pointer(b))
}
// AsTombstoneBlock converts the Block to a TombstoneBlock.
func (b *Block) AsTombstoneBlock() *TombstoneBlock {
return (*TombstoneBlock)(unsafe.Pointer(b))
}
// AsArrayBlock converts the Block to a ArrayBlock.
func (b *Block) AsArrayBlock() *ArrayBlock {
return (*ArrayBlock)(unsafe.Pointer(b))
}
// AsLinkBlock converts the Block to a LinkBlock.
func (b *Block) AsLinkBlock() *LinkBlock {
return (*LinkBlock)(unsafe.Pointer(b))
}
func (b *Block) zeroPayload(size uint64, off uintptr) {
p := uintptr(unsafe.Pointer(&b.payload)) + off
for i := uint64(0); i < size; i++ {
*(*byte)(unsafe.Pointer(p + uintptr(i))) = 0
}
}
func (b *Block) Free(order BlockOrder, nextFree BlockIndex) {
b.header = (uint64(order) & 0xf) | ((uint64(nextFree) & 0xfffffff) << 8)
}
func (b Block) String() string {
return fmt.Sprintf("Header: %x, Payload: %x, Type: %s, Order: %s\n", b.header, b.payload, b.GetType(), b.GetOrder())
}
// SetHeader sets the header fields for Block.
func (b *Block) SetHeader(Order BlockOrder, Type BlockType) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240))
}
// GetOrder returns the Order field in the Block.
func (b *Block) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the Block.
func (b *Block) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the Block.
func (b *Block) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the Block.
func (b *Block) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// The FreeBlock type represents a block of type FreeBlock.
type FreeBlock Block
// SetHeader sets the header fields for FreeBlock.
func (b *FreeBlock) SetHeader(Order BlockOrder, Type BlockType, NextFree BlockIndex) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(NextFree) << 8) & 68719476480))
}
// GetOrder returns the Order field in the FreeBlock.
func (b *FreeBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the FreeBlock.
func (b *FreeBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the FreeBlock.
func (b *FreeBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the FreeBlock.
func (b *FreeBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetNextFree returns the NextFree field in the FreeBlock.
func (b *FreeBlock) GetNextFree() BlockIndex {
return BlockIndex((b.header & 68719476480) >> 8)
}
// SetNextFree sets the NextFree field in the FreeBlock.
func (b *FreeBlock) SetNextFree(v BlockIndex) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// The ReservedBlock type represents a block of type ReservedBlock.
type ReservedBlock Block
// SetHeader sets the header fields for ReservedBlock.
func (b *ReservedBlock) SetHeader(Order BlockOrder, Type BlockType) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240))
}
// GetOrder returns the Order field in the ReservedBlock.
func (b *ReservedBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the ReservedBlock.
func (b *ReservedBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the ReservedBlock.
func (b *ReservedBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the ReservedBlock.
func (b *ReservedBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// The HeaderBlock type represents a block of type HeaderBlock.
type HeaderBlock Block
// SetHeader sets the header fields for HeaderBlock.
func (b *HeaderBlock) SetHeader(Order BlockOrder, Type BlockType, Version uint, Magic uint) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(Version) << 8) & 4294967040) | ((uint64(Magic) << 32) & 18446744069414584320))
}
// GetOrder returns the Order field in the HeaderBlock.
func (b *HeaderBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the HeaderBlock.
func (b *HeaderBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the HeaderBlock.
func (b *HeaderBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the HeaderBlock.
func (b *HeaderBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetVersion returns the Version field in the HeaderBlock.
func (b *HeaderBlock) GetVersion() uint {
return uint((b.header & 4294967040) >> 8)
}
// SetVersion sets the Version field in the HeaderBlock.
func (b *HeaderBlock) SetVersion(v uint) {
mask := uint64(4294967040)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// GetMagic returns the Magic field in the HeaderBlock.
func (b *HeaderBlock) GetMagic() uint {
return uint((b.header & 18446744069414584320) >> 32)
}
// SetMagic sets the Magic field in the HeaderBlock.
func (b *HeaderBlock) SetMagic(v uint) {
mask := uint64(18446744069414584320)
b.header &= ^mask
b.header |= ((uint64(v) << 32) & mask)
}
// The NodeValueBlock type represents a block of type NodeValueBlock.
type NodeValueBlock Block
// SetHeader sets the header fields for NodeValueBlock.
func (b *NodeValueBlock) SetHeader(Order BlockOrder, Type BlockType, ParentIndex BlockIndex, NameIndex BlockIndex) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(ParentIndex) << 8) & 68719476480) | ((uint64(NameIndex) << 36) & 18446744004990074880))
}
// GetOrder returns the Order field in the NodeValueBlock.
func (b *NodeValueBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the NodeValueBlock.
func (b *NodeValueBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the NodeValueBlock.
func (b *NodeValueBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the NodeValueBlock.
func (b *NodeValueBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetParentIndex returns the ParentIndex field in the NodeValueBlock.
func (b *NodeValueBlock) GetParentIndex() BlockIndex {
return BlockIndex((b.header & 68719476480) >> 8)
}
// SetParentIndex sets the ParentIndex field in the NodeValueBlock.
func (b *NodeValueBlock) SetParentIndex(v BlockIndex) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// GetNameIndex returns the NameIndex field in the NodeValueBlock.
func (b *NodeValueBlock) GetNameIndex() BlockIndex {
return BlockIndex((b.header & 18446744004990074880) >> 36)
}
// SetNameIndex sets the NameIndex field in the NodeValueBlock.
func (b *NodeValueBlock) SetNameIndex(v BlockIndex) {
mask := uint64(18446744004990074880)
b.header &= ^mask
b.header |= ((uint64(v) << 36) & mask)
}
func (b *NodeValueBlock) SetPayload(data []byte) {
p := uintptr(unsafe.Pointer(b)) + 8
for i, v := range data {
*(*byte)(unsafe.Pointer(p + uintptr(i))) = v
}
}
// The IntValueBlock type represents a block of type IntValueBlock.
type IntValueBlock Block
// SetHeader sets the header fields for IntValueBlock.
func (b *IntValueBlock) SetHeader(Order BlockOrder, Type BlockType, ParentIndex BlockIndex, NameIndex BlockIndex) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(ParentIndex) << 8) & 68719476480) | ((uint64(NameIndex) << 36) & 18446744004990074880))
}
// GetOrder returns the Order field in the IntValueBlock.
func (b *IntValueBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the IntValueBlock.
func (b *IntValueBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the IntValueBlock.
func (b *IntValueBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the IntValueBlock.
func (b *IntValueBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetParentIndex returns the ParentIndex field in the IntValueBlock.
func (b *IntValueBlock) GetParentIndex() BlockIndex {
return BlockIndex((b.header & 68719476480) >> 8)
}
// SetParentIndex sets the ParentIndex field in the IntValueBlock.
func (b *IntValueBlock) SetParentIndex(v BlockIndex) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// GetNameIndex returns the NameIndex field in the IntValueBlock.
func (b *IntValueBlock) GetNameIndex() BlockIndex {
return BlockIndex((b.header & 18446744004990074880) >> 36)
}
// SetNameIndex sets the NameIndex field in the IntValueBlock.
func (b *IntValueBlock) SetNameIndex(v BlockIndex) {
mask := uint64(18446744004990074880)
b.header &= ^mask
b.header |= ((uint64(v) << 36) & mask)
}
// GetValue returns the Value field in the IntValueBlock.
func (b *IntValueBlock) GetValue() int64 {
return int64((b.payload & 18446744073709551615) >> 0)
}
// SetValue sets the Value field in the IntValueBlock.
func (b *IntValueBlock) SetValue(v int64) {
mask := uint64(18446744073709551615)
b.payload &= ^mask
b.payload |= ((uint64(v) << 0) & mask)
}
// The UintValueBlock type represents a block of type UintValueBlock.
type UintValueBlock Block
// SetHeader sets the header fields for UintValueBlock.
func (b *UintValueBlock) SetHeader(Order BlockOrder, Type BlockType, ParentIndex uint, NameIndex uint) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(ParentIndex) << 8) & 68719476480) | ((uint64(NameIndex) << 36) & 18446744004990074880))
}
// GetOrder returns the Order field in the UintValueBlock.
func (b *UintValueBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the UintValueBlock.
func (b *UintValueBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the UintValueBlock.
func (b *UintValueBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the UintValueBlock.
func (b *UintValueBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetParentIndex returns the ParentIndex field in the UintValueBlock.
func (b *UintValueBlock) GetParentIndex() uint {
return uint((b.header & 68719476480) >> 8)
}
// SetParentIndex sets the ParentIndex field in the UintValueBlock.
func (b *UintValueBlock) SetParentIndex(v uint) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// GetNameIndex returns the NameIndex field in the UintValueBlock.
func (b *UintValueBlock) GetNameIndex() uint {
return uint((b.header & 18446744004990074880) >> 36)
}
// SetNameIndex sets the NameIndex field in the UintValueBlock.
func (b *UintValueBlock) SetNameIndex(v uint) {
mask := uint64(18446744004990074880)
b.header &= ^mask
b.header |= ((uint64(v) << 36) & mask)
}
// GetValue returns the Value field in the UintValueBlock.
func (b *UintValueBlock) GetValue() uint64 {
return uint64((b.payload & 18446744073709551615) >> 0)
}
// SetValue sets the Value field in the UintValueBlock.
func (b *UintValueBlock) SetValue(v uint64) {
mask := uint64(18446744073709551615)
b.payload &= ^mask
b.payload |= ((uint64(v) << 0) & mask)
}
// The DoubleValueBlock type represents a block of type DoubleValueBlock.
type DoubleValueBlock Block
// SetHeader sets the header fields for DoubleValueBlock.
func (b *DoubleValueBlock) SetHeader(Order BlockOrder, Type BlockType, ParentIndex BlockIndex, NameIndex BlockIndex) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(ParentIndex) << 8) & 68719476480) | ((uint64(NameIndex) << 36) & 18446744004990074880))
}
// GetOrder returns the Order field in the DoubleValueBlock.
func (b *DoubleValueBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the DoubleValueBlock.
func (b *DoubleValueBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the DoubleValueBlock.
func (b *DoubleValueBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the DoubleValueBlock.
func (b *DoubleValueBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetParentIndex returns the ParentIndex field in the DoubleValueBlock.
func (b *DoubleValueBlock) GetParentIndex() BlockIndex {
return BlockIndex((b.header & 68719476480) >> 8)
}
// SetParentIndex sets the ParentIndex field in the DoubleValueBlock.
func (b *DoubleValueBlock) SetParentIndex(v BlockIndex) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// GetNameIndex returns the NameIndex field in the DoubleValueBlock.
func (b *DoubleValueBlock) GetNameIndex() BlockIndex {
return BlockIndex((b.header & 18446744004990074880) >> 36)
}
// SetNameIndex sets the NameIndex field in the DoubleValueBlock.
func (b *DoubleValueBlock) SetNameIndex(v BlockIndex) {
mask := uint64(18446744004990074880)
b.header &= ^mask
b.header |= ((uint64(v) << 36) & mask)
}
// GetValue returns the Value field in the DoubleValueBlock.
func (b *DoubleValueBlock) GetValue() float64 {
return math.Float64frombits(((b.payload & 18446744073709551615) >> 0))
}
// SetValue sets the Value field in the DoubleValueBlock.
func (b *DoubleValueBlock) SetValue(f float64) {
v := math.Float64bits(f)
mask := uint64(18446744073709551615)
b.payload &= ^mask
b.payload |= ((uint64(v) << 0) & mask)
}
// The PropertyBlock type represents a block of type PropertyBlock.
type PropertyBlock Block
// SetHeader sets the header fields for PropertyBlock.
func (b *PropertyBlock) SetHeader(Order BlockOrder, Type BlockType, ParentIndex BlockIndex, NameIndex BlockIndex) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(ParentIndex) << 8) & 68719476480) | ((uint64(NameIndex) << 36) & 18446744004990074880))
}
// GetOrder returns the Order field in the PropertyBlock.
func (b *PropertyBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the PropertyBlock.
func (b *PropertyBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the PropertyBlock.
func (b *PropertyBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the PropertyBlock.
func (b *PropertyBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetParentIndex returns the ParentIndex field in the PropertyBlock.
func (b *PropertyBlock) GetParentIndex() BlockIndex {
return BlockIndex((b.header & 68719476480) >> 8)
}
// SetParentIndex sets the ParentIndex field in the PropertyBlock.
func (b *PropertyBlock) SetParentIndex(v BlockIndex) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// GetNameIndex returns the NameIndex field in the PropertyBlock.
func (b *PropertyBlock) GetNameIndex() BlockIndex {
return BlockIndex((b.header & 18446744004990074880) >> 36)
}
// SetNameIndex sets the NameIndex field in the PropertyBlock.
func (b *PropertyBlock) SetNameIndex(v BlockIndex) {
mask := uint64(18446744004990074880)
b.header &= ^mask
b.header |= ((uint64(v) << 36) & mask)
}
// GetLength returns the Length field in the PropertyBlock.
func (b *PropertyBlock) GetLength() uint {
return uint((b.payload & 4294967295) >> 0)
}
// SetLength sets the Length field in the PropertyBlock.
func (b *PropertyBlock) SetLength(v uint) {
mask := uint64(4294967295)
b.payload &= ^mask
b.payload |= ((uint64(v) << 0) & mask)
}
// GetExtentIndex returns the ExtentIndex field in the PropertyBlock.
func (b *PropertyBlock) GetExtentIndex() uint {
return uint((b.payload & 1152921500311879680) >> 32)
}
// SetExtentIndex sets the ExtentIndex field in the PropertyBlock.
func (b *PropertyBlock) SetExtentIndex(v uint) {
mask := uint64(1152921500311879680)
b.payload &= ^mask
b.payload |= ((uint64(v) << 32) & mask)
}
// GetFlags returns the Flags field in the PropertyBlock.
func (b *PropertyBlock) GetFlags() uint {
return uint((b.payload & 17293822569102704640) >> 60)
}
// SetFlags sets the Flags field in the PropertyBlock.
func (b *PropertyBlock) SetFlags(v uint) {
mask := uint64(17293822569102704640)
b.payload &= ^mask
b.payload |= ((uint64(v) << 60) & mask)
}
// The ExtentBlock type represents a block of type ExtentBlock.
type ExtentBlock Block
// SetHeader sets the header fields for ExtentBlock.
func (b *ExtentBlock) SetHeader(Order BlockOrder, Type BlockType, NextExtent BlockIndex) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(NextExtent) << 8) & 68719476480))
}
// GetOrder returns the Order field in the ExtentBlock.
func (b *ExtentBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the ExtentBlock.
func (b *ExtentBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the ExtentBlock.
func (b *ExtentBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the ExtentBlock.
func (b *ExtentBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetNextExtent returns the NextExtent field in the ExtentBlock.
func (b *ExtentBlock) GetNextExtent() BlockIndex {
return BlockIndex((b.header & 68719476480) >> 8)
}
// SetNextExtent sets the NextExtent field in the ExtentBlock.
func (b *ExtentBlock) SetNextExtent(v BlockIndex) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// The NameBlock type represents a block of type NameBlock.
type NameBlock Block
// SetHeader sets the header fields for NameBlock.
func (b *NameBlock) SetHeader(Order BlockOrder, Type BlockType, Length uint) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(Length) << 8) & 1048320))
}
// GetOrder returns the Order field in the NameBlock.
func (b *NameBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the NameBlock.
func (b *NameBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the NameBlock.
func (b *NameBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the NameBlock.
func (b *NameBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetLength returns the Length field in the NameBlock.
func (b *NameBlock) GetLength() uint {
return uint((b.header & 1048320) >> 8)
}
// SetLength sets the Length field in the NameBlock.
func (b *NameBlock) SetLength(v uint) {
mask := uint64(1048320)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
func (b *NameBlock) SetPayload(data []byte) {
p := uintptr(unsafe.Pointer(b)) + 8
for i, v := range data {
*(*byte)(unsafe.Pointer(p + uintptr(i))) = v
}
}
// The TombstoneBlock type represents a block of type TombstoneBlock.
type TombstoneBlock Block
// SetHeader sets the header fields for TombstoneBlock.
func (b *TombstoneBlock) SetHeader(Order BlockOrder, Type BlockType) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240))
}
// GetOrder returns the Order field in the TombstoneBlock.
func (b *TombstoneBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the TombstoneBlock.
func (b *TombstoneBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the TombstoneBlock.
func (b *TombstoneBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the TombstoneBlock.
func (b *TombstoneBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetRefCount returns the RefCount field in the TombstoneBlock.
func (b *TombstoneBlock) GetRefCount() uint64 {
return uint64((b.payload & 18446744073709551615) >> 0)
}
// SetRefCount sets the RefCount field in the TombstoneBlock.
func (b *TombstoneBlock) SetRefCount(v uint64) {
mask := uint64(18446744073709551615)
b.payload &= ^mask
b.payload |= ((uint64(v) << 0) & mask)
}
// The ArrayBlock type represents a block of type ArrayBlock.
type ArrayBlock Block
// SetHeader sets the header fields for ArrayBlock.
func (b *ArrayBlock) SetHeader(Order BlockOrder, Type BlockType, ParentIndex BlockIndex, NameIndex BlockIndex) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240) | ((uint64(ParentIndex) << 8) & 68719476480) | ((uint64(NameIndex) << 36) & 18446744004990074880))
}
// GetOrder returns the Order field in the ArrayBlock.
func (b *ArrayBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the ArrayBlock.
func (b *ArrayBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the ArrayBlock.
func (b *ArrayBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the ArrayBlock.
func (b *ArrayBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetParentIndex returns the ParentIndex field in the ArrayBlock.
func (b *ArrayBlock) GetParentIndex() BlockIndex {
return BlockIndex((b.header & 68719476480) >> 8)
}
// SetParentIndex sets the ParentIndex field in the ArrayBlock.
func (b *ArrayBlock) SetParentIndex(v BlockIndex) {
mask := uint64(68719476480)
b.header &= ^mask
b.header |= ((uint64(v) << 8) & mask)
}
// GetNameIndex returns the NameIndex field in the ArrayBlock.
func (b *ArrayBlock) GetNameIndex() BlockIndex {
return BlockIndex((b.header & 18446744004990074880) >> 36)
}
// SetNameIndex sets the NameIndex field in the ArrayBlock.
func (b *ArrayBlock) SetNameIndex(v BlockIndex) {
mask := uint64(18446744004990074880)
b.header &= ^mask
b.header |= ((uint64(v) << 36) & mask)
}
// GetEntryType returns the EntryType field in the ArrayBlock.
func (b *ArrayBlock) GetEntryType() uint {
return uint((b.payload & 15) >> 0)
}
// SetEntryType sets the EntryType field in the ArrayBlock.
func (b *ArrayBlock) SetEntryType(v uint) {
mask := uint64(15)
b.payload &= ^mask
b.payload |= ((uint64(v) << 0) & mask)
}
// GetFlags returns the Flags field in the ArrayBlock.
func (b *ArrayBlock) GetFlags() uint {
return uint((b.payload & 240) >> 4)
}
// SetFlags sets the Flags field in the ArrayBlock.
func (b *ArrayBlock) SetFlags(v uint) {
mask := uint64(240)
b.payload &= ^mask
b.payload |= ((uint64(v) << 4) & mask)
}
// GetCount returns the Count field in the ArrayBlock.
func (b *ArrayBlock) GetCount() uint {
return uint((b.payload & 65280) >> 8)
}
// SetCount sets the Count field in the ArrayBlock.
func (b *ArrayBlock) SetCount(v uint) {
mask := uint64(65280)
b.payload &= ^mask
b.payload |= ((uint64(v) << 8) & mask)
}
func (b *ArrayBlock) SetPayload(data []byte) {
p := uintptr(unsafe.Pointer(b)) + 16
for i, v := range data {
*(*byte)(unsafe.Pointer(p + uintptr(i))) = v
}
}
// The LinkBlock type represents a block of type LinkBlock.
type LinkBlock Block
// SetHeader sets the header fields for LinkBlock.
func (b *LinkBlock) SetHeader(Order BlockOrder, Type BlockType) {
b.header = uint64(((uint64(Order) << 0) & 15) | ((uint64(Type) << 4) & 240))
}
// GetOrder returns the Order field in the LinkBlock.
func (b *LinkBlock) GetOrder() BlockOrder {
return BlockOrder((b.header & 15) >> 0)
}
// SetOrder sets the Order field in the LinkBlock.
func (b *LinkBlock) SetOrder(v BlockOrder) {
mask := uint64(15)
b.header &= ^mask
b.header |= ((uint64(v) << 0) & mask)
}
// GetType returns the Type field in the LinkBlock.
func (b *LinkBlock) GetType() BlockType {
return BlockType((b.header & 240) >> 4)
}
// SetType sets the Type field in the LinkBlock.
func (b *LinkBlock) SetType(v BlockType) {
mask := uint64(240)
b.header &= ^mask
b.header |= ((uint64(v) << 4) & mask)
}
// GetContextIndex returns the ContextIndex field in the LinkBlock.
func (b *LinkBlock) GetContextIndex() uint {
return uint((b.payload & 1048575) >> 0)
}
// SetContextIndex sets the ContextIndex field in the LinkBlock.
func (b *LinkBlock) SetContextIndex(v uint) {
mask := uint64(1048575)
b.payload &= ^mask
b.payload |= ((uint64(v) << 0) & mask)
}
// GetFlags returns the Flags field in the LinkBlock.
func (b *LinkBlock) GetFlags() uint {
return uint((b.payload & 17293822569102704640) >> 60)
}
// SetFlags sets the Flags field in the LinkBlock.
func (b *LinkBlock) SetFlags(v uint) {
mask := uint64(17293822569102704640)
b.payload &= ^mask
b.payload |= ((uint64(v) << 60) & mask)
} | garnet/go/src/inspect/block.go | 0.730963 | 0.461259 | block.go | starcoder |
package validate
import (
stdliberr "errors"
"reflect"
"time"
"go.thethings.network/lorawan-stack/pkg/errors"
"go.thethings.network/lorawan-stack/pkg/types"
)
// IsZeroer is an interface, which reports whether it represents a zero value.
type IsZeroer interface {
IsZero() bool
}
var isZeroerType = reflect.TypeOf((*IsZeroer)(nil)).Elem()
// isZeroValue is like isZero, but acts on values of reflect.Value type.
func isZeroValue(v reflect.Value) bool {
iv := reflect.Indirect(v)
if !iv.IsValid() {
return true
}
if v.Type().Implements(isZeroerType) {
return v.Interface().(IsZeroer).IsZero()
}
if iv.Type().Implements(isZeroerType) {
return iv.Interface().(IsZeroer).IsZero()
}
v = iv
switch v.Kind() {
case reflect.Array:
for i := 0; i < v.Len(); i++ {
if !isZero(v.Index(i)) {
return false
}
}
return true
case reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Complex64, reflect.Complex128:
return v.Complex() == 0
case reflect.Chan, reflect.Func, reflect.Interface:
return v.IsNil()
case reflect.UnsafePointer:
return v.Pointer() == 0
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
if !isZeroValue(v.Field(i)) {
return false
}
}
return true
}
return v.Interface() == reflect.Zero(v.Type()).Interface()
}
// isZero reports whether the value is the zero of its type.
func isZero(v interface{}) bool {
if v == nil {
return true
}
switch v := v.(type) {
case nil:
return true
case bool:
return !v
case int:
return v == 0
case int64:
return v == 0
case int32:
return v == 0
case int16:
return v == 0
case int8:
return v == 0
case uint:
return v == 0
case uint64:
return v == 0
case uint32:
return v == 0
case uint16:
return v == 0
case uint8:
return v == 0
case float64:
return v == 0
case float32:
return v == 0
case string:
return v == ""
case []bool:
return len(v) == 0
case []string:
return len(v) == 0
case []uint:
return len(v) == 0
case []uint64:
return len(v) == 0
case []uint32:
return len(v) == 0
case []uint16:
return len(v) == 0
case []uint8:
return len(v) == 0
case []int:
return len(v) == 0
case []int64:
return len(v) == 0
case []int32:
return len(v) == 0
case []int16:
return len(v) == 0
case []int8:
return len(v) == 0
case []float64:
return len(v) == 0
case []float32:
return len(v) == 0
case map[string]interface{}:
return len(v) == 0
case map[string]string:
return len(v) == 0
case *time.Time:
return v == nil || v.IsZero()
case time.Time:
return v.IsZero()
case *types.AES128Key:
return v == nil || v.IsZero()
case types.AES128Key:
return v.IsZero()
case *types.EUI64:
return v == nil || v.IsZero()
case types.EUI64:
return v.IsZero()
case *types.NetID:
return v == nil || v.IsZero()
case types.NetID:
return v.IsZero()
case *types.DevAddr:
return v == nil || v.IsZero()
case types.DevAddr:
return v.IsZero()
case *types.DevNonce:
return v == nil || v.IsZero()
case types.DevNonce:
return v.IsZero()
case *types.JoinNonce:
return v == nil || v.IsZero()
case types.JoinNonce:
return v.IsZero()
}
return isZeroValue(reflect.ValueOf(v))
}
var errFieldSet = errors.DefineInvalidArgument("field_set", "field is set")
// Empty returns error if v is set.
// It is meant to be used as the first validator function passed as argument to Field.
// It uses IsZero, if v implements IsZeroer interface.
func Empty(v interface{}) error {
if !isZero(v) {
return errFieldSet.New()
}
return nil
}
// errZeroValue is a flag value indicating a value is not required. If a value is not set,
// requirements on its value will be ignored.
var errZeroValue = stdliberr.New("Value not set")
// NotRequired returns an error, used internally in Field, if v is zero.
// It is meant to be used as the first validator function passed as argument to Field.
// It uses IsZero, if v implements IsZeroer interface.
func NotRequired(v interface{}) error {
if isZero(v) {
return errZeroValue
}
return nil
}
// Required returns error if v is empty.
// It is meant to be used as the first validator function passed as argument to Field.
// It uses IsZero, if v implements IsZeroer interface.
func Required(v interface{}) error {
if isZero(v) {
return errRequired.New()
}
return nil
} | pkg/validate/required.go | 0.61855 | 0.51312 | required.go | starcoder |
package main
// ObjCustomDice builds a dice centered in the origin, the size of an edge is 2*(1+R)
func ObjCustomDice(matBody, matDots *Material, R, D float64) *Csg {
objects := []Groupable{}
add := func(object *Shape) {
objects = append(objects, object)
}
dice_edge := func(x, y, z, rotx, rotz float64) {
cylinder := NewCylinder(-1, +1, true) // Cylinder must be capped or visual artifacts occur!
cylinder.SetTransform(Translation(x, y, z), RotationX(rotx), RotationZ(rotz), Scaling(R, 1, R))
add(cylinder)
}
dice_corner := func(x, y, z float64) {
sphere := NewSphere()
sphere.SetTransform(Translation(x, y, z), Scaling(R))
add(sphere)
}
dice_face := func(x, y, z float64) {
cube := NewCube()
cube.SetTransform(Scaling(1+x, 1+y, 1+z))
add(cube)
}
dice_number := func(x, y, z float64) {
sphere := NewSphere()
sphere.SetTransform(Translation(x, y, z), Scaling(R))
add(sphere)
// Debugf("translate(%.2f, %.2f, %.2f, scale(%.2f, sphere {} ))\n", x, y, z, R)
}
dice_edge(-1, 0, -1, 0, 0)
dice_edge(-1, 0, +1, 0, 0)
dice_edge(+1, 0, -1, 0, 0)
dice_edge(+1, 0, +1, 0, 0)
dice_edge(-1, -1, 0, Pi/2, 0)
dice_edge(-1, +1, 0, Pi/2, 0)
dice_edge(+1, -1, 0, Pi/2, 0)
dice_edge(+1, +1, 0, Pi/2, 0)
dice_edge(0, -1, -1, 0, Pi/2)
dice_edge(0, +1, -1, 0, Pi/2)
dice_edge(0, -1, +1, 0, Pi/2)
dice_edge(0, +1, +1, 0, Pi/2)
dice_corner(-1, -1, -1)
dice_corner(-1, +1, -1)
dice_corner(+1, -1, -1)
dice_corner(+1, +1, -1)
dice_corner(-1, -1, +1)
dice_corner(-1, +1, +1)
dice_corner(+1, -1, +1)
dice_corner(+1, +1, +1)
dice_face(R, 0, 0)
dice_face(0, R, 0)
dice_face(0, 0, R)
csgBody := NewCsgUnion(objects...)
csgBody.SetMaterial(matBody)
objects = objects[:0]
dice_number(0, 0, -1-R) // 1
dice_number(1+R, -D, -D) // 2
dice_number(1+R, D, D)
dice_number(0, -1-R, 0) // 3
dice_number(-D, -1-R, -D)
dice_number(D, -1-R, D)
dice_number(-D, 1+R, -D) // 4
dice_number(-D, 1+R, +D)
dice_number(+D, 1+R, -D)
dice_number(+D, 1+R, +D)
dice_number(-1-R, D, D) // 5
dice_number(-1-R, -D, D)
dice_number(-1-R, -D, -D)
dice_number(-1-R, D, -D)
dice_number(-1-R, 0, 0)
dice_number(-D, -D, 1+R) // 6
dice_number(-D, 0, 1+R)
dice_number(-D, D, 1+R)
dice_number(+D, -D, 1+R)
dice_number(+D, 0, 1+R)
dice_number(+D, D, 1+R)
csgDots := NewCsgUnion(objects...)
csgDots.SetMaterial(matDots)
csg := NewCsg(CsgDifference, csgBody, csgDots)
return csg
}
func ObjDice(body, dots Color) *Csg {
return ObjCustomDice(MatMatte(body), MatMatte(dots), 0.18, 0.60)
}
func init() {
ObjDice(Black, White)
} | stock_shapes.go | 0.659515 | 0.605303 | stock_shapes.go | starcoder |
package iso20022
// Provides amounts taken in to account to calculate the collateral position.
type SummaryAmounts1 struct {
// Amount of unsecured exposure a counterparty will accept before issuing a margin call in the base currency.
ThresholdAmount *ActiveCurrencyAndAmount `xml:"ThrshldAmt,omitempty"`
// Specifies if the threshold amount is secured or unsecured.
ThresholdType *ThresholdType1Code `xml:"ThrshldTp,omitempty"`
// Total value of posted collateral (pre-haircut) held by the taker.
PreHaircutCollateralValue *ActiveCurrencyAndAmount `xml:"PreHrcutCollVal,omitempty"`
// Total amount of collateral required (unrounded).
AdjustedExposure *ActiveCurrencyAndAmount `xml:"AdjstdXpsr,omitempty"`
// Total amount of collateral required (rounded).
CollateralRequired *ActiveCurrencyAndAmount `xml:"CollReqrd,omitempty"`
// Minimum amount to pay/receive as specified in the agreement in the base currency (to avoid the need to transfer an inconveniently small amount of collateral).
MinimumTransferAmount *ActiveCurrencyAndAmount `xml:"MinTrfAmt,omitempty"`
// Amount specified to avoid the need to transfer uneven amounts of collateral.
RoundingAmount *ActiveCurrencyAndAmount `xml:"RndgAmt,omitempty"`
// Exposure value at previous valuation.
PreviousExposureValue *ActiveCurrencyAndAmount `xml:"PrvsXpsrVal,omitempty"`
// Value of collateral at previous valuation.
PreviousCollateralValue *ActiveCurrencyAndAmount `xml:"PrvsCollVal,omitempty"`
// Value of incoming collateral, to be settled.
TotalPendingIncomingCollateral *ActiveCurrencyAndAmount `xml:"TtlPdgIncmgColl,omitempty"`
// Value of outgoing collateral, to be settled.
TotalPendingOutgoingCollateral *ActiveCurrencyAndAmount `xml:"TtlPdgOutgngColl,omitempty"`
// Sum of accrued interest.
TotalAccruedInterestAmount *ActiveCurrencyAndAmount `xml:"TtlAcrdIntrstAmt,omitempty"`
// Sum of fees/commissions.
TotalFees *ActiveCurrencyAndAmount `xml:"TtlFees,omitempty"`
}
func (s *SummaryAmounts1) SetThresholdAmount(value, currency string) {
s.ThresholdAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetThresholdType(value string) {
s.ThresholdType = (*ThresholdType1Code)(&value)
}
func (s *SummaryAmounts1) SetPreHaircutCollateralValue(value, currency string) {
s.PreHaircutCollateralValue = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetAdjustedExposure(value, currency string) {
s.AdjustedExposure = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetCollateralRequired(value, currency string) {
s.CollateralRequired = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetMinimumTransferAmount(value, currency string) {
s.MinimumTransferAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetRoundingAmount(value, currency string) {
s.RoundingAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetPreviousExposureValue(value, currency string) {
s.PreviousExposureValue = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetPreviousCollateralValue(value, currency string) {
s.PreviousCollateralValue = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetTotalPendingIncomingCollateral(value, currency string) {
s.TotalPendingIncomingCollateral = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetTotalPendingOutgoingCollateral(value, currency string) {
s.TotalPendingOutgoingCollateral = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetTotalAccruedInterestAmount(value, currency string) {
s.TotalAccruedInterestAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SummaryAmounts1) SetTotalFees(value, currency string) {
s.TotalFees = NewActiveCurrencyAndAmount(value, currency)
} | SummaryAmounts1.go | 0.849504 | 0.464719 | SummaryAmounts1.go | starcoder |
package xlsx
import (
"fmt"
)
// Row represents a single Row in the current Sheet.
type Row struct {
Hidden bool // Hidden determines whether this Row is hidden or not.
Sheet *Sheet // Sheet is a reference back to the Sheet that this Row is within.
height float64 // Height is the current height of the Row in PostScript Points
outlineLevel uint8 // OutlineLevel contains the outline level of this Row. Used for collapsing.
isCustom bool // isCustom is a flag that is set to true when the Row has been modified
num int // Num hold the positional number of the Row in the Sheet
cellStoreRow CellStoreRow // A reference to the underlying CellStoreRow which handles persistence of the cells
}
// GetCoordinate returns the y coordinate of the row (the row number). This number is zero based, i.e. the Excel CellID "A1" is in Row 0, not Row 1.
func (r *Row) GetCoordinate() int {
return r.num
}
// SetHeight sets the height of the Row in PostScript points
func (r *Row) SetHeight(ht float64) {
r.cellStoreRow.Updatable()
r.height = ht
r.isCustom = true
}
// SetHeightCM sets the height of the Row in centimetres, inherently converting it to PostScript points.
func (r *Row) SetHeightCM(ht float64) {
r.cellStoreRow.Updatable()
r.height = ht * 28.3464567 // Convert CM to postscript points
r.isCustom = true
}
// GetHeight returns the height of the Row in PostScript points.
func (r *Row) GetHeight() float64 {
return r.height
}
// SetOutlineLevel sets the outline level of the Row (used for collapsing rows)
func (r *Row) SetOutlineLevel(outlineLevel uint8) {
r.cellStoreRow.Updatable()
r.outlineLevel = outlineLevel
if r.Sheet != nil {
if r.outlineLevel > r.Sheet.SheetFormat.OutlineLevelRow {
r.Sheet.SheetFormat.OutlineLevelRow = outlineLevel
}
}
r.isCustom = true
}
// GetOutlineLevel returns the outline level of the Row.
func (r *Row) GetOutlineLevel() uint8 {
return r.outlineLevel
}
// AddCell adds a new Cell to the end of the Row
func (r *Row) AddCell() *Cell {
r.cellStoreRow.Updatable()
r.isCustom = true
cell := r.cellStoreRow.AddCell()
if cell.num > r.Sheet.MaxCol-1 {
r.Sheet.MaxCol = cell.num + 1
}
return cell
}
// PushCell adds a predefiend cell to the end of the Row
func (r *Row) PushCell(c *Cell) {
r.cellStoreRow.Updatable()
r.isCustom = true
r.cellStoreRow.PushCell(c)
}
func (r *Row) makeCellKey(colIdx int) string {
return fmt.Sprintf("%s:%06d:%06d", r.Sheet.Name, r.num, colIdx)
}
func (r *Row) key() string {
return r.makeCellKeyRowPrefix()
}
func (r *Row) makeCellKeyRowPrefix() string {
return fmt.Sprintf("%s:%06d", r.Sheet.Name, r.num)
}
func (r *Row) makeRowNum() string {
return fmt.Sprintf("%06d", r.num)
}
// GetCell returns the Cell at a given column index, creating it if it doesn't exist.
func (r *Row) GetCell(colIdx int) *Cell {
return r.cellStoreRow.GetCell(colIdx)
}
// cellVisitorFlags contains flags that can be set by CellVisitorOption implementations to modify the behaviour of ForEachCell
type cellVisitorFlags struct {
// skipEmptyCells indicates if we should skip nil cells.
skipEmptyCells bool
}
// CellVisitorOption describes a function that can set values in a
// cellVisitorFlags struct to affect the way ForEachCell operates
type CellVisitorOption func(flags *cellVisitorFlags)
// SkipEmptyCells can be passed as an option to Row.ForEachCell in
// order to make it skip over empty cells in the sheet.
func SkipEmptyCells(flags *cellVisitorFlags) {
flags.skipEmptyCells = true
}
// ForEachCell will call the provided CellVisitorFunc for each
// currently defined cell in the Row. Optionally you may pass one or
// more CellVisitorOption to affect how ForEachCell operates. For
// example you may wish to pass SkipEmptyCells to only visit cells
// which are populated.
func (r *Row) ForEachCell(cvf CellVisitorFunc, option ...CellVisitorOption) error {
return r.cellStoreRow.ForEachCell(cvf, option...)
} | row.go | 0.789842 | 0.51501 | row.go | starcoder |
package geo
import (
"math"
)
const (
earthRadius = 6371e3
radians = math.Pi / 180
degrees = 180 / math.Pi
)
// DistanceTo return the distance in meteres between two point.
func DistanceTo(latA, lonA, latB, lonB float64) (meters float64) {
φ1 := latA * radians
λ1 := lonA * radians
φ2 := latB * radians
λ2 := lonB * radians
Δφ := φ2 - φ1
Δλ := λ2 - λ1
a := math.Sin(Δφ/2)*math.Sin(Δφ/2) +
math.Cos(φ1)*math.Cos(φ2)*math.Sin(Δλ/2)*math.Sin(Δλ/2)
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
return earthRadius * c
}
// DestinationPoint return the destination from a point based on a
// distance and bearing.
func DestinationPoint(lat, lon, meters, bearingDegrees float64) (
destLat, destLon float64,
) {
// see http://williams.best.vwh.net/avform.htm#LL
δ := meters / earthRadius // angular distance in radians
θ := bearingDegrees * radians
φ1 := lat * radians
λ1 := lon * radians
φ2 := math.Asin(math.Sin(φ1)*math.Cos(δ) +
math.Cos(φ1)*math.Sin(δ)*math.Cos(θ))
λ2 := λ1 + math.Atan2(math.Sin(θ)*math.Sin(δ)*math.Cos(φ1),
math.Cos(δ)-math.Sin(φ1)*math.Sin(φ2))
λ2 = math.Mod(λ2+3*math.Pi, 2*math.Pi) - math.Pi // normalise to -180..+180°
return φ2 * degrees, λ2 * degrees
}
// BearingTo returns the (initial) bearing from point 'A' to point 'B'.
func BearingTo(latA, lonA, latB, lonB float64) float64 {
// tanθ = sinΔλ⋅cosφ2 / cosφ1⋅sinφ2 − sinφ1⋅cosφ2⋅cosΔλ
// see mathforum.org/library/drmath/view/55417.html for derivation
φ1 := latA * radians
φ2 := latB * radians
Δλ := (lonB - lonA) * radians
y := math.Sin(Δλ) * math.Cos(φ2)
x := math.Cos(φ1)*math.Sin(φ2) - math.Sin(φ1)*math.Cos(φ2)*math.Cos(Δλ)
θ := math.Atan2(y, x)
return math.Mod(θ*degrees+360, 360)
}
// // SegmentIntersectsCircle ...
// func SegmentIntersectsCircle(
// startLat, startLon, endLat, endLon, centerLat, centerLon, meters float64,
// ) bool {
// // These are faster checks.
// // If they succeed there's no need do complicate things.
// if DistanceTo(startLat, startLon, centerLat, centerLon) <= meters {
// return true
// }
// if DistanceTo(endLat, endLon, centerLat, centerLon) <= meters {
// return true
// }
// // Distance between start and end
// l := DistanceTo(startLat, startLon, endLat, endLon)
// // Unit direction vector
// dLat := (endLat - startLat) / l
// dLon := (endLon - startLon) / l
// // Point of the line closest to the center
// t := dLon*(centerLon-startLon) + dLat*(centerLat-startLat)
// pLat := t*dLat + startLat
// pLon := t*dLon + startLon
// if pLon < startLon || pLon > endLon || pLat < startLat || pLat > endLat {
// // closest point is outside the segment
// return false
// }
// // Distance from the closest point to the center
// return DistanceTo(centerLat, centerLon, pLat, pLon) <= meters
// } | vendor/github.com/tidwall/geojson/geo/geo.go | 0.679604 | 0.710531 | geo.go | starcoder |
package export
import (
"github.com/opendroid/hk/logger"
"go.uber.org/zap"
"sort"
"strconv"
"strings"
)
// WalkingDataElement for daily StepCount and DistanceWalkingRunning
type WalkingDataElement struct {
YYYYMMDD string `json:"yyyymmdd"` // CreationDate truncated to CreationDate in format "YYYY-MM-DD"
SourceName string `json:"source"`
Unit string `json:"unit,omitempty"`
Value float32 `json:"value"`
Count int `json:"count"`
}
// WalkerData holds step count and walking orr running distance
type WalkerData struct {
StepCount []WalkingDataElement `json:"step_count"`
DistanceWalkingRunning []WalkingDataElement `json:"distance_walking_running"`
}
// Get Walker data and send back
func (h *HealthData) WalkerData() *WalkerData {
if h == nil {
return nil
}
// Save data as sum by date
sc := make(map[string]WalkingDataElement)
dwr := make(map[string]WalkingDataElement)
skipped := make(map[string]int)
for _, r := range h.Records {
sd := string([]byte(r.StartDate)[:10])
ed := string([]byte(r.EndDate)[:10])
if sd == ed { // For now ignore multi day data
if RecordType(r.Type) == StepCount {
saveWalkElementValue(sc, &r)
} else if RecordType(r.Type) == DistanceWalkingRunning {
saveWalkElementValue(dwr, &r)
}
} else {
skipped[r.Type]++
}
}
a, _ := maps2SortedSlice(skipped)
logger.Info("Skipped", zap.Array("skipped", a))
var wd WalkerData // Prepare data
wd.StepCount = make([]WalkingDataElement, 0) // Create underlying data slice for Steps
wd.DistanceWalkingRunning = make([]WalkingDataElement, 0)
wd.StepCount = mapToWalkingDataElementSlice(wd.StepCount, sc)
wd.DistanceWalkingRunning = mapToWalkingDataElementSlice(wd.DistanceWalkingRunning, dwr)
return &wd
}
// saveWalkElementValue adds a record 'r' to map[yyyymmdd]
func saveWalkElementValue(m map[string]WalkingDataElement, r *Record) {
date := strings.Split(r.StartDate, " ") // Extract "2019-10-23" from "2019-10-23 19:10:11 -0800"
if len(date) == 0 {
logger.Warn("Illegal date", zap.String("method", "saveStepCount"), zap.String("date", r.StartDate))
return
}
d := date[0] // Valid date extracted
num, err := strconv.ParseFloat(r.Value, 32) // Convert value to a number
if err != nil {
logger.Error("strconv error",
zap.String("method", "saveStepCount"),
zap.String("value", r.Value), zap.String("info", err.Error()))
}
// Add 'r' record to m["2019-10-23"]
v, ok := m[d]
if !ok { // New value for the day
m[d] = WalkingDataElement{d, r.SourceName, r.Unit, float32(num), 1}
return
}
// Update collected value so far
if v.Unit != r.Unit { // For now log and continue
logger.Warn("Non matching unit", zap.String("method", "saveStepCount"),
zap.String("found", r.Unit), zap.String("new", v.Unit))
}
if !strings.Contains(v.SourceName, r.SourceName) {
v.SourceName += ", " + r.SourceName // For now append all unique sources
}
v.Value += float32(num)
v.Count++ // How many such counts for a day
m[d] = v // Update value
}
func mapToWalkingDataElementSlice(wd []WalkingDataElement, m map[string]WalkingDataElement) []WalkingDataElement {
for _, v := range m {
wd = append(wd, v)
}
sort.Slice(wd, func(i, j int) bool { return wd[i].YYYYMMDD < wd[j].YYYYMMDD })
return wd
}
// Get all GetRecords
func (h *HealthData) GetRecords(tag RecordType, date string) []Record {
if h == nil {
return nil
}
wd := make([]Record, 0)
for _, r := range h.Records {
if (tag == All || RecordType(r.Type) == tag) && strings.Contains(r.CreationDate, date) {
wd = append(wd, r)
}
}
sort.Slice(wd, func(i, j int) bool { return wd[i].StartDate > wd[j].StartDate })
return wd
} | export/walking.go | 0.521959 | 0.418103 | walking.go | starcoder |
package minmax
import "math"
// F64 represents a min / max range for float64 values.
// Supports clipping, renormalizing, etc
type F64 struct {
Min float64
Max float64
}
// Set sets the min and max values
func (mr *F64) Set(min, max float64) {
mr.Min, mr.Max = min, max
}
// SetInfinity sets the Min to +MaxFloat, Max to -MaxFloat -- suitable for
// iteratively calling Fit*InRange
func (mr *F64) SetInfinity() {
mr.Min, mr.Max = math.MaxFloat64, -math.MaxFloat64
}
// IsValid returns true if Min <= Max
func (mr *F64) IsValid() bool {
return mr.Min <= mr.Max
}
// InRange tests whether value is within the range (>= Min and <= Max)
func (mr *F64) InRange(val float64) bool {
return ((val >= mr.Min) && (val <= mr.Max))
}
// IsLow tests whether value is lower than the minimum
func (mr *F64) IsLow(val float64) bool {
return (val < mr.Min)
}
// IsHigh tests whether value is higher than the maximum
func (mr *F64) IsHigh(val float64) bool {
return (val > mr.Min)
}
// Range returns Max - Min
func (mr *F64) Range() float64 {
return mr.Max - mr.Min
}
// Scale returns 1 / Range -- if Range = 0 then returns 0
func (mr *F64) Scale() float64 {
r := mr.Range()
if r != 0 {
return 1 / r
}
return 0
}
// Midpoint returns point halfway between Min and Max
func (mr *F64) Midpoint() float64 {
return 0.5 * (mr.Max + mr.Min)
}
// FitInRange adjusts our Min, Max to fit within those of other F64
// returns true if we had to adjust to fit.
func (mr *F64) FitInRange(oth F64) bool {
adj := false
if oth.Min < mr.Min {
mr.Min = oth.Min
adj = true
}
if oth.Max > mr.Max {
mr.Max = oth.Max
adj = true
}
return adj
}
// FitValInRange adjusts our Min, Max to fit given value within Min, Max range
// returns true if we had to adjust to fit.
func (mr *F64) FitValInRange(val float64) bool {
adj := false
if val < mr.Min {
mr.Min = val
adj = true
}
if val > mr.Max {
mr.Max = val
adj = true
}
return adj
}
// NormVal normalizes value to 0-1 unit range relative to current Min / Max range
// Clips the value within Min-Max range first.
func (mr *F64) NormVal(val float64) float64 {
return (mr.ClipVal(val) - mr.Min) * mr.Scale()
}
// ProjVal projects a 0-1 normalized unit value into current Min / Max range (inverse of NormVal)
func (mr *F64) ProjVal(val float64) float64 {
return mr.Min + (val * mr.Range())
}
// ClipVal clips given value within Min / Max rangee
func (mr *F64) ClipVal(val float64) float64 {
if val < mr.Min {
return mr.Min
}
if val > mr.Max {
return mr.Max
}
return val
}
// ClipNormVal clips then normalizes given value within 0-1
func (mr *F64) ClipNormVal(val float64) float64 {
if val < mr.Min {
return 0
}
if val > mr.Max {
return 1
}
return mr.NormVal(val)
} | minmax/minmax64.go | 0.853684 | 0.582105 | minmax64.go | starcoder |
package ring
import (
"encoding/binary"
"errors"
"math/bits"
)
// Poly is the structure containing the coefficients of a polynomial.
type Poly struct {
Coeffs [][]uint64 //Coefficients in CRT representation
}
// GetDegree returns the number of coefficients (degree) of the polynomial.
func (Pol *Poly) GetDegree() int {
return len(Pol.Coeffs[0])
}
// GetLenModuli returns the number of modulies
func (Pol *Poly) GetLenModuli() int {
return len(Pol.Coeffs)
}
// Zero sets all coefficient of the target polynomial to 0.
func (Pol *Poly) Zero() {
for i := range Pol.Coeffs {
p0tmp := Pol.Coeffs[i]
for j := range Pol.Coeffs[0] {
p0tmp[j] = 0
}
}
}
// CopyNew creates a new polynomial p1 which is a copy of the target polynomial.
func (Pol *Poly) CopyNew() (p1 *Poly) {
p1 = new(Poly)
p1.Coeffs = make([][]uint64, len(Pol.Coeffs))
for i := range Pol.Coeffs {
p1.Coeffs[i] = make([]uint64, len(Pol.Coeffs[i]))
p0tmp, p1tmp := Pol.Coeffs[i], p1.Coeffs[i]
for j := range Pol.Coeffs[i] {
p1tmp[j] = p0tmp[j]
}
}
return p1
}
// Copy copies the coefficients of p0 on p1 within the given context. Requiers p1 to be as big as the target context.
func (context *Context) Copy(p0, p1 *Poly) {
if p0 != p1 {
for i := range context.Modulus {
p0tmp, p1tmp := p0.Coeffs[i], p1.Coeffs[i]
for j := uint64(0); j < context.N; j++ {
p1tmp[j] = p0tmp[j]
}
}
}
}
// Copy copies the coefficients of p0 on p1 within the given context. Requiers p1 to be as big as the target context.
func (context *Context) CopyLvl(level uint64, p0, p1 *Poly) {
if p0 != p1 {
for i := uint64(0); i < level+1; i++ {
p0tmp, p1tmp := p0.Coeffs[i], p1.Coeffs[i]
for j := uint64(0); j < context.N; j++ {
p1tmp[j] = p0tmp[j]
}
}
}
}
// Copy copies the receiver's coefficients from p1.
func (Pol *Poly) Copy(p1 *Poly) {
if Pol != p1 {
for i := range p1.Coeffs {
p0tmp, p1tmp := Pol.Coeffs[i], p1.Coeffs[i]
for j := range p1.Coeffs[i] {
p0tmp[j] = p1tmp[j]
}
}
}
}
// SetCoefficients sets the coefficients of polynomial directly from a CRT format (double slice).
func (Pol *Poly) SetCoefficients(coeffs [][]uint64) {
for i := range coeffs {
for j := range coeffs[0] {
Pol.Coeffs[i][j] = coeffs[i][j]
}
}
}
// GetCoefficients returns a double slice containing the coefficients of the polynomial.
func (Pol *Poly) GetCoefficients() [][]uint64 {
coeffs := make([][]uint64, len(Pol.Coeffs))
for i := range Pol.Coeffs {
coeffs[i] = make([]uint64, len(Pol.Coeffs[i]))
for j := range Pol.Coeffs[i] {
coeffs[i][j] = Pol.Coeffs[i][j]
}
}
return coeffs
}
// WriteCoeffsTo converts a matrix of coefficients to a byte array.
func WriteCoeffsTo(pointer, N, numberModuli uint64, coeffs [][]uint64, data []byte) (uint64, error) {
tmp := N << 3
for i := uint64(0); i < numberModuli; i++ {
for j := uint64(0); j < N; j++ {
binary.BigEndian.PutUint64(data[pointer+(j<<3):pointer+((j+1)<<3)], coeffs[i][j])
}
pointer += tmp
}
return pointer, nil
}
// DecodeCoeffs converts a byte array to a matrix of coefficients.
func DecodeCoeffs(pointer, N, numberModuli uint64, coeffs [][]uint64, data []byte) (uint64, error) {
tmp := N << 3
for i := uint64(0); i < numberModuli; i++ {
for j := uint64(0); j < N; j++ {
coeffs[i][j] = binary.BigEndian.Uint64(data[pointer+(j<<3) : pointer+((j+1)<<3)])
}
pointer += tmp
}
return pointer, nil
}
// DecodeCoeffs converts a byte array to a matrix of coefficients.
func DecodeCoeffsNew(pointer, N, numberModuli uint64, coeffs [][]uint64, data []byte) (uint64, error) {
tmp := N << 3
for i := uint64(0); i < numberModuli; i++ {
coeffs[i] = make([]uint64, N)
for j := uint64(0); j < N; j++ {
coeffs[i][j] = binary.BigEndian.Uint64(data[pointer+(j<<3) : pointer+((j+1)<<3)])
}
pointer += tmp
}
return pointer, nil
}
func (Pol *Poly) MarshalBinary() ([]byte, error) {
N := uint64(len(Pol.Coeffs[0]))
numberModulies := uint64(len(Pol.Coeffs))
data := make([]byte, 2+((N*numberModulies)<<3))
if numberModulies > 0xFF {
return nil, errors.New("error : poly max modulies uint16 overflow")
}
data[0] = uint8(bits.Len64(uint64(N)) - 1)
data[1] = uint8(numberModulies)
var pointer uint64
pointer = 2
if _, err := WriteCoeffsTo(pointer, N, numberModulies, Pol.Coeffs, data); err != nil {
return nil, err
}
return data, nil
}
func (Pol *Poly) UnMarshalBinary(data []byte) (*Poly, error) {
N := uint64(int(1 << data[0]))
numberModulies := uint64(int(data[1]))
var pointer uint64
pointer = 2
if ((uint64(len(data)) - pointer) >> 3) != N*numberModulies {
return nil, errors.New("error : invalid polynomial encoding")
}
if _, err := DecodeCoeffs(pointer, N, numberModulies, Pol.Coeffs, data); err != nil {
return nil, err
}
return Pol, nil
} | HE/ring/ring_object.go | 0.713332 | 0.521167 | ring_object.go | starcoder |
package processor
import (
"time"
"github.com/Jeffail/benthos/v3/lib/bloblang/x/mapping"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/message"
"github.com/Jeffail/benthos/v3/lib/message/tracing"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/response"
"github.com/Jeffail/benthos/v3/lib/types"
"github.com/opentracing/opentracing-go"
olog "github.com/opentracing/opentracing-go/log"
"golang.org/x/xerrors"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeBloblang] = TypeSpec{
constructor: NewBloblang,
Summary: `
Executes a [Bloblang](/docs/guides/bloblang/about) mapping on messages.`,
Description: `
Bloblang is a powerful language that enables a wide range of mapping,
transformation and filtering tasks. For more information
[check out the docs](/docs/guides/bloblang/about).`,
Footnotes: `
## Error Handling
Bloblang mappings can fail, in which case the message remains unchanged, errors
are logged, and the message is flagged as having failed, allowing you to use
[standard processor error handling patterns](/docs/configuration/error_handling).
However, Bloblang itself also provides powerful ways of ensuring your mappings
do not fail by specifying desired fallback behaviour, which you can read about
[in this section](/docs/guides/bloblang/about#error-handling).
## Examples
### Mapping
Given JSON documents containing an array of fans:
` + "```json" + `
{
"id":"foo",
"description":"a show about foo",
"fans":[
{"name":"bev","obsession":0.57},
{"name":"grace","obsession":0.21},
{"name":"ali","obsession":0.89},
{"name":"vic","obsession":0.43}
]
}
` + "```" + `
We can reduce the fans to only those with an obsession score above 0.5 with this
mapping:
` + "```yaml" + `
pipeline:
processors:
- bloblang: |
root = this
fans = fans.map_each(match {
this.obsession > 0.5 => this
_ => deleted()
})
` + "```" + `
Giving us:
` + "```json" + `
{
"id":"foo",
"description":"a show about foo",
"fans":[
{"name":"bev","obsession":0.57},
{"name":"ali","obsession":0.89}
]
}
` + "```" + `
### Parsing CSV
Bloblang can be used to parse some basic CSV files, given files of the following
format:
` + "```" + `
foo,bar,baz
1,2,3
7,11,23
89,23,2
` + "```" + `
We can write a parser that does cool things like calculating the sum of each
line:
` + "```yaml" + `
pipeline:
processors:
- bloblang: |
root = content().string().split("\n").enumerated().map_each(match {
index == 0 => deleted() # Drop the first line
_ => match value.trim() {
this.length() == 0 => deleted() # Drop empty lines
_ => this.split(",") # Split the remaining by comma
}
}).map_each(
# Then do something cool like sum each row
this.map_each(this.trim().number(0)).sum()
)
` + "```" + `
To give an output like this:
` + "```json" + `
[6,41,114]
` + "```" + ``,
}
}
//------------------------------------------------------------------------------
// BloblangConfig contains configuration fields for the Bloblang processor.
type BloblangConfig string
// NewBloblangConfig returns a BloblangConfig with default values.
func NewBloblangConfig() BloblangConfig {
return ""
}
//------------------------------------------------------------------------------
// Bloblang is a processor that performs a Bloblang mapping.
type Bloblang struct {
exec *mapping.Executor
log log.Modular
stats metrics.Type
mCount metrics.StatCounter
mErr metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
mDropped metrics.StatCounter
}
// NewBloblang returns a Bloblang processor.
func NewBloblang(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
exec, err := mapping.NewExecutor(string(conf.Bloblang))
if err != nil {
return nil, xerrors.Errorf("failed to parse mapping: %w", err)
}
return &Bloblang{
exec: exec,
log: log,
stats: stats,
mCount: stats.GetCounter("count"),
mErr: stats.GetCounter("error"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
mDropped: stats.GetCounter("dropped"),
}, nil
}
//------------------------------------------------------------------------------
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (b *Bloblang) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
b.mCount.Incr(1)
newParts := make([]types.Part, 0, msg.Len())
msg.Iter(func(i int, part types.Part) error {
span := tracing.GetSpan(part)
if span == nil {
span = opentracing.StartSpan(TypeBloblang)
} else {
span = opentracing.StartSpan(
TypeBloblang,
opentracing.ChildOf(span.Context()),
)
}
p, err := b.exec.MapPart(i, msg)
if err != nil {
p = part.Copy()
b.mErr.Incr(1)
b.log.Errorf("%v\n", err)
FlagErr(p, err)
span.SetTag("error", true)
span.LogFields(
olog.String("event", "error"),
olog.String("type", err.Error()),
)
}
span.Finish()
if p != nil {
newParts = append(newParts, p)
} else {
b.mDropped.Incr(1)
}
return nil
})
if len(newParts) == 0 {
return nil, response.NewAck()
}
newMsg := message.New(nil)
newMsg.SetAll(newParts)
b.mBatchSent.Incr(1)
b.mSent.Incr(int64(newMsg.Len()))
return []types.Message{newMsg}, nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (b *Bloblang) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (b *Bloblang) WaitForClose(timeout time.Duration) error {
return nil
}
//------------------------------------------------------------------------------ | lib/processor/bloblang.go | 0.809577 | 0.746647 | bloblang.go | starcoder |
package evolution
import (
"fmt"
"math"
"math/rand"
"sort"
"sync"
)
const (
CrossoverSinglePoint = "CrossoverSinglePoint"
CrossoverFixedPoint = "CrossoverFixedPoint"
CrossoverKPoint = "CrossoverKPoint"
CrossoverUniform = "CrossoverUniform"
)
// CrossoverSinglePoint performs a single-point crossover that is dictated by the crossover percentage float.
// Both parent chromosomes are split at the percentage section specified by crossoverPercentage
func SinglePointCrossover(parentA, parentB *Individual) (childA Individual,
childB Individual,
err error) {
// Require
if parentA.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("parentA strategy cannot be nil")
}
if len(parentA.Strategy) < 1 {
return Individual{}, Individual{}, fmt.Errorf("parentA strategy cannot be empty")
}
if parentB.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("parentB strategy cannot be nil")
}
if len(parentB.Strategy) < 1 {
return Individual{}, Individual{}, fmt.Errorf("parentB strategy cannot be empty")
}
// DO
childA, _ = parentA.Clone()
childA.Id += "c1"
childA.Fitness = nil
childA.Program = nil
childA.AverageFitness = 0
childA.FitnessStdDev = 0
childA.FitnessVariance = 0
childA.Deltas = nil
childB, _ = parentB.Clone()
childB.Id += "c1"
childB.Fitness = nil
childB.Program = nil
childB.AverageFitness = 0
childB.FitnessStdDev = 0
childB.FitnessVariance = 0
childB.Deltas = nil
mut := sync.Mutex{}
mut.Lock()
if len(parentA.Strategy) >= len(parentB.Strategy) {
prob := 0
for prob == 0 {
prob = rand.Intn(len(parentB.Strategy))
}
for i := 0; i < prob; i++ {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
}
} else {
prob := 0
for prob == 0 {
prob = rand.Intn(len(parentA.Strategy))
}
for i := 0; i < prob; i++ {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
}
}
mut.Unlock()
return childA, childB, nil
}
// CrossoverSinglePoint performs a single-point crossover that is dictated by the crossover percentage float.
// Both parent chromosomes are split at the percentage section specified by crossoverPercentage
func KPointCrossover(parentA, parentB *Individual, kPoint int) (childA Individual, childB Individual, err error) {
// Require
if parentA.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("parentA strategy cannot be nil")
}
if len(parentA.Strategy) < 1 {
return Individual{}, Individual{}, fmt.Errorf("parentA strategy cannot be empty")
}
if parentB.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("parentB strategy cannot be nil")
}
if len(parentB.Strategy) < 1 {
return Individual{}, Individual{}, fmt.Errorf("parentB strategy cannot be empty")
}
//DO
childA, _ = parentA.Clone()
childA.Id += "c1"
childA.Fitness = nil
childA.Program = nil
childA.AverageFitness = 0
childA.FitnessStdDev = 0
childA.FitnessVariance = 0
childA.Deltas = nil
childB, _ = parentB.Clone()
childB.Id += "c1"
childB.Fitness = nil
childB.Program = nil
childB.AverageFitness = 0
childB.FitnessStdDev = 0
childB.FitnessVariance = 0
childB.Deltas = nil
mut := sync.Mutex{}
mut.Lock()
// Swap every element
if kPoint < 1 || (kPoint > len(parentA.Strategy) && kPoint > len(parentB.Strategy)) {
if len(parentA.Strategy) >= len(parentB.Strategy) {
for i := 0; i < len(parentB.Strategy); i++ {
if i%2 == 0 {
childA.Strategy[i] = parentA.Strategy[i]
childB.Strategy[i] = parentB.Strategy[i]
} else {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
}
}
} else {
for i := 0; i < len(parentA.Strategy); i++ {
if i%2 == 0 {
childA.Strategy[i] = parentA.Strategy[i]
childB.Strategy[i] = parentB.Strategy[i]
} else {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
}
}
}
} else {
// USe the smaller chromosome as reference for K. Randomly select K points on the smaller one.
if len(parentA.Strategy) >= len(parentB.Strategy) {
kPoints := rand.Perm(kPoint)
sort.Ints(kPoints)
shouldSwap := true
for i := 0; i < len(parentB.Strategy); i++ {
for j := range kPoints {
if i == kPoints[j] {
shouldSwap = !shouldSwap
}
if shouldSwap {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
} else {
childA.Strategy[i] = parentA.Strategy[i]
childB.Strategy[i] = parentB.Strategy[i]
}
}
}
} else {
kPoints := rand.Perm(kPoint)
sort.Ints(kPoints)
shouldSwap := true
for i := 0; i < len(parentA.Strategy); i++ {
for j := range kPoints {
if i == kPoints[j] {
shouldSwap = !shouldSwap
}
if shouldSwap {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
} else {
childA.Strategy[i] = parentA.Strategy[i]
childB.Strategy[i] = parentB.Strategy[i]
}
}
}
}
}
mut.Unlock()
return childA, childB, nil
}
// CrossoverSinglePoint performs a single-point crossover that is dictated by the crossover percentage float.
// Both parent chromosomes are split at the percentage section specified by crossoverPercentage
func UniformCrossover(parentA, parentB *Individual) (childA Individual,
childB Individual,
err error) {
// Require
if parentA.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("parentA strategy cannot be nil")
}
if len(parentA.Strategy) < 1 {
return Individual{}, Individual{}, fmt.Errorf("parentA strategy cannot be empty")
}
if parentB.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("parentB strategy cannot be nil")
}
if len(parentB.Strategy) < 1 {
return Individual{}, Individual{}, fmt.Errorf("parentB strategy cannot be empty")
}
//DO
childA, _ = parentA.Clone()
childA.Id += "c1"
childA.Fitness = nil
childA.Program = nil
childA.AverageFitness = 0
childA.FitnessStdDev = 0
childA.FitnessVariance = 0
childA.Deltas = nil
childB, _ = parentB.Clone()
childB.Id += "c1"
childB.Fitness = nil
childB.Program = nil
childB.AverageFitness = 0
childB.FitnessStdDev = 0
childB.FitnessVariance = 0
childB.Deltas = nil
mut := sync.Mutex{}
mut.Lock()
if len(parentA.Strategy) >= len(parentB.Strategy) {
for i := 0; i < len(parentB.Strategy); i++ {
prob := rand.Intn(2)
if prob == 0 {
childA.Strategy[i] = parentA.Strategy[i]
childB.Strategy[i] = parentB.Strategy[i]
} else {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
}
}
} else {
for i := 0; i < len(parentA.Strategy); i++ {
prob := rand.Intn(2)
if prob == 0 {
childA.Strategy[i] = parentA.Strategy[i]
childB.Strategy[i] = parentB.Strategy[i]
} else {
childA.Strategy[i] = parentB.Strategy[i]
childB.Strategy[i] = parentA.Strategy[i]
}
}
}
mut.Unlock()
return childA, childB, nil
}
// FixedPointCrossover will perform crossover on the strategies of a given set of individuals
func FixedPointCrossover(individual Individual, individual2 Individual, params EvolutionParams) (Individual, Individual,
error) {
if individual.Id == "" {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual1 - individual Id cannot be empty")
}
if individual.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual1 - Strategy array cannot be nil")
}
if len(individual.Strategy) == 0 {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual1 - Strategy array cannot be empty")
}
if individual.HasCalculatedFitness == false {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual1 - HasCalculatedFitness should be true")
}
if individual.HasAppliedStrategy == false {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual1 - HasAppliedStrategy should be true")
}
if individual.Program == nil {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual1 - program cannot be nil")
}
if individual.Program.T == nil {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual1 - program Tree cannot be nil")
}
if individual2.Id == "" {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual2 - individual Id cannot be empty")
}
if individual2.Strategy == nil {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual2 - Strategy array cannot be nil")
}
if len(individual2.Strategy) == 0 {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual2 - Strategy array cannot be empty")
}
if individual2.HasCalculatedFitness == false {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual2 - HasCalculatedFitness should be true")
}
if individual2.HasAppliedStrategy == false {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual2 - HasAppliedStrategy should be true")
}
if individual2.Program == nil {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual2 - program cannot be nil")
}
if individual2.Program.T == nil {
return Individual{}, Individual{}, fmt.Errorf("crossover | individual2 - program Tree cannot be nil")
}
individual1Len := len(individual.Strategy)
individual2Len := len(individual2.Strategy)
child1, err := individual.Clone()
child1.Id = child1.Id + "c1"
if err != nil {
return Individual{}, Individual{}, err
}
child2, err := individual2.Clone()
child2.Id = child2.Id + "c2"
if err != nil {
return Individual{}, Individual{}, err
}
crossoverPercentage := params.Reproduction.CrossoverPercentage
if crossoverPercentage == 0 {
return child1, child2, err
}
if crossoverPercentage == 1 {
return child2, child1, err
}
individual1ChunkSize := int(math.Ceil(float64(individual1Len) * float64(crossoverPercentage)))
individual2ChunkSize := int(float64(individual2Len) * crossoverPercentage)
if individual1ChunkSize >= individual2ChunkSize {
var ind1StartIndex int
if individual1Len == individual1ChunkSize {
ind1StartIndex = 0
} else {
ind1StartIndex = rand.Intn((individual1Len + 1) - individual1ChunkSize)
}
c1, c2 := StrategySwapper(individual.Strategy, individual2.Strategy, individual1ChunkSize, ind1StartIndex)
child1.Strategy = c1
child2.Strategy = c2
return child1, child2, nil
} else {
var ind2StartIndex int
if individual2Len == individual2ChunkSize {
ind2StartIndex = 0
} else {
ind2StartIndex = rand.Intn(individual1Len + 1 - individual1ChunkSize)
}
c1, c2 := StrategySwapper(individual.Strategy, individual2.Strategy, individual1ChunkSize, ind2StartIndex)
child1.Strategy = c1
child2.Strategy = c2
return child1, child2, nil
}
}
// StrategySwapper takes two slices containing variable length strategies.
// The swapLength must be smaller than the length of the largest, but less than the length of the smallest.
// A swap length of 0 will return the same arrays a and b untouched.
func StrategySwapper(a []Strategy, b []Strategy, swapLength int, startIndex int) ([]Strategy, []Strategy) {
if a == nil || b == nil {
return nil, nil
}
if len(a) == 0 || len(b) == 0 {
return nil, nil
}
if swapLength == 0 {
return a, b
}
if swapLength < 0 {
swapLength = 0
}
if startIndex < 0 {
startIndex = 0
}
aCopy := make([]Strategy, len(a))
bCopy := make([]Strategy, len(b))
copy(aCopy, a)
copy(bCopy, b)
if len(a) >= len(b) {
if swapLength > len(b) {
swapLength = len(b)
}
if (swapLength + startIndex) > len(b) {
startIndex = 0
}
} else {
if swapLength > len(a) {
swapLength = len(a)
}
if (swapLength + startIndex) > len(a) {
startIndex = 0
}
}
aHolder := make([]Strategy, swapLength)
bHolder := make([]Strategy, swapLength)
for i := 0; i < swapLength; i++ {
aHolder[i] = a[i+startIndex]
bHolder[i] = b[i+startIndex]
}
for i := 0; i < swapLength; i++ {
aCopy[startIndex+i] = bHolder[i]
bCopy[startIndex+i] = aHolder[i]
}
return aCopy, bCopy
}
// StrategySwapperIgnorant will perform crossover regardless of size
func StrategySwapperIgnorant(a []Strategy, b []Strategy, swapLength int, startIndex int) ([]Strategy, []Strategy) {
if a == nil || b == nil {
return nil, nil
}
if len(a) == 0 || len(b) == 0 {
return nil, nil
}
if swapLength == 0 {
return a, b
}
if swapLength < 0 {
swapLength = 0
}
if startIndex < 0 {
startIndex = 0
}
var aCopy, bCopy, aHolder, bHolder []Strategy
if len(a) >= len(b) {
if swapLength > len(a) {
swapLength = len(a)
}
if startIndex+swapLength >= len(a) {
startIndex = 0
}
aCopy = make([]Strategy, len(a))
bCopy = make([]Strategy, len(a))
aHolder = make([]Strategy, swapLength)
bHolder = make([]Strategy, swapLength)
copy(aCopy, a)
copy(bCopy, b)
for i := 0; i < swapLength; i++ {
aHolder[i] = a[i+startIndex]
}
for i := 0; i < swapLength; i++ {
bHolder[i] = b[i+startIndex]
}
} else {
if swapLength > len(b) {
swapLength = len(b)
}
if startIndex+swapLength >= len(b) {
startIndex = 0
}
aCopy = make([]Strategy, len(b))
bCopy = make([]Strategy, len(b))
aHolder = make([]Strategy, swapLength)
bHolder = make([]Strategy, swapLength)
copy(aCopy, a)
copy(bCopy, b)
for i := 0; i < len(aCopy); i++ {
aHolder[i] = a[i+startIndex]
}
for i := 0; i < len(bCopy); i++ {
bHolder[i] = b[i+startIndex]
}
}
for i := 0; i < swapLength; i++ {
aCopy[startIndex+i] = bHolder[i]
bCopy[startIndex+i] = aHolder[i]
}
return aCopy, bCopy
}
// Mutate will mutate the Strategy in a given individual
func (individual *Individual) Mutate(availableStrategies []Strategy) error {
if availableStrategies == nil {
return fmt.Errorf("Mutate | availableStrategies param cannot be nil")
}
if individual.Strategy == nil {
return fmt.Errorf("Mutate | individual's strategies cannot be nil")
}
if len(individual.Strategy) < 1 {
return fmt.Errorf("Mutate | individual's strategies cannot empty")
}
randIndexToMutate := rand.Intn(len(individual.Strategy))
randIndexForStrategies := rand.Intn(len(availableStrategies))
individual.Strategy[randIndexToMutate] = availableStrategies[randIndexForStrategies]
return nil
}
func depthPenaltyIgnore(maxDepth int, individual1Depth int, individual2Depth int) (int, int) {
if maxDepth < 0 {
maxDepth = 0
}
var individual1DepthRemainderFromMaX, individual2DepthRemainderFromMax int
if individual1Depth >= maxDepth {
individual1DepthRemainderFromMaX = 0
} else {
individual1DepthRemainderFromMaX = maxDepth - individual1Depth
}
if individual2Depth >= maxDepth {
individual2DepthRemainderFromMax = 0
} else {
individual2DepthRemainderFromMax = maxDepth - individual2Depth
}
return individual1DepthRemainderFromMaX, individual2DepthRemainderFromMax
} | evolution/reproduction.go | 0.61231 | 0.458712 | reproduction.go | starcoder |
package def
import (
"fmt"
)
type Direction int
// Directions
const (
NORTH Direction = iota
EAST
SOUTH
WEST
)
type Status int
// Health status
const (
ALIVE Status = iota
BROKEN
EATEN
)
type Action int
// Actions
const (
IDLE Action = iota
FACE_NORTH
FACE_EAST
FACE_SOUTH
FACE_WEST
MOVE
SHOOT
PICK
)
// This is used to keep track of the state of the simulation
type Simulation struct {
world World // The World, meaning the position of elements
hunterPos Point // Keeps track of the hunter easily, It is also on the world, but this way it is easier to find
iterations int // (!) (UNUSED) Counts the number of movements performed
isHunterEaten bool // When the hunter dies eaten by the wumpus
isHunterBroken bool // When the hunter dies falling of a pit
hasHunterShot bool // If the hunter spend an arrow
hunterFacing Direction // The direction the hunter faces
hasHunterGold bool
isHunterKnockedUp bool
isWumpusScreaming bool
}
// Used to get where the hunter is on the world
func findHunter(world *World) Point {
for y := 0; y < world.sizey; y++ {
for x := 0; x < world.sizex; x++ {
if world.squares[y][x].hasHunter {
return Point {x, y} // Found
}
}
}
return Point {-1, -1} // Not found
}
// Creates a new simulation from a world
func (s *Simulation) FromWorld(world World) {
s.world = world
s.hunterPos = findHunter(&world)
s.iterations = 0
s.isHunterEaten = false
s.isHunterBroken = false
s.hasHunterShot = false
s.hunterFacing = NORTH
s.hasHunterGold = false
s.isWumpusScreaming = false
s.isHunterKnockedUp = false
}
func IsInBounds(p Point, sizex, sizey int) bool {
return (p.PosX < sizex && p.PosX > -1 && p.PosY < sizey && p.PosY > -1)
}
func perceiveSquare(perception *Perception, square Square) {
if square.hasWump {
perception.Smell = true
}
if square.terrain == Pit {
perception.Breeze = true
}
}
// Perceives the cave
func (sim *Simulation) Perceive() Perception {
var perception Perception
var point Point
perception.Shock = sim.isHunterKnockedUp
perception.Scream = sim.isWumpusScreaming
hunterSquare := sim.world.squares[sim.hunterPos.PosY][sim.hunterPos.PosX]
if hunterSquare.hasGold {
perception.Shine = true
}
point = sim.hunterPos
point.PosX++ // Move on X
if IsInBounds(point, sim.world.sizex, sim.world.sizey) {
perceiveSquare(&perception, sim.world.squares[point.PosY][point.PosX])
}
point = sim.hunterPos
point.PosX-- // Move on X
if IsInBounds(point, sim.world.sizex, sim.world.sizey) {
perceiveSquare(&perception, sim.world.squares[point.PosY][point.PosX])
}
point = sim.hunterPos
point.PosY++ // Move on Y
if IsInBounds(point, sim.world.sizex, sim.world.sizey) {
perceiveSquare(&perception, sim.world.squares[point.PosY][point.PosX])
}
point = sim.hunterPos
point.PosY-- // Move on Y
if IsInBounds(point, sim.world.sizex, sim.world.sizey) {
perceiveSquare(&perception, sim.world.squares[point.PosY][point.PosX])
}
return perception
}
// Perceives status ailments... Yeah...
func (sim *Simulation) GetStatus() Status {
switch {
case sim.isHunterBroken:
return BROKEN
case sim.isHunterEaten:
return EATEN
}
return ALIVE
}
// Gets the actual facing direction
func (sim *Simulation) Compass() Direction {
return sim.hunterFacing
}
// Set the hunter where to look at (direction, NORTH, EAST, SOUTH or WEST)
func (sim *Simulation) face(direction Direction) {
sim.hunterFacing = direction
}
// Sets the hunter position to a point
func (sim *Simulation) setHunterPos(point Point) {
sim.world.squares[sim.hunterPos.PosY][sim.hunterPos.PosX].hasHunter = false // Hunter moved
sim.world.squares[point.PosY][point.PosX].hasHunter = true // Hunter moved
sim.hunterPos = point
if sim.world.squares[point.PosY][point.PosX].hasWump { // Oh no.
sim.isHunterEaten = true
} else if sim.world.squares[point.PosY][point.PosX].terrain == Pit { // Oh no.
sim.isHunterBroken = true
}
}
// Moves the hunter to the square being faced. If the square is
// out of bounds, it will set the shock perception
func (sim *Simulation) move() {
point := sim.hunterPos
switch (sim.hunterFacing) {
case NORTH:
point.PosY--
break
case EAST:
point.PosX++
break
case SOUTH:
point.PosY++
break
case WEST:
point.PosX--
}
if IsInBounds(point, sim.world.sizex, sim.world.sizey) {
sim.setHunterPos(point)
sim.isHunterKnockedUp = false
} else {
sim.isHunterKnockedUp = true
}
}
// Shoots an arrow to the direction being faced
func (sim *Simulation) shoot() {
if sim.hasHunterShot {
return // No more arrows
}
diff := Point {0, 0}
switch (sim.hunterFacing) {
case NORTH:
diff.PosY--
break;
case EAST:
diff.PosX++
break;
case SOUTH:
diff.PosY++
break;
case WEST:
diff.PosX--
}
point := Point {sim.hunterPos.PosX+diff.PosX, sim.hunterPos.PosY+diff.PosY}
for ; IsInBounds(point, sim.world.sizex, sim.world.sizey); {
if sim.world.squares[point.PosY][point.PosX].hasWump {
sim.isWumpusScreaming = true
sim.world.squares[point.PosY][point.PosX].hasWump = false // Killed him, YAY!
}
point.PosX += diff.PosX
point.PosY += diff.PosY
}
}
func (sim* Simulation) pick() {
point := sim.hunterPos
if sim.world.squares[point.PosY][point.PosX].hasGold {
sim.world.squares[point.PosY][point.PosX].hasGold = false
sim.hasHunterGold = true
}
}
func (sim *Simulation) Act(a Action) {
switch a {
case FACE_NORTH:
sim.face(NORTH);
break;
case FACE_EAST:
sim.face(EAST);
break;
case FACE_SOUTH:
sim.face(SOUTH);
break;
case FACE_WEST:
sim.face(WEST);
break;
case MOVE:
sim.move();
break;
case SHOOT:
sim.shoot();
break;
case PICK:
sim.pick();
break;
case IDLE:
// Do nothing
}
sim.iterations++;
}
func (sim Simulation) String() string {
return fmt.Sprintf("%v %v\n%s", sim.iterations, sim.hunterPos, sim.world)
}
func (d Direction) String() string {
var directionName string
switch d {
case NORTH:
directionName = "↑ NORTH"
break
case EAST:
directionName = "→ EAST"
break
case SOUTH:
directionName = "↓ SOUTH"
break
case WEST:
directionName = "← WEST"
break
}
return directionName;
}
func (action Action) String() string {
switch action {
case IDLE:
return "IDLE"
break
case FACE_NORTH:
return "FACE_NORTH"
break
case FACE_EAST:
return "FACE_EAST"
break
case FACE_SOUTH:
return "FACE_SOUTH"
break
case FACE_WEST:
return "FACE_WEST"
break
case MOVE:
return "MOVE"
break
case SHOOT:
return "SHOOT"
break
case PICK:
return "PICK"
break
}
return "?"
} | def/simulation.go | 0.629661 | 0.492188 | simulation.go | starcoder |
package mimic
import (
"encoding/binary"
"fmt"
"github.com/cilium/ebpf/asm"
)
var _ VMMem = (*RingMemory)(nil)
// RingMemory is very similar to PlainMemory, except RingMemory will wrap around to the start when reading or writing
// out of bounds.
type RingMemory struct {
Backing []byte
ByteOrder binary.ByteOrder
}
// Load loads a scalar value of the given `size` and `offset` from the memory.
func (pm *RingMemory) Load(offset uint32, size asm.Size) (uint64, error) {
if pm.ByteOrder == nil {
pm.ByteOrder = GetNativeEndianness()
}
b := make([]byte, size.Sizeof())
err := pm.Read(offset, b)
if err != nil {
return 0, err
}
switch size {
case asm.Byte:
return uint64(b[0]), nil
case asm.Half:
return uint64(pm.ByteOrder.Uint16(b)), nil
case asm.Word:
return uint64(pm.ByteOrder.Uint32(b)), nil
case asm.DWord:
return pm.ByteOrder.Uint64(b), nil
default:
return 0, fmt.Errorf("unknown size '%v'", size)
}
}
// Store stores a scalar value of the given `size` and `offset` from the memory.
func (pm *RingMemory) Store(offset uint32, value uint64, size asm.Size) error {
bytes := size.Sizeof()
if pm.ByteOrder == nil {
pm.ByteOrder = GetNativeEndianness()
}
b := make([]byte, bytes)
switch size {
case asm.Byte:
b[0] = byte(value)
case asm.Half:
pm.ByteOrder.PutUint16(b, uint16(value))
case asm.Word:
pm.ByteOrder.PutUint32(b, uint32(value))
case asm.DWord:
pm.ByteOrder.PutUint64(b, value)
default:
return fmt.Errorf("unknown size '%v'", size)
}
return pm.Write(offset, b)
}
// Read reads a byte slice of arbitrary size, the length of 'b' is used to determine the requested size
func (pm *RingMemory) Read(offset uint32, b []byte) error {
// Read from offset to the end.
n := copy(b, pm.Backing[offset:])
if n == len(b) {
// If we filled `b` fully, no need to wrap around
return nil
}
// Wrap around to the start, and copy into the rest of b
copy(b[n:], pm.Backing)
return nil
}
// Write write a byte slice of arbitrary size to the memory
func (pm *RingMemory) Write(offset uint32, b []byte) error {
n := copy(pm.Backing[offset:], b)
if n == len(b) {
// If all of `b`'s bytes were copied, no need to wrap around
return nil
}
// Wrap around an copy the rest of the bytes
copy(pm.Backing, b[n:])
return nil
} | memory_ring.go | 0.849893 | 0.433802 | memory_ring.go | starcoder |
package flattree
import (
"errors"
"math/bits"
)
// Index returns the flat-tree of the node at the provided depth and offset
func Index(depth, offset uint64) uint64 {
return (offset << (depth + 1)) | ((1 << depth) - 1)
}
// Depth returns the depth of a given node
func Depth(n uint64) uint64 {
return uint64(bits.TrailingZeros64(^n))
}
// Offset returns the offset of a given node
// The offset is the distance from the left edge of the tree
func Offset(n uint64) uint64 {
if isEven(n) {
return n / 2
}
return n >> (Depth(n) + 1)
}
// Parent returns the parent node of the provided node
func Parent(n uint64) uint64 {
return Index(Depth(n)+1, Offset(n)/2)
}
// Sibling returns the sibling of the provided node
func Sibling(n uint64) uint64 {
return Index(Depth(n), Offset(n)^1)
}
// Uncle returns the parent's sibling of the provided node
func Uncle(n uint64) uint64 {
return Index(Depth(n)+1, Offset(Parent(n))^1)
}
// Children returns the children of the provided node, if it exists
// Returns the children and a bool indicating if they exist
func Children(n uint64) (left uint64, right uint64, exists bool) {
if isEven(n) {
return 0, 0, false
}
depth := Depth(n)
offset := Offset(n) * 2
left = Index(depth-1, offset)
right = Index(depth-1, offset+1)
return left, right, true
}
// LeftChild returns the left child of the provided node, if it exists
// Returns the left child and a bool indicating if it exists
func LeftChild(n uint64) (uint64, bool) {
if isEven(n) {
return 0, false
}
return Index(Depth(n)-1, Offset(n)*2), true
}
// RightChild returns the left child of the provided node, if it exists
// Returns the right child and a bool indicating if it exists
func RightChild(n uint64) (uint64, bool) {
if isEven(n) {
return 0, false
}
return Index(Depth(n)-1, (Offset(n)*2)+1), true
}
// Spans returns the left and right most nodes in the tree which the provided node spans
func Spans(n uint64) (left uint64, right uint64) {
if isEven(n) {
return n, n
}
depth := Depth(n)
offset := Offset(n)
left = offset * (2 << depth)
right = (offset+1)*(2<<depth) - 2
return
}
// LeftSpan returns the left most node in the tree which the provided node spans
func LeftSpan(n uint64) uint64 {
if isEven(n) {
return n
}
return Offset(n) * (2 << Depth(n))
}
// RightSpan returns the right most node in the tree which the provided node spans
func RightSpan(n uint64) uint64 {
if isEven(n) {
return n
}
return (Offset(n)+1)*(2<<Depth(n)) - 2
}
// Count returns the number of nodes under the given node, including the provided node itself
func Count(n uint64) uint64 {
return (2 << Depth(n)) - 1
}
// FullRoots returns a list of all roots less than the provided index
// A root is a subtrees where all nodes have either 2 or 0 children
func FullRoots(index uint64) (roots []uint64, err error) {
roots = []uint64{}
if !isEven(index) {
err = errors.New("odd index passed to FullRoots()")
return
}
index /= 2
offset := uint64(0)
factor := uint64(1)
for {
if index == 0 {
return
}
for uint64(factor*2) <= index {
factor *= 2
}
root := offset + factor - 1
roots = append(roots, root)
offset += 2 * factor
index -= factor
factor = 1
}
}
func isEven(n uint64) bool {
return n%2 == 0
} | flat-tree.go | 0.863593 | 0.62111 | flat-tree.go | starcoder |
package bulletproofs
import (
"math/big"
)
/*
bprp structure contains 2 BulletProofs in order to allow computation of
generic Range Proofs, for any interval [A, B).
*/
type bprp struct {
A int64
B int64
BP1 BulletProofSetupParams
BP2 BulletProofSetupParams
}
/*
ProofBPRP stores the generic ZKRP.
*/
type ProofBPRP struct {
P1 BulletProof
P2 BulletProof
}
/*
SetupGeneric is responsible for calling the Setup algorithm for each
BulletProof.
*/
func SetupGeneric(a, b int64) (*bprp, error) {
params := new(bprp)
params.A = a
params.B = b
var errBp1, errBp2 error
params.BP1, errBp1 = Setup(MAX_RANGE_END)
if errBp1 != nil {
return nil, errBp1
}
params.BP2, errBp2 = Setup(MAX_RANGE_END)
if errBp2 != nil {
return nil, errBp2
}
return params, nil
}
/*
BulletProof only works for interval in the format [0, 2^N). In order to
allow generic intervals in the format [A, B) it is necessary to use 2
BulletProofs, as explained in Section 4.3 from the following paper:
https://infoscience.epfl.ch/record/128718/files/CCS08.pdf
*/
func ProveGeneric(secret *big.Int, params *bprp) (ProofBPRP, error) {
var proof ProofBPRP
// x - b + 2^N
p2 := new(big.Int).SetInt64(MAX_RANGE_END)
xb := new(big.Int).Sub(secret, new(big.Int).SetInt64(params.B))
xb.Add(xb, p2)
var err1 error
proof.P1, err1 = Prove(xb, params.BP1)
if err1 != nil {
return proof, err1
}
xa := new(big.Int).Sub(secret, new(big.Int).SetInt64(params.A))
var err2 error
proof.P2, err2 = Prove(xa, params.BP2)
if err2 != nil {
return proof, err2
}
return proof, nil
}
/*
Verify call the Verification algorithm for each BulletProof argument.
*/
func (proof ProofBPRP) Verify() (bool, error) {
ok1, err1 := proof.P1.Verify()
if !ok1 {
return false, err1
}
ok2, err2 := proof.P2.Verify()
if !ok2 {
return false, err2
}
return ok1 && ok2, nil
} | crypto/vendor/ing-bank/zkrp/bulletproofs/bprp.go | 0.672117 | 0.442576 | bprp.go | starcoder |
package statsd
import "time"
// A NoopClient is a client that does nothing.
type NoopClient struct{}
// Close closes the connection and cleans up.
func (s *NoopClient) Close() error {
return nil
}
// Inc increments a statsd count type.
// stat is a string name for the metric.
// value is the integer value
// rate is the sample rate (0.0 to 1.0)
func (s *NoopClient) Inc(stat string, value int64, rate float32) error {
return nil
}
// Dec decrements a statsd count type.
// stat is a string name for the metric.
// value is the integer value.
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) Dec(stat string, value int64, rate float32) error {
return nil
}
// Gauge submits/Updates a statsd gauge type.
// stat is a string name for the metric.
// value is the integer value.
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) Gauge(stat string, value int64, rate float32) error {
return nil
}
// GaugeDelta submits a delta to a statsd gauge.
// stat is the string name for the metric.
// value is the (positive or negative) change.
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) GaugeDelta(stat string, value int64, rate float32) error {
return nil
}
// Timing submits a statsd timing type.
// stat is a string name for the metric.
// delta is the time duration value in milliseconds
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) Timing(stat string, delta int64, rate float32) error {
return nil
}
// TimingDuration submits a statsd timing type.
// stat is a string name for the metric.
// delta is the timing value as time.Duration
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) TimingDuration(stat string, delta time.Duration, rate float32) error {
return nil
}
// Set submits a stats set type.
// stat is a string name for the metric.
// value is the string value
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) Set(stat string, value string, rate float32) error {
return nil
}
// SetInt submits a number as a stats set type.
// convenience method for Set with number.
// stat is a string name for the metric.
// value is the integer value
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) SetInt(stat string, value int64, rate float32) error {
return nil
}
// Raw formats the statsd event data, handles sampling, prepares it,
// and sends it to the server.
// stat is the string name for the metric.
// value is the preformatted "raw" value string.
// rate is the sample rate (0.0 to 1.0).
func (s *NoopClient) Raw(stat string, value string, rate float32) error {
return nil
}
// SetPrefix sets/updates the statsd client prefix
func (s *NoopClient) SetPrefix(prefix string) {}
// NewSubStatter returns a SubStatter with appended prefix
func (s *NoopClient) NewSubStatter(prefix string) SubStatter {
return &NoopClient{}
}
// SetSamplerFunc sets the sampler function
func (s *NoopClient) SetSamplerFunc(sampler SamplerFunc) {}
// NewNoopClient returns a pointer to a new NoopClient, and an error (always
// nil, just supplied to support api convention).
// Use variadic arguments to support identical format as NewClient, or a more
// conventional no argument form.
func NewNoopClient(a ...interface{}) (Statter, error) {
return &NoopClient{}, nil
}
// NewNoop is a compatibility alias for NewNoopClient
var NewNoop = NewNoopClient | vendor/github.com/cactus/go-statsd-client/statsd/client_noop.go | 0.883726 | 0.550849 | client_noop.go | starcoder |
package ahrs
import (
"github.com/skelterjohn/go.matrix"
"math"
)
type Kalman1State struct {
State
}
func (s *Kalman1State) CalcRollPitchHeadingUncertainty() (droll float64, dpitch float64, dheading float64) {
droll, dpitch, dheading = VarFromQuaternion(s.E0, s.E1, s.E2, s.E3,
math.Sqrt(s.M.Get(6, 6)), math.Sqrt(s.M.Get(7, 7)),
math.Sqrt(s.M.Get(8, 8)), math.Sqrt(s.M.Get(9, 9)))
return
}
// GetState returns the Kalman state of the system
func (s *Kalman1State) GetState() *State {
return &s.State
}
// GetStateMap returns the state information for analysis
func (s *Kalman1State) GetStateMap() (dat *map[string]float64) {
phi, theta, psi := FromQuaternion(s.E0, s.E1, s.E2, s.E3)
phi0, theta0, psi0 := FromQuaternion(s.F0, s.F1, s.F2, s.F3)
dphi, dtheta, dpsi := s.CalcRollPitchHeadingUncertainty()
dphi0, dtheta0, dpsi0 := VarFromQuaternion(s.F0, s.F1, s.F2, s.F3,
math.Sqrt(s.M.Get(22, 22)), math.Sqrt(s.M.Get(23, 23)),
math.Sqrt(s.M.Get(24, 24)), math.Sqrt(s.M.Get(25, 25)))
dat = &map[string]float64{
"T": s.T,
"E0": s.E0,
"E1": s.E1,
"E2": s.E2,
"E3": s.E3,
"Phi": phi / Deg,
"Theta": theta / Deg,
"Psi": psi / Deg,
"H1": s.H1,
"H2": s.H2,
"H3": s.H3,
"F0": s.F0,
"F1": s.F1,
"F2": s.F2,
"F3": s.F3,
"Phi0": phi0 / Deg,
"Theta0": theta0 / Deg,
"Psi0": psi0 / Deg,
"D1": s.D1,
"D2": s.D2,
"D3": s.D3,
"dPhi": dphi,
"dTheta": dtheta,
"dPsi": dpsi,
"dH1": math.Sqrt(s.M.Get(10, 10)),
"dH2": math.Sqrt(s.M.Get(11, 11)),
"dH3": math.Sqrt(s.M.Get(12, 12)),
"dPhi0": dphi0,
"dTheta0": dtheta0,
"dPsi0": dpsi0,
"dD1": math.Sqrt(s.M.Get(26, 26)),
"dD2": math.Sqrt(s.M.Get(27, 27)),
"dD3": math.Sqrt(s.M.Get(28, 28)),
}
return
}
// Initialize the state at the start of the Kalman filter, based on current measurements
func InitializeKalman1(m *Measurement) (s *Kalman1State) {
s = new(Kalman1State)
s.init(m)
return
}
func (s *Kalman1State) init(m *Measurement) {
s.E0 = 1 // Initial guess is East
s.F0 = 1 // Initial guess is that it's oriented pointing forward and level
s.normalize()
s.T = m.T
// Diagonal matrix of initial state uncertainties, will be squared into covariance below
// Specifics here aren't too important--it will change very quickly
s.M = matrix.Diagonal([]float64{
Big, Big, Big, // U*3
Big, Big, Big, // Z*3
0.5, 0.5, 0.5, 0.5, // E*4
2, 2, 2, // H*3
Big, Big, Big, // N*3
Big, Big, Big, // V*3
Big, Big, Big, // C*3
0.002, 0.002, 0.002, 0.002, // F*4
0.1, 0.1, 0.1, // D*3
Big, Big, Big, // L*3
})
s.M = matrix.Product(s.M, s.M)
// Diagonal matrix of state process uncertainties per s, will be squared into covariance below
// Tuning these is more important
tt := math.Sqrt(60.0 * 60.0) // One-hour time constant for drift of biases V, C, F, D, L
s.N = matrix.Diagonal([]float64{
Big, Big, Big, // U*3
Big, Big, Big, // Z*3
0.02, 0.02, 0.02, 0.02, // E*4
1, 1, 1, // H*3
Big, Big, Big, // N*3
Big, Big, Big, // V*3
Big, Big, Big, // C*3
0.0001 / tt, 0.0001 / tt, 0.0001 / tt, 0.0001 / tt, // F*4
0.1 / tt, 0.1 / tt, 0.1 / tt, // D*3
Big, Big, Big, // L*3
})
s.N = matrix.Product(s.N, s.N)
return
}
// Compute runs first the prediction and then the update phases of the Kalman filter
func (s *Kalman1State) Compute(m *Measurement) {
s.Predict(m.T)
s.Update(m)
}
// Valid applies some heuristics to detect whether the computed state is valid or not
func (s *Kalman1State) Valid() (ok bool) {
return true
}
// Predict performs the prediction phase of the Kalman filter
func (s *Kalman1State) Predict(t float64) {
f := s.calcJacobianState(t)
dt := t - s.T
s.E0 += 0.5 * dt * (-s.E1*s.H1 - s.E2*s.H2 - s.E3*s.H3) * Deg
s.E1 += 0.5 * dt * (+s.E0*s.H1 - s.E3*s.H2 + s.E2*s.H3) * Deg
s.E2 += 0.5 * dt * (+s.E3*s.H1 + s.E0*s.H2 - s.E1*s.H3) * Deg
s.E3 += 0.5 * dt * (-s.E2*s.H1 + s.E1*s.H2 + s.E0*s.H3) * Deg
s.normalize()
s.T = t
s.M = matrix.Sum(matrix.Product(f, matrix.Product(s.M, f.Transpose())), matrix.Scaled(s.N, dt))
}
func (s *Kalman1State) PredictMeasurement() (m *Measurement) {
m = NewMeasurement()
m.SValid = true
m.B1 = s.f11*s.H1 + s.f12*s.H2 + s.f13*s.H3 + s.D1
m.B2 = s.f21*s.H1 + s.f22*s.H2 + s.f23*s.H3 + s.D2
m.B3 = s.f31*s.H1 + s.f32*s.H2 + s.f33*s.H3 + s.D3
m.T = s.T
return
}
// Update applies the Kalman filter corrections given the measurements
func (s *Kalman1State) Update(m *Measurement) {
z := s.PredictMeasurement()
y := matrix.Zeros(15, 1)
y.Set(9, 0, m.B1-z.B1)
y.Set(10, 0, m.B2-z.B2)
y.Set(11, 0, m.B3-z.B3)
h := s.calcJacobianMeasurement()
var v float64
_, _, v = m.Accums[9](m.B1)
m.M.Set(9, 9, v)
_, _, v = m.Accums[10](m.B2)
m.M.Set(10, 10, v)
_, _, v = m.Accums[11](m.B3)
m.M.Set(11, 11, v)
ss := matrix.Sum(matrix.Product(h, matrix.Product(s.M, h.Transpose())), m.M)
m2, err := ss.Inverse()
if err != nil {
return
}
kk := matrix.Product(s.M, matrix.Product(h.Transpose(), m2))
su := matrix.Product(kk, y)
s.E0 += su.Get(6, 0)
s.E1 += su.Get(7, 0)
s.E2 += su.Get(8, 0)
s.E3 += su.Get(9, 0)
s.H1 += su.Get(10, 0)
s.H2 += su.Get(11, 0)
s.H3 += su.Get(12, 0)
s.F0 += su.Get(22, 0)
s.F1 += su.Get(23, 0)
s.F2 += su.Get(24, 0)
s.F3 += su.Get(25, 0)
s.D1 += su.Get(26, 0)
s.D2 += su.Get(27, 0)
s.D3 += su.Get(28, 0)
s.T = m.T
s.M = matrix.Product(matrix.Difference(matrix.Eye(32), matrix.Product(kk, h)), s.M)
s.normalize()
}
func (s *Kalman1State) calcJacobianState(t float64) (jac *matrix.DenseMatrix) {
dt := t - s.T
jac = matrix.Eye(32)
// U*3, Z*3, E*4, H*3, N*3,
// V*3, C*3, F*4, D*3, L*3
//s.E0 += 0.5*dt*(-s.E1*s.H1 - s.E2*s.H2 - s.E3*s.H3)*Deg
jac.Set(6, 7, -0.5*dt*s.H1*Deg) // E0/E1
jac.Set(6, 8, -0.5*dt*s.H2*Deg) // E0/E2
jac.Set(6, 9, -0.5*dt*s.H3*Deg) // E0/E3
jac.Set(6, 10, -0.5*dt*s.E1*Deg) // E0/H1
jac.Set(6, 11, -0.5*dt*s.E2*Deg) // E0/H2
jac.Set(6, 12, -0.5*dt*s.E3*Deg) // E0/H3
//s.E1 += 0.5*dt*(+s.E0*s.H1 - s.E3*s.H2 + s.E2*s.H3)*Deg
jac.Set(7, 6, +0.5*dt*s.H1*Deg) // E1/E0
jac.Set(7, 8, +0.5*dt*s.H3*Deg) // E1/E2
jac.Set(7, 9, -0.5*dt*s.H2*Deg) // E1/E3
jac.Set(7, 10, +0.5*dt*s.E0*Deg) // E1/H1
jac.Set(7, 11, -0.5*dt*s.E3*Deg) // E1/H2
jac.Set(7, 12, +0.5*dt*s.E2*Deg) // E1/H3
//s.E2 += 0.5*dt*(+s.E3*s.H1 + s.E0*s.H2 - s.E1*s.H3)*Deg
jac.Set(8, 6, +0.5*dt*s.H2*Deg) // E2/E0
jac.Set(8, 7, -0.5*dt*s.H3*Deg) // E2/E1
jac.Set(8, 9, +0.5*dt*s.H1*Deg) // E2/E3
jac.Set(8, 10, +0.5*dt*s.E3*Deg) // E2/H1
jac.Set(8, 11, +0.5*dt*s.E0*Deg) // E2/H2
jac.Set(8, 12, -0.5*dt*s.E1*Deg) // E2/H3
//s.E3 += 0.5*dt*(-s.E2*s.H1 + s.E1*s.H2 + s.E0*s.H3)*Deg
jac.Set(9, 6, +0.5*dt*s.H3*Deg) // E3/E0
jac.Set(9, 7, +0.5*dt*s.H2*Deg) // E3/E1
jac.Set(9, 8, -0.5*dt*s.H1*Deg) // E3/E2
jac.Set(9, 10, -0.5*dt*s.E2*Deg) // E3/H1
jac.Set(9, 11, +0.5*dt*s.E1*Deg) // E3/H2
jac.Set(9, 12, +0.5*dt*s.E0*Deg) // E3/H3
return
}
func (s *Kalman1State) calcJacobianMeasurement() (jac *matrix.DenseMatrix) {
// B = F*H*conj(F) + D
jac = matrix.Zeros(15, 32)
// U*3, Z*3, E*4, H*3, N*3,
// V*3, C*3, F*4, D*3, L*3
// U*3, W*3, A*3, B*3, M*3
//m.B1 = s.f11*s.H1 + s.f12*s.H2 + s.f13*s.H3 + s.D1
//s.f11 = (+s.F0 * s.F0 + s.F1 * s.F1 - s.F2 * s.F2 - s.F3 * s.F3)
//s.f12 = 2*(-s.F0 * s.F3 + s.F1 * s.F2)
//s.f13 = 2*(+s.F0 * s.F2 + s.F3 * s.F1)
jac.Set(9, 10, s.f11) // B1/H1
jac.Set(9, 11, s.f12) // B1/H2
jac.Set(9, 12, s.f13) // B1/H3
jac.Set(9, 22, 2*(s.H1*s.F0-s.H2*s.F3+s.H3*s.F2)) // B1/F0
jac.Set(9, 23, 2*(s.H1*s.F1+s.H2*s.F2+s.H3*s.F3)) // B1/F1
jac.Set(9, 24, 2*(-s.H1*s.F2+s.H2*s.F1+s.H3*s.F0)) // B1/F2
jac.Set(9, 25, 2*(-s.H1*s.F3-s.H2*s.F0+s.H3*s.F1)) // B1/F3
jac.Set(9, 26, 1) // B1/D1
//m.B2 = s.f21*s.H1 + s.f22*s.H2 + s.f23*s.H3 + s.D2
//s.f21 = 2*(+s.F0 * s.F3 + s.F1 * s.F2)
//s.f22 = (+s.F0 * s.F0 - s.F1 * s.F1 + s.F2 * s.F2 - s.F3 * s.F3)
//s.f23 = 2*(-s.F0 * s.F1 + s.F2 * s.F3)
jac.Set(10, 10, s.f21) // B2/H1
jac.Set(10, 11, s.f22) // B2/H2
jac.Set(10, 12, s.f23) // B2/H3
jac.Set(10, 22, 2*(s.H1*s.F3+s.H2*s.F0-s.H3*s.F1)) // B2/F0
jac.Set(10, 23, 2*(s.H1*s.F2-s.H2*s.F1-s.H3*s.F0)) // B2/F1
jac.Set(10, 24, 2*(s.H1*s.F1+s.H2*s.F2+s.H3*s.F3)) // B2/F2
jac.Set(10, 25, 2*(s.H1*s.F0-s.H2*s.F3+s.H3*s.F2)) // B2/F3
jac.Set(10, 27, 1) // B2/D2
//m.B3 = s.f31*s.H1 + s.f32*s.H2 + s.f33*s.H3 + s.D3
//s.f31 = 2*(-s.F0 * s.F2 + s.F3 * s.F1)
//s.f32 = 2*(+s.F0 * s.F1 + s.F2 * s.F3)
//s.f33 = (+s.F0 * s.F0 - s.F1 * s.F1 - s.F2 * s.F2 + s.F3 * s.F3)
jac.Set(11, 10, s.f31) // B3/H1
jac.Set(11, 11, s.f32) // B3/H2
jac.Set(11, 12, s.f33) // B3/H3
jac.Set(11, 22, 2*(-s.H1*s.F2+s.H2*s.F1+s.H3*s.F0)) // B3/F0
jac.Set(11, 23, 2*(s.H1*s.F3+s.H2*s.F0-s.H3*s.F1)) // B3/F1
jac.Set(11, 24, 2*(-s.H1*s.F0+s.H2*s.F3-s.H3*s.F2)) // B3/F2
jac.Set(11, 25, 2*(s.H1*s.F1+s.H2*s.F2+s.H3*s.F3)) // B3/F3
jac.Set(11, 28, 1) // B3/D3
return
}
var Kalman1JSONConfig = "" | goflying/ahrs/ahrs_kalman1.go | 0.8557 | 0.57081 | ahrs_kalman1.go | starcoder |
package dataframe
import "fmt"
type DataFrame interface {
NRow() int
NCol() int
GetAllSeries() []Series
GetSeries(name string) (index int, s Series, ok bool)
SetSeries(series Series) error
// SetSeriesDirectly set series by index, without looking up by name of series.
SetSeriesDirectly(index int, series Series) error
AppendSeries(series ...Series) error
Copy() DataFrame
Select(indexes []int) DataFrame
String() string
}
type formatter func(DataFrame) string
func NewDataFrame(nrow int, options ...Option) DataFrame {
ov := newOptionValues()
for _, o := range options {
o(ov)
}
return &dataFrame{
nrow: nrow,
formatter: ov.formatter,
}
}
type dataFrame struct {
nrow int
series []Series
formatter formatter
}
func (df *dataFrame) NRow() int {
return df.nrow
}
func (df *dataFrame) NCol() int {
return len(df.series)
}
func (df *dataFrame) GetAllSeries() []Series {
return df.series
}
func (df *dataFrame) GetSeries(name string) (index int, s Series, ok bool) {
for i, s := range df.series {
if s.Name() == name {
return i, s, true
}
}
return -1, nil, false
}
func (df *dataFrame) SetSeries(series Series) error {
if series.Len() != df.nrow {
return fmt.Errorf("nrow not equal")
}
if index, _, ok := df.GetSeries(series.Name()); ok {
df.series[index] = series
return nil
}
df.series = append(df.series, series)
return nil
}
func (df *dataFrame) SetSeriesDirectly(index int, series Series) error {
if index > len(df.series) {
return fmt.Errorf("out of range")
}
if series.Len() != df.nrow {
return fmt.Errorf("nrow not equal")
}
if index == len(df.series) {
df.series = append(df.series, series)
return nil
}
df.series[index] = series
return nil
}
func (df *dataFrame) AppendSeries(series ...Series) error {
for _, s := range series {
if s.Len() != df.nrow {
return fmt.Errorf("%s: nrow not equal", s.Name())
}
}
df.series = append(df.series, series...)
return nil
}
func (df *dataFrame) Copy() DataFrame {
ndf := NewDataFrame(df.NRow())
for _, s := range ndf.GetAllSeries() {
ndf.AppendSeries(s.Copy())
}
return ndf
}
func (df *dataFrame) Select(indexes []int) DataFrame {
ndf := NewDataFrame(df.NRow())
series := df.GetAllSeries()
for _, index := range indexes {
ndf.AppendSeries(series[index])
}
return ndf
}
func (df *dataFrame) String() string {
return df.formatter(df)
} | dataframe.go | 0.694199 | 0.485295 | dataframe.go | starcoder |
package vkg
import (
"fmt"
vk "github.com/vulkan-go/vulkan"
)
// Buffer in vulkan are essentially a way of identifying and describing resources to the system. So for example
// you can have a buffer which holds vertex data in a specific format, or index data or a U.B.O (Uniform Buffer Object -
// which is data which is provided to a shader), or a buffer which is a source or destination for data from other locations.
// Buffers can reside either in the host memory or in the GPU (device) memory. The buffer itself is not the allocation of
// memory but simply a description of what the memory is and where it is. Device or host memory must still be allocated using
// the physical device object to actually hold the data associated with the buffer.
type Buffer struct {
Device *Device
VKBuffer vk.Buffer
Usage vk.BufferUsageFlagBits
Size uint64
}
func usageToString(usage vk.BufferUsageFlagBits) string {
str := ""
if usage&vk.BufferUsageTransferSrcBit == vk.BufferUsageTransferSrcBit {
str += "TransferSrc|"
}
if usage&vk.BufferUsageTransferDstBit == vk.BufferUsageTransferDstBit {
str += "TransferDst|"
}
if usage&vk.BufferUsageUniformBufferBit == vk.BufferUsageUniformBufferBit {
str += "UniformBuffer|"
}
if usage&vk.BufferUsageStorageBufferBit == vk.BufferUsageStorageBufferBit {
str += "StorageBuffer|"
}
if usage&vk.BufferUsageVertexBufferBit == vk.BufferUsageVertexBufferBit {
str += "VertexBuffer|"
}
if usage&vk.BufferUsageIndexBufferBit == vk.BufferUsageIndexBufferBit {
str += "IndexBuffer|"
}
if len(str) > 0 {
str = str[:len(str)-1]
}
return str
}
// CreateBufferWithOptions creates a buffer object of a certain size, for a certain usage, with certain sharing options. This buffer
// can be used to describe memory which is allocated on either the host or device.
func (d *Device) CreateBufferWithOptions(sizeInBytes uint64, usage vk.BufferUsageFlagBits, sharing vk.SharingMode) (*Buffer, error) {
bufferCreateInfo := vk.BufferCreateInfo{
SType: vk.StructureTypeBufferCreateInfo,
Size: vk.DeviceSize(sizeInBytes),
Usage: vk.BufferUsageFlags(usage),
SharingMode: sharing,
}
var buffer vk.Buffer
err := vk.Error(vk.CreateBuffer(d.VKDevice, &bufferCreateInfo, nil, &buffer))
if err != nil {
return nil, err
}
var ret Buffer
ret.VKBuffer = buffer
ret.Device = d
ret.Size = sizeInBytes
ret.Usage = usage
return &ret, nil
}
func (b *Buffer) String() string {
return fmt.Sprintf("{type:buffer size:%d , usage: %s }", b.Size, usageToString(b.Usage))
}
// VKMemoryRequirements returns the vulkan native vk.MemoryRequirements objects which can be inspected to learn more about
// the memory requirements assocaited with this buffer. (You must call .Deref() on this object to populate it).
func (b *Buffer) VKMemoryRequirements() vk.MemoryRequirements {
var memoryRequirements vk.MemoryRequirements
vk.GetBufferMemoryRequirements(b.Device.VKDevice, b.VKBuffer, &memoryRequirements)
return memoryRequirements
}
// Bind associates a specific bit of device memory with this buffer, essentially identifying the memory as being used
// by this buffer. The offset is provied so that the buffer can be bound to a certain place in memory. There is a requirement
// that the buffer be bound in accordance with the alignment requirements returned by .VKMemoryRequirements().
func (b *Buffer) Bind(memory *DeviceMemory, offset uint64) error {
return vk.Error((vk.BindBufferMemory(b.Device.VKDevice, b.VKBuffer, memory.VKDeviceMemory, vk.DeviceSize(offset))))
}
// Destroy the buffer
func (b *Buffer) Destroy() {
if b.VKBuffer != vk.NullBuffer {
vk.DestroyBuffer(b.Device.VKDevice, b.VKBuffer, nil)
b.VKBuffer = vk.NullBuffer
}
} | buffer.go | 0.720762 | 0.487307 | buffer.go | starcoder |
package diagnostics
import (
"context"
"fmt"
"time"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
diag_utils "github.com/dapr/dapr/pkg/diagnostics/utils"
)
var (
processStatusKey = tag.MustNewKey("process_status")
successKey = tag.MustNewKey("success")
topicKey = tag.MustNewKey("topic")
)
const (
Delete = "delete"
Get = "get"
Set = "set"
StateQuery = "query"
ConfigurationSubscribe = "subscribe"
ConfigurationUnsubscribe = "unsubscribe"
StateTransaction = "transaction"
BulkGet = "bulk_get"
BulkDelete = "bulk_delete"
)
// componentMetrics holds dapr runtime metrics for components.
type componentMetrics struct {
pubsubIngressCount *stats.Int64Measure
pubsubIngressLatency *stats.Float64Measure
pubsubEgressCount *stats.Int64Measure
pubsubEgressLatency *stats.Float64Measure
inputBindingCount *stats.Int64Measure
inputBindingLatency *stats.Float64Measure
outputBindingCount *stats.Int64Measure
outputBindingLatency *stats.Float64Measure
stateCount *stats.Int64Measure
stateLatency *stats.Float64Measure
configurationCount *stats.Int64Measure
configurationLatency *stats.Float64Measure
secretCount *stats.Int64Measure
secretLatency *stats.Float64Measure
appID string
enabled bool
namespace string
}
// newComponentMetrics returns a componentMetrics instance with default stats.
func newComponentMetrics() *componentMetrics {
return &componentMetrics{
pubsubIngressCount: stats.Int64(
"component/pubsub_ingress/count",
"The number of incoming messages arriving from the pub/sub component.",
stats.UnitDimensionless),
pubsubIngressLatency: stats.Float64(
"component/pubsub_ingress/latencies",
"The consuming app event processing latency.",
stats.UnitMilliseconds),
pubsubEgressCount: stats.Int64(
"component/pubsub_egress/count",
"The number of outgoing messages published to the pub/sub component.",
stats.UnitDimensionless),
pubsubEgressLatency: stats.Float64(
"component/pubsub_egress/latencies",
"The latency of the response from the pub/sub component.",
stats.UnitMilliseconds),
inputBindingCount: stats.Int64(
"component/input_binding/count",
"The number of incoming events arriving from the input binding component.",
stats.UnitDimensionless),
inputBindingLatency: stats.Float64(
"component/input_binding/latencies",
"The triggered app event processing latency.",
stats.UnitMilliseconds),
outputBindingCount: stats.Int64(
"component/output_binding/count",
"The number of operations invoked on the output binding component.",
stats.UnitDimensionless),
outputBindingLatency: stats.Float64(
"component/output_binding/latencies",
"The latency of the response from the output binding component.",
stats.UnitMilliseconds),
stateCount: stats.Int64(
"component/state/count",
"The number of operations performed on the state component.",
stats.UnitDimensionless),
stateLatency: stats.Float64(
"component/state/latencies",
"The latency of the response from the state component.",
stats.UnitMilliseconds),
configurationCount: stats.Int64(
"component/configuration/count",
"The number of operations performed on the configuration component.",
stats.UnitDimensionless),
configurationLatency: stats.Float64(
"component/configuration/latencies",
"The latency of the response from the configuration component.",
stats.UnitMilliseconds),
secretCount: stats.Int64(
"component/secret/count",
"The number of operations performed on the secret component.",
stats.UnitDimensionless),
secretLatency: stats.Float64(
"component/secret/latencies",
"The latency of the response from the secret component.",
stats.UnitMilliseconds),
}
}
// Init registers the component metrics views.
func (c *componentMetrics) Init(appID, namespace string) error {
c.appID = appID
c.enabled = true
c.namespace = namespace
return view.Register(
diag_utils.NewMeasureView(c.pubsubIngressLatency, []tag.Key{appIDKey, componentKey, namespaceKey, processStatusKey, topicKey}, defaultLatencyDistribution),
diag_utils.NewMeasureView(c.pubsubIngressCount, []tag.Key{appIDKey, componentKey, namespaceKey, processStatusKey, topicKey}, view.Count()),
diag_utils.NewMeasureView(c.pubsubEgressLatency, []tag.Key{appIDKey, componentKey, namespaceKey, successKey, topicKey}, defaultLatencyDistribution),
diag_utils.NewMeasureView(c.pubsubEgressCount, []tag.Key{appIDKey, componentKey, namespaceKey, successKey, topicKey}, view.Count()),
diag_utils.NewMeasureView(c.inputBindingLatency, []tag.Key{appIDKey, componentKey, namespaceKey, successKey}, defaultLatencyDistribution),
diag_utils.NewMeasureView(c.inputBindingCount, []tag.Key{appIDKey, componentKey, namespaceKey, successKey}, view.Count()),
diag_utils.NewMeasureView(c.outputBindingLatency, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, defaultLatencyDistribution),
diag_utils.NewMeasureView(c.outputBindingCount, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, view.Count()),
diag_utils.NewMeasureView(c.stateLatency, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, defaultLatencyDistribution),
diag_utils.NewMeasureView(c.stateCount, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, view.Count()),
diag_utils.NewMeasureView(c.configurationLatency, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, defaultLatencyDistribution),
diag_utils.NewMeasureView(c.configurationCount, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, view.Count()),
diag_utils.NewMeasureView(c.secretLatency, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, defaultLatencyDistribution),
diag_utils.NewMeasureView(c.secretCount, []tag.Key{appIDKey, componentKey, namespaceKey, operationKey, successKey}, view.Count()),
)
}
// PubsubIngressEvent records the metrics for a pub/sub ingress event.
func (c *componentMetrics) PubsubIngressEvent(ctx context.Context, component, processStatus, topic string, elapsed float64) {
if c.enabled {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, processStatusKey, processStatus, topicKey, topic),
c.pubsubIngressCount.M(1))
if elapsed > 0 {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, processStatusKey, processStatus, topicKey, topic),
c.pubsubIngressLatency.M(elapsed))
}
}
}
// PubsubEgressEvent records the metris for a pub/sub egress event.
func (c *componentMetrics) PubsubEgressEvent(ctx context.Context, component, topic string, success bool, elapsed float64) {
if c.enabled {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, successKey, fmt.Sprintf("%v", success), topicKey, topic),
c.pubsubEgressCount.M(1))
if elapsed > 0 {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, successKey, fmt.Sprintf("%v", success), topicKey, topic),
c.pubsubEgressLatency.M(elapsed))
}
}
}
// InputBindingEvent records the metrics for an input binding event.
func (c *componentMetrics) InputBindingEvent(ctx context.Context, component string, success bool, elapsed float64) {
if c.enabled {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, successKey, fmt.Sprintf("%v", success)),
c.inputBindingCount.M(1))
if elapsed > 0 {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, successKey, fmt.Sprintf("%v", success)),
c.inputBindingLatency.M(elapsed))
}
}
}
// OutputBindingEvent records the metrics for an output binding event.
func (c *componentMetrics) OutputBindingEvent(ctx context.Context, component, operation string, success bool, elapsed float64) {
if c.enabled {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.outputBindingCount.M(1))
if elapsed > 0 {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.outputBindingLatency.M(elapsed))
}
}
}
// StateInvoked records the metrics for a state event.
func (c *componentMetrics) StateInvoked(ctx context.Context, component, operation string, success bool, elapsed float64) {
if c.enabled {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.stateCount.M(1))
if elapsed > 0 {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.stateLatency.M(elapsed))
}
}
}
// ConfigurationInvoked records the metrics for a configuration event.
func (c *componentMetrics) ConfigurationInvoked(ctx context.Context, component, operation string, success bool, elapsed float64) {
if c.enabled {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.configurationCount.M(1))
if elapsed > 0 {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.configurationLatency.M(elapsed))
}
}
}
// SecretInvoked records the metrics for a secret event.
func (c *componentMetrics) SecretInvoked(ctx context.Context, component, operation string, success bool, elapsed float64) {
if c.enabled {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.secretCount.M(1))
if elapsed > 0 {
stats.RecordWithTags(
ctx,
diag_utils.WithTags(appIDKey, c.appID, componentKey, component, namespaceKey, c.namespace, operationKey, operation, successKey, fmt.Sprintf("%v", success)),
c.secretLatency.M(elapsed))
}
}
}
func ElapsedSince(start time.Time) float64 {
return float64(time.Since(start) / time.Millisecond)
} | pkg/diagnostics/component_monitoring.go | 0.620047 | 0.404537 | component_monitoring.go | starcoder |
package graph
import (
i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization"
)
// WorkbookRange
type WorkbookRange struct {
Entity
// Represents the range reference in A1-style. Address value will contain the Sheet reference (e.g. Sheet1!A1:B4). Read-only.
address *string;
// Represents range reference for the specified range in the language of the user. Read-only.
addressLocal *string;
// Number of cells in the range. Read-only.
cellCount *int32;
// Represents the total number of columns in the range. Read-only.
columnCount *int32;
// Represents if all columns of the current range are hidden.
columnHidden *bool;
// Represents the column number of the first cell in the range. Zero-indexed. Read-only.
columnIndex *int32;
// Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. Read-only.
format *WorkbookRangeFormat;
// Represents the formula in A1-style notation.
formulas *Json;
// Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English '=SUM(A1, 1.5)' formula would become '=SUMME(A1; 1,5)' in German.
formulasLocal *Json;
// Represents the formula in R1C1-style notation.
formulasR1C1 *Json;
// Represents if all cells of the current range are hidden. Read-only.
hidden *bool;
// Represents Excel's number format code for the given cell.
numberFormat *Json;
// Returns the total number of rows in the range. Read-only.
rowCount *int32;
// Represents if all rows of the current range are hidden.
rowHidden *bool;
// Returns the row number of the first cell in the range. Zero-indexed. Read-only.
rowIndex *int32;
// The worksheet containing the current range. Read-only.
sort *WorkbookRangeSort;
// Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only.
text *Json;
// Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.
values *Json;
// Represents the type of data of each cell. The possible values are: Unknown, Empty, String, Integer, Double, Boolean, Error. Read-only.
valueTypes *Json;
// The worksheet containing the current range. Read-only.
worksheet *WorkbookWorksheet;
}
// NewWorkbookRange instantiates a new workbookRange and sets the default values.
func NewWorkbookRange()(*WorkbookRange) {
m := &WorkbookRange{
Entity: *NewEntity(),
}
return m
}
// GetAddress gets the address property value. Represents the range reference in A1-style. Address value will contain the Sheet reference (e.g. Sheet1!A1:B4). Read-only.
func (m *WorkbookRange) GetAddress()(*string) {
if m == nil {
return nil
} else {
return m.address
}
}
// GetAddressLocal gets the addressLocal property value. Represents range reference for the specified range in the language of the user. Read-only.
func (m *WorkbookRange) GetAddressLocal()(*string) {
if m == nil {
return nil
} else {
return m.addressLocal
}
}
// GetCellCount gets the cellCount property value. Number of cells in the range. Read-only.
func (m *WorkbookRange) GetCellCount()(*int32) {
if m == nil {
return nil
} else {
return m.cellCount
}
}
// GetColumnCount gets the columnCount property value. Represents the total number of columns in the range. Read-only.
func (m *WorkbookRange) GetColumnCount()(*int32) {
if m == nil {
return nil
} else {
return m.columnCount
}
}
// GetColumnHidden gets the columnHidden property value. Represents if all columns of the current range are hidden.
func (m *WorkbookRange) GetColumnHidden()(*bool) {
if m == nil {
return nil
} else {
return m.columnHidden
}
}
// GetColumnIndex gets the columnIndex property value. Represents the column number of the first cell in the range. Zero-indexed. Read-only.
func (m *WorkbookRange) GetColumnIndex()(*int32) {
if m == nil {
return nil
} else {
return m.columnIndex
}
}
// GetFormat gets the format property value. Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. Read-only.
func (m *WorkbookRange) GetFormat()(*WorkbookRangeFormat) {
if m == nil {
return nil
} else {
return m.format
}
}
// GetFormulas gets the formulas property value. Represents the formula in A1-style notation.
func (m *WorkbookRange) GetFormulas()(*Json) {
if m == nil {
return nil
} else {
return m.formulas
}
}
// GetFormulasLocal gets the formulasLocal property value. Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English '=SUM(A1, 1.5)' formula would become '=SUMME(A1; 1,5)' in German.
func (m *WorkbookRange) GetFormulasLocal()(*Json) {
if m == nil {
return nil
} else {
return m.formulasLocal
}
}
// GetFormulasR1C1 gets the formulasR1C1 property value. Represents the formula in R1C1-style notation.
func (m *WorkbookRange) GetFormulasR1C1()(*Json) {
if m == nil {
return nil
} else {
return m.formulasR1C1
}
}
// GetHidden gets the hidden property value. Represents if all cells of the current range are hidden. Read-only.
func (m *WorkbookRange) GetHidden()(*bool) {
if m == nil {
return nil
} else {
return m.hidden
}
}
// GetNumberFormat gets the numberFormat property value. Represents Excel's number format code for the given cell.
func (m *WorkbookRange) GetNumberFormat()(*Json) {
if m == nil {
return nil
} else {
return m.numberFormat
}
}
// GetRowCount gets the rowCount property value. Returns the total number of rows in the range. Read-only.
func (m *WorkbookRange) GetRowCount()(*int32) {
if m == nil {
return nil
} else {
return m.rowCount
}
}
// GetRowHidden gets the rowHidden property value. Represents if all rows of the current range are hidden.
func (m *WorkbookRange) GetRowHidden()(*bool) {
if m == nil {
return nil
} else {
return m.rowHidden
}
}
// GetRowIndex gets the rowIndex property value. Returns the row number of the first cell in the range. Zero-indexed. Read-only.
func (m *WorkbookRange) GetRowIndex()(*int32) {
if m == nil {
return nil
} else {
return m.rowIndex
}
}
// GetSort gets the sort property value. The worksheet containing the current range. Read-only.
func (m *WorkbookRange) GetSort()(*WorkbookRangeSort) {
if m == nil {
return nil
} else {
return m.sort
}
}
// GetText gets the text property value. Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only.
func (m *WorkbookRange) GetText()(*Json) {
if m == nil {
return nil
} else {
return m.text
}
}
// GetValues gets the values property value. Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.
func (m *WorkbookRange) GetValues()(*Json) {
if m == nil {
return nil
} else {
return m.values
}
}
// GetValueTypes gets the valueTypes property value. Represents the type of data of each cell. The possible values are: Unknown, Empty, String, Integer, Double, Boolean, Error. Read-only.
func (m *WorkbookRange) GetValueTypes()(*Json) {
if m == nil {
return nil
} else {
return m.valueTypes
}
}
// GetWorksheet gets the worksheet property value. The worksheet containing the current range. Read-only.
func (m *WorkbookRange) GetWorksheet()(*WorkbookWorksheet) {
if m == nil {
return nil
} else {
return m.worksheet
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *WorkbookRange) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["address"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAddress(val)
}
return nil
}
res["addressLocal"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAddressLocal(val)
}
return nil
}
res["cellCount"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetCellCount(val)
}
return nil
}
res["columnCount"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetColumnCount(val)
}
return nil
}
res["columnHidden"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetColumnHidden(val)
}
return nil
}
res["columnIndex"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetColumnIndex(val)
}
return nil
}
res["format"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewWorkbookRangeFormat() })
if err != nil {
return err
}
if val != nil {
m.SetFormat(val.(*WorkbookRangeFormat))
}
return nil
}
res["formulas"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetFormulas(val.(*Json))
}
return nil
}
res["formulasLocal"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetFormulasLocal(val.(*Json))
}
return nil
}
res["formulasR1C1"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetFormulasR1C1(val.(*Json))
}
return nil
}
res["hidden"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetHidden(val)
}
return nil
}
res["numberFormat"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetNumberFormat(val.(*Json))
}
return nil
}
res["rowCount"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetRowCount(val)
}
return nil
}
res["rowHidden"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetRowHidden(val)
}
return nil
}
res["rowIndex"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetRowIndex(val)
}
return nil
}
res["sort"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewWorkbookRangeSort() })
if err != nil {
return err
}
if val != nil {
m.SetSort(val.(*WorkbookRangeSort))
}
return nil
}
res["text"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetText(val.(*Json))
}
return nil
}
res["values"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetValues(val.(*Json))
}
return nil
}
res["valueTypes"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewJson() })
if err != nil {
return err
}
if val != nil {
m.SetValueTypes(val.(*Json))
}
return nil
}
res["worksheet"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return NewWorkbookWorksheet() })
if err != nil {
return err
}
if val != nil {
m.SetWorksheet(val.(*WorkbookWorksheet))
}
return nil
}
return res
}
func (m *WorkbookRange) IsNil()(bool) {
return m == nil
}
// Serialize serializes information the current object
func (m *WorkbookRange) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteStringValue("address", m.GetAddress())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("addressLocal", m.GetAddressLocal())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("cellCount", m.GetCellCount())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("columnCount", m.GetColumnCount())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("columnHidden", m.GetColumnHidden())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("columnIndex", m.GetColumnIndex())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("format", m.GetFormat())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("formulas", m.GetFormulas())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("formulasLocal", m.GetFormulasLocal())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("formulasR1C1", m.GetFormulasR1C1())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("hidden", m.GetHidden())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("numberFormat", m.GetNumberFormat())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("rowCount", m.GetRowCount())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("rowHidden", m.GetRowHidden())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("rowIndex", m.GetRowIndex())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("sort", m.GetSort())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("text", m.GetText())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("values", m.GetValues())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("valueTypes", m.GetValueTypes())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("worksheet", m.GetWorksheet())
if err != nil {
return err
}
}
return nil
}
// SetAddress sets the address property value. Represents the range reference in A1-style. Address value will contain the Sheet reference (e.g. Sheet1!A1:B4). Read-only.
func (m *WorkbookRange) SetAddress(value *string)() {
if m != nil {
m.address = value
}
}
// SetAddressLocal sets the addressLocal property value. Represents range reference for the specified range in the language of the user. Read-only.
func (m *WorkbookRange) SetAddressLocal(value *string)() {
if m != nil {
m.addressLocal = value
}
}
// SetCellCount sets the cellCount property value. Number of cells in the range. Read-only.
func (m *WorkbookRange) SetCellCount(value *int32)() {
if m != nil {
m.cellCount = value
}
}
// SetColumnCount sets the columnCount property value. Represents the total number of columns in the range. Read-only.
func (m *WorkbookRange) SetColumnCount(value *int32)() {
if m != nil {
m.columnCount = value
}
}
// SetColumnHidden sets the columnHidden property value. Represents if all columns of the current range are hidden.
func (m *WorkbookRange) SetColumnHidden(value *bool)() {
if m != nil {
m.columnHidden = value
}
}
// SetColumnIndex sets the columnIndex property value. Represents the column number of the first cell in the range. Zero-indexed. Read-only.
func (m *WorkbookRange) SetColumnIndex(value *int32)() {
if m != nil {
m.columnIndex = value
}
}
// SetFormat sets the format property value. Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties. Read-only.
func (m *WorkbookRange) SetFormat(value *WorkbookRangeFormat)() {
if m != nil {
m.format = value
}
}
// SetFormulas sets the formulas property value. Represents the formula in A1-style notation.
func (m *WorkbookRange) SetFormulas(value *Json)() {
if m != nil {
m.formulas = value
}
}
// SetFormulasLocal sets the formulasLocal property value. Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English '=SUM(A1, 1.5)' formula would become '=SUMME(A1; 1,5)' in German.
func (m *WorkbookRange) SetFormulasLocal(value *Json)() {
if m != nil {
m.formulasLocal = value
}
}
// SetFormulasR1C1 sets the formulasR1C1 property value. Represents the formula in R1C1-style notation.
func (m *WorkbookRange) SetFormulasR1C1(value *Json)() {
if m != nil {
m.formulasR1C1 = value
}
}
// SetHidden sets the hidden property value. Represents if all cells of the current range are hidden. Read-only.
func (m *WorkbookRange) SetHidden(value *bool)() {
if m != nil {
m.hidden = value
}
}
// SetNumberFormat sets the numberFormat property value. Represents Excel's number format code for the given cell.
func (m *WorkbookRange) SetNumberFormat(value *Json)() {
if m != nil {
m.numberFormat = value
}
}
// SetRowCount sets the rowCount property value. Returns the total number of rows in the range. Read-only.
func (m *WorkbookRange) SetRowCount(value *int32)() {
if m != nil {
m.rowCount = value
}
}
// SetRowHidden sets the rowHidden property value. Represents if all rows of the current range are hidden.
func (m *WorkbookRange) SetRowHidden(value *bool)() {
if m != nil {
m.rowHidden = value
}
}
// SetRowIndex sets the rowIndex property value. Returns the row number of the first cell in the range. Zero-indexed. Read-only.
func (m *WorkbookRange) SetRowIndex(value *int32)() {
if m != nil {
m.rowIndex = value
}
}
// SetSort sets the sort property value. The worksheet containing the current range. Read-only.
func (m *WorkbookRange) SetSort(value *WorkbookRangeSort)() {
if m != nil {
m.sort = value
}
}
// SetText sets the text property value. Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API. Read-only.
func (m *WorkbookRange) SetText(value *Json)() {
if m != nil {
m.text = value
}
}
// SetValues sets the values property value. Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.
func (m *WorkbookRange) SetValues(value *Json)() {
if m != nil {
m.values = value
}
}
// SetValueTypes sets the valueTypes property value. Represents the type of data of each cell. The possible values are: Unknown, Empty, String, Integer, Double, Boolean, Error. Read-only.
func (m *WorkbookRange) SetValueTypes(value *Json)() {
if m != nil {
m.valueTypes = value
}
}
// SetWorksheet sets the worksheet property value. The worksheet containing the current range. Read-only.
func (m *WorkbookRange) SetWorksheet(value *WorkbookWorksheet)() {
if m != nil {
m.worksheet = value
}
} | models/microsoft/graph/workbook_range.go | 0.756447 | 0.646293 | workbook_range.go | starcoder |
package client
// Volume represents a named volume in a pod that may be accessed by any container in the pod.
type V1Volume struct {
// AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore
AwsElasticBlockStore V1AwsElasticBlockStoreVolumeSource `json:"awsElasticBlockStore,omitempty"`
// AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.
AzureDisk V1AzureDiskVolumeSource `json:"azureDisk,omitempty"`
// AzureFile represents an Azure File Service mount on the host and bind mount to the pod.
AzureFile V1AzureFileVolumeSource `json:"azureFile,omitempty"`
// CephFS represents a Ceph FS mount on the host that shares a pod's lifetime
Cephfs V1CephFsVolumeSource `json:"cephfs,omitempty"`
// Cinder represents a cinder volume attached and mounted on kubelets host machine More info: https://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md
Cinder V1CinderVolumeSource `json:"cinder,omitempty"`
// ConfigMap represents a configMap that should populate this volume
ConfigMap V1ConfigMapVolumeSource `json:"configMap,omitempty"`
// DownwardAPI represents downward API about the pod that should populate this volume
DownwardAPI V1DownwardApiVolumeSource `json:"downwardAPI,omitempty"`
// EmptyDir represents a temporary directory that shares a pod's lifetime. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir
EmptyDir V1EmptyDirVolumeSource `json:"emptyDir,omitempty"`
// FC represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.
Fc V1FcVolumeSource `json:"fc,omitempty"`
// FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin. This is an alpha feature and may change in future.
FlexVolume V1FlexVolumeSource `json:"flexVolume,omitempty"`
// Flocker represents a Flocker volume attached to a kubelet's host machine. This depends on the Flocker control service being running
Flocker V1FlockerVolumeSource `json:"flocker,omitempty"`
// GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk
GcePersistentDisk V1GcePersistentDiskVolumeSource `json:"gcePersistentDisk,omitempty"`
// GitRepo represents a git repository at a particular revision.
GitRepo V1GitRepoVolumeSource `json:"gitRepo,omitempty"`
// Glusterfs represents a Glusterfs mount on the host that shares a pod's lifetime. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md
Glusterfs V1GlusterfsVolumeSource `json:"glusterfs,omitempty"`
// HostPath represents a pre-existing file or directory on the host machine that is directly exposed to the container. This is generally used for system agents or other privileged things that are allowed to see the host machine. Most containers will NOT need this. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath
HostPath V1HostPathVolumeSource `json:"hostPath,omitempty"`
// ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://releases.k8s.io/HEAD/examples/volumes/iscsi/README.md
Iscsi V1IscsiVolumeSource `json:"iscsi,omitempty"`
// Volume's name. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
Name string `json:"name"`
// NFS represents an NFS mount on the host that shares a pod's lifetime More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs
Nfs V1NfsVolumeSource `json:"nfs,omitempty"`
// PersistentVolumeClaimVolumeSource represents a reference to a PersistentVolumeClaim in the same namespace. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims
PersistentVolumeClaim V1PersistentVolumeClaimVolumeSource `json:"persistentVolumeClaim,omitempty"`
// PhotonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine
PhotonPersistentDisk V1PhotonPersistentDiskVolumeSource `json:"photonPersistentDisk,omitempty"`
// PortworxVolume represents a portworx volume attached and mounted on kubelets host machine
PortworxVolume V1PortworxVolumeSource `json:"portworxVolume,omitempty"`
// Items for all in one resources secrets, configmaps, and downward API
Projected V1ProjectedVolumeSource `json:"projected,omitempty"`
// Quobyte represents a Quobyte mount on the host that shares a pod's lifetime
Quobyte V1QuobyteVolumeSource `json:"quobyte,omitempty"`
// RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://releases.k8s.io/HEAD/examples/volumes/rbd/README.md
Rbd V1RbdVolumeSource `json:"rbd,omitempty"`
// ScaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes.
ScaleIO V1ScaleIoVolumeSource `json:"scaleIO,omitempty"`
// Secret represents a secret that should populate this volume. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret
Secret V1SecretVolumeSource `json:"secret,omitempty"`
// StorageOS represents a StorageOS volume attached and mounted on Kubernetes nodes.
Storageos V1StorageOsVolumeSource `json:"storageos,omitempty"`
// VsphereVolume represents a vSphere volume attached and mounted on kubelets host machine
VsphereVolume V1VsphereVirtualDiskVolumeSource `json:"vsphereVolume,omitempty"`
} | pkg/client/v1_volume.go | 0.85959 | 0.549882 | v1_volume.go | starcoder |
package toy
import (
"github.com/OpenWhiteBox/primitives/number"
)
// parasite represents the input or output mask of a single byte going into/out of an obfuscated affine layer.
type parasite struct {
frobenius int
scalar number.ByteFieldElem
}
func (p *parasite) Encode(in byte) byte {
temp := number.ByteFieldElem(in)
for i := 0; i < p.frobenius; i++ {
temp = temp.Mul(temp)
}
return byte(temp.Mul(p.scalar))
}
func (p *parasite) Decode(in byte) byte {
temp := number.ByteFieldElem(in).Mul(p.scalar.Invert())
n := (8 - p.frobenius) % 8
for i := 0; i < n; i++ {
temp = temp.Mul(temp)
}
return byte(temp)
}
// Convert returns the parasite which corresponds to p on the other side of an S-box layer.
func (p *parasite) Convert() *parasite {
frob := (8 - p.frobenius) % 8
scalar := p.scalar
for i := 0; i < frob; i++ {
scalar = scalar.Mul(scalar)
}
return ¶site{frob, scalar}
}
// parasites is a pre-computed lookup table, mapping 8-by-8 matrices to the parasites that induced them.
var parasites = map[string]*parasite{
"0102040810204080": ¶site{0, 0x01},
"8081028488102040": ¶site{0, 0x02},
"8183068c983060c0": ¶site{0, 0x03},
"40c08142c4881020": ¶site{0, 0x04},
"41c2854ad4a850a0": ¶site{0, 0x05},
"c04183c64c983060": ¶site{0, 0x06},
"c14387ce5cb870e0": ¶site{0, 0x07},
"2060c0a162c48810": ¶site{0, 0x08},
"2162c4a972e4c890": ¶site{0, 0x09},
"a0e1c225ead4a850": ¶site{0, 0x0a},
"a1e3c62dfaf4e8d0": ¶site{0, 0x0b},
"60a041e3a64c9830": ¶site{0, 0x0c},
"61a245ebb66cd8b0": ¶site{0, 0x0d},
"e02143672e5cb870": ¶site{0, 0x0e},
"e123476f3e7cf8f0": ¶site{0, 0x0f},
"103060d0b162c488": ¶site{0, 0x10},
"113264d8a1428408": ¶site{0, 0x11},
"90b162543972e4c8": ¶site{0, 0x12},
"91b3665c2952a448": ¶site{0, 0x13},
"50f0e19275ead4a8": ¶site{0, 0x14},
"51f2e59a65ca9428": ¶site{0, 0x15},
"d071e316fdfaf4e8": ¶site{0, 0x16},
"d173e71eeddab468": ¶site{0, 0x17},
"3050a071d3a64c98": ¶site{0, 0x18},
"3152a479c3860c18": ¶site{0, 0x19},
"b0d1a2f55bb66cd8": ¶site{0, 0x1a},
"b1d3a6fd4b962c58": ¶site{0, 0x1b},
"70902133172e5cb8": ¶site{0, 0x1c},
"7192253b070e1c38": ¶site{0, 0x1d},
"f01123b79f3e7cf8": ¶site{0, 0x1e},
"f11327bf8f1e3c78": ¶site{0, 0x1f},
"889830e858b162c4": ¶site{0, 0x20},
"899a34e048912244": ¶site{0, 0x21},
"0819326cd0a14284": ¶site{0, 0x22},
"091b3664c0810204": ¶site{0, 0x23},
"c858b1aa9c3972e4": ¶site{0, 0x24},
"c95ab5a28c193264": ¶site{0, 0x25},
"48d9b32e142952a4": ¶site{0, 0x26},
"49dbb72604091224": ¶site{0, 0x27},
"a8f8f0493a75ead4": ¶site{0, 0x28},
"a9faf4412a55aa54": ¶site{0, 0x29},
"2879f2cdb265ca94": ¶site{0, 0x2a},
"297bf6c5a2458a14": ¶site{0, 0x2b},
"e838710bfefdfaf4": ¶site{0, 0x2c},
"e93a7503eeddba74": ¶site{0, 0x2d},
"68b9738f76eddab4": ¶site{0, 0x2e},
"69bb778766cd9a34": ¶site{0, 0x2f},
"98a85038e9d3a64c": ¶site{0, 0x30},
"99aa5430f9f3e6cc": ¶site{0, 0x31},
"182952bc61c3860c": ¶site{0, 0x32},
"192b56b471e3c68c": ¶site{0, 0x33},
"d868d17a2d5bb66c": ¶site{0, 0x34},
"d96ad5723d7bf6ec": ¶site{0, 0x35},
"58e9d3fea54b962c": ¶site{0, 0x36},
"59ebd7f6b56bd6ac": ¶site{0, 0x37},
"b8c890998b172e5c": ¶site{0, 0x38},
"b9ca94919b376edc": ¶site{0, 0x39},
"3849921d03070e1c": ¶site{0, 0x3a},
"394b961513274e9c": ¶site{0, 0x3b},
"f80811db4f9f3e7c": ¶site{0, 0x3c},
"f90a15d35fbf7efc": ¶site{0, 0x3d},
"7889135fc78f1e3c": ¶site{0, 0x3e},
"798b1757d7af5ebc": ¶site{0, 0x3f},
"c44c98f42c58b162": ¶site{0, 0x40},
"c54e9cfc3c78f1e2": ¶site{0, 0x41},
"44cd9a70a4489122": ¶site{0, 0x42},
"45cf9e78b468d1a2": ¶site{0, 0x43},
"848c19b6e8d0a142": ¶site{0, 0x44},
"858e1dbef8f0e1c2": ¶site{0, 0x45},
"040d1b3260c08102": ¶site{0, 0x46},
"050f1f3a70e0c182": ¶site{0, 0x47},
"e42c58554e9c3972": ¶site{0, 0x48},
"e52e5c5d5ebc79f2": ¶site{0, 0x49},
"64ad5ad1c68c1932": ¶site{0, 0x4a},
"65af5ed9d6ac59b2": ¶site{0, 0x4b},
"a4ecd9178a142952": ¶site{0, 0x4c},
"a5eedd1f9a3469d2": ¶site{0, 0x4d},
"246ddb9302040912": ¶site{0, 0x4e},
"256fdf9b12244992": ¶site{0, 0x4f},
"d47cf8249d3a75ea": ¶site{0, 0x50},
"d57efc2c8d1a356a": ¶site{0, 0x51},
"54fdfaa0152a55aa": ¶site{0, 0x52},
"55fffea8050a152a": ¶site{0, 0x53},
"94bc796659b265ca": ¶site{0, 0x54},
"95be7d6e4992254a": ¶site{0, 0x55},
"143d7be2d1a2458a": ¶site{0, 0x56},
"153f7feac182050a": ¶site{0, 0x57},
"f41c3885fffefdfa": ¶site{0, 0x58},
"f51e3c8defdebd7a": ¶site{0, 0x59},
"749d3a0177eeddba": ¶site{0, 0x5a},
"759f3e0967ce9d3a": ¶site{0, 0x5b},
"b4dcb9c73b76edda": ¶site{0, 0x5c},
"b5debdcf2b56ad5a": ¶site{0, 0x5d},
"345dbb43b366cd9a": ¶site{0, 0x5e},
"355fbf4ba3468d1a": ¶site{0, 0x5f},
"4cd4a81c74e9d3a6": ¶site{0, 0x60},
"4dd6ac1464c99326": ¶site{0, 0x61},
"cc55aa98fcf9f3e6": ¶site{0, 0x62},
"cd57ae90ecd9b366": ¶site{0, 0x63},
"0c14295eb061c386": ¶site{0, 0x64},
"0d162d56a0418306": ¶site{0, 0x65},
"8c952bda3871e3c6": ¶site{0, 0x66},
"8d972fd22851a346": ¶site{0, 0x67},
"6cb468bd162d5bb6": ¶site{0, 0x68},
"6db66cb5060d1b36": ¶site{0, 0x69},
"ec356a399e3d7bf6": ¶site{0, 0x6a},
"ed376e318e1d3b76": ¶site{0, 0x6b},
"2c74e9ffd2a54b96": ¶site{0, 0x6c},
"2d76edf7c2850b16": ¶site{0, 0x6d},
"acf5eb7b5ab56bd6": ¶site{0, 0x6e},
"adf7ef734a952b56": ¶site{0, 0x6f},
"5ce4c8ccc58b172e": ¶site{0, 0x70},
"5de6ccc4d5ab57ae": ¶site{0, 0x71},
"dc65ca484d9b376e": ¶site{0, 0x72},
"dd67ce405dbb77ee": ¶site{0, 0x73},
"1c24498e0103070e": ¶site{0, 0x74},
"1d264d861123478e": ¶site{0, 0x75},
"9ca54b0a8913274e": ¶site{0, 0x76},
"9da74f02993367ce": ¶site{0, 0x77},
"7c84086da74f9f3e": ¶site{0, 0x78},
"7d860c65b76fdfbe": ¶site{0, 0x79},
"fc050ae92f5fbf7e": ¶site{0, 0x7a},
"fd070ee13f7ffffe": ¶site{0, 0x7b},
"3c44892f63c78f1e": ¶site{0, 0x7c},
"3d468d2773e7cf9e": ¶site{0, 0x7d},
"bcc58babebd7af5e": ¶site{0, 0x7e},
"bdc78fa3fbf7efde": ¶site{0, 0x7f},
"62a64cfa962c58b1": ¶site{0, 0x80},
"63a448f2860c1831": ¶site{0, 0x81},
"e2274e7e1e3c78f1": ¶site{0, 0x82},
"e3254a760e1c3871": ¶site{0, 0x83},
"2266cdb852a44891": ¶site{0, 0x84},
"2364c9b042840811": ¶site{0, 0x85},
"a2e7cf3cdab468d1": ¶site{0, 0x86},
"a3e5cb34ca942851": ¶site{0, 0x87},
"42c68c5bf4e8d0a1": ¶site{0, 0x88},
"43c48853e4c89021": ¶site{0, 0x89},
"c2478edf7cf8f0e1": ¶site{0, 0x8a},
"c3458ad76cd8b061": ¶site{0, 0x8b},
"02060d193060c081": ¶site{0, 0x8c},
"0304091120408001": ¶site{0, 0x8d},
"82870f9db870e0c1": ¶site{0, 0x8e},
"83850b95a850a041": ¶site{0, 0x8f},
"72962c2a274e9c39": ¶site{0, 0x90},
"73942822376edcb9": ¶site{0, 0x91},
"f2172eaeaf5ebc79": ¶site{0, 0x92},
"f3152aa6bf7efcf9": ¶site{0, 0x93},
"3256ad68e3c68c19": ¶site{0, 0x94},
"3354a960f3e6cc99": ¶site{0, 0x95},
"b2d7afec6bd6ac59": ¶site{0, 0x96},
"b3d5abe47bf6ecd9": ¶site{0, 0x97},
"52f6ec8b458a1429": ¶site{0, 0x98},
"53f4e88355aa54a9": ¶site{0, 0x99},
"d277ee0fcd9a3469": ¶site{0, 0x9a},
"d375ea07ddba74e9": ¶site{0, 0x9b},
"12366dc981020409": ¶site{0, 0x9c},
"133469c191224489": ¶site{0, 0x9d},
"92b76f4d09122449": ¶site{0, 0x9e},
"93b56b45193264c9": ¶site{0, 0x9f},
"ea3e7c12ce9d3a75": ¶site{0, 0xa0},
"eb3c781adebd7af5": ¶site{0, 0xa1},
"6abf7e96468d1a35": ¶site{0, 0xa2},
"6bbd7a9e56ad5ab5": ¶site{0, 0xa3},
"aafefd500a152a55": ¶site{0, 0xa4},
"abfcf9581a356ad5": ¶site{0, 0xa5},
"2a7fffd482050a15": ¶site{0, 0xa6},
"2b7dfbdc92254a95": ¶site{0, 0xa7},
"ca5ebcb3ac59b265": ¶site{0, 0xa8},
"cb5cb8bbbc79f2e5": ¶site{0, 0xa9},
"4adfbe3724499225": ¶site{0, 0xaa},
"4bddba3f3469d2a5": ¶site{0, 0xab},
"8a9e3df168d1a245": ¶site{0, 0xac},
"8b9c39f978f1e2c5": ¶site{0, 0xad},
"0a1f3f75e0c18205": ¶site{0, 0xae},
"0b1d3b7df0e1c285": ¶site{0, 0xaf},
"fa0e1cc27ffffefd": ¶site{0, 0xb0},
"fb0c18ca6fdfbe7d": ¶site{0, 0xb1},
"7a8f1e46f7efdebd": ¶site{0, 0xb2},
"7b8d1a4ee7cf9e3d": ¶site{0, 0xb3},
"bace9d80bb77eedd": ¶site{0, 0xb4},
"bbcc9988ab57ae5d": ¶site{0, 0xb5},
"3a4f9f043367ce9d": ¶site{0, 0xb6},
"3b4d9b0c23478e1d": ¶site{0, 0xb7},
"da6edc631d3b76ed": ¶site{0, 0xb8},
"db6cd86b0d1b366d": ¶site{0, 0xb9},
"5aefdee7952b56ad": ¶site{0, 0xba},
"5beddaef850b162d": ¶site{0, 0xbb},
"9aae5d21d9b366cd": ¶site{0, 0xbc},
"9bac5929c993264d": ¶site{0, 0xbd},
"1a2f5fa551a3468d": ¶site{0, 0xbe},
"1b2d5bad4183060d": ¶site{0, 0xbf},
"a6ead40eba74e9d3": ¶site{0, 0xc0},
"a7e8d006aa54a953": ¶site{0, 0xc1},
"266bd68a3264c993": ¶site{0, 0xc2},
"2769d28222448913": ¶site{0, 0xc3},
"e62a554c7efcf9f3": ¶site{0, 0xc4},
"e72851446edcb973": ¶site{0, 0xc5},
"66ab57c8f6ecd9b3": ¶site{0, 0xc6},
"67a953c0e6cc9933": ¶site{0, 0xc7},
"868a14afd8b061c3": ¶site{0, 0xc8},
"878810a7c8902143": ¶site{0, 0xc9},
"060b162b50a04183": ¶site{0, 0xca},
"0709122340800103": ¶site{0, 0xcb},
"c64a95ed1c3871e3": ¶site{0, 0xcc},
"c74891e50c183163": ¶site{0, 0xcd},
"46cb9769942851a3": ¶site{0, 0xce},
"47c9936184081123": ¶site{0, 0xcf},
"b6dab4de0b162d5b": ¶site{0, 0xd0},
"b7d8b0d61b366ddb": ¶site{0, 0xd1},
"365bb65a83060d1b": ¶site{0, 0xd2},
"3759b25293264d9b": ¶site{0, 0xd3},
"f61a359ccf9e3d7b": ¶site{0, 0xd4},
"f7183194dfbe7dfb": ¶site{0, 0xd5},
"769b3718478e1d3b": ¶site{0, 0xd6},
"7799331057ae5dbb": ¶site{0, 0xd7},
"96ba747f69d2a54b": ¶site{0, 0xd8},
"97b8707779f2e5cb": ¶site{0, 0xd9},
"163b76fbe1c2850b": ¶site{0, 0xda},
"173972f3f1e2c58b": ¶site{0, 0xdb},
"d67af53dad5ab56b": ¶site{0, 0xdc},
"d778f135bd7af5eb": ¶site{0, 0xdd},
"56fbf7b9254a952b": ¶site{0, 0xde},
"57f9f3b1356ad5ab": ¶site{0, 0xdf},
"2e72e4e6e2c58b17": ¶site{0, 0xe0},
"2f70e0eef2e5cb97": ¶site{0, 0xe1},
"aef3e6626ad5ab57": ¶site{0, 0xe2},
"aff1e26a7af5ebd7": ¶site{0, 0xe3},
"6eb265a4264d9b37": ¶site{0, 0xe4},
"6fb061ac366ddbb7": ¶site{0, 0xe5},
"ee336720ae5dbb77": ¶site{0, 0xe6},
"ef316328be7dfbf7": ¶site{0, 0xe7},
"0e12244780010307": ¶site{0, 0xe8},
"0f10204f90214387": ¶site{0, 0xe9},
"8e9326c308112347": ¶site{0, 0xea},
"8f9122cb183163c7": ¶site{0, 0xeb},
"4ed2a50544891327": ¶site{0, 0xec},
"4fd0a10d54a953a7": ¶site{0, 0xed},
"ce53a781cc993367": ¶site{0, 0xee},
"cf51a389dcb973e7": ¶site{0, 0xef},
"3e42843653a74f9f": ¶site{0, 0xf0},
"3f40803e43870f1f": ¶site{0, 0xf1},
"bec386b2dbb76fdf": ¶site{0, 0xf2},
"bfc182bacb972f5f": ¶site{0, 0xf3},
"7e820574972f5fbf": ¶site{0, 0xf4},
"7f80017c870f1f3f": ¶site{0, 0xf5},
"fe0307f01f3f7fff": ¶site{0, 0xf6},
"ff0103f80f1f3f7f": ¶site{0, 0xf7},
"1e2244973163c78f": ¶site{0, 0xf8},
"1f20409f2143870f": ¶site{0, 0xf9},
"9ea34613b973e7cf": ¶site{0, 0xfa},
"9fa1421ba953a74f": ¶site{0, 0xfb},
"5ee2c5d5f5ebd7af": ¶site{0, 0xfc},
"5fe0c1dde5cb972f": ¶site{0, 0xfd},
"de63c7517dfbf7ef": ¶site{0, 0xfe},
"df61c3596ddbb76f": ¶site{0, 0xff},
"51d022f0946028c0": ¶site{1, 0x01},
"c091d0e230946028": ¶site{1, 0x02},
"9141f212a4f448e8": ¶site{1, 0x03},
"28e891f8ca309460": ¶site{1, 0x04},
"7938b3085e50bca0": ¶site{1, 0x05},
"e879411afaa4f448": ¶site{1, 0x06},
"b9a963ea6ec4dc88": ¶site{1, 0x07},
"6048e8f198ca3094": ¶site{1, 0x08},
"3198ca010caa1854": ¶site{1, 0x09},
"a0d93813a85e50bc": ¶site{1, 0x0a},
"f1091ae33c3e787c": ¶site{1, 0x0b},
"48a0790952faa4f4": ¶site{1, 0x0c},
"19705bf9c69a8c34": ¶site{1, 0x0d},
"8831a9eb626ec4dc": ¶site{1, 0x0e},
"d9e18b1bf60eec1c": ¶site{1, 0x0f},
"94f4487c6598ca30": ¶site{1, 0x10},
"c5246a8cf1f8e2f0": ¶site{1, 0x11},
"5465989e550caa18": ¶site{1, 0x12},
"05b5ba6ec16c82d8": ¶site{1, 0x13},
"bc1cd984afa85e50": ¶site{1, 0x14},
"edccfb743bc87690": ¶site{1, 0x15},
"7c8d09669f3c3e78": ¶site{1, 0x16},
"2d5d2b960b5c16b8": ¶site{1, 0x17},
"f4bca08dfd52faa4": ¶site{1, 0x18},
"a56c827d6932d264": ¶site{1, 0x19},
"342d706fcdc69a8c": ¶site{1, 0x1a},
"65fd529f59a6b24c": ¶site{1, 0x1b},
"dc54317537626ec4": ¶site{1, 0x1c},
"8d841385a3024604": ¶site{1, 0x1d},
"1cc5e19707f60eec": ¶site{1, 0x1e},
"4d15c3679396262c": ¶site{1, 0x1f},
"30a4f4784c6598ca": ¶site{1, 0x20},
"6174d688d805b00a": ¶site{1, 0x21},
"f035249a7cf1f8e2": ¶site{1, 0x22},
"a1e5066ae891d022": ¶site{1, 0x23},
"184c658086550caa": ¶site{1, 0x24},
"499c47701235246a": ¶site{1, 0x25},
"d8ddb562b6c16c82": ¶site{1, 0x26},
"890d979222a14442": ¶site{1, 0x27},
"50ec1c89d4afa85e": ¶site{1, 0x28},
"013c3e7940cf809e": ¶site{1, 0x29},
"907dcc6be43bc876": ¶site{1, 0x2a},
"c1adee9b705be0b6": ¶site{1, 0x2b},
"78048d711e9f3c3e": ¶site{1, 0x2c},
"29d4af818aff14fe": ¶site{1, 0x2d},
"b8955d932e0b5c16": ¶site{1, 0x2e},
"e9457f63ba6b74d6": ¶site{1, 0x2f},
"a450bc0429fd52fa": ¶site{1, 0x30},
"f5809ef4bd9d7a3a": ¶site{1, 0x31},
"64c16ce6196932d2": ¶site{1, 0x32},
"35114e168d091a12": ¶site{1, 0x33},
"8cb82dfce3cdc69a": ¶site{1, 0x34},
"dd680f0c77adee5a": ¶site{1, 0x35},
"4c29fd1ed359a6b2": ¶site{1, 0x36},
"1df9dfee47398e72": ¶site{1, 0x37},
"c41854f5b137626e": ¶site{1, 0x38},
"95c8760525574aae": ¶site{1, 0x39},
"0489841781a30246": ¶site{1, 0x3a},
"5559a6e715c32a86": ¶site{1, 0x3b},
"ecf0c50d7b07f60e": ¶site{1, 0x3c},
"bd20e7fdef67dece": ¶site{1, 0x3d},
"2c6115ef4b939626": ¶site{1, 0x3e},
"7db1371fdff3bee6": ¶site{1, 0x3f},
"cafaa43eb24c6598": ¶site{1, 0x40},
"9b2a86ce262c4d58": ¶site{1, 0x41},
"0a6b74dc82d805b0": ¶site{1, 0x42},
"5bbb562c16b82d70": ¶site{1, 0x43},
"e21235c6787cf1f8": ¶site{1, 0x44},
"b3c21736ec1cd938": ¶site{1, 0x45},
"2283e52448e891d0": ¶site{1, 0x46},
"7353c7d4dc88b910": ¶site{1, 0x47},
"aab24ccf2a86550c": ¶site{1, 0x48},
"fb626e3fbee67dcc": ¶site{1, 0x49},
"6a239c2d1a123524": ¶site{1, 0x4a},
"3bf3bedd8e721de4": ¶site{1, 0x4b},
"825add37e0b6c16c": ¶site{1, 0x4c},
"d38affc774d6e9ac": ¶site{1, 0x4d},
"42cb0dd5d022a144": ¶site{1, 0x4e},
"131b2f2544428984": ¶site{1, 0x4f},
"5e0eec42d7d4afa8": ¶site{1, 0x50},
"0fdeceb243b48768": ¶site{1, 0x51},
"9e9f3ca0e740cf80": ¶site{1, 0x52},
"cf4f1e507320e740": ¶site{1, 0x53},
"76e67dba1de43bc8": ¶site{1, 0x54},
"27365f4a89841308": ¶site{1, 0x55},
"b677ad582d705be0": ¶site{1, 0x56},
"e7a78fa8b9107320": ¶site{1, 0x57},
"3e4604b34f1e9f3c": ¶site{1, 0x58},
"6f962643db7eb7fc": ¶site{1, 0x59},
"fed7d4517f8aff14": ¶site{1, 0x5a},
"af07f6a1ebead7d4": ¶site{1, 0x5b},
"16ae954b852e0b5c": ¶site{1, 0x5c},
"477eb7bb114e239c": ¶site{1, 0x5d},
"d63f45a9b5ba6b74": ¶site{1, 0x5e},
"87ef675921da43b4": ¶site{1, 0x5f},
"fa5e5046fe29fd52": ¶site{1, 0x60},
"ab8e72b66a49d592": ¶site{1, 0x61},
"3acf80a4cebd9d7a": ¶site{1, 0x62},
"6b1fa2545addb5ba": ¶site{1, 0x63},
"d2b6c1be34196932": ¶site{1, 0x64},
"8366e34ea07941f2": ¶site{1, 0x65},
"1227115c048d091a": ¶site{1, 0x66},
"43f733ac90ed21da": ¶site{1, 0x67},
"9a16b8b766e3cdc6": ¶site{1, 0x68},
"cbc69a47f283e506": ¶site{1, 0x69},
"5a8768555677adee": ¶site{1, 0x6a},
"0b574aa5c217852e": ¶site{1, 0x6b},
"b2fe294facd359a6": ¶site{1, 0x6c},
"e32e0bbf38b37166": ¶site{1, 0x6d},
"726ff9ad9c47398e": ¶site{1, 0x6e},
"23bfdb5d0827114e": ¶site{1, 0x6f},
"6eaa183a9bb13762": ¶site{1, 0x70},
"3f7a3aca0fd11fa2": ¶site{1, 0x71},
"ae3bc8d8ab25574a": ¶site{1, 0x72},
"ffebea283f457f8a": ¶site{1, 0x73},
"464289c25181a302": ¶site{1, 0x74},
"1792ab32c5e18bc2": ¶site{1, 0x75},
"86d359206115c32a": ¶site{1, 0x76},
"d7037bd0f575ebea": ¶site{1, 0x77},
"0ee2f0cb037b07f6": ¶site{1, 0x78},
"5f32d23b971b2f36": ¶site{1, 0x79},
"ce73202933ef67de": ¶site{1, 0x7a},
"9fa302d9a78f4f1e": ¶site{1, 0x7b},
"260a6133c94b9396": ¶site{1, 0x7c},
"77da43c35d2bbb56": ¶site{1, 0x7d},
"e69bb1d1f9dff3be": ¶site{1, 0x7e},
"b74b93216dbfdb7e": ¶site{1, 0x7f},
"9852fa3ca6b24c65": ¶site{1, 0x80},
"c982d8cc32d264a5": ¶site{1, 0x81},
"58c32ade96262c4d": ¶site{1, 0x82},
"0913082e0246048d": ¶site{1, 0x83},
"b0ba6bc46c82d805": ¶site{1, 0x84},
"e16a4934f8e2f0c5": ¶site{1, 0x85},
"702bbb265c16b82d": ¶site{1, 0x86},
"21fb99d6c87690ed": ¶site{1, 0x87},
"f81a12cd3e787cf1": ¶site{1, 0x88},
"a9ca303daa185431": ¶site{1, 0x89},
"388bc22f0eec1cd9": ¶site{1, 0x8a},
"695be0df9a8c3419": ¶site{1, 0x8b},
"d0f28335f448e891": ¶site{1, 0x8c},
"8122a1c56028c051": ¶site{1, 0x8d},
"106353d7c4dc88b9": ¶site{1, 0x8e},
"41b3712750bca079": ¶site{1, 0x8f},
"0ca6b240c32a8655": ¶site{1, 0x90},
"5d7690b0574aae95": ¶site{1, 0x91},
"cc3762a2f3bee67d": ¶site{1, 0x92},
"9de7405267decebd": ¶site{1, 0x93},
"244e23b8091a1235": ¶site{1, 0x94},
"759e01489d7a3af5": ¶site{1, 0x95},
"e4dff35a398e721d": ¶site{1, 0x96},
"b50fd1aaadee5add": ¶site{1, 0x97},
"6cee5ab15be0b6c1": ¶site{1, 0x98},
"3d3e7841cf809e01": ¶site{1, 0x99},
"ac7f8a536b74d6e9": ¶site{1, 0x9a},
"fdafa8a3ff14fe29": ¶site{1, 0x9b},
"4406cb4991d022a1": ¶site{1, 0x9c},
"15d6e9b905b00a61": ¶site{1, 0x9d},
"84971baba1444289": ¶site{1, 0x9e},
"d547395b35246a49": ¶site{1, 0x9f},
"a8f60e44ead7d4af": ¶site{1, 0xa0},
"f9262cb47eb7fc6f": ¶site{1, 0xa1},
"6867dea6da43b487": ¶site{1, 0xa2},
"39b7fc564e239c47": ¶site{1, 0xa3},
"801e9fbc20e740cf": ¶site{1, 0xa4},
"d1cebd4cb487680f": ¶site{1, 0xa5},
"408f4f5e107320e7": ¶site{1, 0xa6},
"115f6dae84130827": ¶site{1, 0xa7},
"c8bee6b5721de43b": ¶site{1, 0xa8},
"996ec445e67dccfb": ¶site{1, 0xa9},
"082f365742898413": ¶site{1, 0xaa},
"59ff14a7d6e9acd3": ¶site{1, 0xab},
"e056774db82d705b": ¶site{1, 0xac},
"b18655bd2c4d589b": ¶site{1, 0xad},
"20c7a7af88b91073": ¶site{1, 0xae},
"7117855f1cd938b3": ¶site{1, 0xaf},
"3c0246388f4f1e9f": ¶site{1, 0xb0},
"6dd264c81b2f365f": ¶site{1, 0xb1},
"fc9396dabfdb7eb7": ¶site{1, 0xb2},
"ad43b42a2bbb5677": ¶site{1, 0xb3},
"14ead7c0457f8aff": ¶site{1, 0xb4},
"453af530d11fa23f": ¶site{1, 0xb5},
"d47b072275ebead7": ¶site{1, 0xb6},
"85ab25d2e18bc217": ¶site{1, 0xb7},
"5c4aaec917852e0b": ¶site{1, 0xb8},
"0d9a8c3983e506cb": ¶site{1, 0xb9},
"9cdb7e2b27114e23": ¶site{1, 0xba},
"cd0b5cdbb37166e3": ¶site{1, 0xbb},
"74a23f31ddb5ba6b": ¶site{1, 0xbc},
"25721dc149d592ab": ¶site{1, 0xbd},
"b433efd3ed21da43": ¶site{1, 0xbe},
"e5e3cd237941f283": ¶site{1, 0xbf},
"52a85e0214fe29fd": ¶site{1, 0xc0},
"03787cf2809e013d": ¶site{1, 0xc1},
"92398ee0246a49d5": ¶site{1, 0xc2},
"c3e9ac10b00a6115": ¶site{1, 0xc3},
"7a40cffadecebd9d": ¶site{1, 0xc4},
"2b90ed0a4aae955d": ¶site{1, 0xc5},
"bad11f18ee5addb5": ¶site{1, 0xc6},
"eb013de87a3af575": ¶site{1, 0xc7},
"32e0b6f38c341969": ¶site{1, 0xc8},
"63309403185431a9": ¶site{1, 0xc9},
"f2716611bca07941": ¶site{1, 0xca},
"a3a144e128c05181": ¶site{1, 0xcb},
"1a08270b46048d09": ¶site{1, 0xcc},
"4bd805fbd264a5c9": ¶site{1, 0xcd},
"da99f7e97690ed21": ¶site{1, 0xce},
"8b49d519e2f0c5e1": ¶site{1, 0xcf},
"c65c167e7166e3cd": ¶site{1, 0xd0},
"978c348ee506cb0d": ¶site{1, 0xd1},
"06cdc69c41f283e5": ¶site{1, 0xd2},
"571de46cd592ab25": ¶site{1, 0xd3},
"eeb48786bb5677ad": ¶site{1, 0xd4},
"bf64a5762f365f6d": ¶site{1, 0xd5},
"2e2557648bc21785": ¶site{1, 0xd6},
"7ff575941fa23f45": ¶site{1, 0xd7},
"a614fe8fe9acd359": ¶site{1, 0xd8},
"f7c4dc7f7dccfb99": ¶site{1, 0xd9},
"66852e6dd938b371": ¶site{1, 0xda},
"37550c9d4d589bb1": ¶site{1, 0xdb},
"8efc6f77239c4739": ¶site{1, 0xdc},
"df2c4d87b7fc6ff9": ¶site{1, 0xdd},
"4e6dbf9513082711": ¶site{1, 0xde},
"1fbd9d6587680fd1": ¶site{1, 0xdf},
"620caa7a589bb137": ¶site{1, 0xe0},
"33dc888accfb99f7": ¶site{1, 0xe1},
"a29d7a98680fd11f": ¶site{1, 0xe2},
"f34d5868fc6ff9df": ¶site{1, 0xe3},
"4ae43b8292ab2557": ¶site{1, 0xe4},
"1b34197206cb0d97": ¶site{1, 0xe5},
"8a75eb60a23f457f": ¶site{1, 0xe6},
"dba5c990365f6dbf": ¶site{1, 0xe7},
"0244428bc05181a3": ¶site{1, 0xe8},
"5394607b5431a963": ¶site{1, 0xe9},
"c2d59269f0c5e18b": ¶site{1, 0xea},
"9305b09964a5c94b": ¶site{1, 0xeb},
"2aacd3730a6115c3": ¶site{1, 0xec},
"7b7cf1839e013d03": ¶site{1, 0xed},
"ea3d03913af575eb": ¶site{1, 0xee},
"bbed2161ae955d2b": ¶site{1, 0xef},
"f6f8e2063d037b07": ¶site{1, 0xf0},
"a728c0f6a96353c7": ¶site{1, 0xf1},
"366932e40d971b2f": ¶site{1, 0xf2},
"67b9101499f733ef": ¶site{1, 0xf3},
"de1073fef733ef67": ¶site{1, 0xf4},
"8fc0510e6353c7a7": ¶site{1, 0xf5},
"1e81a31cc7a78f4f": ¶site{1, 0xf6},
"4f5181ec53c7a78f": ¶site{1, 0xf7},
"96b00af7a5c94b93": ¶site{1, 0xf8},
"c760280731a96353": ¶site{1, 0xf9},
"5621da15955d2bbb": ¶site{1, 0xfa},
"07f1f8e5013d037b": ¶site{1, 0xfb},
"be589b0f6ff9dff3": ¶site{1, 0xfc},
"ef88b9fffb99f733": ¶site{1, 0xfd},
"7ec94bed5f6dbfdb": ¶site{1, 0xfe},
"2f19691dcb0d971b": ¶site{1, 0xff},
"ed7cb01c764890e8": ¶site{2, 0x01},
"e8057c58f4764890": ¶site{2, 0x02},
"0579cc44823ed878": ¶site{2, 0x03},
"907805ecc8f47648": ¶site{2, 0x04},
"7d04b5f0bebce6a0": ¶site{2, 0x05},
"787d79b43c823ed8": ¶site{2, 0x06},
"9501c9a84acaae30": ¶site{2, 0x07},
"48d8784da4c8f476": ¶site{2, 0x08},
"a5a4c851d280649e": ¶site{2, 0x09},
"a0dd041550bebce6": ¶site{2, 0x0a},
"4da1b40926f62c0e": ¶site{2, 0x0b},
"d8a07da16c3c823e": ¶site{2, 0x0c},
"35dccdbd1a7412d6": ¶site{2, 0x0d},
"30a501f9984acaae": ¶site{2, 0x0e},
"ddd9b1e5ee025a46": ¶site{2, 0x0f},
"763ed80e3ba4c8f4": ¶site{2, 0x10},
"9b4268124dec581c": ¶site{2, 0x11},
"9e3ba456cfd28064": ¶site{2, 0x12},
"7347144ab99a108c": ¶site{2, 0x13},
"e646dde2f350bebc": ¶site{2, 0x14},
"0b3a6dfe85182e54": ¶site{2, 0x15},
"0e43a1ba0726f62c": ¶site{2, 0x16},
"e33f11a6716e66c4": ¶site{2, 0x17},
"3ee6a0439f6c3c82": ¶site{2, 0x18},
"d39a105fe924ac6a": ¶site{2, 0x19},
"d6e3dc1b6b1a7412": ¶site{2, 0x1a},
"3b9f6c071d52e4fa": ¶site{2, 0x1b},
"ae9ea5af57984aca": ¶site{2, 0x1c},
"43e215b321d0da22": ¶site{2, 0x1d},
"469bd9f7a3ee025a": ¶site{2, 0x1e},
"abe769ebd5a692b2": ¶site{2, 0x1f},
"f4823e2cfa3ba4c8": ¶site{2, 0x20},
"19fe8e308c733420": ¶site{2, 0x21},
"1c8742740e4dec58": ¶site{2, 0x22},
"f1fbf26878057cb0": ¶site{2, 0x23},
"64fa3bc032cfd280": ¶site{2, 0x24},
"89868bdc44874268": ¶site{2, 0x25},
"8cff4798c6b99a10": ¶site{2, 0x26},
"6183f784b0f10af8": ¶site{2, 0x27},
"bc5a46615ef350be": ¶site{2, 0x28},
"5126f67d28bbc056": ¶site{2, 0x29},
"545f3a39aa85182e": ¶site{2, 0x2a},
"b9238a25dccd88c6": ¶site{2, 0x2b},
"2c22438d960726f6": ¶site{2, 0x2c},
"c15ef391e04fb61e": ¶site{2, 0x2d},
"c4273fd562716e66": ¶site{2, 0x2e},
"295b8fc91439fe8e": ¶site{2, 0x2f},
"82bce622c19f6c3c": ¶site{2, 0x30},
"6fc0563eb7d7fcd4": ¶site{2, 0x31},
"6ab99a7a35e924ac": ¶site{2, 0x32},
"87c52a6643a1b444": ¶site{2, 0x33},
"12c4e3ce096b1a74": ¶site{2, 0x34},
"ffb853d27f238a9c": ¶site{2, 0x35},
"fac19f96fd1d52e4": ¶site{2, 0x36},
"17bd2f8a8b55c20c": ¶site{2, 0x37},
"ca649e6f6557984a": ¶site{2, 0x38},
"27182e73131f08a2": ¶site{2, 0x39},
"2261e2379121d0da": ¶site{2, 0x3a},
"cf1d522be7694032": ¶site{2, 0x3b},
"5a1c9b83ada3ee02": ¶site{2, 0x3c},
"b7602b9fdbeb7eea": ¶site{2, 0x3d},
"b219e7db59d5a692": ¶site{2, 0x3e},
"5f6557c72f9d367a": ¶site{2, 0x3f},
"c83c82f6e4fa3ba4": ¶site{2, 0x40},
"254032ea92b2ab4c": ¶site{2, 0x41},
"2039feae108c7334": ¶site{2, 0x42},
"cd454eb266c4e3dc": ¶site{2, 0x43},
"5844871a2c0e4dec": ¶site{2, 0x44},
"b53837065a46dd04": ¶site{2, 0x45},
"b041fb42d878057c": ¶site{2, 0x46},
"5d3d4b5eae309594": ¶site{2, 0x47},
"80e4fabb4032cfd2": ¶site{2, 0x48},
"6d984aa7367a5f3a": ¶site{2, 0x49},
"68e186e3b4448742": ¶site{2, 0x4a},
"859d36ffc20c17aa": ¶site{2, 0x4b},
"109cff5788c6b99a": ¶site{2, 0x4c},
"fde04f4bfe8e2972": ¶site{2, 0x4d},
"f899830f7cb0f10a": ¶site{2, 0x4e},
"15e533130af861e2": ¶site{2, 0x4f},
"be025af8df5ef350": ¶site{2, 0x50},
"537eeae4a91663b8": ¶site{2, 0x51},
"560726a02b28bbc0": ¶site{2, 0x52},
"bb7b96bc5d602b28": ¶site{2, 0x53},
"2e7a5f1417aa8518": ¶site{2, 0x54},
"c306ef0861e215f0": ¶site{2, 0x55},
"c67f234ce3dccd88": ¶site{2, 0x56},
"2b03935095945d60": ¶site{2, 0x57},
"f6da22b57b960726": ¶site{2, 0x58},
"1ba692a90dde97ce": ¶site{2, 0x59},
"1edf5eed8fe04fb6": ¶site{2, 0x5a},
"f3a3eef1f9a8df5e": ¶site{2, 0x5b},
"66a22759b362716e": ¶site{2, 0x5c},
"8bde9745c52ae186": ¶site{2, 0x5d},
"8ea75b01471439fe": ¶site{2, 0x5e},
"63dbeb1d315ca916": ¶site{2, 0x5f},
"3cbebcda1ec19f6c": ¶site{2, 0x60},
"d1c20cc668890f84": ¶site{2, 0x61},
"d4bbc082eab7d7fc": ¶site{2, 0x62},
"39c7709e9cff4714": ¶site{2, 0x63},
"acc6b936d635e924": ¶site{2, 0x64},
"41ba092aa07d79cc": ¶site{2, 0x65},
"44c3c56e2243a1b4": ¶site{2, 0x66},
"a9bf7572540b315c": ¶site{2, 0x67},
"7466c497ba096b1a": ¶site{2, 0x68},
"991a748bcc41fbf2": ¶site{2, 0x69},
"9c63b8cf4e7f238a": ¶site{2, 0x6a},
"711f08d33837b362": ¶site{2, 0x6b},
"e41ec17b72fd1d52": ¶site{2, 0x6c},
"0962716704b58dba": ¶site{2, 0x6d},
"0c1bbd23868b55c2": ¶site{2, 0x6e},
"e1670d3ff0c3c52a": ¶site{2, 0x6f},
"4a8064d425655798": ¶site{2, 0x70},
"a7fcd4c8532dc770": ¶site{2, 0x71},
"a285188cd1131f08": ¶site{2, 0x72},
"4ff9a890a75b8fe0": ¶site{2, 0x73},
"daf86138ed9121d0": ¶site{2, 0x74},
"3784d1249bd9b138": ¶site{2, 0x75},
"32fd1d6019e76940": ¶site{2, 0x76},
"df81ad7c6faff9a8": ¶site{2, 0x77},
"02581c9981ada3ee": ¶site{2, 0x78},
"ef24ac85f7e53306": ¶site{2, 0x79},
"ea5d60c175dbeb7e": ¶site{2, 0x7a},
"0721d0dd03937b96": ¶site{2, 0x7b},
"922019754959d5a6": ¶site{2, 0x7c},
"7f5ca9693f11454e": ¶site{2, 0x7d},
"7a25652dbd2f9d36": ¶site{2, 0x7e},
"9759d531cb670dde": ¶site{2, 0x7f},
"a46c3c2652e4fa3b": ¶site{2, 0x80},
"49108c3a24ac6ad3": ¶site{2, 0x81},
"4c69407ea692b2ab": ¶site{2, 0x82},
"a115f062d0da2243": ¶site{2, 0x83},
"341439ca9a108c73": ¶site{2, 0x84},
"d96889d6ec581c9b": ¶site{2, 0x85},
"dc1145926e66c4e3": ¶site{2, 0x86},
"316df58e182e540b": ¶site{2, 0x87},
"ecb4446bf62c0e4d": ¶site{2, 0x88},
"01c8f47780649ea5": ¶site{2, 0x89},
"04b13833025a46dd": ¶site{2, 0x8a},
"e9cd882f7412d635": ¶site{2, 0x8b},
"7ccc41873ed87805": ¶site{2, 0x8c},
"91b0f19b4890e8ed": ¶site{2, 0x8d},
"94c93ddfcaae3095": ¶site{2, 0x8e},
"79b58dc3bce6a07d": ¶site{2, 0x8f},
"d252e428694032cf": ¶site{2, 0x90},
"3f2e54341f08a227": ¶site{2, 0x91},
"3a5798709d367a5f": ¶site{2, 0x92},
"d72b286ceb7eeab7": ¶site{2, 0x93},
"422ae1c4a1b44487": ¶site{2, 0x94},
"af5651d8d7fcd46f": ¶site{2, 0x95},
"aa2f9d9c55c20c17": ¶site{2, 0x96},
"47532d80238a9cff": ¶site{2, 0x97},
"9a8a9c65cd88c6b9": ¶site{2, 0x98},
"77f62c79bbc05651": ¶site{2, 0x99},
"728fe03d39fe8e29": ¶site{2, 0x9a},
"9ff350214fb61ec1": ¶site{2, 0x9b},
"0af29989057cb0f1": ¶site{2, 0x9c},
"e78e299573342019": ¶site{2, 0x9d},
"e2f7e5d1f10af861": ¶site{2, 0x9e},
"0f8b55cd87426889": ¶site{2, 0x9f},
"50ee020aa8df5ef3": ¶site{2, 0xa0},
"bd92b216de97ce1b": ¶site{2, 0xa1},
"b8eb7e525ca91663": ¶site{2, 0xa2},
"5597ce4e2ae1868b": ¶site{2, 0xa3},
"c09607e6602b28bb": ¶site{2, 0xa4},
"2deab7fa1663b853": ¶site{2, 0xa5},
"28937bbe945d602b": ¶site{2, 0xa6},
"c5efcba2e215f0c3": ¶site{2, 0xa7},
"18367a470c17aa85": ¶site{2, 0xa8},
"f54aca5b7a5f3a6d": ¶site{2, 0xa9},
"f033061ff861e215": ¶site{2, 0xaa},
"1d4fb6038e2972fd": ¶site{2, 0xab},
"884e7fabc4e3dccd": ¶site{2, 0xac},
"6532cfb7b2ab4c25": ¶site{2, 0xad},
"604b03f33095945d": ¶site{2, 0xae},
"8d37b3ef46dd04b5": ¶site{2, 0xaf},
"26d0da04937b9607": ¶site{2, 0xb0},
"cbac6a18e53306ef": ¶site{2, 0xb1},
"ced5a65c670dde97": ¶site{2, 0xb2},
"23a9164011454e7f": ¶site{2, 0xb3},
"b6a8dfe85b8fe04f": ¶site{2, 0xb4},
"5bd46ff42dc770a7": ¶site{2, 0xb5},
"5eada3b0aff9a8df": ¶site{2, 0xb6},
"b3d113acd9b13837": ¶site{2, 0xb7},
"6e08a24937b36271": ¶site{2, 0xb8},
"8374125541fbf299": ¶site{2, 0xb9},
"860dde11c3c52ae1": ¶site{2, 0xba},
"6b716e0db58dba09": ¶site{2, 0xbb},
"fe70a7a5ff471439": ¶site{2, 0xbc},
"130c17b9890f84d1": ¶site{2, 0xbd},
"1675dbfd0b315ca9": ¶site{2, 0xbe},
"fb096be17d79cc41": ¶site{2, 0xbf},
"6c50bed0b61ec19f": ¶site{2, 0xc0},
"812c0eccc0565177": ¶site{2, 0xc1},
"8455c2884268890f": ¶site{2, 0xc2},
"69297294342019e7": ¶site{2, 0xc3},
"fc28bb3c7eeab7d7": ¶site{2, 0xc4},
"11540b2008a2273f": ¶site{2, 0xc5},
"142dc7648a9cff47": ¶site{2, 0xc6},
"f9517778fcd46faf": ¶site{2, 0xc7},
"2488c69d12d635e9": ¶site{2, 0xc8},
"c9f47681649ea501": ¶site{2, 0xc9},
"cc8dbac5e6a07d79": ¶site{2, 0xca},
"21f10ad990e8ed91": ¶site{2, 0xcb},
"b4f0c371da2243a1": ¶site{2, 0xcc},
"598c736dac6ad349": ¶site{2, 0xcd},
"5cf5bf292e540b31": ¶site{2, 0xce},
"b1890f35581c9bd9": ¶site{2, 0xcf},
"1a6e66de8dba096b": ¶site{2, 0xd0},
"f712d6c2fbf29983": ¶site{2, 0xd1},
"f26b1a8679cc41fb": ¶site{2, 0xd2},
"1f17aa9a0f84d113": ¶site{2, 0xd3},
"8a166332454e7f23": ¶site{2, 0xd4},
"676ad32e3306efcb": ¶site{2, 0xd5},
"62131f6ab13837b3": ¶site{2, 0xd6},
"8f6faf76c770a75b": ¶site{2, 0xd7},
"52b61e932972fd1d": ¶site{2, 0xd8},
"bfcaae8f5f3a6df5": ¶site{2, 0xd9},
"bab362cbdd04b58d": ¶site{2, 0xda},
"57cfd2d7ab4c2565": ¶site{2, 0xdb},
"c2ce1b7fe1868b55": ¶site{2, 0xdc},
"2fb2ab6397ce1bbd": ¶site{2, 0xdd},
"2acb672715f0c3c5": ¶site{2, 0xde},
"c7b7d73b63b8532d": ¶site{2, 0xdf},
"98d280fc4c256557": ¶site{2, 0xe0},
"75ae30e03a6df5bf": ¶site{2, 0xe1},
"70d7fca4b8532dc7": ¶site{2, 0xe2},
"9dab4cb8ce1bbd2f": ¶site{2, 0xe3},
"08aa851084d1131f": ¶site{2, 0xe4},
"e5d6350cf29983f7": ¶site{2, 0xe5},
"e0aff94870a75b8f": ¶site{2, 0xe6},
"0dd3495406efcb67": ¶site{2, 0xe7},
"d00af8b1e8ed9121": ¶site{2, 0xe8},
"3d7648ad9ea501c9": ¶site{2, 0xe9},
"380f84e91c9bd9b1": ¶site{2, 0xea},
"d57334f56ad34959": ¶site{2, 0xeb},
"4072fd5d2019e769": ¶site{2, 0xec},
"ad0e4d4156517781": ¶site{2, 0xed},
"a8778105d46faff9": ¶site{2, 0xee},
"450b3119a2273f11": ¶site{2, 0xef},
"eeec58f27781ada3": ¶site{2, 0xf0},
"0390e8ee01c93d4b": ¶site{2, 0xf1},
"06e924aa83f7e533": ¶site{2, 0xf2},
"eb9594b6f5bf75db": ¶site{2, 0xf3},
"7e945d1ebf75dbeb": ¶site{2, 0xf4},
"93e8ed02c93d4b03": ¶site{2, 0xf5},
"969121464b03937b": ¶site{2, 0xf6},
"7bed915a3d4b0393": ¶site{2, 0xf7},
"a63420bfd34959d5": ¶site{2, 0xf8},
"4b4890a3a501c93d": ¶site{2, 0xf9},
"4e315ce7273f1145": ¶site{2, 0xfa},
"a34decfb517781ad": ¶site{2, 0xfb},
"364c25531bbd2f9d": ¶site{2, 0xfc},
"db30954f6df5bf75": ¶site{2, 0xfd},
"de49590befcb670d": ¶site{2, 0xfe},
"3335e9179983f7e5": ¶site{2, 0xff},
"0b0e34462ed85478": ¶site{3, 0x01},
"78730e4c3e2ed854": ¶site{3, 0x02},
"737d3a0a10f68c2c": ¶site{3, 0x03},
"542c735a183e2ed8": ¶site{3, 0x04},
"5f22471c36e67aa0": ¶site{3, 0x05},
"2c5f7d162610f68c": ¶site{3, 0x06},
"2751495008c8a2f4": ¶site{3, 0x07},
"d88c2cab82183e2e": ¶site{3, 0x08},
"d38218edacc06a56": ¶site{3, 0x09},
"a0ff22e7bc36e67a": ¶site{3, 0x0a},
"abf116a192eeb202": ¶site{3, 0x0b},
"8ca05ff19a2610f6": ¶site{3, 0x0c},
"87ae6bb7b4fe448e": ¶site{3, 0x0d},
"f4d351bda408c8a2": ¶site{3, 0x0e},
"ffdd65fb8ad09cda": ¶site{3, 0x0f},
"2ef68c028582183e": ¶site{3, 0x10},
"25f8b844ab5a4c46": ¶site{3, 0x11},
"5685824ebbacc06a": ¶site{3, 0x12},
"5d8bb60895749412": ¶site{3, 0x13},
"7adaff589dbc36e6": ¶site{3, 0x14},
"71d4cb1eb364629e": ¶site{3, 0x15},
"02a9f114a392eeb2": ¶site{3, 0x16},
"09a7c5528d4abaca": ¶site{3, 0x17},
"f67aa0a9079a2610": ¶site{3, 0x18},
"fd7494ef29427268": ¶site{3, 0x19},
"8e09aee539b4fe44": ¶site{3, 0x1a},
"85079aa3176caa3c": ¶site{3, 0x1b},
"a256d3f31fa408c8": ¶site{3, 0x1c},
"a958e7b5317c5cb0": ¶site{3, 0x1d},
"da25ddbf218ad09c": ¶site{3, 0x1e},
"d12be9f90f5284e4": ¶site{3, 0x1f},
"3e10f6b23c858218": ¶site{3, 0x20},
"351ec2f4125dd660": ¶site{3, 0x21},
"4663f8fe02ab5a4c": ¶site{3, 0x22},
"4d6dccb82c730e34": ¶site{3, 0x23},
"6a3c85e824bbacc0": ¶site{3, 0x24},
"6132b1ae0a63f8b8": ¶site{3, 0x25},
"124f8ba41a957494": ¶site{3, 0x26},
"1941bfe2344d20ec": ¶site{3, 0x27},
"e69cda19be9dbc36": ¶site{3, 0x28},
"ed92ee5f9045e84e": ¶site{3, 0x29},
"9eefd45580b36462": ¶site{3, 0x2a},
"95e1e013ae6b301a": ¶site{3, 0x2b},
"b2b0a943a6a392ee": ¶site{3, 0x2c},
"b9be9d05887bc696": ¶site{3, 0x2d},
"cac3a70f988d4aba": ¶site{3, 0x2e},
"c1cd9349b6551ec2": ¶site{3, 0x2f},
"10e67ab0b9079a26": ¶site{3, 0x30},
"1be84ef697dfce5e": ¶site{3, 0x31},
"689574fc87294272": ¶site{3, 0x32},
"639b40baa9f1160a": ¶site{3, 0x33},
"44ca09eaa139b4fe": ¶site{3, 0x34},
"4fc43dac8fe1e086": ¶site{3, 0x35},
"3cb907a69f176caa": ¶site{3, 0x36},
"37b733e0b1cf38d2": ¶site{3, 0x37},
"c86a561b3b1fa408": ¶site{3, 0x38},
"c364625d15c7f070": ¶site{3, 0x39},
"b019585705317c5c": ¶site{3, 0x3a},
"bb176c112be92824": ¶site{3, 0x3b},
"9c46254123218ad0": ¶site{3, 0x3c},
"974811070df9dea8": ¶site{3, 0x3d},
"e4352b0d1d0f5284": ¶site{3, 0x3e},
"ef3b1f4b33d706fc": ¶site{3, 0x3f},
"182610eeaa3c8582": ¶site{3, 0x40},
"132824a884e4d1fa": ¶site{3, 0x41},
"60551ea294125dd6": ¶site{3, 0x42},
"6b5b2ae4baca09ae": ¶site{3, 0x43},
"4c0a63b4b202ab5a": ¶site{3, 0x44},
"470457f29cdaff22": ¶site{3, 0x45},
"34796df88c2c730e": ¶site{3, 0x46},
"3f7759bea2f42776": ¶site{3, 0x47},
"c0aa3c452824bbac": ¶site{3, 0x48},
"cba4080306fcefd4": ¶site{3, 0x49},
"b8d93209160a63f8": ¶site{3, 0x4a},
"b3d7064f38d23780": ¶site{3, 0x4b},
"94864f1f301a9574": ¶site{3, 0x4c},
"9f887b591ec2c10c": ¶site{3, 0x4d},
"ecf541530e344d20": ¶site{3, 0x4e},
"e7fb751520ec1958": ¶site{3, 0x4f},
"36d09cec2fbe9dbc": ¶site{3, 0x50},
"3ddea8aa0166c9c4": ¶site{3, 0x51},
"4ea392a0119045e8": ¶site{3, 0x52},
"45ada6e63f481190": ¶site{3, 0x53},
"62fcefb63780b364": ¶site{3, 0x54},
"69f2dbf01958e71c": ¶site{3, 0x55},
"1a8fe1fa09ae6b30": ¶site{3, 0x56},
"1181d5bc27763f48": ¶site{3, 0x57},
"ee5cb047ada6a392": ¶site{3, 0x58},
"e5528401837ef7ea": ¶site{3, 0x59},
"962fbe0b93887bc6": ¶site{3, 0x5a},
"9d218a4dbd502fbe": ¶site{3, 0x5b},
"ba70c31db5988d4a": ¶site{3, 0x5c},
"b17ef75b9b40d932": ¶site{3, 0x5d},
"c203cd518bb6551e": ¶site{3, 0x5e},
"c90df917a56e0166": ¶site{3, 0x5f},
"2636e65c96b9079a": ¶site{3, 0x60},
"2d38d21ab86153e2": ¶site{3, 0x61},
"5e45e810a897dfce": ¶site{3, 0x62},
"554bdc56864f8bb6": ¶site{3, 0x63},
"721a95068e872942": ¶site{3, 0x64},
"7914a140a05f7d3a": ¶site{3, 0x65},
"0a699b4ab0a9f116": ¶site{3, 0x66},
"0167af0c9e71a56e": ¶site{3, 0x67},
"febacaf714a139b4": ¶site{3, 0x68},
"f5b4feb13a796dcc": ¶site{3, 0x69},
"86c9c4bb2a8fe1e0": ¶site{3, 0x6a},
"8dc7f0fd0457b598": ¶site{3, 0x6b},
"aa96b9ad0c9f176c": ¶site{3, 0x6c},
"a1988deb22474314": ¶site{3, 0x6d},
"d2e5b7e132b1cf38": ¶site{3, 0x6e},
"d9eb83a71c699b40": ¶site{3, 0x6f},
"08c06a5e133b1fa4": ¶site{3, 0x70},
"03ce5e183de34bdc": ¶site{3, 0x71},
"70b364122d15c7f0": ¶site{3, 0x72},
"7bbd505403cd9388": ¶site{3, 0x73},
"5cec19040b05317c": ¶site{3, 0x74},
"57e22d4225dd6504": ¶site{3, 0x75},
"249f1748352be928": ¶site{3, 0x76},
"2f91230e1bf3bd50": ¶site{3, 0x77},
"d04c46f59123218a": ¶site{3, 0x78},
"db4272b3bffb75f2": ¶site{3, 0x79},
"a83f48b9af0df9de": ¶site{3, 0x7a},
"a3317cff81d5ada6": ¶site{3, 0x7b},
"846035af891d0f52": ¶site{3, 0x7c},
"8f6e01e9a7c55b2a": ¶site{3, 0x7d},
"fc133be3b733d706": ¶site{3, 0x7e},
"f71d0fa599eb837e": ¶site{3, 0x7f},
"829a26926caa3c85": ¶site{3, 0x80},
"899412d4427268fd": ¶site{3, 0x81},
"fae928de5284e4d1": ¶site{3, 0x82},
"f1e71c987c5cb0a9": ¶site{3, 0x83},
"d6b655c87494125d": ¶site{3, 0x84},
"ddb8618e5a4c4625": ¶site{3, 0x85},
"aec55b844abaca09": ¶site{3, 0x86},
"a5cb6fc264629e71": ¶site{3, 0x87},
"5a160a39eeb202ab": ¶site{3, 0x88},
"51183e7fc06a56d3": ¶site{3, 0x89},
"22650475d09cdaff": ¶site{3, 0x8a},
"296b3033fe448e87": ¶site{3, 0x8b},
"0e3a7963f68c2c73": ¶site{3, 0x8c},
"05344d25d854780b": ¶site{3, 0x8d},
"7649772fc8a2f427": ¶site{3, 0x8e},
"7d474369e67aa05f": ¶site{3, 0x8f},
"ac6caa90e92824bb": ¶site{3, 0x90},
"a7629ed6c7f070c3": ¶site{3, 0x91},
"d41fa4dcd706fcef": ¶site{3, 0x92},
"df11909af9dea897": ¶site{3, 0x93},
"f840d9caf1160a63": ¶site{3, 0x94},
"f34eed8cdfce5e1b": ¶site{3, 0x95},
"8033d786cf38d237": ¶site{3, 0x96},
"8b3de3c0e1e0864f": ¶site{3, 0x97},
"74e0863b6b301a95": ¶site{3, 0x98},
"7feeb27d45e84eed": ¶site{3, 0x99},
"0c938877551ec2c1": ¶site{3, 0x9a},
"079dbc317bc696b9": ¶site{3, 0x9b},
"20ccf561730e344d": ¶site{3, 0x9c},
"2bc2c1275dd66035": ¶site{3, 0x9d},
"58bffb2d4d20ec19": ¶site{3, 0x9e},
"53b1cf6b63f8b861": ¶site{3, 0x9f},
"bc8ad020502fbe9d": ¶site{3, 0xa0},
"b784e4667ef7eae5": ¶site{3, 0xa1},
"c4f9de6c6e0166c9": ¶site{3, 0xa2},
"cff7ea2a40d932b1": ¶site{3, 0xa3},
"e8a6a37a48119045": ¶site{3, 0xa4},
"e3a8973c66c9c43d": ¶site{3, 0xa5},
"90d5ad36763f4811": ¶site{3, 0xa6},
"9bdb997058e71c69": ¶site{3, 0xa7},
"6406fc8bd23780b3": ¶site{3, 0xa8},
"6f08c8cdfcefd4cb": ¶site{3, 0xa9},
"1c75f2c7ec1958e7": ¶site{3, 0xaa},
"177bc681c2c10c9f": ¶site{3, 0xab},
"302a8fd1ca09ae6b": ¶site{3, 0xac},
"3b24bb97e4d1fa13": ¶site{3, 0xad},
"4859819df427763f": ¶site{3, 0xae},
"4357b5dbdaff2247": ¶site{3, 0xaf},
"927c5c22d5ada6a3": ¶site{3, 0xb0},
"99726864fb75f2db": ¶site{3, 0xb1},
"ea0f526eeb837ef7": ¶site{3, 0xb2},
"e1016628c55b2a8f": ¶site{3, 0xb3},
"c6502f78cd93887b": ¶site{3, 0xb4},
"cd5e1b3ee34bdc03": ¶site{3, 0xb5},
"be232134f3bd502f": ¶site{3, 0xb6},
"b52d1572dd650457": ¶site{3, 0xb7},
"4af0708957b5988d": ¶site{3, 0xb8},
"41fe44cf796dccf5": ¶site{3, 0xb9},
"32837ec5699b40d9": ¶site{3, 0xba},
"398d4a83474314a1": ¶site{3, 0xbb},
"1edc03d34f8bb655": ¶site{3, 0xbc},
"15d237956153e22d": ¶site{3, 0xbd},
"66af0d9f71a56e01": ¶site{3, 0xbe},
"6da139d95f7d3a79": ¶site{3, 0xbf},
"9abc367cc696b907": ¶site{3, 0xc0},
"91b2023ae84eed7f": ¶site{3, 0xc1},
"e2cf3830f8b86153": ¶site{3, 0xc2},
"e9c10c76d660352b": ¶site{3, 0xc3},
"ce904526dea897df": ¶site{3, 0xc4},
"c59e7160f070c3a7": ¶site{3, 0xc5},
"b6e34b6ae0864f8b": ¶site{3, 0xc6},
"bded7f2cce5e1bf3": ¶site{3, 0xc7},
"42301ad7448e8729": ¶site{3, 0xc8},
"493e2e916a56d351": ¶site{3, 0xc9},
"3a43149b7aa05f7d": ¶site{3, 0xca},
"314d20dd54780b05": ¶site{3, 0xcb},
"161c698d5cb0a9f1": ¶site{3, 0xcc},
"1d125dcb7268fd89": ¶site{3, 0xcd},
"6e6f67c1629e71a5": ¶site{3, 0xce},
"656153874c4625dd": ¶site{3, 0xcf},
"b44aba7e4314a139": ¶site{3, 0xd0},
"bf448e386dccf541": ¶site{3, 0xd1},
"cc39b4327d3a796d": ¶site{3, 0xd2},
"c737807453e22d15": ¶site{3, 0xd3},
"e066c9245b2a8fe1": ¶site{3, 0xd4},
"eb68fd6275f2db99": ¶site{3, 0xd5},
"9815c768650457b5": ¶site{3, 0xd6},
"931bf32e4bdc03cd": ¶site{3, 0xd7},
"6cc696d5c10c9f17": ¶site{3, 0xd8},
"67c8a293efd4cb6f": ¶site{3, 0xd9},
"14b59899ff224743": ¶site{3, 0xda},
"1fbbacdfd1fa133b": ¶site{3, 0xdb},
"38eae58fd932b1cf": ¶site{3, 0xdc},
"33e4d1c9f7eae5b7": ¶site{3, 0xdd},
"4099ebc3e71c699b": ¶site{3, 0xde},
"4b97df85c9c43de3": ¶site{3, 0xdf},
"a4acc0cefa133b1f": ¶site{3, 0xe0},
"afa2f488d4cb6f67": ¶site{3, 0xe1},
"dcdfce82c43de34b": ¶site{3, 0xe2},
"d7d1fac4eae5b733": ¶site{3, 0xe3},
"f080b394e22d15c7": ¶site{3, 0xe4},
"fb8e87d2ccf541bf": ¶site{3, 0xe5},
"88f3bdd8dc03cd93": ¶site{3, 0xe6},
"83fd899ef2db99eb": ¶site{3, 0xe7},
"7c20ec65780b0531": ¶site{3, 0xe8},
"772ed82356d35149": ¶site{3, 0xe9},
"0453e2294625dd65": ¶site{3, 0xea},
"0f5dd66f68fd891d": ¶site{3, 0xeb},
"280c9f3f60352be9": ¶site{3, 0xec},
"2302ab794eed7f91": ¶site{3, 0xed},
"507f91735e1bf3bd": ¶site{3, 0xee},
"5b71a53570c3a7c5": ¶site{3, 0xef},
"8a5a4ccc7f912321": ¶site{3, 0xf0},
"8154788a51497759": ¶site{3, 0xf1},
"f229428041bffb75": ¶site{3, 0xf2},
"f92776c66f67af0d": ¶site{3, 0xf3},
"de763f9667af0df9": ¶site{3, 0xf4},
"d5780bd049775981": ¶site{3, 0xf5},
"a60531da5981d5ad": ¶site{3, 0xf6},
"ad0b059c775981d5": ¶site{3, 0xf7},
"52d66067fd891d0f": ¶site{3, 0xf8},
"59d85421d3514977": ¶site{3, 0xf9},
"2aa56e2bc3a7c55b": ¶site{3, 0xfa},
"21ab5a6ded7f9123": ¶site{3, 0xfb},
"06fa133de5b733d7": ¶site{3, 0xfc},
"0df4277bcb6f67af": ¶site{3, 0xfd},
"7e891d71db99eb83": ¶site{3, 0xfe},
"75872937f541bffb": ¶site{3, 0xff},
"7102d6da628c9e2c": ¶site{4, 0x01},
"2c5d02faf6628c9e": ¶site{4, 0x02},
"5d5fd42094ee12b2": ¶site{4, 0x03},
"9eb25d9c64f6628c": ¶site{4, 0x04},
"efb08b46067afca0": ¶site{4, 0x05},
"b2ef5f669294ee12": ¶site{4, 0x06},
"c3ed89bcf018703e": ¶site{4, 0x07},
"8c12b2d11064f662": ¶site{4, 0x08},
"fd10640b72e8684e": ¶site{4, 0x09},
"a04fb02be6067afc": ¶site{4, 0x0a},
"d14d66f1848ae4d0": ¶site{4, 0x0b},
"12a0ef4d749294ee": ¶site{4, 0x0c},
"63a23997161e0ac2": ¶site{4, 0x0d},
"3efdedb782f01870": ¶site{4, 0x0e},
"4fff3b6de07c865c": ¶site{4, 0x0f},
"62ee12d0b31064f6": ¶site{4, 0x10},
"13ecc40ad19cfada": ¶site{4, 0x11},
"4eb3102a4572e868": ¶site{4, 0x12},
"3fb1c6f027fe7644": ¶site{4, 0x13},
"fc5c4f4cd7e6067a": ¶site{4, 0x14},
"8d5e9996b56a9856": ¶site{4, 0x15},
"d0014db621848ae4": ¶site{4, 0x16},
"a1039b6c430814c8": ¶site{4, 0x17},
"eefca001a3749294": ¶site{4, 0x18},
"9ffe76dbc1f80cb8": ¶site{4, 0x19},
"c2a1a2fb55161e0a": ¶site{4, 0x1a},
"b3a37421379a8026": ¶site{4, 0x1b},
"704efd9dc782f018": ¶site{4, 0x1c},
"014c2b47a50e6e34": ¶site{4, 0x1d},
"5c13ff6731e07c86": ¶site{4, 0x1e},
"2d1129bd536ce2aa": ¶site{4, 0x1f},
"f694eee426b31064": ¶site{4, 0x20},
"8796383e443f8e48": ¶site{4, 0x21},
"dac9ec1ed0d19cfa": ¶site{4, 0x22},
"abcb3ac4b25d02d6": ¶site{4, 0x23},
"6826b378424572e8": ¶site{4, 0x24},
"192465a220c9ecc4": ¶site{4, 0x25},
"447bb182b427fe76": ¶site{4, 0x26},
"35796758d6ab605a": ¶site{4, 0x27},
"7a865c3536d7e606": ¶site{4, 0x28},
"0b848aef545b782a": ¶site{4, 0x29},
"56db5ecfc0b56a98": ¶site{4, 0x2a},
"27d98815a239f4b4": ¶site{4, 0x2b},
"e43401a95221848a": ¶site{4, 0x2c},
"9536d77330ad1aa6": ¶site{4, 0x2d},
"c8690353a4430814": ¶site{4, 0x2e},
"b96bd589c6cf9638": ¶site{4, 0x2f},
"947afc3495a37492": ¶site{4, 0x30},
"e5782aeef72feabe": ¶site{4, 0x31},
"b827fece63c1f80c": ¶site{4, 0x32},
"c9252814014d6620": ¶site{4, 0x33},
"0ac8a1a8f155161e": ¶site{4, 0x34},
"7bca777293d98832": ¶site{4, 0x35},
"2695a35207379a80": ¶site{4, 0x36},
"5797758865bb04ac": ¶site{4, 0x37},
"18684ee585c782f0": ¶site{4, 0x38},
"696a983fe74b1cdc": ¶site{4, 0x39},
"34354c1f73a50e6e": ¶site{4, 0x3a},
"45379ac511299042": ¶site{4, 0x3b},
"86da1379e131e07c": ¶site{4, 0x3c},
"f7d8c5a383bd7e50": ¶site{4, 0x3d},
"aa87118317536ce2": ¶site{4, 0x3e},
"db85c75975dff2ce": ¶site{4, 0x3f},
"6492948a8026b310": ¶site{4, 0x40},
"15904250e2aa2d3c": ¶site{4, 0x41},
"48cf967076443f8e": ¶site{4, 0x42},
"39cd40aa14c8a1a2": ¶site{4, 0x43},
"fa20c916e4d0d19c": ¶site{4, 0x44},
"8b221fcc865c4fb0": ¶site{4, 0x45},
"d67dcbec12b25d02": ¶site{4, 0x46},
"a77f1d36703ec32e": ¶site{4, 0x47},
"e880265b90424572": ¶site{4, 0x48},
"9982f081f2cedb5e": ¶site{4, 0x49},
"c4dd24a16620c9ec": ¶site{4, 0x4a},
"b5dff27b04ac57c0": ¶site{4, 0x4b},
"76327bc7f4b427fe": ¶site{4, 0x4c},
"0730ad1d9638b9d2": ¶site{4, 0x4d},
"5a6f793d02d6ab60": ¶site{4, 0x4e},
"2b6dafe7605a354c": ¶site{4, 0x4f},
"067c865a3336d7e6": ¶site{4, 0x50},
"777e508051ba49ca": ¶site{4, 0x51},
"2a2184a0c5545b78": ¶site{4, 0x52},
"5b23527aa7d8c554": ¶site{4, 0x53},
"98cedbc657c0b56a": ¶site{4, 0x54},
"e9cc0d1c354c2b46": ¶site{4, 0x55},
"b493d93ca1a239f4": ¶site{4, 0x56},
"c5910fe6c32ea7d8": ¶site{4, 0x57},
"8a6e348b23522184": ¶site{4, 0x58},
"fb6ce25141debfa8": ¶site{4, 0x59},
"a6333671d530ad1a": ¶site{4, 0x5a},
"d731e0abb7bc3336": ¶site{4, 0x5b},
"14dc691747a44308": ¶site{4, 0x5c},
"65debfcd2528dd24": ¶site{4, 0x5d},
"38816bedb1c6cf96": ¶site{4, 0x5e},
"4983bd37d34a51ba": ¶site{4, 0x5f},
"92067a6ea695a374": ¶site{4, 0x60},
"e304acb4c4193d58": ¶site{4, 0x61},
"be5b789450f72fea": ¶site{4, 0x62},
"cf59ae4e327bb1c6": ¶site{4, 0x63},
"0cb427f2c263c1f8": ¶site{4, 0x64},
"7db6f128a0ef5fd4": ¶site{4, 0x65},
"20e9250834014d66": ¶site{4, 0x66},
"51ebf3d2568dd34a": ¶site{4, 0x67},
"1e14c8bfb6f15516": ¶site{4, 0x68},
"6f161e65d47dcb3a": ¶site{4, 0x69},
"3249ca454093d988": ¶site{4, 0x6a},
"434b1c9f221f47a4": ¶site{4, 0x6b},
"80a69523d207379a": ¶site{4, 0x6c},
"f1a443f9b08ba9b6": ¶site{4, 0x6d},
"acfb97d92465bb04": ¶site{4, 0x6e},
"ddf9410346e92528": ¶site{4, 0x6f},
"f0e868be1585c782": ¶site{4, 0x70},
"81eabe64770959ae": ¶site{4, 0x71},
"dcb56a44e3e74b1c": ¶site{4, 0x72},
"adb7bc9e816bd530": ¶site{4, 0x73},
"6e5a35227173a50e": ¶site{4, 0x74},
"1f58e3f813ff3b22": ¶site{4, 0x75},
"420737d887112990": ¶site{4, 0x76},
"3305e102e59db7bc": ¶site{4, 0x77},
"7cfada6f05e131e0": ¶site{4, 0x78},
"0df80cb5676dafcc": ¶site{4, 0x79},
"50a7d895f383bd7e": ¶site{4, 0x7a},
"21a50e4f910f2352": ¶site{4, 0x7b},
"e24887f36117536c": ¶site{4, 0x7c},
"934a5129039bcd40": ¶site{4, 0x7d},
"ce1585099775dff2": ¶site{4, 0x7e},
"bf1753d3f5f941de": ¶site{4, 0x7f},
"107492849a8026b3": ¶site{4, 0x80},
"6176445ef80cb89f": ¶site{4, 0x81},
"3c29907e6ce2aa2d": ¶site{4, 0x82},
"4d2b46a40e6e3401": ¶site{4, 0x83},
"8ec6cf18fe76443f": ¶site{4, 0x84},
"ffc419c29cfada13": ¶site{4, 0x85},
"a29bcde20814c8a1": ¶site{4, 0x86},
"d3991b386a98568d": ¶site{4, 0x87},
"9c6620558ae4d0d1": ¶site{4, 0x88},
"ed64f68fe8684efd": ¶site{4, 0x89},
"b03b22af7c865c4f": ¶site{4, 0x8a},
"c139f4751e0ac263": ¶site{4, 0x8b},
"02d47dc9ee12b25d": ¶site{4, 0x8c},
"73d6ab138c9e2c71": ¶site{4, 0x8d},
"2e897f3318703ec3": ¶site{4, 0x8e},
"5f8ba9e97afca0ef": ¶site{4, 0x8f},
"729a805429904245": ¶site{4, 0x90},
"0398568e4b1cdc69": ¶site{4, 0x91},
"5ec782aedff2cedb": ¶site{4, 0x92},
"2fc55474bd7e50f7": ¶site{4, 0x93},
"ec28ddc84d6620c9": ¶site{4, 0x94},
"9d2a0b122feabee5": ¶site{4, 0x95},
"c075df32bb04ac57": ¶site{4, 0x96},
"b17709e8d988327b": ¶site{4, 0x97},
"fe88328539f4b427": ¶site{4, 0x98},
"8f8ae45f5b782a0b": ¶site{4, 0x99},
"d2d5307fcf9638b9": ¶site{4, 0x9a},
"a3d7e6a5ad1aa695": ¶site{4, 0x9b},
"603a6f195d02d6ab": ¶site{4, 0x9c},
"1138b9c33f8e4887": ¶site{4, 0x9d},
"4c676de3ab605a35": ¶site{4, 0x9e},
"3d65bb39c9ecc419": ¶site{4, 0x9f},
"e6e07c60bc3336d7": ¶site{4, 0xa0},
"97e2aabadebfa8fb": ¶site{4, 0xa1},
"cabd7e9a4a51ba49": ¶site{4, 0xa2},
"bbbfa84028dd2465": ¶site{4, 0xa3},
"785221fcd8c5545b": ¶site{4, 0xa4},
"0950f726ba49ca77": ¶site{4, 0xa5},
"540f23062ea7d8c5": ¶site{4, 0xa6},
"250df5dc4c2b46e9": ¶site{4, 0xa7},
"6af2ceb1ac57c0b5": ¶site{4, 0xa8},
"1bf0186bcedb5e99": ¶site{4, 0xa9},
"46afcc4b5a354c2b": ¶site{4, 0xaa},
"37ad1a9138b9d207": ¶site{4, 0xab},
"f440932dc8a1a239": ¶site{4, 0xac},
"854245f7aa2d3c15": ¶site{4, 0xad},
"d81d91d73ec32ea7": ¶site{4, 0xae},
"a91f470d5c4fb08b": ¶site{4, 0xaf},
"840e6eb00f235221": ¶site{4, 0xb0},
"f50cb86a6dafcc0d": ¶site{4, 0xb1},
"a8536c4af941debf": ¶site{4, 0xb2},
"d951ba909bcd4093": ¶site{4, 0xb3},
"1abc332c6bd530ad": ¶site{4, 0xb4},
"6bbee5f60959ae81": ¶site{4, 0xb5},
"36e131d69db7bc33": ¶site{4, 0xb6},
"47e3e70cff3b221f": ¶site{4, 0xb7},
"081cdc611f47a443": ¶site{4, 0xb8},
"791e0abb7dcb3a6f": ¶site{4, 0xb9},
"2441de9be92528dd": ¶site{4, 0xba},
"554308418ba9b6f1": ¶site{4, 0xbb},
"96ae81fd7bb1c6cf": ¶site{4, 0xbc},
"e7ac5727193d58e3": ¶site{4, 0xbd},
"baf383078dd34a51": ¶site{4, 0xbe},
"cbf155ddef5fd47d": ¶site{4, 0xbf},
"74e6060e1aa695a3": ¶site{4, 0xc0},
"05e4d0d4782a0b8f": ¶site{4, 0xc1},
"58bb04f4ecc4193d": ¶site{4, 0xc2},
"29b9d22e8e488711": ¶site{4, 0xc3},
"ea545b927e50f72f": ¶site{4, 0xc4},
"9b568d481cdc6903": ¶site{4, 0xc5},
"c609596888327bb1": ¶site{4, 0xc6},
"b70b8fb2eabee59d": ¶site{4, 0xc7},
"f8f4b4df0ac263c1": ¶site{4, 0xc8},
"89f66205684efded": ¶site{4, 0xc9},
"d4a9b625fca0ef5f": ¶site{4, 0xca},
"a5ab60ff9e2c7173": ¶site{4, 0xcb},
"6646e9436e34014d": ¶site{4, 0xcc},
"17443f990cb89f61": ¶site{4, 0xcd},
"4a1bebb998568dd3": ¶site{4, 0xce},
"3b193d63fada13ff": ¶site{4, 0xcf},
"160814dea9b6f155": ¶site{4, 0xd0},
"670ac204cb3a6f79": ¶site{4, 0xd1},
"3a5516245fd47dcb": ¶site{4, 0xd2},
"4b57c0fe3d58e3e7": ¶site{4, 0xd3},
"88ba4942cd4093d9": ¶site{4, 0xd4},
"f9b89f98afcc0df5": ¶site{4, 0xd5},
"a4e74bb83b221f47": ¶site{4, 0xd6},
"d5e59d6259ae816b": ¶site{4, 0xd7},
"9a1aa60fb9d20737": ¶site{4, 0xd8},
"eb1870d5db5e991b": ¶site{4, 0xd9},
"b647a4f54fb08ba9": ¶site{4, 0xda},
"c745722f2d3c1585": ¶site{4, 0xdb},
"04a8fb93dd2465bb": ¶site{4, 0xdc},
"75aa2d49bfa8fb97": ¶site{4, 0xdd},
"28f5f9692b46e925": ¶site{4, 0xde},
"59f72fb349ca7709": ¶site{4, 0xdf},
"8272e8ea3c1585c7": ¶site{4, 0xe0},
"f3703e305e991beb": ¶site{4, 0xe1},
"ae2fea10ca770959": ¶site{4, 0xe2},
"df2d3ccaa8fb9775": ¶site{4, 0xe3},
"1cc0b57658e3e74b": ¶site{4, 0xe4},
"6dc263ac3a6f7967": ¶site{4, 0xe5},
"309db78cae816bd5": ¶site{4, 0xe6},
"419f6156cc0df5f9": ¶site{4, 0xe7},
"0e605a3b2c7173a5": ¶site{4, 0xe8},
"7f628ce14efded89": ¶site{4, 0xe9},
"223d58c1da13ff3b": ¶site{4, 0xea},
"533f8e1bb89f6117": ¶site{4, 0xeb},
"90d207a748871129": ¶site{4, 0xec},
"e1d0d17d2a0b8f05": ¶site{4, 0xed},
"bc8f055dbee59db7": ¶site{4, 0xee},
"cd8dd387dc69039b": ¶site{4, 0xef},
"e09cfa3a8f05e131": ¶site{4, 0xf0},
"919e2ce0ed897f1d": ¶site{4, 0xf1},
"ccc1f8c079676daf": ¶site{4, 0xf2},
"bdc32e1a1bebf383": ¶site{4, 0xf3},
"7e2ea7a6ebf383bd": ¶site{4, 0xf4},
"0f2c717c897f1d91": ¶site{4, 0xf5},
"5273a55c1d910f23": ¶site{4, 0xf6},
"237173867f1d910f": ¶site{4, 0xf7},
"6c8e48eb9f611753": ¶site{4, 0xf8},
"1d8c9e31fded897f": ¶site{4, 0xf9},
"40d34a1169039bcd": ¶site{4, 0xfa},
"31d19ccb0b8f05e1": ¶site{4, 0xfb},
"f23c1577fb9775df": ¶site{4, 0xfc},
"833ec3ad991bebf3": ¶site{4, 0xfd},
"de61178d0df5f941": ¶site{4, 0xfe},
"af63c1576f79676d": ¶site{4, 0xff},
"8dd08e5c981256b2": ¶site{5, 0x01},
"b23fd03cee981256": ¶site{5, 0x02},
"3fef5e60768a44e4": ¶site{5, 0x03},
"56e43f866aee9812": ¶site{5, 0x04},
"db34b1daf2fccea0": ¶site{5, 0x05},
"e4dbefba84768a44": ¶site{5, 0x06},
"690b61e61c64dcf6": ¶site{5, 0x07},
"1244e42d946aee98": ¶site{5, 0x08},
"9f946a710c78b82a": ¶site{5, 0x09},
"a07b34117af2fcce": ¶site{5, 0x0a},
"2dabba4de2e0aa7c": ¶site{5, 0x0b},
"44a0dbabfe84768a": ¶site{5, 0x0c},
"c97055f766962038": ¶site{5, 0x0d},
"f69f0b97101c64dc": ¶site{5, 0x0e},
"7b4f85cb880e326e": ¶site{5, 0x0f},
"988a447cb5946aee": ¶site{5, 0x10},
"155aca202d863c5c": ¶site{5, 0x11},
"2ab594405b0c78b8": ¶site{5, 0x12},
"a7651a1cc31e2e0a": ¶site{5, 0x13},
"ce6e7bfadf7af2fc": ¶site{5, 0x14},
"43bef5a64768a44e": ¶site{5, 0x15},
"7c51abc631e2e0aa": ¶site{5, 0x16},
"f181259aa9f0b618": ¶site{5, 0x17},
"8acea05121fe8476": ¶site{5, 0x18},
"071e2e0db9ecd2c4": ¶site{5, 0x19},
"38f1706dcf669620": ¶site{5, 0x1a},
"b521fe315774c092": ¶site{5, 0x1b},
"dc2a9fd74b101c64": ¶site{5, 0x1c},
"51fa118bd3024ad6": ¶site{5, 0x1d},
"6e154feba5880e32": ¶site{5, 0x1e},
"e3c5c1b73d9a5880": ¶site{5, 0x1f},
"ee768aaa92b5946a": ¶site{5, 0x20},
"63a604f60aa7c2d8": ¶site{5, 0x21},
"5c495a967c2d863c": ¶site{5, 0x22},
"d199d4cae43fd08e": ¶site{5, 0x23},
"b892b52cf85b0c78": ¶site{5, 0x24},
"35423b7060495aca": ¶site{5, 0x25},
"0aad651016c31e2e": ¶site{5, 0x26},
"877deb4c8ed1489c": ¶site{5, 0x27},
"fc326e8706df7af2": ¶site{5, 0x28},
"71e2e0db9ecd2c40": ¶site{5, 0x29},
"4e0dbebbe84768a4": ¶site{5, 0x2a},
"c3dd30e770553e16": ¶site{5, 0x2b},
"aad651016c31e2e0": ¶site{5, 0x2c},
"2706df5df423b452": ¶site{5, 0x2d},
"18e9813d82a9f0b6": ¶site{5, 0x2e},
"95390f611abba604": ¶site{5, 0x2f},
"76fcced62721fe84": ¶site{5, 0x30},
"fb2c408abf33a836": ¶site{5, 0x31},
"c4c31eeac9b9ecd2": ¶site{5, 0x32},
"491390b651abba60": ¶site{5, 0x33},
"2018f1504dcf6696": ¶site{5, 0x34},
"adc87f0cd5dd3024": ¶site{5, 0x35},
"9227216ca35774c0": ¶site{5, 0x36},
"1ff7af303b452272": ¶site{5, 0x37},
"64b82afbb34b101c": ¶site{5, 0x38},
"e968a4a72b5946ae": ¶site{5, 0x39},
"d687fac75dd3024a": ¶site{5, 0x3a},
"5b57749bc5c154f8": ¶site{5, 0x3b},
"325c157dd9a5880e": ¶site{5, 0x3c},
"bf8c9b2141b7debc": ¶site{5, 0x3d},
"8063c541373d9a58": ¶site{5, 0x3e},
"0db34b1daf2fccea": ¶site{5, 0x3f},
"6a8476e0c092b594": ¶site{5, 0x40},
"e754f8bc5880e326": ¶site{5, 0x41},
"d8bba6dc2e0aa7c2": ¶site{5, 0x42},
"556b2880b618f170": ¶site{5, 0x43},
"3c604966aa7c2d86": ¶site{5, 0x44},
"b1b0c73a326e7b34": ¶site{5, 0x45},
"8e5f995a44e43fd0": ¶site{5, 0x46},
"038f1706dcf66962": ¶site{5, 0x47},
"78c092cd54f85b0c": ¶site{5, 0x48},
"f5101c91ccea0dbe": ¶site{5, 0x49},
"caff42f1ba60495a": ¶site{5, 0x4a},
"472fccad22721fe8": ¶site{5, 0x4b},
"2e24ad4b3e16c31e": ¶site{5, 0x4c},
"a3f42317a60495ac": ¶site{5, 0x4d},
"9c1b7d77d08ed148": ¶site{5, 0x4e},
"11cbf32b489c87fa": ¶site{5, 0x4f},
"f20e329c7506df7a": ¶site{5, 0x50},
"7fdebcc0ed1489c8": ¶site{5, 0x51},
"4031e2a09b9ecd2c": ¶site{5, 0x52},
"cde16cfc038c9b9e": ¶site{5, 0x53},
"a4ea0d1a1fe84768": ¶site{5, 0x54},
"293a834687fa11da": ¶site{5, 0x55},
"16d5dd26f170553e": ¶site{5, 0x56},
"9b05537a6962038c": ¶site{5, 0x57},
"e04ad6b1e16c31e2": ¶site{5, 0x58},
"6d9a58ed797e6750": ¶site{5, 0x59},
"5275068d0ff423b4": ¶site{5, 0x5a},
"dfa588d197e67506": ¶site{5, 0x5b},
"b6aee9378b82a9f0": ¶site{5, 0x5c},
"3b7e676b1390ff42": ¶site{5, 0x5d},
"0491390b651abba6": ¶site{5, 0x5e},
"8941b757fd08ed14": ¶site{5, 0x5f},
"84f2fc4a522721fe": ¶site{5, 0x60},
"09227216ca35774c": ¶site{5, 0x61},
"36cd2c76bcbf33a8": ¶site{5, 0x62},
"bb1da22a24ad651a": ¶site{5, 0x63},
"d216c3cc38c9b9ec": ¶site{5, 0x64},
"5fc64d90a0dbef5e": ¶site{5, 0x65},
"602913f0d651abba": ¶site{5, 0x66},
"edf99dac4e43fd08": ¶site{5, 0x67},
"96b61867c64dcf66": ¶site{5, 0x68},
"1b66963b5e5f99d4": ¶site{5, 0x69},
"2489c85b28d5dd30": ¶site{5, 0x6a},
"a9594607b0c78b82": ¶site{5, 0x6b},
"c05227e1aca35774": ¶site{5, 0x6c},
"4d82a9bd34b101c6": ¶site{5, 0x6d},
"726df7dd423b4522": ¶site{5, 0x6e},
"ffbd7981da291390": ¶site{5, 0x6f},
"1c78b836e7b34b10": ¶site{5, 0x70},
"91a8366a7fa11da2": ¶site{5, 0x71},
"ae47680a092b5946": ¶site{5, 0x72},
"2397e65691390ff4": ¶site{5, 0x73},
"4a9c87b08d5dd302": ¶site{5, 0x74},
"c74c09ec154f85b0": ¶site{5, 0x75},
"f8a3578c63c5c154": ¶site{5, 0x76},
"7573d9d0fbd797e6": ¶site{5, 0x77},
"0e3c5c1b73d9a588": ¶site{5, 0x78},
"83ecd247ebcbf33a": ¶site{5, 0x79},
"bc038c279d41b7de": ¶site{5, 0x7a},
"31d3027b0553e16c": ¶site{5, 0x7b},
"58d8639d19373d9a": ¶site{5, 0x7c},
"d508edc181256b28": ¶site{5, 0x7d},
"eae7b3a1f7af2fcc": ¶site{5, 0x7e},
"67373dfd6fbd797e": ¶site{5, 0x7f},
"94fe84e274c092b5": ¶site{5, 0x80},
"192e0abeecd2c407": ¶site{5, 0x81},
"26c154de9a5880e3": ¶site{5, 0x82},
"ab11da82024ad651": ¶site{5, 0x83},
"c21abb641e2e0aa7": ¶site{5, 0x84},
"4fca3538863c5c15": ¶site{5, 0x85},
"70256b58f0b618f1": ¶site{5, 0x86},
"fdf5e50468a44e43": ¶site{5, 0x87},
"86ba60cfe0aa7c2d": ¶site{5, 0x88},
"0b6aee9378b82a9f": ¶site{5, 0x89},
"3485b0f30e326e7b": ¶site{5, 0x8a},
"b9553eaf962038c9": ¶site{5, 0x8b},
"d05e5f498a44e43f": ¶site{5, 0x8c},
"5d8ed1151256b28d": ¶site{5, 0x8d},
"62618f7564dcf669": ¶site{5, 0x8e},
"efb10129fccea0db": ¶site{5, 0x8f},
"0c74c09ec154f85b": ¶site{5, 0x90},
"81a44ec25946aee9": ¶site{5, 0x91},
"be4b10a22fccea0d": ¶site{5, 0x92},
"339b9efeb7debcbf": ¶site{5, 0x93},
"5a90ff18abba6049": ¶site{5, 0x94},
"d740714433a836fb": ¶site{5, 0x95},
"e8af2f244522721f": ¶site{5, 0x96},
"657fa178dd3024ad": ¶site{5, 0x97},
"1e3024b3553e16c3": ¶site{5, 0x98},
"93e0aaefcd2c4071": ¶site{5, 0x99},
"ac0ff48fbba60495": ¶site{5, 0x9a},
"21df7ad323b45227": ¶site{5, 0x9b},
"48d41b353fd08ed1": ¶site{5, 0x9c},
"c5049569a7c2d863": ¶site{5, 0x9d},
"faebcb09d1489c87": ¶site{5, 0x9e},
"773b4555495aca35": ¶site{5, 0x9f},
"7a880e48e67506df": ¶site{5, 0xa0},
"f75880147e67506d": ¶site{5, 0xa1},
"c8b7de7408ed1489": ¶site{5, 0xa2},
"4567502890ff423b": ¶site{5, 0xa3},
"2c6c31ce8c9b9ecd": ¶site{5, 0xa4},
"a1bcbf921489c87f": ¶site{5, 0xa5},
"9e53e1f262038c9b": ¶site{5, 0xa6},
"13836faefa11da29": ¶site{5, 0xa7},
"68ccea65721fe847": ¶site{5, 0xa8},
"e51c6439ea0dbef5": ¶site{5, 0xa9},
"daf33a599c87fa11": ¶site{5, 0xaa},
"5723b4050495aca3": ¶site{5, 0xab},
"3e28d5e318f17055": ¶site{5, 0xac},
"b3f85bbf80e326e7": ¶site{5, 0xad},
"8c1705dff6696203": ¶site{5, 0xae},
"01c78b836e7b34b1": ¶site{5, 0xaf},
"e2024a3453e16c31": ¶site{5, 0xb0},
"6fd2c468cbf33a83": ¶site{5, 0xb1},
"503d9a08bd797e67": ¶site{5, 0xb2},
"dded1454256b28d5": ¶site{5, 0xb3},
"b4e675b2390ff423": ¶site{5, 0xb4},
"3936fbeea11da291": ¶site{5, 0xb5},
"06d9a58ed797e675": ¶site{5, 0xb6},
"8b092bd24f85b0c7": ¶site{5, 0xb7},
"f046ae19c78b82a9": ¶site{5, 0xb8},
"7d9620455f99d41b": ¶site{5, 0xb9},
"42797e25291390ff": ¶site{5, 0xba},
"cfa9f079b101c64d": ¶site{5, 0xbb},
"a6a2919fad651abb": ¶site{5, 0xbc},
"2b721fc335774c09": ¶site{5, 0xbd},
"149d41a343fd08ed": ¶site{5, 0xbe},
"994dcfffdbef5e5f": ¶site{5, 0xbf},
"fe7af202b4522721": ¶site{5, 0xc0},
"73aa7c5e2c407193": ¶site{5, 0xc1},
"4c45223e5aca3577": ¶site{5, 0xc2},
"c195ac62c2d863c5": ¶site{5, 0xc3},
"a89ecd84debcbf33": ¶site{5, 0xc4},
"254e43d846aee981": ¶site{5, 0xc5},
"1aa11db83024ad65": ¶site{5, 0xc6},
"977193e4a836fbd7": ¶site{5, 0xc7},
"ec3e162f2038c9b9": ¶site{5, 0xc8},
"61ee9873b82a9f0b": ¶site{5, 0xc9},
"5e01c613cea0dbef": ¶site{5, 0xca},
"d3d1484f56b28d5d": ¶site{5, 0xcb},
"bada29a94ad651ab": ¶site{5, 0xcc},
"370aa7f5d2c40719": ¶site{5, 0xcd},
"08e5f995a44e43fd": ¶site{5, 0xce},
"853577c93c5c154f": ¶site{5, 0xcf},
"66f0b67e01c64dcf": ¶site{5, 0xd0},
"eb20382299d41b7d": ¶site{5, 0xd1},
"d4cf6642ef5e5f99": ¶site{5, 0xd2},
"591fe81e774c092b": ¶site{5, 0xd3},
"301489f86b28d5dd": ¶site{5, 0xd4},
"bdc407a4f33a836f": ¶site{5, 0xd5},
"822b59c485b0c78b": ¶site{5, 0xd6},
"0ffbd7981da29139": ¶site{5, 0xd7},
"74b4525395aca357": ¶site{5, 0xd8},
"f964dc0f0dbef5e5": ¶site{5, 0xd9},
"c68b826f7b34b101": ¶site{5, 0xda},
"4b5b0c33e326e7b3": ¶site{5, 0xdb},
"22506dd5ff423b45": ¶site{5, 0xdc},
"af80e38967506df7": ¶site{5, 0xdd},
"906fbde911da2913": ¶site{5, 0xde},
"1dbf33b589c87fa1": ¶site{5, 0xdf},
"100c78a826e7b34b": ¶site{5, 0xe0},
"9ddcf6f4bef5e5f9": ¶site{5, 0xe1},
"a233a894c87fa11d": ¶site{5, 0xe2},
"2fe326c8506df7af": ¶site{5, 0xe3},
"46e8472e4c092b59": ¶site{5, 0xe4},
"cb38c972d41b7deb": ¶site{5, 0xe5},
"f4d79712a291390f": ¶site{5, 0xe6},
"7907194e3a836fbd": ¶site{5, 0xe7},
"02489c85b28d5dd3": ¶site{5, 0xe8},
"8f9812d92a9f0b61": ¶site{5, 0xe9},
"b0774cb95c154f85": ¶site{5, 0xea},
"3da7c2e5c4071937": ¶site{5, 0xeb},
"54aca303d863c5c1": ¶site{5, 0xec},
"d97c2d5f40719373": ¶site{5, 0xed},
"e693733f36fbd797": ¶site{5, 0xee},
"6b43fd63aee98125": ¶site{5, 0xef},
"88863cd49373d9a5": ¶site{5, 0xf0},
"0556b2880b618f17": ¶site{5, 0xf1},
"3ab9ece87debcbf3": ¶site{5, 0xf2},
"b76962b4e5f99d41": ¶site{5, 0xf3},
"de620352f99d41b7": ¶site{5, 0xf4},
"53b28d0e618f1705": ¶site{5, 0xf5},
"6c5dd36e170553e1": ¶site{5, 0xf6},
"e18d5d328f170553": ¶site{5, 0xf7},
"9ac2d8f90719373d": ¶site{5, 0xf8},
"171256a59f0b618f": ¶site{5, 0xf9},
"28fd08c5e981256b": ¶site{5, 0xfa},
"a52d8699719373d9": ¶site{5, 0xfb},
"cc26e77f6df7af2f": ¶site{5, 0xfc},
"41f66923f5e5f99d": ¶site{5, 0xfd},
"7e193743836fbd79": ¶site{5, 0xfe},
"f3c9b91f1b7debcb": ¶site{5, 0xff},
"437cc26ea4444ee4": ¶site{6, 0x01},
"e4a77c268aa4444e": ¶site{6, 0x02},
"a7dbbe482ee00aaa": ¶site{6, 0x03},
"4eaaa732688aa444": ¶site{6, 0x04},
"0dd6655cccceeaa0": ¶site{6, 0x05},
"aa0ddb14e22ee00a": ¶site{6, 0x06},
"e971197a466aaeee": ¶site{6, 0x07},
"440aaae376688aa4": ¶site{6, 0x08},
"0776688dd22cc440": ¶site{6, 0x09},
"a0add6c5fcccceea": ¶site{6, 0x0a},
"e3d114ab5888800e": ¶site{6, 0x0b},
"0aa00dd11ee22ee0": ¶site{6, 0x0c},
"49dccfbfbaa66004": ¶site{6, 0x0d},
"ee0771f794466aae": ¶site{6, 0x0e},
"ad7bb3993002244a": ¶site{6, 0x0f},
"a4e00a0e4776688a": ¶site{6, 0x10},
"e79cc860e332266e": ¶site{6, 0x11},
"40477628cdd22cc4": ¶site{6, 0x12},
"033bb44669966220": ¶site{6, 0x13},
"ea4aad3c2ffcccce": ¶site{6, 0x14},
"a9366f528bb8822a": ¶site{6, 0x15},
"0eedd11aa5588880": ¶site{6, 0x16},
"4d911374011cc664": ¶site{6, 0x17},
"e0eaa0ed311ee22e": ¶site{6, 0x18},
"a3966283955aacca": ¶site{6, 0x19},
"044ddccbbbbaa660": ¶site{6, 0x1a},
"47311ea51ffee884": ¶site{6, 0x1b},
"ae4007df5994466a": ¶site{6, 0x1c},
"ed3cc5b1fdd0088e": ¶site{6, 0x1d},
"4ae77bf9d3300224": ¶site{6, 0x1e},
"099bb99777744cc0": ¶site{6, 0x1f},
"8a2ee08084477668": ¶site{6, 0x20},
"c95222ee2003388c": ¶site{6, 0x21},
"6e899ca60ee33226": ¶site{6, 0x22},
"2df55ec8aaa77cc2": ¶site{6, 0x23},
"c48447b2eccdd22c": ¶site{6, 0x24},
"87f885dc48899cc8": ¶site{6, 0x25},
"20233b9466699662": ¶site{6, 0x26},
"635ff9fac22dd886": ¶site{6, 0x27},
"ce244a63f22ffccc": ¶site{6, 0x28},
"8d58880d566bb228": ¶site{6, 0x29},
"2a833645788bb882": ¶site{6, 0x2a},
"69fff42bdccff666": ¶site{6, 0x2b},
"808eed519aa55888": ¶site{6, 0x2c},
"c3f22f3f3ee1166c": ¶site{6, 0x2d},
"6429917710011cc6": ¶site{6, 0x2e},
"27555319b4455222": ¶site{6, 0x2f},
"2eceea8ec3311ee2": ¶site{6, 0x30},
"6db228e067755006": ¶site{6, 0x31},
"ca6996a849955aac": ¶site{6, 0x32},
"891554c6edd11448": ¶site{6, 0x33},
"60644dbcabbbbaa6": ¶site{6, 0x34},
"23188fd20ffff442": ¶site{6, 0x35},
"84c3319a211ffee8": ¶site{6, 0x36},
"c7bff3f4855bb00c": ¶site{6, 0x37},
"6ac4406db5599446": ¶site{6, 0x38},
"29b88203111ddaa2": ¶site{6, 0x39},
"8e633c4b3ffdd008": ¶site{6, 0x3a},
"cd1ffe259bb99eec": ¶site{6, 0x3b},
"246ee75fddd33002": ¶site{6, 0x3c},
"6712253179977ee6": ¶site{6, 0x3d},
"c0c99b795777744c": ¶site{6, 0x3e},
"83b55917f3333aa8": ¶site{6, 0x3f},
"68e22e88e8844776": ¶site{6, 0x40},
"2b9eece64cc00992": ¶site{6, 0x41},
"8c4552ae62200338": ¶site{6, 0x42},
"cf3990c0c6644ddc": ¶site{6, 0x43},
"264889ba800ee332": ¶site{6, 0x44},
"65344bd4244aadd6": ¶site{6, 0x45},
"c2eff59c0aaaa77c": ¶site{6, 0x46},
"819337f2aeeee998": ¶site{6, 0x47},
"2ce8846b9eeccdd2": ¶site{6, 0x48},
"6f9446053aa88336": ¶site{6, 0x49},
"c84ff84d1448899c": ¶site{6, 0x4a},
"8b333a23b00cc778": ¶site{6, 0x4b},
"62422359f6666996": ¶site{6, 0x4c},
"213ee13752222772": ¶site{6, 0x4d},
"86e55f7f7cc22dd8": ¶site{6, 0x4e},
"c5999d11d886633c": ¶site{6, 0x4f},
"cc022486aff22ffc": ¶site{6, 0x50},
"8f7ee6e80bb66118": ¶site{6, 0x51},
"28a558a025566bb2": ¶site{6, 0x52},
"6bd99ace81122556": ¶site{6, 0x53},
"82a883b4c7788bb8": ¶site{6, 0x54},
"c1d441da633cc55c": ¶site{6, 0x55},
"660fff924ddccff6": ¶site{6, 0x56},
"25733dfce9988112": ¶site{6, 0x57},
"88088e65d99aa558": ¶site{6, 0x58},
"cb744c0b7ddeebbc": ¶site{6, 0x59},
"6caff243533ee116": ¶site{6, 0x5a},
"2fd3302df77aaff2": ¶site{6, 0x5b},
"c6a22957b110011c": ¶site{6, 0x5c},
"85deeb3915544ff8": ¶site{6, 0x5d},
"220555713bb44552": ¶site{6, 0x5e},
"6179971f9ff00bb6": ¶site{6, 0x5f},
"e2ccce086cc3311e": ¶site{6, 0x60},
"a1b00c66c8877ffa": ¶site{6, 0x61},
"066bb22ee6677550": ¶site{6, 0x62},
"4517704042233bb4": ¶site{6, 0x63},
"ac66693a0449955a": ¶site{6, 0x64},
"ef1aab54a00ddbbe": ¶site{6, 0x65},
"48c1151c8eedd114": ¶site{6, 0x66},
"0bbdd7722aa99ff0": ¶site{6, 0x67},
"a6c664eb1aabbbba": ¶site{6, 0x68},
"e5baa685beeff55e": ¶site{6, 0x69},
"426118cd900ffff4": ¶site{6, 0x6a},
"011ddaa3344bb110": ¶site{6, 0x6b},
"e86cc3d972211ffe": ¶site{6, 0x6c},
"ab1001b7d665511a": ¶site{6, 0x6d},
"0ccbbffff8855bb0": ¶site{6, 0x6e},
"4fb77d915cc11554": ¶site{6, 0x6f},
"462cc4062bb55994": ¶site{6, 0x70},
"055006688ff11770": ¶site{6, 0x71},
"a28bb820a1111dda": ¶site{6, 0x72},
"e1f77a4e0555533e": ¶site{6, 0x73},
"08866334433ffdd0": ¶site{6, 0x74},
"4bfaa15ae77bb334": ¶site{6, 0x75},
"ec211f12c99bb99e": ¶site{6, 0x76},
"af5ddd7c6ddff77a": ¶site{6, 0x77},
"02266ee55dddd330": ¶site{6, 0x78},
"415aac8bf9999dd4": ¶site{6, 0x79},
"e68112c3d779977e": ¶site{6, 0x7a},
"a5fdd0ad733dd99a": ¶site{6, 0x7b},
"4c8cc9d735577774": ¶site{6, 0x7c},
"0ff00bb991133990": ¶site{6, 0x7d},
"a82bb5f1bff3333a": ¶site{6, 0x7e},
"eb57779f1bb77dde": ¶site{6, 0x7f},
"761ee258fee88447": ¶site{6, 0x80},
"356220365aaccaa3": ¶site{6, 0x81},
"92b99e7e744cc009": ¶site{6, 0x82},
"d1c55c10d0088eed": ¶site{6, 0x83},
"38b4456a96622003": ¶site{6, 0x84},
"7bc8870432266ee7": ¶site{6, 0x85},
"dc13394c1cc6644d": ¶site{6, 0x86},
"9f6ffb22b8822aa9": ¶site{6, 0x87},
"321448bb88800ee3": ¶site{6, 0x88},
"71688ad52cc44007": ¶site{6, 0x89},
"d6b3349d02244aad": ¶site{6, 0x8a},
"95cff6f3a6600449": ¶site{6, 0x8b},
"7cbeef89e00aaaa7": ¶site{6, 0x8c},
"3fc22de7444ee443": ¶site{6, 0x8d},
"981993af6aaeeee9": ¶site{6, 0x8e},
"db6551c1ceeaa00d": ¶site{6, 0x8f},
"d2fee856b99eeccd": ¶site{6, 0x90},
"91822a381ddaa229": ¶site{6, 0x91},
"36599470333aa883": ¶site{6, 0x92},
"7525561e977ee667": ¶site{6, 0x93},
"9c544f64d1144889": ¶site{6, 0x94},
"df288d0a7550066d": ¶site{6, 0x95},
"78f333425bb00cc7": ¶site{6, 0x96},
"3b8ff12cfff44223": ¶site{6, 0x97},
"96f442b5cff66669": ¶site{6, 0x98},
"d58880db6bb2288d": ¶site{6, 0x99},
"72533e9345522227": ¶site{6, 0x9a},
"312ffcfde1166cc3": ¶site{6, 0x9b},
"d85ee587a77cc22d": ¶site{6, 0x9c},
"9b2227e903388cc9": ¶site{6, 0x9d},
"3cf999a12dd88663": ¶site{6, 0x9e},
"7f855bcf899cc887": ¶site{6, 0x9f},
"fc3002d87aaff22f": ¶site{6, 0xa0},
"bf4cc0b6deebbccb": ¶site{6, 0xa1},
"18977efef00bb661": ¶site{6, 0xa2},
"5bebbc90544ff885": ¶site{6, 0xa3},
"b29aa5ea1225566b": ¶site{6, 0xa4},
"f1e66784b661188f": ¶site{6, 0xa5},
"563dd9cc98811225": ¶site{6, 0xa6},
"15411ba23cc55cc1": ¶site{6, 0xa7},
"b83aa83b0cc7788b": ¶site{6, 0xa8},
"fb466a55a883366f": ¶site{6, 0xa9},
"5c9dd41d86633cc5": ¶site{6, 0xaa},
"1fe1167322277221": ¶site{6, 0xab},
"f6900f09644ddccf": ¶site{6, 0xac},
"b5eccd67c009922b": ¶site{6, 0xad},
"1237732feee99881": ¶site{6, 0xae},
"514bb1414aadd665": ¶site{6, 0xaf},
"58d008d63dd99aa5": ¶site{6, 0xb0},
"1baccab8999dd441": ¶site{6, 0xb1},
"bc7774f0b77ddeeb": ¶site{6, 0xb2},
"ff0bb69e1339900f": ¶site{6, 0xb3},
"167aafe455533ee1": ¶site{6, 0xb4},
"55066d8af1177005": ¶site{6, 0xb5},
"f2ddd3c2dff77aaf": ¶site{6, 0xb6},
"b1a111ac7bb3344b": ¶site{6, 0xb7},
"1cdaa2354bb11001": ¶site{6, 0xb8},
"5fa6605beff55ee5": ¶site{6, 0xb9},
"f87dde13c115544f": ¶site{6, 0xba},
"bb011c7d65511aab": ¶site{6, 0xbb},
"52700507233bb445": ¶site{6, 0xbc},
"110cc769877ffaa1": ¶site{6, 0xbd},
"b6d77921a99ff00b": ¶site{6, 0xbe},
"f5abbb4f0ddbbeef": ¶site{6, 0xbf},
"1efcccd0166cc331": ¶site{6, 0xc0},
"5d800ebeb2288dd5": ¶site{6, 0xc1},
"fa5bb0f69cc8877f": ¶site{6, 0xc2},
"b9277298388cc99b": ¶site{6, 0xc3},
"50566be27ee66775": ¶site{6, 0xc4},
"132aa98cdaa22991": ¶site{6, 0xc5},
"b4f117c4f442233b": ¶site{6, 0xc6},
"f78dd5aa50066ddf": ¶site{6, 0xc7},
"5af6663360044995": ¶site{6, 0xc8},
"198aa45dc4400771": ¶site{6, 0xc9},
"be511a15eaa00ddb": ¶site{6, 0xca},
"fd2dd87b4ee4433f": ¶site{6, 0xcb},
"145cc101088eedd1": ¶site{6, 0xcc},
"5720036faccaa335": ¶site{6, 0xcd},
"f0fbbd27822aa99f": ¶site{6, 0xce},
"b3877f49266ee77b": ¶site{6, 0xcf},
"ba1cc6de511aabbb": ¶site{6, 0xd0},
"f96004b0f55ee55f": ¶site{6, 0xd1},
"5ebbbaf8dbbeeff5": ¶site{6, 0xd2},
"1dc778967ffaa111": ¶site{6, 0xd3},
"f4b661ec39900fff": ¶site{6, 0xd4},
"b7caa3829dd4411b": ¶site{6, 0xd5},
"10111dcab3344bb1": ¶site{6, 0xd6},
"536ddfa417700555": ¶site{6, 0xd7},
"fe166c3d2772211f": ¶site{6, 0xd8},
"bd6aae5383366ffb": ¶site{6, 0xd9},
"1ab1101badd66551": ¶site{6, 0xda},
"59cdd27509922bb5": ¶site{6, 0xdb},
"b0bccb0f4ff8855b": ¶site{6, 0xdc},
"f3c00961ebbccbbf": ¶site{6, 0xdd},
"541bb729c55cc115": ¶site{6, 0xde},
"1767754761188ff1": ¶site{6, 0xdf},
"94d22c50922bb559": ¶site{6, 0xe0},
"d7aeee3e366ffbbd": ¶site{6, 0xe1},
"70755076188ff117": ¶site{6, 0xe2},
"33099218bccbbff3": ¶site{6, 0xe3},
"da788b62faa1111d": ¶site{6, 0xe4},
"9904490c5ee55ff9": ¶site{6, 0xe5},
"3edff74470055553": ¶site{6, 0xe6},
"7da3352ad4411bb7": ¶site{6, 0xe7},
"d0d886b3e4433ffd": ¶site{6, 0xe8},
"93a444dd40077119": ¶site{6, 0xe9},
"347ffa956ee77bb3": ¶site{6, 0xea},
"770338fbcaa33557": ¶site{6, 0xeb},
"9e7221818cc99bb9": ¶site{6, 0xec},
"dd0ee3ef288dd55d": ¶site{6, 0xed},
"7ad55da7066ddff7": ¶site{6, 0xee},
"39a99fc9a2299113": ¶site{6, 0xef},
"3032265ed55dddd3": ¶site{6, 0xf0},
"734ee43071199337": ¶site{6, 0xf1},
"d4955a785ff9999d": ¶site{6, 0xf2},
"97e99816fbbdd779": ¶site{6, 0xf3},
"7e98816cbdd77997": ¶site{6, 0xf4},
"3de4430219933773": ¶site{6, 0xf5},
"9a3ffd4a37733dd9": ¶site{6, 0xf6},
"d9433f249337733d": ¶site{6, 0xf7},
"74388cbda3355777": ¶site{6, 0xf8},
"37444ed307711993": ¶site{6, 0xf9},
"909ff09b29911339": ¶site{6, 0xfa},
"d3e332f58dd55ddd": ¶site{6, 0xfb},
"3a922b8fcbbff333": ¶site{6, 0xfc},
"79eee9e16ffbbdd7": ¶site{6, 0xfd},
"de3557a9411bb77d": ¶site{6, 0xfe},
"9d4995c7e55ff999": ¶site{6, 0xff},
"a90e384a820a2aaa": ¶site{7, 0x01},
"aa030e92e0820a2a": ¶site{7, 0x02},
"030d36d862882080": ¶site{7, 0x03},
"2a800324b8e0820a": ¶site{7, 0x04},
"838e3b6e3aeaa8a0": ¶site{7, 0x05},
"80830db658628820": ¶site{7, 0x06},
"298d35fcda68a28a": ¶site{7, 0x07},
"0a2080092eb8e082": ¶site{7, 0x08},
"a32eb843acb2ca28": ¶site{7, 0x09},
"a0238e9bce3aeaa8": ¶site{7, 0x0a},
"092db6d14c30c002": ¶site{7, 0x0b},
"20a0832d96586288": ¶site{7, 0x0c},
"89aebb6714524822": ¶site{7, 0x0d},
"8aa38dbf76da68a2": ¶site{7, 0x0e},
"23adb5f5f4d04208": ¶site{7, 0x0f},
"828820028b2eb8e0": ¶site{7, 0x10},
"2b8618480924924a": ¶site{7, 0x11},
"288b2e906bacb2ca": ¶site{7, 0x12},
"818516dae9a69860": ¶site{7, 0x13},
"a808232633ce3aea": ¶site{7, 0x14},
"01061b6cb1c41040": ¶site{7, 0x15},
"020b2db4d34c30c0": ¶site{7, 0x16},
"ab0515fe51461a6a": ¶site{7, 0x17},
"88a8a00ba5965862": ¶site{7, 0x18},
"21a69841279c72c8": ¶site{7, 0x19},
"22abae9945145248": ¶site{7, 0x1a},
"8ba596d3c71e78e2": ¶site{7, 0x1b},
"a228a32f1d76da68": ¶site{7, 0x1c},
"0b269b659f7cf0c2": ¶site{7, 0x1d},
"082badbdfdf4d042": ¶site{7, 0x1e},
"a12595f77ffefae8": ¶site{7, 0x1f},
"e06288c0e28b2eb8": ¶site{7, 0x20},
"496cb08a60810412": ¶site{7, 0x21},
"4a61865202092492": ¶site{7, 0x22},
"e36fbe1880030e38": ¶site{7, 0x23},
"cae28be45a6bacb2": ¶site{7, 0x24},
"63ecb3aed8618618": ¶site{7, 0x25},
"60e18576bae9a698": ¶site{7, 0x26},
"c9efbd3c38e38c32": ¶site{7, 0x27},
"ea4208c9cc33ce3a": ¶site{7, 0x28},
"434c30834e39e490": ¶site{7, 0x29},
"4041065b2cb1c410": ¶site{7, 0x2a},
"e94f3e11aebbeeba": ¶site{7, 0x2b},
"c0c20bed74d34c30": ¶site{7, 0x2c},
"69cc33a7f6d9669a": ¶site{7, 0x2d},
"6ac1057f9451461a": ¶site{7, 0x2e},
"c3cf3d35165b6cb0": ¶site{7, 0x2f},
"62eaa8c269a59658": ¶site{7, 0x30},
"cbe49088ebafbcf2": ¶site{7, 0x31},
"c8e9a65089279c72": ¶site{7, 0x32},
"61e79e1a0b2db6d8": ¶site{7, 0x33},
"486aabe6d1451452": ¶site{7, 0x34},
"e16493ac534f3ef8": ¶site{7, 0x35},
"e269a57431c71e78": ¶site{7, 0x36},
"4b679d3eb3cd34d2": ¶site{7, 0x37},
"68ca28cb471d76da": ¶site{7, 0x38},
"c1c41081c5175c70": ¶site{7, 0x39},
"c2c92659a79f7cf0": ¶site{7, 0x3a},
"6bc71e132595565a": ¶site{7, 0x3b},
"424a2beffffdf4d0": ¶site{7, 0x3c},
"eb4413a57df7de7a": ¶site{7, 0x3d},
"e849257d1f7ffefa": ¶site{7, 0x3e},
"41471d379d75d450": ¶site{7, 0x3f},
"b858623078e28b2e": ¶site{7, 0x40},
"11565a7afae8a184": ¶site{7, 0x41},
"125b6ca298608104": ¶site{7, 0x42},
"bb5554e81a6aabae": ¶site{7, 0x43},
"92d86114c0020924": ¶site{7, 0x44},
"3bd6595e4208238e": ¶site{7, 0x45},
"38db6f862080030e": ¶site{7, 0x46},
"91d557cca28a29a4": ¶site{7, 0x47},
"b278e239565a6bac": ¶site{7, 0x48},
"1b76da73d4504106": ¶site{7, 0x49},
"187becabb6d86186": ¶site{7, 0x4a},
"b175d4e134d24b2c": ¶site{7, 0x4b},
"98f8e11deebae9a6": ¶site{7, 0x4c},
"31f6d9576cb0c30c": ¶site{7, 0x4d},
"32fbef8f0e38e38c": ¶site{7, 0x4e},
"9bf5d7c58c32c926": ¶site{7, 0x4f},
"3ad04232f3cc33ce": ¶site{7, 0x50},
"93de7a7871c61964": ¶site{7, 0x51},
"90d34ca0134e39e4": ¶site{7, 0x52},
"39dd74ea9144134e": ¶site{7, 0x53},
"105041164b2cb1c4": ¶site{7, 0x54},
"b95e795cc9269b6e": ¶site{7, 0x55},
"ba534f84abaebbee": ¶site{7, 0x56},
"135d77ce29a49144": ¶site{7, 0x57},
"30f0c23bdd74d34c": ¶site{7, 0x58},
"99fefa715f7ef9e6": ¶site{7, 0x59},
"9af3cca93df6d966": ¶site{7, 0x5a},
"33fdf4e3bffcf3cc": ¶site{7, 0x5b},
"1a70c11f65945146": ¶site{7, 0x5c},
"b37ef955e79e7bec": ¶site{7, 0x5d},
"b073cf8d85165b6c": ¶site{7, 0x5e},
"197df7c7071c71c6": ¶site{7, 0x5f},
"583aeaf09a69a596": ¶site{7, 0x60},
"f134d2ba18638f3c": ¶site{7, 0x61},
"f239e4627aebafbc": ¶site{7, 0x62},
"5b37dc28f8e18516": ¶site{7, 0x63},
"72bae9d42289279c": ¶site{7, 0x64},
"dbb4d19ea0830d36": ¶site{7, 0x65},
"d8b9e746c20b2db6": ¶site{7, 0x66},
"71b7df0c4001071c": ¶site{7, 0x67},
"521a6af9b4d14514": ¶site{7, 0x68},
"fb1452b336db6fbe": ¶site{7, 0x69},
"f819646b54534f3e": ¶site{7, 0x6a},
"51175c21d6596594": ¶site{7, 0x6b},
"789a69dd0c31c71e": ¶site{7, 0x6c},
"d19451978e3bedb4": ¶site{7, 0x6d},
"d299674fecb3cd34": ¶site{7, 0x6e},
"7b975f056eb9e79e": ¶site{7, 0x6f},
"dab2caf211471d76": ¶site{7, 0x70},
"73bcf2b8934d37dc": ¶site{7, 0x71},
"70b1c460f1c5175c": ¶site{7, 0x72},
"d9bffc2a73cf3df6": ¶site{7, 0x73},
"f032c9d6a9a79f7c": ¶site{7, 0x74},
"593cf19c2badb5d6": ¶site{7, 0x75},
"5a31c74449259556": ¶site{7, 0x76},
"f33fff0ecb2fbffc": ¶site{7, 0x77},
"d0924afb3ffffdf4": ¶site{7, 0x78},
"799c72b1bdf5d75e": ¶site{7, 0x79},
"7a914469df7df7de": ¶site{7, 0x7a},
"d39f7c235d77dd74": ¶site{7, 0x7b},
"fa1249df871f7ffe": ¶site{7, 0x7c},
"531c719505155554": ¶site{7, 0x7d},
"5011474d679d75d4": ¶site{7, 0x7e},
"f91f7f07e5975f7e": ¶site{7, 0x7f},
"2e96584c1e78e28b": ¶site{7, 0x80},
"879860069c72c821": ¶site{7, 0x81},
"849556defefae8a1": ¶site{7, 0x82},
"2d9b6e947cf0c20b": ¶site{7, 0x83},
"04165b68a6986081": ¶site{7, 0x84},
"ad18632224924a2b": ¶site{7, 0x85},
"ae1555fa461a6aab": ¶site{7, 0x86},
"071b6db0c4104001": ¶site{7, 0x87},
"24b6d84530c00209": ¶site{7, 0x88},
"8db8e00fb2ca28a3": ¶site{7, 0x89},
"8eb5d6d7d0420823": ¶site{7, 0x8a},
"27bbee9d52482289": ¶site{7, 0x8b},
"0e36db6188208003": ¶site{7, 0x8c},
"a738e32b0a2aaaa9": ¶site{7, 0x8d},
"a435d5f368a28a29": ¶site{7, 0x8e},
"0d3bedb9eaa8a083": ¶site{7, 0x8f},
"ac1e784e95565a6b": ¶site{7, 0x90},
"05104004175c70c1": ¶site{7, 0x91},
"061d76dc75d45041": ¶site{7, 0x92},
"af134e96f7de7aeb": ¶site{7, 0x93},
"869e7b6a2db6d861": ¶site{7, 0x94},
"2f904320afbcf2cb": ¶site{7, 0x95},
"2c9d75f8cd34d24b": ¶site{7, 0x96},
"85934db24f3ef8e1": ¶site{7, 0x97},
"a63ef847bbeebae9": ¶site{7, 0x98},
"0f30c00d39e49043": ¶site{7, 0x99},
"0c3df6d55b6cb0c3": ¶site{7, 0x9a},
"a533ce9fd9669a69": ¶site{7, 0x9b},
"8cbefb63030e38e3": ¶site{7, 0x9c},
"25b0c32981041249": ¶site{7, 0x9d},
"26bdf5f1e38c32c9": ¶site{7, 0x9e},
"8fb3cdbb61861863": ¶site{7, 0x9f},
"cef4d08cfcf3cc33": ¶site{7, 0xa0},
"67fae8c67ef9e699": ¶site{7, 0xa1},
"64f7de1e1c71c619": ¶site{7, 0xa2},
"cdf9e6549e7becb3": ¶site{7, 0xa3},
"e474d3a844134e39": ¶site{7, 0xa4},
"4d7aebe2c6196493": ¶site{7, 0xa5},
"4e77dd3aa4914413": ¶site{7, 0xa6},
"e779e570269b6eb9": ¶site{7, 0xa7},
"c4d45085d24b2cb1": ¶site{7, 0xa8},
"6dda68cf5041061b": ¶site{7, 0xa9},
"6ed75e1732c9269b": ¶site{7, 0xaa},
"c7d9665db0c30c31": ¶site{7, 0xab},
"ee5453a16aabaebb": ¶site{7, 0xac},
"475a6bebe8a18411": ¶site{7, 0xad},
"44575d338a29a491": ¶site{7, 0xae},
"ed59657908238e3b": ¶site{7, 0xaf},
"4c7cf08e77dd74d3": ¶site{7, 0xb0},
"e572c8c4f5d75e79": ¶site{7, 0xb1},
"e67ffe1c975f7ef9": ¶site{7, 0xb2},
"4f71c65615555453": ¶site{7, 0xb3},
"66fcf3aacf3df6d9": ¶site{7, 0xb4},
"cff2cbe04d37dc73": ¶site{7, 0xb5},
"ccfffd382fbffcf3": ¶site{7, 0xb6},
"65f1c572adb5d659": ¶site{7, 0xb7},
"465c708759659451": ¶site{7, 0xb8},
"ef5248cddb6fbefb": ¶site{7, 0xb9},
"ec5f7e15b9e79e7b": ¶site{7, 0xba},
"4551465f3bedb4d1": ¶site{7, 0xbb},
"6cdc73a3e185165b": ¶site{7, 0xbc},
"c5d24be9638f3cf1": ¶site{7, 0xbd},
"c6df7d3101071c71": ¶site{7, 0xbe},
"6fd1457b830d36db": ¶site{7, 0xbf},
"96ce3a7c669a69a5": ¶site{7, 0xc0},
"3fc00236e490430f": ¶site{7, 0xc1},
"3ccd34ee8618638f": ¶site{7, 0xc2},
"95c30ca404124925": ¶site{7, 0xc3},
"bc4e3958de7aebaf": ¶site{7, 0xc4},
"154001125c70c105": ¶site{7, 0xc5},
"164d37ca3ef8e185": ¶site{7, 0xc6},
"bf430f80bcf2cb2f": ¶site{7, 0xc7},
"9ceeba7548228927": ¶site{7, 0xc8},
"35e0823fca28a38d": ¶site{7, 0xc9},
"36edb4e7a8a0830d": ¶site{7, 0xca},
"9fe38cad2aaaa9a7": ¶site{7, 0xcb},
"b66eb951f0c20b2d": ¶site{7, 0xcc},
"1f60811b72c82187": ¶site{7, 0xcd},
"1c6db7c310400107": ¶site{7, 0xce},
"b5638f89924a2bad": ¶site{7, 0xcf},
"14461a7eedb4d145": ¶site{7, 0xd0},
"bd4822346fbefbef": ¶site{7, 0xd1},
"be4514ec0d36db6f": ¶site{7, 0xd2},
"174b2ca68f3cf1c5": ¶site{7, 0xd3},
"3ec6195a5554534f": ¶site{7, 0xd4},
"97c82110d75e79e5": ¶site{7, 0xd5},
"94c517c8b5d65965": ¶site{7, 0xd6},
"3dcb2f8237dc73cf": ¶site{7, 0xd7},
"1e669a77c30c31c7": ¶site{7, 0xd8},
"b768a23d41061b6d": ¶site{7, 0xd9},
"b46594e5238e3bed": ¶site{7, 0xda},
"1d6bacafa1841147": ¶site{7, 0xdb},
"34e699537becb3cd": ¶site{7, 0xdc},
"9de8a119f9e69967": ¶site{7, 0xdd},
"9ee597c19b6eb9e7": ¶site{7, 0xde},
"37ebaf8b1964934d": ¶site{7, 0xdf},
"76acb2bc8411471d": ¶site{7, 0xe0},
"dfa28af6061b6db7": ¶site{7, 0xe1},
"dcafbc2e64934d37": ¶site{7, 0xe2},
"75a18464e699679d": ¶site{7, 0xe3},
"5c2cb1983cf1c517": ¶site{7, 0xe4},
"f52289d2befbefbd": ¶site{7, 0xe5},
"f62fbf0adc73cf3d": ¶site{7, 0xe6},
"5f2187405e79e597": ¶site{7, 0xe7},
"7c8c32b5aaa9a79f": ¶site{7, 0xe8},
"d5820aff28a38d35": ¶site{7, 0xe9},
"d68f3c274a2badb5": ¶site{7, 0xea},
"7f81046dc821871f": ¶site{7, 0xeb},
"560c319112492595": ¶site{7, 0xec},
"ff0209db90430f3f": ¶site{7, 0xed},
"fc0f3f03f2cb2fbf": ¶site{7, 0xee},
"5501074970c10515": ¶site{7, 0xef},
"f42492be0f3ffffd": ¶site{7, 0xf0},
"5d2aaaf48d35d557": ¶site{7, 0xf1},
"5e279c2cefbdf5d7": ¶site{7, 0xf2},
"f729a4666db7df7d": ¶site{7, 0xf3},
"dea4919ab7df7df7": ¶site{7, 0xf4},
"77aaa9d035d5575d": ¶site{7, 0xf5},
"74a79f08575d77dd": ¶site{7, 0xf6},
"dda9a742d5575d77": ¶site{7, 0xf7},
"fe0412b721871f7f": ¶site{7, 0xf8},
"570a2afda38d35d5": ¶site{7, 0xf9},
"54071c25c1051555": ¶site{7, 0xfa},
"fd09246f430f3fff": ¶site{7, 0xfb},
"d484119399679d75": ¶site{7, 0xfc},
"7d8a29d91b6db7df": ¶site{7, 0xfd},
"7e871f0179e5975f": ¶site{7, 0xfe},
"d789274bfbefbdf5": ¶site{7, 0xff},
} | cryptanalysis/toy/parasite.go | 0.709221 | 0.412057 | parasite.go | starcoder |
package docs
import (
"errors"
"fmt"
"strconv"
"gopkg.in/yaml.v3"
)
func getFieldFromMapping(name string, createMissing bool, node *yaml.Node) (*yaml.Node, error) {
node.Kind = yaml.MappingNode
var foundNode *yaml.Node
for i := 0; i < len(node.Content)-1; i += 2 {
if node.Content[i].Value == name {
foundNode = node.Content[i+1]
break
}
}
if foundNode == nil {
if !createMissing {
return nil, fmt.Errorf("%v: key not found in mapping", name)
}
var keyNode yaml.Node
if err := keyNode.Encode(name); err != nil {
return nil, fmt.Errorf("%v: failed to encode key: %w", name, err)
}
node.Content = append(node.Content, &keyNode)
foundNode = &yaml.Node{}
node.Content = append(node.Content, foundNode)
}
return foundNode, nil
}
func getIndexFromSequence(name string, allowAppend bool, node *yaml.Node) (*yaml.Node, error) {
node.Kind = yaml.SequenceNode
var foundNode *yaml.Node
if name != "-" {
index, err := strconv.Atoi(name)
if err != nil {
return nil, fmt.Errorf("%v: failed to parse path segment as array index: %w", name, err)
}
if len(node.Content) <= index {
return nil, fmt.Errorf("%v: target index greater than array length", name)
}
foundNode = node.Content[index]
} else {
if !allowAppend {
return nil, fmt.Errorf("%v: append directive not allowed", name)
}
foundNode = &yaml.Node{}
node.Content = append(node.Content, foundNode)
}
return foundNode, nil
}
// SetYAMLPath sets the value of a node within a YAML document identified by a
// path to a value.
func (f FieldSpecs) SetYAMLPath(docsProvider Provider, root, value *yaml.Node, path ...string) error {
root = unwrapDocumentNode(root)
value = unwrapDocumentNode(value)
var foundSpec FieldSpec
for _, spec := range f {
if spec.Name == path[0] {
foundSpec = spec
break
}
}
if foundSpec.Name == "" {
return fmt.Errorf("%v: field not recognised", path[0])
}
foundNode, err := getFieldFromMapping(path[0], true, root)
if err != nil {
return err
}
if err := foundSpec.SetYAMLPath(docsProvider, foundNode, value, path[1:]...); err != nil {
return fmt.Errorf("%v.%w", path[0], err)
}
return nil
}
func setYAMLPathCore(docsProvider Provider, coreType Type, root, value *yaml.Node, path ...string) error {
if docsProvider == nil {
docsProvider = globalProvider
}
foundNode, err := getFieldFromMapping(path[0], true, root)
if err != nil {
return err
}
if f, exists := reservedFieldsByType(coreType)[path[0]]; exists {
if err = f.SetYAMLPath(docsProvider, foundNode, value, path[1:]...); err != nil {
return fmt.Errorf("%v.%w", path[0], err)
}
return nil
}
cSpec, exists := GetDocs(docsProvider, path[0], coreType)
if !exists {
return fmt.Errorf("%v: field not recognised", path[0])
}
if err = cSpec.Config.SetYAMLPath(docsProvider, foundNode, value, path[1:]...); err != nil {
return fmt.Errorf("%v.%w", path[0], err)
}
return nil
}
// SetYAMLPath sets the value of a node within a YAML document identified by a
// path to a value.
func (f FieldSpec) SetYAMLPath(docsProvider Provider, root, value *yaml.Node, path ...string) error {
root = unwrapDocumentNode(root)
value = unwrapDocumentNode(value)
switch f.Kind {
case Kind2DArray:
if len(path) == 0 {
if value.Kind == yaml.SequenceNode {
*root = *value
} else {
root.Kind = yaml.SequenceNode
root.Content = []*yaml.Node{{
Kind: yaml.SequenceNode,
Content: []*yaml.Node{value},
}}
}
return nil
}
target, err := getIndexFromSequence(path[0], true, root)
if err != nil {
return err
}
if err = f.Array().SetYAMLPath(docsProvider, target, value, path[1:]...); err != nil {
return fmt.Errorf("%v.%w", path[0], err)
}
return nil
case KindArray:
if len(path) == 0 {
if value.Kind == yaml.SequenceNode {
*root = *value
} else {
root.Kind = yaml.SequenceNode
root.Content = []*yaml.Node{value}
}
return nil
}
target, err := getIndexFromSequence(path[0], true, root)
if err != nil {
return err
}
if err = f.Scalar().SetYAMLPath(docsProvider, target, value, path[1:]...); err != nil {
return fmt.Errorf("%v.%w", path[0], err)
}
return nil
case KindMap:
if len(path) == 0 {
return errors.New("cannot set map directly")
}
target, err := getFieldFromMapping(path[0], true, root)
if err != nil {
return err
}
if err = f.Scalar().SetYAMLPath(docsProvider, target, value, path[1:]...); err != nil {
return fmt.Errorf("%v.%w", path[0], err)
}
return nil
}
if len(path) == 0 {
*root = *value
return nil
}
if coreType, isCore := f.Type.IsCoreComponent(); isCore {
if len(path) == 0 {
return fmt.Errorf("(%v): cannot set core type directly", coreType)
}
return setYAMLPathCore(docsProvider, coreType, root, value, path...)
}
if len(f.Children) > 0 {
return f.Children.SetYAMLPath(docsProvider, root, value, path...)
}
return fmt.Errorf("%v: field not recognised", path[0])
}
// GetYAMLPath attempts to obtain a specific value within a YAML tree by
// following a sequence of path identifiers.
func GetYAMLPath(root *yaml.Node, path ...string) (*yaml.Node, error) {
root = unwrapDocumentNode(root)
if len(path) == 0 {
return root, nil
}
if root.Kind == yaml.SequenceNode {
newRoot, err := getIndexFromSequence(path[0], false, root)
if err != nil {
return nil, err
}
if newRoot, err = GetYAMLPath(newRoot, path[1:]...); err != nil {
return nil, fmt.Errorf("%v.%w", path[0], err)
}
return newRoot, nil
}
newRoot, err := getFieldFromMapping(path[0], false, root)
if err != nil {
return nil, err
}
if newRoot, err = GetYAMLPath(newRoot, path[1:]...); err != nil {
return nil, fmt.Errorf("%v.%w", path[0], err)
}
return newRoot, nil
}
//------------------------------------------------------------------------------
// YAMLLabelsToPaths walks a YAML tree using a field spec as a reference point.
// When a component of the YAML tree has a label field it is added to the
// provided labelsToPaths map with the path to the component.
func (f FieldSpecs) YAMLLabelsToPaths(docsProvider Provider, node *yaml.Node, labelsToPaths map[string][]string, path []string) {
node = unwrapDocumentNode(node)
fieldMap := map[string]FieldSpec{}
for _, spec := range f {
fieldMap[spec.Name] = spec
}
for i := 0; i < len(node.Content)-1; i += 2 {
key := node.Content[i].Value
if spec, exists := fieldMap[key]; exists {
spec.YAMLLabelsToPaths(docsProvider, node.Content[i+1], labelsToPaths, append(path, key))
}
}
}
// YAMLLabelsToPaths walks a YAML tree using a field spec as a reference point.
// When a component of the YAML tree has a label field it is added to the
// provided labelsToPaths map with the path to the component.
func (f FieldSpec) YAMLLabelsToPaths(docsProvider Provider, node *yaml.Node, labelsToPaths map[string][]string, path []string) {
node = unwrapDocumentNode(node)
switch f.Kind {
case Kind2DArray:
nextSpec := f.Array()
for i, child := range node.Content {
nextSpec.YAMLLabelsToPaths(docsProvider, child, labelsToPaths, append(path, strconv.Itoa(i)))
}
case KindArray:
nextSpec := f.Scalar()
for i, child := range node.Content {
nextSpec.YAMLLabelsToPaths(docsProvider, child, labelsToPaths, append(path, strconv.Itoa(i)))
}
case KindMap:
nextSpec := f.Scalar()
for i, child := range node.Content {
nextSpec.YAMLLabelsToPaths(docsProvider, child, labelsToPaths, append(path, strconv.Itoa(i)))
}
for i := 0; i < len(node.Content)-1; i += 2 {
key := node.Content[i].Value
nextSpec.YAMLLabelsToPaths(docsProvider, node.Content[i+1], labelsToPaths, append(path, key))
}
default:
if coreType, isCore := f.Type.IsCoreComponent(); isCore {
if docsProvider == nil {
docsProvider = globalProvider
}
coreFields := FieldSpecs{}
for _, f := range reservedFieldsByType(coreType) {
coreFields = append(coreFields, f)
}
if inferred, cSpec, err := GetInferenceCandidateFromYAML(docsProvider, coreType, node); err == nil {
conf := cSpec.Config
conf.Name = inferred
coreFields = append(coreFields, conf)
}
coreFields.YAMLLabelsToPaths(docsProvider, node, labelsToPaths, path)
} else if len(f.Children) > 0 {
f.Children.YAMLLabelsToPaths(docsProvider, node, labelsToPaths, path)
} else if f.Name == labelField.Name && f.Description == labelField.Description {
pathCopy := make([]string, len(path)-1)
copy(pathCopy, path[:len(path)-1])
labelsToPaths[node.Value] = pathCopy // Add path to the parent node
}
}
} | internal/docs/yaml_path.go | 0.554953 | 0.40157 | yaml_path.go | starcoder |
package match
import (
"reflect"
"emperror.dev/errors"
)
// ErrorMatcher checks if an error matches a certain condition.
type ErrorMatcher interface {
// MatchError checks if err matches a certain condition.
MatchError(err error) bool
}
// ErrorMatcherFunc turns a plain function into an ErrorMatcher if it's definition matches the interface.
type ErrorMatcherFunc func(err error) bool
// MatchError calls the underlying function to check if err matches a certain condition.
func (fn ErrorMatcherFunc) MatchError(err error) bool {
return fn(err)
}
// Any matches an error if any of the underlying matchers match it.
type Any []ErrorMatcher
// MatchError calls underlying matchers with err.
// If any of them matches err it returns true, otherwise false.
func (m Any) MatchError(err error) bool {
for _, matcher := range m {
if matcher.MatchError(err) {
return true
}
}
return false
}
// All matches an error if all of the underlying matchers match it.
type All []ErrorMatcher
// MatchError calls underlying matchers with err.
// If all of them matches err it returns true, otherwise false.
func (m All) MatchError(err error) bool {
for _, matcher := range m {
if !matcher.MatchError(err) {
return false
}
}
return true
}
// Is returns an error matcher that determines matching by calling errors.Is.
func Is(target error) ErrorMatcher {
return ErrorMatcherFunc(func(err error) bool {
return errors.Is(err, target)
})
}
// As returns an error matcher that determines matching by calling errors.As.
func As(target interface{}) ErrorMatcher {
if target == nil {
panic("errors: target cannot be nil")
}
val := reflect.ValueOf(target)
typ := val.Type()
if typ.Kind() != reflect.Ptr || val.IsNil() {
panic("errors: target must be a non-nil pointer")
}
if e := typ.Elem(); e.Kind() != reflect.Interface && !e.Implements(errorType) {
panic("errors: *target must be interface or implement error")
}
tar := reflect.New(typ).Interface()
return ErrorMatcherFunc(func(err error) bool {
target := tar
return errors.As(err, &target)
})
}
var errorType = reflect.TypeOf((*error)(nil)).Elem() | match/match.go | 0.777975 | 0.418281 | match.go | starcoder |
package ast
import (
"github.com/cntzr/remgo/token"
)
type (
Node interface {
TokenLiteral() string
}
// Represents one complete reminder as a one-liner
Statement interface {
Node
statementNode()
}
// List of all reminders in one file or over all files
Reminders struct {
Statements []Statement
}
// Marks a reminder ... in the future there may be RUN statements as well
REMStatement struct {
Token token.Token // the REM token
Weekdays []*Weekday
Day *Day
Month *Month
Year *Year
Lead *Lead
At *At
AtTime *AtTime
Duration *Duration
DurationTime *DurationTime
Repeat *Repeat
Msg *Msg
MsgTxt *MsgTxt
Value string
}
Month struct {
Token token.Token // the Element's token
Value string
}
Weekday struct {
Token token.Token // the Element's token
Value string
}
Day struct {
Token token.Token // the Element's token
Value string
}
Year struct {
Token token.Token // the Element's token
Value string
}
Repeat struct {
Token token.Token // the Element's token
Value string
}
At struct {
Token token.Token // the Element's token
Value string
}
AtTime struct {
Token token.Token // the Element's token
Value string
}
Duration struct {
Token token.Token // the Element's token
Value string
}
DurationTime struct {
Token token.Token // the Element's token
Value string
}
Lead struct {
Token token.Token // the Element's token
Value string
}
Msg struct {
Token token.Token // the Element's token
Value string
}
MsgTxt struct {
Token token.Token // the Element's token
Value string
}
)
func (r *Reminders) TokenLiteral() string {
if len(r.Statements) > 0 {
return r.Statements[0].TokenLiteral()
}
return ""
}
func (rs *REMStatement) statementNode() {}
func (rs *REMStatement) TokenLiteral() string { return rs.Token.Literal }
func (e *Weekday) statementNode() {}
func (e *Weekday) TokenLiteral() string { return e.Token.Literal }
func (e *Month) statementNode() {}
func (e *Month) TokenLiteral() string { return e.Token.Literal }
func (e *Day) statementNode() {}
func (e *Day) TokenLiteral() string { return e.Token.Literal }
func (e *Year) statementNode() {}
func (e *Year) TokenLiteral() string { return e.Token.Literal }
func (rs *Repeat) statementNode() {}
func (e *Repeat) TokenLiteral() string { return e.Token.Literal }
func (rs *At) statementNode() {}
func (e *At) TokenLiteral() string { return e.Token.Literal }
func (rs *AtTime) statementNode() {}
func (e *AtTime) TokenLiteral() string { return e.Token.Literal }
func (rs *Duration) statementNode() {}
func (e *Duration) TokenLiteral() string { return e.Token.Literal }
func (rs *DurationTime) statementNode() {}
func (e *DurationTime) TokenLiteral() string { return e.Token.Literal }
func (rs *Lead) statementNode() {}
func (e *Lead) TokenLiteral() string { return e.Token.Literal }
func (rs *Msg) statementNode() {}
func (e *Msg) TokenLiteral() string { return e.Token.Literal }
func (rs *MsgTxt) statementNode() {}
func (e *MsgTxt) TokenLiteral() string { return e.Token.Literal } | ast/ast.go | 0.553747 | 0.587174 | ast.go | starcoder |
package rest
import (
"sort"
)
// Filter tests if a value fulfills the given logic.
type Filter func(interface{}) bool
// Dict is a container with guaranteed key ordering.
type Dict struct {
Keys []string
Values []interface{}
}
// NewDictWithCap creates a new Dict object with given capacity.
func NewDictWithCap(n int) *Dict {
return &Dict{Keys: make([]string, 0, n), Values: make([]interface{}, 0, n)}
}
// NewDict creates a new Dict object.
func NewDict() *Dict {
return NewDictWithCap(8)
}
// Index finds the index closest to the given key.
func (d *Dict) Index(key string) int {
return sort.Search(len(d.Keys), func(i int) bool {
return d.Keys[i] >= key
})
}
// Get a value for a given key. Returns nil if the key does not exist.
func (d *Dict) Get(key string) interface{} {
if i := d.Index(key); i < d.Len() && d.Keys[i] == key {
return d.Values[i]
}
return nil
}
// Set a value for the given key. Returns false if the key does not exist.
func (d *Dict) Set(key string, value interface{}) bool {
if i := d.Index(key); i < d.Len() && d.Keys[i] == key {
d.Values[i] = value
return true
}
return false
}
// Insert a value for the given key. Returns false if the key exists.
func (d *Dict) Insert(key string, value interface{}) bool {
if d.Len() == 0 {
d.Keys = append(d.Keys, key)
d.Values = append(d.Values, value)
return true
}
i := d.Index(key)
if i == d.Len() {
d.Keys = append(d.Keys, key)
d.Values = append(d.Values, value)
return true
}
if d.Keys[i] != key {
d.Keys = append(d.Keys, "")
copy(d.Keys[i+1:], d.Keys[i:])
d.Keys[i] = key
d.Values = append(d.Values, nil)
copy(d.Values[i+1:], d.Values[i:])
d.Values[i] = value
return true
}
return false
}
// Remove a value for the given key. Returns nil if the key does not exist.
func (d *Dict) Remove(key string) interface{} {
if i := d.Index(key); i < d.Len() && d.Keys[i] == key {
copy(d.Keys[i:], d.Keys[i+1:])
d.Keys[len(d.Keys)-1] = ""
d.Keys = d.Keys[:len(d.Keys)-1]
value := d.Values[i]
copy(d.Values[i:], d.Values[i+1:])
d.Values[len(d.Values)-1] = nil
d.Values = d.Values[:len(d.Values)-1]
return value
}
return nil
}
// ClearWithCap initializes the content with the given capacity.
func (d *Dict) ClearWithCap(n int) {
d.Keys = make([]string, 0, n)
d.Values = make([]interface{}, 0, n)
}
// Clear the entire content.
func (d *Dict) Clear() {
d.ClearWithCap(8)
}
// Search indices for values matching the filter provided.
func (d *Dict) Search(f Filter) []int {
indices := make([]int, 0, 8)
for i := range d.Keys {
if f(d.Values[i]) {
indices = append(indices, i)
}
}
return indices
}
// Len returns the length of the Dict (keys).
func (d *Dict) Len() int {
return len(d.Keys)
} | dict.go | 0.796807 | 0.433802 | dict.go | starcoder |
package main
import (
"fmt"
"time"
)
// Return difference between two times in a printable format
func getTimeDiffString(a, b time.Time) (timeDiff string) {
year, month, day, hour, min, sec := getTimeDiffNumbers(a, b)
// Format the output
timeDiff = ""
if year > 0 {
if year > 1 {
timeDiff += fmt.Sprintf("%d years, ", year)
} else {
timeDiff += fmt.Sprintf("%d year, ", year)
}
}
if len(timeDiff) > 0 || month > 0 {
if month == 0 || month > 1 {
timeDiff += fmt.Sprintf("%d months, ", month)
} else {
timeDiff += fmt.Sprintf("%d month, ", month)
}
}
if len(timeDiff) > 0 || day > 0 {
if day == 0 || day > 1 {
timeDiff += fmt.Sprintf("%d days, ", day)
} else {
timeDiff += fmt.Sprintf("%d day, ", day)
}
}
switch {
case len(timeDiff) > 0 || hour > 0:
timeDiff += fmt.Sprintf("%d:%2.2d:%2.2d", hour, min, sec)
case min > 0:
timeDiff = fmt.Sprintf("%d:%2.2d", min, sec)
default:
if sec == 0 || sec > 1 {
timeDiff = fmt.Sprintf("%d seconds", sec)
} else {
timeDiff = fmt.Sprintf("%d second", sec)
}
}
return
}
func daysIn(year int, month time.Month) int {
return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
}
// Return difference between two times numerically
// Source: https://stackoverflow.com/questions/36530251/golang-time-since-with-months-and-years
func getTimeDiffNumbers(from, to time.Time) (years, months, days, hours, minutes, seconds int) {
if from.Location() != to.Location() {
to = to.In(from.Location())
}
if from.After(to) {
from, to = to, from
}
y1, M1, d1 := from.Date()
y2, M2, d2 := to.Date()
h1, m1, s1 := from.Clock()
h2, m2, s2 := to.Clock()
years = y2 - y1
months = int(M2 - M1)
days = d2 - d1
hours = h2 - h1
minutes = m2 - m1
seconds = s2 - s1
if seconds < 0 {
seconds += 60
minutes--
}
if minutes < 0 {
minutes += 60
hours--
}
if hours < 0 {
hours += 24
days--
}
if days < 0 {
days += daysIn(y2, M2-1)
months--
}
if months < 0 {
months += 12
years--
}
return
} | timeutils.go | 0.53607 | 0.525612 | timeutils.go | starcoder |
package vector
import (
"github.com/zhangxianweihebei/gostl/utils/iterator"
)
//ArrayIterator is an implementation of RandomAccessIterator
var _ iterator.RandomAccessIterator = (*VectorIterator)(nil)
// VectorIterator represents a vector iterator
type VectorIterator struct {
vec *Vector
position int // the position of iterator point to
}
// IsValid returns true if the iterator is valid, otherwise returns false
func (iter *VectorIterator) IsValid() bool {
if iter.position >= 0 && iter.position < iter.vec.Size() {
return true
}
return false
}
// Value returns the value of the iterator point to
func (iter *VectorIterator) Value() interface{} {
val := iter.vec.At(iter.position)
return val
}
// SetValue sets the value of the iterator point to
func (iter *VectorIterator) SetValue(val interface{}) {
iter.vec.SetAt(iter.position, val)
}
// Next moves the position of iterator to the next position and returns itself
func (iter *VectorIterator) Next() iterator.ConstIterator {
if iter.position < iter.vec.Size() {
iter.position++
}
return iter
}
// Prev moves the position of the iterator to the previous position and returns itself
func (iter *VectorIterator) Prev() iterator.ConstBidIterator {
if iter.position >= 0 {
iter.position--
}
return iter
}
// Clone clones the iterator into a new iterator
func (iter *VectorIterator) Clone() iterator.ConstIterator {
return &VectorIterator{vec: iter.vec, position: iter.position}
}
// IteratorAt creates an iterator with the passed position
func (iter *VectorIterator) IteratorAt(position int) iterator.RandomAccessIterator {
return &VectorIterator{vec: iter.vec, position: position}
}
// Position return the position of the iterator point to
func (iter *VectorIterator) Position() int {
return iter.position
}
// Equal returns true if the iterator is equal to the passed iterator
func (iter *VectorIterator) Equal(other iterator.ConstIterator) bool {
otherIter, ok := other.(*VectorIterator)
if !ok {
return false
}
if otherIter.vec == iter.vec && otherIter.position == iter.position {
return true
}
return false
} | ds/vector/iterator.go | 0.86332 | 0.474692 | iterator.go | starcoder |
package main
import (
"crypto/md5"
"encoding/json"
"fmt"
"strings"
)
func minmax(a, b int) (int, int) {
if a < b {
return a, b
} else {
return b, a
}
}
type Line struct {
X1, Y1, X2, Y2 int
}
type VectorImage struct {
Lines []Line
}
// The interface given
func NewRectangle(width, height int) *VectorImage {
width -= 1
height -= 1
return &VectorImage{[]Line{
Line{0, 0, width, 0},
Line{0, 0, 0, height},
Line{width, 0, width, height},
Line{0, height, width, height},
}}
}
type Point struct {
X, Y int
}
type RasterImage interface {
GetPoints() []Point
}
type runeMatrix struct {
data [][]rune
}
func NewRuneMatrix(width, height int) *runeMatrix {
data := make([][]rune, height)
for i := 0; i < height; i++ {
data[i] = make([]rune, width)
for j := range data[i] {
data[i][j] = ' '
}
}
return &runeMatrix{data}
}
func (r *runeMatrix) Draw(points []Point) *runeMatrix {
for _, point := range points {
r.data[point.Y][point.X] = '*'
}
return r
}
func (r *runeMatrix) String() string {
b := strings.Builder{}
for _, line := range r.data {
b.WriteString(string(line))
b.WriteRune('\n')
}
return b.String()
}
type borders struct {
Point
}
func NewBorders(points []Point) *borders {
maxX, maxY := 0, 0
for _, point := range points {
if point.X > maxX {
maxX = point.X
}
if point.Y > maxY {
maxY = point.Y
}
}
return &borders{Point{maxX + 1, maxY + 1}}
}
func DrawPoints(owner RasterImage) string {
points := owner.GetPoints()
b := NewBorders(points)
return NewRuneMatrix(b.X, b.Y).
Draw(points).
String()
}
var pointCache = map[[16]byte][]Point{}
type vectorToRasterAdapter struct {
points []Point
}
func (a vectorToRasterAdapter) GetPoints() []Point {
return a.points
}
func (a *vectorToRasterAdapter) addLine(line Line) {
left, right := minmax(line.X1, line.X2)
top, bottom := minmax(line.Y1, line.Y2)
dx := right - left
dy := line.Y2 - line.Y1
if dx == 0 {
for y := top; y <= bottom; y++ {
a.points = append(a.points, Point{left, y})
}
} else if dy == 0 {
for x := left; x <= right; x++ {
a.points = append(a.points, Point{x, top})
}
}
fmt.Println("We currently have", len(a.points), "points")
}
func (a *vectorToRasterAdapter) addLineCached(line Line) {
hash := func(obj interface{}) [16]byte {
bytes, _ := json.Marshal(obj)
return md5.Sum(bytes)
}
h := hash(line)
if points, ok := pointCache[h]; ok {
for _, point := range points {
a.points = append(a.points, point)
}
} else {
a.addLine(line)
pointCache[h] = a.points
}
}
func VectorToRaster(vi *VectorImage) RasterImage {
adapter := vectorToRasterAdapter{}
for _, line := range vi.Lines {
adapter.addLineCached(line)
}
return adapter
}
func main() {
rc := NewRectangle(60, 14)
rc2 := NewRectangle(10, 16)
a := VectorToRaster(rc)
b := VectorToRaster(rc2)
fmt.Print(DrawPoints(a))
fmt.Print(DrawPoints(b))
} | Structural/Adapter/adapter_with_caching.go | 0.669205 | 0.405714 | adapter_with_caching.go | starcoder |
package entity
import (
"fmt"
"math"
"unsafe"
)
// Coord is the of coordinations entity position (x, y, z)
type Coord float32
// Vector3 is type of entity position
type Vector3 struct {
X Coord
Y Coord
Z Coord
}
func (p Vector3) String() string {
return fmt.Sprintf("(%.2f, %.2f, %.2f)", p.X, p.Y, p.Z)
}
// DistanceTo calculates distance between two positions
func (p Vector3) DistanceTo(o Vector3) Coord {
dx := p.X - o.X
dy := p.Y - o.Y
dz := p.Z - o.Z
return Coord(math.Sqrt(float64(dx*dx + dy*dy + dz*dz)))
}
// Sub calculates Vector3 p - Vector3 o
func (p Vector3) Sub(o Vector3) Vector3 {
return Vector3{p.X - o.X, p.Y - o.Y, p.Z - o.Z}
}
func (p Vector3) Add(o Vector3) Vector3 {
return Vector3{p.X + o.X, p.Y + o.Y, p.Z + o.Z}
}
// Mul calculates Vector3 p * m
func (p Vector3) Mul(m Coord) Vector3 {
return Vector3{p.X * m, p.Y * m, p.Z * m}
}
// DirToYaw convert direction represented by Vector3 to Yaw
func (dir Vector3) DirToYaw() Yaw {
dir.Normalize()
yaw := math.Acos(float64(dir.X))
if dir.Z < 0 {
yaw = math.Pi*2 - yaw
}
yaw = yaw / math.Pi * 180 // convert to angle
if yaw <= 90 {
yaw = 90 - yaw
} else {
yaw = 90 + (360 - yaw)
}
return Yaw(yaw)
}
func (p *Vector3) Normalize() {
d := Coord(math.Sqrt(float64(p.X*p.X + p.Y + p.Y + p.Z*p.Z)))
if d == 0 {
return
}
p.X /= d
p.Y /= d
p.Z /= d
}
func (p Vector3) Normalized() Vector3 {
p.Normalize()
return p
}
type aoi struct {
pos Vector3
neighbors EntitySet
xNext *aoi
xPrev *aoi
zNext *aoi
zPrev *aoi
markVal int
}
func initAOI(aoi *aoi) {
aoi.neighbors = EntitySet{}
}
// Get the owner entity of this aoi
// This is very tricky but also effective
var aoiFieldOffset uintptr
func init() {
dummyEntity := (*Entity)(unsafe.Pointer(&aoiFieldOffset))
aoiFieldOffset = uintptr(unsafe.Pointer(&dummyEntity.aoi)) - uintptr(unsafe.Pointer(dummyEntity))
}
func (aoi *aoi) getEntity() *Entity {
return (*Entity)(unsafe.Pointer((uintptr)(unsafe.Pointer(aoi)) - aoiFieldOffset))
}
func (aoi *aoi) interest(other *Entity) {
aoi.neighbors.Add(other)
}
func (aoi *aoi) uninterest(other *Entity) {
aoi.neighbors.Del(other)
}
type aoiSet map[*aoi]struct{}
func (aoiset aoiSet) Add(aoi *aoi) {
aoiset[aoi] = struct{}{}
}
func (aoiset aoiSet) Del(aoi *aoi) {
delete(aoiset, aoi)
}
func (aoiset aoiSet) Contains(aoi *aoi) bool {
_, ok := aoiset[aoi]
return ok
}
func (aoiset aoiSet) Join(other aoiSet) aoiSet {
join := aoiSet{}
for aoi := range aoiset {
if other.Contains(aoi) {
join.Add(aoi)
}
}
return join
} | engine/entity/AOI.go | 0.766905 | 0.569494 | AOI.go | starcoder |
package src
import (
"strings"
"strconv"
//"fmt"
)
/** Lists all user-callable functions that return matrices */
var Functions = map[string]bool {
"zeros(" : true,
"id(" : true,
"rref(" : true,
"transpose(" : true,
"inv(" : true,
"col(" : true,
"row(" : true,
"null(": true,
"Lnull(" : true,
"solve(" : true,
"hsolve(" : true,
"llse(" : true,
"proj(" : true,
"norm(" : true,
"gs(" : true,
"qr(" : true,
"roll(": true,
"xcorr(": true,
"autocorr(": true,
}
func isFunctionCall(query string) bool {
if (!strings.Contains(query, "(") || !strings.Contains(query, ")")) {
return false;
}
funcNameIndex := strings.Index(query, "(");
funcName := query[0:funcNameIndex+1];
_, match := Functions[funcName];
_, match2 := IntFunctions[funcName];
_, match3 := FloatFunctions[funcName];
if (!match && !match2 && !match3) {
return false;
}
return true;
}
func getFunctionArgs(query string) (string, string) {
funcNameIndex := strings.Index(query, "(");
funcName := query[0:funcNameIndex];
endCallIndex := strings.LastIndex(query, ")");
parameters := query[funcNameIndex+1:endCallIndex];
return funcName, parameters;
}
func ApplyFunction(query string) (*Matrix, string) {
function, params := getFunctionArgs(query);
if (params == "") {
return nil, "ERROR: Must pass in a parameter";
}
switch {
case function == "id":
params = eval(params);
i, err := strconv.Atoi(params);
if (err != nil) {
return nil, "ERROR: Parameter must be an int";
}
matrix, e := id(i);
return matrix, e;
case function == "zeros":
args := splitParams(params);
if (args == nil) {
return nil, "ERROR: zeros can only take in one or two arguments";
}
return zeros(args...);
case function == "rref":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return rref(args);
case function == "transpose":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return transpose(args);
case function == "inv":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return inv(args);
case function == "col":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return col(args);
case function == "row":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return row(args);
case function == "null":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return null(args);
case function == "Lnull":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return Lnull(args);
case function == "solve":
arg1, arg2 := splitMatrices(params);
if (arg1 == nil || arg2 == nil) {
return nil, "ERROR: Invalid parameters."
}
return solve(arg1, arg2);
case function == "hsolve":
args := paramToMatrix(params);
if (args == nil) {
return nil, "ERROR: Parameter must be a valid matrix";
}
return hsolve(args);
case function == "llse":
arg1, arg2 := splitMatrices(params);
if (arg1 == nil || arg2 == nil) {
return nil, "ERROR: Invalid parameters";
}
return llse(arg1, arg2);
case function == "proj":
arg1, arg2 := splitMatrices(params);
if (arg1 == nil || arg2 == nil) {
return nil, "ERROR: Invalid parameters";
}
return proj(arg1, arg2);
case function == "norm":
arg := paramToMatrix(params);
if (arg == nil) {
return nil, "ERROR: Invalid parameter";
}
return norm(arg);
case function == "gs":
arg := paramToMatrix(params);
if (arg == nil) {
return nil, "ERROR: Invalid parameter";
}
return gs(arg);
case function == "qr":
arg1, arg2 := splitTag(params);
if (arg1 == nil) {
return nil, "ERROR: Invalid parameters";
}
return qr(arg1, arg2);
case function == "roll":
arg1, arg2 := splitInt(params);
if (arg1 == nil) {
return nil, "ERROR: Invalid parameters";
}
return roll(arg1, arg2);
case function == "xcorr":
arg1, arg2 := splitMatrices(params);
if (arg1 == nil || arg2 == nil) {
return nil, "ERROR: Invalid parameters";
}
return xcorr(arg1, arg2);
case function == "autocorr":
arg := paramToMatrix(params);
if (arg == nil) {
return nil, "ERROR: Invalid parameter";
}
return autocorr(arg);
default:
return nil, "ERROR: Invalid function call";
}
}
func paramToMatrix(params string) *Matrix {
var args *Matrix = nil;
if (IsVariable(params)) {
variable := Variables[params];
if (variable.class != "matrix") {
return nil;
}
args = variable.matrix;
} else if (isFunctionCall(params)) {
args, _ = ApplyFunction(params);
} else {
vals := queryToValues(params);
args, _ = NewMatrix(vals);
}
return args;
}
// splits parameters for variadic functions
func splitParams(params string) []int {
oldArgs := strings.Split(params, ",");
args := make([]int, len(oldArgs));
for i := 0; i < len(oldArgs); i++ {
j, err := strconv.Atoi(oldArgs[i]);
if (err != nil) {
return nil;
}
args[i] = j;
}
return args;
}
// Splits parameters into two matrices
func splitMatrices(params string) (*Matrix, *Matrix) {
oldArgs := strings.Split(params, ",");
if (len(oldArgs) != 2) {
return nil, nil;
}
mat1 := paramToMatrix(oldArgs[0]);
mat2 := paramToMatrix(oldArgs[1]);
return mat1, mat2;
}
func splitTag(params string) (*Matrix, string) {
oldArgs := strings.Split(params, ",");
if (len(oldArgs) != 2) {
return nil, "";
}
matrix := paramToMatrix(oldArgs[0]);
tag := oldArgs[1];
return matrix, tag;
}
func splitInt(params string) (*Matrix, int) {
oldArgs := strings.Split(params, ",");
if (len(oldArgs) != 2) {
return nil, 0;
}
matrix := paramToMatrix(oldArgs[0]);
n, e := strconv.Atoi(oldArgs[1]);
if (e != nil) {
return nil, 0;
}
return matrix, n;
} | src/Functions.go | 0.538983 | 0.497986 | Functions.go | starcoder |
package gofra
import (
"image/color"
. "github.com/gitchander/gofra/complex"
"github.com/gitchander/gofra/fcolor"
"github.com/gitchander/gofra/math2d"
)
type colorСomputer interface {
colorСompute(x, y int) color.RGBA
Clone() colorСomputer
}
type aliasingСomputer struct {
iterations int
colorTable []fcolor.RGB
spaceColor fcolor.RGB
orbitFactory OrbitFactory
transform math2d.Matrix
}
func (c aliasingСomputer) colorСompute(x, y int) color.RGBA {
var Z Complex
Z.Re, Z.Im = c.transform.TransformPoint(float64(x), float64(y))
orbit := c.orbitFactory.NewOrbit(Z)
iter, ok := TraceOrbit(orbit, c.iterations)
var fc fcolor.RGB
if !ok {
fc = c.spaceColor
} else {
fc = c.colorTable[iter]
}
return color.RGBAModel.Convert(fc).(color.RGBA)
}
func (c aliasingСomputer) Clone() colorСomputer {
v := aliasingСomputer{}
v.iterations = c.iterations
v.colorTable = make([]fcolor.RGB, len(c.colorTable))
copy(v.colorTable, c.colorTable)
v.spaceColor = c.spaceColor
v.orbitFactory = c.orbitFactory
v.transform = c.transform
return v
}
type antiAliasingСomputer struct {
aliasingСomputer
spTable []spPoint // subpixel shifts
spColors []fcolor.RGB // subpixel colors
}
func (c antiAliasingСomputer) colorСompute(x, y int) color.RGBA {
var Z Complex
for i, dz := range c.spTable {
Z.Re, Z.Im = c.transform.TransformPoint(
float64(x)+dz.X,
float64(y)+dz.Y,
)
orbit := c.orbitFactory.NewOrbit(Z)
iter, ok := TraceOrbit(orbit, c.iterations)
var fc fcolor.RGB
if !ok {
fc = c.spaceColor
} else {
fc = c.colorTable[iter]
}
c.spColors[i] = fc
}
fc := fcolor.MixRGB(c.spColors)
return color.RGBAModel.Convert(fc).(color.RGBA)
}
func (c antiAliasingСomputer) Clone() colorСomputer {
v := antiAliasingСomputer{}
v.aliasingСomputer = c.aliasingСomputer.Clone().(aliasingСomputer)
v.spTable = make([]spPoint, len(c.spTable))
copy(v.spTable, c.spTable)
v.spColors = make([]fcolor.RGB, len(c.spColors))
copy(v.spColors, c.spColors)
return v
}
func newColorСomputer(config Config, transform math2d.Matrix) colorСomputer {
ac := aliasingСomputer{
iterations: config.Calculation.Iterations,
colorTable: newColorTable(config.Calculation.Iterations, config.Palette),
spaceColor: config.Palette.SpaceColor,
orbitFactory: newOrbitFactory(config.FractalInfo),
transform: transform,
}
spTable := makeSubpixelTable(config.Calculation.AntiAliasing)
if len(spTable) == 0 {
return ac
}
return antiAliasingСomputer{
aliasingСomputer: ac,
spTable: spTable,
spColors: make([]fcolor.RGB, len(spTable)),
}
} | compute.go | 0.704872 | 0.431405 | compute.go | starcoder |
package timeutils
import (
"time"
)
const pATTERN string = "2006-01-02 15:04:05"
/**
return Now time-object within Golang builtin type `time.Time`.
*/
func NowTime() time.Time {
return time.Now()
}
/**
return formatted string from Now time-object within Golang builtin type `time.Time`.
Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard
and convenient representations of the reference time. For more information
about the formats and the definition of the reference time, see the
documentation for ANSIC and the other constants defined by package time
*/
func NowTimeStringWithinPattern(pattern string) string {
now := time.Now()
resultStr := now.Format(pattern)
return resultStr
}
/**
return formatted string from specified parameter @param t using pattern.
*/
func FormetTime(t time.Time, pattern string) string {
return t.Format(pattern)
}
/**
return timestamp now int second
*/
func NowInSecond() int64 {
timeNowInNanoSecond := time.Now().Unix()
return timeNowInNanoSecond
}
/**
return timestamp now in millisecond
*/
func NowInMillisecond() int64 {
timeNowInNanoSecond := time.Now().UnixNano()
return timeNowInNanoSecond / 1e6
}
/**
return timestamp now in nanosecond
*/
func NowInNanosecond() int64 {
timeNowInNanoSecond := time.Now().UnixNano()
return timeNowInNanoSecond
}
/**
return the YEAR from system clock in int.
e.g, Now is 2019-08-10 10:29:56, then return 2019
*/
func NowYear() int {
year := time.Now().Year()
return year
}
/**
return the MONTH from system clock in int.
1——"January",
2——"February",
3——"March",
4——"April",
5——"May",
6——"June",
7——"July",
8——"August",
9——"September",
10——"October",
11——"November",
12——"December",
e.g, Now is 2019-08-10 10:29:56, then return 8
*/
func NowMonth() int {
month := time.Now().Month()
return int(month)
}
/**
return the MONTH from system clock in STRING.
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
e.g, Now is 2019-08-10 10:29:56, then return "August"
*/
func NowMonthString() string {
month := time.Now().Month()
return month.String()
}
/**
return the Day from system clock.
e.g, Now is 2019-08-10 10:29:56, then return 10
*/
func NowDay() int {
return time.Now().Day()
}
/**
return the Hour from system clock.
e.g, Now is 2019-01-10 10:29:56, then return 10
*/
func NowHour() int {
return time.Now().Hour()
}
/**
return the Minute from system clock.
e.g, Now is 2019-01-10 10:29:56, then return 29
*/
func NowMinute() int {
return time.Now().Minute()
}
/**
return the Second from system clock.
e.g, Now is 2019-01-10 10:29:56, then return 56
*/
func NowSecond() int {
return time.Now().Second()
}
/**
ParseTime parses a formatted string and returns the time value it represents.
The layout defines the format by showing how the reference time,
defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be interpreted if it were the value; it serves as an example of
the input format. The same interpretation will then be made to the
input string.
Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard
and convenient representations of the reference time. For more information
about the formats and the definition of the reference time, see the
documentation for ANSIC and the other constants defined by this package.
Also, the executable example for Time.Format demonstrates the working
of the layout string in detail and is a good reference.
Elements omitted from the value are assumed to be zero or, when
zero is impossible, one, so parsing "3:04pm" returns the time
corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is
0, this time is before the zero Time).
Years must be in the range 0000..9999. The day of the week is checked
for syntax but it is otherwise ignored.
In the absence of a time zone indicator, Parse returns a time in UTC.
When parsing a time with a zone offset like -0700, if the offset corresponds
to a time zone used by the current location (Local), then Parse uses that
location and zone in the returned time. Otherwise it records the time as
being in a fabricated location with time fixed at the given zone offset.
When parsing a time with a zone abbreviation like MST, if the zone abbreviation
has a defined offset in the current location, then that offset is used.
The zone abbreviation "UTC" is recognized as UTC regardless of location.
If the zone abbreviation is unknown, Parse records the time as being
in a fabricated location with the given zone abbreviation and a zero offset.
This choice means that such a time can be parsed and reformatted with the
same layout losslessly, but the exact instant used in the representation will
differ by the actual zone offset. To avoid such problems, prefer time layouts
that use a numeric zone offset, or use ParseInLocation.
*/
func ParseTime(pattern string, value string) (time.Time, error) {
t, err := time.Parse(pattern, value)
return t, err
}
/**
ParseTimeInLocation is like Parse but differs in two important ways.
First, in the absence of time zone information, Parse interprets a time as UTC;
ParseInLocation interprets the time as in the given location.
Second, when given a zone offset or abbreviation, Parse tries to match it
against the Local location; ParseInLocation uses the given location.
Yo find the time.Location, you can use `time.LoadLocation(name)`. the name you can find from pkg/zone/zoneinfo.
If you want to know the details, you can read from https://github.com/eiDear/gotools/blob/master/pkg/zone/locationnames.md
*/
func ParseTimeInLocation(pattern, value string, loc *time.Location) (time.Time, error) {
return time.ParseInLocation(pattern, value, loc)
} | pkg/timeutils/timeutils.go | 0.905572 | 0.498413 | timeutils.go | starcoder |
package main
import (
"strconv"
"math"
"syscall/js"
)
func main() {
}
type node struct {
data int
// For each node, which node it can most efficiently be reached from.
// If a node can be reached from many nodes, cameFrom will eventually contain the
// most efficient previous step.
previous *node
// For each node, the cost of getting from the start node to that node.
gScore float64
// For each node, the total cost of getting from the start node to the goal
// by passing by that node. That value is partly known, partly heuristic.
fScore float64
// The heuristic cost
hScore float64
world *squareGridWorld
index int
costModifier float64
}
type squareGridWorld struct {
nodes []*node
m map[int]*node
N int
neighbours map[int]map[int]int
}
func (g squareGridWorld) coords(i int) (int, int) {
x := i % g.N
y := i / g.N
return x, y
}
type x struct {
a int
}
//go:export add
func add(a, b int) int {
return a + b
}
//go:export update
func update() {
document := js.Global().Get("document")
aStr := document.Call("getElementById", "a").Get("value").String()
bStr := document.Call("getElementById", "b").Get("value").String()
a, _ := strconv.Atoi(aStr)
b, _ := strconv.Atoi(bStr)
result := add(a, b)
x1 := x{ a: 100 }
g := NewGrid(100)
document.Call("getElementById", "result").Set("value", g.N + x1.a + result)
}
//go:export NewGrid
func NewGrid(n int) *squareGridWorld {
nodes := make([]*node, n*n, n*n)
g := &squareGridWorld{
nodes: nodes, N: n,
neighbours: make(map[int]map[int]int),
m: make(map[int]*node),
}
nodes[0] = &node{data: 0, gScore: 0, index: 0, world: g}
g.m[0] = nodes[0]
for i := 1; i < len(nodes); i++ {
x1, y1 := g.coords(i)
x2, y2 := g.coords(n)
nodes[i] = &node{data: i, previous: nil, gScore: DistanceBetween(x1, y1, x2, y2), index: i, world: g}
g.m[i] = nodes[i]
}
for i := range nodes {
//g.apply(i, g.N, up, upright, right, downright, down, downleft, left, upleft)
right(i, n)
}
g.updateHValues(0, n * n -1)
return g
}
//go:export DistanceBetween
func DistanceBetween(x1, y1, x2, y2 int) float64 {
dx, dy := x2-x1, y2-y1
return math.Sqrt(float64(dx*dx +dy*dy))
}
//go:export neighbour
func (g *squareGridWorld) neighbour(i, n int) {
if g.neighbours[i] == nil {
g.neighbours[i] = make(map[int]int)
}
g.neighbours[i][n] = 1
}
//go:export right
func right(i, n int) {
resolve(i, i+1, n)
}
//go:export left
func left(i, n int) {
resolve(i, i-1, n)
}
//go:export down
func down(i, n int) {
resolve(i, i+n, n)
}
//go:export up
func up(i, n int) {
resolve(i, i-n, n)
}
//go:export downright
func downright(i, n int) {
resolve(i, i+n+1, n)
}
//go:export downleft
func downleft(i, n int) {
resolve(i, i+n-1, n)
}
//go:export upright
func upright(i, n int) {
resolve(i, i-n+1, n)
}
//go:export upleft
func upleft(i, n int) {
resolve(i, i-n-1, n)
}
//go:export resolve
func resolve(i, i2, n int){
if i2 >= (n*n) || i2 < 0 {return }
if i%n == 0 && i2%n == n-1 {return }
if i%n == n-1 && i2%n == 0 {return }
//neighbour(i, n)
}
//go:export updateHValues
func (g *squareGridWorld) updateHValues(i, j int) {
for i < len(g.nodes) {
x1, y1 := g.coords(i)
x2, y2 := g.coords(j)
g.nodes[i].hScore = DistanceBetween(x1, y1, x2, y2)
i++
}
} | src/examples/wasm/export/wasm.go | 0.521959 | 0.458894 | wasm.go | starcoder |
package clone_graph
import "container/list"
/*
133. 克隆图
https://leetcode-cn.com/problems/clone-graph
给你无向 连通 图中一个结点的引用,请你返回该图的 深拷贝(克隆)。
图中的每个结点都包含它的值 val(int) 和其邻居的列表(list[Node])。
class Node {
public int val;
public List<Node> neighbors;
}
测试用例格式:
简单起见,每个结点的值都和它的索引相同。例如,第一个结点值为 1(val = 1),第二个结点值为 2(val = 2),以此类推。该图在测试用例中使用邻接列表表示。
邻接列表 是用于表示有限图的无序列表的集合。每个列表都描述了图中结点的邻居集。
给定结点将始终是图中的第一个结点(值为 1)。你必须将 给定结点的拷贝 作为对克隆图的引用返回。
示例 1:
输入:adjList = [[2,4],[1,3],[2,4],[1,3]]
输出:[[2,4],[1,3],[2,4],[1,3]]
解释:
图中有 4 个结点。
结点 1 的值是 1,它有两个邻居:结点 2 和 4 。
结点 2 的值是 2,它有两个邻居:结点 1 和 3 。
结点 3 的值是 3,它有两个邻居:结点 2 和 4 。
结点 4 的值是 4,它有两个邻居:结点 1 和 3 。
示例 2:
输入:adjList = [[]]
输出:[[]]
解释:输入包含一个空列表。该图仅仅只有一个值为 1 的结点,它没有任何邻居。
示例 3:
输入:adjList = []
输出:[]
解释:这个图是空的,它不含任何结点。
示例 4:
输入:adjList = [[2],[1]]
输出:[[2],[1]]
提示:
结点数不超过 100 。
每个结点值 Node.val 都是唯一的,1 <= Node.val <= 100。
无向图是一个简单图,这意味着图中没有重复的边,也没有自环。
由于图是无向的,如果结点 p 是结点 q 的邻居,那么结点 q 也必须是结点 p 的邻居。
图是连通图,你可以从给定结点访问到所有结点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/clone-graph
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
type Node struct {
Val int
Neighbors []*Node
}
/*
把图看成一棵树会比较好理解
要注意和树不同的是,孩子结点可能反过来成为父结点,递归或遍历会形成无限循环
需要用额外的数据结构如哈希表来记录结点是否访问过
直观的做法是哈希表定义为键为*Node值为bool,这样不太好处理;想想,改成值为原图中结点,键为新图中结点,会比较好。
*/
/*
递归DFS
假设所有结点个数为n,
时间复杂度O(n),每个结点处理一次,栈调用时间复杂度O(H),H为图的最大深度,综合复杂度O(n)
空间复杂度O(n),哈希表需要O(n),栈需要O(H)
*/
func cloneGraph1(node *Node) *Node {
return help(node, make(map[*Node]*Node, 0))
}
func help(node *Node, seen map[*Node]*Node) *Node {
if node == nil {
return nil
}
if seen[node] != nil {
return seen[node]
}
cloned := &Node{Val: node.Val, Neighbors: make([]*Node, len(node.Neighbors))}
seen[node] = cloned
for i, v := range node.Neighbors {
cloned.Neighbors[i] = help(v, seen)
}
return cloned
}
/*
迭代BFS,存放临时结点的容器可随意选用,这里选list
时间复杂度O(n),每个结点处理一次
空间复杂度O(n),哈希表需要O(n), BFS使用的容器需要O(W),其中W是图的宽度, 综合复杂度O(n)
*/
func cloneGraph(node *Node) *Node {
if node == nil {
return nil
}
queue := list.New()
queue.PushBack(node)
seen := make(map[*Node]*Node, 0)
seen[node] = &Node{Val: node.Val, Neighbors: make([]*Node, len(node.Neighbors))}
for queue.Len() > 0 {
n := queue.Remove(queue.Front()).(*Node)
for i, v := range n.Neighbors {
if _, ok := seen[v]; !ok {
queue.PushBack(v)
seen[v] = &Node{Val: v.Val, Neighbors: make([]*Node, len(v.Neighbors))}
}
seen[n].Neighbors[i] = seen[v]
}
}
return seen[node]
} | solutions/clone-graph/d.go | 0.53048 | 0.506591 | d.go | starcoder |
package indicators
import (
"container/list"
"errors"
"github.com/jaybutera/gotrade"
"math"
)
// A Highest High Value Bars Indicator (HhvBars), no storage, for use in other indicators
type HhvBarsWithoutStorage struct {
*baseIndicatorWithIntBounds
// private variables
periodHistory *list.List
currentHigh float64
currentHighIndex int64
timePeriod int
}
// NewHhvBarsWithoutStorage creates a Highest High Value Bars Indicator Indicator (HhvBars) without storage
func NewHhvBarsWithoutStorage(timePeriod int, valueAvailableAction ValueAvailableActionInt) (indicator *HhvBarsWithoutStorage, err error) {
// an indicator without storage MUST have a value available action
if valueAvailableAction == nil {
return nil, ErrValueAvailableActionIsNil
}
// the minimum timeperiod for this indicator is 1
if timePeriod < 1 {
return nil, errors.New("timePeriod is less than the minimum (1)")
}
// check the maximum timeperiod
if timePeriod > MaximumLookbackPeriod {
return nil, errors.New("timePeriod is greater than the maximum (100000)")
}
lookback := timePeriod - 1
ind := HhvBarsWithoutStorage{
baseIndicatorWithIntBounds: newBaseIndicatorWithIntBounds(lookback, valueAvailableAction),
currentHigh: math.SmallestNonzeroFloat64,
currentHighIndex: 0,
periodHistory: list.New(),
timePeriod: timePeriod,
}
return &ind, nil
}
// A Highest High Value Bars Indicator (HhvBars)
type HhvBars struct {
*HhvBarsWithoutStorage
selectData gotrade.DOHLCVDataSelectionFunc
// public variables
Data []int64
}
// NewHhvBars creates a Highest High Value Bars Indicator (HhvBars) for online usage
func NewHhvBars(timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *HhvBars, err error) {
if selectData == nil {
return nil, ErrDOHLCVDataSelectFuncIsNil
}
ind := HhvBars{
selectData: selectData,
}
ind.HhvBarsWithoutStorage, err = NewHhvBarsWithoutStorage(timePeriod, func(dataItem int64, streamBarIndex int) {
ind.Data = append(ind.Data, dataItem)
})
return &ind, err
}
// NewDefaultHhvBars creates a Highest High Value Indicator (HhvBars) for online usage with default parameters
// - timePeriod: 25
func NewDefaultHhvBars() (indicator *HhvBars, err error) {
timePeriod := 25
return NewHhvBars(timePeriod, gotrade.UseClosePrice)
}
// NewHhvBarsWithSrcLen creates a Highest High Value Indicator (HhvBars)for offline usage
func NewHhvBarsWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *HhvBars, err error) {
ind, err := NewHhvBars(timePeriod, selectData)
// only initialise the storage if there is enough source data to require it
if sourceLength-uint(ind.GetLookbackPeriod()) > 1 {
ind.Data = make([]int64, 0, sourceLength-uint(ind.GetLookbackPeriod()))
}
return ind, err
}
// NewDefaultHhvBarsWithSrcLen creates a Highest High Value Indicator (HhvBars)for offline usage with default parameters
func NewDefaultHhvBarsWithSrcLen(sourceLength uint) (indicator *HhvBars, err error) {
ind, err := NewDefaultHhvBars()
// only initialise the storage if there is enough source data to require it
if sourceLength-uint(ind.GetLookbackPeriod()) > 1 {
ind.Data = make([]int64, 0, sourceLength-uint(ind.GetLookbackPeriod()))
}
return ind, err
}
// NewHhvBarsForStream creates a Highest High Value Indicator (HhvBars)for online usage with a source data stream
func NewHhvBarsForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *HhvBars, err error) {
ind, err := NewHhvBars(timePeriod, selectData)
priceStream.AddTickSubscription(ind)
return ind, err
}
// NewDefaultHhvBarsForStream creates a Highest High Value Indicator (HhvBars)for online usage with a source data stream
func NewDefaultHhvBarsForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *HhvBars, err error) {
ind, err := NewDefaultHhvBars()
priceStream.AddTickSubscription(ind)
return ind, err
}
// NewHhvBarsForStreamWithSrcLen creates a Highest High Value Indicator (HhvBars)for offline usage with a source data stream
func NewHhvBarsForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *HhvBars, err error) {
ind, err := NewHhvBarsWithSrcLen(sourceLength, timePeriod, selectData)
priceStream.AddTickSubscription(ind)
return ind, err
}
// NewDefaultHhvBarsForStreamWithSrcLen creates a Highest High Value Indicator (HhvBars)for offline usage with a source data stream
func NewDefaultHhvBarsForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *HhvBars, err error) {
ind, err := NewDefaultHhvBarsWithSrcLen(sourceLength)
priceStream.AddTickSubscription(ind)
return ind, err
}
// ReceiveDOHLCVTick consumes a source data DOHLCV price tick
func (ind *HhvBars) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) {
var selectedData = ind.selectData(tickData)
ind.ReceiveTick(selectedData, streamBarIndex)
}
func (ind *HhvBarsWithoutStorage) ReceiveTick(tickData float64, streamBarIndex int) {
ind.periodHistory.PushBack(tickData)
// resize the history
if ind.periodHistory.Len() > ind.timePeriod {
first := ind.periodHistory.Front()
ind.periodHistory.Remove(first)
// make sure we haven't just removed the current high
if ind.currentHighIndex == int64(ind.timePeriod-1) {
ind.currentHigh = math.SmallestNonzeroFloat64
// we have we need to find the new high in the history
var i int = ind.timePeriod - 1
for e := ind.periodHistory.Front(); e != nil; e = e.Next() {
value := e.Value.(float64)
if value > ind.currentHigh {
ind.currentHigh = value
ind.currentHighIndex = int64(i)
}
i -= 1
}
} else {
if tickData > ind.currentHigh {
ind.currentHigh = tickData
ind.currentHighIndex = 0
} else {
ind.currentHighIndex += 1
}
}
var result = ind.currentHighIndex
ind.UpdateIndicatorWithNewValue(result, streamBarIndex)
} else {
if tickData > ind.currentHigh {
ind.currentHigh = tickData
ind.currentHighIndex = 0
} else {
ind.currentHighIndex += 1
}
if ind.periodHistory.Len() == ind.timePeriod {
var result = ind.currentHighIndex
ind.UpdateIndicatorWithNewValue(result, streamBarIndex)
}
}
} | indicators/hhvbars.go | 0.619011 | 0.484563 | hhvbars.go | starcoder |
package match
import "time"
// Condition is used to match a time.
// All fields are optional and can be used in any combination.
// For each field one value of the list has
// to match to find a match for the condition.
type Condition struct {
Year []int
Month []time.Month
Day []int // 1 to 31
Weekday []time.Weekday
Hour []int // 0 to 23
Minute []int // 0 to 59
Second []int // 0 to 59
}
// Next finds the next time the passed condition matches.
// Returns an empty time.Time when no possible match can be found.
// This can only happen when there is no future year condition.
// Use .IsZero() to test if result is empty.
func Next(start time.Time, c Condition) time.Time {
if noMatch(start, c) {
return time.Time{}
}
t := setBase(start, c)
// Stop when when no condition
if t.Equal(start) {
return t
}
// Walk until all units match.
// Adjust biggest unit first.
for {
switch {
case wrong(c.Year, t.Year()):
t = addYear(t)
case wrongMonth(c.Month, t.Month()):
t = addMonth(t)
case wrong(c.Day, t.Day()) || wrongWeekday(c.Weekday, t.Weekday()):
t = addDay(t)
case wrong(c.Hour, t.Hour()):
t = addHour(t)
case wrong(c.Minute, t.Minute()):
t = addMinute(t)
case wrong(c.Second, t.Second()):
t = addSecond(t)
default:
// Found matching time.
return t
}
}
}
// Find smallest unit and start counting from there.
// At least have to increment by one.
func setBase(t time.Time, c Condition) time.Time {
switch {
case len(c.Second) > 0:
return addSecond(t)
case len(c.Minute) > 0:
return addMinute(t)
case len(c.Hour) > 0:
return addHour(t)
case len(c.Day) > 0 || len(c.Weekday) > 0:
return addDay(t)
case len(c.Month) > 0:
return addMonth(t)
case len(c.Year) > 0:
return addYear(t)
default:
return t
}
}
func noMatch(t time.Time, c Condition) bool {
for _, y := range c.Year {
if y <= t.Year() {
return true
}
}
return false
}
func wrong(xs []int, x int) bool {
if len(xs) == 0 {
return false
}
for _, y := range xs {
if x == y {
return false
}
}
return true
}
func wrongMonth(ms []time.Month, m time.Month) bool {
xs := make([]int, len(ms))
for i := range ms {
xs[i] = int(ms[i])
}
return wrong(xs, int(m))
}
func wrongWeekday(ds []time.Weekday, d time.Weekday) bool {
xs := make([]int, len(ds))
for i := range ds {
xs[i] = int(ds[i])
}
return wrong(xs, int(d))
}
func addYear(t time.Time) time.Time {
return t.AddDate(1, 1-int(t.Month()), 1-t.Day()).Truncate(time.Hour * 24)
}
func addMonth(t time.Time) time.Time {
return t.AddDate(0, 1, 1-t.Day()).Truncate(time.Hour * 24)
}
func addDay(t time.Time) time.Time {
return t.AddDate(0, 0, 1).Truncate(time.Hour * 24)
}
func addHour(t time.Time) time.Time {
return t.Add(time.Hour).Truncate(time.Hour)
}
func addMinute(t time.Time) time.Time {
return t.Add(time.Minute).Truncate(time.Minute)
}
func addSecond(t time.Time) time.Time {
return t.Add(time.Second).Truncate(time.Second)
} | match/next.go | 0.736401 | 0.652449 | next.go | starcoder |
package bin
import (
"bytes"
"encoding/binary"
"io"
"reflect"
"strconv"
"github.com/dyrkin/bin/util"
)
type decoder struct {
buf *bytes.Buffer
}
//Decode struct from byte array
func Decode(payload []byte, response interface{}) {
value := reflect.ValueOf(response)
decoder := &decoder{bytes.NewBuffer(payload)}
decoder.decode(value)
}
func (d *decoder) decode(value reflect.Value) {
switch value.Kind() {
case reflect.Ptr:
d.pointer(value)
case reflect.Struct:
d.strukt(value)
}
}
func deserialize(value reflect.Value, r io.Reader) {
value.MethodByName("Deserialize").Call([]reflect.Value{reflect.ValueOf(r)})
}
func (d *decoder) pointer(value reflect.Value) {
if value.IsNil() {
element := reflect.New(value.Type().Elem())
if value.CanSet() {
value.Set(element)
}
}
if value.Type().Implements(serializable) {
deserialize(value, d.buf)
} else {
d.decode(value.Elem())
}
}
func (d *decoder) strukt(value reflect.Value) {
var bitmaskBytes uint64
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
fieldType := value.Type().Field(i)
tags := tags(fieldType.Tag)
if !(tags.transient() == "true") && checkConditions(tags.cond(), value) {
switch field.Kind() {
case reflect.Ptr:
d.pointer(field)
case reflect.String:
d.string(field, tags)
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
d.uint(field, tags, &bitmaskBytes)
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
d.int(field, tags)
case reflect.Array:
d.array(field, tags)
case reflect.Slice:
d.slice(value, field, tags)
}
}
}
}
func (d *decoder) slice(parent reflect.Value, value reflect.Value, tags tags) {
if tags.size().nonEmpty() {
length := d.dynamicLength(tags)
value.Set(reflect.MakeSlice(value.Type(), length, length))
for i := 0; i < length; i++ {
sliceElement := value.Index(i)
switch sliceElement.Kind() {
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
d.uint(sliceElement, tags, nil)
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
d.int(sliceElement, tags)
case reflect.String:
d.string(sliceElement, tags)
case reflect.Ptr:
d.pointer(sliceElement)
case reflect.Struct:
d.strukt(sliceElement)
}
}
} else {
value.Set(reflect.MakeSlice(value.Type(), 0, 0))
for {
if d.buf.Len() == 0 {
return
}
sliceElement := reflect.New(value.Type().Elem()).Elem()
switch sliceElement.Kind() {
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
d.uint(sliceElement, tags, nil)
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
d.int(sliceElement, tags)
case reflect.String:
d.string(sliceElement, tags)
case reflect.Ptr:
d.pointer(sliceElement)
case reflect.Struct:
d.strukt(sliceElement)
}
value.Set(reflect.Append(value, sliceElement))
}
}
}
func (d *decoder) array(value reflect.Value, tags tags) {
if value.Len() > 0 {
size := int(value.Index(0).Type().Size())
for i := 0; i < value.Len(); i++ {
arrayElem := value.Index(i)
v := d.readUint(tags.endianness(), size)
arrayElem.SetUint(v)
}
}
}
func (d *decoder) uint(value reflect.Value, tags tags, bitmaskBytes *uint64) {
if value.CanAddr() {
if tags.bits().nonEmpty() {
if tags.bitmask() == "start" {
*bitmaskBytes = d.readUint(tags.endianness(), int(value.Type().Size()))
}
bitmaskBits := bitmaskBits(tags.bits())
pos := util.FirstBitPosition(bitmaskBits)
v := (*bitmaskBytes & bitmaskBits) >> pos
value.SetUint(v)
} else if tags.bound().nonEmpty() {
size, _ := strconv.Atoi(string(tags.bound()))
v := d.readUint(tags.endianness(), size)
value.SetUint(v)
} else {
v := d.readUint(tags.endianness(), int(value.Type().Size()))
value.SetUint(v)
}
} else {
panic("Unaddressable uint value")
}
}
func (d *decoder) int(value reflect.Value, tags tags) {
if value.CanAddr() {
if tags.bound().nonEmpty() {
size, _ := strconv.Atoi(string(tags.bound()))
v := d.readInt(tags.endianness(), size)
value.SetInt(v)
} else {
v := d.readInt(tags.endianness(), int(value.Type().Size()))
value.SetInt(v)
}
} else {
panic("Unaddressable uint value")
}
}
func (d *decoder) string(value reflect.Value, tags tags) {
if tags.hex().nonEmpty() {
size, _ := strconv.Atoi(string(tags.hex()))
v := d.readUint(tags.endianness(), size)
hexString, _ := util.UintToHexString(v, size)
value.SetString(hexString)
} else {
length := d.dynamicLength(tags)
b := make([]uint8, length, length)
d.read(tags.endianness(), b)
value.SetString(string(b))
}
}
func (d *decoder) dynamicLength(tags tags) int {
if tags.size().nonEmpty() {
size, _ := strconv.Atoi(string(tags.size()))
return int(d.readUint(tags.endianness(), size))
}
return len(d.buf.Bytes())
}
func (d *decoder) read(endianness tag, v interface{}) {
binary.Read(d.buf, order(endianness), v)
}
func (d *decoder) readUint(endianness tag, size int) uint64 {
var v uint64
if endianness == "be" {
for i := 0; i < size; i++ {
t, _ := d.buf.ReadByte()
v = v | uint64(t)<<byte((size-i-1)*8)
}
} else {
for i := 0; i < size; i++ {
t, _ := d.buf.ReadByte()
v = v | uint64(t)<<byte(i*8)
}
}
return v
}
func (d *decoder) readInt(endianness tag, size int) int64 {
var v int64
buf := make([]uint8, size)
d.buf.Read(buf)
if endianness == "be" {
for i := 0; i < size; i++ {
t := buf[i]
if i == 0 {
v = v | int64(int8(t))<<byte((size-i-1)*8)
} else {
v = v | int64(t)<<byte((size-i-1)*8)
}
}
} else {
for i := 0; i < size; i++ {
t := buf[i]
if i != 0 {
v = v | int64(int8(t))<<byte(i*8)
} else {
v = v | int64(t)<<byte(i*8)
}
}
}
return v
} | decoder.go | 0.535098 | 0.432423 | decoder.go | starcoder |
package plot
import (
"fmt"
"math"
"time"
)
const (
_ = iota
// ConsolidateAverage represents an average consolidation type.
ConsolidateAverage
// ConsolidateLast represents a last value consolidation type.
ConsolidateLast
// ConsolidateMax represents a maximal value consolidation type.
ConsolidateMax
// ConsolidateMin represents a minimal value consolidation type.
ConsolidateMin
// ConsolidateSum represents a sum consolidation type.
ConsolidateSum
)
const (
_ = iota
// OperTypeNone represents a null operation group mode.
OperTypeNone
// OperTypeAverage represents a AVG operation group mode.
OperTypeAverage
// OperTypeSum represents a SUM operation group mode.
OperTypeSum
// OperTypeNormalize represents a NORMALIZE operation group mode.
OperTypeNormalize
)
type plotBucket struct {
startTime time.Time
plots []Plot
}
// Consolidate consolidates plots buckets based on consolidation function.
func (bucket plotBucket) Consolidate(consolidationType int) Plot {
consolidatedPlot := Plot{
Value: Value(math.NaN()),
Time: bucket.startTime,
}
bucketCount := len(bucket.plots)
if bucketCount == 0 {
return consolidatedPlot
}
switch consolidationType {
case ConsolidateAverage:
sum := 0.0
sumCount := 0
for _, plot := range bucket.plots {
if plot.Value.IsNaN() {
continue
}
sum += float64(plot.Value)
sumCount++
}
if sumCount > 0 {
consolidatedPlot.Value = Value(sum / float64(sumCount))
}
if bucketCount == 1 {
consolidatedPlot.Time = bucket.plots[0].Time
} else {
// Interpolate median time
consolidatedPlot.Time = bucket.plots[0].Time.Add(bucket.plots[bucketCount-1].Time.
Sub(bucket.plots[0].Time) / 2)
}
case ConsolidateSum:
sum := 0.0
sumCount := 0
for _, plot := range bucket.plots {
if plot.Value.IsNaN() {
continue
}
sum += float64(plot.Value)
sumCount++
}
if sumCount > 0 {
consolidatedPlot.Value = Value(sum)
}
consolidatedPlot.Time = bucket.plots[bucketCount-1].Time
case ConsolidateLast:
consolidatedPlot = bucket.plots[bucketCount-1]
case ConsolidateMax:
for _, plot := range bucket.plots {
if !plot.Value.IsNaN() && plot.Value > consolidatedPlot.Value || consolidatedPlot.Value.IsNaN() {
consolidatedPlot = plot
}
}
case ConsolidateMin:
for _, plot := range bucket.plots {
if !plot.Value.IsNaN() && plot.Value < consolidatedPlot.Value || consolidatedPlot.Value.IsNaN() {
consolidatedPlot = plot
}
}
}
return consolidatedPlot
}
// Normalize aligns multiple plot series on a common time step, consolidates plots samples if necessary.
func Normalize(seriesList []Series, startTime, endTime time.Time, sample int, consolidationType int) ([]Series, error) {
if sample == 0 {
return nil, fmt.Errorf("sample must be greater than zero")
}
seriesCount := len(seriesList)
if seriesCount == 0 {
return nil, fmt.Errorf("no series provided")
}
normalizedSeries := make([]Series, seriesCount)
buckets := make([][]plotBucket, seriesCount)
// Override sample to max series length if smaller than requested
maxLength := 0
for _, series := range seriesList {
seriesLength := len(series.Plots)
if seriesLength > maxLength {
maxLength = seriesLength
}
}
if maxLength > 0 && maxLength < sample {
sample = maxLength
}
// Calculate the common step for all series based on time specs and requested sampling
step := endTime.Sub(startTime) / time.Duration(sample)
// Store each series' plots into the proper time step plot buckets,
// then consolidate each series plots buckets according to consolidation function
for seriesIndex, series := range seriesList {
buckets[seriesIndex] = make([]plotBucket, sample)
// Initialize time step plot buckets
for stepIndex := 0; stepIndex < sample; stepIndex++ {
buckets[seriesIndex][stepIndex] = plotBucket{
startTime: startTime.Add(time.Duration(stepIndex) * step),
plots: make([]Plot, 0),
}
}
// Dispatch series plots in the right time plot bucket
for _, plot := range series.Plots {
// Discard series plots out of time specs range
if plot.Time.Before(startTime) || plot.Time.After(endTime) {
continue
}
plotIndex := int64(float64(plot.Time.UnixNano()-startTime.UnixNano())/float64(step.Nanoseconds())+1) - 1
if plotIndex >= int64(sample) {
continue
}
buckets[seriesIndex][plotIndex].plots = append(buckets[seriesIndex][plotIndex].plots, plot)
}
normalizedSeries[seriesIndex] = Series{
Name: seriesList[seriesIndex].Name,
Step: int(step.Seconds()),
Plots: make([]Plot, sample),
Summary: make(map[string]Value),
}
seriesLength := len(series.Plots)
plotRatio := sample / seriesLength
plotCount := 0
plotLast := Value(math.NaN())
// Consolidate each series' plot buckets
for bucketIndex := range buckets[seriesIndex] {
normalizedSeries[seriesIndex].Plots[bucketIndex] = buckets[seriesIndex][bucketIndex].
Consolidate(consolidationType)
if seriesCount == 1 {
continue
}
plot := &normalizedSeries[seriesIndex].Plots[bucketIndex]
// Align consolidated plots timestamps among normalized series lists
plot.Time = buckets[seriesIndex][bucketIndex].startTime.Add(
time.Duration(step.Seconds() * float64(bucketIndex)),
).Round(time.Second)
if plotRatio <= 1 {
continue
}
// Interpolate missing plots values
if !plot.Value.IsNaN() {
if plotCount <= plotRatio && !plotLast.IsNaN() {
plotChunk := (plot.Value - plotLast) / Value(plotCount+1)
for plotIndex := bucketIndex - plotCount; plotIndex < bucketIndex; plotIndex++ {
normalizedSeries[seriesIndex].Plots[plotIndex].Value = plotLast +
Value(plotCount-(bucketIndex-plotIndex)+1)*plotChunk
}
}
plotLast = plot.Value
plotCount = 0
} else {
plotCount++
}
}
}
return normalizedSeries, nil
}
// AverageSeries returns a new series averaging each series' datapoints.
func AverageSeries(seriesList []Series) (Series, error) {
return operSeries(seriesList, OperTypeAverage)
}
// SumSeries add series plots together and return the sum at each datapoint.
func SumSeries(seriesList []Series) (Series, error) {
return operSeries(seriesList, OperTypeSum)
}
func operSeries(seriesList []Series, operType int) (Series, error) {
nSeries := len(seriesList)
if nSeries == 0 {
return Series{}, fmt.Errorf("no series provided")
}
plotsCount := len(seriesList[0].Plots)
operSeries := Series{
Plots: make([]Plot, plotsCount),
Summary: make(map[string]Value),
}
for plotIndex := 0; plotIndex < plotsCount; plotIndex++ {
operSeries.Plots[plotIndex].Time = seriesList[0].Plots[plotIndex].Time
sumCount := 0
for _, series := range seriesList {
if series.Plots[plotIndex].Value.IsNaN() {
continue
}
operSeries.Plots[plotIndex].Value += series.Plots[plotIndex].Value
sumCount++
}
if sumCount == 0 {
operSeries.Plots[plotIndex].Value = Value(math.NaN())
} else if operType == OperTypeAverage {
operSeries.Plots[plotIndex].Value /= Value(sumCount)
}
}
return operSeries, nil
}
func gcd(a, b int) int {
if a <= 0 || b <= 0 {
return 0
}
c := a % b
if c == 0 {
return b
}
return gcd(b, c)
}
func lcm(a, b int) int {
return a * b / gcd(a, b)
} | pkg/plot/func.go | 0.86923 | 0.538073 | func.go | starcoder |
package spin
// Sizing from
// https://github.com/preble/pyprocgame/blob/master/procgame/modes/scoredisplay.py#L104
func singlePlayerPanel(e *ScriptEnv, r Renderer) {
g := r.Graphics()
player := GetPlayerVars(e)
switch {
case player.Score < 1_000_000_000:
g.Font = Font18x12
case player.Score < 10_000_000_000:
g.Font = Font18x11
default:
g.Font = Font18x10
}
g.Y = 3
r.Print(g, FormatScore("%d", player.Score))
}
func multiPlayerPanel(e *ScriptEnv, r Renderer) {
g := r.Graphics()
game := GetGameVars(e)
sizedFont := func(active bool, score int) string {
//active := game.Player == playerNum
//score := GetPlayerVarsFor(e, playerNum).Score
switch {
case active && score < 10_000_000:
return Font14x10
case active && score < 100_000_000:
return Font14x9
case active:
return Font14x8
case score < 10_000_000:
return Font09x7
case score < 10_000_000:
return Font09x6
default:
return Font09x5
}
}
g.X, g.Y = 0, 0
g.AnchorX = AnchorLeft
score := GetPlayerVarsFor(e, 1).Score
g.Font = sizedFont(game.Player == 1, score)
r.Print(g, FormatScore("%d", score))
g.X, g.Y = r.Width()+1, 0
g.AnchorX = AnchorRight
score = GetPlayerVarsFor(e, 2).Score
g.Font = sizedFont(game.Player == 2, score)
score = GetPlayerVarsFor(e, 2).Score
r.Print(g, FormatScore("%d", score))
if game.NumPlayers >= 3 {
g.X, g.Y = 0, r.Height()-6
g.AnchorX = AnchorLeft
g.AnchorY = AnchorBottom
score = GetPlayerVarsFor(e, 3).Score
g.Font = sizedFont(game.Player == 3, score)
r.Print(g, FormatScore("%d", score))
}
if game.NumPlayers == 4 {
g.X, g.Y = r.Width(), r.Height()-6
g.AnchorX = AnchorRight
g.AnchorY = AnchorBottom
score = GetPlayerVarsFor(e, 4).Score
g.Font = sizedFont(game.Player == 4, score)
r.Print(g, FormatScore("%d", score))
}
}
func ScorePanel(e *ScriptEnv, r Renderer) {
g := r.Graphics()
game := GetGameVars(e)
r.Fill(ColorOff)
if game.NumPlayers <= 1 {
singlePlayerPanel(e, r)
} else if game.NumPlayers > 1 {
multiPlayerPanel(e, r)
}
g.Font = Font04B_03_7px
g.AnchorX = AnchorLeft
g.X, g.Y = 25, r.Height()-5
r.Print(g, "BALL %v", game.Ball)
g.X = 75
r.Print(g, "FREE PLAY")
} | panels.go | 0.688468 | 0.417093 | panels.go | starcoder |
package predicate
import (
"github.com/searKing/golang/go/error/exception"
"github.com/searKing/golang/go/util/class"
"github.com/searKing/golang/go/util/object"
)
/**
* Represents a predicate (boolean-valued function) of one argument.
*/
type Predicater interface {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
Test(value interface{}) bool
/**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
And(other Predicater) Predicater
/**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/
Negate() Predicater
/**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
Or(other Predicater) Predicater
/**
* Returns a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}.
*
* @param <T> the type of arguments to the predicate
* @param targetRef the object reference with which to compare for equality,
* which may be {@code null}
* @return a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}
*/
IsEqual(targetRef interface{}) Predicater
}
type PredicaterFunc func(value interface{}) bool
func (f PredicaterFunc) Test(value interface{}) bool {
return f(value)
}
func (f PredicaterFunc) And(other Predicater) Predicater {
object.RequireNonNil(other)
return PredicaterFunc(func(value interface{}) bool {
return f.Test(value) && other.Test(value)
})
}
func (f PredicaterFunc) Negate() Predicater {
return PredicaterFunc(func(value interface{}) bool {
return !f.Test(value)
})
}
func (f PredicaterFunc) Or(other Predicater) Predicater {
object.RequireNonNil(other)
return PredicaterFunc(func(value interface{}) bool {
return f.Test(value) || other.Test(value)
})
}
func (f PredicaterFunc) IsEqual(targetRef interface{}) Predicater {
if targetRef == nil {
return PredicaterFunc(object.IsNil)
}
return PredicaterFunc(func(value interface{}) bool {
return value == targetRef
})
}
type AbstractPredicaterClass struct {
class.Class
}
func (pred *AbstractPredicaterClass) Test(value interface{}) bool {
panic(exception.NewIllegalStateException1("called wrong Test method"))
}
func (pred *AbstractPredicaterClass) And(other Predicater) Predicater {
return PredicaterFunc(func(value interface{}) bool {
return pred.GetDerivedElse(pred).(Predicater).Test(value) && other.Test(value)
})
}
func (pred *AbstractPredicaterClass) Negate() Predicater {
return PredicaterFunc(func(value interface{}) bool {
return !pred.GetDerivedElse(pred).(Predicater).Test(value)
})
}
func (pred *AbstractPredicaterClass) Or(other Predicater) Predicater {
object.RequireNonNil(other)
return PredicaterFunc(func(value interface{}) bool {
return pred.GetDerivedElse(pred).(Predicater).Test(value) || other.Test(value)
})
}
func (pred *AbstractPredicaterClass) IsEqual(targetRef interface{}) Predicater {
if targetRef == nil {
return PredicaterFunc(object.IsNil)
}
return PredicaterFunc(func(value interface{}) bool {
return value == targetRef
})
} | go/util/function/predicate/predicate.go | 0.890157 | 0.500244 | predicate.go | starcoder |
package main
type Version string
// From rpmio/rpmvercmp.c
// https://github.com/rpm-software-management/rpm/blob/master/rpmio/rpmvercmp.c
/* compare alpha and numeric segments of two versions */
/* return 1: a is newer than b */
/* 0: a and b are the same version */
/* -1: b is newer than a */
func (a Version) RpmVerCmp(b Version) int {
/* easy comparison to see if versions are identical */
if a == b {
return 0
}
// From rpmio/rpmstring.h
// https://github.com/rpm-software-management/rpm/blob/master/rpmio/rpmstring.h
rislower := func(c rune) bool { return c >= 'a' && c <= 'z' }
risupper := func(c rune) bool { return c >= 'A' && c <= 'Z' }
risalpha := func(c rune) bool { return rislower(c) || risupper(c) }
risdigit := func(c rune) bool { return c >= '0' && c <= '9' }
risalnum := func(c rune) bool { return risalpha(c) || risdigit(c) }
abuf, bbuf := append([]rune(a), 0), append([]rune(b), 0)
str1, str2 := 0, 0
one, two := str1, str2
/* loop through each version segment of str1 and str2 and compare them */
for abuf[one] != 0 || bbuf[two] != 0 {
for abuf[one] != 0 && !risalnum(abuf[one]) && abuf[one] != '~' && abuf[one] != '^' {
one++
}
for bbuf[two] != 0 && !risalnum(bbuf[two]) && bbuf[two] != '~' && bbuf[two] != '^' {
two++
}
/* handle the tilde separator, it sorts before everything else */
if abuf[one] == '~' || bbuf[two] == '~' {
if abuf[one] != '~' {
return 1
}
if bbuf[two] != '~' {
return -1
}
one++
two++
continue
}
/*
* Handle caret separator. Concept is the same as tilde,
* except that if one of the strings ends (base version),
* the other is considered as higher version.
*/
if abuf[one] == '^' || bbuf[two] == '^' {
if abuf[one] == 0 {
return -1
}
if bbuf[two] == 0 {
return 1
}
if abuf[one] != '^' {
return 1
}
if bbuf[two] != '^' {
return -1
}
one++
two++
continue
}
/* If we ran to the end of either, we are finished with the loop */
if abuf[one] == 0 || bbuf[two] == 0 {
break
}
str1 = one
str2 = two
/* grab first completely alpha or completely numeric segment */
/* leave one and two pointing to the start of the alpha or numeric */
/* segment and walk str1 and str2 to end of segment */
var isnum bool
if risdigit(abuf[str1]) {
for risdigit(abuf[str1]) {
str1++
}
for risdigit(bbuf[str2]) {
str2++
}
isnum = true
} else {
for risalpha(abuf[str1]) {
str1++
}
for risalpha(bbuf[str2]) {
str2++
}
isnum = false
}
/* take care of the case where the two version segments are */
/* different types: one numeric, the other alpha (i.e. empty) */
/* numeric segments are always newer than alpha segments */
/* XXX See patch #60884 (and details) from bugzilla #50977. */
if two == str2 {
if isnum {
return 1
} else {
return -1
}
}
if isnum {
/* this used to be done by converting the digit segments */
/* to ints using atoi() - it's changed because long */
/* digit segments can overflow an int - this should fix that. */
/* throw away any leading zeros - it's a number, right? */
for abuf[one] == '0' {
one++
}
for bbuf[two] == '0' {
two++
}
/* whichever number has more digits wins */
onelen := str1 - one
twolen := str2 - two
if onelen > twolen {
return 1
}
if twolen > onelen {
return -1
}
}
/* strcmp will return which one is greater - even if the two */
/* segments are alpha or if they are numeric. don't return */
/* if they are equal because there might be more segments to */
/* compare */
if string(abuf[one:str1]) < string(bbuf[two:str2]) {
return -1
}
if string(abuf[one:str1]) > string(bbuf[two:str2]) {
return 1
}
one = str1
two = str2
}
/* this catches the case where all numeric and alpha segments have */
/* compared identically but the segment sepparating characters were */
/* different */
if abuf[one] == 0 && bbuf[two] == 0 {
return 0
}
/* whichever version still has characters left over wins */
if abuf[one] == 0 {
return -1
} else {
return 1
}
} | web/rpmvercmp.go | 0.713032 | 0.400749 | rpmvercmp.go | starcoder |
package db
import (
"reflect"
"time"
"github.com/upper/db/v4/internal/adapter"
)
// Comparison represents a relationship between values.
type Comparison struct {
*adapter.Comparison
}
// Gte is a comparison that means: is greater than or equal to value.
func Gte(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorGreaterThanOrEqualTo, value)}
}
// Lte is a comparison that means: is less than or equal to value.
func Lte(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorLessThanOrEqualTo, value)}
}
// Eq is a comparison that means: is equal to value.
func Eq(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorEqual, value)}
}
// NotEq is a comparison that means: is not equal to value.
func NotEq(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorNotEqual, value)}
}
// Gt is a comparison that means: is greater than value.
func Gt(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorGreaterThan, value)}
}
// Lt is a comparison that means: is less than value.
func Lt(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorLessThan, value)}
}
// In is a comparison that means: is any of the values.
func In(value ...interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorIn, toInterfaceArray(value))}
}
// AnyOf is a comparison that means: is any of the values of the slice.
func AnyOf(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorIn, toInterfaceArray(value))}
}
// NotIn is a comparison that means: is none of the values.
func NotIn(value ...interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorNotIn, toInterfaceArray(value))}
}
// NotAnyOf is a comparison that means: is none of the values of the slice.
func NotAnyOf(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorNotIn, toInterfaceArray(value))}
}
// After is a comparison that means: is after the (time.Time) value.
func After(value time.Time) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorGreaterThan, value)}
}
// Before is a comparison that means: is before the (time.Time) value.
func Before(value time.Time) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorLessThan, value)}
}
// OnOrAfter is a comparison that means: is on or after the (time.Time) value.
func OnOrAfter(value time.Time) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorGreaterThanOrEqualTo, value)}
}
// OnOrBefore is a comparison that means: is on or before the (time.Time) value.
func OnOrBefore(value time.Time) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorLessThanOrEqualTo, value)}
}
// Between is a comparison that means: is between lowerBound and upperBound.
func Between(lowerBound interface{}, upperBound interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorBetween, []interface{}{lowerBound, upperBound})}
}
// NotBetween is a comparison that means: is not between lowerBound and upperBound.
func NotBetween(lowerBound interface{}, upperBound interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorNotBetween, []interface{}{lowerBound, upperBound})}
}
// Is is a comparison that means: is equivalent to nil, true or false.
func Is(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorIs, value)}
}
// IsNot is a comparison that means: is not equivalent to nil, true nor false.
func IsNot(value interface{}) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorIsNot, value)}
}
// IsNull is a comparison that means: is equivalent to nil.
func IsNull() *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorIs, nil)}
}
// IsNotNull is a comparison that means: is not equivalent to nil.
func IsNotNull() *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorIsNot, nil)}
}
// Like is a comparison that checks whether the reference matches the wildcard
// value.
func Like(value string) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorLike, value)}
}
// NotLike is a comparison that checks whether the reference does not match the
// wildcard value.
func NotLike(value string) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorNotLike, value)}
}
// RegExp is a comparison that checks whether the reference matches the regular
// expression.
func RegExp(value string) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorRegExp, value)}
}
// NotRegExp is a comparison that checks whether the reference does not match
// the regular expression.
func NotRegExp(value string) *Comparison {
return &Comparison{adapter.NewComparisonOperator(adapter.ComparisonOperatorNotRegExp, value)}
}
// Op returns a custom comparison operator.
func Op(customOperator string, value interface{}) *Comparison {
return &Comparison{adapter.NewCustomComparisonOperator(customOperator, value)}
}
func toInterfaceArray(value interface{}) []interface{} {
rv := reflect.ValueOf(value)
switch rv.Type().Kind() {
case reflect.Ptr:
return toInterfaceArray(rv.Elem().Interface())
case reflect.Slice:
elems := rv.Len()
args := make([]interface{}, elems)
for i := 0; i < elems; i++ {
args[i] = rv.Index(i).Interface()
}
return args
}
return []interface{}{value}
} | comparison.go | 0.840979 | 0.502441 | comparison.go | starcoder |
package main
import (
"fmt"
"github.com/gtfierro/xboswave/ingester/types"
xbospb "github.com/gtfierro/xboswave/proto"
"strings"
)
var lookup = map[string]func(msg xbospb.XBOS) float64{
"uptime": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.Uptime)
},
"acc_x": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.AccX)
},
"acc_y": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.AccY)
},
"acc_z": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.AccZ)
},
"mag_x": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.MagX)
},
"mag_y": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.MagY)
},
"mag_z": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.MagZ)
},
"air_temp": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.AirTemp)
},
"air_hum": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.AirHum)
},
"air_rh": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.AirRh)
},
"light_lux": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.LightLux)
},
"buttons": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.Buttons)
},
"occupancy": func(msg xbospb.XBOS) float64 {
return float64(msg.HamiltonData.H3C.Occupancy)
},
}
func build(uri types.SubscriptionURI, name string, msg xbospb.XBOS) types.ExtractedTimeseries {
value := lookup[name](msg)
var extracted types.ExtractedTimeseries
time := int64(msg.HamiltonData.Time)
extracted.Values = append(extracted.Values, value)
extracted.Times = append(extracted.Times, time)
extracted.UUID = types.GenerateUUID(uri, []byte(name))
parts := strings.Split(uri.Resource, "/")
extracted.Collection = fmt.Sprintf("hamilton/%s/%s", name, parts[2]) //uri.Resource
extracted.Tags = map[string]string{
"unit": "seconds",
"name": name,
}
return extracted
}
func Extract(uri types.SubscriptionURI, msg xbospb.XBOS, add func(types.ExtractedTimeseries) error) error {
if msg.HamiltonData != nil {
for name := range lookup {
extracted := build(uri, name, msg)
if err := add(extracted); err != nil {
return err
}
}
}
return nil
} | ingester/plugins/hamilton1.go | 0.544559 | 0.565179 | hamilton1.go | starcoder |
package vesper
import (
"math"
"math/rand"
"strconv"
)
const epsilon = 0.000000001
// Zero is the Vesper 0 value
var Zero = Number(0)
// One is the Vesper 1 value
var One = Number(1)
// MinusOne is the Vesper -1 value
var MinusOne = Number(-1)
// Number - create a Number object for the given value
func Number(f float64) *Object {
return &Object{
Type: NumberType,
fval: f,
}
}
// Int converts an integer to a vector Number
func Int(n int64) *Object {
return Number(float64(n))
}
// Round - return the closest integer value to the float value
func Round(f float64) float64 {
if f > 0 {
return math.Floor(f + 0.5)
}
return math.Ceil(f - 0.5)
}
// ToNumber - convert object to a number, if possible
func ToNumber(o *Object) (*Object, error) {
switch o.Type {
case NumberType:
return o, nil
case CharacterType:
return Number(o.fval), nil
case BooleanType:
return Number(o.fval), nil
case StringType:
f, err := strconv.ParseFloat(o.text, 64)
if err == nil {
return Number(f), nil
}
}
return nil, Error(ArgumentErrorKey, "cannot convert to an number: ", o)
}
// ToInt - convert the object to an integer number, if possible
func ToInt(o *Object) (*Object, error) {
switch o.Type {
case NumberType:
return Number(Round(o.fval)), nil
case CharacterType:
return Number(o.fval), nil
case BooleanType:
return Number(o.fval), nil
case StringType:
n, err := strconv.ParseInt(o.text, 10, 64)
if err == nil {
return Number(float64(n)), nil
}
}
return nil, Error(ArgumentErrorKey, "cannot convert to an integer: ", o)
}
// IsInt returns true if the object is an integer
func IsInt(obj *Object) bool {
if obj.Type == NumberType {
f := obj.fval
return math.Trunc(f) == f
}
return false
}
// IsFloat returns true if the object is a float
func IsFloat(obj *Object) bool {
if obj.Type == NumberType {
return !IsInt(obj)
}
return false
}
// AsFloat64Value returns the floating point value of the object
func AsFloat64Value(obj *Object) (float64, error) {
if obj.Type == NumberType {
return obj.fval, nil
}
return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type)
}
// AsInt64Value returns the int64 value of the object
func AsInt64Value(obj *Object) (int64, error) {
if obj.Type == NumberType {
return int64(obj.fval), nil
}
return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type)
}
// AsIntValue returns the int value of the object
func AsIntValue(obj *Object) (int, error) {
if obj.Type == NumberType {
return int(obj.fval), nil
}
return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type)
}
// AsByteValue returns the value of the object as a byte
func AsByteValue(obj *Object) (byte, error) {
if obj.Type == NumberType {
return byte(obj.fval), nil
}
return 0, Error(ArgumentErrorKey, "Expected a <number>, got a ", obj.Type)
}
// NumberEqual returns true if the object is equal to the argument, within epsilon
func NumberEqual(f1 float64, f2 float64) bool {
return f1 == f2 || math.Abs(f1-f2) < epsilon
}
var randomGenerator = rand.New(rand.NewSource(1))
// RandomSeed seeds the random number generator with the given seed value
func RandomSeed(n int64) {
randomGenerator = rand.New(rand.NewSource(n))
}
// Random returns a random value within the given range
func Random(min float64, max float64) *Object {
return Number(min + (randomGenerator.Float64() * (max - min)))
}
// RandomList returns a list of random numbers with the given size and range
func RandomList(size int, min float64, max float64) *Object {
result := EmptyList
tail := EmptyList
for i := 0; i < size; i++ {
tmp := List(Random(min, max))
if result == EmptyList {
result = tmp
tail = tmp
} else {
tail.cdr = tmp
tail = tmp
}
}
return result
} | number.go | 0.716417 | 0.516169 | number.go | starcoder |
package studio
import (
"github.com/chewxy/math32"
)
func (v *Vec3) VectorLength() float32 {
return math32.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])
}
func (v *Vec3) VectorNormalize() float32 {
length := v.VectorLength()
if length > 0.0 {
ilength := 1 / length
v[0] *= ilength
v[1] *= ilength
v[2] *= ilength
}
return length
}
func (v1 *Vec3) VectorCompare(v2 *Vec3) bool {
if v1[0] != v2[0] || v1[1] != v2[1] || v1[2] != v2[2] {
return false
}
return true
}
func (v1 *Vec3) DotProduct(v2 *Vec3) float32 {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}
func (v1 *Vec3) DotProductV4(v2 [4]float32) float32 {
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]
}
func (v1 *Vec3) CrossProduct(v2 *Vec3, cross *Vec3) {
cross[0] = v1[1]*v2[2] - v1[2]*v2[1]
cross[1] = v1[2]*v2[0] - v1[0]*v2[2]
cross[2] = v1[0]*v2[1] - v1[1]*v2[0]
}
func (in1 *Vec3) VectorTransform(in2 *Mat34, out *Vec3) {
out[0] = in1.DotProductV4(in2[0]) + in2[0][3]
out[1] = in1.DotProductV4(in2[1]) + in2[1][3]
out[2] = in1.DotProductV4(in2[2]) + in2[2][3]
}
// rotate by the inverse of the matrix
func (in1 *Vec3) VectorIRotate(in2 *Mat34, out *Vec3) {
out[0] = in1[0]*in2[0][0] + in1[1]*in2[1][0] + in1[2]*in2[2][0]
out[1] = in1[0]*in2[0][1] + in1[1]*in2[1][1] + in1[2]*in2[2][1]
out[2] = in1[0]*in2[0][2] + in1[1]*in2[1][2] + in1[2]*in2[2][2]
}
func (in *Vec3) VectorScale(scale float32, out *Vec3) {
out[0] = in[0] * scale
out[1] = in[1] * scale
out[2] = in[2] * scale
}
func (in1 *Mat34) ConcatTransforms(in2 *Mat34, out *Mat34) {
out[0][0] = in1[0][0]*in2[0][0] + in1[0][1]*in2[1][0] +
in1[0][2]*in2[2][0]
out[0][1] = in1[0][0]*in2[0][1] + in1[0][1]*in2[1][1] +
in1[0][2]*in2[2][1]
out[0][2] = in1[0][0]*in2[0][2] + in1[0][1]*in2[1][2] +
in1[0][2]*in2[2][2]
out[0][3] = in1[0][0]*in2[0][3] + in1[0][1]*in2[1][3] +
in1[0][2]*in2[2][3] + in1[0][3]
out[1][0] = in1[1][0]*in2[0][0] + in1[1][1]*in2[1][0] +
in1[1][2]*in2[2][0]
out[1][1] = in1[1][0]*in2[0][1] + in1[1][1]*in2[1][1] +
in1[1][2]*in2[2][1]
out[1][2] = in1[1][0]*in2[0][2] + in1[1][1]*in2[1][2] +
in1[1][2]*in2[2][2]
out[1][3] = in1[1][0]*in2[0][3] + in1[1][1]*in2[1][3] +
in1[1][2]*in2[2][3] + in1[1][3]
out[2][0] = in1[2][0]*in2[0][0] + in1[2][1]*in2[1][0] +
in1[2][2]*in2[2][0]
out[2][1] = in1[2][0]*in2[0][1] + in1[2][1]*in2[1][1] +
in1[2][2]*in2[2][1]
out[2][2] = in1[2][0]*in2[0][2] + in1[2][1]*in2[1][2] +
in1[2][2]*in2[2][2]
out[2][3] = in1[2][0]*in2[0][3] + in1[2][1]*in2[1][3] +
in1[2][2]*in2[2][3] + in1[2][3]
}
func (qt *Vec4) QuaternionMatrix(mat *Mat34) {
mat[0][0] = 1.0 - 2.0*qt[1]*qt[1] - 2.0*qt[2]*qt[2]
mat[1][0] = 2.0*qt[0]*qt[1] + 2.0*qt[3]*qt[2]
mat[2][0] = 2.0*qt[0]*qt[2] - 2.0*qt[3]*qt[1]
mat[0][1] = 2.0*qt[0]*qt[1] - 2.0*qt[3]*qt[2]
mat[1][1] = 1.0 - 2.0*qt[0]*qt[0] - 2.0*qt[2]*qt[2]
mat[2][1] = 2.0*qt[1]*qt[2] + 2.0*qt[3]*qt[0]
mat[0][2] = 2.0*qt[0]*qt[2] + 2.0*qt[3]*qt[1]
mat[1][2] = 2.0*qt[1]*qt[2] - 2.0*qt[3]*qt[0]
mat[2][2] = 1.0 - 2.0*qt[0]*qt[0] - 2.0*qt[1]*qt[1]
}
func (p *Vec4) QuaternionSlerp(q Vec4, t float32, qt *Vec4) {
// decide if one of the quaternions is backwards
var a, b float32 = 0, 0
for i := 0; i < 4; i++ {
a += (p[i] - q[i]) * (p[i] - q[i])
b += (p[i] + q[i]) * (p[i] + q[i])
}
if a > b {
for i := 0; i < 4; i++ {
q[i] = -q[i]
}
}
var omega, cosom, sinom, sclp, sclq float32
cosom = p[0]*q[0] + p[1]*q[1] + p[2]*q[2] + p[3]*q[3]
if (1.0 + cosom) > 0.000001 {
if (1.0 - cosom) > 0.000001 {
omega = math32.Acos(cosom)
sinom = math32.Sin(omega)
sclp = math32.Sin((1.0-t)*omega) / sinom
sclq = math32.Sin(t*omega) / sinom
} else {
sclp = 1.0 - t
sclq = t
}
for i := 0; i < 4; i++ {
qt[i] = sclp*p[i] + sclq*q[i]
}
} else {
qt[0] = -q[1]
qt[1] = q[0]
qt[2] = -q[3]
qt[3] = q[2]
sclp = math32.Sin((1.0 - t) * (0.5 * math32.Pi))
sclq = math32.Sin(t * (0.5 * math32.Pi))
for i := 0; i < 3; i++ {
qt[i] = sclp*p[i] + sclq*qt[i]
}
}
}
func (angles *Vec3) AngleQuaternion(qt *Vec4) {
var ang float32
var sr, sp, sy, cr, cp, cy float32
ang = angles[2] * 0.5
sy = math32.Sin(ang)
cy = math32.Cos(ang)
ang = angles[1] * 0.5
sp = math32.Sin(ang)
cp = math32.Cos(ang)
ang = angles[0] * 0.5
sr = math32.Sin(ang)
cr = math32.Cos(ang)
qt[0] = sr*cp*cy - cr*sp*sy // X
qt[1] = cr*sp*cy + sr*cp*sy // Y
qt[2] = cr*cp*sy - sr*sp*cy // Z
qt[3] = cr*cp*cy + sr*sp*sy // W
} | studio/vecutil.go | 0.605682 | 0.526404 | vecutil.go | starcoder |
package timezone
import "regexp"
// TimezoneInfo is the data for parsing timezone from a string.
type TimezoneInfo struct {
RegexPatterns []string
AlternativePatterns map[*regexp.Regexp]string
Timezones map[string]int
}
// These timezone list are taken fromseveral sources:
// - http://stackoverflow.com/q/1703546
// - http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
// - https://github.com/scrapinghub/dateparser/pull/4
// - http://en.wikipedia.org/wiki/List_of_UTC_time_offsets
var timezoneInfoList = []TimezoneInfo{
{
RegexPatterns: []string{
`(.)%s$`,
},
AlternativePatterns: map[*regexp.Regexp]string{
// UTC+n, UTC-n, GMT+n, GMT-n:
regexp.MustCompile(`(?:UTC|GMT)\\?([+-])0(\d):00`): `(?:UTC|GMT)\$1$2`,
// UTC+n:mm, UTC-n:mm, GMT+n:mm, GMT-n:mm:
regexp.MustCompile(`(?:UTC|GMT)\\?([+-])0(\d):(\d{2})`): `(?:UTC|GMT)\$1$2:$3`,
// UTC+nn, UTC-nn, GMT+nn, GMT-nn:
regexp.MustCompile(`(?:UTC|GMT)\\?([+-])(\d{2}):00`): `(?:UTC|GMT)\$1$2`,
// UTC+nnmm, UTC-nnmm, GMT+nnmm, GMT-nnmm:
regexp.MustCompile(`(?:UTC|GMT)\\?([+-])(\d{2}):(\d{2})`): `(?:UTC|GMT)\$1$2:?$3.*`,
// Others:
regexp.MustCompile(`UTC`): "",
regexp.MustCompile(`:`): "",
regexp.MustCompile(`:|UTC`): "",
regexp.MustCompile(`UTC`): "GMT",
},
Timezones: map[string]int{
`UTC-12:00`: -43200,
`UTC-11:00`: -39600,
`UTC-10:00`: -36000,
`UTC-09:30`: -34200,
`UTC-09:00`: -32400,
`UTC-08:00`: -28800,
`UTC-07:00`: -25200,
`UTC-06:00`: -21600,
`UTC-05:00`: -18000,
`UTC-04:30`: -16200,
`UTC-04:00`: -14400,
`UTC-03:30`: -12600,
`UTC-03:00`: -10800,
`UTC-02:30`: -9000,
`UTC-02:00`: -7200,
`UTC-01:00`: -3600,
`UTC-00:00`: 0,
`UTC+00:00`: 0,
`UTC+01:00`: 3600,
`UTC+02:00`: 7200,
`UTC+03:00`: 10800,
`UTC+03:30`: 12600,
`UTC+04:00`: 14400,
`UTC+04:30`: 16200,
`UTC+05:00`: 18000,
`UTC+05:30`: 19800,
`UTC+05:45`: 20700,
`UTC+06:00`: 21600,
`UTC+06:30`: 23400,
`UTC+07:00`: 25200,
`UTC+08:00`: 28800,
`UTC+08:45`: 31500,
`UTC+09:00`: 32400,
`UTC+09:30`: 34200,
`UTC+10:00`: 36000,
`UTC+10:30`: 37800,
`UTC+11:00`: 39600,
`UTC+11:30`: 41400,
`UTC+12:00`: 43200,
`UTC+12:45`: 45900,
`UTC+13:00`: 46800,
`UTC+14:00`: 50400,
},
}, {
RegexPatterns: []string{
(`(\W|\d|_)%s($|\W)`),
},
Timezones: map[string]int{
`ACDT`: 37800,
`ACST`: 34200,
`ACT`: -18000,
`ACWDT`: 35100,
`ACWST`: 31500,
`ADDT`: -7200,
`ADMT`: 9300,
`ADT`: -10800,
`AEDT`: 39600,
`AEST`: 36000,
`AFT`: 16200,
`AHDT`: -32400,
`AHST`: -36000,
`AKDT`: -28800,
`AKST`: -32400,
`AKTST`: 21600,
`AKTT`: 18000,
`ALMST`: 25200,
`ALMT`: 21600,
`AMST`: 18000,
`AMT`: 14400,
`ANAST`: 43200,
`ANAT`: 43200,
`ANT`: -16200,
`APT`: -10800,
`AQTST`: 21600,
`AQTT`: 18000,
`ARST`: -10800,
`ART`: -10800,
`ASHST`: 21600,
`ASHT`: 18000,
`AST`: -14400,
`AWDT`: 32400,
`AWST`: 28800,
`AWT`: -10800,
`AZOMT`: 0,
`AZOST`: -3600,
`AZOT`: -3600,
`AZST`: 18000,
`AZT`: 14400,
`BAKST`: 14400,
`BAKT`: 10800,
`BDST`: 7200,
`BDT`: 28800,
`BEAT`: 9000,
`BEAUT`: 9900,
`BIOT`: 21600,
`BMT`: 1800,
`BNT`: 28800,
`BORT`: 28800,
`BOST`: -12780,
`BOT`: -14400,
`BRST`: -7200,
`BRT`: -10800,
`BST`: 39600,
`BTT`: 21600,
`BURT`: 23400,
`CANT`: -3600,
`CAPT`: -32400,
`CAST`: 10800,
`CAT`: 7200,
`CAWT`: -32400,
`CCT`: 23400,
`CDDT`: -14400,
`CDT`: -18000,
`CEDT`: 7200,
`CEMT`: 10800,
`CEST`: 7200,
`CET`: 3600,
`CGST`: -3600,
`CGT`: -7200,
`CHADT`: 49500,
`CHAST`: 45900,
`CHDT`: -19800,
`CHOST`: 36000,
`CHOT`: 28800,
`CIST`: -28800,
`CKHST`: -34200,
`CKT`: -36000,
`CLST`: -10800,
`CLT`: -14400,
`CMT`: -16080,
`COST`: -14400,
`COT`: -18000,
`CPT`: -18000,
`CST`: -21600,
`CUT`: 8400,
`CVST`: -3600,
`CVT`: -3600,
`CWT`: -18000,
`CXT`: 25200,
`ChST`: 36000,
`DACT`: 21600,
`DAVT`: 25200,
`DDUT`: 36000,
`DFT`: 3600,
`DMT`: -1500,
`DUSST`: 21600,
`DUST`: 21600,
`EASST`: -18000,
`EAST`: -21600,
`EAT`: 10800,
`ECT`: -18000,
`EDDT`: -10800,
`EDT`: -14400,
`EEDT`: 10800,
`EEST`: 10800,
`EET`: 7200,
`EGST`: 0,
`EGT`: -3600,
`EHDT`: -16200,
`EMT`: -26220,
`EPT`: -14400,
`EST`: -18000,
`ET`: -18000,
`EWT`: -14400,
`FET`: 10800,
`FFMT`: -14640,
`FJST`: 46800,
`FJT`: 43200,
`FKST`: -10800,
`FKT`: -14400,
`FMT`: -4080,
`FNST`: -3600,
`FNT`: -7200,
`FORT`: 14400,
`FRUST`: 25200,
`FRUT`: 18000,
`GALT`: -21600,
`GAMT`: -32400,
`GBGT`: -13500,
`GEST`: 14400,
`GET`: 14400,
`GFT`: -10800,
`GHST`: 1200,
`GILT`: 43200,
`GIT`: -32400,
`GMT`: 0,
`GST`: 14400,
`GYT`: -14400,
`HAA`: -10800,
`HAC`: -18000,
`HADT`: -32400,
`HAE`: -14400,
`HAP`: -25200,
`HAR`: -21600,
`HAST`: -36000,
`HAT`: -9000,
`HAY`: -28800,
`HDT`: -34200,
`HKST`: 32400,
`HKT`: 28800,
`HLV`: -16200,
`HMT`: 18000,
`HNA`: -14400,
`HNC`: -21600,
`HNE`: -18000,
`HNP`: -28800,
`HNR`: -25200,
`HNT`: -12600,
`HNY`: -32400,
`HOVST`: 28800,
`HOVT`: 25200,
`HST`: -36000,
`ICT`: 25200,
`IDDT`: 14400,
`IDT`: 10800,
`IHST`: 21600,
`IMT`: 7020,
`IOT`: 21600,
`IRDT`: 16200,
`IRKST`: 32400,
`IRKT`: 28800,
`IRST`: 12600,
`ISST`: 0,
`IST`: 7200,
`JAVT`: 26400,
`JCST`: 32400,
`JDT`: 36000,
`JMT`: 8460,
`JST`: 32400,
`JWST`: 28800,
`KART`: 18000,
`KDT`: 32400,
`KGST`: 21600,
`KGT`: 21600,
`KIZST`: 21600,
`KIZT`: 18000,
`KMT`: 5760,
`KOST`: 39600,
`KRAST`: 28800,
`KRAT`: 25200,
`KST`: 32400,
`KUYST`: 18000,
`KUYT`: 14400,
`KWAT`: -43200,
`LHDT`: 39600,
`LHST`: 37800,
`LINT`: 50400,
`LKT`: 23400,
`LMT`: -20160,
// `LMT`: -17640,
// `LMT`: -20580,
// `LMT`: -14400,
`LRT`: -2640,
`LST`: 9420,
`MADMT`: 3600,
`MADST`: 0,
`MADT`: -3600,
`MAGST`: 43200,
`MAGT`: 39600,
`MALST`: 26400,
`MALT`: 27000,
`MART`: -34200,
`MAWT`: 18000,
`MDDT`: -18000,
`MDST`: 16260,
`MDT`: -21600,
`MEST`: 7200,
`MESZ`: 7200,
`MET`: 3600,
`MEZ`: 3600,
`MHT`: 43200,
`MIST`: 39600,
`MIT`: -34200,
`MMT`: 23400,
`MOST`: 32400,
`MOT`: 28800,
`MPT`: -21600,
`MSD`: 14400,
`MSK`: 10800,
`MSM`: 18000,
`MST`: -25200,
`MUST`: 18000,
`MUT`: 14400,
`MVT`: 18000,
`MWT`: -21600,
`MYT`: 28800,
`NCST`: 43200,
`NCT`: 39600,
`NDDT`: -5400,
`NDT`: -9000,
`NEGT`: -12600,
`NEST`: 4800,
`NET`: 1200,
`NFT`: 41400,
`NMT`: 40320,
`NOVST`: 25200,
`NOVT`: 21600,
`NPT`: 20700,
`NRT`: 41400,
`NST`: -12600,
`NT`: -12600,
`NUT`: -39600,
`NWT`: -36000,
`NZDT`: 46800,
`NZMT`: 41400,
`NZST`: 43200,
`OMSST`: 25200,
`OMST`: 21600,
`ORAST`: 18000,
`ORAT`: 18000,
`PDDT`: -21600,
`PDT`: -25200,
`PEST`: -14400,
`PET`: -18000,
`PETST`: 43200,
`PETT`: 43200,
`PGT`: 36000,
`PHOT`: 46800,
`PHST`: 32400,
`PHT`: 28800,
`PKST`: 21600,
`PKT`: 18000,
`PLMT`: 25620,
`PMDT`: -7200,
`PMMT`: 35340,
`PMST`: -10800,
`PMT`: 540,
`PNT`: -30600,
`PONT`: 39600,
`PPMT`: -17340,
`PPT`: -25200,
`PST`: -28800,
`PT`: -28800,
`PWT`: -25200,
`PYST`: -10800,
`PYT`: -14400,
`QMT`: -18840,
`QYZST`: 25200,
`QYZT`: 21600,
`RET`: 14400,
`RMT`: 3000,
`ROTT`: -10800,
`SAKST`: 43200,
`SAKT`: 39600,
`SAMT`: 14400,
`SAST`: 7200,
`SBT`: 39600,
`SCT`: 14400,
`SDMT`: -16800,
`SDT`: -36000,
`SEČ`: 3600,
`SET`: 3600,
`SELČ`: 7200,
`SGT`: 28800,
`SHEST`: 21600,
`SHET`: 18000,
`SJMT`: -20160,
`SLT`: 19800,
`SMT`: -13860,
`SRET`: 39600,
`SRT`: -10800,
`SST`: -39600,
`STAT`: 10800,
`SVEST`: 21600,
`SVET`: 14400,
`SWAT`: 5400,
`SYOT`: 10800,
`TAHT`: -36000,
`TASST`: 25200,
`TAST`: 21600,
`TBIST`: 18000,
`TBIT`: 10800,
`TBMT`: 10740,
`TFT`: 18000,
`THA`: 25200,
`TJT`: 18000,
`TKT`: -39600,
`TLT`: 32400,
`TMT`: 18000,
`TOST`: 50400,
`TOT`: 46800,
`TRST`: 14400,
`TRT`: 10800,
`TSAT`: 10800,
`TVT`: 43200,
`ULAST`: 32400,
`ULAT`: 28800,
`URAST`: 18000,
`URAT`: 18000,
`UT`: 0,
`UTC`: 0,
`UYHST`: -9000,
`UYST`: -7200,
`UYT`: -10800,
`UZST`: 21600,
`UZT`: 18000,
`VEČ`: 7200,
`VET`: -16200,
`VLAST`: 39600,
`VLAT`: 36000,
`VOLST`: 14400,
`VOLT`: 14400,
`VOST`: 21600,
`VUST`: 43200,
`VUT`: 39600,
`WARST`: -10800,
`WART`: -14400,
`WAST`: 7200,
`WAT`: 3600,
`WDT`: 32400,
`WEDT`: 3600,
`WEMT`: 7200,
`WEST`: 3600,
`WET`: 0,
`WFT`: 43200,
`WGST`: -7200,
`WGT`: -10800,
`WIB`: 25200,
`WIT`: 32400,
`WITA`: 28800,
`WMT`: 5040,
`WSDT`: 50400,
`WSST`: 46800,
`WST`: 28800,
`WT`: 0,
`XJT`: 21600,
`YAKST`: 36000,
`YAKT`: 32400,
`YAPT`: 36000,
`YDDT`: -25200,
`YDT`: -28800,
`YEKST`: 21600,
`YEKT`: 18000,
`YERST`: 14400,
`YERT`: 10800,
`YPT`: -28800,
`YST`: -32400,
`YWT`: -28800,
`zzz`: 0,
`Z`: 0,
`ZEČ`: 0,
},
},
} | internal/timezone/timezones.go | 0.656438 | 0.601301 | timezones.go | starcoder |
package plot
import (
"errors"
"fmt"
"reflect"
"sort"
"github.com/ShawnROGrady/benchparse"
"github.com/ShawnROGrady/benchplot/plot/plotter"
)
// The available plot types.
const (
ScatterType = "scatter"
AvgLineType = "avg_line"
)
type plotOptions struct {
groupBy []string
plotTypes []string
filterExprs []string
}
// Benchmark plots the benchmark.
func Benchmark(b benchparse.Benchmark, p plotter.Plotter, xName, yName string, options ...plotOption) error {
pltOptions := &plotOptions{
groupBy: []string{},
plotTypes: []string{},
filterExprs: []string{},
}
for _, opt := range options {
opt.apply(pltOptions)
}
var (
res = b.Results
err error
)
for _, expr := range pltOptions.filterExprs {
res, err = res.Filter(expr)
if err != nil {
return err
}
}
grouped := res.Group(pltOptions.groupBy)
splitGrouped, err := splitGroupedResult(grouped, xName, yName)
if err != nil {
return fmt.Errorf("err splitting grouped results: %w", err)
}
if len(pltOptions.plotTypes) == 0 {
plotTypes, err := defaultPlotTypes(splitGrouped)
if err != nil {
return err
}
pltOptions.plotTypes = plotTypes
}
for i, plotType := range pltOptions.plotTypes {
includeLegend := i == 0
switch plotType {
case ScatterType:
if err := plotScatter(p, b.Name, xName, yName, splitGrouped, includeLegend); err != nil {
return fmt.Errorf("error creating scatter plot: %w", err)
}
case AvgLineType:
if err := plotAvgLine(p, b.Name, xName, yName, splitGrouped, includeLegend); err != nil {
return fmt.Errorf("error creating average line plot: %w", err)
}
default:
return fmt.Errorf("unknown plot type: %s", plotType)
}
}
return nil
}
func defaultPlotTypes(splitGrouped map[string][]splitRes) ([]string, error) {
// just use the first x value
for _, res := range splitGrouped {
if len(res) == 0 {
continue
}
xKind := reflect.TypeOf(res[0].x).Kind()
switch xKind {
case reflect.Int, reflect.Float64, reflect.Uint64:
return []string{ScatterType, AvgLineType}, nil
}
}
return []string{}, errors.New("could not determine default plot type")
}
// plotScatter plots the benchmark results as a scatter plot.
func plotScatter(p plotter.Plotter, title, xName, yName string, splitGrouped map[string][]splitRes, includeLegend bool) error {
var (
xLabel = xName
yLabel = yName // TODO: include units
)
data, err := splitGroupedPlotData(splitGrouped)
if err != nil {
return err
}
return p.PlotScatter(data, title, xLabel, yLabel, includeLegend)
}
// plotAvgLine plots the benchmark results as a line where y(x) = avg(f(x)).
func plotAvgLine(p plotter.Plotter, title, xName, yName string, splitGrouped map[string][]splitRes, includeLegend bool) error {
var (
xLabel = xName
yLabel = yName // TODO: include units
)
data, err := splitGroupedAvgPlotData(splitGrouped)
if err != nil {
return err
}
return p.PlotLine(data, title, xLabel, yLabel, includeLegend)
}
func splitGroupedPlotData(splitGrouped map[string][]splitRes) (map[string]plotter.NumericData, error) {
data := map[string]plotter.NumericData{}
for groupName, splitResults := range splitGrouped {
var (
xData = []float64{}
yData = []float64{}
)
for _, res := range splitResults {
xF, err := getFloat(res.x)
if err != nil {
return nil, fmt.Errorf("cannot create scatter plot from x data: %w", err)
}
xData = append(xData, xF)
yF, err := getFloat(res.y)
if err != nil {
return nil, fmt.Errorf("cannot create scatter plot from y data: %w", err)
}
yData = append(yData, yF)
}
data[groupName] = plotter.NumericData{
X: xData,
Y: yData,
}
}
return data, nil
}
func splitGroupedAvgPlotData(splitGrouped map[string][]splitRes) (map[string]plotter.NumericData, error) {
data := map[string]plotter.NumericData{}
for groupName, splitResults := range splitGrouped {
// track y values corresponding to each x
vals := map[float64][]float64{}
for _, res := range splitResults {
xF, err := getFloat(res.x)
if err != nil {
return nil, fmt.Errorf("cannot create scatter plot from x data: %w", err)
}
yF, err := getFloat(res.y)
if err != nil {
return nil, fmt.Errorf("cannot create scatter plot from y data: %w", err)
}
if xVals, ok := vals[xF]; ok {
vals[xF] = append(xVals, yF)
} else {
vals[xF] = []float64{yF}
}
}
var (
xData = make([]float64, len(vals))
yData = make([]float64, len(vals))
)
i := 0
for x := range vals {
xData[i] = x
i++
}
// keep data sorted wrt x
sort.Float64s(xData)
for i, xVal := range xData {
yVals := vals[xVal]
var totY float64 = 0
for _, yVal := range yVals {
totY += yVal
}
yData[i] = totY / float64(len(yVals))
}
data[groupName] = plotter.NumericData{
X: xData,
Y: yData,
}
}
return data, nil
}
func getFloat(data interface{}) (float64, error) {
val := reflect.ValueOf(data)
switch val.Type().Kind() {
case reflect.Int:
return float64(val.Int()), nil
case reflect.Float64:
return val.Float(), nil
case reflect.Uint64:
return float64(val.Uint()), nil
default:
return 0, fmt.Errorf("unexpected kind: '%s'", val.Type().Kind())
}
} | plot/benchmark.go | 0.627837 | 0.430506 | benchmark.go | starcoder |
package faker
import (
"fmt"
"golang.org/x/exp/rand"
)
type nameFaker struct {
formatsFemale, formatsMale *weightedEntries
firstNameFemale, firstNameMale *weightedEntries
lastName *weightedEntries
prefixFemale, prefixMale *weightedEntries
suffixFemale, suffixMale *weightedEntries
}
// Name returns a random en_US person name.
func (f *nameFaker) Name(rng *rand.Rand) string {
if rng.Intn(2) == 0 {
return f.formatsFemale.Rand(rng).(func(rng *rand.Rand) string)(rng)
}
return f.formatsMale.Rand(rng).(func(rng *rand.Rand) string)(rng)
}
func newNameFaker() nameFaker {
f := nameFaker{}
f.formatsFemale = makeWeightedEntries(
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s`, f.firstNameFemale.Rand(rng), f.lastName.Rand(rng))
}, 0.97,
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s %s`, f.prefixFemale.Rand(rng), f.firstNameFemale.Rand(rng), f.lastName.Rand(rng))
}, 0.015,
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s %s`, f.firstNameFemale.Rand(rng), f.lastName.Rand(rng), f.suffixFemale.Rand(rng))
}, 0.02,
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s %s %s`, f.prefixFemale.Rand(rng), f.firstNameFemale.Rand(rng), f.lastName.Rand(rng), f.suffixFemale.Rand(rng))
}, 0.005,
)
f.formatsMale = makeWeightedEntries(
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s`, f.firstNameMale.Rand(rng), f.lastName.Rand(rng))
}, 0.97,
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s %s`, f.prefixMale.Rand(rng), f.firstNameMale.Rand(rng), f.lastName.Rand(rng))
}, 0.015,
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s %s`, f.firstNameMale.Rand(rng), f.lastName.Rand(rng), f.suffixMale.Rand(rng))
}, 0.02,
func(rng *rand.Rand) string {
return fmt.Sprintf(`%s %s %s %s`, f.prefixMale.Rand(rng), f.firstNameMale.Rand(rng), f.lastName.Rand(rng), f.suffixMale.Rand(rng))
}, 0.005,
)
f.firstNameFemale = firstNameFemale()
f.firstNameMale = firstNameMale()
f.lastName = lastName()
f.prefixFemale = makeWeightedEntries(
`Mrs.`, 0.5,
`Ms.`, 0.1,
`Miss`, 0.1,
`Dr.`, 0.3,
)
f.prefixMale = makeWeightedEntries(
`Mr.`, 0.7,
`Dr.`, 0.3,
)
f.suffixFemale = makeWeightedEntries(
`MD`, 0.5,
`DDS`, 0.3,
`PhD`, 0.1,
`DVM`, 0.2,
)
f.suffixMale = makeWeightedEntries(
`Jr.`, 0.2,
`II`, 0.05,
`III`, 0.03,
`IV`, 0.015,
`V`, 0.005,
`MD`, 0.3,
`DDS`, 0.2,
`PhD`, 0.1,
`DVM`, 0.1,
)
return f
} | pkg/workload/faker/name.go | 0.560493 | 0.477432 | name.go | starcoder |
package main
import (
"fmt"
"math/cmplx"
)
func main() {
fmt.Println(quartic([]float64{7, 0, 0, 0, 5}))
fmt.Println(quartic([]float64{7, 50, 49, 6, 5}))
fmt.Println(quartic([]float64{10, 4, 0, 0, 0}))
fmt.Println(quartic([]float64{2, 4, 6, 8, 10}))
fmt.Println(quartic([]float64{-6, -4, 190, 45, 19}))
}
func linear(v []float64) (z []complex128) {
a := complex(v[0], 0)
b := complex(v[1], 0)
switch {
case a == 0 && b == 0: // one real root
z = []complex128{0}
case a == 0: // no solution
default: // one real root
z = []complex128{-b / a}
}
return
}
func quadratic(v []float64) (z []complex128) {
a := complex(v[0], 0)
b := complex(v[1], 0)
c := complex(v[2], 0)
d := b*b - 4*a*c
switch {
case a == 0: // equation collapsed to linear
z = linear(v[1:])
case d == 0: // one real root
z = []complex128{-b / (2 * a)}
default: // two complex roots
d = cmplx.Sqrt(d)
z = []complex128{
(-b + d) / (2 * a),
(-b - d) / (2 * a),
}
}
return
}
func cubic(v []float64) (z []complex128) {
a := complex(v[0], 0)
b := complex(v[1], 0)
c := complex(v[2], 0)
d := complex(v[3], 0)
d0 := b*b - 3*a*c
d1 := 2*b*b*b - 9*a*b*c + 27*a*a*d
d2 := cmplx.Sqrt(d1*d1 - 4*d0*d0*d0)
Z := (-1 + cmplx.Sqrt(-3)) / 2
C := (d1 + d2) / 2
if C == 0 {
C = (d1 - d2) / 2
}
switch {
case a == 0: // equation collapsed to quadratic
z = quadratic(v[1:])
case C == 0: // only real root
z = []complex128{-1 / (3 * a) * b}
default: // one real root, two complex roots
C = cmplx.Pow(C, 1.0/3)
z = []complex128{
-1 / (3 * a) * (b + C + d0/C),
-1 / (3 * a) * (b + Z*C + d0/(Z*C)),
-1 / (3 * a) * (b + Z*Z*C + d0/(Z*Z*C)),
}
}
return
}
func quartic(v []float64) (z []complex128) {
a := complex(v[0], 0)
b := complex(v[1], 0)
c := complex(v[2], 0)
d := complex(v[3], 0)
e := complex(v[4], 0)
// collapsed to cubic
if a == 0 {
return cubic(v[1:])
}
p := (8*a*c - 3*b*b) / (8 * a * a)
q := (b*b*b - 4*a*b*c + 8*a*a*d) / (8 * a * a * a)
d0 := c*c - 3*b*d + 12*a*e
d1 := 2*c*c*c - 9*b*c*d + 27*b*b*e + 27*a*d*d - 72*a*c*e
dm := d1*d1 - 4*d0*d0*d0
// three common roots, one simple root
if dm == 0 && d0 == 0 {
r := quadratic([]float64{12 * v[0], 6 * v[1], v[2]})
r0 := r[0]
r1 := r[1]
m0 := cmplx.Abs(a*r0*r0*r0*r0 + b*r0*r0*r0 + c*r0*r0 + d*r0 + e)
m1 := cmplx.Abs(a*r1*r1*r1*r1 + b*r1*r1*r1 + c*r1*r1 + d*r1 + e)
x0 := r[0]
if m1 < m0 {
x0 = r[1]
}
x1 := -b/a - 3*x0
return []complex128{x1, x0, x0, x0}
}
// four roots
dq := d1 * d1
if dm != 0 && d0 == 0 {
dq = -dq
}
Q := cmplx.Pow(0.5*(d1+cmplx.Sqrt(dq-4*d0*d0*d0)), 1/3.0)
S := 0.5 * cmplx.Sqrt(-2*p/3+(Q+d0/Q)/(3*a))
y0 := 0.5 * cmplx.Sqrt(-4*S*S-2*p+q/S)
y1 := 0.5 * cmplx.Sqrt(-4*S*S-2*p-q/S)
x := -b / (4 * a)
z = []complex128{
x - S + y0,
x - S - y0,
x + S + y1,
x + S - y1,
}
return
} | math/quartic-equation.go | 0.589835 | 0.413004 | quartic-equation.go | starcoder |
package world
// GameMode represents a game mode that may be assigned to a player. Upon joining the world, players will be
// given the default game mode that the world holds.
// Game modes specify the way that a player interacts with and plays in the world.
type GameMode interface {
// AllowsEditing specifies if a player with this GameMode can edit the World it's in.
AllowsEditing() bool
// AllowsTakingDamage specifies if a player with this GameMode can take damage from other entities.
AllowsTakingDamage() bool
// CreativeInventory specifies if a player with this GameMode has access to the creative inventory.
CreativeInventory() bool
}
// GameModeSurvival represents the survival game mode: Players with this game mode have limited supplies and
// can break blocks using only the right tools.
type GameModeSurvival struct{}
// AllowsEditing ...
func (GameModeSurvival) AllowsEditing() bool {
return true
}
// AllowsTakingDamage ...
func (GameModeSurvival) AllowsTakingDamage() bool {
return true
}
// CreativeInventory ...
func (GameModeSurvival) CreativeInventory() bool {
return false
}
// GameModeCreative represents the creative game mode: Players with this game mode have infinite blocks and
// items and can break blocks instantly. Players with creative mode can also fly.
type GameModeCreative struct{}
// AllowsEditing ...
func (GameModeCreative) AllowsEditing() bool {
return true
}
// AllowsTakingDamage ...
func (GameModeCreative) AllowsTakingDamage() bool {
return false
}
// CreativeInventory ...
func (GameModeCreative) CreativeInventory() bool {
return true
}
// GameModeAdventure represents the adventure game mode: Players with this game mode cannot edit the world
// (placing or breaking blocks).
type GameModeAdventure struct{}
// AllowsEditing ...
func (GameModeAdventure) AllowsEditing() bool {
return false
}
// AllowsTakingDamage ...
func (GameModeAdventure) AllowsTakingDamage() bool {
return true
}
// CreativeInventory ...
func (GameModeAdventure) CreativeInventory() bool {
return false
}
// GameModeSpectator represents the spectator game mode: Players with this game mode cannot interact with the
// world and cannot be seen by other players. GameModeSpectator players can fly, like creative mode, and can
// move through blocks.
type GameModeSpectator struct{}
// AllowsEditing ...
func (GameModeSpectator) AllowsEditing() bool {
return false
}
// AllowsTakingDamage ...
func (GameModeSpectator) AllowsTakingDamage() bool {
return false
}
// CreativeInventory ...
func (GameModeSpectator) CreativeInventory() bool {
return true
} | server/world/game_mode.go | 0.825871 | 0.597256 | game_mode.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.