How to use stringToRat method of lib Package

Best K6 code snippet using lib.stringToRat

execution_segment.go

Source:execution_segment.go Github

copy

Full Screen

...78 to: to,79 length: new(big.Rat).Sub(to, from),80 }81}82// stringToRat is a helper function that tries to convert a string to a rational83// number while allowing percentage, decimal, and fraction values.84func stringToRat(s string) (*big.Rat, error) {85 if strings.HasSuffix(s, "%") {86 num, ok := new(big.Int).SetString(strings.TrimSuffix(s, "%"), 10)87 if !ok {88 return nil, fmt.Errorf("'%s' is not a valid percentage", s)89 }90 return new(big.Rat).SetFrac(num, big.NewInt(100)), nil91 }92 rat, ok := new(big.Rat).SetString(s)93 if !ok {94 return nil, fmt.Errorf("'%s' is not a valid percentage, decimal, fraction or interval value", s)95 }96 return rat, nil97}98// NewExecutionSegmentFromString validates the supplied string value and returns99// the newly created ExecutionSegment or and error from it.100//101// We are able to parse both single percentage/float/fraction values, and actual102// (from: to] segments. For the single values, we just treat them as the103// beginning segment - thus the execution segment can be used as a shortcut for104// quickly running an arbitrarily scaled-down version of a test.105//106// The parsing logic is that values with a colon, i.e. ':', are full segments:107// `1/2:3/4`, `0.5:0.75`, `50%:75%`, and even `2/4:75%` should be (1/2, 3/4]108// And values without a colon are the end of a first segment:109// `20%`, `0.2`, and `1/5` should be converted to (0, 1/5]110// empty values should probably be treated as "1", i.e. the whole execution111func NewExecutionSegmentFromString(toStr string) (result *ExecutionSegment, err error) {112 from := zeroRat113 if toStr == "" {114 toStr = "1" // an empty string means a full 0:1 execution segment115 }116 if strings.ContainsRune(toStr, ':') {117 fromToStr := strings.SplitN(toStr, ":", 2)118 toStr = fromToStr[1]119 if from, err = stringToRat(fromToStr[0]); err != nil {120 return nil, err121 }122 }123 to, err := stringToRat(toStr)124 if err != nil {125 return nil, err126 }127 return NewExecutionSegment(from, to)128}129// UnmarshalText implements the encoding.TextUnmarshaler interface, so that130// execution segments can be specified as CLI flags, environment variables, and131// JSON strings. It is a wrapper for the NewExecutionFromString() constructor.132func (es *ExecutionSegment) UnmarshalText(text []byte) (err error) {133 segment, err := NewExecutionSegmentFromString(string(text))134 if err != nil {135 return err136 }137 *es = *segment138 return nil139}140func (es *ExecutionSegment) String() string {141 if es == nil {142 return "0:1"143 }144 return es.from.RatString() + ":" + es.to.RatString()145}146// MarshalText implements the encoding.TextMarshaler interface, so is used for147// text and JSON encoding of the execution segment.148func (es *ExecutionSegment) MarshalText() ([]byte, error) {149 if es == nil {150 return nil, nil151 }152 return []byte(es.String()), nil153}154// FloatLength is a helper method for getting some more human-readable155// information about the execution segment.156func (es *ExecutionSegment) FloatLength() float64 {157 if es == nil {158 return 1.0159 }160 res, _ := es.length.Float64()161 return res162}163// Split evenly divides the execution segment into the specified number of164// equal consecutive execution sub-segments.165func (es *ExecutionSegment) Split(numParts int64) ([]*ExecutionSegment, error) {166 if numParts < 1 {167 return nil, fmt.Errorf("the number of parts should be at least 1, %d received", numParts)168 }169 from, to := zeroRat, oneRat170 if es != nil {171 from, to = es.from, es.to172 }173 increment := new(big.Rat).Sub(to, from)174 increment.Denom().Mul(increment.Denom(), big.NewInt(numParts))175 results := make([]*ExecutionSegment, numParts)176 for i := int64(0); i < numParts; i++ {177 segmentTo := new(big.Rat).Add(from, increment)178 segment, err := NewExecutionSegment(from, segmentTo)179 if err != nil {180 return nil, err181 }182 results[i] = segment183 from = segmentTo184 }185 if from.Cmp(to) != 0 {186 return nil, fmt.Errorf("expected %s and %s to be equal", from, to)187 }188 return results, nil189}190// Equal returns true only if the two execution segments have the same from and191// to values.192func (es *ExecutionSegment) Equal(other *ExecutionSegment) bool {193 if es == other {194 return true195 }196 thisFrom, otherFrom, thisTo, otherTo := zeroRat, zeroRat, oneRat, oneRat197 if es != nil {198 thisFrom, thisTo = es.from, es.to199 }200 if other != nil {201 otherFrom, otherTo = other.from, other.to202 }203 return thisFrom.Cmp(otherFrom) == 0 && thisTo.Cmp(otherTo) == 0204}205// SubSegment returns a new execution sub-segment - if a is (1/2:1] and b is206// (0:1/2], then a.SubSegment(b) will return a new segment (1/2, 3/4].207//208// The basic formula for c = a.SubSegment(b) is:209// c.from = a.from + b.from * (a.to - a.from)210// c.to = c.from + (b.to - b.from) * (a.to - a.from)211func (es *ExecutionSegment) SubSegment(child *ExecutionSegment) *ExecutionSegment {212 if child == nil {213 return es // 100% sub-segment is the original segment214 }215 parentFrom, parentLength := zeroRat, oneRat216 if es != nil {217 parentFrom, parentLength = es.from, es.length218 }219 resultFrom := new(big.Rat).Mul(parentLength, child.from)220 resultFrom.Add(resultFrom, parentFrom)221 resultLength := new(big.Rat).Mul(parentLength, child.length)222 return &ExecutionSegment{223 from: resultFrom,224 length: resultLength,225 to: new(big.Rat).Add(resultFrom, resultLength),226 }227}228// helper function for rounding (up) of rational numbers to big.Int values229func roundUp(rat *big.Rat) *big.Int {230 quo, rem := new(big.Int).QuoRem(rat.Num(), rat.Denom(), new(big.Int))231 if rem.Mul(rem, twoBigInt).Cmp(rat.Denom()) >= 0 {232 return quo.Add(quo, oneBigInt)233 }234 return quo235}236// Scale proportionally scales the supplied value, according to the execution237// segment's position and size of the work.238func (es *ExecutionSegment) Scale(value int64) int64 {239 if es == nil { // no execution segment, i.e. 100%240 return value241 }242 // Instead of the first proposal that used remainders and floor:243 // floor( (value * from) % 1 + value * length )244 // We're using an alternative approach with rounding that (hopefully) has245 // the same properties, but it's simpler and has better precision:246 // round( (value * from) - round(value * from) + (value * (to - from)) )?247 // which reduces to:248 // round( (value * to) - round(value * from) )?249 toValue := big.NewRat(value, 1)250 toValue.Mul(toValue, es.to)251 fromValue := big.NewRat(value, 1)252 fromValue.Mul(fromValue, es.from)253 toValue.Sub(toValue, new(big.Rat).SetFrac(roundUp(fromValue), oneBigInt))254 return roundUp(toValue).Int64()255}256// InPlaceScaleRat scales rational numbers in-place - it changes the passed257// argument (and also returns it, to allow for chaining, like many other big.Rat258// methods).259func (es *ExecutionSegment) InPlaceScaleRat(value *big.Rat) *big.Rat {260 if es == nil { // no execution segment, i.e. 100%261 return value262 }263 return value.Mul(value, es.length)264}265// CopyScaleRat scales rational numbers without changing them - creates a new266// bit.Rat object and uses it for the calculation.267func (es *ExecutionSegment) CopyScaleRat(value *big.Rat) *big.Rat {268 if es == nil { // no execution segment, i.e. 100%269 return value270 }271 return new(big.Rat).Mul(value, es.length)272}273// ExecutionSegmentSequence represents an ordered chain of execution segments,274// where the end of one segment is the beginning of the next. It can serialized275// as a comma-separated string of rational numbers "r1,r2,r3,...,rn", which276// represents the sequence (r1, r2], (r2, r3], (r3, r4], ..., (r{n-1}, rn].277// The empty value should be treated as if there is a single (0, 1] segment.278type ExecutionSegmentSequence []*ExecutionSegment279// NewExecutionSegmentSequence validates the that the supplied execution280// segments are non-overlapping and without gaps. It will return a new execution281// segment sequence if that is true, and an error if it's not.282func NewExecutionSegmentSequence(segments ...*ExecutionSegment) (ExecutionSegmentSequence, error) {283 if len(segments) > 1 {284 to := segments[0].to285 for i, segment := range segments[1:] {286 if segment.from.Cmp(to) != 0 {287 return nil, fmt.Errorf(288 "the start value %s of segment #%d should be equal to the end value of the previous one, but it is %s",289 segment.from, i+1, to,290 )291 }292 to = segment.to293 }294 }295 return ExecutionSegmentSequence(segments), nil296}297// NewExecutionSegmentSequenceFromString parses strings of the format298// "r1,r2,r3,...,rn", which represents the sequences like (r1, r2], (r2, r3],299// (r3, r4], ..., (r{n-1}, rn].300func NewExecutionSegmentSequenceFromString(strSeq string) (ExecutionSegmentSequence, error) {301 if len(strSeq) == 0 {302 return nil, nil303 }304 points := strings.Split(strSeq, ",")305 if len(points) < 2 {306 return nil, fmt.Errorf("at least 2 points are needed for an execution segment sequence, %d given", len(points))307 }308 var start *big.Rat309 segments := make([]*ExecutionSegment, 0, len(points)-1)310 for i, point := range points {311 rat, err := stringToRat(point)312 if err != nil {313 return nil, err314 }315 if i == 0 {316 start = rat317 continue318 }319 segment, err := NewExecutionSegment(start, rat)320 if err != nil {321 return nil, err322 }323 segments = append(segments, segment)324 start = rat325 }...

Full Screen

Full Screen

stringToRat

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter a number")4 fmt.Scanf("%s", &str)5 fmt.Println(str)6 fmt.Println("The number is ", new(big.Rat).SetString(str))7}

Full Screen

Full Screen

stringToRat

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(lib.StringToRat("3.14159"))4}5import (6func StringToRat(s string) *big.Rat {7 s = strings.TrimSpace(s)8 parts := strings.Split(s, ".")9 if len(parts) == 1 {10 parts = append(parts, "0")11 }12 integer := new(big.Int)13 integer.SetString(parts[0], 10)14 fractional := new(big.Int)15 fractional.SetString(parts[1], 10)16 n := big.NewInt(int64(len(parts[1])))17 denominator := new(big.Int)18 denominator.Exp(big.NewInt(10), n, nil)19 numerator := new(big.Int)20 numerator.Mul(integer, denominator)21 numerator.Add(numerator, fractional)22 return new(big.Rat).SetFrac(numerator, denominator)23}24import (25func main() {26 fmt.Println(lib.StringToRat

Full Screen

Full Screen

stringToRat

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", handler)4 http.ListenAndServe(":8080", nil)5}6func handler(w http.ResponseWriter, r *http.Request) {7 fmt.Fprintf(w, "Hello World!")8}9cannot use func literal (type func(http.ResponseWriter, *http.Request)) as type http.Handler in argument to http.ListenAndServe:10func(http.ResponseWriter, *http.Request) does not implement http.Handler (ServeHTTP method has pointer receiver)11import (12func main() {13 http.HandleFunc("/", handler)14 http.ListenAndServe(":8080", nil)15}16func handler(w http.ResponseWriter, r *http.Request) {17 fmt.Fprintf(w, "Hello World!")18}19cannot use func literal (type func(http.ResponseWriter, *http.Request)) as type http.Handler in argument to http.ListenAndServe: func(http.ResponseWriter, *http.Request) does not implement http.Handler (ServeHTTP method has pointer receiver)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful