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 jwt
import (
"github.com/urfave/cli"
)
// Command returns the cli.Command for jwt and related subcommands.
func Command() cli.Command {
return cli.Command{
Name: "jwt",
Usage: "sign and verify data using JSON Web Tokens (JWT)",
UsageText: "step crypto jwt <subcommand> [arguments] [global-flags] [subcommand-flags]",
Description: `A JSON Web Token or JWT (pronounced "jot") is a compact data structure used
to represent some JSON encoded "claims" that are passed as the payload of a
JWS or JWE structure, enabling the claims to be digitally signed and/or
encrypted. The "claims" (or "claim set") are represented as an ordinary JSON
object. JWTs are represented using a compact format that's URL safe and can be
used in space-constrained environments. JWTs can be passed in HTTP
Authorization headers and as URI query parameters.
A "claim" is a piece of information asserted about a subject, represented as a
key/value pair. Logically a verified JWT can be interpreted as "<issuer> says to
<audience> that <subject>'s <claim-name> is <claim-value>" for each claim.
A JWT signed using JWS has three parts:
1. A base64 encoded JSON object representing the JOSE (JSON Object
Signing and Encryption) header that describes the cryptographic
operations applied to the JWT Claims Set
2. A base64 encoded JSON object representing the JWT Claims Set
3. A base64 encoded digital signature of message authentication code
## EXAMPLES
Create a signed JWT using a JWK (with line breaks for display purposes only):
'''
$ step crypto jwt sign --key p256.priv.json --iss "<EMAIL>" \
--aud "https://example.com" --sub auth --exp $(date -v+1M +"%s")
<KEY>
'''
Create a signed JWT using a JWK and a custom payload:
'''
$ echo '{"srv":"https://srv.example.com"}' | step crypto jwt sign \
--key p256.priv.json --iss "<EMAIL>" \
--aud "https://example.com" --sub auth --exp $(date -v+1M +"%s")
<KEY>
'''
Verify the the previous token:
'''
$ echo $TOKEN | step crypto jwt verify --key p256.pub.json --iss "<EMAIL>" --aud "https://example.com"
{
"header": {
"alg": "ES256",
"kid": "ZjGX97LmcflPolWvsoAWzC5WPWkNFFH3QdKLUW978hk",
"typ": "JWT"
},
"payload": {
"aud": "https://example.com",
"exp": 1535242472,
"iat": 1532564073,
"iss": "<EMAIL>",
"nbf": 1532564073,
"srv": "https://srv.example.com",
"sub": "auth"
},
"signature": "DlSkxICjk2h1LarwJgXPbXQe7DwpLMOCvWp3I4GMcBP_5_QYPhVNBPQEeTKAUuQjYwlxZ5zVQnyp8ujvyf1Lqw"
}
'''
Read the information in the previous token without verifying it:
'''
$ echo $TOKEN | step crypto jwt inspect --insecure
{
"header": {
"alg": "ES256",
"kid": "ZjGX97LmcflPolWvsoAWzC5WPWkNFFH3QdKLUW978hk",
"typ": "JWT"
},
"payload": {
"aud": "https://example.com",
"exp": 1535242472,
"iat": 1532564073,
"iss": "<EMAIL>",
"nbf": 1532564073,
"srv": "https://srv.example.com",
"sub": "auth"
},
"signature": "DlSkxICjk2h1LarwJgXPbXQe7DwpLMOCvWp3I4GMcBP_5_QYPhVNBPQEeTKAU<KEY>"
}
'''`,
Subcommands: cli.Commands{
signCommand(),
verifyCommand(),
inspectCommand(),
},
}
} | command/crypto/jwt/jwt.go | 0.823257 | 0.469946 | jwt.go | starcoder |
package blackscholes
import (
"math"
"github.com/pkg/errors"
)
type OptionType rune
const (
Call = OptionType('c')
Put = OptionType('p')
Straddle = OptionType('s')
)
const InvSqrt2PI float64 = 1.0 / math.Sqrt2 / math.SqrtPi
var (
ErrNegPremium = errors.New("Negative option premium")
ErrNegPrice = errors.New("Negative underlying price")
ErrNegStrike = errors.New("Negative strike")
ErrNegTimeToExp = errors.New("Negative time to expiry")
ErrUnknownOptionType = errors.New("Unknown option type")
ErrNilPtrArg = errors.New("Nil pointer argument")
ErrNoncovergence = errors.New("Did not converge")
)
var (
abs func(float64) float64 = math.Abs
exp func(float64) float64 = math.Exp
inf func(int) float64 = math.Inf
log func(float64) float64 = math.Log
max func(float64, float64) float64 = math.Max
nan func() float64 = math.NaN
sqrt func(float64) float64 = math.Sqrt
)
type PriceParams struct {
Vol float64
TimeToExpiry float64
Underlying float64
Strike float64
Rate float64
Dividend float64
Type OptionType
}
func Price(pars *PriceParams) (price float64, err error) {
if pars == nil {
return nan(), ErrNilPtrArg
}
v, t, x, k, r, q := GetFloatPriceParams(pars)
if err = CheckPriceParams(t, x, k, pars.Type); err != nil {
return nan(), err
}
price = BSPriceNoErrorCheck(v, t, x, k, r, q, pars.Type)
return
}
func Delta(pars *PriceParams) (delta float64, err error) {
if pars == nil {
return nan(), ErrNilPtrArg
}
v, t, x, k, r, q := GetFloatPriceParams(pars)
if err = CheckPriceParams(t, x, k, pars.Type); err != nil {
return nan(), err
}
delta = BSDelta(v, t, x, k, r, q, pars.Type)
return
}
func Gamma(pars *PriceParams) (gamma float64, err error) {
if pars == nil {
return nan(), ErrNilPtrArg
}
v, t, x, k, r, q := GetFloatPriceParams(pars)
if err = CheckPriceParams(t, x, k, pars.Type); err != nil {
return nan(), err
}
gamma = BSGamma(v, t, x, k, r, q, pars.Type)
return
}
func Vega(pars *PriceParams) (vega float64, err error) {
if pars == nil {
return nan(), ErrNilPtrArg
}
v, t, x, k, r, q := GetFloatPriceParams(pars)
if err = CheckPriceParams(t, x, k, pars.Type); err != nil {
return nan(), err
}
vega = BSVega(v, t, x, k, r, q, pars.Type)
return
}
func Theta(pars *PriceParams) (theta float64, err error) {
if pars == nil {
return nan(), ErrNilPtrArg
}
v, t, x, k, r, q := GetFloatPriceParams(pars)
if err = CheckPriceParams(t, x, k, pars.Type); err != nil {
return nan(), err
}
theta = BSTheta(v, t, x, k, r, q, pars.Type)
return
}
// AtmApprox approximates the option price when exp(-q*t)*x == exp(-r*t)*k
// v = volatility in same units as t
// t = time to expiry
// x = value of spot/underlying
// r = continuously compounded interest rate in same units as t
// q = continuous dividend yield in same units as t
// o = option type (Call, Put, Straddle)
func AtmApprox(v, t, x, q float64, o OptionType) float64 {
switch o {
case Call, Put:
return exp(-q*t) * v * x * sqrt(t) * InvSqrt2PI
case Straddle:
return 2 * exp(-q*t) * v * x * sqrt(t) * InvSqrt2PI
}
return nan()
}
// CheckPriceParams checks whether t, x, k are non-negative and
// o is one of the defined Option Types
func CheckPriceParams(t, x, k float64, o OptionType) error {
if !ValidOptionType(o) {
return ErrUnknownOptionType
}
switch {
case t < 0:
return ErrNegTimeToExp
case x < 0:
return ErrNegPrice
case k < 0:
return ErrNegStrike
}
return nil
}
func GetFloatPriceParams(pars *PriceParams) (v, t, x, k, r, q float64) {
if pars == nil {
panic(ErrNilPtrArg)
}
v, t, x, k, r, q = pars.Vol, pars.TimeToExpiry,
pars.Underlying, pars.Strike, pars.Rate, pars.Dividend
return
}
// BSPrice returns the Black Scholes option price.
// v = volatility in same units as t
// t = time to expiry
// x = value of spot/underlying
// k = strike price
// r = continuously compounded interest rate in same units as t
// q = continuous dividend yield in same units as t
// o = option type (Call, Put, Straddle)
func BSPrice(v, t, x, k, r, q float64, o OptionType) float64 {
if CheckPriceParams(t, x, k, o) != nil {
return nan()
}
return BSPriceNoErrorCheck(v, t, x, k, r, q, o)
}
func BSPriceNoErrorCheck(v, t, x, k, r, q float64, o OptionType) float64 {
if v < 0 {
p := BSPrice(-v, t, x, k, r, q, o)
i := Intrinsic(t, x, k, r, q, o)
e := p - i
return i - e
}
switch {
case x == 0:
return ZeroUnderlyingBSPrice(t, k, r, o)
case k == 0:
return ZeroStrikeBSPrice(t, x, q, o)
case v == 0:
return Intrinsic(t, x, k, r, q, o)
}
d1 := D1(v, t, x, k, r, q)
d2 := D2fromD1(d1, v, t)
Nd1, Nd2 := NormCDF(d1), NormCDF(d2)
x, k = exp(-q*t)*x, exp(-r*t)*k
switch o {
case Call:
return Nd1*x - Nd2*k
case Put:
return (Nd1-1)*x - (Nd2-1)*k
}
return (2*Nd1-1)*x - (2*Nd2-1)*k
}
func BSDelta(v, t, x, k, r, q float64, o OptionType) float64 {
if v < 0 {
return 2*ZeroVolBSDelta(t, x, k, r, q, o) - BSDelta(-v, t, x, k, r, q, o)
}
if CheckPriceParams(t, x, k, o) != nil {
return nan()
}
switch {
case x == 0:
return ZeroUnderlyingBSDelta(t, q, o)
case k == 0:
return ZeroStrikeBSDelta(t, q, o)
case v == 0:
return ZeroVolBSDelta(t, x, k, r, q, o)
}
Nd1 := NormCDF(D1(v, t, x, k, r, q))
switch o {
case Call:
return exp(-q*t) * Nd1
case Put:
return exp(-q*t) * (Nd1 - 1)
}
return exp(-q*t) * (2*Nd1 - 1)
}
func BSGamma(v, t, x, k, r, q float64, o OptionType) float64 {
if v < 0 {
return 2*ZeroVolBSGamma(t, x, k, r, q) - BSGamma(-v, t, x, k, r, q, o)
}
if CheckPriceParams(t, x, k, o) != nil {
return nan()
}
switch {
case x == 0, k == 0:
return 0
case v == 0:
return ZeroVolBSGamma(t, x, k, r, q)
}
d1 := D1(v, t, x, k, r, q)
if o == Call || o == Put {
return exp(-q*t-d1*d1/2) / x / v / sqrt(t) * InvSqrt2PI
}
return 2 * exp(-q*t-d1*d1/2) / x / v / sqrt(t) * InvSqrt2PI
}
func BSTheta(v, t, x, k, r, q float64, o OptionType) float64 {
if v < 0 {
return 2*ZeroVolBSTheta(t, x, k, r, q, o) - BSTheta(-v, t, x, k, r, q, o)
}
if CheckPriceParams(t, x, k, o) != nil {
return nan()
}
switch {
case x == 0:
return ZeroUnderlyingBSTheta(t, k, r, o)
case k == 0:
return ZeroStrikeBSTheta(t, x, q, o)
case v == 0:
return ZeroVolBSTheta(t, x, k, r, q, o)
case t == 0:
return inf(-1)
}
d1 := D1(v, t, x, k, r, q)
d2 := D2fromD1(d1, v, t)
x, k = exp(-q*t)*x, exp(-r*t)*k
theta := -v * x * exp(-d1*d1/2) / 2 / sqrt(t) * InvSqrt2PI
theta += q*x*NormCDF(d1) - r*k*NormCDF(d2)
if o == Call || o == Put {
return theta
}
return 2 * theta
}
func BSVega(v, t, x, k, r, q float64, o OptionType) float64 {
if v < 0 {
return -BSVega(-v, t, x, k, r, q, o)
}
if CheckPriceParams(t, x, k, o) != nil {
return nan()
}
if v == 0 || t == 0 || x == 0 || k == 0 {
return 0
}
d1 := D1(v, t, x, k, r, q)
if o == Call || o == Put {
return x * exp(-q*t-d1*d1/2) * sqrt(t) * InvSqrt2PI
}
return 2 * x * exp(-q*t-d1*d1/2) * sqrt(t) * InvSqrt2PI
}
func D2fromD1(d1, v, t float64) float64 {
return d1 - v*sqrt(t)
}
func D1(v, t, x, k, r, q float64) float64 {
return (log(x/k) + (r-q+0.5*v*v)*t) / v / sqrt(t)
}
func D2(v, t, x, k, r, q float64) float64 {
return (log(x/k) + (r-q-0.5*v*v)*t) / v / sqrt(t)
}
func Intrinsic(t, x, k, r, q float64, o OptionType) float64 {
p := exp(-q*t)*x - exp(-r*t)*k
switch o {
case Call:
return max(0, +p)
case Put:
return max(0, -p)
}
return abs(p)
}
func ValidOptionType(o OptionType) bool {
return o == Call || o == Put || o == Straddle
}
func ZeroStrikeBSPrice(t, x, q float64, o OptionType) float64 {
switch o {
case Call, Straddle:
return exp(-q*t) * x
case Put:
return 0
}
return nan()
}
func ZeroUnderlyingBSPrice(t, k, r float64, o OptionType) float64 {
switch o {
case Call:
return 0
case Put, Straddle:
return exp(-r*t) * k
}
return nan()
}
func ZeroStrikeBSDelta(t, q float64, o OptionType) float64 {
switch o {
case Call, Straddle:
return exp(-q * t)
case Put:
return 0
}
return nan()
}
func ZeroUnderlyingBSDelta(t, q float64, o OptionType) float64 {
switch o {
case Call:
return 0
case Put, Straddle:
return -exp(-q * t)
}
return nan()
}
func ZeroVolBSDelta(t, x, k, r, q float64, o OptionType) float64 {
dfq := exp(-q * t)
x, k = dfq*x, exp(-r*t)*k
switch o {
case Call:
if x < k {
return 0
}
return dfq
case Put:
if x < k {
return -dfq
}
return 0
case Straddle:
if x < k {
return -dfq
}
return dfq
}
return nan()
}
func ZeroVolBSGamma(t, x, k, r, q float64) float64 {
if exp(-q*t)*x-exp(-r*t)*k != 0 {
return 0
}
return inf(1)
}
func ZeroStrikeBSTheta(t, x, q float64, o OptionType) float64 {
switch o {
case Call, Straddle:
return q * x * exp(-q*t)
case Put:
return 0
}
return nan()
}
func ZeroUnderlyingBSTheta(t, k, r float64, o OptionType) float64 {
switch o {
case Call:
return 0
case Put, Straddle:
return r * k * exp(-r*t)
}
return nan()
}
func ZeroVolBSTheta(t, x, k, r, q float64, o OptionType) float64 {
x, k = exp(-q*t)*x, exp(-r*t)*k
switch o {
case Call:
switch {
case x > k:
return q*x - r*k
case x < k:
return 0
default:
return q * x
}
case Put:
switch {
case x > k:
return 0
case x < k:
return r*k - q*x
default:
return r * k
}
case Straddle:
switch {
case x > k:
return q*x - r*k
case x < k:
return r*k - q*x
default:
return q*x + r*k
}
}
return nan()
} | blackscholes.go | 0.753739 | 0.40869 | blackscholes.go | starcoder |
package collection
import (
"github.com/goal-web/contracts"
"github.com/goal-web/supports/utils"
)
func (this *Collection) Pluck(key string) contracts.Fields {
fields := contracts.Fields{}
for index, data := range this.mapData {
var name, ok = data[key].(string)
if _, exists := fields[name]; ok && !exists {
fields[name] = this.array[index]
}
}
return fields
}
func (this *Collection) Only(keys ...string) contracts.Collection {
arrayFields := make([]contracts.Fields, 0)
rawResults := make([]interface{}, 0)
for index, data := range this.mapData {
fields := contracts.Fields{}
for key, value := range data {
if utils.IsIn(key, keys) {
fields[key] = value
}
}
arrayFields = append(arrayFields, fields)
rawResults = append(rawResults, this.array[index])
}
return &Collection{mapData: arrayFields, array: rawResults}
}
func (this *Collection) First(keys ...string) interface{} {
if this.Count() == 0 {
return nil
}
if len(keys) == 0 {
return this.array[0]
}
return this.mapData[0][keys[0]]
}
func (this *Collection) Last(keys ...string) interface{} {
if this.Count() == 0 {
return nil
}
if len(keys) == 0 {
return this.array[len(this.array)-1]
}
return this.mapData[len(this.array)-1][keys[0]]
}
func (this *Collection) Prepend(items ...interface{}) contracts.Collection {
newCollection := &Collection{}
newCollection.array = append(items, this.array...)
if len(this.mapData) > 0 {
newMaps := make([]contracts.Fields, 0)
for _, item := range items {
fields, _ := utils.ConvertToFields(item)
newMaps = append(newMaps, fields)
}
newCollection.mapData = append(newMaps, this.mapData...)
}
return newCollection
}
func (this *Collection) Push(items ...interface{}) contracts.Collection {
newCollection := &Collection{}
newCollection.array = append(this.array, items...)
if len(this.mapData) > 0 {
newMaps := make([]contracts.Fields, 0)
for _, item := range items {
fields, _ := utils.ConvertToFields(item)
newMaps = append(newMaps, fields)
}
newCollection.mapData = append(this.mapData, newMaps...)
}
return newCollection
}
func (this *Collection) Pull(defaultValue ...interface{}) interface{} {
if result := this.Last(); result != nil {
this.array = this.array[:this.Count()-1]
if len(this.mapData) > 0 {
this.mapData = this.mapData[:this.Count()-1]
}
return result
} else if len(defaultValue) > 0 {
return defaultValue[0]
}
return nil
}
func (this *Collection) Shift(defaultValue ...interface{}) interface{} {
if result := this.First(); result != nil {
this.array = this.array[1:]
if len(this.mapData) > 0 {
this.mapData = this.mapData[1:]
}
return result
} else if len(defaultValue) > 0 {
return defaultValue[0]
}
return nil
}
func (this *Collection) Offset(index int, item interface{}) contracts.Collection {
if this.Count() > index {
this.array[index] = item
if len(this.mapData) > 0 {
fields, _ := utils.ConvertToFields(item)
this.mapData[index] = fields
}
return this
}
return this.Push(item)
}
func (this *Collection) Put(index int, item interface{}) contracts.Collection {
if this.Count() > index {
return (&Collection{array: append(this.array), mapData: append(this.mapData)}).Offset(index, item)
}
return this.Push(item)
}
func (this *Collection) Merge(collections ...contracts.Collection) contracts.Collection {
newCollection := &Collection{array: append(this.array), mapData: append(this.mapData)}
for _, collection := range collections {
newCollection.mapData = append(newCollection.mapData, collection.ToArrayFields()...)
newCollection.array = append(newCollection.array, collection.ToInterfaceArray()...)
}
return newCollection
}
func (this *Collection) Reverse() contracts.Collection {
newCollection := &Collection{array: append(this.array), mapData: append(this.mapData)}
for from, to := 0, len(newCollection.array)-1; from < to; from, to = from+1, to-1 {
newCollection.array[from], newCollection.array[to] = newCollection.array[to], newCollection.array[from]
if len(this.mapData) > 0 {
newCollection.mapData[from], newCollection.mapData[to] = newCollection.mapData[to], newCollection.mapData[from]
}
}
return newCollection
}
func (this *Collection) Chunk(size int, handler func(collection contracts.Collection, page int) error) (err error) {
total := this.Count()
page := 1
for err == nil && (page-1)*size <= total {
offset := (page - 1) * size
endIndex := size + offset
if endIndex > total {
endIndex = total
}
newCollection := &Collection{array: this.array[offset:endIndex]}
if len(this.mapData) > 0 {
newCollection.mapData = this.mapData[offset:endIndex]
}
err = handler(newCollection, page)
page++
}
return
}
func (this *Collection) Random(size ...uint) contracts.Collection {
num := 1
if len(size) > 0 {
num = int(size[0])
}
newCollection := &Collection{}
if this.Count() >= num {
for _, index := range utils.RandIntArray(0, this.Count()-1, num) {
newCollection.array = append(newCollection.array, this.array[index])
if len(this.mapData) > 0 {
newCollection.mapData = append(newCollection.mapData, this.mapData[index])
}
}
}
return newCollection
} | operate.go | 0.515132 | 0.402598 | operate.go | starcoder |
package statsd
import (
"math"
"math/rand"
"sort"
)
const defaultPercentileLimit = 1000
// // RunningStats calculates a running mean, variance, standard deviation,
// // lower bound, upper bound, count, and can calculate estimated percentiles.
// // It is based on the incremental algorithm described here:
// // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
// type RunningStats struct {
// k float64
// n int64
// ex float64
// ex2 float64
// // Array used to calculate estimated percentiles
// // We will store a maximum of PercLimit values, at which point we will start
// // randomly replacing old values, hence it is an estimated percentile.
// perc []float64
// PercLimit int
// sum float64
// lower float64
// upper float64
// // cache if we have sorted the list so that we never re-sort a sorted list,
// // which can have very bad performance.
// sorted bool
// }
// RunningStats calculates a running mean, variance, standard deviation,
// lower bound, upper bound, count, and can calculate estimated percentiles.
// It is based on the incremental algorithm described here:
// https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
type RunningStats struct {
perc []float64
k float64
n int64
ex float64
ex2 float64
PercLimit int
sum float64
lower float64
upper float64
sorted bool
}
func (rs *RunningStats) AddValue(v float64) {
// Whenever a value is added, the list is no longer sorted.
rs.sorted = false
if rs.n == 0 {
rs.k = v
rs.upper = v
rs.lower = v
if rs.PercLimit == 0 {
rs.PercLimit = defaultPercentileLimit
}
rs.perc = make([]float64, 0, rs.PercLimit)
}
// These are used for the running mean and variance
rs.n++
rs.ex += v - rs.k
rs.ex2 += (v - rs.k) * (v - rs.k)
// add to running sum
rs.sum += v
// track upper and lower bounds
if v > rs.upper {
rs.upper = v
} else if v < rs.lower {
rs.lower = v
}
if len(rs.perc) < rs.PercLimit {
rs.perc = append(rs.perc, v)
} else {
// Reached limit, choose random index to overwrite in the percentile array
rs.perc[rand.Intn(len(rs.perc))] = v //nolint:gosec // G404
}
}
func (rs *RunningStats) Mean() float64 {
return rs.k + rs.ex/float64(rs.n)
}
func (rs *RunningStats) Variance() float64 {
return (rs.ex2 - (rs.ex*rs.ex)/float64(rs.n)) / float64(rs.n)
}
func (rs *RunningStats) Stddev() float64 {
return math.Sqrt(rs.Variance())
}
func (rs *RunningStats) Sum() float64 {
return rs.sum
}
func (rs *RunningStats) Upper() float64 {
return rs.upper
}
func (rs *RunningStats) Lower() float64 {
return rs.lower
}
func (rs *RunningStats) Count() int64 {
return rs.n
}
func (rs *RunningStats) Percentile(n float64) float64 {
if n > 100 {
n = 100
}
if !rs.sorted {
sort.Float64s(rs.perc)
rs.sorted = true
}
i := float64(len(rs.perc)) * n / float64(100)
return rs.perc[clamp(i, 0, len(rs.perc)-1)]
}
func clamp(i float64, min int, max int) int {
if i < float64(min) {
return min
}
if i > float64(max) {
return max
}
return int(i)
} | plugins/inputs/statsd/running_stats.go | 0.765243 | 0.549882 | running_stats.go | starcoder |
package accountmgmtclient
import (
"encoding/json"
"time"
)
// SummaryVector struct for SummaryVector
type SummaryVector struct {
Time *time.Time `json:"time,omitempty"`
Value *float64 `json:"value,omitempty"`
}
// NewSummaryVector instantiates a new SummaryVector 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 NewSummaryVector() *SummaryVector {
this := SummaryVector{}
return &this
}
// NewSummaryVectorWithDefaults instantiates a new SummaryVector 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 NewSummaryVectorWithDefaults() *SummaryVector {
this := SummaryVector{}
return &this
}
// GetTime returns the Time field value if set, zero value otherwise.
func (o *SummaryVector) GetTime() time.Time {
if o == nil || o.Time == nil {
var ret time.Time
return ret
}
return *o.Time
}
// GetTimeOk returns a tuple with the Time field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *SummaryVector) GetTimeOk() (*time.Time, bool) {
if o == nil || o.Time == nil {
return nil, false
}
return o.Time, true
}
// HasTime returns a boolean if a field has been set.
func (o *SummaryVector) HasTime() bool {
if o != nil && o.Time != nil {
return true
}
return false
}
// SetTime gets a reference to the given time.Time and assigns it to the Time field.
func (o *SummaryVector) SetTime(v time.Time) {
o.Time = &v
}
// GetValue returns the Value field value if set, zero value otherwise.
func (o *SummaryVector) GetValue() float64 {
if o == nil || o.Value == nil {
var ret float64
return ret
}
return *o.Value
}
// GetValueOk returns a tuple with the Value field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *SummaryVector) GetValueOk() (*float64, bool) {
if o == nil || o.Value == nil {
return nil, false
}
return o.Value, true
}
// HasValue returns a boolean if a field has been set.
func (o *SummaryVector) HasValue() bool {
if o != nil && o.Value != nil {
return true
}
return false
}
// SetValue gets a reference to the given float64 and assigns it to the Value field.
func (o *SummaryVector) SetValue(v float64) {
o.Value = &v
}
func (o SummaryVector) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.Time != nil {
toSerialize["time"] = o.Time
}
if o.Value != nil {
toSerialize["value"] = o.Value
}
return json.Marshal(toSerialize)
}
type NullableSummaryVector struct {
value *SummaryVector
isSet bool
}
func (v NullableSummaryVector) Get() *SummaryVector {
return v.value
}
func (v *NullableSummaryVector) Set(val *SummaryVector) {
v.value = val
v.isSet = true
}
func (v NullableSummaryVector) IsSet() bool {
return v.isSet
}
func (v *NullableSummaryVector) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableSummaryVector(val *SummaryVector) *NullableSummaryVector {
return &NullableSummaryVector{value: val, isSet: true}
}
func (v NullableSummaryVector) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableSummaryVector) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | accountmgmt/apiv1/client/model_summary_vector.go | 0.859546 | 0.560734 | model_summary_vector.go | starcoder |
package util
import (
"fmt"
"reflect"
"github.com/kr/pretty"
)
// IsString reports whether value is a string type.
func IsString(value interface{}) bool {
return reflect.TypeOf(value).Kind() == reflect.String
}
// IsPtr reports whether value is a ptr type.
func IsPtr(value interface{}) bool {
return reflect.TypeOf(value).Kind() == reflect.Ptr
}
// IsMap reports whether value is a map type.
func IsMap(value interface{}) bool {
return reflect.TypeOf(value).Kind() == reflect.Map
}
// IsMapPtr reports whether v is a map ptr type.
func IsMapPtr(v interface{}) bool {
t := reflect.TypeOf(v)
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Map
}
// IsSlice reports whether value is a slice type.
func IsSlice(value interface{}) bool {
return reflect.TypeOf(value).Kind() == reflect.Slice
}
// IsSlicePtr reports whether v is a slice ptr type.
func IsSlicePtr(v interface{}) bool {
t := reflect.TypeOf(v)
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Slice
}
// IsSliceInterfacePtr reports whether v is a slice ptr type.
func IsSliceInterfacePtr(v interface{}) bool {
// Must use ValueOf because Elem().Elem() type resolves dynamically.
vv := reflect.ValueOf(v)
return vv.Kind() == reflect.Ptr && vv.Elem().Kind() == reflect.Interface && vv.Elem().Elem().Kind() == reflect.Slice
}
// IsInterfacePtr reports whether v is a slice ptr type.
func IsInterfacePtr(v interface{}) bool {
t := reflect.TypeOf(v)
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Interface
}
// IsTypeStruct reports whether t is a struct type.
func IsTypeStruct(t reflect.Type) bool {
return t.Kind() == reflect.Struct
}
// IsTypeStructPtr reports whether v is a struct ptr type.
func IsTypeStructPtr(t reflect.Type) bool {
if t == reflect.TypeOf(nil) {
return false
}
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}
// IsTypeSlice reports whether v is a slice type.
func IsTypeSlice(t reflect.Type) bool {
return t.Kind() == reflect.Slice
}
// IsTypeSlicePtr reports whether v is a slice ptr type.
func IsTypeSlicePtr(t reflect.Type) bool {
if t == reflect.TypeOf(nil) {
return false
}
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Slice
}
// IsTypeMap reports whether v is a map type.
func IsTypeMap(t reflect.Type) bool {
if t == reflect.TypeOf(nil) {
return false
}
return t.Kind() == reflect.Map
}
// IsTypeInterface reports whether v is an interface.
func IsTypeInterface(t reflect.Type) bool {
if t == reflect.TypeOf(nil) {
return false
}
return t.Kind() == reflect.Interface
}
// IsTypeSliceOfInterface reports whether v is a slice of interface.
func IsTypeSliceOfInterface(t reflect.Type) bool {
if t == reflect.TypeOf(nil) {
return false
}
return t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Interface
}
// IsNilOrInvalidValue reports whether v is nil or reflect.Zero.
func IsNilOrInvalidValue(v reflect.Value) bool {
return !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) || IsValueNil(v.Interface())
}
// IsValueNil returns true if either value is nil, or has dynamic type {ptr,
// map, slice} with value nil.
func IsValueNil(value interface{}) bool {
if value == nil {
return true
}
switch reflect.TypeOf(value).Kind() {
case reflect.Slice, reflect.Ptr, reflect.Map:
return reflect.ValueOf(value).IsNil()
}
return false
}
// IsValueNilOrDefault returns true if either IsValueNil(value) or the default
// value for the type.
func IsValueNilOrDefault(value interface{}) bool {
if IsValueNil(value) {
return true
}
if !IsValueScalar(reflect.ValueOf(value)) {
// Default value is nil for non-scalar types.
return false
}
return value == reflect.New(reflect.TypeOf(value)).Elem().Interface()
}
// IsValuePtr reports whether v is a ptr type.
func IsValuePtr(v reflect.Value) bool {
return v.Kind() == reflect.Ptr
}
// IsValueInterface reports whether v is an interface type.
func IsValueInterface(v reflect.Value) bool {
return v.Kind() == reflect.Interface
}
// IsValueStruct reports whether v is a struct type.
func IsValueStruct(v reflect.Value) bool {
return v.Kind() == reflect.Struct
}
// IsValueStructPtr reports whether v is a struct ptr type.
func IsValueStructPtr(v reflect.Value) bool {
return v.Kind() == reflect.Ptr && IsValueStruct(v.Elem())
}
// IsValueMap reports whether v is a map type.
func IsValueMap(v reflect.Value) bool {
return v.Kind() == reflect.Map
}
// IsValueSlice reports whether v is a slice type.
func IsValueSlice(v reflect.Value) bool {
return v.Kind() == reflect.Slice
}
// IsValueScalar reports whether v is a scalar type.
func IsValueScalar(v reflect.Value) bool {
if IsNilOrInvalidValue(v) {
return false
}
if IsValuePtr(v) {
if v.IsNil() {
return false
}
v = v.Elem()
}
return !IsValueStruct(v) && !IsValueMap(v) && !IsValueSlice(v)
}
// ValuesAreSameType returns true if v1 and v2 has the same reflect.Type,
// otherwise it returns false.
func ValuesAreSameType(v1 reflect.Value, v2 reflect.Value) bool {
return v1.Type() == v2.Type()
}
// IsEmptyString returns true if value is an empty string.
func IsEmptyString(value interface{}) bool {
if value == nil {
return true
}
switch reflect.TypeOf(value).Kind() {
case reflect.String:
return value.(string) == ""
}
return false
}
// DeleteFromSlicePtr deletes an entry at index from the parent, which must be a slice ptr.
func DeleteFromSlicePtr(parentSlice interface{}, index int) error {
dbgPrint("DeleteFromSlicePtr index=%d, slice=\n%s", index, pretty.Sprint(parentSlice))
pv := reflect.ValueOf(parentSlice)
if !IsSliceInterfacePtr(parentSlice) {
return fmt.Errorf("deleteFromSlicePtr parent type is %T, must be *[]interface{}", parentSlice)
}
pvv := pv.Elem()
if pvv.Kind() == reflect.Interface {
pvv = pvv.Elem()
}
pv.Elem().Set(reflect.AppendSlice(pvv.Slice(0, index), pvv.Slice(index+1, pvv.Len())))
return nil
}
// UpdateSlicePtr updates an entry at index in the parent, which must be a slice ptr, with the given value.
func UpdateSlicePtr(parentSlice interface{}, index int, value interface{}) error {
dbgPrint("UpdateSlicePtr parent=\n%s\n, index=%d, value=\n%v", pretty.Sprint(parentSlice), index, value)
pv := reflect.ValueOf(parentSlice)
v := reflect.ValueOf(value)
if !IsSliceInterfacePtr(parentSlice) {
return fmt.Errorf("updateSlicePtr parent type is %T, must be *[]interface{}", parentSlice)
}
pvv := pv.Elem()
if pvv.Kind() == reflect.Interface {
pv.Elem().Elem().Index(index).Set(v)
return nil
}
pv.Elem().Index(index).Set(v)
return nil
}
// InsertIntoMap inserts value with key into parent which must be a map, map ptr, or interface to map.
func InsertIntoMap(parentMap interface{}, key interface{}, value interface{}) error {
dbgPrint("InsertIntoMap key=%v, value=%s, map=\n%s", key, pretty.Sprint(value), pretty.Sprint(parentMap))
v := reflect.ValueOf(parentMap)
kv := reflect.ValueOf(key)
vv := reflect.ValueOf(value)
if v.Type().Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Type().Kind() == reflect.Interface {
v = v.Elem()
}
if v.Type().Kind() != reflect.Map {
dbgPrint("error %v", v.Type().Kind())
return fmt.Errorf("insertIntoMap parent type is %T, must be map", parentMap)
}
v.SetMapIndex(kv, vv)
return nil
}
// ToIntValue returns 0, false if val is not a number type, otherwise it returns the int value of val.
func ToIntValue(val interface{}) (int, bool) {
if IsValueNil(val) {
return 0, true
}
v := reflect.ValueOf(val)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return int(v.Int()), true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return int(v.Uint()), true
}
return 0, false
} | pkg/util/reflect.go | 0.758913 | 0.568775 | reflect.go | starcoder |
package position
import (
"strconv"
"strings"
"github.com/scancel/go-deribit/v3/models"
)
// Position is almost the same struct as in v3/models/position.go
type Position struct {
// Average price of trades that built this position
// Required: true
AveragePrice float64
// Only for options, average price in USD
AveragePriceUsd float64
// Delta parameter
// Required: true
Delta float64
// direction
// Required: true
Direction models.Direction
// Only for futures, estimated liquidation price
EstimatedLiquidationPrice float64
// Floating profit or loss
// Required: true
FloatingProfitLoss float64
// Only for options, floating profit or loss in USD
FloatingProfitLossUsd float64
// Current index price
// Required: true
IndexPrice float64
// Initial margin
// Required: true
InitialMargin float64
// instrument name
// Required: true
InstrumentName models.InstrumentName
// kind
// Required: true
Kind models.Kind
// Maintenance margin
// Required: true
MaintenanceMargin float64
// Current mark price for position's instrument
// Required: true
MarkPrice float64
// Open orders margin
// Required: true
OpenOrdersMargin float64
// Realized profit or loss
// Required: true
RealizedProfitLoss float64
// Last settlement price for position's instrument 0 if instrument wasn't settled yet
// Required: true
SettlementPrice float64
// Position size for futures size in quote currency (e.g. USD), for options size is in base currency (e.g. BTC)
// Required: true
Size float64
// Only for futures, position size in base currency
SizeCurrency float64
// Profit or loss from position
// Required: true
TotalProfitLoss float64
}
// Sprintf exports a string
func (pPosition Position) Sprintf() string {
var output string
output += "AveragePrice: " + strconv.FormatFloat(pPosition.AveragePrice, 'f', 6, 32) + "\n"
output += "AveragePriceUsd: " + strconv.FormatFloat(pPosition.AveragePriceUsd, 'f', 6, 32) + "\n"
output += "Delta: " + strconv.FormatFloat(pPosition.Delta, 'f', 2, 32) + "\n"
output += "Direction:" + strings.ToUpper(string(pPosition.Direction)) + "\n"
output += "EstimatedLiquidationPrice: " + strconv.FormatFloat(pPosition.EstimatedLiquidationPrice, 'f', 6, 32) + "\n"
output += "FloatingProfitLoss:" + strconv.FormatFloat(pPosition.FloatingProfitLoss, 'f', 2, 32) + "\n"
output += "FloatingProfitLossUsd: " + strconv.FormatFloat(pPosition.FloatingProfitLossUsd, 'f', 2, 32) + "\n"
output += "IndexPrice:" + strconv.FormatFloat(pPosition.IndexPrice, 'f', 6, 32) + "\n"
output += "InitialMargin: " + strconv.FormatFloat(pPosition.InitialMargin, 'f', 6, 32) + "\n"
output += "InstrumentName: " + strings.ToUpper(string(pPosition.InstrumentName)) + "\n"
output += "Kind: " + string(pPosition.Kind) + "\n"
output += "MaintenanceMargin: " + strconv.FormatFloat(pPosition.MaintenanceMargin, 'f', 6, 32) + "\n"
output += "MarkPrice: " + strconv.FormatFloat(pPosition.MarkPrice, 'f', 6, 32) + "\n"
output += "OpenOrdersMargin: " + strconv.FormatFloat(pPosition.OpenOrdersMargin, 'f', 6, 32) + "\n"
output += "RealizedProfitLoss: " + strconv.FormatFloat(pPosition.RealizedProfitLoss, 'f', 6, 32) + "\n"
output += "SettlementPrice: " + strconv.FormatFloat(pPosition.SettlementPrice, 'f', 6, 32) + "\n"
output += "Size: " + strconv.FormatFloat(pPosition.Size, 'f', 6, 32) + "\n"
output += "SizeCurrency: " + strconv.FormatFloat(pPosition.SizeCurrency, 'f', 6, 32) + "\n"
output += "TotalProfitLoss: " + strconv.FormatFloat(pPosition.TotalProfitLoss, 'f', 6, 32) + "\n"
return output
} | v3/structures/position/position.go | 0.562417 | 0.423339 | position.go | starcoder |
package main
import (
"image"
"image/draw"
"log"
"github.com/mewkiz/pkg/imgutil"
"github.com/mewmew/pgg/grid"
"github.com/mewmew/pgg/tileset"
"github.com/mewmew/pgg/view"
)
func init() {
// Specify the width and height of grid cells.
grid.CellWidth = 48
grid.CellHeight = 48
}
func main() {
err := world()
if err != nil {
log.Fatalln(err)
}
}
// Number of columns and rows of the entire map.
const (
MapCols = 9
MapRows = 11
)
// Tile identifiers.
const (
Grass tileset.TileID = 1
Sand tileset.TileID = 2
Water tileset.TileID = 3
Gravel tileset.TileID = 4
)
// world initializes and renders the game world.
func world() (err error) {
// Initialize map.
m := grid.NewMap(MapCols, MapRows)
initLevel(m)
// Initialize view.
viewCols := 6
viewRows := 6
width := viewCols * grid.CellWidth
height := viewRows * grid.CellHeight
mapWidth := MapCols * grid.CellWidth
mapHeight := MapRows * grid.CellHeight
end := image.Pt(mapWidth, mapHeight)
v := view.NewView(width, height, end)
// Initialize world image.
world := image.NewRGBA(image.Rect(0, 0, width, height))
// Initialize tileset.
tileWidth := grid.CellWidth
tileHeight := grid.CellHeight
ts, err := tileset.Open("tileset 2.png", tileWidth, tileHeight)
if err != nil {
return err
}
// drawTile draws the tile at the specified column and row.
drawTile := func(col, row int) {
x := col*grid.CellWidth - v.X()
y := row*grid.CellHeight - v.Y()
dr := image.Rect(x, y, x+tileWidth, y+tileHeight)
viewCol := col + v.Col()
viewRow := row + v.Row()
id := tileset.TileID(m[viewCol][viewRow])
tile := ts.Tile(id)
sp := tile.Bounds().Min
draw.Draw(world, dr, tile, sp, draw.Over)
}
// Draw loop.
for col := 0; col < v.Cols(); col++ {
for row := 0; row < v.Rows(); row++ {
drawTile(col, row)
}
}
// Output world image.
err = imgutil.WriteFile("world.png", world)
if err != nil {
return err
}
return nil
}
// initLevel initializes the provided map with the tiles of a simple level.
func initLevel(m grid.Map) {
// Col 0.
m[0][0] = grid.Cell(Water)
m[0][1] = grid.Cell(Water)
m[0][2] = grid.Cell(Water)
m[0][3] = grid.Cell(Water)
m[0][4] = grid.Cell(Water)
m[0][5] = grid.Cell(Water)
m[0][6] = grid.Cell(Water)
m[0][7] = grid.Cell(Water)
m[0][8] = grid.Cell(Water)
m[0][9] = grid.Cell(Water)
m[0][10] = grid.Cell(Water)
// Col 1.
m[1][0] = grid.Cell(Water)
m[1][1] = grid.Cell(Water)
m[1][2] = grid.Cell(Water)
m[1][3] = grid.Cell(Water)
m[1][4] = grid.Cell(Water)
m[1][5] = grid.Cell(Water)
m[1][6] = grid.Cell(Water)
m[1][7] = grid.Cell(Water)
m[1][8] = grid.Cell(Water)
m[1][9] = grid.Cell(Water)
m[1][10] = grid.Cell(Water)
// Col 2.
m[2][0] = grid.Cell(Water)
m[2][1] = grid.Cell(Water)
m[2][2] = grid.Cell(Sand)
m[2][3] = grid.Cell(Sand)
m[2][4] = grid.Cell(Sand)
m[2][5] = grid.Cell(Sand)
m[2][6] = grid.Cell(Sand)
m[2][7] = grid.Cell(Water)
m[2][8] = grid.Cell(Water)
m[2][9] = grid.Cell(Water)
m[2][10] = grid.Cell(Water)
// Col 3.
m[3][0] = grid.Cell(Sand)
m[3][1] = grid.Cell(Sand)
m[3][2] = grid.Cell(Gravel)
m[3][3] = grid.Cell(Gravel)
m[3][4] = grid.Cell(Gravel)
m[3][5] = grid.Cell(Gravel)
m[3][6] = grid.Cell(Sand)
m[3][7] = grid.Cell(Sand)
m[3][8] = grid.Cell(Sand)
m[3][9] = grid.Cell(Water)
m[3][10] = grid.Cell(Water)
// Col 4.
m[4][0] = grid.Cell(Sand)
m[4][1] = grid.Cell(Gravel)
m[4][2] = grid.Cell(Gravel)
m[4][3] = grid.Cell(Gravel)
m[4][4] = grid.Cell(Gravel)
m[4][5] = grid.Cell(Gravel)
m[4][6] = grid.Cell(Gravel)
m[4][7] = grid.Cell(Gravel)
m[4][8] = grid.Cell(Sand)
m[4][9] = grid.Cell(Sand)
m[4][10] = grid.Cell(Water)
// Col 5.
m[5][0] = grid.Cell(Gravel)
m[5][1] = grid.Cell(Gravel)
m[5][2] = grid.Cell(Gravel)
m[5][3] = grid.Cell(Grass)
m[5][4] = grid.Cell(Grass)
m[5][5] = grid.Cell(Grass)
m[5][6] = grid.Cell(Gravel)
m[5][7] = grid.Cell(Gravel)
m[5][8] = grid.Cell(Gravel)
m[5][9] = grid.Cell(Sand)
m[5][10] = grid.Cell(Water)
// Col 6.
m[6][0] = grid.Cell(Gravel)
m[6][1] = grid.Cell(Gravel)
m[6][2] = grid.Cell(Gravel)
m[6][3] = grid.Cell(Grass)
m[6][4] = grid.Cell(Grass)
m[6][5] = grid.Cell(Grass)
m[6][6] = grid.Cell(Gravel)
m[6][7] = grid.Cell(Gravel)
m[6][8] = grid.Cell(Gravel)
m[6][9] = grid.Cell(Sand)
m[6][10] = grid.Cell(Water)
// Col 7.
m[7][0] = grid.Cell(Gravel)
m[7][1] = grid.Cell(Gravel)
m[7][2] = grid.Cell(Gravel)
m[7][3] = grid.Cell(Grass)
m[7][4] = grid.Cell(Grass)
m[7][5] = grid.Cell(Grass)
m[7][6] = grid.Cell(Gravel)
m[7][7] = grid.Cell(Gravel)
m[7][8] = grid.Cell(Gravel)
m[7][9] = grid.Cell(Sand)
m[7][10] = grid.Cell(Water)
// Col 8.
m[8][0] = grid.Cell(Water)
m[8][1] = grid.Cell(Sand)
m[8][2] = grid.Cell(Water)
m[8][3] = grid.Cell(Grass)
m[8][4] = grid.Cell(Water)
m[8][5] = grid.Cell(Sand)
m[8][6] = grid.Cell(Water)
m[8][7] = grid.Cell(Grass)
m[8][8] = grid.Cell(Water)
m[8][9] = grid.Cell(Sand)
m[8][10] = grid.Cell(Water)
} | cmd/world/world.go | 0.635109 | 0.429071 | world.go | starcoder |
package cap1xxx
import (
"errors"
"periph.io/x/conn/v3/gpio"
)
// SamplingTime determines the time to make a single sample.
type SamplingTime uint8
// Valid SamplingTime values.
const (
S320us SamplingTime = 0
S640us SamplingTime = 1
// S1_28ms represents 1.28ms sampling time, which is the default.
S1_28ms SamplingTime = 2
S2_56ms SamplingTime = 3
)
// AvgSampling set the number of samples per measurement that get averaged.
type AvgSampling uint8
// Valid AvgSampling values.
const (
// Avg1 means that 1 sample is taken per measurement
Avg1 AvgSampling = iota // 0
Avg2 // 1
Avg4 // 2
Avg8 // 3 default
Avg16 // 4
Avg32 // 5
Avg64 // 6
Avg128 // 7
)
// CycleTime determines the overall cycle time for all measured channels during
// normal operation.
type CycleTime uint8
// Valid CycleTime values.
const (
C35ms CycleTime = iota // 0
C70ms // default
C105ms
C140ms
)
// MaxDur is the maximum duration of a touch event before it triggers a
// recalibration.
type MaxDur uint8
// Valid MaxDur values.
const (
MaxDur560ms MaxDur = iota
MaxDur840ms
MaxDur1120ms
MaxDur1400ms
MaxDur1680ms
MaxDur2240ms
MaxDur2800ms
MaxDur3360ms
MaxDur3920ms
MaxDur44800ms
MaxDur5600ms // default
MaxDur6720ms
MaxDur7840ms
MaxDur8906ms
MaxDur10080ms
MaxDur11200ms
)
// Opts is options to pass to the constructor.
type Opts struct {
// Debug turns on extra logging capabilities.
Debug bool
// I2CAddr is the I²C slave address to use. It can only used on creation of
// an I²C-device. Its default value is 0x28. It can be set to other values
// (0x29, 0x2a, 0x2b, 0x2c) depending on the HW configuration of the
// ADDR_COMM pin. Must not be set when used over SPI.
I2CAddr uint16
// LinkedLEDs indicates if the LEDs should be activated automatically
// when their sensors detect a touch event.
LinkedLEDs bool
// MaxTouchDuration sets the touch duration threshold. It is possible that a
// “stuck button” occurs when something is placed on a button which causes a
// touch to be detected for a long period. By setting this value, a
// recalibration can be forced when a touch is held on a button for longer
// than the duration specified.
MaxTouchDuration MaxDur
// EnableRecalibration is used to force the recalibration if a touch event
// lasts longer than MaxTouchDuration.
EnableRecalibration bool
// AlertPin is the pin receiving the interrupt when a touch event is detected
// and optionally if a release event is detected.
AlertPin gpio.PinIn
// ResetPin is the pin used to reset the device.
ResetPin gpio.PinOut
// InterruptOnRelease indicates if the device should also trigger an
// interrupt on the AlertPin when a release event is detected.
InterruptOnRelease bool
// RetriggerOnHold forces a retrigger of the interrupt when a sensor is
// pressed for longer than MaxTouchDuration
RetriggerOnHold bool
// Averaging and Sampling Configuration Register.
// SamplesPerMeasurement is the number of samples taken per measurement. All
// samples are taken consecutively on the same channel before the next
// channel is sampled and the result is averaged over the number of samples
// measured before updating the measured results.
// Available options: 1, 2, 4, 8 (default), 16, 32, 64, 128
SamplesPerMeasurement AvgSampling
// SamplingTime Determines the time to take a single sample as shown.
SamplingTime SamplingTime
// CycleTime determines the overall cycle time for all measured channels
// during normal operation. All measured channels are sampled at the
// beginning of the cycle time. If additional time is remaining, then the
// device is placed into a lower power state for the remaining duration of
// the cycle.
CycleTime CycleTime
}
func (o *Opts) i2cAddr() (uint16, error) {
switch o.I2CAddr {
case 0:
// Default address.
return 0x28, nil
case 0x28, 0x29, 0x2a, 0x2b, 0x2c:
return o.I2CAddr, nil
default:
return 0, errors.New("given address not supported by device")
}
}
// DefaultOpts contains default options to use.
var DefaultOpts = Opts{
LinkedLEDs: true,
MaxTouchDuration: MaxDur5600ms,
RetriggerOnHold: false,
EnableRecalibration: false,
InterruptOnRelease: false,
SamplesPerMeasurement: Avg1,
SamplingTime: S1_28ms,
CycleTime: C35ms,
} | cap1xxx/cap1xxx_options.go | 0.65379 | 0.400163 | cap1xxx_options.go | starcoder |
package zkbpp
import (
"math/big"
lr "github.com/ldsec/lattigo/ring"
)
//================================================================
//Gate functions at user's disposal
//================================================================
//MpcAdd adds *big.Int x to *big.Int y and returns the result
func (c *Circuit) MpcAdd(x ZKBVar, y ZKBVar) (z ZKBVar) {
z.shares = c.gates.add(x.shares, y.shares, c)
return
}
//MpcAddK adds *big.Int x to constant k and returns the result
func (c *Circuit) MpcAddK(x ZKBVar, k *big.Int) (z ZKBVar) {
z.shares = c.gates.addk(x.shares, []*big.Int{k}, c)
return
}
//MpcSub subtract *big.Int y from *big.Int x and returns the result
func (c *Circuit) MpcSub(x ZKBVar, y ZKBVar) (z ZKBVar) {
z.shares = c.gates.sub(x.shares, y.shares, c)
return
}
//MpcAddK adds *big.Int x to constant k and returns the result
func (c *Circuit) MpcSubK(x ZKBVar, k *big.Int) (z ZKBVar) {
z.shares = c.gates.subk(x.shares, []*big.Int{k}, c)
return
}
//MpcMult multiplies *big.Int x to *big.Int y and returns the result
func (c *Circuit) MpcMult(x ZKBVar, y ZKBVar) (z ZKBVar) {
z.shares = c.gates.mult(x.shares, y.shares, c)
return
}
//MpcMultK multiplies *big.Int x to constant k and returns the result
func (c *Circuit) MpcMultK(x ZKBVar, k *big.Int) (z ZKBVar) {
z.shares = c.gates.multk(x.shares, []*big.Int{k}, c)
return
}
//MpcRqAdd adds poly x to poly y and returns the result
func (c *Circuit) MpcRqAdd(x ZKBVar, y ZKBVar) (z ZKBVar) {
z.rqShares = c.rqGates.add(x.rqShares, y.rqShares, c)
return
}
//MpcRqAddK adds poly x to constant k and returns the result
func (c *Circuit) MpcRqAddK(x ZKBVar, k *lr.Poly) (z ZKBVar) {
z.rqShares = c.rqGates.addk(x.rqShares, []*lr.Poly{k}, c)
return
}
//MpcRqMultK multiplies poly x to constant k and returns the result
func (c *Circuit) MpcRqMultK(x ZKBVar, k *lr.Poly) (z ZKBVar) {
z.rqShares = c.rqGates.multk(x.rqShares, []*lr.Poly{k}, c)
return
}
//MpcZ2Xor computes the xor of var x and y, and returns the result
func (c *Circuit) MpcZ2Xor(x, y ZKBVar) (z ZKBVar) {
z.z2Shares = c.z2Gates.xor(x.z2Shares, y.z2Shares, c)
return
}
//MpcZ2Not computes the not of var x and returns the result
func (c *Circuit) MpcZ2Not(x ZKBVar) (z ZKBVar) {
z.z2Shares = c.z2Gates.not(x.z2Shares, nil, c)
return
}
//MpcZ2And computes the and of var x and y, and returns the result
func (c *Circuit) MpcZ2And(x, y ZKBVar) (z ZKBVar) {
z.z2Shares = c.z2Gates.and(x.z2Shares, y.z2Shares, c)
return
}
//MpcZ2RightShift rightshift var x by i and returns the result
func (c *Circuit) MpcZ2RightShift(x ZKBVar, i uint) (z ZKBVar) {
z.z2Shares = c.z2Gates.rightShift(x.z2Shares, i, c)
return
}
//MpcZ2And add var x and y, and returns the result
func (c *Circuit) MpcZ2Add(x, y ZKBVar) (z ZKBVar) {
z.z2Shares = c.z2Gates.add(x.z2Shares, y.z2Shares, c)
for i, share := range z.z2Shares {
z.z2Shares[i] = c.z2.Reduce(share)
}
return
}
//MpcZ2And add var x and constant k, and returns the result
func (c *Circuit) MpcZ2AddK(x ZKBVar, k *big.Int) (z ZKBVar) {
z.z2Shares = c.z2Gates.addk(x.z2Shares, []*big.Int{k}, c)
for i, share := range z.z2Shares {
z.z2Shares[i] = c.z2.Reduce(share)
}
return
}
//MpcBitdec transforms a additive secrect sharing into a XOR secrect sharing
//Use to go from ring Zq to ring Z2
func (c *Circuit) MpcBitDec(x ZKBVar) (z ZKBVar) {
z.z2Shares = c.z2Gates.bitDec(x.shares, c)
return
} | CRISP_go/zkbpp/circuit_gates.go | 0.776538 | 0.473414 | circuit_gates.go | starcoder |
package fan1
import "fmt"
const (
Table string = "table"
Ceiling string = "ceiling"
)
type Fan1 struct {
speed int // 1 through 5
kind string // "table", "ceiling"
color string
}
// First, we define an option type. It is a function that takes one argument, the Foo (Fan1) we are operating on.
type option func(fan *Fan1)
// The idea is that an option is implemented as a function we call to set the state of that option.
// That may seem odd, but there's a method in the madness.
// Given the option type, we next define an Option method on *Fan1 that applies the options it's passed
// by calling them as functions. That method is defined in the same package, say fan1, in which Fan1 is defined.
// Option sets the options specified.
func (f *Fan1) Option(opts ...option) {
for _, opt := range opts {
opt(f)
}
}
// Now to provide an option, we define in package fan1 a function with the appropriate name and signature.
// Let's say we want to control speed by setting an integer value stored in a field of a Fan1.
// We provide the speed option by writing a function with the obvious name and have it return an option,
// which means a closure; inside that closure we set the field (Me: encapsulation?) :
//Speed returns a function (closure) that accepts a Fan1 and sets its speed to the given speed
func Speed(s int) option {
return func(fan *Fan1) {
fan.speed = s
}
}
//Kind returns a function (closure) that accepts a Fan1 and sets its kind to the given kind
func Kind(k string) option {
return func(fan *Fan1) {
fan.kind = k
}
}
//Color returns a function (closure) that accepts a Fan1 and sets its color to the given color
func Color(c string) option {
return func(fan *Fan1) {
fan.color = c
}
}
// Why return a closure instead of just doing the setting?
// Because we don't want the user to have to write the closure and we want the
// Option method to be nice to use. (Plus there's more to come....)
//New returns a Ceiling Fan1
func New() *Fan1 {
return &Fan1{kind: Ceiling}
}
//String satisfies Stringer interface for Fan1
func (f *Fan1) String() string {
return fmt.Sprintf("Fan with speed: %v, kind: %v, color: %v", f.speed, f.kind, f.color)
} | src/fan1/fan.go | 0.739516 | 0.40028 | fan.go | starcoder |
package arg
import (
"errors"
"fmt"
"reflect"
"strconv"
)
type Argument struct {
// common fields
Type ArgType
Value string
// named only fields
Key string
// indexed only fields
Positon int
}
type expectedArg struct {
Type ArgType
ScalarType reflect.Value
Offset int
Keys []string
Values []string
Usage string
Default []string
Required bool
Override bool
Validate ValidatorFunc
}
type commandArg struct {
Key string
Title string
Usage string
}
func (e *expectedArg) inflate() error {
var err error
switch kind(e.ScalarType) {
case reflect.Bool:
err = inflateBool(e)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
err = inflateInt(e)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
err = inflateUint(e)
case reflect.Float32, reflect.Float64:
err = inflateFloat(e)
case reflect.String:
err = inflateString(e)
default:
// do nothing
}
return err
}
func inflateString(arg *expectedArg) error {
if isSlice(arg.ScalarType) {
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(arg.Values)))
} else {
arg.ScalarType.SetString(arg.Values[len(arg.Values)-1])
}
return nil
}
func inflateInt(arg *expectedArg) error {
var err error
var i int64
if isSlice(arg.ScalarType) {
switch kind(arg.ScalarType) {
case reflect.Int:
err = inflateIntslice(arg)
case reflect.Int32:
err = inflateInt32slice(arg)
case reflect.Int64:
err = inflateInt64slice(arg)
case reflect.Int16:
err = inflateInt16slice(arg)
case reflect.Int8:
err = inflateInt8slice(arg)
}
} else {
switch kind(arg.ScalarType) {
case reflect.Int:
i, err = strconv.ParseInt(arg.Values[len(arg.Values)-1], 10, 64)
case reflect.Int32:
i, err = strconv.ParseInt(arg.Values[len(arg.Values)-1], 10, 32)
case reflect.Int64:
i, err = strconv.ParseInt(arg.Values[len(arg.Values)-1], 10, 64)
case reflect.Int16:
i, err = strconv.ParseInt(arg.Values[len(arg.Values)-1], 10, 16)
case reflect.Int8:
i, err = strconv.ParseInt(arg.Values[len(arg.Values)-1], 10, 8)
}
if err == nil {
arg.ScalarType.SetInt(i)
}
}
return generateError(err, arg, kind(arg.ScalarType).String())
}
func inflateIntslice(arg *expectedArg) error {
var err error
var i int64
var newvals []int
for _, v := range arg.Values {
if i, err = strconv.ParseInt(v, 10, 64); nil != err {
return err
}
newvals = append(newvals, int(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateInt64slice(arg *expectedArg) error {
var err error
var i int64
var newvals []int64
for _, v := range arg.Values {
if i, err = strconv.ParseInt(v, 10, 64); nil != err {
return err
}
newvals = append(newvals, int64(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateInt32slice(arg *expectedArg) error {
var err error
var i int64
var newvals []int32
for _, v := range arg.Values {
if i, err = strconv.ParseInt(v, 10, 32); nil != err {
return err
}
newvals = append(newvals, int32(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateInt16slice(arg *expectedArg) error {
var err error
var i int64
var newvals []int16
for _, v := range arg.Values {
if i, err = strconv.ParseInt(v, 10, 16); nil != err {
return err
}
newvals = append(newvals, int16(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateInt8slice(arg *expectedArg) error {
var err error
var i int64
var newvals []int8
for _, v := range arg.Values {
if i, err = strconv.ParseInt(v, 10, 8); nil != err {
return err
}
newvals = append(newvals, int8(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateUint(arg *expectedArg) error {
var i uint64
var err error
if isSlice(arg.ScalarType) {
switch kind(arg.ScalarType) {
case reflect.Uint:
err = inflateUintslice(arg)
case reflect.Uint32:
err = inflateUint32slice(arg)
case reflect.Uint64:
err = inflateUint64slice(arg)
case reflect.Uint16:
err = inflateUint16slice(arg)
case reflect.Uint8:
err = inflateUint8slice(arg)
}
} else {
switch kind(arg.ScalarType) {
case reflect.Uint:
i, err = strconv.ParseUint(arg.Values[len(arg.Values)-1], 10, 64)
case reflect.Uint32:
i, err = strconv.ParseUint(arg.Values[len(arg.Values)-1], 10, 32)
case reflect.Uint64:
i, err = strconv.ParseUint(arg.Values[len(arg.Values)-1], 10, 64)
case reflect.Uint16:
i, err = strconv.ParseUint(arg.Values[len(arg.Values)-1], 10, 16)
case reflect.Uint8:
i, err = strconv.ParseUint(arg.Values[len(arg.Values)-1], 10, 8)
}
if err == nil {
arg.ScalarType.SetUint(i)
}
}
return generateError(err, arg, kind(arg.ScalarType).String())
}
func inflateUintslice(arg *expectedArg) error {
var err error
var i uint64
var newvals []uint
for _, v := range arg.Values {
if i, err = strconv.ParseUint(v, 10, 64); nil != err {
return err
}
newvals = append(newvals, uint(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateUint64slice(arg *expectedArg) error {
var err error
var i uint64
var newvals []uint64
for _, v := range arg.Values {
if i, err = strconv.ParseUint(v, 10, 64); nil != err {
return err
}
newvals = append(newvals, uint64(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateUint32slice(arg *expectedArg) error {
var err error
var i uint64
var newvals []uint32
for _, v := range arg.Values {
if i, err = strconv.ParseUint(v, 10, 32); nil != err {
return err
}
newvals = append(newvals, uint32(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateUint16slice(arg *expectedArg) error {
var err error
var i uint64
var newvals []uint16
for _, v := range arg.Values {
if i, err = strconv.ParseUint(v, 10, 16); nil != err {
return err
}
newvals = append(newvals, uint16(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateUint8slice(arg *expectedArg) error {
var err error
var i uint64
var newvals []uint8
for _, v := range arg.Values {
if i, err = strconv.ParseUint(v, 10, 8); nil != err {
return err
}
newvals = append(newvals, uint8(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateFloat(arg *expectedArg) error {
var i float64
var err error
if isSlice(arg.ScalarType) {
switch kind(arg.ScalarType) {
case reflect.Float32:
err = inflateFloat32slice(arg)
case reflect.Float64:
err = inflateFloat64slice(arg)
}
} else {
i, err = strconv.ParseFloat(arg.Values[len(arg.Values)-1], 64)
if err == nil {
arg.ScalarType.SetFloat(i)
}
}
return generateError(err, arg, kind(arg.ScalarType).String())
}
func inflateFloat32slice(arg *expectedArg) error {
var err error
var i float64
var newvals []float32
for _, v := range arg.Values {
if i, err = strconv.ParseFloat(v, 32); nil != err {
return err
}
newvals = append(newvals, float32(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateFloat64slice(arg *expectedArg) error {
var err error
var i float64
var newvals []float64
for _, v := range arg.Values {
if i, err = strconv.ParseFloat(v, 64); nil != err {
return err
}
newvals = append(newvals, float64(i))
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
return nil
}
func inflateBool(arg *expectedArg) error {
var i bool
var err error
if isSlice(arg.ScalarType) {
var newvals []bool
for _, v := range arg.Values {
if i, err = strconv.ParseBool(v); nil == err {
newvals = append(newvals, i)
}
}
arg.ScalarType.Set(reflect.AppendSlice(arg.ScalarType, reflect.ValueOf(newvals)))
} else {
i, err = strconv.ParseBool(arg.Values[len(arg.Values)-1])
if err == nil {
arg.ScalarType.SetBool(i)
}
}
return generateError(err, arg, kind(arg.ScalarType).String())
}
func generateError(err error, arg *expectedArg, typ string) error {
if nil == err {
return nil
}
if T_POSITIONAL == arg.Type {
return errors.New(fmt.Sprintf("Arg given at position %d was not of type %s", arg.Offset, typ))
} else {
return errors.New(fmt.Sprintf("Arg given for %s was notof type %s", arg.Keys[0], typ))
}
} | arg.go | 0.52902 | 0.450178 | arg.go | starcoder |
package gollection
func ArrayStackOf[T any](elements ...T) ArrayStack[T] {
var size = len(elements)
var stack = MakeArrayStack[T](size)
copy(stack.inner.elements, elements)
stack.inner.size = size
return stack
}
func MakeArrayStack[T any](capacity int) ArrayStack[T] {
if capacity < defaultElementsSize {
capacity = defaultElementsSize
}
var inner = &arrayStack[T]{make([]T, capacity), 0}
return ArrayStack[T]{inner}
}
func ArrayStackFrom[T any, I Collection[T]](collection I) ArrayStack[T] {
var inner = &arrayStack[T]{collection.ToSlice(), collection.Size()}
return ArrayStack[T]{inner}
}
type ArrayStack[T any] struct {
inner *arrayStack[T]
}
type arrayStack[T any] struct {
elements []T
size int
}
func (a ArrayStack[T]) Size() int {
return a.inner.size
}
func (a ArrayStack[T]) IsEmpty() bool {
return a.inner.size == 0
}
func (a ArrayStack[T]) Push(element T) {
if growSize := a.inner.size + 1; len(a.inner.elements) < growSize {
a.grow(growSize)
}
a.inner.elements[a.inner.size] = element
a.inner.size++
}
func (a ArrayStack[T]) Pop() T {
if v, ok := a.TryPop().Get(); ok {
return v
}
panic(OutOfBounds)
}
func (a ArrayStack[T]) Peek() T {
if v, ok := a.TryPeek().Get(); ok {
return v
}
panic(OutOfBounds)
}
func (a ArrayStack[T]) TryPop() Option[T] {
if a.IsEmpty() {
return None[T]()
}
var index = a.inner.size - 1
var item = a.inner.elements[index]
var empty T
a.inner.elements[index] = empty
a.inner.size--
return Some(item)
}
func (a ArrayStack[T]) TryPeek() Option[T] {
if a.IsEmpty() {
return None[T]()
}
return Some(a.inner.elements[a.inner.size-1])
}
func (a ArrayStack[T]) Iter() Iterator[T] {
return &arrayStackIterator[T]{a.Size(), a}
}
func (a ArrayStack[T]) ToSlice() []T {
var arr = make([]T, a.Size())
copy(arr, a.inner.elements)
return arr
}
func (a ArrayStack[T]) Clone() ArrayStack[T] {
var elements = make([]T, len(a.inner.elements))
copy(elements, a.inner.elements)
var inner = &arrayStack[T]{
elements: elements,
size: a.inner.size,
}
return ArrayStack[T]{inner}
}
func (a ArrayStack[T]) Reserve(additional int) {
if addable := len(a.inner.elements) - a.inner.size; addable < additional {
a.grow(a.inner.size + additional)
}
}
func (a ArrayStack[T]) Capacity() int {
return len(a.inner.elements)
}
func (a ArrayStack[T]) Clear() {
var emptyValue T
for i := 0; i < a.inner.size; i++ {
a.inner.elements[i] = emptyValue
}
a.inner.size = 0
}
func (a ArrayStack[T]) grow(minCapacity int) {
var newSize = arrayGrow(len(a.inner.elements))
if newSize < minCapacity {
newSize = minCapacity
}
var newSource = make([]T, newSize)
copy(newSource, a.inner.elements)
a.inner.elements = newSource
}
type arrayStackIterator[T any] struct {
index int
source ArrayStack[T]
}
func (a *arrayStackIterator[T]) Next() Option[T] {
if a.index > 0 {
a.index--
return Some(a.source.inner.elements[a.index])
}
return None[T]()
}
func (a *arrayStackIterator[T]) Iter() Iterator[T] {
return a
} | array_stack.go | 0.64131 | 0.495728 | array_stack.go | starcoder |
package parser
import (
"errors"
"github.com/Callidon/joseki/rdf"
)
// tokenURI represent a RDF URI
type tokenURI struct {
value string
}
// newTokenURI creates a new tokenURI
func newTokenURI(value string) *tokenURI {
return &tokenURI{value}
}
// Interpret evaluate the token & produce an action.
// In the case of a tokenURI, it push a URI on top of the stack
func (t tokenURI) Interpret(nodeStack *stack, prefixes *map[string]string, out chan rdf.Triple) error {
nodeStack.Push(rdf.NewURI(t.value))
return nil
}
// tokenLiteral represent a RDF Literal
type tokenLiteral struct {
value string
}
// newTokenLiteral creates a new tokenLiteral
func newTokenLiteral(value string) *tokenLiteral {
return &tokenLiteral{value}
}
// Interpret evaluate the token & produce an action.
// In the case of a tokenLiteral, it push a Literal on top of the stack
func (t tokenLiteral) Interpret(nodeStack *stack, prefixes *map[string]string, out chan rdf.Triple) error {
nodeStack.Push(rdf.NewLiteral(t.value))
return nil
}
// tokenType represent a type for a RDF Literal
type tokenType struct {
value string
*tokenPosition
}
// newTokenType creates a new tokenType.
// Since this token can produce an error, its position is needed for a better error handling
func newTokenType(value string, line int, row int) *tokenType {
return &tokenType{value, newTokenPosition(line, row)}
}
// Interpret evaluate the token & produce an action.
// In the case of a tokenType, it push a typed Literal on top of the stack
func (t tokenType) Interpret(nodeStack *stack, prefixes *map[string]string, out chan rdf.Triple) error {
if nodeStack.Len() < 1 {
return errors.New("encountered a malformed literal at " + t.position())
}
literal, isLiteral := nodeStack.Pop().(rdf.Literal)
if !isLiteral {
return errors.New("A XML type can only be associated with a RDF Literal, at " + t.position())
}
nodeStack.Push(rdf.NewTypedLiteral(literal.Value, t.value))
return nil
}
// tokenLang represent a localization information about a RDF Literal
type tokenLang struct {
value string
*tokenPosition
}
// newTokenLang creates a new tokenLang.
// Since this token can produce an error, its position is needed for a better error handling
func newTokenLang(value string, line int, row int) *tokenLang {
return &tokenLang{value, newTokenPosition(line, row)}
}
// Interpret evaluate the token & produce an action.
// In the case of a tokenLang, it push a Literal with its associated language on top of the stack
func (t tokenLang) Interpret(nodeStack *stack, prefixes *map[string]string, out chan rdf.Triple) error {
if nodeStack.Len() < 1 {
return errors.New("encountered a malformed literal at " + t.position())
}
literal, isLiteral := nodeStack.Pop().(rdf.Literal)
if !isLiteral {
return errors.New("A localization information can only be associated with a RDF Literal, at " + t.position())
}
nodeStack.Push(rdf.NewLangLiteral(literal.Value, t.value))
return nil
}
// tokenBlankNode represent a RDF Blank Node
type tokenBlankNode struct {
value string
}
// newTokenBlankNode creates a new tokenBlankNode
func newTokenBlankNode(value string) *tokenBlankNode {
return &tokenBlankNode{value}
}
// Interpret evaluate the token & produce an action.
// In the case of a tokenBlankNode, it push a Blank Node on top of the stack
func (t tokenBlankNode) Interpret(nodeStack *stack, prefixes *map[string]string, out chan rdf.Triple) error {
nodeStack.Push(rdf.NewBlankNode(t.value))
return nil
} | parser/baseTokens.go | 0.825238 | 0.514827 | baseTokens.go | starcoder |
GoAniGiffy is a utility for converting a set of alphabetically sorted images such as video frames
grabbed from VLC or MPlayer into an animated GIF with options to Crop, Resize, Rotate & Flip the
images prior to creating the GIF
GoAniGiffy performs image operations in the order of cropping, scaling, rotating & flipping
before converting the images into an Animated GIF. Image manipulation is done using
Grigory Dryapak's imaging package. We use the Lanczos filter in Resizing and the default
Floyd-Steinberg dithering used by Go Language's image/gif package to ensure video quality.
Arbitrary angle rotations are not supported.
The -delay parameter must be an integer specifying delay between frames in hundredths of
a second. A value of 3 would give approximately 33 fps theoritically
Usage of goanigiffy:
-cropheight=-1: height of cropped image, -1 specified full height
-cropleft=0: left co-ordinate for crop to start
-croptop=0: top co-ordinate for crop to start
-cropwidth=-1: width of cropped image, -1 specifies full width
-delay=3: delay time between frame in hundredths of a second
-dest="movie.gif": a destination filename for the animated gif
-flip="none": valid falues are none, horizontal, vertical
-rotate=0: valid values are 0, 90, 180, 270
-scale=1: scaling factor to apply if any
-src="*.jpg": a glob pattern for source images. defaults to *.jpg
-verbose=false: show in-process messages
Sources: https://github.com/srinathh/goanigiffy
*/
package main
import (
"bytes"
"flag"
"image"
"image/gif"
_ "image/jpeg"
_ "image/png"
"log"
"os"
"path/filepath"
"runtime"
"sort"
"github.com/disintegration/imaging"
)
func CropImage(cropleft, croptop, cropwidth, cropheight int, img image.Image, verbose bool) image.Image {
//Crop operation. Ignore if there is no crop operation specified
if !(cropwidth == -1 && cropheight == -1 && cropleft == 0 && croptop == 0) {
if cropwidth == -1 {
cropwidth = img.Bounds().Dx()
}
if cropheight == -1 {
cropheight = img.Bounds().Dy()
}
if verbose {
log.Printf("Cropping original image at (%d,%d)->(%d,%d)", cropleft, croptop, cropleft+cropwidth-1, croptop+cropheight-1)
}
img = imaging.Crop(img, image.Rect(cropleft, croptop, cropleft+cropwidth-1, croptop+cropheight-1))
}
return img
}
func ScaleImage(scale float64, img image.Image, verbose bool) image.Image {
//Scale operation. Ignore if scale is 1.0
if scale != 1.0 {
newwidth := int(float64(img.Bounds().Dx()) * scale)
newheight := int(float64(img.Bounds().Dy()) * scale)
if verbose {
log.Printf("Scaling image from (%d, %d) -> (%d, %d)", img.Bounds().Dx(), img.Bounds().Dy(), newwidth, newheight)
}
img = imaging.Resize(img, newwidth, newheight, imaging.Lanczos)
}
return img
}
func RotateImage(rotate int, img image.Image, verbose bool) image.Image {
//Rotate operation. Ignore if rotate is 0
if rotate != 0 && verbose {
log.Printf("Rotating by %d", rotate)
}
switch rotate {
case 90:
img = imaging.Rotate90(img)
case 180:
img = imaging.Rotate180(img)
case 270:
img = imaging.Rotate270(img)
}
return img
}
//FlipImage takes a string
func FlipImage(flip string, img image.Image, verbose bool) image.Image {
//Flip operation
if flip != "none" && verbose {
log.Printf("Flipping %s", flip)
}
switch flip {
case "horizontal":
img = imaging.FlipH(img)
case "vertical":
img = imaging.FlipV(img)
}
return img
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
srcglob := flag.String("src", "*.jpg", "a glob pattern for source images. defaults to *.jpg")
destname := flag.String("dest", "movie.gif", "a destination filename for the animated gif")
cropleft := flag.Int("cropleft", 0, "left co-ordinate for crop to start")
croptop := flag.Int("croptop", 0, "top co-ordinate for crop to start")
cropwidth := flag.Int("cropwidth", -1, "width of cropped image, -1 specifies full width")
cropheight := flag.Int("cropheight", -1, "height of cropped image, -1 specified full height")
delay := flag.Int("delay", 3, "delay time between frame in hundredths of a second")
verbose := flag.Bool("verbose", false, "show in-process messages")
scale := flag.Float64("scale", 1.0, "scaling factor to apply if any")
rotate := flag.Int("rotate", 0, "valid values are 0, 90, 180, 270")
flip := flag.String("flip", "none", "valid falues are none, horizontal, vertical")
flag.Parse()
if !(*rotate == 0 || *rotate == 90 || *rotate == 180 || *rotate == 270) {
log.Printf("rotate flag must be one of 0, 90, 180 or 270")
flag.PrintDefaults()
os.Exit(1)
}
if !(*flip == "none" || *flip == "horizontal" || *flip == "vertical") {
log.Printf("flip flag must be one of none, horizontal or vertical")
flag.PrintDefaults()
os.Exit(1)
}
srcfilenames, err := filepath.Glob(*srcglob)
if err != nil {
log.Fatalf("Error in globbing source file pattern %s : %s", *srcglob, err)
}
if len(srcfilenames) == 0 {
log.Fatalf("No source images found via pattern %s", *srcglob)
}
if *verbose {
log.Printf("Found %d images to parse", len(srcfilenames))
}
sort.Strings(srcfilenames)
var frames []*image.Paletted
for ctr, filename := range srcfilenames {
img, err := imaging.Open(filename)
if err != nil {
log.Printf("Skipping file %s due to error reading it :%s", filename, err)
continue
}
if *verbose {
log.Printf("Parsing image %d of %d : %s", ctr, len(srcfilenames), filename)
}
img = CropImage(*cropleft, *croptop, *cropwidth, *cropheight, img, *verbose)
img = ScaleImage(*scale, img, *verbose)
img = RotateImage(*rotate, img, *verbose)
img = FlipImage(*flip, img, *verbose)
buf := bytes.Buffer{}
if err := gif.Encode(&buf, img, nil); err != nil {
log.Printf("Skipping file %s due to error in gif encoding:%s", filename, err)
continue
}
tmpimg, err := gif.Decode(&buf)
if err != nil {
log.Printf("Skipping file %s due to weird error reading the temporary gif :%s", filename, err)
continue
}
frames = append(frames, tmpimg.(*image.Paletted))
}
if *verbose {
log.Printf("Parsed all images.. now attemting to create animated GIF %s", *destname)
}
delays := make([]int, len(frames))
for j, _ := range delays {
delays[j] = *delay
}
opfile, err := os.Create(*destname)
if err != nil {
log.Fatalf("Error creating the destination file %s : %s", *destname, err)
}
if err := gif.EncodeAll(opfile, &gif.GIF{Image: frames, Delay: delays, LoopCount: 0}); err != nil {
log.Printf("Error encoding output into animated gif :%s", err)
}
opfile.Close()
} | goanigiffy.go | 0.673192 | 0.569733 | goanigiffy.go | starcoder |
package main
import (
"fmt"
"strconv"
"bytes"
"os"
)
// Spiral is a square, 2D slice containing the numbers within the range of a particular number
// squared organized in a spiral fashion.
type Spiral [][]int
// NewSpiral returns a pointer to a Spiral made with the specified number.
func NewSpiral(n int) Spiral {
// Make a new square, 2D grid.
s := make(Spiral, n)
for i := range s {
s[i] = make([]int, n)
}
// Define the initial amount of steps to take when walking the grid in a spiral fashion.
steps := map[string]int {
"Right" : n - 1,
"Down" : n - 2,
"Left": n - 2,
"Up" : n - 3,
}
// Starting point will be the top-left corner (0,0).
pos := struct {
x, y int
}{
0,
0,
}
// Always start to fill the grid with 1.
fill := 1
// Start by moving toward the right then down, then left, then up, etc.
dir := "Right"
// Keep track of the number of steps we've taken in each dir.
dist := 0
// We've reached the end of the line, turn.
turn := func(d string) {
steps[dir] -= 2
dist = 0
dir = d
}
// Keep walking down the line.
walk := func() bool {
if dist == steps[dir] {
return false
}
dist++
return true
}
for fill <= (n * n) { // While we haven't reached the final number...
s[pos.x][pos.y] = fill
switch dir {
case "Right":
if walk() {
pos.x++
break
}
pos.y++
turn("Down")
case "Down":
if walk() {
pos.y++
break
}
pos.x--
turn("Left")
case "Left":
if walk() {
pos.x--
break
}
pos.y--
turn("Up")
case "Up":
if walk() {
pos.y--
break
}
pos.x++
turn("Right")
}
fill++
}
return s
}
func (s Spiral) String() string {
var ns bytes.Buffer
w := len(strconv.Itoa(len(s) * len(s)))
for i := range s {
for j := range s[i] {
e := bytes.NewBufferString(strconv.Itoa(s[j][i]))
for p := len(e.String()); p <= w; p++ {
e.WriteString(" ")
}
ns.WriteString(e.String())
}
if i != len(s) - 1 {
ns.WriteString("\n")
}
}
return ns.String()
}
func main() {
num, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println("Incorrect usage")
os.Exit(1)
}
s := NewSpiral(num)
fmt.Println(s)
} | 320-spiral_ascension/main.go | 0.829319 | 0.55917 | main.go | starcoder |
package math32
// Vector2 is a 2D vector/point with X and Y components.
type Vector2 struct {
X float32
Y float32
}
// NewVector2 creates and returns a pointer to a new Vector2 with
// the specified x and y components
func NewVector2(x, y float32) *Vector2 {
return &Vector2{X: x, Y: y}
}
// NewVec2 creates and returns a pointer to a new zero-ed Vector2.
func NewVec2() *Vector2 {
return &Vector2{X: 0, Y: 0}
}
// Clone returns a copy of this vector
func (v *Vector2) Clone() *Vector2 {
return NewVector2(v.X, v.Y)
}
// Set sets this vector X and Y components.
// Returns the pointer to this updated vector.
func (v *Vector2) Set(x, y float32) *Vector2 {
v.X = x
v.Y = y
return v
}
// SetX sets this vector X component.
// Returns the pointer to this updated Vector.
func (v *Vector2) SetX(x float32) *Vector2 {
v.X = x
return v
}
// SetY sets this vector Y component.
// Returns the pointer to this updated vector.
func (v *Vector2) SetY(y float32) *Vector2 {
v.Y = y
return v
}
// SetComponent sets this vector component value by its index: 0 for X, 1 for Y.
// Returns the pointer to this updated vector
func (v *Vector2) SetComponent(index int, value float32) *Vector2 {
switch index {
case 0:
v.X = value
case 1:
v.Y = value
default:
panic("index is out of range")
}
return v
}
// Component returns this vector component by its index: 0 for X, 1 for Y
func (v *Vector2) Component(index int) float32 {
switch index {
case 0:
return v.X
case 1:
return v.Y
default:
panic("index is out of range")
}
}
// SetByName sets this vector component value by its case insensitive name: "x" or "y".
func (v *Vector2) SetByName(name string, value float32) {
switch name {
case "x", "X":
v.X = value
case "y", "Y":
v.Y = value
default:
panic("Invalid Vector2 component name: " + name)
}
}
// Zero sets this vector X and Y components to be zero.
// Returns the pointer to this updated vector.
func (v *Vector2) Zero() *Vector2 {
v.X = 0
v.Y = 0
return v
}
// Copy copies other vector to this one.
// It is equivalent to: *v = *other.
// Returns the pointer to this updated vector.
func (v *Vector2) Copy(other *Vector2) *Vector2 {
v.X = other.X
v.Y = other.Y
return v
}
// Add adds other vector to this one.
// Returns the pointer to this updated vector.
func (v *Vector2) Add(other *Vector2) *Vector2 {
v.X += other.X
v.Y += other.Y
return v
}
// AddScalar adds scalar s to each component of this vector.
// Returns the pointer to this updated vector.
func (v *Vector2) AddScalar(s float32) *Vector2 {
v.X += s
v.Y += s
return v
}
// AddVectors adds vectors a and b to this one.
// Returns the pointer to this updated vector.
func (v *Vector2) AddVectors(a, b *Vector2) *Vector2 {
v.X = a.X + b.X
v.Y = a.Y + b.Y
return v
}
// Sub subtracts other vector from this one.
// Returns the pointer to this updated vector.
func (v *Vector2) Sub(other *Vector2) *Vector2 {
v.X -= other.X
v.Y -= other.Y
return v
}
// SubScalar subtracts scalar s from each component of this vector.
// Returns the pointer to this updated vector.
func (v *Vector2) SubScalar(s float32) *Vector2 {
v.X -= s
v.Y -= s
return v
}
// SubVectors sets this vector to a - b.
// Returns the pointer to this updated vector.
func (v *Vector2) SubVectors(a, b *Vector2) *Vector2 {
v.X = a.X - b.X
v.Y = a.Y - b.Y
return v
}
// Multiply multiplies each component of this vector by the corresponding one from other vector.
// Returns the pointer to this updated vector.
func (v *Vector2) Multiply(other *Vector2) *Vector2 {
v.X *= other.X
v.Y *= other.Y
return v
}
// MultiplyScalar multiplies each component of this vector by the scalar s.
// Returns the pointer to this updated vector.
func (v *Vector2) MultiplyScalar(s float32) *Vector2 {
v.X *= s
v.Y *= s
return v
}
// Divide divides each component of this vector by the corresponding one from other vector.
// Returns the pointer to this updated vector
func (v *Vector2) Divide(other *Vector2) *Vector2 {
v.X /= other.X
v.Y /= other.Y
return v
}
// DivideScalar divides each component of this vector by the scalar s.
// If scalar is zero, sets this vector to zero.
// Returns the pointer to this updated vector.
func (v *Vector2) DivideScalar(scalar float32) *Vector2 {
if scalar != 0 {
invScalar := 1 / scalar
v.X *= invScalar
v.Y *= invScalar
} else {
v.X = 0
v.Y = 0
}
return v
}
// Min sets this vector components to the minimum values of itself and other vector.
// Returns the pointer to this updated vector.
func (v *Vector2) Min(other *Vector2) *Vector2 {
if v.X > other.X {
v.X = other.X
}
if v.Y > other.Y {
v.Y = other.Y
}
return v
}
// Max sets this vector components to the maximum value of itself and other vector.
// Returns the pointer to this updated vector.
func (v *Vector2) Max(other *Vector2) *Vector2 {
if v.X < other.X {
v.X = other.X
}
if v.Y < other.Y {
v.Y = other.Y
}
return v
}
// Clamp sets this vector components to be no less than the corresponding components of min
// and not greater than the corresponding components of max.
// Assumes min < max, if this assumption isn't true it will not operate correctly.
// Returns the pointer to this updated vector.
func (v *Vector2) Clamp(min, max *Vector2) *Vector2 {
if v.X < min.X {
v.X = min.X
} else if v.X > max.X {
v.X = max.X
}
if v.Y < min.Y {
v.Y = min.Y
} else if v.Y > max.Y {
v.Y = max.Y
}
return v
}
// ClampScalar sets this vector components to be no less than minVal and not greater than maxVal.
// Returns the pointer to this updated vector.
func (v *Vector2) ClampScalar(minVal, maxVal float32) *Vector2 {
if v.X < minVal {
v.X = minVal
} else if v.X > maxVal {
v.X = maxVal
}
if v.Y < minVal {
v.Y = minVal
} else if v.Y > maxVal {
v.Y = maxVal
}
return v
}
// Floor applies math32.Floor() to each of this vector's components.
// Returns the pointer to this updated vector.
func (v *Vector2) Floor() *Vector2 {
v.X = Floor(v.X)
v.Y = Floor(v.Y)
return v
}
// Ceil applies math32.Ceil() to each of this vector's components.
// Returns the pointer to this updated vector.
func (v *Vector2) Ceil() *Vector2 {
v.X = Ceil(v.X)
v.Y = Ceil(v.Y)
return v
}
// Round rounds each of this vector's components.
// Returns the pointer to this updated vector.
func (v *Vector2) Round() *Vector2 {
v.X = Floor(v.X + 0.5)
v.Y = Floor(v.Y + 0.5)
return v
}
// Negate negates each of this vector's components.
// Returns the pointer to this updated vector.
func (v *Vector2) Negate() *Vector2 {
v.X = -v.X
v.Y = -v.Y
return v
}
// Dot returns the dot product of this vector with other.
// None of the vectors are changed.
func (v *Vector2) Dot(other *Vector2) float32 {
return v.X*other.X + v.Y*other.Y
}
// LengthSq returns the length squared of this vector.
// LengthSq can be used to compare vectors' lengths without the need to perform a square root.
func (v *Vector2) LengthSq() float32 {
return v.X*v.X + v.Y*v.Y
}
// Length returns the length of this vector.
func (v *Vector2) Length() float32 {
return Sqrt(v.X*v.X + v.Y*v.Y)
}
// Normalize normalizes this vector so its length will be 1.
// Returns the pointer to this updated vector.
func (v *Vector2) Normalize() *Vector2 {
return v.DivideScalar(v.Length())
}
// DistanceTo returns the distance of this point to other.
func (v *Vector2) DistanceTo(other *Vector2) float32 {
return Sqrt(v.DistanceToSquared(other))
}
// DistanceToSquared returns the distance squared of this point to other.
func (v *Vector2) DistanceToSquared(other *Vector2) float32 {
dx := v.X - other.X
dy := v.Y - other.Y
return dx*dx + dy*dy
}
// SetLength sets this vector to have the specified length.
// Returns the pointer to this updated vector.
func (v *Vector2) SetLength(l float32) *Vector2 {
oldLength := v.Length()
if oldLength != 0 && l != oldLength {
v.MultiplyScalar(l / oldLength)
}
return v
}
// Lerp sets each of this vector's components to the linear interpolated value of
// alpha between ifself and the corresponding other component.
// Returns the pointer to this updated vector.
func (v *Vector2) Lerp(other *Vector2, alpha float32) *Vector2 {
v.X += (other.X - v.X) * alpha
v.Y += (other.Y - v.Y) * alpha
return v
}
// Equals returns if this vector is equal to other.
func (v *Vector2) Equals(other *Vector2) bool {
return (other.X == v.X) && (other.Y == v.Y)
}
// FromArray sets this vector's components from the specified array and offset
// Returns the pointer to this updated vector.
func (v *Vector2) FromArray(array []float32, offset int) *Vector2 {
v.X = array[offset]
v.Y = array[offset+1]
return v
}
// ToArray copies this vector's components to array starting at offset.
// Returns the array.
func (v *Vector2) ToArray(array []float32, offset int) []float32 {
array[offset] = v.X
array[offset+1] = v.Y
return array
}
// InTriangle returns whether the vector is inside the specified triangle.
func (v *Vector2) InTriangle(p0, p1, p2 *Vector2) bool {
A := 0.5 * (-p1.Y*p2.X + p0.Y*(-p1.X+p2.X) + p0.X*(p1.Y-p2.Y) + p1.X*p2.Y)
sign := float32(1)
if A < 0 {
sign = float32(-1)
}
s := (p0.Y*p2.X - p0.X*p2.Y + (p2.Y-p0.Y)*v.X + (p0.X-p2.X)*v.Y) * sign
t := (p0.X*p1.Y - p0.Y*p1.X + (p0.Y-p1.Y)*v.X + (p1.X-p0.X)*v.Y) * sign
return s >= 0 && t >= 0 && (s+t) < 2*A*sign
}
// AlmostEquals returns whether the vector is almost equal to another vector within the specified tolerance.
func (v *Vector2) AlmostEquals(other *Vector2, tolerance float32) bool {
if (Abs(v.X-other.X) < tolerance) &&
(Abs(v.Y-other.Y) < tolerance) {
return true
}
return false
} | math32/vector2.go | 0.95033 | 0.850033 | vector2.go | starcoder |
package orderedmap
import "fmt"
// OrderedMap class
type OrderedMap struct {
table map[interface{}]*node
root *node
}
// NewOrderedMap creates an empty OrderedMap
func NewOrderedMap() *OrderedMap {
root := newNode(nil, nil, nil, nil) // sentinel Node
root.Next, root.Prev = root, root
om := &OrderedMap{
table: make(map[interface{}]*node),
root: root,
}
return om
}
// Len returns the number of elements in the Map
func (om *OrderedMap) Len() int {
return len(om.table)
}
// Set the key value, if the key overwrites an existing entry, the original
// insertion position is left unchanged, otherwise the key is inserted at the end.
func (om *OrderedMap) Set(key interface{}, value interface{}) {
if node, ok := om.table[key]; !ok {
// New Node
root := om.root
node := newNode(key, value, root, root.Prev)
root.Prev.Next = node
root.Prev = node
om.table[key] = node
} else {
// Update existing node value
node.Value = value
}
}
// Get the value of an existing key, leaving the map unchanged
func (om *OrderedMap) Get(key interface{}) (value interface{}, ok bool) {
if node, isOk := om.table[key]; !isOk {
value, ok = nil, false
} else {
value, ok = node.Value, true
}
return
}
// GetLast return the key and value for the last element added, leaving
// the map unchanged
func (om *OrderedMap) GetLast() (key interface{}, value interface{}, ok bool) {
if len(om.table) == 0 {
key, value, ok = nil, nil, false
} else {
node := om.root.Prev
key, value, ok = node.Key, node.Value, true
}
return
}
// GetFirst returns the key and value for the first element, leaving the map unchanged
func (om *OrderedMap) GetFirst() (key interface{}, value interface{}, ok bool) {
if len(om.table) == 0 {
key, value, ok = nil, nil, false
} else {
node := om.root.Next
key, value, ok = node.Key, node.Value, true
}
return
}
// Delete a key:value pair from the map.
func (om *OrderedMap) Delete(key interface{}) {
if node, ok := om.table[key]; ok {
node.Next.Prev = node.Prev
node.Prev.Next = node.Next
delete(om.table, key)
}
}
// Pop and return key:value for the newest or oldest element on the OrderedMap
func (om *OrderedMap) Pop(last bool) (key interface{}, value interface{}, ok bool) {
if last {
key, value, ok = om.GetLast()
} else {
key, value, ok = om.GetFirst()
}
if ok {
om.Delete(key)
}
return
}
// PopLast is a shortcut to Pop the last element
func (om *OrderedMap) PopLast() (key interface{}, value interface{}, ok bool) {
return om.Pop(true)
}
// PopFirst is a shortcut to Pop the first element
func (om *OrderedMap) PopFirst() (key interface{}, value interface{}, ok bool) {
return om.Pop(false)
}
// Move an existing key to either the end of the OrderedMap
func (om *OrderedMap) Move(key interface{}, last bool) (ok bool) {
var moved *node
// Remove from current position
anode, ok := om.table[key]
if !ok {
return false
}
anode.Next.Prev = anode.Prev
anode.Prev.Next = anode.Next
moved = anode
// Insert at the start or end
root := om.root
if last {
moved.Next = root
moved.Prev = root.Prev
root.Prev.Next = moved
root.Prev = moved
} else {
moved.Prev = root
moved.Next = root.Next
root.Next.Prev = moved
root.Next = moved
}
return true
}
// MoveLast is a shortcut to Move a key to the end o the map
func (om *OrderedMap) MoveLast(key interface{}) (ok bool) {
return om.Move(key, true)
}
// MoveFirst is a shortcut to Move a key to the beginning of the map
func (om *OrderedMap) MoveFirst(key interface{}) (ok bool) {
return om.Move(key, false)
}
// MapIterator is a iterator over an OrderedMap
type MapIterator struct {
curr *node
root *node
reverse bool
}
// Iter creates a map iterator
func (om *OrderedMap) Iter() *MapIterator {
return &MapIterator{
curr: om.root,
root: om.root,
reverse: false,
}
}
// IterReverse creates a reverse order map iterator
func (om *OrderedMap) IterReverse() *MapIterator {
return &MapIterator{
curr: om.root,
root: om.root,
reverse: true,
}
}
// Next key:value pair
func (mi *MapIterator) Next() (key interface{}, value interface{}, ok bool) {
// Already finished
if mi.curr == nil {
return nil, nil, false
}
// Advance pointer
if mi.reverse {
mi.curr = mi.curr.Prev
} else {
mi.curr = mi.curr.Next
}
// This is the last iteration
if mi.curr == mi.root {
mi.curr = nil
key, value, ok = nil, nil, false
} else {
key, value, ok = mi.curr.Key, mi.curr.Value, true
}
return
}
// String interface
func (om *OrderedMap) String() string {
buffer := make([]string, om.Len())
iter := om.Iter()
index := 0
for key, value, ok := iter.Next(); ok; key, value, ok = iter.Next() {
buffer[index] = fmt.Sprintf("%v:%v, ", key, value)
index++
}
return fmt.Sprintf("OrderedMap%v", buffer)
} | orderedmap.go | 0.721939 | 0.474205 | orderedmap.go | starcoder |
package main
import (
"fmt"
"math"
"time"
)
// Vector
// ---
type Vector struct {
x, y, z float64
}
func (a Vector) Add(b Vector) Vector {
return Vector{a.x + b.x, a.y + b.y, a.z + b.z}
}
func (a Vector) Sub(b Vector) Vector {
return Vector{a.x - b.x, a.y - b.y, a.z - b.z}
}
func (a Vector) Mul(b Vector) Vector {
return Vector{a.x * b.x, a.y * b.y, a.z * b.z}
}
func (a Vector) Dist(b Vector) float64 {
s := a.Sub(b)
return math.Sqrt(s.x*s.x + s.y*s.y + s.z*s.z)
}
// Block
// ---
const BlockTypes = 256
type BlockId int
type Block struct {
loc Vector // x, y, z within a chunk
name string
durability int
typ BlockId
textureid int
breakable bool
visible bool
}
// Entity
// ---
type Type int
const (
Zombie Type = iota
Chicken
Creeper
Enderman
)
type Entity struct {
loc Vector // x, y, z within a chunk
typ Type
name string
hp int
speed Vector
}
func (e *Entity) Move() {
// Complex movement AI
rngVector := Vector{1, 1, 1}
moveVector := rngVector.Mul(e.speed)
e.loc = e.loc.Add(moveVector)
}
func NewEntity(loc Vector, typ Type) *Entity {
e := &Entity{
loc: loc,
typ: typ,
}
switch typ {
case Zombie:
e.name = "Zombie"
e.hp = 50
e.speed = Vector{0.5, 0, 0.5} // slow, can't fly
case Chicken:
e.name = "Chicken"
e.hp = 25
e.speed = Vector{0.75, 0.25, 0.75} // can fly a bit
case Creeper:
e.name = "Creeper"
e.hp = 75
e.speed = Vector{0.75, 0, 0.75}
case Enderman:
e.name = "Enderman"
e.hp = 500
e.speed = Vector{1, 1, 1} // does what he wants
}
return e
}
// Chunk
// ---
const (
ChunkBlocks = 65536
ChunkEntities = 1000
)
type Chunk struct {
loc Vector // x, y, z within the world
blocks []BlockId
entities []*Entity
}
func (c *Chunk) ProcessEntities() {
for _, e := range c.entities {
e.Move()
}
}
func genBlockIds() []BlockId {
ids := make([]BlockId, ChunkBlocks)
for i := range ids {
ids[i] = BlockId(i)
}
return ids
}
func genEntities() []*Entity {
entities := make([]*Entity, 0, ChunkEntities)
for i := 0; i < ChunkEntities/4; i++ {
// Fancy procedural generation initial position equation
f := float64(i)
entities = append(entities, NewEntity(Vector{f, f, f}, Zombie))
entities = append(entities, NewEntity(Vector{f + 1, f, f}, Chicken))
entities = append(entities, NewEntity(Vector{f + 2, f, f}, Creeper))
entities = append(entities, NewEntity(Vector{f + 3, f, f}, Enderman))
}
return entities
}
func NewChunk(loc Vector) *Chunk {
return &Chunk{
loc: loc,
blocks: genBlockIds(),
entities: genEntities(),
}
}
// Game
// ---
const GameChunks = 100
type Game struct {
chunks []*Chunk
blocks []Block
chunkCount int
playerLoc Vector
}
func (g *Game) LoadWorld() {
for i := 0; i < GameChunks; i++ {
g.chunks = append(g.chunks, NewChunk(Vector{float64(g.chunkCount), 0, 0}))
g.chunkCount++
}
g.blocks = make([]Block, BlockTypes)
for i := range g.blocks {
f := float64(i)
g.blocks[i] = Block{
loc: Vector{f, f, f},
name: fmt.Sprintf("Block:%d", i),
durability: 100,
typ: BlockId(i),
textureid: 1,
breakable: true,
visible: true,
}
}
}
func (g *Game) removeChunk(id int) {
// see https://github.com/golang/go/wiki/SliceTricks
copy(g.chunks[:id], g.chunks[id+1:])
g.chunks[len(g.chunks)-1] = NewChunk(Vector{float64(g.chunkCount), 0, 0})
g.chunkCount++
}
func (g *Game) UpdateChunks() {
// remove chunks by index, duh
for i, chunk := range g.chunks {
if g.playerLoc.Dist(chunk.loc) > GameChunks {
g.removeChunk(i)
} else {
chunk.ProcessEntities()
}
}
}
func NewGame() *Game {
return &Game{
chunkCount: 0,
playerLoc: Vector{0, 0, 0},
}
}
// main
// ---
func main() {
game := NewGame()
fmt.Println("Loading World...")
start := time.Now()
game.LoadWorld()
loadWorldTime := time.Since(start)
fmt.Println("FINISHED!")
fmt.Printf("Load Time: %s\n", loadWorldTime)
// Game Loop, you can never leave
frames := 0
for i := 0; i < 100; i++ {
// check for dead entities
start = time.Now()
// mocking polling of the VR controller
playerMov := Vector{0.1, 0, 0}
game.playerLoc = game.playerLoc.Add(playerMov)
game.UpdateChunks()
t := time.Since(start)
fmt.Println(frames, t)
// Lock it at 60FPS
if t < 16*time.Millisecond {
time.Sleep(16*time.Millisecond - t)
}
frames++
}
} | go/naive1.go | 0.677367 | 0.548069 | naive1.go | starcoder |
package gm
import (
"testing"
)
// VerifyNamed generates a file name based on current test name and
// the 'name' argument and compares its contents in git index (i.e.
// staged or committed if the changes are staged for the file) to
// that of of 'data' argument. The test will fail if the data
// differs. In this case the target file is updated and the user
// must stage or commit the changes to make the test pass.
// If data is string or []byte, it's compared directly to the contents
// of the file (the data are supposed to be human-readable and
// easily diffable).
// If data implements Verifier interface, the comparison is done
// by invoking it's Verify method on the contents of the file.
// Otherwise, the comparison is done based on JSON representation
// of the data ignoring any changes in JSON formatting and any
// changes introduced by the encoding/json marshalling mechanism.
// If data implements Verifier interface, the updated contents of the
// data file is generated using its Marshal() method.
// The suffix of the data file name is generated based on the
// data argument, too. For text content, ".out.txt" suffix is used.
// For json content, the suffix is ".out.json". For Verifier type,
// the suffix is ".out" concatenated with the value of the Suffix()
// method.
func VerifyNamed(t *testing.T, name string, data interface{}) {
testName := t.Name()
if name != "" {
testName += "__" + name
}
filename, err := GetFilenameForTest(testName, data)
if err != nil {
t.Errorf("can't get filename for test %q: %v", testName, err)
return
}
hasDiff, err := DataFileDiffers(filename, data)
if err != nil {
t.Errorf("failed to diff data file %q: %v", filename, err)
return
}
if hasDiff {
if err := WriteDataFile(filename, data); err != nil {
t.Errorf("failed to write file %q: %v", filename, data)
}
}
gitDiff, err := GitDiff(filename)
switch {
case err != nil:
t.Errorf("git diff failed on %q: %v", filename, err)
case gitDiff == "":
// no difference
default:
t.Errorf("got difference for %q (%q):\n%s", testName, filename, gitDiff)
}
}
// Verify invokes VerifyNamed with empty 'name' argument
func Verify(t *testing.T, data interface{}) {
VerifyNamed(t, "", data)
} | tests/gm/gm.go | 0.511717 | 0.423339 | gm.go | starcoder |
package nn
import (
"github.com/sudachen/go-ml/fu"
"github.com/sudachen/go-ml/model"
"github.com/sudachen/go-ml/tables"
"github.com/sudachen/go-zorros/zorros"
"reflect"
)
type ModelMapFunction func(network *Network, features []string, predicts string) model.MemorizeMap
func DefaultModelMap(network *Network, features []string, predicts string) model.MemorizeMap {
return model.MemorizeMap{"model": mnemosyne{network, features, predicts}}
}
func Train(e Model, dataset model.Dataset, w model.Workout, mmf ModelMapFunction) (report *model.Report, err error) {
t, err := dataset.Source.Lazy().First(1).Collect()
if err != nil {
return
}
features := t.OnlyNames(dataset.Features...)
Test := fu.Fnzs(dataset.Test, model.TestCol)
if fu.IndexOf(Test, t.Names()) < 0 {
err = zorros.Errorf("dataset does not have column `%v`", Test)
return
}
Label := fu.Fnzs(dataset.Label, model.LabelCol)
if fu.IndexOf(Label, t.Names()) < 0 {
err = zorros.Errorf("dataset does not have column `%v`", Label)
return
}
predicts := fu.Fnzs(e.Predicted, model.PredictedCol)
network := New(e.Context.Upgrade(), e.Network, e.Input, e.Loss, e.BatchSize, e.Seed)
train := dataset.Source.Lazy().IfNotFlag(dataset.Test).Batch(e.BatchSize).Parallel()
full := dataset.Source.Lazy().Batch(e.BatchSize).Parallel()
out := make([]float32, network.Graph.Output.Dim().Total())
loss := make([]float32, network.Graph.Loss.Dim().Total())
//network.PrintSummary(true)
for done := false; w != nil && !done; w = w.Next() {
opt := e.Optimizer.Init(w.Iteration())
if err = train.Drain(func(value reflect.Value) error {
if value.Kind() == reflect.Bool {
return nil
}
t := value.Interface().(*tables.Table)
m, err := t.MatrixWithLabel(features, dataset.Label, e.BatchSize)
if err != nil {
return err
}
network.Train(m.Features, m.Labels, opt)
return nil
}); err != nil {
return
}
trainmu := w.TrainMetrics()
testmu := w.TestMetrics()
if err = full.Drain(func(value reflect.Value) error {
if value.Kind() == reflect.Bool {
return nil
}
t := value.Interface().(*tables.Table)
m, err := t.MatrixWithLabel(features, dataset.Label, e.BatchSize)
if err != nil {
return err
}
network.Label.SetValues(m.Labels)
network.Forward(m.Features, out)
resultCol := tables.MatrixColumn(out, e.BatchSize)
labelCol := t.Col(dataset.Label)
network.Loss.CopyValuesTo(loss)
l := loss[0]
for i, c := range t.Col(dataset.Test).ExtractAs(fu.Bool, true).([]bool) {
if len(loss) > 1 {
l = loss[i]
}
if c {
testmu.Update(resultCol.Value(i), labelCol.Value(i), float64(l))
} else {
trainmu.Update(resultCol.Value(i), labelCol.Value(i), float64(l))
}
}
return nil
}); err != nil {
return
}
lr0, _ := trainmu.Complete()
lr1, d := testmu.Complete()
memorize := mmf(network, features, predicts)
if report, done, err = w.Complete(memorize, lr0, lr1, d); err != nil {
return nil, zorros.Wrapf(err, "tailed to complete model: %s", err.Error())
}
}
return
} | nn/train.go | 0.651244 | 0.469277 | train.go | starcoder |
package plan
import (
"math"
"github.com/insionng/yougam/libraries/pingcap/tidb/ast"
)
// Plan is a description of an execution flow.
// It is created from ast.Node first, then optimized by optimizer,
// then used by executor to create a Cursor which executes the statement.
type Plan interface {
// Fields returns the result fields of the plan.
Fields() []*ast.ResultField
// SetFields sets the results fields of the plan.
SetFields(fields []*ast.ResultField)
// The cost before returning fhe first row.
StartupCost() float64
// The cost after returning all the rows.
TotalCost() float64
// The expected row count.
RowCount() float64
// SetLimit is used to push limit to upstream to estimate the cost.
SetLimit(limit float64)
// AddParent means append a parent for plan.
AddParent(parent Plan)
// AddChild means append a child for plan.
AddChild(children Plan)
// ReplaceParent means replace a parent with another one.
ReplaceParent(parent, newPar Plan) error
// ReplaceChild means replace a child with another one.
ReplaceChild(children, newChild Plan) error
// Retrieve parent by index.
GetParentByIndex(index int) Plan
// Retrieve child by index.
GetChildByIndex(index int) Plan
// Get all the parents.
GetParents() []Plan
// Get all the children.
GetChildren() []Plan
}
// basePlan implements base Plan interface.
// Should be used as embedded struct in Plan implementations.
type basePlan struct {
fields []*ast.ResultField
startupCost float64
totalCost float64
rowCount float64
limit float64
parents []Plan
children []Plan
}
// StartupCost implements Plan StartupCost interface.
func (p *basePlan) StartupCost() float64 {
return p.startupCost
}
// TotalCost implements Plan TotalCost interface.
func (p *basePlan) TotalCost() float64 {
return p.totalCost
}
// RowCount implements Plan RowCount interface.
func (p *basePlan) RowCount() float64 {
if p.limit == 0 {
return p.rowCount
}
return math.Min(p.rowCount, p.limit)
}
// SetLimit implements Plan SetLimit interface.
func (p *basePlan) SetLimit(limit float64) {
p.limit = limit
}
// Fields implements Plan Fields interface.
func (p *basePlan) Fields() []*ast.ResultField {
return p.fields
}
// SetFields implements Plan SetFields interface.
func (p *basePlan) SetFields(fields []*ast.ResultField) {
p.fields = fields
}
// AddParent implements Plan AddParent interface.
func (p *basePlan) AddParent(parent Plan) {
p.parents = append(p.parents, parent)
}
// AddChild implements Plan AddChild interface.
func (p *basePlan) AddChild(child Plan) {
p.children = append(p.children, child)
}
// ReplaceParent means replace a parent for another one.
func (p *basePlan) ReplaceParent(parent, newPar Plan) error {
for i, par := range p.parents {
if par == parent {
p.parents[i] = newPar
return nil
}
}
return SystemInternalErrorType.Gen("RemoveParent Failed!")
}
// ReplaceChild means replace a child with another one.
func (p *basePlan) ReplaceChild(child, newChild Plan) error {
for i, ch := range p.children {
if ch == child {
p.children[i] = newChild
return nil
}
}
return SystemInternalErrorType.Gen("RemoveChildren Failed!")
}
// GetParentByIndex implements Plan GetParentByIndex interface.
func (p *basePlan) GetParentByIndex(index int) (parent Plan) {
if index < len(p.parents) && index >= 0 {
return p.parents[index]
}
return nil
}
// GetChildByIndex implements Plan GetChildByIndex interface.
func (p *basePlan) GetChildByIndex(index int) (parent Plan) {
if index < len(p.children) && index >= 0 {
return p.children[index]
}
return nil
}
// GetParents implements Plan GetParents interface.
func (p *basePlan) GetParents() []Plan {
return p.parents
}
// GetChildren implements Plan GetChildren interface.
func (p *basePlan) GetChildren() []Plan {
return p.children
} | libraries/pingcap/tidb/optimizer/plan/plan.go | 0.737631 | 0.421076 | plan.go | starcoder |
package lcs
import (
"fmt"
)
// Myers represents an implementation of Myer's longest common subsequence
// and shortest edit script algorithm as as documented in:
// An O(ND) Difference Algorithm and Its Variations, 1986.
type Myers struct {
a, b interface{}
na, nb int
slicer func(v interface{}, from, to int32) interface{}
edits func(v interface{}, op EditOp, cx, cy int) []Edit
}
// NewMyers returns a new instance of Myers. The implementation supports slices
// of bytes/uint8, rune/int32 and int64s.
func NewMyers(a, b interface{}) *Myers {
na, nb, err := configureAndValidate(a, b)
if err != nil {
panic(err)
}
return &Myers{
a: a,
b: b,
na: na,
nb: nb,
}
}
// Details on the implementation and details of the algorithms can be found
// here:
// http://xmailserver.org/diff2.pdf
// http://simplygenius.net/Article/DiffTutorial1
// https://blog.robertelder.org/diff-algorithm/
func forwardSearch(cmp comparator, na, nb int32, d int32, forward, reverse []int32, offset int32) (nd, mx, my, x, y int32, ok bool) {
delta := na - nb
odd := delta%2 != 0
for k := -d; k <= d; k += 2 {
// Edge cases are:
// k == -d - move down
// k == d * 2 - move right
// Normal case:
// move down or right depending on how far the move would be.
if k == -d || k != d && forward[offset+k-1] < forward[offset+k+1] {
x = forward[offset+k+1]
} else {
x = forward[offset+k-1] + 1
}
y = x - k
mx, my = x, y
for x < na && y < nb && cmp(int(x), int(y)) {
x++
y++
}
forward[offset+k] = x
// Can this snake potentially overlap with one of the reverse ones?
// Going forward only odd paths can be the longest ones.
if odd && (-(k - delta)) >= -(d-1) && (-(k - delta)) <= (d-1) {
// Doe this snake overlap with one of the reverse ones? If so,
// the last snake is the longest one.
if forward[offset+k]+reverse[offset-(k-delta)] >= na {
return 2*d - 1, mx, my, x, y, true
}
}
}
return 0, 0, 0, 0, 0, false
}
func reverseSearch(cmp comparator, na, nb int32, d int32, forward, reverse []int32, offset int32) (nd, mx, my, x, y int32, ok bool) {
delta := na - nb
even := delta%2 == 0
for k := -d; k <= d; k += 2 {
// Edge cases as per forward search, but looking at the reverse
// stored values.
if k == -d || k != d && reverse[offset+k-1] < reverse[offset+k+1] {
x = reverse[offset+k+1]
} else {
x = reverse[offset+k-1] + 1
}
y = x - k
mx, my = x, y
for x < na && y < nb && cmp(int(na-x-1), int(nb-y-1)) {
x++
y++
}
reverse[offset+k] = x
// Can this snake potentially overlap with one of the forward ones?
// Going backward only even paths can be the longest ones.
if even && (-(k - delta)) >= -d && (-(k - delta)) <= d {
// Doe this snake overlap with one of the forward ones? If so,
// the last snake is the longest one.
if reverse[offset+k]+forward[offset-(k-delta)] >= na {
return 2 * d, na - x, nb - y, na - mx, nb - my, true
}
}
}
return 0, 0, 0, 0, 0, false
}
func middleSnake(cmp comparator, na, nb int32) (d, x1, y1, x2, y2 int32) {
max := na + nb // max # edits (delete all a, insert all of b)
// forward and reverse are accessed using k which is in the
// range -d .. +d, hence offset must be added to k.
forward := make([]int32, max+2)
reverse := make([]int32, max+2)
offset := int32(len(forward) / 2)
// Only need to search for D halfway through the table.
halfway := max / 2
if max%2 != 0 {
halfway++
}
for d := int32(0); d <= halfway; d++ {
if nd, mx, my, x, y, ok := forwardSearch(cmp, na, nb, d, forward, reverse, offset); ok {
return nd, mx, my, x, y
}
if nd, mx, my, x, y, ok := reverseSearch(cmp, na, nb, d, forward, reverse, offset); ok {
return nd, mx, my, x, y
}
}
panic("unreachable")
}
func myersLCS64(a, b []int64) []int64 {
na, nb := int32(len(a)), int32(len(b))
if na == 0 || nb == 0 {
return []int64{}
}
d, x, y, u, v := middleSnake(cmpFor(a, b), na, nb)
if d > 1 {
nd := myersLCS64(a[:x], b[:y])
nd = append(nd, a[x:u]...)
nd = append(nd, myersLCS64(a[u:na], b[v:nb])...)
return nd
}
if nb > na {
return append([]int64{}, a...)
}
return append([]int64{}, b...)
}
func myersLCS32(a, b []int32) []int32 {
na, nb := int32(len(a)), int32(len(b))
if na == 0 || nb == 0 {
return []int32{}
}
d, x, y, u, v := middleSnake(cmpFor(a, b), na, nb)
if d > 1 {
nd := myersLCS32(a[:x], b[:y])
nd = append(nd, a[x:u]...)
nd = append(nd, myersLCS32(a[u:na], b[v:nb])...)
return nd
}
if nb > na {
return append([]int32{}, a...)
}
return append([]int32{}, b...)
}
func myersLCS8(a, b []uint8) []uint8 {
na, nb := int32(len(a)), int32(len(b))
if na == 0 || nb == 0 {
return []uint8{}
}
d, x, y, u, v := middleSnake(cmpFor(a, b), na, nb)
if d > 1 {
nd := myersLCS8(a[:x], b[:y])
nd = append(nd, a[x:u]...)
nd = append(nd, myersLCS8(a[u:na], b[v:nb])...)
return nd
}
if nb > na {
return append([]uint8{}, a...)
}
return append([]uint8{}, b...)
}
// LCS returns the longest common subsquence.
func (m *Myers) LCS() interface{} {
switch av := m.a.(type) {
case []int64:
return myersLCS64(av, m.b.([]int64))
case []int32:
return myersLCS32(av, m.b.([]int32))
case []uint8:
return myersLCS8(av, m.b.([]uint8))
}
panic(fmt.Sprintf("unreachable: wrong type: %T", m.a))
}
func (m *Myers) ses(idx int, a, b interface{}, na, nb, cx, cy int32) []Edit {
var ses []Edit
if na > 0 && nb > 0 {
d, x, y, u, v := middleSnake(cmpFor(a, b), na, nb)
if d > 1 || (x != u && y != v) {
ses = append(ses,
m.ses(idx+1, m.slicer(a, 0, x), m.slicer(b, 0, y), x, y, cx, cy)...)
if x != u && y != v {
// middle snake is part of the lcs.
ses = append(ses, m.edits(m.slicer(a, x, u), Identical, int(cx+x), int(cy+y))...)
}
return append(ses,
m.ses(idx+1, m.slicer(a, u, na), m.slicer(b, v, nb), na-u, nb-v, cx+u, cy+v)...)
}
if nb > na {
// a is part of the LCS.
ses = append(ses, m.edits(m.slicer(a, 0, na), Identical, int(cx), int(cy))...)
return append(ses,
m.ses(idx+1, nil, m.slicer(b, na, nb), 0, nb-na, cx+na, cy+na)...)
}
if na > nb {
// b is part of the LCS.
ses = append(ses, m.edits(m.slicer(b, 0, nb), Identical, int(cx), int(cy))...)
return append(ses,
m.ses(idx+1, m.slicer(a, nb, na), nil, na-nb, 0, cx+nb, cy+nb)...)
}
return ses
}
if na > 0 {
return m.edits(a, Delete, int(cx), int(cy))
}
return m.edits(b, Insert, int(cx), int(cy))
}
// SES returns the shortest edit script.
func (m *Myers) SES() EditScript {
createEdit := func(cx, cy, i int, op EditOp, val interface{}) Edit {
atx := cx + i
if op == Insert {
atx = cx
}
return Edit{op, atx, cy + i, val}
}
switch m.a.(type) {
case []int64:
m.slicer = func(v interface{}, from, to int32) interface{} {
return v.([]int64)[from:to]
}
m.edits = func(v interface{}, op EditOp, cx, cy int) []Edit {
var edits []Edit
for i, val := range v.([]int64) {
edits = append(edits, createEdit(cx, cy, i, op, val))
}
return edits
}
case []int32:
m.slicer = func(v interface{}, from, to int32) interface{} {
return v.([]int32)[from:to]
}
m.edits = func(v interface{}, op EditOp, cx, cy int) []Edit {
var edits []Edit
for i, val := range v.([]int32) {
edits = append(edits, createEdit(cx, cy, i, op, val))
}
return edits
}
case []uint8:
m.slicer = func(v interface{}, from, to int32) interface{} {
return v.([]uint8)[from:to]
}
m.edits = func(v interface{}, op EditOp, cx, cy int) []Edit {
var edits []Edit
for i, val := range v.([]uint8) {
edits = append(edits, createEdit(cx, cy, i, op, val))
}
return edits
}
default:
panic(fmt.Sprintf("unreachable: wrong type: %T", m.a))
}
return m.ses(0, m.a, m.b, int32(m.na), int32(m.nb), 0, 0)
} | algo/lcs/myers.go | 0.617167 | 0.442877 | myers.go | starcoder |
package values
import (
"reflect"
"github.com/ppapapetrou76/go-testing/types"
)
// MapValue is a struct that holds a string map value
type MapValue struct {
value interface{}
}
// Value returns the actual value of the map
func (s MapValue) Value() interface{} {
return s.value
}
// IsEqualTo returns true if the value is equal to the expected value, else false
func (s MapValue) IsEqualTo(expected interface{}) bool {
if !IsMap(expected) {
return false
}
if reflect.TypeOf(s.Value()).Elem() != reflect.TypeOf(expected).Elem() {
return false
}
expectedValue := reflect.ValueOf(expected)
actualValue := reflect.ValueOf(s.Value())
return areMapsEqual(actualValue, expectedValue)
}
// IsEmpty returns true if the map is empty else false
func (s MapValue) IsEmpty() bool {
return s.HasSize(0)
}
// IsNotEmpty returns true if the map is not empty else false
func (s MapValue) IsNotEmpty() bool {
return !s.IsEmpty()
}
// HasSize returns true if the map has the expected size else false
func (s MapValue) HasSize(length int) bool {
return reflect.ValueOf(s.Value()).Len() == length
}
// Size returns the map size
func (s MapValue) Size() int {
return 0
}
func (s MapValue) hasKeyValue(key, value interface{}) bool {
actualValue := reflect.ValueOf(s.Value())
keyValue := actualValue.MapIndex(reflect.ValueOf(key))
return areEqualValues(keyValue, reflect.ValueOf(value))
}
// HasEntry returns true if the map has the given key,value pair (map entry)
func (s MapValue) HasEntry(entry types.MapEntry) bool {
return s.HasKey(entry.Key()) && s.hasKeyValue(entry.Key(), entry.Value())
}
// HasKey returns true if the map has the given key
func (s MapValue) HasKey(key interface{}) bool {
if !reflect.TypeOf(key).Comparable() {
return false
}
actualValue := reflect.ValueOf(s.Value())
return actualValue.MapIndex(reflect.ValueOf(key)).IsValid()
}
// HasValue returns true if the map has the given value
func (s MapValue) HasValue(value interface{}) bool {
actualValue := reflect.ValueOf(s.Value())
keys := reflect.ValueOf(s.Value()).MapKeys()
for _, k := range keys {
if areEqualValues(actualValue.MapIndex(k), reflect.ValueOf(value)) {
return true
}
}
return false
}
// NewKeyStringMap creates and returns a MapValue struct initialed with the given value
func NewKeyStringMap(value interface{}) MapValue {
return MapValue{value: value}
}
// IsMap returns true if the given value is a map, else false
func IsMap(value interface{}) bool {
return reflect.ValueOf(value).Kind() == reflect.Map
} | internal/pkg/values/map_value.go | 0.882535 | 0.579222 | map_value.go | starcoder |
// Package matrix can be used to wrap a DataFrame such that it implements the Matrix
// interface found in various external packages such as gonum.
package matrix
import (
"strconv"
"github.com/padchin/dataframe-go"
)
// Matrix replicates gonum/mat Matrix interface.
type Matrix interface {
// Dims returns the dimensions of a Matrix.
Dims() (r, c int)
// At returns the value of a matrix element at row i, column j.
// It will panic if i or j are out of bounds for the matrix.
At(i, j int) float64
// T returns the transpose of the Matrix. Whether T returns a copy of the
// underlying data is implementation dependent.
// This method may be implemented using the Transpose type, which
// provides an implicit matrix transpose.
T() Matrix
}
// MatrixWrap is used to wrap a dataframe so that it can satisfy the Matrix interface.
// All Series contained by DataFrame must be of type SeriesFloat64.
type MatrixWrap struct {
*dataframe.DataFrame
}
// Dims returns the dimensions of a Matrix.
func (m MatrixWrap) Dims() (r, c int) {
return m.NRows(dataframe.DontLock), len(m.Series)
}
// At returns the value of a matrix element at row i, column j.
// It will panic if i or j are out of bounds for the matrix.
func (m MatrixWrap) At(i, j int) float64 {
col := m.Series[j]
return col.Value(i, dataframe.DontLock).(float64)
}
// T returns the transpose of the MatrixWrap. It returns a copy instead of performing
// the operation "in-place".
func (m MatrixWrap) T() Matrix {
// More direct approach: https://gist.github.com/tanaikech/5cb41424ff8be0fdf19e78d375b6adb8
mm, nn := m.Dims()
// Create new dataframe
ss := []dataframe.Series{}
init := &dataframe.SeriesInit{Size: nn}
for i := 0; i < mm; i++ {
ss = append(ss, dataframe.NewSeriesFloat64(strconv.Itoa(i), init))
}
df := dataframe.NewDataFrame(ss...)
// Copy values into df
for i := 0; i < mm; i++ {
vals := m.Row(i, true, dataframe.SeriesIdx)
for k, v := range vals {
df.Series[i].Update(k.(int), v, dataframe.DontLock)
}
}
return MatrixWrap{df}
}
// Set alters the matrix element at row i, column j to v.
// It will panic if i or j are out of bounds for the matrix.
func (m MatrixWrap) Set(i, j int, v float64) {
m.Update(i, j, v, dataframe.DontLock)
} | math/matrix/matrix.go | 0.860252 | 0.703269 | matrix.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// RoleAssignment
type RoleAssignment struct {
Entity
// Description of the Role Assignment.
description *string
// The display or friendly name of the role Assignment.
displayName *string
// List of ids of role scope member security groups. These are IDs from Azure Active Directory.
resourceScopes []string
// Role definition this assignment is part of.
roleDefinition RoleDefinitionable
// List of ids of role scope member security groups. These are IDs from Azure Active Directory.
scopeMembers []string
// Specifies the type of scope for a Role Assignment. Default type 'ResourceScope' allows assignment of ResourceScopes. For 'AllDevices', 'AllLicensedUsers', and 'AllDevicesAndLicensedUsers', the ResourceScopes property should be left empty. Possible values are: resourceScope, allDevices, allLicensedUsers, allDevicesAndLicensedUsers.
scopeType *RoleAssignmentScopeType
}
// NewRoleAssignment instantiates a new roleAssignment and sets the default values.
func NewRoleAssignment()(*RoleAssignment) {
m := &RoleAssignment{
Entity: *NewEntity(),
}
return m
}
// CreateRoleAssignmentFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateRoleAssignmentFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewRoleAssignment(), nil
}
// GetDescription gets the description property value. Description of the Role Assignment.
func (m *RoleAssignment) GetDescription()(*string) {
if m == nil {
return nil
} else {
return m.description
}
}
// GetDisplayName gets the displayName property value. The display or friendly name of the role Assignment.
func (m *RoleAssignment) GetDisplayName()(*string) {
if m == nil {
return nil
} else {
return m.displayName
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *RoleAssignment) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["description"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetDescription(val)
}
return nil
}
res["displayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetDisplayName(val)
}
return nil
}
res["resourceScopes"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfPrimitiveValues("string")
if err != nil {
return err
}
if val != nil {
res := make([]string, len(val))
for i, v := range val {
res[i] = *(v.(*string))
}
m.SetResourceScopes(res)
}
return nil
}
res["roleDefinition"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateRoleDefinitionFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetRoleDefinition(val.(RoleDefinitionable))
}
return nil
}
res["scopeMembers"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfPrimitiveValues("string")
if err != nil {
return err
}
if val != nil {
res := make([]string, len(val))
for i, v := range val {
res[i] = *(v.(*string))
}
m.SetScopeMembers(res)
}
return nil
}
res["scopeType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseRoleAssignmentScopeType)
if err != nil {
return err
}
if val != nil {
m.SetScopeType(val.(*RoleAssignmentScopeType))
}
return nil
}
return res
}
// GetResourceScopes gets the resourceScopes property value. List of ids of role scope member security groups. These are IDs from Azure Active Directory.
func (m *RoleAssignment) GetResourceScopes()([]string) {
if m == nil {
return nil
} else {
return m.resourceScopes
}
}
// GetRoleDefinition gets the roleDefinition property value. Role definition this assignment is part of.
func (m *RoleAssignment) GetRoleDefinition()(RoleDefinitionable) {
if m == nil {
return nil
} else {
return m.roleDefinition
}
}
// GetScopeMembers gets the scopeMembers property value. List of ids of role scope member security groups. These are IDs from Azure Active Directory.
func (m *RoleAssignment) GetScopeMembers()([]string) {
if m == nil {
return nil
} else {
return m.scopeMembers
}
}
// GetScopeType gets the scopeType property value. Specifies the type of scope for a Role Assignment. Default type 'ResourceScope' allows assignment of ResourceScopes. For 'AllDevices', 'AllLicensedUsers', and 'AllDevicesAndLicensedUsers', the ResourceScopes property should be left empty. Possible values are: resourceScope, allDevices, allLicensedUsers, allDevicesAndLicensedUsers.
func (m *RoleAssignment) GetScopeType()(*RoleAssignmentScopeType) {
if m == nil {
return nil
} else {
return m.scopeType
}
}
// Serialize serializes information the current object
func (m *RoleAssignment) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteStringValue("description", m.GetDescription())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("displayName", m.GetDisplayName())
if err != nil {
return err
}
}
if m.GetResourceScopes() != nil {
err = writer.WriteCollectionOfStringValues("resourceScopes", m.GetResourceScopes())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("roleDefinition", m.GetRoleDefinition())
if err != nil {
return err
}
}
if m.GetScopeMembers() != nil {
err = writer.WriteCollectionOfStringValues("scopeMembers", m.GetScopeMembers())
if err != nil {
return err
}
}
if m.GetScopeType() != nil {
cast := (*m.GetScopeType()).String()
err = writer.WriteStringValue("scopeType", &cast)
if err != nil {
return err
}
}
return nil
}
// SetDescription sets the description property value. Description of the Role Assignment.
func (m *RoleAssignment) SetDescription(value *string)() {
if m != nil {
m.description = value
}
}
// SetDisplayName sets the displayName property value. The display or friendly name of the role Assignment.
func (m *RoleAssignment) SetDisplayName(value *string)() {
if m != nil {
m.displayName = value
}
}
// SetResourceScopes sets the resourceScopes property value. List of ids of role scope member security groups. These are IDs from Azure Active Directory.
func (m *RoleAssignment) SetResourceScopes(value []string)() {
if m != nil {
m.resourceScopes = value
}
}
// SetRoleDefinition sets the roleDefinition property value. Role definition this assignment is part of.
func (m *RoleAssignment) SetRoleDefinition(value RoleDefinitionable)() {
if m != nil {
m.roleDefinition = value
}
}
// SetScopeMembers sets the scopeMembers property value. List of ids of role scope member security groups. These are IDs from Azure Active Directory.
func (m *RoleAssignment) SetScopeMembers(value []string)() {
if m != nil {
m.scopeMembers = value
}
}
// SetScopeType sets the scopeType property value. Specifies the type of scope for a Role Assignment. Default type 'ResourceScope' allows assignment of ResourceScopes. For 'AllDevices', 'AllLicensedUsers', and 'AllDevicesAndLicensedUsers', the ResourceScopes property should be left empty. Possible values are: resourceScope, allDevices, allLicensedUsers, allDevicesAndLicensedUsers.
func (m *RoleAssignment) SetScopeType(value *RoleAssignmentScopeType)() {
if m != nil {
m.scopeType = value
}
} | models/role_assignment.go | 0.640748 | 0.422505 | role_assignment.go | starcoder |
package physical
import (
"math"
"github.com/tidepool-org/platform/data"
"github.com/tidepool-org/platform/structure"
)
const (
DistanceFeetPerMile = 5280.0
DistanceKilometersPerMile = 1.609344
DistanceMetersPerMile = 1609.344
DistanceUnitsFeet = "feet"
DistanceUnitsKilometers = "kilometers"
DistanceUnitsMeters = "meters"
DistanceUnitsMiles = "miles"
DistanceUnitsYards = "yards"
DistanceValueFeetMaximum = DistanceValueMilesMaximum * DistanceFeetPerMile
DistanceValueFeetMinimum = DistanceValueMilesMinimum * DistanceFeetPerMile
DistanceValueKilometersMaximum = DistanceValueMilesMaximum * DistanceKilometersPerMile
DistanceValueKilometersMinimum = DistanceValueMilesMinimum * DistanceKilometersPerMile
DistanceValueMetersMaximum = DistanceValueMilesMaximum * DistanceMetersPerMile
DistanceValueMetersMinimum = DistanceValueMilesMinimum * DistanceMetersPerMile
DistanceValueMilesMaximum = 100.0
DistanceValueMilesMinimum = 0.0
DistanceValueYardsMaximum = DistanceValueMilesMaximum * DistanceYardsPerMile
DistanceValueYardsMinimum = DistanceValueMilesMinimum * DistanceYardsPerMile
DistanceYardsPerMile = 1760.0
)
func DistanceUnits() []string {
return []string{
DistanceUnitsFeet,
DistanceUnitsKilometers,
DistanceUnitsMeters,
DistanceUnitsMiles,
DistanceUnitsYards,
}
}
type Distance struct {
Units *string `json:"units,omitempty" bson:"units,omitempty"`
Value *float64 `json:"value,omitempty" bson:"value,omitempty"`
}
func ParseDistance(parser structure.ObjectParser) *Distance {
if !parser.Exists() {
return nil
}
datum := NewDistance()
parser.Parse(datum)
return datum
}
func NewDistance() *Distance {
return &Distance{}
}
func (d *Distance) Parse(parser structure.ObjectParser) {
d.Units = parser.String("units")
d.Value = parser.Float64("value")
}
func (d *Distance) Validate(validator structure.Validator) {
validator.String("units", d.Units).Exists().OneOf(DistanceUnits()...)
validator.Float64("value", d.Value).Exists().InRange(DistanceValueRangeForUnits(d.Units))
}
func (d *Distance) Normalize(normalizer data.Normalizer) {}
func DistanceValueRangeForUnits(units *string) (float64, float64) {
if units != nil {
switch *units {
case DistanceUnitsFeet:
return DistanceValueFeetMinimum, DistanceValueFeetMaximum
case DistanceUnitsKilometers:
return DistanceValueKilometersMinimum, DistanceValueKilometersMaximum
case DistanceUnitsMeters:
return DistanceValueMetersMinimum, DistanceValueMetersMaximum
case DistanceUnitsMiles:
return DistanceValueMilesMinimum, DistanceValueMilesMaximum
case DistanceUnitsYards:
return DistanceValueYardsMinimum, DistanceValueYardsMaximum
}
}
return -math.MaxFloat64, math.MaxFloat64
} | data/types/activity/physical/distance.go | 0.812421 | 0.441854 | distance.go | starcoder |
package coefficient
// Pairing notes the multiplier and the powers applied to a oldformula term.
type Pairing struct {
PowerN int
PowerM int
NegateMultiplier bool
}
// GenerateCoefficientSets creates a list of locked coefficient sets (powers and multipliers)
// based on a given list of relationships.
func (pairing Pairing) GenerateCoefficientSets(relationships []Relationship) []*Pairing {
pairs := []*Pairing{}
negateMultiplierIfPowerNIsOdd := pairing.PowerN%2 != 0
negateMultiplierIfSumIsOdd := (pairing.PowerN+pairing.PowerM)%2 != 0
pairingByRelationship := map[Relationship]*Pairing{
PlusNPlusM: {
PowerN: pairing.PowerN,
PowerM: pairing.PowerM,
NegateMultiplier: false,
},
PlusMPlusN: {
PowerN: pairing.PowerM,
PowerM: pairing.PowerN,
NegateMultiplier: false,
},
PlusMPlusNNegateMultiplierIfOddPowerSum: {
PowerN: pairing.PowerM,
PowerM: pairing.PowerN,
NegateMultiplier: negateMultiplierIfSumIsOdd,
},
MinusNMinusM: {
PowerN: -1 * pairing.PowerN,
PowerM: -1 * pairing.PowerM,
NegateMultiplier: false,
},
MinusMMinusN: {
PowerN: -1 * pairing.PowerM,
PowerM: -1 * pairing.PowerN,
NegateMultiplier: false,
},
MinusMMinusNNegateMultiplierIfOddPowerSum: {
PowerN: -1 * pairing.PowerM,
PowerM: -1 * pairing.PowerN,
NegateMultiplier: negateMultiplierIfSumIsOdd,
},
PlusMMinusSumNAndM: {
PowerN: pairing.PowerM,
PowerM: -1 * (pairing.PowerN + pairing.PowerM),
NegateMultiplier: false,
},
MinusSumNAndMPlusN: {
PowerN: -1 * (pairing.PowerN + pairing.PowerM),
PowerM: pairing.PowerN,
NegateMultiplier: false,
},
PlusNMinusM: {
PowerN: pairing.PowerN,
PowerM: -1 * pairing.PowerM,
NegateMultiplier: false,
},
PlusNMinusMNegateMultiplierIfOddPowerN: {
PowerN: pairing.PowerN,
PowerM: -1 * pairing.PowerM,
NegateMultiplier: negateMultiplierIfPowerNIsOdd,
},
PlusNMinusMNegateMultiplierIfOddPowerSum: {
PowerN: pairing.PowerN,
PowerM: -1 * pairing.PowerM,
NegateMultiplier: negateMultiplierIfSumIsOdd,
},
MinusNPlusMNegateMultiplierIfOddPowerN: {
PowerN: -1 * pairing.PowerN,
PowerM: pairing.PowerM,
NegateMultiplier: negateMultiplierIfPowerNIsOdd,
},
MinusNPlusMNegateMultiplierIfOddPowerSum: {
PowerN: -1 * pairing.PowerN,
PowerM: pairing.PowerM,
NegateMultiplier: negateMultiplierIfSumIsOdd,
},
PlusMMinusN: {
PowerN: pairing.PowerM,
PowerM: -1 * pairing.PowerN,
NegateMultiplier: false,
},
MinusMPlusN: {
PowerN: -1 * pairing.PowerM,
PowerM: pairing.PowerN,
NegateMultiplier: false,
},
MinusNPlusM: {
PowerN: -1 * pairing.PowerN,
PowerM: pairing.PowerM,
NegateMultiplier: false,
},
}
for _, relationship := range relationships {
pairWithSameRelationship := pairingByRelationship[relationship]
newPair := &Pairing{
PowerN: pairWithSameRelationship.PowerN,
PowerM: pairWithSameRelationship.PowerM,
NegateMultiplier: pairWithSameRelationship.NegateMultiplier,
}
pairs = append(pairs, newPair)
}
return pairs
}
// Relationship relates how a pair of coordinates should be applied.
type Relationship string
// Relationship s determine the order and sign of powers n and m.
// Plus means *1, Minus means *-1
// If N appears first the powers then power N is applied to the number and power M to the complex conjugate.
// If M appears first the powers then power M is applied to the number and power N to the complex conjugate.
// MaybeFlipScale will multiply the scale by -1 if N + M is odd.
const (
PlusNPlusM Relationship = "+N+M"
PlusMPlusN Relationship = "+M+N"
MinusNMinusM Relationship = "-N-M"
MinusMMinusN Relationship = "-M-N"
PlusMPlusNNegateMultiplierIfOddPowerSum Relationship = "+M+NF(N+M)"
MinusMMinusNNegateMultiplierIfOddPowerSum Relationship = "-M-NF(N+M)"
PlusMMinusSumNAndM Relationship = "+M-(N+M)"
MinusSumNAndMPlusN Relationship = "-(N+M)+N"
PlusMMinusN Relationship = "+M-N"
MinusMPlusN Relationship = "-M+N"
PlusNMinusM Relationship = "+N-M"
PlusNMinusMNegateMultiplierIfOddPowerN Relationship = "+N-MF(N)"
MinusNPlusMNegateMultiplierIfOddPowerN Relationship = "-N+MF(N)"
MinusNPlusM Relationship = "-N+M"
PlusNMinusMNegateMultiplierIfOddPowerSum Relationship = "+N-MF(N+M)"
MinusNPlusMNegateMultiplierIfOddPowerSum Relationship = "-N+MF(N+M)"
) | entities/formula/coefficient/coefficientPair.go | 0.716318 | 0.527682 | coefficientPair.go | starcoder |
package cthramp
import "fmt"
// Range holds value minimum and value maximum (range) and provides the similar
// functions as a module.
type Range struct {
VMin, VMax float64
}
// AsFloat returns red, green, blue values each as float64 in range [0..1].
func (r *Range) AsFloat(val float64) (float64, float64, float64) {
return AsFloat(val, r.VMin, r.VMax)
}
// NewRange return new Range with defined minimum and maximum values.
func NewRange(min, max float64) *Range {
r := new(Range)
r.VMin, r.VMax = min, max
return r
}
// AsUInt8 returns red, green, blue values each as uint8 in range [0..255].
func (r *Range) AsUInt8(val float64) (uint8, uint8, uint8) {
return AsUInt8(val, r.VMin, r.VMax)
}
// AsStr returns red, green, blue values represented as six hex digits string
// which begins with hash (#). It looks like a HTML RGB color #00FF00.
func (r *Range) AsStr(val float64) string {
return AsStr(val, r.VMin, r.VMax)
}
// AsFloat returns red, green, blue values each as float64 in range [0..1].
func AsFloat(val, vmin, vmax float64) (float64, float64, float64) {
return cth(val, vmin, vmax)
}
// AsUInt8 returns red, green, blue values each as uint8 in range [0..255].
func AsUInt8(val, vmin, vmax float64) (uint8, uint8, uint8) {
const m = 0xFF
r, g, b := AsFloat(val, vmin, vmax)
return uint8(r * m), uint8(g * m), uint8(b * m)
}
// AsStr returns red, green, blue values represented as six hex digits string
// which begins with hash (#). It looks like a HTML RGB color #00FF00.
func AsStr(val, vmin, vmax float64) string {
r, g, b := AsUInt8(val, vmin, vmax)
return fmt.Sprintf("#%02X%02X%02X", r, g, b)
}
// Pivot points can be modified/adjusted for better correlation.
func cth(val, vmin, vmax float64) (float64, float64, float64) {
var (
vrange float64 = vmax - vmin
r, g, b float64 = 1, 1, 1
)
if val < vmin {
val = vmin
}
if val > vmax {
val = vmax
}
if val < (vmin + 0.25*vrange) {
r = 0
g = 4 * (val - vmin) / vrange
} else if val < (vmin + 0.5*vrange) {
r = 0
b = 1 + 4*(vmin+0.25*vrange-val)/vrange
} else if val < (vmin + 0.75*vrange) {
b = 0
r = 4 * (val - vmin - 0.5*vrange) / vrange
} else {
b = 0
g = 1 + 4*(vmin+0.75*vrange-val)/vrange
}
return r, g, b
} | cthramp.go | 0.864654 | 0.556882 | cthramp.go | starcoder |
package components
import (
"github.com/b4tman/caldav-go/icalendar/values"
"github.com/b4tman/caldav-go/utils"
"time"
)
type Event struct {
// defines the persistent, globally unique identifier for the calendar component.
UID string `ical:",required"`
// indicates the date/time that the instance of the iCalendar object was created.
DateStamp *values.DateTime `ical:"dtstamp,required"`
// specifies when the calendar component begins.
DateStart *values.DateTime `ical:"dtstart,required"`
// specifies the date and time that a calendar component ends.
DateEnd *values.DateTime `ical:"dtend,omitempty"`
// specifies a positive duration of time.
Duration *values.Duration `ical:",omitempty"`
// defines the access classification for a calendar component.
AccessClassification values.EventAccessClassification `ical:"class,omitempty"`
// specifies the date and time that the calendar information was created by the calendar user agent in the
// calendar store.
// Note: This is analogous to the creation date and time for a file in the file system.
Created *values.DateTime `ical:",omitempty"`
// provides a more complete description of the calendar component, than that provided by the Summary property.
Description string `ical:",omitempty"`
// specifies information related to the global position for the activity specified by a calendar component.
Geo *values.Geo `ical:",omitempty"`
// specifies the date and time that the information associated with the calendar component was last revised in the
// calendar store.
// Note: This is analogous to the modification date and time for a file in the file system.
LastModified *values.DateTime `ical:"last-modified,omitempty"`
// defines the intended venue for the activity defined by a calendar component.
Location *values.Location `ical:",omitempty"`
// defines the organizer for a calendar component.
Organizer *values.OrganizerContact `ical:",omitempty"`
// defines the relative priority for a calendar component.
Priority int `ical:",omitempty"`
// defines the revision sequence number of the calendar component within a sequence of revisions.
Sequence int `ical:",omitempty"`
// efines the overall status or confirmation for the calendar component.
Status values.EventStatus `ical:",omitempty"`
// defines a short summary or subject for the calendar component.
Summary string `ical:",omitempty"`
// defines whether an event is transparent or not to busy time searches.
values.TimeTransparency `ical:"transp,omitempty"`
// defines a Uniform Resource Locator (URL) associated with the iCalendar object.
Url *values.Url `ical:",omitempty"`
// used in conjunction with the "UID" and "SEQUENCE" property to identify a specific instance of a recurring
// event calendar component. The property value is the effective value of the DateStart property of the
// recurrence instance.
RecurrenceId *values.DateTime `ical:"recurrence_id,omitempty"`
// defines a rule or repeating pattern for recurring events, to-dos, or time zone definitions.
RecurrenceRules []*values.RecurrenceRule `ical:",omitempty"`
// property provides the capability to associate a document object with a calendar component.
Attachment *values.Url `ical:"attach,omitempty"`
// defines an "Attendee" within a calendar component.
Attendees []*values.AttendeeContact `ical:"attendee,omitempty"`
// defines the categories for a calendar component.
Categories *values.CSV `ical:",omitempty"`
// specifies non-processing information intended to provide a comment to the calendar user.
Comments []values.Comment `ical:",omitempty"`
// used to represent contact information or alternately a reference to contact information associated with the calendar component.
ContactInfo *values.CSV `ical:"contact,omitempty"`
// defines the list of date/time exceptions for a recurring calendar component.
*values.ExceptionDateTimes `ical:",omitempty"`
// defines the list of date/times for a recurrence set.
*values.RecurrenceDateTimes `ical:",omitempty"`
// used to represent a relationship or reference between one calendar component and another.
RelatedTo *values.Url `ical:"related-to,omitempty"`
// defines the equipment or resources anticipated for an activity specified by a calendar entity.
Resources *values.CSV `ical:",omitempty"`
}
// validates the event internals
func (e *Event) ValidateICalValue() error {
if e.UID == "" {
return utils.NewError(e.ValidateICalValue, "the UID value must be set", e, nil)
}
if e.DateStart == nil {
return utils.NewError(e.ValidateICalValue, "event start date must be set", e, nil)
}
if e.DateEnd == nil && e.Duration == nil {
return utils.NewError(e.ValidateICalValue, "event end date or duration must be set", e, nil)
}
if e.DateEnd != nil && e.Duration != nil {
return utils.NewError(e.ValidateICalValue, "event end date and duration are mutually exclusive fields", e, nil)
}
return nil
}
// adds one or more recurrence rule to the event
func (e *Event) AddRecurrenceRules(r ...*values.RecurrenceRule) {
e.RecurrenceRules = append(e.RecurrenceRules, r...)
}
// adds one or more recurrence rule exception to the event
func (e *Event) AddRecurrenceExceptions(d ...*values.DateTime) {
if e.ExceptionDateTimes == nil {
e.ExceptionDateTimes = new(values.ExceptionDateTimes)
}
*e.ExceptionDateTimes = append(*e.ExceptionDateTimes, d...)
}
// checks to see if the event is a recurrence
func (e *Event) IsRecurrence() bool {
return e.RecurrenceId != nil
}
// checks to see if the event is a recurrence override
func (e *Event) IsOverride() bool {
return e.IsRecurrence() && !e.RecurrenceId.Equals(e.DateStart)
}
// creates a new iCalendar event with no end time
func NewEvent(uid string, start time.Time) *Event {
e := new(Event)
e.UID = uid
e.DateStamp = values.NewDateTime(time.Now().UTC())
e.DateStart = values.NewDateTime(start)
return e
}
// creates a new iCalendar event that lasts a certain duration
func NewEventWithDuration(uid string, start time.Time, duration time.Duration) *Event {
e := NewEvent(uid, start)
e.Duration = values.NewDuration(duration)
return e
}
// creates a new iCalendar event that has an explicit start and end time
func NewEventWithEnd(uid string, start time.Time, end time.Time) *Event {
e := NewEvent(uid, start)
e.DateEnd = values.NewDateTime(end)
return e
} | icalendar/components/event.go | 0.863952 | 0.569314 | event.go | starcoder |
package mines
import (
"fmt"
"math/rand"
"strconv"
"time"
)
const (
// String to be marked for the mined cell.
Mine = "*"
// String to be marked for the Empty cell.
Empty = " "
)
// Generate board based on the input count configuration.
func GenerateBoard(rows int, columns int, mines int) [][]string {
board := EmptyBoard(rows, columns)
fmt.Println(len(board), len(board[0]))
GenerateMines(board, rows, columns, mines)
GenerateValues(board)
return board
}
// Generate values on the board.
func GenerateValues(board [][]string) {
directions := [][]int{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if !IsMine(board, i, j) {
k := 0
for _, d := range directions {
k += CheckMine(board, i+d[0], j+d[1])
}
if k != 0 {
board[i][j] = strconv.Itoa(k)
}
}
}
}
}
// Returns 1 if the coordinate has a mine.
func CheckMine(board [][]string, x int, y int) int {
if IsMine(board, x, y) {
return 1
}
return 0
}
// Returns true if the coordinate has a mine.
func IsMine(board [][]string, x int, y int) bool {
if x < 0 || y < 0 || x >= len(board) || y >= len(board[x]) {
return false
}
return board[x][y] == Mine
}
// Generates mines from the randomized mine positions.
func GenerateMines(mines [][]string, rows int, columns int, count int) {
mp := MinePositions(rows, columns, count)
for k := range mp {
mines[k/columns][k%columns] = Mine
}
}
// Generate mines after generating random positions.
func MinePositions(rows int, columns int, count int) map[int]int {
total := rows * columns
mp := make(map[int]int)
rand.Seed(time.Now().UnixNano())
for {
if len(mp) < count {
mp[rand.Intn(total)] = 1
} else {
break
}
}
return mp
}
// Generate an empty board from rows and columns count.
func EmptyBoard(rows int, columns int) [][]string {
mines := make([][]string, rows)
for i := 0; i < rows; i++ {
mines[i] = make([]string, columns)
for j := range mines[i] {
mines[i][j] = Empty
}
}
return mines
} | mines/minesweeper.go | 0.636805 | 0.409221 | minesweeper.go | starcoder |
package main
// Astar algorithm
type Astar struct {
graph *graph
source int
target int
hFn func(nd1, nd2 int) float32 // heuristic
frontier map[int]graphEdge // search frontier
gcost map[int]float32 // cost to some node
fcost map[int]float32 // cost to target. fcost = gcost + hcost (heuristic)
spt map[int]graphEdge // shortest path tree
err error
}
// NewAstar returns a instance of Dijkstra.
func NewAstar(g *graph, s, t int) *Astar {
return &Astar{
graph: g,
source: s,
target: t,
hFn: func(nd1, nd2 int) float32 { return 0 },
frontier: make(map[int]graphEdge),
fcost: make(map[int]float32),
gcost: make(map[int]float32),
spt: make(map[int]graphEdge),
}
}
// NewAstarWithH returns a instance of Dijkstra.
func NewAstarWithH(g *graph, s, t int, h func(nd1, nd2 int) float32) *Astar {
return &Astar{
graph: g,
source: s,
target: t,
hFn: h,
frontier: make(map[int]graphEdge),
fcost: make(map[int]float32),
gcost: make(map[int]float32),
spt: make(map[int]graphEdge),
}
}
// Search trys to find the shortest path from source to target.
// source is a node index, same as target.
func (d *Astar) Search() {
d.frontier[d.source] = graphEdge{From: d.source, To: d.source}
d.gcost[d.source] = 0
d.fcost[d.source] = 0
pq := NewIndexedPriorityQueueMin(d.fcost)
pq.Insert(d.source)
for !pq.IsEmpty() {
idx, err := pq.Pop()
if err != nil {
d.err = err
return
}
edge := d.frontier[idx]
d.spt[idx] = edge
i := edge.To
if i == d.target {
return
}
for _, e := range d.graph.edges[i] {
t := e.To
g := d.gcost[i] + e.Cost
if _, ok := d.frontier[t]; !ok {
d.frontier[t] = e
d.gcost[t] = g
d.fcost[t] = g + d.hFn(t, d.target)
pq.Insert(t)
} else if g < d.gcost[t] {
if _, ok := d.spt[t]; !ok {
d.frontier[t] = e
d.gcost[t] = g
d.fcost[t] = g + d.hFn(t, d.target)
pq.ChangePriority(t)
}
}
}
}
}
// PathToTarget returns shortest path from source to target.
func (d *Astar) PathToTarget() ([]graphEdge, error) {
if d.err != nil {
return []graphEdge{}, d.err
}
var path []graphEdge
idx := d.target
for {
if idx == d.source {
break
}
e, ok := d.spt[idx]
if !ok {
break
}
path = append(path, e)
idx = e.From
}
return reversePath(path), nil
} | astar.go | 0.703244 | 0.401365 | astar.go | starcoder |
package fieldpath
import (
"fmt"
"strconv"
"strings"
"unicode/utf8"
"github.com/crossplane/crossplane-runtime/pkg/errors"
)
// A SegmentType within a field path; either a field within an object, or an
// index within an array.
type SegmentType int
// Segment types.
const (
_ SegmentType = iota
SegmentField
SegmentIndex
)
// A Segment of a field path.
type Segment struct {
Type SegmentType
Field string
Index uint
}
// Segments of a field path.
type Segments []Segment
func (sg Segments) String() string {
var b strings.Builder
for _, s := range sg {
switch s.Type {
case SegmentField:
if s.Field == wildcard || strings.ContainsRune(s.Field, period) {
b.WriteString(fmt.Sprintf("[%s]", s.Field))
continue
}
b.WriteString(fmt.Sprintf(".%s", s.Field))
case SegmentIndex:
b.WriteString(fmt.Sprintf("[%d]", s.Index))
}
}
return strings.TrimPrefix(b.String(), ".")
}
// FieldOrIndex produces a new segment from the supplied string. The segment is
// considered to be an array index if the string can be interpreted as an
// unsigned 32 bit integer. Anything else is interpreted as an object field
// name.
func FieldOrIndex(s string) Segment {
// Attempt to parse the segment as an unsigned integer. If the integer is
// larger than 2^32 (the limit for most JSON arrays) we presume it's too big
// to be an array index, and is thus a field name.
if i, err := strconv.ParseUint(s, 10, 32); err == nil {
return Segment{Type: SegmentIndex, Index: uint(i)}
}
// If the segment is not a valid unsigned integer we presume it's
// a string field name.
return Field(s)
}
// Field produces a new segment from the supplied string. The segment is always
// considered to be an object field name.
func Field(s string) Segment {
return Segment{Type: SegmentField, Field: strings.Trim(s, "'\"")}
}
// Parse the supplied path into a slice of Segments.
func Parse(path string) (Segments, error) {
l := &lexer{input: path, items: make(chan item)}
go l.run()
segments := make(Segments, 0, 1)
for i := range l.items {
// We're only worried about names, not separators.
switch i.typ { // nolint:exhaustive
case itemField:
segments = append(segments, Field(i.val))
case itemFieldOrIndex:
segments = append(segments, FieldOrIndex(i.val))
case itemError:
return nil, errors.Errorf("%s at position %d", i.val, i.pos)
}
}
return segments, nil
}
const (
period = '.'
leftBracket = '['
rightBracket = ']'
wildcard = "*"
)
type itemType int
const (
itemError itemType = iota
itemPeriod
itemLeftBracket
itemRightBracket
itemField
itemFieldOrIndex
itemEOL
)
type item struct {
typ itemType
pos int
val string
}
type stateFn func(*lexer) stateFn
// A simplified version of the text/template lexer.
// https://github.com/golang/go/blob/6396bc9d/src/text/template/parse/lex.go#L108
type lexer struct {
input string
pos int
start int
items chan item
}
func (l *lexer) run() {
for state := lexField; state != nil; {
state = state(l)
}
close(l.items)
}
func (l *lexer) emit(t itemType) {
// Don't emit empty values.
if l.pos <= l.start {
return
}
l.items <- item{typ: t, pos: l.start, val: l.input[l.start:l.pos]}
l.start = l.pos
}
func (l *lexer) errorf(pos int, format string, args ...interface{}) stateFn {
l.items <- item{typ: itemError, pos: pos, val: fmt.Sprintf(format, args...)}
return nil
}
func lexField(l *lexer) stateFn {
for i, r := range l.input[l.pos:] {
switch r {
// A right bracket may not appear in an object field name.
case rightBracket:
return l.errorf(l.pos+i, "unexpected %q", rightBracket)
// A left bracket indicates the end of the field name.
case leftBracket:
l.pos += i
l.emit(itemField)
return lexLeftBracket
// A period indicates the end of the field name.
case period:
l.pos += i
l.emit(itemField)
return lexPeriod
}
}
// The end of the input indicates the end of the field name.
l.pos = len(l.input)
l.emit(itemField)
l.emit(itemEOL)
return nil
}
func lexPeriod(l *lexer) stateFn {
// A period may not appear at the beginning or the end of the input.
if l.pos == 0 || l.pos == len(l.input)-1 {
return l.errorf(l.pos, "unexpected %q", period)
}
l.pos += utf8.RuneLen(period)
l.emit(itemPeriod)
// A period may only be followed by a field name. We defer checking for
// right brackets to lexField, where they are invalid.
r, _ := utf8.DecodeRuneInString(l.input[l.pos:])
if r == period {
return l.errorf(l.pos, "unexpected %q", period)
}
if r == leftBracket {
return l.errorf(l.pos, "unexpected %q", leftBracket)
}
return lexField
}
func lexLeftBracket(l *lexer) stateFn {
// A right bracket must appear before the input ends.
if !strings.ContainsRune(l.input[l.pos:], rightBracket) {
return l.errorf(l.pos, "unterminated %q", leftBracket)
}
l.pos += utf8.RuneLen(leftBracket)
l.emit(itemLeftBracket)
return lexFieldOrIndex
}
// Strings between brackets may be either a field name or an array index.
// Periods have no special meaning in this context.
func lexFieldOrIndex(l *lexer) stateFn {
// We know a right bracket exists before EOL thanks to the preceding
// lexLeftBracket.
rbi := strings.IndexRune(l.input[l.pos:], rightBracket)
// A right bracket may not immediately follow a left bracket.
if rbi == 0 {
return l.errorf(l.pos, "unexpected %q", rightBracket)
}
// A left bracket may not appear before the next right bracket.
if lbi := strings.IndexRune(l.input[l.pos:l.pos+rbi], leftBracket); lbi > -1 {
return l.errorf(l.pos+lbi, "unexpected %q", leftBracket)
}
// Periods are not considered field separators when we're inside brackets.
l.pos += rbi
l.emit(itemFieldOrIndex)
return lexRightBracket
}
func lexRightBracket(l *lexer) stateFn {
l.pos += utf8.RuneLen(rightBracket)
l.emit(itemRightBracket)
return lexField
} | pkg/fieldpath/fieldpath.go | 0.690037 | 0.45423 | fieldpath.go | starcoder |
package path
import (
"github.com/loki-os/go-ethernet-ip/bufferx"
"github.com/loki-os/go-ethernet-ip/types"
)
type SegmentType types.USInt
const (
SegmentTypePort SegmentType = 0 << 5
SegmentTypeLogical SegmentType = 1 << 5
SegmentTypeNetwork SegmentType = 2 << 5
SegmentTypeSymbolic SegmentType = 3 << 5
SegmentTypeData SegmentType = 4 << 5
SegmentTypeDataType1 SegmentType = 5 << 5
SegmentTypeDataType2 SegmentType = 6 << 5
)
func Paths(arg ...[]byte) []byte {
io := bufferx.New(nil)
for i := 0; i < len(arg); i++ {
io.WL(arg[i])
}
return io.Bytes()
}
type DataTypes types.USInt
const (
DataTypeSimple DataTypes = 0x0
DataTypeANSI DataTypes = 0x11
)
type LogicalType types.USInt
const (
LogicalTypeClassID LogicalType = 0 << 2
LogicalTypeInstanceID LogicalType = 1 << 2
LogicalTypeMemberID LogicalType = 2 << 2
LogicalTypeConnPoint LogicalType = 3 << 2
LogicalTypeAttributeID LogicalType = 4 << 2
LogicalTypeSpecial LogicalType = 5 << 2
LogicalTypeServiceID LogicalType = 6 << 2
)
func DataBuild(tp DataTypes, data []byte, padded bool) []byte {
io := bufferx.New(nil)
firstByte := uint8(SegmentTypeData) | uint8(tp)
io.WL(firstByte)
length := uint8(len(data))
io.WL(length)
io.WL(data)
if padded && io.Len()%2 == 1 {
io.WL(uint8(0))
}
return io.Bytes()
}
func LogicalBuild(tp LogicalType, address types.UDInt, padded bool) []byte {
format := uint8(0)
if address <= 255 {
format = 0
} else if address > 255 && address <= 65535 {
format = 1
} else {
format = 2
}
io := bufferx.New(nil)
firstByte := uint8(SegmentTypeLogical) | uint8(tp) | format
io.WL(firstByte)
if address > 255 && address <= 65535 && padded {
io.WL(uint8(0))
}
if address <= 255 {
io.WL(uint8(address))
} else if address > 255 && address <= 65535 {
io.WL(uint16(address))
} else {
io.WL(address)
}
return io.Bytes()
}
func PortBuild(link []byte, portID uint16, padded bool) []byte {
extendedLinkTag := len(link) > 1
extendedPortTag := !(portID < 15)
io := bufferx.New(nil)
firstByte := uint8(SegmentTypePort)
if extendedLinkTag {
firstByte = firstByte | 0x10
}
if !extendedPortTag {
firstByte = firstByte | uint8(portID)
} else {
firstByte = firstByte | 0xf
}
io.WL(firstByte)
if extendedLinkTag {
io.WL(uint8(len(link)))
}
if extendedPortTag {
io.WL(portID)
}
io.WL(link)
if padded && io.Len()%2 == 1 {
io.WL(uint8(0))
}
return io.Bytes()
} | path/path.go | 0.536313 | 0.522872 | path.go | starcoder |
package store
// Both the S3 and BlackPearl interfaces have a need to cache remote data and
// state in memory. This file implements a few kinds of caches.
import (
"sync"
"time"
)
// head is the structure stored in a sizecache.
type head struct {
expire time.Time
size int64 // size of item. 0 = ?, -1 = doesn't exist. see constant below
}
// A sizecache is used to remember the size or non-size of a remote object.
// The size is either a positive int64, 0 = we don't know, -1 = item doesn't
// exist. Entries will expire after some amount of time. Items not existing
// will expire quicker than items with a positive size.
type sizecache struct {
m sync.RWMutex // protects everything below
cache map[string]head // cache for item sizes
sweeptime time.Time // next time to age everything
}
const (
// constants for head.size. Indicates that the given key is deleted.
sizeDeleted int64 = -1 // any negative number will work
defaultMissTTL = 3 * time.Hour // 3 hours
defaultHitTTL = 240 * time.Hour // 10 days
)
func newSizeCache() *sizecache {
return &sizecache{
cache: make(map[string]head),
}
}
// Get returns the size associated with key. If key is not in the cache
// it will call the fill function to figure out what the size is.
// If a size is negative the error ErrNotExist is returned.
func (s *sizecache) Get(key string, fill func(key string) (int64, error)) (int64, error) {
s.m.Lock()
defer s.m.Unlock()
if time.Now().After(s.sweeptime) {
go s.age()
}
entry := s.cache[key]
if entry.size > 0 {
return entry.size, nil
}
if entry.size < 0 {
// we have previously determined this key does not exist
return 0, ErrNotExist
}
if fill == nil {
return 0, nil
}
// key is not cached, so try to fill it
// TODO(dbrower): we hold the lock m during this call.
// Is there a way to release it? need to take into account
// what if the key is deleted while fill() is executing.
size, err := fill(key)
s.set0(key, size)
return size, err
}
// Set caches a size to use for the given key.
// Use sizeDeleted to mark the key as missing.
func (s *sizecache) Set(key string, size int64) {
s.m.Lock()
s.set0(key, size)
s.m.Unlock()
}
// set0 is just like set but assumes caller already has a lock on s.m
func (s *sizecache) set0(key string, size int64) {
ttl := defaultHitTTL
switch {
case size < 0:
ttl = defaultMissTTL
case size == 0:
ttl = 0
}
s.cache[key] = head{expire: time.Now().Add(ttl), size: size}
}
// age will age all the cache entries, and remove the ones that have
// become too old. It holds m the entire time.
func (s *sizecache) age() {
s.m.Lock()
defer s.m.Unlock()
now := time.Now()
s.sweeptime = now.Add(time.Hour) // next sweep in an hour
for k, v := range s.cache {
if now.After(v.expire) {
delete(s.cache, k) // remove aged entries
}
}
} | store/cache.go | 0.586641 | 0.417984 | cache.go | starcoder |
package hibe
import (
"crypto/rand"
"io"
"math/big"
"vuvuzela.io/crypto/bn256"
)
// Params represents the system parameters for a hierarchy.
type Params struct {
G *bn256.G2
G1 *bn256.G2
G2 *bn256.G1
G3 *bn256.G1
H []*bn256.G1
// Some cached state
Pairing *bn256.GT
}
// MasterKey represents the key for a hierarchy that can create a key for any
// element.
type MasterKey *bn256.G1
// MaximumDepth returns the maximum depth of the hierarchy. This was specified
// via the "l" argument when Setup was called.
func (params *Params) MaximumDepth() int {
return len(params.H)
}
// PrivateKey represents a key for an ID in a hierarchy that can decrypt
// messages encrypted with that ID and issue keys for children of that ID in
// the hierarchy.
type PrivateKey struct {
A0 *bn256.G1
A1 *bn256.G2
B []*bn256.G1
}
// Ciphertext represents an encrypted message.
type Ciphertext struct {
A *bn256.GT
B *bn256.G2
C *bn256.G1
}
// DepthLeft returns the maximum depth of descendants in the hierarchy whose
// keys can be generated from this one.
func (privkey *PrivateKey) DepthLeft() int {
return len(privkey.B)
}
// Setup generates the system parameters, (hich may be made visible to an
// adversary. The parameter "l" is the maximum depth that the hierarchy will
// support.
func Setup(random io.Reader, l int) (*Params, MasterKey, error) {
params := &Params{}
var err error
// The algorithm technically needs g to be a generator of G, but since G is
// isomorphic to Zp, any element in G is technically a generator. So, we
// just choose a random element.
_, params.G, err = bn256.RandomG2(random)
if err != nil {
return nil, nil, err
}
// Choose a random alpha in Zp.
alpha, err := rand.Int(random, bn256.Order)
if err != nil {
return nil, nil, err
}
// Choose g1 = g ^ alpha.
params.G1 = new(bn256.G2).ScalarMult(params.G, alpha)
// Randomly choose g2 and g3.
_, params.G2, err = bn256.RandomG1(random)
if err != nil {
return nil, nil, err
}
_, params.G3, err = bn256.RandomG1(random)
if err != nil {
return nil, nil, err
}
// Randomly choose h1 ... hl.
params.H = make([]*bn256.G1, l, l)
for i := range params.H {
_, params.H[i], err = bn256.RandomG1(random)
if err != nil {
return nil, nil, err
}
}
// Compute the master key as g2 ^ alpha.
master := new(bn256.G1).ScalarMult(params.G2, alpha)
return params, master, nil
}
// KeyGenFromMaster generates a key for an ID using the master key.
func KeyGenFromMaster(random io.Reader, params *Params, master MasterKey, id []*big.Int) (*PrivateKey, error) {
key := &PrivateKey{}
k := len(id)
l := len(params.H)
if k > l {
panic("Cannot generate key at greater than maximum depth.")
}
// Randomly choose r in Zp.
r, err := rand.Int(random, bn256.Order)
if err != nil {
return nil, err
}
product := new(bn256.G1).Set(params.G3)
for i := 0; i != k; i++ {
h := new(bn256.G1).ScalarMult(params.H[i], id[i])
product.Add(product, h)
}
product.ScalarMult(product, r)
key.A0 = new(bn256.G1).Add(master, product)
key.A1 = new(bn256.G2).ScalarMult(params.G, r)
key.B = make([]*bn256.G1, l-k)
for j := 0; j != l-k; j++ {
key.B[j] = new(bn256.G1).ScalarMult(params.H[k+j], r)
}
return key, nil
}
// KeyGenFromParent generates a key for an ID using the private key of the
// parent of ID in the hierarchy. Using a different parent will result in
// undefined behavior.
func KeyGenFromParent(random io.Reader, params *Params, parent *PrivateKey, id []*big.Int) (*PrivateKey, error) {
key := &PrivateKey{}
k := len(id)
l := len(params.H)
if k > l {
panic("Cannot generate key at greater than maximum depth")
}
if parent.DepthLeft() != l-k+1 {
panic("Trying to generate key at depth that is not the child of the provided parent")
}
// Randomly choose t in Zp
t, err := rand.Int(random, bn256.Order)
if err != nil {
return nil, err
}
product := new(bn256.G1).Set(params.G3)
for i := 0; i != k; i++ {
h := new(bn256.G1).ScalarMult(params.H[i], id[i])
product.Add(product, h)
}
product.ScalarMult(product, t)
bpower := new(bn256.G1).ScalarMult(parent.B[0], id[k-1])
key.A0 = new(bn256.G1).Add(parent.A0, bpower)
key.A0.Add(key.A0, product)
key.A1 = new(bn256.G2).ScalarMult(params.G, t)
key.A1.Add(parent.A1, key.A1)
key.B = make([]*bn256.G1, l-k)
for j := 0; j != l-k; j++ {
key.B[j] = new(bn256.G1).ScalarMult(params.H[k+j], t)
key.B[j].Add(parent.B[j+1], key.B[j])
}
return key, nil
}
// Precache forces "cached params" to be computed. Normally, they are computed
// on the fly, but that is not thread-safe. If you plan to call functions
// (especially Encrypt) multiple times concurrently, you should call this first,
// to eliminate race conditions.
func (params *Params) Precache() {
if params.Pairing == nil {
params.Pairing = bn256.Pair(params.G2, params.G1)
}
}
// Encrypt converts the provided message to ciphertext, using the provided ID
// as the public key.
func Encrypt(random io.Reader, params *Params, id []*big.Int, message *bn256.GT) (*Ciphertext, error) {
ciphertext := &Ciphertext{}
k := len(id)
// Randomly choose s in Zp
s, err := rand.Int(random, bn256.Order)
if err != nil {
return nil, err
}
if params.Pairing == nil {
params.Pairing = bn256.Pair(params.G2, params.G1)
}
ciphertext.A = new(bn256.GT)
ciphertext.A.ScalarMult(params.Pairing, s)
ciphertext.A.Add(ciphertext.A, message)
ciphertext.B = new(bn256.G2).ScalarMult(params.G, s)
ciphertext.C = new(bn256.G1).Set(params.G3)
for i := 0; i != k; i++ {
h := new(bn256.G1).ScalarMult(params.H[i], id[i])
ciphertext.C.Add(ciphertext.C, h)
}
ciphertext.C.ScalarMult(ciphertext.C, s)
return ciphertext, nil
}
// Decrypt recovers the original message from the provided ciphertext, using
// the provided private key.
func Decrypt(key *PrivateKey, ciphertext *Ciphertext) *bn256.GT {
plaintext := bn256.Pair(ciphertext.C, key.A1)
invdenominator := new(bn256.GT).Neg(bn256.Pair(key.A0, ciphertext.B))
plaintext.Add(plaintext, invdenominator)
plaintext.Add(ciphertext.A, plaintext)
return plaintext
} | core.go | 0.810404 | 0.486697 | core.go | starcoder |
package utility
import (
"reflect"
"strconv"
"strings"
"time"
)
type ReflectHelper struct {
mTargetValue reflect.Value
mTargetInterface interface{}
}
func NewReflectHelper(targetInterface interface{}) *ReflectHelper {
var ret ReflectHelper
ret.mTargetValue = reflect.Indirect(reflect.ValueOf(targetInterface))
ret.mTargetInterface = targetInterface
return &ret
}
func (this *ReflectHelper) NumField() int {
return this.mTargetValue.NumField()
}
func (this *ReflectHelper) InterfaceName() string {
return reflect.TypeOf(this.mTargetInterface).Name()
}
func (this *ReflectHelper) FieldName(index int) string {
return this.mTargetValue.Type().Field(index).Name
}
func (this *ReflectHelper) FieldIndex(name string) int {
ret := -1
for i := 0; i < this.mTargetValue.NumField(); i++ {
if this.mTargetValue.Type().Field(i).Name == name {
ret = i
break
}
}
return ret
}
func (this *ReflectHelper) Tag(index int) reflect.StructTag {
if reflect.TypeOf(this.mTargetInterface).Kind() == reflect.Ptr {
return reflect.TypeOf(this.mTargetInterface).Elem().Field(index).Tag
} else {
return reflect.TypeOf(this.mTargetValue).Field(index).Tag
}
}
func (this *ReflectHelper) BoolValue(index int) bool {
return this.mTargetValue.Field(index).Bool()
}
func (this *ReflectHelper) StringValue(index int) string {
return this.mTargetValue.Field(index).String()
}
func (this *ReflectHelper) String(index int) string {
var ret string
var value reflect.Value = this.mTargetValue.Field(index)
if this.IsBool(index) {
ret = strconv.FormatBool(value.Bool())
} else if this.IsInt32(index) || this.IsInt64(index) {
ret = strconv.FormatInt(value.Int(), 10)
} else if this.IsUint32(index) || this.IsUint64(index) {
ret = strconv.FormatUint(value.Uint(), 10)
} else if this.IsFloat32(index) {
ret = strconv.FormatFloat(value.Float(), 'e', -1, 32)
} else if this.IsFloat64(index) {
ret = strconv.FormatFloat(value.Float(), 'e', -1, 64)
}
return ret
}
func (this *ReflectHelper) IntValue(index int) int64 {
return this.mTargetValue.Field(index).Int()
}
func (this *ReflectHelper) UintValue(index int) uint64 {
return this.mTargetValue.Field(index).Uint()
}
func (this *ReflectHelper) FloatValue(index int) float64 {
return this.mTargetValue.Field(index).Float()
}
func (this *ReflectHelper) TimeValue(index int) time.Time {
fieldInf := this.mTargetValue.Field(index).Interface()
ret, assertionOK := fieldInf.(time.Time)
if !assertionOK {
LogfE("fail to assertion: %v -> time.Time", fieldInf)
}
return ret
}
func (this *ReflectHelper) ValueKind(index int) reflect.Kind {
return this.mTargetValue.Field(index).Kind()
}
func (this *ReflectHelper) IsBool(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Bool
}
func (this *ReflectHelper) IsString(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.String
}
func (this *ReflectHelper) IsInt8(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Int8
}
func (this *ReflectHelper) IsInt16(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Int16
}
func (this *ReflectHelper) IsInt32(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Int32
}
func (this *ReflectHelper) IsInt64(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Int64
}
func (this *ReflectHelper) IsUint8(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Uint8
}
func (this *ReflectHelper) IsUint16(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Uint16
}
func (this *ReflectHelper) IsUint32(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Uint32
}
func (this *ReflectHelper) IsUint64(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Uint64
}
func (this *ReflectHelper) IsFloat32(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Float32
}
func (this *ReflectHelper) IsFloat64(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Float64
}
func (this *ReflectHelper) IsFloat(index int) bool {
return this.mTargetValue.Field(index).Kind() == reflect.Float32 || this.mTargetValue.Field(index).Kind() == reflect.Float64
}
func (this *ReflectHelper) IsInt(index int) bool {
ret := false
switch this.mTargetValue.Field(index).Kind() {
case reflect.Int:
fallthrough
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
ret = true
break
}
return ret
}
func (this *ReflectHelper) IsUint(index int) bool {
ret := false
switch this.mTargetValue.Field(index).Kind() {
case reflect.Uint:
fallthrough
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
ret = true
break
}
return ret
}
func (this *ReflectHelper) IsIntUint(index int) bool {
return this.IsInt(index) || this.IsUint(index)
}
func (this *ReflectHelper) IsNumber(index int) bool {
return this.IsInt(index) || this.IsUint(index) || this.IsFloat(index)
}
func (this *ReflectHelper) IsTime(index int) bool {
ret := false
if this.mTargetValue.Field(index).Kind() == reflect.Struct {
_, ret = this.mTargetValue.Field(index).Interface().(time.Time)
}
return ret
}
func (this *ReflectHelper) SetByName(name string, value interface{}) bool {
var ret bool = false
var tempValue reflect.Value = this.mTargetValue.FieldByName(name)
if tempValue.Kind() == reflect.ValueOf(value).Kind() {
tempValue.Set(reflect.ValueOf(value))
ret = true
}
return ret
}
func (this *ReflectHelper) SetByIndex(index int, valueInf interface{}) bool {
var ret bool = false
var tempValue reflect.Value = this.mTargetValue.Field(index).Addr().Elem()
if tempValue.CanSet() {
v := reflect.ValueOf(valueInf)
if v.Kind() == reflect.Ptr {
v = reflect.Indirect(v)
}
if tempValue.Kind() == v.Kind() {
tempValue.Set(v)
ret = true
}
}
return ret
}
func (this *ReflectHelper) GetByName(name string) interface{} {
var ret interface{} = nil
tempValue := this.mTargetValue.FieldByName(name)
if tempValue.IsValid() {
ret = tempValue.Interface()
}
return ret
}
func (this *ReflectHelper) GetByTagName(key string, name string) interface{} {
var ret interface{} = nil
for i := 0; i < this.NumField(); i++ {
tagData := this.Tag(i)
if tempName, exist := tagData.Lookup(key); exist {
if strings.Compare(name, tempName) == 0 {
ret = this.GetByIndex(i)
break
}
}
}
return ret
}
func (this *ReflectHelper) GetByIndex(index int) interface{} {
return this.mTargetValue.Field(index).Interface()
}
func (this *ReflectHelper) GetValueByIndex(index int) reflect.Value {
return this.mTargetValue.Field(index)
}
func (this *ReflectHelper) GetPtrByIndex(index int) reflect.Value {
return this.mTargetValue.Field(index).Addr().Elem()
}
func (this *ReflectHelper) GetAddrByIndex(index int) reflect.Value {
return this.mTargetValue.Field(index).Addr()
}
func (this *ReflectHelper) Call(methodName string, values []reflect.Value) []reflect.Value {
return reflect.ValueOf(this.mTargetInterface).MethodByName(methodName).Call(values)
}
func (this *ReflectHelper) CanSet(name string, value interface{}) bool {
var ret bool = false
var tempValue reflect.Value = this.mTargetValue.FieldByName(name)
if tempValue.CanSet() && (tempValue.Type() == reflect.TypeOf(value)) {
ret = true
}
return ret
} | ReflectHelper.go | 0.588061 | 0.479382 | ReflectHelper.go | starcoder |
package gunstructured
import (
"fmt"
"reflect"
"github.com/totherme/unstructured"
)
// DataTypeMatcher is a gomega matcher which tests if a given value represents
// json data of a given type.
type DataTypeMatcher struct {
typ string
}
// BeAnObject returns a gomega matcher which tests if a given value represents
// a json object.
func BeAnObject() DataTypeMatcher {
return DataTypeMatcher{
typ: unstructured.DataOb,
}
}
// BeAnObject returns a gomega matcher which tests if a given value represents
// a json string.
func BeAString() DataTypeMatcher {
return DataTypeMatcher{
typ: unstructured.DataString,
}
}
// BeAList returns a gomega matcher which tests if a given value represents
// a json list.
func BeAList() DataTypeMatcher {
return DataTypeMatcher{
typ: unstructured.DataList,
}
}
// BeANum returns a gomega matcher which tests if a given value represents
// a json num.
func BeANum() DataTypeMatcher {
return DataTypeMatcher{
typ: unstructured.DataNum,
}
}
// BeABool returns a gomega matcher which tests if a given value represents
// a json bool.
func BeABool() DataTypeMatcher {
return DataTypeMatcher{
typ: unstructured.DataBool,
}
}
// BeNull returns a gomega matcher which tests if a given value represents
// json null.
func BeANull() DataTypeMatcher {
return DataTypeMatcher{
typ: unstructured.DataNull,
}
}
// Match is the gomega function that actually checks if the given value is of
// the appropriate json type.
func (m DataTypeMatcher) Match(actual interface{}) (success bool, err error) {
switch json := actual.(type) {
default:
return false, fmt.Errorf("actual is not a Data -- actually of type %s", reflect.TypeOf(actual))
case unstructured.Data:
return json.IsOfType(m.typ), nil
}
}
// FailureMessage constructs a hopefully-helpful error message in the case that
// the given value is not of the appropriate json type.
func (m DataTypeMatcher) FailureMessage(actual interface{}) (message string) {
if reflect.TypeOf(actual) != reflect.TypeOf(unstructured.Data{}) {
return fmt.Sprintf("expected a Data object -- got a %s", reflect.TypeOf(actual))
}
json := actual.(unstructured.Data)
for _, t := range []string{unstructured.DataBool,
unstructured.DataString,
unstructured.DataNum,
unstructured.DataList,
unstructured.DataNull,
unstructured.DataOb} {
if json.IsOfType(t) {
return fmt.Sprintf("expected a Data %s -- got a Data %s", m.typ, t)
}
}
return fmt.Sprintf("expected a Data %s -- got some other crazy kind of Data", m.typ)
}
// NegatedFailureMessage constructs a hopefully-helpful error message in the
// case that the given value is unexpectedly of the appropriate json type.
func (m DataTypeMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return fmt.Sprintf("got a Data %s, but expected not to", m.typ)
} | gunstructured/unstructured_type_matcher.go | 0.81582 | 0.691673 | unstructured_type_matcher.go | starcoder |
package telemetry
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
)
// Counter tracks how many times something is happening.
type Counter interface {
// Inc increments the counter with the given tags value.
Inc(tagsValue ...string)
// Add adds the given value to the counter with the given tags value.
Add(value float64, tagsValue ...string)
// Delete deletes the value for the counter with the given tags value.
Delete(tagsValue ...string)
// IncWithTags increments the counter with the given tags.
// Even if less convenient, this signature could be used in hot path
// instead of Inc(...string) to avoid escaping the parameters on the heap.
IncWithTags(tags map[string]string)
// AddWithTags adds the given value to the counter with the given tags.
// Even if less convenient, this signature could be used in hot path
// instead of Add(float64, ...string) to avoid escaping the parameters on the heap.
AddWithTags(value float64, tags map[string]string)
// DeleteWithTags deletes the value for the counter with the given tags.
// Even if less convenient, this signature could be used in hot path
// instead of Delete(...string) to avoid escaping the parameters on the heap.
DeleteWithTags(tags map[string]string)
}
// NewCounter creates a Counter with default options for telemetry purpose.
// Current implementation used: Prometheus Counter
func NewCounter(subsystem, name string, tags []string, help string) Counter {
return NewCounterWithOpts(subsystem, name, tags, help, DefaultOptions)
}
// NewCounterWithOpts creates a Counter with the given options for telemetry purpose.
// See NewCounter()
func NewCounterWithOpts(subsystem, name string, tags []string, help string, opts Options) Counter {
// subsystem is optional
if subsystem != "" && !opts.NoDoubleUnderscoreSep {
// Prefix metrics with a _, prometheus will add a second _
// It will create metrics with a custom separator and
// will let us replace it to a dot later in the process.
name = fmt.Sprintf("_%s", name)
}
c := &promCounter{
pc: prometheus.NewCounterVec(
prometheus.CounterOpts{
Subsystem: subsystem,
Name: name,
Help: help,
},
tags,
),
}
telemetryRegistry.MustRegister(c.pc)
return c
} | pkg/telemetry/counter.go | 0.701406 | 0.400955 | counter.go | starcoder |
package painter
import (
"image"
"math"
"fyne.io/fyne/v2/canvas"
"github.com/srwiley/rasterx"
"golang.org/x/image/math/fixed"
)
// DrawCircle rasterizes the given circle object into an image.
// The bounds of the output image will be increased by vectorPad to allow for stroke overflow at the edges.
// The scale function is used to understand how many pixels are required per unit of size.
func DrawCircle(circle *canvas.Circle, vectorPad float32, scale func(float32) float32) *image.RGBA {
radius := float32(math.Min(float64(circle.Size().Width), float64(circle.Size().Height)) / 2)
width := int(scale(circle.Size().Width + vectorPad*2))
height := int(scale(circle.Size().Height + vectorPad*2))
stroke := scale(circle.StrokeWidth)
raw := image.NewRGBA(image.Rect(0, 0, width, height))
scanner := rasterx.NewScannerGV(int(circle.Size().Width), int(circle.Size().Height), raw, raw.Bounds())
if circle.FillColor != nil {
filler := rasterx.NewFiller(width, height, scanner)
filler.SetColor(circle.FillColor)
rasterx.AddCircle(float64(width/2), float64(height/2), float64(scale(radius)), filler)
filler.Draw()
}
dasher := rasterx.NewDasher(width, height, scanner)
dasher.SetColor(circle.StrokeColor)
dasher.SetStroke(fixed.Int26_6(float64(stroke)*64), 0, nil, nil, nil, 0, nil, 0)
rasterx.AddCircle(float64(width/2), float64(height/2), float64(scale(radius)), dasher)
dasher.Draw()
return raw
}
// DrawLine rasterizes the given line object into an image.
// The bounds of the output image will be increased by vectorPad to allow for stroke overflow at the edges.
// The scale function is used to understand how many pixels are required per unit of size.
func DrawLine(line *canvas.Line, vectorPad float32, scale func(float32) float32) *image.RGBA {
col := line.StrokeColor
width := int(scale(line.Size().Width + vectorPad*2))
height := int(scale(line.Size().Height + vectorPad*2))
stroke := scale(line.StrokeWidth)
raw := image.NewRGBA(image.Rect(0, 0, width, height))
scanner := rasterx.NewScannerGV(int(line.Size().Width), int(line.Size().Height), raw, raw.Bounds())
dasher := rasterx.NewDasher(width, height, scanner)
dasher.SetColor(col)
dasher.SetStroke(fixed.Int26_6(float64(stroke)*64), 0, nil, nil, nil, 0, nil, 0)
p1x, p1y := scale(line.Position1.X-line.Position().X+vectorPad), scale(line.Position1.Y-line.Position().Y+vectorPad)
p2x, p2y := scale(line.Position2.X-line.Position().X+vectorPad), scale(line.Position2.Y-line.Position().Y+vectorPad)
dasher.Start(rasterx.ToFixedP(float64(p1x), float64(p1y)))
dasher.Line(rasterx.ToFixedP(float64(p2x), float64(p2y)))
dasher.Stop(true)
dasher.Draw()
return raw
}
// DrawRectangle rasterizes the given rectangle object with stroke border into an image.
// The bounds of the output image will be increased by vectorPad to allow for stroke overflow at the edges.
// The scale function is used to understand how many pixels are required per unit of size.
func DrawRectangle(rect *canvas.Rectangle, vectorPad float32, scale func(float32) float32) *image.RGBA {
width := int(scale(rect.Size().Width + vectorPad*2))
height := int(scale(rect.Size().Height + vectorPad*2))
stroke := scale(rect.StrokeWidth)
raw := image.NewRGBA(image.Rect(0, 0, width, height))
scanner := rasterx.NewScannerGV(int(rect.Size().Width), int(rect.Size().Height), raw, raw.Bounds())
scaledPad := scale(vectorPad)
p1x, p1y := scaledPad, scaledPad
p2x, p2y := scale(rect.Size().Width)+scaledPad, scaledPad
p3x, p3y := scale(rect.Size().Width)+scaledPad, scale(rect.Size().Height)+scaledPad
p4x, p4y := scaledPad, scale(rect.Size().Height)+scaledPad
if rect.FillColor != nil {
filler := rasterx.NewFiller(width, height, scanner)
filler.SetColor(rect.FillColor)
rasterx.AddRect(float64(p1x), float64(p1y), float64(p3x), float64(p3y), 0, filler)
filler.Draw()
}
if rect.StrokeColor != nil && rect.StrokeWidth > 0 {
dasher := rasterx.NewDasher(width, height, scanner)
dasher.SetColor(rect.StrokeColor)
dasher.SetStroke(fixed.Int26_6(float64(stroke)*64), 0, nil, nil, nil, 0, nil, 0)
dasher.Start(rasterx.ToFixedP(float64(p1x), float64(p1y)))
dasher.Line(rasterx.ToFixedP(float64(p2x), float64(p2y)))
dasher.Line(rasterx.ToFixedP(float64(p3x), float64(p3y)))
dasher.Line(rasterx.ToFixedP(float64(p4x), float64(p4y)))
dasher.Stop(true)
dasher.Draw()
}
return raw
} | vendor/fyne.io/fyne/v2/internal/painter/draw.go | 0.792865 | 0.594875 | draw.go | starcoder |
package expression
import (
"bytes"
"github.com/dolthub/go-mysql-server/sql"
)
// CaseBranch is a single branch of a case expression.
type CaseBranch struct {
Cond sql.Expression
Value sql.Expression
}
// Case is an expression that returns the value of one of its branches when a
// condition is met.
type Case struct {
Expr sql.Expression
Branches []CaseBranch
Else sql.Expression
}
// NewCase returns an new Case expression.
func NewCase(expr sql.Expression, branches []CaseBranch, elseExpr sql.Expression) *Case {
return &Case{expr, branches, elseExpr}
}
// From the description of operator typing here:
// https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#operator_case
func combinedCaseBranchType(left, right sql.Type) sql.Type {
if left == sql.Null {
return right
}
if right == sql.Null {
return left
}
if sql.IsTextOnly(left) && sql.IsTextOnly(right) {
return sql.LongText
}
if sql.IsTextBlob(left) && sql.IsTextBlob(right) {
return sql.LongBlob
}
if sql.IsTime(left) && sql.IsTime(right) {
if left == right {
return left
}
return sql.Datetime
}
if sql.IsNumber(left) && sql.IsNumber(right) {
if left == sql.Float64 || right == sql.Float64 {
return sql.Float64
}
if left == sql.Float32 || right == sql.Float32 {
return sql.Float32
}
if sql.IsDecimal(left) || sql.IsDecimal(right) {
return sql.MustCreateDecimalType(65, 10)
}
if left == sql.Uint64 && sql.IsSigned(right) ||
right == sql.Uint64 && sql.IsSigned(left) {
return sql.MustCreateDecimalType(65, 10)
}
if !sql.IsSigned(left) && !sql.IsSigned(right) {
return sql.Uint64
} else {
return sql.Int64
}
}
return sql.LongText
}
// Type implements the sql.Expression interface.
func (c *Case) Type() sql.Type {
curr := sql.Null
for _, b := range c.Branches {
curr = combinedCaseBranchType(curr, b.Value.Type())
}
if c.Else != nil {
curr = combinedCaseBranchType(curr, c.Else.Type())
}
return curr
}
// IsNullable implements the sql.Expression interface.
func (c *Case) IsNullable() bool {
for _, b := range c.Branches {
if b.Value.IsNullable() {
return true
}
}
return c.Else == nil || c.Else.IsNullable()
}
// Resolved implements the sql.Expression interface.
func (c *Case) Resolved() bool {
if (c.Expr != nil && !c.Expr.Resolved()) ||
(c.Else != nil && !c.Else.Resolved()) {
return false
}
for _, b := range c.Branches {
if !b.Cond.Resolved() || !b.Value.Resolved() {
return false
}
}
return true
}
// Children implements the sql.Expression interface.
func (c *Case) Children() []sql.Expression {
var children []sql.Expression
if c.Expr != nil {
children = append(children, c.Expr)
}
for _, b := range c.Branches {
children = append(children, b.Cond, b.Value)
}
if c.Else != nil {
children = append(children, c.Else)
}
return children
}
// Eval implements the sql.Expression interface.
func (c *Case) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
span, ctx := ctx.Span("expression.Case")
defer span.Finish()
var expr interface{}
var err error
if c.Expr != nil {
expr, err = c.Expr.Eval(ctx, row)
if err != nil {
return nil, err
}
}
t := c.Type()
for _, b := range c.Branches {
var cond sql.Expression
if expr != nil {
cond = NewEquals(NewLiteral(expr, c.Expr.Type()), b.Cond)
} else {
cond = b.Cond
}
res, err := sql.EvaluateCondition(ctx, cond, row)
if err != nil {
return nil, err
}
if sql.IsTrue(res) {
bval, err := b.Value.Eval(ctx, row)
if err != nil {
return nil, err
}
return t.Convert(bval)
}
}
if c.Else != nil {
val, err := c.Else.Eval(ctx, row)
if err != nil {
return nil, err
}
return t.Convert(val)
}
return nil, nil
}
// WithChildren implements the Expression interface.
func (c *Case) WithChildren(children ...sql.Expression) (sql.Expression, error) {
var expected = len(c.Branches) * 2
if c.Expr != nil {
expected++
}
if c.Else != nil {
expected++
}
if len(children) != expected {
return nil, sql.ErrInvalidChildrenNumber.New(c, len(children), expected)
}
var expr, elseExpr sql.Expression
if c.Expr != nil {
expr = children[0]
children = children[1:]
}
if c.Else != nil {
elseExpr = children[len(children)-1]
children = children[:len(children)-1]
}
var branches []CaseBranch
for i := 0; i < len(children); i += 2 {
branches = append(branches, CaseBranch{
Cond: children[i],
Value: children[i+1],
})
}
return NewCase(expr, branches, elseExpr), nil
}
func (c *Case) String() string {
var buf bytes.Buffer
buf.WriteString("CASE ")
if c.Expr != nil {
buf.WriteString(c.Expr.String())
}
for _, b := range c.Branches {
buf.WriteString(" WHEN ")
buf.WriteString(b.Cond.String())
buf.WriteString(" THEN ")
buf.WriteString(b.Value.String())
}
if c.Else != nil {
buf.WriteString(" ELSE ")
buf.WriteString(c.Else.String())
}
buf.WriteString(" END")
return buf.String()
}
func (c *Case) DebugString() string {
var buf bytes.Buffer
buf.WriteString("CASE ")
if c.Expr != nil {
buf.WriteString(sql.DebugString(c.Expr))
}
for _, b := range c.Branches {
buf.WriteString(" WHEN ")
buf.WriteString(sql.DebugString(b.Cond))
buf.WriteString(" THEN ")
buf.WriteString(sql.DebugString(b.Value))
}
if c.Else != nil {
buf.WriteString(" ELSE ")
buf.WriteString(sql.DebugString(c.Else))
}
buf.WriteString(" END")
return buf.String()
} | sql/expression/case.go | 0.667906 | 0.453806 | case.go | starcoder |
package histogramvec
import (
"sync"
"github.com/giantswarm/exporterkit/histogram"
"github.com/giantswarm/microerror"
)
type Config struct {
// BucketLimits is the upper limit of each bucket used when creating new internal Histograms.
// See https://godoc.org/github.com/prometheus/client_golang/prometheus#HistogramOpts.
BucketLimits []float64
}
// HistogramVec is a data structure suitable for holding multiple Histograms,
// and then providing the inputs to multiple Prometheus Histograms.
// See https://godoc.org/github.com/prometheus/client_golang/prometheus#MustNewConstHistogram.
type HistogramVec struct {
// bucketLimits is the upper limit of buckets for the Histograms that the HistogramVec manages.
bucketLimits []float64
// histograms is a mapping between labels and the Histograms that the HistogramVec manages.
histograms map[string]*histogram.Histogram
// mutex controls access to the histograms map, to allow for safe concurrent access.
mutex sync.Mutex
}
func New(config Config) (*HistogramVec, error) {
if len(config.BucketLimits) == 0 {
return nil, microerror.Maskf(invalidConfigError, "%T.BucketLimits must not be empty", config)
}
hv := &HistogramVec{
bucketLimits: config.BucketLimits,
histograms: map[string]*histogram.Histogram{},
}
return hv, nil
}
// Add saves an entry to the Histogram with the given label,
// creating it internally if required.
func (hv *HistogramVec) Add(label string, x float64) error {
hv.mutex.Lock()
defer hv.mutex.Unlock()
if _, ok := hv.histograms[label]; !ok {
c := histogram.Config{
BucketLimits: hv.bucketLimits,
}
h, err := histogram.New(c)
if err != nil {
return microerror.Mask(err)
}
hv.histograms[label] = h
}
hv.histograms[label].Add(x)
return nil
}
// Ensure removes any internal Histograms that aren't in the given slice of labels.
// This is useful when a label is no longer being recorded, such as in dynamic systems.
func (hv *HistogramVec) Ensure(labels []string) {
hv.mutex.Lock()
defer hv.mutex.Unlock()
for existingLabel := range hv.histograms {
labelRequested := false
for _, requestedLabel := range labels {
if requestedLabel == existingLabel {
labelRequested = true
}
}
if !labelRequested {
delete(hv.histograms, existingLabel)
}
}
}
// Histograms returns a copy of the currently managed Histograms.
func (hv *HistogramVec) Histograms() map[string]*histogram.Histogram {
hv.mutex.Lock()
defer hv.mutex.Unlock()
histogramsCopy := map[string]*histogram.Histogram{}
for label, histogram := range hv.histograms {
h := *histogram
histogramsCopy[label] = &h
}
return histogramsCopy
} | vendor/github.com/giantswarm/exporterkit/histogramvec/histogramvec.go | 0.797793 | 0.428771 | histogramvec.go | starcoder |
package dataset
import (
"net/url"
"github.com/reearth/reearth-backend/pkg/value"
)
type LatLng = value.LatLng
type LatLngHeight = value.LatLngHeight
type Coordinates = value.Coordinates
type Rect = value.Rect
type Polygon = value.Polygon
type ValueType value.Type
var (
ValueTypeUnknown = ValueType(value.TypeUnknown)
ValueTypeBool = ValueType(value.TypeBool)
ValueTypeNumber = ValueType(value.TypeNumber)
ValueTypeString = ValueType(value.TypeString)
ValueTypeRef = ValueType(value.TypeRef)
ValueTypeURL = ValueType(value.TypeURL)
ValueTypeLatLng = ValueType(value.TypeLatLng)
ValueTypeLatLngHeight = ValueType(value.TypeLatLngHeight)
ValueTypeCoordinates = ValueType(value.TypeCoordinates)
ValueTypeRect = ValueType(value.TypeRect)
TypePolygon = ValueType(value.TypePolygon)
)
func (vt ValueType) Valid() bool {
return value.Type(vt).Default()
}
func (t ValueType) Default() bool {
return value.Type(t).Default()
}
func (t ValueType) ValueFrom(i interface{}) *Value {
vv := value.Type(t).ValueFrom(i, nil)
if vv == nil {
return nil
}
return &Value{v: *vv}
}
func (vt ValueType) MustBeValue(i interface{}) *Value {
if v := vt.ValueFrom(i); v != nil {
return v
}
panic("invalid value")
}
func (vt ValueType) None() *OptionalValue {
return NewOptionalValue(vt, nil)
}
type Value struct {
v value.Value
}
func (v *Value) IsEmpty() bool {
return v == nil || v.v.IsEmpty()
}
func (v *Value) Clone() *Value {
if v == nil {
return nil
}
vv := v.v.Clone()
if vv == nil {
return nil
}
return &Value{v: *vv}
}
func (v *Value) Some() *OptionalValue {
return OptionalValueFrom(v)
}
func (v *Value) Type() ValueType {
if v == nil {
return ValueTypeUnknown
}
return ValueType(v.v.Type())
}
func (v *Value) Value() interface{} {
if v == nil {
return nil
}
return v.v.Value()
}
func (v *Value) Interface() interface{} {
if v == nil {
return nil
}
return v.v.Interface()
}
func (v *Value) Cast(vt ValueType) *Value {
if v == nil {
return nil
}
nv := v.v.Cast(value.Type(vt), nil)
if nv == nil {
return nil
}
return &Value{v: *nv}
}
func (v *Value) ValueBool() *bool {
if v == nil {
return nil
}
vv, ok := v.v.ValueBool()
if ok {
return &vv
}
return nil
}
func (v *Value) ValueNumber() *float64 {
if v == nil {
return nil
}
vv, ok := v.v.ValueNumber()
if ok {
return &vv
}
return nil
}
func (v *Value) ValueString() *string {
if v == nil {
return nil
}
vv, ok := v.v.ValueString()
if ok {
return &vv
}
return nil
}
func (v *Value) ValueRef() *string {
if v == nil {
return nil
}
vv, ok := v.v.ValueRef()
if ok {
return &vv
}
return nil
}
func (v *Value) ValueURL() *url.URL {
if v == nil {
return nil
}
vv, ok := v.v.ValueURL()
if ok {
return vv
}
return nil
}
func (v *Value) ValueLatLng() *LatLng {
if v == nil {
return nil
}
vv, ok := v.v.ValueLatLng()
if ok {
return &vv
}
return nil
}
func (v *Value) ValueLatLngHeight() *LatLngHeight {
if v == nil {
return nil
}
vv, ok := v.v.ValueLatLngHeight()
if ok {
return &vv
}
return nil
}
func (v *Value) ValueCoordinates() *Coordinates {
if v == nil {
return nil
}
vv, ok := v.v.ValueCoordinates()
if ok {
return &vv
}
return nil
}
func (v *Value) ValueRect() *Rect {
if v == nil {
return nil
}
vv, ok := v.v.ValueRect()
if ok {
return &vv
}
return nil
}
func (v *Value) ValuePolygon() *Polygon {
if v == nil {
return nil
}
vv, ok := v.v.ValuePolygon()
if ok {
return &vv
}
return nil
}
func ValueFromStringOrNumber(s string) *Value {
if s == "true" || s == "false" || s == "TRUE" || s == "FALSE" || s == "True" || s == "False" {
return ValueTypeBool.ValueFrom(s)
}
if v := ValueTypeNumber.ValueFrom(s); v != nil {
return v
}
return ValueTypeString.ValueFrom(s)
} | pkg/dataset/value.go | 0.661267 | 0.514339 | value.go | starcoder |
package texture
import (
"github.com/g3n/engine/geometry"
"github.com/g3n/engine/gls"
"github.com/g3n/engine/graphic"
"github.com/g3n/engine/light"
"github.com/g3n/engine/material"
"github.com/g3n/engine/math32"
"github.com/g3n/engine/texture"
"github.com/g3n/engine/util/helper"
"github.com/g3n/g3nd/app"
"math"
"time"
)
func init() {
app.DemoMap["texture.sphere"] = &Texsphere{}
}
type Texsphere struct {
sphere1 *graphic.Mesh
sphere2 *graphic.Mesh
sphere3 *graphic.Mesh
sphere4 *graphic.Mesh
}
// Start is called once at the start of the demo.
func (t *Texsphere) Start(a *app.App) {
// Adds directional front light
dir1 := light.NewDirectional(&math32.Color{1, 1, 1}, 1.0)
dir1.SetPosition(0, 0, 100)
a.Scene().Add(dir1)
// Adds directional top light
dir2 := light.NewDirectional(&math32.Color{1, 1, 1}, 1.0)
dir2.SetPosition(0, 100, 0)
a.Scene().Add(dir2)
// Creates texture 1
texfile := a.DirData() + "/images/checkerboard.jpg"
tex1, err := texture.NewTexture2DFromImage(texfile)
if err != nil {
a.Log().Fatal("Error loading texture: %s", err)
}
tex1.SetWrapS(gls.REPEAT)
tex1.SetWrapT(gls.REPEAT)
tex1.SetRepeat(2, 2)
// Creates sphere 1
geom1 := geometry.NewSphere(1, 32, 32)
mat1 := material.NewStandard(&math32.Color{1, 1, 1})
mat1.AddTexture(tex1)
t.sphere1 = graphic.NewMesh(geom1, mat1)
t.sphere1.SetPosition(-1.1, 1.1, 0)
a.Scene().Add(t.sphere1)
// Creates texture 2
texfile = a.DirData() + "/images/earth_clouds_big.jpg"
tex2, err := texture.NewTexture2DFromImage(texfile)
if err != nil {
a.Log().Fatal("Error loading texture: %s", err)
}
tex2.SetFlipY(false)
// Creates sphere 2
geom2 := geometry.NewSphere(1, 32, 32)
mat2 := material.NewStandard(&math32.Color{1, 1, 1})
mat2.AddTexture(tex2)
t.sphere2 = graphic.NewMesh(geom2, mat2)
t.sphere2.SetPosition(1.1, 1.1, 0)
a.Scene().Add(t.sphere2)
// Creates texture 3
texfile = a.DirData() + "/images/uvgrid.jpg"
tex3, err := texture.NewTexture2DFromImage(texfile)
if err != nil {
a.Log().Fatal("Error loading texture: %s", err)
}
tex3.SetFlipY(false)
// Creates sphere 3
geom3 := geometry.NewSphere(1, 32, 32)
mat3 := material.NewStandard(&math32.Color{1, 1, 1})
mat3.AddTexture(tex3)
t.sphere3 = graphic.NewMesh(geom3, mat3)
t.sphere3.SetPosition(-1.1, -1.1, 0)
a.Scene().Add(t.sphere3)
// Creates texture 4
texfile = a.DirData() + "/images/brick1.jpg"
tex4, err := texture.NewTexture2DFromImage(texfile)
if err != nil {
a.Log().Fatal("Error loading texture: %s", err)
}
// Creates sphere 4
geom4 := geometry.NewSphereSector(1, 32, 32, 0, math.Pi, 0, math.Pi/2)
mat4 := material.NewStandard(&math32.Color{1, 1, 1})
mat4.AddTexture(tex4)
mat4.SetSide(material.SideDouble)
t.sphere4 = graphic.NewMesh(geom4, mat4)
t.sphere4.SetPosition(1.1, -1.1, 0)
a.Scene().Add(t.sphere4)
// Create axes helper
axes := helper.NewAxes(2)
a.Scene().Add(axes)
}
// Update is called every frame.
func (t *Texsphere) Update(a *app.App, deltaTime time.Duration) {
// TODO use deltaTime
t.sphere1.RotateY(0.01)
t.sphere2.RotateY(-0.01)
t.sphere3.RotateY(0.01)
t.sphere4.RotateY(-0.01)
}
// Cleanup is called once at the end of the demo.
func (t *Texsphere) Cleanup(a *app.App) {} | demos/texture/sphere.go | 0.639286 | 0.426262 | sphere.go | starcoder |
package duplo
import (
"github.com/nfnt/resize"
"image"
"math"
"math/rand"
"vincit.fi/image-sorter/duplo/haar"
)
// Hash represents the visual hash of an image.
type Hash struct {
haar.Matrix
// Thresholds contains the coefficient threholds. If you discard all
// coefficients with abs(coef) < threshold, you end up with TopCoefs
// coefficients.
Thresholds haar.Coef
// Ratio is image width / image height or 0 if height is 0.
Ratio float64
}
// CreateHash calculates and returns the visual hash of the provided image as
// well as a resized version of it (ImageScale x ImageScale) which may be
// ignored if not needed anymore.
func CreateHash(img image.Image) (Hash, image.Image) {
// Determine image ratio.
bounds := img.Bounds()
width := bounds.Max.X - bounds.Min.X
height := bounds.Max.Y - bounds.Min.Y
var ratio float64
if height > 0 {
ratio = float64(width) / float64(height)
}
// Resize the image for the Wavelet transform.
scaled := resize.Resize(ImageScale, ImageScale, img, resize.Bicubic)
// Then perform a 2D Haar Wavelet transform.
matrix := haar.Transform(scaled)
// Find the kth largest coefficients for each colour channel.
thresholds := coefThresholds(matrix.Coefs, TopCoefs)
return Hash{haar.Matrix{
Coefs: matrix.Coefs,
Width: ImageScale,
Height: ImageScale,
}, thresholds, ratio}, scaled
}
// coefThreshold returns, for the given coefficients, the kth largest absolute
// value. Only the nth element in each Coef is considered. If you discard all
// values v with abs(v) < threshold, you will end up with k values.
func coefThreshold(coefs []haar.Coef, k int, n int) float64 {
// It's the QuickSelect algorithm.
randomIndex := rand.Intn(len(coefs))
pivot := math.Abs(coefs[randomIndex][n])
leftCoefs := make([]haar.Coef, 0, len(coefs))
rightCoefs := make([]haar.Coef, 0, len(coefs))
for _, coef := range coefs {
if math.Abs(coef[n]) > pivot {
leftCoefs = append(leftCoefs, coef)
} else if math.Abs(coef[n]) < pivot {
rightCoefs = append(rightCoefs, coef)
}
}
if k <= len(leftCoefs) {
return coefThreshold(leftCoefs, k, n)
} else if k > len(coefs)-len(rightCoefs) {
return coefThreshold(rightCoefs, k-(len(coefs)-len(rightCoefs)), n)
} else {
return pivot
}
}
// coefThreshold returns, for the given coefficients, the kth largest absolute
// values per colour channel. If you discard all values v with
// abs(v) < threshold, you will end up with k values.
func coefThresholds(coefs []haar.Coef, k int) haar.Coef {
// No data, no thresholds.
if len(coefs) == 0 {
return haar.Coef{}
}
// Select thresholds.
var thresholds haar.Coef
for index := range thresholds {
thresholds[index] = coefThreshold(coefs, k, index)
}
return thresholds
} | duplo/hash.go | 0.829285 | 0.418519 | hash.go | starcoder |
package blockchain
import "fmt"
// BalanceSheet represents the data representation to maintain address balances.
type BalanceSheet map[string]uint
// newBalanceSheet constructs a new balance sheet for use.
func newBalanceSheet() BalanceSheet {
return make(BalanceSheet)
}
// replace updates the balance sheet for a given address.
func (bs BalanceSheet) replace(address string, value uint) {
bs[address] = value
}
// remove deletes the address from the balance sheet
func (bs BalanceSheet) remove(address string) {
delete(bs, address)
}
// =============================================================================
// copyBalanceSheet makes a copy of the specified balance sheet.
func copyBalanceSheet(org BalanceSheet) BalanceSheet {
balanceSheet := newBalanceSheet()
for acct, value := range org {
balanceSheet.replace(acct, value)
}
return balanceSheet
}
// applyMiningRewardToBalance gives the beneficiary address a reward for mining a block.
func applyMiningRewardToBalance(balanceSheet BalanceSheet, beneficiary string, reward uint) {
balanceSheet[beneficiary] += reward
}
// applyMiningFeeToBalance gives the beneficiary address a fee for mining the block.
func applyMiningFeeToBalance(balanceSheet BalanceSheet, beneficiary string, tx BlockTx) {
from, err := tx.FromAddress()
if err != nil {
return
}
fee := tx.Gas + tx.Tip
balanceSheet[beneficiary] += fee
balanceSheet[from] -= fee
}
// applyTransactionToBalance performs the business logic for applying a
// transaction to the balance sheet.
func applyTransactionToBalance(balanceSheet BalanceSheet, tx BlockTx) error {
if string(tx.Data) == TxDataReward {
balanceSheet[tx.To] += tx.Value
return nil
}
// Capture the address of the account that signed this transaction.
from, err := tx.FromAddress()
if err != nil {
return fmt.Errorf("invalid signature, %s", err)
}
if from == tx.To {
return fmt.Errorf("invalid transaction, do you mean to give a reward, from %s, to %s", from, tx.To)
}
if tx.Value > balanceSheet[from] {
return fmt.Errorf("%s has an insufficient balance", from)
}
balanceSheet[from] -= tx.Value
balanceSheet[tx.To] += tx.Value
if tx.Tip > 0 {
balanceSheet[from] -= tx.Tip
}
return nil
} | foundation/blockchain/balances.go | 0.850282 | 0.42668 | balances.go | starcoder |
package metric
type SparseCategoricalAccuracy struct {
Name string
Confidence float64
Average bool
Precision int
total float64
count float64
}
func (m *SparseCategoricalAccuracy) Init() {
if m.Precision == 0 {
m.Precision = 4
}
}
func (m *SparseCategoricalAccuracy) Reset() {
m.total = 0
m.count = 0
}
func (m *SparseCategoricalAccuracy) GetName() string {
return m.Name
}
func (m *SparseCategoricalAccuracy) Compute(yTrue interface{}, yPred interface{}) Value {
yPredValue := yPred.([][]float32)
yTrueValue := yTrue.([][]int32)
correct := 0
for i, pred := range yPredValue {
truth := yTrueValue[i][0]
if float64(pred[int(truth)]) >= m.Confidence {
correct++
}
}
if !m.Average {
return Value{
Name: m.Name,
Value: float64(correct) / float64(len(yTrueValue)),
Precision: m.Precision,
}
}
m.total += float64(correct) / float64(len(yTrueValue))
m.count++
return Value{
Name: m.Name,
Value: m.total / m.count,
Precision: m.Precision,
}
}
func (m *SparseCategoricalAccuracy) ComputeFinal() Value {
return Value{
Name: m.Name,
Value: m.total / m.count,
Precision: m.Precision,
}
}
type BinaryAccuracy struct {
Name string
Confidence float64
Average bool
Precision int
total float64
count float64
}
func (m *BinaryAccuracy) Init() {
if m.Precision == 0 {
m.Precision = 4
}
}
func (m *BinaryAccuracy) Reset() {
m.total = 0
m.count = 0
}
func (m *BinaryAccuracy) GetName() string {
return m.Name
}
func (m *BinaryAccuracy) Compute(yTrue interface{}, yPred interface{}) Value {
yPredValue := yPred.([][]float32)
yTrueValue := yTrue.([][]int32)
correct := 0
for i, pred := range yPredValue {
if float64(pred[0]) >= m.Confidence && yTrueValue[i][0] == 1 {
correct++
} else if float64(pred[0]) < m.Confidence && yTrueValue[i][0] == 0 {
correct++
}
}
if !m.Average {
return Value{
Name: m.Name,
Value: float64(correct) / float64(len(yTrueValue)),
Precision: m.Precision,
}
}
m.total += float64(correct) / float64(len(yTrueValue))
m.count++
return Value{
Name: m.Name,
Value: m.total / m.count,
Precision: m.Precision,
}
}
func (m *BinaryAccuracy) ComputeFinal() Value {
return Value{
Name: m.Name,
Value: m.total / m.count,
Precision: m.Precision,
}
} | metric/accuracy.go | 0.843831 | 0.409339 | accuracy.go | starcoder |
package main
import (
"fmt"
"github.com/sajari/regression"
"gonum.org/v1/gonum/floats"
)
type Model struct {
paths []string
observations []observation
regression *regression.Regression
hasTrained bool
}
type Coefficient struct {
Path string
Coefficient float64
}
type observation struct {
// responseTime is the observed response time in seconds.
responseTime float64
// pathProbabilities is the order of {@link Model.Paths} given.
pathProbabilities []float64
}
func NewPathProbabilitiesModel(paths []string) *Model {
r := new(regression.Regression)
r.SetObserved("Response time, s")
for i, path := range paths {
r.SetVar(i, path)
}
return &Model{
paths: paths,
observations: []observation{},
regression: r,
hasTrained: false,
}
}
func (m *Model) AddObservation(responseTime float64, pathProbabilities []float64) {
if m.hasTrained {
panic("developer error: called AddObservation after training complete")
}
m.observations = append(m.observations, observation{
responseTime: responseTime,
pathProbabilities: pathProbabilities,
})
}
func (m *Model) Train() error {
if m.hasTrained {
panic("developer error: called Train after training complete")
}
var dataPoints regression.DataPoints
for _, obs := range m.observations {
dataPoints = append(dataPoints, regression.DataPoint(obs.responseTime, obs.pathProbabilities))
}
m.regression.Train(dataPoints...)
err := m.regression.Run()
if err != nil {
return fmt.Errorf("train() failed on regression training with error: %w", m.regression.Run())
}
m.hasTrained = true
return nil
}
func (m *Model) Coefficients() []Coefficient {
if !m.hasTrained {
panic("developer error: called Coefficients before training complete")
}
var coefficients []Coefficient
for i, path := range m.paths {
coefficients = append(coefficients, Coefficient{
path,
m.regression.Coeff(i + 1),
})
}
return coefficients
}
// NormalisedCoefficients returns a set of coefficients which have been
// normalised between 0 and 1.
func (m *Model) NormalisedCoefficients() []Coefficient {
if !m.hasTrained {
panic("developer error: called NormalisedCoefficients before training complete")
}
normalised := m.Coefficients()
// https://stats.stackexchange.com/a/70807
var originalCoeffs []float64
for _, coeff := range normalised {
originalCoeffs = append(originalCoeffs, coeff.Coefficient)
}
min := floats.Min(originalCoeffs)
max := floats.Max(originalCoeffs)
coeffsRange := max - min
for i := range normalised {
normalised[i].Coefficient = (normalised[i].Coefficient - min) / coeffsRange
}
return normalised
}
// ComplementaryNormalisedCoefficients performs (1 - coeff) on each of the
// normalised coefficients, to represent
func (m *Model) ComplementaryNormalisedCoefficients() []Coefficient {
normalised := m.NormalisedCoefficients()
for i := range normalised {
normalised[i].Coefficient = 1 - normalised[i].Coefficient
}
return normalised
}
func (m *Model) Formula() string {
if !m.hasTrained {
panic("developer error: called Formula before training complete")
}
return m.regression.Formula
} | model.go | 0.807612 | 0.46478 | model.go | starcoder |
package bloom
import (
"math"
"github.com/markuskont/probstruct/pkg/hasher"
"github.com/markuskont/probstruct/pkg/util"
)
// Filter is bitvector of length m elements
// items will be hashed to integers with k non-cryptographic functions
// boolean values in corresponding positions will be flipped
type Filter struct {
m uint64
k uint64
bits []bool
hsh hasher.Algorithm
}
// InitFilterWithEstimate instantiates a new bloom filter with user defined estimate parameters
// hash = hashing method to use ( <= 1 for murmur, 2 for fnv)
// n = number of elements in data set
// p = acceptable false positive 0 < p < 1 (no checks atm)
func NewFilterWithEstimate(n uint, p float64, h hasher.Algorithm) (b *Filter, err error) {
m, k := estimateBloomSize(n, p)
if b, err = NewFilter(m, k, h); err != nil {
return nil, err
}
return b, nil
}
// InitFilter instantiates a new bloom filter with static length and hash function number
func NewFilter(m, k uint64, h hasher.Algorithm) (b *Filter, err error) {
b = &Filter{
m: m,
k: k,
hsh: h,
}
b.bits = make([]bool, b.m)
return b, nil
}
// m = estimated size of bloom filter array
// m = -1 * float64(n) * math.Log(p) / math.Pow(math.Log(2), 2)
// k = num of needed hash functions
func estimateBloomSize(n uint, p float64) (m, k uint64) {
size := math.Ceil(-1 * float64(n) * math.Log(p) / math.Pow(math.Log(2.0), 2.0))
k = uint64(util.RoundFloat64(math.Log(2.0) * size / float64(n)))
m = uint64(size)
return
}
// Add method adds new element to bloom filter
func (b *Filter) Add(data ...[]byte) *Filter {
if data == nil || len(data) == 0 {
return b
}
locations := b.hsh.GetBaseHash(data...).Transform(b.m, b.k)
if len(locations) == 0 {
return b
}
for _, elem := range locations {
b.bits[elem] = true
}
return b
}
// AddString is a helper to require need for type casting
func (b *Filter) AddString(data string) *Filter {
return b.Add([]byte(data))
}
// AddStringSlice is a helper like AddString but assumes arbitrary number of strings
func (b *Filter) AddStringSlice(data ...string) *Filter {
if data == nil || len(data) == 0 {
return b
}
casted := make([][]byte, len(data))
for i, v := range data {
casted[i] = []byte(v)
}
return b.Add(casted...)
}
// Query returns the presence boolean of item from filter
// one missing bit is enough to verify non-existence
func (b Filter) Query(data []byte) bool {
if data == nil || len(data) == 0 {
return false
}
locations := b.hsh.GetBaseHash(data).Transform(b.m, b.k)
if len(locations) == 0 {
return false
}
for _, elem := range locations {
if b.bits[elem] == false {
return false
}
}
return true
}
// QueryString is a helper to avoid excessive typecasting
func (b Filter) QueryString(data string) bool {
return b.Query([]byte(data))
}
// QuerySlice is a wrapper for getting existence of multiple items with one go
func (b Filter) QuerySlice(data ...[]byte) []bool {
if data == nil || len(data) == 0 {
return []bool{}
}
res := make([]bool, len(data))
for i, v := range data {
res[i] = b.Query(v)
}
return res
}
// VecLen is a helper to get length of bloom, mostly for testing
func (b Filter) VecLen() uint64 {
return b.m
}
// HashNo is a helper to get number of hash functions
func (b Filter) HashNo() uint64 {
return b.k
} | pkg/bloom/bloom.go | 0.738952 | 0.534248 | bloom.go | starcoder |
package graph
import (
i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization"
)
// OutlookGeoCoordinates
type OutlookGeoCoordinates struct {
// The accuracy of the latitude and longitude. As an example, the accuracy can be measured in meters, such as the latitude and longitude are accurate to within 50 meters.
accuracy *float64;
// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
additionalData map[string]interface{};
// The altitude of the location.
altitude *float64;
// The accuracy of the altitude.
altitudeAccuracy *float64;
// The latitude of the location.
latitude *float64;
// The longitude of the location.
longitude *float64;
}
// NewOutlookGeoCoordinates instantiates a new outlookGeoCoordinates and sets the default values.
func NewOutlookGeoCoordinates()(*OutlookGeoCoordinates) {
m := &OutlookGeoCoordinates{
}
m.SetAdditionalData(make(map[string]interface{}));
return m
}
// GetAccuracy gets the accuracy property value. The accuracy of the latitude and longitude. As an example, the accuracy can be measured in meters, such as the latitude and longitude are accurate to within 50 meters.
func (m *OutlookGeoCoordinates) GetAccuracy()(*float64) {
if m == nil {
return nil
} else {
return m.accuracy
}
}
// GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *OutlookGeoCoordinates) GetAdditionalData()(map[string]interface{}) {
if m == nil {
return nil
} else {
return m.additionalData
}
}
// GetAltitude gets the altitude property value. The altitude of the location.
func (m *OutlookGeoCoordinates) GetAltitude()(*float64) {
if m == nil {
return nil
} else {
return m.altitude
}
}
// GetAltitudeAccuracy gets the altitudeAccuracy property value. The accuracy of the altitude.
func (m *OutlookGeoCoordinates) GetAltitudeAccuracy()(*float64) {
if m == nil {
return nil
} else {
return m.altitudeAccuracy
}
}
// GetLatitude gets the latitude property value. The latitude of the location.
func (m *OutlookGeoCoordinates) GetLatitude()(*float64) {
if m == nil {
return nil
} else {
return m.latitude
}
}
// GetLongitude gets the longitude property value. The longitude of the location.
func (m *OutlookGeoCoordinates) GetLongitude()(*float64) {
if m == nil {
return nil
} else {
return m.longitude
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *OutlookGeoCoordinates) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) {
res := make(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error))
res["accuracy"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetAccuracy(val)
}
return nil
}
res["altitude"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetAltitude(val)
}
return nil
}
res["altitudeAccuracy"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetAltitudeAccuracy(val)
}
return nil
}
res["latitude"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetLatitude(val)
}
return nil
}
res["longitude"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetLongitude(val)
}
return nil
}
return res
}
func (m *OutlookGeoCoordinates) IsNil()(bool) {
return m == nil
}
// Serialize serializes information the current object
func (m *OutlookGeoCoordinates) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) {
{
err := writer.WriteFloat64Value("accuracy", m.GetAccuracy())
if err != nil {
return err
}
}
{
err := writer.WriteFloat64Value("altitude", m.GetAltitude())
if err != nil {
return err
}
}
{
err := writer.WriteFloat64Value("altitudeAccuracy", m.GetAltitudeAccuracy())
if err != nil {
return err
}
}
{
err := writer.WriteFloat64Value("latitude", m.GetLatitude())
if err != nil {
return err
}
}
{
err := writer.WriteFloat64Value("longitude", m.GetLongitude())
if err != nil {
return err
}
}
{
err := writer.WriteAdditionalData(m.GetAdditionalData())
if err != nil {
return err
}
}
return nil
}
// SetAccuracy sets the accuracy property value. The accuracy of the latitude and longitude. As an example, the accuracy can be measured in meters, such as the latitude and longitude are accurate to within 50 meters.
func (m *OutlookGeoCoordinates) SetAccuracy(value *float64)() {
if m != nil {
m.accuracy = value
}
}
// SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *OutlookGeoCoordinates) SetAdditionalData(value map[string]interface{})() {
if m != nil {
m.additionalData = value
}
}
// SetAltitude sets the altitude property value. The altitude of the location.
func (m *OutlookGeoCoordinates) SetAltitude(value *float64)() {
if m != nil {
m.altitude = value
}
}
// SetAltitudeAccuracy sets the altitudeAccuracy property value. The accuracy of the altitude.
func (m *OutlookGeoCoordinates) SetAltitudeAccuracy(value *float64)() {
if m != nil {
m.altitudeAccuracy = value
}
}
// SetLatitude sets the latitude property value. The latitude of the location.
func (m *OutlookGeoCoordinates) SetLatitude(value *float64)() {
if m != nil {
m.latitude = value
}
}
// SetLongitude sets the longitude property value. The longitude of the location.
func (m *OutlookGeoCoordinates) SetLongitude(value *float64)() {
if m != nil {
m.longitude = value
}
} | models/microsoft/graph/outlook_geo_coordinates.go | 0.761272 | 0.506225 | outlook_geo_coordinates.go | starcoder |
package node
import (
"fmt"
"github.com/hslam/code"
)
// SetCommand represents a set command.
type SetCommand struct {
Key string
Value string
}
// Size returns the size of the buffer required to represent the data when encoded.
func (d *SetCommand) Size() int {
var size uint64
size += 11 + uint64(len(d.Key))
size += 11 + uint64(len(d.Value))
return int(size)
}
// Marshal returns the encoded bytes.
func (d *SetCommand) Marshal() ([]byte, error) {
size := d.Size()
buf := make([]byte, size)
n, err := d.MarshalTo(buf[:size])
return buf[:n], err
}
// MarshalTo marshals into buf and returns the number of bytes.
func (d *SetCommand) MarshalTo(buf []byte) (int, error) {
var size = uint64(d.Size())
if uint64(cap(buf)) >= size {
buf = buf[:size]
} else {
return 0, fmt.Errorf("proto: buf is too short")
}
var offset uint64
var n uint64
if len(d.Key) > 0 {
buf[offset] = 1<<3 | 2
offset++
n = code.EncodeString(buf[offset:], d.Key)
offset += n
}
if len(d.Value) > 0 {
buf[offset] = 2<<3 | 2
offset++
n = code.EncodeString(buf[offset:], d.Value)
offset += n
}
return int(offset), nil
}
// Unmarshal unmarshals from data.
func (d *SetCommand) Unmarshal(data []byte) error {
var length = uint64(len(data))
var offset uint64
var n uint64
var tag uint64
var fieldNumber int
var wireType uint8
for {
if offset < length {
tag = uint64(data[offset])
offset++
} else {
break
}
fieldNumber = int(tag >> 3)
wireType = uint8(tag & 0x7)
switch fieldNumber {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
n = code.DecodeString(data[offset:], &d.Key)
offset += n
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
n = code.DecodeString(data[offset:], &d.Value)
offset += n
}
}
return nil
}
// Request represents an RPC request.
type Request struct {
Key string
Value string
}
// Size returns the size of the buffer required to represent the data when encoded.
func (d *Request) Size() int {
var size uint64
size += 11 + uint64(len(d.Key))
size += 11 + uint64(len(d.Value))
return int(size)
}
// Marshal returns the encoded bytes.
func (d *Request) Marshal() ([]byte, error) {
size := d.Size()
buf := make([]byte, size)
n, err := d.MarshalTo(buf[:size])
return buf[:n], err
}
// MarshalTo marshals into buf and returns the number of bytes.
func (d *Request) MarshalTo(buf []byte) (int, error) {
var size = uint64(d.Size())
if uint64(cap(buf)) >= size {
buf = buf[:size]
} else {
return 0, fmt.Errorf("proto: buf is too short")
}
var offset uint64
var n uint64
if len(d.Key) > 0 {
buf[offset] = 1<<3 | 2
offset++
n = code.EncodeString(buf[offset:], d.Key)
offset += n
}
if len(d.Value) > 0 {
buf[offset] = 2<<3 | 2
offset++
n = code.EncodeString(buf[offset:], d.Value)
offset += n
}
return int(offset), nil
}
// Unmarshal unmarshals from data.
func (d *Request) Unmarshal(data []byte) error {
var length = uint64(len(data))
var offset uint64
var n uint64
var tag uint64
var fieldNumber int
var wireType uint8
for {
if offset < length {
tag = uint64(data[offset])
offset++
} else {
break
}
fieldNumber = int(tag >> 3)
wireType = uint8(tag & 0x7)
switch fieldNumber {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType)
}
n = code.DecodeString(data[offset:], &d.Key)
offset += n
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType)
}
n = code.DecodeString(data[offset:], &d.Value)
offset += n
}
}
return nil
}
// Response represents an RPC response.
type Response struct {
Ok bool
Result string
Leader string
}
// Size returns the size of the buffer required to represent the data when encoded.
func (d *Response) Size() int {
var size uint64
size += 11
size += 11 + uint64(len(d.Result))
size += 11 + uint64(len(d.Leader))
return int(size)
}
// Marshal returns the encoded bytes.
func (d *Response) Marshal() ([]byte, error) {
size := d.Size()
buf := make([]byte, size)
n, err := d.MarshalTo(buf[:size])
if err != nil {
return nil, err
}
return buf[:n], nil
}
// MarshalTo marshals into buf and returns the number of bytes.
func (d *Response) MarshalTo(buf []byte) (int, error) {
var size = uint64(d.Size())
if uint64(cap(buf)) >= size {
buf = buf[:size]
} else {
return 0, fmt.Errorf("proto: buf is too short")
}
var offset uint64
var n uint64
if d.Ok {
buf[offset] = 1<<3 | 0
offset++
n = code.EncodeBool(buf[offset:], d.Ok)
offset += n
}
if len(d.Result) > 0 {
buf[offset] = 2<<3 | 2
offset++
n = code.EncodeString(buf[offset:], d.Result)
offset += n
}
if len(d.Leader) > 0 {
buf[offset] = 3<<3 | 2
offset++
n = code.EncodeString(buf[offset:], d.Leader)
offset += n
}
return int(offset), nil
}
// Unmarshal unmarshals from data.
func (d *Response) Unmarshal(data []byte) error {
var length = uint64(len(data))
var offset uint64
var n uint64
var tag uint64
var fieldNumber int
var wireType uint8
for {
if offset < length {
tag = uint64(data[offset])
offset++
} else {
break
}
fieldNumber = int(tag >> 3)
wireType = uint8(tag & 0x7)
switch fieldNumber {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Ok", wireType)
}
n = code.DecodeBool(data[offset:], &d.Ok)
offset += n
case 2:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType)
}
n = code.DecodeString(data[offset:], &d.Result)
offset += n
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Leader", wireType)
}
n = code.DecodeString(data[offset:], &d.Leader)
offset += n
}
}
return nil
} | node/node.pb.go | 0.659515 | 0.40928 | node.pb.go | starcoder |
package block
import (
"github.com/df-mc/dragonfly/dragonfly/block/model"
"github.com/df-mc/dragonfly/dragonfly/item"
"github.com/df-mc/dragonfly/dragonfly/world"
"github.com/go-gl/mathgl/mgl64"
)
// Cake is an edible block.
type Cake struct {
noNBT
transparent
// Bites is the amount of bites taken out of the cake.
Bites int
}
// CanDisplace ...
func (c Cake) CanDisplace(b world.Liquid) bool {
_, water := b.(Water)
return water
}
// SideClosed ...
func (c Cake) SideClosed(world.BlockPos, world.BlockPos, *world.World) bool {
return false
}
// UseOnBlock ...
func (c Cake) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) bool {
pos, _, used := firstReplaceable(w, pos, face, c)
if !used {
return false
}
if _, air := w.Block(pos.Side(world.FaceDown)).(Air); air {
return false
}
place(w, pos, c, user, ctx)
return placed(ctx)
}
// NeighbourUpdateTick ...
func (c Cake) NeighbourUpdateTick(pos, _ world.BlockPos, w *world.World) {
if _, air := w.Block(pos.Side(world.FaceDown)).(Air); air {
w.BreakBlock(pos)
}
}
// Activate ...
func (c Cake) Activate(pos world.BlockPos, _ world.Face, w *world.World, u item.User) {
if i, ok := u.(interface {
Saturate(food int, saturation float64)
}); ok {
i.Saturate(2, 0.4)
c.Bites++
if c.Bites > 6 {
w.BreakBlockWithoutParticles(pos)
return
}
w.PlaceBlock(pos, c)
}
}
// BreakInfo ...
func (c Cake) BreakInfo() BreakInfo {
return BreakInfo{
Hardness: 0.5,
Harvestable: nothingEffective,
Effective: nothingEffective,
Drops: simpleDrops(),
}
}
// EncodeItem ...
func (c Cake) EncodeItem() (id int32, meta int16) {
return 354, 0
}
// EncodeBlock ...
func (c Cake) EncodeBlock() (name string, properties map[string]interface{}) {
return "minecraft:cake", map[string]interface{}{"bite_counter": int32(c.Bites)}
}
// Hash ...
func (c Cake) Hash() uint64 {
return hashCake | (uint64(c.Bites) << 32)
}
// Model ...
func (c Cake) Model() world.BlockModel {
return model.Cake{Bites: c.Bites}
}
// allCake ...
func allCake() (cake []world.Block) {
for i := 0; i <= 6; i++ {
cake = append(cake, Cake{Bites: i})
}
return
} | dragonfly/block/cake.go | 0.64131 | 0.405655 | cake.go | starcoder |
package properties
// GetExpression returns the Expression field if it's non-nil, zero value otherwise.
func (m *MultiDimensional) GetExpression() string {
if m == nil || m.Expression == nil {
return ""
}
return *m.Expression
}
// GetIndex returns the Index field if it's non-nil, zero value otherwise.
func (m *MultiDimensional) GetIndex() int {
if m == nil || m.Index == nil {
return 0
}
return *m.Index
}
// GetExpression returns the Expression field if it's non-nil, zero value otherwise.
func (m *MultiDimensionalKeyframed) GetExpression() string {
if m == nil || m.Expression == nil {
return ""
}
return *m.Expression
}
// GetIndex returns the Index field if it's non-nil, zero value otherwise.
func (m *MultiDimensionalKeyframed) GetIndex() int {
if m == nil || m.Index == nil {
return 0
}
return *m.Index
}
// GetIn returns the In field.
func (o *OffsetKeyframe) GetIn() *In {
if o == nil {
return nil
}
return o.In
}
// GetOut returns the Out field.
func (o *OffsetKeyframe) GetOut() *Out {
if o == nil {
return nil
}
return o.Out
}
// GetStartTime returns the StartTime field if it's non-nil, zero value otherwise.
func (o *OffsetKeyframe) GetStartTime() float64 {
if o == nil || o.StartTime == nil {
return 0.0
}
return *o.StartTime
}
// GetExpression returns the Expression field if it's non-nil, zero value otherwise.
func (v *Value) GetExpression() string {
if v == nil || v.Expression == nil {
return ""
}
return *v.Expression
}
// GetIndex returns the Index field if it's non-nil, zero value otherwise.
func (v *Value) GetIndex() int {
if v == nil || v.Index == nil {
return 0
}
return *v.Index
}
// GetValue returns the Value field if it's non-nil, zero value otherwise.
func (v *Value) GetValue() float64 {
if v == nil || v.Value == nil {
return 0.0
}
return *v.Value
}
// GetIn returns the In field.
func (v *ValueKeyframe) GetIn() *In {
if v == nil {
return nil
}
return v.In
}
// GetOut returns the Out field.
func (v *ValueKeyframe) GetOut() *Out {
if v == nil {
return nil
}
return v.Out
}
// GetStartTime returns the StartTime field if it's non-nil, zero value otherwise.
func (v *ValueKeyframe) GetStartTime() float64 {
if v == nil || v.StartTime == nil {
return 0.0
}
return *v.StartTime
}
// GetExpression returns the Expression field if it's non-nil, zero value otherwise.
func (v *ValueKeyframed) GetExpression() string {
if v == nil || v.Expression == nil {
return ""
}
return *v.Expression
}
// GetIndex returns the Index field if it's non-nil, zero value otherwise.
func (v *ValueKeyframed) GetIndex() int {
if v == nil || v.Index == nil {
return 0
}
return *v.Index
} | lottie/properties/properties-accessors.go | 0.859354 | 0.490175 | properties-accessors.go | starcoder |
package onshape
import (
"encoding/json"
)
// BTMSketchPoint158AllOf struct for BTMSketchPoint158AllOf
type BTMSketchPoint158AllOf struct {
BtType *string `json:"btType,omitempty"`
IsUserPoint *bool `json:"isUserPoint,omitempty"`
X *float64 `json:"x,omitempty"`
Y *float64 `json:"y,omitempty"`
}
// NewBTMSketchPoint158AllOf instantiates a new BTMSketchPoint158AllOf 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 NewBTMSketchPoint158AllOf() *BTMSketchPoint158AllOf {
this := BTMSketchPoint158AllOf{}
return &this
}
// NewBTMSketchPoint158AllOfWithDefaults instantiates a new BTMSketchPoint158AllOf 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 NewBTMSketchPoint158AllOfWithDefaults() *BTMSketchPoint158AllOf {
this := BTMSketchPoint158AllOf{}
return &this
}
// GetBtType returns the BtType field value if set, zero value otherwise.
func (o *BTMSketchPoint158AllOf) 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 *BTMSketchPoint158AllOf) 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 *BTMSketchPoint158AllOf) 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 *BTMSketchPoint158AllOf) SetBtType(v string) {
o.BtType = &v
}
// GetIsUserPoint returns the IsUserPoint field value if set, zero value otherwise.
func (o *BTMSketchPoint158AllOf) GetIsUserPoint() bool {
if o == nil || o.IsUserPoint == nil {
var ret bool
return ret
}
return *o.IsUserPoint
}
// GetIsUserPointOk returns a tuple with the IsUserPoint field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTMSketchPoint158AllOf) GetIsUserPointOk() (*bool, bool) {
if o == nil || o.IsUserPoint == nil {
return nil, false
}
return o.IsUserPoint, true
}
// HasIsUserPoint returns a boolean if a field has been set.
func (o *BTMSketchPoint158AllOf) HasIsUserPoint() bool {
if o != nil && o.IsUserPoint != nil {
return true
}
return false
}
// SetIsUserPoint gets a reference to the given bool and assigns it to the IsUserPoint field.
func (o *BTMSketchPoint158AllOf) SetIsUserPoint(v bool) {
o.IsUserPoint = &v
}
// GetX returns the X field value if set, zero value otherwise.
func (o *BTMSketchPoint158AllOf) GetX() float64 {
if o == nil || o.X == nil {
var ret float64
return ret
}
return *o.X
}
// GetXOk returns a tuple with the X field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTMSketchPoint158AllOf) GetXOk() (*float64, bool) {
if o == nil || o.X == nil {
return nil, false
}
return o.X, true
}
// HasX returns a boolean if a field has been set.
func (o *BTMSketchPoint158AllOf) HasX() bool {
if o != nil && o.X != nil {
return true
}
return false
}
// SetX gets a reference to the given float64 and assigns it to the X field.
func (o *BTMSketchPoint158AllOf) SetX(v float64) {
o.X = &v
}
// GetY returns the Y field value if set, zero value otherwise.
func (o *BTMSketchPoint158AllOf) GetY() float64 {
if o == nil || o.Y == nil {
var ret float64
return ret
}
return *o.Y
}
// GetYOk returns a tuple with the Y field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTMSketchPoint158AllOf) GetYOk() (*float64, bool) {
if o == nil || o.Y == nil {
return nil, false
}
return o.Y, true
}
// HasY returns a boolean if a field has been set.
func (o *BTMSketchPoint158AllOf) HasY() bool {
if o != nil && o.Y != nil {
return true
}
return false
}
// SetY gets a reference to the given float64 and assigns it to the Y field.
func (o *BTMSketchPoint158AllOf) SetY(v float64) {
o.Y = &v
}
func (o BTMSketchPoint158AllOf) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.BtType != nil {
toSerialize["btType"] = o.BtType
}
if o.IsUserPoint != nil {
toSerialize["isUserPoint"] = o.IsUserPoint
}
if o.X != nil {
toSerialize["x"] = o.X
}
if o.Y != nil {
toSerialize["y"] = o.Y
}
return json.Marshal(toSerialize)
}
type NullableBTMSketchPoint158AllOf struct {
value *BTMSketchPoint158AllOf
isSet bool
}
func (v NullableBTMSketchPoint158AllOf) Get() *BTMSketchPoint158AllOf {
return v.value
}
func (v *NullableBTMSketchPoint158AllOf) Set(val *BTMSketchPoint158AllOf) {
v.value = val
v.isSet = true
}
func (v NullableBTMSketchPoint158AllOf) IsSet() bool {
return v.isSet
}
func (v *NullableBTMSketchPoint158AllOf) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableBTMSketchPoint158AllOf(val *BTMSketchPoint158AllOf) *NullableBTMSketchPoint158AllOf {
return &NullableBTMSketchPoint158AllOf{value: val, isSet: true}
}
func (v NullableBTMSketchPoint158AllOf) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableBTMSketchPoint158AllOf) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | onshape/model_btm_sketch_point_158_all_of.go | 0.721939 | 0.432782 | model_btm_sketch_point_158_all_of.go | starcoder |
package datastore //nolint:dupl // it's cleaner to keep each type separate, even with duplication
import (
"encoding/binary"
"math"
"github.com/hexbee-net/errors"
"github.com/hexbee-net/parquet/parquet"
)
const sizeDouble = 8
type DoubleStore struct {
valueStore
min float64
max float64
}
// NewDoubleStore creates a new column store to store double (float64) values. If allowDict is true,
// then using a dictionary is considered by the column store depending on its heuristics.
// If allowDict is false, a dictionary will never be used to encode the data.
func NewDoubleStore(enc parquet.Encoding, allowDict bool, params *ColumnParameters) (*ColumnStore, error) {
switch enc { //nolint:exhaustive // supported encoding only
case parquet.Encoding_PLAIN:
default:
return nil, errors.WithFields(
errors.New("encoding not supported on double type"),
errors.Fields{
"encoding": enc.String(),
})
}
return NewColumnStore(&DoubleStore{valueStore: valueStore{ColumnParameters: params}}, enc, allowDict), nil
}
func (s *DoubleStore) ParquetType() parquet.Type {
return parquet.Type_DOUBLE
}
func (s *DoubleStore) Reset(repetitionType parquet.FieldRepetitionType) {
s.repTyp = repetitionType
s.min = math.MaxFloat64
s.max = -math.MaxFloat64
}
func (s *DoubleStore) MinValue() []byte {
if s.min == math.MaxFloat64 {
return nil
}
ret := make([]byte, sizeDouble)
binary.LittleEndian.PutUint64(ret, math.Float64bits(s.min))
return ret
}
func (s *DoubleStore) MaxValue() []byte {
if s.max == -math.MaxFloat64 {
return nil
}
ret := make([]byte, sizeDouble)
binary.LittleEndian.PutUint64(ret, math.Float64bits(s.max))
return ret
}
func (s *DoubleStore) SizeOf(v interface{}) int {
return sizeDouble
}
func (s *DoubleStore) GetValues(v interface{}) ([]interface{}, error) { //nolint:dupl // duplication is the easiest way without generics
var values []interface{}
switch typed := v.(type) {
case float64:
s.setMinMax(typed)
values = []interface{}{typed}
case []float64:
if s.repTyp != parquet.FieldRepetitionType_REPEATED {
return nil, errors.New("the value is not repeated but it is an array")
}
values = make([]interface{}, len(typed))
for j := range typed {
s.setMinMax(typed[j])
values[j] = typed[j]
}
default:
return nil, errors.WithFields(
errors.New("unsupported type for storing in float64 column"),
errors.Fields{
"value": v,
})
}
return values, nil
}
func (s *DoubleStore) Append(arrayIn, value interface{}) interface{} {
if arrayIn == nil {
arrayIn = make([]float64, 0, 1)
}
return append(arrayIn.([]float64), value.(float64))
}
func (s *DoubleStore) setMinMax(n float64) {
if n < s.min {
s.min = n
}
if n > s.max {
s.max = n
}
} | datastore/double.go | 0.747432 | 0.408572 | double.go | starcoder |
package cryptoapis
import (
"encoding/json"
)
// AddressCoinsTransactionConfirmedDataItem Defines an `item` as one result.
type AddressCoinsTransactionConfirmedDataItem struct {
// Represents the specific blockchain protocol name, e.g. Ethereum, Bitcoin, etc.
Blockchain string `json:"blockchain"`
// Represents the name of the blockchain network used; blockchain networks are usually identical as technology and software, but they differ in data, e.g. - \"mainnet\" is the live network with actual data while networks like \"testnet\", \"ropsten\", \"rinkeby\" are test networks.
Network string `json:"network"`
// Defines the specific address to which the coin transaction has been sent and is confirmed.
Address string `json:"address"`
MinedInBlock AddressCoinsTransactionConfirmedDataItemMinedInBlock `json:"minedInBlock"`
// Defines the unique ID of the specific transaction, i.e. its identification number.
TransactionId string `json:"transactionId"`
// Defines the amount of coins sent with the confirmed transaction.
Amount string `json:"amount"`
// Defines the unit of the transaction, e.g. BTC.
Unit string `json:"unit"`
// Defines whether the transaction is \"incoming\" or \"outgoing\".
Direction string `json:"direction"`
}
// NewAddressCoinsTransactionConfirmedDataItem instantiates a new AddressCoinsTransactionConfirmedDataItem 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 NewAddressCoinsTransactionConfirmedDataItem(blockchain string, network string, address string, minedInBlock AddressCoinsTransactionConfirmedDataItemMinedInBlock, transactionId string, amount string, unit string, direction string) *AddressCoinsTransactionConfirmedDataItem {
this := AddressCoinsTransactionConfirmedDataItem{}
this.Blockchain = blockchain
this.Network = network
this.Address = address
this.MinedInBlock = minedInBlock
this.TransactionId = transactionId
this.Amount = amount
this.Unit = unit
this.Direction = direction
return &this
}
// NewAddressCoinsTransactionConfirmedDataItemWithDefaults instantiates a new AddressCoinsTransactionConfirmedDataItem 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 NewAddressCoinsTransactionConfirmedDataItemWithDefaults() *AddressCoinsTransactionConfirmedDataItem {
this := AddressCoinsTransactionConfirmedDataItem{}
return &this
}
// GetBlockchain returns the Blockchain field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetBlockchain() string {
if o == nil {
var ret string
return ret
}
return o.Blockchain
}
// GetBlockchainOk returns a tuple with the Blockchain field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetBlockchainOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Blockchain, true
}
// SetBlockchain sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetBlockchain(v string) {
o.Blockchain = v
}
// GetNetwork returns the Network field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetNetwork() string {
if o == nil {
var ret string
return ret
}
return o.Network
}
// GetNetworkOk returns a tuple with the Network field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetNetworkOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Network, true
}
// SetNetwork sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetNetwork(v string) {
o.Network = v
}
// GetAddress returns the Address field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetAddress() string {
if o == nil {
var ret string
return ret
}
return o.Address
}
// GetAddressOk returns a tuple with the Address field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetAddressOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Address, true
}
// SetAddress sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetAddress(v string) {
o.Address = v
}
// GetMinedInBlock returns the MinedInBlock field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetMinedInBlock() AddressCoinsTransactionConfirmedDataItemMinedInBlock {
if o == nil {
var ret AddressCoinsTransactionConfirmedDataItemMinedInBlock
return ret
}
return o.MinedInBlock
}
// GetMinedInBlockOk returns a tuple with the MinedInBlock field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetMinedInBlockOk() (*AddressCoinsTransactionConfirmedDataItemMinedInBlock, bool) {
if o == nil {
return nil, false
}
return &o.MinedInBlock, true
}
// SetMinedInBlock sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetMinedInBlock(v AddressCoinsTransactionConfirmedDataItemMinedInBlock) {
o.MinedInBlock = v
}
// GetTransactionId returns the TransactionId field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetTransactionId() string {
if o == nil {
var ret string
return ret
}
return o.TransactionId
}
// GetTransactionIdOk returns a tuple with the TransactionId field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetTransactionIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.TransactionId, true
}
// SetTransactionId sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetTransactionId(v string) {
o.TransactionId = v
}
// GetAmount returns the Amount field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetAmount() string {
if o == nil {
var ret string
return ret
}
return o.Amount
}
// GetAmountOk returns a tuple with the Amount field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetAmountOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Amount, true
}
// SetAmount sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetAmount(v string) {
o.Amount = v
}
// GetUnit returns the Unit field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetUnit() string {
if o == nil {
var ret string
return ret
}
return o.Unit
}
// GetUnitOk returns a tuple with the Unit field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetUnitOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Unit, true
}
// SetUnit sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetUnit(v string) {
o.Unit = v
}
// GetDirection returns the Direction field value
func (o *AddressCoinsTransactionConfirmedDataItem) GetDirection() string {
if o == nil {
var ret string
return ret
}
return o.Direction
}
// GetDirectionOk returns a tuple with the Direction field value
// and a boolean to check if the value has been set.
func (o *AddressCoinsTransactionConfirmedDataItem) GetDirectionOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Direction, true
}
// SetDirection sets field value
func (o *AddressCoinsTransactionConfirmedDataItem) SetDirection(v string) {
o.Direction = v
}
func (o AddressCoinsTransactionConfirmedDataItem) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["blockchain"] = o.Blockchain
}
if true {
toSerialize["network"] = o.Network
}
if true {
toSerialize["address"] = o.Address
}
if true {
toSerialize["minedInBlock"] = o.MinedInBlock
}
if true {
toSerialize["transactionId"] = o.TransactionId
}
if true {
toSerialize["amount"] = o.Amount
}
if true {
toSerialize["unit"] = o.Unit
}
if true {
toSerialize["direction"] = o.Direction
}
return json.Marshal(toSerialize)
}
type NullableAddressCoinsTransactionConfirmedDataItem struct {
value *AddressCoinsTransactionConfirmedDataItem
isSet bool
}
func (v NullableAddressCoinsTransactionConfirmedDataItem) Get() *AddressCoinsTransactionConfirmedDataItem {
return v.value
}
func (v *NullableAddressCoinsTransactionConfirmedDataItem) Set(val *AddressCoinsTransactionConfirmedDataItem) {
v.value = val
v.isSet = true
}
func (v NullableAddressCoinsTransactionConfirmedDataItem) IsSet() bool {
return v.isSet
}
func (v *NullableAddressCoinsTransactionConfirmedDataItem) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableAddressCoinsTransactionConfirmedDataItem(val *AddressCoinsTransactionConfirmedDataItem) *NullableAddressCoinsTransactionConfirmedDataItem {
return &NullableAddressCoinsTransactionConfirmedDataItem{value: val, isSet: true}
}
func (v NullableAddressCoinsTransactionConfirmedDataItem) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableAddressCoinsTransactionConfirmedDataItem) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | model_address_coins_transaction_confirmed_data_item.go | 0.844922 | 0.420005 | model_address_coins_transaction_confirmed_data_item.go | starcoder |
package checksum
import (
"errors"
"strconv"
)
var multiplicationTable = map[int]map[int]int{
0: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9},
1: {0: 1, 1: 2, 2: 3, 3: 4, 4: 0, 5: 6, 6: 7, 7: 8, 8: 9, 9: 5},
2: {0: 2, 1: 3, 2: 4, 3: 0, 4: 1, 5: 7, 6: 8, 7: 9, 8: 5, 9: 6},
3: {0: 3, 1: 4, 2: 0, 3: 1, 4: 2, 5: 8, 6: 9, 7: 5, 8: 6, 9: 7},
4: {0: 4, 1: 0, 2: 1, 3: 2, 4: 3, 5: 9, 6: 5, 7: 6, 8: 7, 9: 8},
5: {0: 5, 1: 9, 2: 8, 3: 7, 4: 6, 5: 0, 6: 4, 7: 3, 8: 2, 9: 1},
6: {0: 6, 1: 5, 2: 9, 3: 8, 4: 7, 5: 1, 6: 0, 7: 4, 8: 3, 9: 2},
7: {0: 7, 1: 6, 2: 5, 3: 9, 4: 8, 5: 2, 6: 1, 7: 0, 8: 4, 9: 3},
8: {0: 8, 1: 7, 2: 6, 3: 5, 4: 9, 5: 3, 6: 2, 7: 1, 8: 0, 9: 4},
9: {0: 9, 1: 8, 2: 7, 3: 6, 4: 5, 5: 4, 6: 3, 7: 2, 8: 1, 9: 0},
}
var inverseTable = map[int]int{
0: 0,
1: 4,
2: 3,
3: 2,
4: 1,
5: 5,
6: 6,
7: 7,
8: 8,
9: 9,
}
var permutationTable = map[int]map[int]int{
0: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9},
1: {0: 1, 1: 5, 2: 7, 3: 6, 4: 2, 5: 8, 6: 3, 7: 0, 8: 9, 9: 4},
2: {0: 5, 1: 8, 2: 0, 3: 3, 4: 7, 5: 9, 6: 6, 7: 1, 8: 4, 9: 2},
3: {0: 8, 1: 9, 2: 1, 3: 6, 4: 0, 5: 4, 6: 3, 7: 5, 8: 2, 9: 7},
4: {0: 9, 1: 4, 2: 5, 3: 3, 4: 1, 5: 2, 6: 6, 7: 8, 8: 7, 9: 0},
5: {0: 4, 1: 2, 2: 8, 3: 6, 4: 5, 5: 7, 6: 3, 7: 9, 8: 0, 9: 1},
6: {0: 2, 1: 7, 2: 9, 3: 3, 4: 8, 5: 0, 6: 6, 7: 4, 8: 1, 9: 5},
7: {0: 7, 1: 0, 2: 4, 3: 6, 4: 9, 5: 1, 6: 3, 7: 2, 8: 5, 9: 8},
}
// Verhoeff implements the Verhoeff algorithm.
type Verhoeff struct{}
// The Verhoeff checksum calculation is performed as follows:
// 1. Create an array n out of the individual digits of the number, taken from right to left (rightmost digit is n0, etc.).
// 2. Initialize the checksum c to zero.
// 3. For each index i of the array n, starting at zero, replace c with d(c, p(i mod 8, ni)).
// The original number is valid if and only if c = 0.
// To generate a check digit, append a 0, perform the calculation: the correct check digit is inv(c).
func verhoeff(s string) (int, error) {
c := 0
for i := range s {
char := s[len(s)-1-i] // get characters in reverse order
if char < 48 || char > 57 { // Checks character is between [0-9]
return 0, errors.New("Not a numeric string")
}
digit := int(char - '0')
c = multiplicationTable[c][permutationTable[i%8][digit]]
}
return c, nil
}
// Check the checksum of a given string representing a numeric value, always assuming the last digit is the checksum.
func (*Verhoeff) Check(s string) (bool, error) {
c, err := verhoeff(s)
if err != nil {
return false, err
}
if c != 0 {
return false, nil
}
return true, nil
}
// Compute the checksum digit of a given string representing a numeric value.
func (*Verhoeff) Compute(s string) (int, string, error) {
c, err := verhoeff(s + "0")
if err != nil {
return 0, "", err
}
return inverseTable[c], s + strconv.Itoa(inverseTable[c]), nil
} | verhoeff.go | 0.746509 | 0.729399 | verhoeff.go | starcoder |
package base
import (
"fmt"
)
// Feature types are very thin (no memory footprint) wrappers over actual data with some useful methods.
// Instead of defining the features in the metadata for a tuple/collection,
// we will put a very thin wrapper around every piece of data.
type Feature interface {
Value() interface{}
IsNumeric() bool
}
type NumericFeature interface {
Feature
NumericValue() float64
}
// Nil
type NilFeature byte
func Nil() NilFeature {
return NilFeature(0);
}
func (this NilFeature) Value() interface{} {
return nil;
}
func (this NilFeature) IsNumeric() bool {
return false;
}
// Integer
type IntFeature int
func Int(val int) IntFeature {
return IntFeature(val);
}
func (this IntFeature) Value() interface{} {
return int(this);
}
func (this IntFeature) NumericValue() float64 {
return float64(this);
}
func (this IntFeature) IntValue() int {
return int(this);
}
func (this IntFeature) IsNumeric() bool {
return true;
}
// Float
type FloatFeature float64
func Float(val float64) FloatFeature {
return FloatFeature(val);
}
func (this FloatFeature) Value() interface{} {
return float64(this);
}
func (this FloatFeature) NumericValue() float64 {
return float64(this);
}
func (this FloatFeature) FloatValue() float64 {
return float64(this);
}
func (this FloatFeature) IsNumeric() bool {
return true;
}
// Bool
type BoolFeature bool
func Bool(val bool) BoolFeature {
return BoolFeature(val);
}
func (this BoolFeature) Value() interface{} {
return bool(this);
}
func (this BoolFeature) NumericValue() float64 {
if (bool(this)) {
return 1;
}
return 0;
}
func (this BoolFeature) BoolValue() bool {
return bool(this);
}
func (this BoolFeature) IsNumeric() bool {
return true;
}
// String
type StringFeature string
func String(val string) StringFeature {
return StringFeature(val);
}
func (this StringFeature) Value() interface{} {
return string(this);
}
func (this StringFeature) StringValue() string {
return string(this);
}
func (this StringFeature) IsNumeric() bool {
return false;
}
// Infer feature types from the data.
// If the data is already a feature type, then that will be returned.
// If the data type does not match the allowed feature types
// (eg a string is passed to InferNumericFeature(), then we will panic.
func InferFeatures(data []interface{}) []Feature {
var rtn []Feature = make([]Feature, len(data));
for i, val := range(data) {
rtn[i] = InferFeature(val);
}
return rtn;
}
func InferFeature(data interface{}) Feature {
if (data == nil) {
return Nil();
}
// Note that we can't group up the cases (fallthrough semantics)
// since then data would be an interface{} instead of a hard type.
// Which would then forace a type assertion before the cast.
switch data := data.(type) {
// Check for Feature types first.
case NilFeature:
return data;
case IntFeature:
return data;
case FloatFeature:
return data;
case StringFeature:
return data;
case BoolFeature:
return data;
// Check for builtin types.
case int:
return Int(data)
case int32:
return Int(int(data))
case int64:
return Int(int(data))
case uint:
return Int(int(data))
case uint32:
return Int(int(data))
case uint64:
return Int(int(data))
case bool:
return Bool(data);
case float32:
return Float(float64(data))
case float64:
return Float(data)
case string:
return String(data);
default:
panic(fmt.Sprintf("Unknown type for feature conversion: %T", data))
}
}
func InferNumericFeatures(data []interface{}) []NumericFeature {
var rtn []NumericFeature = make([]NumericFeature, len(data));
for i, val := range(data) {
rtn[i] = InferNumericFeature(val);
}
return rtn;
}
func InferNumericFeature(data interface{}) NumericFeature {
var feature Feature = InferFeature(data);
numericFeature, ok := feature.(NumericFeature);
if (!ok) {
panic(fmt.Sprintf("Tried to infer numeric feature from non-numeric value: %v", data));
}
return numericFeature;
}
func InferIntFeatures(data []interface{}) []IntFeature {
var rtn []IntFeature = make([]IntFeature, len(data));
for i, val := range(data) {
rtn[i] = InferIntFeature(val);
}
return rtn;
}
func InferIntFeature(data interface{}) IntFeature {
var feature Feature = InferFeature(data);
intFeature, ok := feature.(IntFeature);
if (!ok) {
panic(fmt.Sprintf("Tried to infer int feature from non-int value: %v", data));
}
return intFeature;
} | base/features.go | 0.8156 | 0.514461 | features.go | starcoder |
// Package primitive contains types similar to Go primitives for BSON types can do not have direct
// Go primitive representations.
package primitive
import (
"bytes"
"fmt"
"github.com/mongodb/mongo-go-driver/bson/objectid"
)
// Binary represents a BSON binary value.
type Binary struct {
Subtype byte
Data []byte
}
// Equal compaes bp to bp2 and returns true is the are equal.
func (bp Binary) Equal(bp2 Binary) bool {
if bp.Subtype != bp2.Subtype {
return false
}
return bytes.Equal(bp.Data, bp2.Data)
}
// Undefined represents the BSON undefined value type.
type Undefined struct{}
// DateTime represents the BSON datetime value.
type DateTime int64
// Null repreesnts the BSON null value.
type Null struct{}
// Regex represents a BSON regex value.
type Regex struct {
Pattern string
Options string
}
func (rp Regex) String() string {
return fmt.Sprintf(`{"pattern": "%s", "options": "%s"}`, rp.Pattern, rp.Options)
}
// Equal compaes rp to rp2 and returns true is the are equal.
func (rp Regex) Equal(rp2 Regex) bool {
return rp.Pattern == rp2.Pattern && rp.Options == rp.Options
}
// DBPointer represents a BSON dbpointer value.
type DBPointer struct {
DB string
Pointer objectid.ObjectID
}
func (d DBPointer) String() string {
return fmt.Sprintf(`{"db": "%s", "pointer": "%s"}`, d.DB, d.Pointer)
}
// Equal compaes d to d2 and returns true is the are equal.
func (d DBPointer) Equal(d2 DBPointer) bool {
return d.DB == d2.DB && bytes.Equal(d.Pointer[:], d2.Pointer[:])
}
// JavaScript represents a BSON JavaScript code value.
type JavaScript string
// Symbol represents a BSON symbol value.
type Symbol string
// CodeWithScope represents a BSON JavaScript code with scope value.
type CodeWithScope struct {
Code JavaScript
Scope interface{}
}
func (cws CodeWithScope) String() string {
return fmt.Sprintf(`{"code": "%s", "scope": %v}`, cws.Code, cws.Scope)
}
// Timestamp represents a BSON timestamp value.
type Timestamp struct {
T uint32
I uint32
}
// Equal compaes tp to tp2 and returns true is the are equal.
func (tp Timestamp) Equal(tp2 Timestamp) bool {
return tp.T == tp2.T && tp.I == tp2.I
}
// MinKey represents the BSON minkey value.
type MinKey struct{}
// MaxKey represents the BSON maxkey value.
type MaxKey struct{} | vendor/github.com/mongodb/mongo-go-driver/bson/primitive/primitive.go | 0.842215 | 0.480662 | primitive.go | starcoder |
package model
// Implementations represent a repository of information about users and their associated Preferences for items.
type DataModel interface {
// Add a particular preference for a user.
AddPreference(p Preference)
// Get user's preferences, ordered by item id
GetUserPreferences(userId uint64) (PreferenceArray, error)
// Get all existing preferences expressed for that item, ordered by user id, as an array
GetItemPreferences(itemId uint64) (PreferenceArray, error)
PreferenceValue(userId, itemId uint64) (float64, error)
// The maximum preference value that is possible in the current problem domain being evaluated.
// For example, if the domain is movie ratings on a scale of 1 to 5, this should be 5. While a
// Recommender may estimate a preference value above 5.0, it isn't "fair" to consider that
// the system is actually suggesting an impossible rating of, say, 5.4 stars.
// In practice the application would cap this estimate to 5.0. Since evaluators evaluate
// the difference between estimated and actual value, this at least prevents this effect from unfairly
// penalizing a Recommender
MaxPreferenceValue() float64
// See MaxPreferenceValue
MinPreferenceValue() float64
// All item ids array in the model
ItemIds() []uint64
// Get total number of items known to the model. This is generally the union of all items preferred by
NumItems() int
// All user ids array in the model
UserIds() []uint64
// Get total number of users known to the model.
NumUsers() int
}
type Preference interface {
// Id of user who prefers the item
UserId() uint64
// Item id that is preferred
ItemId() uint64
// Strength of the preference for that item. Zero should indicate "no preference either way";
// positive values indicate preference and negative values indicate dislike
Value() float64
}
// An alternate representation of an array of Preference.
// Implementations, in theory, can produce a more memory-efficient representation.
type PreferenceArray interface {
// Get a materialized Preference representation of the preference at i
Get(i int) Preference
// Size of preference arary
Size() int
// Get user or item id
Id() uint64
// Get all user or item ids
Ids() []uint64
// Get preferences values
Values() []float64
Raw() []Preference
}
type PreferenceArrayMap interface {
Set(p Preference)
Raw() map[uint64]PreferenceArray
}
type RecommendedItem struct {
ItemId uint64
Value float64
}
const (
MinPreferenceValue = -1000.0
) | cf/model/interface.go | 0.819316 | 0.569075 | interface.go | starcoder |
package lm
import "math"
type Quat [4]float64
func QuatIdentity() (r Quat) {
r[0] = 0
r[1] = 0
r[2] = 0
r[3] = 1.0
return r
}
func (q Quat) Add(b Quat) (r Quat) {
for i := 0; i < 4; i++ {
r[i] = q[i] + b[i]
}
return r
}
func (q Quat) Sub(b Quat) (r Quat) {
for i := 0; i < 4; i++ {
r[i] = q[i] - b[i]
}
return r
}
func (q Quat) Vec3() (r Vec3) {
r[0] = q[0]
r[1] = q[1]
r[2] = q[2]
return r
}
func (q Quat) Mul(b Quat) (r Quat) {
v := q.Vec3().MulCross(b.Vec3()).Add(q.Vec3().Scale(b[3])).Add(b.Vec3().Scale(q[3]))
r[0] = v[0]
r[1] = v[1]
r[2] = v[2]
r[3] = q[3]*b[3] - q.Vec3().MulInner(b.Vec3())
return r
}
func (q Quat) Scale(s float64) (r Quat) {
for i := 0; i < 4; i++ {
r[i] = q[i] * s
}
return r
}
func (q Quat) InnerProduct(b Quat) (p float64) {
for i := 0; i < 4; i++ {
p += q[i] * b[i]
}
return p
}
func (q Quat) Conj() (r Quat) {
for i := 0; i < 3; i++ {
r[i] = -q[i]
}
r[3] = q[3]
return r
}
func QuatRotate(angle float64, axis Vec3) (r Quat) {
v := axis.Scale(math.Sin(angle / 2))
for i := 0; i < 3; i++ {
r[i] = v[i]
}
r[3] = math.Cos(angle / 2)
return r
}
func (v Vec4) Quat() (q Quat) {
return Quat(v)
}
func (q Quat) Vec4() (v Vec4) {
return Vec4(q)
}
func (q Quat) Norm() Quat {
return q.Vec4().Norm().Quat()
}
func (q Quat) MulVec3(v Vec3) (r Vec3) {
/*
Method by Fabian 'ryg' Giessen (of Farbrausch)
t = 2 * cross(q.xyz, v)
v' = v + q.w * t + cross(q.xyz, t)
*/
qXyz := Vec3{q[0], q[1], q[2]}
u := Vec3{q[0], q[1], q[2]}
t := qXyz.MulCross(v).Scale(2)
u = qXyz.MulCross(t)
t = t.Scale(q[3])
return v.Add(t).Add(u)
}
func (q Quat) Mat4x4() (M Mat4x4) {
a := q[3]
b := q[0]
c := q[1]
d := q[2]
a2 := a * a
b2 := b * b
c2 := c * c
d2 := d * d
M[0][0] = a2 + b2 - c2 - d2
M[0][1] = 2.0 * (b*c + a*d)
M[0][2] = 2.0 * (b*d - a*c)
M[0][3] = 0
M[1][0] = 2 * (b*c - a*d)
M[1][1] = a2 - b2 + c2 - d2
M[1][2] = 2.0 * (c*d + a*b)
M[1][3] = 0
M[2][0] = 2.0 * (b*d + a*c)
M[2][1] = 2.0 * (c*d - a*b)
M[2][2] = a2 - b2 - c2 + d2
M[2][3] = 0
M[3][0] = 0
M[3][1] = 0
M[3][2] = 0
M[3][3] = 1.0
return M
}
func (M *Mat4x4) MulQuat(RM Mat4x4, q Quat) {
/* XXX: The way this is written only works for othogonal matrices. */
/* TODO: Take care of non-orthogonal case. */
(*M)[0] = q.MulVec3(RM[0].Vec3()).Vec4()
(*M)[1] = q.MulVec3(RM[1].Vec3()).Vec4()
(*M)[2] = q.MulVec3(RM[2].Vec3()).Vec4()
(*M)[3][0] = 0
(*M)[3][1] = 0
(*M)[3][2] = 0
(*M)[3][3] = 1.0
}
func (M *Mat4x4) Quat() (q Quat) {
r := 0.0
for i := 0; i < 3; i++ {
m := (*M)[i][i]
if m < r {
continue
}
m = r
}
p0 := 2
p1 := 0
p2 := 1
r = math.Sqrt(1.0 + (*M)[p0][p0] - (*M)[p1][p1] - (*M)[p2][p2])
if r < 1e-6 {
q[0] = 1.0
q[1] = 0
q[2] = 0
q[3] = 0
return q
}
q[0] = r / 2.0
q[1] = ((*M)[p0][p1] - (*M)[p1][p0]) / (2.0 * r)
q[2] = ((*M)[p2][p0] - (*M)[p0][p2]) / (2.0 * r)
q[3] = ((*M)[p2][p1] - (*M)[p1][p2]) / (2.0 * r)
return q
} | quat.go | 0.575111 | 0.526038 | quat.go | starcoder |
package game
import (
"math"
"github.com/go-gl/mathgl/mgl32"
)
// Movable is a movable Thing. eg. Monsters
type Movable struct {
*DoomThing
speed float32
collisionCB func(me *DoomThing, to mgl32.Vec2) mgl32.Vec2
}
// NewMovable creates a new movable thing
func NewMovable(x, y, angle float32, sprite string) *Movable {
var m = &Movable{
DoomThing: NewDoomThing(x, y, angle, sprite, true),
}
return m
}
// SetCollision sets the collision callback.
func (m *Movable) SetCollision(cb func(thing *DoomThing, to mgl32.Vec2) mgl32.Vec2) {
m.collisionCB = cb
}
// Walk move player x steps back or forth
func (m *Movable) Walk(steps float32) {
if m.collisionCB != nil {
tmpPos := m.position
tmpPos[0] += -m.direction[0] * steps
tmpPos[1] += m.direction[1] * steps
m.position = m.collisionCB(m.DoomThing, tmpPos)
return
}
m.position[0] += -m.direction[0] * steps
m.position[1] += m.direction[1] * steps
}
// Strafe move player x steps left or right
func (m *Movable) Strafe(steps float32) {
if m.collisionCB != nil {
tmpPos := m.position
tmpPos[0] += m.direction[1] * steps
tmpPos[1] += m.direction[0] * steps
m.position = m.collisionCB(m.DoomThing, tmpPos)
return
}
m.position[0] += m.direction[1] * steps
m.position[1] += m.direction[0] * steps
}
// Lift set players height
func (m *Movable) Lift(steps float32, timePassed float32) {
m.height += steps * timePassed
}
// Turn player
func (m *Movable) Turn(angle float32) {
if angle == 0 {
return
}
m.hAngle += angle
m.updateDirection()
}
// Pitch is looking up and down
func (m *Movable) Pitch(angle float32) {
if angle == 0 {
return
}
m.vAngle += angle
if m.vAngle > 89 {
m.vAngle = 89
}
if m.vAngle < -89 {
m.vAngle = -89
}
m.updateDirection()
}
// ResetPitch makes the player look to the horizon
func (m *Movable) ResetPitch() {
m.vAngle = 0
m.updateDirection()
}
// SetDirection of the movable.
func (m *Movable) SetDirectionAngles(hAngle, vAngle float32) {
m.hAngle = hAngle
m.vAngle = vAngle
m.updateDirection()
}
func (m *Movable) updateDirection() {
y, x := math.Sincos(float64(m.hAngle) * math.Pi / 180)
z := math.Pi * m.vAngle / 90
m.direction = mgl32.Vec3{float32(x), float32(y), float32(z)}
} | game/movable.go | 0.684897 | 0.536313 | movable.go | starcoder |
package cmd
const version = "2.3.1"
const releaseNotes = `------------------------------------------------------------------------------|
| Version | Description |
|-----------|-----------------------------------------------------------------|
| 2.3.1 | Allow creating volumes without a snapshot policy by passing |
| | --count 0 |
|-----------|-----------------------------------------------------------------|
| 2.3 | Added support for the "organization" API |
| | Support pagination for packet baremetal list-devices |
|-----------|-----------------------------------------------------------------|
| 2.2.2 | Fixed a bug that blows away all tags on device updates |
| | Added --tags flag(not mandatory) to create-device and |
| | update-device commands |
|-----------|-----------------------------------------------------------------|
| 2.2.1 | Fixed compilation issue that emerged with updated Packet API |
|-----------|-----------------------------------------------------------------|
| 2.2 | "update-device" command added; more options for "create-device" |
| | command |
|-----------|-----------------------------------------------------------------|
| 2.1.3 | Fixed an issue that emerged with the updated Packet API |
|-----------|-----------------------------------------------------------------|
| 2.1.2 | Fixed an issue that emerged with the updated Packet API |
|-----------|-----------------------------------------------------------------|
| 2.1.1 | Bug fix around profile configuration. Now you can use --name |
| | or -n to configure and name a profile |
|-----------|-----------------------------------------------------------------|
| 2.1 | Add support for spot market |
|-----------|-----------------------------------------------------------------|
| 2.0 | Changed command structure, many bugs fixed |
|-----------|-----------------------------------------------------------------|
| 1.3 | Can now delete profiles |
|-----------|-----------------------------------------------------------------|
| 1.2 | Added profile support: use --profile option to switch between |
| | profiles. |
| | ssh command now reads keys from files, use --file instead of |
| | ssh-key to read from files. |
|-----------|-----------------------------------------------------------------|
| 1.1 | Added support for userdata |
|-----------|-----------------------------------------------------------------|
| 1.0 | First version |
-------------------------------------------------------------------------------` | cmd/version.go | 0.629205 | 0.416797 | version.go | starcoder |
package main
import (
"encoding/json"
"fmt"
"math/bits"
"os"
)
/*
* RegisterSet represents a subset of all registers. Each register is
* associated to a bit in the uint64. If the bit is 1, the register belongs
* to the RegisterSet and if it's 0 the register doesn't belong to the set.
* Using this representation is much more efficient than using a map or a list
* but it can only represent a fixed number of registers.
*/
type RegisterSet uint32
// AnalysisResult is the result of a register analysis.
type AnalysisResult struct {
/*
* FreeRegs is a slice containing the names of the registers that are free
* at each instruction.
*/
FreeRegs [][]string
// FunctionName is the name of the function that was analyzed.
FunctionName string
}
// Address is the address of an object in an ELF file.
type Address struct {
// SectionName is the name of the section that contains the object.
SectionName string
// Offset is the offset form the start of the section.
Offset uint64
}
// InstructionInfo contains data about an instruction in a program.
type InstructionInfo struct {
// Address is the address of the instruction.
Address Address
/*
* Successors is the list of successors of the instruction. A successor can
* be an integer (encoded as float64 because that's what Go uses for JSON
* numbers) if the successor is an instruction, or a string if the
* successor is special ("ret" if the instruction returns from
* the function, "call" if the instruction is a function call, and "undef"
* if the next instruction is unknown, for example if the instruction is an
* indirect jump with unknown target).
*/
Successors []interface{}
/*
* RegsWritten is a slice of strings containing the names of the registers
* that this instruction writes to.
*/
RegsWritten []string `json:"regs_written"`
// RegsWrittenSet is the same as RegsWritten but in bitset form.
RegsWrittenSet RegisterSet
/*
* RegsRead is a slice of strings containing the names of the registers
* that this instruction reads from.
*/
RegsRead []string `json:"regs_read"`
// RegsReadSet is the same as RegsRead but in bitset form.
RegsReadSet RegisterSet
}
// FunctionInfo contains information about a function.
type FunctionInfo struct {
// Address is the starting address of the function.
Address Address
/*
*Instructions contains an InstructionInfo structure for each instruction
* in the function.
*/
Instructions []InstructionInfo
BbStarts []string
}
// RegisterInfo contains information about an x86 register
type RegisterInfo struct {
/*
* FullRegisterName is the name of the full (64-bit) register corresponding
* to this register. For example the FullRegisterName of ah is rax.
*/
FullRegisterName string
// RegisterSize is the size of this register in bits.
RegisterSize int
}
/*
* maxIterations is the maximum number of iterations that the register analysis
* will run for before bailing out.
*/
const maxIterations = 8192
// allRegs is a list of the names of all registers.
var allRegs = []string{
"rax", "rbx", "rcx", "rdx", "rdi", "rsi", "rbp", "rsp", "r8", "r9",
"r10", "r11", "r12", "r13", "r14", "r15", "rip", "rflags",
}
// allRegsSet is a RegisterSet that contains all the registers.
var allRegsSet = regSetFromRegList(allRegs)
/*
* subRegs maps subregister names to the name of the full register
* (e.g. al -> rax, esp -> rsp).
*/
var subRegs = initializeSubRegs()
var regsUsedByRet = regSetFromRegList([]string{
"rbx", "rbp", "rsp", "r12", "r13", "r14", "r15", "rax", "rdx", "r10",
"r11", "r8", "r9", "rcx", "rdi", "rsi",
})
var regsUsedByCall = regSetFromRegList([]string{
"rbx", "rbp", "rsp", "r12", "r13", "r14", "r15", "rdi", "rsi", "rdx",
"rcx", "r8", "r9", "rax",
})
// regNameToUnitSet creates a RegisterSet containing only one register
func regNameToUnitSet(regName string) RegisterSet {
for i, r := range allRegs {
if subRegs[regName].FullRegisterName == r {
return 1 << uint(i)
}
}
panic(fmt.Sprintf("Unknown register name %s", regName))
}
// regSetFromRegList creates a RegisterSet from a list of register names
func regSetFromRegList(regList []string) RegisterSet {
ret := RegisterSet(0)
if len(regList) > 32 {
panic("Register list too long")
}
for _, r := range regList {
if r == "ds" || r == "gs" {
// Skip segment registers
continue
}
ret = ret.regSetUnion(regNameToUnitSet(r))
}
return ret
}
// regSetDifference computes the set difference between two register sets.
func (rs RegisterSet) regSetDifference(other RegisterSet) RegisterSet {
return (rs ^ other) & rs
}
// regSetUnion computes the set union between two register sets.
func (rs RegisterSet) regSetUnion(other RegisterSet) RegisterSet {
return rs | other
}
// regSetComplement computes the complement of a register set
func (rs RegisterSet) regSetComplement() RegisterSet {
return ^rs
}
// regSetComplement computes the size of a register set
func (rs RegisterSet) regSetSize() int {
return bits.OnesCount32(uint32(rs))
}
// regSetToRegList converts a RegisterSet to a list of register names
func (rs RegisterSet) regSetToRegList() []string {
ret := make([]string, 0)
for i, r := range allRegs {
if (rs & (1 << uint(i))) != 0 && r != "rip" && r != "rsp" {
ret = append(ret, r)
}
}
return ret
}
func analyzeInstruction(i int, functionName string, functionInfo *FunctionInfo, usedRegs []RegisterSet) bool {
instructionInfo := functionInfo.Instructions[i]
reguses := instructionInfo.RegsReadSet
regwrites := instructionInfo.RegsWrittenSet.regSetDifference(reguses)
for _, successor := range instructionInfo.Successors {
var regsUsedBySuccessor RegisterSet
switch v := successor.(type) {
case float64:
succIndex := int(v)
if succIndex > len(usedRegs) {
panic(fmt.Sprintf("Successor index out of range in %s instruction %d (%d/%d)", functionName, i, succIndex, len(usedRegs)))
} else if succIndex == len(usedRegs) {
// tail call?
regsUsedBySuccessor = allRegsSet
} else {
regsUsedBySuccessor = usedRegs[succIndex]
}
case string:
switch v {
case "ret":
regsUsedBySuccessor = regsUsedByRet
case "call":
regsUsedBySuccessor = regsUsedByCall
case "undef":
regsUsedBySuccessor = allRegsSet
}
}
regsUsedBySuccessor = regsUsedBySuccessor.regSetDifference(regwrites)
reguses = reguses.regSetUnion(regsUsedBySuccessor)
}
if reguses != usedRegs[i] {
usedRegs[i] = reguses
return true
}
return false
}
func analyzeFunction(functionName string, functionInfo *FunctionInfo) AnalysisResult {
usedRegs := make([]RegisterSet, 0, len(functionInfo.Instructions))
// Initialize the data so that every instruction initially uses every register
for _ = range functionInfo.Instructions {
usedRegs = append(usedRegs, allRegsSet)
}
// Convert to register set representation
for i := range functionInfo.Instructions {
regsRead := functionInfo.Instructions[i].RegsRead
regsWritten := functionInfo.Instructions[i].RegsWritten
functionInfo.Instructions[i].RegsReadSet = regSetFromRegList(regsRead)
functionInfo.Instructions[i].RegsWrittenSet = regSetFromRegList(regsWritten)
for _, rw := range regsWritten {
rinfo := subRegs[rw]
if rinfo.RegisterSize < 32 {
/*
* If an instruction writes to a 16-bit or 8-bit register it
* should also be marked as reading from the full register
* since the rest of the register is preserved by the write.
* otherwise the register analysis will be wrong.
*
* Consider the following example:
* xor ecx, ecx ; zeros all of rcx because 32-bit results
* ; are zero-extended to 64-bit
*
* [other stuff...]
*
* setz cl ; Capstone marks this instruction as writing
* ; from cl but not reading from it
*
* add ecx, ecx ; after this instruction ecx = 0 or ecx = 2
*
* The analysis will see that setz writes to cl (and therefore
* to rcx) and will consider rcx to be free for <other stuff>
* to overwrite. This is a problem because setz (or any
* instruction that writes to a 8-bit or 16-bit register)
* preserves the rest of the register. If other_stuff
* overwrites rcx, the result won't be 0 or 2 but something
* else, which is bad.
*
* To fix this, we need to mark all instructions that write
* to a 8- or 16-bit register as also reading from that
* register.
*/
functionInfo.Instructions[i].RegsReadSet |= regNameToUnitSet(rinfo.FullRegisterName)
}
}
}
change := true
for i := 0; i < maxIterations && change; i++ {
change = false
for i := range functionInfo.Instructions {
change = change || analyzeInstruction(i, functionName, functionInfo, usedRegs)
}
}
functionFreeRegs := make([][]string, 0, len(functionInfo.Instructions))
// Compute the set of free registers as the complement of the set of used registers
for _, instructionUsedRegs := range usedRegs {
instructionFreeRegs := instructionUsedRegs.regSetComplement().regSetToRegList()
functionFreeRegs = append(functionFreeRegs, instructionFreeRegs)
}
return AnalysisResult{FreeRegs: functionFreeRegs, FunctionName: functionName}
}
func initializeSubRegs() map[string]RegisterInfo {
ret := make(map[string]RegisterInfo)
for _, r := range allRegs {
ret[r] = RegisterInfo{FullRegisterName: r, RegisterSize: 64}
switch r {
case "rax":
fallthrough
case "rbx":
fallthrough
case "rcx":
fallthrough
case "rdx":
// eax, ...
ret["e"+r[1:]] = RegisterInfo{FullRegisterName: r, RegisterSize: 32}
// ax, ...
ret[r[1:]] = RegisterInfo{FullRegisterName: r, RegisterSize: 16}
// al, ...
ret[r[1:2]+"l"] = RegisterInfo{FullRegisterName: r, RegisterSize: 8}
// ah, ...
ret[r[1:2]+"h"] = RegisterInfo{FullRegisterName: r, RegisterSize: 8}
case "rdi":
fallthrough
case "rsi":
// edi, ...
ret["e"+r[1:]] = RegisterInfo{FullRegisterName: r, RegisterSize: 32}
// di, ...
ret[r[1:]] = RegisterInfo{FullRegisterName: r, RegisterSize: 16}
// dil, ...
ret[r[1:]+"l"] = RegisterInfo{FullRegisterName: r, RegisterSize: 8}
case "r8":
fallthrough
case "r9":
fallthrough
case "r10":
fallthrough
case "r11":
fallthrough
case "r12":
fallthrough
case "r13":
fallthrough
case "r14":
fallthrough
case "r15":
ret[r+"d"] = RegisterInfo{FullRegisterName: r, RegisterSize: 32}
ret[r+"w"] = RegisterInfo{FullRegisterName: r, RegisterSize: 16}
ret[r+"b"] = RegisterInfo{FullRegisterName: r, RegisterSize: 8}
case "rbp":
ret["ebp"] = RegisterInfo{FullRegisterName: r, RegisterSize: 32}
ret["bp"] = RegisterInfo{FullRegisterName: r, RegisterSize: 16}
ret["bpl"] = RegisterInfo{FullRegisterName: r, RegisterSize: 8}
}
}
return ret
}
func main() {
if len(os.Args) < 3 {
fmt.Printf("Usage: %s <control flow information> <output>\n", os.Args[0])
return
}
infile, err := os.Open(os.Args[1])
if err != nil {
fmt.Printf("Error opening input file: %s\n", err)
return
}
defer infile.Close()
outfile, err := os.Create(os.Args[2])
if err != nil {
fmt.Printf("Error creating output file: %s\n", err)
return
}
defer outfile.Close()
decoder := json.NewDecoder(infile)
encoder := json.NewEncoder(outfile)
// data maps the name of a function to its FunctionInfo structure
var data map[string]*FunctionInfo
// Load the function data
err = decoder.Decode(&data)
if err != nil {
fmt.Printf("Decoding error: %s\n", err)
return
}
/*
* completionChannel is used by the worker goroutines to send analysis
* results to the main goroutine
*/
completionChannel := make(chan AnalysisResult)
/*
* Each function can be analyzed independently, spawn one goroutine per
* function to process them in parallel
*/
for functionName, functionInfo := range data {
go func(fn string, fi *FunctionInfo) {
analysisResult := analyzeFunction(fn, fi)
completionChannel <- analysisResult
}(functionName, functionInfo)
}
// Receive the results from the worker goroutines and write them out
out := make(map[string]map[string]map[string][]string, len(data))
for i := 0; i < len(data); i++ {
ar := <-completionChannel
out[ar.FunctionName] = make(map[string]map[string][]string)
out[ar.FunctionName]["free_registers"] = make(map[string][]string)
for i, fr := range ar.FreeRegs {
out[ar.FunctionName]["free_registers"][fmt.Sprintf("%d", i)] = fr
}
}
err = encoder.Encode(out)
if err != nil {
fmt.Printf("Encoding error: %s\n", err)
}
} | cftool/main.go | 0.700485 | 0.481941 | main.go | starcoder |
package assert
import (
"fmt"
"strings"
"testing"
)
// test represents the functions to be used by Assertion.
type test interface {
Helper()
Error(...interface{})
}
// Assertion is a wrapper around testing.T.
type Assertion struct {
t test
}
// NewAssertion constructs and returns the wrapper.
func NewAssertion(t *testing.T) *Assertion {
return newAssertion(t)
}
// newAssertion constructs and returns the wrapper.
func newAssertion(t test) *Assertion {
if t == nil {
panic("nil test")
}
return &Assertion{t}
}
// buildMessage builds an error message.
func buildMessage(message string, args ...interface{}) string {
if len(args) == 0 {
return message
} else {
if format, ok := args[0].(string); !ok {
if len(args) == 1 {
return format
} else {
var formatCount = strings.Count(format, "%") - 2*strings.Count(format, "%%")
if formatCount != len(args)-1 {
panic("invalid format")
}
return fmt.Sprintf(format, args[1:])
}
} else {
panic("args[0] is not a string")
}
}
}
// True checks if actual is true.
func (assert *Assertion) True(actual bool, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage("expected: true, actual: false", args)
if actual {
return true
}
assert.t.Error(message)
return false
}
// False checks if actual is false.
func (assert *Assertion) False(actual bool, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage("expected: false, actual: true", args)
if !actual {
return true
}
assert.t.Error(message)
return false
}
// Nil checks if actual is nil.
func (assert *Assertion) Nil(actual interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("expected: nil, actual: %v", actual), args)
if isNil(actual) {
return true
}
assert.t.Error(message)
return false
}
// NotNil checks if actual is not nil
func (assert *Assertion) NotNil(actual interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage("unexpected: nil, actual: nil", args)
if !isNil(actual) {
return true
}
assert.t.Error(message)
return false
}
// Equals checks if expected and actual are equal.
func (assert *Assertion) Equals(expected interface{}, actual interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("expected: %v, actual: %v", expected, actual), args)
if expected == actual {
return true
}
assert.t.Error(message)
return false
}
// NotEquals checks if unexpected and actual are not equal.
func (assert *Assertion) NotEquals(unexpected interface{}, actual interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("unexpected: %v, actual: %v", unexpected, actual), args)
if unexpected != actual {
return true
}
assert.t.Error(message)
return false
}
// Length checks if collection is of length expected.
func (assert *Assertion) Length(collection interface{}, expected int, args ...interface{}) bool {
assert.t.Helper()
var actual = getLength(collection)
var message = buildMessage(fmt.Sprintf("expected length: %v, actual: %v", expected, actual), args)
if expected == actual {
return true
}
assert.t.Error(message)
return false
}
// NotLength checks if collection is not of length unexpected.
func (assert *Assertion) NotLength(collection interface{}, unexpected int, args ...interface{}) bool {
assert.t.Helper()
var actual = getLength(collection)
var message = buildMessage(fmt.Sprintf("unexpected length: %v, actual: %v", unexpected, actual), args)
if unexpected != actual {
return true
}
assert.t.Error(message)
return false
}
// Contains checks if collection contains element.
func (assert *Assertion) Contains(collection interface{}, element interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("collection %v does not contain %v", collection, element), args)
if contains(collection, element) {
return true
}
assert.t.Error(message)
return false
}
// NotContains checks if collection does not contain element.
func (assert *Assertion) NotContains(collection interface{}, element interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("collection %v contains %v", collection, element), args)
if !contains(collection, element) {
return true
}
assert.t.Error(message)
return false
}
// HasKey checks if _map has key as a key.
func (assert *Assertion) HasKey(_map interface{}, key interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("map %v does not contain key %v", _map, key), args)
if hasKey(_map, key) {
return true
}
assert.t.Error(message)
return false
}
// NotHasKey checks if _map doesn't have key as a key.
func (assert *Assertion) NotHasKey(_map interface{}, key interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("map %v contains key %v", _map, key), args)
if !hasKey(_map, key) {
return true
}
assert.t.Error(message)
return false
}
// ContainsPair checks if _map contains key -> value.
func (assert *Assertion) ContainsPair(_map interface{}, key interface{}, value interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("map %v does not contain the pair (%v, %v)", _map, key, value), args)
if containsPair(_map, key, value) {
return true
}
assert.t.Error(message)
return false
}
// NotContainsPair checks if _map does not contain key -> value.
func (assert *Assertion) NotContainsPair(_map interface{}, key interface{}, value interface{}, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("map %v contains the pair (%v, %v)", _map, key, value), args)
if !containsPair(_map, key, value) {
return true
}
assert.t.Error(message)
return false
}
// Prefix checks if _string has prefix as prefix.
func (assert *Assertion) Prefix(_string string, prefix string, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("string \"%v\" does not begin with \"%v\"", _string, prefix), args)
if strings.HasPrefix(_string, prefix) {
return true
}
assert.t.Error(message)
return false
}
// NotPrefix checks if _string does not have prefix as prefix.
func (assert *Assertion) NotPrefix(_string string, prefix string, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("string \"%v\" begins with \"%v\"", _string, prefix), args)
if !strings.HasPrefix(_string, prefix) {
return true
}
assert.t.Error(message)
return false
}
// Suffix checks if _string has suffix as suffix.
func (assert *Assertion) Suffix(_string string, suffix string, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("string \"%v\" does not end with \"%v\"", _string, suffix), args)
if strings.HasSuffix(_string, suffix) {
return true
}
assert.t.Error(message)
return false
}
// NotSuffix checks if _string does not have suffix as suffix.
func (assert *Assertion) NotSuffix(_string string, suffix string, args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("string \"%v\" ends with \"%v\"", _string, suffix), args)
if !strings.HasSuffix(_string, suffix) {
return true
}
assert.t.Error(message)
return false
}
// Panics checks if function panics.
func (assert *Assertion) Panics(function func(), args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("function did not panic"), args)
if panics(function) {
return true
}
assert.t.Error(message)
return false
}
// NotPanics checks if function does not panic.
func (assert *Assertion) NotPanics(function func(), args ...interface{}) bool {
assert.t.Helper()
var message = buildMessage(fmt.Sprintf("function panicked"), args)
if !panics(function) {
return true
}
assert.t.Error(message)
return false
}
// PanicValue checks if function panics with the provided value.
func (assert *Assertion) PanicValue(function func(), expected interface{}, args ...interface{}) bool {
assert.t.Helper()
var messageValue = buildMessage(fmt.Sprintf("function did not panic with value %v", expected), args)
var value = panicsWithValue(function, expected)
if !value {
assert.t.Error(messageValue)
} else {
return true
}
return false
} | assert/assertion.go | 0.777511 | 0.616416 | assertion.go | starcoder |
package expr
import (
"fmt"
"hash/crc32"
"math"
"math/rand"
"reflect"
"strings"
)
const kEpsilon = 1e-7
type Env map[Var]interface{}
type runtimePanic string
func EvalBool(expr Expr, env Env) (value bool, err error) {
defer func() {
switch x := recover().(type) {
case nil:
// no panic
case runtimePanic:
value = false
err = fmt.Errorf("%s", x)
default:
// unexpected panic: resume state of panic.
panic(x)
}
}()
if expr == nil {
return false, nil
}
value = ConvertToBool(expr.Eval(env))
return
}
func EvalInt(expr Expr, env Env) (value int64, err error) {
defer func() {
switch x := recover().(type) {
case nil:
// no panic
case runtimePanic:
value = 0
err = fmt.Errorf("%s", x)
default:
// unexpected panic: resume state of panic.
panic(x)
}
}()
if expr == nil {
return 0, nil
}
value = ConvertToInt(expr.Eval(env))
return
}
func (v Var) Eval(env Env) reflect.Value {
switch v {
case "true":
return reflect.ValueOf(true)
case "false":
return reflect.ValueOf(false)
default:
if i, ok := env[v]; ok {
return reflect.ValueOf(i)
}
panic(runtimePanic(fmt.Sprintf("undefined variable: %s", v)))
}
}
func (l literal) Eval(_ Env) reflect.Value {
return reflect.ValueOf(l.value)
}
func (u unary) Eval(env Env) reflect.Value {
switch u.op {
case "+":
return unaryPlus(u.x.Eval(env))
case "-":
return unaryMinus(u.x.Eval(env))
case "!":
return logicalNegation(u.x.Eval(env))
case "~":
return bitwiseComplement(u.x.Eval(env))
}
panic(runtimePanic(fmt.Sprintf("unsupported unary operator: %q", u.op)))
}
func (b binary) Eval(env Env) reflect.Value {
switch b.op {
case "+":
return addition(b.x.Eval(env), b.y.Eval(env))
case "-":
return subtraction(b.x.Eval(env), b.y.Eval(env))
case "*":
return multiplication(b.x.Eval(env), b.y.Eval(env))
case "/":
return division(b.x.Eval(env), b.y.Eval(env))
case "%":
return modulus(b.x.Eval(env), b.y.Eval(env))
case "&":
return bitwiseAnd(b.x.Eval(env), b.y.Eval(env))
case "&&":
return logicalAnd(b.x.Eval(env), b.y.Eval(env))
case "|":
return bitwiseOr(b.x.Eval(env), b.y.Eval(env))
case "||":
return logicalOr(b.x.Eval(env), b.y.Eval(env))
case "=", "==":
return comparisonEqual(b.x.Eval(env), b.y.Eval(env))
case ">":
return comparisonGreater(b.x.Eval(env), b.y.Eval(env))
case ">=":
return comparisonGreaterOrEqual(b.x.Eval(env), b.y.Eval(env))
case "<":
return comparisonLess(b.x.Eval(env), b.y.Eval(env))
case "<=":
return comparisonLessOrEqual(b.x.Eval(env), b.y.Eval(env))
case "!=":
return comparisonNotEqual(b.x.Eval(env), b.y.Eval(env))
}
panic(runtimePanic(fmt.Sprintf("unsupported binary operator: %q", b.op)))
}
func (c call) Eval(env Env) reflect.Value {
switch c.fn {
case "pow":
return reflect.ValueOf(math.Pow(ConvertToFloat(c.args[0].Eval(env)), ConvertToFloat(c.args[1].Eval(env))))
case "sin":
return reflect.ValueOf(math.Sin(ConvertToFloat(c.args[0].Eval(env))))
case "sqrt":
v := ConvertToFloat(c.args[0].Eval(env))
if v < 0 {
panic(runtimePanic(fmt.Sprintf("function call: %s only accept normal number", c.fn)))
}
return reflect.ValueOf(math.Sqrt(v))
case "rand":
return reflect.ValueOf(rand.Float64())
case "log":
v := ConvertToFloat(c.args[0].Eval(env))
if v < 0 {
panic(runtimePanic(fmt.Sprintf("function call: %s only accept normal number", c.fn)))
}
return reflect.ValueOf(math.Log10(v))
case "to_upper":
v := c.args[0].Eval(env)
if v.Kind() != reflect.String {
panic(runtimePanic(fmt.Sprintf("function call: %s only accept string", c.fn)))
}
return reflect.ValueOf(strings.ToUpper(v.String()))
case "to_lower":
v := c.args[0].Eval(env)
if v.Kind() != reflect.String {
panic(runtimePanic(fmt.Sprintf("function call: %s only accept string", c.fn)))
}
return reflect.ValueOf(strings.ToLower(v.String()))
case "crc32":
v := c.args[0].Eval(env)
if v.Kind() != reflect.String {
panic(runtimePanic(fmt.Sprintf("function call: %s only accept string", c.fn)))
}
return reflect.ValueOf(crc32.ChecksumIEEE([]byte(v.String())))
}
panic(runtimePanic(fmt.Sprintf("unsupported function call: %s", c.fn)))
}
func ConvertToBool(v reflect.Value) bool {
switch v.Kind() {
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:
return v.Uint() != 0
case reflect.Float32, reflect.Float64:
return v.Float() != 0
case reflect.String:
return v.String() != ""
default:
panic(runtimePanic(fmt.Sprintf("cannot convert data type: %s to bool", v.Kind().String())))
}
}
func ConvertToInt(v reflect.Value) int64 {
switch v.Kind() {
case reflect.Bool:
if v.Bool() {
return 1
} else {
return 0
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return int64(v.Uint())
case reflect.Float32, reflect.Float64:
return int64(v.Float())
default:
panic(runtimePanic(fmt.Sprintf("cannot convert data type: %s to int", v.Kind().String())))
}
}
func ConvertToUint(v reflect.Value) uint64 {
switch v.Kind() {
case reflect.Bool:
if v.Bool() {
return 1
} else {
return 0
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return uint64(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint()
case reflect.Float32, reflect.Float64:
return uint64(v.Float())
default:
panic(runtimePanic(fmt.Sprintf("cannot convert data type: %s to uint", v.Kind().String())))
}
}
func ConvertToFloat(v reflect.Value) float64 {
switch v.Kind() {
case reflect.Bool:
if v.Bool() {
return 1
} else {
return 0
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(v.Uint())
case reflect.Float32, reflect.Float64:
return v.Float()
default:
panic(runtimePanic(fmt.Sprintf("cannot convert data type: %s to float", v.Kind().String())))
}
}
func unaryPlus(v reflect.Value) reflect.Value {
return v
}
func unaryMinus(v reflect.Value) reflect.Value {
switch v.Kind() {
case reflect.Bool:
return v
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return reflect.ValueOf(-v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return reflect.ValueOf(-v.Uint())
case reflect.Float32, reflect.Float64:
return reflect.ValueOf(-v.Float())
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) not support unary minus", v.Interface(), v.Kind().String())))
}
}
func logicalNegation(v reflect.Value) reflect.Value {
return reflect.ValueOf(!ConvertToBool(v))
}
func bitwiseComplement(v reflect.Value) reflect.Value {
switch v.Kind() {
case reflect.Bool:
return reflect.ValueOf(!v.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return reflect.ValueOf(^v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return reflect.ValueOf(^v.Uint())
case reflect.Float32, reflect.Float64:
panic(runtimePanic("cannot eval ~ for float"))
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) not support bitwise complement", v.Interface(), v.Kind().String())))
}
}
func typeLevel(k reflect.Kind) int {
switch k {
case reflect.String:
return 5
case reflect.Float32, reflect.Float64:
return 4
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return 3
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return 2
case reflect.Bool:
return 1
default:
return 0
}
}
func typeAscend(a reflect.Kind, b reflect.Kind) reflect.Kind {
if typeLevel(a) >= typeLevel(b) {
return a
} else {
return b
}
}
func addition(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) + ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) + ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) + ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) + ConvertToInt(right)
return reflect.ValueOf(r != 0)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support addition",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func subtraction(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) - ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) - ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) - ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) - ConvertToInt(right)
return reflect.ValueOf(r != 0)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support subtraction",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func multiplication(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) * ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) * ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) * ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) * ConvertToInt(right)
return reflect.ValueOf(r != 0)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support multiplication",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func division(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
lv := ConvertToFloat(left)
rv := ConvertToFloat(right)
if math.Abs(rv) < kEpsilon {
panic(runtimePanic(fmt.Sprintf("%f div %f, divide by zero", lv, rv)))
}
return reflect.ValueOf(lv / rv)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
lv := ConvertToUint(left)
rv := ConvertToUint(right)
if rv == 0 {
panic(runtimePanic(fmt.Sprintf("%d div %d, divide by zero", lv, rv)))
}
return reflect.ValueOf(lv / rv)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
lv := ConvertToInt(left)
rv := ConvertToInt(right)
if rv == 0 {
panic(runtimePanic(fmt.Sprintf("%d div %d, divide by zero", lv, rv)))
}
return reflect.ValueOf(lv / rv)
case reflect.Bool:
lv := ConvertToInt(left)
rv := ConvertToInt(right)
if rv == 0 {
panic(runtimePanic(fmt.Sprintf("%d div %d, divide by zero", lv, rv)))
}
return reflect.ValueOf(lv/rv != 0)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support division",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func modulus(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) % ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) % ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) % ConvertToInt(right)
return reflect.ValueOf(r != 0)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support division",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func bitwiseAnd(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) & ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) & ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToBool(left) && ConvertToBool(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support bitwise and",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func bitwiseOr(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) | ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) | ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToBool(left) || ConvertToBool(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support bitwise or",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func logicalAnd(left reflect.Value, right reflect.Value) reflect.Value {
r := ConvertToBool(left) && ConvertToBool(right)
return reflect.ValueOf(r)
}
func logicalOr(left reflect.Value, right reflect.Value) reflect.Value {
r := ConvertToBool(left) || ConvertToBool(right)
return reflect.ValueOf(r)
}
func comparisonEqual(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.String:
if left.Kind() != reflect.String || right.Kind() != reflect.String {
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support comparison equal",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
r := strings.Compare(left.String(), right.String()) == 0
return reflect.ValueOf(r)
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) == ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) == ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) == ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) == ConvertToInt(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support comparison equal",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
}
func comparisonNotEqual(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.String:
if left.Kind() != reflect.String || right.Kind() != reflect.String {
panic(runtimePanic(fmt.Sprintf("%v(%s) and %v(%s) not support comparison equal",
left.Interface(), left.Kind().String(), right.Interface(), right.Kind().String())))
}
r := strings.Compare(left.String(), right.String()) != 0
return reflect.ValueOf(r)
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) != ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) != ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) != ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) != ConvertToInt(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("type %s and %s not support comparison not equal", left.Kind().String(), right.Kind().String())))
}
}
func comparisonGreater(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) > ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) > ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) > ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) > ConvertToInt(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("type %s and %s not support comparison greater", left.Kind().String(), right.Kind().String())))
}
}
func comparisonGreaterOrEqual(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) >= ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) >= ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) >= ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) >= ConvertToInt(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("type %s and %s not support comparison greater or equal", left.Kind().String(), right.Kind().String())))
}
}
func comparisonLess(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) < ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) < ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) < ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) < ConvertToInt(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("type %s and %s not support comparison less", left.Kind().String(), right.Kind().String())))
}
}
func comparisonLessOrEqual(left reflect.Value, right reflect.Value) reflect.Value {
k := typeAscend(left.Kind(), right.Kind())
switch k {
case reflect.Float32, reflect.Float64:
r := ConvertToFloat(left) <= ConvertToFloat(right)
return reflect.ValueOf(r)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
r := ConvertToUint(left) <= ConvertToUint(right)
return reflect.ValueOf(r)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
r := ConvertToInt(left) <= ConvertToInt(right)
return reflect.ValueOf(r)
case reflect.Bool:
r := ConvertToInt(left) <= ConvertToInt(right)
return reflect.ValueOf(r)
default:
panic(runtimePanic(fmt.Sprintf("type %s and %s not support comparison less or equal", left.Kind().String(), right.Kind().String())))
}
} | app/service/live/zeus/expr/eval.go | 0.557604 | 0.451629 | eval.go | starcoder |
package jptime
import "time"
// A JpTime represents an instant in japanese time.
type JpTime struct {
time.Time
}
// NewJpTime returns JpTime.
func NewJpTime(t time.Time) JpTime {
return JpTime{t.In(time.FixedZone("Asia/Tokyo", 9*60*60))}
}
var chineseNumerals = [...]rune{
'〇',
'一',
'二',
'三',
'四',
'五',
'六',
'七',
'八',
'九',
}
var digitChineseNumerals = [...]rune{
'一',
'十',
'百',
'千',
'万',
}
// FmtInt returns 数字(記数法)[0<].
func FmtInt(i int) string {
buf := make([]rune, 0, 10)
for i > 0 {
buf = append(buf, rune(i%10)+'0')
i /= 10
}
return string(reverseRune(buf))
}
// FmtIntKanji returns 漢数字(記数法)[0<]
func FmtIntKanji(i int) string {
buf := make([]rune, 0, 10)
for i > 0 {
buf = append(buf, chineseNumerals[i%10])
i /= 10
}
return string(reverseRune(buf))
}
// FmtIntKanjiMeisuu returns 漢数字(命数法)[0, 99999]
func FmtIntKanjiMeisuu(i int) string {
if i < 0 || i >= 100000 {
return ""
}
if i == 0 {
return "零"
}
buf := make([]rune, 0, 10)
for digit := 0; i > 0; digit++ {
if digit > 0 && i%10 > 0 {
buf = append(buf, digitChineseNumerals[digit])
}
if (digit == 0 && i%10 > 0) || i%10 > 1 {
buf = append(buf, chineseNumerals[i%10])
}
i /= 10
}
return string(reverseRune(buf))
}
func reverseRune(runes []rune) []rune {
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return runes
}
// A JpYear specifies a year.
type JpYear int
// JpYear returns the year specifies by t.
func (t JpTime) JpYear() JpYear { return JpYear(int(t.Year())) }
func (y JpYear) String() string {
year := int(y)
if year <= 0 {
return "紀元前" + FmtIntKanji(1-year) + "年"
}
return FmtIntKanji(year) + "年"
}
// A JpMonth specifies a month of the year.
type JpMonth int
// JpMonth returns the month of the year specifies by t.
func (t JpTime) JpMonth() JpMonth { return JpMonth(int(t.Month())) }
func (m JpMonth) String() string { return FmtIntKanjiMeisuu(int(m)) + "月" }
var jpdays = [...]string{
"日",
"月",
"火",
"水",
"木",
"金",
"土",
}
// A JpWeekday specifies a day of the week.
type JpWeekday int
// JpWeekday returns the day of the week specifies by t.
func (t JpTime) JpWeekday() JpWeekday { return JpWeekday(int(t.Weekday())) }
func (w JpWeekday) String() string { return jpdays[int(w)] }
// A JpDay specifies a day.
type JpDay int
// JpDay returns the day specifies by t.
func (t JpTime) JpDay() JpDay { return JpDay(t.Day()) }
func (d JpDay) String() string { return FmtIntKanjiMeisuu(int(d)) + "日" }
// A JpHour specifies a hour of the day.
type JpHour int
// JpHour returns the hour within the day specifies by t, in the range [0, 23].
func (t JpTime) JpHour() JpHour { return JpHour(t.Hour()) }
func (h JpHour) String() string { return FmtIntKanjiMeisuu(int(h)) + "時" }
// A JpMinute specifies a minute of the hour.
type JpMinute int
// JpMinute returns the minute offset within the hour specifies by t, in the range [0, 59].
func (t JpTime) JpMinute() JpMinute { return JpMinute(t.Minute()) }
func (m JpMinute) String() string { return FmtIntKanjiMeisuu(int(m)) + "分" }
// A JpSecond specifies a second of the minute.
type JpSecond int
// JpSecond returns the second offset within the minute specifies by t, in the range [0, 59].
func (t JpTime) JpSecond() JpSecond { return JpSecond(t.Second()) }
func (s JpSecond) String() string { return FmtIntKanjiMeisuu(int(s)) + "秒" }
var kyuurekimonths = [...]string{
"睦月",
"如月",
"弥生",
"卯月",
"皐月",
"水無月",
"文月",
"葉月",
"長月",
"神無月",
"霜月",
"師走",
}
// KyuurekiMonth returns 月(旧暦).
func (t JpTime) KyuurekiMonth() string { return kyuurekimonths[t.Month()-1] }
// A Wareki specifies a month of the year in wareki.
type Wareki int
// These are predefined wareki.
const (
Kigenzen Wareki = iota
Seireki
Meiji
Taisho
Showa
Heisei
)
type jpTimeWareki struct {
name string
initial string
start time.Time
}
var wareki = [...]jpTimeWareki{
{name: "紀元前", initial: "B.C."},
{name: "西暦", initial: "A.D.", start: time.Date(1, time.January, 1, 0, 0, 0, 0, time.Local)},
{name: "明治", initial: "M", start: time.Date(1873, time.January, 1, 0, 0, 0, 0, time.Local)},
{name: "大正", initial: "T", start: time.Date(1912, time.July, 30, 0, 0, 0, 0, time.Local)},
{name: "昭和", initial: "S", start: time.Date(1926, time.December, 25, 0, 0, 0, 0, time.Local)},
{name: "平成", initial: "H", start: time.Date(1989, time.January, 8, 0, 0, 0, 0, time.Local)},
}
// Wareki returns 和暦.
func (t JpTime) Wareki() (string, string, int) {
var name, initial string
var year int
for i, w := range wareki {
if (Wareki(i) == Kigenzen || t.After(w.start) || t.Equal(w.start)) &&
(Wareki(i) == Heisei || t.Before(wareki[i+1].start)) {
name = w.name
initial = w.initial
switch Wareki(i) {
case Kigenzen:
year = 1 - t.Year()
case Meiji:
// 明治6年からグレゴリオ暦採用のため
year = t.Year() - w.start.Year() + 5 + 1
default:
year = t.Year() - w.start.Year() + 1
}
break
}
}
return name, initial, year
}
var eto = [...]string{
"子",
"丑",
"寅",
"卯",
"辰",
"巳",
"午",
"未",
"申",
"酉",
"戌",
"亥",
}
// Eto returns 干支.
func (t JpTime) Eto() string { return eto[(t.Year()+8)%12] }
// Sekku returns 節句.
func (t JpTime) Sekku() (bool, string, string) {
switch t.Month() {
case time.January:
if t.Day() == 7 {
return true, "人日", "七草の節句"
}
case time.March:
if t.Day() == 3 {
return true, "上巳", "桃の節句"
}
case time.May:
if t.Day() == 5 {
return true, "端午", "菖蒲の節句"
}
case time.July:
if t.Day() == 7 {
return true, "七夕", "笹の節句"
}
case time.September:
if t.Day() == 9 {
return true, "重陽", "菊の節句"
}
}
return false, "", ""
}
// http://www.h3.dion.ne.jp/~sakatsu/sekki24_topic.htm
type jpTimeSekki24 struct {
name string
month time.Month
d float64
a float64
}
var sekki24 = [...]jpTimeSekki24{
{"小寒", time.January, 6.3811, 0.242778},
{"大寒", time.January, 21.1046, 0.242765},
{"立春", time.February, 4.8693, 0.242713},
{"雨水", time.February, 19.7062, 0.242627},
{"啓蟄", time.March, 6.3968, 0.242512},
{"春分", time.March, 21.4471, 0.242377},
{"清明", time.April, 5.6280, 0.242231},
{"穀雨", time.April, 20.9375, 0.242083},
{"立夏", time.May, 6.3771, 0.241945},
{"小満", time.May, 21.9300, 0.241825},
{"芒種", time.June, 6.5733, 0.241731},
{"夏至", time.June, 22.2747, 0.241669},
{"小暑", time.July, 8.0091, 0.241642},
{"大暑", time.July, 23.7317, 0.241654},
{"立秋", time.August, 8.4102, 0.241703},
{"処暑", time.August, 24.0125, 0.241786},
{"白露", time.September, 8.5186, 0.241898},
{"秋分", time.September, 23.8896, 0.242032},
{"寒露", time.October, 9.1414, 0.242179},
{"霜降", time.October, 24.2487, 0.242328},
{"立冬", time.November, 8.2396, 0.242469},
{"小雪", time.November, 23.1189, 0.242592},
{"大雪", time.December, 7.9152, 0.242689},
{"冬至", time.December, 22.6587, 0.242752},
}
// Sekki24 returns 二十四節気.
func (t JpTime) Sekki24() (bool, string) {
year := t.Year()
if year >= 2100 {
return false, ""
}
if t.Month() == time.January || t.Month() == time.February {
year--
}
for _, s := range sekki24 {
if t.Month() == s.month && t.Day() == int(s.d+s.a*float64(year-1900)-float64(int((year-1900)/4))) {
return true, s.name
}
}
return false, ""
}
// Holiday returns 祝日名
func (t JpTime) Holiday() (bool, string) {
isHoliday, holidayName := t.holiday()
if !isHoliday {
isHoliday, holidayName = t.furikaeHoliday()
if !isHoliday {
isHoliday, holidayName = t.kokuminHoliday()
}
}
return isHoliday, holidayName
}
// 祝日名.
func (t JpTime) holiday() (bool, string) {
if t.Year() < 1948 {
return false, ""
}
switch t.Month() {
case time.January:
if t.Day() == 1 {
return true, "元日"
} else if (t.Year() >= 2000 && t.happyMonday(2)) || (t.Year() < 2000 && t.Day() == 15) {
return true, "成人の日"
}
case time.February:
if t.Day() == 11 {
return true, "建国記念の日"
}
case time.March:
if _, sekki := t.Sekki24(); sekki == "春分" {
return true, "春分の日"
}
case time.April:
if t.Day() == 29 {
if t.Year() >= 2007 {
return true, "昭和の日"
} else if t.Year() >= 1989 {
return true, "みどりの日"
} else {
return true, "天皇誕生日"
}
}
case time.May:
if t.Day() == 3 {
return true, "憲法記念日"
} else if t.Year() >= 2007 && t.Day() == 4 {
return true, "みどりの日"
} else if t.Day() == 5 {
return true, "こどもの日"
}
case time.June:
case time.July:
if (t.Year() >= 2003 && t.happyMonday(3)) || (t.Year() < 2003 && t.Year() >= 1995 && t.Day() == 20) {
return true, "海の日"
}
case time.August:
if t.Year() >= 2016 && t.Day() == 11 {
return true, "山の日"
}
case time.September:
if (t.Year() >= 2003 && t.happyMonday(3)) || (t.Year() < 2003 && t.Year() >= 1966 && t.Day() == 15) {
return true, "敬老の日"
} else if _, sekki := t.Sekki24(); sekki == "秋分" {
return true, "秋分の日"
}
case time.October:
if (t.Year() >= 2003 && t.happyMonday(2)) || (t.Year() < 2003 && t.Year() >= 1966 && t.Day() == 10) {
return true, "体育の日"
}
case time.November:
if t.Day() == 3 {
return true, "文化の日"
} else if t.Day() == 23 {
return true, "勤労感謝の日"
}
case time.December:
if t.Year() >= 1989 && t.Day() == 23 {
return true, "天皇誕生日"
}
}
return false, ""
}
// ハッピーマンデー.
func (t JpTime) happyMonday(wnum int) bool {
if t.Weekday() == time.Monday && t.weekNumber() == wnum {
return true
}
return false
}
// 何週目.
func (t JpTime) weekNumber() int {
return ((t.Day() - 1) / 7) + 1
}
// 振替休日.
func (t JpTime) furikaeHoliday() (bool, string) {
if t.Year() < 1973 || t.Weekday() == time.Sunday {
return false, ""
}
for i := 1; i <= 5; i++ {
prevday := NewJpTime(t.AddDate(0, 0, -i))
if isHoliday, _ := prevday.holiday(); isHoliday {
if prevday.Weekday() == time.Sunday {
return true, "振替休日"
} else if t.Year() < 2007 {
// 2007年までは前日のみチェック
break
}
} else {
break
}
}
return false, ""
}
// 国民の休日.
func (t JpTime) kokuminHoliday() (bool, string) {
if t.Year() < 1988 || t.Weekday() == time.Sunday {
return false, ""
}
if yIsHoliday, _ := NewJpTime(t.AddDate(0, 0, -1)).holiday(); yIsHoliday {
if tIsholiday, _ := NewJpTime(t.AddDate(0, 0, 1)).holiday(); tIsholiday {
return true, "国民の休日"
}
}
return false, ""
} | jptime.go | 0.606149 | 0.419648 | jptime.go | starcoder |
package smoothspline
import (
"fmt"
"github.com/helloworldpark/gonaturalspline/bspline"
"gonum.org/v1/gonum/mat"
)
type SmoothSolver struct {
bSpline bspline.BSpline
bRegressionMat *mat.Dense
bSolvedMat *mat.Dense
bPenaltyMat *mat.Dense // scale by lambda at calculation
lambda float64
}
func NewSmoothSolver(spline bspline.BSpline, lambda float64) *SmoothSolver {
return &SmoothSolver{
bSpline: spline,
lambda: lambda,
}
}
func (solver *SmoothSolver) calcRegressionMatrix() {
order := solver.bSpline.Order()
N := solver.bSpline.Knots().Count() / 3
B := mat.NewDense(N, N+order+1, nil)
for i := 0; i < N; i++ {
x := solver.bSpline.Knots().At(i * 3)
for j := 0; j < N+order+1; j++ {
v := solver.bSpline.GetBSpline(j).Evaluate(x)
B.Set(i, j, v)
}
}
solver.bRegressionMat = B
}
func (solver *SmoothSolver) RegressionMatrix() *mat.Dense {
if solver.bRegressionMat == nil {
return nil
}
regMat := mat.NewDense(solver.bRegressionMat.RawMatrix().Rows, solver.bRegressionMat.RawMatrix().Cols, nil)
_, _ = regMat.Copy(solver.bRegressionMat)
return regMat
}
func (solver *SmoothSolver) calcCholesky() {
regMat := solver.bRegressionMat
cols := regMat.RawMatrix().Cols
btb := mat.NewDense(cols, cols, nil)
btb.Mul(regMat.T(), regMat)
if solver.bPenaltyMat != nil {
btb.Add(btb, solver.bPenaltyMat)
}
btbSym := mat.NewSymDense(cols, btb.RawMatrix().Data)
r, c := btbSym.Dims()
fmt.Printf("BTB: %dx%d \n%0.2v\n", r, c, mat.Formatted(btbSym))
var eigsym mat.EigenSym
ok := eigsym.Factorize(btbSym, true)
if !ok {
fmt.Println("Eigendecomposition failed")
}
fmt.Printf("Eigenvalues of A:\n%f\n\n", eigsym.Values(nil))
var chol mat.Cholesky
if ok := chol.Factorize(btbSym); !ok {
panic(">>>>>>>>>>")
}
L := mat.NewTriDense(cols, mat.Lower, nil)
chol.LTo(L)
L.InverseTri(L)
btb.Mul(L, regMat.T())
L.InverseTri(L)
btb.Mul(L, btb)
solver.bSolvedMat = btb
}
func (solver *SmoothSolver) SolverMatrix() *mat.Dense {
if solver.bSolvedMat == nil {
return nil
}
solMat := mat.NewDense(solver.bSolvedMat.RawMatrix().Rows, solver.bSolvedMat.RawMatrix().Cols, nil)
_, _ = solMat.Copy(solver.bSolvedMat)
return solMat
} | smoothspline/smoothSolver.go | 0.642657 | 0.414543 | smoothSolver.go | starcoder |
package activityrings
import (
"image/color"
"io"
"math"
"github.com/fogleman/gg"
"github.com/lucasb-eyer/go-colorful"
)
// ActivityType is a type that represents one of the rings
type ActivityType int
const (
// Stand is the activity type for the Apple Watch stand goal
Stand ActivityType = iota
// Exercise is the activity type for the exercise goal on the Apple Watch Activity app
Exercise
// Move is the activity type for the Move goal on the Apple Watch
Move
)
const (
// TODO: All of these values should be a function of the actual image size. right now they are appropriate for the size in the example cmd/activity/main.go
lineWidth = 86.0
ringPadding = 6.0
innerCircle = 115.0
)
// Inactive ring colors
var (
InactiveRed = color.RGBA{30, 1, 3, 255}
InactiveGreen = color.RGBA{14, 32, 3, 255}
InactiveBlue = color.RGBA{6, 27, 33, 255}
)
// Active starting colors
var (
// Credit to the MKRingProgressView Example project
RedStart = colorful.Color{R: 0.8823529412, G: 0, B: 0.07843137255}
RedEnd = colorful.Color{R: 1, G: 0.1960784314, B: 0.5294117647}
GreenStart = colorful.Color{R: 0.2156862745, G: 0.862745098, B: 0}
GreenEnd = colorful.Color{R: 0.7176470588, G: 1, B: 0}
BlueStart = colorful.Color{R: 0, G: 0.7294117647, B: 0.8823529412}
BlueEnd = colorful.Color{R: 0, G: 0.9803921569, B: 0.8156862745}
)
// ActivityRing represents the data needed to draw a single activity ring including the type of activity
// it represents and the colors needed to do the drawing.
type ActivityRing struct {
radius float64
inactiveColor color.RGBA
startColor colorful.Color
endColor colorful.Color
ActivityType
}
// ActivityRingsImage is a representation of a collection of activity rings that can be drawn.
type ActivityRingsImage struct {
ctx *gg.Context
backgroundColor color.Color
center float64
lineWidth float64
ringPadding float64
innerCircleRadius float64
rings map[ActivityType]*ActivityRing
}
// NewActivityRingsImage is a convenience method for creating a new ActivityRingsImage with the provided background color and full image size.
// The drawn image will be a square using the imgSize parameter.
func NewActivityRingsImage(imgSize int, bgColor color.Color) *ActivityRingsImage {
radius := innerCircle + (lineWidth / 2.0)
standRing := &ActivityRing{radius: radius, inactiveColor: InactiveBlue, startColor: BlueStart, endColor: BlueEnd, ActivityType: Stand}
radius += lineWidth + ringPadding
exerciseRing := &ActivityRing{radius: radius, inactiveColor: InactiveGreen, startColor: GreenStart, endColor: GreenEnd, ActivityType: Exercise}
radius += lineWidth + ringPadding
moveRing := &ActivityRing{radius: radius, inactiveColor: InactiveRed, startColor: RedStart, endColor: RedEnd, ActivityType: Move}
context := gg.NewContext(imgSize, imgSize)
context.SetLineCapRound()
context.SetLineWidth(lineWidth)
img := &ActivityRingsImage{
ctx: context,
center: float64(imgSize) / 2.0,
backgroundColor: bgColor,
lineWidth: lineWidth,
ringPadding: ringPadding,
innerCircleRadius: innerCircle,
rings: map[ActivityType]*ActivityRing{Stand: standRing, Exercise: exerciseRing, Move: moveRing},
}
img.drawEmptyActivityRings()
return img
}
func (img *ActivityRingsImage) drawEmptyActivityRings() {
img.ctx.SetColor(img.backgroundColor)
img.ctx.DrawRectangle(0, 0, float64(img.ctx.Width()), float64(img.ctx.Height()))
img.ctx.Fill()
for _, ring := range img.rings {
img.ctx.SetStrokeStyle(gg.NewSolidPattern(ring.inactiveColor))
img.ctx.DrawArc(img.center, img.center, ring.radius, 0, 2*math.Pi)
img.ctx.Stroke()
}
}
// DrawActivity is the main method for drawing a set of activity values. If an unrecognized activity type is provided, it is ignored. The activity
// values should represent a fraction of the activity goal completed. A value of 1.0 means the activity goal is met exactly, 2.0 means the activity is double the goal.
func (img *ActivityRingsImage) DrawActivity(values map[ActivityType]float64) {
// TODO: This parameter could be expanded to allow an arbitrary number of rings? or possibly a mapping of ActivityTypes to values.
for t, v := range values {
if ring, ok := img.rings[t]; ok {
img.drawActivityValue(ring, v)
}
}
}
func (img *ActivityRingsImage) drawActivityValue(ring *ActivityRing, value float64) {
// TODO: This probably needs a special case for value == 0.0, should probably just draw a circle at the top with the active starting color fill
startValue := value
direction := topDownDirection
startColor := ring.startColor
needsShadow := false
if value >= 1.0 {
needsShadow = true
}
currentValue := 0.0
for {
if value <= 0.0 {
break
}
startRadians := -0.5 * math.Pi
if direction == bottomUpDirection {
startRadians = 0.5 * math.Pi
}
if needsShadow && value <= 0.5 {
angle := (startValue * (2.0 * math.Pi)) - (0.5 * math.Pi) + (0.01 * math.Pi)
img.drawShadow(angle, ring.radius)
}
// Draw either the current value or a full half circle segment, which ever is smaller
segmentValue := math.Min(value, 0.5)
endRadians := ((segmentValue / 0.5) * math.Pi) + startRadians
currentValue += segmentValue
stopColor := NextColor(ring.startColor, ring.endColor, currentValue/startValue)
grad := newRingGradient(img.center, direction, startColor, stopColor, ring.radius)
img.ctx.SetStrokeStyle(grad)
img.ctx.DrawArc(img.center, img.center, ring.radius, startRadians, endRadians)
img.ctx.Stroke()
value -= 0.5
direction = direction.flip()
startColor = stopColor
}
}
func (img *ActivityRingsImage) drawShadow(angle, radius float64) {
x, y := arcEnd(angle, radius, img.center)
grad := gg.NewRadialGradient(x, y, (img.lineWidth/2.0)-11, x, y, (img.lineWidth / 2.0))
grad.AddColorStop(0.0, color.RGBA{0, 0, 0, 255})
grad.AddColorStop(1.0, color.RGBA{0, 0, 0, 10})
img.ctx.SetFillStyle(grad)
img.ctx.DrawCircle(x, y, (img.lineWidth / 2.0))
img.ctx.Fill()
}
func arcEnd(angle, radius, center float64) (float64, float64) {
x := center + radius*math.Cos(angle)
y := center + radius*math.Sin(angle)
return x, y
}
// SavePNG will write the activity rings image to the provided path, returning an error if the write operation fails.
func (img *ActivityRingsImage) SavePNG(path string) error {
return img.ctx.SavePNG(path)
}
// EncodePNG will write the rings activity image to the provided Writer as a PNG.
func (img *ActivityRingsImage) EncodePNG(w io.Writer) error {
return img.ctx.EncodePNG(w)
} | activity-rings.go | 0.60288 | 0.434911 | activity-rings.go | starcoder |
package trisnake
import (
"fmt"
tl "github.com/JoelOtter/termloop"
tb "github.com/nsf/termbox-go"
)
var counterSnake = 10
var counterArena = 10
// Tick listens for a keypress and then returns a direction for the snake.
func (snake *Snake) Tick(event tl.Event) {
// Checks if the event is a keyevent.
if event.Type == tl.EventKey {
switch event.Key {
// Checks if the key is a → press.
case tl.KeyArrowRight:
// Check if the direction is not opposite to the current direction.
if snake.Direction != left {
// Changes the direction of the snake to right.
snake.Direction = right
}
// Checks if the key is a ← press.
case tl.KeyArrowLeft:
// Check if the direction is not opposite to the current direction.
if snake.Direction != right {
// Changes the direction of the snake to left.
snake.Direction = left
}
// Checks if the key is a ↑ press.
case tl.KeyArrowUp:
// Check if the direction is not opposite to the current direction.
if snake.Direction != down {
// Changes the direction of the snake to down.
snake.Direction = up
}
// Checks if the key is a ↓ press.
case tl.KeyArrowDown:
// Check if the direction is not opposite to the current direction.
if snake.Direction != up {
// Changes the direction of the snake to up.
snake.Direction = down
}
}
}
}
// Tick is a method for the gameoverscreen which listens for either a restart or a quit input from the user.
func (gos *Gameoverscreen) Tick(event tl.Event) {
// Check if the event is a key event.
if event.Type == tl.EventKey {
switch event.Key {
// If the key pressed is backspace the game will restart!!
case tl.KeyHome:
// Will call the RestartGame function to restart the game.
RestartGame()
case tl.KeyDelete:
// Will end the game using a fatal log. This uses the termbox package as termloop does not have a function like that.
tb.Close()
case tl.KeySpace:
SaveHighScore(gs.Score, gs.FPS, Difficulty)
}
}
}
// Tick will listen for a keypress to initiate the game.
func (ts *Titlescreen) Tick(event tl.Event) {
// Checks if the event is a keypress event and the key pressed is the enter key.
if event.Type == tl.EventKey {
if event.Key == tl.KeyEnter {
gs = NewGamescreen()
sg.Screen().SetLevel(gs)
}
if event.Key == tl.KeyInsert {
gop := NewOptionsscreen()
sg.Screen().SetLevel(gop)
}
}
}
// Tick will listen for a keypress to initiate the game.
func (g *Gameoptionsscreen) Tick(event tl.Event) {
// Checks if the event is a keypress event.
if event.Type == tl.EventKey {
switch event.Key {
case tl.KeyF1:
ts.GameDifficulty = easy
Difficulty = "Easy"
gop.CurrentDifficultyText.SetText(fmt.Sprintf("Current difficulty: %s", Difficulty))
case tl.KeyF2:
ts.GameDifficulty = normal
Difficulty = "Normal"
gop.CurrentDifficultyText.SetText(fmt.Sprintf("Current difficulty: %s", Difficulty))
case tl.KeyArrowUp:
switch ColorObject {
case "Snake":
if counterSnake <= 10 {
return
}
counterSnake -= 2
gop.ColorSelectedIcon.SetPosition(73, counterSnake)
case "Arena":
if counterArena <= 10 {
return
}
counterArena -= 2
gop.ColorSelectedIcon.SetPosition(73, counterArena)
}
case tl.KeyArrowDown:
switch ColorObject {
case "Snake":
if counterSnake >= 22 {
return
}
counterSnake += 2
gop.ColorSelectedIcon.SetPosition(73, counterSnake)
case "Arena":
if counterArena >= 22 {
return
}
counterArena += 2
gop.ColorSelectedIcon.SetPosition(73, counterArena)
}
case tl.KeyF3:
ts.GameDifficulty = hard
Difficulty = "Hard"
gop.CurrentDifficultyText.SetText(fmt.Sprintf("Current difficulty: %s", Difficulty))
case tl.KeyF4:
ColorObject = "Snake"
gop.CurrentColorObjectText.SetText(fmt.Sprintf("Current object: %s", ColorObject))
case tl.KeyF5:
ColorObject = "Food"
gop.CurrentColorObjectText.SetText(fmt.Sprintf("Current object: %s", ColorObject))
case tl.KeyF6:
ColorObject = "Arena"
gop.CurrentColorObjectText.SetText(fmt.Sprintf("Current object: %s", ColorObject))
case tl.KeyEnter:
gs = NewGamescreen()
sg.Screen().SetLevel(gs)
}
}
}
func CheckSelectedColor(c int) tl.Attr {
switch c {
case 10:
return tl.ColorWhite
case 12:
return tl.ColorRed
case 14:
return tl.ColorGreen
case 16:
return tl.ColorBlue
case 18:
return tl.ColorYellow
case 20:
return tl.ColorMagenta
case 22:
return tl.ColorCyan
default:
return tl.ColorDefault
}
} | game/keyinput.go | 0.625896 | 0.40157 | keyinput.go | starcoder |
package gomeasure
import (
"fmt"
"time"
)
// Stats holds the cumulative statistics for an action. All recorded samples for
// that action contribute to the stats figures. Once captures a set of stats
// will not be updated by the action is represents.
type Stats struct {
// Action is the name of the action the stats relate to.
Action string `json:"action"`
// Created is the timestamp when this set of stats was taken.
Created time.Time `json:"created"`
// Min is the shortest duration taken to perform the action. If no
// samples have been recorded then the duration will be 0.
Min time.Duration `json:"min"`
// Max is the longest duration taken to perform the action. If no samples
// have been recorded then the duration will be 0.
Max time.Duration `json:"max"`
// Mean is the average duration taken to perform the action. If no samples
// have been recorded then the duration will be 0.
Mean time.Duration `json:"mean"`
// Sigma is the standard deviation of durations for this action. If no
// samples have been recorded the duration will be 0, however, it is also
// possible to have a variance of 0 if actions have be recorded, but with no
// variance.
Sigma time.Duration `json:"s"`
// Total is the cumulative duration spent performing this action. If
// no samples have been recorded then the duration will be 0.
Total time.Duration `json:"total"`
// Samples is the total number of timings that have been recorded against
// this action.
Samples int `json:"samples"`
}
const format = "Action: %s [Min: %s, Max: %s, Mean: %s, Sigma: %s, " +
"Total: %s, Samples: %d], recorded at %s"
// EmptyStats returns a new, empty set of stats for the given action with all
// values zeroed, and the current time as the created time.
func EmptyStats(action string) Stats {
return Stats{Action: action, Created: time.Now()}
}
// String returns the stats as a human readable string.
func (s Stats) String() string {
return fmt.Sprintf(format, s.Action, s.Min, s.Max, s.Mean, s.Sigma,
s.Total, s.Samples, s.Created)
} | stats.go | 0.747432 | 0.432303 | stats.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// EntitlementManagement
type EntitlementManagement struct {
Entity
// Approval stages for assignment requests.
accessPackageAssignmentApprovals []Approvalable
// Represents access package objects.
accessPackages []AccessPackageable
// Access package assignment policies.
assignmentPolicies []AccessPackageAssignmentPolicyable
// Represents access package assignment requests created by or on behalf of a user.
assignmentRequests []AccessPackageAssignmentRequestable
// Represents the grant of an access package to a subject (user or group).
assignments []AccessPackageAssignmentable
// Represents a collection of access packages.
catalogs []AccessPackageCatalogable
// Represents references to a directory or domain of another organization whose users can request access.
connectedOrganizations []ConnectedOrganizationable
// Represents the settings that control the behavior of Azure AD entitlement management.
settings EntitlementManagementSettingsable
}
// NewEntitlementManagement instantiates a new entitlementManagement and sets the default values.
func NewEntitlementManagement()(*EntitlementManagement) {
m := &EntitlementManagement{
Entity: *NewEntity(),
}
return m
}
// CreateEntitlementManagementFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateEntitlementManagementFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewEntitlementManagement(), nil
}
// GetAccessPackageAssignmentApprovals gets the accessPackageAssignmentApprovals property value. Approval stages for assignment requests.
func (m *EntitlementManagement) GetAccessPackageAssignmentApprovals()([]Approvalable) {
if m == nil {
return nil
} else {
return m.accessPackageAssignmentApprovals
}
}
// GetAccessPackages gets the accessPackages property value. Represents access package objects.
func (m *EntitlementManagement) GetAccessPackages()([]AccessPackageable) {
if m == nil {
return nil
} else {
return m.accessPackages
}
}
// GetAssignmentPolicies gets the assignmentPolicies property value. Access package assignment policies.
func (m *EntitlementManagement) GetAssignmentPolicies()([]AccessPackageAssignmentPolicyable) {
if m == nil {
return nil
} else {
return m.assignmentPolicies
}
}
// GetAssignmentRequests gets the assignmentRequests property value. Represents access package assignment requests created by or on behalf of a user.
func (m *EntitlementManagement) GetAssignmentRequests()([]AccessPackageAssignmentRequestable) {
if m == nil {
return nil
} else {
return m.assignmentRequests
}
}
// GetAssignments gets the assignments property value. Represents the grant of an access package to a subject (user or group).
func (m *EntitlementManagement) GetAssignments()([]AccessPackageAssignmentable) {
if m == nil {
return nil
} else {
return m.assignments
}
}
// GetCatalogs gets the catalogs property value. Represents a collection of access packages.
func (m *EntitlementManagement) GetCatalogs()([]AccessPackageCatalogable) {
if m == nil {
return nil
} else {
return m.catalogs
}
}
// GetConnectedOrganizations gets the connectedOrganizations property value. Represents references to a directory or domain of another organization whose users can request access.
func (m *EntitlementManagement) GetConnectedOrganizations()([]ConnectedOrganizationable) {
if m == nil {
return nil
} else {
return m.connectedOrganizations
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *EntitlementManagement) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["accessPackageAssignmentApprovals"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateApprovalFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]Approvalable, len(val))
for i, v := range val {
res[i] = v.(Approvalable)
}
m.SetAccessPackageAssignmentApprovals(res)
}
return nil
}
res["accessPackages"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAccessPackageFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AccessPackageable, len(val))
for i, v := range val {
res[i] = v.(AccessPackageable)
}
m.SetAccessPackages(res)
}
return nil
}
res["assignmentPolicies"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAccessPackageAssignmentPolicyFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AccessPackageAssignmentPolicyable, len(val))
for i, v := range val {
res[i] = v.(AccessPackageAssignmentPolicyable)
}
m.SetAssignmentPolicies(res)
}
return nil
}
res["assignmentRequests"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAccessPackageAssignmentRequestFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AccessPackageAssignmentRequestable, len(val))
for i, v := range val {
res[i] = v.(AccessPackageAssignmentRequestable)
}
m.SetAssignmentRequests(res)
}
return nil
}
res["assignments"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAccessPackageAssignmentFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AccessPackageAssignmentable, len(val))
for i, v := range val {
res[i] = v.(AccessPackageAssignmentable)
}
m.SetAssignments(res)
}
return nil
}
res["catalogs"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAccessPackageCatalogFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AccessPackageCatalogable, len(val))
for i, v := range val {
res[i] = v.(AccessPackageCatalogable)
}
m.SetCatalogs(res)
}
return nil
}
res["connectedOrganizations"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateConnectedOrganizationFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]ConnectedOrganizationable, len(val))
for i, v := range val {
res[i] = v.(ConnectedOrganizationable)
}
m.SetConnectedOrganizations(res)
}
return nil
}
res["settings"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateEntitlementManagementSettingsFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetSettings(val.(EntitlementManagementSettingsable))
}
return nil
}
return res
}
// GetSettings gets the settings property value. Represents the settings that control the behavior of Azure AD entitlement management.
func (m *EntitlementManagement) GetSettings()(EntitlementManagementSettingsable) {
if m == nil {
return nil
} else {
return m.settings
}
}
// Serialize serializes information the current object
func (m *EntitlementManagement) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
if m.GetAccessPackageAssignmentApprovals() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAccessPackageAssignmentApprovals()))
for i, v := range m.GetAccessPackageAssignmentApprovals() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("accessPackageAssignmentApprovals", cast)
if err != nil {
return err
}
}
if m.GetAccessPackages() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAccessPackages()))
for i, v := range m.GetAccessPackages() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("accessPackages", cast)
if err != nil {
return err
}
}
if m.GetAssignmentPolicies() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAssignmentPolicies()))
for i, v := range m.GetAssignmentPolicies() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("assignmentPolicies", cast)
if err != nil {
return err
}
}
if m.GetAssignmentRequests() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAssignmentRequests()))
for i, v := range m.GetAssignmentRequests() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("assignmentRequests", cast)
if err != nil {
return err
}
}
if m.GetAssignments() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAssignments()))
for i, v := range m.GetAssignments() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("assignments", cast)
if err != nil {
return err
}
}
if m.GetCatalogs() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCatalogs()))
for i, v := range m.GetCatalogs() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("catalogs", cast)
if err != nil {
return err
}
}
if m.GetConnectedOrganizations() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetConnectedOrganizations()))
for i, v := range m.GetConnectedOrganizations() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("connectedOrganizations", cast)
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("settings", m.GetSettings())
if err != nil {
return err
}
}
return nil
}
// SetAccessPackageAssignmentApprovals sets the accessPackageAssignmentApprovals property value. Approval stages for assignment requests.
func (m *EntitlementManagement) SetAccessPackageAssignmentApprovals(value []Approvalable)() {
if m != nil {
m.accessPackageAssignmentApprovals = value
}
}
// SetAccessPackages sets the accessPackages property value. Represents access package objects.
func (m *EntitlementManagement) SetAccessPackages(value []AccessPackageable)() {
if m != nil {
m.accessPackages = value
}
}
// SetAssignmentPolicies sets the assignmentPolicies property value. Access package assignment policies.
func (m *EntitlementManagement) SetAssignmentPolicies(value []AccessPackageAssignmentPolicyable)() {
if m != nil {
m.assignmentPolicies = value
}
}
// SetAssignmentRequests sets the assignmentRequests property value. Represents access package assignment requests created by or on behalf of a user.
func (m *EntitlementManagement) SetAssignmentRequests(value []AccessPackageAssignmentRequestable)() {
if m != nil {
m.assignmentRequests = value
}
}
// SetAssignments sets the assignments property value. Represents the grant of an access package to a subject (user or group).
func (m *EntitlementManagement) SetAssignments(value []AccessPackageAssignmentable)() {
if m != nil {
m.assignments = value
}
}
// SetCatalogs sets the catalogs property value. Represents a collection of access packages.
func (m *EntitlementManagement) SetCatalogs(value []AccessPackageCatalogable)() {
if m != nil {
m.catalogs = value
}
}
// SetConnectedOrganizations sets the connectedOrganizations property value. Represents references to a directory or domain of another organization whose users can request access.
func (m *EntitlementManagement) SetConnectedOrganizations(value []ConnectedOrganizationable)() {
if m != nil {
m.connectedOrganizations = value
}
}
// SetSettings sets the settings property value. Represents the settings that control the behavior of Azure AD entitlement management.
func (m *EntitlementManagement) SetSettings(value EntitlementManagementSettingsable)() {
if m != nil {
m.settings = value
}
} | models/entitlement_management.go | 0.617628 | 0.479199 | entitlement_management.go | starcoder |
package cryptoapis
import (
"encoding/json"
)
// ListTransactionsByBlockHeightRI struct for ListTransactionsByBlockHeightRI
type ListTransactionsByBlockHeightRI struct {
// Represents the index position of the transaction in the specific block.
Index int32 `json:"index"`
// Represents the hash of the block where this transaction was mined/confirmed for first time. The hash is defined as a cryptographic digital fingerprint made by hashing the block header twice through the SHA256 algorithm.
MinedInBlockHash string `json:"minedInBlockHash"`
// Represents the hight of the block where this transaction was mined/confirmed for first time. The height is defined as the number of blocks in the blockchain preceding this specific block.
MinedInBlockHeight int32 `json:"minedInBlockHeight"`
// Represents a list of recipient addresses with the respective amounts. In account-based protocols like Ethereum there is only one address in this list.
Recipients []GetTransactionDetailsByTransactionIDRIRecipients `json:"recipients"`
// Represents a list of sender addresses with the respective amounts. In account-based protocols like Ethereum there is only one address in this list.
Senders []GetTransactionDetailsByTransactionIDRISenders `json:"senders"`
// Defines the exact date/time in Unix Timestamp when this transaction was mined, confirmed or first seen in Mempool, if it is unconfirmed.
Timestamp int32 `json:"timestamp"`
// Represents the same as `transactionId` for account-based protocols like Ethereum, while it could be different in UTXO-based protocols like Bitcoin. E.g., in UTXO-based protocols `hash` is different from `transactionId` for SegWit transactions.
TransactionHash string `json:"transactionHash"`
// Represents the unique identifier of a transaction, i.e. it could be `transactionId` in UTXO-based protocols like Bitcoin, and transaction `hash` in Ethereum blockchain.
TransactionId string `json:"transactionId"`
Fee ListTransactionsByBlockHeightRIFee `json:"fee"`
BlockchainSpecific ListTransactionsByBlockHeightRIBS `json:"blockchainSpecific"`
}
// NewListTransactionsByBlockHeightRI instantiates a new ListTransactionsByBlockHeightRI 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 NewListTransactionsByBlockHeightRI(index int32, minedInBlockHash string, minedInBlockHeight int32, recipients []GetTransactionDetailsByTransactionIDRIRecipients, senders []GetTransactionDetailsByTransactionIDRISenders, timestamp int32, transactionHash string, transactionId string, fee ListTransactionsByBlockHeightRIFee, blockchainSpecific ListTransactionsByBlockHeightRIBS) *ListTransactionsByBlockHeightRI {
this := ListTransactionsByBlockHeightRI{}
this.Index = index
this.MinedInBlockHash = minedInBlockHash
this.MinedInBlockHeight = minedInBlockHeight
this.Recipients = recipients
this.Senders = senders
this.Timestamp = timestamp
this.TransactionHash = transactionHash
this.TransactionId = transactionId
this.Fee = fee
this.BlockchainSpecific = blockchainSpecific
return &this
}
// NewListTransactionsByBlockHeightRIWithDefaults instantiates a new ListTransactionsByBlockHeightRI 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 NewListTransactionsByBlockHeightRIWithDefaults() *ListTransactionsByBlockHeightRI {
this := ListTransactionsByBlockHeightRI{}
return &this
}
// GetIndex returns the Index field value
func (o *ListTransactionsByBlockHeightRI) GetIndex() int32 {
if o == nil {
var ret int32
return ret
}
return o.Index
}
// GetIndexOk returns a tuple with the Index field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetIndexOk() (*int32, bool) {
if o == nil {
return nil, false
}
return &o.Index, true
}
// SetIndex sets field value
func (o *ListTransactionsByBlockHeightRI) SetIndex(v int32) {
o.Index = v
}
// GetMinedInBlockHash returns the MinedInBlockHash field value
func (o *ListTransactionsByBlockHeightRI) GetMinedInBlockHash() string {
if o == nil {
var ret string
return ret
}
return o.MinedInBlockHash
}
// GetMinedInBlockHashOk returns a tuple with the MinedInBlockHash field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetMinedInBlockHashOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.MinedInBlockHash, true
}
// SetMinedInBlockHash sets field value
func (o *ListTransactionsByBlockHeightRI) SetMinedInBlockHash(v string) {
o.MinedInBlockHash = v
}
// GetMinedInBlockHeight returns the MinedInBlockHeight field value
func (o *ListTransactionsByBlockHeightRI) GetMinedInBlockHeight() int32 {
if o == nil {
var ret int32
return ret
}
return o.MinedInBlockHeight
}
// GetMinedInBlockHeightOk returns a tuple with the MinedInBlockHeight field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetMinedInBlockHeightOk() (*int32, bool) {
if o == nil {
return nil, false
}
return &o.MinedInBlockHeight, true
}
// SetMinedInBlockHeight sets field value
func (o *ListTransactionsByBlockHeightRI) SetMinedInBlockHeight(v int32) {
o.MinedInBlockHeight = v
}
// GetRecipients returns the Recipients field value
func (o *ListTransactionsByBlockHeightRI) GetRecipients() []GetTransactionDetailsByTransactionIDRIRecipients {
if o == nil {
var ret []GetTransactionDetailsByTransactionIDRIRecipients
return ret
}
return o.Recipients
}
// GetRecipientsOk returns a tuple with the Recipients field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetRecipientsOk() (*[]GetTransactionDetailsByTransactionIDRIRecipients, bool) {
if o == nil {
return nil, false
}
return &o.Recipients, true
}
// SetRecipients sets field value
func (o *ListTransactionsByBlockHeightRI) SetRecipients(v []GetTransactionDetailsByTransactionIDRIRecipients) {
o.Recipients = v
}
// GetSenders returns the Senders field value
func (o *ListTransactionsByBlockHeightRI) GetSenders() []GetTransactionDetailsByTransactionIDRISenders {
if o == nil {
var ret []GetTransactionDetailsByTransactionIDRISenders
return ret
}
return o.Senders
}
// GetSendersOk returns a tuple with the Senders field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetSendersOk() (*[]GetTransactionDetailsByTransactionIDRISenders, bool) {
if o == nil {
return nil, false
}
return &o.Senders, true
}
// SetSenders sets field value
func (o *ListTransactionsByBlockHeightRI) SetSenders(v []GetTransactionDetailsByTransactionIDRISenders) {
o.Senders = v
}
// GetTimestamp returns the Timestamp field value
func (o *ListTransactionsByBlockHeightRI) GetTimestamp() int32 {
if o == nil {
var ret int32
return ret
}
return o.Timestamp
}
// GetTimestampOk returns a tuple with the Timestamp field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetTimestampOk() (*int32, bool) {
if o == nil {
return nil, false
}
return &o.Timestamp, true
}
// SetTimestamp sets field value
func (o *ListTransactionsByBlockHeightRI) SetTimestamp(v int32) {
o.Timestamp = v
}
// GetTransactionHash returns the TransactionHash field value
func (o *ListTransactionsByBlockHeightRI) GetTransactionHash() string {
if o == nil {
var ret string
return ret
}
return o.TransactionHash
}
// GetTransactionHashOk returns a tuple with the TransactionHash field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetTransactionHashOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.TransactionHash, true
}
// SetTransactionHash sets field value
func (o *ListTransactionsByBlockHeightRI) SetTransactionHash(v string) {
o.TransactionHash = v
}
// GetTransactionId returns the TransactionId field value
func (o *ListTransactionsByBlockHeightRI) GetTransactionId() string {
if o == nil {
var ret string
return ret
}
return o.TransactionId
}
// GetTransactionIdOk returns a tuple with the TransactionId field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetTransactionIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.TransactionId, true
}
// SetTransactionId sets field value
func (o *ListTransactionsByBlockHeightRI) SetTransactionId(v string) {
o.TransactionId = v
}
// GetFee returns the Fee field value
func (o *ListTransactionsByBlockHeightRI) GetFee() ListTransactionsByBlockHeightRIFee {
if o == nil {
var ret ListTransactionsByBlockHeightRIFee
return ret
}
return o.Fee
}
// GetFeeOk returns a tuple with the Fee field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetFeeOk() (*ListTransactionsByBlockHeightRIFee, bool) {
if o == nil {
return nil, false
}
return &o.Fee, true
}
// SetFee sets field value
func (o *ListTransactionsByBlockHeightRI) SetFee(v ListTransactionsByBlockHeightRIFee) {
o.Fee = v
}
// GetBlockchainSpecific returns the BlockchainSpecific field value
func (o *ListTransactionsByBlockHeightRI) GetBlockchainSpecific() ListTransactionsByBlockHeightRIBS {
if o == nil {
var ret ListTransactionsByBlockHeightRIBS
return ret
}
return o.BlockchainSpecific
}
// GetBlockchainSpecificOk returns a tuple with the BlockchainSpecific field value
// and a boolean to check if the value has been set.
func (o *ListTransactionsByBlockHeightRI) GetBlockchainSpecificOk() (*ListTransactionsByBlockHeightRIBS, bool) {
if o == nil {
return nil, false
}
return &o.BlockchainSpecific, true
}
// SetBlockchainSpecific sets field value
func (o *ListTransactionsByBlockHeightRI) SetBlockchainSpecific(v ListTransactionsByBlockHeightRIBS) {
o.BlockchainSpecific = v
}
func (o ListTransactionsByBlockHeightRI) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["index"] = o.Index
}
if true {
toSerialize["minedInBlockHash"] = o.MinedInBlockHash
}
if true {
toSerialize["minedInBlockHeight"] = o.MinedInBlockHeight
}
if true {
toSerialize["recipients"] = o.Recipients
}
if true {
toSerialize["senders"] = o.Senders
}
if true {
toSerialize["timestamp"] = o.Timestamp
}
if true {
toSerialize["transactionHash"] = o.TransactionHash
}
if true {
toSerialize["transactionId"] = o.TransactionId
}
if true {
toSerialize["fee"] = o.Fee
}
if true {
toSerialize["blockchainSpecific"] = o.BlockchainSpecific
}
return json.Marshal(toSerialize)
}
type NullableListTransactionsByBlockHeightRI struct {
value *ListTransactionsByBlockHeightRI
isSet bool
}
func (v NullableListTransactionsByBlockHeightRI) Get() *ListTransactionsByBlockHeightRI {
return v.value
}
func (v *NullableListTransactionsByBlockHeightRI) Set(val *ListTransactionsByBlockHeightRI) {
v.value = val
v.isSet = true
}
func (v NullableListTransactionsByBlockHeightRI) IsSet() bool {
return v.isSet
}
func (v *NullableListTransactionsByBlockHeightRI) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableListTransactionsByBlockHeightRI(val *ListTransactionsByBlockHeightRI) *NullableListTransactionsByBlockHeightRI {
return &NullableListTransactionsByBlockHeightRI{value: val, isSet: true}
}
func (v NullableListTransactionsByBlockHeightRI) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableListTransactionsByBlockHeightRI) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | model_list_transactions_by_block_height_ri.go | 0.87456 | 0.424651 | model_list_transactions_by_block_height_ri.go | starcoder |
package slice
import (
"container/heap"
"fmt"
"sort"
)
// SliceInt type
type SliceInt []int
// Set sets all element to c
func (slice SliceInt) Set(c int) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceInt) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceInt) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceInt) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceInt) Get(i int) int {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceInt) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceInt) Push(c interface{}) {
*slice = append(*slice, c.(int))
}
// Pop element
func (slice *SliceInt) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceInt) Append(values ...int) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceInt) Prepend(values ...int) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceInt) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceInt struct for min heap
type MinHeapSliceInt struct {
Slice *SliceInt
}
// MinHeap returns struct with min heap functionality based on SliceInt
func (slice *SliceInt) MinHeap() MinHeapSliceInt {
hp := MinHeapSliceInt{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceInt) Min() int {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceInt) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceInt) Pop() int {
return heap.Pop(hp.Slice).(int)
}
// Push v to heap
func (hp MinHeapSliceInt) Push(v int) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceInt) Remove(i int) int {
return heap.Remove(hp.Slice, i).(int)
}
// MaxHeapSliceInt struct for max heap
type MaxHeapSliceInt struct {
Slice *SliceInt
}
// MaxHeap returns struct with max heap functionality based on SliceInt
func (slice *SliceInt) MaxHeap() MaxHeapSliceInt {
hp := MaxHeapSliceInt{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceInt) Max() int {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceInt) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceInt) Pop() int {
return heap.Pop(HeapReverse(hp.Slice)).(int)
}
// Push v to heap
func (hp MaxHeapSliceInt) Push(v int) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceInt) Remove(i int) int {
return heap.Remove(HeapReverse(hp.Slice), i).(int)
}
// SliceSliceInt type
type SliceSliceInt []SliceInt
// Set sets all element to c
func (slice SliceSliceInt) Set(c SliceInt) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceSliceInt) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceSliceInt) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceSliceInt) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceSliceInt) Get(i int) SliceInt {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceSliceInt) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceSliceInt) Push(c interface{}) {
*slice = append(*slice, c.(SliceInt))
}
// Pop element
func (slice *SliceSliceInt) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceSliceInt) Append(values ...SliceInt) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceSliceInt) Prepend(values ...SliceInt) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceSliceInt) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceSliceInt struct for min heap
type MinHeapSliceSliceInt struct {
Slice *SliceSliceInt
}
// MinHeap returns struct with min heap functionality based on SliceSliceInt
func (slice *SliceSliceInt) MinHeap() MinHeapSliceSliceInt {
hp := MinHeapSliceSliceInt{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceSliceInt) Min() SliceInt {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceSliceInt) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceSliceInt) Pop() SliceInt {
return heap.Pop(hp.Slice).(SliceInt)
}
// Push v to heap
func (hp MinHeapSliceSliceInt) Push(v SliceInt) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceSliceInt) Remove(i int) SliceInt {
return heap.Remove(hp.Slice, i).(SliceInt)
}
// MaxHeapSliceSliceInt struct for max heap
type MaxHeapSliceSliceInt struct {
Slice *SliceSliceInt
}
// MaxHeap returns struct with max heap functionality based on SliceSliceInt
func (slice *SliceSliceInt) MaxHeap() MaxHeapSliceSliceInt {
hp := MaxHeapSliceSliceInt{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceSliceInt) Max() SliceInt {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceSliceInt) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceSliceInt) Pop() SliceInt {
return heap.Pop(HeapReverse(hp.Slice)).(SliceInt)
}
// Push v to heap
func (hp MaxHeapSliceSliceInt) Push(v SliceInt) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceSliceInt) Remove(i int) SliceInt {
return heap.Remove(HeapReverse(hp.Slice), i).(SliceInt)
}
// SliceFloat64 type
type SliceFloat64 []float64
// Set sets all element to c
func (slice SliceFloat64) Set(c float64) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceFloat64) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceFloat64) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceFloat64) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceFloat64) Get(i int) float64 {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceFloat64) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceFloat64) Push(c interface{}) {
*slice = append(*slice, c.(float64))
}
// Pop element
func (slice *SliceFloat64) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceFloat64) Append(values ...float64) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceFloat64) Prepend(values ...float64) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceFloat64) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceFloat64 struct for min heap
type MinHeapSliceFloat64 struct {
Slice *SliceFloat64
}
// MinHeap returns struct with min heap functionality based on SliceFloat64
func (slice *SliceFloat64) MinHeap() MinHeapSliceFloat64 {
hp := MinHeapSliceFloat64{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceFloat64) Min() float64 {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceFloat64) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceFloat64) Pop() float64 {
return heap.Pop(hp.Slice).(float64)
}
// Push v to heap
func (hp MinHeapSliceFloat64) Push(v float64) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceFloat64) Remove(i int) float64 {
return heap.Remove(hp.Slice, i).(float64)
}
// MaxHeapSliceFloat64 struct for max heap
type MaxHeapSliceFloat64 struct {
Slice *SliceFloat64
}
// MaxHeap returns struct with max heap functionality based on SliceFloat64
func (slice *SliceFloat64) MaxHeap() MaxHeapSliceFloat64 {
hp := MaxHeapSliceFloat64{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceFloat64) Max() float64 {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceFloat64) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceFloat64) Pop() float64 {
return heap.Pop(HeapReverse(hp.Slice)).(float64)
}
// Push v to heap
func (hp MaxHeapSliceFloat64) Push(v float64) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceFloat64) Remove(i int) float64 {
return heap.Remove(HeapReverse(hp.Slice), i).(float64)
}
// SliceSliceFloat64 type
type SliceSliceFloat64 []SliceFloat64
// Set sets all element to c
func (slice SliceSliceFloat64) Set(c SliceFloat64) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceSliceFloat64) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceSliceFloat64) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceSliceFloat64) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceSliceFloat64) Get(i int) SliceFloat64 {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceSliceFloat64) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceSliceFloat64) Push(c interface{}) {
*slice = append(*slice, c.(SliceFloat64))
}
// Pop element
func (slice *SliceSliceFloat64) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceSliceFloat64) Append(values ...SliceFloat64) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceSliceFloat64) Prepend(values ...SliceFloat64) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceSliceFloat64) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceSliceFloat64 struct for min heap
type MinHeapSliceSliceFloat64 struct {
Slice *SliceSliceFloat64
}
// MinHeap returns struct with min heap functionality based on SliceSliceFloat64
func (slice *SliceSliceFloat64) MinHeap() MinHeapSliceSliceFloat64 {
hp := MinHeapSliceSliceFloat64{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceSliceFloat64) Min() SliceFloat64 {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceSliceFloat64) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceSliceFloat64) Pop() SliceFloat64 {
return heap.Pop(hp.Slice).(SliceFloat64)
}
// Push v to heap
func (hp MinHeapSliceSliceFloat64) Push(v SliceFloat64) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceSliceFloat64) Remove(i int) SliceFloat64 {
return heap.Remove(hp.Slice, i).(SliceFloat64)
}
// MaxHeapSliceSliceFloat64 struct for max heap
type MaxHeapSliceSliceFloat64 struct {
Slice *SliceSliceFloat64
}
// MaxHeap returns struct with max heap functionality based on SliceSliceFloat64
func (slice *SliceSliceFloat64) MaxHeap() MaxHeapSliceSliceFloat64 {
hp := MaxHeapSliceSliceFloat64{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceSliceFloat64) Max() SliceFloat64 {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceSliceFloat64) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceSliceFloat64) Pop() SliceFloat64 {
return heap.Pop(HeapReverse(hp.Slice)).(SliceFloat64)
}
// Push v to heap
func (hp MaxHeapSliceSliceFloat64) Push(v SliceFloat64) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceSliceFloat64) Remove(i int) SliceFloat64 {
return heap.Remove(HeapReverse(hp.Slice), i).(SliceFloat64)
}
// SliceString type
type SliceString []string
// Set sets all element to c
func (slice SliceString) Set(c string) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceString) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceString) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceString) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceString) Get(i int) string {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceString) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceString) Push(c interface{}) {
*slice = append(*slice, c.(string))
}
// Pop element
func (slice *SliceString) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceString) Append(values ...string) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceString) Prepend(values ...string) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceString) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceString struct for min heap
type MinHeapSliceString struct {
Slice *SliceString
}
// MinHeap returns struct with min heap functionality based on SliceString
func (slice *SliceString) MinHeap() MinHeapSliceString {
hp := MinHeapSliceString{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceString) Min() string {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceString) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceString) Pop() string {
return heap.Pop(hp.Slice).(string)
}
// Push v to heap
func (hp MinHeapSliceString) Push(v string) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceString) Remove(i int) string {
return heap.Remove(hp.Slice, i).(string)
}
// MaxHeapSliceString struct for max heap
type MaxHeapSliceString struct {
Slice *SliceString
}
// MaxHeap returns struct with max heap functionality based on SliceString
func (slice *SliceString) MaxHeap() MaxHeapSliceString {
hp := MaxHeapSliceString{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceString) Max() string {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceString) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceString) Pop() string {
return heap.Pop(HeapReverse(hp.Slice)).(string)
}
// Push v to heap
func (hp MaxHeapSliceString) Push(v string) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceString) Remove(i int) string {
return heap.Remove(HeapReverse(hp.Slice), i).(string)
}
// SliceSliceString type
type SliceSliceString []SliceString
// Set sets all element to c
func (slice SliceSliceString) Set(c SliceString) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceSliceString) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceSliceString) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceSliceString) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceSliceString) Get(i int) SliceString {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceSliceString) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceSliceString) Push(c interface{}) {
*slice = append(*slice, c.(SliceString))
}
// Pop element
func (slice *SliceSliceString) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceSliceString) Append(values ...SliceString) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceSliceString) Prepend(values ...SliceString) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceSliceString) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceSliceString struct for min heap
type MinHeapSliceSliceString struct {
Slice *SliceSliceString
}
// MinHeap returns struct with min heap functionality based on SliceSliceString
func (slice *SliceSliceString) MinHeap() MinHeapSliceSliceString {
hp := MinHeapSliceSliceString{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceSliceString) Min() SliceString {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceSliceString) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceSliceString) Pop() SliceString {
return heap.Pop(hp.Slice).(SliceString)
}
// Push v to heap
func (hp MinHeapSliceSliceString) Push(v SliceString) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceSliceString) Remove(i int) SliceString {
return heap.Remove(hp.Slice, i).(SliceString)
}
// MaxHeapSliceSliceString struct for max heap
type MaxHeapSliceSliceString struct {
Slice *SliceSliceString
}
// MaxHeap returns struct with max heap functionality based on SliceSliceString
func (slice *SliceSliceString) MaxHeap() MaxHeapSliceSliceString {
hp := MaxHeapSliceSliceString{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceSliceString) Max() SliceString {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceSliceString) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceSliceString) Pop() SliceString {
return heap.Pop(HeapReverse(hp.Slice)).(SliceString)
}
// Push v to heap
func (hp MaxHeapSliceSliceString) Push(v SliceString) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceSliceString) Remove(i int) SliceString {
return heap.Remove(HeapReverse(hp.Slice), i).(SliceString)
}
// SliceByte type
type SliceByte []byte
// Set sets all element to c
func (slice SliceByte) Set(c byte) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceByte) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceByte) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceByte) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceByte) Get(i int) byte {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceByte) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceByte) Push(c interface{}) {
*slice = append(*slice, c.(byte))
}
// Pop element
func (slice *SliceByte) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceByte) Append(values ...byte) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceByte) Prepend(values ...byte) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceByte) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceByte struct for min heap
type MinHeapSliceByte struct {
Slice *SliceByte
}
// MinHeap returns struct with min heap functionality based on SliceByte
func (slice *SliceByte) MinHeap() MinHeapSliceByte {
hp := MinHeapSliceByte{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceByte) Min() byte {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceByte) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceByte) Pop() byte {
return heap.Pop(hp.Slice).(byte)
}
// Push v to heap
func (hp MinHeapSliceByte) Push(v byte) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceByte) Remove(i int) byte {
return heap.Remove(hp.Slice, i).(byte)
}
// MaxHeapSliceByte struct for max heap
type MaxHeapSliceByte struct {
Slice *SliceByte
}
// MaxHeap returns struct with max heap functionality based on SliceByte
func (slice *SliceByte) MaxHeap() MaxHeapSliceByte {
hp := MaxHeapSliceByte{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceByte) Max() byte {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceByte) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceByte) Pop() byte {
return heap.Pop(HeapReverse(hp.Slice)).(byte)
}
// Push v to heap
func (hp MaxHeapSliceByte) Push(v byte) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceByte) Remove(i int) byte {
return heap.Remove(HeapReverse(hp.Slice), i).(byte)
}
// SliceSliceByte type
type SliceSliceByte []SliceByte
// Set sets all element to c
func (slice SliceSliceByte) Set(c SliceByte) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceSliceByte) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceSliceByte) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceSliceByte) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceSliceByte) Get(i int) SliceByte {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceSliceByte) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceSliceByte) Push(c interface{}) {
*slice = append(*slice, c.(SliceByte))
}
// Pop element
func (slice *SliceSliceByte) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceSliceByte) Append(values ...SliceByte) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceSliceByte) Prepend(values ...SliceByte) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceSliceByte) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceSliceByte struct for min heap
type MinHeapSliceSliceByte struct {
Slice *SliceSliceByte
}
// MinHeap returns struct with min heap functionality based on SliceSliceByte
func (slice *SliceSliceByte) MinHeap() MinHeapSliceSliceByte {
hp := MinHeapSliceSliceByte{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceSliceByte) Min() SliceByte {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceSliceByte) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceSliceByte) Pop() SliceByte {
return heap.Pop(hp.Slice).(SliceByte)
}
// Push v to heap
func (hp MinHeapSliceSliceByte) Push(v SliceByte) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceSliceByte) Remove(i int) SliceByte {
return heap.Remove(hp.Slice, i).(SliceByte)
}
// MaxHeapSliceSliceByte struct for max heap
type MaxHeapSliceSliceByte struct {
Slice *SliceSliceByte
}
// MaxHeap returns struct with max heap functionality based on SliceSliceByte
func (slice *SliceSliceByte) MaxHeap() MaxHeapSliceSliceByte {
hp := MaxHeapSliceSliceByte{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceSliceByte) Max() SliceByte {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceSliceByte) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceSliceByte) Pop() SliceByte {
return heap.Pop(HeapReverse(hp.Slice)).(SliceByte)
}
// Push v to heap
func (hp MaxHeapSliceSliceByte) Push(v SliceByte) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceSliceByte) Remove(i int) SliceByte {
return heap.Remove(HeapReverse(hp.Slice), i).(SliceByte)
}
// SliceBool type
type SliceBool []bool
// Set sets all element to c
func (slice SliceBool) Set(c bool) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceBool) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceBool) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceBool) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceBool) Get(i int) bool {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceBool) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceBool) Push(c interface{}) {
*slice = append(*slice, c.(bool))
}
// Pop element
func (slice *SliceBool) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceBool) Append(values ...bool) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceBool) Prepend(values ...bool) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceBool) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceBool struct for min heap
type MinHeapSliceBool struct {
Slice *SliceBool
}
// MinHeap returns struct with min heap functionality based on SliceBool
func (slice *SliceBool) MinHeap() MinHeapSliceBool {
hp := MinHeapSliceBool{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceBool) Min() bool {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceBool) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceBool) Pop() bool {
return heap.Pop(hp.Slice).(bool)
}
// Push v to heap
func (hp MinHeapSliceBool) Push(v bool) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceBool) Remove(i int) bool {
return heap.Remove(hp.Slice, i).(bool)
}
// MaxHeapSliceBool struct for max heap
type MaxHeapSliceBool struct {
Slice *SliceBool
}
// MaxHeap returns struct with max heap functionality based on SliceBool
func (slice *SliceBool) MaxHeap() MaxHeapSliceBool {
hp := MaxHeapSliceBool{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceBool) Max() bool {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceBool) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceBool) Pop() bool {
return heap.Pop(HeapReverse(hp.Slice)).(bool)
}
// Push v to heap
func (hp MaxHeapSliceBool) Push(v bool) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceBool) Remove(i int) bool {
return heap.Remove(HeapReverse(hp.Slice), i).(bool)
}
// SliceSliceBool type
type SliceSliceBool []SliceBool
// Set sets all element to c
func (slice SliceSliceBool) Set(c SliceBool) {
for i := 0; i < len(slice); i++ {
slice[i] = c
}
}
// SortAsc sort ascending
func (slice SliceSliceBool) SortAsc() {
sort.Sort(slice)
}
// SortDesc sort descending
func (slice SliceSliceBool) SortDesc() {
sort.Sort(sort.Reverse(slice))
}
// Len length
func (slice SliceSliceBool) Len() int {
return len(slice)
}
// Get i-th element
func (slice SliceSliceBool) Get(i int) SliceBool {
if i < 0 {
i += len(slice)
}
return slice[i]
}
// Swap two elements
func (slice SliceSliceBool) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
// Push element
func (slice *SliceSliceBool) Push(c interface{}) {
*slice = append(*slice, c.(SliceBool))
}
// Pop element
func (slice *SliceSliceBool) Pop() interface{} {
element := slice.Get(-1)
*slice = (*slice)[:len(*slice)-1]
return element
}
// Append values
func (slice *SliceSliceBool) Append(values ...SliceBool) {
*slice = append(*slice, values...)
}
// Prepend values
func (slice *SliceSliceBool) Prepend(values ...SliceBool) {
*slice = append(values, (*slice)...)
}
// Print prints using separator
func (slice SliceSliceBool) Print(sep string) string {
output := ""
for _, c := range slice {
if output != "" {
output += sep
}
output += fmt.Sprintf("%v", c)
}
return output
}
// MinHeapSliceSliceBool struct for min heap
type MinHeapSliceSliceBool struct {
Slice *SliceSliceBool
}
// MinHeap returns struct with min heap functionality based on SliceSliceBool
func (slice *SliceSliceBool) MinHeap() MinHeapSliceSliceBool {
hp := MinHeapSliceSliceBool{
Slice: slice,
}
heap.Init(hp.Slice)
return hp
}
// Min returns min element
func (hp MinHeapSliceSliceBool) Min() SliceBool {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MinHeapSliceSliceBool) Fix(i int) {
heap.Fix(hp.Slice, i)
}
// Pop removes the minimum element
func (hp MinHeapSliceSliceBool) Pop() SliceBool {
return heap.Pop(hp.Slice).(SliceBool)
}
// Push v to heap
func (hp MinHeapSliceSliceBool) Push(v SliceBool) {
heap.Push(hp.Slice, v)
}
// Remove i-th element
func (hp MinHeapSliceSliceBool) Remove(i int) SliceBool {
return heap.Remove(hp.Slice, i).(SliceBool)
}
// MaxHeapSliceSliceBool struct for max heap
type MaxHeapSliceSliceBool struct {
Slice *SliceSliceBool
}
// MaxHeap returns struct with max heap functionality based on SliceSliceBool
func (slice *SliceSliceBool) MaxHeap() MaxHeapSliceSliceBool {
hp := MaxHeapSliceSliceBool{
Slice: slice,
}
heap.Init(HeapReverse(hp.Slice))
return hp
}
// Max returns max element
func (hp MaxHeapSliceSliceBool) Max() SliceBool {
return (*hp.Slice)[0]
}
// Fix re-establishes heap ordering after i has changed value
func (hp MaxHeapSliceSliceBool) Fix(i int) {
heap.Fix(HeapReverse(hp.Slice), i)
}
// Pop removes the minimum element
func (hp MaxHeapSliceSliceBool) Pop() SliceBool {
return heap.Pop(HeapReverse(hp.Slice)).(SliceBool)
}
// Push v to heap
func (hp MaxHeapSliceSliceBool) Push(v SliceBool) {
heap.Push(HeapReverse(hp.Slice), v)
}
// Remove i-th element
func (hp MaxHeapSliceSliceBool) Remove(i int) SliceBool {
return heap.Remove(HeapReverse(hp.Slice), i).(SliceBool)
} | datastructures/slice/gen-slice.go | 0.787196 | 0.400163 | gen-slice.go | starcoder |
package scanner
import (
"bytes"
)
// FindKey accepts a JSON object and returns the value associated with the key specified
func FindKey(in []byte, pos int, k []byte) ([]byte, error) {
// The start variable will be available to hold our start position for each type
// we scan through. Same for the end. And depth is there to measure any object
// nesting that we may have to do.
var start int
// Skip past any initial space that may be present. We are looking for the beginning
// of a JSON object, denoted by a left brace. `{`
pos, err := SkipSpace(in, pos)
if err != nil {
return nil, err
}
// We have skipped past the space, so we should be at the start of an object. Check
// to make sure that is the case.
if v := in[pos]; v != '{' {
// If we have not found the start of an object, throw an error for now. But it
// must be noted that *technically* we may be starting with an array of objects
// and not know it. In which case we would need to look for a left bracket. `[`
return nil, NewError(pos, v)
}
// If we reach this point, we have found our opening left brace '{'. We should now
// increment the positional counter and then go into our loop.
pos++
// We are now inside a JSON object.
for {
// Skip any leading whitespace, then look for a string.
pos, err = SkipSpace(in, pos)
if err != nil {
return nil, err
}
// Mark our start position, in case we find our key without any errors.
start = pos
// Our key will be a string, so lets see if we have it by trying to return
// the ending position of a string. If we do not encounter an error we
// have found it.
pos, err = String(in, pos)
if err != nil {
return nil, err
}
// We have successfully identified our first key.
key := in[start+1 : pos-1]
// Check it against our supplied key to determine if we have a match and
// store the result of our potential match for later.
match := bytes.Equal(k, key)
// It might be worth noting here that maybe we should check to see if we
// have a match sooner than later, like now. And if we do not have a match,
// then we can potentially make a choice when we get to our any value call.
// Next, skip past any potential whitespace.
pos, err = SkipSpace(in, pos)
if err != nil {
return nil, err
}
// Look for a colon. If we do not find one, return an error.
pos, err = Expect(in, pos, ':')
if err != nil {
return nil, err
}
// Otherwise, consume it and continue.
// Skip past any potential whitespace.
pos, err = SkipSpace(in, pos)
if err != nil {
return nil, err
}
// We are now on the lookout for a value.
// Mark our start position, in case we find our value without any errors.
start = pos
// Our value could be of any type, but we think we have it in our sights
// and the best way to find out is to try and find the end of it without
// encountering any errors.
pos, err = Any(in, pos)
if err != nil {
return nil, err
}
// We must have found it, because we were not met with any error.
// Now, lets check to see if we have a match.
if match {
// If we do, we will return the value that we have isolated.
return in[start:pos], nil
}
// Otherwise, we did not have a matching key. So we must continue on to
// inspect more keys. So, we must skip past any potential whitespace.
pos, err = SkipSpace(in, pos)
if err != nil {
return nil, err
}
// After which, we will either be met with a comma, indicating that we
// have more keys to inspect, or the end of the JSON object.
switch in[pos] {
case ',':
// More keys to inspect, so lets increment our positional counter
// and start the loop over.
pos++
case '}':
// Oh no, we have found the end of the JSON object, and have not
// located our matching key. Return an error.
return nil, ErrKeyNotFound
}
}
} | pkg/json/ndjson/tools/jsonv1/scanner/find_key.go | 0.733165 | 0.599632 | find_key.go | starcoder |
package logging
import (
"fmt"
"io"
"strings"
)
// BreakpointLogger contains data gathered during the Knuth-Plass algorithm.
type BreakpointLogger struct {
AdjustmentRatiosTable *Table
LineDemeritsTable *Table
TotalDemeritsTable *Table
}
// NewBreakpointLogger returns a new initialized BreakpointLogger.
func NewBreakpointLogger() *BreakpointLogger {
return &BreakpointLogger{
AdjustmentRatiosTable: NewTable("Adjustment ratios"),
LineDemeritsTable: NewTable("Line demerits"),
TotalDemeritsTable: NewTable("Total demerits"),
}
}
// Key is an interface for the row/column keys that can be used in a Table.
type Key interface {
ID() string
}
// DataPoint is an interface for the kind of data that can be placed in a cell of a Table.
type DataPoint interface {
String() string
}
// Table is a data structure for holding tabular data where both the row and column indices are Keys.
type Table struct {
name string
keyTracker keyTracker
data map[string]map[string]DataPoint
}
// AddCell adds a new data point to the Table (or replaces the data point, if it already exists).
func (table *Table) AddCell(row Key, col Key, value DataPoint) {
table.keyTracker.initNode(row)
table.keyTracker.initNode(col)
_, rowExists := table.data[row.ID()]
if !rowExists {
table.data[row.ID()] = make(map[string]DataPoint)
}
table.data[row.ID()][col.ID()] = value
}
func fprintf(w io.Writer, format string, a ...interface{}) {
_, err := fmt.Fprintf(w, format, a...)
if err != nil {
fmt.Println("Encountered error when printing to string buffer: ", err)
}
}
// String returns the Table as a string.
func (table *Table) String() string {
var b strings.Builder
fprintf(&b, " +---[ %s ]---\n", table.name)
headerLine := fmt.Sprintf(" | %10s | ", "")
// Calculate the width of each column
colKeyToColWidth := make(map[string]int)
for _, colKey := range table.keyTracker.keysInOrder {
colKeyToColWidth[colKey.ID()] = -1.0
for _, rowKey := range table.keyTracker.keysInOrder {
value, hasValue := table.data[rowKey.ID()][colKey.ID()]
if !hasValue {
continue
}
stringValue := fmt.Sprintf("%9s", value)
if len(stringValue) > colKeyToColWidth[colKey.ID()] {
colKeyToColWidth[colKey.ID()] = len(stringValue)
}
}
}
// String the header row
fprintf(&b, " | %10s | ", "")
for _, colKey := range table.keyTracker.keysInOrder {
if colKeyToColWidth[colKey.ID()] < 0 {
continue
}
headerLine = headerLine + fmt.Sprintf(" %*s |", colKeyToColWidth[colKey.ID()], colKey.ID())
fprintf(&b, " %*s |", colKeyToColWidth[colKey.ID()], colKey.ID())
}
fprintf(&b, "\n")
for _, rowKey := range table.keyTracker.keysInOrder {
// We store this row's data in another buffer. If there is no data in the whole row, we won't print it.
var lineB strings.Builder
fprintf(&lineB, " | %10s | ", rowKey.ID())
rowHasValues := false
for _, colKey := range table.keyTracker.keysInOrder {
if colKeyToColWidth[colKey.ID()] < 0 {
continue
}
value, hasValue := table.data[rowKey.ID()][colKey.ID()]
if hasValue {
stringValue := fmt.Sprintf("%9s", value)
fprintf(&lineB, " %*s |", colKeyToColWidth[colKey.ID()], stringValue)
rowHasValues = true
} else {
fprintf(&lineB, " %*s |", colKeyToColWidth[colKey.ID()], "")
}
}
if !rowHasValues {
continue
}
fprintf(&b, lineB.String())
fprintf(&b, "\n")
}
fprintf(&b, " +----")
fprintf(&b, " Node id: [item index]/[line index]/[fitness class]. Line index may...")
fprintf(&b, "\n")
return b.String()
}
// NewTable creates a new table with the given name.
func NewTable(name string) *Table {
return &Table{
name: name,
keyTracker: newKeyTracker(),
data: make(map[string]map[string]DataPoint),
}
}
type keyTracker struct {
keysInOrder []Key
keysSeen map[string]bool
}
func newKeyTracker() keyTracker {
return keyTracker{
keysInOrder: []Key{},
keysSeen: make(map[string]bool),
}
}
func (tracker *keyTracker) initNode(thisNode Key) {
if tracker.keysSeen[thisNode.ID()] {
return
}
tracker.keysSeen[thisNode.ID()] = true
tracker.keysInOrder = append(tracker.keysInOrder, thisNode)
} | pkg/knuthplass/logging/logging.go | 0.641535 | 0.450359 | logging.go | starcoder |
package interpolate
// Interpolator is a 1D interpolator. These interpolators all use caching, so
// they are not thread safe.
type Interpolator interface {
// Eval evaluates the interpolator at x.
Eval(x float64) float64
// EvalAll evaluates a sequeunce of values and returns the result. An
// optional output array can be supplied to prevent unneeded heap
// allocations.
EvalAll(xs []float64, out ...[]float64) []float64
// Ref creates a shallow copy of the interpolator with its own cache.
// Each thread using the same interpolator must make a copy with Ref
// first.
Ref() Interpolator
}
var (
_ Interpolator = &Spline{}
_ Interpolator = &Linear{}
_ Interpolator = &splineRef{}
_ Interpolator = &linearRef{}
)
// BiInterpolator is a 2D interpolator. These interpolators all use caching, so
// they are not thread safe.
type BiInterpolator interface {
// Eval evaluates the interpolator at a point.
Eval(x, y float64) float64
// EvalAll evaluates a sequeunce of points and returns the result. An
// optional output array can be supplied to prevent unneeded heap
// allocations.
EvalAll(xs, ys []float64, out ...[]float64) []float64
// Ref creates a shallow copy of the interpolator with its own cache.
// Each thread using the saem interpolator must make a copy with Ref
// first.
Ref() BiInterpolator
}
var (
_ BiInterpolator = &BiLinear{}
_ BiInterpolator = &BiCubic{}
_ BiInterpolator = &biLinearRef{}
_ BiInterpolator = &biCubicRef{}
)
// BiInterpolator is a 2D interpolator. These interpolators all use caching, so
// they are not thread safe.
type TriInterpolator interface {
// Eval evaluates the interpolator at a point.
Eval(x, y, z float64) float64
// EvalAll evaluates a sequeunce of points and returns the result. An
// optional output array can be supplied to prevent unneeded heap
// allocations.
EvalAll(xs, ys, zs []float64, out ...[]float64) []float64
// Ref creates a shallow copy of the interpolator with its own cache.
// Each thread using the saem interpolator must make a copy with Ref
// first.
Ref() TriInterpolator
}
var (
_ TriInterpolator = &TriLinear{}
_ TriInterpolator = &TriCubic{}
_ TriInterpolator = &triLinearRef{}
_ TriInterpolator = &triCubicRef{}
) | math/interpolate/interpolator.go | 0.78968 | 0.518912 | interpolator.go | starcoder |
package main
import (
"github.com/katydid/katydid/gen"
)
const compareStr = `
type {{.Type}}{{.CName}} struct {
V1 {{.CType}}
V2 {{.CType}}
}
func (this *{{.Type}}{{.CName}}) Eval() bool {
{{if .Eval}}{{.Eval}}{{else}}return this.V1.Eval() {{.Operator}} this.V2.Eval(){{end}}
}
func init() {
Register("{{.Name}}", new({{.Type}}{{.CName}}))
}
`
type compare struct {
Name string
Operator string
Type string
Eval string
}
func (this *compare) CName() string {
return gen.CapFirst(this.Name)
}
func (this *compare) CType() string {
return gen.CapFirst(this.Type)
}
const newFuncStr = `
func New{{.}}Func(uniq string, values ...interface{}) ({{.}}, error) {
f, err := newFunc(uniq, values...)
if err != nil {
return nil, err
}
return f.({{.}}), nil
}
`
const constStr = `
type Const{{.CType}} interface {
{{.CType}}
}
var typConst{{.CType}} reflect.Type = reflect.TypeOf((*Const{{.CType}})(nil)).Elem()
type const{{.CType}} struct {
v {{.GoType}}
}
func NewConst{{.CType}}(v {{.GoType}}) Const{{.CType}} {
return &const{{.CType}}{v}
}
func (this *const{{.CType}}) IsConst() {}
func (this *const{{.CType}}) Eval() {{.GoType}} {
return this.v
}
func (this *const{{.CType}}) String() string {
{{if .ListType}}ss := make([]string, len(this.v))
for i := range this.v {
ss[i] = fmt.Sprintf("{{.String}}", this.v[i])
}
return "[]{{.ListType}}{" + strings.Join(ss, ",") + "}"{{else}}return fmt.Sprintf("{{.String}}", this.v){{end}}
}
`
type conster struct {
CType string
GoType string
String string
ListType string
}
const listStr = `
type listOf{{.FuncType}} struct {
List []{{.FuncType}}
}
func NewListOf{{.FuncType}}(v []{{.FuncType}}) {{.CType}} {
return &listOf{{.FuncType}}{v}
}
func (this *listOf{{.FuncType}}) Eval() []{{.GoType}} {
res := make([]{{.GoType}}, len(this.List))
for i, e := range this.List {
res[i] = e.Eval()
}
return res
}
func (this *listOf{{.FuncType}}) String() string {
ss := make([]string, len(this.List))
for i := range this.List {
ss[i] = Sprint(this.List[i])
}
return "[]{{.GoType}}{" + strings.Join(ss, ",") + "}"
}
func (this *listOf{{.FuncType}}) IsListOf() {}
`
type list struct {
CType string
FuncType string
GoType string
}
const printStr = `
type print{{.Name}} struct {
E {{.Name}}
}
func (this *print{{.Name}}) Eval() {{.GoType}} {
v := this.E.Eval()
fmt.Printf("%#v\n", v)
return v
}
func (this *print{{.Name}}) IsVariable() {}
func init() {
Register("print", new(print{{.Name}}))
}
`
type printer struct {
Name string
GoType string
}
const lengthStr = `
type len{{.}} struct {
E {{.}}
}
func (this *len{{.}}) Eval() int64 {
return int64(len(this.E.Eval()))
}
func init() {
Register("length", new(len{{.}}))
}
`
const elemStr = `
type elem{{.ListType}} struct {
List {{.ListType}}
Index Int64
Thrower
}
func (this *elem{{.ListType}}) Eval() {{.ReturnType}} {
list := this.List.Eval()
index := int(this.Index.Eval())
if len(list) == 0 {
return this.Throw{{.ThrowType}}(NewRangeCheckErr(index, len(list)))
}
if index < 0 {
index = index % len(list)
}
if len(list) <= index {
return this.Throw{{.ThrowType}}(NewRangeCheckErr(index, len(list)))
}
return list[index]
}
func init() {
Register("elem", new(elem{{.ListType}}))
}
`
type elemer struct {
ListType string
ReturnType string
ThrowType string
}
const rangeStr = `
type range{{.ListType}} struct {
List {{.ListType}}
First Int64
Last Int64
Thrower
}
func (this *range{{.ListType}}) Eval() {{.ReturnType}} {
list := this.List.Eval()
first := int(this.First.Eval())
if len(list) == 0 {
return this.Throw{{.ListType}}(NewRangeCheckErr(first, len(list)))
}
if first < 0 {
first = first % len(list)
}
if first > len(list) {
return this.Throw{{.ListType}}(NewRangeCheckErr(first, len(list)))
}
last := int(this.Last.Eval())
if last < 0 {
last = last % len(list)
}
if last > len(list) {
return this.Throw{{.ListType}}(NewRangeCheckErr(last, len(list)))
}
if first > last {
return this.Throw{{.ListType}}(NewRangeErr(first, last))
}
return list[first:last]
}
func init() {
Register("range", new(range{{.ListType}}))
}
`
type ranger struct {
ListType string
ReturnType string
}
const variableStr = `
type var{{.Name}} struct {
Dec serialize.Decoder
Thrower
}
var _ Decoder = &var{{.Name}}{}
var _ Variable = &var{{.Name}}{}
func (this *var{{.Name}}) Eval() {{.GoType}} {
v, err := this.Dec.{{.Name}}()
if err != nil {
return this.Throw{{.Name}}(err)
}
return v
}
func (this *var{{.Name}}) IsVariable() {}
func (this *var{{.Name}}) SetDecoder(dec serialize.Decoder) {
this.Dec = dec
}
func (this *var{{.Name}}) String() string {
return "var{{.Name}}"
}
func New{{.Name}}Variable() *var{{.Name}} {
return &var{{.Name}}{}
}
`
var existsStr = `
type exists{{.Name}} struct {
Field {{.Name}}
}
func (this *exists{{.Name}}) Eval() bool {
this.Field.Eval()
return true
}
func init() {
Register("exists", new(exists{{.Name}}))
}
`
func main() {
gen := gen.NewFunc("funcs")
gen(compareStr, "compare.gen.go", []interface{}{
&compare{"ge", ">=", "float64", ""},
&compare{"ge", ">=", "float32", ""},
&compare{"ge", ">=", "int64", ""},
&compare{"ge", ">=", "uint64", ""},
&compare{"ge", ">=", "int32", ""},
&compare{"ge", ">=", "uint32", ""},
&compare{"ge", "", "bytes", "return bytes.Compare(this.V1.Eval(), this.V2.Eval()) >= 0"},
&compare{"gt", ">", "float64", ""},
&compare{"gt", ">", "float32", ""},
&compare{"gt", ">", "int64", ""},
&compare{"gt", ">", "uint64", ""},
&compare{"gt", ">", "int32", ""},
&compare{"gt", ">", "uint32", ""},
&compare{"gt", "", "bytes", "return bytes.Compare(this.V1.Eval(), this.V2.Eval()) > 0"},
&compare{"le", "<=", "float64", ""},
&compare{"le", "<=", "float32", ""},
&compare{"le", "<=", "int64", ""},
&compare{"le", "<=", "uint64", ""},
&compare{"le", "<=", "int32", ""},
&compare{"le", "<=", "uint32", ""},
&compare{"le", "", "bytes", "return bytes.Compare(this.V1.Eval(), this.V2.Eval()) <= 0"},
&compare{"lt", "<", "float64", ""},
&compare{"lt", "<", "float32", ""},
&compare{"lt", "<", "int64", ""},
&compare{"lt", "<", "uint64", ""},
&compare{"lt", "<", "int32", ""},
&compare{"lt", "<", "uint32", ""},
&compare{"lt", "", "bytes", "return bytes.Compare(this.V1.Eval(), this.V2.Eval()) < 0"},
&compare{"eq", "==", "float64", ""},
&compare{"eq", "==", "float32", ""},
&compare{"eq", "==", "int64", ""},
&compare{"eq", "==", "uint64", ""},
&compare{"eq", "==", "int32", ""},
&compare{"eq", "==", "uint32", ""},
&compare{"eq", "==", "bool", ""},
&compare{"eq", "==", "string", ""},
&compare{"eq", "", "bytes", "return bytes.Equal(this.V1.Eval(), this.V2.Eval())"},
}, `"bytes"`)
gen(newFuncStr, "newfunc.gen.go", []interface{}{
"Float64",
"Float32",
"Int64",
"Uint64",
"Int32",
"Uint32",
"Bool",
"String",
"Bytes",
"Float64s",
"Float32s",
"Int64s",
"Uint64s",
"Int32s",
"Uint32s",
"Bools",
"Strings",
"ListOfBytes",
})
gen(constStr, "const.gen.go", []interface{}{
&conster{"Float64", "float64", "double(%f)", ""},
&conster{"Float32", "float32", "float(%f)", ""},
&conster{"Int64", "int64", "int64(%d)", ""},
&conster{"Uint64", "uint64", "uint64(%d)", ""},
&conster{"Int32", "int32", "int32(%d)", ""},
&conster{"Uint32", "uint32", "uint32(%d)", ""},
&conster{"Bool", "bool", "%v", ""},
&conster{"String", "string", "`%s`", ""},
&conster{"Bytes", "[]byte", "%#v", ""},
&conster{"Float64s", "[]float64", "double(%f)", "double"},
&conster{"Float32s", "[]float32", "float(%f)", "float"},
&conster{"Int64s", "[]int64", "int64(%d)", "int64"},
&conster{"Uint64s", "[]uint64", "uint64(%d)", "uint64"},
&conster{"Int32s", "[]int32", "int32(%d)", "int32"},
&conster{"Uint32s", "[]uint32", "uint32(%d)", "uint32"},
&conster{"Bools", "[]bool", "%v", "bool"},
&conster{"Strings", "[]string", "`%s`", "string"},
&conster{"ListOfBytes", "[][]byte", "%#v", "[]byte"},
}, `"fmt"`, `"strings"`, `"reflect"`)
gen(listStr, "list.gen.go", []interface{}{
&list{"Float64s", "Float64", "float64"},
&list{"Float32s", "Float32", "float32"},
&list{"Int64s", "Int64", "int64"},
&list{"Uint64s", "Uint64", "uint64"},
&list{"Int32s", "Int32", "int32"},
&list{"Bools", "Bool", "bool"},
&list{"Strings", "String", "string"},
&list{"ListOfBytes", "Bytes", "[]byte"},
&list{"Uint32s", "Uint32", "uint32"},
}, `"strings"`)
gen(printStr, "print.gen.go", []interface{}{
&printer{"Float64", "float64"},
&printer{"Float32", "float32"},
&printer{"Int64", "int64"},
&printer{"Uint64", "uint64"},
&printer{"Int32", "int32"},
&printer{"Uint32", "uint32"},
&printer{"Bool", "bool"},
&printer{"String", "string"},
&printer{"Bytes", "[]byte"},
&printer{"Float64s", "[]float64"},
&printer{"Float32s", "[]float32"},
&printer{"Int64s", "[]int64"},
&printer{"Uint64s", "[]uint64"},
&printer{"Int32s", "[]int32"},
&printer{"Uint32s", "[]uint32"},
&printer{"Bools", "[]bool"},
&printer{"Strings", "[]string"},
&printer{"ListOfBytes", "[][]byte"},
}, `"fmt"`)
gen(lengthStr, "length.gen.go", []interface{}{
"Float64s",
"Float32s",
"Int64s",
"Uint64s",
"Int32s",
"Uint32s",
"Bools",
"Strings",
"ListOfBytes",
"String",
"Bytes",
})
gen(elemStr, "elem.gen.go", []interface{}{
&elemer{"Float64s", "float64", "Float64"},
&elemer{"Float32s", "float32", "Float32"},
&elemer{"Int64s", "int64", "Int64"},
&elemer{"Uint64s", "uint64", "Uint64"},
&elemer{"Int32s", "int32", "Int32"},
&elemer{"Uint32s", "uint32", "Uint32"},
&elemer{"Bools", "bool", "Bool"},
&elemer{"Strings", "string", "String"},
&elemer{"ListOfBytes", "[]byte", "Bytes"},
})
gen(rangeStr, "range.gen.go", []interface{}{
&ranger{"Float64s", "[]float64"},
&ranger{"Float32s", "[]float32"},
&ranger{"Int64s", "[]int64"},
&ranger{"Uint64s", "[]uint64"},
&ranger{"Int32s", "[]int32"},
&ranger{"Uint32s", "[]uint32"},
&ranger{"Bools", "[]bool"},
&ranger{"Strings", "[]string"},
&ranger{"ListOfBytes", "[][]byte"},
})
gen(variableStr, "variable.gen.go", []interface{}{
&printer{"Float64", "float64"},
&printer{"Float32", "float32"},
&printer{"Int64", "int64"},
&printer{"Uint64", "uint64"},
&printer{"Int32", "int32"},
&printer{"Uint32", "uint32"},
&printer{"Bool", "bool"},
&printer{"String", "string"},
&printer{"Bytes", "[]byte"},
}, `"github.com/katydid/katydid/serialize"`)
gen(existsStr, "exists.gen.go", []interface{}{
&printer{"Float64", "float64"},
&printer{"Float32", "float32"},
&printer{"Int64", "int64"},
&printer{"Uint64", "uint64"},
&printer{"Int32", "int32"},
&printer{"Uint32", "uint32"},
&printer{"Bool", "bool"},
&printer{"String", "string"},
&printer{"Bytes", "[]byte"},
})
} | funcs/funcs-gen/main.go | 0.539226 | 0.415521 | main.go | starcoder |
package main
// O(nm.8^s + ws) time | O(nm + ws) space
// where N is the width of the board, M is the height of the board
// where W is the number of words, S is the length of the longest word
func BoggleBoard(board [][]rune, words []string) []string {
trie := Trie{children: map[rune]Trie{}}
for _, word := range words {
trie.Add(word)
}
visited := make([][]bool, len(board))
for i := range visited {
visited[i] = make([]bool, len(board[i]))
}
finalWords := map[string]bool{}
for i := range board {
for j := range board[i] {
explore(i, j, board, trie, visited, finalWords)
}
}
result := []string{}
for word := range finalWords {
result = append(result, word)
}
return result
}
func explore(i, j int, board [][]rune, trie Trie, visited [][]bool, finalWords map[string]bool) {
if visited[i][j] {
return
}
letter := board[i][j]
if _, found := trie.children[letter]; !found {
return
}
visited[i][j] = true
trie = trie.children[letter]
if end, found := trie.children['*']; found {
finalWords[end.word] = true
}
neighbors := getNeighbors(i, j, board)
for _, neighbor := range neighbors {
explore(neighbor[0], neighbor[1], board, trie, visited, finalWords)
}
visited[i][j] = false
}
func getNeighbors(i, j int, board [][]rune) [][]int {
neighbors := [][]int{}
if i > 0 && j > 0 {
neighbors = append(neighbors, []int{i - 1, j - 1})
}
if i > 0 && j < len(board[0])-1 {
neighbors = append(neighbors, []int{i - 1, j + 1})
}
if i < len(board)-1 && j < len(board[0])-1 {
neighbors = append(neighbors, []int{i + 1, j + 1})
}
if i < len(board)-1 && j > 0 {
neighbors = append(neighbors, []int{i + 1, j - 1})
}
if i > 0 {
neighbors = append(neighbors, []int{i - 1, j})
}
if i < len(board)-1 {
neighbors = append(neighbors, []int{i + 1, j})
}
if j > 0 {
neighbors = append(neighbors, []int{i, j - 1})
}
if j < len(board[0])-1 {
neighbors = append(neighbors, []int{i, j + 1})
}
return neighbors
}
type Trie struct {
children map[rune]Trie
word string
}
func (t Trie) Add(word string) {
current := t
for _, letter := range word {
if _, found := current.children[letter]; !found {
current.children[letter] = Trie{
children: map[rune]Trie{},
}
}
current = current.children[letter]
}
current.children['*'] = Trie{
children: map[rune]Trie{},
word: word,
}
} | src/graphs/hard/boggle-board/go/recursive-trie.go | 0.575469 | 0.407982 | recursive-trie.go | starcoder |
package assertions
import (
"fmt"
"reflect"
)
// ShouldHaveSameTypeAs receives exactly two parameters and compares their underlying types for equality.
func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
first := reflect.TypeOf(actual)
second := reflect.TypeOf(expected[0])
if equal := ShouldEqual(first, second); equal != success {
return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first))
}
return success
}
// ShouldNotHaveSameTypeAs receives exactly two parameters and compares their underlying types for inequality.
func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
first := reflect.TypeOf(actual)
second := reflect.TypeOf(expected[0])
if equal := ShouldEqual(first, second); equal == success {
return fmt.Sprintf(shouldNotHaveBeenA, actual, second)
}
return success
}
// ShouldImplement receives exactly two parameters and ensures
// that the first implements the interface type of the second.
func ShouldImplement(actual interface{}, expectedList ...interface{}) string {
if fail := need(1, expectedList); fail != success {
return fail
}
expected := expectedList[0]
if fail := ShouldBeNil(expected); fail != success {
return shouldCompareWithInterfacePointer
}
if fail := ShouldNotBeNil(actual); fail != success {
return shouldNotBeNilActual
}
var actualType reflect.Type
if reflect.TypeOf(actual).Kind() != reflect.Ptr {
actualType = reflect.PtrTo(reflect.TypeOf(actual))
} else {
actualType = reflect.TypeOf(actual)
}
expectedType := reflect.TypeOf(expected)
if fail := ShouldNotBeNil(expectedType); fail != success {
return shouldCompareWithInterfacePointer
}
expectedInterface := expectedType.Elem()
if actualType == nil {
return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actual)
}
if !actualType.Implements(expectedInterface) {
return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType)
}
return success
}
// ShouldNotImplement receives exactly two parameters and ensures
// that the first does NOT implement the interface type of the second.
func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string {
if fail := need(1, expectedList); fail != success {
return fail
}
expected := expectedList[0]
if fail := ShouldBeNil(expected); fail != success {
return shouldCompareWithInterfacePointer
}
if fail := ShouldNotBeNil(actual); fail != success {
return shouldNotBeNilActual
}
var actualType reflect.Type
if reflect.TypeOf(actual).Kind() != reflect.Ptr {
actualType = reflect.PtrTo(reflect.TypeOf(actual))
} else {
actualType = reflect.TypeOf(actual)
}
expectedType := reflect.TypeOf(expected)
if fail := ShouldNotBeNil(expectedType); fail != success {
return shouldCompareWithInterfacePointer
}
expectedInterface := expectedType.Elem()
if actualType.Implements(expectedInterface) {
return fmt.Sprintf(shouldNotHaveImplemented, actualType, expectedInterface)
}
return success
}
// ShouldBeError receives one parameter and ensures
// that it is an error interface.
// It optionally takes an additional second parameter to test
// an expected error message.
func ShouldBeError(actual interface{}, expected ...interface{}) string {
expectedErrMsg, err := cleanShouldBeErrorInput(actual, expected...)
if err != "" {
return err
}
val, ok := actual.(error)
if !ok {
return shouldBeError
}
if expectedErrMsg != "" && val.Error() != expectedErrMsg {
return fmt.Sprintf(shouldBeErrorExpectedMessage, expectedErrMsg, val.Error())
}
return success
}
// Clean the `ShouldBeError` assertion input.
// If a second, optional argument was passed (the expected error message),
// it will be returned. Otherwise, return an empty string and an error message.
func cleanShouldBeErrorInput(actual interface{}, expected ...interface{}) (string, string) {
if len(expected) == 0 {
return "", ""
}
// Make sure the provided is a string
val, ok := expected[0].(string)
if !ok {
return "", "This assertion requires an error message string to be provided (you provided a non-string type)."
}
return val, ""
} | vendor/github.com/smartystreets/assertions/type.go | 0.797123 | 0.637722 | type.go | starcoder |
package appkit
// #include "text_table.h"
import "C"
import (
"unsafe"
"github.com/hsiafan/cocoa/coregraphics"
"github.com/hsiafan/cocoa/foundation"
"github.com/hsiafan/cocoa/objc"
)
type TextBlock interface {
objc.Object
SetValue_Type_ForDimension(val coregraphics.Float, _type TextBlockValueType, dimension TextBlockDimension)
ValueForDimension(dimension TextBlockDimension) coregraphics.Float
ValueTypeForDimension(dimension TextBlockDimension) TextBlockValueType
SetContentWidth_Type(val coregraphics.Float, _type TextBlockValueType)
SetWidth_Type_ForLayer_Edge(val coregraphics.Float, _type TextBlockValueType, layer TextBlockLayer, edge foundation.RectEdge)
SetWidth_Type_ForLayer(val coregraphics.Float, _type TextBlockValueType, layer TextBlockLayer)
WidthForLayer_Edge(layer TextBlockLayer, edge foundation.RectEdge) coregraphics.Float
WidthValueTypeForLayer_Edge(layer TextBlockLayer, edge foundation.RectEdge) TextBlockValueType
SetBorderColor_ForEdge(color Color, edge foundation.RectEdge)
SetBorderColor(color Color)
BorderColorForEdge(edge foundation.RectEdge) NSColor
RectForLayoutAtPoint_InRect_TextContainer_CharacterRange(startingPoint foundation.Point, rect foundation.Rect, textContainer TextContainer, charRange foundation.Range) foundation.Rect
BoundsRectForContentRect_InRect_TextContainer_CharacterRange(contentRect foundation.Rect, rect foundation.Rect, textContainer TextContainer, charRange foundation.Range) foundation.Rect
DrawBackgroundWithFrame_InView_CharacterRange_LayoutManager(frameRect foundation.Rect, controlView View, charRange foundation.Range, layoutManager LayoutManager)
ContentWidth() coregraphics.Float
ContentWidthValueType() TextBlockValueType
VerticalAlignment() TextBlockVerticalAlignment
SetVerticalAlignment(value TextBlockVerticalAlignment)
BackgroundColor() NSColor
SetBackgroundColor(value Color)
}
type NSTextBlock struct {
objc.NSObject
}
func MakeTextBlock(ptr unsafe.Pointer) NSTextBlock {
return NSTextBlock{
NSObject: objc.MakeObject(ptr),
}
}
func (n NSTextBlock) Init() NSTextBlock {
result_ := C.C_NSTextBlock_Init(n.Ptr())
return MakeTextBlock(result_)
}
func AllocTextBlock() NSTextBlock {
result_ := C.C_NSTextBlock_AllocTextBlock()
return MakeTextBlock(result_)
}
func NewTextBlock() NSTextBlock {
result_ := C.C_NSTextBlock_NewTextBlock()
return MakeTextBlock(result_)
}
func (n NSTextBlock) Autorelease() NSTextBlock {
result_ := C.C_NSTextBlock_Autorelease(n.Ptr())
return MakeTextBlock(result_)
}
func (n NSTextBlock) Retain() NSTextBlock {
result_ := C.C_NSTextBlock_Retain(n.Ptr())
return MakeTextBlock(result_)
}
func (n NSTextBlock) SetValue_Type_ForDimension(val coregraphics.Float, _type TextBlockValueType, dimension TextBlockDimension) {
C.C_NSTextBlock_SetValue_Type_ForDimension(n.Ptr(), C.double(float64(val)), C.uint(uint(_type)), C.uint(uint(dimension)))
}
func (n NSTextBlock) ValueForDimension(dimension TextBlockDimension) coregraphics.Float {
result_ := C.C_NSTextBlock_ValueForDimension(n.Ptr(), C.uint(uint(dimension)))
return coregraphics.Float(float64(result_))
}
func (n NSTextBlock) ValueTypeForDimension(dimension TextBlockDimension) TextBlockValueType {
result_ := C.C_NSTextBlock_ValueTypeForDimension(n.Ptr(), C.uint(uint(dimension)))
return TextBlockValueType(uint(result_))
}
func (n NSTextBlock) SetContentWidth_Type(val coregraphics.Float, _type TextBlockValueType) {
C.C_NSTextBlock_SetContentWidth_Type(n.Ptr(), C.double(float64(val)), C.uint(uint(_type)))
}
func (n NSTextBlock) SetWidth_Type_ForLayer_Edge(val coregraphics.Float, _type TextBlockValueType, layer TextBlockLayer, edge foundation.RectEdge) {
C.C_NSTextBlock_SetWidth_Type_ForLayer_Edge(n.Ptr(), C.double(float64(val)), C.uint(uint(_type)), C.int(int(layer)), C.uint(uint(edge)))
}
func (n NSTextBlock) SetWidth_Type_ForLayer(val coregraphics.Float, _type TextBlockValueType, layer TextBlockLayer) {
C.C_NSTextBlock_SetWidth_Type_ForLayer(n.Ptr(), C.double(float64(val)), C.uint(uint(_type)), C.int(int(layer)))
}
func (n NSTextBlock) WidthForLayer_Edge(layer TextBlockLayer, edge foundation.RectEdge) coregraphics.Float {
result_ := C.C_NSTextBlock_WidthForLayer_Edge(n.Ptr(), C.int(int(layer)), C.uint(uint(edge)))
return coregraphics.Float(float64(result_))
}
func (n NSTextBlock) WidthValueTypeForLayer_Edge(layer TextBlockLayer, edge foundation.RectEdge) TextBlockValueType {
result_ := C.C_NSTextBlock_WidthValueTypeForLayer_Edge(n.Ptr(), C.int(int(layer)), C.uint(uint(edge)))
return TextBlockValueType(uint(result_))
}
func (n NSTextBlock) SetBorderColor_ForEdge(color Color, edge foundation.RectEdge) {
C.C_NSTextBlock_SetBorderColor_ForEdge(n.Ptr(), objc.ExtractPtr(color), C.uint(uint(edge)))
}
func (n NSTextBlock) SetBorderColor(color Color) {
C.C_NSTextBlock_SetBorderColor(n.Ptr(), objc.ExtractPtr(color))
}
func (n NSTextBlock) BorderColorForEdge(edge foundation.RectEdge) NSColor {
result_ := C.C_NSTextBlock_BorderColorForEdge(n.Ptr(), C.uint(uint(edge)))
return MakeColor(result_)
}
func (n NSTextBlock) RectForLayoutAtPoint_InRect_TextContainer_CharacterRange(startingPoint foundation.Point, rect foundation.Rect, textContainer TextContainer, charRange foundation.Range) foundation.Rect {
result_ := C.C_NSTextBlock_RectForLayoutAtPoint_InRect_TextContainer_CharacterRange(n.Ptr(), *(*C.CGPoint)(unsafe.Pointer(&startingPoint)), *(*C.CGRect)(unsafe.Pointer(&rect)), objc.ExtractPtr(textContainer), *(*C.NSRange)(unsafe.Pointer(&charRange)))
return *((*coregraphics.Rect)(unsafe.Pointer(&result_)))
}
func (n NSTextBlock) BoundsRectForContentRect_InRect_TextContainer_CharacterRange(contentRect foundation.Rect, rect foundation.Rect, textContainer TextContainer, charRange foundation.Range) foundation.Rect {
result_ := C.C_NSTextBlock_BoundsRectForContentRect_InRect_TextContainer_CharacterRange(n.Ptr(), *(*C.CGRect)(unsafe.Pointer(&contentRect)), *(*C.CGRect)(unsafe.Pointer(&rect)), objc.ExtractPtr(textContainer), *(*C.NSRange)(unsafe.Pointer(&charRange)))
return *((*coregraphics.Rect)(unsafe.Pointer(&result_)))
}
func (n NSTextBlock) DrawBackgroundWithFrame_InView_CharacterRange_LayoutManager(frameRect foundation.Rect, controlView View, charRange foundation.Range, layoutManager LayoutManager) {
C.C_NSTextBlock_DrawBackgroundWithFrame_InView_CharacterRange_LayoutManager(n.Ptr(), *(*C.CGRect)(unsafe.Pointer(&frameRect)), objc.ExtractPtr(controlView), *(*C.NSRange)(unsafe.Pointer(&charRange)), objc.ExtractPtr(layoutManager))
}
func (n NSTextBlock) ContentWidth() coregraphics.Float {
result_ := C.C_NSTextBlock_ContentWidth(n.Ptr())
return coregraphics.Float(float64(result_))
}
func (n NSTextBlock) ContentWidthValueType() TextBlockValueType {
result_ := C.C_NSTextBlock_ContentWidthValueType(n.Ptr())
return TextBlockValueType(uint(result_))
}
func (n NSTextBlock) VerticalAlignment() TextBlockVerticalAlignment {
result_ := C.C_NSTextBlock_VerticalAlignment(n.Ptr())
return TextBlockVerticalAlignment(uint(result_))
}
func (n NSTextBlock) SetVerticalAlignment(value TextBlockVerticalAlignment) {
C.C_NSTextBlock_SetVerticalAlignment(n.Ptr(), C.uint(uint(value)))
}
func (n NSTextBlock) BackgroundColor() NSColor {
result_ := C.C_NSTextBlock_BackgroundColor(n.Ptr())
return MakeColor(result_)
}
func (n NSTextBlock) SetBackgroundColor(value Color) {
C.C_NSTextBlock_SetBackgroundColor(n.Ptr(), objc.ExtractPtr(value))
} | appkit/text_table.go | 0.610221 | 0.575767 | text_table.go | starcoder |
package CronScheduler
import (
"BUtils"
"time"
)
type Scheduler struct {
//Debug bool
Min string
Hour string
DayM string
DayW string
Month string
MinInt []int
HourInt []int
DayMInt []int
DayWInt []int
MonthInt []int
}
func New() *Scheduler {
return &Scheduler{
Min: "*",
Hour: "*",
DayM: "*",
DayW: "*",
Month: "*",
MinInt: []int{},
HourInt: []int{},
DayMInt: []int{},
DayWInt: []int{},
MonthInt: []int{},
}
}
func (sched *Scheduler) Clone() *Scheduler {
return &Scheduler{
Min: sched.Min,
Hour: sched.Hour,
DayM: sched.DayM,
DayW: sched.DayW,
Month: sched.Month,
MinInt: BUtils.CopyIntsList(sched.MinInt),
HourInt: BUtils.CopyIntsList(sched.HourInt),
DayMInt: BUtils.CopyIntsList(sched.DayMInt),
DayWInt: BUtils.CopyIntsList(sched.DayWInt),
MonthInt: BUtils.CopyIntsList(sched.MonthInt),
}
}
func (sched *Scheduler) StartTime(prevTime, finishTime time.Time) bool {
return true
}
func (sched *Scheduler) GetNextTime(t time.Time) time.Time {
Dur, _ := time.ParseDuration("1m")
t = t.Add(Dur)
day, month, year := sched.getNextDay(t, 0)
if day > int(t.Day()) || month > int(t.Month()) || year > int(t.Year()) {
return time.Date(year, time.Month(month), day, sched.HourInt[0],
sched.MinInt[0], 0, 0, t.Location())
}
addDay, hour, min := sched.getNextHourMin(t, 0)
if addDay {
day, month, year := sched.getNextDay(t, 1)
return time.Date(year, time.Month(month), day, sched.HourInt[0],
sched.MinInt[0], 0, 0, t.Location())
}
return time.Date(year, time.Month(month), day, hour, min, 0, 0, t.Location())
}
func (sched *Scheduler) getNextHourMin(t time.Time, add int) (bool, int, int) {
min := int(t.Minute())
hour := int(t.Hour())
minI := getNextI(min, sched.MinInt)
hourI := getNextI(hour, sched.HourInt)
if sched.HourInt[hourI] >= hour && sched.MinInt[minI] >= min {
return false, sched.HourInt[hourI], sched.MinInt[minI]
}
if sched.HourInt[hourI] < hour {
return true, 0, 0
}
minI = (minI + 1) % len(sched.MinInt)
if sched.MinInt[minI] < min {
hourI = (hourI + 1) % len(sched.HourInt)
minI = 0
}
if sched.HourInt[hourI] >= hour {
return false, sched.HourInt[hourI], sched.MinInt[minI]
}
return true, 0, 0
}
func (sched *Scheduler) getNextDay(t time.Time, add int) (int, int, int) {
D, _ := time.ParseDuration("24h")
day := int(t.Day())
dayW := int(t.Weekday())
month := int(t.Month())
year := int(t.Year())
if sched.checkDay(day, dayW, month) {
return day, month, year
}
// 28 years * 365 day + 7 (of 29/02) = 10227 It's full cyle for "day of week", "day of month" and "month"
for i := 0; i < 10230; i++ {
t = t.Add(D)
day = int(t.Day())
dayW = int(t.Weekday())
month = int(t.Month())
year = int(t.Year())
if sched.checkDay(day, dayW, month) {
return day, month, year
}
}
return 0, 0, 0
}
func (sched *Scheduler) checkDay(day, dayW, month int) bool {
if !checkList(dayW, sched.DayWInt) {
return false
}
if !checkList(month, sched.MonthInt) {
return false
}
if !checkList(day, sched.DayMInt) {
return false
}
return true
}
func checkList(v int, list []int) bool {
for _, d := range list {
if d == v {
return true
}
}
return false
}
func getNextI(v int, list []int) int {
if v <= list[0] || list[len(list)-1] < v {
return 0
}
for i := 1; i < len(list); i++ {
if list[i-1] < v && v <= list[i] {
return i
}
}
return -1
} | bratok/src/Config/CronScheduler/CronScheduler.go | 0.530723 | 0.467514 | CronScheduler.go | starcoder |
package smetrics
// BytePair structs hold a pair of bytes
type BytePair struct {
firstByte byte
secondByte byte
}
//DefaultSubstitutionWeights holds weights for common misidentifications of
// letters and numbers taken from https://www.ismp.org/resources/misidentification-alphanumeric-symbols
var DefaultSubstitutionWeights = map[BytePair]int{
BytePair{'l', '1'}: 1,
BytePair{'b', '6'}: 1,
BytePair{'o', '0'}: 1,
BytePair{'g', '9'}: 1,
BytePair{'q', '9'}: 1,
BytePair{'G', '6'}: 1,
BytePair{'F', '7'}: 1,
BytePair{'Z', '2'}: 1,
BytePair{'Z', '7'}: 1,
BytePair{'Q', '2'}: 1,
BytePair{'O', '0'}: 1,
BytePair{'B', '8'}: 1,
BytePair{'D', '0'}: 1,
BytePair{'S', '5'}: 1,
BytePair{'S', '8'}: 1,
BytePair{'Y', '5'}: 1,
BytePair{'T', '7'}: 1,
BytePair{'U', '0'}: 1,
BytePair{'U', '4'}: 1,
BytePair{'A', '4'}: 1,
BytePair{'}', '1'}: 1,
BytePair{'{', '1'}: 1,
BytePair{'0', '8'}: 3,
BytePair{'3', '9'}: 3,
BytePair{'3', '8'}: 3,
BytePair{'4', '9'}: 3,
BytePair{'5', '8'}: 3,
BytePair{'3', '5'}: 3,
BytePair{'6', '8'}: 3,
BytePair{'0', '9'}: 3,
BytePair{'7', '1'}: 3,
BytePair{'g', 'q'}: 1,
BytePair{'p', 'n'}: 1,
BytePair{'m', 'n'}: 1,
BytePair{'y', 'z'}: 1,
BytePair{'u', 'v'}: 1,
BytePair{'c', 'e'}: 1,
BytePair{'l', 'I'}: 1,
BytePair{'T', 'I'}: 1,
BytePair{'D', 'O'}: 1,
BytePair{'C', 'G'}: 1,
BytePair{'L', 'I'}: 1,
BytePair{'M', 'N'}: 1,
BytePair{'P', 'B'}: 1,
BytePair{'F', 'R'}: 1,
BytePair{'U', 'O'}: 1,
BytePair{'U', 'V'}: 1,
BytePair{'E', 'F'}: 1,
BytePair{'V', 'W'}: 1,
BytePair{'X', 'Y'}: 1,
}
// WagnerFischer computes the Levenshtein Distance using the Wagner-Fisher algorithm
func WagnerFischer(aStr, bStr string, icost, dcost, scost int) int {
// Convert to runes to support multibyte characters
a := []rune(aStr)
b := []rune(bStr)
// Allocate both rows.
row1 := make([]int, len(b)+1)
row2 := make([]int, len(b)+1)
var tmp []int
// Initialize the first row.
for i := 1; i <= len(b); i++ {
row1[i] = i * icost
}
// For each row...
for i := 1; i <= len(a); i++ {
row2[0] = i * dcost
// For each column...
for j := 1; j <= len(b); j++ {
if a[i-1] == b[j-1] {
row2[j] = row1[j-1]
} else {
ins := row2[j-1] + icost
del := row1[j] + dcost
sub := row1[j-1] + scost
if ins < del && ins < sub {
row2[j] = ins
} else if del < sub {
row2[j] = del
} else {
row2[j] = sub
}
}
}
// Swap the rows at the end of each row.
tmp = row1
row1 = row2
row2 = tmp
}
// Because we swapped the rows, the final result is in row1 instead of row2.
return row1[len(row1)-1]
}
// WagnerFischerWithWeightedSubs computes the Levenshtein Distance with substitution weights given as a map of bytes to maps of bytes to int
func WagnerFischerWithWeightedSubs(a, b string, icost, dcost, scost int, substitutionWeights map[BytePair]int) int {
// Allocate both rows.
row1 := make([]int, len(b)+1)
row2 := make([]int, len(b)+1)
var tmp []int
// Initialize the first row.
for i := 1; i <= len(b); i++ {
row1[i] = i * icost
}
// For each row...
for i := 1; i <= len(a); i++ {
row2[0] = i * dcost
// For each column...
for j := 1; j <= len(b); j++ {
if a[i-1] == b[j-1] {
row2[j] = row1[j-1]
} else {
ins := row2[j-1] + icost
del := row1[j] + dcost
finalScost := scost
if weight, foundPair := substitutionWeights[BytePair{a[i-1], b[j-1]}]; foundPair {
finalScost = weight
}
if weight, foundPair := substitutionWeights[BytePair{b[j-1], a[i-1]}]; foundPair {
if weight < finalScost {
finalScost = weight
}
}
sub := row1[j-1] + finalScost
if ins < del && ins < sub {
row2[j] = ins
} else if del < sub {
row2[j] = del
} else {
row2[j] = sub
}
}
}
// Swap the rows at the end of each row.
tmp = row1
row1 = row2
row2 = tmp
}
// Because we swapped the rows, the final result is in row1 instead of row2.
return row1[len(row1)-1]
} | wagner-fischer.go | 0.649023 | 0.459319 | wagner-fischer.go | starcoder |
Package featureflag implements simple feature-flagging.
Feature flags can become an anti-pattern if abused.
We should try to use them for two use-cases:
- `Preview` feature flags enable a piece of functionality we haven't yet fully baked. The user needs to 'opt-in'.
We expect these flags to be removed at some time. Normally these will default to false.
- Escape-hatch feature flags turn off a default that we consider risky (e.g. pre-creating DNS records).
This lets us ship a behaviour, and if we encounter unusual circumstances in the field, we can
allow the user to turn the behaviour off. Normally these will default to true.
Feature flags are set via a single environment variable.
The value is a string of feature flag keys separated by sequences of
whitespace and comma.
Each key can be prefixed with `+` (enable flag) or `-` (disable flag).
Without prefix the flag gets enabled.
*/
package featureflag
import (
"os"
"regexp"
"sync"
"k8s.io/klog/v2"
)
const (
// Name is the name of the environment variable which encapsulates feature flags.
Name = "STEWARD_FEATURE_FLAGS"
)
func init() {
ParseFlags(os.Getenv(Name))
}
var (
flags = make(map[string]*FeatureFlag)
flagsMutex sync.Mutex
)
// FeatureFlag defines a feature flag
type FeatureFlag struct {
Key string
enabled *bool
defaultValue *bool
}
// New creates a new feature flag.
func New(key string, defaultValue *bool) *FeatureFlag {
flagsMutex.Lock()
defer flagsMutex.Unlock()
f := flags[key]
if f == nil {
f = &FeatureFlag{
Key: key,
}
flags[key] = f
}
if f.defaultValue == nil {
f.defaultValue = defaultValue
}
return f
}
// Enabled checks if the flag is enabled.
func (f *FeatureFlag) Enabled() bool {
if f.enabled != nil {
return *f.enabled
}
if f.defaultValue != nil {
return *f.defaultValue
}
return false
}
// Bool returns a pointer to the boolean value.
func Bool(b bool) *bool {
return &b
}
// ParseFlags is responsible for parse out the feature flag usage.
func ParseFlags(f string) {
if f == "" {
return
}
for _, s := range regexp.MustCompile(`[[:space:],]+`).Split(f, -1) {
if s == "" {
continue
}
enabled := true
var ff *FeatureFlag
if s[0] == '+' || s[0] == '-' {
ff = New(s[1:], nil)
if s[0] == '-' {
enabled = false
}
} else {
ff = New(s, nil)
}
klog.InfoS("feature flag", "key", ff.Key, "enabled", enabled)
ff.enabled = &enabled
}
} | pkg/featureflag/types.go | 0.748168 | 0.608361 | types.go | starcoder |
package wm
// DatacubeParams represent common parameters for requesting model run data
type DatacubeParams struct {
DataID string `json:"data_id"`
RunID string `json:"run_id"`
Feature string `json:"feature"`
Resolution string `json:"resolution"`
TemporalAggFunc string `json:"temporal_agg"`
SpatialAggFunc string `json:"spatial_agg"`
}
// FullTimeseriesParams represent all parameters for fetching a timeseries
type FullTimeseriesParams struct {
DatacubeParams
RegionID string `json:"region_id"`
Transform Transform `json:"transform"`
Key string `json:"key"`
}
// RegionListParams represent parameters needed to fetch region lists representing the hierarchy
type RegionListParams struct {
DataID string `json:"data_id"`
RunIDs []string `json:"run_ids"`
Feature string `json:"feature"`
}
// QualifierInfoParams represent common parameters needed to fetch summary info about qualifiers
type QualifierInfoParams struct {
DataID string `json:"data_id"`
RunID string `json:"run_id"`
Feature string `json:"feature"`
}
// PipelineResultsParams represent parameters needed to fetch pipeline results
type PipelineResultsParams struct {
DataID string `json:"data_id"`
RunID string `json:"run_id"`
}
// TimeseriesValue represent a timeseries data point
type TimeseriesValue struct {
Timestamp int64 `json:"timestamp"`
Value float64 `json:"value"`
}
// ModelOutputRawDataPoint represent a raw data point
type ModelOutputRawDataPoint struct {
Timestamp int64 `json:"timestamp"`
Country string `json:"country"`
Admin1 string `json:"admin1"`
Admin2 string `json:"admin2"`
Admin3 string `json:"admin3"`
Lat *float64 `json:"lat"`
Lng *float64 `json:"lng"`
Value *float64 `json:"value"`
Qualifiers map[string]string `json:"qualifiers"`
}
// ModelOutputQualifierTimeseries represent a timeseries for one qualifier value
type ModelOutputQualifierTimeseries struct {
Name string `json:"name"`
Timeseries []*TimeseriesValue `json:"timeseries"`
}
// ModelOutputKeyedTimeSeries holds time series values for a unique key
type ModelOutputKeyedTimeSeries struct {
Key string `json:"key"`
Timeseries []*TimeseriesValue `json:"timeseries"`
}
// ModelOutputRegionalTimeSeries holds regional time series values
type ModelOutputRegionalTimeSeries struct {
RegionID string `json:"region_id"`
Timeseries []*TimeseriesValue `json:"timeseries"`
}
// ModelOutputRegionQualifierBreakdown represent a list of qualifier breakdown values for a specific region
type ModelOutputRegionQualifierBreakdown struct {
ID string `json:"id"`
Values map[string]float64 `json:"values"`
}
// ModelOutputQualifierBreakdown represent a list of qualifier breakdown values
type ModelOutputQualifierBreakdown struct {
Name string `json:"name"`
Options []*ModelOutputQualifierValue `json:"options"`
}
// ModelOutputQualifierValue represent a breakdown value for one qualifier value
type ModelOutputQualifierValue struct {
Name string `json:"name"`
Value *float64 `json:"value"` //nil represents missing value
}
// ModelOutputStat represent min and max stat of the model output data
type ModelOutputStat struct {
Min float64 `json:"min"`
Max float64 `json:"max"`
}
// OutputStatWithZoom represent min and max stat of the output data for a specific zoom level
type OutputStatWithZoom struct {
Zoom uint8 `json:"zoom"`
Min float64 `json:"min"`
Max float64 `json:"max"`
}
// ModelRegionalOutputStat represent regional data for all admin levels
type ModelRegionalOutputStat struct {
Country *ModelOutputStat `json:"country"`
Admin1 *ModelOutputStat `json:"admin1"`
Admin2 *ModelOutputStat `json:"admin2"`
Admin3 *ModelOutputStat `json:"admin3"`
}
// RegionListOutput represents region list hierarchies for all admin levels
type RegionListOutput struct {
Country []string `json:"country"`
Admin1 []string `json:"admin1"`
Admin2 []string `json:"admin2"`
Admin3 []string `json:"admin3"`
}
// QualifierCountsOutput provides the number of qualifier values per qualifier
// as well as the thresholds used when computing
type QualifierCountsOutput struct {
Thresholds map[string]int32 `json:"thresholds"`
Counts map[string]int32 `json:"counts"`
}
// QualifierListsOutput provides a mapping of qualifiers to a list of all its values
type QualifierListsOutput map[string][]string
// PipelineResultsOutput represents the pipeline results file
type PipelineResultsOutput struct {
OutputAggValues []interface{} `json:"output_agg_values,omitempty"`
DataInfo interface{} `json:"data_info"`
}
// Timestamps holds input for bulk-regional-data
type Timestamps struct {
Timestamps []string `json:"timestamps"`
AllTimestamps []string `json:"all_timestamps"`
}
// ModelOutputBulkAggregateRegionalAdmins holds all bulk and aggregate regional data
type ModelOutputBulkAggregateRegionalAdmins struct {
ModelOutputBulkRegionalAdmins *[]ModelOutputBulkRegionalAdmins `json:"regional_data"`
SelectAgg *ModelOutputRegionalAdmins `json:"select_agg"`
AllAgg *ModelOutputRegionalAdmins `json:"all_agg"`
}
// ModelOutputBulkRegionalAdmins associates a timestamp for regional data
type ModelOutputBulkRegionalAdmins struct {
Timestamp string `json:"timestamp"`
*ModelOutputRegionalAdmins `json:"data"`
}
// ModelOutputRegionalAdmins represent regional data for all admin levels
type ModelOutputRegionalAdmins struct {
Country []ModelOutputAdminData `json:"country"`
Admin1 []ModelOutputAdminData `json:"admin1"`
Admin2 []ModelOutputAdminData `json:"admin2"`
Admin3 []ModelOutputAdminData `json:"admin3"`
}
// ModelOutputRegionalQualifiers represent regional data for all admin levels broken down by qualifiers
type ModelOutputRegionalQualifiers struct {
Country []ModelOutputRegionQualifierBreakdown `json:"country"`
Admin1 []ModelOutputRegionQualifierBreakdown `json:"admin1"`
Admin2 []ModelOutputRegionQualifierBreakdown `json:"admin2"`
Admin3 []ModelOutputRegionQualifierBreakdown `json:"admin3"`
}
// ModelOutputAdminData represent a data point of regional data
type ModelOutputAdminData struct {
ID string `json:"id"`
Value float64 `json:"value"`
}
// Transform is type for available transforms
type Transform string
// Available transforms
const (
TransformPerCapita Transform = "percapita"
TransformPerCapita1K Transform = "percapita1k"
TransformPerCapita1M Transform = "percapita1m"
TransformNormalization Transform = "normalization"
)
// TransformConfig defines transform configuration
type TransformConfig struct {
Transform Transform `json:"transform"`
RegionID string `json:"region_id"`
ScaleFactor float64 `json:"scale_factor"`
}
// DataOutput defines the methods that output database implementation needs to satisfy
type DataOutput interface {
// GetTile returns mapbox vector tile
GetTile(zoom, x, y uint32, specs GridTileOutputSpecs, expression string) (*Tile, error)
// GetOutputStats returns datacube output stats
GetOutputStats(params DatacubeParams, timestamp string) ([]*OutputStatWithZoom, error)
// GetRegionalOutputStats returns regional output statistics
GetRegionalOutputStats(params DatacubeParams) (*ModelRegionalOutputStat, error)
// GetOutputTimeseries returns datacube output timeseries
GetOutputTimeseries(params DatacubeParams) ([]*TimeseriesValue, error)
// GetOutputTimeseriesByRegion returns timeseries data for a specific region
GetOutputTimeseriesByRegion(params DatacubeParams, regionID string) ([]*TimeseriesValue, error)
// GetRegionAggregation returns regional data for ALL admin regions at ONE timestamp
GetRegionAggregation(params DatacubeParams, timestamp string) (*ModelOutputRegionalAdmins, error)
// GetRawData returns datacube raw data
GetRawData(params DatacubeParams) ([]*ModelOutputRawDataPoint, error)
// GetRegionLists returns region hierarchies in list form
GetRegionLists(params RegionListParams) (*RegionListOutput, error)
// GetQualifierCounts returns region hierarchy output
GetQualifierCounts(params QualifierInfoParams) (*QualifierCountsOutput, error)
// GetQualifierLists returns region hierarchy output
GetQualifierLists(params QualifierInfoParams, qualifiers []string) (*QualifierListsOutput, error)
// GetPipelineResults returns the pipeline results file
GetPipelineResults(params PipelineResultsParams) (*PipelineResultsOutput, error)
// GetQualifierTimeseries returns datacube output timeseries broken down by qualifiers
GetQualifierTimeseries(params DatacubeParams, qualifier string, qualifierOptions []string) ([]*ModelOutputQualifierTimeseries, error)
// GetQualifierTimeseriesByRegion returns datacube output timeseries broken down by qualifiers for a specific region
GetQualifierTimeseriesByRegion(params DatacubeParams, qualifier string, qualifierOptions []string, regionID string) ([]*ModelOutputQualifierTimeseries, error)
// GetQualifierData returns datacube output data broken down by qualifiers for ONE timestamp
GetQualifierData(params DatacubeParams, timestamp string, qualifiers []string) ([]*ModelOutputQualifierBreakdown, error)
// GetQualifierRegional returns datacube output data broken down by qualifiers for ONE timestamp
GetQualifierRegional(params DatacubeParams, timestamp string, qualifier string) (*ModelOutputRegionalQualifiers, error)
// TransformOutputTimeseriesByRegion returns transformed timeseries data
TransformOutputTimeseriesByRegion(timeseries []*TimeseriesValue, config TransformConfig) ([]*TimeseriesValue, error)
// TransformRegionAggregation returns transformed regional data for ALL admin regions at ONE timestamp
TransformRegionAggregation(data *ModelOutputRegionalAdmins, timestamp string, config TransformConfig) (*ModelOutputRegionalAdmins, error)
// TransformOutputQualifierTimeseriesByRegion returns transformed qualifier timeseries data
TransformOutputQualifierTimeseriesByRegion(data []*ModelOutputQualifierTimeseries, config TransformConfig) ([]*ModelOutputQualifierTimeseries, error)
// TransformQualifierRegional returns transformed qualifier regional data for ALL admin regions at ONE timestamp
TransformQualifierRegional(data *ModelOutputRegionalQualifiers, timestamp string, config TransformConfig) (*ModelOutputRegionalQualifiers, error)
}
// VectorTile defines methods that tile storage/database needs to satisfy
type VectorTile interface {
GetVectorTile(zoom, x, y uint32, tilesetName string) ([]byte, error)
} | pkg/wm/maas.go | 0.783285 | 0.445952 | maas.go | starcoder |
package countrymaam
import (
"bytes"
"encoding/gob"
"io"
"github.com/ar90n/countrymaam/number"
)
type Index[T number.Number, U any] interface {
Add(feature []T, item U)
Search(feature []T, n uint, maxCandidates uint) ([]Candidate[U], error)
Build() error
HasIndex() bool
Save(reader io.Writer) error
}
type Candidate[U any] struct {
Distance float64
Item U
}
func saveIndex[T any](index *T, w io.Writer) error {
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
if err := enc.Encode(index); err != nil {
return err
}
beg := 0
byteArray := buffer.Bytes()
for beg < len(byteArray) {
n, err := w.Write(byteArray[beg:])
if err != nil {
return err
}
beg += n
}
return nil
}
func loadIndex[T any](r io.Reader) (ret T, _ error) {
dec := gob.NewDecoder(r)
if err := dec.Decode(&ret); err != nil {
return ret, err
}
return ret, nil
}
func NewFlatIndex[T number.Number, U any](dim uint) *flatIndex[T, U] {
return &flatIndex[T, U]{
Dim: dim,
Features: make([][]T, 0),
Items: make([]U, 0),
}
}
func LoadFlatIndex[T number.Number, U any](r io.Reader) (*flatIndex[T, U], error) {
index, err := loadIndex[flatIndex[T, U]](r)
if err != nil {
return nil, err
}
return &index, nil
}
func NewKdTreeIndex[T number.Number, U any](dim uint, leafSize uint) *bspTreeIndex[T, U, kdCutPlane[T, U]] {
gob.Register(kdCutPlane[T, U]{})
return &bspTreeIndex[T, U, kdCutPlane[T, U]]{
Dim: dim,
Pool: make([]treeElement[T, U], 0, 4096),
Roots: make([]*treeNode[T, U], 1),
LeafSize: leafSize,
}
}
func LoadKdTreeIndex[T number.Number, U any](r io.Reader) (*bspTreeIndex[T, U, kdCutPlane[T, U]], error) {
gob.Register(kdCutPlane[T, U]{})
index, err := loadIndex[bspTreeIndex[T, U, kdCutPlane[T, U]]](r)
if err != nil {
return nil, err
}
return &index, nil
}
func NewRpTreeIndex[T number.Number, U any](dim uint, leafSize uint) *bspTreeIndex[T, U, rpCutPlane[T, U]] {
gob.Register(rpCutPlane[T, U]{})
return &bspTreeIndex[T, U, rpCutPlane[T, U]]{
Dim: dim,
Pool: make([]treeElement[T, U], 0),
Roots: make([]*treeNode[T, U], 1),
LeafSize: leafSize,
}
}
func LoadRpTreeIndex[T number.Number, U any](r io.Reader) (*bspTreeIndex[T, U, rpCutPlane[T, U]], error) {
gob.Register(rpCutPlane[T, U]{})
index, err := loadIndex[bspTreeIndex[T, U, rpCutPlane[T, U]]](r)
if err != nil {
return nil, err
}
return &index, nil
}
func NewRandomizedKdTreeIndex[T number.Number, U any](dim uint, leafSize uint, nTrees uint) *bspTreeIndex[T, U, randomizedKdCutPlane[T, U]] {
gob.Register(kdCutPlane[T, U]{})
gob.Register(randomizedKdCutPlane[T, U]{})
return &bspTreeIndex[T, U, randomizedKdCutPlane[T, U]]{
Dim: dim,
Pool: make([]treeElement[T, U], 0),
Roots: make([]*treeNode[T, U], nTrees),
LeafSize: leafSize,
}
}
func LoadRandomizedKdTreeIndex[T number.Number, U any](r io.Reader) (*bspTreeIndex[T, U, randomizedKdCutPlane[T, U]], error) {
gob.Register(kdCutPlane[T, U]{})
gob.Register(randomizedKdCutPlane[T, U]{})
index, err := loadIndex[bspTreeIndex[T, U, randomizedKdCutPlane[T, U]]](r)
if err != nil {
return nil, err
}
return &index, nil
}
func NewRandomizedRpTreeIndex[T number.Number, U any](dim uint, leafSize uint, nTrees uint) *bspTreeIndex[T, U, rpCutPlane[T, U]] {
gob.Register(rpCutPlane[T, U]{})
return &bspTreeIndex[T, U, rpCutPlane[T, U]]{
Dim: dim,
Pool: make([]treeElement[T, U], 0, 4096),
Roots: make([]*treeNode[T, U], nTrees),
LeafSize: leafSize,
}
}
func LoadRandomizedRpTreeIndex[T number.Number, U any](r io.Reader) (*bspTreeIndex[T, U, rpCutPlane[T, U]], error) {
gob.Register(rpCutPlane[T, U]{})
index, err := loadIndex[bspTreeIndex[T, U, rpCutPlane[T, U]]](r)
if err != nil {
return nil, err
}
return &index, nil
} | countrymaam.go | 0.551332 | 0.434041 | countrymaam.go | starcoder |
package msf
import (
"errors"
"fmt"
"math"
"sort"
"strconv"
)
type Splice struct {
Drive int
Length float32
}
type Ping struct {
Length float32
Extrusion float32
}
type Algorithm struct {
Ingoing int
Outgoing int
HeatFactor float32
CompressionFactor float32
CoolingFactor float32
Reverse bool
}
type MSF struct {
Palette *Palette
DrivesUsed []bool
SpliceList []Splice
PingList []Ping
}
func NewMSF(paletteData *Palette) MSF {
return MSF{
Palette: paletteData,
DrivesUsed: make([]bool, paletteData.GetInputCount()),
SpliceList: make([]Splice, 0),
PingList: make([]Ping, 0),
}
}
func (msf *MSF) GetRequiredExtraSpliceLength(spliceLength float32) float32 {
if len(msf.SpliceList) == 0 {
// first splice
minLength := msf.Palette.GetFirstSpliceMinLength()
if spliceLength < minLength {
return minLength - spliceLength
}
return 0
}
// all other splices
spliceDelta := spliceLength - msf.SpliceList[len(msf.SpliceList)-1].Length
minSpliceLength := msf.Palette.GetSpliceMinLength()
if spliceDelta < minSpliceLength {
return minSpliceLength - spliceDelta
}
return 0
}
func (msf *MSF) addSplice(splice Splice) error {
// splice length validation first
if len(msf.SpliceList) == 0 {
// first splice
minLength := msf.Palette.GetFirstSpliceMinLength()
if splice.Length < minLength - 5 {
message := "First Piece Too Short\n"
message += fmt.Sprintf("The first piece created by %s would be %.2f mm long, but must be at least %.2f mm.", msf.Palette.ProductName(), splice.Length, minLength)
return errors.New(message)
}
} else {
// all others
spliceDelta := splice.Length - msf.SpliceList[len(msf.SpliceList)-1].Length
minSpliceLength := msf.Palette.GetSpliceMinLength()
if spliceDelta < minSpliceLength - 5 {
message := "Piece Too Short\n"
message += fmt.Sprintf("Canvas attempted to create a splice that was %.2f mm long, but %s's minimum splice length is %.2f mm.", spliceDelta, msf.Palette.ProductName(), minSpliceLength)
return errors.New(message)
}
}
msf.SpliceList = append(msf.SpliceList, splice)
msf.DrivesUsed[splice.Drive] = true
return nil
}
func (msf *MSF) AddSplice(drive int, length float32) error {
return msf.addSplice(Splice{
Drive: drive,
Length: length,
})
}
func (msf *MSF) AddLastSplice(drive int, finalLength float32) error {
prevSpliceLength := float32(0)
requiredLength := msf.Palette.GetFirstSpliceMinLength()
if len(msf.SpliceList) > 0 {
prevSplice := msf.SpliceList[len(msf.SpliceList)-1]
prevSpliceLength = prevSplice.Length
requiredLength = msf.Palette.GetSpliceMinLength()
}
extraLength := (finalLength - prevSpliceLength) * 0.04
if (finalLength - prevSpliceLength) < requiredLength {
extraLength += requiredLength - (finalLength - prevSpliceLength)
}
splice := Splice{
Drive: drive,
Length: finalLength + extraLength + msf.Palette.BowdenTubeLength,
}
effectiveLoadingOffset := msf.Palette.GetEffectiveLoadingOffset()
if effectiveLoadingOffset > 2000 {
if splice.Length < 2000 {
splice.Length = 2000
}
} else {
if splice.Length < (effectiveLoadingOffset * 1.02) {
splice.Length = effectiveLoadingOffset * 1.02
}
}
return msf.addSplice(splice)
}
func (msf *MSF) addPing(ping Ping) {
msf.PingList = append(msf.PingList, ping)
}
func (msf *MSF) AddPing(length float32) {
msf.addPing(Ping{
Length: length,
Extrusion: 0,
})
}
func (msf *MSF) AddPingWithExtrusion(length, extrusion float32) {
msf.addPing(Ping{
Length: length,
Extrusion: extrusion,
})
}
func (msf *MSF) GetFilamentLengthsByDrive() []float32 {
lengths := make([]float32, msf.Palette.GetInputCount())
if len(msf.SpliceList) == 0 {
return lengths
}
cumulativeLength := float32(0)
for _, splice := range msf.SpliceList {
lengths[splice.Drive] += splice.Length - cumulativeLength
cumulativeLength = splice.Length
}
return lengths
}
func (msf *MSF) GetTotalFilamentLength() float32 {
if len(msf.SpliceList) == 0 {
return 0
}
return msf.SpliceList[len(msf.SpliceList)-1].Length
}
func (msf *MSF) GetOutputAlgorithmsList() []Algorithm {
numInputs := msf.Palette.GetInputCount()
algIsPresent := make([][]bool, 0, numInputs)
for i := 0; i < numInputs; i++ {
algIsPresent = append(algIsPresent, make([]bool, numInputs))
}
algs := make([]Algorithm, 0)
firstSplice := true
outgoingExt := 0
var ingoingExt int
// "combination" algorithms (splicing two different drives, when transitioning)
for _, splice := range msf.SpliceList {
ingoingExt = splice.Drive
if !firstSplice {
ingoingIndex := msf.Palette.MaterialMeta[ingoingExt].Index
outgoingIndex := msf.Palette.MaterialMeta[outgoingExt].Index
ingoingId := strconv.Itoa(ingoingIndex)
outgoingId := strconv.Itoa(outgoingIndex)
if !algIsPresent[ingoingIndex - 1][outgoingIndex - 1] {
for _, spliceSettings := range msf.Palette.SpliceSettings {
if spliceSettings.IngoingID == ingoingId &&
spliceSettings.OutgoingID == outgoingId {
alg := Algorithm{
Ingoing: ingoingIndex,
Outgoing: outgoingIndex,
HeatFactor: spliceSettings.HeatFactor,
CompressionFactor: spliceSettings.CompressionFactor,
CoolingFactor: spliceSettings.CoolingFactor,
Reverse: spliceSettings.Reverse,
}
algs = append(algs, alg)
break
}
}
algIsPresent[ingoingIndex - 1][outgoingIndex - 1] = true
}
}
outgoingExt = ingoingExt
firstSplice = false
}
// "self-splicing" algorithms (splicing a drive with itself, for run-out detection or hot-swapping)
// (included manually as MSF will not contain any self-splices)
for drive := 0; drive < numInputs; drive++ {
if msf.DrivesUsed[drive] {
materialIndex := msf.Palette.MaterialMeta[drive].Index
materialId := strconv.Itoa(materialIndex)
if !algIsPresent[materialIndex - 1][materialIndex - 1] {
for _, spliceSettings := range msf.Palette.SpliceSettings {
if spliceSettings.IngoingID == materialId &&
spliceSettings.OutgoingID == materialId {
alg := Algorithm{
Ingoing: materialIndex,
Outgoing: materialIndex,
HeatFactor: spliceSettings.HeatFactor,
CompressionFactor: spliceSettings.CompressionFactor,
CoolingFactor: spliceSettings.CoolingFactor,
Reverse: spliceSettings.Reverse,
}
algs = append(algs, alg)
break
}
}
algIsPresent[materialIndex - 1][materialIndex - 1] = true
}
}
}
sort.Slice(algs, func(i, j int) bool {
a := algs[i]
b := algs[j]
if a.Ingoing != b.Ingoing {
return a.Ingoing < b.Ingoing
}
return a.Outgoing < b.Outgoing
})
return algs
}
func (msf *MSF) GetMSF2Header() string {
header := msf.createMSF2()
// start multicolor mode
msfFilename := replaceSpaces(truncate(msf.Palette.Filename, charLimitMSF2))
printLength := msf.GetTotalFilamentLength()
intLength := uint(math.Ceil(float64(printLength)))
header += "O1 D" + msfFilename + " D" + intToHexString(intLength, 8) + EOL
header += "M0" + EOL
return header
}
func (msf *MSF) GetMSF2Footer() string {
return "O9" + EOL
}
func getMSF2PingLine(ping Ping) string {
line := "O31 D" + floatToHexString(ping.Length)
if ping.Extrusion > 0 {
line += " D" + floatToHexString(ping.Extrusion)
}
line += EOL
return line
}
func getMSF3PingLine(ping Ping) string {
if ping.Extrusion > 0 {
return fmt.Sprintf("O31 L%.2f E%.2f%s", ping.Length, ping.Extrusion, EOL)
}
return fmt.Sprintf("O31 L%.2f%s", ping.Length, EOL)
}
func (msf *MSF) GetConnectedPingLine() string {
pingCount := len(msf.PingList)
if pingCount == 0 || !msf.Palette.ConnectedMode {
return ""
}
if msf.Palette.Type == TypeP2 {
return getMSF2PingLine(msf.PingList[pingCount-1])
}
return getMSF3PingLine(msf.PingList[pingCount-1])
}
func (msf *MSF) createMSF1() string {
const Version = "1.4"
numInputs := msf.Palette.GetInputCount()
algorithmList := msf.GetOutputAlgorithmsList()
pulsesPerMM := msf.Palette.GetPulsesPerMM()
loadingOffset := msf.Palette.LoadingOffset
str := "MSF" + Version + EOL
// drives used
str += "cu:"
for drive := 0; drive < numInputs; drive++ {
material := msf.Palette.MaterialMeta[drive]
str += strconv.Itoa(material.Index)
if material.Index > 0 {
str += truncate(material.Name, charLimitMSF1)
}
str += ";"
}
str += EOL
// pulses per MM
str += "ppm:" + floatToHexString(pulsesPerMM) + EOL
// loading offset
str += "lo:" + intToHexString(uint(loadingOffset), 4) + EOL
// number of splices
str += "ns:" + intToHexString(uint(len(msf.SpliceList)), 4) + EOL
// number of pings
str += "np:" + intToHexString(uint(len(msf.PingList)), 4) + EOL
// number of hot swaps (always 0)
str += "nh:" + intToHexString(0, 4) + EOL
// number of algorithms
str += "na:" + intToHexString(uint(len(algorithmList)), 4) + EOL
// splice list
for _, splice := range msf.SpliceList {
str += "(" + intToHexString(uint(splice.Drive), 2) + "," + floatToHexString(splice.Length) + ")" + EOL
}
// ping list
for _, ping := range msf.PingList {
str += "(64," + floatToHexString(ping.Length) + ")" + EOL
}
// algorithm list
for _, alg := range algorithmList {
str += "(" + strconv.Itoa(alg.Ingoing) + strconv.Itoa(alg.Outgoing) + ","
str += floatToHexString(alg.HeatFactor) + ","
str += floatToHexString(alg.CompressionFactor) + ","
if alg.Reverse {
str += "1"
} else {
str += "0"
}
str += ")" + EOL
}
return str
}
func (msf *MSF) createMSF2() string {
const VersionMajor = 2
const VersionMinor = 0
numInputs := msf.Palette.GetInputCount()
algorithmList := msf.GetOutputAlgorithmsList()
// MSF version
str := msfVersionToO21(VersionMajor, VersionMinor)
// printer profile identifier
str += "O22 D" + msf.Palette.PrinterID + EOL
// style profile identifier (unused)
str += "O23 D0001" + EOL
// adjusted PPM (0 for now)
str += "O24 D0000" + EOL
// materials used
str += "O25"
for drive := 0; drive < numInputs; drive++ {
str += " D"
if msf.DrivesUsed[drive] {
material := msf.Palette.MaterialMeta[drive]
str += intToHexString(uint(material.Index), 1)
if material.Index > 0 {
str += material.Color
str += replaceSpaces(truncate(material.Name, charLimitMSF2))
}
} else {
str += "0"
}
}
str += EOL
// number of splices
str += "O26 D" + intToHexString(uint(len(msf.SpliceList)), 4) + EOL
// number of pings
str += "O27 D" + intToHexString(uint(len(msf.PingList)), 4) + EOL
// number of algorithms
str += "O28 D" + intToHexString(uint(len(algorithmList)), 4) + EOL
// number of hot swaps (0 for now)
str += "O29 D0000" + EOL
// splice data
for _, splice := range msf.SpliceList {
str += "O30 D" + intToHexString(uint(splice.Drive), 1)
str += " D" + floatToHexString(splice.Length) + EOL
}
// ping data
if !msf.Palette.ConnectedMode {
for _, ping := range msf.PingList {
str += getMSF2PingLine(ping)
}
}
// algorithm data
for _, alg := range algorithmList {
str += "O32 D" + intToHexString(uint(alg.Ingoing), 1) + intToHexString(uint(alg.Outgoing), 1)
str += " D" + int16ToHexString(int16(alg.HeatFactor))
str += " D" + int16ToHexString(int16(alg.CompressionFactor))
str += " D" + int16ToHexString(int16(alg.CoolingFactor))
str += EOL
}
// hot swap data (nonexistent for now)
return str
}
func (msf *MSF) createMSF3() (string, error) {
const Version = "3.0"
numInputs := msf.Palette.GetInputCount()
algorithmList := msf.Palette.SpliceSettings
numSplices := len(msf.SpliceList)
numPings := len(msf.PingList)
numAlgorithms := len(algorithmList)
json := palette3Json{
Version: Version,
Drives: make([]int, numInputs),
Splices: make([]palette3Splice, 0, numSplices),
Pings: make([]palette3Ping, 0, numPings),
Algorithms: make([]palette3Algorithm, 0, numAlgorithms),
}
// materials used
for drive := 0; drive < numInputs; drive++ {
if msf.DrivesUsed[drive] {
material := msf.Palette.MaterialMeta[drive]
json.Drives[drive] = material.FilamentID
}
}
// splice data
for _, splice := range msf.SpliceList {
material := msf.Palette.MaterialMeta[splice.Drive]
jsonSplice := palette3Splice{
ID: material.FilamentID,
Length: splice.Length,
}
json.Splices = append(json.Splices, jsonSplice)
}
// ping data
for _, ping := range msf.PingList {
jsonPing := palette3Ping{
Length: ping.Length,
Extrusion: ping.Extrusion,
}
json.Pings = append(json.Pings, jsonPing)
}
// algorithm data
for _, alg := range algorithmList {
iid, err := strconv.Atoi(alg.IngoingID)
if err != nil {
return "", err
}
oid, err := strconv.Atoi(alg.OutgoingID)
if err != nil {
return "", err
}
jsonAlgorithm := palette3Algorithm{
IngoingID: iid,
OutgoingID: oid,
Heat: alg.HeatFactor,
Compression: alg.CompressionFactor,
Cooling: alg.CoolingFactor,
}
json.Algorithms = append(json.Algorithms, jsonAlgorithm)
}
return json.marshal(msf.Palette.ConnectedMode, msf.Palette.Type == TypeElement)
}
func (msf *MSF) CreateMSF() (string, error) {
if msf.Palette.Type == TypeP1 {
return msf.createMSF1(), nil
}
if msf.Palette.Type == TypeP2 {
return msf.createMSF2(), nil
}
return msf.createMSF3()
} | msf/msf.go | 0.784236 | 0.453383 | msf.go | starcoder |
package writer
import pub "github.com/whisperverse/activitystream"
// Accept
func Accept(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeAccept).
Actor(actor).
Object(object)
}
// Add
func Add(actor Object, object Object, target Object) Object {
return NewObject().
Type(pub.ActivityTypeAdd).
Actor(actor).
Object(object).
Target(target)
}
// Announce
func Announce(actor Object, object Object, target Object) Object {
return NewObject().
Type(pub.ActivityTypeAnnounce).
Actor(actor).
Object(object).
Target(target)
}
// Arrive
func Arrive(actor Object, location Object, origin Object) Object {
return NewObject().
Type(pub.ActivityTypeArrive).
Actor(actor).
Location(location).
Origin(origin)
}
// Block
func Block(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeBlock).
Actor(actor).
Object(object)
}
// Create
func Create(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeCreate).
Actor(actor).
Object(object)
}
// Delete
func Delete(actor Object, object Object, origin Object) Object {
return NewObject().
Type(pub.ActivityTypeDelete).
Actor(actor).
Object(object).
Origin(origin)
}
// Dislike
func Dislike(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeDislike).
Actor(actor).
Object(object)
}
// Flag
func Flag(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeFlag).
Actor(actor).
Object(object)
}
// Follow
func Follow(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeFollow).
Actor(actor).
Object(object)
}
// Ignore
func Ignore(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeIgnore).
Actor(actor).
Object(object)
}
// Invite
func Invite(actor Object, object Object, target Object) Object {
return NewObject().
Type(pub.ActivityTypeInvite).
Actor(actor).
Object(object).
Target(target)
}
// Join
func Join(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeJoin).
Actor(actor).
Object(object)
}
// Leave
func Leave(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeLeave).
Actor(actor).
Object(object)
}
// Like
func Like(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeLike).
Actor(actor).
Object(object)
}
// Listen
func Listen(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeListen).
Actor(actor).
Object(object)
}
// Move
func Move(actor Object, object Object, origin Object, target Object) Object {
return NewObject().
Type(pub.ActivityTypeMove).
Actor(actor).
Object(object).
Origin(origin).
Target(target)
}
// Offer
func Offer(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeLike).
Actor(actor).
Object(object)
}
// Question
func Question() Object {
// TODO: this is not complete
return NewObject().
Type(pub.ActivityTypeQuestion)
}
// Reject
func Reject(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeReject).
Actor(actor).
Object(object)
}
// Read
func Read(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeRead).
Actor(actor).
Object(object)
}
// Remove
func Remove(actor Object, object Object, origin Object) Object {
return NewObject().
Type(pub.ActivityTypeRemove).
Actor(actor).
Object(object).
Origin(origin)
}
// TentativeAccept
func TentativeAccept(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeTentativeAccept).
Actor(actor).
Object(object)
}
// TentativeReject
func TentativeReject(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeTentativeReject).
Actor(actor).
Object(object)
}
// Travel
func Travel(actor Object, origin Object, target Object) Object {
return NewObject().
Type(pub.ActivityTypeTravel).
Actor(actor).
Origin(origin).
Target(target)
}
// Undo
func Undo(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeUndo).
Actor(actor).
Object(object)
}
// Update
func Update(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeUpdate).
Actor(actor).
Object(object)
}
// View
func View(actor Object, object Object) Object {
return NewObject().
Type(pub.ActivityTypeView).
Actor(actor).
Object(object)
} | writer/activities.go | 0.514888 | 0.477676 | activities.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// InferenceData
type InferenceData struct {
// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
additionalData map[string]interface{}
// Confidence score reflecting the accuracy of the data inferred about the user.
confidenceScore *float64
// Records if the user has confirmed this inference as being True or False.
userHasVerifiedAccuracy *bool
}
// NewInferenceData instantiates a new inferenceData and sets the default values.
func NewInferenceData()(*InferenceData) {
m := &InferenceData{
}
m.SetAdditionalData(make(map[string]interface{}));
return m
}
// CreateInferenceDataFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateInferenceDataFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewInferenceData(), nil
}
// GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *InferenceData) GetAdditionalData()(map[string]interface{}) {
if m == nil {
return nil
} else {
return m.additionalData
}
}
// GetConfidenceScore gets the confidenceScore property value. Confidence score reflecting the accuracy of the data inferred about the user.
func (m *InferenceData) GetConfidenceScore()(*float64) {
if m == nil {
return nil
} else {
return m.confidenceScore
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *InferenceData) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))
res["confidenceScore"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetConfidenceScore(val)
}
return nil
}
res["userHasVerifiedAccuracy"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetUserHasVerifiedAccuracy(val)
}
return nil
}
return res
}
// GetUserHasVerifiedAccuracy gets the userHasVerifiedAccuracy property value. Records if the user has confirmed this inference as being True or False.
func (m *InferenceData) GetUserHasVerifiedAccuracy()(*bool) {
if m == nil {
return nil
} else {
return m.userHasVerifiedAccuracy
}
}
// Serialize serializes information the current object
func (m *InferenceData) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
{
err := writer.WriteFloat64Value("confidenceScore", m.GetConfidenceScore())
if err != nil {
return err
}
}
{
err := writer.WriteBoolValue("userHasVerifiedAccuracy", m.GetUserHasVerifiedAccuracy())
if err != nil {
return err
}
}
{
err := writer.WriteAdditionalData(m.GetAdditionalData())
if err != nil {
return err
}
}
return nil
}
// SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *InferenceData) SetAdditionalData(value map[string]interface{})() {
if m != nil {
m.additionalData = value
}
}
// SetConfidenceScore sets the confidenceScore property value. Confidence score reflecting the accuracy of the data inferred about the user.
func (m *InferenceData) SetConfidenceScore(value *float64)() {
if m != nil {
m.confidenceScore = value
}
}
// SetUserHasVerifiedAccuracy sets the userHasVerifiedAccuracy property value. Records if the user has confirmed this inference as being True or False.
func (m *InferenceData) SetUserHasVerifiedAccuracy(value *bool)() {
if m != nil {
m.userHasVerifiedAccuracy = value
}
} | models/inference_data.go | 0.806129 | 0.469277 | inference_data.go | starcoder |
package scramPkg
import (
"encoding/csv"
"fmt"
"log"
"math"
"os"
"path/filepath"
"strconv"
)
//CompareNoSplitCounts takes and alignment map and returns a map with the ref_header as key and the
//mean_se (mean and standard error) of aligned reads for that ref seq as value. Read counts are NOT split by the number
//of times a read aligns to all reference sequences.
func CompareNoSplitCounts(alignmentMap map[string]map[string][]int, seqMap map[string]interface{}) map[string]interface{} {
//cdp_alignment_map := make(map[string]meanSe)
cdpAlignmentMap := make(map[string]interface{})
for header, alignment := range alignmentMap {
var headerMeanCounts float64
var meanCountsErr []float64
var headerCounts []float64
firstPos := true
for srna, pos := range alignment {
switch v := seqMap[srna].(type) {
case *meanSe:
headerMeanCounts += v.Mean * float64(len(pos))
meanCountsErr = append(meanCountsErr, v.Se*float64(len(pos)))
case *[]float64:
if firstPos {
headerCounts = make([]float64, len(*v))
firstPos = false
}
countPos := 0
for _, i := range *v {
headerCounts[countPos] += i * float64(len(pos))
countPos++
}
}
}
if meanCountsErr != nil {
cdpAlignmentMap = calcHeaderMeanSe(meanCountsErr, headerMeanCounts, cdpAlignmentMap, header)
} else {
cdpAlignmentMap[header] = headerCounts
}
}
return cdpAlignmentMap
}
//CompareSplitCounts takes and alignment map and returns a map with the ref_header as key and the
//mean_se (mean and standard error) of aligned reads for that ref seq as value. Read counts are split by the number
//of times a read aligns to all reference sequences.
func CompareSplitCounts(alignmentMap map[string]map[string][]int, seqMap map[string]interface{}) map[string]interface{} {
cdpAlignmentMap := make(map[string]interface{})
//Calc. no. of times each read aligns
srnaAlignmentMap := calcTimesReadAligns(alignmentMap)
for header, alignment := range alignmentMap {
var headerMeanCounts float64
var meanCountsErr []float64
var headerCounts []float64
firstPos := true
for srna, pos := range alignment {
switch v := seqMap[srna].(type) {
case *meanSe:
headerMeanCounts += v.Mean * float64(len(pos)) / float64(srnaAlignmentMap[srna])
// should be err=sqrt(x^2/n) for each alignment ??
// They are perfectly correlated (dependent), so maybe not?
meanCountsErr = append(meanCountsErr,
v.Se*float64(len(pos))/float64(srnaAlignmentMap[srna]))
//counts_err = append(counts_err, (math.Sqrt((seq_map[srna].Se*seq_map[srna].Se)/
// float64(srna_alignment_map[srna])))*float64(len(pos)))
case *[]float64:
if firstPos {
headerCounts = make([]float64, len(*v))
firstPos = false
}
countPos := 0
for _, i := range *v {
headerCounts[countPos] += i * float64(len(pos)) / float64(srnaAlignmentMap[srna])
countPos++
}
}
}
if meanCountsErr != nil {
cdpAlignmentMap = calcHeaderMeanSe(meanCountsErr, headerMeanCounts, cdpAlignmentMap, header)
} else {
cdpAlignmentMap[header] = headerCounts
}
}
return cdpAlignmentMap
}
//Calculates the number of times an aligned read aligns
func calcTimesReadAligns(alignmentMap map[string]map[string][]int) map[string]int {
srnaAlignmentMap := make(map[string]int)
for _, alignment := range alignmentMap {
for srna, pos := range alignment {
if _, ok := srnaAlignmentMap[srna]; ok {
srnaAlignmentMap[srna] += len(pos)
} else {
srnaAlignmentMap[srna] = len(pos)
}
}
}
return srnaAlignmentMap
}
//Calculates the mean and se of alignments to a header
func calcHeaderMeanSe(countsErr []float64, counts float64, cdpAlignmentMap map[string]interface{},
header string) map[string]interface{} {
var errSqSum float64
for _, errs := range countsErr {
errSqSum += errs * errs
}
refAlignErr := math.Sqrt(errSqSum)
cdpCountsAndErr := meanSe{counts, refAlignErr}
cdpAlignmentMap[header] = cdpCountsAndErr
return cdpAlignmentMap
}
//Compare combines individual alignments for set sets of sequences (treatments). It returns a map of ref header
//as key and a slice of set 1 mean/se and set2 mean/se as value.
func Compare(countsMap1 map[string]interface{}, countsMap2 map[string]interface{}) map[string]interface{} {
cdpFinalMap := make(map[string]interface{})
//TODO: This only includes if BOTH maps have a non-zero count alignment - perhaps should mod?
for header, countStats := range countsMap1 {
if countStats2, ok := countsMap2[header]; ok {
switch v := countStats.(type) {
case meanSe:
cdpFinalMap[header] = compMeanSeOutput{}
cdpFinalMap[header] = cdpFinalMap[header].(compMeanSeOutput).append(
v.Mean,
v.Se,
countStats2.(meanSe).Mean,
countStats2.(meanSe).Se)
case []float64:
cdpFinalMap[header] = countsOutput{}
pos := 0
for pos < len(v) {
cdpFinalMap[header] = cdpFinalMap[header].(countsOutput).append(v[pos])
pos++
}
pos = 0
for pos < len(countStats2.([]float64)) {
cdpFinalMap[header] = cdpFinalMap[header].(countsOutput).append(countStats2.([]float64)[pos])
pos++
}
}
}
}
return cdpFinalMap
}
type compMeanSeOutput struct {
output []float64
}
func (f compMeanSeOutput) append(a ...float64) compMeanSeOutput {
for _, i := range a {
f.output = append(f.output, i)
}
return f
}
type countsOutput struct {
output []float64
}
func (f countsOutput) append(a ...float64) countsOutput {
for _, i := range a {
f.output = append(f.output, i)
}
return f
}
func MirnaCompare(mirnaAlignmentMap1 map[string]interface{},
mirnaAlignmentMap2 map[string]interface{}, noSplit bool) map[string]interface{} {
cdpFinalMap := make(map[string]interface{})
for header, countStats := range mirnaAlignmentMap1 {
if countStats2, ok := mirnaAlignmentMap2[header]; ok {
//assume count_stats.(type) == count_stats_2.(type)
switch v := countStats.(type) {
case *mean_se_dup:
cdpFinalMap[header] = compMeanSeOutput{}
switch {
case noSplit == true:
cdpFinalMap[header] = cdpFinalMap[header].(compMeanSeOutput).append(
v.mean_se.(*meanSe).Mean,
v.mean_se.(*meanSe).Se,
countStats2.(*mean_se_dup).mean_se.(*meanSe).Mean,
countStats2.(*mean_se_dup).mean_se.(*meanSe).Se)
default:
cdpFinalMap[header] = cdpFinalMap[header].(compMeanSeOutput).append(
v.mean_se.(*meanSe).Mean/v.dup,
v.mean_se.(*meanSe).Se/v.dup,
countStats2.(*mean_se_dup).mean_se.(*meanSe).Mean/countStats2.(*mean_se_dup).dup,
countStats2.(*mean_se_dup).mean_se.(*meanSe).Se/countStats2.(*mean_se_dup).dup)
}
case *counts_dup:
cdpFinalMap[header] = countsOutput{}
switch {
case noSplit == true:
cdpFinalMap[header] = cdpFinalMap[header].(countsOutput).append(v.counts...)
cdpFinalMap[header] = cdpFinalMap[header].(countsOutput).append(countStats2.(*counts_dup).counts...)
default:
pos := 0
for pos < len(v.counts) {
cdpFinalMap[header] = cdpFinalMap[header].(countsOutput).append(v.counts[pos] / v.dup)
pos++
}
pos = 0
for pos < len(countStats2.(*counts_dup).counts) {
cdpFinalMap[header] = cdpFinalMap[header].(countsOutput).append(countStats2.(*counts_dup).counts[pos] / v.dup)
pos++
}
}
}
}
}
return cdpFinalMap
}
//CompareToCsv writes the output to a csv file.
func CompareToCsv(cdpAlignmentMap map[string]interface{}, nt int, outPrefix string, aFileOrder []string, bFileOrder []string) {
firstLine := true
var alignments [][]string
for header, countStats := range cdpAlignmentMap {
switch v := countStats.(type) {
case compMeanSeOutput:
if firstLine {
alignments = append(alignments, []string{"Header", "Mean count 1", "Std. err 1", "Mean count 2",
"Std. err 2"})
firstLine = false
} else {
alignment := []string{header,
strconv.FormatFloat(v.output[0], 'f', 3, 64),
strconv.FormatFloat(v.output[1], 'f', 8, 64),
strconv.FormatFloat(v.output[2], 'f', 3, 64),
strconv.FormatFloat(v.output[3], 'f', 8, 64)}
alignments = append(alignments, alignment)
}
case countsOutput:
if firstLine {
alignment := []string{"Header"}
alignment = append(alignment, aFileOrder...)
alignment = append(alignment, bFileOrder...)
alignments = append(alignments, alignment)
firstLine = false
}
alignment := []string{header}
pos := 0
for pos < len(v.output) {
alignment = append(alignment, strconv.FormatFloat(v.output[pos], 'f', 3, 64))
pos++
}
alignments = append(alignments, alignment)
}
}
var outFile string
switch {
case nt > 0:
outFile = outPrefix + "_" + strconv.Itoa(nt) + ".csv"
default:
outFile = outPrefix + "_miR.csv"
}
outDir := filepath.Dir(outFile)
if err := os.MkdirAll(outDir, os.ModePerm); err != nil { fmt.Println("Not creating directory "+ outDir) }
f, err := os.Create(outFile)
if err != nil {
fmt.Println("Can't create save directory/file "+ outFile)
errorShutdown()
}
w := csv.NewWriter(f)
w.WriteAll(alignments)
if err := w.Error(); err != nil {
log.Fatalln("error writing csv:", err)
}
} | compare.go | 0.53777 | 0.447641 | compare.go | starcoder |
package cpe
type Relation int
const (
Disjoint = Relation(iota)
Equal
Subset
Superset
Undefined
)
// CheckDisjoint implements CPE_DISJOINT. Returns true if the set-theoretic reration between the names is DISJOINT.
func CheckDisjoint(src, trg *Item) bool {
type obj struct {
src Attribute
trg Attribute
}
for _, v := range []obj{
{src.part, trg.part},
{src.vendor, trg.vendor},
{src.product, trg.product},
{src.version, trg.version},
{src.update, trg.update},
{src.edition, trg.edition},
{src.language, trg.language},
{src.sw_edition, trg.sw_edition},
{src.target_sw, trg.target_sw},
{src.target_hw, trg.target_hw},
{src.other, trg.other},
} {
switch v.src.Comparison(v.trg) {
case Disjoint:
return true
}
}
return false
}
// CheckEqual implements CPE_EQUAL. Returns true if the set-theoretic relation between src and trg is EQUAL.
func CheckEqual(src, trg *Item) bool {
type obj struct {
src Attribute
trg Attribute
}
for _, v := range []obj{
{src.part, trg.part},
{src.vendor, trg.vendor},
{src.product, trg.product},
{src.version, trg.version},
{src.update, trg.update},
{src.edition, trg.edition},
{src.language, trg.language},
{src.sw_edition, trg.sw_edition},
{src.target_sw, trg.target_sw},
{src.target_hw, trg.target_hw},
{src.other, trg.other},
} {
switch v.src.Comparison(v.trg) {
case Equal:
default:
return false
}
}
return true
}
// CheckSubset implements CPE_SUBSET. Returns true if the set-theoretic relation between src and trg is SUBSET.
func CheckSubset(src, trg *Item) bool {
type obj struct {
src Attribute
trg Attribute
}
for _, v := range []obj{
{src.part, trg.part},
{src.vendor, trg.vendor},
{src.product, trg.product},
{src.version, trg.version},
{src.update, trg.update},
{src.edition, trg.edition},
{src.language, trg.language},
{src.sw_edition, trg.sw_edition},
{src.target_sw, trg.target_sw},
{src.target_hw, trg.target_hw},
{src.other, trg.other},
} {
switch v.src.Comparison(v.trg) {
case Subset, Equal:
default:
return false
}
}
return true
}
// CheckSuperset implements CPE_SUPERSET. Returns true if the set-theoretic relation between src and trg is SUPERSET.
func CheckSuperset(src, trg *Item) bool {
type obj struct {
src Attribute
trg Attribute
}
for _, v := range []obj{
{src.part, trg.part},
{src.vendor, trg.vendor},
{src.product, trg.product},
{src.version, trg.version},
{src.update, trg.update},
{src.edition, trg.edition},
{src.language, trg.language},
{src.sw_edition, trg.sw_edition},
{src.target_sw, trg.target_sw},
{src.target_hw, trg.target_hw},
{src.other, trg.other},
} {
switch v.src.Comparison(v.trg) {
case Superset, Equal:
default:
return false
}
}
return true
} | matching.go | 0.694821 | 0.408159 | matching.go | starcoder |
package compact
import (
"github.com/dnovikoff/tempai-core/tile"
)
// Not more than 4 tiles per type by implementation
type Instances []PackedMasks
const (
instancesBits = 64
instancesInts = 4
tilesPerPack = 9
)
const _ = uint(tilesPerPack*instancesInts*4 - tile.InstanceCount)
func AllInstancesFromTo(from, to tile.Tile) Instances {
x := NewInstances()
for t := from; t < to; t++ {
x.SetCount(t, 4)
}
return x
}
func AllInstances() Instances {
return AllInstancesFromTo(tile.TileBegin, tile.TileEnd)
}
func NewInstances() Instances {
return make(Instances, instancesInts)
}
func (is Instances) Each(f func(mask Mask) bool) bool {
start := tile.Man1
for _, v := range is {
cur := start
for v != 0 {
mask := uint(v & 15)
if mask != 0 {
if !f(NewMask(mask, cur)) {
return false
}
}
cur++
v >>= 4
}
start += tilesPerPack
}
return true
}
func (is Instances) GetMask(t tile.Tile) Mask {
block := is[int(shift(t)/tilesPerPack)]
return block.Get(shift(t)%tilesPerPack, t)
}
func (is Instances) CountFree(in Tiles) int {
result := 0
in.Each(func(t tile.Tile) bool {
result += 4 - is.GetCount(t)
return true
})
return result
}
func (is Instances) GetFree() Tiles {
return is.GetFull().Invert()
}
func (is Instances) GetFull() Tiles {
result := Tiles(0)
is.Each(func(m Mask) bool {
if m.IsFull() {
result = result.Set(m.Tile())
}
return true
})
return result
}
func (is Instances) Invert() Instances {
return is.CopyFree(AllTiles)
}
func (is Instances) CopyFree(in Tiles) Instances {
result := NewInstances()
in.Each(func(t tile.Tile) bool {
i := is.GetMask(t).InvertTiles()
result.SetMask(i)
return true
})
return result
}
func (is Instances) CopyFrom(x Instances) {
for k, v := range x {
is[k] = v
}
}
func (is Instances) setMaskImpl(index uint, mask Mask) {
blocknum := index / tilesPerPack
shift := index % tilesPerPack
is[blocknum] = is[blocknum].Set(mask, shift)
}
func (is Instances) SetMask(mask Mask) {
is.setMaskImpl(shift(mask.Tile()), mask)
}
func (is Instances) Add(t tile.Instances) Instances {
for _, v := range t {
is.Set(v)
}
return is
}
func (is Instances) Clone() Instances {
clone := make(Instances, len(is))
clone.CopyFrom(is)
return clone
}
func (is Instances) AddCount(t tile.Tile, x int) Instances {
is.SetCount(t, is.GetMask(t).Count()+x)
return is
}
func (is Instances) SetCount(t tile.Tile, x int) {
m := NewMask(MaskByCount(x), t)
is.SetMask(m)
}
func (is Instances) GetCount(t tile.Tile) int {
return is.GetMask(t).Count()
}
func (is Instances) Set(t tile.Instance) {
current := is.GetMask(t.Tile())
is.SetMask(current.SetCopyBit(t.CopyID()))
}
func (is Instances) Check(t tile.Instance) bool {
return is.GetMask(t.Tile()).Check(t.CopyID())
}
func (is Instances) Remove(t tile.Instance) bool {
current := is.GetMask(t.Tile())
next := current.UnsetCopyBit(t.CopyID())
is.SetMask(next)
return next != current
}
func (is Instances) UniqueTiles() Tiles {
cts := Tiles(0)
start := tile.TileBegin
for _, v := range is {
t := start
for v != 0 {
if (v & 15) != 0 {
cts = cts.Set(t)
}
t++
v >>= 4
}
start += tilesPerPack
}
return cts
}
func (is Instances) Instances() tile.Instances {
ret := make(tile.Instances, is.CountBits())
x := 0
is.Each(func(mask Mask) bool {
return mask.Each(func(inst tile.Instance) bool {
ret[x] = inst
x++
return true
})
})
return ret
}
func (is Instances) CountBits() int {
x := 0
for _, v := range is {
x += v.CountBits()
}
return x
}
func (is Instances) IsEmpty() bool {
for _, v := range is {
if v != 0 {
return false
}
}
return true
}
func (is Instances) Contains(x Instances) bool {
for k, v := range is {
xv := x[k]
if (xv & v) != xv {
return false
}
}
return true
}
func (is Instances) Merge(other Instances) Instances {
// TODO: check
if other == nil {
return is
}
for k, v := range is {
is[k] = v | other[k]
}
return is
}
func (is Instances) Sub(other Instances) Instances {
for k, v := range is {
is[k] = v & (^other[k])
}
return is
} | compact/instances.go | 0.505371 | 0.568835 | instances.go | starcoder |
package humanize
import (
"fmt"
"log"
"strings"
"time"
)
// Duration takes a `time.Duration` and converts it to the nearest-second string output
// Example output: 01:59:59
func Duration(duration time.Duration) string {
// Truncate away any non-second data
duration = duration.Truncate(1 * time.Second)
var hours, minutes, seconds time.Duration
hours = duration / time.Hour
duration -= hours * time.Hour
minutes = duration / time.Minute
duration -= minutes * time.Minute
seconds = duration / time.Second
return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
}
// DurationPT takes a PT-formatted string `time.Duration` and converts it to the nearest-second string output using the `Duration` helper
// Example output: 01:59:59
// See also: Duration
func DurationPT(pt string) string {
pt = strings.ToLower(pt)
pt = strings.Replace(pt, "pt", "", 1)
duration, _ := time.ParseDuration(pt)
return Duration(duration)
}
// DurationSeconds takes a `time.Duration` and converts it to a string in the following format: %gs where %g is the number of seconds contained within this duration
// Example output: 53s
func DurationSeconds(duration time.Duration) string {
// Truncate away any non-second data
duration = duration.Truncate(1 * time.Second)
if duration > 90*time.Second {
log.Println("WARNING: humanize.DurationSeconds used for duration that's larger than 90 seconds")
}
return fmt.Sprintf("%gs", duration.Seconds())
}
// CreationDate returns the `time.Time`'s date formatted in the `02 Jan 2006` format
// Example output: 02 Dec 2016
func CreationDate(t time.Time) string {
return t.Format("02 Jan 2006")
}
// CreationDateRFC3339 parses the incoming string as an RFC3339-formatted date and then formats it into the `02 Jan 2006` format
// If the given string is not a valid RFC3339-formatted date, we will return an empty string
// Example output: 02 Dec 2016
// See more: `CreationDate`
func CreationDateRFC3339(str string) string {
t, err := time.Parse(time.RFC3339, str)
if err != nil {
return ""
}
return CreationDate(t)
}
// CreationDateUnix parses the incoming int64 as a unix timestamp and then returns the date in the `CreationDate` format.
// Example output: 02 Dec 2016
// See more: `CreationDate`
func CreationDateUnix(unix int64) string {
t := time.Unix(unix, 0)
return CreationDate(t)
}
// CreationDateTime returns the `time.Time`'s date formatted in the `02 Jan 2006 • 15:04 UTC` format
// Example output: 02 Jan 2006 • 15:04 UTC
func CreationDateTime(t time.Time) string {
return t.Format("02 Jan 2006 • 15:04 UTC")
}
// CreationDateTimeUnix parses the incoming `int64` as a unix timestamp and then formats it with the CreationDateTime function
// Example output: 02 Jan 2006 • 15:04 UTC
func CreationDateTimeUnix(unix int64) string {
t := time.Unix(unix, 0)
return CreationDateTime(t.UTC())
} | pkg/humanize/date.go | 0.87637 | 0.535584 | date.go | starcoder |
package stats
import (
"math"
"math/rand"
)
// NormalDist is a normal (Gaussian) distribution with mean Mu and
// standard deviation Sigma.
type NormalDist struct {
Mu, Sigma float64
}
// StdNormal is the standard normal distribution (Mu = 0, Sigma = 1)
var StdNormal = NormalDist{0, 1}
// 1/sqrt(2 * pi)
const invSqrt2Pi = 0.39894228040143267793994605993438186847585863116493465766592583
func (n NormalDist) PDF(x float64) float64 {
z := x - n.Mu
return math.Exp(-z*z/(2*n.Sigma*n.Sigma)) * invSqrt2Pi / n.Sigma
}
func (n NormalDist) pdfEach(xs []float64) []float64 {
res := make([]float64, len(xs))
if n.Mu == 0 && n.Sigma == 1 {
// Standard normal fast path
for i, x := range xs {
res[i] = math.Exp(-x*x/2) * invSqrt2Pi
}
} else {
a := -1 / (2 * n.Sigma * n.Sigma)
b := invSqrt2Pi / n.Sigma
for i, x := range xs {
z := x - n.Mu
res[i] = math.Exp(z*z*a) * b
}
}
return res
}
func (n NormalDist) CDF(x float64) float64 {
return math.Erfc(-(x-n.Mu)/(n.Sigma*math.Sqrt2)) / 2
}
func (n NormalDist) cdfEach(xs []float64) []float64 {
res := make([]float64, len(xs))
a := 1 / (n.Sigma * math.Sqrt2)
for i, x := range xs {
res[i] = math.Erfc(-(x-n.Mu)*a) / 2
}
return res
}
func (n NormalDist) InvCDF(p float64) (x float64) {
// This is based on <NAME>'s inverse normal CDF
// algorithm: http://home.online.no/~pjacklam/notes/invnorm/
const (
a1 = -3.969683028665376e+01
a2 = 2.209460984245205e+02
a3 = -2.759285104469687e+02
a4 = 1.383577518672690e+02
a5 = -3.066479806614716e+01
a6 = 2.506628277459239e+00
b1 = -5.447609879822406e+01
b2 = 1.615858368580409e+02
b3 = -1.556989798598866e+02
b4 = 6.680131188771972e+01
b5 = -1.328068155288572e+01
c1 = -7.784894002430293e-03
c2 = -3.223964580411365e-01
c3 = -2.400758277161838e+00
c4 = -2.549732539343734e+00
c5 = 4.374664141464968e+00
c6 = 2.938163982698783e+00
d1 = 7.784695709041462e-03
d2 = 3.224671290700398e-01
d3 = 2.445134137142996e+00
d4 = 3.754408661907416e+00
plow = 0.02425
phigh = 1 - plow
)
if p < 0 || p > 1 {
return math.NaN()
} else if p == 0 {
return math.Inf(-1)
} else if p == 1 {
return math.Inf(1)
}
if p < plow {
// Rational approximation for lower region.
q := math.Sqrt(-2 * math.Log(p))
x = (((((c1*q+c2)*q+c3)*q+c4)*q+c5)*q + c6) /
((((d1*q+d2)*q+d3)*q+d4)*q + 1)
} else if phigh < p {
// Rational approximation for upper region.
q := math.Sqrt(-2 * math.Log(1-p))
x = -(((((c1*q+c2)*q+c3)*q+c4)*q+c5)*q + c6) /
((((d1*q+d2)*q+d3)*q+d4)*q + 1)
} else {
// Rational approximation for central region.
q := p - 0.5
r := q * q
x = (((((a1*r+a2)*r+a3)*r+a4)*r+a5)*r + a6) * q /
(((((b1*r+b2)*r+b3)*r+b4)*r+b5)*r + 1)
}
// Refine approximation.
e := 0.5*math.Erfc(-x/math.Sqrt2) - p
u := e * math.Sqrt(2*math.Pi) * math.Exp(x*x/2)
x = x - u/(1+x*u/2)
// Adjust from standard normal.
return x*n.Sigma + n.Mu
}
func (n NormalDist) Rand(r *rand.Rand) float64 {
var x float64
if r == nil {
x = rand.NormFloat64()
} else {
x = r.NormFloat64()
}
return x*n.Sigma + n.Mu
}
func (n NormalDist) Bounds() (float64, float64) {
const stddevs = 3
return n.Mu - stddevs*n.Sigma, n.Mu + stddevs*n.Sigma
} | stats/normaldist.go | 0.720467 | 0.598957 | normaldist.go | starcoder |
package synchronizer
import (
"math"
"time"
"github.com/relab/hotstuff/consensus"
)
// ViewDuration determines the duration of a view.
// The view synchronizer uses this interface to set its timeouts.
type ViewDuration interface {
// Duration returns the duration that the next view should last.
Duration() time.Duration
// ViewStarted is called by the synchronizer when starting a new view.
ViewStarted()
// ViewSucceeded is called by the synchronizer when a view ended successfully.
ViewSucceeded()
// ViewTimeout is called by the synchronizer when a view timed out.
ViewTimeout()
}
// NewViewDuration returns a ViewDuration that approximates the view duration based on durations of previous views.
// sampleSize determines the number of previous views that should be considered.
// startTimeout determines the view duration of the first views.
// When a timeout occurs, the next view duration will be multiplied by the multiplier.
func NewViewDuration(sampleSize uint64, startTimeout, maxTimeout, multiplier float64) ViewDuration {
return &viewDuration{
limit: sampleSize,
mean: startTimeout,
max: maxTimeout,
mul: multiplier,
}
}
// viewDuration uses statistics from previous views to guess a good value for the view duration.
// It only takes a limited amount of measurements into account.
type viewDuration struct {
mods *consensus.Modules
mul float64 // on failed views, multiply the current mean by this number (should be > 1)
limit uint64 // how many measurements should be included in mean
count uint64 // total number of measurements
startTime time.Time // the start time for the current measurement
mean float64 // the mean view duration
m2 float64 // sum of squares of differences from the mean
prevM2 float64 // m2 calculated from the last period
max float64 // upper bound on view timeout
}
// InitConsensusModule gives the module a reference to the Modules object.
// It also allows the module to set module options using the OptionsBuilder.
func (v *viewDuration) InitConsensusModule(mods *consensus.Modules, _ *consensus.OptionsBuilder) {
v.mods = mods
}
// ViewSucceeded calculates the duration of the view
// and updates the internal values used for mean and variance calculations.
func (v *viewDuration) ViewSucceeded() {
if v.startTime.IsZero() {
return
}
duration := float64(time.Since(v.startTime)) / float64(time.Millisecond)
v.count++
// Reset m2 occasionally such that we will pick up on changes in variance faster.
// We store the m2 to prevM2, which will be used when calculating the variance.
// This ensures that at least 'limit' measurements have contributed to the approximate variance.
if v.count%v.limit == 0 {
v.prevM2 = v.m2
v.m2 = 0
}
var c float64
if v.count > v.limit {
c = float64(v.limit)
// throw away one measurement
v.mean -= v.mean / float64(c)
} else {
c = float64(v.count)
}
// Welford's algorithm
d1 := duration - v.mean
v.mean += d1 / c
d2 := duration - v.mean
v.m2 += d1 * d2
}
// ViewTimeout should be called when a view timeout occurred. It will multiply the current mean by 'mul'.
func (v *viewDuration) ViewTimeout() {
v.mean *= v.mul
}
// ViewStarted records the start time of a view.
func (v *viewDuration) ViewStarted() {
v.startTime = time.Now()
}
// Duration returns the upper bound of the 95% confidence interval for the mean view duration.
func (v *viewDuration) Duration() time.Duration {
conf := 1.96 // 95% confidence
dev := float64(0)
if v.count > 1 {
c := float64(v.count)
m2 := v.m2
// The standard deviation is calculated from the sum of prevM2 and m2.
if v.count >= v.limit {
c = float64(v.limit) + float64(v.count%v.limit)
m2 += v.prevM2
}
dev = math.Sqrt(m2 / c)
}
duration := v.mean + dev*conf
if v.max > 0 && duration > v.max {
duration = v.max
}
if uint64(v.mods.Synchronizer().View())%v.limit == 0 {
v.mods.Logger().Infof("Mean: %.2fms, Dev: %.2f, Timeout: %.2fms (last %d views)", v.mean, dev, duration, v.limit)
}
return time.Duration(duration * float64(time.Millisecond))
} | synchronizer/viewduration.go | 0.855202 | 0.418162 | viewduration.go | starcoder |
package api
import (
"time"
)
// Time is a wrapper around time.Time which supports correct
// marshaling to YAML and JSON. Wrappers are provided for many
// of the factory methods that the time package offers.
type Time struct {
time.Time
}
// Date returns the Time corresponding to the supplied parameters
// by wrapping time.Date.
func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time {
return Time{time.Date(year, month, day, hour, min, sec, nsec, loc)}
}
// Now returns the current local time.
func Now() Time {
return Time{time.Now()}
}
// Unix returns the local time corresponding to the given Unix time
// by wrapping time.Unix.
func Unix(sec int64, nsec int64) Time {
return Time{time.Unix(sec, nsec)}
}
// IsZero returns true if the value is nil or time is zero.
func (t Time) IsZero() bool {
return t.Time.IsZero()
}
// Before reports whether the time instant t is before u.
func (t Time) Before(u Time) bool {
return t.Time.Before(u.Time)
}
// After reports whether the time instant t is before u.
func (t Time) After(u Time) bool {
return t.Time.After(u.Time)
}
func (t Time) Add(d time.Duration) Time {
return Time{t.Time.Add(d)}
}
func (t Time) Sub(u Time) time.Duration {
return t.Time.Sub(u.Time)
}
// Equal reports whether the time instant t is equal to u.
func (t Time) Equal(u Time) bool {
return t.Time.Equal(u.Time)
}
// Rfc3339Copy returns a copy of the Time at second-level precision.
func (t Time) Rfc3339Copy() Time {
copied, _ := time.Parse(time.RFC3339, t.Format(time.RFC3339))
return Time{copied}
}
// Note: We don't use the K8s serialization cause we want to have
// nanoseconds on there
func (in *Time) DeepCopy() *Time {
if in == nil {
return nil
}
out := new(Time)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto creates a deep-copy of the Time value. The underlying time.Time
// type is effectively immutable in the time API, so it is safe to
// copy-by-assign, despite the presence of (unexported) Pointer fields.
func (t *Time) DeepCopyInto(out *Time) {
*out = *t
} | pkg/api/time.go | 0.829008 | 0.524943 | time.go | starcoder |
package dltree
import (
"bytes"
"math"
"strconv"
)
// A DomainLabel represents content of a label.
type DomainLabel []byte
// GetFirstLabelSize returns size in bytes needed to store first label of given domain name as a DomainLabel. Additionally the function returns position right after the label in given string (or length of the string if the first label also is the last).
func GetFirstLabelSize(s string) (int, int) {
size := 0
escaped := 0
var code [3]byte
for i := 0; i < len(s); i++ {
c := s[i]
if escaped <= 0 {
switch c {
case '.':
return size, i
case '\\':
escaped = 1
default:
size++
}
} else if escaped == 1 {
if c >= '0' && c <= '9' {
code[0] = c
escaped++
} else {
size++
escaped = 0
}
} else if escaped > 1 && escaped < 4 {
if c >= '0' && c <= '9' {
code[escaped-1] = c
escaped++
} else {
size += escaped
escaped = 0
switch c {
case '.':
return size, i
case '\\':
escaped = 1
default:
size++
}
}
} else {
if n, _ := strconv.Atoi(string(code[:])); n >= 0 && n <= math.MaxUint8 {
size++
} else {
size += escaped
}
escaped = 0
switch c {
case '.':
return size, i
case '\\':
escaped = 1
default:
size++
}
}
}
if escaped > 0 && escaped < 4 {
size += escaped
} else if escaped >= 4 {
if n, _ := strconv.Atoi(string(code[:])); n >= 0 && n <= math.MaxUint8 {
size++
} else {
size += escaped
}
}
return size, len(s)
}
// MakeDomainLabel returns first domain label found in given string as DomainLabel and position in the string right after the label.
func MakeDomainLabel(s string) (DomainLabel, int) {
size, end := GetFirstLabelSize(s)
out := make(DomainLabel, size)
escaped := 0
var code [3]byte
p := 0
for i := 0; i < len(s); i++ {
c := s[i]
if escaped <= 0 {
switch c {
case '.':
return out, end
case '\\':
escaped = 1
default:
if c >= 'A' && c <= 'Z' {
c += 0x20
}
out[p] = c
p++
}
} else if escaped == 1 {
if c >= '0' && c <= '9' {
code[0] = c
escaped++
} else {
if c >= 'A' && c <= 'Z' {
c += 0x20
}
out[p] = c
p++
escaped = 0
}
} else if escaped > 1 && escaped < 4 {
if c >= '0' && c <= '9' {
code[escaped-1] = c
escaped++
} else {
out[p] = '\\'
p++
for j := 0; j < escaped-1; j++ {
out[p] = code[j]
p++
}
escaped = 0
switch c {
case '.':
return out, end
case '\\':
escaped = 1
default:
if c >= 'A' && c <= 'Z' {
c += 0x20
}
out[p] = c
p++
}
}
} else {
if n, _ := strconv.Atoi(string(code[:])); n >= 0 && n <= math.MaxUint8 {
out[p] = byte(n)
if out[p] >= 'A' && out[p] <= 'Z' {
out[p] += 0x20
}
p++
} else {
out[p] = '\\'
p++
for _, b := range code {
out[p] = b
p++
}
}
escaped = 0
switch c {
case '.':
return out, end
case '\\':
escaped = 1
default:
if c >= 'A' && c <= 'Z' {
c += 0x20
}
out[p] = c
p++
}
}
}
if escaped > 0 && escaped < 4 {
out[p] = '\\'
p++
for i := 0; i < escaped-1; i++ {
out[p] = code[i]
p++
}
} else if escaped >= 4 {
if n, _ := strconv.Atoi(string(code[:])); n >= 0 && n <= math.MaxUint8 {
out[p] = byte(n)
if out[p] >= 'A' && out[p] <= 'Z' {
out[p] += 0x20
}
p++
} else {
out[p] = '\\'
p++
for _, b := range code {
out[p] = b
p++
}
}
}
return out, end
}
// String returns domain label in human readable format.
func (l DomainLabel) String() string {
size := 0
for _, c := range l {
size++
if c < ' ' || c > '~' {
size += 3
} else if c == '.' || c == '\\' {
size++
}
}
out := make([]byte, size)
i := 0
for _, c := range l {
if c < ' ' || c > '~' {
out[i] = '\\'
if c < 100 {
i++
out[i] = '0'
if c < 10 {
i++
out[i] = '0'
}
}
for _, n := range strconv.Itoa(int(c)) {
i++
out[i] = byte(n)
}
} else {
if c == '.' || c == '\\' {
out[i] = '\\'
i++
}
out[i] = c
}
i++
}
return string(out)
}
func compare(a, b DomainLabel) int {
d := len(a) - len(b)
if d != 0 {
return d
}
return bytes.Compare(a, b)
} | dltree/domain_label.go | 0.643329 | 0.478712 | domain_label.go | starcoder |
package main
import (
"math"
"github.com/go-gl/gl/v2.1/gl"
)
const (
// gridMargin controls the distance between grid points.
gridMargin = 30
// gridDestructionForce controls the amount of ripple created from entity
// destruction.
gridDestructionForce = 50
// gridMoveForce controls the amount of ripple created from entity
// movement.
gridMoveForce = 10
)
// grid provides a visual grid with water rippling effects.
type grid struct {
uidGenerator
points [][]gridPoint
}
func newGrid(width, height float64) *grid {
g := &grid{}
// Make a new 2D array of points
g.points = make([][]gridPoint, int(math.Ceil(width/gridMargin)))
for i := range g.points {
g.points[i] = make([]gridPoint, int(math.Ceil(height/gridMargin)))
}
// Place all points
for x := range g.points {
for y := range g.points[x] {
g.points[x][y] = newGridPoint(vertex{
(-width / 2.0) + float64(x)*gridMargin,
(-height / 2.0) + float64(y)*gridMargin,
0.0})
}
}
return g
}
func (g *grid) tick() []entity {
// Update every point
for x := range g.points {
for y := range g.points[x] {
g.points[x][y].tick()
}
}
return []entity{}
}
func (g *grid) draw() {
gl.PushMatrix()
// Give the grid some generic off white material
matAmbient := []float32{0.6, 0.6, 0.6, 1.0}
matDiffuse := []float32{0.6, 0.6, 0.6, 1.0}
matSpecular := []float32{0.0, 0.0, 0.0, 1.0}
gl.Materialfv(gl.FRONT, gl.AMBIENT, fPtr(matAmbient))
gl.Materialfv(gl.FRONT, gl.DIFFUSE, fPtr(matDiffuse))
gl.Materialfv(gl.FRONT, gl.SPECULAR, fPtr(matSpecular))
gl.Materialf(gl.FRONT, gl.SHININESS, 0)
// Draw lines between every point
gl.Begin(gl.LINES)
for x := 0; x < len(g.points); x++ {
for y := 0; y < len(g.points[x]); y++ {
if x+1 < len(g.points) {
gl.Normal3d(0, 0, 1)
gl.Vertex3d(
g.points[x][y].loc.x,
g.points[x][y].loc.y,
gridPointZVal)
gl.Normal3d(0, 0, 1)
gl.Vertex3d(
g.points[x+1][y].loc.x,
g.points[x+1][y].loc.y,
gridPointZVal)
}
if y+1 < len(g.points[x]) {
gl.Normal3d(0, 0, 1)
gl.Vertex3d(
g.points[x][y].loc.x,
g.points[x][y].loc.y,
gridPointZVal)
gl.Normal3d(0, 0, 1)
gl.Vertex3d(
g.points[x][y+1].loc.x,
g.points[x][y+1].loc.y,
gridPointZVal)
}
}
}
gl.End()
gl.PopMatrix()
}
func (g *grid) entityMove(e physicalEntity, loc vertex) {
// Create a ripple around moving enemies
// TODO(velovix): Refactor this into a method
for x := range g.points {
for y := range g.points[x] {
dist := g.points[x][y].loc.distance(loc)
// TODO(velovix): assign a constant to this 25 value
magnitude := (gridMoveForce / (dist / 25.0)) * e.mass()
if magnitude > gridMoveForce {
magnitude = gridMoveForce
}
direction := normalize(loc.subtract(g.points[x][y].loc))
g.points[x][y].applyForce(vertex{
-direction.x * magnitude,
-direction.y * magnitude,
0})
}
}
}
func (g *grid) entityDestruction(e entity) {
// Create a ripple around destroyed enemies
// TODO(velovix): Refactor this into a method
if pe, ok := e.(physicalEntity); ok {
for x := range g.points {
for y := range g.points[x] {
dist := g.points[x][y].loc.distance(pe.location())
baseForce := gridDestructionForce * pe.mass()
// TODO(velovix): assign a constnant to this 50 value
magnitude := baseForce / (dist / (50.0 * pe.mass()))
if magnitude > gridDestructionForce*pe.mass() {
magnitude = baseForce
}
direction := normalize(pe.location().subtract(g.points[x][y].loc))
g.points[x][y].applyForce(vertex{
-direction.x * magnitude,
-direction.y * magnitude,
0})
}
}
}
}
func (g *grid) location() vertex {
return vertex{0, 0, 0}
}
func (g *grid) collisions() []collision {
return []collision{}
}
func (g *grid) collision(yours, other collision) {
}
func (g *grid) mass() float64 {
return 0
}
func (g *grid) deletable() bool {
return false
}
const (
// gridPointMass is an arbitrary mass value.
gridPointMass = 3
// gridPointSpringConst controls how quickly a point snaps back to the
// direction of its original location.
gridPointSpringConst = 1.0
// gridPointSprintDampening dampens the point's movement so it eventually
// stops.
gridPointSpringDampening = 0.9
// gridPointZVal is the Z value of all grid points.
gridPointZVal = -3
)
// gridPoint is a single point on the grid.
type gridPoint struct {
loc, origLoc, accel vertex
}
func newGridPoint(loc vertex) gridPoint {
return gridPoint{
loc: loc,
origLoc: loc}
}
func (gp *gridPoint) tick() {
// Apply the current acceleration
gp.loc.x += gp.accel.x * mainWindow.delta
gp.loc.y += gp.accel.y * mainWindow.delta
// Affect acceleration using Hooke's law
gp.accel.x += ((gridPointSpringConst * (gp.origLoc.x - gp.loc.x)) / gridPointMass)
gp.accel.y += ((gridPointSpringConst * (gp.origLoc.y - gp.loc.y)) / gridPointMass)
// Dampen the acceleration
gp.accel.x *= (gridPointSpringDampening)
gp.accel.y *= (gridPointSpringDampening)
}
func (gp *gridPoint) applyForce(force vertex) {
gp.accel.x += force.x / gridPointMass
gp.accel.y += force.y / gridPointMass
} | grid.go | 0.668339 | 0.407451 | grid.go | starcoder |
package iso8601
import (
core "github.com/elimity-com/abnf/core"
"github.com/elimity-com/abnf/operators"
)
// date = datespec-full / datespec-year / datespec-month / datespec-mday / datespec-week / datespec-wday / datespec-yday
func Date(s []byte) operators.Alternatives {
return operators.Alts(
"date",
DatespecFull,
DatespecYear,
DatespecMonth,
DatespecMday,
DatespecWeek,
DatespecWday,
DatespecYday,
)(s)
}
// date-century = 2DIGIT
func DateCentury(s []byte) operators.Alternatives {
return operators.RepeatN("date-century", 2, core.DIGIT())(s)
}
// date-decade = DIGIT
func DateDecade(s []byte) operators.Alternatives {
return core.DIGIT()(s)
}
// date-fullyear = date-century date-year
func DateFullyear(s []byte) operators.Alternatives {
return operators.Concat(
"date-fullyear",
DateCentury,
DateYear,
)(s)
}
// date-mday = 2DIGIT
func DateMday(s []byte) operators.Alternatives {
return operators.RepeatN("date-mday", 2, core.DIGIT())(s)
}
// date-month = 2DIGIT
func DateMonth(s []byte) operators.Alternatives {
return operators.RepeatN("date-month", 2, core.DIGIT())(s)
}
// date-subdecade = DIGIT
func DateSubdecade(s []byte) operators.Alternatives {
return core.DIGIT()(s)
}
// date-wday = DIGIT
func DateWday(s []byte) operators.Alternatives {
return core.DIGIT()(s)
}
// date-week = 2DIGIT
func DateWeek(s []byte) operators.Alternatives {
return operators.RepeatN("date-week", 2, core.DIGIT())(s)
}
// date-yday = 3DIGIT
func DateYday(s []byte) operators.Alternatives {
return operators.RepeatN("date-yday", 3, core.DIGIT())(s)
}
// date-year = date-decade date-subdecade
func DateYear(s []byte) operators.Alternatives {
return operators.Concat(
"date-year",
DateDecade,
DateSubdecade,
)(s)
}
// dateopt-century = "-" / date-century
func DateoptCentury(s []byte) operators.Alternatives {
return operators.Alts(
"dateopt-century",
operators.String("-", "-"),
DateCentury,
)(s)
}
// dateopt-fullyear = "-" / datepart-fullyear
func DateoptFullyear(s []byte) operators.Alternatives {
return operators.Alts(
"dateopt-fullyear",
operators.String("-", "-"),
DatepartFullyear,
)(s)
}
// dateopt-month = "-" / (date-month ["-"])
func DateoptMonth(s []byte) operators.Alternatives {
return operators.Alts(
"dateopt-month",
operators.String("-", "-"),
operators.Concat(
"date-month [\"-\"]",
DateMonth,
operators.Optional("[\"-\"]", operators.String("-", "-")),
),
)(s)
}
// dateopt-week = "-" / (date-week ["-"])
func DateoptWeek(s []byte) operators.Alternatives {
return operators.Alts(
"dateopt-week",
operators.String("-", "-"),
operators.Concat(
"date-week [\"-\"]",
DateWeek,
operators.Optional("[\"-\"]", operators.String("-", "-")),
),
)(s)
}
// dateopt-year = "-" / (date-year ["-"])
func DateoptYear(s []byte) operators.Alternatives {
return operators.Alts(
"dateopt-year",
operators.String("-", "-"),
operators.Concat(
"date-year [\"-\"]",
DateYear,
operators.Optional("[\"-\"]", operators.String("-", "-")),
),
)(s)
}
// datepart-fullyear = [date-century] date-year ["-"]
func DatepartFullyear(s []byte) operators.Alternatives {
return operators.Concat(
"datepart-fullyear",
operators.Optional("[date-century]", DateCentury),
DateYear,
operators.Optional("[\"-\"]", operators.String("-", "-")),
)(s)
}
// datepart-ptyear = "-" [date-subdecade ["-"]]
func DatepartPtyear(s []byte) operators.Alternatives {
return operators.Concat(
"datepart-ptyear",
operators.String("-", "-"),
operators.Optional("[date-subdecade [\"-\"]]", operators.Concat(
"date-subdecade [\"-\"]",
DateSubdecade,
operators.Optional("[\"-\"]", operators.String("-", "-")),
)),
)(s)
}
// datepart-wkyear = datepart-ptyear / datepart-fullyear
func DatepartWkyear(s []byte) operators.Alternatives {
return operators.Alts(
"datepart-wkyear",
DatepartPtyear,
DatepartFullyear,
)(s)
}
// datespec-full = datepart-fullyear date-month ["-"] date-mday
func DatespecFull(s []byte) operators.Alternatives {
return operators.Concat(
"datespec-full",
DatepartFullyear,
DateMonth,
operators.Optional("[\"-\"]", operators.String("-", "-")),
DateMday,
)(s)
}
// datespec-mday = "--" dateopt-month date-mday
func DatespecMday(s []byte) operators.Alternatives {
return operators.Concat(
"datespec-mday",
operators.String("--", "--"),
DateoptMonth,
DateMday,
)(s)
}
// datespec-month = "-" dateopt-year date-month [["-"] date-mday]
func DatespecMonth(s []byte) operators.Alternatives {
return operators.Concat(
"datespec-month",
operators.String("-", "-"),
DateoptYear,
DateMonth,
operators.Optional("[[\"-\"] date-mday]", operators.Concat(
"[\"-\"] date-mday",
operators.Optional("[\"-\"]", operators.String("-", "-")),
DateMday,
)),
)(s)
}
// datespec-wday = "---" date-wday
func DatespecWday(s []byte) operators.Alternatives {
return operators.Concat(
"datespec-wday",
operators.String("---", "---"),
DateWday,
)(s)
}
// datespec-week = datepart-wkyear "W" (date-week / dateopt-week date-wday)
func DatespecWeek(s []byte) operators.Alternatives {
return operators.Concat(
"datespec-week",
DatepartWkyear,
operators.String("W", "W"),
operators.Alts(
"date-week / dateopt-week date-wday",
DateWeek,
operators.Concat(
"dateopt-week date-wday",
DateoptWeek,
DateWday,
),
),
)(s)
}
// datespec-yday = dateopt-fullyear date-yday
func DatespecYday(s []byte) operators.Alternatives {
return operators.Concat(
"datespec-yday",
DateoptFullyear,
DateYday,
)(s)
}
// datespec-year = date-century / dateopt-century date-year
func DatespecYear(s []byte) operators.Alternatives {
return operators.Alts(
"datespec-year",
DateCentury,
operators.Concat(
"dateopt-century date-year",
DateoptCentury,
DateYear,
),
)(s)
} | iso8601/date.go | 0.6488 | 0.538194 | date.go | starcoder |
package main
import "fmt"
type FullAdder func(circuit *Circuit, a, b, c, d string) (sum, carry string)
type HalfAdder func(circuit *Circuit, b, c, d string) (sum, carry string)
func FullAdderA1(circuit *Circuit, a, b, c, d string) (sum, carry string) {
circuit.AddGateCCNot(a, b, d)
circuit.AddGateCNot(b, a)
circuit.AddGateCCNot(a, c, d)
circuit.AddGateCNot(c, a)
circuit.AddAlias(b, "G")
circuit.AddAlias(c, "G")
return a, d
}
func HalfAdderA1(circuit *Circuit, a, b, d string) (sum, carry string) {
circuit.AddGateCCNot(a, b, d)
circuit.AddGateCNot(b, a)
circuit.AddAlias(b, "G")
return a, d
}
func FullAdderA2(circuit *Circuit, a, b, c, d string) (sum, carry string) {
circuit.AddGateCCNot(a, c, d)
circuit.AddGateCNot(a, c)
circuit.AddGateCCNot(b, c, d)
circuit.AddGateCNot(c, b)
circuit.AddAlias(a, "G")
circuit.AddAlias(c, "G")
return b, d
}
func HalfAdderA2(circuit *Circuit, b, c, d string) (sum, carry string) {
circuit.AddGateCCNot(b, c, d)
circuit.AddGateCNot(c, b)
circuit.AddAlias(c, "G")
return b, d
}
func FullAdderA3(circuit *Circuit, a, b, c, d string) (sum, carry string) {
circuit.AddGateCCNot(a, c, d)
circuit.AddGateCNot(a, c)
circuit.AddGateCCNot(b, c, d)
circuit.AddGateCNot(b, c)
circuit.AddAlias(a, "G")
circuit.AddAlias(b, "G")
return c, d
}
func HalfAdderA3(circuit *Circuit, b, c, d string) (sum, carry string) {
circuit.AddGateCCNot(b, c, d)
circuit.AddGateCNot(b, c)
circuit.AddAlias(b, "G")
return c, d
}
func Multiplier(size int, full FullAdder, half HalfAdder) Circuit {
circuit := NewCircuit()
circuit.AddBus("I", 0, true)
circuit.AddBus("Y", size, false)
circuit.AddBus("X", size, false)
circuit.AddBus("A", size*size, false)
circuit.AddBus("P", 2*size, true)
circuit.AddBus("Z", 0, false)
circuit.AddBus("G", 0, true)
circuit.AddAlias("Y", "I")
circuit.AddAlias("X", "I")
circuit.AddAlias("Y", "G")
circuit.AddAlias("X", "G")
a, sums := 0, make([][]string, 2*size)
for x := 0; x < size; x++ {
for y := 0; y < size; y++ {
product, column := fmt.Sprintf("A%d", a), x+y
circuit.AddGateCCNot(fmt.Sprintf("Y%d", y), fmt.Sprintf("X%d", x), product)
sums[column] = append(sums[column], product)
a++
}
}
for i := range sums {
product := fmt.Sprintf("P%d", i)
for {
if length := len(sums[i]); length > 2 {
z := circuit.AddWire("Z", false)
sum, carry := full(&circuit, sums[i][0], sums[i][1], sums[i][2], z)
sums[i][2] = sum
sums[i] = sums[i][2:]
sums[i+1] = append(sums[i+1], carry)
} else if length == 2 {
z := circuit.AddWire("Z", false)
sum, carry := half(&circuit, sums[i][0], sums[i][1], z)
sums[i][1] = sum
sums[i] = sums[i][1:]
sums[i+1] = append(sums[i+1], carry)
} else {
circuit.AddAlias(sums[i][0], product)
break
}
}
}
return circuit
} | multiplier.go | 0.693265 | 0.407098 | multiplier.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.