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 pac
import (
"bytes"
"gopkg.in/jcmturner/gokrb5.v6/iana/chksumtype"
"gopkg.in/jcmturner/rpc.v1/mstypes"
)
/*
https://msdn.microsoft.com/en-us/library/cc237955.aspx
The Key Usage Value MUST be KERB_NON_KERB_CKSUM_SALT (17) [MS-KILE] (section 3.1.5.9).
Server Signature (SignatureType = 0x00000006)
https://msdn.microsoft.com/en-us/library/cc237957.aspx
The KDC will use the long-term key that the KDC shares with the server, so that the server can verify this signature on receiving a PAC.
The server signature is a keyed hash [RFC4757] of the entire PAC message, with the Signature fields of both PAC_SIGNATURE_DATA structures set to zero.
The key used to protect the ciphertext part of the response is used.
The checksum type corresponds to the key unless the key is DES, in which case the KERB_CHECKSUM_HMAC_MD5 key is used.
The resulting hash value is then placed in the Signature field of the server's PAC_SIGNATURE_DATA structure.
KDC Signature (SignatureType = 0x00000007)
https://msdn.microsoft.com/en-us/library/dd357117.aspx
The KDC will use KDC (krbtgt) key [RFC4120], so that other KDCs can verify this signature on receiving a PAC.
The KDC signature is a keyed hash [RFC4757] of the Server Signature field in the PAC message.
The cryptographic system that is used to calculate the checksum depends on which system the KDC supports, as defined below:
- Supports RC4-HMAC --> KERB_CHECKSUM_HMAC_MD5
- Does not support RC4-HMAC and supports AES256 --> HMAC_SHA1_96_AES256
- Does not support RC4-HMAC or AES256-CTS-HMAC-SHA1-96, and supports AES128-CTS-HMAC-SHA1-96 --> HMAC_SHA1_96_AES128
- Does not support RC4-HMAC, AES128-CTS-HMAC-SHA1-96 or AES256-CTS-HMAC-SHA1-96 --> None. The checksum operation will fail.
*/
// SignatureData implements https://msdn.microsoft.com/en-us/library/cc237955.aspx
type SignatureData struct {
SignatureType uint32 // A 32-bit unsigned integer value in little-endian format that defines the cryptographic system used to calculate the checksum. This MUST be one of the following checksum types: KERB_CHECKSUM_HMAC_MD5 (signature size = 16), HMAC_SHA1_96_AES128 (signature size = 12), HMAC_SHA1_96_AES256 (signature size = 12).
Signature []byte // Size depends on the type. See comment above.
RODCIdentifier uint16 // A 16-bit unsigned integer value in little-endian format that contains the first 16 bits of the key version number ([MS-KILE] section 3.1.5.8) when the KDC is an RODC. When the KDC is not an RODC, this field does not exist.
}
// Unmarshal bytes into the SignatureData struct
func (k *SignatureData) Unmarshal(b []byte) (rb []byte, err error) {
r := mstypes.NewReader(bytes.NewReader(b))
k.SignatureType, err = r.Uint32()
if err != nil {
return
}
var c int
switch k.SignatureType {
case chksumtype.KERB_CHECKSUM_HMAC_MD5_UNSIGNED:
c = 16
case uint32(chksumtype.HMAC_SHA1_96_AES128):
c = 12
case uint32(chksumtype.HMAC_SHA1_96_AES256):
c = 12
}
k.Signature, err = r.ReadBytes(c)
if err != nil {
return
}
// When the KDC is not an Read Only Domain Controller (RODC), this field does not exist.
if len(b) >= 4+c+2 {
k.RODCIdentifier, err = r.Uint16()
if err != nil {
return
}
}
// Create bytes with zeroed signature needed for checksum verification
rb = make([]byte, len(b), len(b))
copy(rb, b)
z := make([]byte, len(b), len(b))
copy(rb[4:4+c], z)
return
} | pac/signature_data.go | 0.719285 | 0.481576 | signature_data.go | starcoder |
package core
import (
"fmt"
"reflect"
)
// Convert and apply args to arbitrary function fn
func Cumin(fn interface{}, args []interface{}) ([]interface{}, error) {
reciever := reflect.TypeOf(fn)
var ret []interface{}
if reciever.Kind() != reflect.Func {
return ret, fmt.Errorf("Handler is not a function!")
}
if reciever.NumIn() != len(args) {
return ret, fmt.Errorf("Cumin: expected %d args for function %s, got %d", reciever.NumIn(), reciever, len(args))
}
// Iterate over the params listed in the method and try their casts
values := make([]reflect.Value, len(args))
for i := 0; i < reciever.NumIn(); i++ {
param := reciever.In(i)
arg := GetValueOf(args[i])
if param == arg.Type() {
values[i] = arg
} else if arg.Type().ConvertibleTo(param) {
values[i] = arg.Convert(param)
} else {
return ret, fmt.Errorf("Cumin: expected %s for arg[%d] in (%s), got %s.", param, i, reciever, arg.Type())
}
}
// Perform the call
result := reflect.ValueOf(fn).Call(values)
for _, x := range result {
ret = append(ret, x.Interface())
}
// Catch any exceptions this produces and pass them to the function that sent them, or some kind of handler
return ret, nil
}
/*
There are four cases SoftCumin can hit.
- Initial case: positional array of heterogenous elements (starting condition)
- Lists: array of homogenous elements checked against one type
- Dictionaries: dictionary of key/value pairs. Check key, value, and recursive
- Primitive: end case
The type of the next case is determined by reflecting the type of the expected element at that position.
Current version is not recursive, so dictionaries are not handled.
Version from the test:
[int [str] map[a:str b:int]] against [1 [Hey There] map[b:1 a:alpha]]
Version from swift:
[int [str] map[age:int name:str]]
[int [str] {name: str, age: int}] against [1 [Hey There] map[name:Billiam]]
*/
// Checks the types of the provided positional arguments and the receiver.
func SoftCumin(types []interface{}, args []interface{}) error {
//fmt.Printf("SOFTCUMIN: %v against %v\n", types, args)
if CuminLevel == CuminOff {
return nil
}
// Special case-- allow any arguments
if len(types) == 1 && types[0] == nil {
return nil
}
// Description to print on every failure
description := fmt.Sprintf("Types: %v, Arguments: %v", types, args)
if len(types) != len(args) {
return fmt.Errorf("Cumin: Invalid number of arguments, expected %d, receieved %d. %v", len(types), len(args), description)
}
for i := range args {
if e := _softCumin(types[i], args[i], i, description); e != nil {
return e
}
}
return nil
}
// Wraps reflect.ValueOf to handle the case where an integer value is stored as
// a float64, as JSON unmarshal does.
func GetValueOf(x interface{}) reflect.Value {
value := reflect.ValueOf(x)
if value.Kind() == reflect.Float64 {
asfloat := value.Float()
asint := int(asfloat)
if float64(asint) == asfloat {
value = reflect.ValueOf(asint)
}
}
return value
}
// Recursive worker function for SoftCumin.
func _softCumin(expected interface{}, x interface{}, i int, description string) error {
argument := GetValueOf(x)
// If the expected type is a string, we're looking for a primitive
if s, ok := expected.(string); ok {
if e := primitiveCheck(s, argument.Kind()); e != nil {
return e
}
} else if nestedSlice, ok := expected.([]interface{}); ok {
if len(nestedSlice) != 1 {
return fmt.Errorf("Cumin: array expected at position #%d is not homogenous. %s", i, expected)
}
if argumentList, ok := x.([]interface{}); !ok {
return fmt.Errorf("Cant read interface list %v at position %d", x, i)
} else {
for i := range argumentList {
if e := _softCumin(nestedSlice[0], argumentList[i], i, description); e != nil {
return e
}
}
}
} else if nestedMap, ok := expected.(map[string]interface{}); ok {
if argumentMap, ok := x.(map[string]interface{}); !ok {
return fmt.Errorf("Cumin: expected dictionary at position %d, got %v", i, reflect.TypeOf(x))
} else {
if e := mapCheck(nestedMap, argumentMap); e != nil {
return e
}
}
} else {
return fmt.Errorf("Cumin: couldnt find primitive, list, or dictionary at #%d. %v", i, description)
}
return nil
}
// Return an error if the argument is not of the expected type OR the expected type is not a primitive
func primitiveCheck(expected string, argument reflect.Kind) error {
if argument == reflect.Bool && expected == "bool" ||
argument == reflect.String && expected == "str" ||
argument == reflect.Float64 && (expected == "float" || expected == "int" || expected == "double") ||
argument == reflect.Int && (expected == "float" || expected == "int" || expected == "double") ||
argument == reflect.Map && expected == "dict" {
return nil
}
return fmt.Errorf("Cumin: expecting primitive %s, got %s", expected, argument)
}
// Recursively check an object. Return nil if the object matches the expected types
func mapCheck(expected map[string]interface{}, argument map[string]interface{}) error {
if len(expected) != len(argument) {
return fmt.Errorf("Cumin: object invalid number of keys, expected %d, receieved %d", len(expected), len(argument))
}
// TODO: nested collections and objects
for k, v := range argument {
if e := primitiveCheck(expected[k].(string), GetValueOf(v).Kind()); e != nil {
return e
}
}
return nil
} | cumin.go | 0.625667 | 0.512815 | cumin.go | starcoder |
package query
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"github.com/Jeffail/gabs/v2"
jsonschema "github.com/xeipuuv/gojsonschema"
)
var _ = registerSimpleMethod(
NewMethodSpec(
"all",
"Checks each element of an array against a query and returns true if all elements passed. An error occurs if the target is not an array, or if any element results in the provided query returning a non-boolean result. Returns false if the target array is empty.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root.all_over_21 = this.patrons.all(patron -> patron.age >= 21)`,
`{"patrons":[{"id":"1","age":18},{"id":"2","age":23}]}`,
`{"all_over_21":false}`,
`{"patrons":[{"id":"1","age":45},{"id":"2","age":23}]}`,
`{"all_over_21":true}`,
),
).Param(ParamQuery("test", "A test query to apply to each element.", false)),
func(args *ParsedParams) (simpleMethod, error) {
queryFn, err := args.FieldQuery("test")
if err != nil {
return nil, err
}
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
arr, ok := res.([]interface{})
if !ok {
return nil, NewTypeError(res, ValueArray)
}
if len(arr) == 0 {
return false, nil
}
for i, v := range arr {
res, err := queryFn.Exec(ctx.WithValue(v))
if err != nil {
return nil, fmt.Errorf("element %v: %w", i, err)
}
b, ok := res.(bool)
if !ok {
return nil, fmt.Errorf("element %v: %w", i, NewTypeError(res, ValueBool))
}
if !b {
return false, nil
}
}
return true, nil
}, nil
},
)
var _ = registerSimpleMethod(
NewMethodSpec(
"any",
"Checks the elements of an array against a query and returns true if any element passes. An error occurs if the target is not an array, or if an element results in the provided query returning a non-boolean result. Returns false if the target array is empty.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root.any_over_21 = this.patrons.any(patron -> patron.age >= 21)`,
`{"patrons":[{"id":"1","age":18},{"id":"2","age":23}]}`,
`{"any_over_21":true}`,
`{"patrons":[{"id":"1","age":10},{"id":"2","age":12}]}`,
`{"any_over_21":false}`,
),
).Param(ParamQuery("test", "A test query to apply to each element.", false)),
func(args *ParsedParams) (simpleMethod, error) {
queryFn, err := args.FieldQuery("test")
if err != nil {
return nil, err
}
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
arr, ok := res.([]interface{})
if !ok {
return nil, NewTypeError(res, ValueArray)
}
if len(arr) == 0 {
return false, nil
}
for i, v := range arr {
res, err := queryFn.Exec(ctx.WithValue(v))
if err != nil {
return nil, fmt.Errorf("element %v: %w", i, err)
}
b, ok := res.(bool)
if !ok {
return nil, fmt.Errorf("element %v: %w", i, NewTypeError(res, ValueBool))
}
if b {
return true, nil
}
}
return false, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"append",
"Returns an array with new elements appended to the end.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root.foo = this.foo.append("and", "this")`,
`{"foo":["bar","baz"]}`,
`{"foo":["bar","baz","and","this"]}`,
),
).VariadicParams(),
func(args *ParsedParams) (simpleMethod, error) {
argsList := args.Raw()
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
arr, ok := res.([]interface{})
if !ok {
return nil, NewTypeError(res, ValueArray)
}
copied := make([]interface{}, 0, len(arr)+len(argsList))
copied = append(copied, arr...)
return append(copied, argsList...), nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"collapse", "",
).InCategory(
MethodCategoryObjectAndArray,
"Collapse an array or object into an object of key/value pairs for each field, where the key is the full path of the structured field in dot path notation. Empty arrays an objects are ignored by default.",
NewExampleSpec("",
`root.result = this.collapse()`,
`{"foo":[{"bar":"1"},{"bar":{}},{"bar":"2"},{"bar":[]}]}`,
`{"result":{"foo.0.bar":"1","foo.2.bar":"2"}}`,
),
NewExampleSpec(
"An optional boolean parameter can be set to true in order to include empty objects and arrays.",
`root.result = this.collapse(include_empty: true)`,
`{"foo":[{"bar":"1"},{"bar":{}},{"bar":"2"},{"bar":[]}]}`,
`{"result":{"foo.0.bar":"1","foo.1.bar":{},"foo.2.bar":"2","foo.3.bar":[]}}`,
),
).Param(ParamBool("include_empty", "Whether to include empty objects and arrays in the resulting object.").Default(false)),
func(args *ParsedParams) (simpleMethod, error) {
includeEmpty, err := args.FieldBool("include_empty")
if err != nil {
return nil, err
}
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
gObj := gabs.Wrap(v)
if includeEmpty {
return gObj.FlattenIncludeEmpty()
}
return gObj.Flatten()
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"contains", "",
).InCategory(
MethodCategoryObjectAndArray,
"Checks whether an array contains an element matching the argument, or an object contains a value matching the argument, and returns a boolean result. Numerical comparisons are made irrespective of the representation type (float versus integer).",
NewExampleSpec("",
`root.has_foo = this.thing.contains("foo")`,
`{"thing":["this","foo","that"]}`,
`{"has_foo":true}`,
`{"thing":["this","bar","that"]}`,
`{"has_foo":false}`,
),
NewExampleSpec("",
`root.has_bar = this.thing.contains(20)`,
`{"thing":[10.3,20.0,"huh",3]}`,
`{"has_bar":true}`,
`{"thing":[2,3,40,67]}`,
`{"has_bar":false}`,
),
).InCategory(
MethodCategoryStrings,
"Checks whether a string contains a substring and returns a boolean result.",
NewExampleSpec("",
`root.has_foo = this.thing.contains("foo")`,
`{"thing":"this foo that"}`,
`{"has_foo":true}`,
`{"thing":"this bar that"}`,
`{"has_foo":false}`,
),
).Param(ParamAny("value", "A value to test against elements of the target.")),
func(args *ParsedParams) (simpleMethod, error) {
compareRight, err := args.Field("value")
if err != nil {
return nil, err
}
compareFn := func(compareLeft interface{}) bool {
return compareRight == compareLeft
}
if compareRightNum, err := IGetNumber(compareRight); err == nil {
compareFn = func(compareLeft interface{}) bool {
if leftAsNum, err := IGetNumber(compareLeft); err == nil {
return leftAsNum == compareRightNum
}
return false
}
}
sub := IToString(compareRight)
bsub := IToBytes(compareRight)
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
switch t := v.(type) {
case string:
return strings.Contains(t, sub), nil
case []byte:
return bytes.Contains(t, bsub), nil
case []interface{}:
for _, compareLeft := range t {
if compareFn(compareLeft) {
return true, nil
}
}
case map[string]interface{}:
for _, compareLeft := range t {
if compareFn(compareLeft) {
return true, nil
}
}
default:
return nil, NewTypeError(v, ValueString, ValueArray, ValueObject)
}
return false, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"enumerated",
"Converts an array into a new array of objects, where each object has a field index containing the `index` of the element and a field `value` containing the original value of the element.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.foo = this.foo.enumerated()`,
`{"foo":["bar","baz"]}`,
`{"foo":[{"index":0,"value":"bar"},{"index":1,"value":"baz"}]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
arr, ok := v.([]interface{})
if !ok {
return nil, NewTypeError(v, ValueArray)
}
enumerated := make([]interface{}, 0, len(arr))
for i, ele := range arr {
enumerated = append(enumerated, map[string]interface{}{
"index": int64(i),
"value": ele,
})
}
return enumerated, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"exists",
"Checks that a field, identified via a [dot path][field_paths], exists in an object.",
NewExampleSpec("",
`root.result = this.foo.exists("bar.baz")`,
`{"foo":{"bar":{"baz":"yep, I exist"}}}`,
`{"result":true}`,
`{"foo":{"bar":{}}}`,
`{"result":false}`,
`{"foo":{}}`,
`{"result":false}`,
),
).Param(ParamString("path", "A [dot path][field_paths] to a field.")),
func(args *ParsedParams) (simpleMethod, error) {
pathStr, err := args.FieldString("path")
if err != nil {
return nil, err
}
path := gabs.DotPathToSlice(pathStr)
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
return gabs.Wrap(v).Exists(path...), nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"explode", "",
).InCategory(
MethodCategoryObjectAndArray,
"Explodes an array or object at a [field path][field_paths].",
NewExampleSpec(`##### On arrays
Exploding arrays results in an array containing elements matching the original document, where the target field of each element is an element of the exploded array:`,
`root = this.explode("value")`,
`{"id":1,"value":["foo","bar","baz"]}`,
`[{"id":1,"value":"foo"},{"id":1,"value":"bar"},{"id":1,"value":"baz"}]`,
),
NewExampleSpec(`##### On objects
Exploding objects results in an object where the keys match the target object, and the values match the original document but with the target field replaced by the exploded value:`,
`root = this.explode("value")`,
`{"id":1,"value":{"foo":2,"bar":[3,4],"baz":{"bev":5}}}`,
`{"bar":{"id":1,"value":[3,4]},"baz":{"id":1,"value":{"bev":5}},"foo":{"id":1,"value":2}}`,
),
).Param(ParamString("path", "A [dot path][field_paths] to a field to explode.")),
func(args *ParsedParams) (simpleMethod, error) {
pathRaw, err := args.FieldString("path")
if err != nil {
return nil, err
}
path := gabs.DotPathToSlice(pathRaw)
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
target := gabs.Wrap(v).Search(path...)
switch t := target.Data().(type) {
case []interface{}:
result := make([]interface{}, len(t))
for i, ele := range t {
gExploded := gabs.Wrap(IClone(v))
gExploded.Set(ele, path...)
result[i] = gExploded.Data()
}
return result, nil
case map[string]interface{}:
result := make(map[string]interface{}, len(t))
for key, ele := range t {
gExploded := gabs.Wrap(IClone(v))
gExploded.Set(ele, path...)
result[key] = gExploded.Data()
}
return result, nil
}
return nil, fmt.Errorf("expected array or object value at path '%v', found: %v", pathRaw, ITypeOf(target.Data()))
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"filter", "",
).InCategory(
MethodCategoryObjectAndArray,
"Executes a mapping query argument for each element of an array or key/value pair of an object. If the query returns `false` the item is removed from the resulting array or object. The item will also be removed if the query returns any non-boolean value.",
NewExampleSpec(``,
`root.new_nums = this.nums.filter(num -> num > 10)`,
`{"nums":[3,11,4,17]}`,
`{"new_nums":[11,17]}`,
),
NewExampleSpec(`##### On objects
When filtering objects the mapping query argument is provided a context with a field `+"`key`"+` containing the value key, and a field `+"`value`"+` containing the value.`,
`root.new_dict = this.dict.filter(item -> item.value.contains("foo"))`,
`{"dict":{"first":"hello foo","second":"world","third":"this foo is great"}}`,
`{"new_dict":{"first":"hello foo","third":"this foo is great"}}`,
),
).Param(ParamQuery("test", "A query to apply to each element, if this query resolves to any value other than a boolean `true` the element will be removed from the result.", false)),
func(args *ParsedParams) (simpleMethod, error) {
mapFn, err := args.FieldQuery("test")
if err != nil {
return nil, err
}
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
var resValue interface{}
switch t := res.(type) {
case []interface{}:
newSlice := make([]interface{}, 0, len(t))
for _, v := range t {
f, err := mapFn.Exec(ctx.WithValue(v))
if err != nil {
return nil, err
}
if b, _ := f.(bool); b {
newSlice = append(newSlice, v)
}
}
resValue = newSlice
case map[string]interface{}:
newMap := make(map[string]interface{}, len(t))
for k, v := range t {
var ctxMap interface{} = map[string]interface{}{
"key": k,
"value": v,
}
f, err := mapFn.Exec(ctx.WithValue(ctxMap))
if err != nil {
return nil, err
}
if b, _ := f.(bool); b {
newMap[k] = v
}
}
resValue = newMap
default:
return nil, NewTypeError(res, ValueArray, ValueObject)
}
return resValue, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"flatten",
"Iterates an array and any element that is itself an array is removed and has its elements inserted directly in the resulting array.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(``,
`root.result = this.flatten()`,
`["foo",["bar","baz"],"buz"]`,
`{"result":["foo","bar","baz","buz"]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
array, isArray := v.([]interface{})
if !isArray {
return nil, NewTypeError(v, ValueArray)
}
result := make([]interface{}, 0, len(array))
for _, child := range array {
switch t := child.(type) {
case []interface{}:
result = append(result, t...)
default:
result = append(result, t)
}
}
return result, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"fold",
"Takes two arguments: an initial value, and a mapping query. For each element of an array the mapping context is an object with two fields `tally` and `value`, where `tally` contains the current accumulated value and `value` is the value of the current element. The mapping must return the result of adding the value to the tally.\n\nThe first argument is the value that `tally` will have on the first call.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(``,
`root.sum = this.foo.fold(0, item -> item.tally + item.value)`,
`{"foo":[3,8,11]}`,
`{"sum":22}`,
),
NewExampleSpec(``,
`root.result = this.foo.fold("", item -> "%v%v".format(item.tally, item.value))`,
`{"foo":["hello ", "world"]}`,
`{"result":"hello world"}`,
),
NewExampleSpec(`You can use fold to merge an array of objects together:`,
`root.smoothie = this.fruits.fold({}, item -> item.tally.merge(item.value))`,
`{"fruits":[{"apple":5},{"banana":3},{"orange":8}]}`,
`{"smoothie":{"apple":5,"banana":3,"orange":8}}`,
),
).
Param(ParamAny("initial", "The initial value to start the fold with. For example, an empty object `{}`, a zero count `0`, or an empty string `\"\"`.")).
Param(ParamQuery("query", "A query to apply for each element. The query is provided an object with two fields; `tally` containing the current tally, and `value` containing the value of the current element. The query should result in a new tally to be passed to the next element query.", false)),
func(args *ParsedParams) (simpleMethod, error) {
foldTallyStart, err := args.Field("initial")
if err != nil {
return nil, err
}
foldFn, err := args.FieldQuery("query")
if err != nil {
return nil, err
}
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
resArray, ok := res.([]interface{})
if !ok {
return nil, NewTypeError(res, ValueArray)
}
tally := IClone(foldTallyStart)
for _, v := range resArray {
newV, mapErr := foldFn.Exec(ctx.WithValue(map[string]interface{}{
"tally": tally,
"value": v,
}))
if mapErr != nil {
return nil, mapErr
}
tally = newV
}
return tally, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"index",
"Extract an element from an array by an index. The index can be negative, and if so the element will be selected from the end counting backwards starting from -1. E.g. an index of -1 returns the last element, an index of -2 returns the element before the last, and so on.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.last_name = this.names.index(-1)`,
`{"names":["rachel","stevens"]}`,
`{"last_name":"stevens"}`,
),
NewExampleSpec("It is also possible to use this method on byte arrays, in which case the selected element will be returned as an integer.",
`root.last_byte = this.name.bytes().index(-1)`,
`{"name":"<NAME>"}`,
`{"last_byte":110}`,
),
).Param(ParamInt64("index", "The index to obtain from an array.")),
func(args *ParsedParams) (simpleMethod, error) {
index, err := args.FieldInt64("index")
if err != nil {
return nil, err
}
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
switch array := v.(type) {
case []interface{}:
i := int(index)
if i < 0 {
i = len(array) + i
}
if i < 0 || i >= len(array) {
return nil, fmt.Errorf("index '%v' was out of bounds for array size: %v", i, len(array))
}
return array[i], nil
case []byte:
i := int(index)
if i < 0 {
i = len(array) + i
}
if i < 0 || i >= len(array) {
return nil, fmt.Errorf("index '%v' was out of bounds for array size: %v", i, len(array))
}
return int64(array[i]), nil
default:
return nil, NewTypeError(v, ValueArray)
}
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"json_schema",
"Checks a [JSON schema](https://json-schema.org/) against a value and returns the value if it matches or throws and error if it does not.",
).InCategory(
MethodCategoryObjectAndArray,
"",
NewExampleSpec("",
`root = this.json_schema("""{
"type":"object",
"properties":{
"foo":{
"type":"string"
}
}
}""")`,
`{"foo":"bar"}`,
`{"foo":"bar"}`,
`{"foo":5}`,
`Error("failed assignment (line 1): field `+"`this`"+`: foo invalid type. expected: string, given: integer")`,
),
NewExampleSpec(
"In order to load a schema from a file use the `file` function.",
`root = this.json_schema(file(var("BENTHOS_TEST_BLOBLANG_SCHEMA_FILE")))`,
),
).Beta().Param(ParamString("schema", "The schema to check values against.")),
func(args *ParsedParams) (simpleMethod, error) {
schemaStr, err := args.FieldString("schema")
if err != nil {
return nil, err
}
schema, err := jsonschema.NewSchema(jsonschema.NewStringLoader(schemaStr))
if err != nil {
return nil, fmt.Errorf("failed to parse json schema definition: %w", err)
}
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
result, err := schema.Validate(jsonschema.NewGoLoader(res))
if err != nil {
return nil, err
}
if !result.Valid() {
var errStr string
for i, desc := range result.Errors() {
if i > 0 {
errStr += "\n"
}
description := strings.ToLower(desc.Description())
if property := desc.Details()["property"]; property != nil {
description = property.(string) + strings.TrimPrefix(description, strings.ToLower(property.(string)))
}
errStr = errStr + desc.Field() + " " + description
}
return nil, errors.New(errStr)
}
return res, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"keys",
"Returns the keys of an object as an array.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.foo_keys = this.foo.keys()`,
`{"foo":{"bar":1,"baz":2}}`,
`{"foo_keys":["bar","baz"]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
if m, ok := v.(map[string]interface{}); ok {
keys := make([]interface{}, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i].(string) < keys[j].(string)
})
return keys, nil
}
return nil, NewTypeError(v, ValueObject)
}, nil
},
)
var _ = registerSimpleMethod(
NewMethodSpec(
"key_values",
"Returns the key/value pairs of an object as an array, where each element is an object with a `key` field and a `value` field. The order of the resulting array will be random.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec("",
`root.foo_key_values = this.foo.key_values().sort_by(pair -> pair.key)`,
`{"foo":{"bar":1,"baz":2}}`,
`{"foo_key_values":[{"key":"bar","value":1},{"key":"baz","value":2}]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
if m, ok := v.(map[string]interface{}); ok {
keyValues := make([]interface{}, 0, len(m))
for k, v := range m {
keyValues = append(keyValues, map[string]interface{}{
"key": k,
"value": v,
})
}
return keyValues, nil
}
return nil, NewTypeError(v, ValueObject)
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"length", "",
).InCategory(
MethodCategoryStrings, "Returns the length of a string.",
NewExampleSpec("",
`root.foo_len = this.foo.length()`,
`{"foo":"hello world"}`,
`{"foo_len":11}`,
),
).InCategory(
MethodCategoryObjectAndArray, "Returns the length of an array or object (number of keys).",
NewExampleSpec("",
`root.foo_len = this.foo.length()`,
`{"foo":["first","second"]}`,
`{"foo_len":2}`,
`{"foo":{"first":"bar","second":"baz"}}`,
`{"foo_len":2}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
var length int64
switch t := v.(type) {
case string:
length = int64(len(t))
case []byte:
length = int64(len(t))
case []interface{}:
length = int64(len(t))
case map[string]interface{}:
length = int64(len(t))
default:
return nil, NewTypeError(v, ValueString, ValueArray, ValueObject)
}
return length, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"map_each", "",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(`##### On arrays
Apply a mapping to each element of an array and replace the element with the result. Within the argument mapping the context is the value of the element being mapped.`,
`root.new_nums = this.nums.map_each(num -> if num < 10 {
deleted()
} else {
num - 10
})`,
`{"nums":[3,11,4,17]}`,
`{"new_nums":[1,7]}`,
),
NewExampleSpec(`##### On objects
Apply a mapping to each value of an object and replace the value with the result. Within the argument mapping the context is an object with a field `+"`key`"+` containing the value key, and a field `+"`value`"+`.`,
`root.new_dict = this.dict.map_each(item -> item.value.uppercase())`,
`{"dict":{"foo":"hello","bar":"world"}}`,
`{"new_dict":{"bar":"WORLD","foo":"HELLO"}}`,
),
).Param(ParamQuery("query", "A query that will be used to map each element.", false)),
func(args *ParsedParams) (simpleMethod, error) {
mapFn, err := args.FieldQuery("query")
if err != nil {
return nil, err
}
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
var resValue interface{}
var err error
switch t := res.(type) {
case []interface{}:
newSlice := make([]interface{}, 0, len(t))
for i, v := range t {
newV, mapErr := mapFn.Exec(ctx.WithValue(v))
if mapErr != nil {
return nil, fmt.Errorf("failed to process element %v: %w", i, ErrFrom(mapErr, mapFn))
}
switch newV.(type) {
case Delete:
case Nothing:
newSlice = append(newSlice, v)
default:
newSlice = append(newSlice, newV)
}
}
resValue = newSlice
case map[string]interface{}:
newMap := make(map[string]interface{}, len(t))
for k, v := range t {
var ctxMap interface{} = map[string]interface{}{
"key": k,
"value": v,
}
newV, mapErr := mapFn.Exec(ctx.WithValue(ctxMap))
if mapErr != nil {
return nil, fmt.Errorf("failed to process element %v: %w", k, ErrFrom(mapErr, mapFn))
}
switch newV.(type) {
case Delete:
case Nothing:
newMap[k] = v
default:
newMap[k] = newV
}
}
resValue = newMap
default:
return nil, NewTypeError(res, ValueArray)
}
if err != nil {
return nil, err
}
return resValue, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"map_each_key", "",
).InCategory(
MethodCategoryObjectAndArray, `Apply a mapping to each key of an object, and replace the key with the result, which must be a string.`,
NewExampleSpec(``,
`root.new_dict = this.dict.map_each_key(key -> key.uppercase())`,
`{"dict":{"keya":"hello","keyb":"world"}}`,
`{"new_dict":{"KEYA":"hello","KEYB":"world"}}`,
),
NewExampleSpec(``,
`root = this.map_each_key(key -> if key.contains("kafka") { "_" + key })`,
`{"amqp_key":"foo","kafka_key":"bar","kafka_topic":"baz"}`,
`{"_kafka_key":"bar","_kafka_topic":"baz","amqp_key":"foo"}`,
),
).Param(ParamQuery("query", "A query that will be used to map each key.", false)),
func(args *ParsedParams) (simpleMethod, error) {
mapFn, err := args.FieldQuery("query")
if err != nil {
return nil, err
}
return func(res interface{}, ctx FunctionContext) (interface{}, error) {
obj, ok := res.(map[string]interface{})
if !ok {
return nil, NewTypeError(res, ValueObject)
}
newMap := make(map[string]interface{}, len(obj))
for k, v := range obj {
var ctxVal interface{} = k
newKey, mapErr := mapFn.Exec(ctx.WithValue(ctxVal))
if mapErr != nil {
return nil, mapErr
}
switch t := newKey.(type) {
// TODO: Revise whether we want this.
// case Delete:
case Nothing:
newMap[k] = v
case string:
newMap[t] = v
default:
return nil, fmt.Errorf("unexpected result from key mapping: %w", NewTypeError(newKey, ValueString))
}
}
return newMap, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerMethod(
NewMethodSpec(
"merge", "Merge a source object into an existing destination object. When a collision is found within the merged structures (both a source and destination object contain the same non-object keys) the result will be an array containing both values, where values that are already arrays will be expanded into the resulting array.",
).InCategory(
MethodCategoryObjectAndArray, "",
NewExampleSpec(``,
`root = this.foo.merge(this.bar)`,
`{"foo":{"first_name":"fooer","likes":"bars"},"bar":{"second_name":"barer","likes":"foos"}}`,
`{"first_name":"fooer","likes":["bars","foos"],"second_name":"barer"}`,
),
).Param(ParamAny("with", "A value to merge the target value with.")),
mergeMethod,
)
func mergeMethod(target Function, args *ParsedParams) (Function, error) {
mergeFromSource, err := args.Field("with")
if err != nil {
return nil, err
}
return ClosureFunction("method merge", func(ctx FunctionContext) (interface{}, error) {
mergeInto, err := target.Exec(ctx)
if err != nil {
return nil, err
}
mergeFrom := IClone(mergeFromSource)
if root, isArray := mergeInto.([]interface{}); isArray {
if rhs, isAlsoArray := mergeFrom.([]interface{}); isAlsoArray {
return append(root, rhs...), nil
}
return append(root, mergeFrom), nil
}
if _, isObject := mergeInto.(map[string]interface{}); !isObject {
return nil, NewTypeErrorFrom(target.Annotation(), mergeInto, ValueObject, ValueArray)
}
root := gabs.New()
if err = root.Merge(gabs.Wrap(mergeInto)); err == nil {
err = root.Merge(gabs.Wrap(mergeFrom))
}
if err != nil {
return nil, err
}
return root.Data(), nil
}, target.QueryTargets), nil
}
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"not_empty", "",
).InCategory(
MethodCategoryCoercion,
"Ensures that the given string, array or object value is not empty, and if so returns it, otherwise an error is returned.",
NewExampleSpec("",
`root.a = this.a.not_empty()`,
`{"a":"foo"}`,
`{"a":"foo"}`,
`{"a":""}`,
`Error("failed assignment (line 1): field `+"`this.a`"+`: string value is empty")`,
`{"a":["foo","bar"]}`,
`{"a":["foo","bar"]}`,
`{"a":[]}`,
`Error("failed assignment (line 1): field `+"`this.a`"+`: array value is empty")`,
`{"a":{"b":"foo","c":"bar"}}`,
`{"a":{"b":"foo","c":"bar"}}`,
`{"a":{}}`,
`Error("failed assignment (line 1): field `+"`this.a`"+`: object value is empty")`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
switch t := v.(type) {
case string:
if t == "" {
return nil, errors.New("string value is empty")
}
case []interface{}:
if len(t) == 0 {
return nil, errors.New("array value is empty")
}
case map[string]interface{}:
if len(t) == 0 {
return nil, errors.New("object value is empty")
}
default:
return nil, NewTypeError(v, ValueString, ValueArray, ValueObject)
}
return v, nil
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerMethod(
NewMethodSpec(
"sort", "",
).InCategory(
MethodCategoryObjectAndArray,
"Attempts to sort the values of an array in increasing order. The type of all values must match in order for the ordering to succeed. Supports string and number values.",
NewExampleSpec("",
`root.sorted = this.foo.sort()`,
`{"foo":["bbb","ccc","aaa"]}`,
`{"sorted":["aaa","bbb","ccc"]}`,
),
NewExampleSpec("It's also possible to specify a mapping argument, which is provided an object context with fields `left` and `right`, the mapping must return a boolean indicating whether the `left` value is less than `right`. This allows you to sort arrays containing non-string or non-number values.",
`root.sorted = this.foo.sort(item -> item.left.v < item.right.v)`,
`{"foo":[{"id":"foo","v":"bbb"},{"id":"bar","v":"ccc"},{"id":"baz","v":"aaa"}]}`,
`{"sorted":[{"id":"baz","v":"aaa"},{"id":"foo","v":"bbb"},{"id":"bar","v":"ccc"}]}`,
),
).
Param(ParamQuery(
"compare",
"An optional query that should explicitly compare elements `left` and `right` and provide a boolean result.",
false,
).Optional()),
sortMethod,
)
func sortMethod(target Function, args *ParsedParams) (Function, error) {
compareFn := func(ctx FunctionContext, values []interface{}, i, j int) (bool, error) {
switch values[i].(type) {
case float64, int, int64, uint64, json.Number:
lhs, err := IGetNumber(values[i])
if err != nil {
return false, fmt.Errorf("sort element %v: %w", i, err)
}
rhs, err := IGetNumber(values[j])
if err != nil {
return false, fmt.Errorf("sort element %v: %w", j, err)
}
return lhs < rhs, nil
case string, []byte:
lhs, err := IGetString(values[i])
if err != nil {
return false, fmt.Errorf("sort element %v: %w", i, err)
}
rhs, err := IGetString(values[j])
if err != nil {
return false, fmt.Errorf("sort element %v: %w", j, err)
}
return lhs < rhs, nil
}
return false, fmt.Errorf("sort element %v: %w", i, NewTypeError(values[i], ValueNumber, ValueString))
}
mapFn, err := args.FieldOptionalQuery("compare")
if err != nil {
return nil, err
}
if mapFn != nil {
compareFn = func(ctx FunctionContext, values []interface{}, i, j int) (bool, error) {
var ctxValue interface{} = map[string]interface{}{
"left": values[i],
"right": values[j],
}
v, err := mapFn.Exec(ctx.WithValue(ctxValue))
if err != nil {
return false, err
}
b, ok := v.(bool)
if !ok {
return false, NewTypeErrorFrom("sort argument", v, ValueBool)
}
return b, nil
}
}
targets := target.QueryTargets
if mapFn != nil {
targets = aggregateTargetPaths(target, mapFn)
}
return ClosureFunction("method sort", func(ctx FunctionContext) (interface{}, error) {
v, err := target.Exec(ctx)
if err != nil {
return nil, err
}
if m, ok := v.([]interface{}); ok {
values := make([]interface{}, 0, len(m))
values = append(values, m...)
sort.Slice(values, func(i, j int) bool {
if err == nil {
var b bool
b, err = compareFn(ctx, values, i, j)
return b
}
return false
})
if err != nil {
return nil, err
}
return values, nil
}
return nil, NewTypeErrorFrom(target.Annotation(), v, ValueArray)
}, targets), nil
}
var _ = registerMethod(
NewMethodSpec(
"sort_by", "",
).InCategory(
MethodCategoryObjectAndArray,
"Attempts to sort the elements of an array, in increasing order, by a value emitted by an argument query applied to each element. The type of all values must match in order for the ordering to succeed. Supports string and number values.",
NewExampleSpec("",
`root.sorted = this.foo.sort_by(ele -> ele.id)`,
`{"foo":[{"id":"bbb","message":"bar"},{"id":"aaa","message":"foo"},{"id":"ccc","message":"baz"}]}`,
`{"sorted":[{"id":"aaa","message":"foo"},{"id":"bbb","message":"bar"},{"id":"ccc","message":"baz"}]}`,
),
).Param(ParamQuery("query", "A query to apply to each element that yields a value used for sorting.", false)),
sortByMethod,
)
func sortByMethod(target Function, args *ParsedParams) (Function, error) {
mapFn, err := args.FieldQuery("query")
if err != nil {
return nil, err
}
compareFn := func(ctx FunctionContext, values []interface{}, i, j int) (bool, error) {
var leftValue, rightValue interface{}
var err error
if leftValue, err = mapFn.Exec(ctx.WithValue(values[i])); err != nil {
return false, err
}
if rightValue, err = mapFn.Exec(ctx.WithValue(values[j])); err != nil {
return false, err
}
switch leftValue.(type) {
case float64, int, int64, uint64, json.Number:
lhs, err := IGetNumber(leftValue)
if err != nil {
return false, fmt.Errorf("sort_by element %v: %w", i, ErrFrom(err, mapFn))
}
rhs, err := IGetNumber(rightValue)
if err != nil {
return false, fmt.Errorf("sort_by element %v: %w", j, ErrFrom(err, mapFn))
}
return lhs < rhs, nil
case string, []byte:
lhs, err := IGetString(leftValue)
if err != nil {
return false, fmt.Errorf("sort_by element %v: %w", i, ErrFrom(err, mapFn))
}
rhs, err := IGetString(rightValue)
if err != nil {
return false, fmt.Errorf("sort_by element %v: %w", j, ErrFrom(err, mapFn))
}
return lhs < rhs, nil
}
return false, fmt.Errorf("sort_by element %v: %w", i, ErrFrom(NewTypeError(leftValue, ValueNumber, ValueString), mapFn))
}
return ClosureFunction("method sort_by", func(ctx FunctionContext) (interface{}, error) {
v, err := target.Exec(ctx)
if err != nil {
return nil, err
}
if m, ok := v.([]interface{}); ok {
values := make([]interface{}, 0, len(m))
values = append(values, m...)
sort.Slice(values, func(i, j int) bool {
if err == nil {
var b bool
b, err = compareFn(ctx, values, i, j)
return b
}
return false
})
if err != nil {
return nil, err
}
return values, nil
}
return nil, NewTypeErrorFrom(target.Annotation(), v, ValueArray)
}, aggregateTargetPaths(target, mapFn)), nil
}
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"slice", "",
).InCategory(
MethodCategoryStrings,
"Extract a slice from a string by specifying two indices, a low and high bound, which selects a half-open range that includes the first character, but excludes the last one. If the second index is omitted then it defaults to the length of the input sequence.",
NewExampleSpec("",
`root.beginning = this.value.slice(0, 2)
root.end = this.value.slice(4)`,
`{"value":"foo bar"}`,
`{"beginning":"fo","end":"bar"}`,
),
NewExampleSpec(`A negative low index can be used, indicating an offset from the end of the sequence. If the low index is greater than the length of the sequence then an empty result is returned.`,
`root.last_chunk = this.value.slice(-4)
root.the_rest = this.value.slice(0, -4)`,
`{"value":"foo bar"}`,
`{"last_chunk":" bar","the_rest":"foo"}`,
),
).InCategory(
MethodCategoryObjectAndArray,
"Extract a slice from an array by specifying two indices, a low and high bound, which selects a half-open range that includes the first element, but excludes the last one. If the second index is omitted then it defaults to the length of the input sequence.",
NewExampleSpec("",
`root.beginning = this.value.slice(0, 2)
root.end = this.value.slice(4)`,
`{"value":["foo","bar","baz","buz","bev"]}`,
`{"beginning":["foo","bar"],"end":["bev"]}`,
),
NewExampleSpec(
`A negative low index can be used, indicating an offset from the end of the sequence. If the low index is greater than the length of the sequence then an empty result is returned.`,
`root.last_chunk = this.value.slice(-2)
root.the_rest = this.value.slice(0, -2)`,
`{"value":["foo","bar","baz","buz","bev"]}`,
`{"last_chunk":["buz","bev"],"the_rest":["foo","bar","baz"]}`,
),
).
Param(ParamInt64("low", "The low bound, which is the first element of the selection, or if negative selects from the end.")).
Param(ParamInt64("high", "An optional high bound.").Optional()),
sliceMethod,
)
func sliceMethod(args *ParsedParams) (simpleMethod, error) {
low, err := args.FieldInt64("low")
if err != nil {
return nil, err
}
high, err := args.FieldOptionalInt64("high")
if err != nil {
return nil, err
}
if high != nil && *high > 0 && low >= *high {
return nil, fmt.Errorf("lower slice bound %v must be lower than upper (%v)", low, *high)
}
getBounds := func(l int64) (lowV, highV int64, err error) {
highV = l
if high != nil {
if *high < 0 {
highV += *high
} else {
highV = *high
}
}
if highV > l {
highV = l
}
if highV < 0 {
highV = 0
}
lowV = low
if lowV < 0 {
lowV = l + lowV
if lowV < 0 {
lowV = 0
}
}
if lowV > highV {
err = fmt.Errorf("lower slice bound %v must be lower than or equal to upper bound (%v) and target length (%v)", lowV, highV, l)
}
return
}
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
switch t := v.(type) {
case string:
start, end, err := getBounds(int64(len(t)))
if err != nil {
return nil, err
}
return t[start:end], nil
case []byte:
start, end, err := getBounds(int64(len(t)))
if err != nil {
return nil, err
}
return t[start:end], nil
case []interface{}:
start, end, err := getBounds(int64(len(t)))
if err != nil {
return nil, err
}
return t[start:end], nil
}
return nil, NewTypeError(v, ValueArray, ValueString)
}, nil
}
//------------------------------------------------------------------------------
var _ = registerMethod(
NewMethodSpec(
"sum", "",
).InCategory(
MethodCategoryObjectAndArray,
"Sum the numerical values of an array.",
NewExampleSpec("",
`root.sum = this.foo.sum()`,
`{"foo":[3,8,4]}`,
`{"sum":15}`,
),
),
sumMethod,
)
func sumMethod(target Function, _ *ParsedParams) (Function, error) {
return ClosureFunction("method sum", func(ctx FunctionContext) (interface{}, error) {
v, err := target.Exec(ctx)
if err != nil {
return nil, err
}
switch t := ISanitize(v).(type) {
case float64, int64, uint64, json.Number:
return v, nil
case []interface{}:
var total float64
for i, v := range t {
n, nErr := IGetNumber(v)
if nErr != nil {
err = fmt.Errorf("index %v: %w", i, nErr)
} else {
total += n
}
}
if err != nil {
return nil, err
}
return total, nil
}
return nil, NewTypeErrorFrom(target.Annotation(), v, ValueArray)
}, target.QueryTargets), nil
}
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"unique", "",
).InCategory(
MethodCategoryObjectAndArray,
"Attempts to remove duplicate values from an array. The array may contain a combination of different value types, but numbers and strings are checked separately (`\"5\"` is a different element to `5`).",
NewExampleSpec("",
`root.uniques = this.foo.unique()`,
`{"foo":["a","b","a","c"]}`,
`{"uniques":["a","b","c"]}`,
),
).
Param(ParamQuery(
"emit",
"An optional query that can be used in order to yield a value for each element to determine uniqueness.",
false,
).Optional()),
uniqueMethod,
)
func uniqueMethod(args *ParsedParams) (simpleMethod, error) {
emitFn, err := args.FieldOptionalQuery("emit")
if err != nil {
return nil, err
}
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
slice, ok := v.([]interface{})
if !ok {
return nil, NewTypeError(v, ValueArray)
}
var strCompares map[string]struct{}
var numCompares map[float64]struct{}
checkStr := func(str string) bool {
if strCompares == nil {
strCompares = make(map[string]struct{}, len(slice))
}
_, exists := strCompares[str]
if !exists {
strCompares[str] = struct{}{}
}
return !exists
}
checkNum := func(num float64) bool {
if numCompares == nil {
numCompares = make(map[float64]struct{}, len(slice))
}
_, exists := numCompares[num]
if !exists {
numCompares[num] = struct{}{}
}
return !exists
}
uniqueSlice := make([]interface{}, 0, len(slice))
for i, v := range slice {
check := v
if emitFn != nil {
var err error
if check, err = emitFn.Exec(ctx.WithValue(v)); err != nil {
return nil, fmt.Errorf("index %v: %w", i, err)
}
}
var unique bool
switch t := ISanitize(check).(type) {
case string:
unique = checkStr(t)
case []byte:
unique = checkStr(string(t))
case json.Number:
f, err := t.Float64()
if err != nil {
var i int64
if i, err = t.Int64(); err == nil {
f = float64(i)
}
}
if err != nil {
return nil, fmt.Errorf("index %v: failed to parse number: %w", i, err)
}
unique = checkNum(f)
case int64:
unique = checkNum(float64(t))
case uint64:
unique = checkNum(float64(t))
case float64:
unique = checkNum(t)
default:
return nil, fmt.Errorf("index %v: %w", i, NewTypeError(check, ValueString, ValueNumber))
}
if unique {
uniqueSlice = append(uniqueSlice, v)
}
}
return uniqueSlice, nil
}, nil
}
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"values", "",
).InCategory(
MethodCategoryObjectAndArray,
"Returns the values of an object as an array. The order of the resulting array will be random.",
NewExampleSpec("",
`root.foo_vals = this.foo.values().sort()`,
`{"foo":{"bar":1,"baz":2}}`,
`{"foo_vals":[1,2]}`,
),
),
func(*ParsedParams) (simpleMethod, error) {
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
if m, ok := v.(map[string]interface{}); ok {
values := make([]interface{}, 0, len(m))
for _, e := range m {
values = append(values, e)
}
return values, nil
}
return nil, NewTypeError(v, ValueObject)
}, nil
},
)
//------------------------------------------------------------------------------
var _ = registerSimpleMethod(
NewMethodSpec(
"without", "",
).InCategory(
MethodCategoryObjectAndArray,
`Returns an object where one or more [field path][field_paths] arguments are removed. Each path specifies a specific field to be deleted from the input object, allowing for nested fields.
If a key within a nested path does not exist or is not an object then it is not removed.`,
NewExampleSpec("",
`root = this.without("inner.a","inner.c","d")`,
`{"inner":{"a":"first","b":"second","c":"third"},"d":"fourth","e":"fifth"}`,
`{"e":"fifth","inner":{"b":"second"}}`,
),
).VariadicParams(),
func(args *ParsedParams) (simpleMethod, error) {
excludeList := make([][]string, 0, len(args.Raw()))
for i, argVal := range args.Raw() {
argStr, err := IGetString(argVal)
if err != nil {
return nil, fmt.Errorf("argument %v: %w", i, err)
}
excludeList = append(excludeList, gabs.DotPathToSlice(argStr))
}
return func(v interface{}, ctx FunctionContext) (interface{}, error) {
m, ok := v.(map[string]interface{})
if !ok {
return nil, NewTypeError(v, ValueObject)
}
return mapWithout(m, excludeList), nil
}, nil
},
)
func mapWithout(m map[string]interface{}, paths [][]string) map[string]interface{} {
newMap := make(map[string]interface{}, len(m))
for k, v := range m {
excluded := false
var nestedExclude [][]string
for _, p := range paths {
if p[0] == k {
if len(p) > 1 {
nestedExclude = append(nestedExclude, p[1:])
} else {
excluded = true
}
}
}
if !excluded {
if len(nestedExclude) > 0 {
vMap, ok := v.(map[string]interface{})
if ok {
newMap[k] = mapWithout(vMap, nestedExclude)
} else {
newMap[k] = v
}
} else {
newMap[k] = v
}
}
}
return newMap
} | internal/bloblang/query/methods_structured.go | 0.625438 | 0.446253 | methods_structured.go | starcoder |
package buffer
import (
"sync/atomic"
"time"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/types"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeNone] = TypeSpec{
constructor: NewEmpty,
Summary: `
Do not buffer messages. This is the default and most resilient configuration.`,
Description: `
Selecting no buffer means the output layer is directly coupled with the input
layer. This is the safest and lowest latency option since acknowledgements from
at-least-once protocols can be propagated all the way from the output protocol
to the input protocol.
If the output layer is hit with back pressure it will propagate all the way to
the input layer, and further up the data stream. If you need to relieve your
pipeline of this back pressure consider using a more robust buffering solution
such as Kafka before resorting to alternatives.`,
config: docs.FieldComponent().HasType(docs.FieldTypeObject),
}
}
//------------------------------------------------------------------------------
// Empty is an empty buffer, simply forwards messages on directly.
type Empty struct {
running int32
messagesOut chan types.Transaction
messagesIn <-chan types.Transaction
closeChan chan struct{}
closed chan struct{}
}
// NewEmpty creates a new buffer interface but doesn't buffer messages.
func NewEmpty(config Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
e := &Empty{
running: 1,
messagesOut: make(chan types.Transaction),
closeChan: make(chan struct{}),
closed: make(chan struct{}),
}
return e, nil
}
//------------------------------------------------------------------------------
// loop is an internal loop of the empty buffer.
func (e *Empty) loop() {
defer func() {
atomic.StoreInt32(&e.running, 0)
close(e.messagesOut)
close(e.closed)
}()
var open bool
for atomic.LoadInt32(&e.running) == 1 {
var inT types.Transaction
select {
case inT, open = <-e.messagesIn:
if !open {
return
}
case <-e.closeChan:
return
}
select {
case e.messagesOut <- inT:
case <-e.closeChan:
return
}
}
}
//------------------------------------------------------------------------------
// Consume assigns a messages channel for the output to read.
func (e *Empty) Consume(msgs <-chan types.Transaction) error {
if e.messagesIn != nil {
return types.ErrAlreadyStarted
}
e.messagesIn = msgs
go e.loop()
return nil
}
// TransactionChan returns the channel used for consuming messages from this
// input.
func (e *Empty) TransactionChan() <-chan types.Transaction {
return e.messagesOut
}
// ErrorsChan returns the errors channel.
func (e *Empty) ErrorsChan() <-chan []error {
return nil
}
// StopConsuming instructs the buffer to no longer consume data.
func (e *Empty) StopConsuming() {
e.CloseAsync()
}
// CloseAsync shuts down the StackBuffer output and stops processing messages.
func (e *Empty) CloseAsync() {
if atomic.CompareAndSwapInt32(&e.running, 1, 0) {
close(e.closeChan)
}
}
// WaitForClose blocks until the StackBuffer output has closed down.
func (e *Empty) WaitForClose(timeout time.Duration) error {
select {
case <-e.closed:
case <-time.After(timeout):
return types.ErrTimeout
}
return nil
}
//------------------------------------------------------------------------------ | lib/buffer/none.go | 0.608827 | 0.477371 | none.go | starcoder |
package output
import (
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/internal/service/redis"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/output/writer"
"github.com/Jeffail/benthos/v3/lib/types"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeRedisStreams] = TypeSpec{
constructor: fromSimpleConstructor(NewRedisStreams),
Summary: `
Pushes messages to a Redis (v5.0+) Stream (which is created if it doesn't
already exist) using the XADD command.`,
Description: `
It's possible to specify a maximum length of the target stream by setting it to
a value greater than 0, in which case this cap is applied only when Redis is
able to remove a whole macro node, for efficiency.
Redis stream entries are key/value pairs, as such it is necessary to specify the
key to be set to the body of the message. All metadata fields of the message
will also be set as key/value pairs, if there is a key collision between
a metadata item and the body then the body takes precedence.`,
Async: true,
FieldSpecs: redis.ConfigDocs().Add(
docs.FieldCommon("stream", "The stream to add messages to."),
docs.FieldCommon("body_key", "A key to set the raw body of the message to."),
docs.FieldCommon("max_length", "When greater than zero enforces a rough cap on the length of the target stream."),
docs.FieldCommon("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."),
),
Categories: []Category{
CategoryServices,
},
}
}
//------------------------------------------------------------------------------
// NewRedisStreams creates a new RedisStreams output type.
func NewRedisStreams(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
w, err := writer.NewRedisStreams(conf.RedisStreams, log, stats)
if err != nil {
return nil, err
}
if conf.RedisStreams.MaxInFlight == 1 {
return NewWriter(TypeRedisStreams, w, log, stats)
}
return NewAsyncWriter(TypeRedisStreams, conf.RedisStreams.MaxInFlight, w, log, stats)
}
//------------------------------------------------------------------------------ | lib/output/redis_streams.go | 0.669853 | 0.430506 | redis_streams.go | starcoder |
package geoindex
import (
"fmt"
)
type CountIndex struct {
index *geoIndex
currentPosition map[string]Point
}
type CountPoint struct {
*GeoPoint
Count interface{}
}
func (p *CountPoint) String() string {
return fmt.Sprintf("%f %f %d", p.Lat(), p.Lon(), p.Count)
}
// NewCountIndex creates an index which counts the points in each cell.
func NewCountIndex(resolution Meters) *CountIndex {
newCounter := func() interface{} {
return &singleValueAccumulatingCounter{}
}
return &CountIndex{newGeoIndex(resolution, newCounter), make(map[string]Point)}
}
// NewExpiringCountIndex creates an index, which maintains an expiring counter for each cell.
func NewExpiringCountIndex(resolution Meters, expiration Minutes) *CountIndex {
newExpiringCounter := func() interface{} {
return newExpiringCounter(expiration)
}
return &CountIndex{newGeoIndex(resolution, newExpiringCounter), make(map[string]Point)}
}
func (index *CountIndex) Clone() *CountIndex {
clone := &CountIndex{}
// Copy all entries from current positions
clone.currentPosition = make(map[string]Point, len(index.currentPosition))
for k, v := range index.currentPosition {
clone.currentPosition[k] = v
}
// Copying underlying geoindex data
clone.index = index.index.Clone()
return clone
}
// Add adds a point.
func (countIndex *CountIndex) Add(point Point) {
countIndex.Remove(point.Id())
countIndex.currentPosition[point.Id()] = point
countIndex.index.AddEntryAt(point).(counter).Add(point)
}
// Remove removes a point.
func (countIndex *CountIndex) Remove(id string) {
if prev, ok := countIndex.currentPosition[id]; ok {
countIndex.index.GetEntryAt(prev).(counter).Remove(prev)
delete(countIndex.currentPosition, id)
}
}
// Range returns the counters within some lat, lng range.
func (countIndex *CountIndex) Range(topLeft Point, bottomRight Point) []Point {
counters := countIndex.index.Range(topLeft, bottomRight)
points := make([]Point, 0)
for _, c := range counters {
if c.(counter).Point() != nil {
points = append(points, c.(counter).Point())
}
}
return points
}
// KNearest just to satisfy an interface. Doesn't make much sense for count index.
func (index *CountIndex) KNearest(point Point, k int, maxDistance Meters, accept func(p Point) bool) []Point {
panic("Unsupported operation")
} | hotelReservation/vendor/github.com/hailocab/go-geoindex/count-index.go | 0.816443 | 0.589332 | count-index.go | starcoder |
package analysis
import (
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
)
// funcLookup allows the performant lookup of function and method declarations in the current package by name,
// and the lookup of cached error codes and affectors for function declarations.
type funcLookup struct {
functions map[string]*ast.FuncDecl // Mapping Function Names to Declarations
methods map[string][]*ast.FuncDecl // Mapping Method Names to Declarations (Multiple Possible per Name)
methodSet typeutil.MethodSetCache
foundCodes map[funcDeclOrLit]CodeSet // Mapping Function Declarations and Function Literals to cached error codes
}
func newFuncLookup() *funcLookup {
return &funcLookup{
map[string]*ast.FuncDecl{},
map[string][]*ast.FuncDecl{},
typeutil.MethodSetCache{},
map[funcDeclOrLit]CodeSet{},
}
}
// collectFunctions creates a funcLookup using the given analysis object.
func collectFunctions(pass *analysis.Pass) *funcLookup {
result := newFuncLookup()
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
// We only need to see function declarations at first; we'll recurse ourselves within there.
nodeFilter := []ast.Node{
(*ast.FuncDecl)(nil),
}
inspect.Nodes(nodeFilter, func(node ast.Node, _ bool) bool {
funcDecl := node.(*ast.FuncDecl)
// Check if it's a function or a method and add accordingly.
if !isMethod(funcDecl) {
result.functions[funcDecl.Name.Name] = funcDecl
} else {
result.methods[funcDecl.Name.Name] = append(result.methods[funcDecl.Name.Name], funcDecl)
}
// Never recurse into the function bodies
return false
})
return result
}
// forEach traverses all the functions and methods in the lookup,
// and applies the given function f to every ast.FuncDecl.
func (lookup *funcLookup) forEach(f func(*ast.FuncDecl)) {
for _, funcDecl := range lookup.functions {
f(funcDecl)
}
for _, methods := range lookup.methods {
for _, funcDecl := range methods {
f(funcDecl)
}
}
}
// searchMethodType searches for method in the type information using receiver type and method name.
func (lookup *funcLookup) searchMethodType(pass *analysis.Pass, receiver types.Type, methodName string) *types.Selection {
methodSet := lookup.methodSet.MethodSet(receiver)
searchedMethodType := methodSet.Lookup(pass.Pkg, methodName)
if searchedMethodType == nil {
// No methods were found for T
// Search methods for *T if T is not already a pointer.
_, ok := receiver.(*types.Pointer)
if !ok {
methodSet = lookup.methodSet.MethodSet(types.NewPointer(receiver))
searchedMethodType = methodSet.Lookup(pass.Pkg, methodName)
}
}
return searchedMethodType
}
// searchMethod tries to find the correct function declaration for a method given the receiver type and method name.
func (lookup *funcLookup) searchMethod(pass *analysis.Pass, receiver types.Type, methodName string) *ast.FuncDecl {
methods, ok := lookup.methods[methodName]
if !ok || len(methods) == 0 {
// Return early if there is no method in the current package with the given name
return nil
}
searchedMethodType := lookup.searchMethodType(pass, receiver, methodName)
if searchedMethodType == nil {
// Return early if there is no method matching receiver and name
return nil
}
// Method we're looking for exists in the current package, we only need to find the right declaration
for _, method := range methods {
methodObj := pass.TypesInfo.ObjectOf(method.Name)
if searchedMethodType.Obj() == methodObj {
return method
}
}
return nil
} | analysis/function_lookup.go | 0.681515 | 0.44077 | function_lookup.go | starcoder |
// Package stats provides support for recording telemetry statistics.
// It acts as a coordination point between things that want to record stats,
// and things that want to aggregate and report stats.
package stats
import (
"context"
"github.com/fhs/acme-lsp/internal/golang_org_x_tools/telemetry/unit"
)
// Int64Measure is used to record integer values.
type Int64Measure struct {
name string
description string
unit unit.Unit
subscribers []Int64Subscriber
}
// Int64Measure is used to record floating point values.
type Float64Measure struct {
name string
description string
unit unit.Unit
subscribers []Float64Subscriber
}
// Int64Subscriber is the type for functions that want to listen to
// integer statistic events.
type Int64Subscriber func(context.Context, *Int64Measure, int64)
// Float64Subscriber is the type for functions that want to listen to
// floating point statistic events.
type Float64Subscriber func(context.Context, *Float64Measure, float64)
// Int64 creates a new Int64Measure and prepares it for use.
func Int64(name string, description string, unit unit.Unit) *Int64Measure {
return &Int64Measure{
name: name,
description: description,
unit: unit,
}
}
// Float64 creates a new Float64Measure and prepares it for use.
func Float64(name string, description string, unit unit.Unit) *Float64Measure {
return &Float64Measure{
name: name,
description: description,
unit: unit,
}
}
// Name returns the name this measure was given on construction.
func (m *Int64Measure) Name() string { return m.name }
// Description returns the description this measure was given on construction.
func (m *Int64Measure) Description() string { return m.description }
// Unit returns the units this measure was given on construction.
func (m *Int64Measure) Unit() unit.Unit { return m.unit }
// Subscribe adds a new subscriber to this measure.
func (m *Int64Measure) Subscribe(s Int64Subscriber) { m.subscribers = append(m.subscribers, s) }
// Record delivers a new value to the subscribers of this measure.
func (m *Int64Measure) Record(ctx context.Context, value int64) {
do(func() {
for _, s := range m.subscribers {
s(ctx, m, value)
}
})
}
// Name returns the name this measure was given on construction.
func (m *Float64Measure) Name() string { return m.name }
// Description returns the description this measure was given on construction.
func (m *Float64Measure) Description() string { return m.description }
// Unit returns the units this measure was given on construction.
func (m *Float64Measure) Unit() unit.Unit { return m.unit }
// Subscribe adds a new subscriber to this measure.
func (m *Float64Measure) Subscribe(s Float64Subscriber) { m.subscribers = append(m.subscribers, s) }
// Record delivers a new value to the subscribers of this measure.
func (m *Float64Measure) Record(ctx context.Context, value float64) {
do(func() {
for _, s := range m.subscribers {
s(ctx, m, value)
}
})
} | internal/golang_org_x_tools/telemetry/stats/stats.go | 0.827515 | 0.537406 | stats.go | starcoder |
package rxgo
import "context"
type (
operatorOptions struct {
stop func()
resetIterable func(Iterable)
}
// Comparator defines a func that returns an int:
// - 0 if two elements are equals
// - A negative value if the first argument is less than the second
// - A positive value if the first argument is greater than the second
Comparator func(interface{}, interface{}) int
// ItemToObservable defines a function that computes an observable from an item.
ItemToObservable func(Item) Observable
// ErrorToObservable defines a function that transforms an observable from an error.
ErrorToObservable func(error) Observable
// Func defines a function that computes a value from an input value.
Func func(context.Context, interface{}) (interface{}, error)
// Func2 defines a function that computes a value from two input values.
Func2 func(context.Context, interface{}, interface{}) (interface{}, error)
// FuncN defines a function that computes a value from N input values.
FuncN func(...interface{}) interface{}
// ErrorFunc defines a function that computes a value from an error.
ErrorFunc func(error) interface{}
// Predicate defines a func that returns a bool from an input value.
Predicate func(interface{}) bool
// Marshaller defines a marshaller type (interface{} to []byte).
Marshaller func(interface{}) ([]byte, error)
// Unmarshaller defines an unmarshaller type ([]byte to interface).
Unmarshaller func([]byte, interface{}) error
// Producer defines a producer implementation.
Producer func(ctx context.Context, next chan<- Item)
// Supplier defines a function that supplies a result from nothing.
Supplier func(ctx context.Context) Item
// Disposed is a notification channel indicating when an Observable is closed.
Disposed <-chan struct{}
// Disposable is a function to be called in order to dispose a subscription.
Disposable context.CancelFunc
// NextFunc handles a next item in a stream.
NextFunc func(interface{})
// ErrFunc handles an error in a stream.
ErrFunc func(error)
// CompletedFunc handles the end of a stream.
CompletedFunc func()
)
// BackpressureStrategy is the backpressure strategy type.
type BackpressureStrategy uint32
const (
// Block blocks until the channel is available.
Block BackpressureStrategy = iota
// Drop drops the message.
Drop
)
// OnErrorStrategy is the Observable error strategy.
type OnErrorStrategy uint32
const (
// StopOnError is the default error strategy.
// An operator will stop processing items on error.
StopOnError OnErrorStrategy = iota
// ContinueOnError means an operator will continue processing items after an error.
ContinueOnError
)
// ObservationStrategy defines the strategy to consume from an Observable.
type ObservationStrategy uint32
const (
// Lazy is the default observation strategy, when an Observer subscribes.
Lazy ObservationStrategy = iota
// Eager means consuming as soon as the Observable is created.
Eager
) | types.go | 0.665954 | 0.42054 | types.go | starcoder |
package flattree
import "errors"
// Range type is an inclusive tree range that is in the form of [start, finish]
type Range []uint64
// FullRoots returns a list of all the full roots (subtrees where all nodes have either 2 or 0 children) `<` index.
// For example `fullRoots(8)` returns `[3]` since the subtree rooted at `3` spans `0 -> 6` and the tree
// rooted at `7` has a child located at `9` which is `>= 8`.
func FullRoots(index uint64, result []uint64) ([]uint64, error) {
if (index & 1) == 1 {
return nil, errors.New("You can only look up roots for depth(0) blocks")
}
index /= 2
var offset uint64
var factor uint64 = 1
for true {
if index == 0 {
return result, nil
}
for (factor * 2) <= index {
factor *= 2
}
result = append(result, offset+factor-1)
offset = offset + 2*factor
index -= factor
factor = 1
}
return nil, nil
}
// Depth returns the depth of an element.
func Depth(index uint64) uint64 {
var depth uint64
index++
for (index & 1) == 0 {
depth++
index = rightShift(index)
}
return depth
}
// Sibling returns the index of this elements sibling.
func Sibling(index, depth uint64) uint64 {
if depth == 0 {
depth = Depth(index)
}
offset := Offset(index, depth)
if offset&1 == 1 {
return Index(depth, offset-1)
}
return Index(depth, offset+1)
}
// Parent returns the index of the parent element in tree.
func Parent(index, depth uint64) uint64 {
if depth == 0 {
depth = Depth(index)
}
offset := Offset(index, depth)
return Index(depth+1, rightShift(offset))
}
// LeftChild returns the left most child at index and depth.
func LeftChild(index, depth uint64) (uint64, error) {
if (index & 1) == 0 {
return 0, errors.New("No more left children")
}
if depth == 0 {
depth = Depth(index)
}
return Index(depth-1, Offset(index, depth)*2), nil
}
// RightChild returns the right most child at index and depth.
func RightChild(index, depth uint64) (uint64, error) {
if (index & 1) == 0 {
return 0, errors.New("No more right children")
}
if depth == 0 {
depth = Depth(index)
}
return Index(depth-1, 1+Offset(index, depth)*2), nil
}
// Children returns a Range slice `[leftChild, rightChild]` with indexes of this elements children.
// If this element does not have any children it returns an empty slice.
func Children(index, depth uint64) Range {
if (index & 1) == 0 {
return Range{}
}
if depth == 0 {
depth = Depth(index)
}
offset := Offset(index, depth)
return Range{Index(depth-1, offset), Index(depth-1, offset+1)}
}
// LeftSpan returns the left spanning in index in the tree `index` spans.
func LeftSpan(index, depth uint64) uint64 {
if (index & 1) == 0 {
return index
}
if depth == 0 {
depth = Depth(index)
}
return Offset(index, depth) * twoPow(depth+1)
}
// RightSpan returns the right spanning in index in the tree `index` spans.
func RightSpan(index, depth uint64) uint64 {
if (index & 1) == 0 {
return index
}
if depth == 0 {
depth = Depth(index)
}
return (Offset(index, depth)+1)*twoPow(depth+1) - 2
}
// Count returns how many nodes (including the parent nodes) a tree contains.
func Count(index, depth uint64) uint64 {
if (index & 1) == 0 {
return 1
}
if depth == 0 {
depth = Depth(index)
}
return twoPow(depth+1) - 1
}
// Spans returns the Range (inclusive) the tree root at `index` spans.
// For example `Spans(3)` would return `[]Range{0, 6}`
func Spans(index, depth uint64) Range {
if (index & 1) == 0 {
return Range{index, index}
}
if depth == 0 {
depth = Depth(index)
}
offset := Offset(index, depth)
width := twoPow(depth + 1)
return Range{offset * width, (offset+1)*width - 2}
}
// Index returns an array index for the tree element at the given depth and offset.
func Index(depth, offset uint64) uint64 {
return (1+2*offset)*twoPow(depth) - 1
}
// Offset returns the relative offset of an element.
func Offset(index, depth uint64) uint64 {
if (index & 1) == 0 {
return index / 2
}
if depth == 0 {
depth = Depth(index)
}
return ((index+1)/twoPow(depth) - 1) / 2
}
func twoPow(n uint64) uint64 {
if n < 31 {
return 1 << n
}
return ((1 << 30) * (1 << (n - 30)))
}
func rightShift(n uint64) uint64 {
return (n - (n & 1)) / 2
}
// NewIterator returns a stateful tree iterator at a given index.
func NewIterator(index uint64) *Iterator {
var ite Iterator
ite.Seek(index)
return &ite
}
// Iterator is a stateful iterator type. Use NewIterator to create tree Iterators at a given index.
type Iterator struct {
Index, Offset, Factor uint64
}
// Seek moves the iterator to this specific tree index.
func (i *Iterator) Seek(index uint64) {
i.Index = index
if i.Index&1 == 1 {
i.Offset = Offset(index, 0)
i.Factor = twoPow(Depth(index) + 1)
} else {
i.Offset = index / 2
i.Factor = 2
}
}
// IsLeft tests if the iterator at a left sibling.
func (i *Iterator) IsLeft() bool {
if i.Offset&1 == 0 {
return true
}
return false
}
// IsRight tests if the iterator is at a right subling.
func (i *Iterator) IsRight() bool {
return !i.IsLeft()
}
// Prev moves the iterator to the prev item in the tree.
func (i *Iterator) Prev() uint64 {
if i.Offset == 0 {
return i.Index
}
i.Offset--
i.Index -= i.Factor
return i.Index
}
// Next moves the iterator to the next item in the tree.
func (i *Iterator) Next() uint64 {
i.Offset++
i.Index += i.Factor
return i.Index
}
// Sibling moves the iterator to the current sibling.
func (i *Iterator) Sibling() uint64 {
if i.IsLeft() {
return i.Next()
}
return i.Prev()
}
// Parent moves the iterator to the current parent index.
func (i *Iterator) Parent() uint64 {
if (i.Offset & 1) == 1 {
i.Index -= i.Factor / 2
i.Offset = (i.Offset - 1) / 2
} else {
i.Index += i.Factor / 2
i.Offset /= 2
}
i.Factor *= 2
return i.Index
}
// LeftSpan moves the iterator to the current left span index.
func (i *Iterator) LeftSpan() uint64 {
i.Index = i.Index - i.Factor/2 + 1
i.Offset = i.Index / 2
i.Factor = 2
return i.Index
}
// RightSpan moves the iterator to the current right span index.
func (i *Iterator) RightSpan() uint64 {
i.Index = i.Index + i.Factor/2 - 1
i.Offset = i.Index / 2
i.Factor = 2
return i.Index
}
// LeftChild moves the iterator to the current left child index.
func (i *Iterator) LeftChild() uint64 {
if i.Factor == 2 {
return i.Index
}
i.Factor /= 2
i.Index -= i.Factor / 2
i.Offset *= 2
return i.Index
}
// RightChild moves the iterator to the current right child index.
func (i *Iterator) RightChild() uint64 {
if i.Factor == 2 {
return i.Index
}
i.Factor /= 2
i.Index += i.Factor / 2
i.Offset = 2*i.Offset + 1
return i.Index
} | flattree.go | 0.872266 | 0.719728 | flattree.go | starcoder |
package solver
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
)
// ParseSlice parse a slice of slice of lits and returns the equivalent problem.
// The argument is supposed to be a well-formed CNF.
func ParseSlice(cnf [][]int) *Problem {
var pb Problem
pb.parseSlice(cnf)
return &pb
}
// ParseSliceNb parse a slice of slice of lits and returns the equivalent problem.
// The argument is supposed to be a well-formed CNF.
// The number of vars is provided because clauses might be added to it later.
func ParseSliceNb(cnf [][]int, nbVars int) *Problem {
pb := Problem{NbVars: nbVars}
pb.parseSlice(cnf)
return &pb
}
func (pb *Problem) parseSlice(cnf [][]int) {
for _, line := range cnf {
switch len(line) {
case 0:
pb.Status = Unsat
return
case 1:
if line[0] == 0 {
panic("null unit clause")
}
lit := IntToLit(int32(line[0]))
v := lit.Var()
if int(v) >= pb.NbVars {
pb.NbVars = int(v) + 1
}
pb.Units = append(pb.Units, lit)
default:
lits := make([]Lit, len(line))
for j, val := range line {
if val == 0 {
panic(fmt.Sprintf("null literal in clause %v", lits))
}
lits[j] = IntToLit(int32(val))
if v := int(lits[j].Var()); v >= pb.NbVars {
pb.NbVars = v + 1
}
}
pb.Clauses = append(pb.Clauses, NewClause(lits))
}
}
pb.Model = make([]decLevel, pb.NbVars)
for _, unit := range pb.Units {
v := unit.Var()
if pb.Model[v] == 0 {
if unit.IsPositive() {
pb.Model[v] = 1
} else {
pb.Model[v] = -1
}
} else if pb.Model[v] > 0 != unit.IsPositive() {
pb.Status = Unsat
return
}
}
pb.simplify2()
}
func isSpace(b byte) bool {
return b == ' ' || b == '\t' || b == '\n' || b == '\r'
}
// readInt reads an int from r.
// 'b' is the last read byte. It can be a space, a '-' or a digit.
// The int can be negated.
// All spaces before the int value are ignored.
// Can return EOF.
func readInt(b *byte, r *bufio.Reader) (res int, err error) {
for err == nil && isSpace(*b) {
*b, err = r.ReadByte()
}
if err == io.EOF {
return res, io.EOF
}
if err != nil {
return res, fmt.Errorf("could not read digit: %v", err)
}
neg := 1
if *b == '-' {
neg = -1
*b, err = r.ReadByte()
if err != nil {
return 0, fmt.Errorf("cannot read int: %v", err)
}
}
for err == nil {
if *b < '0' || *b > '9' {
return 0, fmt.Errorf("cannot read int: %q is not a digit", *b)
}
res = 10*res + int(*b-'0')
*b, err = r.ReadByte()
if isSpace(*b) {
break
}
}
res *= neg
return res, err
}
func parseHeader(r *bufio.Reader) (nbVars, nbClauses int, err error) {
line, err := r.ReadString('\n')
if err != nil {
return 0, 0, fmt.Errorf("cannot read header: %v", err)
}
fields := strings.Fields(line)
if len(fields) < 3 {
return 0, 0, fmt.Errorf("invalid syntax %q in header", line)
}
nbVars, err = strconv.Atoi(fields[1])
if err != nil {
return 0, 0, fmt.Errorf("nbvars not an int : %q", fields[1])
}
nbClauses, err = strconv.Atoi(fields[2])
if err != nil {
return 0, 0, fmt.Errorf("nbClauses not an int : '%s'", fields[2])
}
return nbVars, nbClauses, nil
}
// ParseCNF parses a CNF file and returns the corresponding Problem.
func ParseCNF(f io.Reader) (*Problem, error) {
r := bufio.NewReader(f)
var (
nbClauses int
pb Problem
)
b, err := r.ReadByte()
for err == nil {
if b == 'c' || b == '%' { // Ignore comment
b, err = r.ReadByte()
for err == nil && b != '\n' {
b, err = r.ReadByte()
}
} else if b == 'p' { // Parse header
pb.NbVars, nbClauses, err = parseHeader(r)
if err != nil {
return nil, fmt.Errorf("cannot parse CNF header: %v", err)
}
pb.Model = make([]decLevel, pb.NbVars)
pb.Clauses = make([]*Clause, 0, nbClauses)
} else if b != ' ' && b != '0' {
lits := make([]Lit, 0, 3) // Make room for some lits to improve performance
for {
val, err := readInt(&b, r)
if err == io.EOF {
if len(lits) != 0 { // This is not a trailing space at the end...
return nil, fmt.Errorf("unfinished clause while EOF found")
}
break // When there are only several useless spaces at the end of the file, that is ok
}
if err != nil {
return nil, fmt.Errorf("cannot parse clause: %v", err)
}
if val == 0 {
pb.Clauses = append(pb.Clauses, NewClause(lits))
break
} else {
if val > pb.NbVars || -val > pb.NbVars {
return nil, fmt.Errorf("invalid literal %d for problem with %d vars only", val, pb.NbVars)
}
lits = append(lits, IntToLit(int32(val)))
}
}
}
b, err = r.ReadByte()
}
if err != io.EOF {
return nil, err
}
pb.simplify2()
return &pb, nil
} | solver/parser.go | 0.650578 | 0.478285 | parser.go | starcoder |
package geometry
import (
"github.com/schidstorm/engine/gls"
"github.com/schidstorm/engine/math32"
"math"
)
// NewTorus creates a torus geometry with the specified revolution radius, tube radius,
// number of radial segments, number of tubular segments, and arc length angle in radians.
// TODO instead of 'arc' have thetaStart and thetaLength for consistency with other generators
// TODO then rename this to NewTorusSector and add a NewTorus constructor
func NewTorus(radius, tubeRadius float64, radialSegments, tubularSegments int, arc float64) *Geometry {
t := NewGeometry()
// Create buffers
positions := math32.NewArrayF32(0, 0)
normals := math32.NewArrayF32(0, 0)
uvs := math32.NewArrayF32(0, 0)
indices := math32.NewArrayU32(0, 0)
var center math32.Vector3
for j := 0; j <= radialSegments; j++ {
for i := 0; i <= tubularSegments; i++ {
u := float64(i) / float64(tubularSegments) * arc
v := float64(j) / float64(radialSegments) * math.Pi * 2
center.X = float32(radius * math.Cos(u))
center.Y = float32(radius * math.Sin(u))
var vertex math32.Vector3
vertex.X = float32((radius + tubeRadius*math.Cos(v)) * math.Cos(u))
vertex.Y = float32((radius + tubeRadius*math.Cos(v)) * math.Sin(u))
vertex.Z = float32(tubeRadius * math.Sin(v))
positions.AppendVector3(&vertex)
uvs.Append(float32(float64(i)/float64(tubularSegments)), float32(float64(j)/float64(radialSegments)))
normals.AppendVector3(vertex.Sub(¢er).Normalize())
}
}
for j := 1; j <= radialSegments; j++ {
for i := 1; i <= tubularSegments; i++ {
a := (tubularSegments+1)*j + i - 1
b := (tubularSegments+1)*(j-1) + i - 1
c := (tubularSegments+1)*(j-1) + i
d := (tubularSegments+1)*j + i
indices.Append(uint32(a), uint32(b), uint32(d), uint32(b), uint32(c), uint32(d))
}
}
t.SetIndices(indices)
t.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition))
t.AddVBO(gls.NewVBO(normals).AddAttrib(gls.VertexNormal))
t.AddVBO(gls.NewVBO(uvs).AddAttrib(gls.VertexTexcoord))
return t
} | geometry/torus.go | 0.51562 | 0.492981 | torus.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// WorkbookChartLegend
type WorkbookChartLegend struct {
Entity
// Represents the formatting of a chart legend, which includes fill and font formatting. Read-only.
format WorkbookChartLegendFormatable
// Boolean value for whether the chart legend should overlap with the main body of the chart.
overlay *bool
// Represents the position of the legend on the chart. The possible values are: Top, Bottom, Left, Right, Corner, Custom.
position *string
// A boolean value the represents the visibility of a ChartLegend object.
visible *bool
}
// NewWorkbookChartLegend instantiates a new workbookChartLegend and sets the default values.
func NewWorkbookChartLegend()(*WorkbookChartLegend) {
m := &WorkbookChartLegend{
Entity: *NewEntity(),
}
return m
}
// CreateWorkbookChartLegendFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateWorkbookChartLegendFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewWorkbookChartLegend(), nil
}
// GetFieldDeserializers the deserialization information for the current model
func (m *WorkbookChartLegend) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["format"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateWorkbookChartLegendFormatFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetFormat(val.(WorkbookChartLegendFormatable))
}
return nil
}
res["overlay"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetOverlay(val)
}
return nil
}
res["position"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetPosition(val)
}
return nil
}
res["visible"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetVisible(val)
}
return nil
}
return res
}
// GetFormat gets the format property value. Represents the formatting of a chart legend, which includes fill and font formatting. Read-only.
func (m *WorkbookChartLegend) GetFormat()(WorkbookChartLegendFormatable) {
if m == nil {
return nil
} else {
return m.format
}
}
// GetOverlay gets the overlay property value. Boolean value for whether the chart legend should overlap with the main body of the chart.
func (m *WorkbookChartLegend) GetOverlay()(*bool) {
if m == nil {
return nil
} else {
return m.overlay
}
}
// GetPosition gets the position property value. Represents the position of the legend on the chart. The possible values are: Top, Bottom, Left, Right, Corner, Custom.
func (m *WorkbookChartLegend) GetPosition()(*string) {
if m == nil {
return nil
} else {
return m.position
}
}
// GetVisible gets the visible property value. A boolean value the represents the visibility of a ChartLegend object.
func (m *WorkbookChartLegend) GetVisible()(*bool) {
if m == nil {
return nil
} else {
return m.visible
}
}
// Serialize serializes information the current object
func (m *WorkbookChartLegend) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteObjectValue("format", m.GetFormat())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("overlay", m.GetOverlay())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("position", m.GetPosition())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("visible", m.GetVisible())
if err != nil {
return err
}
}
return nil
}
// SetFormat sets the format property value. Represents the formatting of a chart legend, which includes fill and font formatting. Read-only.
func (m *WorkbookChartLegend) SetFormat(value WorkbookChartLegendFormatable)() {
if m != nil {
m.format = value
}
}
// SetOverlay sets the overlay property value. Boolean value for whether the chart legend should overlap with the main body of the chart.
func (m *WorkbookChartLegend) SetOverlay(value *bool)() {
if m != nil {
m.overlay = value
}
}
// SetPosition sets the position property value. Represents the position of the legend on the chart. The possible values are: Top, Bottom, Left, Right, Corner, Custom.
func (m *WorkbookChartLegend) SetPosition(value *string)() {
if m != nil {
m.position = value
}
}
// SetVisible sets the visible property value. A boolean value the represents the visibility of a ChartLegend object.
func (m *WorkbookChartLegend) SetVisible(value *bool)() {
if m != nil {
m.visible = value
}
} | models/workbook_chart_legend.go | 0.752468 | 0.473292 | workbook_chart_legend.go | starcoder |
// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file implements data elements.
package golisp
import (
"errors"
"fmt"
"strings"
"unsafe"
)
const (
ConsCellType = iota
AlistType
AlistCellType
IntegerType
FloatType
BooleanType
StringType
SymbolType
FunctionType
MacroType
PrimitiveType
ObjectType
)
type Data struct {
Type int // data type
Car *Data // ConsCellType & AlistType
Cdr *Data // ConsCellType & AlistType
String string // StringType & SymbolType
Integer int64 // IntegerType & BooleanType
Float float32
Func *Function // FunctionType
Mac *Macro // MacroType
Prim *PrimitiveFunction // PrimitiveType
ObjType string // ObjectType
Obj unsafe.Pointer // ObjectType
}
// Boolean constants
var True *Data = BooleanWithValue(true)
var False *Data = BooleanWithValue(false)
func TypeOf(d *Data) int {
return d.Type
}
func TypeName(t int) string {
switch t {
case ConsCellType:
return "List"
case AlistType:
return "Association List"
case AlistCellType:
return "Association List Cell"
case IntegerType:
return "Integer"
case FloatType:
return "Float"
case BooleanType:
return "Boolean"
case StringType:
return "String"
case SymbolType:
return "Symbol"
case FunctionType:
return "Function"
case MacroType:
return "Macro"
case PrimitiveType:
return "Primitive"
case ObjectType:
return "Go Object"
default:
return "Unknown"
}
}
func NilP(d *Data) bool {
if d == nil {
return true
}
if (PairP(d) || AlistP(d) || DottedPairP(d)) && Car(d) == nil && Cdr(d) == nil {
return true
}
return false
}
func NotNilP(d *Data) bool {
return !NilP(d)
}
func PairP(d *Data) bool {
return d == nil || TypeOf(d) == ConsCellType
}
func ListP(d *Data) bool {
return PairP(d) || AlistP(d)
}
func DottedPairP(d *Data) bool {
return d == nil || TypeOf(d) == AlistCellType
}
func AlistP(d *Data) bool {
return d == nil || TypeOf(d) == AlistType
}
func BooleanP(d *Data) bool {
return d != nil && TypeOf(d) == BooleanType
}
func SymbolP(d *Data) bool {
return d != nil && TypeOf(d) == SymbolType
}
func StringP(d *Data) bool {
return d != nil && TypeOf(d) == StringType
}
func IntegerP(d *Data) bool {
return d != nil && TypeOf(d) == IntegerType
}
func FloatP(d *Data) bool {
return d != nil && TypeOf(d) == FloatType
}
func NumberP(d *Data) bool {
return IntegerP(d) || FloatP(d)
}
func ObjectP(d *Data) bool {
return d != nil && TypeOf(d) == ObjectType
}
func FunctionP(d *Data) bool {
return d != nil && TypeOf(d) == FunctionType || TypeOf(d) == PrimitiveType
}
func MacroP(d *Data) bool {
return d != nil && TypeOf(d) == MacroType
}
func Cons(car *Data, cdr *Data) *Data {
return &Data{Type: ConsCellType, Car: car, Cdr: cdr, String: "", Integer: 0, Func: nil, Prim: nil}
}
func AppendBang(l *Data, value *Data) *Data {
if NilP(l) {
return Cons(value, nil)
}
var c *Data
for c = l; NotNilP(c.Cdr); c = Cdr(c) {
}
c.Cdr = Cons(value, nil)
return l
}
func AppendBangList(l *Data, otherList *Data) *Data {
if NilP(l) {
return otherList
}
var c *Data
for c = l; NotNilP(c.Cdr); c = Cdr(c) {
}
c.Cdr = otherList
return l
}
func Append(l *Data, value *Data) *Data {
if NilP(l) {
return Cons(value, nil)
}
var newList = Copy(l)
var c *Data
for c = newList; NotNilP(c.Cdr); c = Cdr(c) {
}
c.Cdr = Cons(value, nil)
return newList
}
func AppendList(l *Data, otherList *Data) *Data {
if NilP(l) {
return otherList
}
var newList = Copy(l)
var c *Data
for c = newList; NotNilP(c.Cdr); c = Cdr(c) {
}
c.Cdr = otherList
return newList
}
func Acons(car *Data, cdr *Data, alist *Data) *Data {
pair, _ := Assoc(car, alist)
if NilP(pair) {
cell := &Data{Type: AlistCellType, Car: car, Cdr: cdr, String: "", Integer: 0, Func: nil, Prim: nil}
return &Data{Type: AlistType, Car: cell, Cdr: alist, String: "", Integer: 0, Func: nil, Prim: nil}
} else {
pair.Cdr = cdr
return alist
}
}
func Alist(d *Data) *Data {
if NilP(d) {
return nil
}
if PairP(d) {
headPair := Car(d)
return Acons(Car(headPair), Cdr(headPair), Alist(Cdr(d)))
}
return d
}
func InternalMakeList(c ...*Data) *Data {
return ArrayToList(c)
}
func EmptyCons() *Data {
return Cons(nil, nil)
}
func IntegerWithValue(n int64) *Data {
return &Data{Type: IntegerType, Integer: n}
}
func FloatWithValue(n float32) *Data {
return &Data{Type: FloatType, Float: n}
}
func BooleanWithValue(b bool) *Data {
var num int = 0
if b {
num = 1
}
return &Data{Type: BooleanType, Integer: int64(num)}
}
func StringWithValue(s string) *Data {
return &Data{Type: StringType, String: s}
}
func SymbolWithName(s string) *Data {
return &Data{Type: SymbolType, String: s}
}
func FunctionWithNameParamsBodyAndParent(name string, params *Data, body *Data, parentEnv *SymbolTableFrame) *Data {
return &Data{Type: FunctionType, Func: MakeFunction(name, params, body, parentEnv)}
}
func MacroWithNameParamsBodyAndParent(name string, params *Data, body *Data, parentEnv *SymbolTableFrame) *Data {
return &Data{Type: MacroType, Mac: MakeMacro(name, params, body, parentEnv)}
}
func PrimitiveWithNameAndFunc(name string, f *PrimitiveFunction) *Data {
return &Data{Type: PrimitiveType, Prim: f}
}
func ObjectWithTypeAndValue(typeName string, o unsafe.Pointer) *Data {
return &Data{Type: ObjectType, ObjType: typeName, Obj: o}
}
func IntegerValue(d *Data) int64 {
if d == nil {
return 0
}
if IntegerP(d) {
return d.Integer
}
if FloatP(d) {
return int64(d.Float)
}
return 0
}
func FloatValue(d *Data) float32 {
if d == nil {
return 0
}
if FloatP(d) {
return d.Float
}
if IntegerP(d) {
return float32(d.Integer)
}
return 0
}
func StringValue(d *Data) string {
if d == nil {
return ""
}
if StringP(d) || SymbolP(d) {
return d.String
}
return ""
}
func BooleanValue(d *Data) bool {
if d == nil {
return false
}
if BooleanP(d) {
return d.Integer != 0
}
return true
}
func TypeOfObject(d *Data) (oType string) {
if d == nil {
return
}
if ObjectP(d) {
return d.ObjType
}
return
}
func ObjectValue(d *Data) (p unsafe.Pointer) {
if d == nil {
return
}
if ObjectP(d) {
return d.Obj
}
return
}
func Length(d *Data) int {
if d == nil {
return 0
}
if ListP(d) || AlistP(d) {
return 1 + Length(d.Cdr)
}
return 0
}
func Reverse(d *Data) (result *Data) {
if d == nil {
return nil
}
if !ListP(d) {
return d
}
var l *Data = nil
for c := d; NotNilP(c); c = Cdr(c) {
l = Cons(Car(c), l)
}
return l
}
func Flatten(d *Data) (result *Data, err error) {
if d == nil {
return nil, nil
}
if !ListP(d) {
return d, nil
}
var l []*Data = make([]*Data, 0, 10)
for c := d; NotNilP(c); c = Cdr(c) {
if ListP(Car(c)) {
for i := Car(c); NotNilP(i); i = Cdr(i) {
l = append(l, Car(i))
}
} else {
l = append(l, Car(c))
}
}
return ArrayToList(l), nil
}
func RecursiveFlatten(d *Data) (result *Data, err error) {
if d == nil {
return nil, nil
}
if !ListP(d) {
return d, nil
}
var l []*Data = make([]*Data, 0, 10)
var elem *Data
for c := d; NotNilP(c); c = Cdr(c) {
if ListP(Car(c)) {
elem, err = RecursiveFlatten(Car(c))
if err != nil {
return
}
for i := elem; NotNilP(i); i = Cdr(i) {
l = append(l, Car(i))
}
} else {
l = append(l, Car(c))
}
}
return ArrayToList(l), nil
}
func QuoteIt(value *Data) (result *Data) {
return InternalMakeList(SymbolWithName("quote"), value)
}
func QuoteAll(d *Data) (result *Data) {
var l []*Data = make([]*Data, 0, 10)
for c := d; NotNilP(c); c = Cdr(c) {
l = append(l, QuoteIt(Car(c)))
}
return ArrayToList(l)
}
func Assoc(key *Data, alist *Data) (result *Data, err error) {
for c := alist; NotNilP(c); c = Cdr(c) {
pair := Car(c)
if !DottedPairP(pair) && !PairP(pair) {
err = errors.New("An alist MUST be made of pairs.")
return
}
if IsEqual(Car(pair), key) {
result = pair
return
}
}
return
}
func Dissoc(key *Data, alist *Data) (result *Data, err error) {
var newList *Data = nil
for c := alist; NotNilP(c); c = Cdr(c) {
pair := Car(c)
if !DottedPairP(pair) && !PairP(pair) {
err = errors.New("An alist MUST be made of pairs.")
return
}
if !IsEqual(Car(pair), key) {
newList = Acons(Car(pair), Cdr(pair), newList)
}
}
return newList, nil
}
func Copy(d *Data) *Data {
if d == nil {
return d
}
switch d.Type {
case AlistType:
{
alist := Acons(Copy(Caar(d)), Copy(Cdar(d)), nil)
for c := Cdr(d); NotNilP(c); c = Cdr(c) {
alist = Acons(Copy(Caar(c)), Copy(Cdar(c)), alist)
}
return alist
}
case ConsCellType:
{
if NilP(d) {
return d
}
return Cons(Copy(Car(d)), Copy(Cdr(d)))
}
}
return d
}
func IsEqual(d *Data, o *Data) bool {
if d == o {
return true
}
if d == nil || o == nil {
return false
}
if AlistP(d) {
if !AlistP(o) && !ListP(o) {
return false
}
} else if DottedPairP(d) {
if !PairP(o) && !DottedPairP(o) {
return false
}
} else if TypeOf(o) != TypeOf(d) {
return false
}
if AlistP(d) {
if Length(d) != Length(o) {
return false
}
for c := d; NotNilP(c); c = Cdr(c) {
otherPair, err := Assoc(Caar(c), o)
if err != nil || NilP(otherPair) || !IsEqual(Cdar(c), Cdr(otherPair)) {
return false
}
}
return true
}
if DottedPairP(d) {
return IsEqual(Car(d), Car(o)) && IsEqual(Cdr(d), Cdr(o))
}
if ListP(d) {
if Length(d) != Length(o) {
return false
}
for a1, a2 := d, o; NotNilP(a1); a1, a2 = Cdr(a1), Cdr(a2) {
if !IsEqual(Car(a1), Car(a2)) {
return false
}
}
return true
}
return *d == *o
}
func escapeQuotes(str string) string {
buffer := make([]rune, 0, 10)
for _, ch := range str {
if rune(ch) == '"' {
buffer = append(buffer, '\\')
}
buffer = append(buffer, rune(ch))
}
return string(buffer)
}
func String(d *Data) string {
if d == nil {
return "()"
}
switch d.Type {
case ConsCellType:
{
if NilP(Car(d)) && NilP(Cdr(d)) {
return "()"
}
var c *Data = d
contents := make([]string, 0, Length(d))
for NotNilP(c) && PairP(c) {
contents = append(contents, String(Car(c)))
c = Cdr(c)
}
if c == nil {
if SymbolP(Car(d)) && StringValue(Car(d)) == "quote" {
if len(contents) == 1 {
return fmt.Sprintf("'()")
} else {
return fmt.Sprintf("'%s", contents[1])
}
} else {
return fmt.Sprintf("(%s)", strings.Join(contents, " "))
}
} else {
return fmt.Sprintf("(%s . %s)", strings.Join(contents, " "), String(c))
}
}
case AlistType:
{
if NilP(Car(d)) && NilP(Cdr(d)) {
return "()"
}
contents := make([]string, 0, Length(d))
for c := d; NotNilP(c); c = Cdr(c) {
contents = append(contents, String(Car(c)))
}
return fmt.Sprintf("(%s)", strings.Join(contents, " "))
}
case AlistCellType:
return fmt.Sprintf("(%s . %s)", String(Car(d)), String(Cdr(d)))
case IntegerType:
return fmt.Sprintf("%d", d.Integer)
case FloatType:
{
raw := fmt.Sprintf("%g", d.Float)
if strings.ContainsRune(raw, '.') {
return raw
}
return fmt.Sprintf("%s.0", raw)
}
case BooleanType:
if d.Integer == 0 {
return "#f"
} else {
return "#t"
}
case StringType:
return fmt.Sprintf(`"%s"`, escapeQuotes(d.String))
case SymbolType:
return d.String
case FunctionType:
return fmt.Sprintf("<function: %s>", d.Func.Name)
case MacroType:
return fmt.Sprintf("<macro: %s>", d.Mac.Name)
case PrimitiveType:
return d.Prim.String()
case ObjectType:
if d.ObjType == "[]byte" {
bytes := (*[]byte)(d.Obj)
contents := make([]string, 0, len(*bytes))
for _, b := range *bytes {
contents = append(contents, fmt.Sprintf("%d", b))
}
return fmt.Sprintf("[%s]", strings.Join(contents, " "))
} else {
return fmt.Sprintf("<opaque Go object of type %s : 0x%x>", d.ObjType, (*uint64)(d.Obj))
}
}
return ""
}
func PrintString(d *Data) string {
if StringP(d) {
return d.String
} else {
return String(d)
}
}
func Eval(d *Data, env *SymbolTableFrame) (result *Data, err error) {
if d == nil {
return
}
switch d.Type {
case ConsCellType:
{
var function *Data
function, err = Eval(Car(d), env)
if err != nil {
return
}
if function == nil {
err = errors.New(fmt.Sprintf("Nil when function or macro expected for %s.", String(Car(d))))
return
}
args := Cdr(d)
result, err = Apply(function, args, env)
if err != nil {
err = errors.New(fmt.Sprintf("\nEvaling %s. %s", String(d), err))
return
}
return
}
case SymbolType:
result = env.ValueOf(d)
return
}
return d, nil
}
func Apply(function *Data, args *Data, env *SymbolTableFrame) (result *Data, err error) {
if function == nil {
err = errors.New("Nil when function expected.")
return
}
switch function.Type {
case FunctionType:
return function.Func.Apply(args, env)
case MacroType:
return function.Mac.Apply(args, env)
case PrimitiveType:
return function.Prim.Apply(args, env)
}
return
}
func ApplyWithoutEval(function *Data, args *Data, env *SymbolTableFrame) (result *Data, err error) {
if function == nil {
err = errors.New("Nil when function or macro expected.")
return
}
switch function.Type {
case FunctionType:
return function.Func.ApplyWithoutEval(args, env)
case MacroType:
return function.Mac.ApplyWithoutEval(args, env)
case PrimitiveType:
return function.Prim.ApplyWithoutEval(args, env)
}
return
} | data.go | 0.763484 | 0.524029 | data.go | starcoder |
package drawing
// Liner receive segment definition
type Liner interface {
// LineTo Draw a line from the current position to the point (x, y)
LineTo(x, y float64)
}
// Flattener receive segment definition
type Flattener interface {
// MoveTo Start a New line from the point (x, y)
MoveTo(x, y float64)
// LineTo Draw a line from the current position to the point (x, y)
LineTo(x, y float64)
// LineJoin add the most recent starting point to close the path to create a polygon
LineJoin()
// Close add the most recent starting point to close the path to create a polygon
Close()
// End mark the current line as finished so we can draw caps
End()
}
// Flatten convert curves into straight segments keeping join segments info
func Flatten(path *Path, flattener Flattener, scale float64) {
// First Point
var startX, startY float64
// Current Point
var x, y float64
var i int
for _, cmp := range path.Components {
switch cmp {
case MoveToComponent:
x, y = path.Points[i], path.Points[i+1]
startX, startY = x, y
if i != 0 {
flattener.End()
}
flattener.MoveTo(x, y)
i += 2
case LineToComponent:
x, y = path.Points[i], path.Points[i+1]
flattener.LineTo(x, y)
flattener.LineJoin()
i += 2
case QuadCurveToComponent:
// we include the previous point for the start of the curve
TraceQuad(flattener, path.Points[i-2:], 0.5)
x, y = path.Points[i+2], path.Points[i+3]
flattener.LineTo(x, y)
i += 4
case CubicCurveToComponent:
TraceCubic(flattener, path.Points[i-2:], 0.5)
x, y = path.Points[i+4], path.Points[i+5]
flattener.LineTo(x, y)
i += 6
case ArcToComponent:
x, y = TraceArc(flattener, path.Points[i], path.Points[i+1], path.Points[i+2], path.Points[i+3], path.Points[i+4], path.Points[i+5], scale)
flattener.LineTo(x, y)
i += 6
case CloseComponent:
flattener.LineTo(startX, startY)
flattener.Close()
}
}
flattener.End()
}
// SegmentedPath is a path of disparate point sectinos.
type SegmentedPath struct {
Points []float64
}
// MoveTo implements the path interface.
func (p *SegmentedPath) MoveTo(x, y float64) {
p.Points = append(p.Points, x, y)
// TODO need to mark this point as moveto
}
// LineTo implements the path interface.
func (p *SegmentedPath) LineTo(x, y float64) {
p.Points = append(p.Points, x, y)
}
// LineJoin implements the path interface.
func (p *SegmentedPath) LineJoin() {
// TODO need to mark the current point as linejoin
}
// Close implements the path interface.
func (p *SegmentedPath) Close() {
// TODO Close
}
// End implements the path interface.
func (p *SegmentedPath) End() {
// Nothing to do
} | vendor/github.com/wcharczuk/go-chart/v2/drawing/flattener.go | 0.633864 | 0.609059 | flattener.go | starcoder |
package nets
import (
"fmt"
"math"
"math/rand"
"time"
"github.com/qvantel/nerd/api/types"
"github.com/qvantel/nerd/internal/config"
"github.com/qvantel/nerd/internal/logger"
"github.com/qvantel/nerd/internal/series/pointstores"
)
// Chromosome represents a neural network configuration
type Chromosome struct {
ActivationFunc string
Fitness float32 // Aptitude for infering outputs for the given inputs
HLayers int // Number of hidden layers
LearningRate float32
Type string
Net Network
}
// Check trains a network with the chromosome's config and updates its fitness based on the accuracy
func (c *Chromosome) Check(tr types.TrainRequest, outputs []string, points []pointstores.Point, params config.MLParams) error {
if c.Net != nil {
return nil
}
id := tr.SeriesID + "-" + hash(tr.Inputs) + "-" + hash(outputs) + "-" + c.Type
var err error
c.Net, err = NewNetwork(id, tr.Inputs, outputs, *c)
if err != nil {
return err
}
c.Fitness, err = c.Net.Train(points, params.MaxEpoch, tr.ErrMargin, params.TestSet, params.Tolerance)
if err != nil {
return err
}
return nil
}
// Crossover exchanges n+1 parameters between the chromosomes to create two new configurations
func (c Chromosome) Crossover(b Chromosome, n int) []Chromosome {
// Clear the net pointers from the copies of c and b
c.Net, b.Net = nil, nil
c.LearningRate, b.LearningRate = b.LearningRate, c.LearningRate
if n >= 1 {
c.HLayers, b.HLayers = b.HLayers, c.HLayers
}
if n >= 2 {
c.ActivationFunc, b.ActivationFunc = b.ActivationFunc, c.ActivationFunc
}
return []Chromosome{c, b}
}
// decimals returns the number of decimal places of a given float
func decimals(number float32) int {
count := 0
for i := float32(10); number < 1; i *= 10 {
number *= i
count++
}
return count
}
// Mutate randomly alters the given gene
func (c *Chromosome) Mutate(gene int) {
rand.Seed(time.Now().UnixNano())
switch gene {
case 0:
c.ActivationFunc = randomString(types.ActivationFuncs())
case 1:
if c.HLayers == 1 {
c.HLayers = 2
} else {
c.HLayers += rand.Intn(2)*2 - 1
}
case 2:
d := float32(math.Pow10(decimals(c.LearningRate)))
if c.LearningRate == 1/d {
c.LearningRate = 2 / d
} else {
c.LearningRate += float32(rand.Intn(2)*2-1) / d
}
default:
return
}
// Reset the net as it no longer matches the configuration
c.Net = nil
}
// Population represents a collection of individuals and their metadata
type Population struct {
first int
individuals []Chromosome
last int
params config.MLParams
second int
}
// NewPopulation creates a new set of individuals and initializes their metadata
func NewPopulation(params config.MLParams) *Population {
pop := Population{
first: -1,
last: -1,
params: params,
second: -1,
}
pop.individuals = make([]Chromosome, params.Variations)
rand.Seed(time.Now().UnixNano())
for i := 0; i < params.Variations; i++ {
pop.individuals[i] = Chromosome{
ActivationFunc: randomString(types.ActivationFuncs()),
Fitness: -1,
HLayers: rand.Intn(params.MaxHLayers+1) + params.MinHLayers,
LearningRate: float32(rand.Intn(999)+1) / 1000,
Type: randomString(types.Nets()),
}
}
return &pop
}
// Optimal uses a genetic algorithm to find the config that results in the most accurate net for the given points and
// returns that net
func (pop *Population) Optimal(tr types.TrainRequest, outputs []string, points []pointstores.Point) (Network, error) {
for gen := 0; gen < pop.params.Generations; gen++ {
rand.Seed(time.Now().UnixNano())
// Calculate fitness for each individual
err := pop.rank(tr, outputs, points)
if err != nil {
return nil, err
}
logger.Debug(fmt.Sprintf(
"Gen %d fitness: first = %f, second = %f, last = %f",
gen,
pop.individuals[pop.first].Fitness,
pop.individuals[pop.second].Fitness,
pop.individuals[pop.last].Fitness,
))
// Cross fittest individuals
cp := rand.Intn(3)
offspring := pop.individuals[pop.first].Crossover(pop.individuals[pop.second], cp)
// Mutate offspring (20% chance)
mc := rand.Intn(5)
if mc == 0 {
gene := rand.Intn(3)
offspring[0].Mutate(gene)
gene = rand.Intn(3)
offspring[1].Mutate(gene)
}
// Calculate offspring fitness
for index := range offspring {
err := offspring[index].Check(tr, outputs, points, pop.params)
if err != nil {
return nil, err
}
}
// Replace least fit individual with fittest offspring
if offspring[0].Fitness > offspring[1].Fitness {
pop.individuals[pop.last] = offspring[0]
} else {
pop.individuals[pop.last] = offspring[1]
}
}
// If the fittest offspring is better, return it instead
if pop.individuals[pop.last].Fitness > pop.individuals[pop.first].Fitness {
return pop.individuals[pop.last].Net, nil
}
return pop.individuals[pop.first].Net, nil
}
// randomString returns a randomly selected string from a slice
func randomString(options []string) string {
i := rand.Intn(len(options))
return options[i]
}
// rank traverses the population calculating the fitness of each individual and identifying the fittest, second fittest
// and least fit
func (pop *Population) rank(tr types.TrainRequest, outputs []string, points []pointstores.Point) error {
pop.first, pop.second, pop.last = -1, -1, -1
for index := range pop.individuals {
err := pop.individuals[index].Check(tr, outputs, points, pop.params)
if err != nil {
return err
}
if pop.first == -1 || pop.individuals[index].Fitness > pop.individuals[pop.first].Fitness {
if pop.last == -1 {
pop.last = pop.second
}
pop.second, pop.first = pop.first, index
} else if pop.second == -1 || pop.individuals[index].Fitness > pop.individuals[pop.second].Fitness {
if pop.last == -1 {
pop.last = pop.second
}
pop.second = index
} else if pop.last == -1 || pop.individuals[index].Fitness < pop.individuals[pop.last].Fitness {
pop.last = index
}
}
return nil
} | internal/nets/evolution.go | 0.716615 | 0.451145 | evolution.go | starcoder |
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
)
type GraphVertex interface {
fmt.Stringer
}
type SimpleVertex string
func (v SimpleVertex) String() string {
return string(v)
}
type TagVertex Tag
func (v TagVertex) String() string {
return fmt.Sprintf("tag_%d", int(v))
}
type NodeSourceVertex Node
func (v NodeSourceVertex) String() string {
return fmt.Sprintf("node_%d_source", int(v))
}
type NodeSinkVertex Node
func (v NodeSinkVertex) String() string {
return fmt.Sprintf("node_%d_sink", int(v))
}
type TagNodeVertex struct {
Tag Tag
Node Node
}
func (v TagNodeVertex) String() string {
return fmt.Sprintf("tag_%d_node_%d", int(v.Tag), int(v.Node))
}
const (
Source SimpleVertex = "source"
Sink SimpleVertex = "sink"
supplySource SimpleVertex = "supply"
demandSink SimpleVertex = "demand"
)
type edgeType int
const (
edgeNormal edgeType = iota
edgeReverse edgeType = iota
edgeDemand edgeType = iota
)
type GraphEdge struct {
Src GraphVertex
Dst GraphVertex
Demand int
ReverseEdge *GraphEdge
// actual capacity adjusted for demand
capacity int
// flow according to adjusted capacity
flow int
etype edgeType
demandEdges []*GraphEdge
}
func (edge GraphEdge) Capacity() int {
return edge.Demand + edge.capacity
}
func (edge GraphEdge) Flow() int {
if edge.demandEdges == nil {
return edge.flow
} else {
demandFlow := MaxInt
for _, demandEdge := range edge.demandEdges {
if demandEdge.flow < demandFlow {
demandFlow = demandEdge.flow
}
}
return edge.flow + demandFlow
}
}
func (edge GraphEdge) String() string {
return fmt.Sprintf("%s->%s", edge.Src, edge.Dst)
}
func (edge GraphEdge) residual() int {
return edge.capacity - edge.flow
}
func (edge GraphEdge) mustREdge() *GraphEdge {
if edge.ReverseEdge == nil {
panic(fmt.Sprintf("Edge %s does not have a reverse edge", edge))
}
return edge.ReverseEdge
}
func (edge GraphEdge) IsReverseEdge() bool {
return edge.etype == edgeReverse
}
func (edge *GraphEdge) pushFlow(flow int) {
residual := edge.residual()
if flow > residual {
panic(fmt.Sprintf("Trying to push flow %d "+
"via edge %s with residual capacity %d",
flow, edge, residual))
}
edge.flow += flow
if edge.ReverseEdge != nil {
edge.ReverseEdge.flow -= flow
}
}
func (edge GraphEdge) isSaturated() bool {
return edge.residual() == 0
}
func (edge *GraphEdge) IncreaseCapacity(capacity int) {
if capacity < edge.Capacity() {
panic("new capacity is less than the old one")
}
edge.capacity = capacity - edge.Demand
}
type augPath []*GraphEdge
func (path *augPath) addEdge(edge *GraphEdge) {
*path = append(*path, edge)
}
func (path *augPath) removeLastEdge() (edge *GraphEdge) {
n := len(*path)
if n == 0 {
panic("Removing edge from empty path")
}
edge = (*path)[n-1]
*path = (*path)[0 : n-1]
return
}
func (path augPath) capacity() (result int) {
if len(path) == 0 {
panic("capacity called on empty path")
}
result = path[0].residual()
for _, edge := range path {
residual := edge.residual()
if residual < result {
result = residual
}
}
return
}
func (path *augPath) truncate(i int) {
if i >= len(*path) {
panic("index out of range in truncate")
}
*path = (*path)[0:i]
}
type graphVertexData struct {
allEdges []*GraphEdge
firstEdge int
}
func makeGraphVertexData() *graphVertexData {
return &graphVertexData{allEdges: []*GraphEdge{}, firstEdge: 0}
}
func (v graphVertexData) edges() []*GraphEdge {
return v.allEdges[v.firstEdge:]
}
func (v *graphVertexData) addEdge(edge *GraphEdge) {
v.allEdges = append(v.allEdges, edge)
}
func (v *graphVertexData) forgetFirstEdge() {
v.firstEdge += 1
}
func (v *graphVertexData) reset() {
v.firstEdge = 0
}
func (v *graphVertexData) flow() (result int) {
for _, edge := range v.edges() {
if edge.etype == edgeNormal {
result += edge.Flow()
}
}
return
}
type graphStats struct {
numVertices int
numEdges int
}
func (stats graphStats) String() string {
return fmt.Sprintf("Graph stats:\n\tVertices: %d\n\tEdges: %d\n",
stats.numVertices, stats.numEdges)
}
func (stats *graphStats) noteVertexAdded() {
stats.numVertices += 1
}
func (stats *graphStats) noteEdgeAdded() {
stats.numEdges += 1
}
type maxflowStats struct {
iteration int
numAdvances int
numRetreats int
numAugments int
numEdges int
}
func (stats maxflowStats) String() string {
return fmt.Sprintf("\tCurrent iteration: %d\n"+
"\tNumber of advances: %d\n\tNumber of retreats: %d\n"+
"\tNumber of augments: %d\n"+
"\tTotal number of edges processed: %d\n",
stats.iteration, stats.numAdvances,
stats.numRetreats, stats.numAugments, stats.numEdges)
}
func (stats *maxflowStats) reset() {
stats.iteration = 0
stats.numAdvances = 0
stats.numRetreats = 0
stats.numAugments = 0
stats.numEdges = 0
}
func (stats *maxflowStats) nextIteration() {
iter := stats.iteration
stats.reset()
stats.iteration = iter + 1
}
func (stats *maxflowStats) noteAdvance() {
stats.numAdvances += 1
}
func (stats *maxflowStats) noteRetreat() {
stats.numRetreats += 1
}
func (stats *maxflowStats) noteAugment() {
stats.numAugments += 1
}
func (stats *maxflowStats) noteEdgeProcessed() {
stats.numEdges += 1
}
type Graph struct {
name string
vertices map[GraphVertex]*graphVertexData
distances map[GraphVertex]int
graphStats
maxflowStats
}
func NewGraph(name string) (g *Graph) {
g = &Graph{}
g.name = name
g.vertices = make(map[GraphVertex]*graphVertexData)
g.distances = make(map[GraphVertex]int)
g.addEdge(Sink, Source, MaxInt, 0, edgeDemand)
return
}
type edgePredicate func(*GraphEdge) bool
func (g *Graph) bfsGeneric(source GraphVertex, pred edgePredicate) int {
queue := []GraphVertex{source}
seen := make(map[GraphVertex]bool)
for v, _ := range g.vertices {
g.distances[v] = -1
}
seen[source] = true
g.distances[source] = 0
var d int
for len(queue) != 0 {
v := queue[0]
d = g.distances[v]
queue = queue[1:]
for _, edge := range g.vertices[v].edges() {
if !pred(edge) {
continue
}
_, present := seen[edge.Dst]
if !present {
dst := edge.Dst
queue = append(queue, dst)
seen[dst] = true
g.distances[dst] = d + 1
}
}
}
return d
}
func (g *Graph) bfsUnsaturated(source, sink GraphVertex) bool {
_ = g.bfsGeneric(source, func(edge *GraphEdge) bool {
return !edge.isSaturated()
})
return g.distances[sink] != -1
}
func (g *Graph) bfsNetwork(source GraphVertex) int {
return g.bfsGeneric(source, func(edge *GraphEdge) bool {
return edge.etype == edgeNormal
})
}
func (g *Graph) dfsPath(from, to GraphVertex, path *augPath) bool {
if from == to {
return true
}
d := g.distances[from]
fromData := g.vertices[from]
for _, edge := range fromData.edges() {
g.noteEdgeProcessed()
dst := edge.Dst
if g.distances[dst] == d+1 && !edge.isSaturated() {
g.noteAdvance()
path.addEdge(edge)
if g.dfsPath(dst, to, path) {
return true
}
path.removeLastEdge()
}
fromData.forgetFirstEdge()
}
g.noteRetreat()
return false
}
func (g *Graph) augmentFlow(source, sink GraphVertex) bool {
for _, vertexData := range g.vertices {
vertexData.reset()
}
if !g.bfsUnsaturated(source, sink) {
return false
}
path := augPath(nil)
v := source
for {
pathFound := g.dfsPath(v, sink, &path)
if pathFound {
capacity := path.capacity()
firstSaturatedEdge := -1
for i, edge := range path {
edge.pushFlow(capacity)
if firstSaturatedEdge == -1 && edge.isSaturated() {
firstSaturatedEdge = i
}
}
g.noteAugment()
if firstSaturatedEdge == -1 {
panic("No saturated edge on augmenting path")
}
v = path[firstSaturatedEdge].Src
path.truncate(firstSaturatedEdge)
} else {
if v == source {
break
} else {
g.distances[v] = -1
edge := path.removeLastEdge()
v = edge.Src
}
}
}
return true
}
func (g *Graph) addVertex(vertex GraphVertex) {
_, present := g.vertices[vertex]
if !present {
g.noteVertexAdded()
g.vertices[vertex] = makeGraphVertexData()
}
}
func (g *Graph) addEdge(src, dst GraphVertex,
capacity, demand int, etype edgeType) *GraphEdge {
g.addVertex(src)
g.addVertex(dst)
edge := &GraphEdge{Src: src, Dst: dst, Demand: demand,
capacity: capacity, etype: etype}
g.noteEdgeAdded()
g.vertices[src].addEdge(edge)
return edge
}
func (g *Graph) AddEdge(src, dst GraphVertex, capacity, demand int) {
capacity -= demand
edge := g.addEdge(src, dst, capacity, demand, edgeNormal)
redge := g.addEdge(dst, src, 0, 0, edgeReverse)
edge.ReverseEdge = redge
redge.ReverseEdge = edge
if demand != 0 {
demandEdge1 := g.addEdge(src, demandSink, demand, 0, edgeDemand)
demandEdge2 := g.addEdge(supplySource, dst, demand, 0, edgeDemand)
edge.demandEdges = []*GraphEdge{demandEdge1, demandEdge2}
}
}
func (g *Graph) edges() (result []*GraphEdge) {
for _, vertexData := range g.vertices {
for _, edge := range vertexData.edges() {
result = append(result, edge)
}
}
return
}
func (g *Graph) hasFeasibleFlow() (result bool, violation int) {
_, haveDemands := g.vertices[supplySource]
if !haveDemands {
return true, 0
}
for _, edge := range g.vertices[supplySource].edges() {
violation += edge.residual()
}
return violation == 0, violation
}
func (g *Graph) FindFeasibleFlow() (bool, int) {
if feasible, _ := g.hasFeasibleFlow(); feasible {
return true, 0
}
g.doMaximizeFlow(supplySource, demandSink, "FindFeasibleFlow stats")
return g.hasFeasibleFlow()
}
func (g *Graph) MaximizeFlow() bool {
if feasible, _ := g.FindFeasibleFlow(); !feasible {
return false
}
g.doMaximizeFlow(Source, Sink, "MaximizeFlow stats")
return true
}
func (g *Graph) doMaximizeFlow(source, sink GraphVertex, statsHeader string) {
g.maxflowStats.reset()
for {
augmented := g.augmentFlow(source, sink)
if !augmented {
break
}
diag.Printf("%s:\n%s", statsHeader, g.maxflowStats.String())
g.maxflowStats.nextIteration()
}
}
func (g *Graph) EdgesFromVertex(v GraphVertex) (edges []*GraphEdge) {
for _, edge := range g.vertices[v].edges() {
if edge.etype == edgeNormal {
edges = append(edges, edge)
}
}
return
}
func (g *Graph) EdgesToVertex(v GraphVertex) (edges []*GraphEdge) {
for _, edge := range g.vertices[v].edges() {
if edge.etype == edgeReverse {
edges = append(edges, edge.mustREdge())
}
}
return
}
func (g *Graph) Vertices() (vertices []GraphVertex) {
for v, _ := range g.vertices {
vertices = append(vertices, v)
}
return
}
func (g *Graph) Dot(path string, verbose bool) (err error) {
buffer := &bytes.Buffer{}
fmt.Fprintf(buffer, "digraph G {\n")
fmt.Fprintf(buffer, "rankdir=LR;\n")
fmt.Fprintf(buffer, "labelloc=t; labeljust=l; ")
feasible, violation := g.hasFeasibleFlow()
label := fmt.Sprintf(`%s\nflow = %d\nfeasible = %v, violation = %d`,
g.name, g.vertices[Source].flow(), feasible, violation)
fmt.Fprintf(buffer, "label=\"%s\";\n", label)
dist := g.bfsNetwork(Source)
groups := make([][]GraphVertex, dist+1)
for v, _ := range g.vertices {
d := g.distances[v]
if d != -1 {
groups[d] = append(groups[d], v)
}
}
groupVertices(buffer, groups[0], "source")
groupVertices(buffer, groups[dist], "sink")
for _, group := range groups[1:dist] {
groupVertices(buffer, group, "same")
}
for _, edge := range g.edges() {
var style string
if edge.etype != edgeNormal && !verbose {
continue
}
switch edge.etype {
case edgeNormal:
style = "solid"
case edgeReverse:
style = "dashed"
case edgeDemand:
style = "dotted"
}
color := "red"
if edge.Flow() < edge.Capacity() {
color = "darkgreen"
}
labelcolor := "black"
if edge.etype == edgeNormal && edge.Flow() < edge.Demand {
labelcolor = "red"
}
capacity := edge.Capacity()
capacityString := fmt.Sprintf("%d", capacity)
if capacity == MaxInt {
capacityString = "∞"
}
fmt.Fprintf(buffer,
"%s -> %s [label=\"%d (%d..%s)\", decorate=true,"+
" style=%s, color=%s, fontcolor=%s];\n",
edge.Src, edge.Dst, edge.Flow(),
edge.Demand, capacityString, style, color, labelcolor)
}
fmt.Fprintf(buffer, "}\n")
return ioutil.WriteFile(path, buffer.Bytes(), 0644)
}
func groupVertices(w io.Writer, vertices []GraphVertex, rank string) {
fmt.Fprintf(w, "{\n")
fmt.Fprintf(w, "rank=%s;\n", rank)
for _, v := range vertices {
fmt.Fprintf(w, "%s;\n", v)
}
fmt.Fprintf(w, "}\n")
} | deps/vbmap/graph.go | 0.663669 | 0.519338 | graph.go | starcoder |
package main
import ()
/* Objectives
- Playing with values
- Bytes
- Integers
- Strings
- Booleans
- Arrays
- Maps
- Data type and Storage
*/
/* Values
- literal - 1, true, "text"
- computed - 1 + 4
*/
/* Everything is a Number
- Everything typed into a computer is a character
- Every character is represented by a number
- A number is build up by bit by bit, quite literally
*/
/* What is a bit ?
- A bit, is like a switch, it is either on or off
- Each bit represents a binary value of 0 or 1
1 bit - 2 states - 0 or 1
2 bits - 4 states - 00, 01, 10, 11
*/
/* Bit Grouping Illustrated
MSB 0 1 2 3 4 5 6 7 LSB
value - 1208
Big Endian (left-to-right): 1-2-0-8
Little Endian (right-to-left): 8-0-2-1
*/
/* Grouping Bits
- Grouping bits to represents numbers
- 4 bits = nibble
- 8 bits = 1 byte
- 16 bits
- 32 bits
- 64 bits
- 128 bits
// 16, 32, 64, 128 - depends on programming language and sometimes on processor
*/
/* Binary Number system
- The `binary numbering system` uses bits tio represent numbers.
- Since a certain number of bits allows us to represent a dsitinct number of states, we can choose to represent
either positve or negative numbers.
- To represent a negative number, we designate the MSB as the `signed bit`
- The `sign bit` tells us if the number is positive or negative.
- Signed and Unsigned Bits:
Unsigned Bits Unsigned Value Signed Bits Signed Value
000 0 0-00 0
001 1 0-01 1
010 2 0-10 2
011 3 0-11 3
100 4 1-00 0
101 5 1-01 -3
110 6 1-10 -2
111 7 1-11 -1
*/
/* Bit Grouping and Numeric Range
# of bits # of unique values Unsigned Number Range Signed Number Range
8 2^8 = 256 0 to 255 -127 to 127
16 2^16 = 65,535 0 to 65,534 -32,767 to 32,767
32 2^32 = 4,294,967,295 0 to 4,294,967,294 -2,147,483,647
64 2^16 = 18,446,744,073 0 to 18,446,744,073,709, -9.22337203685478E18 to
709,551,615 551,614 9.22337203685478E18
*/
/* ASCII Table
https://www.rapidtables.com/code/text/ascii-table.html
*/ | series_4/go_004_values_bits_numbers.go | 0.628521 | 0.427337 | go_004_values_bits_numbers.go | starcoder |
package iter
import "math"
// FloatRange represets a range of float64
type FloatRange struct {
Start, End, Step float64
}
// FloatIterator iterates over a FloatRange
type FloatIterator struct {
*IdxIterator
FloatRange
}
// Iter creates a new FloatIterator from a FloatRange
func (r FloatRange) Iter() (*FloatIterator, float64) {
i := &FloatIterator{
&IdxIterator{IdxRange(math.Ceil((r.End - r.Start) / r.Step)), 0},
r,
}
return i, r.Start
}
// Reset to the start of the range
func (i *FloatIterator) Reset() float64 {
i.Idx = 0
return i.Start
}
// Next value from the iterator
func (i *FloatIterator) Next() float64 {
return i.At(float64(i.IdxIterator.Next()))
}
// At returns the value at the given step.
func (i *FloatIterator) At(step float64) float64 {
return i.Start + i.Step*float64(step)
}
// Include creates a float range that is guarenteed to include the end value.
func Include(end, step float64) FloatRange {
d := end / step
if d-math.Floor(d) < 1e-10 {
end += step * 1e-10
}
return FloatRange{
Start: 0,
End: end,
Step: step,
}
}
// Each calls the function passed in for each value in the range.
func (i *FloatIterator) Each(fn func(float64)) {
for f := i.Reset(); !i.Done(); f = i.Next() {
fn(f)
}
}
// Each calls the function passed in for each value in the range.
func (r FloatRange) Each(fn func(float64)) {
i, _ := r.Iter()
i.Each(fn)
}
// Ch returns a chan that will iterate over the floats in the range.
func (i *FloatIterator) Ch() <-chan float64 {
ln := int(i.IdxRange)
if ln > BufferLen {
ln = BufferLen
}
ch := make(chan float64, ln)
go func() {
for f := i.Reset(); !i.Done(); f = i.Next() {
ch <- f
}
close(ch)
}()
return ch
}
// Ch returns a chan that will iterate over the floats in the range.
func (r FloatRange) Ch() <-chan float64 {
i, _ := r.Iter()
return i.Ch()
}
// FloatChan returns a chan that will iterate over the floats in the range.
func FloatChan(start, end, step float64) <-chan float64 {
return FloatRange{
Start: start,
End: end,
Step: step,
}.Ch()
} | iter/float.go | 0.843927 | 0.574693 | float.go | starcoder |
package autobatch
import (
ds "github.com/ipfs/go-datastore"
dsq "github.com/ipfs/go-datastore/query"
)
// Datastore implements a go-datatsore.
type Datastore struct {
child ds.Batching
// TODO: discuss making ds.Batch implement the full ds.Datastore interface
buffer map[ds.Key][]byte
maxBufferEntries int
}
// NewAutoBatching returns a new datastore that automatically
// batches writes using the given Batching datastore. The size
// of the memory pool is given by size.
func NewAutoBatching(d ds.Batching, size int) *Datastore {
return &Datastore{
child: d,
buffer: make(map[ds.Key][]byte),
maxBufferEntries: size,
}
}
// Delete deletes a key/value
func (d *Datastore) Delete(k ds.Key) error {
_, found := d.buffer[k]
delete(d.buffer, k)
err := d.child.Delete(k)
if found && err == ds.ErrNotFound {
return nil
}
return err
}
// Get retrieves a value given a key.
func (d *Datastore) Get(k ds.Key) ([]byte, error) {
val, ok := d.buffer[k]
if ok {
return val, nil
}
return d.child.Get(k)
}
// Put stores a key/value.
func (d *Datastore) Put(k ds.Key, val []byte) error {
d.buffer[k] = val
if len(d.buffer) > d.maxBufferEntries {
return d.Flush()
}
return nil
}
// Flush flushes the current batch to the underlying datastore.
func (d *Datastore) Flush() error {
b, err := d.child.Batch()
if err != nil {
return err
}
for k, v := range d.buffer {
err := b.Put(k, v)
if err != nil {
return err
}
}
// clear out buffer
d.buffer = make(map[ds.Key][]byte)
return b.Commit()
}
// Has checks if a key is stored.
func (d *Datastore) Has(k ds.Key) (bool, error) {
_, ok := d.buffer[k]
if ok {
return true, nil
}
return d.child.Has(k)
}
// GetSize implements Datastore.GetSize
func (d *Datastore) GetSize(k ds.Key) (int, error) {
v, ok := d.buffer[k]
if ok {
return len(v), nil
}
return d.child.GetSize(k)
}
// Query performs a query
func (d *Datastore) Query(q dsq.Query) (dsq.Results, error) {
err := d.Flush()
if err != nil {
return nil, err
}
return d.child.Query(q)
}
// DiskUsage implements the PersistentDatastore interface.
func (d *Datastore) DiskUsage() (uint64, error) {
return ds.DiskUsage(d.child)
}
func (d *Datastore) Close() error {
return d.child.Close()
} | autobatch/autobatch.go | 0.572962 | 0.470797 | autobatch.go | starcoder |
package cqlnls
// Node is an element block that contains the data and has pointers to other
// Nodes that it's connected
type Node struct {
Value interface{}
Next, Previous *Node
}
// CircularLinkedList provides the interface for Nodes to connect
// add and remove nodes from the structure
type CircularLinkedList struct {
head, tail, current *Node
len int
}
func (c *CircularLinkedList) addInit(n *Node) {
c.head = n
c.tail = n
c.current = n
}
// Prepend is used to add a Node before the head of the list
func (c *CircularLinkedList) Prepend(n *Node) *Node {
if c.len == 0 {
c.addInit(n)
} else {
c.head.Previous = n
c.tail.Next = n
n.Next = c.head
n.Previous = c.tail
c.head = n
c.current = n
}
c.len++
return c.current
}
// Append is used to add a Node after the tail of the list
func (c *CircularLinkedList) Append(n *Node) *Node {
if c.len == 0 {
c.addInit(n)
} else {
c.head.Previous = n
c.tail.Next = n
n.Next = c.head
n.Previous = c.tail
c.tail = n
c.current = n
}
c.len++
return c.current
}
// Length returns the size of the list (How many Nodes are in the list)
func (c *CircularLinkedList) Length() int {
return c.len
}
// Current returns the Node that is active in the list
func (c *CircularLinkedList) Current() *Node {
if c.current != nil {
return c.current
}
return c.head
}
// Next returns the following Node of the current one
func (c *CircularLinkedList) Next() *Node {
if c.current != nil {
c.current = c.current.Next
return c.current
}
return nil
}
// Previous returns the Node before the current one
func (c *CircularLinkedList) Previous() *Node {
if c.current != nil {
c.current = c.current.Previous
return c.current
}
return nil
}
// AddBefore adds a new Node before the current one
func (c *CircularLinkedList) AddBefore(n *Node) *Node {
switch {
case c.len == 0:
c.addInit(n)
case c.current == c.head:
return c.Prepend(n)
default:
c.current.Previous.Next = n
c.current.Previous = n
n.Previous = c.current.Previous
n.Next = c.current
c.current = n
}
c.len++
return c.current
}
// AddAfter adds a new Node after the current one
func (c *CircularLinkedList) AddAfter(n *Node) *Node {
switch {
case c.len == 0:
c.addInit(n)
case c.current == c.tail:
return c.Append(n)
default:
c.current.Next.Previous = n
c.current.Next = n
n.Previous = c.current
n.Next = c.current.Next
c.current = n
}
c.len++
return c.current
}
// Remove is disconnecting the current node from the list
func (c *CircularLinkedList) Remove() *Node {
if c.len == 0 {
return nil
}
c.current.Previous.Next = c.current.Next
c.current.Next.Previous = c.current.Previous
c.current = c.current.Next
c.len--
return c.current
} | cqlnls.go | 0.734786 | 0.408749 | cqlnls.go | starcoder |
package common
import (
"encoding/json"
"regexp"
"strings"
)
// Statistics provide a type and method receivers for marshalling and
// un-marshalling statistics, as JSON, for components across the network.
type Statistics map[string]interface{}
// NewStatistics return a new instance of stat structure initialized with
// data.
func NewStatistics(data interface{}) (stat Statistics, err error) {
var statm Statistics
switch v := data.(type) {
case string:
statm = make(Statistics)
err = json.Unmarshal([]byte(v), &statm)
case []byte:
statm = make(Statistics)
err = json.Unmarshal(v, &statm)
case map[string]interface{}:
statm = Statistics(v)
case nil:
statm = make(Statistics)
}
return statm, err
}
// Name is part of MessageMarshaller interface.
func (s Statistics) Name() string {
return "stats"
}
// Encode is part of MessageMarshaller interface.
func (s Statistics) Encode() (data []byte, err error) {
data, err = json.Marshal(s)
return
}
// Decode is part of MessageMarshaller interface.
func (s Statistics) Decode(data []byte) (err error) {
return json.Unmarshal(data, &s)
}
// ContentType is part of MessageMarshaller interface.
func (s Statistics) ContentType() string {
return "application/json"
}
// Statistic operations.
// Incr increments stat value(s) by `vals`.
func (s Statistics) Incr(path string, vals ...int) {
l := len(vals)
if l == 0 {
Warnf("Incr called without value")
return
}
switch vs := s[path].(type) {
case float64:
s[path] = vs + float64(vals[0])
case []interface{}:
if l != len(vs) {
Warnf("Incr expected %v values, got %v", len(vs), l)
return
}
for i, v := range vs {
vs[i] = v.(float64) + float64(vals[i])
}
case []float64:
if l != len(vs) {
Warnf("Incr expected %v values, got %v", len(vs), l)
return
}
for i, v := range vs {
vs[i] = v + float64(vals[i])
}
}
}
// Decr increments stat value(s) by `vals`.
func (s Statistics) Decr(path string, vals ...int) {
l := len(vals)
if l == 0 {
Warnf("Decr called without value")
return
}
switch vs := s[path].(type) {
case float64:
s[path] = vs - float64(vals[0])
case []interface{}:
if l != len(vs) {
Warnf("Decr expected %v values, got %v", len(vs), l)
return
}
for i, v := range vs {
vs[i] = v.(float64) - float64(vals[i])
}
case []float64:
if l != len(vs) {
Warnf("Incr expected %v values, got %v", len(vs), l)
return
}
for i, v := range vs {
vs[i] = v - float64(vals[i])
}
}
}
// Set stat value
func (s Statistics) Set(path string, val interface{}) {
s[path] = val
}
// Get stat value
func (s Statistics) Get(path string) interface{} {
return s[path]
}
// ToMap converts Statistics to map.
func (s Statistics) ToMap() map[string]interface{} {
return map[string]interface{}(s)
}
// StatsURLPath construct url path for statistics.
func StatsURLPath(prefix, path string) string {
prefix = strings.TrimRight(prefix, UrlSep)
return strings.Join([]string{prefix, "stats", path}, UrlSep)
}
var regxStatPath, _ = regexp.Compile(`(.*)/stats/(.*)`)
// ParseStatsPath is opposite of StatsURLPath
func ParseStatsPath(urlPath string) string {
matches := regxStatPath.FindStringSubmatch(urlPath)
if len(matches) != 3 {
Fatalf("ParseStatsPath(%q)\n", urlPath)
}
return matches[2]
} | secondary/common/stats.go | 0.692954 | 0.400691 | stats.go | starcoder |
package ring
import (
"math"
"math/big"
)
// NewFloat creates a new big.Float element with "logPrecision" bits of precision
func NewFloat(x float64, logPrecision int) (y *big.Float) {
y = new(big.Float)
y.SetPrec(uint(logPrecision)) // decimal precision
y.SetFloat64(x)
return
}
// Cos implements the arbitrary precision computation of Cos(x)
// Iterative process with an error of ~10^{−0.60206*k} after k iterations.
// ref: Johansson, <NAME>, An elementary algorithm to evaluate trigonometric functions to high precision, 2018
func Cos(x *big.Float) (cosx *big.Float) {
tmp := new(big.Float)
prec := int(x.Prec())
k := int(math.Ceil(float64(x.Prec()) / (3.3219280948873626 * 0.60206))) // number of iterations : ceil( prec(log2) / (log10* 0.60206))
t := NewFloat(0.5, prec)
half := new(big.Float).Copy(t)
for i := 1; i < k-1; i++ {
t.Mul(t, half)
}
s := new(big.Float).Mul(x, t)
s.Mul(s, x)
s.Mul(s, t)
four := NewFloat(4.0, prec)
for i := 1; i < k; i++ {
tmp.Sub(four, s)
s.Mul(s, tmp)
}
cosx = new(big.Float).Quo(s, NewFloat(2.0, prec))
cosx.Sub(NewFloat(1.0, prec), cosx)
return
}
// Complex is a type for arbitrary precision complex number
type Complex [2]*big.Float
// NewComplex creates a new arbitrary precision complex number
func NewComplex(a, b *big.Float) (c *Complex) {
c = new(Complex)
for i := 0; i < 2; i++ {
c[i] = new(big.Float)
}
if a != nil {
c[0].Set(a)
}
if b != nil {
c[1].Set(b)
}
return
}
// Set sets a arbitrary precision complex number
func (c *Complex) Set(a *Complex) {
c[0].Set(a[0])
c[1].Set(a[1])
}
// Copy returns a new copy of the target arbitrary precision complex number
func (c *Complex) Copy() *Complex {
return NewComplex(c[0], c[1])
}
// Real returns the real part as a big.Float
func (c *Complex) Real() *big.Float {
return c[0]
}
// Imag returns the imaginary part as a big.Float
func (c *Complex) Imag() *big.Float {
return c[1]
}
// Float64 returns the arbitrary precision complex number as a complex128
func (c *Complex) Float64() complex128 {
a, _ := c[0].Float64()
b, _ := c[1].Float64()
return complex(a, b)
}
// Add adds two arbitrary precision complex numbers together
func (c *Complex) Add(a, b *Complex) {
c[0].Add(a[0], b[0])
c[1].Add(a[1], b[1])
}
// Sub subtracts two arbitrary precision complex numbers together
func (c *Complex) Sub(a, b *Complex) {
c[0].Sub(a[0], b[0])
c[1].Sub(a[1], b[1])
}
// ComplexMultiplier is a struct for the multiplication or division of two arbitrary precision complex numbers
type ComplexMultiplier struct {
tmp0 *big.Float
tmp1 *big.Float
tmp2 *big.Float
tmp3 *big.Float
}
// NewComplexMultiplier creates a new ComplexMultiplier
func NewComplexMultiplier() (cEval *ComplexMultiplier) {
cEval = new(ComplexMultiplier)
cEval.tmp0 = new(big.Float)
cEval.tmp1 = new(big.Float)
cEval.tmp2 = new(big.Float)
cEval.tmp3 = new(big.Float)
return
}
// Mul multiplies two arbitrary precision complex numbers together
func (cEval *ComplexMultiplier) Mul(a, b, c *Complex) {
cEval.tmp0.Mul(a[0], b[0])
cEval.tmp1.Mul(a[1], b[1])
cEval.tmp2.Mul(a[0], b[1])
cEval.tmp3.Mul(a[1], b[0])
c[0].Sub(cEval.tmp0, cEval.tmp1)
c[1].Add(cEval.tmp2, cEval.tmp3)
}
// Div divides two arbitrary precision complex numbers together
func (cEval *ComplexMultiplier) Div(a, b, c *Complex) {
// tmp0 = (a[0] * b[0]) + (a[1] * b[1]) real part
// tmp1 = (a[1] * b[0]) - (a[0] * b[0]) imag part
// tmp2 = (b[0] * b[0]) + (b[1] * b[1]) denominator
cEval.tmp0.Mul(a[0], b[0])
cEval.tmp1.Mul(a[1], b[1])
cEval.tmp2.Mul(a[1], b[0])
cEval.tmp3.Mul(a[0], b[1])
cEval.tmp0.Add(cEval.tmp0, cEval.tmp1)
cEval.tmp1.Sub(cEval.tmp2, cEval.tmp3)
cEval.tmp2.Mul(b[0], b[0])
cEval.tmp3.Mul(b[1], b[1])
cEval.tmp2.Add(cEval.tmp2, cEval.tmp3)
c[0].Quo(cEval.tmp0, cEval.tmp2)
c[1].Quo(cEval.tmp1, cEval.tmp2)
} | ring/complex128.go | 0.760428 | 0.444866 | complex128.go | starcoder |
// Package compare provides functions for comparing types by value.
package compare
import (
"reflect"
"strconv"
)
// Comparable defines the interface for a comparable type.
type Comparable interface {
Int64() int64
}
func getValues(a, b interface{}) (int64, int64) {
var (
left, right int64
av = reflect.ValueOf(a)
bv = reflect.ValueOf(b)
at = reflect.TypeOf(a)
bt = reflect.TypeOf(b)
)
switch av.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
left = int64(av.Len())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
left = av.Int()
case reflect.String:
left, _ = strconv.ParseInt(av.String(), 10, 64)
default:
if at.Implements(reflect.TypeOf((*Comparable)(nil)).Elem()) {
left = a.(Comparable).Int64()
}
panic("can not compare unsupported type")
}
switch bv.Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
right = int64(bv.Len())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
right = bv.Int()
case reflect.String:
right, _ = strconv.ParseInt(bv.String(), 10, 64)
default:
if bt.Implements(reflect.TypeOf((*Comparable)(nil)).Elem()) {
right = b.(Comparable).Int64()
}
panic("can not compare unsupported type")
}
return left, right
}
// Gt takes two types and returns true if the left type is greather then the rigth type.
// If the type is an arrays, chan, map or slice, this function will consider its length as value.
// If the type is a string, it will be parsed as a base-10 integer.
// If the type is a struct and satisfies Combarable, its Int64() function will be used.
func Gt(a, b interface{}) bool {
left, right := getValues(a, b)
return left > right
}
// Ge takes two types and returns true if the left type is greater than or equal to teh right type.
// If the types is an array, chan, map or slice, this function will consider its length as value.
// If the type is a string, it will be parsed as a base-10 integer.
// If the type is a struct and satisfies Combarable, its Int64() function will be used.
func Ge(a, b interface{}) bool {
left, right := getValues(a, b)
return left >= right
}
// Lt takes two types and returns true if the left type is less than the right type.
// If the type is an array, chan, map or slice, this function will consider its length as value.
// If the type is a string, it will be parsed as a base-10 integer.
// If the type is a struct and satisfies Combarable, its Int64() function will be used.
func Lt(a, b interface{}) bool {
left, right := getValues(a, b)
return left < right
}
// Le takes two types and returns true if the left type is less than or equal to the right type.
// If the type is an array, chan, map or slice, this function will consider its length as value.
// If the type is a string, it will be parsed as a base-10 integer.
// If the type is a struct and satisfies Combarable, its Int64() function will be used.
func Le(a, b interface{}) bool {
left, right := getValues(a, b)
return left <= right
}
// Eq takes two types and returns true if the left type is equal to the right type.
// If the type is an array, chan, map or slice, this function will consider its length as value.
// If the type is a string, it will be parsed as a base-10 integer.
// If the type is a struct and satisfies Combarable, its Int64() function will be used.
func Eq(a, b interface{}) bool {
left, right := getValues(a, b)
return left == right
} | main.go | 0.850313 | 0.561996 | main.go | starcoder |
package jgl
import (
// "fmt"
"math"
"github.com/Stymphalian/go.math/lmath"
"github.com/go-gl/gl/v3.3-compatibility/gl"
)
type Sphere struct {
Pos lmath.Vec3
Radius float64
LightFlag bool
Mat Material
radius_vec lmath.Vec3
vertices []lmath.Vec3
}
func NewSphere(radius float64) *Sphere {
out := &Sphere{}
out.Pos = lmath.Vec3{0, 0, 0}
out.Radius = radius
out.radius_vec = lmath.Vec3{radius, 0, 0}
num_lats := 20
num_longs := 20
var x, y, z, r float64
long_divs := float64(math.Pi) / float64(num_longs)
lat_divs := float64(2*math.Pi) / float64(num_lats)
out.vertices = make([]lmath.Vec3, 0, num_longs*num_lats)
for longs := 0; longs < num_longs; longs++ {
y = math.Cos(long_divs*float64(longs)) * radius
r = math.Sin(long_divs*float64(longs)) * radius
for lat := 0; lat < num_lats; lat++ {
x = math.Cos(lat_divs*float64(lat)) * r
z = math.Sin(lat_divs*float64(lat)) * r
v := lmath.Vec3{x, y, z}
out.vertices = append(out.vertices, v)
}
}
return out
}
func (this *Sphere) Draw(transform lmath.Mat4) {
gl.Begin(gl.POINTS)
// gl.Color3f(float32(this.Mat.Color[0]),
// float32(this.Mat.Color[1]),
// float32(this.Mat.Color[2]))
gl.Color3f(1, 0, 0)
for i := 0; i < len(this.vertices); i++ {
v := transform.MultVec3(this.vertices[i])
// v := this.vertices[i].MultMat4(transform)
gl.Vertex3f(float32(v.X), float32(v.Y), float32(v.Z))
}
gl.End()
}
func (this *Sphere) Intersects(ray Ray, hit HitRecord, transform lmath.Mat4) HitRecord {
// origin - center
trans_pos := transform.MultVec3(this.Pos)
trans_rad_vec := transform.MultVec3(this.radius_vec)
// trans_pos := this.Pos.MultMat4(transform)
// trans_rad_vec := this.radius_vec.MultMat4(transform)
omc := ray.Origin.Sub(trans_pos)
radius := trans_rad_vec.Sub(trans_pos).Length()
A := ray.Dir.Dot(ray.Dir)
B := (ray.Dir.MultScalar(2)).Dot(omc)
C := (omc.Dot(omc)) - radius*radius
// calculate the descriminant and make sure that it has a solution
descriminant := B*B - 4*A*C
if descriminant < epsilon {
hit.Hit = false
return hit
}
// calculate the two possible solutions
descriminant = math.Sqrt(descriminant)
dist1 := (-B + descriminant) / (2 * A)
dist2 := (-B - descriminant) / (2 * A)
dist := 0.0
if dist2 < dist1 {
dist = dist2
} else {
dist = dist1
}
// make sure the dist is in range.
if dist > hit.MinDist && dist < hit.MaxDist {
hit.Hit = true
hit.Dist = dist
hit.MaxDist = hit.Dist
return hit
}
hit.Hit = false
return hit
}
func (this *Sphere) Normal(hitPoint lmath.Vec3, hit HitRecord) lmath.Vec3 {
trans_pos := hit.Transform.MultVec3(this.Pos)
trans_rad_vec := hit.Transform.MultVec3(this.radius_vec)
radius := trans_rad_vec.Sub(trans_pos).Length()
return hitPoint.Sub(trans_pos).DivScalar(radius)
}
func (this Sphere) Material() Material {
return this.Mat
} | jgl/sphere.go | 0.636579 | 0.48377 | sphere.go | starcoder |
package types
// CapabilityStore defines an ephemeral in-memory object capability store.
type CapabilityStore struct {
revMemStore map[string]*Capability
fwdMemStore map[string]string
}
func NewCapabilityStore() CapabilityStore {
return CapabilityStore{
revMemStore: make(map[string]*Capability),
fwdMemStore: make(map[string]string),
}
}
// GetCapability returns a Capability by module and name tuple. If no Capability
// exists, nil will be returned.
func (cs CapabilityStore) GetCapability(module, name string) *Capability {
key := RevCapabilityKey(module, name)
return cs.revMemStore[string(key)]
}
// GetCapabilityName returns a Capability name by module and Capability tuple. If
// no Capability name exists for the given tuple, an empty string is returned.
func (cs CapabilityStore) GetCapabilityName(module string, cap *Capability) string {
key := FwdCapabilityKey(module, cap)
return cs.fwdMemStore[string(key)]
}
// SetCapability sets the reverse mapping between the module and capability name
// and the capability in the in-memory store.
func (cs CapabilityStore) SetCapability(module, name string, cap *Capability) {
key := RevCapabilityKey(module, name)
cs.revMemStore[string(key)] = cap
}
// SetCapabilityName sets the forward mapping between the module and capability
// tuple and the capability name in the in-memory store.
func (cs CapabilityStore) SetCapabilityName(module, name string, cap *Capability) {
key := FwdCapabilityKey(module, cap)
cs.fwdMemStore[string(key)] = name
}
// DeleteCapability removes the reverse mapping between the module and capability
// name and the capability in the in-memory store.
func (cs CapabilityStore) DeleteCapability(module, name string) {
key := RevCapabilityKey(module, name)
delete(cs.revMemStore, string(key))
}
// DeleteCapabilityName removes the forward mapping between the module and capability
// tuple and the capability name in the in-memory store.
func (cs CapabilityStore) DeleteCapabilityName(module string, cap *Capability) {
key := FwdCapabilityKey(module, cap)
delete(cs.fwdMemStore, string(key))
} | x/capability/types/store.go | 0.81309 | 0.556159 | store.go | starcoder |
package sort
import "math"
/* CountingSort
suppose all elements in an array are in a relative small range 0~k, then we can use counting sort to sort the array in O(n+k)
steps:
1. define counting array[k+1] : ca[k+1] example: [0, 0, 0]
2. scan all elements in input array, set: ca[input[i]]++ example: [1, 3, 2]
3. scan ca from 0 - k: make ca[i]=ca[i-1] + ca[i] example: [1, 4, 6]
4. create a new array as the input array len: result array;
5. scan input array (from last to first), result[ca[input[i]] - 1] = input[i], set: ca[input[i]] = ca[input[i]] - 1
return new sorted array
*/
func CountingSort(arr []int, bottom, up int) []int {
ca := make([]int, up-bottom+1)
for i := 0; i < len(arr); i++ {
ca[arr[i]-bottom]++
}
for i := 1; i < len(ca); i++ {
ca[i] += ca[i-1]
}
result := make([]int, len(arr))
for i := len(arr) - 1; i >= 0; i-- {
result[ca[arr[i]-bottom]-1] = arr[i]
ca[arr[i]-bottom] -= 1
}
return result
}
/* RadixSort
when element are positive numbers and distributed a little evenly in a large range, we can use radix sort:
step:
1. define the max bit in numbers, and the base bit we use for split
2. get the base digit we used for counting: baseDigit = 1 << baseBit
3. loop for largest maxBit/baseBit times:
a. sort element on k th digit with counting sort
b. copy sorted array to original array as new input for next round loop
return new sorted array
*/
func RadixSort(arr []int) []int {
result := make([]int, len(arr))
baseBit := 4
maxBit := 32
baseDigit := 1 << 8
for r := 0; r < maxBit/baseBit; r++ {
shift := math.Pow(float64(baseDigit), float64(r))
count := make([]int, baseDigit)
for i := 0; i < len(arr); i++ {
countIndex := getCount(arr, i, int(shift), baseDigit) //get rank of special position
count[countIndex]++
}
for i := 1; i < len(count); i++ {
count[i] += count[i-1]
}
for i := len(arr) - 1; i >= 0; i-- {
countIndex := getCount(arr, i, int(shift), baseDigit)
result[count[countIndex]-1] = arr[i]
count[countIndex]--
}
for i := 0; i < len(arr); i++ {
arr[i] = result[i]
}
}
return result
}
func getCount(arr []int, i, shift, baseDigit int) int {
return arr[i] / int(shift) % baseDigit
}
/* BucketSort
when all elements are in a not very large range, we can split them in some sub-range - subset of the range, and then sort and merge
1. find the max and min element in buckets;
2. define bucket number, and calculate bucket range for every bucket;
3. loop array, find the bucket for every element;
4. loop buckets, sort for every buckets;
5. merge all bucket and get the sorted results.
return new sorted array
*/
func BucketSort(arr []int) []int {
min, max := arr[0], arr[0]
for i := 1; i < len(arr); i++ {
if arr[i] > max {
max = arr[i]
}
if arr[i] < min {
min = arr[i]
}
}
bucketCount := 11
delta := (max-min)/(bucketCount-1) + 1
bucket := make([][]int, bucketCount)
var index map[int]int = make(map[int]int)
for i := 0; i < bucketCount; i++ {
index[i] = 0
bucket[i] = make([]int, 0)
}
for i := 0; i < len(arr); i++ {
bucketIndex := (arr[i] - min) / delta
bucket[bucketIndex] = append(bucket[bucketIndex], arr[i])
index[bucketIndex]++
}
result := make([]int, 0)
for i := 0; i < bucketCount; i++ {
if index[i] > 0 {
result = append(result, CountingSort(bucket[i], min+i*delta, min+i*delta+delta)...)
}
}
return result
} | Algorithm-go/sort/linearsort.go | 0.524151 | 0.569134 | linearsort.go | starcoder |
package local_days
import (
"fmt"
"log"
"time"
)
// NewTimeZoneBasedLocalTimeConverter returns a ToLocalTimeConverter that internally uses the timezone data from the timezone with the given zoneName (e.g. "Europe/Berlin"). It requires the tzdata to be available on the system and will panic if this is not the case.
func NewTimeZoneBasedLocalTimeConverter(zoneName string) LocalDaysCalculator {
location, err := time.LoadLocation(zoneName)
if err != nil {
errorMsg := fmt.Errorf("The timezone data for '%s' could not be found. Import \"time/tzdata\" anywhere in your project or build with `-tags timetzdata`: https://pkg.go.dev/time/tzdata", zoneName)
log.Panic(errorMsg)
}
return locationBasedLocalTimeConverter{location: location}
}
type locationBasedLocalTimeConverter struct {
location *time.Location
}
// ToLocalTimeConverter contains a method to convert a time into a local time. This will, in most cases, happen on the basis of timezone data, but you are free to write your own conversion, although you're probably missing out on details at one point.
type ToLocalTimeConverter interface {
// toLocalTime converts a timestamp to a "local" time by adjusting date, time and UTC-offset. The actual point in time in UTC or Unix does _not_ change.
toLocalTime(timestamp time.Time) time.Time
}
func (l locationBasedLocalTimeConverter) toLocalTime(timestamp time.Time) time.Time {
return timestamp.In(l.location)
}
// LocalDaysCalculator is an interface that encapsulates common date time operations that involve local date times.
type LocalDaysCalculator interface {
// AddLocalDays converts timestamp to local time, then adds 1 day and returns UTC. This will effectively add 24h on 363 out of 365 cases. But on the days on which the calendar switches from Daylight saving time (DST) to "normal" time or vice versa it might add 25 or 23 hours.
AddLocalDays(timestamp time.Time, number int) time.Time
// StartOfLocalDay converts timestamp to local time, then sets hour, minute and seconds to 0 and returns as UTC. The return value is always <= the given timestamp.
StartOfLocalDay(timestamp time.Time) time.Time
// StartOfNextLocalDay converts timestamp to local time, then returns the next start of local day (midnight, 00:00am local time) as UTC. The return value is always > the given timestamp.
StartOfNextLocalDay(timestamp time.Time) time.Time
// StartOfLocalMonth converts timestamp to local time, then returns the start of the local month (day, hours, minutes, seconds=0) as UTC. The return value is always <= the given timestamp.
StartOfLocalMonth(timestamp time.Time) time.Time
// StartOfNextLocalMonth converts timestamp to local time, then returns the start of the next local month (day, hours, minutes, seconds=0) as UTC. The return value is always > the given timestamp.
StartOfNextLocalMonth(timestamp time.Time) time.Time
// GetLocalWeekday returns the weekday of the given timestamp in local timezone.
GetLocalWeekday(timestamp time.Time) time.Weekday
// NextLocalWeekday returns the start of the next local weekday (as specified) in UTC. The result always > than the given timestamp. It might be up to 7 days later than the given timestamp. If e.g. providing a tuesday and requesting the next tuesday, the result will be the timestamp + 7 Local days
NextLocalWeekday(timestamp time.Time, weekday time.Weekday) time.Time
// IsLocalMidnight returns true if and only if timestamp is midnight in local time
IsLocalMidnight(timestamp time.Time) bool
}
// the following implementations are tested by the package "germany"
func (l locationBasedLocalTimeConverter) AddLocalDays(timestamp time.Time, number int) time.Time {
return l.toLocalTime(timestamp).AddDate(0, 0, number).UTC()
}
func (l locationBasedLocalTimeConverter) StartOfLocalDay(timestamp time.Time) time.Time {
localTime := l.toLocalTime(timestamp)
localMidnight := time.Date(localTime.Year(), localTime.Month(), localTime.Day(), 0, 0, 0, 0, l.location)
return localMidnight.UTC()
}
func (l locationBasedLocalTimeConverter) StartOfNextLocalDay(timestamp time.Time) time.Time {
plusOneDayInLocally := l.toLocalTime(timestamp).AddDate(0, 0, 1)
return l.StartOfLocalDay(plusOneDayInLocally.UTC())
}
func (l locationBasedLocalTimeConverter) StartOfLocalMonth(timestamp time.Time) time.Time {
localTime := l.toLocalTime(timestamp)
startOfLocalMonth := time.Date(localTime.Year(), localTime.Month(), 1, 0, 0, 0, 0, l.location)
return startOfLocalMonth.UTC()
}
func (l locationBasedLocalTimeConverter) StartOfNextLocalMonth(timestamp time.Time) time.Time {
localTime := l.toLocalTime(timestamp)
startOfNextLocalMonth := time.Date(localTime.Year(), localTime.Month()+1, 1, 0, 0, 0, 0, l.location)
return startOfNextLocalMonth.UTC()
}
func (l locationBasedLocalTimeConverter) GetLocalWeekday(timestamp time.Time) time.Weekday {
return l.toLocalTime(timestamp).Weekday()
}
func (l locationBasedLocalTimeConverter) NextLocalWeekday(timestamp time.Time, weekday time.Weekday) time.Time {
localTime := l.StartOfNextLocalDay(timestamp).In(l.location)
for {
if localTime.Weekday() == weekday {
return localTime.UTC()
}
localTime = localTime.AddDate(0, 0, 1)
}
}
func (l locationBasedLocalTimeConverter) IsLocalMidnight(timestamp time.Time) bool {
localTime := l.toLocalTime(timestamp)
return localTime.UTC() == l.StartOfLocalDay(timestamp)
} | local_days/local_days.go | 0.83025 | 0.648146 | local_days.go | starcoder |
package main
import (
"errors"
"math"
"math/rand"
blt "bearlibterminal"
)
const (
// Values to catch errors.
WrongIndexValue = -1
)
func RoundFloatToInt(x float64) int {
/* Function RoundFloatToInt takes one float64 number,
rounds it to nearest 1.0, then returns it as a integer. */
return int(math.Round(x))
}
func RandInt(max int) int {
/* Function RandInt wraps rand.Intn function;
instead of returning 0..n-1 it returns 0..n. */
return rand.Intn(max + 1)
}
func RandRange(min, max int) int {
/* Function RandRange returns value between min and max,
both including. */
return RandInt(max-min) + min
}
func OrderToCharacter(i int) string {
/* Function OrderToCharacter takes integer
and converts it to string. Typically,
it will be used with letters, but rune
is alias of int32 and support unicode
well.
Typically, one would like to return
string('a'-1+i)
to convert "1" to "a", but RAWIG will use
it to deal with bare slices that count
from 0.*/
return string('a' + i)
}
func KeyToOrder(key int) int {
/* Function KeyToOrder takes user input as integer
(in BearLibTerminal player input is passed as 0x...)
and return another int that is smaller by
first-key (ie "a" key).
It will need extensive error-checking
(or maybe just LBYL?) for wrong input. */
return key - blt.TK_A
}
func FindCreatureIndex(creature *Creature, arr Creatures) (int, error) {
/* Function FindCreatureIndex works as FindObjectIndex,
but for monsters. */
var err error
index := WrongIndexValue
for i := 0; i < len(arr); i++ {
if arr[i] == creature {
index = i
break
}
if index == WrongIndexValue {
err = errors.New("*Creature not found in []*Creature.")
}
}
return index, err
}
func DistanceBetween(sourceX, sourceY, targetX, targetY int) int {
/* Function DistanceBetween takes coords of source and target;
it computes distance between these two tiles.
As Go uses float64 for such a computations, it is necessary
to transform ints to float64 then round result to int. */
dx := float64(targetX - sourceX)
dy := float64(targetY - sourceY)
distance := RoundFloatToInt(math.Sqrt(math.Pow(dx, 2) + math.Pow(dy, 2)))
return distance
}
func (c *Creature) DistanceBetweenCreatures(c2 *Creature) int {
distance := DistanceBetween(c.X, c.Y, c2.X, c2.Y)
return distance
}
func AbsoluteValue(i int) int {
/* Function AbsoluteValue returns absolute (ie "non negative") value. */
if i < 0 {
return -i
}
return i
}
func ReverseIntSlice(arr []int) []int {
/* Function ReverseIntSlice takes slice of int and returns
it in reversed order. It is odd that "battery included"
language like Go does not have built-in functions for it. */
var reversed = []int{}
for i := len(arr) - 1; i >= 0; i-- {
reversed = append(reversed, arr[i])
}
return reversed
}
func CreatureIsInSlice(c *Creature, arr Creatures) bool {
/* Function CreatureIsInSlice takes Creature and slice of Creature
as arguments, and returns true, if c is present in arr.
Otherwise, returns false. */
for _, v := range arr {
if c == v {
return true
}
}
return false
}
func Percents(value int, of int) int {
return int(math.Round(float64(value) / float64(of) * float64(100)))
} | utilities_math.go | 0.695648 | 0.422922 | utilities_math.go | starcoder |
package types
import (
"bytes"
"fmt"
"sort"
"github.com/spacemeshos/ed25519"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/signing"
)
const (
// ProposalIDSize in bytes.
// FIXME(dshulyak) why do we cast to hash32 when returning bytes?
// probably required for fetching by hash between peers.
ProposalIDSize = Hash32Length
)
// ProposalID is a 20-byte sha256 sum of the serialized ballot used to identify a Proposal.
type ProposalID Hash20
// EmptyProposalID is a canonical empty ProposalID.
var EmptyProposalID = ProposalID{}
// Proposal contains the smesher's signed content proposal for a given layer and vote on the mesh history.
// Proposal is ephemeral and will be discarded after the unified content block is created. the Ballot within
// the Proposal will remain in the mesh.
type Proposal struct {
// the content proposal for a given layer and the votes on the mesh history
InnerProposal
// smesher's signature on InnerProposal
Signature []byte
// the following fields are kept private and from being serialized
proposalID ProposalID
}
// InnerProposal contains a smesher's content proposal for layer and its votes on the mesh history.
// this structure is serialized and signed to produce the signature in Proposal.
type InnerProposal struct {
// smesher's votes on the mesh history
Ballot
// smesher's content proposal for a layer
TxIDs []TransactionID
}
// Initialize calculates and sets the Proposal's cached proposalID.
// this should be called once all the other fields of the Proposal are set.
func (p *Proposal) Initialize() error {
if p.ID() != EmptyProposalID {
return fmt.Errorf("proposal already initialized")
}
if err := p.Ballot.Initialize(); err != nil {
return err
}
// check proposal signature consistent with ballot's
pubkey, err := ed25519.ExtractPublicKey(p.Bytes(), p.Signature)
if err != nil {
return fmt.Errorf("proposal extract key: %w", err)
}
pPubKey := signing.NewPublicKey(pubkey)
if !p.Ballot.SmesherID().Equals(pPubKey) {
return fmt.Errorf("inconsistent smesher in proposal %v and ballot %v", pPubKey.ShortString(), p.Ballot.SmesherID().ShortString())
}
p.proposalID = ProposalID(CalcHash32(p.Bytes()).ToHash20())
return nil
}
// Bytes returns the serialization of the InnerProposal.
func (p *Proposal) Bytes() []byte {
bytes, err := codec.Encode(p.InnerProposal)
if err != nil {
log.Panic("failed to serialize proposal: %v", err)
}
return bytes
}
// ID returns the ProposalID.
func (p *Proposal) ID() ProposalID {
return p.proposalID
}
// MarshalLogObject implements logging interface.
func (p *Proposal) MarshalLogObject(encoder log.ObjectEncoder) error {
encoder.AddString("proposal_id", p.ID().String())
p.Ballot.MarshalLogObject(encoder)
return nil
}
// String returns a short prefix of the hex representation of the ID.
func (id ProposalID) String() string {
return id.AsHash32().ShortString()
}
// Bytes returns the ProposalID as a byte slice.
func (id ProposalID) Bytes() []byte {
return id.AsHash32().Bytes()
}
// AsHash32 returns a Hash32 whose first 20 bytes are the bytes of this ProposalID, it is right-padded with zeros.
func (id ProposalID) AsHash32() Hash32 {
return Hash20(id).ToHash32()
}
// Field returns a log field. Implements the LoggableField interface.
func (id ProposalID) Field() log.Field {
return log.String("proposal_id", id.String())
}
// Compare returns true if other (the given ProposalID) is less than this ProposalID, by lexicographic comparison.
func (id ProposalID) Compare(other ProposalID) bool {
return bytes.Compare(id.Bytes(), other.Bytes()) < 0
}
// ToProposalIDs returns a slice of ProposalID corresponding to the given proposals.
func ToProposalIDs(proposals []*Proposal) []ProposalID {
ids := make([]ProposalID, 0, len(proposals))
for _, p := range proposals {
ids = append(ids, p.ID())
}
return ids
}
// SortProposals sorts a list of Proposal in their ID's lexicographic order, in-place.
func SortProposals(proposals []*Proposal) []*Proposal {
sort.Slice(proposals, func(i, j int) bool { return proposals[i].ID().Compare(proposals[j].ID()) })
return proposals
}
// SortProposalIDs sorts a list of ProposalID in lexicographic order, in-place.
func SortProposalIDs(ids []ProposalID) []ProposalID {
sort.Slice(ids, func(i, j int) bool { return ids[i].Compare(ids[j]) })
return ids
}
// ProposalIDsToHashes turns a list of ProposalID into their Hash32 representation.
func ProposalIDsToHashes(ids []ProposalID) []Hash32 {
hashes := make([]Hash32, 0, len(ids))
for _, id := range ids {
hashes = append(hashes, id.AsHash32())
}
return hashes
}
// DBProposal is a Proposal structure stored in DB to skip signature verification.
type DBProposal struct {
// NOTE(dshulyak) this is a bit redundant to store ID here as well but less likely
// to break if in future key for database will be changed
ID ProposalID
BallotID BallotID
LayerIndex LayerID
TxIDs []TransactionID
Signature []byte
}
// ToProposal creates a Proposal from data that is stored locally.
func (b *DBProposal) ToProposal(ballot *Ballot) *Proposal {
return &Proposal{
InnerProposal: InnerProposal{
Ballot: *ballot,
TxIDs: b.TxIDs,
},
Signature: b.Signature,
proposalID: b.ID,
}
} | common/types/proposal.go | 0.555918 | 0.414543 | proposal.go | starcoder |
package goment
import (
"math"
)
// Get is a string getter using the supplied units. Returns 0 if unsupported property.
func (g *Goment) Get(units string) int {
switch units {
case "y", "year", "years":
return g.Year()
case "M", "month", "months":
return g.Month()
case "D", "date", "dates":
return g.Date()
case "h", "hour", "hours":
return g.Hour()
case "m", "minute", "minutes":
return g.Minute()
case "s", "second", "seconds":
return g.Second()
case "ms", "millisecond", "milliseconds":
return g.Millisecond()
case "ns", "nanosecond", "nanoseconds":
return g.Nanosecond()
}
return 0
}
// Nanosecond gets the nanoseconds.
func (g *Goment) Nanosecond() int {
return g.ToTime().Nanosecond()
}
// Millisecond gets the milliseconds.
func (g *Goment) Millisecond() int {
return g.Second() * 1000
}
// Second gets the seconds.
func (g *Goment) Second() int {
return g.ToTime().Second()
}
// Minute gets the minutes.
func (g *Goment) Minute() int {
return g.ToTime().Minute()
}
// Hour gets the hour.
func (g *Goment) Hour() int {
return g.ToTime().Hour()
}
// Date gets the day of the month.
func (g *Goment) Date() int {
return g.ToTime().Day()
}
// Day gets the day of the week (Sunday = 0...).
func (g *Goment) Day() int {
return int(g.ToTime().Weekday())
}
// Weekday gets the day of the week according to the locale.
func (g *Goment) Weekday() int {
return (g.Day() + 7 - g.locale.Week.Dow) % 7
}
// ISOWeekday gets the ISO day of the week with 1 being Monday and 7 being Sunday.
func (g *Goment) ISOWeekday() int {
wd := g.Day()
if wd == 0 {
wd = 7
}
return wd
}
// DayOfYear gets the day of the year.
func (g *Goment) DayOfYear() int {
return g.ToTime().YearDay()
}
// Week gets the week of the year according to the locale.
func (g *Goment) Week() int {
return weekOfYear(g, g.locale.Week.Dow, g.locale.Week.Doy).week
}
// ISOWeek gets the ISO week of the year.
func (g *Goment) ISOWeek() int {
_, week := g.ToTime().ISOWeek()
return week
}
// Month gets the month (January = 1...).
func (g *Goment) Month() int {
return int(g.ToTime().Month())
}
// Quarter gets the quarter (1 to 4).
func (g *Goment) Quarter() int {
return int(math.Ceil(float64(g.Month()) / 3))
}
// Year gets the year.
func (g *Goment) Year() int {
return g.ToTime().Year()
}
// WeekYear gets the week-year according to the locale.
func (g *Goment) WeekYear() int {
return weekOfYear(g, g.locale.Week.Dow, g.locale.Week.Doy).year
}
// ISOWeekYear gets the ISO week-year.
func (g *Goment) ISOWeekYear() int {
year, _ := g.ToTime().ISOWeek()
return year
}
// WeeksInYear gets the number of weeks according to locale in the current Goment's year.
func (g *Goment) WeeksInYear() int {
return weeksInYear(g.Year(), g.locale.Week.Dow, g.locale.Week.Doy)
}
// ISOWeeksInYear gets the number of weeks in the current Goment's year, according to ISO weeks.
func (g *Goment) ISOWeeksInYear() int {
return weeksInYear(g.Year(), 1, 4)
}
// Set is a generic setter, accepting units as the first argument, and value as the second.
func (g *Goment) Set(units string, value int) *Goment {
switch units {
case "y", "year", "years":
return g.SetYear(value)
case "M", "month", "months":
return g.SetMonth(value)
case "D", "date", "dates":
return g.SetDate(value)
case "h", "hour", "hours":
return g.SetHour(value)
case "m", "minute", "minutes":
return g.SetMinute(value)
case "s", "second", "seconds":
return g.SetSecond(value)
case "ms", "millisecond", "milliseconds":
return g.SetMillisecond(value)
case "ns", "nanosecond", "nanoseconds":
return g.SetNanosecond(value)
}
return g
}
// SetNanosecond sets the nanoseconds.
func (g *Goment) SetNanosecond(nanoseconds int) *Goment {
if nanoseconds >= 0 && nanoseconds <= 999999999 {
return g.addNanoseconds(nanoseconds - g.Nanosecond())
}
return g
}
// SetMillisecond sets the milliseconds.
func (g *Goment) SetMillisecond(milliseconds int) *Goment {
if milliseconds >= 0 && milliseconds <= 59000 {
return g.addMilliseconds(milliseconds - g.Millisecond())
}
return g
}
// SetSecond sets the seconds.
func (g *Goment) SetSecond(seconds int) *Goment {
if seconds >= 0 && seconds <= 59 {
return g.addSeconds(seconds - g.Second())
}
return g
}
// SetMinute sets the minutes.
func (g *Goment) SetMinute(minutes int) *Goment {
if minutes >= 0 && minutes <= 59 {
return g.addMinutes(minutes - g.Minute())
}
return g
}
// SetHour sets the hour.
func (g *Goment) SetHour(hours int) *Goment {
if hours >= 0 && hours <= 23 {
return g.addHours(hours - g.Hour())
}
return g
}
// SetDate sets the day of the month. If the date passed in is greater than the number of days in the month,
// then the day is set to the last day of the month.
func (g *Goment) SetDate(date int) *Goment {
if date >= 1 && date <= 31 {
daysInMonth := g.DaysInMonth()
if date >= daysInMonth {
date = daysInMonth
}
return g.addDays(date - g.Date())
}
return g
}
// SetDay sets the day of the week (Sunday = 0...).
func (g *Goment) SetDay(args ...interface{}) *Goment {
if len(args) != 1 {
return g
}
switch v := args[0].(type) {
case string:
parsed := g.locale.WeekdaysRegex.FindString(v)
if parsed != "" {
val := g.locale.GetWeekdayNumber(parsed)
if val != -1 {
return g.addDays(val - g.Day())
}
}
case int:
return g.addDays(v - g.Day())
}
return g
}
// SetWeekday sets the day of the week according to the locale.
func (g *Goment) SetWeekday(weekday int) *Goment {
currWeekday := g.Weekday()
return g.addDays(weekday - currWeekday)
}
// SetISOWeekday sets the ISO day of the week with 1 being Monday and 7 being Sunday.
func (g *Goment) SetISOWeekday(weekday int) *Goment {
if weekday >= 1 && weekday <= 7 {
if weekday == 7 {
weekday = 0
}
return g.SetDay(weekday)
}
return g
}
// SetDayOfYear sets the day of the year. For non-leap years, 366 is treated as 365.
func (g *Goment) SetDayOfYear(doy int) *Goment {
if doy >= 1 && doy <= 366 {
if !g.IsLeapYear() && doy == 366 {
doy = 365
}
return g.addDays(doy - g.DayOfYear())
}
return g
}
// SetWeek sets the week of the year according to the locale.
func (g *Goment) SetWeek(week int) *Goment {
return g.addDays((week - g.Week()) * 7)
}
// SetISOWeek sets the ISO week of the year.
func (g *Goment) SetISOWeek(week int) *Goment {
woy := weekOfYear(g, 1, 4).week
return g.addDays((week - woy) * 7)
}
// SetMonth sets the month (January = 1...). If new month has less days than current month,
// the date is pinned to the end of the target month.
func (g *Goment) SetMonth(month int) *Goment {
if month >= 1 && month <= 12 {
currentDate := g.Date()
newDaysInMonth := daysInMonth(month, g.Year())
if currentDate > newDaysInMonth {
g.SetDate(newDaysInMonth)
}
return g.addMonths(month - g.Month())
}
return g
}
// SetQuarter sets the quarter (1 to 4).
func (g *Goment) SetQuarter(quarter int) *Goment {
if quarter >= 1 && quarter <= 4 {
return g.addQuarters(quarter - g.Quarter())
}
return g
}
// SetYear sets the year.
func (g *Goment) SetYear(year int) *Goment {
return g.addYears(year - g.Year())
}
// SetWeekYear sets the week-year according to the locale.
func (g *Goment) SetWeekYear(weekYear int) *Goment {
return setWeekYearHelper(g, weekYear, g.Week(), g.Weekday(), g.locale.Week.Dow, g.locale.Week.Doy)
}
// SetISOWeekYear sets the ISO week-year.
func (g *Goment) SetISOWeekYear(weekYear int) *Goment {
return setWeekYearHelper(g, weekYear, g.ISOWeek(), g.ISOWeekday(), 1, 4)
}
func setWeekYearHelper(g *Goment, weekYear int, week int, weekday int, dow int, doy int) *Goment {
weeksTarget := weeksInYear(weekYear, dow, doy)
if week > weeksTarget {
week = weeksTarget
}
dayOfYearData := dayOfYearFromWeeks(weekYear, week, weekday, dow, doy)
d, _ := New(DateTime{Year: dayOfYearData.year, Month: 1, Day: dayOfYearData.dayOfYear})
d.UTC()
g.SetYear(d.Year())
g.SetMonth(d.Month())
g.SetDate(d.Date())
return g
} | get_set.go | 0.834373 | 0.569583 | get_set.go | starcoder |
package mincut
import (
"math/rand"
)
// Graph represents a graph, where map[head]map[tail]edge_count
type Graph map[int]map[int]int
// Edge represents an edge between vertex a and vertex b.
type Edge struct{ a, b int }
// WithEdges first converts the slice of Edges into Graph, and call WithGraph with it.
func WithEdges(edges []Edge) int {
g := Graph{}
for _, e := range edges {
if _, ok := g[e.a]; !ok {
g[e.a] = map[int]int{}
}
if _, ok := g[e.b]; !ok {
g[e.b] = map[int]int{}
}
g[e.a][e.b]++
g[e.b][e.a]++
}
return WithGraph(g)
}
// WithGraph finds the minimum number of edges to cut a graph into two subgraphs
// using randomized contraction algorithm.
func WithGraph(g Graph) int {
n := len(g)
t := n * n
ch := make(chan int, t)
for i := 0; i < t; i++ {
go func() {
g1 := clone(g)
cut := try(g1)
ch <- cut
}()
}
best := len(toEdges(g))
for i := 0; i < t; i++ {
cut := <-ch
if cut < best {
best = cut
}
}
return best
}
func try(g Graph) int {
edges := toEdges(g)
for len(g) > 2 {
e := pickEdge(edges)
g, edges = merge(g, edges, e)
}
return len(edges)
}
func toEdges(g Graph) []Edge {
mark := map[Edge]bool{}
edges := []Edge{}
for h, ts := range g {
for t, cnt := range ts {
// NOTE: Two different entries to the same vertex are
// considered to be distinct edges.
if !mark[Edge{t, h}] {
e := Edge{h, t}
mark[e] = true
for i := 0; i < cnt; i++ {
edges = append(edges, e)
}
}
}
}
return edges
}
func clone(g Graph) Graph {
g1 := make(Graph)
for h, ts := range g {
ts1 := make(map[int]int)
for t, cnt := range ts {
ts1[t] = cnt
}
g1[h] = ts1
}
return g1
}
func pickEdge(edges []Edge) Edge {
i := rand.Intn(len(edges))
return edges[i]
}
func merge(g Graph, edges []Edge, e Edge) (Graph, []Edge) {
ats := g[e.a]
bts := g[e.b]
for t, cnt := range bts {
if t == e.a {
continue
}
// Migrate edges from e.b to e.a.
ats[t] += cnt
// Replace e.b with e.a in g[t]
ots := g[t]
ots[e.a] += cnt
delete(ots, e.b)
}
delete(g, e.b)
delete(ats, e.b)
for i := 0; i < len(edges); {
e1 := edges[i]
if (e1.a == e.a && e1.b == e.b) || (e1.b == e.a && e1.a == e.b) {
edges[i] = edges[len(edges)-1]
edges = edges[:len(edges)-1]
continue
}
if edges[i].a == e.b {
edges[i].a = e.a
}
if edges[i].b == e.b {
edges[i].b = e.a
}
i++
}
return g, edges
} | mincut/mincut.go | 0.730001 | 0.480418 | mincut.go | starcoder |
package should
import "github.com/smartystreets/assertions"
var (
AlmostEqual = assertions.ShouldAlmostEqual
BeBetween = assertions.ShouldBeBetween
BeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual
BeBlank = assertions.ShouldBeBlank
BeChronological = assertions.ShouldBeChronological
BeEmpty = assertions.ShouldBeEmpty
BeError = assertions.ShouldBeError
BeFalse = assertions.ShouldBeFalse
BeGreaterThan = assertions.ShouldBeGreaterThan
BeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo
BeIn = assertions.ShouldBeIn
BeLessThan = assertions.ShouldBeLessThan
BeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo
BeNil = assertions.ShouldBeNil
BeTrue = assertions.ShouldBeTrue
BeZeroValue = assertions.ShouldBeZeroValue
Contain = assertions.ShouldContain
ContainKey = assertions.ShouldContainKey
ContainSubstring = assertions.ShouldContainSubstring
EndWith = assertions.ShouldEndWith
Equal = assertions.ShouldEqual
EqualJSON = assertions.ShouldEqualJSON
EqualTrimSpace = assertions.ShouldEqualTrimSpace
EqualWithout = assertions.ShouldEqualWithout
HappenAfter = assertions.ShouldHappenAfter
HappenBefore = assertions.ShouldHappenBefore
HappenBetween = assertions.ShouldHappenBetween
HappenOnOrAfter = assertions.ShouldHappenOnOrAfter
HappenOnOrBefore = assertions.ShouldHappenOnOrBefore
HappenOnOrBetween = assertions.ShouldHappenOnOrBetween
HappenWithin = assertions.ShouldHappenWithin
HaveLength = assertions.ShouldHaveLength
HaveSameTypeAs = assertions.ShouldHaveSameTypeAs
Implement = assertions.ShouldImplement
NotAlmostEqual = assertions.ShouldNotAlmostEqual
NotBeBetween = assertions.ShouldNotBeBetween
NotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual
NotBeBlank = assertions.ShouldNotBeBlank
NotBeChronological = assertions.ShouldNotBeChronological
NotBeEmpty = assertions.ShouldNotBeEmpty
NotBeIn = assertions.ShouldNotBeIn
NotBeNil = assertions.ShouldNotBeNil
NotBeZeroValue = assertions.ShouldNotBeZeroValue
NotContain = assertions.ShouldNotContain
NotContainKey = assertions.ShouldNotContainKey
NotContainSubstring = assertions.ShouldNotContainSubstring
NotEndWith = assertions.ShouldNotEndWith
NotEqual = assertions.ShouldNotEqual
NotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween
NotHappenWithin = assertions.ShouldNotHappenWithin
NotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs
NotImplement = assertions.ShouldNotImplement
NotPanic = assertions.ShouldNotPanic
NotPanicWith = assertions.ShouldNotPanicWith
NotPointTo = assertions.ShouldNotPointTo
NotResemble = assertions.ShouldNotResemble
NotStartWith = assertions.ShouldNotStartWith
Panic = assertions.ShouldPanic
PanicWith = assertions.ShouldPanicWith
PointTo = assertions.ShouldPointTo
Resemble = assertions.ShouldResemble
StartWith = assertions.ShouldStartWith
) | vendor/github.com/smartystreets/assertions/should/should.go | 0.632276 | 0.609582 | should.go | starcoder |
package iso20022
// Set of elements used to provide information specific to the individual direct debit transaction(s) included in the message.
type DirectDebitTransactionInformation9 struct {
// Set of elements used to reference a payment instruction.
PaymentIdentification *PaymentIdentification1 `xml:"PmtId"`
// Set of elements used to further specify the type of transaction.
PaymentTypeInformation *PaymentTypeInformation20 `xml:"PmtTpInf,omitempty"`
// Amount of money to be moved between the debtor and creditor, before deduction of charges, expressed in the currency as ordered by the initiating party.
InstructedAmount *ActiveOrHistoricCurrencyAndAmount `xml:"InstdAmt"`
// Specifies which party/parties will bear the charges associated with the processing of the payment transaction.
ChargeBearer *ChargeBearerType1Code `xml:"ChrgBr,omitempty"`
// Set of elements providing information specific to the direct debit mandate.
DirectDebitTransaction *DirectDebitTransaction6 `xml:"DrctDbtTx,omitempty"`
// Ultimate party to which an amount of money is due.
UltimateCreditor *PartyIdentification32 `xml:"UltmtCdtr,omitempty"`
// Financial institution servicing an account for the debtor.
DebtorAgent *BranchAndFinancialInstitutionIdentification4 `xml:"DbtrAgt"`
// Unambiguous identification of the account of the debtor agent at its servicing agent in the payment chain.
DebtorAgentAccount *CashAccount16 `xml:"DbtrAgtAcct,omitempty"`
// Party that owes an amount of money to the (ultimate) creditor.
Debtor *PartyIdentification32 `xml:"Dbtr"`
// Unambiguous identification of the account of the debtor to which a debit entry will be made as a result of the transaction.
DebtorAccount *CashAccount16 `xml:"DbtrAcct"`
// Ultimate party that owes an amount of money to the (ultimate) creditor.
UltimateDebtor *PartyIdentification32 `xml:"UltmtDbtr,omitempty"`
// Further information, related to the processing of the payment instruction, that may need to be acted upon by the creditor agent, depending on agreement between creditor and the creditor agent.
InstructionForCreditorAgent *Max140Text `xml:"InstrForCdtrAgt,omitempty"`
// Underlying reason for the payment transaction.
// Usage: Purpose is used by the end-customers, that is initiating party, (ultimate) debtor, (ultimate) creditor to provide information concerning the nature of the payment. Purpose is a content element, which is not used for processing by any of the agents involved in the payment chain.
Purpose *Purpose2Choice `xml:"Purp,omitempty"`
// Information needed due to regulatory and statutory requirements.
RegulatoryReporting []*RegulatoryReporting3 `xml:"RgltryRptg,omitempty"`
// Set of elements used to provide details on the tax.
Tax *TaxInformation3 `xml:"Tax,omitempty"`
// Set of elements used to provide information related to the handling of the remittance information by any of the agents in the transaction processing chain.
RelatedRemittanceInformation []*RemittanceLocation2 `xml:"RltdRmtInf,omitempty"`
// Information supplied to enable the matching of an entry with the items that the transfer is intended to settle, such as commercial invoices in an accounts' receivable system.
RemittanceInformation *RemittanceInformation5 `xml:"RmtInf,omitempty"`
}
func (d *DirectDebitTransactionInformation9) AddPaymentIdentification() *PaymentIdentification1 {
d.PaymentIdentification = new(PaymentIdentification1)
return d.PaymentIdentification
}
func (d *DirectDebitTransactionInformation9) AddPaymentTypeInformation() *PaymentTypeInformation20 {
d.PaymentTypeInformation = new(PaymentTypeInformation20)
return d.PaymentTypeInformation
}
func (d *DirectDebitTransactionInformation9) SetInstructedAmount(value, currency string) {
d.InstructedAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}
func (d *DirectDebitTransactionInformation9) SetChargeBearer(value string) {
d.ChargeBearer = (*ChargeBearerType1Code)(&value)
}
func (d *DirectDebitTransactionInformation9) AddDirectDebitTransaction() *DirectDebitTransaction6 {
d.DirectDebitTransaction = new(DirectDebitTransaction6)
return d.DirectDebitTransaction
}
func (d *DirectDebitTransactionInformation9) AddUltimateCreditor() *PartyIdentification32 {
d.UltimateCreditor = new(PartyIdentification32)
return d.UltimateCreditor
}
func (d *DirectDebitTransactionInformation9) AddDebtorAgent() *BranchAndFinancialInstitutionIdentification4 {
d.DebtorAgent = new(BranchAndFinancialInstitutionIdentification4)
return d.DebtorAgent
}
func (d *DirectDebitTransactionInformation9) AddDebtorAgentAccount() *CashAccount16 {
d.DebtorAgentAccount = new(CashAccount16)
return d.DebtorAgentAccount
}
func (d *DirectDebitTransactionInformation9) AddDebtor() *PartyIdentification32 {
d.Debtor = new(PartyIdentification32)
return d.Debtor
}
func (d *DirectDebitTransactionInformation9) AddDebtorAccount() *CashAccount16 {
d.DebtorAccount = new(CashAccount16)
return d.DebtorAccount
}
func (d *DirectDebitTransactionInformation9) AddUltimateDebtor() *PartyIdentification32 {
d.UltimateDebtor = new(PartyIdentification32)
return d.UltimateDebtor
}
func (d *DirectDebitTransactionInformation9) SetInstructionForCreditorAgent(value string) {
d.InstructionForCreditorAgent = (*Max140Text)(&value)
}
func (d *DirectDebitTransactionInformation9) AddPurpose() *Purpose2Choice {
d.Purpose = new(Purpose2Choice)
return d.Purpose
}
func (d *DirectDebitTransactionInformation9) AddRegulatoryReporting() *RegulatoryReporting3 {
newValue := new(RegulatoryReporting3)
d.RegulatoryReporting = append(d.RegulatoryReporting, newValue)
return newValue
}
func (d *DirectDebitTransactionInformation9) AddTax() *TaxInformation3 {
d.Tax = new(TaxInformation3)
return d.Tax
}
func (d *DirectDebitTransactionInformation9) AddRelatedRemittanceInformation() *RemittanceLocation2 {
newValue := new(RemittanceLocation2)
d.RelatedRemittanceInformation = append(d.RelatedRemittanceInformation, newValue)
return newValue
}
func (d *DirectDebitTransactionInformation9) AddRemittanceInformation() *RemittanceInformation5 {
d.RemittanceInformation = new(RemittanceInformation5)
return d.RemittanceInformation
} | DirectDebitTransactionInformation9.go | 0.767429 | 0.558026 | DirectDebitTransactionInformation9.go | starcoder |
package continuous
import (
gsl "github.com/jtejido/ggsl"
"github.com/jtejido/stats"
"github.com/jtejido/stats/err"
"math"
"math/rand"
)
// Assymetric Laplace distribution
// https://en.wikipedia.org/wiki/Asymmetric_Laplace_distribution
type AssymetricLaplace struct {
baseContinuousWithSource
location, scale, assymetry float64 // m, λ, κ
}
func NewAssymetricLaplace(m, λ, κ float64) (*AssymetricLaplace, error) {
return NewAssymetricLaplaceWithSource(m, λ, κ, nil)
}
func NewAssymetricLaplaceWithSource(m, λ, κ float64, src rand.Source) (*AssymetricLaplace, error) {
if λ <= 0 || κ <= 0 {
return nil, err.Invalid()
}
ret := new(AssymetricLaplace)
ret.location = m
ret.scale = λ
ret.assymetry = κ
ret.src = src
return ret, nil
}
func (al *AssymetricLaplace) String() string {
return "AssymetricLaplace: Parameters - " + al.Parameters().String() + ", Support(x) - " + al.Support().String()
}
func (al *AssymetricLaplace) Parameters() stats.Limits {
return stats.Limits{
"m": stats.Interval{math.Inf(-1), math.Inf(1), true, true},
"λ": stats.Interval{0, math.Inf(1), true, true},
"κ": stats.Interval{0, math.Inf(1), true, true},
}
}
// x ∈ (-∞,∞)
func (al *AssymetricLaplace) Support() stats.Interval {
return stats.Interval{math.Inf(-1), math.Inf(1), true, true}
}
func (al *AssymetricLaplace) Probability(x float64) float64 {
a := al.scale / (al.assymetry + 1/al.assymetry)
if x < al.location {
return a * math.Exp((al.scale/al.assymetry)*(x-al.location))
}
return a * math.Exp(-al.scale*al.assymetry*(x-al.location))
}
func (al *AssymetricLaplace) Distribution(x float64) float64 {
if x <= al.location {
return ((al.assymetry * al.assymetry) / (1 + (al.assymetry * al.assymetry))) * math.Exp((al.scale/al.assymetry)*(x-al.location))
}
return 1 - (1/(1+(al.assymetry*al.assymetry)))*math.Exp(-al.scale*al.assymetry*(x-al.location))
}
func (al *AssymetricLaplace) Inverse(p float64) float64 {
stats.NotImplementedError()
return math.NaN()
}
func (al *AssymetricLaplace) ExKurtosis() float64 {
k4 := al.assymetry * al.assymetry * al.assymetry * al.assymetry
k8 := k4 * al.assymetry * al.assymetry * al.assymetry * al.assymetry
return (6 * (1 + k8)) / math.Pow(1+k4, 2)
}
func (al *AssymetricLaplace) Skewness() float64 {
k4 := al.assymetry * al.assymetry * al.assymetry * al.assymetry
k6 := k4 * al.assymetry * al.assymetry
return (2 * (1 - k6)) / math.Pow(k4+1, 3./2)
}
func (al *AssymetricLaplace) Mean() float64 {
return al.location + ((1 - (al.assymetry * al.assymetry)) / (al.scale * al.assymetry))
}
func (al *AssymetricLaplace) Median() float64 {
return al.location + (al.assymetry/al.scale)*math.Log((1+(al.assymetry*al.assymetry))/(2*(al.assymetry*al.assymetry)))
}
func (al *AssymetricLaplace) Variance() float64 {
s2 := al.scale * al.scale
k2 := al.assymetry * al.assymetry
k4 := k2 * al.assymetry * al.assymetry * al.assymetry * al.assymetry
return (1 + k4) / (s2 * k2)
}
func (al *AssymetricLaplace) Entropy() float64 {
k2 := al.assymetry * al.assymetry
return math.Log(math.Exp((1 + k2) / (al.assymetry * al.scale)))
}
func (al *AssymetricLaplace) Rand() float64 {
var rnd float64
if al.src != nil {
rnd = rand.New(al.src).Float64()
} else {
rnd = rand.Float64()
}
s := gsl.Sign(rnd)
return al.location - (1/(al.scale*s*math.Pow(al.assymetry, s)))*math.Log(1-rnd*s*math.Pow(al.assymetry, s))
} | dist/continuous/assymetric_laplace.go | 0.775987 | 0.474692 | assymetric_laplace.go | starcoder |
package migrator
import (
"bytes"
"database/sql"
"fmt"
"math"
"reflect"
)
// BatchedInsert takes an array of SQL data rows and creates a series of
// batched inserts to insert the data into an existing sql.Tx (transaction)
// object.
func BatchedInsert(tx *sql.Tx, table string, data []SQLUntypedRow, size int, params *Parameters) error {
return BatchedQuery(tx, table, data, size, "INSERT", params)
}
// BatchedReplace takes an array of SQL data rows and creates a series of
// batched replaces to replace the data into an existing sql.Tx (transaction)
// object.
func BatchedReplace(tx *sql.Tx, table string, data []SQLUntypedRow, size int, params *Parameters) error {
return BatchedQuery(tx, table, data, size, "REPLACE", params)
}
// BatchedRemove takes an array of SQL data rows and creates a series of
// DELETE FROM statements to remove the data in an existing sql.Tx (transaction)
// object.
func BatchedRemove(tx *sql.Tx, table string, data []SQLUntypedRow, size int, params *Parameters) error {
debug := paramBool(*params, ParamDebug, false)
// Pull column names from first row
if len(data) < 1 {
return fmt.Errorf("BatchedRemove(): [%s] no data presented", table)
}
keys := reflect.ValueOf(data[0]).MapKeys()
if len(keys) < 1 {
return fmt.Errorf("BatchedRemove(): [%s] no columns presented", table)
}
if size < 1 {
size = 1
}
for i := 0; i < len(data); i++ {
params := make([]interface{}, 0)
// Header is always the same
prepared := new(bytes.Buffer)
prepared.WriteString("DELETE FROM")
prepared.WriteString(" `" + table + "` WHERE ")
for iter, k := range keys {
if iter != 0 {
prepared.WriteString(" AND ")
}
prepared.WriteString("`" + k.String() + "` = ?")
params = append(params, data[i][keys[iter].String()])
}
prepared.WriteString(";")
if debug {
logger.Debugf("BatchedRemove(): [%s] Prepared remove: %s", table, prepared.String())
}
// Attempt to execute
_, err := tx.Exec(prepared.String(), params...)
if err != nil {
logger.Errorf("BatchedRemove(): [%s] ERROR: %s", table, err.Error())
return err
}
}
return nil
}
// BatchedQuery takes an array of SQL data rows and creates a series of
// batched queries to insert/replace the data into an existing sql.Tx
// (transaction) object.
func BatchedQuery(tx *sql.Tx, table string, data []SQLUntypedRow, size int, op string, params *Parameters) error {
debug := paramBool(*params, ParamDebug, false)
lowLevelDebug := paramBool(*params, ParamLowLevelDebug, false)
// Pull column names from first row
if len(data) < 1 {
return fmt.Errorf("BatchedQuery(): [%s] no data presented", table)
}
keys := reflect.ValueOf(data[0]).MapKeys()
if len(keys) < 1 {
return fmt.Errorf("BatchedQuery(): [%s] no columns presented", table)
}
if size < 1 {
size = 1
}
batches := int(math.Ceil(float64(len(data)) / float64(size)))
for i := 0; i < batches; i++ {
params := make([]interface{}, 0)
// Header is always the same
prepared := new(bytes.Buffer)
switch op {
case "INSERT":
prepared.WriteString("INSERT INTO")
case "REPLACE":
prepared.WriteString("REPLACE INTO")
default:
}
prepared.WriteString(" `" + table + "` ( ")
for iter, k := range keys {
if iter != 0 {
prepared.WriteString(", ")
}
prepared.WriteString("`" + k.String() + "`")
}
prepared.WriteString(" ) VALUES")
// Create value clauses
for j := i * size; j < intmin((i+1)*size, len(data)); j++ {
if j > i*size {
prepared.WriteString(",")
}
prepared.WriteString(" ( ")
for l := 0; l < len(keys); l++ {
if l > 0 {
prepared.WriteString(",")
}
prepared.WriteString("?")
params = append(params, data[j][keys[l].String()])
}
prepared.WriteString(" ) ")
}
prepared.WriteString(";")
if debug {
logger.Debugf("BatchedQuery(): [%s] Prepared %s: %s", table, op, prepared.String())
}
// Attempt to execute
res, err := tx.Exec(prepared.String(), params...)
if lowLevelDebug {
logger.Tracef("BatchedQuery(): [%s] %s [%#v]", table, prepared.String(), params)
}
if debug {
lastInsertID, _ := res.LastInsertId()
rowsAffected, _ := res.RowsAffected()
logger.Debugf("BatchedQuery(): [%s] last id inserted = %d, rows affected = %d", table, lastInsertID, rowsAffected)
}
if err != nil {
logger.Errorf("BatchedQuery(): [%s] ERROR: %s", table, err.Error())
return err
}
}
return nil
} | batched_queries.go | 0.624408 | 0.510802 | batched_queries.go | starcoder |
package xxhash
const (
prime32x1 uint32 = 2654435761
prime32x2 uint32 = 2246822519
prime32x3 uint32 = 3266489917
prime32x4 uint32 = 668265263
prime32x5 uint32 = 374761393
prime64x1 uint64 = 11400714785074694791
prime64x2 uint64 = 14029467366897019727
prime64x3 uint64 = 1609587929392839161
prime64x4 uint64 = 9650029242287828579
prime64x5 uint64 = 2870177450012600261
maxInt32 int32 = (1<<31 - 1)
// precomputed zero Vs for seed 0
zero64x1 = 0x60ea27eeadc0b5d6
zero64x2 = 0xc2b2ae3d27d4eb4f
zero64x3 = 0x0
zero64x4 = 0x61c8864e7a143579
)
// Checksum32 returns the checksum of the input data with the seed set to 0.
func Checksum32(in []byte) uint32 {
return Checksum32S(in, 0)
}
// ChecksumString32 returns the checksum of the input data, without creating a copy, with the seed set to 0.
func ChecksumString32(s string) uint32 {
return ChecksumString32S(s, 0)
}
type XXHash32 struct {
mem [16]byte
ln, memIdx int32
v1, v2, v3, v4 uint32
seed uint32
}
// Size returns the number of bytes Sum will return.
func (xx *XXHash32) Size() int {
return 4
}
// BlockSize returns the hash's underlying block size.
// The Write method must be able to accept any amount
// of data, but it may operate more efficiently if all writes
// are a multiple of the block size.
func (xx *XXHash32) BlockSize() int {
return 16
}
// NewS32 creates a new hash.Hash32 computing the 32bit xxHash checksum starting with the specific seed.
func NewS32(seed uint32) (xx *XXHash32) {
xx = &XXHash32{
seed: seed,
}
xx.Reset()
return
}
// New32 creates a new hash.Hash32 computing the 32bit xxHash checksum starting with the seed set to 0.
func New32() *XXHash32 {
return NewS32(0)
}
func (xx *XXHash32) Reset() {
xx.v1 = xx.seed + prime32x1 + prime32x2
xx.v2 = xx.seed + prime32x2
xx.v3 = xx.seed
xx.v4 = xx.seed - prime32x1
xx.ln, xx.memIdx = 0, 0
}
// Sum appends the current hash to b and returns the resulting slice.
// It does not change the underlying hash state.
func (xx *XXHash32) Sum(in []byte) []byte {
s := xx.Sum32()
return append(in, byte(s>>24), byte(s>>16), byte(s>>8), byte(s))
}
// Checksum64 an alias for Checksum64S(in, 0)
func Checksum64(in []byte) uint64 {
return Checksum64S(in, 0)
}
// ChecksumString64 returns the checksum of the input data, without creating a copy, with the seed set to 0.
func ChecksumString64(s string) uint64 {
return ChecksumString64S(s, 0)
}
type XXHash64 struct {
v1, v2, v3, v4 uint64
seed uint64
ln uint64
mem [32]byte
memIdx int8
}
// Size returns the number of bytes Sum will return.
func (xx *XXHash64) Size() int {
return 8
}
// BlockSize returns the hash's underlying block size.
// The Write method must be able to accept any amount
// of data, but it may operate more efficiently if all writes
// are a multiple of the block size.
func (xx *XXHash64) BlockSize() int {
return 32
}
// NewS64 creates a new hash.Hash64 computing the 64bit xxHash checksum starting with the specific seed.
func NewS64(seed uint64) (xx *XXHash64) {
xx = &XXHash64{
seed: seed,
}
xx.Reset()
return
}
// New64 creates a new hash.Hash64 computing the 64bit xxHash checksum starting with the seed set to 0x0.
func New64() *XXHash64 {
return NewS64(0)
}
func (xx *XXHash64) Reset() {
xx.ln, xx.memIdx = 0, 0
xx.v1, xx.v2, xx.v3, xx.v4 = resetVs64(xx.seed)
}
// Sum appends the current hash to b and returns the resulting slice.
// It does not change the underlying hash state.
func (xx *XXHash64) Sum(in []byte) []byte {
s := xx.Sum64()
return append(in, byte(s>>56), byte(s>>48), byte(s>>40), byte(s>>32), byte(s>>24), byte(s>>16), byte(s>>8), byte(s))
}
// force the compiler to use ROTL instructions
func rotl32_1(x uint32) uint32 { return (x << 1) | (x >> (32 - 1)) }
func rotl32_7(x uint32) uint32 { return (x << 7) | (x >> (32 - 7)) }
func rotl32_11(x uint32) uint32 { return (x << 11) | (x >> (32 - 11)) }
func rotl32_12(x uint32) uint32 { return (x << 12) | (x >> (32 - 12)) }
func rotl32_13(x uint32) uint32 { return (x << 13) | (x >> (32 - 13)) }
func rotl32_17(x uint32) uint32 { return (x << 17) | (x >> (32 - 17)) }
func rotl32_18(x uint32) uint32 { return (x << 18) | (x >> (32 - 18)) }
func rotl64_1(x uint64) uint64 { return (x << 1) | (x >> (64 - 1)) }
func rotl64_7(x uint64) uint64 { return (x << 7) | (x >> (64 - 7)) }
func rotl64_11(x uint64) uint64 { return (x << 11) | (x >> (64 - 11)) }
func rotl64_12(x uint64) uint64 { return (x << 12) | (x >> (64 - 12)) }
func rotl64_18(x uint64) uint64 { return (x << 18) | (x >> (64 - 18)) }
func rotl64_23(x uint64) uint64 { return (x << 23) | (x >> (64 - 23)) }
func rotl64_27(x uint64) uint64 { return (x << 27) | (x >> (64 - 27)) }
func rotl64_31(x uint64) uint64 { return (x << 31) | (x >> (64 - 31)) }
func mix64(h uint64) uint64 {
h ^= h >> 33
h *= prime64x2
h ^= h >> 29
h *= prime64x3
h ^= h >> 32
return h
}
func resetVs64(seed uint64) (v1, v2, v3, v4 uint64) {
if seed == 0 {
return zero64x1, zero64x2, zero64x3, zero64x4
}
return (seed + prime64x1 + prime64x2), (seed + prime64x2), (seed), (seed - prime64x1)
}
// borrowed from cespare
func round64(h, v uint64) uint64 {
h += v * prime64x2
h = rotl64_31(h)
h *= prime64x1
return h
}
func mergeRound64(h, v uint64) uint64 {
v = round64(0, v)
h ^= v
h = h*prime64x1 + prime64x4
return h
} | vendor/github.com/elastic/beats/vendor/github.com/OneOfOne/xxhash/xxhash.go | 0.659515 | 0.424889 | xxhash.go | starcoder |
package testdata
import (
"errors"
"fmt"
"io"
)
func HelloWorld() string {
_ = len("hello")
return "Hello, World!"
} // total complexity = 0
func SimpleCond(n int) string { // want "cognitive complexity 1 of func SimpleCond is high \\(> 0\\)"
if n == 100 { // +1
return "a hundred"
}
return "others"
} // total complexity = 1
func IfElseNested(n int) string { // want "cognitive complexity 3 of func IfElseNested is high \\(> 0\\)"
if n == 100 { // +1
return "a hundred"
} else { // + 1
if n == 200 { // + 1
return "two hundred"
}
}
return "others"
} // total complexity = 3
func IfElseIfNested(n int) string { // want "cognitive complexity 3 of func IfElseIfNested is high \\(> 0\\)"
if n == 100 { // +1
return "a hundred"
} else if n < 300 { // + 1
if n == 200 { // + 1
return "two hundred"
}
}
return "others"
} // total complexity = 3
func SimpleLogicalSeq1(a, b, c, d bool) string { // want "cognitive complexity 2 of func SimpleLogicalSeq1 is high \\(> 0\\)"
if a && b && c && d { // +1 for `if`, +1 for `&&` sequence
return "ok"
}
return "not ok"
} // total complexity = 2
func SimpleLogicalSeq2(a, b, c, d bool) string { // want "cognitive complexity 2 of func SimpleLogicalSeq2 is high \\(> 0\\)"
if a || b || c || d { // +1 for `if`, +1 for `||` sequence
return "ok"
}
return "not ok"
} // total complexity = 2
func ComplexLogicalSeq1(a, b, c, d, e, f bool) string { // want "cognitive complexity 4 of func ComplexLogicalSeq1 is high \\(> 0\\)"
if a && b && c || d || e && f { // +1 for `if`, +3 for changing sequence of `&&` `||` `&&`
return "ok"
}
return "not ok"
} // total complexity = 4
func ComplexLogicalSeq2(a, b, c, d, e, f bool) string { // want "cognitive complexity 3 of func ComplexLogicalSeq2 is high \\(> 0\\)"
if a && !(b && c) { // +1 for `if`, +2 for having sequence of `&&` `&&` chain
return "ok"
}
return "not ok"
} // total complexity = 3
func GetWords(number int) string { // want "cognitive complexity 1 of func GetWords is high \\(> 0\\)"
switch number { // +1
case 1:
return "one"
case 2:
return "a couple"
case 3:
return "a few"
default:
return "lots"
}
} // Cognitive complexity = 1
func GetWords_Complex(number int) string { // want "cognitive complexity 4 of func GetWords_Complex is high \\(> 0\\)"
if number == 1 { // +1
return "one"
} else if number == 2 { // +1
return "a couple"
} else if number == 3 { // +1
return "a few"
} else { // +1
return "lots"
}
} // total complexity = 4
func SumOfPrimes(max int) int { // want "cognitive complexity 7 of func SumOfPrimes is high \\(> 0\\)"
var total int
OUT:
for i := 1; i < max; i++ { // +1
for j := 2; j < i; j++ { // +2 (nesting = 1)
if i%j == 0 { // +3 (nesting = 2)
continue OUT // +1
}
}
total += i
i = 0
}
return total
} // Cognitive complexity = 7
func FactRec(n int) int { // want "cognitive complexity 3 of func FactRec is high \\(> 0\\)"
if n <= 1 { // +1
return 1
} else { // +1
return n * FactRec(n-1) // +1
}
} // total complexity = 3
func FactLoop(n int) int { // want "cognitive complexity 1 of func FactLoop is high \\(> 0\\)"
total := 1
for n > 0 { // +1
total *= n
n--
}
return total
} // total complexity = 1
func DumpVal(w io.Writer, i interface{}) error { // want "cognitive complexity 1 of func DumpVal is high \\(> 0\\)"
switch v := i.(type) { // +1
case int:
fmt.Fprint(w, "int ", v)
case string:
fmt.Fprint(w, "string", v)
default:
return errors.New("unrecognized type")
}
return nil
} // total complexity = 1
func ForRange(a []int) int { // want "cognitive complexity 3 of func ForRange is high \\(> 0\\)"
var sum int
for _, v := range a { // +1
sum += v
if v%2 == 0 { // + 2 (nesting = 1)
sum += 1
}
}
return sum
} // total complexity = 3
func MyFunc(a bool) { // want "cognitive complexity 6 of func MyFunc is high \\(> 0\\)"
if a { // +1
for i := 0; i < 10; i++ { // +2 (nesting = 1)
n := 0
for n < 10 { // +3 (nesting = 2)
n++
}
}
}
} // total complexity = 6
func MyFunc2(a bool) { // want "cognitive complexity 2 of func MyFunc2 is high \\(> 0\\)"
x := func() { // +0 (but nesting level is now 1)
if a { // +2 (nesting = 1)
fmt.Fprintln(io.Discard, "true")
}
}
x()
} // total complexity = 2 | testdata/src/a/a.go | 0.744192 | 0.483039 | a.go | starcoder |
package timing
import (
"fmt"
"time"
)
// Span is a pair of times, representing the start and end of a process.
type Span struct {
// Start is the start time of the timespan.
Start time.Time `json:"start,omitempty"`
// End is the end time of the timespan.
End time.Time `json:"end,omitempty"`
}
// SpanFromInstant constructs a Span representing the instant in time t.
func SpanFromInstant(t time.Time) Span {
return Span{
Start: t,
End: t,
}
}
// SpanFromDuration constructs a Span from the start time start and duration d.
func SpanFromDuration(start time.Time, d time.Duration) Span {
return Span{
Start: start,
End: start.Add(d),
}
}
// SpanSince constructs a Span representing the period of time between start and now.
func SpanSince(start time.Time) Span {
return Span{
Start: start,
End: time.Now(),
}
}
// Duration gets the duration of the timespan.
// Duration is zero if either of the ends of the timespan are zero.
func (t *Span) Duration() time.Duration {
if t.IsUndefined() {
return 0
}
return t.End.Sub(t.Start)
}
// IsUndefined gets whether this span is ill-defined.
// This happens if either time is zero, or the end is before the start.
func (t *Span) IsUndefined() bool {
return t.Start.IsZero() || t.End.IsZero() || t.End.Before(t.Start)
}
// IsInstant gets whether this
func (t *Span) IsInstant() bool {
return t.Start.Equal(t.End)
}
// String retrieves a string representation of this timespan.
func (t Span) String() string {
switch {
case t.IsUndefined():
return "(undefined)"
case t.IsInstant():
return t.Start.Format(time.RFC3339)
default:
return fmt.Sprintf("%s (from %s to %s)", t.Duration(), t.Start.Format(time.RFC3339), t.End.Format(time.RFC3339))
}
}
// StartNoLaterThan moves this timespan's start to become start, if start is nonzero and before this timespan's current start.
func (t *Span) StartNoLaterThan(start time.Time) {
if t.Start.IsZero() || (!start.IsZero() && start.Before(t.Start)) {
t.Start = start
}
}
// EndNoEarlierThan moves this timespan's end to become end, if end is nonzero and after this timespan's current end.
func (t *Span) EndNoEarlierThan(end time.Time) {
if t.End.IsZero() || (!end.IsZero() && end.After(t.End)) {
t.End = end
}
}
// Union sets this timespan's start to other's start if it is earlier, and its end to other's end if it is later.
func (t *Span) Union(other Span) {
t.StartNoLaterThan(other.Start)
t.EndNoEarlierThan(other.End)
}
// MockDate is an arbitrary date useful for timespan tests.
var MockDate = time.Date(1997, time.May, 1, 21, 0, 0, 0, time.UTC) | internal/timing/span.go | 0.829181 | 0.504394 | span.go | starcoder |
package metrics_metadata
// Metadata for an individual result of the metrics metadata query
type Metric struct {
// Name of the metric that has the retrieved metadata
Name string `json:"name,omitempty"`
// Description of the metric that has the retrieved metadata. You can use up to 1024 UTF-8 characters.
Description string `json:"description,omitempty"`
// Metric type of the metric that has the retrieved metadata. The possible values are \"GAUGE\", \"COUNTER\", and \"CUMULATIVE_COUNTER\".
Type string `json:"type,omitempty"`
// Dimension metadata for the result object, in the form of a JSON object (dictionary). Each property is a dimension name and dimension value. Dimension names and values have these requirements: <br> **Name:** * UTF-8 string, maximum length of 128 characters (512 bytes) * Must start with an uppercase or lowercase letter. The rest of the name can contain letters, numbers, underscores (`_`) and hyphens (`-`). * Must not start with the underscore character (`_`) * Must not start with the prefix `sf_`, except for dimensions defined by SignalFx such as `sf_hires` * Must not start with the prefix `aws_` <br> **Value:** * String: Maximum length 256 UTF-8 characters (1024 bytes) * Integer or float: Maximum length 8192 bits (1024 bytes)
Dimensions map[string]interface{} `json:"dimensions,omitempty"`
// Custom property metadata for the result object, in the form of a JSON object (dictionary). Each property is a custom property name and value. Custom property names and values have these requirements <br> **Name:** * UTF-8 string, maximum length of 128 characters (512 bytes) * Must start with an uppercase or lowercase letter. The rest of the name can contain letters, numbers, underscores (`_`) and hyphens (`-`). * Must not start with the underscore character (`_`) <br> **Value:** * String: Maximum length 256 UTF-8 characters (1024 bytes) * Integer or float: Maximum length 8192 bits (1024 bytes)
CustomProperties map[string]string `json:"customProperties,omitempty"`
// Tag metadata in the response, in the form of a JSON array (a list) with one element for each tag. Each tag is a UTF-8 string, starting with an uppercase or lowercase alphabetic character. The maximum length is expressed in characters; if a string consists solely of single-byte UTF-8 entities, 1024 characters are available. <br>
Tags []string `json:"tags,omitempty"`
// The time that the metric was created, in Unix time UTC-relative
Created int64 `json:"created,omitempty"`
// SignalFx ID of the user who created the metric. If the value is \"AAAAAAAAAAA\", SignalFx created the metric.
Creator string `json:"creator,omitempty"`
// The time that the metric was last updated, in Unix time UTC-relative
LastUpdated int64 `json:"lastUpdated,omitempty"`
// SignalFx ID of the user who last updated the metric. If the value is \"AAAAAAAAAAA\", SignalFx last updated the metric.
LastUpdatedBy string `json:"lastUpdatedBy,omitempty"`
} | metrics_metadata/model_metric.go | 0.877451 | 0.462898 | model_metric.go | starcoder |
package zgeo
import (
"image"
"math"
)
type Rect struct {
Pos Pos `json:"pos"`
Size Size `json:"size"`
}
func RectMake(x0, y0, x1, y1 float64) Rect {
r := Rect{}
r.Pos.X = x0
r.Pos.Y = y0
r.Size.W = x1 - x0
r.Size.H = y1 - y0
return r
}
func RectFromXYWH(x, y, w, h float64) Rect {
return Rect{Pos{x, y}, Size{w, h}}
}
func RectFromMinMax(min, max Pos) Rect {
return Rect{min, max.Minus(min).Size()}
}
func RectFromCenterSize(center Pos, size Size) Rect {
return Rect{Size: size}.Centered(center)
}
func RectFromXY2(x, y, x2, y2 float64) Rect {
return Rect{Pos{x, y}, Size{x2 - x, y2 - y}}
}
func RectFromWH(w, h float64) Rect {
return Rect{Size: Size{w, h}}
}
var RectNull Rect
func (r Rect) IsNull() bool {
return r.Pos.X == 0 && r.Pos.Y == 0 && r.Size.W == 0 && r.Size.H == 0
}
func (r Rect) GoRect() image.Rectangle {
return image.Rectangle{Min: r.Min().GoPoint(), Max: r.Max().GoPoint()}
}
func RectFromGoRect(rect image.Rectangle) Rect {
return RectFromMinMax(PosFromGoPoint(rect.Min), PosFromGoPoint(rect.Max))
}
func (r Rect) TopLeft() Pos { return r.Min() }
func (r Rect) TopRight() Pos { return Pos{r.Max().X, r.Min().Y} }
func (r Rect) BottomLeft() Pos { return Pos{r.Min().X, r.Max().Y} }
func (r Rect) BottomRight() Pos { return r.Max() }
func (r Rect) Max() Pos {
return Pos{r.Pos.X + r.Size.W, r.Pos.Y + r.Size.H}
}
func (r *Rect) SetMax(max Pos) {
r.Size.W = max.X - r.Pos.X
r.Size.H = max.Y - r.Pos.Y
}
// func (r *Rect) SetMaxAsPos(max Pos) {
// r.Size.W = max.X - r.Pos.X
// r.Size.H = max.Y - r.Pos.Y
// }
func (r Rect) Min() Pos {
return r.Pos
}
func (r *Rect) SetMin(min Pos) {
r.Size.W += (r.Pos.X - min.X)
r.Size.H += (r.Pos.Y - min.Y)
r.Pos = min
}
func (r *Rect) SetMaxX(x float64) {
r.Size.W = x - r.Pos.X
}
func (r *Rect) SetMaxY(y float64) {
r.Size.H = y - r.Pos.Y
}
func (r *Rect) SetMinX(x float64) {
r.Size.W += (r.Pos.X - x)
r.Pos.X = x
}
func (r *Rect) SetMinY(y float64) {
r.Size.H += (r.Pos.Y - y)
r.Pos.Y = y
}
func (r Rect) Center() Pos {
return r.Pos.Plus(r.Size.DividedByD(2).Pos())
}
func (r *Rect) SetCenter(c Pos) {
r.Pos = c.Minus(r.Size.Pos().DividedByD(2))
}
func MergeAll(rects []Rect) []Rect {
var merged = true
var rold = rects
for merged {
var rnew []Rect
merged = false
for i, r := range rold {
var used = false
for j := i + 1; j < len(rold); j++ {
if r.Overlaps(rold[j].ExpandedD(4)) {
var n = rects[i]
n = n.UnionedWith(rold[j])
rnew = append(rnew, n)
merged = true
used = true
}
}
if !used {
rnew = append(rnew, r)
}
}
rold = rnew
}
return rold
}
func (r Rect) ExpandedD(n float64) Rect {
return r.Expanded(SizeBoth(n))
}
func (r Rect) Centered(center Pos) Rect {
return Rect{center.Minus(r.Size.Pos().DividedByD(2)), r.Size}
}
func (r Rect) Expanded(s Size) Rect {
r2 := Rect{Pos: r.Pos.Minus(s.Pos()), Size: r.Size.Plus(s.TimesD(2))}
// zlog.Info("r.Expand:", r, s, r2)
return r2
}
// AlignmentTransform moves right if Left, left if Right, or shrinks in Center
func (r Rect) AlignmentTransform(s Size, a Alignment) Rect {
if a&Left != 0 {
r.Pos.X += s.W
} else if a&Right != 0 {
r.Pos.X -= s.W
} else if a&HorCenter != 0 {
r.SetMinX(r.Min().X + s.W)
r.SetMaxX(r.Max().X - s.W)
}
if a&Top != 0 {
r.Pos.Y += s.H
} else if a&Bottom != 0 {
r.Pos.Y -= s.H
} else if a&VertCenter != 0 {
r.SetMinY(r.Min().Y + s.H)
r.SetMaxY(r.Max().Y - s.H)
}
return r
}
func (r Rect) Overlaps(rect Rect) bool {
min := r.Min()
max := r.Max()
rmin := rect.Min()
rmax := rect.Max()
return rmin.X < max.X && rmin.Y < max.Y && rmax.X > min.X && rmax.Y > min.Y
}
func (r Rect) Intersected(rect Rect) Rect {
max := r.Max().Min(rect.Max())
min := r.Min().Max(rect.Min())
return RectFromMinMax(min, max)
}
func (r Rect) Contains(pos Pos) bool {
min := r.Min()
max := r.Max()
return pos.X >= min.X && pos.X <= max.X && pos.Y >= min.Y && pos.Y <= max.Y
}
func (r Rect) Align(s Size, align Alignment, marg Size) Rect {
return r.AlignPro(s, align, marg, Size{}, Size{})
}
func (r Rect) AlignPro(s Size, align Alignment, marg, maxSize, minSize Size) Rect {
var x float64
var y float64
var scalex float64
var scaley float64
var wa = float64(s.W)
var wf = float64(r.Size.W)
if align&MarginIsOffset == 0 {
wf -= float64(marg.W)
if align&HorCenter != 0 {
wf -= float64(marg.W)
}
}
// }
var ha = float64(s.H)
var hf = float64(r.Size.H)
// if (align & (VertShrink|VertExpand)) {
if align&MarginIsOffset == 0 {
hf -= float64(marg.H * 2.0)
}
if align&HorExpand != 0 && align&VertExpand != 0 {
if align&Proportional == 0 {
wa = wf
ha = hf
} else {
// zlog.Assert(align&HorOut != 0, align) what does this do?
scalex = wf / wa
scaley = hf / ha
if scalex > 1 || scaley > 1 {
if scalex < scaley {
wa = wf
ha *= scalex
} else {
ha = hf
wa *= scaley
}
}
}
} else if align&Proportional == 0 {
if align&HorExpand != 0 && wa < wf {
wa = wf
} else if align&VertExpand != 0 && ha < hf {
ha = hf
}
}
if align&HorShrink != 0 && align&VertShrink != 0 && align&Proportional != 0 {
scalex = wf / wa
scaley = hf / ha
if align&HorOut != 0 && align&VertOut != 0 {
if scalex < 1 || scaley < 1 {
if scalex > scaley {
wa = wf
ha *= scalex
} else {
ha = hf
wa *= scaley
}
}
} else {
if scalex < 1 || scaley < 1 {
if scalex < scaley {
wa = wf
ha *= scalex
} else {
ha = hf
wa *= scaley
}
}
}
} else if align&HorShrink != 0 && wa > wf {
wa = wf
}
// else
if align&VertShrink != 0 && ha > hf {
ha = hf
}
if maxSize.W != 0 && maxSize.H != 0 { // TODO: && align&Proportional != 0 {
s := Size{wa, ha}.ShrunkInto(maxSize)
wa = s.W
ha = s.H
}
if maxSize.W != 0.0 {
wa = math.Min(wa, float64(maxSize.W))
}
if maxSize.H != 0.0 {
ha = math.Min(ha, float64(maxSize.H))
}
if minSize.W != 0 && minSize.H != 0 && align&Proportional != 0 {
s := Size{wa, ha}.ExpandedInto(minSize)
wa = s.W
ha = s.H
}
if minSize.W != 0.0 {
wa = math.Max(wa, float64(minSize.W))
}
if minSize.H != 0.0 {
ha = math.Max(ha, float64(minSize.H))
}
if align&HorOut != 0 {
if align&Left != 0 {
x = float64(r.Pos.X - marg.W - s.W)
} else if align&HorCenter != 0 {
// x = float64(Pos.X) - wa / 2.0
x = float64(r.Pos.X) + (wf-wa)/2.0
} else {
x = float64(r.Max().X + marg.W)
}
} else {
if align&Left != 0 {
x = float64(r.Pos.X + marg.W)
} else if align&Right != 0 {
x = float64(r.Max().X) - wa - float64(marg.W)
} else {
x = float64(r.Pos.X)
if align&MarginIsOffset == 0 {
x += float64(marg.W)
}
x = x + (wf-wa)/2.0
if align&MarginIsOffset != 0 {
x += float64(marg.W)
}
}
}
if align&VertOut != 0 {
if align&Top != 0 {
y = float64(r.Pos.Y-marg.H) - ha
} else if align&VertCenter != 0 {
y = float64(r.Pos.Y) + (hf-ha)/2.0
} else {
y = float64(r.Max().Y + marg.H)
}
} else {
if align&Top != 0 {
y = float64(r.Pos.Y + marg.H)
} else if align&Bottom != 0 {
y = float64(r.Max().Y) - ha - float64(marg.H)
} else {
y = float64(r.Pos.Y)
if align&MarginIsOffset == 0 {
y += float64(marg.H)
}
y = y + math.Max(0.0, hf-ha)/2.0
if align&MarginIsOffset != 0 {
y += float64(marg.H)
}
}
}
return Rect{Pos{x, y}, Size{wa, ha}}
}
func (r Rect) MovedInto(rect Rect) (m Rect) {
m = r
m.Pos.X = math.Max(r.Pos.X, rect.Pos.X)
m.Pos.Y = math.Max(r.Pos.Y, rect.Pos.Y)
min := m.Max().Min(rect.Max())
m.Pos.Add(min.Minus(m.Max()))
return
}
/* #kotlin-raw:
fun copy() : Rect {
var r = SetRect()
r.pos = Pos.copy()
r.size = Size.copy()
return r
}
*/
// Dummy function, but if translated(?) to kotlin needed to actually copy rect, not make reference
func (r Rect) Copy() Rect {
return r
}
func (r Rect) UnionedWith(rect Rect) Rect {
if !rect.IsNull() {
if r.IsNull() {
r.Pos = rect.Pos.Copy()
r.Size = rect.Size.Copy()
} else {
min := r.Min()
max := r.Max()
rmin := rect.Min()
rmax := rect.Max()
if rmin.X < min.X {
r.SetMinX(rmin.X)
}
if rmin.Y < min.Y {
r.SetMinY(rmin.Y)
}
if rmax.X > max.X {
r.SetMaxX(rmax.X)
}
if rmax.Y > max.Y {
r.SetMaxY(rmax.Y)
}
}
}
return r
}
func (r *Rect) UnionWithPos(pos Pos) {
if r.IsNull() {
r.Pos = pos
return
}
min := r.Min()
max := r.Max()
if pos.X > max.X {
r.SetMaxX(pos.X)
}
if pos.Y > max.Y {
r.SetMaxY(pos.Y)
}
if pos.X < min.X {
r.SetMinX(pos.X)
}
if pos.Y < min.Y {
r.SetMinY(pos.Y)
}
}
func (r Rect) Plus(a Rect) Rect { return RectFromMinMax(r.Pos.Plus(a.Pos), r.Max().Plus(a.Max())) }
func (r Rect) PlusPos(pos Pos) Rect { n := r; n.Pos.Add(pos); return n }
func (r Rect) Minus(a Rect) Rect { return RectFromMinMax(r.Pos.Minus(a.Pos), r.Max().Minus(a.Max())) }
func (r Rect) DividedBy(a Size) Rect {
return RectFromMinMax(r.Min().DividedBy(a.Pos()), r.Max().DividedBy(a.Pos()))
}
func (r Rect) TimesD(d float64) Rect {
return RectFromMinMax(r.Min().TimesD(d), r.Max().TimesD(d))
}
func (r *Rect) Add(a Rect) { r.SetMin(r.Min().Plus(a.Pos)); r.SetMax(r.Max().Plus(a.Max())) }
func (r *Rect) AddPos(a Pos) { r.Pos.Add(a) }
func (r *Rect) Subtract(a Pos) { r.Pos.Subtract(a) }
func centerToRect(center Pos, radius float64, radiusy float64) Rect {
var s = Size{radius, radius}
if radiusy != 0 {
s.H = radiusy
}
return Rect{center.Minus(s.Pos()), s.TimesD(2.0)}
}
func (r *Rect) ExpandedToInt() Rect {
var ir Rect
ir.Pos.X = math.Floor(r.Pos.X)
ir.Pos.Y = math.Floor(r.Pos.Y)
ir.Size.W = math.Ceil(r.Size.W)
ir.Size.H = math.Ceil(r.Size.H)
return ir
}
// Swapped returns a Rect where the vertical and horizontal components are swapped
func (r Rect) Swapped() Rect {
return Rect{Pos: r.Pos.Swapped(), Size: r.Size.Swapped()}
} | zgeo/rect.go | 0.79158 | 0.579579 | rect.go | starcoder |
package lexing
import (
"sort"
"strings"
"github.com/efritz/gostgres/internal/syntax/tokens"
)
type tokenSequenceReplacement struct {
pattern []tokens.TokenType
replacement tokens.TokenType
}
var tokenSequenceReplacements = []tokenSequenceReplacement{
{[]tokens.TokenType{tokens.TokenTypeNot, tokens.TokenTypeLike}, tokens.TokenTypeNotLike},
{[]tokens.TokenType{tokens.TokenTypeNot, tokens.TokenTypeILike}, tokens.TokenTypeNotILike},
{[]tokens.TokenType{tokens.TokenTypeNot, tokens.TokenTypeBetween}, tokens.TokenTypeNotBetween},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeTrue}, tokens.TokenTypeIsTrue},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeNot, tokens.TokenTypeTrue}, tokens.TokenTypeIsNotTrue},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeFalse}, tokens.TokenTypeIsFalse},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeNot, tokens.TokenTypeFalse}, tokens.TokenTypeIsNotFalse},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeNull}, tokens.TokenTypeIsNull},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeNot, tokens.TokenTypeNull}, tokens.TokenTypeIsNotNull},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeKwUnknown}, tokens.TokenTypeIsUnknown},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeNot, tokens.TokenTypeKwUnknown}, tokens.TokenTypeIsNotUnknown},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeDistinct, tokens.TokenTypeFrom}, tokens.TokenTypeIsDistinctFrom},
{[]tokens.TokenType{tokens.TokenTypeIs, tokens.TokenTypeNot, tokens.TokenTypeDistinct, tokens.TokenTypeFrom}, tokens.TokenTypeIsNotDistinctFrom},
{[]tokens.TokenType{tokens.TokenTypeBetween, tokens.TokenTypeSymmetric}, tokens.TokenTypeBetweenSymmetric},
{[]tokens.TokenType{tokens.TokenTypeNot, tokens.TokenTypeBetween, tokens.TokenTypeSymmetric}, tokens.TokenTypeNotBetweenSymmetric},
}
func init() {
sort.Slice(tokenSequenceReplacements, func(i, j int) bool {
return len(tokenSequenceReplacements[j].pattern) < len(tokenSequenceReplacements[i].pattern)
})
}
func Lex(text string) (filteredTokens []tokens.Token) {
lexer := newLexer(text)
bufferSize := 0
for _, re := range tokenSequenceReplacements {
if bufferSize < len(re.pattern) {
bufferSize = len(re.pattern)
}
}
var buffer []tokens.Token
for {
for len(buffer) < bufferSize {
if token := lexer.next(); token.Type != tokens.TokenTypeWhitespace {
buffer = append(buffer, hydrateKeywords(token))
}
}
token, hasToken, newBuffer, ok := processBuffer(buffer)
if !ok {
break
}
if hasToken {
filteredTokens = append(filteredTokens, token)
}
buffer = newBuffer
}
return filteredTokens
}
func hydrateKeywords(token tokens.Token) tokens.Token {
if token.Type == tokens.TokenTypeIdent {
if tokenType, ok := keywordSet[strings.ToLower(token.Text)]; ok {
token.Type = tokenType
}
}
return token
}
func processBuffer(buffer []tokens.Token) (tokens.Token, bool, []tokens.Token, bool) {
if buffer[0].Type == tokens.TokenTypeEOF {
return tokens.Token{}, false, nil, false
}
var bufferTypes []tokens.TokenType
for _, t := range buffer {
bufferTypes = append(bufferTypes, t.Type)
}
for _, re := range tokenSequenceReplacements {
matches := true
for i, t := range re.pattern {
if bufferTypes[i] != t {
matches = false
}
}
if !matches {
continue
}
texts := make([]string, 0, len(re.pattern))
for i := range re.pattern {
texts = append(texts, buffer[i].Text)
}
token := tokens.Token{
Type: re.replacement,
Offset: buffer[0].Offset,
Text: strings.Join(texts, " "),
}
return token, true, buffer[len(re.pattern):], true
}
return buffer[0], true, buffer[1:], true
} | internal/syntax/lexing/lex.go | 0.599251 | 0.520679 | lex.go | starcoder |
package api
import (
"net/url"
"strconv"
"github.com/nexucis/grafana-go-client/api/types"
"github.com/nexucis/grafana-go-client/grafanahttp"
)
type QueryParamAnnotation struct {
grafanahttp.QueryInterface
// epoch datetime in milliseconds. Optional.
From int64
// epoch datetime in milliseconds. Optional.
To int64
// number. Optional. Find annotations created by a specific user
UserID int64
// number. Optional. Find annotations for a specified alert.
AlertID int64
// number. Optional. Find annotations that are scoped to a specific dashboard
DashboardID int64
// number. Optional. Find annotations that are scoped to a specific panel
PanelID int64
// string. Optional. Use this to filter global annotations. Global annotations are annotations from an annotation data source that are not connected specifically to a dashboard or panel
Tags []string
// string. Optional. alert|annotation Return alerts or user created annotations
AnnotationType types.AnnotationQueryType
// number. Optional - default is 100. Max limit for results returned.
Limit int64
}
func (q *QueryParamAnnotation) GetValues() url.Values {
values := make(url.Values)
if q.From > 0 {
values["from"] = append(values["from"], strconv.FormatInt(q.From, 10))
}
if q.To > 0 {
values["to"] = append(values["to"], strconv.FormatInt(q.To, 10))
}
if q.UserID > 0 {
values["userId"] = append(values["userId"], strconv.FormatInt(q.UserID, 10))
}
if q.AlertID > 0 {
values["alertId"] = append(values["alertId"], strconv.FormatInt(q.AlertID, 10))
}
if q.DashboardID > 0 {
values["dashboardId"] = append(values["dashboardId"], strconv.FormatInt(q.DashboardID, 10))
}
if q.PanelID > 0 {
values["panelId"] = append(values["panelId"], strconv.FormatInt(q.PanelID, 10))
}
if q.Limit > 0 {
values["limit"] = append(values["limit"], strconv.FormatInt(q.Limit, 10))
}
if len(q.AnnotationType) > 0 {
values["type"] = append(values["type"], string(q.AnnotationType))
}
if len(q.Tags) > 0 {
values["tags"] = append(values["tags"], q.Tags...)
}
return values
}
type QueryParamAlert struct {
grafanahttp.QueryInterface
// Limit response to alert for a specified panel on a dashboard.
PanelID int64
// Limit response to X number of alerts.
Limit int64
// Limit response to alerts having a name like this value
Query string
// Limit response to alerts having a dashboard name like this value.
DashboardQuery string
// Return alerts with one or more of the alert states. You can specify multiple state
States []types.AlertState
// Limit response to alerts in specified dashboard(s). You can specify multiple dashboards
DashboardIDs []int64
// Limit response to alerts of dashboards in specified folder(s).You can specify multiple folders
FolderIDs []int64
// Limit response to alerts of dashboards with specified tags. To do an “AND” filtering with multiple tags, specify the tags parameter multiple times.
DashboardTags []string
}
func (q *QueryParamAlert) GetValues() url.Values {
values := make(url.Values)
if q.PanelID > 0 {
values["panelId"] = append(values["panelId"], strconv.FormatInt(q.PanelID, 10))
}
if len(q.DashboardQuery) > 0 {
values["dashboardQuery"] = append(values["dashboardQuery"], q.DashboardQuery)
}
if len(q.Query) > 0 {
values["query"] = append(values["query"], q.Query)
}
if q.Limit > 0 {
values["limit"] = append(values["limit"], strconv.FormatInt(q.Limit, 10))
}
if len(q.States) > 0 {
for _, state := range q.States {
values["state"] = append(values["state"], string(state))
}
}
if len(q.DashboardIDs) > 0 {
for _, dashboardID := range q.DashboardIDs {
values["dashboardId"] = append(values["dashboardId"], strconv.FormatInt(dashboardID, 10))
}
}
if len(q.FolderIDs) > 0 {
for _, folderID := range q.FolderIDs {
values["folderId"] = append(values["folderId"], strconv.FormatInt(folderID, 10))
}
}
if len(q.DashboardTags) > 0 {
values["dashboardTag"] = append(values["dashboardTag"], q.DashboardTags...)
}
return values
}
type QueryParameterUsers struct {
grafanahttp.QueryInterface
// The number of user per page
PerPage int64
// The number of the page querying
Page int64
// Limit response to user having a similar name, login or email like this value.
Query string
}
func (q *QueryParameterUsers) GetValues() url.Values {
values := make(url.Values)
if q.Page > 0 {
values["page"] = append(values["page"], strconv.FormatInt(q.Page, 10))
}
if q.PerPage > 0 {
values["perpage"] = append(values["perpage"], strconv.FormatInt(q.PerPage, 10))
}
if len(q.Query) > 0 {
values["query"] = append(values["query"], q.Query)
}
return values
}
type QueryParameterTeams struct {
grafanahttp.QueryInterface
// The number of team per page
PerPage int64
// The number of the page querying
Page int64
// Limit response to team having a name like this value.
Query string
// Limit response to the team having a name that matches exactly this value
Name string
}
func (q *QueryParameterTeams) GetValues() url.Values {
values := make(url.Values)
if q.PerPage > 0 {
values["perpage"] = append(values["perpage"], strconv.FormatInt(q.PerPage, 10))
}
if len(q.Name) > 0 {
values["name"] = append(values["name"], q.Name)
}
if len(q.Query) > 0 {
values["query"] = append(values["query"], q.Query)
}
if q.Page > 0 {
values["page"] = append(values["page"], strconv.FormatInt(q.Page, 10))
}
return values
}
type QueryParameterOrgs struct {
grafanahttp.QueryInterface
Name string
Query string
}
func (q *QueryParameterOrgs) GetValues() url.Values {
values := make(url.Values)
if len(q.Query) > 0 {
values["query"] = append(values["query"], q.Query)
}
if len(q.Name) > 0 {
values["name"] = append(values["name"], q.Name)
}
return values
}
type QueryParameterPlaylist struct {
grafanahttp.QueryInterface
// Limit response to X number of playlist.
Limit int64
// Limit response to playlist having a name like this value.
Query string
}
func (q *QueryParameterPlaylist) GetValues() url.Values {
values := make(url.Values)
if len(q.Query) > 0 {
values["query"] = append(values["query"], q.Query)
}
if q.Limit > 0 {
values["limit"] = append(values["limit"], strconv.FormatInt(q.Limit, 10))
}
return values
}
type QueryParameterSearch struct {
grafanahttp.QueryInterface
// search by title
Query string
// List of tags to search
Tags []string
// Type to search for, dash-folder or dash-db
SearchType types.SearchType
// List of dashboard id’s to search
DashboardIDs []int64
// List of folder id’s to search in for dashboards
FolderIDs []int64
// Flag indicating if only starred Dashboards should be returned
Starred bool
Limit int
Permission types.PermissionTypeAsString
}
func (q *QueryParameterSearch) GetValues() url.Values {
values := make(url.Values)
if len(q.Query) > 0 {
values["query"] = append(values["query"], q.Query)
}
if q.Tags != nil {
values["tag"] = append(values["tag"], q.Tags...)
}
if len(q.SearchType) > 0 {
values["type"] = append(values["type"], string(q.SearchType))
}
if len(q.DashboardIDs) > 0 {
for _, id := range q.DashboardIDs {
values["dashboardIds"] = append(values["dashboardIds"], strconv.FormatInt(id, 10))
}
}
if len(q.FolderIDs) > 0 {
for _, id := range q.FolderIDs {
values["folderIds"] = append(values["folderIds"], strconv.FormatInt(id, 10))
}
}
values["starred"] = append(values["starred"], strconv.FormatBool(q.Starred))
if q.Limit > 0 {
values["limit"] = append(values["limit"], strconv.Itoa(q.Limit))
}
if len(q.Permission) > 0 {
values["permission"] = append(values["permission"], string(q.Permission))
}
return values
} | api/query.go | 0.741861 | 0.490053 | query.go | starcoder |
package layer
import tf "github.com/galeone/tensorflow/tensorflow/go"
type LNormalization struct {
axis float64
dtype DataType
inputs []Layer
mean interface{}
name string
shape tf.Shape
trainable bool
variance interface{}
layerWeights []*tf.Tensor
}
func Normalization() *LNormalization {
return &LNormalization{
axis: -1,
dtype: Float32,
mean: nil,
name: UniqueName("normalization"),
trainable: true,
variance: nil,
}
}
func (l *LNormalization) SetAxis(axis float64) *LNormalization {
l.axis = axis
return l
}
func (l *LNormalization) SetDtype(dtype DataType) *LNormalization {
l.dtype = dtype
return l
}
func (l *LNormalization) SetMean(mean interface{}) *LNormalization {
l.mean = mean
return l
}
func (l *LNormalization) SetName(name string) *LNormalization {
l.name = name
return l
}
func (l *LNormalization) SetShape(shape tf.Shape) *LNormalization {
l.shape = shape
return l
}
func (l *LNormalization) SetTrainable(trainable bool) *LNormalization {
l.trainable = trainable
return l
}
func (l *LNormalization) SetVariance(variance interface{}) *LNormalization {
l.variance = variance
return l
}
func (l *LNormalization) SetLayerWeights(layerWeights []*tf.Tensor) *LNormalization {
l.layerWeights = layerWeights
return l
}
func (l *LNormalization) GetShape() tf.Shape {
return l.shape
}
func (l *LNormalization) GetDtype() DataType {
return l.dtype
}
func (l *LNormalization) SetInputs(inputs ...Layer) Layer {
l.inputs = inputs
return l
}
func (l *LNormalization) GetInputs() []Layer {
return l.inputs
}
func (l *LNormalization) GetName() string {
return l.name
}
func (l *LNormalization) GetLayerWeights() []*tf.Tensor {
return l.layerWeights
}
type jsonConfigLNormalization struct {
ClassName string `json:"class_name"`
Name string `json:"name"`
Config map[string]interface{} `json:"config"`
InboundNodes [][][]interface{} `json:"inbound_nodes"`
}
func (l *LNormalization) GetKerasLayerConfig() interface{} {
inboundNodes := [][][]interface{}{
{},
}
for _, input := range l.inputs {
inboundNodes[0] = append(inboundNodes[0], []interface{}{
input.GetName(),
0,
0,
map[string]bool{},
})
}
return jsonConfigLNormalization{
ClassName: "Normalization",
Name: l.name,
Config: map[string]interface{}{
"axis": l.axis,
"dtype": l.dtype.String(),
"mean": l.mean,
"name": l.name,
"trainable": l.trainable,
"variance": l.variance,
},
InboundNodes: inboundNodes,
}
}
func (l *LNormalization) GetCustomLayerDefinition() string {
return ``
} | layer/Normalization.go | 0.752468 | 0.412589 | Normalization.go | starcoder |
package definitions
type (
// System is the main node, obiously
System struct {
// SystemType may be Solitary or Multiple
SystemType string `valid:"alpha,lowercase,in(solitary|multiple)"`
NumberOfStars int `valid:"numeric"`
// CompanionOrbits lists the number of Orbits
CompanionOrbits OrbitData
// Bodies in a System are Stars
Bodies []Star
}
// OrbitData tracks Data for additional Orbits
OrbitData struct {
// Orbits is the number of Orbits
Orbits int `valid:"numeric"`
// Type can be either close or far
Type string `valid:"alpha,lowercase,in(close|far|normal)"`
// FarCompanionDistance holds a distance in AU for any far Orbits
FarCompanionDistance int `valid:"numeric"`
/*
NOTE:
Any star system with small massive stars, such as a white dwarf, within 2au of the primary will be a candidate for
periodic novas. The more massive smaller star leaches stellar material from it‘s less dense companion. As the gas
is compressed and heated on or near the surface of the smaller star nuclear fusion of the material will occur,
blasting the shell of gas away in a violent nova explosion.
In such a system the close orbit planets and perhaps even the outer planets may be striped of their atmospheres.
Life as we know it on the surface of such worlds will be impossible.
Very close stars may be physically touching, making for a very interesting display.
*/
}
// Star is a singular Star in a System, which may have one or multiple Stars
Star struct {
// Primary tells if this the Primary Star of this system
Primary bool
// Class is the Classification, e.g. A,E,F
Class string `valid:"alpha,uppercase,length(1|1)"`
// DecimalClassification saves the Decimal Classification After Class and before Size
DecimalClassification int `valid:"numeric"`
// Size categories Size in Roman Numbers
Size string `valid:"alpha,uppercase,length(1|3)"`
// Dwarf marks this as a Dwarf Star Class
Dwarf bool
// DwarfType gives the Subclassification of a Dwarf Star
DwarfType string `valid:"alpha,length(1|2)"`
// SpectralClass of the Star
SpectralClass SpectralClass
}
// SpectralClass describes Spectral Properties, etc.
SpectralClass struct {
// Class is a single uppercase Letter Description for the Spectral Class
Class string `valid:"alpha,uppercase,length(1|1)"`
// Spectrum is a Color Description, e.g. Yellow
Spectrum string `valid:"alpha"`
// SurfaceTemperature is a freeform Text, e.g. 3500 to 5000 k
SurfaceTemperature string `valid:"alphanum"`
// Mass is the Mass in Average Sun Sizes, e.g. 1, 0.3, etc.
Mass float32 `valid:"float"`
// Color is a RGB hex code
Color string `valid:"hexadecimal"`
// Luminosity Class Info
Luminosity LuminosityClass
}
// LuminosityClass Classification
LuminosityClass struct {
// Type Classification
Type string `valid:"alpha,uppercase,length(1|3)"`
// Description is a freeform Text, e.g. Luminous giants
Description string `valid:"alphanum"`
}
)
func (star *Star) GetDecimalClassification() int {
decimalClassDie := Dice{}
// d Class White Dwarfs have no Decimal Classification
if star.Dwarf == true {
switch star.DwarfType {
case
"dA",
"dF",
"dG":
return -1
}
}
// 5 to 9 are not possible for K and H Class of size IV
if star.Size == "IV" {
switch star.Class {
case
"K",
"H":
decimalClassDie.Sides = 4
return decimalClassDie.Roll()
}
}
// 0 to 4 are not possible for B,A and F Class of size VI
if star.Size == "VI" {
switch star.Class {
case
"B",
"A",
"F":
decimalClassDie.Sides = 5
return 4 + decimalClassDie.Roll()
}
}
decimalClassDie.Sides = 9
return decimalClassDie.Roll()
}
// ApplyGenerator applies a Generator the the System
func (system *System) ApplyGenerator(generator Generator) {
generator.Run(system)
} | src/definitions/system.go | 0.737631 | 0.634925 | system.go | starcoder |
package parser
import (
"fmt"
"github.com/authzed/spicedb/pkg/schemadsl/dslshape"
"github.com/authzed/spicedb/pkg/schemadsl/input"
"github.com/authzed/spicedb/pkg/schemadsl/lexer"
)
// Parse parses the given Schema DSL source into a parse tree.
func Parse(builder NodeBuilder, source input.InputSource, input string) AstNode {
lx := lexer.Lex(source, input)
parser := buildParser(lx, builder, source, input)
return parser.consumeTopLevel()
}
// ignoredTokenTypes are those tokens ignored when parsing.
var ignoredTokenTypes = map[lexer.TokenType]bool{
lexer.TokenTypeWhitespace: true,
lexer.TokenTypeNewline: true,
lexer.TokenTypeSinglelineComment: true,
lexer.TokenTypeMultilineComment: true,
}
// consumeTopLevel attempts to consume the top-level definitions.
func (p *sourceParser) consumeTopLevel() AstNode {
rootNode := p.startNode(dslshape.NodeTypeFile)
defer p.finishNode()
// Start at the first token.
p.consumeToken()
if p.currentToken.Kind == lexer.TokenTypeError {
p.emitError("%s", p.currentToken.Value)
return rootNode
}
Loop:
for {
if p.isToken(lexer.TokenTypeEOF) {
break Loop
}
// Consume a statement terminator if one was found.
p.tryConsumeStatementTerminator()
if p.isToken(lexer.TokenTypeEOF) {
break Loop
}
// The top level of the DSL is a set of definitions:
// definition foobar { ... }
switch {
case p.isKeyword("definition"):
rootNode.Connect(dslshape.NodePredicateChild, p.consumeDefinition())
default:
p.emitError("Unexpected token at root level: %v", p.currentToken.Kind)
break Loop
}
}
return rootNode
}
// consumeDefinition attempts to consume a single schema definition.
// ```definition somedef { ... }````
func (p *sourceParser) consumeDefinition() AstNode {
defNode := p.startNode(dslshape.NodeTypeDefinition)
defer p.finishNode()
// definition ...
p.consumeKeyword("definition")
definitionName, ok := p.consumeTypePath()
if !ok {
return defNode
}
defNode.Decorate(dslshape.NodeDefinitionPredicateName, definitionName)
// {
_, ok = p.consume(lexer.TokenTypeLeftBrace)
if !ok {
return defNode
}
// Relations and permissions.
for {
// }
if _, ok := p.tryConsume(lexer.TokenTypeRightBrace); ok {
break
}
// relation ...
// permission ...
switch {
case p.isKeyword("relation"):
defNode.Connect(dslshape.NodePredicateChild, p.consumeRelation())
case p.isKeyword("permission"):
defNode.Connect(dslshape.NodePredicateChild, p.consumePermission())
}
ok := p.consumeStatementTerminator()
if !ok {
break
}
}
return defNode
}
// consumeRelation consumes a relation.
// ```relation foo: sometype```
func (p *sourceParser) consumeRelation() AstNode {
relNode := p.startNode(dslshape.NodeTypeRelation)
defer p.finishNode()
// relation ...
p.consumeKeyword("relation")
relationName, ok := p.consumeIdentifier()
if !ok {
return relNode
}
relNode.Decorate(dslshape.NodePredicateName, relationName)
// :
_, ok = p.consume(lexer.TokenTypeColon)
if !ok {
return relNode
}
// Relation allowed type(s).
relNode.Connect(dslshape.NodeRelationPredicateAllowedTypes, p.consumeTypeReference())
return relNode
}
// consumeTypeReference consumes a reference to a type or types of relations.
// ```somerel | anotherrel```
func (p *sourceParser) consumeTypeReference() AstNode {
refNode := p.startNode(dslshape.NodeTypeTypeReference)
defer p.finishNode()
for {
refNode.Connect(dslshape.NodeTypeReferencePredicateType, p.consumeSpecificType())
if _, ok := p.tryConsume(lexer.TokenTypePipe); !ok {
break
}
}
return refNode
}
// consumeSpecificType consumes an identifier as a specific type reference.
func (p *sourceParser) consumeSpecificType() AstNode {
specificNode := p.startNode(dslshape.NodeTypeSpecificTypeReference)
defer p.finishNode()
typeName, ok := p.consumeTypePath()
if !ok {
return specificNode
}
specificNode.Decorate(dslshape.NodeSpecificReferencePredicateType, typeName)
// Check for a relation specified.
if _, ok := p.tryConsume(lexer.TokenTypeHash); !ok {
return specificNode
}
// Consume an identifier or an ellipsis.
consumed, ok := p.consume(lexer.TokenTypeIdentifier, lexer.TokenTypeEllipsis)
if !ok {
return specificNode
}
specificNode.Decorate(dslshape.NodeSpecificReferencePredicateRelation, consumed.Value)
return specificNode
}
func (p *sourceParser) consumeTypePath() (string, bool) {
typeNameOrNamespace, ok := p.consumeIdentifier()
if !ok {
return "", false
}
_, ok = p.tryConsume(lexer.TokenTypeDiv)
if !ok {
return typeNameOrNamespace, true
}
typeName, ok := p.consumeIdentifier()
if !ok {
return "", false
}
return fmt.Sprintf("%s/%s", typeNameOrNamespace, typeName), true
}
// consumePermission consumes a permission.
// ```permission foo = bar + baz```
func (p *sourceParser) consumePermission() AstNode {
permNode := p.startNode(dslshape.NodeTypePermission)
defer p.finishNode()
// permission ...
p.consumeKeyword("permission")
permissionName, ok := p.consumeIdentifier()
if !ok {
return permNode
}
permNode.Decorate(dslshape.NodePredicateName, permissionName)
// =
_, ok = p.consume(lexer.TokenTypeEquals)
if !ok {
return permNode
}
permNode.Connect(dslshape.NodePermissionPredicateComputeExpression, p.consumeComputeExpression())
return permNode
}
// ComputeExpressionOperators defines the binary operators in precedence order.
var ComputeExpressionOperators = []binaryOpDefinition{
{lexer.TokenTypeMinus, dslshape.NodeTypeExclusionExpression},
{lexer.TokenTypeAnd, dslshape.NodeTypeIntersectExpression},
{lexer.TokenTypePlus, dslshape.NodeTypeUnionExpression},
}
// consumeComputeExpression consumes an expression for computing a permission.
func (p *sourceParser) consumeComputeExpression() AstNode {
// Compute expressions consist of a set of binary operators, so build a tree with proper
// precedence.
binaryParser := p.buildBinaryOperatorExpressionFnTree(ComputeExpressionOperators)
found, ok := binaryParser()
if !ok {
return p.createErrorNode("Expected compute expression for permission")
}
return found
}
// tryConsumeComputeExpression attempts to consume a nested compute expression.
func (p *sourceParser) tryConsumeComputeExpression(subTryExprFn tryParserFn, binaryTokenType lexer.TokenType, nodeType dslshape.NodeType) (AstNode, bool) {
rightNodeBuilder := func(leftNode AstNode, operatorToken lexer.Lexeme) (AstNode, bool) {
rightNode, ok := subTryExprFn()
if !ok {
return nil, false
}
// Create the expression node representing the binary expression.
exprNode := p.createNode(nodeType)
exprNode.Connect(dslshape.NodeExpressionPredicateLeftExpr, leftNode)
exprNode.Connect(dslshape.NodeExpressionPredicateRightExpr, rightNode)
return exprNode, true
}
return p.performLeftRecursiveParsing(subTryExprFn, rightNodeBuilder, nil, binaryTokenType)
}
// tryConsumeArrowExpression attempts to consume an arrow expression.
// ```foo->bar->baz->meh```
func (p *sourceParser) tryConsumeArrowExpression() (AstNode, bool) {
rightNodeBuilder := func(leftNode AstNode, operatorToken lexer.Lexeme) (AstNode, bool) {
rightNode, ok := p.tryConsumeBaseExpression()
if !ok {
return nil, false
}
// Create the expression node representing the binary expression.
exprNode := p.createNode(dslshape.NodeTypeArrowExpression)
exprNode.Connect(dslshape.NodeExpressionPredicateLeftExpr, leftNode)
exprNode.Connect(dslshape.NodeExpressionPredicateRightExpr, rightNode)
return exprNode, true
}
return p.performLeftRecursiveParsing(p.tryConsumeIdentifierLiteral, rightNodeBuilder, nil, lexer.TokenTypeRightArrow)
}
// tryConsumeBaseExpression attempts to consume base compute expressions (identifiers, parenthesis).
// ```(foo + bar)```
// ```(foo)```
// ```foo```
func (p *sourceParser) tryConsumeBaseExpression() (AstNode, bool) {
switch {
// Nested expression.
case p.isToken(lexer.TokenTypeLeftParen):
comments := p.currentToken.comments
p.consume(lexer.TokenTypeLeftParen)
exprNode := p.consumeComputeExpression()
p.consume(lexer.TokenTypeRightParen)
// Attach any comments found to the consumed expression.
p.decorateComments(exprNode, comments)
return exprNode, true
// Identifier.
case p.isToken(lexer.TokenTypeIdentifier):
return p.tryConsumeIdentifierLiteral()
}
return nil, false
}
// tryConsumeIdentifierLiteral attempts to consume an identifer as a literal expression.
/// ```foo```
func (p *sourceParser) tryConsumeIdentifierLiteral() (AstNode, bool) {
if !p.isToken(lexer.TokenTypeIdentifier) {
return nil, false
}
identNode := p.startNode(dslshape.NodeTypeIdentifier)
defer p.finishNode()
identifier, _ := p.consumeIdentifier()
identNode.Decorate(dslshape.NodeIdentiferPredicateValue, identifier)
return identNode, true
} | pkg/schemadsl/parser/parser.go | 0.743634 | 0.547948 | parser.go | starcoder |
package v1alpha1
import (
v1alpha1 "github.com/openebs/maya/pkg/apis/openebs.io/kubeassert/v1alpha1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// KubeAssertLister helps list KubeAsserts.
type KubeAssertLister interface {
// List lists all KubeAsserts in the indexer.
List(selector labels.Selector) (ret []*v1alpha1.KubeAssert, err error)
// KubeAsserts returns an object that can list and get KubeAsserts.
KubeAsserts(namespace string) KubeAssertNamespaceLister
KubeAssertListerExpansion
}
// kubeAssertLister implements the KubeAssertLister interface.
type kubeAssertLister struct {
indexer cache.Indexer
}
// NewKubeAssertLister returns a new KubeAssertLister.
func NewKubeAssertLister(indexer cache.Indexer) KubeAssertLister {
return &kubeAssertLister{indexer: indexer}
}
// List lists all KubeAsserts in the indexer.
func (s *kubeAssertLister) List(selector labels.Selector) (ret []*v1alpha1.KubeAssert, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.KubeAssert))
})
return ret, err
}
// KubeAsserts returns an object that can list and get KubeAsserts.
func (s *kubeAssertLister) KubeAsserts(namespace string) KubeAssertNamespaceLister {
return kubeAssertNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// KubeAssertNamespaceLister helps list and get KubeAsserts.
type KubeAssertNamespaceLister interface {
// List lists all KubeAsserts in the indexer for a given namespace.
List(selector labels.Selector) (ret []*v1alpha1.KubeAssert, err error)
// Get retrieves the KubeAssert from the indexer for a given namespace and name.
Get(name string) (*v1alpha1.KubeAssert, error)
KubeAssertNamespaceListerExpansion
}
// kubeAssertNamespaceLister implements the KubeAssertNamespaceLister
// interface.
type kubeAssertNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all KubeAsserts in the indexer for a given namespace.
func (s kubeAssertNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.KubeAssert, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.KubeAssert))
})
return ret, err
}
// Get retrieves the KubeAssert from the indexer for a given namespace and name.
func (s kubeAssertNamespaceLister) Get(name string) (*v1alpha1.KubeAssert, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1alpha1.Resource("kubeassert"), name)
}
return obj.(*v1alpha1.KubeAssert), nil
} | pkg/client/generated/openebs.io/kubeassert/v1alpha1/lister/kubeassert/v1alpha1/kubeassert.go | 0.65368 | 0.429908 | kubeassert.go | starcoder |
package multiplication
import (
"math"
"strconv"
)
// Karatsuba returns the product of a and b, which should be positive integers
// represented as strings (e.g. 123 as "123").
func Karatsuba(a string, b string) string {
evenPad(&a, &b)
a = padToPowerOfTwo(a)
b = padToPowerOfTwo(b)
return unpad(karatsuba(a, b))
}
// karatsuba implements Karatsuba's recursive algorithm, assuming a and b
// have the same length, the length being a power of 2.
func karatsuba(a string, b string) string {
if len(a) == 1 {
aint, _ := strconv.Atoi(a)
bint, _ := strconv.Atoi(b)
return strconv.Itoa(aint * bint)
}
n := len(a)
h := n / 2
al := a[:h]
ar := a[h:]
bl := b[:h]
br := b[h:]
x := Karatsuba(al, bl)
z := Karatsuba(ar, br)
y := sub(Karatsuba(add(al, ar), add(bl, br)), add(x, z))
return add(add(shift(x, n), shift(y, h)), z)
}
// add calculates the sum of two positive integers, represented as strings.
func add(a string, b string) string {
evenPad(&a, &b)
sum := ""
c := 0
for i := len(a) - 1; i >= 0; i-- {
aint, _ := strconv.Atoi(string(a[i]))
bint, _ := strconv.Atoi(string(b[i]))
s := aint + bint + c
if s >= 10 {
c = 1
s -= 10
} else {
c = 0
}
sum = strconv.Itoa(s) + sum
}
if c > 0 {
sum = strconv.Itoa(c) + sum
}
return sum
}
// sub calculates the difference of two positive integers, represented as
// strings.
func sub(a string, b string) string {
evenPad(&a, &b)
diff := ""
c := false
for i := len(a) - 1; i >= 0; i-- {
aint, _ := strconv.Atoi(string(a[i]))
bint, _ := strconv.Atoi(string(b[i]))
if c {
aint--
}
if bint > aint {
aint += 10
c = true
} else {
c = false
}
d := aint - bint
diff = strconv.Itoa(d) + diff
}
return unpad(diff)
}
// evenPad pads two positive integers, represented as strings, with leading
// zeros until they are equal in string length.
func evenPad(a *string, b *string) {
if len(*a) != len(*b) {
for len(*a) < len(*b) {
*a = "0" + *a
}
for len(*b) < len(*a) {
*b = "0" + *b
}
}
}
// padToPowerOfTwo pads a positive integer, represented as a string, with
// leading zeros until the string length of a is a power of two.
func padToPowerOfTwo(a string) string {
l := len(a)
p := 1
e := 0
for ; l > p; e++ {
p = int(math.Pow(2, float64(e)))
}
for ; l < p; l++ {
a = "0" + a
}
return a
}
// unpad removes leading zeros from a positive integer represented as a string.
func unpad(a string) string {
var r string
for i, l := range a {
if l != '0' {
r = a[i:]
break
}
}
if r == "" {
r = "0"
}
return r
}
// shift adds n trailing zeros to a positive integer, a, represented as a
// string.
func shift(a string, n int) string {
for i := 0; i < n; i++ {
a = a + "0"
}
return a
} | multiplication/multiplication.go | 0.813868 | 0.519156 | multiplication.go | starcoder |
package parseip4
import (
"fmt"
)
// Octets represents all 4 octets of an address, in as single unsigned integer.
// To produce a sensible Octets value, see OctsList.Pack().
type Octets uint32
// OctsList is a (presumed) len()=4 list of 8-bit unsigned integer values, or
// octets.
type OctsList []uint8
// Addr represents an IP address and its mask, which may or may not be a
// default classful addressing mask.
type Addr struct {
IP OctsList
Mask OctsList
}
// NewAddr builds a proper-length OctsList.
func NewAddr(highest, second, third, lowest uint8) OctsList {
return OctsList{highest, second, third, lowest}
}
const (
bitsOctetA = 32 - 8 // octet A in IP address A.B.C.D
bitsOctetB = 32 - 8*2 // octet B in IP address A.B.C.D
bitsOctetC = 32 - 8*3 // octet C in IP address A.B.C.D
)
// Pack produces a single integer with tthe values of OctsList in the
// appropriate bit location.
func (o OctsList) Pack() Octets {
return (Octets(o[0]) << bitsOctetA) +
(Octets(o[1]) << bitsOctetB) +
(Octets(o[2]) << bitsOctetC) +
(Octets(o[3]))
}
// OctsList unpacks a Octets value into its component 8-bit valued integers.
func (ino Octets) List() OctsList {
return OctsList{
uint8((0xFF000000 & ino) >> bitsOctetA),
uint8((0x00FF0000 & ino) >> bitsOctetB),
uint8((0x0000FF00 & ino) >> bitsOctetC),
uint8(0x000000FF & ino),
}
}
func (a *Addr) String() string {
return fmt.Sprintf(
"%d.%d.%d.%d/%d.%d.%d.%d",
a.IP[0], a.IP[1], a.IP[2], a.IP[3],
a.Mask[0], a.Mask[1], a.Mask[2], a.Mask[3])
}
// Classful determines the classful-addressing "class" of an IP address and
// returns three representations of this: a mask, a CIDR-notation offset, and
// the human-readable class label.
func Classful(ip OctsList) (OctsList, uint, string) {
topOctet := ip[0]
switch {
case topOctet < 128:
return OctsList{255, 0, 0, 0}, 8 * 1, "A"
case topOctet >= 128 && topOctet < 192:
return OctsList{255, 255, 0, 0}, 8 * 2, "B"
case topOctet >= 192 && topOctet < 224:
return OctsList{255, 255, 255, 0}, 8 * 3, "C"
default:
panic("expected only classes A,B, or C")
}
}
// CountOnes counts the on-bits of an 32-bit octets integer.
func CountOnes(o Octets) uint {
var n uint = 0
for i := n; i < 32; i++ {
n += 1 & (uint(o) >> i)
}
return n
}
// CountBitSize counts how much of 32 bit address space is utilized `o`.
func CountBitSize(o Octets) uint {
var i uint = 0
for ; i < 32; i++ {
if ((1 << 31) & (o << i)) != 0 {
break
}
}
return 32 - i
}
// NetworkIndex determines what the integer index of an address's network number
// would be, if it were considered as one of a continuous stream of potential
// networks within the IP address space.
func (a *Addr) NetworkIndex() Octets {
classMask, cidrOffset, _ := Classful(a.IP)
return (a.IP.Pack() & classMask.Pack()) >> (32 - cidrOffset)
}
// SubnetIndex determines what the integer index of an address's subnet number
// would be, if it were considered as one of a continuous stream of potential
// networks within the IP address space.
func (a *Addr) SubnetIndex() Octets {
classMask, cidrOffset, _ := Classful(a.IP)
classMaskPck := classMask.Pack()
uniqSubnetBits := (^classMaskPck) & a.Mask.Pack()
middleSubnetBits := uniqSubnetBits & a.IP.Pack()
totalNetBitsCount := cidrOffset + CountOnes(uniqSubnetBits)
return middleSubnetBits >> (32 - totalNetBitsCount)
}
// HostIndex determines what the integer index of an address's host number
// would be - after considering any classless subnet apparently being utilized,
// according to the addresses' mask - if it were considered as one of a
// continuous stream of potential networks within the IP address space.
func (a *Addr) HostIndex() Octets {
maskPck := a.Mask.Pack()
return (^maskPck) & a.IP.Pack()
} | parseip4/parseip4.go | 0.756358 | 0.419648 | parseip4.go | starcoder |
package telegraf
import (
"fmt"
"strconv"
"strings"
"time"
)
var (
// Escapes the various parts of the influxdb line protocal
measurementEscaper = strings.NewReplacer(`,`, `\,`, ` `, `\ `)
keyEscaper = strings.NewReplacer(`,`, `\,`, ` `, `\ `, `=`, `\=`)
tagValueEscaper = keyEscaper
)
// Measurement that can be sent to influxdb or telegraf. The measurement
// consists of three parts, the name of the metric, a set of fields and their
// values, optional tags and a timestamp.
type Measurement struct {
name string
tagSet map[string]string
fieldSet map[string]interface{}
timestamp time.Time
}
// NewMeasurement creates a blank measurement without any fields, you must add
// a field before trying to send it to telegraf using on of the Add* methods.
// This is useful when you want to add tags before you have a field measurement
// avaiable.
func NewMeasurement(name string) Measurement {
return Measurement{
name: name,
tagSet: map[string]string{},
fieldSet: map[string]interface{}{},
timestamp: time.Now(),
}
}
// Name of the measurement.
func (m Measurement) Name() string {
return m.name
}
// SetTime of the measurement. The default is time.Now(), this can be used to
// override the default. Set it to a zero time to unset the time, which will
// cause telegraf or influxdb to set the time when they recieve the measurement
// instead.
func (m Measurement) SetTime(time time.Time) Measurement {
m.timestamp = time
return m
}
// AddTag to the measurement. Tags are global for all fields in this
// measurement - if you want them to have differenent tags you must create a
// second measurement with the alternate tags.
func (m Measurement) AddTag(name string, value string) Measurement {
if value != "" {
m.tagSet[name] = value
}
return m
}
// AddTags to the measurement. Tags are global for all fields in this
// measurement - if you want them to have differenent tags you must create a
// second measurement with the alternate tags.
func (m Measurement) AddTags(tags map[string]string) Measurement {
for name, value := range tags {
m.AddTag(name, value)
}
return m
}
// MeasureNanosecondsSince creates a new measurement with the given uint64 field.
func MeasureNanosecondsSince(name string, field string, t time.Time) Measurement {
return NewMeasurement(name).AddNanosecondsSince(field, t)
}
// AddNanosecondsSince t as the field called name stored as an uint64.
func (m Measurement) AddNanosecondsSince(name string, t time.Time) Measurement {
m.fieldSet[name] = time.Since(t).Nanoseconds()
return m
}
// MeasureMillisecondsSince creates a new measurement with the given float64 field.
func MeasureMillisecondsSince(name string, field string, t time.Time) Measurement {
return NewMeasurement(name).AddMillisecondsSince(field, t)
}
// AddMillisecondsSince t as the field called name stored as a float64.
func (m Measurement) AddMillisecondsSince(name string, t time.Time) Measurement {
m.fieldSet[name] = float64(time.Since(t).Nanoseconds()) / float64((int64(time.Millisecond) / int64(time.Nanosecond)))
return m
}
// MeasureSecondsSince creates a new measurement with the given float64 field.
func MeasureSecondsSince(name string, field string, t time.Time) Measurement {
return NewMeasurement(name).AddSecondsSince(field, t)
}
// AddSecondsSince t as the field called name stored as a float64.
func (m Measurement) AddSecondsSince(name string, t time.Time) Measurement {
m.fieldSet[name] = time.Since(t).Seconds()
return m
}
// MeasureMinutesSince creates a new measurement with the given float64 field.
func MeasureMinutesSince(name string, field string, t time.Time) Measurement {
return NewMeasurement(name).AddMinutesSince(field, t)
}
// AddMinutesSince t as the field called name stored as a float64.
func (m Measurement) AddMinutesSince(name string, t time.Time) Measurement {
m.fieldSet[name] = time.Since(t).Minutes()
return m
}
// MeasureHoursSince creates a new measurement with the given float64 field.
func MeasureHoursSince(name string, field string, t time.Time) Measurement {
return NewMeasurement(name).AddHoursSince(field, t)
}
// AddHoursSince t as the field called name stored as a float64.
func (m Measurement) AddHoursSince(name string, t time.Time) Measurement {
m.fieldSet[name] = time.Since(t).Hours()
return m
}
// MeasureBool creates a new measurement with the given bool field.
func MeasureBool(name string, field string, value bool) Measurement {
return NewMeasurement(name).AddBool(field, value)
}
// AddBool field called name.
func (m Measurement) AddBool(name string, value bool) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureInt creates a new measurement with the given int field.
func MeasureInt(name string, field string, value int) Measurement {
return NewMeasurement(name).AddInt(field, value)
}
// AddInt field called name.
func (m Measurement) AddInt(name string, value int) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureInt8 creates a new measurement with the given int8 field.
func MeasureInt8(name string, field string, value int8) Measurement {
return NewMeasurement(name).AddInt8(field, value)
}
// AddInt8 field called name.
func (m Measurement) AddInt8(name string, value int8) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureInt16 creates a new measurement with the given int16 field.
func MeasureInt16(name string, field string, value int16) Measurement {
return NewMeasurement(name).AddInt16(field, value)
}
// AddInt16 field called name.
func (m Measurement) AddInt16(name string, value int16) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureInt32 creates a new measurement with the given int32 field.
func MeasureInt32(name string, field string, value int32) Measurement {
return NewMeasurement(name).AddInt32(field, value)
}
// AddInt32 field called name.
func (m Measurement) AddInt32(name string, value int32) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureInt64 creates a new measurement with the given int64 field.
func MeasureInt64(name string, field string, value int64) Measurement {
return NewMeasurement(name).AddInt64(field, value)
}
// AddInt64 field called name.
func (m Measurement) AddInt64(name string, value int64) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureUInt creates a new measurement with the given uint field.
func MeasureUInt(name string, field string, value uint) Measurement {
return NewMeasurement(name).AddUInt(field, value)
}
// AddUInt field called name.
func (m Measurement) AddUInt(name string, value uint) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureUInt8 creates a new measurement with the given uint8 field.
func MeasureUInt8(name string, field string, value uint8) Measurement {
return NewMeasurement(name).AddUInt8(field, value)
}
// AddUInt8 field called name.
func (m Measurement) AddUInt8(name string, value uint8) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureUInt16 creates a new measurement with the given uint16 field.
func MeasureUInt16(name string, field string, value uint16) Measurement {
return NewMeasurement(name).AddUInt16(field, value)
}
// AddUInt16 field called name.
func (m Measurement) AddUInt16(name string, value uint16) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureUInt32 creates a new measurement with the given uint32 field.
func MeasureUInt32(name string, field string, value uint32) Measurement {
return NewMeasurement(name).AddUInt32(field, value)
}
// AddUInt32 field called name.
func (m Measurement) AddUInt32(name string, value uint32) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureUInt64 creates a new measurement with the given uint64 field.
func MeasureUInt64(name string, field string, value uint64) Measurement {
return NewMeasurement(name).AddUInt64(field, value)
}
// AddUInt64 field called name.
func (m Measurement) AddUInt64(name string, value uint64) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureFloat32 creates a new measurement with the given float32 field.
func MeasureFloat32(name string, field string, value float32) Measurement {
return NewMeasurement(name).AddFloat32(field, value)
}
// AddFloat32 field called name.
func (m Measurement) AddFloat32(name string, value float32) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureFloat64 creates a new measurement with the given float64 field.
func MeasureFloat64(name string, field string, value float64) Measurement {
return NewMeasurement(name).AddFloat64(field, value)
}
// AddFloat64 field called name.
func (m Measurement) AddFloat64(name string, value float64) Measurement {
m.fieldSet[name] = value
return m
}
// MeasureString creates a new measurement with the given string field.
func MeasureString(name string, field string, value string) Measurement {
return NewMeasurement(name).AddString(field, value)
}
// AddString field called name.
func (m Measurement) AddString(name string, value string) Measurement {
m.fieldSet[name] = value
return m
}
// ToLineProtocal converts the metric to the influxdb line protocal.
func (m Measurement) ToLineProtocal() string {
line := measurementEscaper.Replace(m.name)
for tag, value := range m.tagSet {
line += "," + keyEscaper.Replace(tag) + "=" + tagValueEscaper.Replace(value)
}
first := true
for field, value := range m.fieldSet {
if first {
line += " "
first = false
} else {
line += ","
}
line += keyEscaper.Replace(field) + "="
switch v := value.(type) {
case int, uint, uint8, uint16, uint32, uint64, int8, int16, int32, int64:
line += fmt.Sprintf("%di", v)
case float32:
line += strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
line += strconv.FormatFloat(v, 'f', -1, 64)
case string:
line += fmt.Sprintf("%q", v)
case bool:
line += fmt.Sprintf("%t", v)
default:
line += fmt.Sprintf("%v", v)
}
}
if !m.timestamp.IsZero() {
line += fmt.Sprintf(" %d", m.timestamp.UnixNano())
}
return line
} | measurement.go | 0.840979 | 0.524456 | measurement.go | starcoder |
package graph
// Vertex represents a single node in a graph.
type Vertex struct {
// Value in our implementation is just an integer for readability
Value int
// Graph allows us to make sure the vertices are in the same graph
Graph *Graph
// Neighbors stores edges between two vertices
Neighbors []*Vertex
}
// GetNeighbors is a convenient function to return the neighboring vertices
func (v *Vertex) GetNeighbors() []*Vertex {
return v.Neighbors
}
// IsAdjacent checks if the current vertex has an edge with another
func (v *Vertex) IsAdjacent(other *Vertex) bool {
if v.Graph != other.Graph {
return false
}
for _, n := range v.Neighbors {
if n == other {
return true
}
}
return false
}
// RemoveEdge removes a neighboring vertex from its list
func (v *Vertex) RemoveEdge(other *Vertex) bool {
if v.Graph != other.Graph {
return false
}
if !v.IsAdjacent(other) {
return false
}
updateNeighbors := func(cur, target *Vertex) []*Vertex {
var removeIndex int
for i, n := range cur.Neighbors {
if n == target {
removeIndex = i
}
}
if len(cur.Neighbors) == 1 {
return []*Vertex{}
}
return append(cur.Neighbors[:removeIndex], cur.Neighbors[removeIndex+1:]...)
}
v.Neighbors = updateNeighbors(v, other)
other.Neighbors = updateNeighbors(other, v)
return true
}
// Graph is a container which holds a list of vertices within it
type Graph struct {
Vertices []*Vertex
}
// NewGraph is a convenience method to instantiate a new graph object
func NewGraph() *Graph {
return &Graph{}
}
// Adjacent checks if two vertices are adjacent to each other
func (g *Graph) Adjacent(first, second *Vertex) bool {
if first.Graph != g || second.Graph != g {
return false
}
return first.IsAdjacent(second)
}
// Edges returns an edge list showing pairs of vertices that connect
func (g *Graph) Edges() [][]int {
var edges [][]int
for _, v := range g.Vertices {
for _, n := range v.Neighbors {
edges = append(edges, []int{v.Value, n.Value})
}
}
return edges
}
// AddVertex inserts a new vertex into the graph returning that new vertex
func (g *Graph) AddVertex(value int) *Vertex {
v := &Vertex{Value: value, Graph: g}
g.Vertices = append(g.Vertices, v)
return v
}
// RemoveVertex removes a given vertex from a graph and its neighbor relations
func (g *Graph) RemoveVertex(v *Vertex) bool {
var removeIndex int
if v.Graph != g {
return false
}
for i, vertex := range g.Vertices {
if vertex == v {
removeIndex = i
for _, neighbor := range vertex.Neighbors {
neighbor.RemoveEdge(v)
}
}
}
g.Vertices = append(g.Vertices[:removeIndex], g.Vertices[removeIndex+1:]...)
return true
}
// AddEdge creates an edge between two vertices
func (g *Graph) AddEdge(first, second *Vertex) {
if first.Graph == second.Graph && !first.IsAdjacent(second) {
second.Neighbors = append(second.Neighbors, first)
first.Neighbors = append(first.Neighbors, second)
}
}
// RemoveEdge removes an edge between two vertices if it exists
func (g *Graph) RemoveEdge(first, second *Vertex) {
if first.Graph == second.Graph && first.IsAdjacent(second) {
first.RemoveEdge(second)
}
}
// GetVertex searches for a vertex based on the value
func (g *Graph) GetVertex(value int) *Vertex {
for _, v := range g.Vertices {
if v.Value == value {
return v
}
}
return nil
}
// ToAdjacencyList returns a graph represented as an Adjacency List
func (g *Graph) ToAdjacencyList() [][]int {
list := make([][]int, len(g.Vertices))
for i, v := range g.Vertices {
for _, n := range v.Neighbors {
list[i] = append(list[i], n.Value)
}
}
return list
}
// ToAdjacencyMatrix returns a graph represented as an Adjacency Matrix
func (g *Graph) ToAdjacencyMatrix() [][]int {
matrix := make([][]int, len(g.Vertices))
for i, _ := range g.Vertices {
row := make([]int, len(g.Vertices))
for j, _ := range g.Vertices {
row[j] = 0
}
matrix[i] = row
}
for _, edge := range g.Edges() {
matrix[edge[0]][edge[1]] = 1
}
return matrix
} | data-structures/graph/graph.go | 0.877306 | 0.745028 | graph.go | starcoder |
package gofa
// Ephemeride
/*
Epv00 Earth position and velocity, heliocentric and barycentric, with
respect to the Barycentric Celestial Reference System.
Given:
date1,date2 float64 TDB date (Note 1)
Returned:
pvh [2][3]float64 heliocentric Earth position/velocity
pvb [2][3]float64 barycentric Earth position/velocity
Returned (function value):
int status: 0 = OK
+1 = warning: date outside the range 1900-2100 AD
Notes:
1) The TDB date date1+date2 is a Julian Date, apportioned in any
convenient way between the two arguments. For example,
JD(TDB)=2450123.7 could be expressed in any of these ways, among
others:
date1 date2
2450123.7 0.0 (JD method)
2451545.0 -1421.3 (J2000 method)
2400000.5 50123.2 (MJD method)
2450123.5 0.2 (date & time method)
The JD method is the most natural and convenient to use in cases
where the loss of several decimal digits of resolution is
acceptable. The J2000 method is best matched to the way the
argument is handled internally and will deliver the optimum
resolution. The MJD method and the date & time methods are both
good compromises between resolution and convenience. However,
the accuracy of the result is more likely to be limited by the
algorithm itself than the way the date has been expressed.
n.b. TT can be used instead of TDB in most applications.
2) On return, the arrays pvh and pvb contain the following:
pvh[0][0] x }
pvh[0][1] y } heliocentric position, au
pvh[0][2] z }
pvh[1][0] xdot }
pvh[1][1] ydot } heliocentric velocity, au/d
pvh[1][2] zdot }
pvb[0][0] x }
pvb[0][1] y } barycentric position, au
pvb[0][2] z }
pvb[1][0] xdot }
pvb[1][1] ydot } barycentric velocity, au/d
pvb[1][2] zdot }
The vectors are with respect to the Barycentric Celestial
Reference System. The time unit is one day in TDB.
3) The function is a SIMPLIFIED SOLUTION from the planetary theory
VSOP2000 (<NAME>, <NAME>, 2001, Celes. Mechanics &
Dyn. Astron., 80, 3/4, 205-213) and is an adaptation of original
Fortran code supplied by <NAME> (private comm., 2000).
4) Comparisons over the time span 1900-2100 with this simplified
solution and the JPL DE405 ephemeris give the following results:
RMS max
Heliocentric:
position error 3.7 11.2 km
velocity error 1.4 5.0 mm/s
Barycentric:
position error 4.6 13.4 km
velocity error 1.4 4.9 mm/s
Comparisons with the JPL DE406 ephemeris show that by 1800 and
2200 the position errors are approximately double their 1900-2100
size. By 1500 and 2500 the deterioration is a factor of 10 and
by 1000 and 3000 a factor of 60. The velocity accuracy falls off
at about half that rate.
5) It is permissible to use the same array for pvh and pvb, which
will receive the barycentric values.
*/
func Epv00(date1, date2 float64, pvh, pvb *[2][3]float64) int {
/*
Matrix elements for orienting the analytical model to DE405.
The corresponding Euler angles are:
d ' "
1st rotation - 23 26 21.4091 about the x-axis (obliquity)
2nd rotation + 0.0475 about the z-axis (RA offset)
These were obtained empirically, by comparisons with DE405 over
1900-2100.
*/
const (
am12 = 0.000000211284
am13 = -0.000000091603
am21 = -0.000000230286
am22 = 0.917482137087
am23 = -0.397776982902
am32 = 0.397776982902
am33 = 0.917482137087
)
/*
----------------------
Ephemeris Coefficients
----------------------
The ephemeris consists of harmonic terms for predicting (i) the Sun
to Earth vector and (ii) the Solar-System-barycenter to Sun vector
respectively. The coefficients are stored in arrays which, although
1-demensional, contain groups of three. Each triplet of
coefficients is the amplitude, phase and frequency for one term in
the model, and each array contains the number of terms called for by
the model.
There are eighteen such arrays, named as follows:
array model power of T component
e0x Sun-to-Earth 0 x
e0y Sun-to-Earth 0 y
e0z Sun-to-Earth 0 z
e1x Sun-to-Earth 1 x
e1y Sun-to-Earth 1 y
e1z Sun-to-Earth 1 z
e2x Sun-to-Earth 2 x
e2y Sun-to-Earth 2 y
e2z Sun-to-Earth 2 z
s0x SSB-to-Sun 0 x
s0y SSB-to-Sun 0 y
s0z SSB-to-Sun 0 z
s1x SSB-to-Sun 1 x
s1y SSB-to-Sun 1 y
s1z SSB-to-Sun 1 z
s2x SSB-to-Sun 2 x
s2y SSB-to-Sun 2 y
s2z SSB-to-Sun 2 z
*/
/* Sun-to-Earth, T^0, X */
e0x := []float64{
0.9998292878132e+00, 0.1753485171504e+01, 0.6283075850446e+01,
0.8352579567414e-02, 0.1710344404582e+01, 0.1256615170089e+02,
0.5611445335148e-02, 0.0000000000000e+00, 0.0000000000000e+00,
0.1046664295572e-03, 0.1667225416770e+01, 0.1884922755134e+02,
0.3110842534677e-04, 0.6687513390251e+00, 0.8399684731857e+02,
0.2552413503550e-04, 0.5830637358413e+00, 0.5296909721118e+00,
0.2137207845781e-04, 0.1092330954011e+01, 0.1577343543434e+01,
0.1680240182951e-04, 0.4955366134987e+00, 0.6279552690824e+01,
0.1679012370795e-04, 0.6153014091901e+01, 0.6286599010068e+01,
0.1445526946777e-04, 0.3472744100492e+01, 0.2352866153506e+01,
0.1091038246184e-04, 0.3689845786119e+01, 0.5223693906222e+01,
0.9344399733932e-05, 0.6073934645672e+01, 0.1203646072878e+02,
0.8993182910652e-05, 0.3175705249069e+01, 0.1021328554739e+02,
0.5665546034116e-05, 0.2152484672246e+01, 0.1059381944224e+01,
0.6844146703035e-05, 0.1306964099750e+01, 0.5753384878334e+01,
0.7346610905565e-05, 0.4354980070466e+01, 0.3981490189893e+00,
0.6815396474414e-05, 0.2218229211267e+01, 0.4705732307012e+01,
0.6112787253053e-05, 0.5384788425458e+01, 0.6812766822558e+01,
0.4518120711239e-05, 0.6087604012291e+01, 0.5884926831456e+01,
0.4521963430706e-05, 0.1279424524906e+01, 0.6256777527156e+01,
0.4497426764085e-05, 0.5369129144266e+01, 0.6309374173736e+01,
0.4062190566959e-05, 0.5436473303367e+00, 0.6681224869435e+01,
0.5412193480192e-05, 0.7867838528395e+00, 0.7755226100720e+00,
0.5469839049386e-05, 0.1461440311134e+01, 0.1414349524433e+02,
0.5205264083477e-05, 0.4432944696116e+01, 0.7860419393880e+01,
0.2149759935455e-05, 0.4502237496846e+01, 0.1150676975667e+02,
0.2279109618501e-05, 0.1239441308815e+01, 0.7058598460518e+01,
0.2259282939683e-05, 0.3272430985331e+01, 0.4694002934110e+01,
0.2558950271319e-05, 0.2265471086404e+01, 0.1216800268190e+02,
0.2561581447555e-05, 0.1454740653245e+01, 0.7099330490126e+00,
0.1781441115440e-05, 0.2962068630206e+01, 0.7962980379786e+00,
0.1612005874644e-05, 0.1473255041006e+01, 0.5486777812467e+01,
0.1818630667105e-05, 0.3743903293447e+00, 0.6283008715021e+01,
0.1818601377529e-05, 0.6274174354554e+01, 0.6283142985870e+01,
0.1554475925257e-05, 0.1624110906816e+01, 0.2513230340178e+02,
0.2090948029241e-05, 0.5852052276256e+01, 0.1179062909082e+02,
0.2000176345460e-05, 0.4072093298513e+01, 0.1778984560711e+02,
0.1289535917759e-05, 0.5217019331069e+01, 0.7079373888424e+01,
0.1281135307881e-05, 0.4802054538934e+01, 0.3738761453707e+01,
0.1518229005692e-05, 0.8691914742502e+00, 0.2132990797783e+00,
0.9450128579027e-06, 0.4601859529950e+01, 0.1097707878456e+02,
0.7781119494996e-06, 0.1844352816694e+01, 0.8827390247185e+01,
0.7733407759912e-06, 0.3582790154750e+01, 0.5507553240374e+01,
0.7350644318120e-06, 0.2695277788230e+01, 0.1589072916335e+01,
0.6535928827023e-06, 0.3651327986142e+01, 0.1176985366291e+02,
0.6324624183656e-06, 0.2241302375862e+01, 0.6262300422539e+01,
0.6298565300557e-06, 0.4407122406081e+01, 0.6303851278352e+01,
0.8587037089179e-06, 0.3024307223119e+01, 0.1672837615881e+03,
0.8299954491035e-06, 0.6192539428237e+01, 0.3340612434717e+01,
0.6311263503401e-06, 0.2014758795416e+01, 0.7113454667900e-02,
0.6005646745452e-06, 0.3399500503397e+01, 0.4136910472696e+01,
0.7917715109929e-06, 0.2493386877837e+01, 0.6069776770667e+01,
0.7556958099685e-06, 0.4159491740143e+01, 0.6496374930224e+01,
0.6773228244949e-06, 0.4034162934230e+01, 0.9437762937313e+01,
0.5370708577847e-06, 0.1562219163734e+01, 0.1194447056968e+01,
0.5710804266203e-06, 0.2662730803386e+01, 0.6282095334605e+01,
0.5709824583726e-06, 0.3985828430833e+01, 0.6284056366286e+01,
0.5143950896447e-06, 0.1308144688689e+01, 0.6290189305114e+01,
0.5088010604546e-06, 0.5352817214804e+01, 0.6275962395778e+01,
0.4960369085172e-06, 0.2644267922349e+01, 0.6127655567643e+01,
0.4803137891183e-06, 0.4008844192080e+01, 0.6438496133249e+01,
0.5731747768225e-06, 0.3794550174597e+01, 0.3154687086868e+01,
0.4735947960579e-06, 0.6107118308982e+01, 0.3128388763578e+01,
0.4808348796625e-06, 0.4771458618163e+01, 0.8018209333619e+00,
0.4115073743137e-06, 0.3327111335159e+01, 0.8429241228195e+01,
0.5230575889287e-06, 0.5305708551694e+01, 0.1336797263425e+02,
0.5133977889215e-06, 0.5784230738814e+01, 0.1235285262111e+02,
0.5065815825327e-06, 0.2052064793679e+01, 0.1185621865188e+02,
0.4339831593868e-06, 0.3644994195830e+01, 0.1726015463500e+02,
0.3952928638953e-06, 0.4930376436758e+01, 0.5481254917084e+01,
0.4898498111942e-06, 0.4542084219731e+00, 0.9225539266174e+01,
0.4757490209328e-06, 0.3161126388878e+01, 0.5856477690889e+01,
0.4727701669749e-06, 0.6214993845446e+00, 0.2544314396739e+01,
0.3800966681863e-06, 0.3040132339297e+01, 0.4265981595566e+00,
0.3257301077939e-06, 0.8064977360087e+00, 0.3930209696940e+01,
0.3255810528674e-06, 0.1974147981034e+01, 0.2146165377750e+01,
0.3252029748187e-06, 0.2845924913135e+01, 0.4164311961999e+01,
0.3255505635308e-06, 0.3017900824120e+01, 0.5088628793478e+01,
0.2801345211990e-06, 0.6109717793179e+01, 0.1256967486051e+02,
0.3688987740970e-06, 0.2911550235289e+01, 0.1807370494127e+02,
0.2475153429458e-06, 0.2179146025856e+01, 0.2629832328990e-01,
0.3033457749150e-06, 0.1994161050744e+01, 0.4535059491685e+01,
0.2186743763110e-06, 0.5125687237936e+01, 0.1137170464392e+02,
0.2764777032774e-06, 0.4822646860252e+00, 0.1256262854127e+02,
0.2199028768592e-06, 0.4637633293831e+01, 0.1255903824622e+02,
0.2046482824760e-06, 0.1467038733093e+01, 0.7084896783808e+01,
0.2611209147507e-06, 0.3044718783485e+00, 0.7143069561767e+02,
0.2286079656818e-06, 0.4764220356805e+01, 0.8031092209206e+01,
0.1855071202587e-06, 0.3383637774428e+01, 0.1748016358760e+01,
0.2324669506784e-06, 0.6189088449251e+01, 0.1831953657923e+02,
0.1709528015688e-06, 0.5874966729774e+00, 0.4933208510675e+01,
0.2168156875828e-06, 0.4302994009132e+01, 0.1044738781244e+02,
0.2106675556535e-06, 0.3800475419891e+01, 0.7477522907414e+01,
0.1430213830465e-06, 0.1294660846502e+01, 0.2942463415728e+01,
0.1388396901944e-06, 0.4594797202114e+01, 0.8635942003952e+01,
0.1922258844190e-06, 0.4943044543591e+00, 0.1729818233119e+02,
0.1888460058292e-06, 0.2426943912028e+01, 0.1561374759853e+03,
0.1789449386107e-06, 0.1582973303499e+00, 0.1592596075957e+01,
0.1360803685374e-06, 0.5197240440504e+01, 0.1309584267300e+02,
0.1504038014709e-06, 0.3120360916217e+01, 0.1649636139783e+02,
0.1382769533389e-06, 0.6164702888205e+01, 0.7632943190217e+01,
0.1438059769079e-06, 0.1437423770979e+01, 0.2042657109477e+02,
0.1326303260037e-06, 0.3609688799679e+01, 0.1213955354133e+02,
0.1159244950540e-06, 0.5463018167225e+01, 0.5331357529664e+01,
0.1433118149136e-06, 0.6028909912097e+01, 0.7342457794669e+01,
0.1234623148594e-06, 0.3109645574997e+01, 0.6279485555400e+01,
0.1233949875344e-06, 0.3539359332866e+01, 0.6286666145492e+01,
0.9927196061299e-07, 0.1259321569772e+01, 0.7234794171227e+01,
0.1242302191316e-06, 0.1065949392609e+01, 0.1511046609763e+02,
0.1098402195201e-06, 0.2192508743837e+01, 0.1098880815746e+02,
0.1158191395315e-06, 0.4054411278650e+01, 0.5729506548653e+01,
0.9048475596241e-07, 0.5429764748518e+01, 0.9623688285163e+01,
0.8889853269023e-07, 0.5046586206575e+01, 0.6148010737701e+01,
0.1048694242164e-06, 0.2628858030806e+01, 0.6836645152238e+01,
0.1112308378646e-06, 0.4177292719907e+01, 0.1572083878776e+02,
0.8631729709901e-07, 0.1601345232557e+01, 0.6418140963190e+01,
0.8527816951664e-07, 0.2463888997513e+01, 0.1471231707864e+02,
0.7892139456991e-07, 0.3154022088718e+01, 0.2118763888447e+01,
0.1051782905236e-06, 0.4795035816088e+01, 0.1349867339771e+01,
0.1048219943164e-06, 0.2952983395230e+01, 0.5999216516294e+01,
0.7435760775143e-07, 0.5420547991464e+01, 0.6040347114260e+01,
0.9869574106949e-07, 0.3695646753667e+01, 0.6566935184597e+01,
0.9156886364226e-07, 0.3922675306609e+01, 0.5643178611111e+01,
0.7006834356188e-07, 0.1233968624861e+01, 0.6525804586632e+01,
0.9806170182601e-07, 0.1919542280684e+01, 0.2122839202813e+02,
0.9052289673607e-07, 0.4615902724369e+01, 0.4690479774488e+01,
0.7554200867893e-07, 0.1236863719072e+01, 0.1253985337760e+02,
0.8215741286498e-07, 0.3286800101559e+00, 0.1097355562493e+02,
0.7185178575397e-07, 0.5880942158367e+01, 0.6245048154254e+01,
0.7130726476180e-07, 0.7674871987661e+00, 0.6321103546637e+01,
0.6650894461162e-07, 0.6987129150116e+00, 0.5327476111629e+01,
0.7396888823688e-07, 0.3576824794443e+01, 0.5368044267797e+00,
0.7420588884775e-07, 0.5033615245369e+01, 0.2354323048545e+02,
0.6141181642908e-07, 0.9449927045673e+00, 0.1296430071988e+02,
0.6373557924058e-07, 0.6206342280341e+01, 0.9517183207817e+00,
0.6359474329261e-07, 0.5036079095757e+01, 0.1990745094947e+01,
0.5740173582646e-07, 0.6105106371350e+01, 0.9555997388169e+00,
0.7019864084602e-07, 0.7237747359018e+00, 0.5225775174439e+00,
0.6398054487042e-07, 0.3976367969666e+01, 0.2407292145756e+02,
0.7797092650498e-07, 0.4305423910623e+01, 0.2200391463820e+02,
0.6466760000900e-07, 0.3500136825200e+01, 0.5230807360890e+01,
0.7529417043890e-07, 0.3514779246100e+01, 0.1842262939178e+02,
0.6924571140892e-07, 0.2743457928679e+01, 0.1554202828031e+00,
0.6220798650222e-07, 0.2242598118209e+01, 0.1845107853235e+02,
0.5870209391853e-07, 0.2332832707527e+01, 0.6398972393349e+00,
0.6263953473888e-07, 0.2191105358956e+01, 0.6277552955062e+01,
0.6257781390012e-07, 0.4457559396698e+01, 0.6288598745829e+01,
0.5697304945123e-07, 0.3499234761404e+01, 0.1551045220144e+01,
0.6335438746791e-07, 0.6441691079251e+00, 0.5216580451554e+01,
0.6377258441152e-07, 0.2252599151092e+01, 0.5650292065779e+01,
0.6484841818165e-07, 0.1992812417646e+01, 0.1030928125552e+00,
0.4735551485250e-07, 0.3744672082942e+01, 0.1431416805965e+02,
0.4628595996170e-07, 0.1334226211745e+01, 0.5535693017924e+00,
0.6258152336933e-07, 0.4395836159154e+01, 0.2608790314060e+02,
0.6196171366594e-07, 0.2587043007997e+01, 0.8467247584405e+02,
0.6159556952126e-07, 0.4782499769128e+01, 0.2394243902548e+03,
0.4987741172394e-07, 0.7312257619924e+00, 0.7771377146812e+02,
0.5459280703142e-07, 0.3001376372532e+01, 0.6179983037890e+01,
0.4863461189999e-07, 0.3767222128541e+01, 0.9027992316901e+02,
0.5349912093158e-07, 0.3663594450273e+01, 0.6386168663001e+01,
0.5673725607806e-07, 0.4331187919049e+01, 0.6915859635113e+01,
0.4745485060512e-07, 0.5816195745518e+01, 0.6282970628506e+01,
0.4745379005326e-07, 0.8323672435672e+00, 0.6283181072386e+01,
0.4049002796321e-07, 0.3785023976293e+01, 0.6254626709878e+01,
0.4247084014515e-07, 0.2378220728783e+01, 0.7875671926403e+01,
0.4026912363055e-07, 0.2864103423269e+01, 0.6311524991013e+01,
0.4062935011774e-07, 0.2415408595975e+01, 0.3634620989887e+01,
0.5347771048509e-07, 0.3343479309801e+01, 0.2515860172507e+02,
0.4829494136505e-07, 0.2821742398262e+01, 0.5760498333002e+01,
0.4342554404599e-07, 0.5624662458712e+01, 0.7238675589263e+01,
0.4021599184361e-07, 0.5557250275009e+00, 0.1101510648075e+02,
0.4104900474558e-07, 0.3296691780005e+01, 0.6709674010002e+01,
0.4376532905131e-07, 0.3814443999443e+01, 0.6805653367890e+01,
0.3314590480650e-07, 0.3560229189250e+01, 0.1259245002418e+02,
0.3232421839643e-07, 0.5185389180568e+01, 0.1066495398892e+01,
0.3541176318876e-07, 0.3921381909679e+01, 0.9917696840332e+01,
0.3689831242681e-07, 0.4190658955386e+01, 0.1192625446156e+02,
0.3890605376774e-07, 0.5546023371097e+01, 0.7478166569050e-01,
0.3038559339780e-07, 0.6231032794494e+01, 0.1256621883632e+02,
0.3137083969782e-07, 0.6207063419190e+01, 0.4292330755499e+01,
0.4024004081854e-07, 0.1195257375713e+01, 0.1334167431096e+02,
0.3300234879283e-07, 0.1804694240998e+01, 0.1057540660594e+02,
0.3635399155575e-07, 0.5597811343500e+01, 0.6208294184755e+01,
0.3032668691356e-07, 0.3191059366530e+01, 0.1805292951336e+02,
0.2809652069058e-07, 0.4094348032570e+01, 0.3523159621801e-02,
0.3696955383823e-07, 0.5219282738794e+01, 0.5966683958112e+01,
0.3562894142503e-07, 0.1037247544554e+01, 0.6357857516136e+01,
0.3510598524148e-07, 0.1430020816116e+01, 0.6599467742779e+01,
0.3617736142953e-07, 0.3002911403677e+01, 0.6019991944201e+01,
0.2624524910730e-07, 0.2437046757292e+01, 0.6702560555334e+01,
0.2535824204490e-07, 0.1581594689647e+01, 0.3141537925223e+02,
0.3519787226257e-07, 0.5379863121521e+01, 0.2505706758577e+03,
0.2578406709982e-07, 0.4904222639329e+01, 0.1673046366289e+02,
0.3423887981473e-07, 0.3646448997315e+01, 0.6546159756691e+01,
0.2776083886467e-07, 0.3307829300144e+01, 0.1272157198369e+02,
0.3379592818379e-07, 0.1747541251125e+01, 0.1494531617769e+02,
0.3050255426284e-07, 0.1784689432607e-01, 0.4732030630302e+01,
0.2652378350236e-07, 0.4420055276260e+01, 0.5863591145557e+01,
0.2374498173768e-07, 0.3629773929208e+01, 0.2388894113936e+01,
0.2716451255140e-07, 0.3079623706780e+01, 0.1202934727411e+02,
0.3038583699229e-07, 0.3312487903507e+00, 0.1256608456547e+02,
0.2220681228760e-07, 0.5265520401774e+01, 0.1336244973887e+02,
0.3044156540912e-07, 0.4766664081250e+01, 0.2908881142201e+02,
0.2731859923561e-07, 0.5069146530691e+01, 0.1391601904066e+02,
0.2285603018171e-07, 0.5954935112271e+01, 0.6076890225335e+01,
0.2025006454555e-07, 0.4061789589267e+01, 0.4701116388778e+01,
0.2012597519804e-07, 0.2485047705241e+01, 0.6262720680387e+01,
0.2003406962258e-07, 0.4163779209320e+01, 0.6303431020504e+01,
0.2207863441371e-07, 0.6923839133828e+00, 0.6489261475556e+01,
0.2481374305624e-07, 0.5944173595676e+01, 0.1204357418345e+02,
0.2130923288870e-07, 0.4641013671967e+01, 0.5746271423666e+01,
0.2446370543391e-07, 0.6125796518757e+01, 0.1495633313810e+00,
0.1932492759052e-07, 0.2234572324504e+00, 0.1352175143971e+02,
0.2600122568049e-07, 0.4281012405440e+01, 0.4590910121555e+01,
0.2431754047488e-07, 0.1429943874870e+00, 0.1162474756779e+01,
0.1875902869209e-07, 0.9781803816948e+00, 0.6279194432410e+01,
0.1874381139426e-07, 0.5670368130173e+01, 0.6286957268481e+01,
0.2156696047173e-07, 0.2008985006833e+01, 0.1813929450232e+02,
0.1965076182484e-07, 0.2566186202453e+00, 0.4686889479442e+01,
0.2334816372359e-07, 0.4408121891493e+01, 0.1002183730415e+02,
0.1869937408802e-07, 0.5272745038656e+01, 0.2427287361862e+00,
0.2436236460883e-07, 0.4407720479029e+01, 0.9514313292143e+02,
0.1761365216611e-07, 0.1943892315074e+00, 0.1351787002167e+02,
0.2156289480503e-07, 0.1418570924545e+01, 0.6037244212485e+01,
0.2164748979255e-07, 0.4724603439430e+01, 0.2301353951334e+02,
0.2222286670853e-07, 0.2400266874598e+01, 0.1266924451345e+02,
0.2070901414929e-07, 0.5230348028732e+01, 0.6528907488406e+01,
0.1792745177020e-07, 0.2099190328945e+01, 0.6819880277225e+01,
0.1841802068445e-07, 0.3467527844848e+00, 0.6514761976723e+02,
0.1578401631718e-07, 0.7098642356340e+00, 0.2077542790660e-01,
0.1561690152531e-07, 0.5943349620372e+01, 0.6272439236156e+01,
0.1558591045463e-07, 0.7040653478980e+00, 0.6293712464735e+01,
0.1737356469576e-07, 0.4487064760345e+01, 0.1765478049437e+02,
0.1434755619991e-07, 0.2993391570995e+01, 0.1102062672231e+00,
0.1482187806654e-07, 0.2278049198251e+01, 0.1052268489556e+01,
0.1424812827089e-07, 0.1682114725827e+01, 0.1311972100268e+02,
0.1380282448623e-07, 0.3262668602579e+01, 0.1017725758696e+02,
0.1811481244566e-07, 0.3187771221777e+01, 0.1887552587463e+02,
0.1504446185696e-07, 0.5650162308647e+01, 0.7626583626240e-01,
0.1740776154137e-07, 0.5487068607507e+01, 0.1965104848470e+02,
0.1374339536251e-07, 0.5745688172201e+01, 0.6016468784579e+01,
0.1761377477704e-07, 0.5748060203659e+01, 0.2593412433514e+02,
0.1535138225795e-07, 0.6226848505790e+01, 0.9411464614024e+01,
0.1788140543676e-07, 0.6189318878563e+01, 0.3301902111895e+02,
0.1375002807996e-07, 0.5371812884394e+01, 0.6327837846670e+00,
0.1242115758632e-07, 0.1471687569712e+01, 0.3894181736510e+01,
0.1450977333938e-07, 0.4143836662127e+01, 0.1277945078067e+02,
0.1297579575023e-07, 0.9003477661957e+00, 0.6549682916313e+01,
0.1462667934821e-07, 0.5760505536428e+01, 0.1863592847156e+02,
0.1381774374799e-07, 0.1085471729463e+01, 0.2379164476796e+01,
0.1682333169307e-07, 0.5409870870133e+01, 0.1620077269078e+02,
0.1190812918837e-07, 0.1397205174601e+01, 0.1149965630200e+02,
0.1221434762106e-07, 0.9001804809095e+00, 0.1257326515556e+02,
0.1549934644860e-07, 0.4262528275544e+01, 0.1820933031200e+02,
0.1252138953050e-07, 0.1411642012027e+01, 0.6993008899458e+01,
0.1237078905387e-07, 0.2844472403615e+01, 0.2435678079171e+02,
0.1446953389615e-07, 0.5295835522223e+01, 0.3813291813120e-01,
0.1388446457170e-07, 0.4969428135497e+01, 0.2458316379602e+00,
0.1019339179228e-07, 0.2491369561806e+01, 0.6112403035119e+01,
0.1258880815343e-07, 0.4679426248976e+01, 0.5429879531333e+01,
0.1297768238261e-07, 0.1074509953328e+01, 0.1249137003520e+02,
0.9913505718094e-08, 0.4735097918224e+01, 0.6247047890016e+01,
0.9830453155969e-08, 0.4158649187338e+01, 0.6453748665772e+01,
0.1192615865309e-07, 0.3438208613699e+01, 0.6290122169689e+01,
0.9835874798277e-08, 0.1913300781229e+01, 0.6319103810876e+01,
0.9639087569277e-08, 0.9487683644125e+00, 0.8273820945392e+01,
0.1175716107001e-07, 0.3228141664287e+01, 0.6276029531202e+01,
0.1018926508678e-07, 0.2216607854300e+01, 0.1254537627298e+02,
0.9500087869225e-08, 0.2625116459733e+01, 0.1256517118505e+02,
0.9664192916575e-08, 0.5860562449214e+01, 0.6259197520765e+01,
0.9612858712203e-08, 0.7885682917381e+00, 0.6306954180126e+01,
0.1117645675413e-07, 0.3932148831189e+01, 0.1779695906178e+02,
0.1158864052160e-07, 0.9995605521691e+00, 0.1778273215245e+02,
0.9021043467028e-08, 0.5263769742673e+01, 0.6172869583223e+01,
0.8836134773563e-08, 0.1496843220365e+01, 0.1692165728891e+01,
0.1045872200691e-07, 0.7009039517214e+00, 0.2204125344462e+00,
0.1211463487798e-07, 0.4041544938511e+01, 0.8257698122054e+02,
0.8541990804094e-08, 0.1447586692316e+01, 0.6393282117669e+01,
0.1038720703636e-07, 0.4594249718112e+00, 0.1550861511662e+02,
0.1126722351445e-07, 0.3925550579036e+01, 0.2061856251104e+00,
0.8697373859631e-08, 0.4411341856037e+01, 0.9491756770005e+00,
0.8869380028441e-08, 0.2402659724813e+01, 0.3903911373650e+01,
0.9247014693258e-08, 0.1401579743423e+01, 0.6267823317922e+01,
0.9205062930950e-08, 0.5245978000814e+01, 0.6298328382969e+01,
0.8000745038049e-08, 0.3590803356945e+01, 0.2648454860559e+01,
0.9168973650819e-08, 0.2470150501679e+01, 0.1498544001348e+03,
0.1075444949238e-07, 0.1328606161230e+01, 0.3694923081589e+02,
0.7817298525817e-08, 0.6162256225998e+01, 0.4804209201333e+01,
0.9541469226356e-08, 0.3942568967039e+01, 0.1256713221673e+02,
0.9821910122027e-08, 0.2360246287233e+00, 0.1140367694411e+02,
0.9897822023777e-08, 0.4619805634280e+01, 0.2280573557157e+02,
0.7737289283765e-08, 0.3784727847451e+01, 0.7834121070590e+01,
0.9260204034710e-08, 0.2223352487601e+01, 0.2787043132925e+01,
0.7320252888486e-08, 0.1288694636874e+01, 0.6282655592598e+01,
0.7319785780946e-08, 0.5359869567774e+01, 0.6283496108294e+01,
0.7147219933778e-08, 0.5516616675856e+01, 0.1725663147538e+02,
0.7946502829878e-08, 0.2630459984567e+01, 0.1241073141809e+02,
0.9001711808932e-08, 0.2849815827227e+01, 0.6281591679874e+01,
0.8994041507257e-08, 0.3795244450750e+01, 0.6284560021018e+01,
0.8298582787358e-08, 0.5236413127363e+00, 0.1241658836951e+02,
0.8526596520710e-08, 0.4794605424426e+01, 0.1098419223922e+02,
0.8209822103197e-08, 0.1578752370328e+01, 0.1096996532989e+02,
0.6357049861094e-08, 0.5708926113761e+01, 0.1596186371003e+01,
0.7370473179049e-08, 0.3842402530241e+01, 0.4061219149443e+01,
0.7232154664726e-08, 0.3067548981535e+01, 0.1610006857377e+03,
0.6328765494903e-08, 0.1313930030069e+01, 0.1193336791622e+02,
0.8030064908595e-08, 0.3488500408886e+01, 0.8460828644453e+00,
0.6275464259232e-08, 0.1532061626198e+01, 0.8531963191132e+00,
0.7051897446325e-08, 0.3285859929993e+01, 0.5849364236221e+01,
0.6161593705428e-08, 0.1477341999464e+01, 0.5573142801433e+01,
0.7754683957278e-08, 0.1586118663096e+01, 0.8662240327241e+01,
0.5889928990701e-08, 0.1304887868803e+01, 0.1232342296471e+02,
0.5705756047075e-08, 0.4555333589350e+01, 0.1258692712880e+02,
0.5964178808332e-08, 0.3001762842062e+01, 0.5333900173445e+01,
0.6712446027467e-08, 0.4886780007595e+01, 0.1171295538178e+02,
0.5941809275464e-08, 0.4701509603824e+01, 0.9779108567966e+01,
0.5466993627395e-08, 0.4588357817278e+01, 0.1884211409667e+02,
0.6340512090980e-08, 0.1164543038893e+01, 0.5217580628120e+02,
0.6325505710045e-08, 0.3919171259645e+01, 0.1041998632314e+02,
0.6164789509685e-08, 0.2143828253542e+01, 0.6151533897323e+01,
0.5263330812430e-08, 0.6066564434241e+01, 0.1885275071096e+02,
0.5597087780221e-08, 0.2926316429472e+01, 0.4337116142245e+00,
0.5396556236817e-08, 0.3244303591505e+01, 0.6286362197481e+01,
0.5396615148223e-08, 0.3404304703662e+01, 0.6279789503410e+01,
0.7091832443341e-08, 0.8532377803192e+00, 0.4907302013889e+01,
0.6572352589782e-08, 0.4901966774419e+01, 0.1176433076753e+02,
0.5960236060795e-08, 0.1874672315797e+01, 0.1422690933580e-01,
0.5125480043511e-08, 0.3735726064334e+01, 0.1245594543367e+02,
0.5928241866410e-08, 0.4502033899935e+01, 0.6414617803568e+01,
0.5249600357424e-08, 0.4372334799878e+01, 0.1151388321134e+02,
0.6059171276087e-08, 0.2581617302908e+01, 0.6062663316000e+01,
0.5295235081662e-08, 0.2974811513158e+01, 0.3496032717521e+01,
0.5820561875933e-08, 0.1796073748244e+00, 0.2838593341516e+00,
0.4754696606440e-08, 0.1981998136973e+01, 0.3104930017775e+01,
0.6385053548955e-08, 0.2559174171605e+00, 0.6133512519065e+01,
0.6589828273941e-08, 0.2750967106776e+01, 0.4087944051283e+02,
0.5383376567189e-08, 0.6325947523578e+00, 0.2248384854122e+02,
0.5928941683538e-08, 0.1672304519067e+01, 0.1581959461667e+01,
0.4816060709794e-08, 0.3512566172575e+01, 0.9388005868221e+01,
0.6003381586512e-08, 0.5610932219189e+01, 0.5326786718777e+01,
0.5504225393105e-08, 0.4037501131256e+01, 0.6503488384892e+01,
0.5353772620129e-08, 0.6122774968240e+01, 0.1735668374386e+03,
0.5786253768544e-08, 0.5527984999515e+01, 0.1350651127443e+00,
0.5065706702002e-08, 0.9980765573624e+00, 0.1248988586463e+02,
0.5972838885276e-08, 0.6044489493203e+01, 0.2673594526851e+02,
0.5323585877961e-08, 0.3924265998147e+01, 0.4171425416666e+01,
0.5210772682858e-08, 0.6220111376901e+01, 0.2460261242967e+02,
0.4726549040535e-08, 0.3716043206862e+01, 0.7232251527446e+01,
0.6029425105059e-08, 0.8548704071116e+00, 0.3227113045244e+03,
0.4481542826513e-08, 0.1426925072829e+01, 0.5547199253223e+01,
0.5836024505068e-08, 0.7135651752625e-01, 0.7285056171570e+02,
0.4137046613272e-08, 0.5330767643283e+01, 0.1087398597200e+02,
0.5171977473924e-08, 0.4494262335353e+00, 0.1884570439172e+02,
0.5694429833732e-08, 0.2952369582215e+01, 0.9723862754494e+02,
0.4009158925298e-08, 0.3500003416535e+01, 0.6244942932314e+01,
0.4784939596873e-08, 0.6196709413181e+01, 0.2929661536378e+02,
0.3983725022610e-08, 0.5103690031897e+01, 0.4274518229222e+01,
0.3870535232462e-08, 0.3187569587401e+01, 0.6321208768577e+01,
0.5140501213951e-08, 0.1668924357457e+01, 0.1232032006293e+02,
0.3849034819355e-08, 0.4445722510309e+01, 0.1726726808967e+02,
0.4002383075060e-08, 0.5226224152423e+01, 0.7018952447668e+01,
0.3890719543549e-08, 0.4371166550274e+01, 0.1491901785440e+02,
0.4887084607881e-08, 0.5973556689693e+01, 0.1478866649112e+01,
0.3739939287592e-08, 0.2089084714600e+01, 0.6922973089781e+01,
0.5031925918209e-08, 0.4658371936827e+01, 0.1715706182245e+02,
0.4387748764954e-08, 0.4825580552819e+01, 0.2331413144044e+03,
0.4147398098865e-08, 0.3739003524998e+01, 0.1376059875786e+02,
0.3719089993586e-08, 0.1148941386536e+01, 0.6297302759782e+01,
0.3934238461056e-08, 0.1559893008343e+01, 0.7872148766781e+01,
0.3672471375622e-08, 0.5516145383612e+01, 0.6268848941110e+01,
0.3768911277583e-08, 0.6116053700563e+01, 0.4157198507331e+01,
0.4033388417295e-08, 0.5076821746017e+01, 0.1567108171867e+02,
0.3764194617832e-08, 0.8164676232075e+00, 0.3185192151914e+01,
0.4840628226284e-08, 0.1360479453671e+01, 0.1252801878276e+02,
0.4949443923785e-08, 0.2725622229926e+01, 0.1617106187867e+03,
0.4117393089971e-08, 0.6054459628492e+00, 0.5642198095270e+01,
0.3925754020428e-08, 0.8570462135210e+00, 0.2139354194808e+02,
0.3630551757923e-08, 0.3552067338279e+01, 0.6294805223347e+01,
0.3627274802357e-08, 0.3096565085313e+01, 0.6271346477544e+01,
0.3806143885093e-08, 0.6367751709777e+00, 0.1725304118033e+02,
0.4433254641565e-08, 0.4848461503937e+01, 0.7445550607224e+01,
0.3712319846576e-08, 0.1331950643655e+01, 0.4194847048887e+00,
0.3849847534783e-08, 0.4958368297746e+00, 0.9562891316684e+00,
0.3483955430165e-08, 0.2237215515707e+01, 0.1161697602389e+02,
0.3961912730982e-08, 0.3332402188575e+01, 0.2277943724828e+02,
0.3419978244481e-08, 0.5785600576016e+01, 0.1362553364512e+02,
0.3329417758177e-08, 0.9812676559709e-01, 0.1685848245639e+02,
0.4207206893193e-08, 0.9494780468236e+00, 0.2986433403208e+02,
0.3268548976410e-08, 0.1739332095686e+00, 0.5749861718712e+01,
0.3321880082685e-08, 0.1423354800666e+01, 0.6279143387820e+01,
0.4503173010852e-08, 0.2314972675293e+00, 0.1385561574497e+01,
0.4316599090954e-08, 0.1012646782616e+00, 0.4176041334900e+01,
0.3283493323850e-08, 0.5233306881265e+01, 0.6287008313071e+01,
0.3164033542343e-08, 0.4005597257511e+01, 0.2099539292909e+02,
0.4159720956725e-08, 0.5365676242020e+01, 0.5905702259363e+01,
0.3565176892217e-08, 0.4284440620612e+01, 0.3932462625300e-02,
0.3514440950221e-08, 0.4270562636575e+01, 0.7335344340001e+01,
0.3540596871909e-08, 0.5953553201060e+01, 0.1234573916645e+02,
0.2960769905118e-08, 0.1115180417718e+01, 0.2670964694522e+02,
0.2962213739684e-08, 0.3863811918186e+01, 0.6408777551755e+00,
0.3883556700251e-08, 0.1268617928302e+01, 0.6660449441528e+01,
0.2919225516346e-08, 0.4908605223265e+01, 0.1375773836557e+01,
0.3115158863370e-08, 0.3744519976885e+01, 0.3802769619140e-01,
0.4099438144212e-08, 0.4173244670532e+01, 0.4480965020977e+02,
0.2899531858964e-08, 0.5910601428850e+01, 0.2059724391010e+02,
0.3289733429855e-08, 0.2488050078239e+01, 0.1081813534213e+02,
0.3933075612875e-08, 0.1122363652883e+01, 0.3773735910827e+00,
0.3021403764467e-08, 0.4951973724904e+01, 0.2982630633589e+02,
0.2798598949757e-08, 0.5117057845513e+01, 0.1937891852345e+02,
0.3397421302707e-08, 0.6104159180476e+01, 0.6923953605621e+01,
0.3720398002179e-08, 0.1184933429829e+01, 0.3066615496545e+02,
0.3598484186267e-08, 0.3505282086105e+01, 0.6147450479709e+01,
0.3694594027310e-08, 0.2286651088141e+01, 0.2636725487657e+01,
0.2680444152969e-08, 0.1871816775482e+00, 0.6816289982179e+01,
0.3497574865641e-08, 0.3143251755431e+01, 0.6418701221183e+01,
0.3130274129494e-08, 0.2462167316018e+01, 0.1235996607578e+02,
0.3241119069551e-08, 0.4256374004686e+01, 0.1652265972112e+02,
0.2601960842061e-08, 0.4970362941425e+01, 0.1045450126711e+02,
0.2690601527504e-08, 0.2372657824898e+01, 0.3163918923335e+00,
0.2908688152664e-08, 0.4232652627721e+01, 0.2828699048865e+02,
0.3120456131875e-08, 0.3925747001137e+00, 0.2195415756911e+02,
0.3148855423384e-08, 0.3093478330445e+01, 0.1172006883645e+02,
0.3051044261017e-08, 0.5560948248212e+01, 0.6055599646783e+01,
0.2826006876660e-08, 0.5072790310072e+01, 0.5120601093667e+01,
0.3100034191711e-08, 0.4998530231096e+01, 0.1799603123222e+02,
0.2398771640101e-08, 0.2561739802176e+01, 0.6255674361143e+01,
0.2384002842728e-08, 0.4087420284111e+01, 0.6310477339748e+01,
0.2842146517568e-08, 0.2515048217955e+01, 0.5469525544182e+01,
0.2847674371340e-08, 0.5235326497443e+01, 0.1034429499989e+02,
0.2903722140764e-08, 0.1088200795797e+01, 0.6510552054109e+01,
0.3187610710605e-08, 0.4710624424816e+01, 0.1693792562116e+03,
0.3048869992813e-08, 0.2857975896445e+00, 0.8390110365991e+01,
0.2860216950984e-08, 0.2241619020815e+01, 0.2243449970715e+00,
0.2701117683113e-08, 0.6651573305272e-01, 0.6129297044991e+01,
0.2509891590152e-08, 0.1285135324585e+01, 0.1044027435778e+02,
0.2623200252223e-08, 0.2981229834530e+00, 0.6436854655901e+01,
0.2622541669202e-08, 0.6122470726189e+01, 0.9380959548977e+01,
0.2818435667099e-08, 0.4251087148947e+01, 0.5934151399930e+01,
0.2365196797465e-08, 0.3465070460790e+01, 0.2470570524223e+02,
0.2358704646143e-08, 0.5791603815350e+01, 0.8671969964381e+01,
0.2388299481390e-08, 0.4142483772941e+01, 0.7096626156709e+01,
0.1996041217224e-08, 0.2101901889496e+01, 0.1727188400790e+02,
0.2687593060336e-08, 0.1526689456959e+01, 0.7075506709219e+02,
0.2618913670810e-08, 0.2397684236095e+01, 0.6632000300961e+01,
0.2571523050364e-08, 0.5751929456787e+00, 0.6206810014183e+01,
0.2582135006946e-08, 0.5595464352926e+01, 0.4873985990671e+02,
0.2372530190361e-08, 0.5092689490655e+01, 0.1590676413561e+02,
0.2357178484712e-08, 0.4444363527851e+01, 0.3097883698531e+01,
0.2451590394723e-08, 0.3108251687661e+01, 0.6612329252343e+00,
0.2370045949608e-08, 0.2608133861079e+01, 0.3459636466239e+02,
0.2268997267358e-08, 0.3639717753384e+01, 0.2844914056730e-01,
0.1731432137906e-08, 0.1741898445707e+00, 0.2019909489111e+02,
0.1629869741622e-08, 0.3902225646724e+01, 0.3035599730800e+02,
0.2206215801974e-08, 0.4971131250731e+01, 0.6281667977667e+01,
0.2205469554680e-08, 0.1677462357110e+01, 0.6284483723224e+01,
0.2148792362509e-08, 0.4236259604006e+01, 0.1980482729015e+02,
0.1873733657847e-08, 0.5926814998687e+01, 0.2876692439167e+02,
0.2026573758959e-08, 0.4349643351962e+01, 0.2449240616245e+02,
0.1807770325110e-08, 0.5700940482701e+01, 0.2045286941806e+02,
0.1881174408581e-08, 0.6601286363430e+00, 0.2358125818164e+02,
0.1368023671690e-08, 0.2211098592752e+01, 0.2473415438279e+02,
0.1720017916280e-08, 0.4942488551129e+01, 0.1679593901136e+03,
0.1702427665131e-08, 0.1452233856386e+01, 0.3338575901272e+03,
0.1414032510054e-08, 0.5525357721439e+01, 0.1624205518357e+03,
0.1652626045364e-08, 0.4108794283624e+01, 0.8956999012000e+02,
0.1642957769686e-08, 0.7344335209984e+00, 0.5267006960365e+02,
0.1614952403624e-08, 0.3541213951363e+01, 0.3332657872986e+02,
0.1535988291188e-08, 0.4031094072151e+01, 0.3852657435933e+02,
0.1593193738177e-08, 0.4185136203609e+01, 0.2282781046519e+03,
0.1074569126382e-08, 0.1720485636868e+01, 0.8397383534231e+02,
0.1074408214509e-08, 0.2758613420318e+01, 0.8401985929482e+02,
0.9700199670465e-09, 0.4216686842097e+01, 0.7826370942180e+02,
0.1258433517061e-08, 0.2575068876639e+00, 0.3115650189215e+03,
0.1240303229539e-08, 0.4800844956756e+00, 0.1784300471910e+03,
0.9018345948127e-09, 0.3896756361552e+00, 0.5886454391678e+02,
0.1135301432805e-08, 0.3700805023550e+00, 0.7842370451713e+02,
0.9215887951370e-09, 0.4364579276638e+01, 0.1014262087719e+03,
0.1055401054147e-08, 0.2156564222111e+01, 0.5660027930059e+02,
0.1008725979831e-08, 0.5454015785234e+01, 0.4245678405627e+02,
0.7217398104321e-09, 0.1597772562175e+01, 0.2457074661053e+03,
0.6912033134447e-09, 0.5824090621461e+01, 0.1679936946371e+03,
0.6833881523549e-09, 0.3578778482835e+01, 0.6053048899753e+02,
0.4887304205142e-09, 0.3724362812423e+01, 0.9656299901946e+02,
0.5173709754788e-09, 0.5422427507933e+01, 0.2442876000072e+03,
0.4671353097145e-09, 0.2396106924439e+01, 0.1435713242844e+03,
0.5652608439480e-09, 0.2804028838685e+01, 0.8365903305582e+02,
0.5604061331253e-09, 0.1638816006247e+01, 0.8433466158131e+02,
0.4712723365400e-09, 0.8979003224474e+00, 0.3164282286739e+03,
0.4909967465112e-09, 0.3210426725516e+01, 0.4059982187939e+03,
0.4771358267658e-09, 0.5308027211629e+01, 0.1805255418145e+03,
0.3943451445989e-09, 0.2195145341074e+01, 0.2568537517081e+03,
0.3952109120244e-09, 0.5081189491586e+01, 0.2449975330562e+03,
0.3788134594789e-09, 0.4345171264441e+01, 0.1568131045107e+03,
0.3738330190479e-09, 0.2613062847997e+01, 0.3948519331910e+03,
0.3099866678136e-09, 0.2846760817689e+01, 0.1547176098872e+03,
0.2002962716768e-09, 0.4921360989412e+01, 0.2268582385539e+03,
0.2198291338754e-09, 0.1130360117454e+00, 0.1658638954901e+03,
0.1491958330784e-09, 0.4228195232278e+01, 0.2219950288015e+03,
0.1475384076173e-09, 0.3005721811604e+00, 0.3052819430710e+03,
0.1661626624624e-09, 0.7830125621203e+00, 0.2526661704812e+03,
0.9015823460025e-10, 0.3807792942715e+01, 0.4171445043968e+03}
/* Sun-to-Earth, T^0, Y */
e0y := []float64{
0.9998921098898e+00, 0.1826583913846e+00, 0.6283075850446e+01,
-0.2442700893735e-01, 0.0000000000000e+00, 0.0000000000000e+00,
0.8352929742915e-02, 0.1395277998680e+00, 0.1256615170089e+02,
0.1046697300177e-03, 0.9641423109763e-01, 0.1884922755134e+02,
0.3110841876663e-04, 0.5381140401712e+01, 0.8399684731857e+02,
0.2570269094593e-04, 0.5301016407128e+01, 0.5296909721118e+00,
0.2147389623610e-04, 0.2662510869850e+01, 0.1577343543434e+01,
0.1680344384050e-04, 0.5207904119704e+01, 0.6279552690824e+01,
0.1679117312193e-04, 0.4582187486968e+01, 0.6286599010068e+01,
0.1440512068440e-04, 0.1900688517726e+01, 0.2352866153506e+01,
0.1135139664999e-04, 0.5273108538556e+01, 0.5223693906222e+01,
0.9345482571018e-05, 0.4503047687738e+01, 0.1203646072878e+02,
0.9007418719568e-05, 0.1605621059637e+01, 0.1021328554739e+02,
0.5671536712314e-05, 0.5812849070861e+00, 0.1059381944224e+01,
0.7451401861666e-05, 0.2807346794836e+01, 0.3981490189893e+00,
0.6393470057114e-05, 0.6029224133855e+01, 0.5753384878334e+01,
0.6814275881697e-05, 0.6472990145974e+00, 0.4705732307012e+01,
0.6113705628887e-05, 0.3813843419700e+01, 0.6812766822558e+01,
0.4503851367273e-05, 0.4527804370996e+01, 0.5884926831456e+01,
0.4522249141926e-05, 0.5991783029224e+01, 0.6256777527156e+01,
0.4501794307018e-05, 0.3798703844397e+01, 0.6309374173736e+01,
0.5514927480180e-05, 0.3961257833388e+01, 0.5507553240374e+01,
0.4062862799995e-05, 0.5256247296369e+01, 0.6681224869435e+01,
0.5414900429712e-05, 0.5499032014097e+01, 0.7755226100720e+00,
0.5463153987424e-05, 0.6173092454097e+01, 0.1414349524433e+02,
0.5071611859329e-05, 0.2870244247651e+01, 0.7860419393880e+01,
0.2195112094455e-05, 0.2952338617201e+01, 0.1150676975667e+02,
0.2279139233919e-05, 0.5951775132933e+01, 0.7058598460518e+01,
0.2278386100876e-05, 0.4845456398785e+01, 0.4694002934110e+01,
0.2559088003308e-05, 0.6945321117311e+00, 0.1216800268190e+02,
0.2561079286856e-05, 0.6167224608301e+01, 0.7099330490126e+00,
0.1792755796387e-05, 0.1400122509632e+01, 0.7962980379786e+00,
0.1818715656502e-05, 0.4703347611830e+01, 0.6283142985870e+01,
0.1818744924791e-05, 0.5086748900237e+01, 0.6283008715021e+01,
0.1554518791390e-05, 0.5331008042713e-01, 0.2513230340178e+02,
0.2063265737239e-05, 0.4283680484178e+01, 0.1179062909082e+02,
0.1497613520041e-05, 0.6074207826073e+01, 0.5486777812467e+01,
0.2000617940427e-05, 0.2501426281450e+01, 0.1778984560711e+02,
0.1289731195580e-05, 0.3646340599536e+01, 0.7079373888424e+01,
0.1282657998934e-05, 0.3232864804902e+01, 0.3738761453707e+01,
0.1528915968658e-05, 0.5581433416669e+01, 0.2132990797783e+00,
0.1187304098432e-05, 0.5453576453694e+01, 0.9437762937313e+01,
0.7842782928118e-06, 0.2823953922273e+00, 0.8827390247185e+01,
0.7352892280868e-06, 0.1124369580175e+01, 0.1589072916335e+01,
0.6570189360797e-06, 0.2089154042840e+01, 0.1176985366291e+02,
0.6324967590410e-06, 0.6704855581230e+00, 0.6262300422539e+01,
0.6298289872283e-06, 0.2836414855840e+01, 0.6303851278352e+01,
0.6476686465855e-06, 0.4852433866467e+00, 0.7113454667900e-02,
0.8587034651234e-06, 0.1453511005668e+01, 0.1672837615881e+03,
0.8068948788113e-06, 0.9224087798609e+00, 0.6069776770667e+01,
0.8353786011661e-06, 0.4631707184895e+01, 0.3340612434717e+01,
0.6009324532132e-06, 0.1829498827726e+01, 0.4136910472696e+01,
0.7558158559566e-06, 0.2588596800317e+01, 0.6496374930224e+01,
0.5809279504503e-06, 0.5516818853476e+00, 0.1097707878456e+02,
0.5374131950254e-06, 0.6275674734960e+01, 0.1194447056968e+01,
0.5711160507326e-06, 0.1091905956872e+01, 0.6282095334605e+01,
0.5710183170746e-06, 0.2415001635090e+01, 0.6284056366286e+01,
0.5144373590610e-06, 0.6020336443438e+01, 0.6290189305114e+01,
0.5103108927267e-06, 0.3775634564605e+01, 0.6275962395778e+01,
0.4960654697891e-06, 0.1073450946756e+01, 0.6127655567643e+01,
0.4786385689280e-06, 0.2431178012310e+01, 0.6438496133249e+01,
0.6109911263665e-06, 0.5343356157914e+01, 0.3154687086868e+01,
0.4839898944024e-06, 0.5830833594047e-01, 0.8018209333619e+00,
0.4734822623919e-06, 0.4536080134821e+01, 0.3128388763578e+01,
0.4834741473290e-06, 0.2585090489754e+00, 0.7084896783808e+01,
0.5134858581156e-06, 0.4213317172603e+01, 0.1235285262111e+02,
0.5064004264978e-06, 0.4814418806478e+00, 0.1185621865188e+02,
0.3753476772761e-06, 0.1599953399788e+01, 0.8429241228195e+01,
0.4935264014283e-06, 0.2157417556873e+01, 0.2544314396739e+01,
0.3950929600897e-06, 0.3359394184254e+01, 0.5481254917084e+01,
0.4895849789777e-06, 0.5165704376558e+01, 0.9225539266174e+01,
0.4215241688886e-06, 0.2065368800993e+01, 0.1726015463500e+02,
0.3796773731132e-06, 0.1468606346612e+01, 0.4265981595566e+00,
0.3114178142515e-06, 0.3615638079474e+01, 0.2146165377750e+01,
0.3260664220838e-06, 0.4417134922435e+01, 0.4164311961999e+01,
0.3976996123008e-06, 0.4700866883004e+01, 0.5856477690889e+01,
0.2801459672924e-06, 0.4538902060922e+01, 0.1256967486051e+02,
0.3638931868861e-06, 0.1334197991475e+01, 0.1807370494127e+02,
0.2487013269476e-06, 0.3749275558275e+01, 0.2629832328990e-01,
0.3034165481994e-06, 0.4236622030873e+00, 0.4535059491685e+01,
0.2676278825586e-06, 0.5970848007811e+01, 0.3930209696940e+01,
0.2764903818918e-06, 0.5194636754501e+01, 0.1256262854127e+02,
0.2485149930507e-06, 0.1002434207846e+01, 0.5088628793478e+01,
0.2199305540941e-06, 0.3066773098403e+01, 0.1255903824622e+02,
0.2571106500435e-06, 0.7588312459063e+00, 0.1336797263425e+02,
0.2049751817158e-06, 0.3444977434856e+01, 0.1137170464392e+02,
0.2599707296297e-06, 0.1873128542205e+01, 0.7143069561767e+02,
0.1785018072217e-06, 0.5015891306615e+01, 0.1748016358760e+01,
0.2324833891115e-06, 0.4618271239730e+01, 0.1831953657923e+02,
0.1709711119545e-06, 0.5300003455669e+01, 0.4933208510675e+01,
0.2107159351716e-06, 0.2229819815115e+01, 0.7477522907414e+01,
0.1750333080295e-06, 0.6161485880008e+01, 0.1044738781244e+02,
0.2000598210339e-06, 0.2967357299999e+01, 0.8031092209206e+01,
0.1380920248681e-06, 0.3027007923917e+01, 0.8635942003952e+01,
0.1412460470299e-06, 0.6037597163798e+01, 0.2942463415728e+01,
0.1888459803001e-06, 0.8561476243374e+00, 0.1561374759853e+03,
0.1788370542585e-06, 0.4869736290209e+01, 0.1592596075957e+01,
0.1360893296167e-06, 0.3626411886436e+01, 0.1309584267300e+02,
0.1506846530160e-06, 0.1550975377427e+01, 0.1649636139783e+02,
0.1800913376176e-06, 0.2075826033190e+01, 0.1729818233119e+02,
0.1436261390649e-06, 0.6148876420255e+01, 0.2042657109477e+02,
0.1220227114151e-06, 0.4382583879906e+01, 0.7632943190217e+01,
0.1337883603592e-06, 0.2036644327361e+01, 0.1213955354133e+02,
0.1159326650738e-06, 0.3892276994687e+01, 0.5331357529664e+01,
0.1352853128569e-06, 0.1447950649744e+01, 0.1673046366289e+02,
0.1433408296083e-06, 0.4457854692961e+01, 0.7342457794669e+01,
0.1234701666518e-06, 0.1538818147151e+01, 0.6279485555400e+01,
0.1234027192007e-06, 0.1968523220760e+01, 0.6286666145492e+01,
0.1244024091797e-06, 0.5779803499985e+01, 0.1511046609763e+02,
0.1097934945516e-06, 0.6210975221388e+00, 0.1098880815746e+02,
0.1254611329856e-06, 0.2591963807998e+01, 0.1572083878776e+02,
0.1158247286784e-06, 0.2483612812670e+01, 0.5729506548653e+01,
0.9039078252960e-07, 0.3857554579796e+01, 0.9623688285163e+01,
0.9108024978836e-07, 0.5826368512984e+01, 0.7234794171227e+01,
0.8887068108436e-07, 0.3475694573987e+01, 0.6148010737701e+01,
0.8632374035438e-07, 0.3059070488983e-01, 0.6418140963190e+01,
0.7893186992967e-07, 0.1583194837728e+01, 0.2118763888447e+01,
0.8297650201172e-07, 0.8519770534637e+00, 0.1471231707864e+02,
0.1019759578988e-06, 0.1319598738732e+00, 0.1349867339771e+01,
0.1010037696236e-06, 0.9937860115618e+00, 0.6836645152238e+01,
0.1047727548266e-06, 0.1382138405399e+01, 0.5999216516294e+01,
0.7351993881086e-07, 0.3833397851735e+01, 0.6040347114260e+01,
0.9868771092341e-07, 0.2124913814390e+01, 0.6566935184597e+01,
0.7007321959390e-07, 0.5946305343763e+01, 0.6525804586632e+01,
0.6861411679709e-07, 0.4574654977089e+01, 0.7238675589263e+01,
0.7554519809614e-07, 0.5949232686844e+01, 0.1253985337760e+02,
0.9541880448335e-07, 0.3495242990564e+01, 0.2122839202813e+02,
0.7185606722155e-07, 0.4310113471661e+01, 0.6245048154254e+01,
0.7131360871710e-07, 0.5480309323650e+01, 0.6321103546637e+01,
0.6651142021039e-07, 0.5411097713654e+01, 0.5327476111629e+01,
0.8538618213667e-07, 0.1827849973951e+01, 0.1101510648075e+02,
0.8634954288044e-07, 0.5443584943349e+01, 0.5643178611111e+01,
0.7449415051484e-07, 0.2011535459060e+01, 0.5368044267797e+00,
0.7421047599169e-07, 0.3464562529249e+01, 0.2354323048545e+02,
0.6140694354424e-07, 0.5657556228815e+01, 0.1296430071988e+02,
0.6353525143033e-07, 0.3463816593821e+01, 0.1990745094947e+01,
0.6221964013447e-07, 0.1532259498697e+01, 0.9517183207817e+00,
0.5852480257244e-07, 0.1375396598875e+01, 0.9555997388169e+00,
0.6398637498911e-07, 0.2405645801972e+01, 0.2407292145756e+02,
0.7039744069878e-07, 0.5397541799027e+01, 0.5225775174439e+00,
0.6977997694382e-07, 0.4762347105419e+01, 0.1097355562493e+02,
0.7460629558396e-07, 0.2711944692164e+01, 0.2200391463820e+02,
0.5376577536101e-07, 0.2352980430239e+01, 0.1431416805965e+02,
0.7530607893556e-07, 0.1943940180699e+01, 0.1842262939178e+02,
0.6822928971605e-07, 0.4337651846959e+01, 0.1554202828031e+00,
0.6220772380094e-07, 0.6716871369278e+00, 0.1845107853235e+02,
0.6586950799043e-07, 0.2229714460505e+01, 0.5216580451554e+01,
0.5873800565771e-07, 0.7627013920580e+00, 0.6398972393349e+00,
0.6264346929745e-07, 0.6202785478961e+00, 0.6277552955062e+01,
0.6257929115669e-07, 0.2886775596668e+01, 0.6288598745829e+01,
0.5343536033409e-07, 0.1977241012051e+01, 0.4690479774488e+01,
0.5587849781714e-07, 0.1922923484825e+01, 0.1551045220144e+01,
0.6905100845603e-07, 0.3570757164631e+01, 0.1030928125552e+00,
0.6178957066649e-07, 0.5197558947765e+01, 0.5230807360890e+01,
0.6187270224331e-07, 0.8193497368922e+00, 0.5650292065779e+01,
0.5385664291426e-07, 0.5406336665586e+01, 0.7771377146812e+02,
0.6329363917926e-07, 0.2837760654536e+01, 0.2608790314060e+02,
0.4546018761604e-07, 0.2933580297050e+01, 0.5535693017924e+00,
0.6196091049375e-07, 0.4157871494377e+01, 0.8467247584405e+02,
0.6159555108218e-07, 0.3211703561703e+01, 0.2394243902548e+03,
0.4995340539317e-07, 0.1459098102922e+01, 0.4732030630302e+01,
0.5457031243572e-07, 0.1430457676136e+01, 0.6179983037890e+01,
0.4863461418397e-07, 0.2196425916730e+01, 0.9027992316901e+02,
0.5342947626870e-07, 0.2086612890268e+01, 0.6386168663001e+01,
0.5674296648439e-07, 0.2760204966535e+01, 0.6915859635113e+01,
0.4745783120161e-07, 0.4245368971862e+01, 0.6282970628506e+01,
0.4745676961198e-07, 0.5544725787016e+01, 0.6283181072386e+01,
0.4049796869973e-07, 0.2213984363586e+01, 0.6254626709878e+01,
0.4248333596940e-07, 0.8075781952896e+00, 0.7875671926403e+01,
0.4027178070205e-07, 0.1293268540378e+01, 0.6311524991013e+01,
0.4066543943476e-07, 0.3986141175804e+01, 0.3634620989887e+01,
0.4858863787880e-07, 0.1276112738231e+01, 0.5760498333002e+01,
0.5277398263530e-07, 0.4916111741527e+01, 0.2515860172507e+02,
0.4105635656559e-07, 0.1725805864426e+01, 0.6709674010002e+01,
0.4376781925772e-07, 0.2243642442106e+01, 0.6805653367890e+01,
0.3235827894693e-07, 0.3614135118271e+01, 0.1066495398892e+01,
0.3073244740308e-07, 0.2460873393460e+01, 0.5863591145557e+01,
0.3088609271373e-07, 0.5678431771790e+01, 0.9917696840332e+01,
0.3393022279836e-07, 0.3814017477291e+01, 0.1391601904066e+02,
0.3038686508802e-07, 0.4660216229171e+01, 0.1256621883632e+02,
0.4019677752497e-07, 0.5906906243735e+01, 0.1334167431096e+02,
0.3288834998232e-07, 0.9536146445882e+00, 0.1620077269078e+02,
0.3889973794631e-07, 0.3942205097644e+01, 0.7478166569050e-01,
0.3050438987141e-07, 0.1624810271286e+01, 0.1805292951336e+02,
0.3601142564638e-07, 0.4030467142575e+01, 0.6208294184755e+01,
0.3689015557141e-07, 0.3648878818694e+01, 0.5966683958112e+01,
0.3563471893565e-07, 0.5749584017096e+01, 0.6357857516136e+01,
0.2776183170667e-07, 0.2630124187070e+01, 0.3523159621801e-02,
0.2922350530341e-07, 0.1790346403629e+01, 0.1272157198369e+02,
0.3511076917302e-07, 0.6142198301611e+01, 0.6599467742779e+01,
0.3619351007632e-07, 0.1432421386492e+01, 0.6019991944201e+01,
0.2561254711098e-07, 0.2302822475792e+01, 0.1259245002418e+02,
0.2626903942920e-07, 0.8660470994571e+00, 0.6702560555334e+01,
0.2550187397083e-07, 0.6069721995383e+01, 0.1057540660594e+02,
0.2535873526138e-07, 0.1079020331795e-01, 0.3141537925223e+02,
0.3519786153847e-07, 0.3809066902283e+01, 0.2505706758577e+03,
0.3424651492873e-07, 0.2075435114417e+01, 0.6546159756691e+01,
0.2372676630861e-07, 0.2057803120154e+01, 0.2388894113936e+01,
0.2710980779541e-07, 0.1510068488010e+01, 0.1202934727411e+02,
0.3038710889704e-07, 0.5043617528901e+01, 0.1256608456547e+02,
0.2220364130585e-07, 0.3694793218205e+01, 0.1336244973887e+02,
0.3025880825460e-07, 0.5450618999049e-01, 0.2908881142201e+02,
0.2784493486864e-07, 0.3381164084502e+01, 0.1494531617769e+02,
0.2294414142438e-07, 0.4382309025210e+01, 0.6076890225335e+01,
0.2012723294724e-07, 0.9142212256518e+00, 0.6262720680387e+01,
0.2036357831958e-07, 0.5676172293154e+01, 0.4701116388778e+01,
0.2003474823288e-07, 0.2592767977625e+01, 0.6303431020504e+01,
0.2207144900109e-07, 0.5404976271180e+01, 0.6489261475556e+01,
0.2481664905135e-07, 0.4373284587027e+01, 0.1204357418345e+02,
0.2674949182295e-07, 0.5859182188482e+01, 0.4590910121555e+01,
0.2450554720322e-07, 0.4555381557451e+01, 0.1495633313810e+00,
0.2601975986457e-07, 0.3933165584959e+01, 0.1965104848470e+02,
0.2199860022848e-07, 0.5227977189087e+01, 0.1351787002167e+02,
0.2448121172316e-07, 0.4858060353949e+01, 0.1162474756779e+01,
0.1876014864049e-07, 0.5690546553605e+01, 0.6279194432410e+01,
0.1874513219396e-07, 0.4099539297446e+01, 0.6286957268481e+01,
0.2156380842559e-07, 0.4382594769913e+00, 0.1813929450232e+02,
0.1981691240061e-07, 0.1829784152444e+01, 0.4686889479442e+01,
0.2329992648539e-07, 0.2836254278973e+01, 0.1002183730415e+02,
0.1765184135302e-07, 0.2803494925833e+01, 0.4292330755499e+01,
0.2436368366085e-07, 0.2836897959677e+01, 0.9514313292143e+02,
0.2164089203889e-07, 0.6127522446024e+01, 0.6037244212485e+01,
0.1847755034221e-07, 0.3683163635008e+01, 0.2427287361862e+00,
0.1674798769966e-07, 0.3316993867246e+00, 0.1311972100268e+02,
0.2222542124356e-07, 0.8294097805480e+00, 0.1266924451345e+02,
0.2071074505925e-07, 0.3659492220261e+01, 0.6528907488406e+01,
0.1608224471835e-07, 0.4774492067182e+01, 0.1352175143971e+02,
0.1857583439071e-07, 0.2873120597682e+01, 0.8662240327241e+01,
0.1793018836159e-07, 0.5282441177929e+00, 0.6819880277225e+01,
0.1575391221692e-07, 0.1320789654258e+01, 0.1102062672231e+00,
0.1840132009557e-07, 0.1917110916256e+01, 0.6514761976723e+02,
0.1760917288281e-07, 0.2972635937132e+01, 0.5746271423666e+01,
0.1561779518516e-07, 0.4372569261981e+01, 0.6272439236156e+01,
0.1558687885205e-07, 0.5416424926425e+01, 0.6293712464735e+01,
0.1951359382579e-07, 0.3094448898752e+01, 0.2301353951334e+02,
0.1569144275614e-07, 0.2802103689808e+01, 0.1765478049437e+02,
0.1479130389462e-07, 0.2136435020467e+01, 0.2077542790660e-01,
0.1467828510764e-07, 0.7072627435674e+00, 0.1052268489556e+01,
0.1627627337440e-07, 0.3947607143237e+01, 0.6327837846670e+00,
0.1503498479758e-07, 0.4079248909190e+01, 0.7626583626240e-01,
0.1297967708237e-07, 0.6269637122840e+01, 0.1149965630200e+02,
0.1374416896634e-07, 0.4175657970702e+01, 0.6016468784579e+01,
0.1783812325219e-07, 0.1476540547560e+01, 0.3301902111895e+02,
0.1525884228756e-07, 0.4653477715241e+01, 0.9411464614024e+01,
0.1451067396763e-07, 0.2573001128225e+01, 0.1277945078067e+02,
0.1297713111950e-07, 0.5612799618771e+01, 0.6549682916313e+01,
0.1462784012820e-07, 0.4189661623870e+01, 0.1863592847156e+02,
0.1384185980007e-07, 0.2656915472196e+01, 0.2379164476796e+01,
0.1221497599801e-07, 0.5612515760138e+01, 0.1257326515556e+02,
0.1560574525896e-07, 0.4783414317919e+01, 0.1887552587463e+02,
0.1544598372036e-07, 0.2694431138063e+01, 0.1820933031200e+02,
0.1531678928696e-07, 0.4105103489666e+01, 0.2593412433514e+02,
0.1349321503795e-07, 0.3082437194015e+00, 0.5120601093667e+01,
0.1252030290917e-07, 0.6124072334087e+01, 0.6993008899458e+01,
0.1459243816687e-07, 0.3733103981697e+01, 0.3813291813120e-01,
0.1226103625262e-07, 0.1267127706817e+01, 0.2435678079171e+02,
0.1019449641504e-07, 0.4367790112269e+01, 0.1725663147538e+02,
0.1380789433607e-07, 0.3387201768700e+01, 0.2458316379602e+00,
0.1019453421658e-07, 0.9204143073737e+00, 0.6112403035119e+01,
0.1297929434405e-07, 0.5786874896426e+01, 0.1249137003520e+02,
0.9912677786097e-08, 0.3164232870746e+01, 0.6247047890016e+01,
0.9829386098599e-08, 0.2586762413351e+01, 0.6453748665772e+01,
0.1226807746104e-07, 0.6239068436607e+01, 0.5429879531333e+01,
0.1192691755997e-07, 0.1867380051424e+01, 0.6290122169689e+01,
0.9836499227081e-08, 0.3424716293727e+00, 0.6319103810876e+01,
0.9642862564285e-08, 0.5661372990657e+01, 0.8273820945392e+01,
0.1165184404862e-07, 0.5768367239093e+01, 0.1778273215245e+02,
0.1175794418818e-07, 0.1657351222943e+01, 0.6276029531202e+01,
0.1018948635601e-07, 0.6458292350865e+00, 0.1254537627298e+02,
0.9500383606676e-08, 0.1054306140741e+01, 0.1256517118505e+02,
0.1227512202906e-07, 0.2505278379114e+01, 0.2248384854122e+02,
0.9664792009993e-08, 0.4289737277000e+01, 0.6259197520765e+01,
0.9613285666331e-08, 0.5500597673141e+01, 0.6306954180126e+01,
0.1117906736211e-07, 0.2361405953468e+01, 0.1779695906178e+02,
0.9611378640782e-08, 0.2851310576269e+01, 0.2061856251104e+00,
0.8845354852370e-08, 0.6208777705343e+01, 0.1692165728891e+01,
0.1054046966600e-07, 0.5413091423934e+01, 0.2204125344462e+00,
0.1215539124483e-07, 0.5613969479755e+01, 0.8257698122054e+02,
0.9932460955209e-08, 0.1106124877015e+01, 0.1017725758696e+02,
0.8785804715043e-08, 0.2869224476477e+01, 0.9491756770005e+00,
0.8538084097562e-08, 0.6159640899344e+01, 0.6393282117669e+01,
0.8648994369529e-08, 0.1374901198784e+01, 0.4804209201333e+01,
0.1039063219067e-07, 0.5171080641327e+01, 0.1550861511662e+02,
0.8867983926439e-08, 0.8317320304902e+00, 0.3903911373650e+01,
0.8327495955244e-08, 0.3605591969180e+01, 0.6172869583223e+01,
0.9243088356133e-08, 0.6114299196843e+01, 0.6267823317922e+01,
0.9205657357835e-08, 0.3675153683737e+01, 0.6298328382969e+01,
0.1033269714606e-07, 0.3313328813024e+01, 0.5573142801433e+01,
0.8001706275552e-08, 0.2019980960053e+01, 0.2648454860559e+01,
0.9171858254191e-08, 0.8992015524177e+00, 0.1498544001348e+03,
0.1075327150242e-07, 0.2898669963648e+01, 0.3694923081589e+02,
0.9884866689828e-08, 0.4946715904478e+01, 0.1140367694411e+02,
0.9541835576677e-08, 0.2371787888469e+01, 0.1256713221673e+02,
0.7739903376237e-08, 0.2213775190612e+01, 0.7834121070590e+01,
0.7311962684106e-08, 0.3429378787739e+01, 0.1192625446156e+02,
0.9724904869624e-08, 0.6195878564404e+01, 0.2280573557157e+02,
0.9251628983612e-08, 0.6511509527390e+00, 0.2787043132925e+01,
0.7320763787842e-08, 0.6001083639421e+01, 0.6282655592598e+01,
0.7320296650962e-08, 0.3789073265087e+01, 0.6283496108294e+01,
0.7947032271039e-08, 0.1059659582204e+01, 0.1241073141809e+02,
0.9005277053115e-08, 0.1280315624361e+01, 0.6281591679874e+01,
0.8995601652048e-08, 0.2224439106766e+01, 0.6284560021018e+01,
0.8288040568796e-08, 0.5234914433867e+01, 0.1241658836951e+02,
0.6359381347255e-08, 0.4137989441490e+01, 0.1596186371003e+01,
0.8699572228626e-08, 0.1758411009497e+01, 0.6133512519065e+01,
0.6456797542736e-08, 0.5919285089994e+01, 0.1685848245639e+02,
0.7424573475452e-08, 0.5414616938827e+01, 0.4061219149443e+01,
0.7235671196168e-08, 0.1496516557134e+01, 0.1610006857377e+03,
0.8104015182733e-08, 0.1919918242764e+01, 0.8460828644453e+00,
0.8098576535937e-08, 0.3819615855458e+01, 0.3894181736510e+01,
0.6275292346625e-08, 0.6244264115141e+01, 0.8531963191132e+00,
0.6052432989112e-08, 0.5037731872610e+00, 0.1567108171867e+02,
0.5705651535817e-08, 0.2984557271995e+01, 0.1258692712880e+02,
0.5789650115138e-08, 0.6087038140697e+01, 0.1193336791622e+02,
0.5512132153377e-08, 0.5855668994076e+01, 0.1232342296471e+02,
0.7388890819102e-08, 0.2443128574740e+01, 0.4907302013889e+01,
0.5467593991798e-08, 0.3017561234194e+01, 0.1884211409667e+02,
0.6388519802999e-08, 0.5887386712935e+01, 0.5217580628120e+02,
0.6106777149944e-08, 0.3483461059895e+00, 0.1422690933580e-01,
0.7383420275489e-08, 0.5417387056707e+01, 0.2358125818164e+02,
0.5505208141738e-08, 0.2848193644783e+01, 0.1151388321134e+02,
0.6310757462877e-08, 0.2349882520828e+01, 0.1041998632314e+02,
0.6166904929691e-08, 0.5728575944077e+00, 0.6151533897323e+01,
0.5263442042754e-08, 0.4495796125937e+01, 0.1885275071096e+02,
0.5591828082629e-08, 0.1355441967677e+01, 0.4337116142245e+00,
0.5397051680497e-08, 0.1673422864307e+01, 0.6286362197481e+01,
0.5396992745159e-08, 0.1833502206373e+01, 0.6279789503410e+01,
0.6572913000726e-08, 0.3331122065824e+01, 0.1176433076753e+02,
0.5123421866413e-08, 0.2165327142679e+01, 0.1245594543367e+02,
0.5930495725999e-08, 0.2931146089284e+01, 0.6414617803568e+01,
0.6431797403933e-08, 0.4134407994088e+01, 0.1350651127443e+00,
0.5003182207604e-08, 0.3805420303749e+01, 0.1096996532989e+02,
0.5587731032504e-08, 0.1082469260599e+01, 0.6062663316000e+01,
0.5935263407816e-08, 0.8384333678401e+00, 0.5326786718777e+01,
0.4756019827760e-08, 0.3552588749309e+01, 0.3104930017775e+01,
0.6599951172637e-08, 0.4320826409528e+01, 0.4087944051283e+02,
0.5902606868464e-08, 0.4811879454445e+01, 0.5849364236221e+01,
0.5921147809031e-08, 0.9942628922396e-01, 0.1581959461667e+01,
0.5505382581266e-08, 0.2466557607764e+01, 0.6503488384892e+01,
0.5353771071862e-08, 0.4551978748683e+01, 0.1735668374386e+03,
0.5063282210946e-08, 0.5710812312425e+01, 0.1248988586463e+02,
0.5926120403383e-08, 0.1333998428358e+01, 0.2673594526851e+02,
0.5211016176149e-08, 0.4649315360760e+01, 0.2460261242967e+02,
0.5347075084894e-08, 0.5512754081205e+01, 0.4171425416666e+01,
0.4872609773574e-08, 0.1308025299938e+01, 0.5333900173445e+01,
0.4727711321420e-08, 0.2144908368062e+01, 0.7232251527446e+01,
0.6029426018652e-08, 0.5567259412084e+01, 0.3227113045244e+03,
0.4321485284369e-08, 0.5230667156451e+01, 0.9388005868221e+01,
0.4476406760553e-08, 0.6134081115303e+01, 0.5547199253223e+01,
0.5835268277420e-08, 0.4783808492071e+01, 0.7285056171570e+02,
0.5172183602748e-08, 0.5161817911099e+01, 0.1884570439172e+02,
0.5693571465184e-08, 0.1381646203111e+01, 0.9723862754494e+02,
0.4060634965349e-08, 0.3876705259495e+00, 0.4274518229222e+01,
0.3967398770473e-08, 0.5029491776223e+01, 0.3496032717521e+01,
0.3943754005255e-08, 0.1923162955490e+01, 0.6244942932314e+01,
0.4781323427824e-08, 0.4633332586423e+01, 0.2929661536378e+02,
0.3871483781204e-08, 0.1616650009743e+01, 0.6321208768577e+01,
0.5141741733997e-08, 0.9817316704659e-01, 0.1232032006293e+02,
0.4002385978497e-08, 0.3656161212139e+01, 0.7018952447668e+01,
0.4901092604097e-08, 0.4404098713092e+01, 0.1478866649112e+01,
0.3740932630345e-08, 0.5181188732639e+00, 0.6922973089781e+01,
0.4387283718538e-08, 0.3254859566869e+01, 0.2331413144044e+03,
0.5019197802033e-08, 0.3086773224677e+01, 0.1715706182245e+02,
0.3834931695175e-08, 0.2797882673542e+01, 0.1491901785440e+02,
0.3760413942497e-08, 0.2892676280217e+01, 0.1726726808967e+02,
0.3719717204628e-08, 0.5861046025739e+01, 0.6297302759782e+01,
0.4145623530149e-08, 0.2168239627033e+01, 0.1376059875786e+02,
0.3932788425380e-08, 0.6271811124181e+01, 0.7872148766781e+01,
0.3686377476857e-08, 0.3936853151404e+01, 0.6268848941110e+01,
0.3779077950339e-08, 0.1404148734043e+01, 0.4157198507331e+01,
0.4091334550598e-08, 0.2452436180854e+01, 0.9779108567966e+01,
0.3926694536146e-08, 0.6102292739040e+01, 0.1098419223922e+02,
0.4841000253289e-08, 0.6072760457276e+01, 0.1252801878276e+02,
0.4949340130240e-08, 0.1154832815171e+01, 0.1617106187867e+03,
0.3761557737360e-08, 0.5527545321897e+01, 0.3185192151914e+01,
0.3647396268188e-08, 0.1525035688629e+01, 0.6271346477544e+01,
0.3932405074189e-08, 0.5570681040569e+01, 0.2139354194808e+02,
0.3631322501141e-08, 0.1981240601160e+01, 0.6294805223347e+01,
0.4130007425139e-08, 0.2050060880201e+01, 0.2195415756911e+02,
0.4433905965176e-08, 0.3277477970321e+01, 0.7445550607224e+01,
0.3851814176947e-08, 0.5210690074886e+01, 0.9562891316684e+00,
0.3485807052785e-08, 0.6653274904611e+00, 0.1161697602389e+02,
0.3979772816991e-08, 0.1767941436148e+01, 0.2277943724828e+02,
0.3402607460500e-08, 0.3421746306465e+01, 0.1087398597200e+02,
0.4049993000926e-08, 0.1127144787547e+01, 0.3163918923335e+00,
0.3420511182382e-08, 0.4214794779161e+01, 0.1362553364512e+02,
0.3640772365012e-08, 0.5324905497687e+01, 0.1725304118033e+02,
0.3323037987501e-08, 0.6135761838271e+01, 0.6279143387820e+01,
0.4503141663637e-08, 0.1802305450666e+01, 0.1385561574497e+01,
0.4314560055588e-08, 0.4812299731574e+01, 0.4176041334900e+01,
0.3294226949110e-08, 0.3657547059723e+01, 0.6287008313071e+01,
0.3215657197281e-08, 0.4866676894425e+01, 0.5749861718712e+01,
0.4129362656266e-08, 0.3809342558906e+01, 0.5905702259363e+01,
0.3137762976388e-08, 0.2494635174443e+01, 0.2099539292909e+02,
0.3514010952384e-08, 0.2699961831678e+01, 0.7335344340001e+01,
0.3327607571530e-08, 0.3318457714816e+01, 0.5436992986000e+01,
0.3541066946675e-08, 0.4382703582466e+01, 0.1234573916645e+02,
0.3216179847052e-08, 0.5271066317054e+01, 0.3802769619140e-01,
0.2959045059570e-08, 0.5819591585302e+01, 0.2670964694522e+02,
0.3884040326665e-08, 0.5980934960428e+01, 0.6660449441528e+01,
0.2922027539886e-08, 0.3337290282483e+01, 0.1375773836557e+01,
0.4110846382042e-08, 0.5742978187327e+01, 0.4480965020977e+02,
0.2934508411032e-08, 0.2278075804200e+01, 0.6408777551755e+00,
0.3966896193000e-08, 0.5835747858477e+01, 0.3773735910827e+00,
0.3286695827610e-08, 0.5838898193902e+01, 0.3932462625300e-02,
0.3720643094196e-08, 0.1122212337858e+01, 0.1646033343740e+02,
0.3285508906174e-08, 0.9182250996416e+00, 0.1081813534213e+02,
0.3753880575973e-08, 0.5174761973266e+01, 0.5642198095270e+01,
0.3022129385587e-08, 0.3381611020639e+01, 0.2982630633589e+02,
0.2798569205621e-08, 0.3546193723922e+01, 0.1937891852345e+02,
0.3397872070505e-08, 0.4533203197934e+01, 0.6923953605621e+01,
0.3708099772977e-08, 0.2756168198616e+01, 0.3066615496545e+02,
0.3599283541510e-08, 0.1934395469918e+01, 0.6147450479709e+01,
0.3688702753059e-08, 0.7149920971109e+00, 0.2636725487657e+01,
0.2681084724003e-08, 0.4899819493154e+01, 0.6816289982179e+01,
0.3495993460759e-08, 0.1572418915115e+01, 0.6418701221183e+01,
0.3130770324995e-08, 0.8912190180489e+00, 0.1235996607578e+02,
0.2744353821941e-08, 0.3800821940055e+01, 0.2059724391010e+02,
0.2842732906341e-08, 0.2644717440029e+01, 0.2828699048865e+02,
0.3046882682154e-08, 0.3987793020179e+01, 0.6055599646783e+01,
0.2399072455143e-08, 0.9908826440764e+00, 0.6255674361143e+01,
0.2384306274204e-08, 0.2516149752220e+01, 0.6310477339748e+01,
0.2977324500559e-08, 0.5849195642118e+01, 0.1652265972112e+02,
0.3062835258972e-08, 0.1681660100162e+01, 0.1172006883645e+02,
0.3109682589231e-08, 0.5804143987737e+00, 0.2751146787858e+02,
0.2903920355299e-08, 0.5800768280123e+01, 0.6510552054109e+01,
0.2823221989212e-08, 0.9241118370216e+00, 0.5469525544182e+01,
0.3187949696649e-08, 0.3139776445735e+01, 0.1693792562116e+03,
0.2922559771655e-08, 0.3549440782984e+01, 0.2630839062450e+00,
0.2436302066603e-08, 0.4735540696319e+01, 0.3946258593675e+00,
0.3049473043606e-08, 0.4998289124561e+01, 0.8390110365991e+01,
0.2863682575784e-08, 0.6709515671102e+00, 0.2243449970715e+00,
0.2641750517966e-08, 0.5410978257284e+01, 0.2986433403208e+02,
0.2704093466243e-08, 0.4778317207821e+01, 0.6129297044991e+01,
0.2445522177011e-08, 0.6009020662222e+01, 0.1171295538178e+02,
0.2623608810230e-08, 0.5010449777147e+01, 0.6436854655901e+01,
0.2079259704053e-08, 0.5980943768809e+01, 0.2019909489111e+02,
0.2820225596771e-08, 0.2679965110468e+01, 0.5934151399930e+01,
0.2365221950927e-08, 0.1894231148810e+01, 0.2470570524223e+02,
0.2359682077149e-08, 0.4220752950780e+01, 0.8671969964381e+01,
0.2387577137206e-08, 0.2571783940617e+01, 0.7096626156709e+01,
0.1982102089816e-08, 0.5169765997119e+00, 0.1727188400790e+02,
0.2687502389925e-08, 0.6239078264579e+01, 0.7075506709219e+02,
0.2207751669135e-08, 0.2031184412677e+01, 0.4377611041777e+01,
0.2618370214274e-08, 0.8266079985979e+00, 0.6632000300961e+01,
0.2591951887361e-08, 0.8819350522008e+00, 0.4873985990671e+02,
0.2375055656248e-08, 0.3520944177789e+01, 0.1590676413561e+02,
0.2472019978911e-08, 0.1551431908671e+01, 0.6612329252343e+00,
0.2368157127199e-08, 0.4178610147412e+01, 0.3459636466239e+02,
0.1764846605693e-08, 0.1506764000157e+01, 0.1980094587212e+02,
0.2291769608798e-08, 0.2118250611782e+01, 0.2844914056730e-01,
0.2209997316943e-08, 0.3363255261678e+01, 0.2666070658668e+00,
0.2292699097923e-08, 0.4200423956460e+00, 0.1484170571900e-02,
0.1629683015329e-08, 0.2331362582487e+01, 0.3035599730800e+02,
0.2206492862426e-08, 0.3400274026992e+01, 0.6281667977667e+01,
0.2205746568257e-08, 0.1066051230724e+00, 0.6284483723224e+01,
0.2026310767991e-08, 0.2779066487979e+01, 0.2449240616245e+02,
0.1762977622163e-08, 0.9951450691840e+00, 0.2045286941806e+02,
0.1368535049606e-08, 0.6402447365817e+00, 0.2473415438279e+02,
0.1720598775450e-08, 0.2303524214705e+00, 0.1679593901136e+03,
0.1702429015449e-08, 0.6164622655048e+01, 0.3338575901272e+03,
0.1414033197685e-08, 0.3954561185580e+01, 0.1624205518357e+03,
0.1573768958043e-08, 0.2028286308984e+01, 0.3144167757552e+02,
0.1650705184447e-08, 0.2304040666128e+01, 0.5267006960365e+02,
0.1651087618855e-08, 0.2538461057280e+01, 0.8956999012000e+02,
0.1616409518983e-08, 0.5111054348152e+01, 0.3332657872986e+02,
0.1537175173581e-08, 0.5601130666603e+01, 0.3852657435933e+02,
0.1593191980553e-08, 0.2614340453411e+01, 0.2282781046519e+03,
0.1499480170643e-08, 0.3624721577264e+01, 0.2823723341956e+02,
0.1493807843235e-08, 0.4214569879008e+01, 0.2876692439167e+02,
0.1074571199328e-08, 0.1496911744704e+00, 0.8397383534231e+02,
0.1074406983417e-08, 0.1187817671922e+01, 0.8401985929482e+02,
0.9757576855851e-09, 0.2655703035858e+01, 0.7826370942180e+02,
0.1258432887565e-08, 0.4969896184844e+01, 0.3115650189215e+03,
0.1240336343282e-08, 0.5192460776926e+01, 0.1784300471910e+03,
0.9016107005164e-09, 0.1960356923057e+01, 0.5886454391678e+02,
0.1135392360918e-08, 0.5082427809068e+01, 0.7842370451713e+02,
0.9216046089565e-09, 0.2793775037273e+01, 0.1014262087719e+03,
0.1061276615030e-08, 0.3726144311409e+01, 0.5660027930059e+02,
0.1010110596263e-08, 0.7404080708937e+00, 0.4245678405627e+02,
0.7217424756199e-09, 0.2697449980577e-01, 0.2457074661053e+03,
0.6912003846756e-09, 0.4253296276335e+01, 0.1679936946371e+03,
0.6871814664847e-09, 0.5148072412354e+01, 0.6053048899753e+02,
0.4887158016343e-09, 0.2153581148294e+01, 0.9656299901946e+02,
0.5161802866314e-09, 0.3852750634351e+01, 0.2442876000072e+03,
0.5652599559057e-09, 0.1233233356270e+01, 0.8365903305582e+02,
0.4710812608586e-09, 0.5610486976767e+01, 0.3164282286739e+03,
0.4909977500324e-09, 0.1639629524123e+01, 0.4059982187939e+03,
0.4772641839378e-09, 0.3737100368583e+01, 0.1805255418145e+03,
0.4487562567153e-09, 0.1158417054478e+00, 0.8433466158131e+02,
0.3943441230497e-09, 0.6243502862796e+00, 0.2568537517081e+03,
0.3952236913598e-09, 0.3510377382385e+01, 0.2449975330562e+03,
0.3788898363417e-09, 0.5916128302299e+01, 0.1568131045107e+03,
0.3738329328831e-09, 0.1042266763456e+01, 0.3948519331910e+03,
0.2451199165151e-09, 0.1166788435700e+01, 0.1435713242844e+03,
0.2436734402904e-09, 0.3254726114901e+01, 0.2268582385539e+03,
0.2213605274325e-09, 0.1687210598530e+01, 0.1658638954901e+03,
0.1491521204829e-09, 0.2657541786794e+01, 0.2219950288015e+03,
0.1474995329744e-09, 0.5013089805819e+01, 0.3052819430710e+03,
0.1661939475656e-09, 0.5495315428418e+01, 0.2526661704812e+03,
0.9015946748003e-10, 0.2236989966505e+01, 0.4171445043968e+03}
/* Sun-to-Earth, T^0, Z */
e0z := []float64{
0.2796207639075e-05, 0.3198701560209e+01, 0.8433466158131e+02,
0.1016042198142e-05, 0.5422360395913e+01, 0.5507553240374e+01,
0.8044305033647e-06, 0.3880222866652e+01, 0.5223693906222e+01,
0.4385347909274e-06, 0.3704369937468e+01, 0.2352866153506e+01,
0.3186156414906e-06, 0.3999639363235e+01, 0.1577343543434e+01,
0.2272412285792e-06, 0.3984738315952e+01, 0.1047747311755e+01,
0.1645620103007e-06, 0.3565412516841e+01, 0.5856477690889e+01,
0.1815836921166e-06, 0.4984507059020e+01, 0.6283075850446e+01,
0.1447461676364e-06, 0.3702753570108e+01, 0.9437762937313e+01,
0.1430760876382e-06, 0.3409658712357e+01, 0.1021328554739e+02,
0.1120445753226e-06, 0.4829561570246e+01, 0.1414349524433e+02,
0.1090232840797e-06, 0.2080729178066e+01, 0.6812766822558e+01,
0.9715727346551e-07, 0.3476295881948e+01, 0.4694002934110e+01,
0.1036267136217e-06, 0.4056639536648e+01, 0.7109288135493e+02,
0.8752665271340e-07, 0.4448159519911e+01, 0.5753384878334e+01,
0.8331864956004e-07, 0.4991704044208e+01, 0.7084896783808e+01,
0.6901658670245e-07, 0.4325358994219e+01, 0.6275962395778e+01,
0.9144536848998e-07, 0.1141826375363e+01, 0.6620890113188e+01,
0.7205085037435e-07, 0.3624344170143e+01, 0.5296909721118e+00,
0.7697874654176e-07, 0.5554257458998e+01, 0.1676215758509e+03,
0.5197545738384e-07, 0.6251760961735e+01, 0.1807370494127e+02,
0.5031345378608e-07, 0.2497341091913e+01, 0.4705732307012e+01,
0.4527110205840e-07, 0.2335079920992e+01, 0.6309374173736e+01,
0.4753355798089e-07, 0.7094148987474e+00, 0.5884926831456e+01,
0.4296951977516e-07, 0.1101916352091e+01, 0.6681224869435e+01,
0.3855341568387e-07, 0.1825495405486e+01, 0.5486777812467e+01,
0.5253930970990e-07, 0.4424740687208e+01, 0.7860419393880e+01,
0.4024630496471e-07, 0.5120498157053e+01, 0.1336797263425e+02,
0.4061069791453e-07, 0.6029771435451e+01, 0.3930209696940e+01,
0.3797883804205e-07, 0.4435193600836e+00, 0.3154687086868e+01,
0.2933033225587e-07, 0.5124157356507e+01, 0.1059381944224e+01,
0.3503000930426e-07, 0.5421830162065e+01, 0.6069776770667e+01,
0.3670096214050e-07, 0.4582101667297e+01, 0.1219403291462e+02,
0.2905609437008e-07, 0.1926566420072e+01, 0.1097707878456e+02,
0.2466827821713e-07, 0.6090174539834e+00, 0.6496374930224e+01,
0.2691647295332e-07, 0.1393432595077e+01, 0.2200391463820e+02,
0.2150554667946e-07, 0.4308671715951e+01, 0.5643178611111e+01,
0.2237481922680e-07, 0.8133968269414e+00, 0.8635942003952e+01,
0.1817741038157e-07, 0.3755205127454e+01, 0.3340612434717e+01,
0.2227820762132e-07, 0.2759558596664e+01, 0.1203646072878e+02,
0.1944713772307e-07, 0.5699645869121e+01, 0.1179062909082e+02,
0.1527340520662e-07, 0.1986749091746e+01, 0.3981490189893e+00,
0.1577282574914e-07, 0.3205017217983e+01, 0.5088628793478e+01,
0.1424738825424e-07, 0.6256747903666e+01, 0.2544314396739e+01,
0.1616563121701e-07, 0.2601671259394e+00, 0.1729818233119e+02,
0.1401210391692e-07, 0.4686939173506e+01, 0.7058598460518e+01,
0.1488726974214e-07, 0.2815862451372e+01, 0.2593412433514e+02,
0.1692626442388e-07, 0.4956894109797e+01, 0.1564752902480e+03,
0.1123571582910e-07, 0.2381192697696e+01, 0.3738761453707e+01,
0.9903308606317e-08, 0.4294851657684e+01, 0.9225539266174e+01,
0.9174533187191e-08, 0.3075171510642e+01, 0.4164311961999e+01,
0.8645985631457e-08, 0.5477534821633e+00, 0.8429241228195e+01,
-0.1085876492688e-07, 0.0000000000000e+00, 0.0000000000000e+00,
0.9264309077815e-08, 0.5968571670097e+01, 0.7079373888424e+01,
0.8243116984954e-08, 0.1489098777643e+01, 0.1044738781244e+02,
0.8268102113708e-08, 0.3512977691983e+01, 0.1150676975667e+02,
0.9043613988227e-08, 0.1290704408221e+00, 0.1101510648075e+02,
0.7432912038789e-08, 0.1991086893337e+01, 0.2608790314060e+02,
0.8586233727285e-08, 0.4238357924414e+01, 0.2986433403208e+02,
0.7612230060131e-08, 0.2911090150166e+01, 0.4732030630302e+01,
0.7097787751408e-08, 0.1908938392390e+01, 0.8031092209206e+01,
0.7640237040175e-08, 0.6129219000168e+00, 0.7962980379786e+00,
0.7070445688081e-08, 0.1380417036651e+01, 0.2146165377750e+01,
0.7690770957702e-08, 0.1680504249084e+01, 0.2122839202813e+02,
0.8051292542594e-08, 0.5127423484511e+01, 0.2942463415728e+01,
0.5902709104515e-08, 0.2020274190917e+01, 0.7755226100720e+00,
0.5134567496462e-08, 0.2606778676418e+01, 0.1256615170089e+02,
0.5525802046102e-08, 0.1613011769663e+01, 0.8018209333619e+00,
0.5880724784221e-08, 0.4604483417236e+01, 0.4690479774488e+01,
0.5211699081370e-08, 0.5718964114193e+01, 0.8827390247185e+01,
0.4891849573562e-08, 0.3689658932196e+01, 0.2132990797783e+00,
0.5150246069997e-08, 0.4099769855122e+01, 0.6480980550449e+02,
0.5102434319633e-08, 0.5660834602509e+01, 0.3379454372902e+02,
0.5083405254252e-08, 0.9842221218974e+00, 0.4136910472696e+01,
0.4206562585682e-08, 0.1341363634163e+00, 0.3128388763578e+01,
0.4663249683579e-08, 0.8130132735866e+00, 0.5216580451554e+01,
0.4099474416530e-08, 0.5791497770644e+01, 0.4265981595566e+00,
0.4628251220767e-08, 0.1249802769331e+01, 0.1572083878776e+02,
0.5024068728142e-08, 0.4795684802743e+01, 0.6290189305114e+01,
0.5120234327758e-08, 0.3810420387208e+01, 0.5230807360890e+01,
0.5524029815280e-08, 0.1029264714351e+01, 0.2397622045175e+03,
0.4757415718860e-08, 0.3528044781779e+01, 0.1649636139783e+02,
0.3915786131127e-08, 0.5593889282646e+01, 0.1589072916335e+01,
0.4869053149991e-08, 0.3299636454433e+01, 0.7632943190217e+01,
0.3649365703729e-08, 0.1286049002584e+01, 0.6206810014183e+01,
0.3992493949002e-08, 0.3100307589464e+01, 0.2515860172507e+02,
0.3320247477418e-08, 0.6212683940807e+01, 0.1216800268190e+02,
0.3287123739696e-08, 0.4699118445928e+01, 0.7234794171227e+01,
0.3472776811103e-08, 0.2630507142004e+01, 0.7342457794669e+01,
0.3423253294767e-08, 0.2946432844305e+01, 0.9623688285163e+01,
0.3896173898244e-08, 0.1224834179264e+01, 0.6438496133249e+01,
0.3388455337924e-08, 0.1543807616351e+01, 0.1494531617769e+02,
0.3062704716523e-08, 0.1191777572310e+01, 0.8662240327241e+01,
0.3270075600400e-08, 0.5483498767737e+01, 0.1194447056968e+01,
0.3101209215259e-08, 0.8000833804348e+00, 0.3772475342596e+02,
0.2780883347311e-08, 0.4077980721888e+00, 0.5863591145557e+01,
0.2903605931824e-08, 0.2617490302147e+01, 0.1965104848470e+02,
0.2682014743119e-08, 0.2634703158290e+01, 0.7238675589263e+01,
0.2534360108492e-08, 0.6102446114873e+01, 0.6836645152238e+01,
0.2392564882509e-08, 0.3681820208691e+01, 0.5849364236221e+01,
0.2656667254856e-08, 0.6216045388886e+01, 0.6133512519065e+01,
0.2331242096773e-08, 0.5864949777744e+01, 0.4535059491685e+01,
0.2287898363668e-08, 0.4566628532802e+01, 0.7477522907414e+01,
0.2336944521306e-08, 0.2442722126930e+01, 0.1137170464392e+02,
0.3156632236269e-08, 0.1626628050682e+01, 0.2509084901204e+03,
0.2982612402766e-08, 0.2803604512609e+01, 0.1748016358760e+01,
0.2774031674807e-08, 0.4654002897158e+01, 0.8223916695780e+02,
0.2295236548638e-08, 0.4326518333253e+01, 0.3378142627421e+00,
0.2190714699873e-08, 0.4519614578328e+01, 0.2908881142201e+02,
0.2191495845045e-08, 0.3012626912549e+01, 0.1673046366289e+02,
0.2492901628386e-08, 0.1290101424052e+00, 0.1543797956245e+03,
0.1993778064319e-08, 0.3864046799414e+01, 0.1778984560711e+02,
0.1898146479022e-08, 0.5053777235891e+01, 0.2042657109477e+02,
0.1918280127634e-08, 0.2222470192548e+01, 0.4165496312290e+02,
0.1916351061607e-08, 0.8719067257774e+00, 0.7737595720538e+02,
0.1834720181466e-08, 0.4031491098040e+01, 0.2358125818164e+02,
0.1249201523806e-08, 0.5938379466835e+01, 0.3301902111895e+02,
0.1477304050539e-08, 0.6544722606797e+00, 0.9548094718417e+02,
0.1264316431249e-08, 0.2059072853236e+01, 0.8399684731857e+02,
0.1203526495039e-08, 0.3644813532605e+01, 0.4558517281984e+02,
0.9221681059831e-09, 0.3241815055602e+01, 0.7805158573086e+02,
0.7849278367646e-09, 0.5043812342457e+01, 0.5217580628120e+02,
0.7983392077387e-09, 0.5000024502753e+01, 0.1501922143975e+03,
0.7925395431654e-09, 0.1398734871821e-01, 0.9061773743175e+02,
0.7640473285886e-09, 0.5067111723130e+01, 0.4951538251678e+02,
0.5398937754482e-09, 0.5597382200075e+01, 0.1613385000004e+03,
0.5626247550193e-09, 0.2601338209422e+01, 0.7318837597844e+02,
0.5525197197855e-09, 0.5814832109256e+01, 0.1432335100216e+03,
0.5407629837898e-09, 0.3384820609076e+01, 0.3230491187871e+03,
0.3856739119801e-09, 0.1072391840473e+01, 0.2334791286671e+03,
0.3856425239987e-09, 0.2369540393327e+01, 0.1739046517013e+03,
0.4350867755983e-09, 0.5255575751082e+01, 0.1620484330494e+03,
0.3844113924996e-09, 0.5482356246182e+01, 0.9757644180768e+02,
0.2854869155431e-09, 0.9573634763143e+00, 0.1697170704744e+03,
0.1719227671416e-09, 0.1887203025202e+01, 0.2265204242912e+03,
0.1527846879755e-09, 0.3982183931157e+01, 0.3341954043900e+03,
0.1128229264847e-09, 0.2787457156298e+01, 0.3119028331842e+03}
/* Sun-to-Earth, T^1, X */
e1x := []float64{
0.1234046326004e-05, 0.0000000000000e+00, 0.0000000000000e+00,
0.5150068824701e-06, 0.6002664557501e+01, 0.1256615170089e+02,
0.1290743923245e-07, 0.5959437664199e+01, 0.1884922755134e+02,
0.1068615564952e-07, 0.2015529654209e+01, 0.6283075850446e+01,
0.2079619142538e-08, 0.1732960531432e+01, 0.6279552690824e+01,
0.2078009243969e-08, 0.4915604476996e+01, 0.6286599010068e+01,
0.6206330058856e-09, 0.3616457953824e+00, 0.4705732307012e+01,
0.5989335313746e-09, 0.3802607304474e+01, 0.6256777527156e+01,
0.5958495663840e-09, 0.2845866560031e+01, 0.6309374173736e+01,
0.4866923261539e-09, 0.5213203771824e+01, 0.7755226100720e+00,
0.4267785823142e-09, 0.4368189727818e+00, 0.1059381944224e+01,
0.4610675141648e-09, 0.1837249181372e-01, 0.7860419393880e+01,
0.3626989993973e-09, 0.2161590545326e+01, 0.5753384878334e+01,
0.3563071194389e-09, 0.1452631954746e+01, 0.5884926831456e+01,
0.3557015642807e-09, 0.4470593393054e+01, 0.6812766822558e+01,
0.3210412089122e-09, 0.5195926078314e+01, 0.6681224869435e+01,
0.2875473577986e-09, 0.5916256610193e+01, 0.2513230340178e+02,
0.2842913681629e-09, 0.1149902426047e+01, 0.6127655567643e+01,
0.2751248215916e-09, 0.5502088574662e+01, 0.6438496133249e+01,
0.2481432881127e-09, 0.2921989846637e+01, 0.5486777812467e+01,
0.2059885976560e-09, 0.3718070376585e+01, 0.7079373888424e+01,
0.2015522342591e-09, 0.5979395259740e+01, 0.6290189305114e+01,
0.1995364084253e-09, 0.6772087985494e+00, 0.6275962395778e+01,
0.1957436436943e-09, 0.2899210654665e+01, 0.5507553240374e+01,
0.1651609818948e-09, 0.6228206482192e+01, 0.1150676975667e+02,
0.1822980550699e-09, 0.1469348746179e+01, 0.1179062909082e+02,
0.1675223159760e-09, 0.3813910555688e+01, 0.7058598460518e+01,
0.1706491764745e-09, 0.3004380506684e+00, 0.7113454667900e-02,
0.1392952362615e-09, 0.1440393973406e+01, 0.7962980379786e+00,
0.1209868266342e-09, 0.4150425791727e+01, 0.4694002934110e+01,
0.1009827202611e-09, 0.3290040429843e+01, 0.3738761453707e+01,
0.1047261388602e-09, 0.4229590090227e+01, 0.6282095334605e+01,
0.1047006652004e-09, 0.2418967680575e+01, 0.6284056366286e+01,
0.9609993143095e-10, 0.4627943659201e+01, 0.6069776770667e+01,
0.9590900593873e-10, 0.1894393939924e+01, 0.4136910472696e+01,
0.9146249188071e-10, 0.2010647519562e+01, 0.6496374930224e+01,
0.8545274480290e-10, 0.5529846956226e-01, 0.1194447056968e+01,
0.8224377881194e-10, 0.1254304102174e+01, 0.1589072916335e+01,
0.6183529510410e-10, 0.3360862168815e+01, 0.8827390247185e+01,
0.6259255147141e-10, 0.4755628243179e+01, 0.8429241228195e+01,
0.5539291694151e-10, 0.5371746955142e+01, 0.4933208510675e+01,
0.7328259466314e-10, 0.4927699613906e+00, 0.4535059491685e+01,
0.6017835843560e-10, 0.5776682001734e-01, 0.1255903824622e+02,
0.7079827775243e-10, 0.4395059432251e+01, 0.5088628793478e+01,
0.5170358878213e-10, 0.5154062619954e+01, 0.1176985366291e+02,
0.4872301838682e-10, 0.6289611648973e+00, 0.6040347114260e+01,
0.5249869411058e-10, 0.5617272046949e+01, 0.3154687086868e+01,
0.4716172354411e-10, 0.3965901800877e+01, 0.5331357529664e+01,
0.4871214940964e-10, 0.4627507050093e+01, 0.1256967486051e+02,
0.4598076850751e-10, 0.6023631226459e+01, 0.6525804586632e+01,
0.4562196089485e-10, 0.4138562084068e+01, 0.3930209696940e+01,
0.4325493872224e-10, 0.1330845906564e+01, 0.7632943190217e+01,
0.5673781176748e-10, 0.2558752615657e+01, 0.5729506548653e+01,
0.3961436642503e-10, 0.2728071734630e+01, 0.7234794171227e+01,
0.5101868209058e-10, 0.4113444965144e+01, 0.6836645152238e+01,
0.5257043167676e-10, 0.6195089830590e+01, 0.8031092209206e+01,
0.5076613989393e-10, 0.2305124132918e+01, 0.7477522907414e+01,
0.3342169352778e-10, 0.5415998155071e+01, 0.1097707878456e+02,
0.3545881983591e-10, 0.3727160564574e+01, 0.4164311961999e+01,
0.3364063738599e-10, 0.2901121049204e+00, 0.1137170464392e+02,
0.3357039670776e-10, 0.1652229354331e+01, 0.5223693906222e+01,
0.4307412268687e-10, 0.4938909587445e+01, 0.1592596075957e+01,
0.3405769115435e-10, 0.2408890766511e+01, 0.3128388763578e+01,
0.3001926198480e-10, 0.4862239006386e+01, 0.1748016358760e+01,
0.2778264787325e-10, 0.5241168661353e+01, 0.7342457794669e+01,
0.2676159480666e-10, 0.3423593942199e+01, 0.2146165377750e+01,
0.2954273399939e-10, 0.1881721265406e+01, 0.5368044267797e+00,
0.3309362888795e-10, 0.1931525677349e+01, 0.8018209333619e+00,
0.2810283608438e-10, 0.2414659495050e+01, 0.5225775174439e+00,
0.3378045637764e-10, 0.4238019163430e+01, 0.1554202828031e+00,
0.2558134979840e-10, 0.1828225235805e+01, 0.5230807360890e+01,
0.2273755578447e-10, 0.5858184283998e+01, 0.7084896783808e+01,
0.2294176037690e-10, 0.4514589779057e+01, 0.1726015463500e+02,
0.2533506099435e-10, 0.2355717851551e+01, 0.5216580451554e+01,
0.2716685375812e-10, 0.2221003625100e+01, 0.8635942003952e+01,
0.2419043435198e-10, 0.5955704951635e+01, 0.4690479774488e+01,
0.2521232544812e-10, 0.1395676848521e+01, 0.5481254917084e+01,
0.2630195021491e-10, 0.5727468918743e+01, 0.2629832328990e-01,
0.2548395840944e-10, 0.2628351859400e-03, 0.1349867339771e+01}
/* Sun-to-Earth, T^1, Y */
e1y := []float64{
0.9304690546528e-06, 0.0000000000000e+00, 0.0000000000000e+00,
0.5150715570663e-06, 0.4431807116294e+01, 0.1256615170089e+02,
0.1290825411056e-07, 0.4388610039678e+01, 0.1884922755134e+02,
0.4645466665386e-08, 0.5827263376034e+01, 0.6283075850446e+01,
0.2079625310718e-08, 0.1621698662282e+00, 0.6279552690824e+01,
0.2078189850907e-08, 0.3344713435140e+01, 0.6286599010068e+01,
0.6207190138027e-09, 0.5074049319576e+01, 0.4705732307012e+01,
0.5989826532569e-09, 0.2231842216620e+01, 0.6256777527156e+01,
0.5961360812618e-09, 0.1274975769045e+01, 0.6309374173736e+01,
0.4874165471016e-09, 0.3642277426779e+01, 0.7755226100720e+00,
0.4283834034360e-09, 0.5148765510106e+01, 0.1059381944224e+01,
0.4652389287529e-09, 0.4715794792175e+01, 0.7860419393880e+01,
0.3751707476401e-09, 0.6617207370325e+00, 0.5753384878334e+01,
0.3559998806198e-09, 0.6155548875404e+01, 0.5884926831456e+01,
0.3558447558857e-09, 0.2898827297664e+01, 0.6812766822558e+01,
0.3211116927106e-09, 0.3625813502509e+01, 0.6681224869435e+01,
0.2875609914672e-09, 0.4345435813134e+01, 0.2513230340178e+02,
0.2843109704069e-09, 0.5862263940038e+01, 0.6127655567643e+01,
0.2744676468427e-09, 0.3926419475089e+01, 0.6438496133249e+01,
0.2481285237789e-09, 0.1351976572828e+01, 0.5486777812467e+01,
0.2060338481033e-09, 0.2147556998591e+01, 0.7079373888424e+01,
0.2015822358331e-09, 0.4408358972216e+01, 0.6290189305114e+01,
0.2001195944195e-09, 0.5385829822531e+01, 0.6275962395778e+01,
0.1953667642377e-09, 0.1304933746120e+01, 0.5507553240374e+01,
0.1839744078713e-09, 0.6173567228835e+01, 0.1179062909082e+02,
0.1643334294845e-09, 0.4635942997523e+01, 0.1150676975667e+02,
0.1768051018652e-09, 0.5086283558874e+01, 0.7113454667900e-02,
0.1674874205489e-09, 0.2243332137241e+01, 0.7058598460518e+01,
0.1421445397609e-09, 0.6186899771515e+01, 0.7962980379786e+00,
0.1255163958267e-09, 0.5730238465658e+01, 0.4694002934110e+01,
0.1013945281961e-09, 0.1726055228402e+01, 0.3738761453707e+01,
0.1047294335852e-09, 0.2658801228129e+01, 0.6282095334605e+01,
0.1047103879392e-09, 0.8481047835035e+00, 0.6284056366286e+01,
0.9530343962826e-10, 0.3079267149859e+01, 0.6069776770667e+01,
0.9604637611690e-10, 0.3258679792918e+00, 0.4136910472696e+01,
0.9153518537177e-10, 0.4398599886584e+00, 0.6496374930224e+01,
0.8562458214922e-10, 0.4772686794145e+01, 0.1194447056968e+01,
0.8232525360654e-10, 0.5966220721679e+01, 0.1589072916335e+01,
0.6150223411438e-10, 0.1780985591923e+01, 0.8827390247185e+01,
0.6272087858000e-10, 0.3184305429012e+01, 0.8429241228195e+01,
0.5540476311040e-10, 0.3801260595433e+01, 0.4933208510675e+01,
0.7331901699361e-10, 0.5205948591865e+01, 0.4535059491685e+01,
0.6018528702791e-10, 0.4770139083623e+01, 0.1255903824622e+02,
0.5150530724804e-10, 0.3574796899585e+01, 0.1176985366291e+02,
0.6471933741811e-10, 0.2679787266521e+01, 0.5088628793478e+01,
0.5317460644174e-10, 0.9528763345494e+00, 0.3154687086868e+01,
0.4832187748783e-10, 0.5329322498232e+01, 0.6040347114260e+01,
0.4716763555110e-10, 0.2395235316466e+01, 0.5331357529664e+01,
0.4871509139861e-10, 0.3056663648823e+01, 0.1256967486051e+02,
0.4598417696768e-10, 0.4452762609019e+01, 0.6525804586632e+01,
0.5674189533175e-10, 0.9879680872193e+00, 0.5729506548653e+01,
0.4073560328195e-10, 0.5939127696986e+01, 0.7632943190217e+01,
0.5040994945359e-10, 0.4549875824510e+01, 0.8031092209206e+01,
0.5078185134679e-10, 0.7346659893982e+00, 0.7477522907414e+01,
0.3769343537061e-10, 0.1071317188367e+01, 0.7234794171227e+01,
0.4980331365299e-10, 0.2500345341784e+01, 0.6836645152238e+01,
0.3458236594757e-10, 0.3825159450711e+01, 0.1097707878456e+02,
0.3578859493602e-10, 0.5299664791549e+01, 0.4164311961999e+01,
0.3370504646419e-10, 0.5002316301593e+01, 0.1137170464392e+02,
0.3299873338428e-10, 0.2526123275282e+01, 0.3930209696940e+01,
0.4304917318409e-10, 0.3368078557132e+01, 0.1592596075957e+01,
0.3402418753455e-10, 0.8385495425800e+00, 0.3128388763578e+01,
0.2778460572146e-10, 0.3669905203240e+01, 0.7342457794669e+01,
0.2782710128902e-10, 0.2691664812170e+00, 0.1748016358760e+01,
0.2711725179646e-10, 0.4707487217718e+01, 0.5296909721118e+00,
0.2981760946340e-10, 0.3190260867816e+00, 0.5368044267797e+00,
0.2811672977772e-10, 0.3196532315372e+01, 0.7084896783808e+01,
0.2863454474467e-10, 0.2263240324780e+00, 0.5223693906222e+01,
0.3333464634051e-10, 0.3498451685065e+01, 0.8018209333619e+00,
0.3312991747609e-10, 0.5839154477412e+01, 0.1554202828031e+00,
0.2813255564006e-10, 0.8268044346621e+00, 0.5225775174439e+00,
0.2665098083966e-10, 0.3934021725360e+01, 0.5216580451554e+01,
0.2349795705216e-10, 0.5197620913779e+01, 0.2146165377750e+01,
0.2330352293961e-10, 0.2984999231807e+01, 0.1726015463500e+02,
0.2728001683419e-10, 0.6521679638544e+00, 0.8635942003952e+01,
0.2484061007669e-10, 0.3468955561097e+01, 0.5230807360890e+01,
0.2646328768427e-10, 0.1013724533516e+01, 0.2629832328990e-01,
0.2518630264831e-10, 0.6108081057122e+01, 0.5481254917084e+01,
0.2421901455384e-10, 0.1651097776260e+01, 0.1349867339771e+01,
0.6348533267831e-11, 0.3220226560321e+01, 0.8433466158131e+02}
/* Sun-to-Earth, T^1, Z */
e1z := []float64{
0.2278290449966e-05, 0.3413716033863e+01, 0.6283075850446e+01,
0.5429458209830e-07, 0.0000000000000e+00, 0.0000000000000e+00,
0.1903240492525e-07, 0.3370592358297e+01, 0.1256615170089e+02,
0.2385409276743e-09, 0.3327914718416e+01, 0.1884922755134e+02,
0.8676928342573e-10, 0.1824006811264e+01, 0.5223693906222e+01,
0.7765442593544e-10, 0.3888564279247e+01, 0.5507553240374e+01,
0.7066158332715e-10, 0.5194267231944e+01, 0.2352866153506e+01,
0.7092175288657e-10, 0.2333246960021e+01, 0.8399684731857e+02,
0.5357582213535e-10, 0.2224031176619e+01, 0.5296909721118e+00,
0.3828035865021e-10, 0.2156710933584e+01, 0.6279552690824e+01,
0.3824857220427e-10, 0.1529755219915e+01, 0.6286599010068e+01,
0.3286995181628e-10, 0.4879512900483e+01, 0.1021328554739e+02}
/* Sun-to-Earth, T^2, X */
e2x := []float64{
-0.4143818297913e-10, 0.0000000000000e+00, 0.0000000000000e+00,
0.2171497694435e-10, 0.4398225628264e+01, 0.1256615170089e+02,
0.9845398442516e-11, 0.2079720838384e+00, 0.6283075850446e+01,
0.9256833552682e-12, 0.4191264694361e+01, 0.1884922755134e+02,
0.1022049384115e-12, 0.5381133195658e+01, 0.8399684731857e+02}
/* Sun-to-Earth, T^2, Y */
e2y := []float64{
0.5063375872532e-10, 0.0000000000000e+00, 0.0000000000000e+00,
0.2173815785980e-10, 0.2827805833053e+01, 0.1256615170089e+02,
0.1010231999920e-10, 0.4634612377133e+01, 0.6283075850446e+01,
0.9259745317636e-12, 0.2620612076189e+01, 0.1884922755134e+02,
0.1022202095812e-12, 0.3809562326066e+01, 0.8399684731857e+02}
/* Sun-to-Earth, T^2, Z */
e2z := []float64{
0.9722666114891e-10, 0.5152219582658e+01, 0.6283075850446e+01,
-0.3494819171909e-11, 0.0000000000000e+00, 0.0000000000000e+00,
0.6713034376076e-12, 0.6440188750495e+00, 0.1256615170089e+02}
/* SSB-to-Sun, T^0, X */
s0x := []float64{
0.4956757536410e-02, 0.3741073751789e+01, 0.5296909721118e+00,
0.2718490072522e-02, 0.4016011511425e+01, 0.2132990797783e+00,
0.1546493974344e-02, 0.2170528330642e+01, 0.3813291813120e-01,
0.8366855276341e-03, 0.2339614075294e+01, 0.7478166569050e-01,
0.2936777942117e-03, 0.0000000000000e+00, 0.0000000000000e+00,
0.1201317439469e-03, 0.4090736353305e+01, 0.1059381944224e+01,
0.7578550887230e-04, 0.3241518088140e+01, 0.4265981595566e+00,
0.1941787367773e-04, 0.1012202064330e+01, 0.2061856251104e+00,
0.1889227765991e-04, 0.3892520416440e+01, 0.2204125344462e+00,
0.1937896968613e-04, 0.4797779441161e+01, 0.1495633313810e+00,
0.1434506110873e-04, 0.3868960697933e+01, 0.5225775174439e+00,
0.1406659911580e-04, 0.4759766557397e+00, 0.5368044267797e+00,
0.1179022300202e-04, 0.7774961520598e+00, 0.7626583626240e-01,
0.8085864460959e-05, 0.3254654471465e+01, 0.3664874755930e-01,
0.7622752967615e-05, 0.4227633103489e+01, 0.3961708870310e-01,
0.6209171139066e-05, 0.2791828325711e+00, 0.7329749511860e-01,
0.4366435633970e-05, 0.4440454875925e+01, 0.1589072916335e+01,
0.3792124889348e-05, 0.5156393842356e+01, 0.7113454667900e-02,
0.3154548963402e-05, 0.6157005730093e+01, 0.4194847048887e+00,
0.3088359882942e-05, 0.2494567553163e+01, 0.6398972393349e+00,
0.2788440902136e-05, 0.4934318747989e+01, 0.1102062672231e+00,
0.3039928456376e-05, 0.4895077702640e+01, 0.6283075850446e+01,
0.2272258457679e-05, 0.5278394064764e+01, 0.1030928125552e+00,
0.2162007057957e-05, 0.5802978019099e+01, 0.3163918923335e+00,
0.1767632855737e-05, 0.3415346595193e-01, 0.1021328554739e+02,
0.1349413459362e-05, 0.2001643230755e+01, 0.1484170571900e-02,
0.1170141900476e-05, 0.2424750491620e+01, 0.6327837846670e+00,
0.1054355266820e-05, 0.3123311487576e+01, 0.4337116142245e+00,
0.9800822461610e-06, 0.3026258088130e+01, 0.1052268489556e+01,
0.1091203749931e-05, 0.3157811670347e+01, 0.1162474756779e+01,
0.6960236715913e-06, 0.8219570542313e+00, 0.1066495398892e+01,
0.5689257296909e-06, 0.1323052375236e+01, 0.9491756770005e+00,
0.6613172135802e-06, 0.2765348881598e+00, 0.8460828644453e+00,
0.6277702517571e-06, 0.5794064466382e+01, 0.1480791608091e+00,
0.6304884066699e-06, 0.7323555380787e+00, 0.2243449970715e+00,
0.4897850467382e-06, 0.3062464235399e+01, 0.3340612434717e+01,
0.3759148598786e-06, 0.4588290469664e+01, 0.3516457698740e-01,
0.3110520548195e-06, 0.1374299536572e+01, 0.6373574839730e-01,
0.3064708359780e-06, 0.4222267485047e+01, 0.1104591729320e-01,
0.2856347168241e-06, 0.3714202944973e+01, 0.1510475019529e+00,
0.2840945514288e-06, 0.2847972875882e+01, 0.4110125927500e-01,
0.2378951599405e-06, 0.3762072563388e+01, 0.2275259891141e+00,
0.2714229481417e-06, 0.1036049980031e+01, 0.2535050500000e-01,
0.2323551717307e-06, 0.4682388599076e+00, 0.8582758298370e-01,
0.1881790512219e-06, 0.4790565425418e+01, 0.2118763888447e+01,
0.2261353968371e-06, 0.1669144912212e+01, 0.7181332454670e-01,
0.2214546389848e-06, 0.3937717281614e+01, 0.2968341143800e-02,
0.2184915594933e-06, 0.1129169845099e+00, 0.7775000683430e-01,
0.2000164937936e-06, 0.4030009638488e+01, 0.2093666171530e+00,
0.1966105136719e-06, 0.8745955786834e+00, 0.2172315424036e+00,
0.1904742332624e-06, 0.5919743598964e+01, 0.2022531624851e+00,
0.1657399705031e-06, 0.2549141484884e+01, 0.7358765972222e+00,
0.1574070533987e-06, 0.5277533020230e+01, 0.7429900518901e+00,
0.1832261651039e-06, 0.3064688127777e+01, 0.3235053470014e+00,
0.1733615346569e-06, 0.3011432799094e+01, 0.1385174140878e+00,
0.1549124014496e-06, 0.4005569132359e+01, 0.5154640627760e+00,
0.1637044713838e-06, 0.1831375966632e+01, 0.8531963191132e+00,
0.1123420082383e-06, 0.1180270407578e+01, 0.1990721704425e+00,
0.1083754165740e-06, 0.3414101320863e+00, 0.5439178814476e+00,
0.1156638012655e-06, 0.6130479452594e+00, 0.5257585094865e+00,
0.1142548785134e-06, 0.3724761948846e+01, 0.5336234347371e+00,
0.7921463895965e-07, 0.2435425589361e+01, 0.1478866649112e+01,
0.7428600285231e-07, 0.3542144398753e+01, 0.2164800718209e+00,
0.8323211246747e-07, 0.3525058072354e+01, 0.1692165728891e+01,
0.7257595116312e-07, 0.1364299431982e+01, 0.2101180877357e+00,
0.7111185833236e-07, 0.2460478875808e+01, 0.4155522422634e+00,
0.6868090383716e-07, 0.4397327670704e+01, 0.1173197218910e+00,
0.7226419974175e-07, 0.4042647308905e+01, 0.1265567569334e+01,
0.6955642383177e-07, 0.2865047906085e+01, 0.9562891316684e+00,
0.7492139296331e-07, 0.5014278994215e+01, 0.1422690933580e-01,
0.6598363128857e-07, 0.2376730020492e+01, 0.6470106940028e+00,
0.7381147293385e-07, 0.3272990384244e+01, 0.1581959461667e+01,
0.6402909624032e-07, 0.5302290955138e+01, 0.9597935788730e-01,
0.6237454263857e-07, 0.5444144425332e+01, 0.7084920306520e-01,
0.5241198544016e-07, 0.4215359579205e+01, 0.5265099800692e+00,
0.5144463853918e-07, 0.1218916689916e+00, 0.5328719641544e+00,
0.5868164772299e-07, 0.2369402002213e+01, 0.7871412831580e-01,
0.6233195669151e-07, 0.1254922242403e+01, 0.2608790314060e+02,
0.6068463791422e-07, 0.5679713760431e+01, 0.1114304132498e+00,
0.4359361135065e-07, 0.6097219641646e+00, 0.1375773836557e+01,
0.4686510366826e-07, 0.4786231041431e+01, 0.1143987543936e+00,
0.3758977287225e-07, 0.1167368068139e+01, 0.1596186371003e+01,
0.4282051974778e-07, 0.1519471064319e+01, 0.2770348281756e+00,
0.5153765386113e-07, 0.1860532322984e+01, 0.2228608264996e+00,
0.4575129387188e-07, 0.7632857887158e+00, 0.1465949902372e+00,
0.3326844933286e-07, 0.1298219485285e+01, 0.5070101000000e-01,
0.3748617450984e-07, 0.1046510321062e+01, 0.4903339079539e+00,
0.2816756661499e-07, 0.3434522346190e+01, 0.2991266627620e+00,
0.3412750405039e-07, 0.2523766270318e+01, 0.3518164938661e+00,
0.2655796761776e-07, 0.2904422260194e+01, 0.6256703299991e+00,
0.2963597929458e-07, 0.5923900431149e+00, 0.1099462426779e+00,
0.2539523734781e-07, 0.4851947722567e+01, 0.1256615170089e+02,
0.2283087914139e-07, 0.3400498595496e+01, 0.6681224869435e+01,
0.2321309799331e-07, 0.5789099148673e+01, 0.3368040641550e-01,
0.2549657649750e-07, 0.3991856479792e-01, 0.1169588211447e+01,
0.2290462303977e-07, 0.2788567577052e+01, 0.1045155034888e+01,
0.1945398522914e-07, 0.3290896998176e+01, 0.1155361302111e+01,
0.1849171512638e-07, 0.2698060129367e+01, 0.4452511715700e-02,
0.1647199834254e-07, 0.3016735644085e+01, 0.4408250688924e+00,
0.1529530765273e-07, 0.5573043116178e+01, 0.6521991896920e-01,
0.1433199339978e-07, 0.1481192356147e+01, 0.9420622223326e+00,
0.1729134193602e-07, 0.1422817538933e+01, 0.2108507877249e+00,
0.1716463931346e-07, 0.3469468901855e+01, 0.2157473718317e+00,
0.1391206061378e-07, 0.6122436220547e+01, 0.4123712502208e+00,
0.1404746661924e-07, 0.1647765641936e+01, 0.4258542984690e-01,
0.1410452399455e-07, 0.5989729161964e+01, 0.2258291676434e+00,
0.1089828772168e-07, 0.2833705509371e+01, 0.4226656969313e+00,
0.1047374564948e-07, 0.5090690007331e+00, 0.3092784376656e+00,
0.1358279126532e-07, 0.5128990262836e+01, 0.7923417740620e-01,
0.1020456476148e-07, 0.9632772880808e+00, 0.1456308687557e+00,
0.1033428735328e-07, 0.3223779318418e+01, 0.1795258541446e+01,
0.1412435841540e-07, 0.2410271572721e+01, 0.1525316725248e+00,
0.9722759371574e-08, 0.2333531395690e+01, 0.8434341241180e-01,
0.9657334084704e-08, 0.6199270974168e+01, 0.1272681024002e+01,
0.1083641148690e-07, 0.2864222292929e+01, 0.7032915397480e-01,
0.1067318403838e-07, 0.5833458866568e+00, 0.2123349582968e+00,
0.1062366201976e-07, 0.4307753989494e+01, 0.2142632012598e+00,
0.1236364149266e-07, 0.2873917870593e+01, 0.1847279083684e+00,
0.1092759489593e-07, 0.2959887266733e+01, 0.1370332435159e+00,
0.8912069362899e-08, 0.5141213702562e+01, 0.2648454860559e+01,
0.9656467707970e-08, 0.4532182462323e+01, 0.4376440768498e+00,
0.8098386150135e-08, 0.2268906338379e+01, 0.2880807454688e+00,
0.7857714675000e-08, 0.4055544260745e+01, 0.2037373330570e+00,
0.7288455940646e-08, 0.5357901655142e+01, 0.1129145838217e+00,
0.9450595950552e-08, 0.4264926963939e+01, 0.5272426800584e+00,
0.9381718247537e-08, 0.7489366976576e-01, 0.5321392641652e+00,
0.7079052646038e-08, 0.1923311052874e+01, 0.6288513220417e+00,
0.9259004415344e-08, 0.2970256853438e+01, 0.1606092486742e+00,
0.8259801499742e-08, 0.3327056314697e+01, 0.8389694097774e+00,
0.6476334355779e-08, 0.2954925505727e+01, 0.2008557621224e+01,
0.5984021492007e-08, 0.9138753105829e+00, 0.2042657109477e+02,
0.5989546863181e-08, 0.3244464082031e+01, 0.2111650433779e+01,
0.6233108606023e-08, 0.4995232638403e+00, 0.4305306221819e+00,
0.6877299149965e-08, 0.2834987233449e+01, 0.9561746721300e-02,
0.8311234227190e-08, 0.2202951835758e+01, 0.3801276407308e+00,
0.6599472832414e-08, 0.4478581462618e+01, 0.1063314406849e+01,
0.6160491096549e-08, 0.5145858696411e+01, 0.1368660381889e+01,
0.6164772043891e-08, 0.3762976697911e+00, 0.4234171675140e+00,
0.6363248684450e-08, 0.3162246718685e+01, 0.1253008786510e-01,
0.6448587520999e-08, 0.3442693302119e+01, 0.5287268506303e+00,
0.6431662283977e-08, 0.8977549136606e+00, 0.5306550935933e+00,
0.6351223158474e-08, 0.4306447410369e+01, 0.5217580628120e+02,
0.5476721393451e-08, 0.3888529177855e+01, 0.2221856701002e+01,
0.5341772572619e-08, 0.2655560662512e+01, 0.7466759693650e-01,
0.5337055758302e-08, 0.5164990735946e+01, 0.7489573444450e-01,
0.5373120816787e-08, 0.6041214553456e+01, 0.1274714967946e+00,
0.5392351705426e-08, 0.9177763485932e+00, 0.1055449481598e+01,
0.6688495850205e-08, 0.3089608126937e+01, 0.2213766559277e+00,
0.5072003660362e-08, 0.4311316541553e+01, 0.2132517061319e+00,
0.5070726650455e-08, 0.5790675464444e+00, 0.2133464534247e+00,
0.5658012950032e-08, 0.2703945510675e+01, 0.7287631425543e+00,
0.4835509924854e-08, 0.2975422976065e+01, 0.7160067364790e-01,
0.6479821978012e-08, 0.1324168733114e+01, 0.2209183458640e-01,
0.6230636494980e-08, 0.2860103632836e+01, 0.3306188016693e+00,
0.4649239516213e-08, 0.4832259763403e+01, 0.7796265773310e-01,
0.6487325792700e-08, 0.2726165825042e+01, 0.3884652414254e+00,
0.4682823682770e-08, 0.6966602455408e+00, 0.1073608853559e+01,
0.5704230804976e-08, 0.5669634104606e+01, 0.8731175355560e-01,
0.6125413585489e-08, 0.1513386538915e+01, 0.7605151500000e-01,
0.6035825038187e-08, 0.1983509168227e+01, 0.9846002785331e+00,
0.4331123462303e-08, 0.2782892992807e+01, 0.4297791515992e+00,
0.4681107685143e-08, 0.5337232886836e+01, 0.2127790306879e+00,
0.4669105829655e-08, 0.5837133792160e+01, 0.2138191288687e+00,
0.5138823602365e-08, 0.3080560200507e+01, 0.7233337363710e-01,
0.4615856664534e-08, 0.1661747897471e+01, 0.8603097737811e+00,
0.4496916702197e-08, 0.2112508027068e+01, 0.7381754420900e-01,
0.4278479042945e-08, 0.5716528462627e+01, 0.7574578717200e-01,
0.3840525503932e-08, 0.6424172726492e+00, 0.3407705765729e+00,
0.4866636509685e-08, 0.4919244697715e+01, 0.7722995774390e-01,
0.3526100639296e-08, 0.2550821052734e+01, 0.6225157782540e-01,
0.3939558488075e-08, 0.3939331491710e+01, 0.5268983110410e-01,
0.4041268772576e-08, 0.2275337571218e+01, 0.3503323232942e+00,
0.3948761842853e-08, 0.1999324200790e+01, 0.1451108196653e+00,
0.3258394550029e-08, 0.9121001378200e+00, 0.5296435984654e+00,
0.3257897048761e-08, 0.3428428660869e+01, 0.5297383457582e+00,
0.3842559031298e-08, 0.6132927720035e+01, 0.9098186128426e+00,
0.3109920095448e-08, 0.7693650193003e+00, 0.3932462625300e-02,
0.3132237775119e-08, 0.3621293854908e+01, 0.2346394437820e+00,
0.3942189421510e-08, 0.4841863659733e+01, 0.3180992042600e-02,
0.3796972285340e-08, 0.1814174994268e+01, 0.1862120789403e+00,
0.3995640233688e-08, 0.1386990406091e+01, 0.4549093064213e+00,
0.2875013727414e-08, 0.9178318587177e+00, 0.1905464808669e+01,
0.3073719932844e-08, 0.2688923811835e+01, 0.3628624111593e+00,
0.2731016580075e-08, 0.1188259127584e+01, 0.2131850110243e+00,
0.2729549896546e-08, 0.3702160634273e+01, 0.2134131485323e+00,
0.3339372892449e-08, 0.7199163960331e+00, 0.2007689919132e+00,
0.2898833764204e-08, 0.1916709364999e+01, 0.5291709230214e+00,
0.2894536549362e-08, 0.2424043195547e+01, 0.5302110212022e+00,
0.3096872473843e-08, 0.4445894977497e+01, 0.2976424921901e+00,
0.2635672326810e-08, 0.3814366984117e+01, 0.1485980103780e+01,
0.3649302697001e-08, 0.2924200596084e+01, 0.6044726378023e+00,
0.3127954585895e-08, 0.1842251648327e+01, 0.1084620721060e+00,
0.2616040173947e-08, 0.4155841921984e+01, 0.1258454114666e+01,
0.2597395859860e-08, 0.1158045978874e+00, 0.2103781122809e+00,
0.2593286172210e-08, 0.4771850408691e+01, 0.2162200472757e+00,
0.2481823585747e-08, 0.4608842558889e+00, 0.1062562936266e+01,
0.2742219550725e-08, 0.1538781127028e+01, 0.5651155736444e+00,
0.3199558469610e-08, 0.3226647822878e+00, 0.7036329877322e+00,
0.2666088542957e-08, 0.1967991731219e+00, 0.1400015846597e+00,
0.2397067430580e-08, 0.3707036669873e+01, 0.2125476091956e+00,
0.2376570772738e-08, 0.1182086628042e+01, 0.2140505503610e+00,
0.2547228007887e-08, 0.4906256820629e+01, 0.1534957940063e+00,
0.2265575594114e-08, 0.3414949866857e+01, 0.2235935264888e+00,
0.2464381430585e-08, 0.4599122275378e+01, 0.2091065926078e+00,
0.2433408527044e-08, 0.2830751145445e+00, 0.2174915669488e+00,
0.2443605509076e-08, 0.4212046432538e+01, 0.1739420156204e+00,
0.2319779262465e-08, 0.9881978408630e+00, 0.7530171478090e-01,
0.2284622835465e-08, 0.5565347331588e+00, 0.7426161660010e-01,
0.2467268750783e-08, 0.5655708150766e+00, 0.2526561439362e+00,
0.2808513492782e-08, 0.1418405053408e+01, 0.5636314030725e+00,
0.2329528932532e-08, 0.4069557545675e+01, 0.1056200952181e+01,
0.9698639532817e-09, 0.1074134313634e+01, 0.7826370942180e+02}
/* SSB-to-Sun, T^0, Y */
s0y := []float64{
0.4955392320126e-02, 0.2170467313679e+01, 0.5296909721118e+00,
0.2722325167392e-02, 0.2444433682196e+01, 0.2132990797783e+00,
0.1546579925346e-02, 0.5992779281546e+00, 0.3813291813120e-01,
0.8363140252966e-03, 0.7687356310801e+00, 0.7478166569050e-01,
0.3385792683603e-03, 0.0000000000000e+00, 0.0000000000000e+00,
0.1201192221613e-03, 0.2520035601514e+01, 0.1059381944224e+01,
0.7587125720554e-04, 0.1669954006449e+01, 0.4265981595566e+00,
0.1964155361250e-04, 0.5707743963343e+01, 0.2061856251104e+00,
0.1891900364909e-04, 0.2320960679937e+01, 0.2204125344462e+00,
0.1937373433356e-04, 0.3226940689555e+01, 0.1495633313810e+00,
0.1437139941351e-04, 0.2301626908096e+01, 0.5225775174439e+00,
0.1406267683099e-04, 0.5188579265542e+01, 0.5368044267797e+00,
0.1178703080346e-04, 0.5489483248476e+01, 0.7626583626240e-01,
0.8079835186041e-05, 0.1683751835264e+01, 0.3664874755930e-01,
0.7623253594652e-05, 0.2656400462961e+01, 0.3961708870310e-01,
0.6248667483971e-05, 0.4992775362055e+01, 0.7329749511860e-01,
0.4366353695038e-05, 0.2869706279678e+01, 0.1589072916335e+01,
0.3829101568895e-05, 0.3572131359950e+01, 0.7113454667900e-02,
0.3175733773908e-05, 0.4535372530045e+01, 0.4194847048887e+00,
0.3092437902159e-05, 0.9230153317909e+00, 0.6398972393349e+00,
0.2874168812154e-05, 0.3363143761101e+01, 0.1102062672231e+00,
0.3040119321826e-05, 0.3324250895675e+01, 0.6283075850446e+01,
0.2699723308006e-05, 0.2917882441928e+00, 0.1030928125552e+00,
0.2134832683534e-05, 0.4220997202487e+01, 0.3163918923335e+00,
0.1770412139433e-05, 0.4747318496462e+01, 0.1021328554739e+02,
0.1377264209373e-05, 0.4305058462401e+00, 0.1484170571900e-02,
0.1127814538960e-05, 0.8538177240740e+00, 0.6327837846670e+00,
0.1055608090130e-05, 0.1551800742580e+01, 0.4337116142245e+00,
0.9802673861420e-06, 0.1459646735377e+01, 0.1052268489556e+01,
0.1090329461951e-05, 0.1587351228711e+01, 0.1162474756779e+01,
0.6959590025090e-06, 0.5534442628766e+01, 0.1066495398892e+01,
0.5664914529542e-06, 0.6030673003297e+01, 0.9491756770005e+00,
0.6607787763599e-06, 0.4989507233927e+01, 0.8460828644453e+00,
0.6269725742838e-06, 0.4222951804572e+01, 0.1480791608091e+00,
0.6301889697863e-06, 0.5444316669126e+01, 0.2243449970715e+00,
0.4891042662861e-06, 0.1490552839784e+01, 0.3340612434717e+01,
0.3457083123290e-06, 0.3030475486049e+01, 0.3516457698740e-01,
0.3032559967314e-06, 0.2652038793632e+01, 0.1104591729320e-01,
0.2841133988903e-06, 0.1276744786829e+01, 0.4110125927500e-01,
0.2855564444432e-06, 0.2143368674733e+01, 0.1510475019529e+00,
0.2765157135038e-06, 0.5444186109077e+01, 0.6373574839730e-01,
0.2382312465034e-06, 0.2190521137593e+01, 0.2275259891141e+00,
0.2808060365077e-06, 0.5735195064841e+01, 0.2535050500000e-01,
0.2332175234405e-06, 0.9481985524859e-01, 0.7181332454670e-01,
0.2322488199659e-06, 0.5180499361533e+01, 0.8582758298370e-01,
0.1881850258423e-06, 0.3219788273885e+01, 0.2118763888447e+01,
0.2196111392808e-06, 0.2366941159761e+01, 0.2968341143800e-02,
0.2183810335519e-06, 0.4825445110915e+01, 0.7775000683430e-01,
0.2002733093326e-06, 0.2457148995307e+01, 0.2093666171530e+00,
0.1967111767229e-06, 0.5586291545459e+01, 0.2172315424036e+00,
0.1568473250543e-06, 0.3708003123320e+01, 0.7429900518901e+00,
0.1852528314300e-06, 0.4310638151560e+01, 0.2022531624851e+00,
0.1832111226447e-06, 0.1494665322656e+01, 0.3235053470014e+00,
0.1746805502310e-06, 0.1451378500784e+01, 0.1385174140878e+00,
0.1555730966650e-06, 0.1068040418198e+01, 0.7358765972222e+00,
0.1554883462559e-06, 0.2442579035461e+01, 0.5154640627760e+00,
0.1638380568746e-06, 0.2597913420625e+00, 0.8531963191132e+00,
0.1159938593640e-06, 0.5834512021280e+01, 0.1990721704425e+00,
0.1083427965695e-06, 0.5054033177950e+01, 0.5439178814476e+00,
0.1156480369431e-06, 0.5325677432457e+01, 0.5257585094865e+00,
0.1141308860095e-06, 0.2153403923857e+01, 0.5336234347371e+00,
0.7913146470946e-07, 0.8642846847027e+00, 0.1478866649112e+01,
0.7439752463733e-07, 0.1970628496213e+01, 0.2164800718209e+00,
0.7280277104079e-07, 0.6073307250609e+01, 0.2101180877357e+00,
0.8319567719136e-07, 0.1954371928334e+01, 0.1692165728891e+01,
0.7137705549290e-07, 0.8904989440909e+00, 0.4155522422634e+00,
0.6900825396225e-07, 0.2825717714977e+01, 0.1173197218910e+00,
0.7245757216635e-07, 0.2481677513331e+01, 0.1265567569334e+01,
0.6961165696255e-07, 0.1292955312978e+01, 0.9562891316684e+00,
0.7571804456890e-07, 0.3427517575069e+01, 0.1422690933580e-01,
0.6605425721904e-07, 0.8052192701492e+00, 0.6470106940028e+00,
0.7375477357248e-07, 0.1705076390088e+01, 0.1581959461667e+01,
0.7041664951470e-07, 0.4848356967891e+00, 0.9597935788730e-01,
0.6322199535763e-07, 0.3878069473909e+01, 0.7084920306520e-01,
0.5244380279191e-07, 0.2645560544125e+01, 0.5265099800692e+00,
0.5143125704988e-07, 0.4834486101370e+01, 0.5328719641544e+00,
0.5871866319373e-07, 0.7981472548900e+00, 0.7871412831580e-01,
0.6300822573871e-07, 0.5979398788281e+01, 0.2608790314060e+02,
0.6062154271548e-07, 0.4108655402756e+01, 0.1114304132498e+00,
0.4361912339976e-07, 0.5322624319280e+01, 0.1375773836557e+01,
0.4417005920067e-07, 0.6240817359284e+01, 0.2770348281756e+00,
0.4686806749936e-07, 0.3214977301156e+01, 0.1143987543936e+00,
0.3758892132305e-07, 0.5879809634765e+01, 0.1596186371003e+01,
0.5151351332319e-07, 0.2893377688007e+00, 0.2228608264996e+00,
0.4554683578572e-07, 0.5475427144122e+01, 0.1465949902372e+00,
0.3442381385338e-07, 0.5992034796640e+01, 0.5070101000000e-01,
0.2831093954933e-07, 0.5367350273914e+01, 0.3092784376656e+00,
0.3756267090084e-07, 0.5758171285420e+01, 0.4903339079539e+00,
0.2816374679892e-07, 0.1863718700923e+01, 0.2991266627620e+00,
0.3419307025569e-07, 0.9524347534130e+00, 0.3518164938661e+00,
0.2904250494239e-07, 0.5304471615602e+01, 0.1099462426779e+00,
0.2471734511206e-07, 0.1297069793530e+01, 0.6256703299991e+00,
0.2539620831872e-07, 0.3281126083375e+01, 0.1256615170089e+02,
0.2281017868007e-07, 0.1829122133165e+01, 0.6681224869435e+01,
0.2275319473335e-07, 0.5797198160181e+01, 0.3932462625300e-02,
0.2547755368442e-07, 0.4752697708330e+01, 0.1169588211447e+01,
0.2285979669317e-07, 0.1223205292886e+01, 0.1045155034888e+01,
0.1913386560994e-07, 0.1757532993389e+01, 0.1155361302111e+01,
0.1809020525147e-07, 0.4246116108791e+01, 0.3368040641550e-01,
0.1649213300201e-07, 0.1445162890627e+01, 0.4408250688924e+00,
0.1834972793932e-07, 0.1126917567225e+01, 0.4452511715700e-02,
0.1439550648138e-07, 0.6160756834764e+01, 0.9420622223326e+00,
0.1487645457041e-07, 0.4358761931792e+01, 0.4123712502208e+00,
0.1731729516660e-07, 0.6134456753344e+01, 0.2108507877249e+00,
0.1717747163567e-07, 0.1898186084455e+01, 0.2157473718317e+00,
0.1418190430374e-07, 0.4180286741266e+01, 0.6521991896920e-01,
0.1404844134873e-07, 0.7654053565412e-01, 0.4258542984690e-01,
0.1409842846538e-07, 0.4418612420312e+01, 0.2258291676434e+00,
0.1090948346291e-07, 0.1260615686131e+01, 0.4226656969313e+00,
0.1357577323612e-07, 0.3558248818690e+01, 0.7923417740620e-01,
0.1018154061960e-07, 0.5676087241256e+01, 0.1456308687557e+00,
0.1412073972109e-07, 0.8394392632422e+00, 0.1525316725248e+00,
0.1030938326496e-07, 0.1653593274064e+01, 0.1795258541446e+01,
0.1180081567104e-07, 0.1285802592036e+01, 0.7032915397480e-01,
0.9708510575650e-08, 0.7631889488106e+00, 0.8434341241180e-01,
0.9637689663447e-08, 0.4630642649176e+01, 0.1272681024002e+01,
0.1068910429389e-07, 0.5294934032165e+01, 0.2123349582968e+00,
0.1063716179336e-07, 0.2736266800832e+01, 0.2142632012598e+00,
0.1234858713814e-07, 0.1302891146570e+01, 0.1847279083684e+00,
0.8912631189738e-08, 0.3570415993621e+01, 0.2648454860559e+01,
0.1036378285534e-07, 0.4236693440949e+01, 0.1370332435159e+00,
0.9667798501561e-08, 0.2960768892398e+01, 0.4376440768498e+00,
0.8108314201902e-08, 0.6987781646841e+00, 0.2880807454688e+00,
0.7648364324628e-08, 0.2499017863863e+01, 0.2037373330570e+00,
0.7286136828406e-08, 0.3787426951665e+01, 0.1129145838217e+00,
0.9448237743913e-08, 0.2694354332983e+01, 0.5272426800584e+00,
0.9374276106428e-08, 0.4787121277064e+01, 0.5321392641652e+00,
0.7100226287462e-08, 0.3530238792101e+00, 0.6288513220417e+00,
0.9253056659571e-08, 0.1399478925664e+01, 0.1606092486742e+00,
0.6636432145504e-08, 0.3479575438447e+01, 0.1368660381889e+01,
0.6469975312932e-08, 0.1383669964800e+01, 0.2008557621224e+01,
0.7335849729765e-08, 0.1243698166898e+01, 0.9561746721300e-02,
0.8743421205855e-08, 0.3776164289301e+01, 0.3801276407308e+00,
0.5993635744494e-08, 0.5627122113596e+01, 0.2042657109477e+02,
0.5981008479693e-08, 0.1674336636752e+01, 0.2111650433779e+01,
0.6188535145838e-08, 0.5214925208672e+01, 0.4305306221819e+00,
0.6596074017566e-08, 0.2907653268124e+01, 0.1063314406849e+01,
0.6630815126226e-08, 0.2127643669658e+01, 0.8389694097774e+00,
0.6156772830040e-08, 0.5082160803295e+01, 0.4234171675140e+00,
0.6446960563014e-08, 0.1872100916905e+01, 0.5287268506303e+00,
0.6429324424668e-08, 0.5610276103577e+01, 0.5306550935933e+00,
0.6302232396465e-08, 0.1592152049607e+01, 0.1253008786510e-01,
0.6399244436159e-08, 0.2746214421532e+01, 0.5217580628120e+02,
0.5474965172558e-08, 0.2317666374383e+01, 0.2221856701002e+01,
0.5339293190692e-08, 0.1084724961156e+01, 0.7466759693650e-01,
0.5334733683389e-08, 0.3594106067745e+01, 0.7489573444450e-01,
0.5392665782110e-08, 0.5630254365606e+01, 0.1055449481598e+01,
0.6682075673789e-08, 0.1518480041732e+01, 0.2213766559277e+00,
0.5079130495960e-08, 0.2739765115711e+01, 0.2132517061319e+00,
0.5077759793261e-08, 0.5290711290094e+01, 0.2133464534247e+00,
0.4832037368310e-08, 0.1404473217200e+01, 0.7160067364790e-01,
0.6463279674802e-08, 0.6038381695210e+01, 0.2209183458640e-01,
0.6240592771560e-08, 0.1290170653666e+01, 0.3306188016693e+00,
0.4672013521493e-08, 0.3261895939677e+01, 0.7796265773310e-01,
0.6500650750348e-08, 0.1154522312095e+01, 0.3884652414254e+00,
0.6344161389053e-08, 0.6206111545062e+01, 0.7605151500000e-01,
0.4682518370646e-08, 0.5409118796685e+01, 0.1073608853559e+01,
0.5329460015591e-08, 0.1202985784864e+01, 0.7287631425543e+00,
0.5701588675898e-08, 0.4098715257064e+01, 0.8731175355560e-01,
0.6030690867211e-08, 0.4132033218460e+00, 0.9846002785331e+00,
0.4336256312655e-08, 0.1211415991827e+01, 0.4297791515992e+00,
0.4688498808975e-08, 0.3765479072409e+01, 0.2127790306879e+00,
0.4675578609335e-08, 0.4265540037226e+01, 0.2138191288687e+00,
0.4225578112158e-08, 0.5237566010676e+01, 0.3407705765729e+00,
0.5139422230028e-08, 0.1507173079513e+01, 0.7233337363710e-01,
0.4619995093571e-08, 0.9023957449848e-01, 0.8603097737811e+00,
0.4494776255461e-08, 0.5414930552139e+00, 0.7381754420900e-01,
0.4274026276788e-08, 0.4145735303659e+01, 0.7574578717200e-01,
0.5018141789353e-08, 0.3344408829055e+01, 0.3180992042600e-02,
0.4866163952181e-08, 0.3348534657607e+01, 0.7722995774390e-01,
0.4111986020501e-08, 0.4198823597220e+00, 0.1451108196653e+00,
0.3356142784950e-08, 0.5609144747180e+01, 0.1274714967946e+00,
0.4070575554551e-08, 0.7028411059224e+00, 0.3503323232942e+00,
0.3257451857278e-08, 0.5624697983086e+01, 0.5296435984654e+00,
0.3256973703026e-08, 0.1857842076707e+01, 0.5297383457582e+00,
0.3830771508640e-08, 0.4562887279931e+01, 0.9098186128426e+00,
0.3725024005962e-08, 0.2358058692652e+00, 0.1084620721060e+00,
0.3136763921756e-08, 0.2049731526845e+01, 0.2346394437820e+00,
0.3795147256194e-08, 0.2432356296933e+00, 0.1862120789403e+00,
0.2877342229911e-08, 0.5631101279387e+01, 0.1905464808669e+01,
0.3076931798805e-08, 0.1117615737392e+01, 0.3628624111593e+00,
0.2734765945273e-08, 0.5899826516955e+01, 0.2131850110243e+00,
0.2733405296885e-08, 0.2130562964070e+01, 0.2134131485323e+00,
0.2898552353410e-08, 0.3462387048225e+00, 0.5291709230214e+00,
0.2893736103681e-08, 0.8534352781543e+00, 0.5302110212022e+00,
0.3095717734137e-08, 0.2875061429041e+01, 0.2976424921901e+00,
0.2636190425832e-08, 0.2242512846659e+01, 0.1485980103780e+01,
0.3645512095537e-08, 0.1354016903958e+01, 0.6044726378023e+00,
0.2808173547723e-08, 0.6705114365631e-01, 0.6225157782540e-01,
0.2625012866888e-08, 0.4775705748482e+01, 0.5268983110410e-01,
0.2572233995651e-08, 0.2638924216139e+01, 0.1258454114666e+01,
0.2604238824792e-08, 0.4826358927373e+01, 0.2103781122809e+00,
0.2596886385239e-08, 0.3200388483118e+01, 0.2162200472757e+00,
0.3228057304264e-08, 0.5384848409563e+01, 0.2007689919132e+00,
0.2481601798252e-08, 0.5173373487744e+01, 0.1062562936266e+01,
0.2745977498864e-08, 0.6250966149853e+01, 0.5651155736444e+00,
0.2669878833811e-08, 0.4906001352499e+01, 0.1400015846597e+00,
0.3203986611711e-08, 0.5034333010005e+01, 0.7036329877322e+00,
0.3354961227212e-08, 0.6108262423137e+01, 0.4549093064213e+00,
0.2400407324558e-08, 0.2135399294955e+01, 0.2125476091956e+00,
0.2379905859802e-08, 0.5893721933961e+01, 0.2140505503610e+00,
0.2550844302187e-08, 0.3331940762063e+01, 0.1534957940063e+00,
0.2268824211001e-08, 0.1843418461035e+01, 0.2235935264888e+00,
0.2464700891204e-08, 0.3029548547230e+01, 0.2091065926078e+00,
0.2436814726024e-08, 0.4994717970364e+01, 0.2174915669488e+00,
0.2443623894745e-08, 0.2645102591375e+01, 0.1739420156204e+00,
0.2318701783838e-08, 0.5700547397897e+01, 0.7530171478090e-01,
0.2284448700256e-08, 0.5268898905872e+01, 0.7426161660010e-01,
0.2468848123510e-08, 0.5276280575078e+01, 0.2526561439362e+00,
0.2814052350303e-08, 0.6130168623475e+01, 0.5636314030725e+00,
0.2243662755220e-08, 0.6631692457995e+00, 0.8886590321940e-01,
0.2330795855941e-08, 0.2499435487702e+01, 0.1056200952181e+01,
0.9757679038404e-09, 0.5796846023126e+01, 0.7826370942180e+02}
/* SSB-to-Sun, T^0, Z */
s0z := []float64{
0.1181255122986e-03, 0.4607918989164e+00, 0.2132990797783e+00,
0.1127777651095e-03, 0.4169146331296e+00, 0.5296909721118e+00,
0.4777754401806e-04, 0.4582657007130e+01, 0.3813291813120e-01,
0.1129354285772e-04, 0.5758735142480e+01, 0.7478166569050e-01,
-0.1149543637123e-04, 0.0000000000000e+00, 0.0000000000000e+00,
0.3298730512306e-05, 0.5978801994625e+01, 0.4265981595566e+00,
0.2733376706079e-05, 0.7665413691040e+00, 0.1059381944224e+01,
0.9426389657270e-06, 0.3710201265838e+01, 0.2061856251104e+00,
0.8187517749552e-06, 0.3390675605802e+00, 0.2204125344462e+00,
0.4080447871819e-06, 0.4552296640088e+00, 0.5225775174439e+00,
0.3169973017028e-06, 0.3445455899321e+01, 0.5368044267797e+00,
0.2438098615549e-06, 0.5664675150648e+01, 0.3664874755930e-01,
0.2601897517235e-06, 0.1931894095697e+01, 0.1495633313810e+00,
0.2314558080079e-06, 0.3666319115574e+00, 0.3961708870310e-01,
0.1962549548002e-06, 0.3167411699020e+01, 0.7626583626240e-01,
0.2180518287925e-06, 0.1544420746580e+01, 0.7113454667900e-02,
0.1451382442868e-06, 0.1583756740070e+01, 0.1102062672231e+00,
0.1358439007389e-06, 0.5239941758280e+01, 0.6398972393349e+00,
0.1050585898028e-06, 0.2266958352859e+01, 0.3163918923335e+00,
0.1050029870186e-06, 0.2711495250354e+01, 0.4194847048887e+00,
0.9934920679800e-07, 0.1116208151396e+01, 0.1589072916335e+01,
0.1048395331560e-06, 0.3408619600206e+01, 0.1021328554739e+02,
0.8370147196668e-07, 0.3810459401087e+01, 0.2535050500000e-01,
0.7989856510998e-07, 0.3769910473647e+01, 0.7329749511860e-01,
0.5441221655233e-07, 0.2416994903374e+01, 0.1030928125552e+00,
0.4610812906784e-07, 0.5858503336994e+01, 0.4337116142245e+00,
0.3923022803444e-07, 0.3354170010125e+00, 0.1484170571900e-02,
0.2610725582128e-07, 0.5410600646324e+01, 0.6327837846670e+00,
0.2455279767721e-07, 0.6120216681403e+01, 0.1162474756779e+01,
0.2375530706525e-07, 0.6055443426143e+01, 0.1052268489556e+01,
0.1782967577553e-07, 0.3146108708004e+01, 0.8460828644453e+00,
0.1581687095238e-07, 0.6255496089819e+00, 0.3340612434717e+01,
0.1594657672461e-07, 0.3782604300261e+01, 0.1066495398892e+01,
0.1563448615040e-07, 0.1997775733196e+01, 0.2022531624851e+00,
0.1463624258525e-07, 0.1736316792088e+00, 0.3516457698740e-01,
0.1331585056673e-07, 0.4331941830747e+01, 0.9491756770005e+00,
0.1130634557637e-07, 0.6152017751825e+01, 0.2968341143800e-02,
0.1028949607145e-07, 0.2101792614637e+00, 0.2275259891141e+00,
0.1024074971618e-07, 0.4071833211074e+01, 0.5070101000000e-01,
0.8826956060303e-08, 0.4861633688145e+00, 0.2093666171530e+00,
0.8572230171541e-08, 0.5268190724302e+01, 0.4110125927500e-01,
0.7649332643544e-08, 0.5134543417106e+01, 0.2608790314060e+02,
0.8581673291033e-08, 0.2920218146681e+01, 0.1480791608091e+00,
0.8430589300938e-08, 0.3604576619108e+01, 0.2172315424036e+00,
0.7776165501012e-08, 0.3772942249792e+01, 0.6373574839730e-01,
0.8311070234408e-08, 0.6200412329888e+01, 0.3235053470014e+00,
0.6927365212582e-08, 0.4543353113437e+01, 0.8531963191132e+00,
0.6791574208598e-08, 0.2882188406238e+01, 0.7181332454670e-01,
0.5593100811839e-08, 0.1776646892780e+01, 0.7429900518901e+00,
0.4553381853021e-08, 0.3949617611240e+01, 0.7775000683430e-01,
0.5758000450068e-08, 0.3859251775075e+01, 0.1990721704425e+00,
0.4281283457133e-08, 0.1466294631206e+01, 0.2118763888447e+01,
0.4206935661097e-08, 0.5421776011706e+01, 0.1104591729320e-01,
0.4213751641837e-08, 0.3412048993322e+01, 0.2243449970715e+00,
0.5310506239878e-08, 0.5421641370995e+00, 0.5154640627760e+00,
0.3827450341320e-08, 0.8887314524995e+00, 0.1510475019529e+00,
0.4292435241187e-08, 0.1405043757194e+01, 0.1422690933580e-01,
0.3189780702289e-08, 0.1060049293445e+01, 0.1173197218910e+00,
0.3226611928069e-08, 0.6270858897442e+01, 0.2164800718209e+00,
0.2893897608830e-08, 0.5117563223301e+01, 0.6470106940028e+00,
0.3239852024578e-08, 0.4079092237983e+01, 0.2101180877357e+00,
0.2956892222200e-08, 0.1594917021704e+01, 0.3092784376656e+00,
0.2980177912437e-08, 0.5258787667564e+01, 0.4155522422634e+00,
0.3163725690776e-08, 0.3854589225479e+01, 0.8582758298370e-01,
0.2662262399118e-08, 0.3561326430187e+01, 0.5257585094865e+00,
0.2766689135729e-08, 0.3180732086830e+00, 0.1385174140878e+00,
0.2411600278464e-08, 0.3324798335058e+01, 0.5439178814476e+00,
0.2483527695131e-08, 0.4169069291947e+00, 0.5336234347371e+00,
0.7788777276590e-09, 0.1900569908215e+01, 0.5217580628120e+02}
/* SSB-to-Sun, T^1, X */
s1x := []float64{
-0.1296310361520e-07, 0.0000000000000e+00, 0.0000000000000e+00,
0.8975769009438e-08, 0.1128891609250e+01, 0.4265981595566e+00,
0.7771113441307e-08, 0.2706039877077e+01, 0.2061856251104e+00,
0.7538303866642e-08, 0.2191281289498e+01, 0.2204125344462e+00,
0.6061384579336e-08, 0.3248167319958e+01, 0.1059381944224e+01,
0.5726994235594e-08, 0.5569981398610e+01, 0.5225775174439e+00,
0.5616492836424e-08, 0.5057386614909e+01, 0.5368044267797e+00,
0.1010881584769e-08, 0.3473577116095e+01, 0.7113454667900e-02,
0.7259606157626e-09, 0.3651858593665e+00, 0.6398972393349e+00,
0.8755095026935e-09, 0.1662835408338e+01, 0.4194847048887e+00,
0.5370491182812e-09, 0.1327673878077e+01, 0.4337116142245e+00,
0.5743773887665e-09, 0.4250200846687e+01, 0.2132990797783e+00,
0.4408103140300e-09, 0.3598752574277e+01, 0.1589072916335e+01,
0.3101892374445e-09, 0.4887822983319e+01, 0.1052268489556e+01,
0.3209453713578e-09, 0.9702272295114e+00, 0.5296909721118e+00,
0.3017228286064e-09, 0.5484462275949e+01, 0.1066495398892e+01,
0.3200700038601e-09, 0.2846613338643e+01, 0.1495633313810e+00,
0.2137637279911e-09, 0.5692163292729e+00, 0.3163918923335e+00,
0.1899686386727e-09, 0.2061077157189e+01, 0.2275259891141e+00,
0.1401994545308e-09, 0.4177771136967e+01, 0.1102062672231e+00,
0.1578057810499e-09, 0.5782460597335e+01, 0.7626583626240e-01,
0.1237713253351e-09, 0.5705900866881e+01, 0.5154640627760e+00,
0.1313076837395e-09, 0.5163438179576e+01, 0.3664874755930e-01,
0.1184963304860e-09, 0.3054804427242e+01, 0.6327837846670e+00,
0.1238130878565e-09, 0.2317292575962e+01, 0.3961708870310e-01,
0.1015959527736e-09, 0.2194643645526e+01, 0.7329749511860e-01,
0.9017954423714e-10, 0.2868603545435e+01, 0.1990721704425e+00,
0.8668024955603e-10, 0.4923849675082e+01, 0.5439178814476e+00,
0.7756083930103e-10, 0.3014334135200e+01, 0.9491756770005e+00,
0.7536503401741e-10, 0.2704886279769e+01, 0.1030928125552e+00,
0.5483308679332e-10, 0.6010983673799e+01, 0.8531963191132e+00,
0.5184339620428e-10, 0.1952704573291e+01, 0.2093666171530e+00,
0.5108658712030e-10, 0.2958575786649e+01, 0.2172315424036e+00,
0.5019424524650e-10, 0.1736317621318e+01, 0.2164800718209e+00,
0.4909312625978e-10, 0.3167216416257e+01, 0.2101180877357e+00,
0.4456638901107e-10, 0.7697579923471e+00, 0.3235053470014e+00,
0.4227030350925e-10, 0.3490910137928e+01, 0.6373574839730e-01,
0.4095456040093e-10, 0.5178888984491e+00, 0.6470106940028e+00,
0.4990537041422e-10, 0.3323887668974e+01, 0.1422690933580e-01,
0.4321170010845e-10, 0.4288484987118e+01, 0.7358765972222e+00,
0.3544072091802e-10, 0.6021051579251e+01, 0.5265099800692e+00,
0.3480198638687e-10, 0.4600027054714e+01, 0.5328719641544e+00,
0.3440287244435e-10, 0.4349525970742e+01, 0.8582758298370e-01,
0.3330628322713e-10, 0.2347391505082e+01, 0.1104591729320e-01,
0.2973060707184e-10, 0.4789409286400e+01, 0.5257585094865e+00,
0.2932606766089e-10, 0.5831693799927e+01, 0.5336234347371e+00,
0.2876972310953e-10, 0.2692638514771e+01, 0.1173197218910e+00,
0.2827488278556e-10, 0.2056052487960e+01, 0.2022531624851e+00,
0.2515028239756e-10, 0.7411863262449e+00, 0.9597935788730e-01,
0.2853033744415e-10, 0.3948481024894e+01, 0.2118763888447e+01}
/* SSB-to-Sun, T^1, Y */
s1y := []float64{
0.8989047573576e-08, 0.5840593672122e+01, 0.4265981595566e+00,
0.7815938401048e-08, 0.1129664707133e+01, 0.2061856251104e+00,
0.7550926713280e-08, 0.6196589104845e+00, 0.2204125344462e+00,
0.6056556925895e-08, 0.1677494667846e+01, 0.1059381944224e+01,
0.5734142698204e-08, 0.4000920852962e+01, 0.5225775174439e+00,
0.5614341822459e-08, 0.3486722577328e+01, 0.5368044267797e+00,
0.1028678147656e-08, 0.1877141024787e+01, 0.7113454667900e-02,
0.7270792075266e-09, 0.5077167301739e+01, 0.6398972393349e+00,
0.8734141726040e-09, 0.9069550282609e-01, 0.4194847048887e+00,
0.5377371402113e-09, 0.6039381844671e+01, 0.4337116142245e+00,
0.4729719431571e-09, 0.2153086311760e+01, 0.2132990797783e+00,
0.4458052820973e-09, 0.5059830025565e+01, 0.5296909721118e+00,
0.4406855467908e-09, 0.2027971692630e+01, 0.1589072916335e+01,
0.3101659310977e-09, 0.3317677981860e+01, 0.1052268489556e+01,
0.3016749232545e-09, 0.3913703482532e+01, 0.1066495398892e+01,
0.3198541352656e-09, 0.1275513098525e+01, 0.1495633313810e+00,
0.2142065389871e-09, 0.5301351614597e+01, 0.3163918923335e+00,
0.1902615247592e-09, 0.4894943352736e+00, 0.2275259891141e+00,
0.1613410990871e-09, 0.2449891130437e+01, 0.1102062672231e+00,
0.1576992165097e-09, 0.4211421447633e+01, 0.7626583626240e-01,
0.1241637259894e-09, 0.4140803368133e+01, 0.5154640627760e+00,
0.1313974830355e-09, 0.3591920305503e+01, 0.3664874755930e-01,
0.1181697118258e-09, 0.1506314382788e+01, 0.6327837846670e+00,
0.1238239742779e-09, 0.7461405378404e+00, 0.3961708870310e-01,
0.1010107068241e-09, 0.6271010795475e+00, 0.7329749511860e-01,
0.9226316616509e-10, 0.1259158839583e+01, 0.1990721704425e+00,
0.8664946419555e-10, 0.3353244696934e+01, 0.5439178814476e+00,
0.7757230468978e-10, 0.1447677295196e+01, 0.9491756770005e+00,
0.7693168628139e-10, 0.1120509896721e+01, 0.1030928125552e+00,
0.5487897454612e-10, 0.4439380426795e+01, 0.8531963191132e+00,
0.5196118677218e-10, 0.3788856619137e+00, 0.2093666171530e+00,
0.5110853339935e-10, 0.1386879372016e+01, 0.2172315424036e+00,
0.5027804534813e-10, 0.1647881805466e+00, 0.2164800718209e+00,
0.4922485922674e-10, 0.1594315079862e+01, 0.2101180877357e+00,
0.6155599524400e-10, 0.0000000000000e+00, 0.0000000000000e+00,
0.4447147832161e-10, 0.5480720918976e+01, 0.3235053470014e+00,
0.4144691276422e-10, 0.1931371033660e+01, 0.6373574839730e-01,
0.4099950625452e-10, 0.5229611294335e+01, 0.6470106940028e+00,
0.5060541682953e-10, 0.1731112486298e+01, 0.1422690933580e-01,
0.4293615946300e-10, 0.2714571038925e+01, 0.7358765972222e+00,
0.3545659845763e-10, 0.4451041444634e+01, 0.5265099800692e+00,
0.3479112041196e-10, 0.3029385448081e+01, 0.5328719641544e+00,
0.3438516493570e-10, 0.2778507143731e+01, 0.8582758298370e-01,
0.3297341285033e-10, 0.7898709807584e+00, 0.1104591729320e-01,
0.2972585818015e-10, 0.3218785316973e+01, 0.5257585094865e+00,
0.2931707295017e-10, 0.4260731012098e+01, 0.5336234347371e+00,
0.2897198149403e-10, 0.1120753978101e+01, 0.1173197218910e+00,
0.2832293240878e-10, 0.4597682717827e+00, 0.2022531624851e+00,
0.2864348326612e-10, 0.2169939928448e+01, 0.9597935788730e-01,
0.2852714675471e-10, 0.2377659870578e+01, 0.2118763888447e+01}
/* SSB-to-Sun, T^1, Z */
s1z := []float64{
0.5444220475678e-08, 0.1803825509310e+01, 0.2132990797783e+00,
0.3883412695596e-08, 0.4668616389392e+01, 0.5296909721118e+00,
0.1334341434551e-08, 0.0000000000000e+00, 0.0000000000000e+00,
0.3730001266883e-09, 0.5401405918943e+01, 0.2061856251104e+00,
0.2894929197956e-09, 0.4932415609852e+01, 0.2204125344462e+00,
0.2857950357701e-09, 0.3154625362131e+01, 0.7478166569050e-01,
0.2499226432292e-09, 0.3657486128988e+01, 0.4265981595566e+00,
0.1937705443593e-09, 0.5740434679002e+01, 0.1059381944224e+01,
0.1374894396320e-09, 0.1712857366891e+01, 0.5368044267797e+00,
0.1217248678408e-09, 0.2312090870932e+01, 0.5225775174439e+00,
0.7961052740870e-10, 0.5283368554163e+01, 0.3813291813120e-01,
0.4979225949689e-10, 0.4298290471860e+01, 0.4194847048887e+00,
0.4388552286597e-10, 0.6145515047406e+01, 0.7113454667900e-02,
0.2586835212560e-10, 0.3019448001809e+01, 0.6398972393349e+00}
/* SSB-to-Sun, T^2, X */
s2x := []float64{
0.1603551636587e-11, 0.4404109410481e+01, 0.2061856251104e+00,
0.1556935889384e-11, 0.4818040873603e+00, 0.2204125344462e+00,
0.1182594414915e-11, 0.9935762734472e+00, 0.5225775174439e+00,
0.1158794583180e-11, 0.3353180966450e+01, 0.5368044267797e+00,
0.9597358943932e-12, 0.5567045358298e+01, 0.2132990797783e+00,
0.6511516579605e-12, 0.5630872420788e+01, 0.4265981595566e+00,
0.7419792747688e-12, 0.2156188581957e+01, 0.5296909721118e+00,
0.3951972655848e-12, 0.1981022541805e+01, 0.1059381944224e+01,
0.4478223877045e-12, 0.0000000000000e+00, 0.0000000000000e+00}
/* SSB-to-Sun, T^2, Y */
s2y := []float64{
0.1609114495091e-11, 0.2831096993481e+01, 0.2061856251104e+00,
0.1560330784946e-11, 0.5193058213906e+01, 0.2204125344462e+00,
0.1183535479202e-11, 0.5707003443890e+01, 0.5225775174439e+00,
0.1158183066182e-11, 0.1782400404928e+01, 0.5368044267797e+00,
0.1032868027407e-11, 0.4036925452011e+01, 0.2132990797783e+00,
0.6540142847741e-12, 0.4058241056717e+01, 0.4265981595566e+00,
0.7305236491596e-12, 0.6175401942957e+00, 0.5296909721118e+00,
-0.5580725052968e-12, 0.0000000000000e+00, 0.0000000000000e+00,
0.3946122651015e-12, 0.4108265279171e+00, 0.1059381944224e+01}
/* SSB-to-Sun, T^2, Z */
s2z := []float64{
0.3749920358054e-12, 0.3230285558668e+01, 0.2132990797783e+00,
0.2735037220939e-12, 0.6154322683046e+01, 0.5296909721118e+00}
/* Pointers to coefficient arrays, in x,y,z sets */
ce0 := [3][]float64{e0x, e0y, e0z}
ce1 := [3][]float64{e1x, e1y, e1z}
ce2 := [3][]float64{e2x, e2y, e2z}
cs0 := [3][]float64{s0x, s0y, s0z}
cs1 := [3][]float64{s1x, s1y, s1z}
cs2 := [3][]float64{s2x, s2y, s2z}
// const double *coeffs;
var coeffs *[]float64
/* Numbers of terms for each component of the model, in x,y,z sets */
ne0 := [3]int{len(e0x) / 3, len(e0y) / 3, len(e0z) / 3}
ne1 := [3]int{len(e1x) / 3, len(e1y) / 3, len(e1z) / 3}
ne2 := [3]int{len(e2x) / 3, len(e2y) / 3, len(e2z) / 3}
ns0 := [3]int{len(s0x) / 3, len(s0y) / 3, len(s0z) / 3}
ns1 := [3]int{len(s1x) / 3, len(s1y) / 3, len(s1z) / 3}
ns2 := [3]int{len(s2x) / 3, len(s2y) / 3, len(s2z) / 3}
var nterms int
/* Miscellaneous */
var jstat, i, j int
var t, t2, xyz, xyzd, a, b, c, ct, p, cp float64
var ph, vh, pb, vb [3]float64
var x, y, z float64
/* ------------------------------------------------------------------ */
/* Time since reference epoch, Julian years. */
t = ((date1 - DJ00) + date2) / DJY
t2 = t * t
/* Set status. */
// jstat = fabs(t) <= 100.0 ? 0 : 1;
if fabs(t) <= 100.0 {
jstat = 0
} else {
jstat = 1
}
/* X then Y then Z. */
for i = 0; i < 3; i++ {
/* Initialize position and velocity component. */
xyz = 0.0
xyzd = 0.0
/* ------------------------------------------------ */
/* Obtain component of Sun to Earth ecliptic vector */
/* ------------------------------------------------ */
/* Sun to Earth, T^0 terms. */
coeffs = &ce0[i]
nterms = ne0[i]
for j = 0; j < nterms; j++ {
a = (*coeffs)[j*3]
b = (*coeffs)[j*3+1]
c = (*coeffs)[j*3+2]
p = b + c*t
xyz += a * cos(p)
xyzd -= a * c * sin(p)
}
/* Sun to Earth, T^1 terms. */
coeffs = &ce1[i]
nterms = ne1[i]
for j = 0; j < nterms; j++ {
a = (*coeffs)[j*3]
b = (*coeffs)[j*3+1]
c = (*coeffs)[j*3+2]
ct = c * t
p = b + ct
cp = cos(p)
xyz += a * t * cp
xyzd += a * (cp - ct*sin(p))
}
/* Sun to Earth, T^2 terms. */
coeffs = &ce2[i]
nterms = ne2[i]
for j = 0; j < nterms; j++ {
a = (*coeffs)[j*3]
b = (*coeffs)[j*3+1]
c = (*coeffs)[j*3+2]
ct = c * t
p = b + ct
cp = cos(p)
xyz += a * t2 * cp
xyzd += a * t * (2.0*cp - ct*sin(p))
}
/* Heliocentric Earth position and velocity component. */
ph[i] = xyz
vh[i] = xyzd / DJY
/* ------------------------------------------------ */
/* Obtain component of SSB to Earth ecliptic vector */
/* ------------------------------------------------ */
/* SSB to Sun, T^0 terms. */
coeffs = &cs0[i]
nterms = ns0[i]
for j = 0; j < nterms; j++ {
a = (*coeffs)[j*3]
b = (*coeffs)[j*3+1]
c = (*coeffs)[j*3+2]
p = b + c*t
xyz += a * cos(p)
xyzd -= a * c * sin(p)
}
/* SSB to Sun, T^1 terms. */
coeffs = &cs1[i]
nterms = ns1[i]
for j = 0; j < nterms; j++ {
a = (*coeffs)[j*3]
b = (*coeffs)[j*3+1]
c = (*coeffs)[j*3+2]
ct = c * t
p = b + ct
cp = cos(p)
xyz += a * t * cp
xyzd += a * (cp - ct*sin(p))
}
/* SSB to Sun, T^2 terms. */
coeffs = &cs2[i]
nterms = ns2[i]
for j = 0; j < nterms; j++ {
a = (*coeffs)[j*3]
b = (*coeffs)[j*3+1]
c = (*coeffs)[j*3+2]
ct = c * t
p = b + ct
cp = cos(p)
xyz += a * t2 * cp
xyzd += a * t * (2.0*cp - ct*sin(p))
}
/* Barycentric Earth position and velocity component. */
pb[i] = xyz
vb[i] = xyzd / DJY
/* Next Cartesian component. */
}
/* Rotate from ecliptic to BCRS coordinates. */
x = ph[0]
y = ph[1]
z = ph[2]
pvh[0][0] = x + am12*y + am13*z
pvh[0][1] = am21*x + am22*y + am23*z
pvh[0][2] = am32*y + am33*z
x = vh[0]
y = vh[1]
z = vh[2]
pvh[1][0] = x + am12*y + am13*z
pvh[1][1] = am21*x + am22*y + am23*z
pvh[1][2] = am32*y + am33*z
x = pb[0]
y = pb[1]
z = pb[2]
pvb[0][0] = x + am12*y + am13*z
pvb[0][1] = am21*x + am22*y + am23*z
pvb[0][2] = am32*y + am33*z
x = vb[0]
y = vb[1]
z = vb[2]
pvb[1][0] = x + am12*y + am13*z
pvb[1][1] = am21*x + am22*y + am23*z
pvb[1][2] = am32*y + am33*z
/* Return the status. */
return jstat
}
/*
Moon98 Moon geocentric position and velocity
Approximate geocentric position and velocity of the Moon.
Given:
date1 float64 TT date part A (Notes 1,4)
date2 float64 TT date part B (Notes 1,4)
Returned:
pv [2][3]float64 Moon p,v, GCRS (AU, AU/d, Note 5)
Notes:
1) The TT date date1+date2 is a Julian Date, apportioned in any
convenient way between the two arguments. For example,
JD(TT)=2450123.7 could be expressed in any of these ways, among
others:
date1 date2
2450123.7 0.0 (JD method)
2451545.0 -1421.3 (J2000 method)
2400000.5 50123.2 (MJD method)
2450123.5 0.2 (date & time method)
The JD method is the most natural and convenient to use in cases
where the loss of several decimal digits of resolution is
acceptable. The J2000 method is best matched to the way the
argument is handled internally and will deliver the optimum
resolution. The MJD method and the date & time methods are both
good compromises between resolution and convenience. The limited
accuracy of the present algorithm is such that any of the methods
is satisfactory.
2) This function is a full implementation of the algorithm
published by Meeus (see reference) except that the light-time
correction to the Moon's mean longitude has been omitted.
3) Comparisons with ELP/MPP02 over the interval 1950-2100 gave RMS
errors of 2.9 arcsec in geocentric direction, 6.1 km in position
and 36 mm/s in velocity. The worst case errors were 18.3 arcsec
in geocentric direction, 31.7 km in position and 172 mm/s in
velocity.
4) The original algorithm is expressed in terms of "dynamical time",
which can either be TDB or TT without any significant change in
accuracy. UT cannot be used without incurring significant errors
(30 arcsec in the present era) due to the Moon's 0.5 arcsec/sec
movement.
5) The result is with respect to the GCRS (the same as J2000.0 mean
equator and equinox to within 23 mas).
6) Velocity is obtained by a complete analytical differentiation
of the Meeus model.
7) The Meeus algorithm generates position and velocity in mean
ecliptic coordinates of date, which the present function then
rotates into GCRS. Because the ecliptic system is precessing,
there is a coupling between this spin (about 1.4 degrees per
century) and the Moon position that produces a small velocity
contribution. In the present function this effect is neglected
as it corresponds to a maximum difference of less than 3 mm/s and
increases the RMS error by only 0.4%.
References:
<NAME>., Astronomical Algorithms, 2nd edition, Willmann-Bell,
1998, p337.
<NAME>., <NAME>., <NAME>., <NAME>.,
Francou, G. & <NAME>., Astron.Astrophys., 1994, 282, 663
Defined in sofam.go:
DAU astronomical unit (m)
DJC days per Julian century
DJ00 reference epoch (J2000.0), Julian Date
DD2R degrees to radians
Called:
S2pv spherical coordinates to pv-vector
Pfw06 bias-precession F-W angles, IAU 2006
Ir initialize r-matrix to identity
Rz rotate around Z-axis
Rx rotate around X-axis
Rxpv product of r-matrix and pv-vector
*/
func Moon98(date1, date2 float64, pv *[2][3]float64) {
/*
Coefficients for fundamental arguments:
. Powers of time in Julian centuries
. Units are degrees.
*/
/* Moon's mean longitude (wrt mean equinox and ecliptic of date) */
const elp0 = 218.31665436 /* Simon et al. (1994). */
const elp1 = 481267.88123421
const elp2 = -0.0015786
const elp3 = 1.0 / 538841.0
const elp4 = -1.0 / 65194000.0
var elp, delp float64
/* Moon's mean elongation */
const d0 = 297.8501921
const d1 = 445267.1114034
const d2 = -0.0018819
const d3 = 1.0 / 545868.0
const d4 = 1.0 / 113065000.0
var d, dd float64
/* Sun's mean anomaly */
const em0 = 357.5291092
const em1 = 35999.0502909
const em2 = -0.0001536
const em3 = 1.0 / 24490000.0
const em4 = 0.0
var em, dem float64
/* Moon's mean anomaly */
const emp0 = 134.9633964
const emp1 = 477198.8675055
const emp2 = 0.0087414
const emp3 = 1.0 / 69699.0
const emp4 = -1.0 / 14712000.0
var emp, demp float64
/* Mean distance of the Moon from its ascending node */
const f0 = 93.2720950
const f1 = 483202.0175233
const f2 = -0.0036539
const f3 = 1.0 / 3526000.0
const f4 = 1.0 / 863310000.0
var f, df float64
/*
Other arguments
*/
/* Meeus A_1, due to Venus (deg) */
const a10 = 119.75
const a11 = 131.849
var a1, da1 float64
/* Meeus A_2, due to Jupiter (deg) */
const a20 = 53.09
const a21 = 479264.290
var a2, da2 float64
/* Meeus A_3, due to sidereal motion of the Moon in longitude (deg) */
const a30 = 313.45
const a31 = 481266.484
var a3, da3 float64
/* Coefficients for Meeus "additive terms" (deg) */
const al1 = 0.003958
const al2 = 0.001962
const al3 = 0.000318
const ab1 = -0.002235
const ab2 = 0.000382
const ab3 = 0.000175
const ab4 = 0.000175
const ab5 = 0.000127
const ab6 = -0.000115
/* Fixed term in distance (m) */
const r0 = 385000560.0
/* Coefficients for (dimensionless) E factor */
const (
e1 = -0.002516
e2 = -0.0000074
)
var e, de, esq, desq float64
/*
Coefficients for Moon longitude and distance series
*/
type termlr struct {
nd int /* multiple of D in argument */
nem int /* " " M " " */
nemp int /* " " M' " " */
nf int /* " " F " " */
coefl float64 /* coefficient of L sine argument (deg) */
coefr float64 /* coefficient of R cosine argument (m) */
}
tlr := []termlr{{0, 0, 1, 0, 6.288774, -20905355.0},
{2, 0, -1, 0, 1.274027, -3699111.0},
{2, 0, 0, 0, 0.658314, -2955968.0},
{0, 0, 2, 0, 0.213618, -569925.0},
{0, 1, 0, 0, -0.185116, 48888.0},
{0, 0, 0, 2, -0.114332, -3149.0},
{2, 0, -2, 0, 0.058793, 246158.0},
{2, -1, -1, 0, 0.057066, -152138.0},
{2, 0, 1, 0, 0.053322, -170733.0},
{2, -1, 0, 0, 0.045758, -204586.0},
{0, 1, -1, 0, -0.040923, -129620.0},
{1, 0, 0, 0, -0.034720, 108743.0},
{0, 1, 1, 0, -0.030383, 104755.0},
{2, 0, 0, -2, 0.015327, 10321.0},
{0, 0, 1, 2, -0.012528, 0.0},
{0, 0, 1, -2, 0.010980, 79661.0},
{4, 0, -1, 0, 0.010675, -34782.0},
{0, 0, 3, 0, 0.010034, -23210.0},
{4, 0, -2, 0, 0.008548, -21636.0},
{2, 1, -1, 0, -0.007888, 24208.0},
{2, 1, 0, 0, -0.006766, 30824.0},
{1, 0, -1, 0, -0.005163, -8379.0},
{1, 1, 0, 0, 0.004987, -16675.0},
{2, -1, 1, 0, 0.004036, -12831.0},
{2, 0, 2, 0, 0.003994, -10445.0},
{4, 0, 0, 0, 0.003861, -11650.0},
{2, 0, -3, 0, 0.003665, 14403.0},
{0, 1, -2, 0, -0.002689, -7003.0},
{2, 0, -1, 2, -0.002602, 0.0},
{2, -1, -2, 0, 0.002390, 10056.0},
{1, 0, 1, 0, -0.002348, 6322.0},
{2, -2, 0, 0, 0.002236, -9884.0},
{0, 1, 2, 0, -0.002120, 5751.0},
{0, 2, 0, 0, -0.002069, 0.0},
{2, -2, -1, 0, 0.002048, -4950.0},
{2, 0, 1, -2, -0.001773, 4130.0},
{2, 0, 0, 2, -0.001595, 0.0},
{4, -1, -1, 0, 0.001215, -3958.0},
{0, 0, 2, 2, -0.001110, 0.0},
{3, 0, -1, 0, -0.000892, 3258.0},
{2, 1, 1, 0, -0.000810, 2616.0},
{4, -1, -2, 0, 0.000759, -1897.0},
{0, 2, -1, 0, -0.000713, -2117.0},
{2, 2, -1, 0, -0.000700, 2354.0},
{2, 1, -2, 0, 0.000691, 0.0},
{2, -1, 0, -2, 0.000596, 0.0},
{4, 0, 1, 0, 0.000549, -1423.0},
{0, 0, 4, 0, 0.000537, -1117.0},
{4, -1, 0, 0, 0.000520, -1571.0},
{1, 0, -2, 0, -0.000487, -1739.0},
{2, 1, 0, -2, -0.000399, 0.0},
{0, 0, 2, -2, -0.000381, -4421.0},
{1, 1, 1, 0, 0.000351, 0.0},
{3, 0, -2, 0, -0.000340, 0.0},
{4, 0, -3, 0, 0.000330, 0.0},
{2, -1, 2, 0, 0.000327, 0.0},
{0, 2, 1, 0, -0.000323, 1165.0},
{1, 1, -1, 0, 0.000299, 0.0},
{2, 0, 3, 0, 0.000294, 0.0},
{2, 0, -1, -2, 0.000000, 8752.0}}
NLR := len(tlr)
/*
Coefficients for Moon latitude series
*/
type termb struct {
nd int /* multiple of D in argument */
nem int /* " " M " " */
nemp int /* " " M' " " */
nf int /* " " F " " */
coefb float64 /* coefficient of B sine argument (deg) */
}
tb := []termb{{0, 0, 0, 1, 5.128122},
{0, 0, 1, 1, 0.280602},
{0, 0, 1, -1, 0.277693},
{2, 0, 0, -1, 0.173237},
{2, 0, -1, 1, 0.055413},
{2, 0, -1, -1, 0.046271},
{2, 0, 0, 1, 0.032573},
{0, 0, 2, 1, 0.017198},
{2, 0, 1, -1, 0.009266},
{0, 0, 2, -1, 0.008822},
{2, -1, 0, -1, 0.008216},
{2, 0, -2, -1, 0.004324},
{2, 0, 1, 1, 0.004200},
{2, 1, 0, -1, -0.003359},
{2, -1, -1, 1, 0.002463},
{2, -1, 0, 1, 0.002211},
{2, -1, -1, -1, 0.002065},
{0, 1, -1, -1, -0.001870},
{4, 0, -1, -1, 0.001828},
{0, 1, 0, 1, -0.001794},
{0, 0, 0, 3, -0.001749},
{0, 1, -1, 1, -0.001565},
{1, 0, 0, 1, -0.001491},
{0, 1, 1, 1, -0.001475},
{0, 1, 1, -1, -0.001410},
{0, 1, 0, -1, -0.001344},
{1, 0, 0, -1, -0.001335},
{0, 0, 3, 1, 0.001107},
{4, 0, 0, -1, 0.001021},
{4, 0, -1, 1, 0.000833},
{0, 0, 1, -3, 0.000777},
{4, 0, -2, 1, 0.000671},
{2, 0, 0, -3, 0.000607},
{2, 0, 2, -1, 0.000596},
{2, -1, 1, -1, 0.000491},
{2, 0, -2, 1, -0.000451},
{0, 0, 3, -1, 0.000439},
{2, 0, 2, 1, 0.000422},
{2, 0, -3, -1, 0.000421},
{2, 1, -1, 1, -0.000366},
{2, 1, 0, 1, -0.000351},
{4, 0, 0, 1, 0.000331},
{2, -1, 1, 1, 0.000315},
{2, -2, 0, -1, 0.000302},
{0, 0, 1, 3, -0.000283},
{2, 1, 1, -1, -0.000229},
{1, 1, 0, -1, 0.000223},
{1, 1, 0, 1, 0.000223},
{0, 1, -2, -1, -0.000220},
{2, 1, -1, -1, -0.000220},
{1, 0, 1, 1, -0.000185},
{2, -1, -2, -1, 0.000181},
{0, 1, 2, 1, -0.000177},
{4, 0, -2, -1, 0.000176},
{4, -1, -1, -1, 0.000166},
{1, 0, 1, -1, -0.000164},
{4, 0, 1, -1, 0.000132},
{1, 0, -1, -1, -0.000119},
{4, -1, 0, -1, 0.000115},
{2, -2, 0, 1, 0.000107}}
NB := len(tb)
/* Miscellaneous */
var n, i int
var t, elpmf, delpmf, vel, vdel, vr, vdr, a1mf, da1mf, a1pf,
da1pf, dlpmp, slpmp, vb, vdb, v, dv, emn, empn, dn, fn, en,
den, arg, darg, farg, coeff, el, del, r, dr, b, db, gamb,
phib, psib, epsa float64
var rm [3][3]float64
/* ------------------------------------------------------------------ */
/* Centuries since J2000.0 */
t = ((date1 - DJ00) + date2) / DJC
/* --------------------- */
/* Fundamental arguments */
/* --------------------- */
/* Arguments (radians) and derivatives (radians per Julian century)
for the current date. */
/* Moon's mean longitude. */
elp = DD2R * fmod(elp0+
(elp1+
(elp2+
(elp3+
elp4*t)*t)*t)*t, 360.0)
delp = DD2R * (elp1 +
(elp2*2.0+
(elp3*3.0+
elp4*4.0*t)*t)*t)
/* Moon's mean elongation. */
d = DD2R * fmod(d0+
(d1+
(d2+
(d3+
d4*t)*t)*t)*t, 360.0)
dd = DD2R * (d1 +
(d2*2.0+
(d3*3.0+
d4*4.0*t)*t)*t)
/* Sun's mean anomaly. */
em = DD2R * fmod(em0+
(em1+
(em2+
(em3+
em4*t)*t)*t)*t, 360.0)
dem = DD2R * (em1 +
(em2*2.0+
(em3*3.0+
em4*4.0*t)*t)*t)
/* Moon's mean anomaly. */
emp = DD2R * fmod(emp0+
(emp1+
(emp2+
(emp3+
emp4*t)*t)*t)*t, 360.0)
demp = DD2R * (emp1 +
(emp2*2.0+
(emp3*3.0+
emp4*4.0*t)*t)*t)
/* Mean distance of the Moon from its ascending node. */
f = DD2R * fmod(f0+
(f1+
(f2+
(f3+
f4*t)*t)*t)*t, 360.0)
df = DD2R * (f1 +
(f2*2.0+
(f3*3.0+
f4*4.0*t)*t)*t)
/* Meeus further arguments. */
a1 = DD2R * (a10 + a11*t)
da1 = DD2R * al1
a2 = DD2R * (a20 + a21*t)
da2 = DD2R * a21
a3 = DD2R * (a30 + a31*t)
da3 = DD2R * a31
/* E-factor, and square. */
e = 1.0 + (e1+e2*t)*t
de = e1 + 2.0*e2*t
esq = e * e
desq = 2.0 * e * de
/* Use the Meeus additive terms (deg) to start off the summations. */
elpmf = elp - f
delpmf = delp - df
vel = al1*sin(a1) + al2*sin(elpmf) + al3*sin(a2)
vdel = al1*cos(a1)*da1 + al2*cos(elpmf)*delpmf + al3*cos(a2)*da2
vr = 0.0
vdr = 0.0
a1mf = a1 - f
da1mf = da1 - df
a1pf = a1 + f
da1pf = da1 + df
dlpmp = elp - emp
slpmp = elp + emp
vb = ab1*sin(elp) + ab2*sin(a3) + ab3*sin(a1mf) + ab4*sin(a1pf) + ab5*sin(dlpmp) + ab6*sin(slpmp)
vdb = ab1*cos(elp)*delp + ab2*cos(a3)*da3 + ab3*cos(a1mf)*da1mf + ab4*cos(a1pf)*da1pf + ab5*cos(dlpmp)*(delp-demp) + ab6*cos(slpmp)*(delp+demp)
/* ----------------- */
/* Series expansions */
/* ----------------- */
/* Longitude and distance plus derivatives. */
for n = NLR - 1; n >= 0; n-- {
dn = float64(tlr[n].nd)
//emn = float64 ( i = tlr[n].nem );
i = tlr[n].nem
emn = float64(tlr[n].nem)
empn = float64(tlr[n].nemp)
fn = float64(tlr[n].nf)
switch abs(i) {
case 1:
en = e
den = de
break
case 2:
en = esq
den = desq
break
default:
en = 1.0
den = 0.0
}
arg = dn*d + emn*em + empn*emp + fn*f
darg = dn*dd + emn*dem + empn*demp + fn*df
farg = sin(arg)
v = farg * en
dv = cos(arg)*darg*en + farg*den
coeff = tlr[n].coefl
vel += coeff * v
vdel += coeff * dv
farg = cos(arg)
v = farg * en
dv = -sin(arg)*darg*en + farg*den
coeff = tlr[n].coefr
vr += coeff * v
vdr += coeff * dv
}
el = elp + DD2R*vel
del = (delp + DD2R*vdel) / DJC
r = (vr + r0) / DAU
dr = vdr / DAU / DJC
/* Latitude plus derivative. */
for n = NB - 1; n >= 0; n-- {
dn = float64(tb[n].nd)
//emn = float64( i = tb[n].nem );
i = tb[n].nem
emn = float64(tb[n].nem)
empn = float64(tb[n].nemp)
fn = float64(tb[n].nf)
switch abs(i) {
case 1:
en = e
den = de
break
case 2:
en = esq
den = desq
break
default:
en = 1.0
den = 0.0
}
arg = dn*d + emn*em + empn*emp + fn*f
darg = dn*dd + emn*dem + empn*demp + fn*df
farg = sin(arg)
v = farg * en
dv = cos(arg)*darg*en + farg*den
coeff = tb[n].coefb
vb += coeff * v
vdb += coeff * dv
}
b = vb * DD2R
db = vdb * DD2R / DJC
/* ------------------------------ */
/* Transformation into final form */
/* ------------------------------ */
/* Longitude, latitude to x, y, z (AU). */
S2pv(el, b, r, del, db, dr, pv)
/* IAU 2006 Fukushima-Williams bias+precession angles. */
Pfw06(date1, date2, &gamb, &phib, &psib, &epsa)
/* Mean ecliptic coordinates to GCRS rotation matrix. */
Ir(&rm)
Rz(psib, &rm)
Rx(-phib, &rm)
Rz(-gamb, &rm)
/* Rotate the Moon position and velocity into GCRS (Note 6). */
Rxpv(rm, *pv, pv)
/* Finished. */
}
/*
Plan94 Major-planet position and velocity
Approximate heliocentric position and velocity of a nominated major
planet: Mercury, Venus, EMB, Mars, Jupiter, Saturn, Uranus or
Neptune (but not the Earth itself).
Given:
date1 float64 TDB date part A (Note 1)
date2 float64 TDB date part B (Note 1)
np int planet (1=Mercury, 2=Venus, 3=EMB, 4=Mars,
5=Jupiter, 6=Saturn, 7=Uranus, 8=Neptune)
Returned (argument):
pv [2][3]float64 planet p,v (heliocentric, J2000.0, au,au/d)
Returned (function value):
int status: -1 = illegal NP (outside 1-8)
0 = OK
+1 = warning: year outside 1000-3000
+2 = warning: failed to converge
Notes:
1) The date date1+date2 is in the TDB time scale (in practice TT can
be used) and is a Julian Date, apportioned in any convenient way
between the two arguments. For example, JD(TDB)=2450123.7 could
be expressed in any of these ways, among others:
date1 date2
2450123.7 0.0 (JD method)
2451545.0 -1421.3 (J2000 method)
2400000.5 50123.2 (MJD method)
2450123.5 0.2 (date & time method)
The JD method is the most natural and convenient to use in cases
where the loss of several decimal digits of resolution is
acceptable. The J2000 method is best matched to the way the
argument is handled internally and will deliver the optimum
resolution. The MJD method and the date & time methods are both
good compromises between resolution and convenience. The limited
accuracy of the present algorithm is such that any of the methods
is satisfactory.
2) If an np value outside the range 1-8 is supplied, an error status
(function value -1) is returned and the pv vector set to zeroes.
3) For np=3 the result is for the Earth-Moon Barycenter. To obtain
the heliocentric position and velocity of the Earth, use instead
the SOFA function iauEpv00.
4) On successful return, the array pv contains the following:
pv[0][0] x }
pv[0][1] y } heliocentric position, au
pv[0][2] z }
pv[1][0] xdot }
pv[1][1] ydot } heliocentric velocity, au/d
pv[1][2] zdot }
The reference frame is equatorial and is with respect to the
mean equator and equinox of epoch J2000.0.
5) The algorithm is due to <NAME>, <NAME>, <NAME>,
<NAME>, <NAME> and <NAME> (Bureau des
Longitudes, Paris, France). From comparisons with JPL
ephemeris DE102, they quote the following maximum errors
over the interval 1800-2050:
L (arcsec) B (arcsec) R (km)
Mercury 4 1 300
Venus 5 1 800
EMB 6 1 1000
Mars 17 1 7700
Jupiter 71 5 76000
Saturn 81 13 267000
Uranus 86 7 712000
Neptune 11 1 253000
Over the interval 1000-3000, they report that the accuracy is no
worse than 1.5 times that over 1800-2050. Outside 1000-3000 the
accuracy declines.
Comparisons of the present function with the JPL DE200 ephemeris
give the following RMS errors over the interval 1960-2025:
position (km) velocity (m/s)
Mercury 334 0.437
Venus 1060 0.855
EMB 2010 0.815
Mars 7690 1.98
Jupiter 71700 7.70
Saturn 199000 19.4
Uranus 564000 16.4
Neptune 158000 14.4
Comparisons against DE200 over the interval 1800-2100 gave the
following maximum absolute differences. (The results using
DE406 were essentially the same.)
L (arcsec) B (arcsec) R (km) Rdot (m/s)
Mercury 7 1 500 0.7
Venus 7 1 1100 0.9
EMB 9 1 1300 1.0
Mars 26 1 9000 2.5
Jupiter 78 6 82000 8.2
Saturn 87 14 263000 24.6
Uranus 86 7 661000 27.4
Neptune 11 2 248000 21.4
6) The present SOFA re-implementation of the original Simon et al.
Fortran code differs from the original in the following respects:
* C instead of Fortran.
* The date is supplied in two parts.
* The result is returned only in equatorial Cartesian form;
the ecliptic longitude, latitude and radius vector are not
returned.
* The result is in the J2000.0 equatorial frame, not ecliptic.
* More is done in-line: there are fewer calls to subroutines.
* Different error/warning status values are used.
* A different Kepler's-equation-solver is used (avoiding
use of double precision complex).
* Polynomials in t are nested to minimize rounding errors.
* Explicit double constants are used to avoid mixed-mode
expressions.
None of the above changes affects the result significantly.
7) The returned status indicates the most serious condition
encountered during execution of the function. Illegal np is
considered the most serious, overriding failure to converge,
which in turn takes precedence over the remote date warning.
Called:
Anpm normalize angle into range +/- pi
Reference: <NAME>, <NAME>., <NAME>.,
<NAME>., <NAME>., and <NAME>.,
Astron.Astrophys., 282, 663 (1994).
*/
func Plan94(date1, date2 float64, np int, pv *[2][3]float64) int {
/* Gaussian constant */
const GK = 0.017202098950
/* Sin and cos of J2000.0 mean obliquity (IAU 1976) */
const SINEPS = 0.3977771559319137
const COSEPS = 0.9174820620691818
/* Maximum number of iterations allowed to solve Kepler's equation */
const KMAX = 10
var jstat, i, k int
var t, da, dl, de, dp, di, dom, dmu, arga, argl, am,
ae, dae, ae2, at, r, v, si2, xq, xp, tl, xsw,
xcw, xm2, xf, ci2, xms, xmc, xpxq2, x, y, z float64
/* Planetary inverse masses */
amas := []float64{6023600.0, /* Mercury */
408523.5, /* Venus */
328900.5, /* EMB */
3098710.0, /* Mars */
1047.355, /* Jupiter */
3498.5, /* Saturn */
22869.0, /* Uranus */
19314.0} /* Neptune */
/*
Tables giving the mean Keplerian elements, limited to t^2 terms:
a semi-major axis (au)
dlm mean longitude (degree and arcsecond)
e eccentricity
pi longitude of the perihelion (degree and arcsecond)
dinc inclination (degree and arcsecond)
omega longitude of the ascending node (degree and arcsecond)
*/
a := [][3]float64{
{0.3870983098, 0.0, 0.0}, /* Mercury */
{0.7233298200, 0.0, 0.0}, /* Venus */
{1.0000010178, 0.0, 0.0}, /* EMB */
{1.5236793419, 3e-10, 0.0}, /* Mars */
{5.2026032092, 19132e-10, -39e-10}, /* Jupiter */
{9.5549091915, -0.0000213896, 444e-10}, /* Saturn */
{19.2184460618, -3716e-10, 979e-10}, /* Uranus */
{30.1103868694, -16635e-10, 686e-10}, /* Neptune */
}
dlm := [][3]float64{
{252.25090552, 5381016286.88982, -1.92789},
{181.97980085, 2106641364.33548, 0.59381},
{100.46645683, 1295977422.83429, -2.04411},
{355.43299958, 689050774.93988, 0.94264},
{34.35151874, 109256603.77991, -30.60378},
{50.07744430, 43996098.55732, 75.61614},
{314.05500511, 15424811.93933, -1.75083},
{304.34866548, 7865503.20744, 0.21103},
}
e := [][3]float64{
{0.2056317526, 0.0002040653, -28349e-10},
{0.0067719164, -0.0004776521, 98127e-10},
{0.0167086342, -0.0004203654, -0.0000126734},
{0.0934006477, 0.0009048438, -80641e-10},
{0.0484979255, 0.0016322542, -0.0000471366},
{0.0555481426, -0.0034664062, -0.0000643639},
{0.0463812221, -0.0002729293, 0.0000078913},
{0.0094557470, 0.0000603263, 0.0},
}
pi := [][3]float64{
{77.45611904, 5719.11590, -4.83016},
{131.56370300, 175.48640, -498.48184},
{102.93734808, 11612.35290, 53.27577},
{336.06023395, 15980.45908, -62.32800},
{14.33120687, 7758.75163, 259.95938},
{93.05723748, 20395.49439, 190.25952},
{173.00529106, 3215.56238, -34.09288},
{48.12027554, 1050.71912, 27.39717},
}
dinc := [][3]float64{
{7.00498625, -214.25629, 0.28977},
{3.39466189, -30.84437, -11.67836},
{0.0, 469.97289, -3.35053},
{1.84972648, -293.31722, -8.11830},
{1.30326698, -71.55890, 11.95297},
{2.48887878, 91.85195, -17.66225},
{0.77319689, -60.72723, 1.25759},
{1.76995259, 8.12333, 0.08135},
}
omega := [][3]float64{
{48.33089304, -4515.21727, -31.79892},
{76.67992019, -10008.48154, -51.32614},
{174.87317577, -8679.27034, 15.34191},
{49.55809321, -10620.90088, -230.57416},
{100.46440702, 6362.03561, 326.52178},
{113.66550252, -9240.19942, -66.23743},
{74.00595701, 2669.15033, 145.93964},
{131.78405702, -221.94322, -0.78728},
}
/* Tables for trigonometric terms to be added to the mean elements of */
/* the semi-major axes */
kp := [][9]float64{
{69613, 75645, 88306, 59899, 15746, 71087, 142173, 3086, 0},
{21863, 32794, 26934, 10931, 26250, 43725, 53867, 28939, 0},
{16002, 21863, 32004, 10931, 14529, 16368, 15318, 32794, 0},
{6345, 7818, 15636, 7077, 8184, 14163, 1107, 4872, 0},
{1760, 1454, 1167, 880, 287, 2640, 19, 2047, 1454},
{574, 0, 880, 287, 19, 1760, 1167, 306, 574},
{204, 0, 177, 1265, 4, 385, 200, 208, 204},
{0, 102, 106, 4, 98, 1367, 487, 204, 0},
}
ca := [][9]float64{
{4, -13, 11, -9, -9, -3, -1, 4, 0},
{-156, 59, -42, 6, 19, -20, -10, -12, 0},
{64, -152, 62, -8, 32, -41, 19, -11, 0},
{124, 621, -145, 208, 54, -57, 30, 15, 0},
{-23437, -2634, 6601, 6259, -1507, -1821, 2620, -2115, -1489},
{62911, -119919, 79336, 17814, -24241, 12068, 8306, -4893, 8902},
{389061, -262125, -44088, 8387, -22976, -2093, -615, -9720, 6633},
{-412235, -157046, -31430, 37817, -9740, -13, -7449, 9644, 0},
}
sa := [][9]float64{
{-29, -1, 9, 6, -6, 5, 4, 0, 0},
{-48, -125, -26, -37, 18, -13, -20, -2, 0},
{-150, -46, 68, 54, 14, 24, -28, 22, 0},
{-621, 532, -694, -20, 192, -94, 71, -73, 0},
{-14614, -19828, -5869, 1881, -4372, -2255, 782, 930, 913},
{139737, 0, 24667, 51123, -5102, 7429, -4095, -1976, -9566},
{-138081, 0, 37205, -49039, -41901, -33872, -27037, -12474, 18797},
{0, 28492, 133236, 69654, 52322, -49577, -26430, -3593, 0},
}
/* Tables giving the trigonometric terms to be added to the mean */
/* elements of the mean longitudes */
kq := [][10]float64{
{3086, 15746, 69613, 59899, 75645, 88306, 12661, 2658, 0, 0},
{21863, 32794, 10931, 73, 4387, 26934, 1473, 2157, 0, 0},
{10, 16002, 21863, 10931, 1473, 32004, 4387, 73, 0, 0},
{10, 6345, 7818, 1107, 15636, 7077, 8184, 532, 10, 0},
{19, 1760, 1454, 287, 1167, 880, 574, 2640, 19, 1454},
{19, 574, 287, 306, 1760, 12, 31, 38, 19, 574},
{4, 204, 177, 8, 31, 200, 1265, 102, 4, 204},
{4, 102, 106, 8, 98, 1367, 487, 204, 4, 102},
}
cl := [][10]float64{
{21, -95, -157, 41, -5, 42, 23, 30, 0, 0},
{-160, -313, -235, 60, -74, -76, -27, 34, 0, 0},
{-325, -322, -79, 232, -52, 97, 55, -41, 0, 0},
{2268, -979, 802, 602, -668, -33, 345, 201, -55, 0},
{7610, -4997, -7689, -5841, -2617, 1115, -748, -607, 6074, 354},
{-18549, 30125, 20012, -730, 824, 23, 1289, -352, -14767, -2062},
{-135245, -14594, 4197, -4030, -5630, -2898, 2540, -306, 2939, 1986},
{89948, 2103, 8963, 2695, 3682, 1648, 866, -154, -1963, -283},
}
sl := [][10]float64{
{-342, 136, -23, 62, 66, -52, -33, 17, 0, 0},
{524, -149, -35, 117, 151, 122, -71, -62, 0, 0},
{-105, -137, 258, 35, -116, -88, -112, -80, 0, 0},
{854, -205, -936, -240, 140, -341, -97, -232, 536, 0},
{-56980, 8016, 1012, 1448, -3024, -3710, 318, 503, 3767, 577},
{138606, -13478, -4964, 1441, -1319, -1482, 427, 1236, -9167, -1918},
{71234, -41116, 5334, -4935, -1848, 66, 434, -1748, 3780, -701},
{-47645, 11647, 2166, 3194, 679, 0, -244, -419, -2531, 48},
}
/* ------------------------------------------------------------------ */
/* Validate the planet number. */
if (np < 1) || (np > 8) {
jstat = -1
/* Reset the result in case of failure. */
for k = 0; k < 2; k++ {
for i = 0; i < 3; i++ {
pv[k][i] = 0.0
}
}
} else {
/* Decrement the planet number to start at zero. */
np--
/* Time: Julian millennia since J2000.0. */
t = ((date1 - DJ00) + date2) / DJM
/* OK status unless remote date. */
// jstat = fabs(t) <= 1.0 ? 0 : 1;
if fabs(t) <= 1.0 {
jstat = 0
} else {
jstat = 1
}
/* Compute the mean elements. */
da = a[np][0] +
(a[np][1]+
a[np][2]*t)*t
dl = (3600.0*dlm[np][0] +
(dlm[np][1]+
dlm[np][2]*t)*t) * DAS2R
de = e[np][0] +
(e[np][1]+
e[np][2]*t)*t
dp = Anpm((3600.0*pi[np][0] +
(pi[np][1]+
pi[np][2]*t)*t) * DAS2R)
di = (3600.0*dinc[np][0] +
(dinc[np][1]+
dinc[np][2]*t)*t) * DAS2R
dom = Anpm((3600.0*omega[np][0] +
(omega[np][1]+
omega[np][2]*t)*t) * DAS2R)
/* Apply the trigonometric terms. */
dmu = 0.35953620 * t
for k = 0; k < 8; k++ {
arga = kp[np][k] * dmu
argl = kq[np][k] * dmu
da += (ca[np][k]*cos(arga) +
sa[np][k]*sin(arga)) * 1e-7
dl += (cl[np][k]*cos(argl) +
sl[np][k]*sin(argl)) * 1e-7
}
arga = kp[np][8] * dmu
da += t * (ca[np][8]*cos(arga) +
sa[np][8]*sin(arga)) * 1e-7
for k = 8; k < 10; k++ {
argl = kq[np][k] * dmu
dl += t * (cl[np][k]*cos(argl) +
sl[np][k]*sin(argl)) * 1e-7
}
dl = fmod(dl, D2PI)
/* Iterative soln. of Kepler's equation to get eccentric anomaly. */
am = dl - dp
ae = am + de*sin(am)
k = 0
dae = 1.0
for k < KMAX && fabs(dae) > 1e-12 {
dae = (am - ae + de*sin(ae)) / (1.0 - de*cos(ae))
ae += dae
k++
if k == KMAX-1 {
jstat = 2
}
}
/* True anomaly. */
ae2 = ae / 2.0
at = 2.0 * atan2(sqrt((1.0+de)/(1.0-de))*sin(ae2),
cos(ae2))
/* Distance (au) and speed (radians per day). */
r = da * (1.0 - de*cos(ae))
v = GK * sqrt((1.0+1.0/amas[np])/(da*da*da))
si2 = sin(di / 2.0)
xq = si2 * cos(dom)
xp = si2 * sin(dom)
tl = at + dp
xsw = sin(tl)
xcw = cos(tl)
xm2 = 2.0 * (xp*xcw - xq*xsw)
xf = da / sqrt(1-de*de)
ci2 = cos(di / 2.0)
xms = (de*sin(dp) + xsw) * xf
xmc = (de*cos(dp) + xcw) * xf
xpxq2 = 2 * xp * xq
/* Position (J2000.0 ecliptic x,y,z in au). */
x = r * (xcw - xm2*xp)
y = r * (xsw + xm2*xq)
z = r * (-xm2 * ci2)
/* Rotate to equatorial. */
pv[0][0] = x
pv[0][1] = y*COSEPS - z*SINEPS
pv[0][2] = y*SINEPS + z*COSEPS
/* Velocity (J2000.0 ecliptic xdot,ydot,zdot in au/d). */
x = v * ((-1.0+2.0*xp*xp)*xms + xpxq2*xmc)
y = v * ((1.0-2.0*xq*xq)*xmc - xpxq2*xms)
z = v * (2.0 * ci2 * (xp*xms + xq*xmc))
/* Rotate to equatorial. */
pv[1][0] = x
pv[1][1] = y*COSEPS - z*SINEPS
pv[1][2] = y*SINEPS + z*COSEPS
}
/* Return the status. */
return jstat
} | ephem.go | 0.765681 | 0.646899 | ephem.go | starcoder |
package pkg
import "fmt"
type Fraction = float64
type Weight = float64
type Probability = float64
// Distribution describes a distribution of values.
type Distribution interface {
GetValue() DistributionValues
IsSingleValue() bool
}
// DistributionValues describe a set of fraction over weight.
// For example, DistributionValues{0.25: 1, 0.8: 2} means 25% reads one third of the time and
// 80% reads two thirds of the time.
type DistributionValues = map[Fraction]Weight
// QuorumDistribution describes a list of DistributionValues.
type QuorumDistribution struct {
values DistributionValues
}
// GetValue gets the list of DistributionValues.
func (qd QuorumDistribution) GetValue() DistributionValues {
return qd.values
}
// IsSingleValue checks if the list of DistributionValues has only 1 element.
func (qd QuorumDistribution) IsSingleValue() bool {
return len(qd.values) == 1
}
// canonicalizeReadsWrites canonicalizes the read Distribution and the write Distribution.
func canonicalizeReadsWrites(readFraction *Distribution, writeFraction *Distribution) (map[Fraction]Probability, error) {
if *readFraction == nil && *writeFraction == nil {
return nil, fmt.Errorf("either readFraction or writeFraction must be given")
}
if *readFraction != nil && *writeFraction != nil {
return nil, fmt.Errorf("only one of read_fraction or write_fraction can be given")
}
if *readFraction != nil {
return canonicalize(readFraction)
}
if *writeFraction != nil {
cDist, err := canonicalize(writeFraction)
if err != nil {
return nil, err
}
r := make(map[Fraction]Probability)
for f, p := range cDist {
r[1-f] = p
}
return r, nil
}
return nil, fmt.Errorf("writeFraction not specified")
}
//canonicalize checks and proceeds by converting the distribution in a standard distribution.
// - no negative weights.
// - no zero weight.
func canonicalize(d *Distribution) (map[Fraction]Probability, error) {
if d == nil || len((*d).GetValue()) == 0 {
return nil, fmt.Errorf("distribution cannot be nil")
}
var totalWeight Weight = 0
for _, w := range (*d).GetValue() {
if w < 0 {
return nil, fmt.Errorf("distribution cannot have negative weights")
}
totalWeight += w
}
if totalWeight == 0 {
return nil, fmt.Errorf("distribution cannot have zero weight")
}
result := make(map[Fraction]Probability)
for f, w := range (*d).GetValue() {
if w > 0 {
result[f] = w / totalWeight
}
}
return result, nil
} | pkg/distribution.go | 0.820757 | 0.444324 | distribution.go | starcoder |
package internal
import (
"sort"
)
// A kd-Tree with k=3 dimensions and payload.
// Inspired by https://en.wikipedia.org/wiki/K-d_tree
// Pointerless idea came up by itself ;)
type KDTree3P []Point3DPayload
// Builds a pointerless k-dimensional tree with k=3 from the points by resorting the array.
// Function for mod 3 == 0 depths which pivots on the X dimension.
func (points KDTree3P) Make() {
sort.Slice(points, func(i, j int) bool {
return points[i].X <= points[j].X
} )
l:=len(points)
if l>1 { // descend left
points[ :l/2].makeY()
if l>2 { // descend right
points[l/2+1: ].makeY()
}
}
}
// Builds a pointerless k-dimensional tree with k=3 from the points by resorting the array.
// Helper function for mod 3 == 1 depths which pivots on the Y dimension.
func (points KDTree3P) makeY() {
sort.Slice(points, func(i, j int) bool {
return points[i].Y <= points[j].Y
} )
l:=len(points)
if l>1 { // descend left
points[ :l/2].makeZ()
if l>2 { // descend right
points[l/2+1: ].makeZ()
}
}
}
// Builds a pointerless k-dimensional tree with k=3 from the points by resorting the array.
// Helper function for mod 3 == 2 depths which pivots on the Z dimension.
func (points KDTree3P) makeZ() {
sort.Slice(points, func(i, j int) bool {
return points[i].Z <= points[j].Z
} )
l:=len(points)
if l>1 { // descend left
points[ :l/2].Make()
if l>2 { // descend right
points[l/2+1: ].Make()
}
}
}
// Performs a nearest neighbor search on the points, which must have been previously transformed
// to a k-dimensional tree using NewKDTree3P()
func (kdt KDTree3P) NearestNeighbor(p Point3D) (closestPt Point3DPayload, closestDsq float32) {
l:=len(kdt)
midpoint:=kdt[l/2]
closestPt,closestDsq=midpoint, Dist3DSquared(p, midpoint.Point3D)
if p.X <= midpoint.X {
if l>1 { // descend left
pt, dsq := kdt[ :l/2].nearestNeighborY(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
if l>2 { // descend right
distToPlane:=p.X-midpoint.X
if distToPlane*distToPlane<=closestDsq {
pt, dsq := kdt[l/2+1:].nearestNeighborY(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
}
}
} else {
if l>2 { // descend right
pt, dsq := kdt[l/2+1:].nearestNeighborY(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
if l>1 { // descend left
distToPlane:=p.X-midpoint.X
if distToPlane*distToPlane<=closestDsq {
pt, dsq := kdt[ :l/2].nearestNeighborY(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
}
}
return closestPt, closestDsq
}
func (kdt KDTree3P) nearestNeighborY(p Point3D) (closestPt Point3DPayload, closestDsq float32) {
l:=len(kdt)
midpoint:=kdt[l/2]
closestPt,closestDsq=midpoint, Dist3DSquared(p, midpoint.Point3D)
if p.Y <= midpoint.Y {
if l>1 { // descend left
pt, dsq := kdt[ :l/2].nearestNeighborZ(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
if l>2 { // descend right
distToPlane:=p.Y-midpoint.Y
if distToPlane*distToPlane<=closestDsq {
pt, dsq := kdt[l/2+1:].nearestNeighborZ(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
}
}
} else {
if l>2 { // descend right
pt, dsq := kdt[l/2+1:].nearestNeighborZ(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
if l>1 { // descend left
distToPlane:=p.Y-midpoint.Y
if distToPlane*distToPlane<=closestDsq {
pt, dsq := kdt[ :l/2].nearestNeighborZ(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
}
}
return closestPt, closestDsq
}
func (kdt KDTree3P) nearestNeighborZ(p Point3D) (closestPt Point3DPayload, closestDsq float32) {
l:=len(kdt)
midpoint:=kdt[l/2]
closestPt,closestDsq=midpoint, Dist3DSquared(p, midpoint.Point3D)
if p.Z <= midpoint.Z {
if l>1 { // descend left
pt, dsq := kdt[ :l/2].NearestNeighbor(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
if l>2 { // descend right
distToPlane:=p.Z-midpoint.Z
if distToPlane*distToPlane<=closestDsq {
pt, dsq := kdt[l/2+1:].NearestNeighbor(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
}
}
} else {
if l>2 { // descend right
pt, dsq := kdt[l/2+1:].NearestNeighbor(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
if l>1 { // descend left
distToPlane:=p.Z-midpoint.Z
if distToPlane*distToPlane<=closestDsq {
pt, dsq := kdt[ :l/2].NearestNeighbor(p)
if dsq<closestDsq { closestPt, closestDsq = pt, dsq }
}
}
}
return closestPt, closestDsq
} | internal/kdtree3p.go | 0.622115 | 0.493775 | kdtree3p.go | starcoder |
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"encoding/asn1"
"errors"
"fmt"
"log"
"math/big"
"github.com/miekg/pkcs11"
)
var stringToCurve = map[string]*elliptic.CurveParams{
elliptic.P224().Params().Name: elliptic.P224().Params(),
elliptic.P256().Params().Name: elliptic.P256().Params(),
elliptic.P384().Params().Name: elliptic.P384().Params(),
elliptic.P521().Params().Name: elliptic.P521().Params(),
}
// curveToOIDDER maps the name of the curves to their DER encoded OIDs
var curveToOIDDER = map[string][]byte{
elliptic.P224().Params().Name: []byte{6, 5, 43, 129, 4, 0, 33},
elliptic.P256().Params().Name: []byte{6, 8, 42, 134, 72, 206, 61, 3, 1, 7},
elliptic.P384().Params().Name: []byte{6, 5, 43, 129, 4, 0, 34},
elliptic.P521().Params().Name: []byte{6, 5, 43, 129, 4, 0, 35},
}
// oidDERToCurve maps the hex of the DER encoding of the various curve OIDs to
// the relevant curve parameters
var oidDERToCurve = map[string]*elliptic.CurveParams{
"06052B81040021": elliptic.P224().Params(),
"06082A8648CE3D030107": elliptic.P256().Params(),
"06052B81040022": elliptic.P384().Params(),
"06052B81040023": elliptic.P521().Params(),
}
var curveToHash = map[*elliptic.CurveParams]crypto.Hash{
elliptic.P224().Params(): crypto.SHA256,
elliptic.P256().Params(): crypto.SHA256,
elliptic.P384().Params(): crypto.SHA384,
elliptic.P521().Params(): crypto.SHA512,
}
var hashToString = map[crypto.Hash]string{
crypto.SHA256: "SHA-256",
crypto.SHA384: "SHA-384",
crypto.SHA512: "SHA-512",
}
// ecArgs constructs the private and public key template attributes sent to the
// device and specifies which mechanism should be used. curve determines which
// type of key should be generated. compatMode is used to determine which
// mechanism and attribute types should be used, for devices that implement
// a pre-2.11 version of the PKCS#11 specification compatMode should be true.
func ecArgs(label string, curve *elliptic.CurveParams, compatMode bool) generateArgs {
encodedCurve := curveToOIDDER[curve.Name]
log.Printf("\tEncoded curve parameters for %s: %X\n", curve.Params().Name, encodedCurve)
var genMech, paramType uint
if compatMode {
genMech = pkcs11.CKM_ECDSA_KEY_PAIR_GEN
paramType = pkcs11.CKA_ECDSA_PARAMS
} else {
genMech = pkcs11.CKM_EC_KEY_PAIR_GEN
paramType = pkcs11.CKA_EC_PARAMS
}
return generateArgs{
mechanism: []*pkcs11.Mechanism{
pkcs11.NewMechanism(genMech, nil),
},
publicAttrs: []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true),
pkcs11.NewAttribute(paramType, encodedCurve),
},
privateAttrs: []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_LABEL, label),
pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true),
// Prevent attributes being retrieved
pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true),
// Prevent the key being extracted from the device
pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false),
// Allow the key to sign data
pkcs11.NewAttribute(pkcs11.CKA_SIGN, true),
},
}
}
// ecPub extracts the generated public key, specified by the provided object
// handle, and constructs an ecdsa.PublicKey. It also checks that the key is of
// the correct curve type. For devices that implement a pre-2.11 version of the
// PKCS#11 specification compatMode should be true.
func ecPub(ctx PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, expectedCurve *elliptic.CurveParams, compatMode bool) (*ecdsa.PublicKey, error) {
var paramType uint
if compatMode {
paramType = pkcs11.CKA_ECDSA_PARAMS
} else {
paramType = pkcs11.CKA_EC_PARAMS
}
// Retrieve the curve and public point for the generated public key
attrs, err := ctx.GetAttributeValue(session, object, []*pkcs11.Attribute{
pkcs11.NewAttribute(paramType, nil),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, nil),
})
if err != nil {
return nil, fmt.Errorf("Failed to retrieve key attributes: %s", err)
}
pubKey := &ecdsa.PublicKey{}
gotCurve, gotPoint := false, false
for _, a := range attrs {
switch a.Type {
case paramType:
rCurve, present := oidDERToCurve[fmt.Sprintf("%X", a.Value)]
if !present {
return nil, errors.New("Unknown curve OID value returned")
}
pubKey.Curve = rCurve
if pubKey.Curve != expectedCurve {
return nil, errors.New("Returned EC parameters doesn't match expected curve")
}
gotCurve = true
case pkcs11.CKA_EC_POINT:
x, y := elliptic.Unmarshal(expectedCurve, a.Value)
if x == nil {
// http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/os/pkcs11-curr-v2.40-os.html#_ftn1
// PKCS#11 v2.20 specified that the CKA_EC_POINT was to be stored in a DER-encoded
// OCTET STRING.
var point asn1.RawValue
_, err = asn1.Unmarshal(a.Value, &point)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal returned CKA_EC_POINT: %s", err)
}
if len(point.Bytes) == 0 {
return nil, errors.New("Invalid CKA_EC_POINT value returned, OCTET string is empty")
}
x, y = elliptic.Unmarshal(expectedCurve, point.Bytes)
if x == nil {
fmt.Println(point.Bytes)
return nil, errors.New("Invalid CKA_EC_POINT value returned, point is malformed")
}
}
pubKey.X, pubKey.Y = x, y
gotPoint = true
log.Printf("\tX: %X\n", pubKey.X.Bytes())
log.Printf("\tY: %X\n", pubKey.Y.Bytes())
}
}
if !gotPoint || !gotCurve {
return nil, errors.New("Couldn't retrieve EC point and EC parameters")
}
return pubKey, nil
}
// ecVerify verifies that the extracted public key corresponds with the generated
// private key on the device, specified by the provided object handle, by signing
// a nonce generated on the device and verifying the returned signature using the
// public key.
func ecVerify(ctx PKCtx, session pkcs11.SessionHandle, object pkcs11.ObjectHandle, pub *ecdsa.PublicKey) error {
err := ctx.SignInit(session, []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_ECDSA, nil)}, object)
if err != nil {
return fmt.Errorf("failed to initialize signing operation: %s", err)
}
nonce, err := getRandomBytes(ctx, session)
if err != nil {
return fmt.Errorf("failed to construct nonce: %s", err)
}
log.Printf("\tConstructed nonce: %d (%X)\n", big.NewInt(0).SetBytes(nonce), nonce)
hashFunc := curveToHash[pub.Curve.Params()].New()
hashFunc.Write(nonce)
hash := hashFunc.Sum(nil)
log.Printf("\tMessage %s hash: %X\n", hashToString[curveToHash[pub.Curve.Params()]], hash)
signature, err := ctx.Sign(session, hash)
if err != nil {
return fmt.Errorf("failed to sign data: %s", err)
}
log.Printf("\tMessage signature: %X\n", signature)
r := big.NewInt(0).SetBytes(signature[:len(signature)/2])
s := big.NewInt(0).SetBytes(signature[len(signature)/2:])
if !ecdsa.Verify(pub, hash[:], r, s) {
return errors.New("failed to verify ECDSA signature over test data")
}
log.Println("\tSignature verified")
return nil
}
// ecGenerate is used to generate and verify a ECDSA key pair of the type
// specified by curveStr and with the provided label. For devices that implement
// a pre-2.11 version of the PKCS#11 specification compatMode should be true.
// It returns the public part of the generated key pair as a ecdsa.PublicKey.
func ecGenerate(ctx PKCtx, session pkcs11.SessionHandle, label, curveStr string, compatMode bool) (*ecdsa.PublicKey, error) {
curve, present := stringToCurve[curveStr]
if !present {
return nil, fmt.Errorf("curve %q not supported", curveStr)
}
log.Printf("Generating ECDSA key with curve %s\n", curveStr)
args := ecArgs(label, curve, compatMode)
pub, priv, err := ctx.GenerateKeyPair(session, args.mechanism, args.publicAttrs, args.privateAttrs)
if err != nil {
return nil, err
}
log.Println("Key generated")
log.Println("Extracting public key")
pk, err := ecPub(ctx, session, pub, curve, compatMode)
if err != nil {
return nil, err
}
log.Println("Extracted public key")
log.Println("Verifying public key")
err = ecVerify(ctx, session, priv, pk)
if err != nil {
return nil, err
}
log.Println("Key verified")
return pk, nil
} | scripts/letsencrypt/boulder/cmd/gen-key/ecdsa.go | 0.554109 | 0.450239 | ecdsa.go | starcoder |
package la
import "github.com/cpmech/gosl/chk"
// --------------------------------------------------------------------------------------------------
// matrix-matrix ------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
// SpMatMatTrMul computes the multiplication of sparse matrix with itself transposed:
// b := α * a * aᵀ b_iq = α * a_ij * a_qj
/// Note: b is symmetric
func SpMatMatTrMul(b *Matrix, α float64, a *CCMatrix) {
b.Fill(0)
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
for l := a.p[j]; l < a.p[j+1]; l++ {
b.Add(a.i[k], a.i[l], α*a.x[k]*a.x[l])
}
}
}
}
// --------------------------------------------------------------------------------------------------
// matrix-vector ------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
// SpMatVecMul returns the (sparse) matrix-vector multiplication (scaled):
// v := α * a * u => vi = α * aij * uj
// NOTE: dense vector v will be first initialised with zeros
func SpMatVecMul(v Vector, α float64, a *CCMatrix, u Vector) {
v.Fill(0)
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[a.i[k]] += α * a.x[k] * u[j]
}
}
}
// SpMatVecMulAdd returns the (sparse) matrix-vector multiplication with addition (scaled):
// v += α * a * u => vi += α * aij * uj
func SpMatVecMulAdd(v Vector, α float64, a *CCMatrix, u Vector) {
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[a.i[k]] += α * a.x[k] * u[j]
}
}
}
// SpMatVecMulAddX returns the (sparse) matrix-vector multiplication with addition (scaled/extended):
// v += a * (α*u + β*w) => vi += aij * (α*uj + β*wj)
func SpMatVecMulAddX(v Vector, a *CCMatrix, α float64, u Vector, β float64, w Vector) {
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[a.i[k]] += a.x[k] * (α*u[j] + β*w[j])
}
}
}
// SpMatTrVecMul returns the (sparse) matrix-vector multiplication with "a" transposed (scaled):
// v := α * transp(a) * u => vj = α * aij * ui
// NOTE: dense vector v will be first initialised with zeros
func SpMatTrVecMul(v Vector, α float64, a *CCMatrix, u Vector) {
v.Fill(0)
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[j] += α * a.x[k] * u[a.i[k]]
}
}
}
// SpMatTrVecMulAdd returns the (sparse) matrix-vector multiplication with addition and "a" transposed (scaled):
// v += α * transp(a) * u => vj += α * aij * ui
func SpMatTrVecMulAdd(v Vector, α float64, a *CCMatrix, u Vector) {
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[j] += α * a.x[k] * u[a.i[k]]
}
}
}
// SpMatVecMulC returns the (sparse/complex) matrix-vector multiplication (scaled):
// v := α * a * u => vi = α * aij * uj
// NOTE: dense vector v will be first initialised with zeros
func SpMatVecMulC(v VectorC, α complex128, a *CCMatrixC, u VectorC) {
v.Fill(0)
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[a.i[k]] += α * a.x[k] * u[j]
}
}
}
// SpMatVecMulAddC returns the (sparse/complex) matrix-vector multiplication with addition (scaled):
// v += α * a * u => vi += α * aij * uj
func SpMatVecMulAddC(v VectorC, α complex128, a *CCMatrixC, u VectorC) {
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[a.i[k]] += α * a.x[k] * u[j]
}
}
}
// SpMatTrVecMulC returns the (sparse/complex) matrix-vector multiplication with "a" transposed (scaled):
// v := α * transp(a) * u => vj = α * aij * ui
// NOTE: dense vector v will be first initialised with zeros
func SpMatTrVecMulC(v VectorC, α complex128, a *CCMatrixC, u VectorC) {
v.Fill(0)
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[j] += α * a.x[k] * u[a.i[k]]
}
}
}
// SpMatTrVecMulAddC returns the (sparse/complex) matrix-vector multiplication with addition and "a" transposed (scaled):
// v += α * transp(a) * u => vj += α * aij * ui
func SpMatTrVecMulAddC(v VectorC, α complex128, a *CCMatrixC, u VectorC) {
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
v[j] += α * a.x[k] * u[a.i[k]]
}
}
}
// --------------------------------------------------------------------------------------------------
// auxiliary ----------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
// SpInitSimilar initialises another matrix "b" with the same structure (Ap, Ai) of
// sparse matrix "a". The values Ax are not copied though.
func SpInitSimilar(b *CCMatrix, a *CCMatrix) {
b.m, b.n, b.nnz = a.m, a.n, a.nnz
b.p = make([]int, a.n+1)
b.i = make([]int, a.nnz)
b.x = make([]float64, a.nnz)
for j := 0; j < a.n+1; j++ {
b.p[j] = a.p[j]
}
for k := 0; k < a.nnz; k++ {
b.i[k] = a.i[k]
}
}
// SpInitSimilarR2C initialises another matrix "b" (complex) with the same structure (Ap, Ai) of
// sparse matrix "a" (real). The values Ax are not copied though (Bx and Bz are not set).
func SpInitSimilarR2C(b *CCMatrixC, a *CCMatrix) {
b.m, b.n, b.nnz = a.m, a.n, a.nnz
b.p = make([]int, a.n+1)
b.i = make([]int, a.nnz)
b.x = make([]complex128, a.nnz)
for j := 0; j < a.n+1; j++ {
b.p[j] = a.p[j]
}
for k := 0; k < a.nnz; k++ {
b.i[k] = a.i[k]
}
}
// SpMatAddI adds an identity matrix I to "a", scaled by α and β according to:
// r := α*a + β*I
func SpMatAddI(r *CCMatrix, α float64, a *CCMatrix, β float64) {
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
if a.i[k] == j {
r.x[k] = α*a.x[k] + β
} else {
r.x[k] = α * a.x[k]
}
}
}
}
// SpCheckDiag checks if all elements on the diagonal of "a" are present.
// OUTPUT:
// ok -- true if all diagonal elements are present;
// otherwise, ok == false if any diagonal element is missing.
func SpCheckDiag(a *CCMatrix) bool {
rowok := make([]bool, a.m)
for j := 0; j < a.n; j++ {
for k := a.p[j]; k < a.p[j+1]; k++ {
if a.i[k] == j {
rowok[j] = true
}
}
}
for i := 0; i < a.m; i++ {
if !rowok[i] {
return false
}
}
return true
}
// SpInitRc initialises two complex sparse matrices (residual correction) according to:
// Real: R := γ *I - J
// Complex: C := (α + βi)*I - J
// NOTE: "J" must include all diagonal elements
func SpInitRc(R *CCMatrix, C *CCMatrixC, J *CCMatrix) {
R.m, R.n, R.nnz = J.m, J.n, J.nnz
R.p = make([]int, J.n+1)
R.i = make([]int, J.nnz)
R.x = make([]float64, J.nnz)
C.m, C.n, C.nnz = J.m, J.n, J.nnz
C.p = make([]int, J.n+1)
C.i = make([]int, J.nnz)
C.x = make([]complex128, J.nnz)
for j := 0; j < J.n+1; j++ {
R.p[j] = J.p[j]
C.p[j] = J.p[j]
}
for k := 0; k < J.nnz; k++ {
R.i[k] = J.i[k]
C.i[k] = J.i[k]
}
}
// SpSetRc sets the values within two complex sparse matrices (residual correction) according to:
// Real: R := γ *I - J
// Complex: C := (α + βi)*I - J
// NOTE: "J" must include all diagonal elements
func SpSetRc(R *CCMatrix, C *CCMatrixC, α, β, γ float64, J *CCMatrix) {
for j := 0; j < J.n; j++ {
for k := J.p[j]; k < J.p[j+1]; k++ {
if J.i[k] == j {
R.x[k] = γ - J.x[k]
C.x[k] = complex(α-J.x[k], β)
} else {
R.x[k] = -J.x[k]
C.x[k] = complex(-J.x[k], 0)
}
}
}
}
// SpTriSetDiag sets a (n x n) real triplet with diagonal values 'v'
func SpTriSetDiag(a *Triplet, n int, v float64) {
a.Init(n, n, n)
for i := 0; i < n; i++ {
a.Put(i, i, v)
}
}
// --------------------------------------------------------------------------------------------------
// matrix-matrix ------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
// SpAllocMatAddMat allocates a matrix 'c' to hold the result of the addition of 'a' and 'b'.
// It also allocates the mapping arrays a2c and b2c, where:
// a2c maps 'k' in 'a' to 'k' in 'c': len(a2c) = a.nnz
// b2c maps 'k' in 'b' to 'k' in 'c': len(b2c) = b.nnz
func SpAllocMatAddMat(a, b *CCMatrix) (c *CCMatrix, a2c, b2c []int) {
if a.m != b.m || a.n != b.n {
chk.Panic("matrices 'a' (%dx%d) and 'b' (%dx%d) must have the same dimensions", a.m, a.n, b.m, b.n)
}
// number of nonzeros in 'c'
var i, j, k, nnz int
r2a := make([]int, a.m) // maps a row index to the corresponding k index of 'a'
r2b := make([]int, a.m) // maps a row index to the corresponding k index of 'b'
exact := true
if exact {
for j = 0; j < a.n; j++ {
for i = 0; i < a.m; i++ {
r2a[i], r2b[i] = -1, -1
}
for k = a.p[j]; k < a.p[j+1]; k++ {
r2a[a.i[k]] = k
}
for k = b.p[j]; k < b.p[j+1]; k++ {
r2b[b.i[k]] = k
}
for i = 0; i < a.m; i++ {
if r2a[i] > -1 || r2b[i] > -1 {
nnz++
}
}
}
} else {
nnz = a.nnz + b.nnz
}
// allocate c, a2c, and b2c
c = new(CCMatrix)
c.m, c.n, c.nnz = a.m, a.n, nnz
c.x = make(Vector, nnz)
c.i = make([]int, nnz)
c.p = make([]int, c.n+1)
a2c = make([]int, a.nnz)
b2c = make([]int, b.nnz)
nnz = 0 // == k of 'c'
for j = 0; j < a.n; j++ {
for i = 0; i < a.m; i++ {
r2a[i], r2b[i] = -1, -1
}
for k = a.p[j]; k < a.p[j+1]; k++ {
r2a[a.i[k]] = k
}
for k = b.p[j]; k < b.p[j+1]; k++ {
r2b[b.i[k]] = k
}
for i = 0; i < a.m; i++ {
if r2a[i] > -1 || r2b[i] > -1 {
if r2a[i] > -1 {
a2c[r2a[i]] = nnz
}
if r2b[i] > -1 {
b2c[r2b[i]] = nnz
}
c.i[nnz] = i
nnz++
}
}
c.p[j+1] = nnz
}
return
}
// SpMatAddMat adds two sparse matrices. The 'c' matrix matrix and the 'a2c' and 'b2c' arrays
// must be pre-allocated by SpAllocMatAddMat. The result is:
// c := α*a + β*b
// NOTE: this routine does not check for the correct sizes, since this is expect to be
// done by SpAllocMatAddMat
func SpMatAddMat(c *CCMatrix, α float64, a *CCMatrix, β float64, b *CCMatrix, a2c, b2c []int) {
for i := 0; i < len(c.x); i++ {
c.x[i] = 0
}
for k := 0; k < a.nnz; k++ {
c.x[a2c[k]] += α * a.x[k]
}
for k := 0; k < b.nnz; k++ {
c.x[b2c[k]] += β * b.x[k]
}
}
// SpMatAddMatC adds two real sparse matrices with two sets of coefficients in such a way that
// one real matrix (R) and another complex matrix (C) are obtained. The results are:
// R := γ *a + μ*b
// C := (α+βi)*a + μ*b
// NOTE: the structure of R and C are the same and can be allocated with SpAllocMatAddMat,
// followed by one call to SpInitSimilarR2C. For example:
// R, a2c, b2c := SpAllocMatAddMat(a, b)
// SpInitSimilarR2C(C, R)
func SpMatAddMatC(C *CCMatrixC, R *CCMatrix, α, β, γ float64, a *CCMatrix, μ float64, b *CCMatrix, a2c, b2c []int) {
for k := 0; k < R.nnz; k++ {
R.x[k], C.x[k] = 0, 0
}
for k := 0; k < a.nnz; k++ {
R.x[a2c[k]] += γ * a.x[k]
C.x[a2c[k]] += complex(α*a.x[k], β*a.x[k])
}
for k := 0; k < b.nnz; k++ {
R.x[b2c[k]] += μ * b.x[k]
C.x[b2c[k]] += complex(μ*b.x[k], 0)
}
}
// --------------------------------------------------------------------------------------------------
// triplet-triplet ----------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------
// SpTriAdd adds two matrices in Triplet format:
// c := α*a + β*b
// NOTE: the output 'c' triplet must be able to hold all nonzeros of 'a' and 'b'
// actually the 'c' triplet is just expanded
func SpTriAdd(c *Triplet, α float64, a *Triplet, β float64, b *Triplet) {
c.Start()
for k := 0; k < a.pos; k++ {
c.Put(a.i[k], a.j[k], α*a.x[k])
}
for k := 0; k < b.pos; k++ {
c.Put(b.i[k], b.j[k], β*b.x[k])
}
}
// SpTriAddR2C adds two real matrices in Triplet format generating a complex triplet
// according to:
// c := (α+βi)*a + μ*b
// NOTE: the output 'c' triplet must be able to hold all nonzeros of 'a' and 'b'
func SpTriAddR2C(c *TripletC, α, β float64, a *Triplet, μ float64, b *Triplet) {
c.Start()
for k := 0; k < a.pos; k++ {
c.Put(a.i[k], a.j[k], complex(α*a.x[k], β*a.x[k]))
}
for k := 0; k < b.pos; k++ {
c.Put(b.i[k], b.j[k], complex(μ*b.x[k], 0))
}
}
// SpTriMatVecMul returns the matrix-vector multiplication with matrix a in
// triplet format and two dense vectors x and y
// y := a * x or y_i := a_ij * x_j
func SpTriMatVecMul(y Vector, a *Triplet, x Vector) {
if len(y) != a.m {
chk.Panic("length of vector y must be equal to %d. y_(%d × 1). a_(%d × %d)", a.m, len(y), a.m, a.n)
}
if len(x) != a.n {
chk.Panic("length of vector x must be equal to %d. x_(%d × 1). a_(%d × %d)", a.n, len(x), a.m, a.n)
}
for i := 0; i < len(y); i++ {
y[i] = 0
}
for k := 0; k < a.pos; k++ {
y[a.i[k]] += a.x[k] * x[a.j[k]]
}
}
// SpTriMatTrVecMul returns the matrix-vector multiplication with transposed matrix a in
// triplet format and two dense vectors x and y
// y := transpose(a) * x or y_I := a_JI * x_J or y_j := a_ij * x_i
func SpTriMatTrVecMul(y Vector, a *Triplet, x Vector) {
if len(y) != a.n {
chk.Panic("length of vector y must be equal to %d. y_(%d × 1). a_(%d × %d)", a.n, len(y), a.m, a.n)
}
if len(x) != a.m {
chk.Panic("length of vector x must be equal to %d. x_(%d × 1). a_(%d × %d)", a.m, len(x), a.m, a.n)
}
for j := 0; j < len(y); j++ {
y[j] = 0
}
for k := 0; k < a.pos; k++ {
y[a.j[k]] += a.x[k] * x[a.i[k]]
}
} | la/sparse_blas.go | 0.747524 | 0.47926 | sparse_blas.go | starcoder |
package util
import (
"math/rand"
)
const (
maxLevel = 16 // Should be enough for 2^16 elements
probability = 0.25 // It's the best practice value (Based on Time and Space)
// Higher level, smaller probability
// Just modify the probability factor P to reduce additional space
)
type slNode struct {
score float64
val interface{}
// forward[i]: the slNode is current node's next one, which is at i_th layer
forward []*slNode
}
type SlElement struct {
Score float64 `json:"score"`
Val interface{} `json:"val"`
}
func newSLNode(score float64, value interface{}, level int) *slNode {
return &slNode{
score: score,
val: value,
forward: make([]*slNode, level),
}
}
type SkipList struct {
header *slNode
len int
level int
}
func NewSkipList() *SkipList {
return &SkipList{
header: &slNode{forward: make([]*slNode, maxLevel)},
len: 0,
}
}
func randomLevel() int {
level := 1
for rand.Float32() < probability && level < maxLevel {
level++
}
return level
}
func (sl *SkipList) Front() *slNode {
return sl.header.forward[0]
}
func (n *slNode) Next() *slNode {
if n != nil {
return n.forward[0]
}
return nil
}
func (sl *SkipList) GetList() []SlElement {
list := make([]SlElement, sl.len)
x := sl.Front()
i := 0
for x != nil {
list[i] = SlElement{
Score: x.score,
Val: x.val,
}
x = x.Next()
i++
}
return list
}
func (sl *SkipList) Search(score float64) ([]*slNode, bool) {
x := sl.header
for i := sl.level - 1; i >= 0; i-- {
for x.forward[i] != nil && x.forward[i].score < score {
x = x.forward[i]
}
}
x = x.Next()
res := make([]*slNode, 0)
if x != nil && x.score == score {
for x != nil && x.score == score {
res = append(res, x)
x = x.Next()
}
return res, true
}
return nil, false
}
func (sl *SkipList) Insert(score float64, value interface{}) *slNode {
update := make([]*slNode, maxLevel)
x := sl.header
for i := sl.level - 1; i >= 0; i-- {
for x.forward[i] != nil && x.forward[i].score < score {
x = x.forward[i]
}
update[i] = x
}
x = x.Next()
level := randomLevel()
if level > sl.level {
level = sl.level + 1
update[sl.level] = sl.header
sl.level = level
}
newNode := newSLNode(score, value, level)
for i := 0; i < level; i++ {
newNode.forward[i] = update[i].forward[i]
update[i].forward[i] = newNode
}
sl.len++
return newNode
}
func (sl *SkipList) Delete(score float64) {
update := make([]*slNode, maxLevel)
x := sl.header
for i := sl.level - 1; i >= 0; i-- {
for x.forward[i] != nil && x.forward[i].score < score {
x = x.forward[i]
}
update[i] = x
}
x = x.Next()
for x != nil && x.score == score {
for i := 0; i < sl.level; i++ {
if update[i].forward[i] != x {
break
}
update[i].forward[i] = x.forward[i]
}
sl.len--
x = x.Next()
}
}
func (sl *SkipList) Len() int {
return sl.len
} | warekv/util/skiplist.go | 0.642208 | 0.440289 | skiplist.go | starcoder |
package tree
import (
"context"
"github.com/itzamna314/battlesnake/game"
)
// expandWorker listens to the tree's expand channel
// It checks each next node to see if its our new best, and
// adds all of its children to the weight channel
func (t *Tree) expandWorker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case exp, ok := <-t.expand:
if !ok {
return
}
if t.curBest == nil || exp.Weight > t.curBestWeight {
t.curBest = []*Node{exp}
t.curBestWeight = exp.Weight
} else if exp.Weight == t.curBestWeight {
t.curBest = append(t.curBest, exp)
}
// Expand this node if:
// * We want to explore the next level
// * The brain thinks its worth exploring this node further
if t.MaxDepth == 0 || t.curDepth < t.MaxDepth {
if !exp.Brain.Abort(exp.Weight) {
t.expandNode(ctx, exp)
}
}
// We're processing a finished node at the current level
t.curLeft--
// Finishing a level. Store the results of the last depth.
// Re-set the current best
if t.curLeft <= 0 {
// Store the results of this level, and queue up the next one
// When all of the next level has been queued, we can begin
// expanding it out
t.completeLevel(ctx)
// Exit if this is the final level
if t.MaxDepth != 0 && t.curDepth > t.MaxDepth {
return
}
}
}
}
}
func (t *Tree) expandNode(ctx context.Context, node *Node) {
for dir, opt := range game.Options(node.Coord) {
child := Node{
Direction: game.Direction(dir),
SnakeID: node.SnakeID,
Coord: opt,
Brain: node.Brain.Clone(),
Parent: node,
Depth: node.Depth + 1,
}
t.nextLevel[node.Depth] = append(t.nextLevel[node.Depth], &child)
t.nextWidth++
}
}
// completeLevel marks the current level as complete
// Called from the expand worker when we finish processing a level
// of the tree.
// Return true to continue traversal, false to exit
func (t *Tree) completeLevel(ctx context.Context) {
t.best = t.curBest
t.curBest = nil
t.curLeft = t.nextWidth
t.nextWidth = 0
t.nextLevel = append(t.nextLevel, []*Node{})
go func(depth int) {
for _, n := range t.nextLevel[depth] {
select {
case t.weight <- n:
case <-ctx.Done():
return
}
}
t.nextLevel[depth] = nil
}(t.curDepth)
t.curDepth++
} | tree/expand.go | 0.541166 | 0.41745 | expand.go | starcoder |
package html
import (
"strings"
"github.com/golangee/dom"
gt "github.com/golangee/gotrino"
)
func Div(e ...gt.Renderable) gt.Node {
return gt.Element("div", e...)
}
func IFrame(e ...gt.Renderable) gt.Node {
return gt.Element("iframe", e...)
}
func Hr(e ...gt.Renderable) gt.Node {
return gt.Element("hr", e...)
}
func Button(e ...gt.Renderable) gt.Node {
return gt.Element("button", e...)
}
func Nav(e ...gt.Renderable) gt.Node {
return gt.Element("nav", e...)
}
// Class sets and replaces all existing class definitions.
func Class(classes ...string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
if len(classes) == 0 {
return
}
if len(classes) == 1 {
e.SetClassName(classes[0])
return
}
e.SetClassName(strings.Join(classes, " "))
})
}
// AddClass appends each given class.
func AddClass(classes ...string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
if len(classes) == 0 {
return
}
for _, class := range classes {
if strings.ContainsRune(class, ' ') {
// separate it
for _, s := range strings.Split(class, " ") {
s = strings.TrimSpace(s)
if s != "" {
e.AddClass(s)
}
}
} else {
e.AddClass(class)
}
}
})
}
// RemoveClass remove each given class.
func RemoveClass(classes ...string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
if len(classes) == 0 {
return
}
for _, class := range classes {
if strings.ContainsRune(class, ' ') {
// separate it
for _, s := range strings.Split(class, " ") {
e.RemoveClass(s)
}
} else {
e.RemoveClass(class)
}
}
})
}
func SetAttribute(attr, value string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute(attr, value)
})
}
func RemoveAttribute(attr string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.RemoveAttribute(attr)
})
}
// Style sets a single CSS property.
func Style(property, value string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Style().SetProperty(property, value)
})
}
func Text(t string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.AppendTextNode(t)
})
}
func InnerHTML(t string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetInnerHTML(t)
})
}
func Src(src string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("src", src)
})
}
func TabIndex(t string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute("tabindex", t)
})
}
func I(mods ...gt.Renderable) gt.Node {
return gt.Element("i", mods...)
}
func A(mods ...gt.Renderable) gt.Node {
return gt.Element("a", mods...)
}
func Em(mods ...gt.Renderable) gt.Node {
return gt.Element("em", mods...)
}
func Alt(a string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("alt", a)
})
}
func Title(a string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("title", a)
})
}
func Href(href string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("href", href)
})
}
func Width(w string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("width", w)
})
}
func Height(h string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("height", h)
})
}
func Figure(mods ...gt.Renderable) gt.Node {
return gt.Element("figure", mods...)
}
func Ul(mods ...gt.Renderable) gt.Node {
return gt.Element("ul", mods...)
}
func Li(mods ...gt.Renderable) gt.Node {
return gt.Element("li", mods...)
}
func Ol(mods ...gt.Renderable) gt.Node {
return gt.Element("ol", mods...)
}
func Img(mods ...gt.Renderable) gt.Node {
return gt.Element("img", mods...)
}
func P(mods ...gt.Renderable) gt.Node {
return gt.Element("p", mods...)
}
func Pre(mods ...gt.Renderable) gt.Node {
return gt.Element("pre", mods...)
}
func Code(mods ...gt.Renderable) gt.Node {
return gt.Element("code", mods...)
}
func Aside(mods ...gt.Renderable) gt.Node {
return gt.Element("aside", mods...)
}
func Blockquote(mods ...gt.Renderable) gt.Node {
return gt.Element("blockquote", mods...)
}
func Figcaption(mods ...gt.Renderable) gt.Node {
return gt.Element("figcaption", mods...)
}
func Span(mods ...gt.Renderable) gt.Node {
return gt.Element("span", mods...)
}
func ID(id string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetID(id)
})
}
func AddEventListener(eventType string, f func()) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.AddEventListener(eventType, false, f)
})
}
func AddClickListener(f func()) gt.Modifier {
return AddEventListener("click", f)
}
func AddKeyDownListener(f func(keyCode int)) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.AddKeyListener("keyup", f)
})
}
func AddEventListenerOnce(eventType string, f func()) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.AddEventListener(eventType, true, f)
})
}
func AriaLabel(label string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute("aria-label", label)
})
}
func AriaOrientation(orientation string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute("aria-orientation", orientation)
})
}
func AriaLabelledby(label string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute("aria-labelledby", label)
})
}
func Role(role string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute("role", role)
})
}
// Table creates a table element.
// See also https://html.spec.whatwg.org/multipage/tables.html#the-table-element.
func Table(e ...gt.Renderable) gt.Node {
return gt.Element("table", e...)
}
// Thead creates a thead element.
// See also https://html.spec.whatwg.org/multipage/tables.html#the-thead-element.
func Thead(e ...gt.Renderable) gt.Node {
return gt.Element("thead", e...)
}
// Tr creates a tr element.
// See also https://html.spec.whatwg.org/multipage/tables.html#the-tr-element.
func Tr(e ...gt.Renderable) gt.Node {
return gt.Element("tr", e...)
}
// Th creates a th element.
// See also https://html.spec.whatwg.org/multipage/tables.html#the-th-element.
func Th(e ...gt.Renderable) gt.Node {
return gt.Element("th", e...)
}
// Td creates a td element.
// See also https://html.spec.whatwg.org/multipage/tables.html#the-td-element.
func Td(e ...gt.Renderable) gt.Node {
return gt.Element("td", e...)
}
// Tbody creates a tbody element.
// See also https://html.spec.whatwg.org/multipage/tables.html#the-tbody-element.
func Tbody(e ...gt.Renderable) gt.Node {
return gt.Element("tbody", e...)
}
// Tfoot creates a tfoot element.
// See also https://html.spec.whatwg.org/multipage/tables.html#the-tfoot-element.
func Tfoot(e ...gt.Renderable) gt.Node {
return gt.Element("tfoot", e...)
}
// Target sets a target attribute.
// See also https://html.spec.whatwg.org/dev/links.html#links-created-by-a-and-area-elements.
func Target(t string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute("target", t)
})
}
// Input creates an input element.
// See also https://html.spec.whatwg.org/dev/input.html#the-input-element.
func Input(e ...gt.Renderable) gt.Node {
return gt.Element("input", e...)
}
// Input creates an input element.
// See also https://html.spec.whatwg.org/multipage/forms.html#the-label-element.
func Label(e ...gt.Renderable) gt.Node {
return gt.Element("label", e...)
}
// Form creates a form element.
// See also https://html.spec.whatwg.org/multipage/forms.html#the-form-element.
func Form(e ...gt.Renderable) gt.Node {
return gt.Element("form", e...)
}
// For set the for attribute.
// See also https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label.
func For(v string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.SetAttribute("for", v)
})
}
// Type sets the type property.
// See https://html.spec.whatwg.org/dev/input.html#states-of-the-type-attribute.
func Type(v string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("type", v)
})
}
// Name sets the name property.
// See https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-name.
func Name(v string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("name", v)
})
}
// Placeholder sets the placeholder property.
// See https://html.spec.whatwg.org/multipage/input.html#the-placeholder-attribute.
func Placeholder(v string) gt.Modifier {
return gt.ModifierFunc(func(e dom.Element) {
e.Set("placeholder", v)
})
} | html.go | 0.578924 | 0.415136 | html.go | starcoder |
package fauxgl
import "math"
type Shader interface {
Vertex(Vertex) Vertex
Fragment(Vertex) Color
}
// SolidColorShader renders with a single, solid color.
type SolidColorShader struct {
Matrix Matrix
Color Color
}
func NewSolidColorShader(matrix Matrix, color Color) *SolidColorShader {
return &SolidColorShader{matrix, color}
}
func (shader *SolidColorShader) Vertex(v Vertex) Vertex {
v.Output = shader.Matrix.MulPositionW(v.Position)
return v
}
func (shader *SolidColorShader) Fragment(v Vertex) Color {
return shader.Color
}
// TextureShader renders with a texture and no lighting.
type TextureShader struct {
Matrix Matrix
Texture Texture
}
func NewTextureShader(matrix Matrix, texture Texture) *TextureShader {
return &TextureShader{matrix, texture}
}
func (shader *TextureShader) Vertex(v Vertex) Vertex {
v.Output = shader.Matrix.MulPositionW(v.Position)
return v
}
func (shader *TextureShader) Fragment(v Vertex) Color {
return shader.Texture.BilinearSample(v.Texture.X, v.Texture.Y)
}
// PhongShader implements Phong shading with an optional texture.
type PhongShader struct {
Matrix Matrix
LightDirection Vector
CameraPosition Vector
ObjectColor Color
AmbientColor Color
DiffuseColor Color
SpecularColor Color
Texture Texture
SpecularPower float64
}
func NewPhongShader(matrix Matrix, lightDirection, cameraPosition Vector) *PhongShader {
ambient := Color{0.2, 0.2, 0.2, 1}
diffuse := Color{0.8, 0.8, 0.8, 1}
specular := Color{1, 1, 1, 1}
return &PhongShader{
matrix, lightDirection, cameraPosition,
Discard, ambient, diffuse, specular, nil, 32}
}
func (shader *PhongShader) Vertex(v Vertex) Vertex {
v.Output = shader.Matrix.MulPositionW(v.Position)
return v
}
func (shader *PhongShader) Fragment(v Vertex) Color {
light := shader.AmbientColor
color := v.Color
if shader.ObjectColor != Discard {
color = shader.ObjectColor
}
if shader.Texture != nil {
color = shader.Texture.BilinearSample(v.Texture.X, v.Texture.Y)
}
diffuse := math.Max(v.Normal.Dot(shader.LightDirection), 0)
light = light.Add(shader.DiffuseColor.MulScalar(diffuse))
if diffuse > 0 && shader.SpecularPower > 0 {
camera := shader.CameraPosition.Sub(v.Position).Normalize()
reflected := shader.LightDirection.Negate().Reflect(v.Normal)
specular := math.Max(camera.Dot(reflected), 0)
if specular > 0 {
specular = math.Pow(specular, shader.SpecularPower)
light = light.Add(shader.SpecularColor.MulScalar(specular))
}
}
return color.Mul(light).Min(White).Alpha(color.A)
} | shader.go | 0.888837 | 0.485356 | shader.go | starcoder |
package geography
import (
"database/sql/driver"
"encoding/binary"
"errors"
"strconv"
"github.com/go-courier/geography/encoding/mvt"
"github.com/go-courier/geography/encoding/wkb"
"github.com/go-courier/geography/encoding/wkt"
)
type MultiPolygon []Polygon
func (mp MultiPolygon) ToGeom() Geom {
return mp
}
func (mp MultiPolygon) Clip(b Bound) Geom {
var result MultiPolygon
for i := range mp {
g := mp[i].Clip(b)
if g != nil {
result = append(result, g.(Polygon))
}
}
return result
}
func (mp MultiPolygon) Project(transform Transform) Geom {
nextMp := make(MultiPolygon, len(mp))
for i := range mp {
nextMp[i] = mp[i].Project(transform).(Polygon)
}
return nextMp
}
func (MultiPolygon) Type() string {
return "MultiPolygon"
}
func (mp MultiPolygon) Bound() Bound {
if len(mp) == 0 {
return emptyBound
}
bound := mp[0].Bound()
for i := 1; i < len(mp); i++ {
bound = bound.Union(mp[i].Bound())
}
return bound
}
func (mp MultiPolygon) Equal(g Geom) bool {
switch multiPolygon := g.(type) {
case MultiPolygon:
if len(mp) != len(multiPolygon) {
return false
}
for i, p := range mp {
if !p.Equal(multiPolygon[i]) {
return false
}
}
return true
}
return false
}
func (mp MultiPolygon) MarshalWKT(w *wkt.WKTWriter) {
for i, polygon := range mp {
w.WriteGroup(polygon.MarshalWKT, i)
}
}
func (mp *MultiPolygon) UnmarshalWKB(r *wkb.WKBReader, order binary.ByteOrder, tpe wkb.GeometryType) error {
if tpe != wkb.MultiPolygonType {
return errors.New("not multi line string wkb")
}
var numOfPolygons uint32
if err := r.ReadBinary(order, &numOfPolygons); err != nil {
return err
}
result := make(MultiPolygon, 0, numOfPolygons)
for i := 0; i < int(numOfPolygons); i++ {
p := Polygon{}
if err := r.ReadWKB(&p); err != nil {
return err
}
result = append(result, p)
}
*mp = result
return nil
}
func (mp MultiPolygon) Cap() int {
c := 0
for _, p := range mp {
c += p.Cap()
}
return c
}
func (mp MultiPolygon) DrawFeature(w *mvt.FeatureWriter) {
for _, p := range mp {
p.DrawFeature(w)
}
}
func (mp MultiPolygon) Geometry() []uint32 {
w := mvt.NewFeatureWriter(mp.Cap())
mp.DrawFeature(w)
return w.Data()
}
func (MultiPolygon) DataType(driverName string) string {
if driverName == "mysql" {
return "MULTIPOLYGON"
}
return "geometry(MULTIPOLYGON)"
}
func (MultiPolygon) ValueEx() string {
return "ST_GeomFromText(?," + strconv.FormatInt(SRS3857, 10) + ")"
}
func (mp MultiPolygon) Value() (driver.Value, error) {
return wkt.MarshalWKT(mp, SRS3857), nil
}
func (mp *MultiPolygon) Scan(src interface{}) error {
return scan(src, mp)
} | geom_multi_polygon.go | 0.630002 | 0.402157 | geom_multi_polygon.go | starcoder |
package ioutil
/*
// A Path is a slice of names.
type Path []string
// Parent returns the parent path segments. The parent of the empty element is nil.
func (p Path) Parent() Path {
if len(p) == 0 {
return nil
}
return p[0 : len(p)-1]
}
// IsEmpty returns true, if no path segments are present
func (p Path) IsEmpty() bool {
return len(p) == 0
}
// Name returns the name of the last segment or the empty string.
func (p Path) Name() string {
if p.IsEmpty() {
return ""
}
return p[len(p)-1]
}
// String returns this path as a joined platform specific path.
func (p Path) String() string {
return filepath.Join(p...)
}
type OpenOptions struct {
}
func NewOpenOptions() *OpenOptions {
return &OpenOptions{}
}
func (o *OpenOptions) Read(read bool) *OpenOptions {
return o
}
func (o *OpenOptions) Write(write bool) *OpenOptions {
return o
}
func (o *OpenOptions) Create(create bool) *OpenOptions {
return o
}
func (o *OpenOptions) CreateNew(createNew bool) *OpenOptions {
return o
}
func (o *OpenOptions) Truncate(truncate bool) *OpenOptions {
return o
}
func (o *OpenOptions) Append(append bool) *OpenOptions {
return o
}
func (o *OpenOptions) Open(name string) io.ReadWriteCloser {
return nil
}
type FSQuery struct {
}
func NewQuery() *FSQuery {
return nil
}
func (q *FSQuery) Select() *FSQuery {
return q
}
func (q *FSQuery) Files() *FSQuery {
return q
}
func (q *FSQuery) Where() *FSQuery {
return q
}
func (q *FSQuery) File() *FSQuery {
return q
}
func (q *FSQuery) Has() *FSQuery {
return q
}
func (q *FSQuery) Name() *FSQuery {
return q
}
func (q *FSQuery) Attribute() *FSQuery {
return q
}
func (q *FSQuery) IsHidden() *FSQuery {
return q
}
func (q *FSQuery) NotHidden() *FSQuery {
return q
}
func (q *FSQuery) From(p string) *FSQuery {
return q
}
func (q *FSQuery) Recursively() *FSQuery {
return q
}
func (q *FSQuery) And() *FSQuery {
return q
}
func (q *FSQuery) EndsWidth(s string) *FSQuery {
return q
}
func (q *FSQuery) Execute() *FSQuery {
return q
}*/ | path.go | 0.816882 | 0.464051 | path.go | starcoder |
package image
import (
"bytes"
"fmt"
"github.com/google/gapid/core/data/endian"
"github.com/google/gapid/core/math/sint"
"github.com/google/gapid/core/os/device"
)
type rgbaF32 struct {
r, g, b, a float32
}
// resizeRGBA_F32 returns a RGBA_F32 image resized from srcW x srcH to dstW x dstH.
// The algorithm uses pixel-pair averaging to down-sample (if required) the
// image to no greater than twice the width or height than the target
// dimensions, then uses a bilinear interpolator to calculate the final image
// at the requested size.
func resizeRGBA_F32(data []byte, srcW, srcH, dstW, dstH int) ([]byte, error) {
if err := checkSize(data, RGBA_F32.format(), srcW, srcH); err != nil {
return nil, err
}
if srcW <= 0 || srcH <= 0 {
return nil, fmt.Errorf("Invalid source size for Resize: %dx%d", srcW, srcH)
}
if dstW <= 0 || dstH <= 0 {
return nil, fmt.Errorf("Invalid target size for Resize: %dx%d", dstW, dstH)
}
r := endian.Reader(bytes.NewReader(data), device.LittleEndian)
bufA, bufB := make([]rgbaF32, srcW*srcH), make([]rgbaF32, srcW*srcH)
for i := range bufA {
bufA[i] = rgbaF32{r.Float32(), r.Float32(), r.Float32(), r.Float32()}
}
dst, src := bufB, bufA
for dstW*2 <= srcW { // Horizontal 2x downsample
newW := srcW / 2
for y := 0; y < srcH; y++ {
i := newW * y
a, b := srcW*y, srcW*y+1
for x := 0; x < srcW/2; x++ {
dst[i].r = (src[a].r + src[b].r) * 0.5
dst[i].g = (src[a].g + src[b].g) * 0.5
dst[i].b = (src[a].b + src[b].b) * 0.5
dst[i].a = (src[a].a + src[b].a) * 0.5
i, a, b = i+1, a+2, b+2
}
}
dst, src, srcW = src, dst, newW
}
for dstH*2 <= srcH { // Vertical 2x downsample
newH := srcH / 2
for y := 0; y < newH; y++ {
i := srcW * y
a, b := i*2, i*2+srcW
for x := 0; x < srcW; x++ {
dst[i].r = (src[a].r + src[b].r) * 0.5
dst[i].g = (src[a].g + src[b].g) * 0.5
dst[i].b = (src[a].b + src[b].b) * 0.5
dst[i].a = (src[a].a + src[b].a) * 0.5
i, a, b = i+1, a+1, b+1
}
}
dst, src, srcH = src, dst, newH
}
out := make([]byte, dstW*dstH*4*4)
w := endian.Writer(bytes.NewBuffer(out[:0]), device.LittleEndian)
if srcW == dstW && srcH == dstH {
for i, c := 0, dstW*dstH; i < c; i++ {
w.Float32(src[i].r)
w.Float32(src[i].g)
w.Float32(src[i].b)
w.Float32(src[i].a)
}
} else {
// bi-linear filtering
sx := float64(sint.Max(srcW-1, 0)) / float64(sint.Max(dstW-1, 1))
sy := float64(sint.Max(srcH-1, 0)) / float64(sint.Max(dstH-1, 1))
for y := 0; y < dstH; y++ {
fy := float64(y) * sy
iy := int(fy)
dy, y0, y1 := float32(fy-float64(iy)), iy, sint.Min(iy+1, srcH-1)
for x := 0; x < dstW; x++ {
fx := float64(x) * sx
ix := int(fx)
dx, x0, x1 := float32(fx-float64(ix)), ix, sint.Min(ix+1, srcW-1)
a, b := src[x0+y0*srcW], src[x1+y0*srcW]
c, d := src[x0+y1*srcW], src[x1+y1*srcW]
p := rgbaF32{a.r + (b.r-a.r)*dx, a.g + (b.g-a.g)*dx, a.b + (b.b-a.b)*dx, a.a + (b.a-a.a)*dx}
q := rgbaF32{c.r + (d.r-c.r)*dx, c.g + (d.g-c.g)*dx, c.b + (d.b-c.b)*dx, c.a + (d.a-c.a)*dx}
r := rgbaF32{p.r + (q.r-p.r)*dy, p.g + (q.g-p.g)*dy, p.b + (q.b-p.b)*dy, p.a + (q.a-p.a)*dy}
w.Float32(r.r)
w.Float32(r.g)
w.Float32(r.b)
w.Float32(r.a)
}
}
}
return out, nil
} | core/image/rgba_f32.go | 0.692226 | 0.471345 | rgba_f32.go | starcoder |
package pointers
import (
"sync/atomic"
"unsafe"
)
// - MARK: Atomics section.
// CASSliceSlot is a function that performs a CAS operation
// on a given slice slot by performing pointer arithmitic
// to find slot address. `addr` is a pointer to slice,
// `data` is a pointer to old value to be compared,
// `target` is a pointer to the new value, `index` is
// the slot number and `ptrsize` is the slice value size.
// It returns true when succesfull.
func CASSliceSlot(addr unsafe.Pointer, data unsafe.Pointer, target unsafe.Pointer, index int, ptrsize uintptr) bool {
var (
tptr *unsafe.Pointer
cptr unsafe.Pointer
)
tptr = (*unsafe.Pointer)(unsafe.Pointer(*(*uintptr)(addr) + (ptrsize * uintptr(index))))
cptr = unsafe.Pointer(tptr)
return atomic.CompareAndSwapPointer(
(*unsafe.Pointer)(unsafe.Pointer(cptr)),
(unsafe.Pointer)(unsafe.Pointer(target)),
(unsafe.Pointer)(unsafe.Pointer(data)),
)
}
// CASSliceSlotPtr is a function that performs a CAS operation
// on a given slice slot by performing pointer arithmitic
// to find slot pointer address. `addr` is a pointer to slice,
// `data` is a pointer to old value to be compared,
// `target` is a pointer to the new value, `index` is
// the slot number and `ptrsize` is the slice value size.
// It returns true when succesfull.
func CASSliceSlotPtr(addr unsafe.Pointer, data unsafe.Pointer, target unsafe.Pointer, index int, ptrsize uintptr) bool {
var (
tptr *unsafe.Pointer
cptr unsafe.Pointer
)
tptr = (*unsafe.Pointer)(unsafe.Pointer((uintptr)(addr) + (ptrsize * uintptr(index))))
cptr = unsafe.Pointer(tptr)
return atomic.CompareAndSwapPointer(
(*unsafe.Pointer)(unsafe.Pointer(cptr)),
(unsafe.Pointer)(unsafe.Pointer(target)),
(unsafe.Pointer)(unsafe.Pointer(data)),
)
}
// CASArraySlot is a function that performs a CAS operation
// on a given array slot by performing pointer arithmitic
// to find slot address. `addr` is a pointer to array,
// `data` is a pointer to old value to be compared,
// `target` is a pointer to the new value, `index` is
// the slot number and `ptrsize` is the slice value size.
// It returns true when succesfull.
func CASArraySlot(addr unsafe.Pointer, data unsafe.Pointer, target unsafe.Pointer, index int, ptrsize uintptr) bool {
var (
tptr *unsafe.Pointer
cptr unsafe.Pointer
)
tptr = (*unsafe.Pointer)(unsafe.Pointer((uintptr)(addr) + (ptrsize * uintptr(index))))
cptr = unsafe.Pointer(tptr)
return atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(cptr)),
(unsafe.Pointer)(unsafe.Pointer(target)),
(unsafe.Pointer)(unsafe.Pointer(data)),
)
}
// OffsetArraySlot takes a array pointer and returns
// slot address by adding `index` times `ptrsize` bytes
// to slice data pointer.
func OffsetArraySlot(addr unsafe.Pointer, index int, ptrsize uintptr) unsafe.Pointer {
return unsafe.Pointer((*unsafe.Pointer)(unsafe.Pointer((uintptr)(addr) + (ptrsize * uintptr(index)))))
}
// OffsetSliceSlot takes a slice pointer and returns
// slot address by adding `index` times `ptrsize` bytes
// to slice data pointer.
func OffsetSliceSlot(addr unsafe.Pointer, index int, ptrsize uintptr) unsafe.Pointer {
return unsafe.Pointer(*(*uintptr)(addr) + (ptrsize * uintptr(index)))
}
// SetSliceSlot is a wrapper function that writes `d`
// to the given slice slot iff its nil and returns
// true when succesfull.
func SetSliceSlot(addr unsafe.Pointer, index int, ptrsize uintptr, d unsafe.Pointer) bool {
return CASSliceSlot(addr, d, nil, index, ptrsize)
}
// SetSliceSlotPtr is a wrapper function that writes `d`
// to the given slice slot opinter iff its nil and returns
// true when succesfull.
func SetSliceSlotPtr(addr unsafe.Pointer, index int, ptrsize uintptr, d unsafe.Pointer) bool {
return CASSliceSlotPtr(addr, d, nil, index, ptrsize)
}
// SetSliceSlotI is a wrapper function that writes `d`
// to the given slice slot iff its nil and return
// true when succesfull. Note, it differs from
// `SetSliceSlot` because `d` is written as a pointer
// to `interface{}`.
func SetSliceSlotI(addr unsafe.Pointer, index int, ptrsize uintptr, d interface{}) bool {
return CASSliceSlot(addr, unsafe.Pointer(&d), nil, index, ptrsize)
}
// SetArraySlot is a wrapper function that writes `d`
// to the given array slot iff its nil. It returns
// true when succesfull.
func SetArraySlot(addr unsafe.Pointer, index int, ptrsize uintptr, d unsafe.Pointer) bool {
return CASArraySlot(addr, d, nil, index, ptrsize)
}
// LoadArraySlot takes a array pointer and loads
// slot address by adding `index` times `ptrsize` bytes
// to slice data pointer.
func LoadArraySlot(addr unsafe.Pointer, index int, ptrsize uintptr) unsafe.Pointer {
var (
tptr *unsafe.Pointer
)
tptr = (*unsafe.Pointer)(unsafe.Pointer((uintptr)(addr) + (ptrsize * uintptr(index))))
return atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(tptr)))
}
// LoadSliceSlot takes a slice pointer and loads
// slot address by adding `index` times `ptrsize` bytes
// to slice data pointer.
func LoadSliceSlot(addr unsafe.Pointer, index int, ptrsize uintptr) unsafe.Pointer {
var (
bin *unsafe.Pointer
)
bin = (*unsafe.Pointer)(unsafe.Pointer(*(*uintptr)(addr) + (ptrsize * uintptr(index))))
return atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(bin)))
}
// PopArraySlot is a wrapper function that pops
// `index` slot of array iff its nil. It returns
// a pointer and true when succesfull.
func PopArraySlot(addr unsafe.Pointer, index int, ptrsize uintptr) (unsafe.Pointer, bool) {
var (
slot unsafe.Pointer = LoadArraySlot(addr, index, ptrsize)
)
if !CASArraySlot(addr, nil, slot, index, ptrsize) {
return nil, false
}
return slot, true
}
// PopSliceSlot is a wrapper function that pops
// `index` slot of slice iff its nil. It returns
// a pointer and true when succesfull.
func PopSliceSlot(addr unsafe.Pointer, index int, ptrsize uintptr) (unsafe.Pointer, bool) {
var (
slot unsafe.Pointer = LoadSliceSlot(addr, index, ptrsize)
)
if !CASSliceSlot(addr, nil, slot, index, ptrsize) {
return nil, false
}
return slot, true
}
// CompareAndSwapPointerTag performs CAS operation
// and swaps `source` to `source` with new tag
// when comparision is successfull. It reutrns a
// pointer and boolean to to indicate its success.
func CompareAndSwapPointerTag(source unsafe.Pointer, oldtag uint, newtag uint) (unsafe.Pointer, bool) {
if oldtag > ArchMAXTAG || newtag > ArchMAXTAG {
panic(EPTRINVALT)
}
var (
sraw unsafe.Pointer = Untag(source)
sptr unsafe.Pointer
target unsafe.Pointer
)
sptr, _ = TaggedPointer(sraw, oldtag)
target, _ = TaggedPointer(sraw, newtag)
if atomic.CompareAndSwapPointer(
(*unsafe.Pointer)(unsafe.Pointer(&sptr)),
(unsafe.Pointer)(source),
(unsafe.Pointer)(target),
) {
return target, true
}
return nil, false
} | pointers/pointers.go | 0.739799 | 0.562477 | pointers.go | starcoder |
package main
import (
"regexp"
"strconv"
"strings"
)
const armyRegex = `^(.*):$`
const groupRegex = `^(\d+) units each with (\d+) hit points (?:\((.*)\) )?with an attack that does (\d+) (\w+) damage at initiative (\d+)$`
func atoi(str string) int {
i, err := strconv.Atoi(str)
if err != nil {
panic(err)
}
return i
}
func parseInput(str string) []*Group {
lines := strings.Split(str, "\n")
groups := make([]*Group, 0)
armyRe := regexp.MustCompile(armyRegex)
groupRe := regexp.MustCompile(groupRegex)
army := ""
for _, line := range lines {
if line == "" {
continue
}
match := armyRe.FindStringSubmatch(line)
if len(match) > 0 {
army = match[1]
continue
}
match = groupRe.FindStringSubmatch(line)
g := NewGroup(army, atoi(match[1]), atoi(match[2]), atoi(match[4]), atoi(match[6]), match[5], match[3])
groups = append(groups, g)
}
return groups
}
const inputStr = `Immune System:
2749 units each with 8712 hit points (immune to radiation, cold; weak to fire) with an attack that does 30 radiation damage at initiative 18
704 units each with 1890 hit points with an attack that does 26 fire damage at initiative 17
1466 units each with 7198 hit points (immune to bludgeoning; weak to slashing, cold) with an attack that does 44 bludgeoning damage at initiative 6
6779 units each with 11207 hit points with an attack that does 13 cold damage at initiative 4
1275 units each with 11747 hit points with an attack that does 66 cold damage at initiative 2
947 units each with 5442 hit points with an attack that does 49 radiation damage at initiative 3
4319 units each with 2144 hit points (weak to bludgeoning, fire) with an attack that does 4 fire damage at initiative 9
6315 units each with 5705 hit points with an attack that does 7 cold damage at initiative 16
8790 units each with 10312 hit points with an attack that does 10 fire damage at initiative 5
3242 units each with 4188 hit points (weak to cold; immune to radiation) with an attack that does 11 bludgeoning damage at initiative 14
Infection:
1230 units each with 11944 hit points (weak to cold) with an attack that does 17 bludgeoning damage at initiative 1
7588 units each with 53223 hit points (immune to bludgeoning) with an attack that does 13 cold damage at initiative 12
1887 units each with 40790 hit points (immune to radiation, slashing, cold) with an attack that does 43 fire damage at initiative 15
285 units each with 8703 hit points (immune to slashing) with an attack that does 60 slashing damage at initiative 7
1505 units each with 29297 hit points with an attack that does 38 fire damage at initiative 8
191 units each with 24260 hit points (immune to bludgeoning; weak to slashing) with an attack that does 173 cold damage at initiative 20
1854 units each with 12648 hit points (weak to fire, cold) with an attack that does 13 bludgeoning damage at initiative 13
1541 units each with 49751 hit points (weak to cold, bludgeoning) with an attack that does 62 slashing damage at initiative 19
3270 units each with 22736 hit points with an attack that does 13 slashing damage at initiative 10
1211 units each with 56258 hit points (immune to slashing, cold) with an attack that does 73 bludgeoning damage at initiative 11`
const testStr = `Immune System:
17 units each with 5390 hit points (weak to radiation, bludgeoning) with an attack that does 4507 fire damage at initiative 2
989 units each with 1274 hit points (immune to fire; weak to bludgeoning, slashing) with an attack that does 25 slashing damage at initiative 3
Infection:
801 units each with 4706 hit points (weak to radiation) with an attack that does 116 bludgeoning damage at initiative 1
4485 units each with 2961 hit points (immune to radiation; weak to fire, cold) with an attack that does 12 slashing damage at initiative 4` | 2018/day24/old/data.go | 0.722821 | 0.654305 | data.go | starcoder |
package fp
// ExistsIntPtr checks if given item exists in the list
func ExistsIntPtr(num *int, list []*int) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsInt64Ptr checks if given item exists in the list
func ExistsInt64Ptr(num *int64, list []*int64) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsInt32Ptr checks if given item exists in the list
func ExistsInt32Ptr(num *int32, list []*int32) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsInt16Ptr checks if given item exists in the list
func ExistsInt16Ptr(num *int16, list []*int16) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsInt8Ptr checks if given item exists in the list
func ExistsInt8Ptr(num *int8, list []*int8) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsUintPtr checks if given item exists in the list
func ExistsUintPtr(num *uint, list []*uint) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsUint64Ptr checks if given item exists in the list
func ExistsUint64Ptr(num *uint64, list []*uint64) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsUint32Ptr checks if given item exists in the list
func ExistsUint32Ptr(num *uint32, list []*uint32) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsUint16Ptr checks if given item exists in the list
func ExistsUint16Ptr(num *uint16, list []*uint16) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsUint8Ptr checks if given item exists in the list
func ExistsUint8Ptr(num *uint8, list []*uint8) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsStrPtr checks if given item exists in the list
func ExistsStrPtr(num *string, list []*string) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsBoolPtr checks if given item exists in the list
func ExistsBoolPtr(num *bool, list []*bool) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsFloat32Ptr checks if given item exists in the list
func ExistsFloat32Ptr(num *float32, list []*float32) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
}
// ExistsFloat64Ptr checks if given item exists in the list
func ExistsFloat64Ptr(num *float64, list []*float64) bool {
for _, v := range list {
if v == num {
return true
}
}
return false
} | fp/existsptr.go | 0.527073 | 0.400779 | existsptr.go | starcoder |
package neuralNetwork
import (
"fmt"
"math"
"gonum.org/v1/gonum/mat"
)
type activationStruct struct{}
// ActivationFunctions WIP
type ActivationFunctions interface {
Func(z, h *mat.Dense)
Grad(z, h, grad *mat.Dense)
}
type identityActivation struct{ activationStruct }
func (identityActivation) Func(z, h *mat.Dense) { h.Copy(z) }
func (identityActivation) Grad(z, h, grad *mat.Dense) {
matx{Dense: grad}.CopyApplied(h, func(h float64) float64 { return 1. })
}
type logisticActivation struct{ activationStruct }
func (logisticActivation) Func(z, h *mat.Dense) {
matx{Dense: h}.CopyApplied(z, func(z float64) float64 { return 1. / (1. + math.Exp(-z)) })
//h.Copy(matApply{Matrix: z, Func: func(z float64) float64 { return 1. / (1. + math.Exp(-z)) }})
}
func (logisticActivation) Grad(z, h, grad *mat.Dense) {
matx{Dense: grad}.CopyApplied(h, func(h float64) float64 { return h * (1. - h) })
}
type tanhActivation struct{ activationStruct }
func (tanhActivation) Func(z, h *mat.Dense) {
matx{Dense: h}.CopyApplied(z, math.Tanh)
}
func (tanhActivation) Grad(z, h, grad *mat.Dense) {
matx{Dense: grad}.CopyApplied(h, func(h float64) float64 { return 1. - h*h })
}
type reluActivation struct{ activationStruct }
func (reluActivation) Func(z, h *mat.Dense) {
matx{Dense: h}.CopyApplied(z, func(z float64) float64 { return math.Max(0, z) })
}
func (reluActivation) Grad(z, h, grad *mat.Dense) {
matx{Dense: grad}.CopyApplied(h, func(h float64) float64 {
if h <= 0 {
return 0.
}
return 1.
})
}
// SupportedActivations is a map[Sing]ActivationFunctions for the supproted activation functions (identity,logistic,tanh,relu)
var SupportedActivations = map[string]ActivationFunctions{
"identity": identityActivation{},
"logistic": logisticActivation{},
"tanh": tanhActivation{},
"relu": reluActivation{},
}
// NewActivation return ActivationFunctions (Func and Grad) from its name (identity,logistic,tanh,relu)
func NewActivation(name string) ActivationFunctions {
activation, ok := SupportedActivations[name]
if !ok {
panic(fmt.Errorf("unknown activation %s", name))
}
return activation
} | neural_network/activation.go | 0.705278 | 0.500732 | activation.go | starcoder |
package map180
import (
"bytes"
"fmt"
)
const (
svgPointQuery = `with p as (
select st_transScale(st_transform(st_setsrid(st_makepoint($1, $2), 4326), 3857), $3, $4, $5, $6) as pt
)
select round(ST_X(pt)), round(ST_Y(pt)*-1) from p`
)
type Marker struct {
longitude, latitude float64
drawSVG SVGMarker
x, y float64
svgColour string
size int
id, label, shortLabel string
}
// NewMarker returns a Marker to be drawn at longitude, latitude (EPSG:4327).
// Latitude must be in the range -85 to 85 otherwise the Marker will not be drawn.
// Defaults to a red triangle size 10.
func NewMarker(longitude, latitude float64, id, label, shortLabel string) Marker {
m := Marker{
longitude: longitude,
latitude: latitude,
drawSVG: SVGTriangle,
svgColour: "red",
size: 10,
id: id,
label: label,
shortLabel: shortLabel,
}
return m
}
func (m *Marker) SetSvgColour(colour string) {
m.svgColour = colour
}
func (m *Marker) SetSize(size int) {
m.size = size
}
// SetSVGMarker sets the SVGMarker func that will be used
// to draw the marker.
func (m *Marker) SetSVGMarker(f SVGMarker) {
m.drawSVG = f
}
type SVGMarker func(Marker, *bytes.Buffer)
// SVGTriangle is an SVGMarker func.
func SVGTriangle(m Marker, b *bytes.Buffer) {
w := int(m.size / 2)
h := w * 2
c := int(float64(h) * 0.33)
b.WriteString(fmt.Sprintf("<g id=\"%s\"><path d=\"M%d %d l%d 0 l-%d -%d l-%d %d Z\" fill=\"%s\" opacity=\"0.5\">",
m.id, int(m.x), int(m.y)+c, w, w, h, w, h, m.svgColour))
b.WriteString(`<desc>` + m.label + `.</desc>`)
b.WriteString(`<set attributeName="opacity" from="0.5" to="1" begin="mouseover" end="mouseout" dur="2s"/></path>`)
b.WriteString(fmt.Sprintf("<path d=\"M%d %d l%d 0 l-%d -%d l-%d %d Z\" stroke=\"%s\" stroke-width=\"1\" fill=\"none\" opacity=\"1\" /></g>",
int(m.x), int(m.y)+c, w, w, h, w, h, m.svgColour))
}
// puts the label or short label on the SVG image all at the same place.
// labels are made visible using mouseover on the marker with the same id.
func labelMarkers(m []Marker, x, y int, anchor string, fontSize int, short bool, b *bytes.Buffer) {
b.WriteString(`<g id="marker_labels">`)
for _, mr := range m {
b.WriteString(fmt.Sprintf("<text x=\"%d\" y=\"%d\" font-size=\"%d\" visibility=\"hidden\" text-anchor=\"%s\">", x, y, fontSize, anchor))
if short {
b.WriteString(mr.shortLabel)
} else {
b.WriteString(mr.label)
}
b.WriteString(fmt.Sprintf("<set attributeName=\"visibility\" from=\"hidden\" to=\"visible\" begin=\"%s.mouseover\" end=\"%s.mouseout\" dur=\"2s\"/>",
mr.id, mr.id))
b.WriteString(`</text>`)
}
b.WriteString(`</g>`)
}
func (m map3857) drawMarkers(markers []Marker, b *bytes.Buffer) (err error) {
for _, mr := range markers {
mr := mr // this prevents lint error
if mr.latitude <= 85.0 && mr.latitude >= -85.0 {
err = m.marker3857(&mr)
if err != nil {
return
}
mr.drawSVG(mr, b)
}
}
return
}
// sets x,y on 3857 from long lat on 4326. Allows for crossing 180.
func (m map3857) marker3857(marker *Marker) (err error) {
// map crosses 180 and the point is to the right
switch m.crossesCentral && marker.longitude > -180.0 && marker.longitude < 0.0 {
case true:
err = db.QueryRow(svgPointQuery, marker.longitude, marker.latitude, width3857-m.llx, m.yshift, m.dx, m.dx).Scan(&marker.x, &marker.y)
case false:
err = db.QueryRow(svgPointQuery, marker.longitude, marker.latitude, m.xshift, m.yshift, m.dx, m.dx).Scan(&marker.x, &marker.y)
}
return
} | vendor/github.com/GeoNet/kit/map180/marker.go | 0.688468 | 0.416559 | marker.go | starcoder |
package aliensim
import (
"bufio"
"fmt"
"io"
"strings"
)
// WorldMap contains all of the data structures relevant to mapping out our
// simulated world.
type WorldMap struct {
cityNames []string // The names of the cities in the order read from the input.
cities map[string]*City // A map of the cities read from the input (key=city name).
aliens []*Alien // A list of our aliens.
parsedLines uint64 // How many lines of the input have we parsed so far?
}
// NewEmptyWorldMap creates an empty world map, but initialises its structures
// so data can easily be added to it.
func NewEmptyWorldMap() *WorldMap {
return &WorldMap{
cityNames: []string{},
cities: map[string]*City{},
aliens: []*Alien{},
parsedLines: 0,
}
}
// ParseWorldMap takes the given input reader, scans it one line at a time,
// attempts to parse each line, and produces a WorldMap data structure on
// success, or an error on failure. A reader is used to allow for greater memory
// efficiency when supplying larger input files.
func ParseWorldMap(worldReader io.Reader) (*WorldMap, error) {
scanner := bufio.NewScanner(worldReader)
worldMap := NewEmptyWorldMap()
for scanner.Scan() {
line := scanner.Text()
// skip empty lines
if len(line) > 0 {
err := worldMap.ParseLine(line)
if err != nil {
return nil, err
}
}
}
if err := scanner.Err(); err != nil {
return nil, NewExtendedSimulationError(ErrFailedToScanWorldInput, "", err)
}
// now run through the map to ensure all the neighbours know about each other
for _, cityName := range worldMap.cityNames {
worldMap.cities[cityName].recomputeNeighbours()
}
return worldMap, nil
}
// ParseLine parses a single line from a world map file. On success, updates the
// world map. On failure, returns an error.
func (m *WorldMap) ParseLine(line string) error {
parts := strings.Split(line, " ")
if len(parts) < 1 {
return NewExtendedSimulationError(
ErrFailedToParseLine,
fmt.Sprintf(
"Too little map data on line %d (must at least be of the form \"CityName direction=OtherCity\").",
m.parsedLines+1,
),
nil,
)
}
cityName := parts[0]
city, exists := m.cities[cityName]
if !exists {
city = NewCity(cityName)
m.cities[cityName] = city
m.cityNames = append(m.cityNames, cityName)
}
for i := 1; i < len(parts); i++ {
dirParts := strings.Split(parts[i], "=")
if len(dirParts) != 2 {
return NewExtendedSimulationError(
ErrFailedToParseLine,
fmt.Sprintf(
"Invalid city location format on line %d (must be of the form \"direction=CityName\").",
m.parsedLines+1,
),
nil,
)
}
dir, otherCityName := strings.ToLower(dirParts[0]), dirParts[1]
otherCity, exists := m.cities[otherCityName]
if !exists {
otherCity = NewCity(otherCityName)
m.cities[otherCityName] = otherCity
m.cityNames = append(m.cityNames, otherCityName)
}
// now we situate the other city relative to our current one
err := city.LocateRelativeTo(otherCity, dir)
if err != nil {
return NewExtendedSimulationError(
ErrFailedToParseLine,
fmt.Sprintf(
"Parsing error on line %d.",
m.parsedLines+1,
),
err,
)
}
}
m.parsedLines++
return nil
}
// Render will generate a mapping similar to the input map format, but only
// containing cities that have not yet been destroyed.
func (m *WorldMap) Render() string {
var b strings.Builder
for _, cityName := range m.cityNames {
city := m.cities[cityName]
if !city.destroyed {
fmt.Fprintf(&b, "%s", cityName)
for dir, neighbour := range city.neighbours {
if neighbour != nil && !neighbour.destroyed {
fmt.Fprintf(&b, " %s=%s", strings.ToLower(directionNames[dir]), neighbour.name)
}
}
fmt.Fprintf(&b, "\n")
}
}
return b.String()
} | pkg/aliensim/worldmap.go | 0.589126 | 0.471588 | worldmap.go | starcoder |
package rel
type FunctionNode struct {
Expressions []Visitable
Alias *SqlLiteralNode
Distinct bool
BaseVisitable
}
type SumNode FunctionNode
type MaxNode FunctionNode
type MinNode FunctionNode
type AvgNode FunctionNode
func Sum(attr *AttributeNode) *SumNode {
return &SumNode{Expressions: []Visitable{attr}}
}
func Max(attr *AttributeNode) *MaxNode {
return &MaxNode{Expressions: []Visitable{attr}}
}
func Min(attr *AttributeNode) *MinNode {
return &MinNode{Expressions: []Visitable{attr}}
}
func Avg(attr *AttributeNode) *AvgNode {
return &AvgNode{Expressions: []Visitable{attr}}
}
func (node *FunctionNode) Over(visitable Visitable) *OverNode {
return windowPredicationOver(node, visitable)
}
func (node *FunctionNode) Eq(visitable Visitable) *EqualityNode {
return predicationEq(node, visitable)
}
func (node *FunctionNode) EqAny(visitables ...Visitable) *GroupingNode {
return predicationEqAny(node, visitables...)
}
func (node *FunctionNode) EqAll(visitables ...Visitable) *GroupingNode {
return predicationEqAll(node, visitables...)
}
func (node *FunctionNode) Lt(visitable Visitable) *LessThanNode {
return predicationLt(node, visitable)
}
func (node *FunctionNode) LtAny(visitables ...Visitable) *GroupingNode {
return predicationLtAny(node, visitables...)
}
func (node *FunctionNode) LtAll(visitables ...Visitable) *GroupingNode {
return predicationLtAll(node, visitables...)
}
func (node *FunctionNode) LtEq(visitable Visitable) *LessThanOrEqualNode {
return predicationLtEq(node, visitable)
}
func (node *FunctionNode) LtEqAny(visitables ...Visitable) *GroupingNode {
return predicationLtEqAny(node, visitables...)
}
func (node *FunctionNode) LtEqAll(visitables ...Visitable) *GroupingNode {
return predicationLtEqAll(node, visitables...)
}
func (node *FunctionNode) Gt(visitable Visitable) *GreaterThanNode {
return predicationGt(node, visitable)
}
func (node *FunctionNode) GtAny(visitables ...Visitable) *GroupingNode {
return predicationGtAny(node, visitables...)
}
func (node *FunctionNode) GtAll(visitables ...Visitable) *GroupingNode {
return predicationGtAll(node, visitables...)
}
func (node *FunctionNode) GtEq(visitable Visitable) *GreaterThanOrEqualNode {
return predicationGtEq(node, visitable)
}
func (node *FunctionNode) GtEqAny(visitables ...Visitable) *GroupingNode {
return predicationGtEqAny(node, visitables...)
}
func (node *FunctionNode) GtEqAll(visitables ...Visitable) *GroupingNode {
return predicationGtEqAll(node, visitables...)
}
func (node *FunctionNode) Count() *CountNode {
return predicationCount(node)
}
func (node *FunctionNode) Extract(literal SqlLiteralNode) *ExtractNode {
return predicationExtract(node, literal)
}
func (node *FunctionNode) In(visitables []Visitable) Visitable {
return predicationIn(node, visitables)
}
func (node *FunctionNode) InAny(visitableslices ...[]Visitable) Visitable {
return predicationInAny(node, visitableslices...)
}
func (node *FunctionNode) InAll(visitableslices ...[]Visitable) Visitable {
return predicationInAll(node, visitableslices...)
}
func (node *FunctionNode) NotIn(visitables []Visitable) Visitable {
return predicationNotIn(node, visitables)
}
func (node *FunctionNode) NotInAny(visitableslices ...[]Visitable) Visitable {
return predicationNotInAny(node, visitableslices...)
}
func (node *FunctionNode) NotInAll(visitableslices ...[]Visitable) Visitable {
return predicationNotInAll(node, visitableslices...)
}
func (node *FunctionNode) NotEq(visitable Visitable) *NotEqualNode {
return predicationNotEq(node, visitable)
}
func (node *FunctionNode) NotEqAny(visitables ...Visitable) *GroupingNode {
return predicationNotEqAny(node, visitables...)
}
func (node *FunctionNode) NotEqAll(visitables ...Visitable) *GroupingNode {
return predicationNotEqAll(node, visitables...)
}
func (node *FunctionNode) DoesNotMatch(literal SqlLiteralNode) *DoesNotMatchNode {
return predicationDoesNotMatch(node, literal)
}
func (node *FunctionNode) DoesNotMatchAny(literals ...SqlLiteralNode) *GroupingNode {
return predicationDoesNotMatchAny(node, literals...)
}
func (node *FunctionNode) DoesNotMatchAll(literals ...SqlLiteralNode) *GroupingNode {
return predicationDoesNotMatchAll(node, literals...)
}
func (node *FunctionNode) Matches(literal SqlLiteralNode) *MatchesNode {
return predicationMatches(node, literal)
}
func (node *FunctionNode) MatchesAny(literals ...SqlLiteralNode) *GroupingNode {
return predicationMatchesAny(node, literals...)
}
func (node *FunctionNode) MatchesAll(literals ...SqlLiteralNode) *GroupingNode {
return predicationMatchesAll(node, literals...)
} | function_node.go | 0.754192 | 0.463201 | function_node.go | starcoder |
package object
// Bitmap3D describes how a bitmap object should be represented in 3D world.
type Bitmap3D uint16
const (
bitmap3DBitmapNumberLowMask uint16 = 0x03FF
bitmap3DBitmapNumberHighMask uint16 = 0x8000
bitmap3DBitmapNumberMask = bitmap3DBitmapNumberLowMask | bitmap3DBitmapNumberHighMask
bitmap3DAnimationMask uint16 = 0x0400
bitmap3DRepeatMask uint16 = 0x0800
bitmap3DFrameNumberMask uint16 = 0x7000
// Bitmap3DBitmapNumberLimit is the maximum amount of bitmaps.
Bitmap3DBitmapNumberLimit uint16 = 0x07FF
// Bitmap3DFrameNumberLimit is the maximum amount of frames.
Bitmap3DFrameNumberLimit uint16 = 0x0007
)
// WithBitmapNumber returns a Bitmap3D with the given value.
func (bmp Bitmap3D) WithBitmapNumber(value uint16) Bitmap3D {
bitmapValue := value & bitmap3DBitmapNumberLowMask
if value >= Bitmap3DBitmapNumberLimit {
bitmapValue = bitmap3DBitmapNumberMask
} else if value > bitmap3DBitmapNumberLowMask {
bitmapValue |= bitmap3DBitmapNumberHighMask
}
return Bitmap3D((uint16(bmp) & ^bitmap3DBitmapNumberMask) | bitmapValue)
}
// BitmapNumber returns the number of bitmaps.
func (bmp Bitmap3D) BitmapNumber() uint16 {
return ((uint16(bmp) & bitmap3DBitmapNumberHighMask) >> 5) | (uint16(bmp) & bitmap3DBitmapNumberLowMask)
}
// WithFrameNumber returns a Bitmap3D with the given value.
func (bmp Bitmap3D) WithFrameNumber(value uint16) Bitmap3D {
frameValue := (value % (Bitmap3DFrameNumberLimit + 1)) << 12
return Bitmap3D((uint16(bmp) & ^bitmap3DFrameNumberMask) | frameValue)
}
// FrameNumber returns the frame number.
func (bmp Bitmap3D) FrameNumber() uint16 {
return (uint16(bmp) & bitmap3DFrameNumberMask) >> 12
}
// WithAnimation returns a Bitmap3D with the given value.
func (bmp Bitmap3D) WithAnimation(value bool) Bitmap3D {
animationValue := uint16(0)
if value {
animationValue = bitmap3DAnimationMask
}
return Bitmap3D((uint16(bmp) & ^bitmap3DAnimationMask) | animationValue)
}
// Animation returns whether this object is animated.
func (bmp Bitmap3D) Animation() bool {
return (uint16(bmp) & bitmap3DAnimationMask) != 0
}
// WithRepeat returns a Bitmap3D with the given value.
func (bmp Bitmap3D) WithRepeat(value bool) Bitmap3D {
repeatValue := uint16(0)
if value {
repeatValue = bitmap3DRepeatMask
}
return Bitmap3D((uint16(bmp) & ^bitmap3DRepeatMask) | repeatValue)
}
// Repeat returns whether this object repeats its animation.
func (bmp Bitmap3D) Repeat() bool {
return (uint16(bmp) & bitmap3DRepeatMask) != 0
} | ss1/content/object/Bitmap3D.go | 0.893629 | 0.638018 | Bitmap3D.go | starcoder |
package avl
import (
"errors"
"fmt"
"math"
ds "github.com/DavidCai1993/datastructures.go"
)
// Errors used by this package
var (
ErrEmptyTree = errors.New("avl: empty tree")
)
// Tree represents an AVL (Adelson, Velski & Landis) tree.
type Tree struct {
root *node
}
type node struct {
val ds.Comparable
parent *node
left *node
right *node
}
// New returns an new AVL tree instance.
func New() *Tree {
return &Tree{root: &node{}}
}
// Insert inserts a value to the tree.
// Time Complexity: O(logN)
func (t *Tree) Insert(val ds.Comparable) {
n := t.root.insert(val, nil)
// an unbalance tree should at least have a height of 2 .
if n.parent == nil || n.parent.parent == nil {
return
}
n.parent.parent.ensureBalance()
}
func (n *node) insert(val ds.Comparable, parent *node) *node {
if n.val == nil {
n.val = val
n.parent = parent
return n
}
c := val.Compare(n.val)
if c == 0 {
return n
} else if c < 0 {
n.left = ensureNode(n.left)
return n.left.insert(val, n)
} else {
n.right = ensureNode(n.right)
return n.right.insert(val, n)
}
}
func (n *node) ensureBalance() {
lh, rh := 0, 0
if !n.left.isNil() {
lh = n.left.getHeight(1)
}
if !n.right.isNil() {
rh = n.right.getHeight(1)
}
diff := int(math.Abs(float64(lh - rh)))
if diff == 1 || diff == 0 {
return
}
if diff != 2 {
panic(fmt.Errorf("invalid diff: %v", diff))
}
// need left rotation
if n.left.isNil() && !n.right.isNil() && !n.right.right.isNil() {
n.right.left = &node{val: n.val}
*n = *n.right
return
}
// need right rotation
if n.right.isNil() && !n.left.isNil() && !n.left.left.isNil() {
n.left.right = &node{val: n.val}
*n = *n.left
return
}
// need left-right rotation
if n.right.isNil() && !n.left.isNil() && !n.left.right.isNil() {
n.left.right.left = &node{val: n.left.val}
*n.left = *n.left.right
n.left.right = &node{val: n.val}
*n = *n.left
return
}
// need right-left rotation
if n.left.isNil() && !n.right.isNil() && !n.right.left.isNil() {
n.right.left.right = &node{val: n.right.val}
*n.right = *n.right.left
n.right.left = &node{val: n.val}
*n = *n.right
return
}
panic("invalid unbalanced situation")
}
func (n *node) isNil() bool {
return n == nil || n.val == nil
}
func (n *node) getHeight(h int) int {
hl, hr := h, h
if !n.left.isNil() {
hl = n.left.getHeight(h + 1)
}
if !n.right.isNil() {
hr = n.right.getHeight(h + 1)
}
if hl > hr {
return hl
}
return hr
}
// FindMin returns the value of the minimum node.
// Time Complexity: O(logN)
func (t Tree) FindMin() ds.Comparable {
return t.root.findMin()
}
func (n node) findMin() ds.Comparable {
if n.left == nil {
return n.val
}
return n.left.findMin()
}
// FindMax returns the value of the maximum node.
// Time Complexity: O(logN)
func (t Tree) FindMax() ds.Comparable {
return t.root.findMax()
}
func (n node) findMax() ds.Comparable {
if n.right == nil {
return n.val
}
return n.right.findMax()
}
// Find checks whether the given value is this tree.
// Time Complexity: O(logN)
func (t Tree) Find(val ds.Comparable) bool {
n := t.root.find(val)
if n != nil {
return true
}
return false
}
func (n *node) find(val ds.Comparable) *node {
c := val.Compare(n.val)
if c == 0 {
return n
}
if c < 0 {
if n.left != nil {
return n.left.find(val)
}
} else {
if n.right != nil {
return n.right.find(val)
}
}
return nil
}
func ensureNode(n *node) *node {
if n == nil {
n = &node{}
}
return n
} | avl-tree/avl.go | 0.845815 | 0.435781 | avl.go | starcoder |
package integration
// CloneAST creates a deep clone of the input.
func CloneAST(in AST) AST {
if in == nil {
return nil
}
switch in := in.(type) {
case BasicType:
return in
case Bytes:
return CloneBytes(in)
case InterfaceContainer:
return CloneInterfaceContainer(in)
case InterfaceSlice:
return CloneInterfaceSlice(in)
case *Leaf:
return CloneRefOfLeaf(in)
case LeafSlice:
return CloneLeafSlice(in)
case *NoCloneType:
return CloneRefOfNoCloneType(in)
case *RefContainer:
return CloneRefOfRefContainer(in)
case *RefSliceContainer:
return CloneRefOfRefSliceContainer(in)
case *SubImpl:
return CloneRefOfSubImpl(in)
case ValueContainer:
return CloneValueContainer(in)
case ValueSliceContainer:
return CloneValueSliceContainer(in)
default:
// this should never happen
return nil
}
}
// EqualsAST does deep equals between the two objects.
func EqualsAST(inA, inB AST) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case BasicType:
b, ok := inB.(BasicType)
if !ok {
return false
}
return a == b
case Bytes:
b, ok := inB.(Bytes)
if !ok {
return false
}
return EqualsBytes(a, b)
case InterfaceContainer:
b, ok := inB.(InterfaceContainer)
if !ok {
return false
}
return EqualsInterfaceContainer(a, b)
case InterfaceSlice:
b, ok := inB.(InterfaceSlice)
if !ok {
return false
}
return EqualsInterfaceSlice(a, b)
case *Leaf:
b, ok := inB.(*Leaf)
if !ok {
return false
}
return EqualsRefOfLeaf(a, b)
case LeafSlice:
b, ok := inB.(LeafSlice)
if !ok {
return false
}
return EqualsLeafSlice(a, b)
case *NoCloneType:
b, ok := inB.(*NoCloneType)
if !ok {
return false
}
return EqualsRefOfNoCloneType(a, b)
case *RefContainer:
b, ok := inB.(*RefContainer)
if !ok {
return false
}
return EqualsRefOfRefContainer(a, b)
case *RefSliceContainer:
b, ok := inB.(*RefSliceContainer)
if !ok {
return false
}
return EqualsRefOfRefSliceContainer(a, b)
case *SubImpl:
b, ok := inB.(*SubImpl)
if !ok {
return false
}
return EqualsRefOfSubImpl(a, b)
case ValueContainer:
b, ok := inB.(ValueContainer)
if !ok {
return false
}
return EqualsValueContainer(a, b)
case ValueSliceContainer:
b, ok := inB.(ValueSliceContainer)
if !ok {
return false
}
return EqualsValueSliceContainer(a, b)
default:
// this should never happen
return false
}
}
// CloneSubIface creates a deep clone of the input.
func CloneSubIface(in SubIface) SubIface {
if in == nil {
return nil
}
switch in := in.(type) {
case *SubImpl:
return CloneRefOfSubImpl(in)
default:
// this should never happen
return nil
}
}
// EqualsSubIface does deep equals between the two objects.
func EqualsSubIface(inA, inB SubIface) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *SubImpl:
b, ok := inB.(*SubImpl)
if !ok {
return false
}
return EqualsRefOfSubImpl(a, b)
default:
// this should never happen
return false
}
}
// CloneBytes creates a deep clone of the input.
func CloneBytes(n Bytes) Bytes {
res := make(Bytes, 0, len(n))
copy(res, n)
return res
}
// EqualsBytes does deep equals between the two objects.
func EqualsBytes(a, b Bytes) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// CloneInterfaceContainer creates a deep clone of the input.
func CloneInterfaceContainer(n InterfaceContainer) InterfaceContainer {
return *CloneRefOfInterfaceContainer(&n)
}
// EqualsInterfaceContainer does deep equals between the two objects.
func EqualsInterfaceContainer(a, b InterfaceContainer) bool {
return true
}
// CloneInterfaceSlice creates a deep clone of the input.
func CloneInterfaceSlice(n InterfaceSlice) InterfaceSlice {
res := make(InterfaceSlice, 0, len(n))
for _, x := range n {
res = append(res, CloneAST(x))
}
return res
}
// EqualsInterfaceSlice does deep equals between the two objects.
func EqualsInterfaceSlice(a, b InterfaceSlice) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsAST(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfLeaf creates a deep clone of the input.
func CloneRefOfLeaf(n *Leaf) *Leaf {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfLeaf does deep equals between the two objects.
func EqualsRefOfLeaf(a, b *Leaf) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.v == b.v
}
// CloneLeafSlice creates a deep clone of the input.
func CloneLeafSlice(n LeafSlice) LeafSlice {
res := make(LeafSlice, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfLeaf(x))
}
return res
}
// EqualsLeafSlice does deep equals between the two objects.
func EqualsLeafSlice(a, b LeafSlice) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfLeaf(a[i], b[i]) {
return false
}
}
return true
}
// CloneRefOfNoCloneType creates a deep clone of the input.
func CloneRefOfNoCloneType(n *NoCloneType) *NoCloneType {
return n
}
// EqualsRefOfNoCloneType does deep equals between the two objects.
func EqualsRefOfNoCloneType(a, b *NoCloneType) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.v == b.v
}
// CloneRefOfRefContainer creates a deep clone of the input.
func CloneRefOfRefContainer(n *RefContainer) *RefContainer {
if n == nil {
return nil
}
out := *n
out.ASTType = CloneAST(n.ASTType)
out.ASTImplementationType = CloneRefOfLeaf(n.ASTImplementationType)
return &out
}
// EqualsRefOfRefContainer does deep equals between the two objects.
func EqualsRefOfRefContainer(a, b *RefContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.NotASTType == b.NotASTType &&
EqualsAST(a.ASTType, b.ASTType) &&
EqualsRefOfLeaf(a.ASTImplementationType, b.ASTImplementationType)
}
// CloneRefOfRefSliceContainer creates a deep clone of the input.
func CloneRefOfRefSliceContainer(n *RefSliceContainer) *RefSliceContainer {
if n == nil {
return nil
}
out := *n
out.ASTElements = CloneSliceOfAST(n.ASTElements)
out.NotASTElements = CloneSliceOfInt(n.NotASTElements)
out.ASTImplementationElements = CloneSliceOfRefOfLeaf(n.ASTImplementationElements)
return &out
}
// EqualsRefOfRefSliceContainer does deep equals between the two objects.
func EqualsRefOfRefSliceContainer(a, b *RefSliceContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSliceOfAST(a.ASTElements, b.ASTElements) &&
EqualsSliceOfInt(a.NotASTElements, b.NotASTElements) &&
EqualsSliceOfRefOfLeaf(a.ASTImplementationElements, b.ASTImplementationElements)
}
// CloneRefOfSubImpl creates a deep clone of the input.
func CloneRefOfSubImpl(n *SubImpl) *SubImpl {
if n == nil {
return nil
}
out := *n
out.inner = CloneSubIface(n.inner)
out.field = CloneRefOfBool(n.field)
return &out
}
// EqualsRefOfSubImpl does deep equals between the two objects.
func EqualsRefOfSubImpl(a, b *SubImpl) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSubIface(a.inner, b.inner) &&
EqualsRefOfBool(a.field, b.field)
}
// CloneValueContainer creates a deep clone of the input.
func CloneValueContainer(n ValueContainer) ValueContainer {
return *CloneRefOfValueContainer(&n)
}
// EqualsValueContainer does deep equals between the two objects.
func EqualsValueContainer(a, b ValueContainer) bool {
return a.NotASTType == b.NotASTType &&
EqualsAST(a.ASTType, b.ASTType) &&
EqualsRefOfLeaf(a.ASTImplementationType, b.ASTImplementationType)
}
// CloneValueSliceContainer creates a deep clone of the input.
func CloneValueSliceContainer(n ValueSliceContainer) ValueSliceContainer {
return *CloneRefOfValueSliceContainer(&n)
}
// EqualsValueSliceContainer does deep equals between the two objects.
func EqualsValueSliceContainer(a, b ValueSliceContainer) bool {
return EqualsSliceOfAST(a.ASTElements, b.ASTElements) &&
EqualsSliceOfInt(a.NotASTElements, b.NotASTElements) &&
EqualsSliceOfRefOfLeaf(a.ASTImplementationElements, b.ASTImplementationElements)
}
// CloneRefOfInterfaceContainer creates a deep clone of the input.
func CloneRefOfInterfaceContainer(n *InterfaceContainer) *InterfaceContainer {
if n == nil {
return nil
}
out := *n
out.v = n.v
return &out
}
// EqualsRefOfInterfaceContainer does deep equals between the two objects.
func EqualsRefOfInterfaceContainer(a, b *InterfaceContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneSliceOfAST creates a deep clone of the input.
func CloneSliceOfAST(n []AST) []AST {
res := make([]AST, 0, len(n))
for _, x := range n {
res = append(res, CloneAST(x))
}
return res
}
// EqualsSliceOfAST does deep equals between the two objects.
func EqualsSliceOfAST(a, b []AST) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsAST(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfInt creates a deep clone of the input.
func CloneSliceOfInt(n []int) []int {
res := make([]int, 0, len(n))
copy(res, n)
return res
}
// EqualsSliceOfInt does deep equals between the two objects.
func EqualsSliceOfInt(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// CloneSliceOfRefOfLeaf creates a deep clone of the input.
func CloneSliceOfRefOfLeaf(n []*Leaf) []*Leaf {
res := make([]*Leaf, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfLeaf(x))
}
return res
}
// EqualsSliceOfRefOfLeaf does deep equals between the two objects.
func EqualsSliceOfRefOfLeaf(a, b []*Leaf) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfLeaf(a[i], b[i]) {
return false
}
}
return true
}
// EqualsRefOfBool does deep equals between the two objects.
func EqualsRefOfBool(a, b *bool) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
// CloneRefOfBool creates a deep clone of the input.
func CloneRefOfBool(n *bool) *bool {
if n == nil {
return nil
}
out := *n
return &out
}
// CloneRefOfValueContainer creates a deep clone of the input.
func CloneRefOfValueContainer(n *ValueContainer) *ValueContainer {
if n == nil {
return nil
}
out := *n
out.ASTType = CloneAST(n.ASTType)
out.ASTImplementationType = CloneRefOfLeaf(n.ASTImplementationType)
return &out
}
// EqualsRefOfValueContainer does deep equals between the two objects.
func EqualsRefOfValueContainer(a, b *ValueContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.NotASTType == b.NotASTType &&
EqualsAST(a.ASTType, b.ASTType) &&
EqualsRefOfLeaf(a.ASTImplementationType, b.ASTImplementationType)
}
// CloneRefOfValueSliceContainer creates a deep clone of the input.
func CloneRefOfValueSliceContainer(n *ValueSliceContainer) *ValueSliceContainer {
if n == nil {
return nil
}
out := *n
out.ASTElements = CloneSliceOfAST(n.ASTElements)
out.NotASTElements = CloneSliceOfInt(n.NotASTElements)
out.ASTImplementationElements = CloneSliceOfRefOfLeaf(n.ASTImplementationElements)
return &out
}
// EqualsRefOfValueSliceContainer does deep equals between the two objects.
func EqualsRefOfValueSliceContainer(a, b *ValueSliceContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSliceOfAST(a.ASTElements, b.ASTElements) &&
EqualsSliceOfInt(a.NotASTElements, b.NotASTElements) &&
EqualsSliceOfRefOfLeaf(a.ASTImplementationElements, b.ASTImplementationElements)
} | go/tools/asthelpergen/integration/clone.go | 0.644225 | 0.482429 | clone.go | starcoder |
package runtime
import (
"math"
"github.com/brettbuddin/shaden/dsp"
"github.com/brettbuddin/shaden/lisp"
)
func hzFn(sampleRate int) func(lisp.List) (interface{}, error) {
return func(args lisp.List) (interface{}, error) {
if err := lisp.CheckArityEqual(args, 1); err != nil {
return nil, err
}
switch v := args[0].(type) {
case float64:
return dsp.Frequency(v, sampleRate), nil
case int:
return dsp.Frequency(float64(v), sampleRate), nil
case dsp.Pitch:
return v, nil
case string:
return dsp.ParsePitch(v, sampleRate)
case lisp.Keyword:
return dsp.ParsePitch(string(v), sampleRate)
default:
return 0, lisp.ArgExpectError(lisp.AcceptTypes(lisp.TypeString, lisp.TypeInt, lisp.TypeFloat), 1)
}
}
}
func msFn(sampleRate int) func(lisp.List) (interface{}, error) {
return func(args lisp.List) (interface{}, error) {
if err := lisp.CheckArityEqual(args, 1); err != nil {
return nil, err
}
switch v := args[0].(type) {
case float64:
return dsp.Duration(v, sampleRate), nil
case int:
return dsp.Duration(float64(v), sampleRate), nil
default:
return 0, lisp.ArgExpectError(lisp.AcceptTypes(lisp.TypeInt, lisp.TypeFloat), 1)
}
}
}
func bpmFn(sampleRate int) func(lisp.List) (interface{}, error) {
return func(args lisp.List) (interface{}, error) {
if err := lisp.CheckArityEqual(args, 1); err != nil {
return nil, err
}
switch v := args[0].(type) {
case float64:
return dsp.BPM(v, sampleRate), nil
case int:
return dsp.BPM(float64(v), sampleRate), nil
default:
return 0, lisp.ArgExpectError(lisp.AcceptTypes(lisp.TypeInt, lisp.TypeFloat), 1)
}
}
}
func dbFn(args lisp.List) (interface{}, error) {
if err := lisp.CheckArityEqual(args, 1); err != nil {
return nil, err
}
switch v := args[0].(type) {
case float64:
return math.Pow(10, 0.05*v), nil
case int:
return math.Pow(10, 0.05*float64(v)), nil
default:
return 0, lisp.ArgExpectError(lisp.AcceptTypes(lisp.TypeInt, lisp.TypeFloat), 1)
}
} | runtime/value.go | 0.524395 | 0.41117 | value.go | starcoder |
package cism
/*
HistoryRecord represents a past state change and the event that caused it.
*/
type HistoryRecord struct {
State State // state that was transitioned to
Event Event // event that triggered the state change
}
/*
Machine is a state machine driven by a state transition table. All state
transitions are managed by the state machine.
*/
type Machine struct {
States StateTransitionTable // states and events the machine uses for transitions
curr State
done bool
endevt *Event
hist []HistoryRecord
initial State
started bool
}
/*
Start will start the machine at the given state. It will return an error if the
state transition table was not set on the machine. It will return an error if
the given state does not exist in the state transition table. It will return an
error if the machine has been stopped. It will return an error if the machine
has already been started.
*/
func (m *Machine) Start(s State) error {
if len(m.States) == 0 {
return &ErrMissingStates{"no states set"}
}
if _, ok := m.States[s]; !ok {
return &ErrStateNotDefined{s, "start state not defined in states"}
}
if m.done {
return &ErrMachineStopped{m.endevt, "machine is done and cannot be started"}
}
if m.started {
return &ErrMachineStarted{"machine has already started"}
}
m.curr = s
m.done = false
m.initial = s
m.started = true
return nil
}
/*
Send will attempt to begin a state change based on the given event and the
current state. It will return an error if the machine has not been started. It
will return an error if the machine has been stopped. It will return an error
if no transition is defined for the given event and current state. The
transition lifecycle hooks will be invoked to determine if the machine can
complete the state change. If the transition guard fails, a failed state change
handler will be invoked. If the transition guard passes, a successful state
change handler will be invoked. If the transition is marked as final, the
machine will be stopped after the state change. If the state change succeeds,
the current history and triggering event will be pushed into a history log.
*/
func (m *Machine) Send(e Event) error {
if !m.started {
return &ErrMachineNotStarted{"machine has not started"}
}
if m.done {
return &ErrMachineStopped{m.endevt, "machine is done and not accepting transitions"}
}
if tran := m.States.GetTransition(m.curr, e); tran != nil {
m.transition(tran, e)
} else {
return &ErrMissingTransition{m.curr, e, "no transition found for event in current state"}
}
return nil
}
/*
Stop marks the machine as stopped and will accept no more state changes.
*/
func (m *Machine) Stop() {
m.stop()
}
/*
Reset marks the machine as not stopped and not started. It will return an error
if the machine has not been stopped. The history log will be cleared on a
successful reset. The machine can be started again after it has been reset.
*/
func (m *Machine) Reset() error {
if !m.done {
return &ErrMachineNotStopped{"machine has not stopped"}
}
m.done = false
m.endevt = nil
m.hist = nil
m.curr = m.initial
m.started = false
return nil
}
/*
Current returns the current state the machine is in.
*/
func (m *Machine) Current() State {
return m.curr
}
/*
History returns a copy of the machine's state change history log.
*/
func (m *Machine) History() []HistoryRecord {
cpyhist := make([]HistoryRecord, len(m.hist))
copy(cpyhist, m.hist)
return cpyhist
}
func (m *Machine) transition(tran *Transition, e Event) {
currstate := m.curr
if tran.Guard == nil || tran.Guard(currstate, e) {
m.hist = append(m.hist, HistoryRecord{currstate, e})
m.curr = tran.To
if tran.OnSuccess != nil {
tran.OnSuccess(currstate, e)
}
if tran.IsFinal {
m.stop()
}
} else if tran.OnFail != nil {
tran.OnFail(currstate, e)
}
}
func (m *Machine) stop() {
histlen := len(m.hist)
if histlen > 0 {
m.endevt = &(m.hist[histlen-1].Event)
}
m.done = true
} | machine.go | 0.665628 | 0.585338 | machine.go | starcoder |
package image
import (
"image"
"image/color"
"golang.org/x/image/draw"
)
const (
// skips image interpolation
ScaleSkip = -1
// initial image interpolation algorithm
ScaleOld = 0
// nearest neighbour interpolation
ScaleNearestNeighbour = 1
// bilinear interpolation
ScaleBilinear = 2
)
func Resize(scaleType int, fn Format, w int, h int, packedW int, vw int, vh int, bpp int, data []byte, out *image.RGBA) {
// !to implement own image interfaces img.Pix = bytes[]
src := image.NewRGBA(image.Rect(0, 0, w, h))
toRgba(fn, w, h, packedW, bpp, data, src)
// !to do set it once instead switching on each iteration
// !to do skip resize if w=vw h=vh
switch scaleType {
case ScaleSkip:
skip(fn, w, h, packedW, vw, vh, bpp, data, src, out)
case ScaleNearestNeighbour:
draw.NearestNeighbor.Scale(out, out.Bounds(), src, src.Bounds(), draw.Src, nil)
//nearest(fn, w, h, packedW, vw, vh, bpp, data, src, out)
case ScaleBilinear:
draw.ApproxBiLinear.Scale(out, out.Bounds(), src, src.Bounds(), draw.Src, nil)
//bilinear(fn, w, h, packedW, vw, vh, bpp, data, src, out)
case ScaleOld:
fallthrough
default:
old(fn, w, h, packedW, vw, vh, bpp, data, src, out)
}
}
func old(fn Format, w int, h int, packedW int, vw int, vh int, bpp int, data []byte, _ *image.RGBA, out *image.RGBA) {
seek := 0
scaleWidth := float64(vw) / float64(w)
scaleHeight := float64(vh) / float64(h)
for y := 0; y < h; y++ {
y2 := int(float64(y) * scaleHeight)
for x := 0; x < packedW; x++ {
x2 := int(float64(x) * scaleWidth)
if x2 < vw {
out.Set(x2, y2, fn(data, seek))
}
seek += bpp
}
}
}
func skip(fn Format, w int, h int, packedW int, _ int, _ int, bpp int, data []byte, _ *image.RGBA, out *image.RGBA) {
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
index := (y * packedW) + x
index *= bpp
out.Set(x, y, fn(data, index))
}
}
}
func nearest(fn Format, w int, h int, packedW int, vw int, vh int, bpp int, data []byte, _ *image.RGBA, out *image.RGBA) {
xRatio := ((w << 16) / vw) + 1
yRatio := ((h << 16) / vh) + 1
for y := 0; y < vh; y++ {
y2 := (y * yRatio) >> 16
for x := 0; x < vw; x++ {
x2 := (x * xRatio) >> 16
index := (y2 * packedW) + x2
index *= bpp
out.Set(x, y, fn(data, index))
}
}
}
// This implementation has some color bleeding issues
func bilinear(fn Format, w int, h int, packedW int, vw int, vh int, bpp int, data []byte, _ *image.RGBA, out *image.RGBA) {
xRatio := float64(w-1) / float64(vw)
yRatio := float64(h-1) / float64(vh)
for y := 0; y < vh; y++ {
y2 := int(yRatio * float64(y))
for x := 0; x < vw; x++ {
x2 := int(xRatio * float64(x))
w := (xRatio * float64(x)) - float64(x2)
h := (yRatio * float64(y)) - float64(y2)
index := (y2 * packedW) + x2
a := fn(data, index*bpp)
b := fn(data, (index+1)*bpp)
c := fn(data, (index+packedW)*bpp)
d := fn(data, (index+packedW+1)*bpp)
out.Set(x, y, color.RGBA{
// don't sink the boat
R: byte(float64(a.R)*(1-w)*(1-h) + float64(b.R)*w*(1-h) + float64(c.R)*h*(1-w) + float64(d.R)*w*h),
G: byte(float64(a.G)*(1-w)*(1-h) + float64(b.G)*w*(1-h) + float64(c.G)*h*(1-w) + float64(d.G)*w*h),
B: byte(float64(a.B)*(1-w)*(1-h) + float64(b.B)*w*(1-h) + float64(c.B)*h*(1-w) + float64(d.B)*w*h),
//A: byte(float64(a.A)*(1-w)*(1-h) + float64(b.A)*w*(1-h) + float64(c.A)*h*(1-w) + float64(d.A)*w*h),
})
}
}
}
func toRgba(fn Format, w int, h int, packedW int, bpp int, data []byte, image *image.RGBA) {
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
index := (y*packedW + x) * bpp
c := fn(data, index)
i := (y-image.Rect.Min.Y)*image.Stride + (x-image.Rect.Min.X)*4
s := image.Pix[i : i+4 : i+4]
s[0] = c.R
s[1] = c.G
s[2] = c.B
s[3] = c.A
}
}
} | pkg/emulator/libretro/image/scale.go | 0.574514 | 0.483466 | scale.go | starcoder |
package mlpack
/*
#cgo CFLAGS: -I./capi -Wall
#cgo LDFLAGS: -L. -lmlpack_go_kmeans
#include <capi/kmeans.h>
#include <stdlib.h>
*/
import "C"
import "gonum.org/v1/gonum/mat"
type KmeansOptionalParam struct {
Algorithm string
AllowEmptyClusters bool
InPlace bool
InitialCentroids *mat.Dense
KillEmptyClusters bool
LabelsOnly bool
MaxIterations int
Percentage float64
RefinedStart bool
Samplings int
Seed int
Verbose bool
}
func KmeansOptions() *KmeansOptionalParam {
return &KmeansOptionalParam{
Algorithm: "naive",
AllowEmptyClusters: false,
InPlace: false,
InitialCentroids: nil,
KillEmptyClusters: false,
LabelsOnly: false,
MaxIterations: 1000,
Percentage: 0.02,
RefinedStart: false,
Samplings: 100,
Seed: 0,
Verbose: false,
}
}
/*
This program performs K-Means clustering on the given dataset. It can return
the learned cluster assignments, and the centroids of the clusters. Empty
clusters are not allowed by default; when a cluster becomes empty, the point
furthest from the centroid of the cluster with maximum variance is taken to
fill that cluster.
Optionally, the Bradley and Fayyad approach ("Refining initial points for
k-means clustering", 1998) can be used to select initial points by specifying
the "RefinedStart" parameter. This approach works by taking random samplings
of the dataset; to specify the number of samplings, the "Samplings" parameter
is used, and to specify the percentage of the dataset to be used in each
sample, the "Percentage" parameter is used (it should be a value between 0.0
and 1.0).
There are several options available for the algorithm used for each Lloyd
iteration, specified with the "Algorithm" option. The standard O(kN)
approach can be used ('naive'). Other options include the Pelleg-Moore
tree-based algorithm ('pelleg-moore'), Elkan's triangle-inequality based
algorithm ('elkan'), Hamerly's modification to Elkan's algorithm ('hamerly'),
the dual-tree k-means algorithm ('dualtree'), and the dual-tree k-means
algorithm using the cover tree ('dualtree-covertree').
The behavior for when an empty cluster is encountered can be modified with the
"AllowEmptyClusters" option. When this option is specified and there is a
cluster owning no points at the end of an iteration, that cluster's centroid
will simply remain in its position from the previous iteration. If the
"KillEmptyClusters" option is specified, then when a cluster owns no points at
the end of an iteration, the cluster centroid is simply filled with DBL_MAX,
killing it and effectively reducing k for the rest of the computation. Note
that the default option when neither empty cluster option is specified can be
time-consuming to calculate; therefore, specifying either of these parameters
will often accelerate runtime.
Initial clustering assignments may be specified using the "InitialCentroids"
parameter, and the maximum number of iterations may be specified with the
"MaxIterations" parameter.
As an example, to use Hamerly's algorithm to perform k-means clustering with
k=10 on the dataset data, saving the centroids to centroids and the
assignments for each point to assignments, the following command could be
used:
// Initialize optional parameters for Kmeans().
param := mlpack.KmeansOptions()
centroids, assignments := mlpack.Kmeans(data, 10, param)
To run k-means on that same dataset with initial centroids specified in
initial with a maximum of 500 iterations, storing the output centroids in
final the following command may be used:
// Initialize optional parameters for Kmeans().
param := mlpack.KmeansOptions()
param.InitialCentroids = initial
param.MaxIterations = 500
final, _ := mlpack.Kmeans(data, 10, param)
Input parameters:
- clusters (int): Number of clusters to find (0 autodetects from
initial centroids).
- input (mat.Dense): Input dataset to perform clustering on.
- Algorithm (string): Algorithm to use for the Lloyd iteration
('naive', 'pelleg-moore', 'elkan', 'hamerly', 'dualtree', or
'dualtree-covertree'). Default value 'naive'.
- AllowEmptyClusters (bool): Allow empty clusters to be persist.
- InPlace (bool): If specified, a column containing the learned cluster
assignments will be added to the input dataset file. In this case,
--output_file is overridden. (Do not use in Python.)
- InitialCentroids (mat.Dense): Start with the specified initial
centroids.
- KillEmptyClusters (bool): Remove empty clusters when they occur.
- LabelsOnly (bool): Only output labels into output file.
- MaxIterations (int): Maximum number of iterations before k-means
terminates. Default value 1000.
- Percentage (float64): Percentage of dataset to use for each refined
start sampling (use when --refined_start is specified). Default value
0.02.
- RefinedStart (bool): Use the refined initial point strategy by
Bradley and Fayyad to choose initial points.
- Samplings (int): Number of samplings to perform for refined start
(use when --refined_start is specified). Default value 100.
- Seed (int): Random seed. If 0, 'std::time(NULL)' is used. Default
value 0.
- Verbose (bool): Display informational messages and the full list of
parameters and timers at the end of execution.
Output parameters:
- centroid (mat.Dense): If specified, the centroids of each cluster
will be written to the given file.
- output (mat.Dense): Matrix to store output labels or labeled data
to.
*/
func Kmeans(clusters int, input *mat.Dense, param *KmeansOptionalParam) (*mat.Dense, *mat.Dense) {
resetTimers()
enableTimers()
disableBacktrace()
disableVerbose()
restoreSettings("K-Means Clustering")
// Detect if the parameter was passed; set if so.
setParamInt("clusters", clusters)
setPassed("clusters")
// Detect if the parameter was passed; set if so.
gonumToArmaMat("input", input)
setPassed("input")
// Detect if the parameter was passed; set if so.
if param.Algorithm != "naive" {
setParamString("algorithm", param.Algorithm)
setPassed("algorithm")
}
// Detect if the parameter was passed; set if so.
if param.AllowEmptyClusters != false {
setParamBool("allow_empty_clusters", param.AllowEmptyClusters)
setPassed("allow_empty_clusters")
}
// Detect if the parameter was passed; set if so.
if param.InPlace != false {
setParamBool("in_place", param.InPlace)
setPassed("in_place")
}
// Detect if the parameter was passed; set if so.
if param.InitialCentroids != nil {
gonumToArmaMat("initial_centroids", param.InitialCentroids)
setPassed("initial_centroids")
}
// Detect if the parameter was passed; set if so.
if param.KillEmptyClusters != false {
setParamBool("kill_empty_clusters", param.KillEmptyClusters)
setPassed("kill_empty_clusters")
}
// Detect if the parameter was passed; set if so.
if param.LabelsOnly != false {
setParamBool("labels_only", param.LabelsOnly)
setPassed("labels_only")
}
// Detect if the parameter was passed; set if so.
if param.MaxIterations != 1000 {
setParamInt("max_iterations", param.MaxIterations)
setPassed("max_iterations")
}
// Detect if the parameter was passed; set if so.
if param.Percentage != 0.02 {
setParamDouble("percentage", param.Percentage)
setPassed("percentage")
}
// Detect if the parameter was passed; set if so.
if param.RefinedStart != false {
setParamBool("refined_start", param.RefinedStart)
setPassed("refined_start")
}
// Detect if the parameter was passed; set if so.
if param.Samplings != 100 {
setParamInt("samplings", param.Samplings)
setPassed("samplings")
}
// Detect if the parameter was passed; set if so.
if param.Seed != 0 {
setParamInt("seed", param.Seed)
setPassed("seed")
}
// Detect if the parameter was passed; set if so.
if param.Verbose != false {
setParamBool("verbose", param.Verbose)
setPassed("verbose")
enableVerbose()
}
// Mark all output options as passed.
setPassed("centroid")
setPassed("output")
// Call the mlpack program.
C.mlpackKmeans()
// Initialize result variable and get output.
var centroidPtr mlpackArma
centroid := centroidPtr.armaToGonumMat("centroid")
var outputPtr mlpackArma
output := outputPtr.armaToGonumMat("output")
// Clear settings.
clearSettings()
// Return output(s).
return centroid, output
} | kmeans.go | 0.685529 | 0.409368 | kmeans.go | starcoder |
package garkov
import (
"math/rand"
"time"
"github.com/mickuehl/garkov/dictionary"
)
// WordCount the number of occurences of a word from the word vector
type WordCount struct {
Idx int
Count int
}
// WordChain is the main structure of the model. It represents a prefix and all its suffixes.
type WordChain struct {
Prefix []int // arrary of words forming the prefix. Index into the dictionaries word vector
Words map[string]WordCount // the collection of suffixes and their count
}
// Markov wraps all data of a markov-chain into one
type Markov struct {
Name string // name of the model
Depth int // prefix size
Chain map[string]WordChain // the prefixes mapped to the word chains
Dict *dictionary.Dictionary // the dictionary used in the model
Start [][]int // array of start prefixes
Language string
Random *rand.Rand
}
// New creates an empty markov model.
func New(name string, depth int) *Markov {
m := Markov{
Name: name,
Depth: depth,
Chain: make(map[string]WordChain),
Dict: dictionary.New(name),
Start: make([][]int, 0),
Language: "en",
Random: rand.New(rand.NewSource(time.Now().UnixNano())),
}
return &m
}
// Sentence creates a new sentence based on the markov-chain
func (m *Markov) Sentence(minWords, maxWords int) string {
sentence := make([]dictionary.Word, m.Depth)
// select a first prefix to start with
_prefix := m.Start[m.Random.Intn(len(m.Start))]
for i := range _prefix {
w, _ := m.Dict.GetAt(_prefix[i])
sentence[i] = w
}
prefix := sentence
n := 0
for {
// get the next word, until we get a STOP word
suffix := m.SuffixFor(prefix)
sentence = append(sentence, suffix)
if suffix.Type == dictionary.STOP && n >= minWords {
break
}
// new prefix
prefix = sentence[len(sentence)-m.Depth:]
n = n + 1
if n > maxWords {
break // emergency break
}
}
return wordsToSentence(sentence)
}
// Update adds a prefix + suffix to the markov model
func (m *Markov) Update(prefix []dictionary.Word, suffix dictionary.Word) {
_prefix := wordsToPrefixString(prefix)
chain, found := m.Chain[_prefix]
if !found {
chain = WordChain{
Prefix: wordsToIndexArray(prefix),
Words: make(map[string]WordCount),
}
}
// add the word to the sequence
chain.AddWord(suffix)
// update the model
m.Chain[_prefix] = chain
}
// Close writes the model to disc
func (m *Markov) Close() {
m.Dict.Close()
}
// SuffixFor returns a word that succeedes a given prefix
func (m *Markov) SuffixFor(prefix []dictionary.Word) dictionary.Word {
// lookup the word chain
_prefix := wordsToPrefixString(prefix)
chain, found := m.Chain[_prefix]
if found {
idx := 0
max := m.Random.Intn(len(chain.Words))
i := 0
// FIXME poor implementation of a random lookup ... need a better way
for p := range chain.Words {
if i == max {
idx = chain.Words[p].Idx
break
}
i = i + 1
}
word, _ := m.Dict.GetAt(idx)
return word
}
// FIXME we should never get here ...
return dictionary.Word{}
}
// AddWord updates a word chain
func (s *WordChain) AddWord(w dictionary.Word) {
words, found := s.Words[w.Word]
if found {
words.Count = words.Count + 1
} else {
words = WordCount{
Idx: w.Idx,
Count: 1,
}
}
// update
s.Words[w.Word] = words
} | markov.go | 0.572723 | 0.564459 | markov.go | starcoder |
package barcode
import (
"fmt"
"image"
"image/color"
"github.com/LLKennedy/imagetemplate/v3/render"
"golang.org/x/tools/godoc/vfs"
)
// Component implements the Component interface for images.
type Component struct {
/*
NamedPropertiesMap maps user/application variables to properties of the component.
This field is filled automatically by VerifyAndSetJSONData, then used in
SetNamedProperties to determine whether a variable being passed in is relevant to this
component.
For example, map[string][]string{"websiteURL": []string{"content"}} would indicate that
the user specified variable "websiteURL" will fill the Content property.
*/
NamedPropertiesMap map[string][]string
// Content is the data which will be encoded as a barcode.
Content string
// Type is the sort of barcode to encode, such as QR, PDF, or two of five.
Type render.BarcodeType
/*
TopLeft is the coordinates of the top-left corner of the rendered barcode (including
background) relative to the top-left corner of the canvas.
*/
TopLeft image.Point
// Width is the width of the barcode (including background).
Width int
// Height is the height of the barcode (including background).
Height int
// DataColour is the colour which will fill the data channel.
DataColour color.NRGBA
// BackgroundColour is the colour which will fill the background channel.
BackgroundColour color.NRGBA
// Extra is additional information required by certain barcode types.
Extra render.BarcodeExtraData
}
type barcodeFormat struct {
Content string `json:"content"`
Type string `json:"barcodeType"`
TopLeftX string `json:"topLeftX"`
TopLeftY string `json:"topLeftY"`
Width string `json:"width"`
Height string `json:"height"`
DataColour struct {
Red string `json:"R"`
Green string `json:"G"`
Blue string `json:"B"`
Alpha string `json:"A"`
} `json:"dataColour"`
BackgroundColour struct {
Red string `json:"R"`
Green string `json:"G"`
Blue string `json:"B"`
Alpha string `json:"A"`
} `json:"backgroundColour"`
}
// Write draws a barcode on the canvas.
func (component Component) Write(canvas render.Canvas) (render.Canvas, error) {
if len(component.NamedPropertiesMap) != 0 {
return canvas, fmt.Errorf("cannot draw barcode, not all named properties are set: %v", component.NamedPropertiesMap)
}
c := canvas
var err error
c, err = c.Barcode(component.Type, []byte(component.Content), component.Extra, component.TopLeft, component.Width, component.Height, component.DataColour, component.BackgroundColour)
if err != nil {
return canvas, err
}
return c, nil
}
// SetNamedProperties processes the named properties and sets them into the barcode properties.
func (component Component) SetNamedProperties(properties render.NamedProperties) (render.Component, error) {
c := component
var err error
c.NamedPropertiesMap, err = render.StandardSetNamedProperties(properties, component.NamedPropertiesMap, (&c).delegatedSetProperties)
if err != nil {
return component, err
}
return c, nil
}
// GetJSONFormat returns the JSON structure of a barcode component.
func (component Component) GetJSONFormat() interface{} {
return &barcodeFormat{}
}
// VerifyAndSetJSONData processes the data parsed from JSON and uses it to set barcode properties and fill the named properties map.
func (component Component) VerifyAndSetJSONData(data interface{}) (render.Component, render.NamedProperties, error) {
c := component
props := make(render.NamedProperties)
stringStruct, ok := data.(*barcodeFormat)
if !ok {
return component, props, fmt.Errorf("failed to convert returned data to component properties")
}
return c.parseJSONFormat(stringStruct, props)
}
func init() {
for _, name := range []string{"barcode", "bar", "code", "Barcode", "BARCODE", "BAR", "Bar Code", "bar code"} {
render.RegisterComponent(name, func(vfs.FileSystem) render.Component { return Component{} })
}
} | components/barcode/barcode.go | 0.734215 | 0.427755 | barcode.go | starcoder |
package curve1174
import (
"github.com/dterei/gotsc"
"math"
"math/rand"
"sort"
"time"
)
const testsNumber = 1 + percentilesNumber + 1
const enoughMeasurements = 10000
const percentilesNumber = 100
type timer struct {
startCount uint64
endCount uint64
}
func (t *timer) Start() {
t.startCount = gotsc.BenchStart()
}
func (t *timer) End() {
t.endCount = gotsc.BenchEnd()
}
func (t *timer) count() uint64 {
return t.endCount - t.startCount
}
func preparePercentiles(ticks []uint64) (percentiles []uint64) {
percentiles = make([]uint64, percentilesNumber)
ticks = append([]uint64{}, ticks...)
sort.Slice(ticks, func(i, j int) bool {
return ticks[i] < ticks[j]
})
for i := 0; i < percentilesNumber; i++ {
index := (1 - math.Pow(0.5, 10*(float64(i)+1)/percentilesNumber)) * float64(len(ticks))
percentiles[i] = ticks[int(index)]
}
return percentiles
}
type ctx struct {
stats [101]stat
percentiles []uint64
}
func (ctx *ctx) measure(testMethod func(timer *timer, random bool, vector int), randomVectors, iterationCount int) float64 {
rand.Seed(time.Now().UnixNano())
//var stats [testsNumber]stat
ticks := make([]uint64, iterationCount)
tests := make([]int, iterationCount)
classes := make([]int, iterationCount)
for i := 0; i < iterationCount; i++ {
tests[i] = rand.Intn(randomVectors)
classes[i] = rand.Intn(2)
}
for i := 0; i < iterationCount; i++ {
timer := new(timer)
testMethod(timer, classes[i] == 1, tests[i])
ticks[i] = timer.count()
}
if ctx.percentiles == nil {
ctx.percentiles = preparePercentiles(ticks)
}
for i := 0; i < iterationCount; i++ {
ctx.stats[0].push(ticks[i], classes[i])
for crop := 0; crop < percentilesNumber; crop++ {
if ticks[i] < ctx.percentiles[crop] {
ctx.stats[crop+1].push(ticks[i], classes[i])
}
}
}
max := 0.0
for i := 0; i < len(ctx.stats); i++ {
if ctx.stats[i].count[0]+ctx.stats[i].count[1] < 10000 {
continue
}
tt := math.Abs(ctx.stats[i].compute())
if tt > max {
max = tt
}
}
return max
}
type stat struct {
mean [2]float64
m2 [2]float64
count [2]float64
}
func (s *stat) push(ticks uint64, class int) {
s.count[class]++
delta := float64(ticks) - s.mean[class]
s.mean[class] += delta / s.count[class]
s.m2[class] += delta * (float64(ticks) - s.mean[class])
}
func (s *stat) compute() float64 {
v0 := s.m2[0] / (s.count[0] - 1)
v1 := s.m2[1] / (s.count[1] - 1)
num := s.mean[0] - s.mean[1]
den := math.Sqrt(v0/s.count[0] + v1/s.count[1])
t := num / den
return t
} | fixture.go | 0.526586 | 0.407864 | fixture.go | starcoder |
package rules
import (
"gonum.org/v1/gonum/mat"
"github.com/pkg/errors"
)
func createVarList(variables []VariableFieldName, varCache map[VariableFieldName]VariableValuePair) ([]float64, error) {
var variableVect []float64
for _, v := range variables {
if val, varOk := varCache[v]; varOk {
variableVect = append(variableVect, val.Values...)
} else {
return nil, errors.Errorf("Variable: '%v' not found in variable cache %v", v, varCache)
}
}
variableVect = append(variableVect, 1)
return variableVect, nil
}
func ruleMul(variableVect []float64, ApplicableMatrix mat.Dense) *mat.VecDense {
nRows, _ := ApplicableMatrix.Dims()
variableFormalVect := mat.NewVecDense(len(variableVect), variableVect)
actual := make([]float64, nRows)
c := mat.NewVecDense(nRows, actual)
c.MulVec(&ApplicableMatrix, variableFormalVect)
return c
}
func genResult(aux mat.VecDense, c *mat.VecDense) ([]bool, error) {
var resultVect []bool
nRows, _ := c.Dims()
for i := 0; i < nRows; i++ {
res := false
switch interpret := aux.AtVec(i); interpret {
case 0:
res = c.AtVec(i) == 0
case 1:
res = c.AtVec(i) > 0
case 2:
res = c.AtVec(i) >= 0
case 3:
res = c.AtVec(i) != 0
default:
return nil, errors.Errorf("At auxiliary vector entry: '%v' aux value outside of 0-3: "+
"'%v' was found", i, interpret)
}
resultVect = append(resultVect, res)
}
return resultVect, nil
}
func genRealResult(aux mat.VecDense, c *mat.VecDense) ([]bool, float64, error) {
var resultVect []bool
nRows, _ := c.Dims()
outputVal := 0.0
for i := 0; i < nRows; i++ {
res := true
switch interpret := aux.AtVec(i); interpret {
case 0:
res = c.AtVec(i) == 0
case 1:
res = c.AtVec(i) > 0
case 2:
res = c.AtVec(i) >= 0
case 3:
res = c.AtVec(i) != 0
case 4:
outputVal = c.AtVec(i)
default:
return nil, 0.0, errors.Errorf("At auxiliary vector entry: '%v' aux value outside of 0-3: "+
"'%v' was found", i, interpret)
}
resultVect = append(resultVect, res)
}
return resultVect, outputVal, nil
}
func checkForFalse(resultVect []bool) bool {
for _, v := range resultVect {
if !v {
return false
}
}
return true
}
func checkForCode4(auxVect mat.VecDense) bool {
nRows, _ := auxVect.Dims()
for i := 0; i < nRows; i++ {
if auxVect.AtVec(i) == 4.0 {
return true
}
}
return false
}
// basicBooleanRuleEvaluator implements a basic version of the Matrix rule evaluator, provides single boolean output (and error if present)
func basicBooleanRuleEvaluator(rule RuleMatrix, variableCache map[VariableFieldName]VariableValuePair) (bool, error) {
variableVect, err := createVarList(rule.RequiredVariables, variableCache)
if err != nil {
return false, &RuleError{
ErrorType: VariableCacheDidNotHaveAllRequiredVariables,
Err: errors.Errorf("Variable cache did not contain all required variables"),
}
}
//Checking dimensions line up
_, nCols := rule.ApplicableMatrix.Dims()
if nCols != len(variableVect) {
return false, &RuleError{
ErrorType: VariableVectDimsDoNotMatchRuleMatrix,
Err: errors.Errorf("Variable Vector Dimensions do not match the rule matrix"),
}
}
c := ruleMul(variableVect, rule.ApplicableMatrix)
resultVect, err := genResult(rule.AuxiliaryVector, c)
if err != nil {
return false, &RuleError{
ErrorType: AuxVectorCodeOutOfRange,
Err: err,
}
}
return checkForFalse(resultVect), nil
}
// basicRealValuedRuleEvaluator implements real valued rule evaluation in the same form as the boolean one
func basicRealValuedRuleEvaluator(rule RuleMatrix, variableCache map[VariableFieldName]VariableValuePair) (bool, float64, error) {
variableVect, err := createVarList(rule.RequiredVariables, variableCache)
if err != nil {
return false, 0, &RuleError{
ErrorType: VariableCacheDidNotHaveAllRequiredVariables,
Err: errors.Errorf("Variable cache did not contain all required variables"),
}
}
//Checking dimensions line up
_, nCols := rule.ApplicableMatrix.Dims()
if nCols != len(variableVect) {
return false, 0, &RuleError{
ErrorType: VariableVectDimsDoNotMatchRuleMatrix,
Err: errors.Errorf("Variable Vector Dimensions do not match the rule matrix"),
}
}
c := ruleMul(variableVect, rule.ApplicableMatrix)
resultVect, outputVal, err := genRealResult(rule.AuxiliaryVector, c)
if err != nil {
return false, 0, &RuleError{
ErrorType: AuxVectorCodeOutOfRange,
Err: err,
}
}
return checkForFalse(resultVect), outputVal, nil
}
// basicLinkedRuleEvaluator evaluates linked rules using the above two evaluators
func basicLinkedRuleEvaluator(rule RuleMatrix, childRule RuleMatrix, variableCache map[VariableFieldName]VariableValuePair) (bool, error) {
link := rule.Link
if !link.Linked {
return basicBooleanRuleEvaluator(rule, variableCache)
}
if link.LinkType == ParentFailAutoRulePass {
parentPass, parentErr := basicBooleanRuleEvaluator(rule, variableCache)
if parentErr != nil {
return false, errors.Errorf("Parent Rule errored out with : %v", parentErr)
}
if !parentPass {
return true, nil
}
childPass, childErr := basicBooleanRuleEvaluator(childRule, variableCache)
if childErr != nil {
return false, errors.Errorf("Parent Rule errored out with : %v", childErr)
}
return childPass, nil
}
return false, errors.Errorf("Unrecognised rule linking %v", link.LinkType)
}
// RuleEvaluationReturn provides a wrapped for the results of a rule evaluation
type RuleEvaluationReturn struct {
RulePasses bool
IsRealOutput bool
RealOutputVal float64
EvalError error
}
func EvaluateRuleFromCaches(ruleName string, rulesCache map[string]RuleMatrix, variableCache map[VariableFieldName]VariableValuePair) RuleEvaluationReturn {
if rule, ok := rulesCache[ruleName]; ok {
if checkAllVariablesAvailable(rule.RequiredVariables, variableCache) {
auxVect := rule.AuxiliaryVector
linked := rule.Link.Linked
if linked {
if childRule, isInCache := rulesCache[rule.Link.LinkedRule]; isInCache {
eval, err := basicLinkedRuleEvaluator(rule, childRule, variableCache)
return RuleEvaluationReturn{
RulePasses: eval,
IsRealOutput: false,
RealOutputVal: 0,
EvalError: err,
}
}
return RuleEvaluationReturn{
RulePasses: false,
IsRealOutput: false,
RealOutputVal: 0,
EvalError: &RuleError{
ErrorType: ChildRuleNotFound,
Err: errors.Errorf("Child rule was not found in cache"),
},
}
}
isRealValued := checkForCode4(auxVect)
if isRealValued {
eval, res, err := basicRealValuedRuleEvaluator(rule, variableCache)
return RuleEvaluationReturn{
RulePasses: eval,
IsRealOutput: true,
RealOutputVal: res,
EvalError: err,
}
}
eval, err := basicBooleanRuleEvaluator(rule, variableCache)
return RuleEvaluationReturn{
RulePasses: eval,
IsRealOutput: false,
RealOutputVal: 0,
EvalError: err,
}
}
return RuleEvaluationReturn{
RulePasses: false,
IsRealOutput: false,
RealOutputVal: 0,
EvalError: &RuleError{
ErrorType: VariableCacheDidNotHaveAllRequiredVariables,
Err: errors.Errorf("Provided variable cache did not contain all required variables"),
},
}
}
return RuleEvaluationReturn{
RulePasses: false,
IsRealOutput: false,
RealOutputVal: 0,
EvalError: &RuleError{
ErrorType: RuleNotInAvailableRulesCache,
Err: errors.Errorf("Rule was not found in the given cache"),
},
}
} | internal/common/rules/basicruleevaluator.go | 0.600774 | 0.465387 | basicruleevaluator.go | starcoder |
package sky
import (
"log"
"github.com/chewxy/math32"
"github.com/go-gl/gl/v3.3-core/gl"
"github.com/go-gl/mathgl/mgl32"
"github.com/benanders/mineral/camera"
"github.com/benanders/mineral/math"
"github.com/benanders/mineral/render"
"github.com/benanders/mineral/world"
)
// The temperature throughout the world (influences the sky, fog, and sunrise
// colors slightly). Individual biomes will have different temperatures in the
// future.
const worldTemperature float32 = 0.5
// Sky is responsible for drawing the background sky in the game.
type Sky struct {
skyPlane skyPlane
sunrisePlane sunrisePlane
}
// RenderInfo stores a bunch of information required by the sky renderer in
// order to draw the sky.
type RenderInfo struct {
WorldTime float32
Camera *camera.Camera
RenderRadius int
LookDir mgl32.Vec3
}
// SkyPlane stores information about the blue ceiling plane and the dark blue
// void plane present in the sky.
type skyPlane struct {
skyVao, skyVbo uint32
voidVao, voidVbo uint32
program uint32
mvpUnf int32
colorUnf int32
fogColorUnf int32
farPlaneUnf int32
}
// SunrisePlane stores information about the red/orange sunrise/sunset plane
// present in the sky during sunrise and sunset.
type sunrisePlane struct {
vao, vbo uint32
program uint32
mvpUnf int32
sunriseColorUnf int32
}
// New creates a new sky renderer instance.
func New() *Sky {
return &Sky{newSkyPlane(), newSunrisePlane()}
}
// Destroy releases all the resources allocated by the sky renderer.
func (s *Sky) Destroy() {
s.skyPlane.destroy()
s.sunrisePlane.destroy()
}
// NewSkyPlane builds the vertex data and allocates the required OpenGL
// resources for the sky plane.
func newSkyPlane() skyPlane {
// Create the program
program, err := render.LoadShaders(
"shaders/skyVert.glsl",
"shaders/skyFrag.glsl")
if err != nil {
log.Fatalln(err)
}
gl.UseProgram(program)
// Cache the locations of uniforms
mvpUnf := gl.GetUniformLocation(program, gl.Str("mvp\x00"))
colorUnf := gl.GetUniformLocation(program, gl.Str("skyColor\x00"))
fogColorUnf := gl.GetUniformLocation(program, gl.Str("fogColor\x00"))
farPlaneUnf := gl.GetUniformLocation(program, gl.Str("farPlane\x00"))
// Create the sky plane
skyVertices := [...]float32{
-384.0, 16.0, -384.0, // The size of the sky plane must be larger
384.0, 16.0, -384.0, // than the far plane distance, or else the
-384.0, 16.0, 384.0, // sky will look noticeably square.
384.0, 16.0, 384.0,
}
skyVao, skyVbo := genPlane(program, skyVertices[:])
// Create the void plane
voidVertices := [...]float32{
-384.0, -16.0, -384.0, // Swap the winding order from the sky plane so
-384.0, -16.0, 384.0, // GL_CULL_FACE still works.
384.0, -16.0, -384.0,
384.0, -16.0, 384.0,
}
voidVao, voidVbo := genPlane(program, voidVertices[:])
// Create the object holding it all together
return skyPlane{skyVao, skyVbo, voidVao, voidVbo, program, mvpUnf,
colorUnf, fogColorUnf, farPlaneUnf}
}
// Generates the sky or void plane VAO and VBO, and enables the vertex
// attributes.
func genPlane(program uint32, vertices []float32) (vao, vbo uint32) {
// Create the VAO
gl.GenVertexArrays(1, &vao)
gl.BindVertexArray(vao)
// Create the VBO and populate it with data
gl.GenBuffers(1, &vbo)
gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(&vertices[0]),
gl.STATIC_DRAW)
// Enable the position attribute
posAttr := uint32(gl.GetAttribLocation(program, gl.Str("position\x00")))
gl.EnableVertexAttribArray(posAttr)
gl.VertexAttribPointer(posAttr, 3, gl.FLOAT, false, 0, gl.PtrOffset(0))
return
}
// Destroy releases all the resources allocated by the sky plane.
func (p *skyPlane) destroy() {
gl.DeleteProgram(p.program)
gl.DeleteVertexArrays(1, &p.skyVao)
gl.DeleteVertexArrays(1, &p.voidVao)
gl.DeleteBuffers(1, &p.skyVbo)
gl.DeleteBuffers(1, &p.voidVbo)
}
// NewSunrisePlane builds the vertex data and allocates the required OpenGL
// resources for the sunrise plane.
func newSunrisePlane() sunrisePlane {
// Create the program
program, err := render.LoadShaders(
"shaders/sunriseVert.glsl",
"shaders/sunriseFrag.glsl")
if err != nil {
log.Fatalln(err)
}
gl.UseProgram(program)
// Cache uniform locations
mvpUnf := gl.GetUniformLocation(program, gl.Str("mvp\x00"))
colorUnf := gl.GetUniformLocation(program, gl.Str("sunriseColor\x00"))
// Create the VAO
var vao uint32
gl.GenVertexArrays(1, &vao)
gl.BindVertexArray(vao)
// Create the VBO and populate it with data
vertices := genSunrisePlaneVertices()
var vbo uint32
gl.GenBuffers(1, &vbo)
gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
gl.BufferData(gl.ARRAY_BUFFER, 4*18*4, gl.Ptr(&vertices[0]), gl.STATIC_DRAW)
// Enable the position attribute
posAttr := uint32(gl.GetAttribLocation(program, gl.Str("position\x00")))
gl.EnableVertexAttribArray(posAttr)
gl.VertexAttribPointer(posAttr, 3, gl.FLOAT, false, 4*4,
gl.PtrOffset(0))
// stride = 4*4 = 4 float32s (position, alpha multiplier) * 4 bytes each
// Enable the alpha multiplier attribute
alphaAttr := uint32(gl.GetAttribLocation(program, gl.Str("alpha\x00")))
gl.EnableVertexAttribArray(alphaAttr)
gl.VertexAttribPointer(alphaAttr, 1, gl.FLOAT, false, 4*4,
gl.PtrOffset(3*4))
// stride = 4*4 = 4 float32s (position, alpha multiplier) * 4 bytes each
// offset = 3*4 = 3 float32s (position) * 4 bytes each
return sunrisePlane{vao, vbo, program, mvpUnf, colorUnf}
}
// GenSunrisePlaneVertices builds the vertex data array for the sunrise plane.
func genSunrisePlaneVertices() []float32 {
// Generate the vertex data
var vertices [18 * 4]float32
vertices[0] = 0.0 // position.x
vertices[1] = 100.0 // position.y
vertices[2] = 0.0 // position.z
vertices[3] = 1.0 // alpha multiplier
for i := 0; i <= 16; i++ {
// The original minecraft source modulates the z component by the alpha
// of the current sunrise/sunset color. Since the alpha changes every
// frame, we do this in the vertex shader to reduce runtime overhead
angle := float32(i) * 2.0 * math32.Pi / 16.0
sin, cos := math32.Sincos(angle)
vertices[(i+1)*4] = sin * 120.0 // position.x
vertices[(i+1)*4+1] = cos * 120.0 // position.y
vertices[(i+1)*4+2] = -cos * 40.0 // position.z
vertices[(i+1)*4+3] = 0.0 // alpha multiplier
}
return vertices[:]
}
// Destroy releases all the resources allocated by the sunrise plane.
func (p *sunrisePlane) destroy() {
gl.DeleteProgram(p.program)
gl.DeleteVertexArrays(1, &p.vao)
gl.DeleteBuffers(1, &p.vbo)
}
// Color represents a color as red, green, and blue color components.
type color struct {
r, g, b float32
}
// HsvToRgb converts a color from HSV color space to RGB color space.
func hsvToRgb(h, s, v float32) color {
option := int(h*6.0) % 6
factor := h*6.0 - float32(option)
a := v * (1.0 - s)
b := v * (1.0 - factor*s)
c := v * (1.0 - (1.0-factor)*s)
switch option {
case 0:
return color{v, c, a}
case 1:
return color{b, v, a}
case 2:
return color{a, v, c}
case 3:
return color{a, b, v}
case 4:
return color{c, a, v}
case 5:
return color{v, a, b}
}
return color{}
}
// GetCelestialAngle returns a value proportional to the angle that the sun
// makes with the horizon. It's between 0 and 1, and can be thought of
// conceptually as the time of day.
func getCelestialAngle(worldTime float32) float32 {
// Since world time is measured in days, the progress through the current
// day is just the fractional part of `worldTime`
dayProgress := worldTime - float32(uint64(worldTime))
// We subtract 0.25 so that the start of the day (worldTime = 0) represents
// sunrise, rather than midnight
dayProgress -= 0.25
// Wrap the day progress to some value between 0 and 1
if dayProgress < 0.0 {
dayProgress += 1.0
} else if dayProgress > 1.0 {
dayProgress -= 1.0
}
// The magical celestial angle calculation from the Minecraft source
celestialAngle := 0.5 * (1.0 - math32.Cos(dayProgress*math32.Pi))
return dayProgress + (celestialAngle-dayProgress)/3.0
}
// GetSkyColor returns the color used for the sky plane, and is normally a
// slightly darker blue than the fog color.
func getSkyColor(celestialAngle float32) color {
// Calculate the base color based on the temperature
temperature := math.Clamp(worldTemperature/3.0, -1.0, 1.0)
base := hsvToRgb(
0.62222224-temperature*0.05,
0.5+temperature*0.1,
1.0)
// Calculate the brightness multiplier
brightness := math32.Cos(celestialAngle*math32.Pi*2.0)*2.0 + 0.5
brightness = math.Clamp(brightness, 0.0, 1.0)
// Calculate the final color
return color{
base.r * brightness,
base.g * brightness,
base.b * brightness,
}
}
// GetVoidColor returns the color used for the void plane, and is normally a
// deeper blue than the sky color.
func getVoidColor(celestialAngle float32) color {
// Calculate the void plane color based off the sky color
skyColor := getSkyColor(celestialAngle)
return color{
skyColor.r*0.2 + 0.04,
skyColor.g*0.2 + 0.04,
skyColor.b*0.6 + 0.1,
}
}
// GetSunriseColor returns the color used for the sunrise/sunset.
func getSunriseColor(celestialAngle float32) (color, float32) {
// Calculate time of day multiplier
multiplier := math32.Cos(celestialAngle * 2.0 * math32.Pi)
// Only apply the sunrise/sunset color if the time of day is right
if multiplier >= -0.4 && multiplier <= 0.4 {
phase := multiplier*1.25 + 0.5
sqrtAlpha := math32.Sin(phase*math32.Pi)*0.99 + 0.01
return color{
phase*0.3 + 0.7,
phase*phase*0.7 + 0.2,
0.2,
}, sqrtAlpha * sqrtAlpha
}
return color{}, 0.0
}
// GetFogColor returns the background fog color, including the influence of
// looking towards the sun during sunrise or sunset.
func getFogColor(celestialAngle float32, renderRadius int,
lookDir mgl32.Vec3) color {
// Calculate the brightness multiplier
brightness := math32.Cos(celestialAngle*math32.Pi*2.0)*2.0 + 0.5
brightness = math.Clamp(brightness, 0.0, 1.0)
// Calculate the fog color using some magic numbers
fogColor := color{
0.7529412 * (brightness*0.94 + 0.06),
0.84705883 * (brightness*0.94 + 0.06),
1.0 * (brightness*0.91 + 0.09),
}
// Modify the fog with the sunrise/sunset color
if renderRadius >= 4 {
// Get a vector whose direction depends on whether this is a sunrise or
// sunset
sinAngle := math32.Sin(celestialAngle * math32.Pi * 2.0)
var sunDir mgl32.Vec3
if sinAngle < 0.0 {
sunDir = mgl32.Vec3{-1.0, 0.0, 0.0}
} else {
sunDir = mgl32.Vec3{1.0, 0.0, 0.0}
}
// Calculate the look direction multiplier (player facing more towards
// the sunrise/sunset makes the sunrise/sunset orange look more intense)
lookMultiplier := math32.Max(lookDir.Dot(sunDir), 0.0)
// Get the sunrise/sunset color
sunriseColor, alpha := getSunriseColor(celestialAngle)
// Modify the fog color based on the sunrise/sunset color
lookMultiplier *= alpha
fogColor.r = math.Lerp(fogColor.r, sunriseColor.r, lookMultiplier)
fogColor.g = math.Lerp(fogColor.g, sunriseColor.g, lookMultiplier)
fogColor.b = math.Lerp(fogColor.b, sunriseColor.b, lookMultiplier)
}
// Modify the fog color with the sky color based on the render radius
sky := getSkyColor(celestialAngle)
fractionalRadius := float32(renderRadius) / float32(world.MaxRenderRadius)
sightFactor := 1.0 - math32.Pow(fractionalRadius*0.75+0.25, 0.25)
fogColor.r += (sky.r - fogColor.r) * sightFactor
fogColor.g += (sky.g - fogColor.g) * sightFactor
fogColor.b += (sky.b - fogColor.b) * sightFactor
return fogColor
}
// RenderBackground clears the screen to the current fog color.
func (s *Sky) renderBackground(info RenderInfo) {
// Get the current fog color
celestialAngle := getCelestialAngle(info.WorldTime)
fogColor := getFogColor(celestialAngle, info.RenderRadius, info.LookDir)
// Clear the screen
gl.ClearColor(fogColor.r, fogColor.g, fogColor.b, 1.0)
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
}
// RenderSky draws the sky plane using the current sky and fog colors, at a
// fixed distance from the player (so that the sky always looks infinitely far
// away).
func (p *skyPlane) renderSky(info RenderInfo) {
// Set the current shader program to the sky plane program
gl.UseProgram(p.program)
// Set the shader's MVP uniform to the camera's orientation matrix
gl.UniformMatrix4fv(p.mvpUnf, 1, false, &info.Camera.Orientation[0])
// Set the color of the sky plane to the sky color
celestialAngle := getCelestialAngle(info.WorldTime)
skyColor := getSkyColor(celestialAngle)
gl.Uniform3f(p.colorUnf, skyColor.r, skyColor.g, skyColor.b)
// Set the fog color uniform
fogColor := getFogColor(celestialAngle, info.RenderRadius, info.LookDir)
gl.Uniform3f(p.fogColorUnf, fogColor.r, fogColor.g, fogColor.b)
// Set the far plane distance, used for fog calculations
gl.Uniform1f(p.farPlaneUnf, info.Camera.FarPlane)
// Render the sky plane
gl.BindVertexArray(p.skyVao)
gl.DrawArrays(gl.TRIANGLE_STRIP, 0, 4)
}
// RenderSky draws the void plane using the current void and fog colors, at a
// fixed distance from the player.
func (p *skyPlane) renderVoid(info RenderInfo) {
// Only change the sky color uniform from rendering the sky plane above,
// to the void color
celestialAngle := getCelestialAngle(info.WorldTime)
voidColor := getVoidColor(celestialAngle)
gl.Uniform3f(p.colorUnf, voidColor.r, voidColor.g, voidColor.b)
// Render the sky plane
gl.BindVertexArray(p.voidVao)
gl.DrawArrays(gl.TRIANGLE_STRIP, 0, 4)
}
// Render draws the sunrise/sunset plane using the current sunrise/sunset
// colors.
func (p *sunrisePlane) render(info RenderInfo) {
// Set the current shader program to the sunrise plane program
gl.UseProgram(p.program)
// Calculate a rotation matrix based on whether it's currently sunrise or
// sunset, to change where the sunrise plane appears in the sky
celestialAngle := getCelestialAngle(info.WorldTime)
var eastOrWest float32
if math32.Sin(celestialAngle*math32.Pi*2.0) < 0.0 {
eastOrWest = math32.Pi
} else {
eastOrWest = 0.0
}
todRot := mgl32.HomogRotate3D(eastOrWest, mgl32.Vec3{0.0, 0.0, 1.0})
// Set the shader's MVP uniform to the camera's orientation matrix
xRot := mgl32.HomogRotate3D(math32.Pi/2.0, mgl32.Vec3{1.0, 0.0, 0.0})
zRot := mgl32.HomogRotate3D(math32.Pi/2.0, mgl32.Vec3{0.0, 0.0, 1.0})
mvp := info.Camera.Orientation.Mul4(xRot.Mul4(todRot.Mul4(zRot)))
gl.UniformMatrix4fv(p.mvpUnf, 1, false, &mvp[0])
// Set the sunrise color uniform
color, alpha := getSunriseColor(celestialAngle)
gl.Uniform4f(p.sunriseColorUnf, color.r, color.g, color.b, alpha)
// Render the sunrise plane with linear alpha blending enabled
gl.Enable(gl.BLEND)
gl.BlendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ZERO)
// Render the sunrise plane
gl.BindVertexArray(p.vao)
gl.DrawArrays(gl.TRIANGLE_FAN, 0, 18)
// Reset the OpenGL state
gl.Disable(gl.BLEND)
}
// Render clears the color buffer to the fog color, renders the sky plane,
// sunrise/sunset plane, sun and moon, stars, and void plane.
func (s *Sky) Render(info RenderInfo) {
// Enable some OpenGL configuration. Having depth testing enabled seems to
// ruin the alpha blending of the sunrise plane
gl.Enable(gl.CULL_FACE)
// Render components of the sky separately
s.renderBackground(info)
s.skyPlane.renderSky(info)
s.skyPlane.renderVoid(info)
s.sunrisePlane.render(info)
// Reset the OpenGL configuration
gl.Disable(gl.CULL_FACE)
} | sky/sky.go | 0.738103 | 0.441974 | sky.go | starcoder |
package def
import (
"math/rand"
"math"
"fmt"
)
const (
Pit = iota
Normal = iota
)
type Point struct {
PosX int
PosY int
}
type Perception struct {
Smell bool
Breeze bool
Shine bool
Shock bool
Scream bool
}
type Square struct {
terrain int
hasGold bool
hasWump bool
hasHunter bool
}
type World struct {
squares [][]Square
sizex int
sizey int
}
/*
Stringer for Square
One may want to optimize this "thing", so I'll explain why it is this
way (as of NOW):
1: I could not spare 2 characters (the space must be there so I'll
not count it) to represent something, so I would only use one
character.
2: There is a way for the hunter to be over the gold, and for the
wumpus to be over the gold.
This made so that I had to draw a different symbol for when the
wumpus or hunter were together with the gold.
*/
func (square Square) String() string {
if square.terrain == Pit {
return "O "
} else if !square.hasGold {
switch {
case square.hasWump:
return "W "
case square.hasHunter:
return "i "
}
} else {
switch {
case square.hasWump:
return "# "
case square.hasHunter:
return "$ "
default:
return "* "
}
}
return ". " // No other option suffices, so it is nothing
}
/*
Stringer for World
*/
func (world World) String() string {
if len(world.squares) == 0{
panic("World was not created correctly, dimension x is 0")
} else if len(world.squares[0]) == 0 {
panic("World was not created correctly, dimension y is 0")
}
str := ""
for y := 0; y < world.sizey; y++ {
for x := 0; x < world.sizex; x++ {
str += world.squares[y][x].String();
}
str += "\n"
}
return str
}
/*
Ok, this function is nuts. The reason for it, is that I wanted to have
a simple problem generator for me to create an intelligent agent, right?
It didn't need to be perfect, for now. It is a small college homework.
So, for every problem be solvable, I needed to list some points that
led in a path to the gold, from the hunter, and I should not put
the bottomless pits in that path. So there is always at least this
(crazy, ill created) path from the hunter to the gold.
This function returns a map with all the points one shouldn't put
a pit into (a map for easy lookup) and then the point at the end,
where the gold shall be put.
I'll divide this function in three parts, inside
*/
func (world *World) guaranteePoints(positionHunter Point, unluckyFactor int) (map[Point]bool, Point) {
// Length calculated based on map size, it may be minor, but never
// bigger
length := int(2 * math.Sqrt(float64(world.sizex * world.sizex) + float64(world.sizey * world.sizey)))
visited := make(map[Point]bool)
positionPath := positionHunter
// The big for
// Image this algorigthm like this, the gold is now a living thing and
// it is right where the hunter is! Now it will move away from it.
// From now on, I'll consider the gold to be "moving".
for n := 0; n < length; n++ {
// Decide to which direction to go, it must always move as:
// {0, 1}, {0, -1}, {1, 0}, {-1, 0} (there is a "thing" after this)
// But diagonal movement is not movement ok? Never.
which := rand.Intn(2)
dx := 2 * rand.Intn(2) - 1
dy := 2 * rand.Intn(2) - 1
// The unluckyFactor, ah...
// Without this code, as the gold is dumb, it is very likely to remain
// next to the hunter, and it is even common to have the gold right
// on the hunter Square! This is not good, too easy. So there is a
// factor for the hunter missfortune: unluckyFactor. This factor
// makes likely, that every time the gold tries to move, it will
// move TWO squares AWAY from the hunter. A little help for the
// dumb gold right?
randomPick := rand.Intn(100)
if which == 0 {
dx *= 0
if (randomPick < unluckyFactor) {
dy = 2 * int(math.Abs(float64(dy)))
}
} else {
dy *= 0
if (randomPick < unluckyFactor) {
dx = 2 * int(math.Abs(float64(dx)))
}
}
// Keep the gold inbounds! Very important
// There is a trick here, when the unlucky factor attacks, the dx or dy
// (one of them) will be 2, if this put them out of bounds, I'm making
// them go back to 1, so that they wont turn arround and go -2.
// This is because the unlucky double movement is already a problem
// regarding the map of positions.
if positionPath.PosX + dx >= world.sizex || positionPath.PosX + dx < 0 {
if dx > 1 {
dx = 1
}
dx *= -1
}
if positionPath.PosY + dy >= world.sizey || positionPath.PosY + dy < 0 {
if dy > 1 {
dy = 1
}
dy *= -1
}
nextPositionPath := Point {positionPath.PosX + dx, positionPath.PosY + dy}
// Ok, the final part, if the place I'm putting the gold was already
// visited by him before, disregard this for iteration, the dumb brat
// lost another step. If not...
if _, isVisited := visited[nextPositionPath]; !isVisited {
positionPath = nextPositionPath
visited[positionPath] = true
// Consider that if he performed a unlucky movement, he should also
// mark as visited the square he jumped
if dx > 1 {
visited[Point {positionPath.PosX-1, positionPath.PosY}] = true
} else if dy > 1 {
visited[Point {positionPath.PosX, positionPath.PosY-1}] = true
}
}
}
return visited, positionPath
}
/*
This function creates a new world, based on the seed given to it
*/
func (world *World) New(sizex, sizey int, seed int64) {
world.NewEx(sizex, sizey, seed, 20, 35)
}
/*
This function creates a new world, based on the seed given to it, it takes more
parameters, to set the probability of pits and a factor that gives difficulty by
making more likely to the gold to be further away from the hunter
pitFactor: the bigger this is, the most likely it is for pits to spawn
There is a problem, however, because there are places where
pits cannot spawn (relative to letting a path to gold) and
the spawn of gold, hunter and wumpus will remove any pit
where they are spawned.
unluckyFactor: the bigger this is, the more likely is to gold to spawn
further away from the hunter
*/
func (world *World) NewEx(sizex, sizey int, seed int64, pitFactor, unluckyFactor int) {
if sizex == 0 || sizey == 0 {
panic("Invalid dimensions!");
}
rand.Seed(seed)
world.sizex = sizex
world.sizey = sizey
// Guarantees a path from 0, 0, to point lastPoint, where the gold will be
guaranteedPoints, lastPoint := world.guaranteePoints(Point {0, 0}, unluckyFactor) // Hunter is always at 0, 0
// Creates a map made from normal terrain and pit terrain
// No pits on guaranteed points
world.squares = make([][]Square, sizey, sizey)
for y := 0; y < sizey; y++ {
world.squares[y] = make([]Square, sizex, sizex)
for x := 0; x < sizex; x++ {
randomPick := rand.Intn(100)
if randomPick < pitFactor && !guaranteedPoints[Point {x, y}] {
world.squares[y][x] = Square{terrain: Pit, hasGold: false, hasWump: false, hasHunter: false}
} else {
world.squares[y][x] = Square{terrain: Normal, hasGold: false, hasWump: false, hasHunter: false}
}
}
}
// Place hunter
world.squares[0][0].terrain = Normal
world.squares[0][0].hasHunter = true
// Place gold
world.squares[lastPoint.PosY][lastPoint.PosX].hasGold = true
// Place wump
wx := rand.Intn(world.sizex)
wy := rand.Intn(world.sizey)
if wx == 0 && wy == 0 { // Not over hunter. Would be instant defeat
wx = 1
}
world.squares[wy][wx].terrain = Normal
world.squares[wy][wx].hasWump = true
}
/*
* This function creates a world from a string
*/
func (world *World) FromString(worldD string, lenX, lenY int) {
world.squares = make([][]Square, lenY)
world.sizey = lenY
world.sizex = lenX
i := 0
for y := 0; y < lenY; y++ {
world.squares[y] = make([]Square, lenX)
for x := 0; x < lenX; x++ {
fmt.Println(y, x, len(world.squares[y]))
switch worldD[i] {
case 'W':
world.squares[y][x].hasWump = true
world.squares[y][x].terrain = Normal
break
case 'i':
world.squares[y][x].hasHunter = true
world.squares[y][x].terrain = Normal
break
case 'O':
world.squares[y][x].terrain = Pit
break
case '.':
world.squares[y][x].terrain = Normal
break
case '*':
world.squares[y][x].hasGold = true
world.squares[y][x].terrain = Normal
break
case '#':
world.squares[y][x].hasGold = true
world.squares[y][x].hasWump = true
world.squares[y][x].terrain = Normal
default:
break
}
i++
}
}
} | def/world.go | 0.564939 | 0.454533 | world.go | starcoder |
package tcp
// https://github.com/aws/aws-sdk-go/blob/master/aws/convert_types.go
// String returns a pointer to the string value passed in.
func String(v string) *string {
return &v
}
// StringValue returns the value of the string pointer passed in or
// "" if the pointer is nil.
func StringValue(v *string) string {
if v != nil {
return *v
}
return ""
}
// StringSlice converts a slice of string values into a slice of
// string pointers
func StringSlice(src []string) []*string {
dst := make([]*string, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// StringValueSlice converts a slice of string pointers into a slice of
// string values
func StringValueSlice(src []*string) []string {
dst := make([]string, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// StringMap converts a string map of string values into a string
// map of string pointers
func StringMap(src map[string]string) map[string]*string {
dst := make(map[string]*string)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// StringValueMap converts a string map of string pointers into a string
// map of string values
func StringValueMap(src map[string]*string) map[string]string {
dst := make(map[string]string)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Bool returns a pointer to the bool value passed in.
func Bool(v bool) *bool {
return &v
}
// BoolValue returns the value of the bool pointer passed in or
// false if the pointer is nil.
func BoolValue(v *bool) bool {
if v != nil {
return *v
}
return false
}
// BoolSlice converts a slice of bool values into a slice of
// bool pointers
func BoolSlice(src []bool) []*bool {
dst := make([]*bool, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// BoolValueSlice converts a slice of bool pointers into a slice of
// bool values
func BoolValueSlice(src []*bool) []bool {
dst := make([]bool, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// BoolMap converts a string map of bool values into a string
// map of bool pointers
func BoolMap(src map[string]bool) map[string]*bool {
dst := make(map[string]*bool)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// BoolValueMap converts a string map of bool pointers into a string
// map of bool values
func BoolValueMap(src map[string]*bool) map[string]bool {
dst := make(map[string]bool)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Int returns a pointer to the int value passed in.
func Int(v int) *int {
return &v
}
// IntValue returns the value of the int pointer passed in or
// 0 if the pointer is nil.
func IntValue(v *int) int {
if v != nil {
return *v
}
return 0
}
// IntSlice converts a slice of int values into a slice of
// int pointers
func IntSlice(src []int) []*int {
dst := make([]*int, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// IntValueSlice converts a slice of int pointers into a slice of
// int values
func IntValueSlice(src []*int) []int {
dst := make([]int, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// IntMap converts a string map of int values into a string
// map of int pointers
func IntMap(src map[string]int) map[string]*int {
dst := make(map[string]*int)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// IntValueMap converts a string map of int pointers into a string
// map of int values
func IntValueMap(src map[string]*int) map[string]int {
dst := make(map[string]int)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Int16 returns a pointer to the int16 value passed in.
func Int16(v int16) *int16 {
return &v
}
// Int16Value returns the value of the int16 pointer passed in or
// 0 if the pointer is nil.
func Int16Value(v *int16) int16 {
if v != nil {
return *v
}
return 0
}
// Int16Slice converts a slice of int16 values into a slice of
// int16 pointers
func Int16Slice(src []int16) []*int16 {
dst := make([]*int16, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Int16ValueSlice converts a slice of int16 pointers into a slice of
// int16 values
func Int16ValueSlice(src []*int16) []int16 {
dst := make([]int16, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Int16Map converts a string map of int16 values into a string
// map of int16 pointers
func Int16Map(src map[string]int16) map[string]*int16 {
dst := make(map[string]*int16)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Int16ValueMap converts a string map of int16 pointers into a string
// map of int16 values
func Int16ValueMap(src map[string]*int16) map[string]int16 {
dst := make(map[string]int16)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Int32 returns a pointer to the int32 value passed in.
func Int32(v int32) *int32 {
return &v
}
// Int32Value returns the value of the int32 pointer passed in or
// 0 if the pointer is nil.
func Int32Value(v *int32) int32 {
if v != nil {
return *v
}
return 0
}
// Int32Slice converts a slice of int32 values into a slice of
// int32 pointers
func Int32Slice(src []int32) []*int32 {
dst := make([]*int32, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Int32ValueSlice converts a slice of int32 pointers into a slice of
// int32 values
func Int32ValueSlice(src []*int32) []int32 {
dst := make([]int32, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Int32Map converts a string map of int32 values into a string
// map of int32 pointers
func Int32Map(src map[string]int32) map[string]*int32 {
dst := make(map[string]*int32)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Int32ValueMap converts a string map of int32 pointers into a string
// map of int32 values
func Int32ValueMap(src map[string]*int32) map[string]int32 {
dst := make(map[string]int32)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Float64 returns a pointer to the float64 value passed in.
func Float64(v float64) *float64 {
return &v
}
// Float64Value returns the value of the float64 pointer passed in or
// 0 if the pointer is nil.
func Float64Value(v *float64) float64 {
if v != nil {
return *v
}
return 0
}
// Float32 returns a pointer to the float32 value passed in.
func Float32(v float32) *float32 {
return &v
}
// Float32Value returns the value of the float32 pointer passed in or
// 0 if the pointer is nil.
func Float32Value(v *float32) float32 {
if v != nil {
return *v
}
return 0
}
// Float32Slice converts a slice of float32 values into a slice of
// float32 pointers
func Float32Slice(src []float32) []*float32 {
dst := make([]*float32, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Float32ValueSlice converts a slice of float32 pointers into a slice of
// float32 values
func Float32ValueSlice(src []*float32) []float32 {
dst := make([]float32, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Float32Map converts a string map of float32 values into a string
// map of float32 pointers
func Float32Map(src map[string]float32) map[string]*float32 {
dst := make(map[string]*float32)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Float32ValueMap converts a string map of float32 pointers into a string
// map of float32 values
func Float32ValueMap(src map[string]*float32) map[string]float32 {
dst := make(map[string]float32)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Byte returns a pointer to the byte value passed in.
func Byte(v byte) *byte {
return &v
}
// ByteValue returns the value of the byte pointer passed in or
// 0 if the pointer is nil.
func ByteValue(v *byte) byte {
if v != nil {
return *v
}
return 0
}
// ByteSlice converts a slice of byte values into a slice of
// byte pointers
func ByteSlice(src []byte) []*byte {
dst := make([]*byte, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// ByteValueSlice converts a slice of byte pointers into a slice of
// byte values
func ByteValueSlice(src []*byte) []byte {
dst := make([]byte, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// ByteMap converts a string map of byte values into a string
// map of byte pointers
func ByteMap(src map[string]byte) map[string]*byte {
dst := make(map[string]*byte)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// ByteValueMap converts a string map of byte pointers into a string
// map of byte values
func ByteValueMap(src map[string]*byte) map[string]byte {
dst := make(map[string]byte)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Uint8 returns a pointer to the uint8 value passed in.
func Uint8(v uint8) *uint8 {
return &v
}
// Uint8Value returns the value of the uint8 pointer passed in or
// 0 if the pointer is nil.
func Uint8Value(v *uint8) uint8 {
if v != nil {
return *v
}
return 0
}
// Uint8Slice converts a slice of uint8 values into a slice of
// uint8 pointers
func Uint8Slice(src []uint8) []*uint8 {
dst := make([]*uint8, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Uint8ValueSlice converts a slice of uint8 pointers into a slice of
// uint8 values
func Uint8ValueSlice(src []*uint8) []uint8 {
dst := make([]uint8, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Uint8Map converts a string map of uint8 values into a string
// map of uint8 pointers
func Uint8Map(src map[string]uint8) map[string]*uint8 {
dst := make(map[string]*uint8)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Uint8ValueMap converts a string map of uint8 pointers into a string
// map of uint8 values
func Uint8ValueMap(src map[string]*uint8) map[string]uint8 {
dst := make(map[string]uint8)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Uint16 returns a pointer to the uint16 value passed in.
func Uint16(v uint16) *uint16 {
return &v
}
// Uint16Value returns the value of the uint16 pointer passed in or
// 0 if the pointer is nil.
func Uint16Value(v *uint16) uint16 {
if v != nil {
return *v
}
return 0
}
// Uint16Slice converts a slice of uint16 values into a slice of
// uint16 pointers
func Uint16Slice(src []uint16) []*uint16 {
dst := make([]*uint16, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Uint16ValueSlice converts a slice of uint16 pointers into a slice of
// uint16 values
func Uint16ValueSlice(src []*uint16) []uint16 {
dst := make([]uint16, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Uint16Map converts a string map of uint16 values into a string
// map of uint16 pointers
func Uint16Map(src map[string]uint16) map[string]*uint16 {
dst := make(map[string]*uint16)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Uint16ValueMap converts a string map of uint16 pointers into a string
// map of uint16 values
func Uint16ValueMap(src map[string]*uint16) map[string]uint16 {
dst := make(map[string]uint16)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
}
// Uint32 returns a pointer to the uint32 value passed in.
func Uint32(v uint32) *uint32 {
return &v
}
// Uint32Value returns the value of the uint32 pointer passed in or
// 0 if the pointer is nil.
func Uint32Value(v *uint32) uint32 {
if v != nil {
return *v
}
return 0
}
// Uint32Slice converts a slice of uint32 values into a slice of
// uint32 pointers
func Uint32Slice(src []uint32) []*uint32 {
dst := make([]*uint32, len(src))
for i := 0; i < len(src); i++ {
dst[i] = &(src[i])
}
return dst
}
// Uint32ValueSlice converts a slice of uint32 pointers into a slice of
// uint32 values
func Uint32ValueSlice(src []*uint32) []uint32 {
dst := make([]uint32, len(src))
for i := 0; i < len(src); i++ {
if src[i] != nil {
dst[i] = *(src[i])
}
}
return dst
}
// Uint32Map converts a string map of uint32 values into a string
// map of uint32 pointers
func Uint32Map(src map[string]uint32) map[string]*uint32 {
dst := make(map[string]*uint32)
for k, val := range src {
v := val
dst[k] = &v
}
return dst
}
// Uint32ValueMap converts a string map of uint32 pointers into a string
// map of uint32 values
func Uint32ValueMap(src map[string]*uint32) map[string]uint32 {
dst := make(map[string]uint32)
for k, val := range src {
if val != nil {
dst[k] = *val
}
}
return dst
} | tcp/convert_types.go | 0.852429 | 0.445771 | convert_types.go | starcoder |
// Package image provides a mockable wrapper for image.
package image
import (
image "image"
color "image/color"
io "io"
)
var _ Interface = &Impl{}
var _ = image.Decode
type Interface interface {
Decode(r io.Reader) (image.Image, string, error)
DecodeConfig(r io.Reader) (image.Config, string, error)
NewAlpha(r image.Rectangle) *image.Alpha
NewAlpha16(r image.Rectangle) *image.Alpha16
NewCMYK(r image.Rectangle) *image.CMYK
NewGray(r image.Rectangle) *image.Gray
NewGray16(r image.Rectangle) *image.Gray16
NewNRGBA(r image.Rectangle) *image.NRGBA
NewNRGBA64(r image.Rectangle) *image.NRGBA64
NewNYCbCrA(r image.Rectangle, subsampleRatio image.YCbCrSubsampleRatio) *image.NYCbCrA
NewPaletted(r image.Rectangle, p color.Palette) *image.Paletted
NewRGBA(r image.Rectangle) *image.RGBA
NewRGBA64(r image.Rectangle) *image.RGBA64
NewUniform(c color.Color) *image.Uniform
NewYCbCr(r image.Rectangle, subsampleRatio image.YCbCrSubsampleRatio) *image.YCbCr
Pt(X int, Y int) image.Point
Rect(x0 int, y0 int, x1 int, y1 int) image.Rectangle
RegisterFormat(name string, magic string, decode func(io.Reader) (image.Image, error), decodeConfig func(io.Reader) (image.Config, error))
}
type Impl struct{}
func (*Impl) Decode(r io.Reader) (image.Image, string, error) {
return image.Decode(r)
}
func (*Impl) DecodeConfig(r io.Reader) (image.Config, string, error) {
return image.DecodeConfig(r)
}
func (*Impl) NewAlpha(r image.Rectangle) *image.Alpha {
return image.NewAlpha(r)
}
func (*Impl) NewAlpha16(r image.Rectangle) *image.Alpha16 {
return image.NewAlpha16(r)
}
func (*Impl) NewCMYK(r image.Rectangle) *image.CMYK {
return image.NewCMYK(r)
}
func (*Impl) NewGray(r image.Rectangle) *image.Gray {
return image.NewGray(r)
}
func (*Impl) NewGray16(r image.Rectangle) *image.Gray16 {
return image.NewGray16(r)
}
func (*Impl) NewNRGBA(r image.Rectangle) *image.NRGBA {
return image.NewNRGBA(r)
}
func (*Impl) NewNRGBA64(r image.Rectangle) *image.NRGBA64 {
return image.NewNRGBA64(r)
}
func (*Impl) NewNYCbCrA(r image.Rectangle, subsampleRatio image.YCbCrSubsampleRatio) *image.NYCbCrA {
return image.NewNYCbCrA(r, subsampleRatio)
}
func (*Impl) NewPaletted(r image.Rectangle, p color.Palette) *image.Paletted {
return image.NewPaletted(r, p)
}
func (*Impl) NewRGBA(r image.Rectangle) *image.RGBA {
return image.NewRGBA(r)
}
func (*Impl) NewRGBA64(r image.Rectangle) *image.RGBA64 {
return image.NewRGBA64(r)
}
func (*Impl) NewUniform(c color.Color) *image.Uniform {
return image.NewUniform(c)
}
func (*Impl) NewYCbCr(r image.Rectangle, subsampleRatio image.YCbCrSubsampleRatio) *image.YCbCr {
return image.NewYCbCr(r, subsampleRatio)
}
func (*Impl) Pt(X int, Y int) image.Point {
return image.Pt(X, Y)
}
func (*Impl) Rect(x0 int, y0 int, x1 int, y1 int) image.Rectangle {
return image.Rect(x0, y0, x1, y1)
}
func (*Impl) RegisterFormat(name string, magic string, decode func(io.Reader) (image.Image, error), decodeConfig func(io.Reader) (image.Config, error)) {
image.RegisterFormat(name, magic, decode, decodeConfig)
} | image/image.go | 0.841696 | 0.485295 | image.go | starcoder |
package prtree
import (
"github.com/tidwall/geoindex/child"
"github.com/tidwall/ptree"
"github.com/tidwall/rtree"
)
// PRTree is a tree for storing points and rects
type PRTree struct {
ptree *ptree.PTree
rtree *rtree.RTree
}
// New returns a new PRTree
func New(min, max [2]float64) *PRTree {
tr := new(PRTree)
tr.ptree = ptree.New(min, max)
tr.rtree = new(rtree.RTree)
return tr
}
// Insert an item into the structure
func (tr *PRTree) Insert(min, max [2]float64, data interface{}) {
if min == max && tr.ptree.InBounds(min) {
tr.ptree.Insert(min, data)
} else {
tr.rtree.Insert(min, max, data)
}
}
// Delete an item from the structure
func (tr *PRTree) Delete(min, max [2]float64, data interface{}) {
if min == max && tr.ptree.InBounds(min) {
tr.ptree.Delete(min, data)
} else {
tr.rtree.Delete(min, max, data)
}
}
// Replace an item in the structure. This is effectively just a Delete
// followed by an Insert. But for some structures it may be possible to
// optimize the operation to avoid multiple passes
func (tr *PRTree) Replace(
oldMin, oldMax [2]float64, oldData interface{},
newMin, newMax [2]float64, newData interface{},
) {
tr.Delete(oldMin, oldMax, oldData)
tr.Insert(newMin, newMax, newData)
}
// Search the structure for items that intersects the rect param
func (tr *PRTree) Search(
min, max [2]float64,
iter func(min, max [2]float64, data interface{}) bool,
) {
var quit bool
tr.ptree.Search(min, max, func(point [2]float64, data interface{}) bool {
if !iter(point, point, data) {
quit = true
return false
}
return true
})
if !quit {
tr.rtree.Search(min, max, iter)
}
}
// Scan iterates through all data in tree in no specified order.
func (tr *PRTree) Scan(iter func(min, max [2]float64, data interface{}) bool) {
var quit bool
tr.ptree.Scan(func(point [2]float64, data interface{}) bool {
if !iter(point, point, data) {
quit = true
return false
}
return true
})
if !quit {
tr.rtree.Scan(iter)
}
}
// Len returns the number of items in tree
func (tr *PRTree) Len() int {
return tr.ptree.Len() + tr.rtree.Len()
}
func expand(amin, amax, bmin, bmax [2]float64) (min, max [2]float64) {
if bmin[0] < amin[0] {
amin[0] = bmin[0]
}
if bmax[0] > amax[0] {
amax[0] = bmax[0]
}
if bmin[1] < amin[1] {
amin[1] = bmin[1]
}
if bmax[1] > amax[1] {
amax[1] = bmax[1]
}
return amin, amax
}
// Bounds returns the minimum bounding box
func (tr *PRTree) Bounds() (min, max [2]float64) {
if tr.ptree.Len() > 0 {
amin, amax := tr.ptree.MinBounds()
if tr.rtree.Len() > 0 {
bmin, bmax := tr.rtree.Bounds()
min, max = expand(amin, amax, bmin, bmax)
} else {
min, max = amin, amax
}
} else if tr.rtree.Len() > 0 {
min, max = tr.rtree.Bounds()
}
return min, max
}
type pChildNode struct {
data interface{}
}
type rChildNode struct {
data interface{}
}
// Children returns all children for parent node. If parent node is nil
// then the root nodes should be returned.
// The reuse buffer is an empty length slice that can optionally be used
// to avoid extra allocations.
func (tr *PRTree) Children(parent interface{}, reuse []child.Child,
) (children []child.Child) {
children = reuse[:0]
switch parent := parent.(type) {
case nil:
// Gather the parent nodes for all PTree and RTree children.
// For all children that are node data (not item data), we'll need to
// wrap the data with a local type to keep track of the which tree the
// node belongs to.
children = tr.ptree.Children(nil, children)
for i := 0; i < len(children); i++ {
if !children[i].Item {
children[i].Data = pChildNode{children[i].Data}
}
}
mark := len(children)
children = tr.rtree.Children(nil, children)
for i := mark; i < len(children); i++ {
if !children[i].Item {
children[i].Data = rChildNode{children[i].Data}
}
}
return children
case pChildNode:
children = tr.ptree.Children(parent.data, children)
for i := 0; i < len(children); i++ {
if !children[i].Item {
children[i].Data = pChildNode{children[i].Data}
}
}
case rChildNode:
children = tr.rtree.Children(parent.data, children)
for i := 0; i < len(children); i++ {
if !children[i].Item {
children[i].Data = rChildNode{children[i].Data}
}
}
default:
panic("invalid node type")
}
return children
} | prtree.go | 0.646795 | 0.443299 | prtree.go | starcoder |
package msgraph
// RatingFranceMoviesType undocumented
type RatingFranceMoviesType string
const (
// RatingFranceMoviesTypeVAllAllowed undocumented
RatingFranceMoviesTypeVAllAllowed RatingFranceMoviesType = "AllAllowed"
// RatingFranceMoviesTypeVAllBlocked undocumented
RatingFranceMoviesTypeVAllBlocked RatingFranceMoviesType = "AllBlocked"
// RatingFranceMoviesTypeVAgesAbove10 undocumented
RatingFranceMoviesTypeVAgesAbove10 RatingFranceMoviesType = "AgesAbove10"
// RatingFranceMoviesTypeVAgesAbove12 undocumented
RatingFranceMoviesTypeVAgesAbove12 RatingFranceMoviesType = "AgesAbove12"
// RatingFranceMoviesTypeVAgesAbove16 undocumented
RatingFranceMoviesTypeVAgesAbove16 RatingFranceMoviesType = "AgesAbove16"
// RatingFranceMoviesTypeVAgesAbove18 undocumented
RatingFranceMoviesTypeVAgesAbove18 RatingFranceMoviesType = "AgesAbove18"
)
// RatingFranceMoviesTypePAllAllowed returns a pointer to RatingFranceMoviesTypeVAllAllowed
func RatingFranceMoviesTypePAllAllowed() *RatingFranceMoviesType {
v := RatingFranceMoviesTypeVAllAllowed
return &v
}
// RatingFranceMoviesTypePAllBlocked returns a pointer to RatingFranceMoviesTypeVAllBlocked
func RatingFranceMoviesTypePAllBlocked() *RatingFranceMoviesType {
v := RatingFranceMoviesTypeVAllBlocked
return &v
}
// RatingFranceMoviesTypePAgesAbove10 returns a pointer to RatingFranceMoviesTypeVAgesAbove10
func RatingFranceMoviesTypePAgesAbove10() *RatingFranceMoviesType {
v := RatingFranceMoviesTypeVAgesAbove10
return &v
}
// RatingFranceMoviesTypePAgesAbove12 returns a pointer to RatingFranceMoviesTypeVAgesAbove12
func RatingFranceMoviesTypePAgesAbove12() *RatingFranceMoviesType {
v := RatingFranceMoviesTypeVAgesAbove12
return &v
}
// RatingFranceMoviesTypePAgesAbove16 returns a pointer to RatingFranceMoviesTypeVAgesAbove16
func RatingFranceMoviesTypePAgesAbove16() *RatingFranceMoviesType {
v := RatingFranceMoviesTypeVAgesAbove16
return &v
}
// RatingFranceMoviesTypePAgesAbove18 returns a pointer to RatingFranceMoviesTypeVAgesAbove18
func RatingFranceMoviesTypePAgesAbove18() *RatingFranceMoviesType {
v := RatingFranceMoviesTypeVAgesAbove18
return &v
} | v1.0/RatingFranceMoviesTypeEnum.go | 0.583678 | 0.441432 | RatingFranceMoviesTypeEnum.go | starcoder |
package geometry
import (
"bufio"
"errors"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"github.com/gonum/matrix/mat64"
"github.com/google/uuid"
)
// PointCloud Represents an array of vectors
type PointCloud struct {
Vectors []*mat64.Vector
boxKNNSize *mat64.Vector
k int
}
// Add adds a Vector to Pointcloud
func (pC *PointCloud) Add(vec ...*mat64.Vector) {
pC.Vectors = append(pC.Vectors, vec...)
}
// FillRandom fills pointcloud with random vectors
func (pC *PointCloud) FillRandom(count int) {
for i := 0; i < count; i++ {
vec := mat64.NewVector(3, []float64{
rand.Float64(),
rand.Float64(),
rand.Float64(),
})
pC.Vectors = append(pC.Vectors, vec)
}
}
// Length returns the amount of vertices in PoinCloud
func (pC *PointCloud) Length() int {
return len(pC.Vectors)
}
// ReadPCD reads in PCD data from Point Cloud Library
func (pC *PointCloud) ReadPCD(path string) error {
fileHandle, err := os.Open(path)
if err != nil {
return err
}
defer fileHandle.Close()
fileScanner := bufio.NewScanner(fileHandle)
isPoint := false
for fileScanner.Scan() {
// line ist die jeweilige Zeile
line := fileScanner.Text()
if isPoint {
// Die Punkte sind zeilenweise als "x y z" gespeichert und werden erstmal in ein unterarray gesplittet
point := strings.Split(line, " ")
// die unterarrays werden zu einem vektor zusammen geschrieben
x, err := strconv.ParseFloat(point[0], 64)
if err != nil {
return err
}
y, err := strconv.ParseFloat(point[1], 64)
if err != nil {
return err
}
z, err := strconv.ParseFloat(point[2], 64)
if err != nil {
return err
}
vector := mat64.NewVector(3, []float64{
x,
y,
z,
})
// der vector wird in die gesamte PointCloud ergänzt
pC.Vectors = append(pC.Vectors, vector)
}
// Erst nach erkennen dieser Zeile werden Vectoren erstellt.
if line == "DATA ascii" || line == "end_header" {
isPoint = true
}
}
return nil
}
// SavePLY saves a Pointcloud to PLY file
func (pC *PointCloud) SavePLY(path string) error {
if pC.Vectors == nil {
return errors.New("pointcloud is empty")
}
ply := []byte{}
ply = append(ply, []byte("ply\n")...)
ply = append(ply, []byte("format ascii 1.0\n")...)
body := []byte{}
var (
x string
y string
z string
)
for _, vector := range pC.Vectors {
x = strconv.FormatFloat(vector.At(0, 0), 'E', -1, 64)
y = strconv.FormatFloat(vector.At(1, 0), 'E', -1, 64)
z = strconv.FormatFloat(vector.At(2, 0), 'E', -1, 64)
body = append(body, []byte(x+" "+y+" "+z+"\n")...)
}
ply = append(ply, []byte("element vertex "+strconv.Itoa(len(pC.Vectors))+"\n")...)
ply = append(ply, []byte("property float x\n")...)
ply = append(ply, []byte("property float y\n")...)
ply = append(ply, []byte("property float z\n")...)
ply = append(ply, []byte("end_header\n")...)
ply = append(ply, body...)
return ioutil.WriteFile(path, ply, 0644)
}
// Transform transforms pointcloud with transformation matrix
func (pC *PointCloud) Transform(transMat *TransMat) {
for i, vector := range pC.Vectors {
pC.Vectors[i] = transMat.Transform(vector)
}
}
// ShowInMeshlab shows the Pointcloudobject in meshlab
func (pC *PointCloud) ShowInMeshlab() error {
tmpPath := os.TempDir() + "/" + uuid.New().String() + ".ply"
err := pC.SavePLY(tmpPath)
if err != nil {
return err
}
meshlabExecPath := "meshlab"
if runtime.GOOS == "windows" {
meshlabExecPath = `C:\Program Files\VCG\MeshLab\meshlab.exe`
}
meshlab := exec.Command(meshlabExecPath, tmpPath)
err = meshlab.Start()
if err != nil {
return errors.New("meshlab could not be started")
}
meshlab.Wait()
return os.Remove(tmpPath)
}
// FindNearestNeighbors finds the closest k-Points to a given point
func (pC *PointCloud) FindNearestNeighbors(point *mat64.Vector, k int) PointCloud {
nn := PointCloud{}
// If the best density is not estimated yet:
if pC.boxKNNSize == nil || pC.k != k {
box := NewBox3(nil, nil)
size := mat64.NewVector(3, []float64{0, 0, 0})
box.SetFromCenterAndSize(point, size)
foundK := 0
for i := 0; i < 1000000; i++ {
if foundK >= k {
break
}
if i > 0 {
foundK = 0
box.ExpandByScalar(0.0001)
}
for _, point := range pC.Vectors {
if box.ContainsPoint(point) {
// nn.Add(point)
foundK++
}
}
}
pC.boxKNNSize = box.GetSize()
}
box := NewBox3(nil, nil)
box.SetFromCenterAndSize(point, pC.boxKNNSize)
for _, point := range pC.Vectors {
if box.ContainsPoint(point) {
nn.Add(point)
}
}
return nn
} | pointcloud3.go | 0.654122 | 0.429489 | pointcloud3.go | starcoder |
package models
import (
"fmt"
)
// TimePoint contains a relative time, the numbers of events of interest and censoring events occured at that time.
type TimePoint struct {
Time int64
Events Events
}
// Events contains the number of events of interest and censoring events occurring at the same relative time.
type Events struct {
EventsOfInterest int64
CensoringEvents int64
}
// TimePoints is a slice containing the time points and respective counts of censoring events and events of interest.
// TimePoints implements sort.Interface interface.
type TimePoints []TimePoint
// Len implements Len method for sort.Interface interface.
func (tps TimePoints) Len() int {
return len(tps)
}
// Less implements Less method for sort.Interface interface
func (tps TimePoints) Less(i, j int) bool {
return tps[i].Time < tps[j].Time
}
//Swap implements Swap method for sort.Interface interface.
func (tps TimePoints) Swap(i, j int) {
tps[i], tps[j] = tps[j], tps[i]
}
// Bin bins the time points according to provided @granularity.
func (tps TimePoints) Bin(granularity string) (TimePoints, error) {
if granFunction, isIn := granularityFunctions[granularity]; isIn {
return tps.binTimePoint(granFunction), nil
}
return nil, fmt.Errorf("granularity %s is not implemented: should be one of year, month, week, day", granularity)
}
func (tps TimePoints) binTimePoint(groupingFunction func(int64) int64) TimePoints {
bins := make(map[int64]struct {
EventsOfInterest int64
CensoringEvents int64
})
var ceiled int64
for _, tp := range tps {
ceiled = groupingFunction(tp.Time)
if val, isInside := bins[ceiled]; isInside {
bins[ceiled] = struct {
EventsOfInterest int64
CensoringEvents int64
}{
EventsOfInterest: val.EventsOfInterest + tp.Events.EventsOfInterest,
CensoringEvents: val.CensoringEvents + tp.Events.CensoringEvents,
}
} else {
bins[ceiled] = struct {
EventsOfInterest int64
CensoringEvents int64
}{
EventsOfInterest: tp.Events.EventsOfInterest,
CensoringEvents: tp.Events.CensoringEvents,
}
}
}
newSQLTimePoints := make(TimePoints, 0)
for time, agg := range bins {
newSQLTimePoints = append(newSQLTimePoints, TimePoint{
Time: time,
Events: struct {
EventsOfInterest int64
CensoringEvents int64
}{
EventsOfInterest: agg.EventsOfInterest,
CensoringEvents: agg.CensoringEvents,
},
})
}
return newSQLTimePoints
}
// Expand adds zeros for events of interest and censoring events for each missing relative time from 0 to timeLimit.
// Relative times greater than @timeLimitDay (time unit: day) are discarded.
func (tps TimePoints) Expand(timeLimitDay int, granularity string) (TimePoints, error) {
var timeLimit int64
if granFunction, isIn := granularityFunctions[granularity]; isIn {
timeLimit = granFunction(int64(timeLimitDay))
} else {
return nil, fmt.Errorf("granularity %s is not implemented", granularity)
}
res := make(TimePoints, timeLimit)
availableTimePoints := make(map[int64]struct {
EventsOfInterest int64
CensoringEvents int64
}, len(tps))
for _, timePoint := range tps {
availableTimePoints[timePoint.Time] = timePoint.Events
}
for i := int64(0); i < timeLimit; i++ {
if events, ok := availableTimePoints[i]; ok {
res[i] = TimePoint{
Time: i,
Events: events,
}
} else {
res[i] = TimePoint{
Time: i,
Events: struct {
EventsOfInterest int64
CensoringEvents int64
}{
EventsOfInterest: 0,
CensoringEvents: 0,
},
}
}
}
return res, nil
} | pkg/datasource/models/survival_query_time_points.go | 0.708313 | 0.526891 | survival_query_time_points.go | starcoder |
package main
import (
"sort"
)
// HuffmanTree is a codification of a Huffman tree. We arbitrary decide that we interpret the left tree as bit 1 and
// the right tree as bit 0. In the right part of the tree we store the values for the level, i.e. the nearer to the
// root on the right side, the higher the frequency of the respective character in the stream.
type HuffmanTree struct {
Value byte
Left *HuffmanTree
Right *HuffmanTree
}
func (tree HuffmanTree) String() string {
s1 := ""
s2 := ""
v := ""
if !tree.isLeaf() {
s1 = "right: " + tree.Right.String()
// We assume that we always have a left tree if we have a right tree.
s2 = ", left: " + tree.Left.String()
} else {
v = string(tree.Value)
}
return "{" + v + s1 + s2 + "}"
}
func (tree HuffmanTree) isLeaf() bool {
return tree.Right == nil && tree.Left == nil
}
// GetCodebook returns the codebook for this particular tree.
func (tree HuffmanTree) GetCodebook() map[byte][]int {
m := make(map[byte][]int)
path := make([]int, 0)
for root := tree; root.Right != nil; root = *root.Left {
curPath := append(path, 1)
m[root.Right.Value] = curPath
path = append(path, 0)
// If we are at the last two elements, use 0 for the last element with the lowest frequency instead of 1.
if root.Left.Right == nil {
m[root.Left.Value] = path
}
}
return m
}
// GenerateHuffmanTree generates a HuffmanTree based on the data passed in the parameter.
func NewHuffmanTree(s []byte) HuffmanTree {
frequencies := ComputeFrequency(s)
byteList := SortFrequencyList(frequencies)
// Combine single sorted lists to a single binary tree.
root := makeLeaf(byteList[0])
for _, leafValue := range byteList[1:] {
leaf := makeLeaf(leafValue)
root = combineLeafs(root, leaf)
}
return root
}
// makeLeaf generate a single leaf without children.
func makeLeaf(value byte) HuffmanTree {
return HuffmanTree{Value: value}
}
// combineLeafs combines two trees into a single new one without a value. Note that we intentionally pass parameters
// by value to have 'fresh' trees.
func combineLeafs(left, right HuffmanTree) HuffmanTree {
return HuffmanTree{0, &left, &right}
}
// SortFrequencyList generates a list of bytes sorted by relative frequency, starting with the smallest ones.
func SortFrequencyList(m map[byte]float32) []byte {
// Convert to array of struct values.
type kv struct {
Key byte
Value float32
}
var kvs []kv
for k, v := range m {
kvs = append(kvs, kv{k, v})
}
// Sort array.
sort.Slice(kvs, func(i, j int) bool {
return kvs[i].Value < kvs[j].Value
})
// Convert to byte array.
var result []byte
for _, v := range kvs {
result = append(result, v.Key)
}
return result
}
// ComputeFrequency computes a relative frequency map of all characters in the array.
func ComputeFrequency(s []byte) map[byte]float32 {
m := make(map[byte]float32)
// Count absolute number.
for _, v := range s {
m[v]++
}
// Compute relative number of occurrences.
for k, v := range m {
m[k] = v / float32(len(s))
}
return m
} | Greedy Algorithms/Huffman/go/huffman.go | 0.805632 | 0.721461 | huffman.go | starcoder |
package sampler
import (
"math"
)
const (
// 2^64 - 1
maxTraceID = ^uint64(0)
maxTraceIDFloat = float64(maxTraceID)
// Good number for Knuth hashing (large, prime, fit in int64 for languages without uint64)
samplerHasher = uint64(1111111111111111111)
)
// SampleByRate tells if a trace (from its ID) with a given rate should be sampled
// Use Knuth multiplicative hashing to leverage imbalanced traceID generators
func SampleByRate(traceID uint64, rate float64) bool {
if rate < 1 {
return traceID*samplerHasher < uint64(rate*maxTraceIDFloat)
}
return true
}
// GetSignatureSampleRate gives the sample rate to apply to any signature.
// For now, only based on count score.
func (s *Sampler) GetSignatureSampleRate(signature Signature) float64 {
return s.loadRate(s.GetCountScore(signature))
}
// getAllSignatureSampleRates gives the sample rate to apply to all signatures.
// For now, only based on count score.
func (s *Sampler) getAllSignatureSampleRates() map[Signature]float64 {
m := s.GetAllCountScores()
for k, v := range m {
m[k] = s.loadRate(v)
}
return m
}
// GetDefaultSampleRate gives the sample rate to apply to an unknown signature.
// For now, only based on count score.
func (s *Sampler) GetDefaultSampleRate() float64 {
return s.loadRate(s.GetDefaultCountScore())
}
func (s *Sampler) loadRate(rate float64) float64 {
if rate >= s.rateThresholdTo1 {
return 1
}
return rate
}
func (s *Sampler) backendScoreToSamplerScore(score float64) float64 {
return s.signatureScoreFactor.Load() / math.Pow(s.signatureScoreSlope.Load(), math.Log10(score))
}
// GetCountScore scores any signature based on its recent throughput
// The score value can be seeing as the sample rate if the count were the only factor
// Since other factors can intervene (such as extra global sampling), its value can be larger than 1
func (s *Sampler) GetCountScore(signature Signature) float64 {
return s.backendScoreToSamplerScore(s.Backend.GetSignatureScore(signature))
}
// GetAllCountScores scores all signatures based on their recent throughput
// The score value can be seeing as the sample rate if the count were the only factor
// Since other factors can intervene (such as extra global sampling), its value can be larger than 1
func (s *Sampler) GetAllCountScores() map[Signature]float64 {
m := s.Backend.GetSignatureScores()
for k, v := range m {
m[k] = s.backendScoreToSamplerScore(v)
}
return m
}
// GetDefaultCountScore returns a default score when not knowing the signature for real.
// Since other factors can intervene (such as extra global sampling), its value can be larger than 1
func (s *Sampler) GetDefaultCountScore() float64 {
return s.backendScoreToSamplerScore(s.Backend.GetTotalScore())
} | pkg/trace/sampler/score.go | 0.846578 | 0.463019 | score.go | starcoder |
package main
import (
"code.google.com/p/gomatrix/matrix"
"fmt"
"math"
)
func sign(s float64) float64 {
if s > 0 {
return 1
} else if s < 0 {
return -1
}
return 0
}
func unitVector(n int) *matrix.DenseMatrix {
vec := matrix.Zeros(n, 1)
vec.Set(0, 0, 1)
return vec
}
func householder(a *matrix.DenseMatrix) *matrix.DenseMatrix {
m := a.Rows()
s := sign(a.Get(0, 0))
e := unitVector(m)
u := matrix.Sum(a, matrix.Scaled(e, a.TwoNorm()*s))
v := matrix.Scaled(u, 1/u.Get(0, 0))
// (error checking skipped in this solution)
prod, _ := v.Transpose().TimesDense(v)
β := 2 / prod.Get(0, 0)
prod, _ = v.TimesDense(v.Transpose())
return matrix.Difference(matrix.Eye(m), matrix.Scaled(prod, β))
}
func qr(a *matrix.DenseMatrix) (q, r *matrix.DenseMatrix) {
m := a.Rows()
n := a.Cols()
q = matrix.Eye(m)
last := n - 1
if m == n {
last--
}
for i := 0; i <= last; i++ {
// (copy is only for compatibility with an older version of gomatrix)
b := a.GetMatrix(i, i, m-i, n-i).Copy()
x := b.GetColVector(0)
h := matrix.Eye(m)
h.SetMatrix(i, i, householder(x))
q, _ = q.TimesDense(h)
a, _ = h.TimesDense(a)
}
return q, a
}
func main() {
// task 1: show qr decomp of wp example
a := matrix.MakeDenseMatrixStacked([][]float64{
{12, -51, 4},
{6, 167, -68},
{-4, 24, -41}})
q, r := qr(a)
fmt.Println("q:\n", q)
fmt.Println("r:\n", r)
// task 2: use qr decomp for polynomial regression example
x := matrix.MakeDenseMatrixStacked([][]float64{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}})
y := matrix.MakeDenseMatrixStacked([][]float64{
{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}})
fmt.Println("\npolyfit:\n", polyfit(x, y, 2))
}
func polyfit(x, y *matrix.DenseMatrix, n int) *matrix.DenseMatrix {
m := x.Cols()
a := matrix.Zeros(m, n+1)
for i := 0; i < m; i++ {
for j := 0; j <= n; j++ {
a.Set(i, j, math.Pow(x.Get(0, i), float64(j)))
}
}
return lsqr(a, y.Transpose())
}
func lsqr(a, b *matrix.DenseMatrix) *matrix.DenseMatrix {
q, r := qr(a)
n := r.Cols()
prod, _ := q.Transpose().TimesDense(b)
return solveUT(r.GetMatrix(0, 0, n, n), prod.GetMatrix(0, 0, n, 1))
}
func solveUT(r, b *matrix.DenseMatrix) *matrix.DenseMatrix {
n := r.Cols()
x := matrix.Zeros(n, 1)
for k := n - 1; k >= 0; k-- {
sum := 0.
for j := k + 1; j < n; j++ {
sum += r.Get(k, j) * x.Get(j, 0)
}
x.Set(k, 0, (b.Get(k, 0)-sum)/r.Get(k, k))
}
return x
} | Task/QR-decomposition/Go/qr-decomposition.go | 0.758153 | 0.680655 | qr-decomposition.go | starcoder |
func getLength(array) {
"""
Get the length of an array like object.
INPUT <= array object
OUTPUT => integer array length
"""
count = 0
for _ in array {
count += 1
return count
func getMiddleOfLengthInsert(length) {
"""
Get the position for inserting an item in the middle the given length.
INPUT <= integer length
OUTPUT => integer position
"""
return (length + 1) // 2
func yieldItemsWithItem(array, item, count, pos) {
"""
Yield items from array with item inserted at the given position.
INPUT
<= array object
<= new item
<= array length
<= middle position
OUTPUT => sequence of items from the array and item
"""
insertCheck = False
for i in range(count) {
if insertCheck {
yield array[i - 1]
elif i == pos {
yield item
insertCheck = True
else {
yield array[i]
func yieldItemsWithoutPos(array, count, pos) {
"""
Yield items from array without given position.
INPUT
<= array object
<= array length
<= middle position
OUTPUT => sequence of items from the array in order
"""
removeCheck = False
for i in range(count) {
if removeCheck {
yield array[i]
elif i == pos {
removeCheck = True
else {
yield array[i]
func insertShiftArray(array, item) {
"""
Create a new array with input array items and new item in the middle.
INPUT
<= array object
<= new item
OUTPUT => new array
"""
count = getLength(array)
pos = getMiddleOfLengthInsert(count)
count += 1
output = list(yieldItemsWithItem(array, item, count, pos))
return output
func removeShiftArray(array) {
"""
Create a new array with the middle item removed from input.
INPUT <= array object
OUTPUT => new array
"""
count = getLength(array)
pos = count // 2
output = list(yieldItemsWithoutPos(array, count, pos))
return output | shift_array/shift_array.go | 0.773388 | 0.788013 | shift_array.go | starcoder |
package mlpack
/*
#cgo CFLAGS: -I./capi -Wall
#cgo LDFLAGS: -L. -lmlpack_go_logistic_regression
#include <capi/logistic_regression.h>
#include <stdlib.h>
*/
import "C"
import "gonum.org/v1/gonum/mat"
type LogisticRegressionOptionalParam struct {
BatchSize int
DecisionBoundary float64
InputModel *logisticRegression
Labels *mat.Dense
Lambda float64
MaxIterations int
Optimizer string
StepSize float64
Test *mat.Dense
Tolerance float64
Training *mat.Dense
Verbose bool
}
func LogisticRegressionOptions() *LogisticRegressionOptionalParam {
return &LogisticRegressionOptionalParam{
BatchSize: 64,
DecisionBoundary: 0.5,
InputModel: nil,
Labels: nil,
Lambda: 0,
MaxIterations: 10000,
Optimizer: "lbfgs",
StepSize: 0.01,
Test: nil,
Tolerance: 1e-10,
Training: nil,
Verbose: false,
}
}
/*
An implementation of L2-regularized logistic regression using either the
L-BFGS optimizer or SGD (stochastic gradient descent). This solves the
regression problem
y = (1 / 1 + e^-(X * b))
where y takes values 0 or 1.
This program allows loading a logistic regression model (via the "InputModel"
parameter) or training a logistic regression model given training data
(specified with the "Training" parameter), or both those things at once. In
addition, this program allows classification on a test dataset (specified with
the "Test" parameter) and the classification results may be saved with the
"Predictions" output parameter. The trained logistic regression model may be
saved using the "OutputModel" output parameter.
The training data, if specified, may have class labels as its last dimension.
Alternately, the "Labels" parameter may be used to specify a separate matrix
of labels.
When a model is being trained, there are many options. L2 regularization (to
prevent overfitting) can be specified with the "Lambda" option, and the
optimizer used to train the model can be specified with the "Optimizer"
parameter. Available options are 'sgd' (stochastic gradient descent) and
'lbfgs' (the L-BFGS optimizer). There are also various parameters for the
optimizer; the "MaxIterations" parameter specifies the maximum number of
allowed iterations, and the "Tolerance" parameter specifies the tolerance for
convergence. For the SGD optimizer, the "StepSize" parameter controls the
step size taken at each iteration by the optimizer. The batch size for SGD is
controlled with the "BatchSize" parameter. If the objective function for your
data is oscillating between Inf and 0, the step size is probably too large.
There are more parameters for the optimizers, but the C++ interface must be
used to access these.
For SGD, an iteration refers to a single point. So to take a single pass over
the dataset with SGD, "MaxIterations" should be set to the number of points in
the dataset.
Optionally, the model can be used to predict the responses for another matrix
of data points, if "Test" is specified. The "Test" parameter can be specified
without the "Training" parameter, so long as an existing logistic regression
model is given with the "InputModel" parameter. The output predictions from
the logistic regression model may be saved with the "Predictions" parameter.
Note : The following parameters are deprecated and will be removed in mlpack
4: "Output", "OutputProbabilities"
Use "Predictions" instead of "Output"
Use "Probabilities" instead of "OutputProbabilities"
This implementation of logistic regression does not support the general
multi-class case but instead only the two-class case. Any labels must be
either 0 or 1. For more classes, see the softmax_regression program.
As an example, to train a logistic regression model on the data 'data' with
labels 'labels' with L2 regularization of 0.1, saving the model to 'lr_model',
the following command may be used:
// Initialize optional parameters for LogisticRegression().
param := mlpack.LogisticRegressionOptions()
param.Training = data
param.Labels = labels
param.Lambda = 0.1
_, lr_model, _, _, _ := mlpack.LogisticRegression(param)
Then, to use that model to predict classes for the dataset 'test', storing the
output predictions in 'predictions', the following command may be used:
// Initialize optional parameters for LogisticRegression().
param := mlpack.LogisticRegressionOptions()
param.InputModel = &lr_model
param.Test = test
predictions, _, _, _, _ := mlpack.LogisticRegression(param)
Input parameters:
- BatchSize (int): Batch size for SGD. Default value 64.
- DecisionBoundary (float64): Decision boundary for prediction; if the
logistic function for a point is less than the boundary, the class is
taken to be 0; otherwise, the class is 1. Default value 0.5.
- InputModel (logisticRegression): Existing model (parameters).
- Labels (mat.Dense): A matrix containing labels (0 or 1) for the
points in the training set (y).
- Lambda (float64): L2-regularization parameter for training. Default
value 0.
- MaxIterations (int): Maximum iterations for optimizer (0 indicates no
limit). Default value 10000.
- Optimizer (string): Optimizer to use for training ('lbfgs' or 'sgd').
Default value 'lbfgs'.
- StepSize (float64): Step size for SGD optimizer. Default value
0.01.
- Test (mat.Dense): Matrix containing test dataset.
- Tolerance (float64): Convergence tolerance for optimizer. Default
value 1e-10.
- Training (mat.Dense): A matrix containing the training set (the
matrix of predictors, X).
- Verbose (bool): Display informational messages and the full list of
parameters and timers at the end of execution.
Output parameters:
- output (mat.Dense): If test data is specified, this matrix is where
the predictions for the test set will be saved.
- outputModel (logisticRegression): Output for trained logistic
regression model.
- outputProbabilities (mat.Dense): If test data is specified, this
matrix is where the class probabilities for the test set will be saved.
- predictions (mat.Dense): If test data is specified, this matrix is
where the predictions for the test set will be saved.
- probabilities (mat.Dense): If test data is specified, this matrix is
where the class probabilities for the test set will be saved.
*/
func LogisticRegression(param *LogisticRegressionOptionalParam) (*mat.Dense, logisticRegression, *mat.Dense, *mat.Dense, *mat.Dense) {
resetTimers()
enableTimers()
disableBacktrace()
disableVerbose()
restoreSettings("L2-regularized Logistic Regression and Prediction")
// Detect if the parameter was passed; set if so.
if param.BatchSize != 64 {
setParamInt("batch_size", param.BatchSize)
setPassed("batch_size")
}
// Detect if the parameter was passed; set if so.
if param.DecisionBoundary != 0.5 {
setParamDouble("decision_boundary", param.DecisionBoundary)
setPassed("decision_boundary")
}
// Detect if the parameter was passed; set if so.
if param.InputModel != nil {
setLogisticRegression("input_model", param.InputModel)
setPassed("input_model")
}
// Detect if the parameter was passed; set if so.
if param.Labels != nil {
gonumToArmaUrow("labels", param.Labels)
setPassed("labels")
}
// Detect if the parameter was passed; set if so.
if param.Lambda != 0 {
setParamDouble("lambda", param.Lambda)
setPassed("lambda")
}
// Detect if the parameter was passed; set if so.
if param.MaxIterations != 10000 {
setParamInt("max_iterations", param.MaxIterations)
setPassed("max_iterations")
}
// Detect if the parameter was passed; set if so.
if param.Optimizer != "lbfgs" {
setParamString("optimizer", param.Optimizer)
setPassed("optimizer")
}
// Detect if the parameter was passed; set if so.
if param.StepSize != 0.01 {
setParamDouble("step_size", param.StepSize)
setPassed("step_size")
}
// Detect if the parameter was passed; set if so.
if param.Test != nil {
gonumToArmaMat("test", param.Test)
setPassed("test")
}
// Detect if the parameter was passed; set if so.
if param.Tolerance != 1e-10 {
setParamDouble("tolerance", param.Tolerance)
setPassed("tolerance")
}
// Detect if the parameter was passed; set if so.
if param.Training != nil {
gonumToArmaMat("training", param.Training)
setPassed("training")
}
// Detect if the parameter was passed; set if so.
if param.Verbose != false {
setParamBool("verbose", param.Verbose)
setPassed("verbose")
enableVerbose()
}
// Mark all output options as passed.
setPassed("output")
setPassed("output_model")
setPassed("output_probabilities")
setPassed("predictions")
setPassed("probabilities")
// Call the mlpack program.
C.mlpackLogisticRegression()
// Initialize result variable and get output.
var outputPtr mlpackArma
output := outputPtr.armaToGonumUrow("output")
var outputModel logisticRegression
outputModel.getLogisticRegression("output_model")
var outputProbabilitiesPtr mlpackArma
outputProbabilities := outputProbabilitiesPtr.armaToGonumMat("output_probabilities")
var predictionsPtr mlpackArma
predictions := predictionsPtr.armaToGonumUrow("predictions")
var probabilitiesPtr mlpackArma
probabilities := probabilitiesPtr.armaToGonumMat("probabilities")
// Clear settings.
clearSettings()
// Return output(s).
return output, outputModel, outputProbabilities, predictions, probabilities
} | logistic_regression.go | 0.667364 | 0.51013 | logistic_regression.go | starcoder |
package view
import (
"fmt"
"github.com/protolambda/ztyp/codec"
. "github.com/protolambda/ztyp/tree"
)
type ComplexVectorTypeDef struct {
ElemType TypeDef
VectorLength uint64
ComplexTypeBase
}
func ComplexVectorType(elemType TypeDef, length uint64) *ComplexVectorTypeDef {
minSize := uint64(0)
maxSize := uint64(0)
size := uint64(0)
isFixedSize := elemType.IsFixedByteLength()
if isFixedSize {
size = length * elemType.TypeByteLength()
minSize = size
maxSize = size
} else {
minSize = length * (elemType.MinByteLength() + OffsetByteLength)
maxSize = length * (elemType.MaxByteLength() + OffsetByteLength)
}
return &ComplexVectorTypeDef{
ElemType: elemType,
VectorLength: length,
ComplexTypeBase: ComplexTypeBase{
MinSize: minSize,
MaxSize: maxSize,
Size: size,
IsFixedSize: isFixedSize,
},
}
}
func (td *ComplexVectorTypeDef) FromElements(v ...View) (*ComplexVectorView, error) {
if td.VectorLength != uint64(len(v)) {
return nil, fmt.Errorf("expected %d elements, got %d", td.VectorLength, len(v))
}
nodes := make([]Node, td.VectorLength, td.VectorLength)
for i, el := range v {
nodes[i] = el.Backing()
}
depth := CoverDepth(td.VectorLength)
rootNode, _ := SubtreeFillToContents(nodes, depth)
vecView, _ := td.ViewFromBacking(rootNode, nil)
return vecView.(*ComplexVectorView), nil
}
func (td *ComplexVectorTypeDef) ElementType() TypeDef {
return td.ElemType
}
func (td *ComplexVectorTypeDef) Length() uint64 {
return td.VectorLength
}
func (td *ComplexVectorTypeDef) DefaultNode() Node {
depth := CoverDepth(td.VectorLength)
// The same node N times: the node is immutable, so re-use is safe.
defaultNode := td.ElemType.DefaultNode()
// can ignore error, depth is derived from length.
rootNode, _ := SubtreeFillToLength(defaultNode, depth, td.VectorLength)
return rootNode
}
func (td *ComplexVectorTypeDef) ViewFromBacking(node Node, hook BackingHook) (View, error) {
depth := CoverDepth(td.VectorLength)
return &ComplexVectorView{
SubtreeView: SubtreeView{
BackedView: BackedView{
ViewBase: ViewBase{
TypeDef: td,
},
Hook: hook,
BackingNode: node,
},
depth: depth,
},
ComplexVectorTypeDef: td,
}, nil
}
func (td *ComplexVectorTypeDef) Default(hook BackingHook) View {
v, _ := td.ViewFromBacking(td.DefaultNode(), hook)
return v
}
func (td *ComplexVectorTypeDef) New() *ComplexVectorView {
return td.Default(nil).(*ComplexVectorView)
}
func (td *ComplexVectorTypeDef) Deserialize(dr *codec.DecodingReader) (View, error) {
scope := dr.Scope()
if td.IsFixedSize {
elemSize := td.ElemType.TypeByteLength()
if td.Size != scope {
return nil, fmt.Errorf("expected size %d does not match scope %d", td.Size, scope)
}
elements := make([]View, td.VectorLength, td.VectorLength)
for i := uint64(0); i < td.VectorLength; i++ {
sub, err := dr.SubScope(elemSize)
if err != nil {
return nil, err
}
el, err := td.ElemType.Deserialize(sub)
if err != nil {
return nil, err
}
elements[i] = el
}
return td.FromElements(elements...)
} else {
offsets := make([]uint32, td.VectorLength, td.VectorLength)
prevOffset := uint32(0)
for i := uint64(0); i < td.VectorLength; i++ {
offset, err := dr.ReadOffset()
if err != nil {
return nil, err
}
if offset < prevOffset {
return nil, fmt.Errorf("offset %d for element %d is smaller than previous offset %d", offset, i, prevOffset)
}
offsets[i] = offset
prevOffset = offset
}
elements := make([]View, td.VectorLength, td.VectorLength)
lastIndex := uint32(len(elements) - 1)
for i := uint32(0); i < lastIndex; i++ {
size := offsets[i+1] - offsets[i]
sub, err := dr.SubScope(uint64(size))
if err != nil {
return nil, err
}
el, err := td.ElemType.Deserialize(sub)
if err != nil {
return nil, err
}
elements[i] = el
}
sub, err := dr.SubScope(scope - uint64(offsets[lastIndex]))
if err != nil {
return nil, err
}
el, err := td.ElemType.Deserialize(sub)
if err != nil {
return nil, err
}
elements[lastIndex] = el
return td.FromElements(elements...)
}
}
func (td *ComplexVectorTypeDef) String() string {
return fmt.Sprintf("Vector[%s, %d]", td.ElemType.String(), td.VectorLength)
}
type ComplexVectorView struct {
SubtreeView
*ComplexVectorTypeDef
}
func AsComplexVector(v View, err error) (*ComplexVectorView, error) {
if err != nil {
return nil, err
}
c, ok := v.(*ComplexVectorView)
if !ok {
return nil, fmt.Errorf("view is not a vector: %v", v)
}
return c, nil
}
func (tv *ComplexVectorView) Get(i uint64) (View, error) {
if i >= tv.ComplexVectorTypeDef.VectorLength {
return nil, fmt.Errorf("cannot get item at element index %d, vector only has %d elements", i, tv.ComplexVectorTypeDef.VectorLength)
}
v, err := tv.SubtreeView.GetNode(i)
if err != nil {
return nil, err
}
return tv.ComplexVectorTypeDef.ElemType.ViewFromBacking(v, tv.ItemHook(i))
}
func (tv *ComplexVectorView) Set(i uint64, v View) error {
return tv.setNode(i, v.Backing())
}
func (tv *ComplexVectorView) setNode(i uint64, b Node) error {
if i >= tv.ComplexVectorTypeDef.VectorLength {
return fmt.Errorf("cannot set item at element index %d, vector only has %d elements", i, tv.ComplexVectorTypeDef.VectorLength)
}
return tv.SubtreeView.SetNode(i, b)
}
func (tv *ComplexVectorView) ItemHook(i uint64) BackingHook {
return func(b Node) error {
return tv.setNode(i, b)
}
}
func (tv *ComplexVectorView) Copy() (View, error) {
tvCopy := *tv
tvCopy.Hook = nil
return &tvCopy, nil
}
func (tv *ComplexVectorView) Iter() ElemIter {
i := uint64(0)
return ElemIterFn(func() (elem View, ok bool, err error) {
if i < tv.VectorLength {
elem, err = tv.Get(i)
ok = true
i += 1
return
} else {
return nil, false, nil
}
})
}
func (tv *ComplexVectorView) ReadonlyIter() ElemIter {
return elemReadonlyIter(tv.BackingNode, tv.VectorLength, tv.depth, tv.ElemType)
}
func (tv *ComplexVectorView) ValueByteLength() (uint64, error) {
if tv.IsFixedSize {
return tv.Size, nil
} else {
size := tv.VectorLength * OffsetByteLength
iter := tv.ReadonlyIter()
for {
elem, ok, err := iter.Next()
if err != nil {
return 0, err
}
if !ok {
break
}
valSize, err := elem.ValueByteLength()
if err != nil {
return 0, err
}
size += valSize
}
return size, nil
}
}
func (tv *ComplexVectorView) Serialize(w *codec.EncodingWriter) error {
if tv.IsFixedSize {
return serializeComplexFixElemSeries(tv.ReadonlyIter(), w)
} else {
return serializeComplexVarElemSeries(tv.VectorLength, tv.ReadonlyIter, w)
}
} | view/complex_vector.go | 0.549399 | 0.554712 | complex_vector.go | starcoder |
package axmlParser
type Listener interface {
StartDocument()
/**
* Receive notification of the end of a document.
*/
EndDocument()
/**
* Begin the scope of a prefix-URI Namespace mapping.
*
* @param prefix
* the Namespace prefix being declared. An empty string is used
* for the default element namespace, which has no prefix.
* @param uri
* the Namespace URI the prefix is mapped to
*/
StartPrefixMapping(prefix, uri string)
/**
* End the scope of a prefix-URI mapping.
*
* @param prefix
* the prefix that was being mapped. This is the empty string
* when a default mapping scope ends.
* @param uri
* the Namespace URI the prefix is mapped to
*/
EndPrefixMapping(prefix, uri string)
/**
* Receive notification of the beginning of an element.
*
* @param uri
* the Namespace URI, or the empty string if the element has no
* Namespace URI or if Namespace processing is not being
* performed
* @param localName
* the local name (without prefix), or the empty string if
* Namespace processing is not being performed
* @param qName
* the qualified name (with prefix), or the empty string if
* qualified names are not available
* @param atts
* the attributes attached to the element. If there are no
* attributes, it shall be an empty Attributes object. The value
* of this object after startElement returns is undefined
*/
StartElement(uri, localName, qName string,
atts []*Attribute)
/**
* Receive notification of the end of an element.
*
* @param uri
* the Namespace URI, or the empty string if the element has no
* Namespace URI or if Namespace processing is not being
* performed
* @param localName
* the local name (without prefix), or the empty string if
* Namespace processing is not being performed
* @param qName
* the qualified XML name (with prefix), or the empty string if
* qualified names are not available
*/
EndElement(uri, localName, qName string)
/**
* Receive notification of text.
*
* @param data
* the text data
*/
Text(data string)
/**
* Receive notification of character data (in a <![CDATA[ ]]> block).
*
* @param data
* the text data
*/
CharacterData(data string)
/**
* Receive notification of a processing instruction.
*
* @param target
* the processing instruction target
* @param data
* the processing instruction data, or null if none was supplied.
* The data does not include any whitespace separating it from
* the target
* @throws org.xml.sax.SAXException
* any SAX exception, possibly wrapping another exception
*/
ProcessingInstruction(target, data string)
} | listener.go | 0.698227 | 0.487002 | listener.go | starcoder |
package types
import (
"encoding/json"
"math/big"
"math/rand"
)
func newIntegerFromString(s string) (*big.Int, bool) {
return new(big.Int).SetString(s, 0)
}
func equal(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 0 }
func gt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == 1 }
func lt(i *big.Int, i2 *big.Int) bool { return i.Cmp(i2) == -1 }
func add(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Add(i, i2) }
func sub(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Sub(i, i2) }
func mul(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mul(i, i2) }
func div(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Div(i, i2) }
func mod(i *big.Int, i2 *big.Int) *big.Int { return new(big.Int).Mod(i, i2) }
func neg(i *big.Int) *big.Int { return new(big.Int).Neg(i) }
func random(i *big.Int) *big.Int { return new(big.Int).Rand(rand.New(rand.NewSource(rand.Int63())), i) }
func min(i *big.Int, i2 *big.Int) *big.Int {
if i.Cmp(i2) == 1 {
return new(big.Int).Set(i2)
}
return new(big.Int).Set(i)
}
// MarshalAmino for custom encoding scheme
func marshalAmino(i *big.Int) (string, error) {
bz, err := i.MarshalText()
return string(bz), err
}
// UnmarshalAmino for custom decoding scheme
func unmarshalAmino(i *big.Int, text string) (err error) {
return i.UnmarshalText([]byte(text))
}
// MarshalJSON for custom encoding scheme
// Must be encoded as a string for JSON precision
func marshalJSON(i *big.Int) ([]byte, error) {
text, err := i.MarshalText()
if err != nil {
return nil, err
}
return json.Marshal(string(text))
}
// UnmarshalJSON for custom decoding scheme
// Must be encoded as a string for JSON precision
func unmarshalJSON(i *big.Int, bz []byte) error {
var text string
err := json.Unmarshal(bz, &text)
if err != nil {
return err
}
return i.UnmarshalText([]byte(text))
}
// BigInt wraps integer with 256 bit range bound
// Checks overflow, underflow and division by zero
// Exists in range from -(2^255-1) to 2^255-1
type BigInt struct {
i *big.Int
}
// BigInt converts BigInt to big.BigInt
func (i BigInt) BigInt() *big.Int {
return new(big.Int).Set(i.i)
}
// NewInt constructs BigInt from int64
func NewInt(n int64) BigInt {
return BigInt{big.NewInt(n)}
}
// NewIntFromBigInt constructs BigInt from big.BigInt
func NewIntFromBigInt(i *big.Int) BigInt {
if i.BitLen() > 255 {
panic("NewIntFromBigInt() out of bound")
}
return BigInt{i}
}
// NewIntFromString constructs BigInt from string
func NewIntFromString(s string) (res BigInt, ok bool) {
i, ok := newIntegerFromString(s)
if !ok {
return
}
// Check overflow
if i.BitLen() > 255 {
ok = false
return
}
return BigInt{i}, true
}
// NewIntWithDecimal constructs BigInt with decimal
// Result value is n*10^dec
func NewIntWithDecimal(n int64, dec int) BigInt {
if dec < 0 {
panic("NewIntWithDecimal() decimal is negative")
}
exp := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(dec)), nil)
i := new(big.Int)
i.Mul(big.NewInt(n), exp)
// Check overflow
if i.BitLen() > 255 {
panic("NewIntWithDecimal() out of bound")
}
return BigInt{i}
}
// ZeroInt returns BigInt value with zero
func ZeroInt() BigInt { return BigInt{big.NewInt(0)} }
// OneInt returns BigInt value with one
func OneInt() BigInt { return BigInt{big.NewInt(1)} }
// Int64 converts BigInt to int64
// Panics if the value is out of range
func (i BigInt) Int64() int64 {
if !i.i.IsInt64() {
panic("Int64() out of bound")
}
return i.i.Int64()
}
// IsInt64 returns true if Int64() not panics
func (i BigInt) IsInt64() bool {
return i.i.IsInt64()
}
// IsZero returns true if BigInt is zero
func (i BigInt) IsZero() bool {
return i.i.Sign() == 0
}
// Sign returns sign of BigInt
func (i BigInt) Sign() int {
return i.i.Sign()
}
// Equal compares two Ints
func (i BigInt) Equal(i2 BigInt) bool {
return equal(i.i, i2.i)
}
// GT returns true if first BigInt is greater than second
func (i BigInt) GT(i2 BigInt) bool {
return gt(i.i, i2.i)
}
// LT returns true if first BigInt is lesser than second
func (i BigInt) LT(i2 BigInt) bool {
return lt(i.i, i2.i)
}
// Add adds BigInt from another
func (i BigInt) Add(i2 BigInt) (res BigInt) {
res = BigInt{add(i.i, i2.i)}
// Check overflow
if res.i.BitLen() > 255 {
panic("BigInt overflow")
}
return
}
// AddRaw adds int64 to BigInt
func (i BigInt) AddRaw(i2 int64) BigInt {
return i.Add(NewInt(i2))
}
// Sub subtracts BigInt from another
func (i BigInt) Sub(i2 BigInt) (res BigInt) {
res = BigInt{sub(i.i, i2.i)}
// Check overflow
if res.i.BitLen() > 255 {
panic("BigInt overflow")
}
return
}
// SubRaw subtracts int64 from BigInt
func (i BigInt) SubRaw(i2 int64) BigInt {
return i.Sub(NewInt(i2))
}
// Mul multiples two Ints
func (i BigInt) Mul(i2 BigInt) (res BigInt) {
// Check overflow
if i.i.BitLen()+i2.i.BitLen()-1 > 255 {
panic("BigInt overflow")
}
res = BigInt{mul(i.i, i2.i)}
// Check overflow if sign of both are same
if res.i.BitLen() > 255 {
panic("BigInt overflow")
}
return
}
// MulRaw multipies BigInt and int64
func (i BigInt) MulRaw(i2 int64) BigInt {
return i.Mul(NewInt(i2))
}
// Div divides BigInt with BigInt
func (i BigInt) Div(i2 BigInt) (res BigInt) {
// Check division-by-zero
if i2.i.Sign() == 0 {
panic("Division by zero")
}
return BigInt{div(i.i, i2.i)}
}
// DivRaw divides BigInt with int64
func (i BigInt) DivRaw(i2 int64) BigInt {
return i.Div(NewInt(i2))
}
// Mod returns remainder after dividing with BigInt
func (i BigInt) Mod(i2 BigInt) BigInt {
if i2.Sign() == 0 {
panic("division-by-zero")
}
return BigInt{mod(i.i, i2.i)}
}
// ModRaw returns remainder after dividing with int64
func (i BigInt) ModRaw(i2 int64) BigInt {
return i.Mod(NewInt(i2))
}
// Neg negates BigInt
func (i BigInt) Neg() (res BigInt) {
return BigInt{neg(i.i)}
}
// Return the minimum of the ints
func MinInt(i1, i2 BigInt) BigInt {
return BigInt{min(i1.BigInt(), i2.BigInt())}
}
// Human readable string
func (i BigInt) String() string {
return i.i.String()
}
// Testing purpose random BigInt generator
func randomInt(i BigInt) BigInt {
return NewIntFromBigInt(random(i.BigInt()))
}
// MarshalAmino defines custom encoding scheme
func (i BigInt) MarshalAmino() (string, error) {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil
i.i = new(big.Int)
}
return marshalAmino(i.i)
}
// UnmarshalAmino defines custom decoding scheme
func (i *BigInt) UnmarshalAmino(text string) error {
if i.i == nil { // Necessary since default BigInt initialization has i.i as nil
i.i = new(big.Int)
}
return unmarshalAmino(i.i, text)
}
// MarshalJSON defines custom encoding scheme
func (i BigInt) MarshalJSON() ([]byte, error) {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil
i.i = new(big.Int)
}
return marshalJSON(i.i)
}
// UnmarshalJSON defines custom decoding scheme
func (i *BigInt) UnmarshalJSON(bz []byte) error {
if i.i == nil { // Necessary since default BigInt initialization has i.i as nil
i.i = new(big.Int)
}
return unmarshalJSON(i.i, bz)
}
// BigInt wraps integer with 256 bit range bound
// Checks overflow, underflow and division by zero
// Exists in range from 0 to 2^256-1
type Uint struct {
i *big.Int
}
// BigInt converts Uint to big.Unt
func (i Uint) BigInt() *big.Int {
return new(big.Int).Set(i.i)
}
// NewUint constructs Uint from int64
func NewUint(n uint64) Uint {
i := new(big.Int)
i.SetUint64(n)
return Uint{i}
}
// NewUintFromBigUint constructs Uint from big.Uint
func NewUintFromBigInt(i *big.Int) Uint {
// Check overflow
if i.Sign() == -1 || i.Sign() == 1 && i.BitLen() > 256 {
panic("Uint overflow")
}
return Uint{i}
}
// NewUintFromString constructs Uint from string
func NewUintFromString(s string) (res Uint, ok bool) {
i, ok := newIntegerFromString(s)
if !ok {
return
}
// Check overflow
if i.Sign() == -1 || i.Sign() == 1 && i.BitLen() > 256 {
ok = false
return
}
return Uint{i}, true
}
// NewUintWithDecimal constructs Uint with decimal
// Result value is n*10^dec
func NewUintWithDecimal(n uint64, dec int) Uint {
if dec < 0 {
panic("NewUintWithDecimal() decimal is negative")
}
exp := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(dec)), nil)
i := new(big.Int)
i.Mul(new(big.Int).SetUint64(n), exp)
// Check overflow
if i.Sign() == -1 || i.Sign() == 1 && i.BitLen() > 256 {
panic("NewUintWithDecimal() out of bound")
}
return Uint{i}
}
// ZeroUint returns Uint value with zero
func ZeroUint() Uint { return Uint{big.NewInt(0)} }
// OneUint returns Uint value with one
func OneUint() Uint { return Uint{big.NewInt(1)} }
// Uint64 converts Uint to uint64
// Panics if the value is out of range
func (i Uint) Uint64() uint64 {
if !i.i.IsUint64() {
panic("Uint64() out of bound")
}
return i.i.Uint64()
}
// IsUint64 returns true if Uint64() not panics
func (i Uint) IsUint64() bool {
return i.i.IsUint64()
}
// IsZero returns true if Uint is zero
func (i Uint) IsZero() bool {
return i.i.Sign() == 0
}
// Sign returns sign of Uint
func (i Uint) Sign() int {
return i.i.Sign()
}
// Equal compares two Uints
func (i Uint) Equal(i2 Uint) bool {
return equal(i.i, i2.i)
}
// GT returns true if first Uint is greater than second
func (i Uint) GT(i2 Uint) bool {
return gt(i.i, i2.i)
}
// LT returns true if first Uint is lesser than second
func (i Uint) LT(i2 Uint) bool {
return lt(i.i, i2.i)
}
// Add adds Uint from another
func (i Uint) Add(i2 Uint) (res Uint) {
res = Uint{add(i.i, i2.i)}
// Check overflow
if res.Sign() == -1 || res.Sign() == 1 && res.i.BitLen() > 256 {
panic("Uint overflow")
}
return
}
// AddRaw adds uint64 to Uint
func (i Uint) AddRaw(i2 uint64) Uint {
return i.Add(NewUint(i2))
}
// Sub subtracts Uint from another
func (i Uint) Sub(i2 Uint) (res Uint) {
res = Uint{sub(i.i, i2.i)}
// Check overflow
if res.Sign() == -1 || res.Sign() == 1 && res.i.BitLen() > 256 {
panic("Uint overflow")
}
return
}
// SubRaw subtracts uint64 from Uint
func (i Uint) SubRaw(i2 uint64) Uint {
return i.Sub(NewUint(i2))
}
// Mul multiples two Uints
func (i Uint) Mul(i2 Uint) (res Uint) {
// Check overflow
if i.i.BitLen()+i2.i.BitLen()-1 > 256 {
panic("Uint overflow")
}
res = Uint{mul(i.i, i2.i)}
// Check overflow
if res.Sign() == -1 || res.Sign() == 1 && res.i.BitLen() > 256 {
panic("Uint overflow")
}
return
}
// MulRaw multipies Uint and uint64
func (i Uint) MulRaw(i2 uint64) Uint {
return i.Mul(NewUint(i2))
}
// Div divides Uint with Uint
func (i Uint) Div(i2 Uint) (res Uint) {
// Check division-by-zero
if i2.Sign() == 0 {
panic("division-by-zero")
}
return Uint{div(i.i, i2.i)}
}
// Div divides Uint with uint64
func (i Uint) DivRaw(i2 uint64) Uint {
return i.Div(NewUint(i2))
}
// Mod returns remainder after dividing with Uint
func (i Uint) Mod(i2 Uint) Uint {
if i2.Sign() == 0 {
panic("division-by-zero")
}
return Uint{mod(i.i, i2.i)}
}
// ModRaw returns remainder after dividing with uint64
func (i Uint) ModRaw(i2 uint64) Uint {
return i.Mod(NewUint(i2))
}
// Return the minimum of the Uints
func MinUint(i1, i2 Uint) Uint {
return Uint{min(i1.BigInt(), i2.BigInt())}
}
// Human readable string
func (i Uint) String() string {
return i.i.String()
}
// Testing purpose random Uint generator
func randomUint(i Uint) Uint {
return NewUintFromBigInt(random(i.BigInt()))
}
// MarshalAmino defines custom encoding scheme
func (i Uint) MarshalAmino() (string, error) {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil
i.i = new(big.Int)
}
return marshalAmino(i.i)
}
// UnmarshalAmino defines custom decoding scheme
func (i *Uint) UnmarshalAmino(text string) error {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil
i.i = new(big.Int)
}
return unmarshalAmino(i.i, text)
}
// MarshalJSON defines custom encoding scheme
func (i Uint) MarshalJSON() ([]byte, error) {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil
i.i = new(big.Int)
}
return marshalJSON(i.i)
}
// UnmarshalJSON defines custom decoding scheme
func (i *Uint) UnmarshalJSON(bz []byte) error {
if i.i == nil { // Necessary since default Uint initialization has i.i as nil
i.i = new(big.Int)
}
return unmarshalJSON(i.i, bz)
} | types/int.go | 0.744749 | 0.425784 | int.go | starcoder |
package volumes
import (
"github.com/rackspace/gophercloud"
"github.com/rackspace/gophercloud/pagination"
"github.com/mitchellh/mapstructure"
)
// Volume contains all the information associated with an OpenStack Volume.
type Volume struct {
// Instances onto which the volume is attached.
Attachments []map[string]interface{} `mapstructure:"attachments"`
// AvailabilityZone is which availability zone the volume is in.
AvailabilityZone string `mapstructure:"availability_zone"`
// Indicates whether this is a bootable volume.
Bootable string `mapstructure:"bootable"`
// ConsistencyGroupID is the consistency group ID.
ConsistencyGroupID string `mapstructure:"consistencygroup_id"`
// The date when this volume was created.
CreatedAt string `mapstructure:"created_at"`
// Human-readable description for the volume.
Description string `mapstructure:"description"`
// Encrypted denotes if the volume is encrypted.
Encrypted bool `mapstructure:"encrypted"`
// Human-readable display name for the volume.
Name string `mapstructure:"name"`
// The type of volume to create, either SATA or SSD.
VolumeType string `mapstructure:"volume_type"`
// ReplicationDriverData contains data about the replication driver.
ReplicationDriverData string `mapstructure:"os-volume-replication:driver_data"`
// ReplicationExtendedStatus contains extended status about replication.
ReplicationExtendedStatus string `mapstructure:"os-volume-replication:extended_status"`
// ReplicationStatus is the status of replication.
ReplicationStatus string `mapstructure:"replication_status"`
// The ID of the snapshot from which the volume was created
SnapshotID string `mapstructure:"snapshot_id"`
// The ID of another block storage volume from which the current volume was created
SourceVolID string `mapstructure:"source_volid"`
// Current status of the volume.
Status string `mapstructure:"status"`
// TenantID is the id of the project that owns the volume.
TenantID string `mapstructure:"os-vol-tenant-attr:tenant_id"`
// Arbitrary key-value pairs defined by the user.
Metadata map[string]string `mapstructure:"metadata"`
// Multiattach denotes if the volume is multi-attach capable.
Multiattach bool `mapstructure:"multiattach"`
// Unique identifier for the volume.
ID string `mapstructure:"id"`
// Size of the volume in GB.
Size int `mapstructure:"size"`
// UserID is the id of the user who created the volume.
UserID string `mapstructure:"user_id"`
}
// CreateResult contains the response body and error from a Create request.
type CreateResult struct {
commonResult
}
// GetResult contains the response body and error from a Get request.
type GetResult struct {
commonResult
}
// DeleteResult contains the response body and error from a Delete request.
type DeleteResult struct {
gophercloud.ErrResult
}
// ListResult is a pagination.pager that is returned from a call to the List function.
type ListResult struct {
pagination.SinglePageBase
}
// IsEmpty returns true if a ListResult contains no Volumes.
func (r ListResult) IsEmpty() (bool, error) {
volumes, err := ExtractVolumes(r)
if err != nil {
return true, err
}
return len(volumes) == 0, nil
}
// ExtractVolumes extracts and returns Volumes. It is used while iterating over a volumes.List call.
func ExtractVolumes(page pagination.Page) ([]Volume, error) {
var response struct {
Volumes []Volume `json:"volumes"`
}
err := mapstructure.Decode(page.(ListResult).Body, &response)
return response.Volumes, err
}
// UpdateResult contains the response body and error from an Update request.
type UpdateResult struct {
commonResult
}
type commonResult struct {
gophercloud.Result
}
// Extract will get the Volume object out of the commonResult object.
func (r commonResult) Extract() (*Volume, error) {
if r.Err != nil {
return nil, r.Err
}
var res struct {
Volume *Volume `json:"volume"`
}
err := mapstructure.Decode(r.Body, &res)
return res.Volume, err
} | vendor/github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes/results.go | 0.752013 | 0.411643 | results.go | starcoder |
package chrono
import (
"fmt"
"strconv"
"time"
)
// Constants for calculating time in microsecond resolution.
const (
secondsPerDay = 86400
microsPerSecond = 1000000
microsPerNano = 1000
)
// Time is interpreted and stored at a microsecond-level resolution. This
// enables times ranging from January 1, 0001 (zero time) to January 10, 292278.
// Time is parsed as UTC.
var (
zero = time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC)
// TimeLayouts is a list of time layouts that are used when parsing
// a time string.
timeLayouts = []string{
"02-01-2006",
"02-01-2006 3:04 PM",
"02-01-2006 3:04 PM -0700",
"02-01-2006 3:04 PM -07:00",
"_2 January 2006",
"_2 January 2006 3:04 PM",
"_2 January 2006 3:04 PM -0700",
"_2 January 2006 3:04 PM -07:00",
"2006-01-02",
"2006-01-02 3:04 PM",
"2006-01-02 3:04 PM -0700",
"2006-01-02 3:04 PM -07:00",
time.RFC1123,
time.RFC1123Z,
time.RFC822,
time.RFC822Z,
"January _2, 2006",
"January _2, 2006 3:04 PM",
"January _2, 2006 3:04 PM -0700",
"January _2, 2006 3:04 PM -07:00",
"Jan _2, 2006",
"Jan _2, 2006, 3:04 PM",
"Jan _2, 2006 3:04 PM -0700",
"Jan _2, 2006 3:04 PM -07:00",
time.RFC3339,
time.ANSIC,
}
)
// ToTime coverts a microsecond resolution timestamp into a time.Time value.
func MicroTime(ts int64) time.Time {
// Integer division will truncate the floating point.
days := ts / secondsPerDay / microsPerSecond
// Get the remaining microseconds
micros := ts - days*secondsPerDay*microsPerSecond
// Add the days
t := zero.AddDate(0, 0, int(days))
// Add remaining microseconds.
return t.Add(time.Duration(micros) * time.Microsecond)
}
// fromTime converts a time.Time value in a microsecond resolution timestamp.
func TimeMicro(t time.Time) int64 {
// Ensure the time is in UTC
t = t.UTC()
yr := int64(t.Year() - 1)
// Elapsed taking in to account leap years.
elapsedDays := int64(yr*365+yr/4-yr/100+yr/400) + int64(t.YearDay()) - 1
// Remaining seconds.
elapsedSeconds := (elapsedDays*secondsPerDay + int64(t.Hour())*3600 + int64(t.Minute())*60 + int64(t.Second()))
return int64(elapsedSeconds*microsPerSecond + int64(t.Nanosecond())/microsPerNano)
}
// Norm takes a time and normalizes it to microsecond resolution.
func Norm(t time.Time) time.Time {
return MicroTime(TimeMicro(t))
}
// Format returns a string representation of the time.
func Format(t time.Time) string {
if t.IsZero() {
return ""
}
return t.Format(time.RFC3339)
}
// FormatNano returns a string representation of the time with nanosecond resolution.
func FormatNano(t time.Time) string {
if t.IsZero() {
return ""
}
return t.Format(time.RFC3339Nano)
}
// Parse parses a string into a time value. The string may represent an
// absolute time, duration relative to the current time, or a microsecond-resolution
// timestamp. All times are converted to UTC.
func Parse(s string) (time.Time, error) {
var (
t time.Time
d time.Duration
err error
)
// Duration
d, err = time.ParseDuration(s)
if err == nil {
return time.Now().UTC().Add(d), nil
}
// Parse time.
for _, layout := range timeLayouts {
t, err = time.Parse(layout, s)
if err == nil {
return t.UTC(), nil
}
}
// Timestamp; assume this is UTC time.
i, err := strconv.ParseInt(s, 10, 64)
if err == nil {
return MicroTime(i), nil
}
return zero, fmt.Errorf("time: could not parse %s", s)
}
// MustParse parses the passed time string or panics.
func MustParse(s string) time.Time {
t, err := Parse(s)
if err != nil {
panic(err)
}
return t
}
// JSON returns an interface value for a time value intended to be used
// when preparing a custom value for JSON encoding. It uses nil for zero
// time values.
func JSON(t time.Time) interface{} {
if t.IsZero() {
return nil
}
return t
} | chrono/time.go | 0.741206 | 0.45175 | time.go | starcoder |
package expression
import (
"fmt"
"github.com/dolthub/go-mysql-server/sql"
)
// Literal represents a literal expression (string, number, bool, ...).
type Literal struct {
value interface{}
fieldType sql.Type
}
var _ sql.Expression = &Literal{}
// NewLiteral creates a new Literal expression.
func NewLiteral(value interface{}, fieldType sql.Type) *Literal {
// TODO(juanjux): we should probably check here if the type is sql.VarChar and the
// Capacity of the Type and the length of the value, but this can't return an error
return &Literal{
value: value,
fieldType: fieldType,
}
}
// Resolved implements the Expression interface.
func (p *Literal) Resolved() bool {
return true
}
// IsNullable implements the Expression interface.
func (p *Literal) IsNullable() bool {
return p.value == nil
}
// Type implements the Expression interface.
func (p *Literal) Type() sql.Type {
return p.fieldType
}
// Eval implements the Expression interface.
func (p *Literal) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
return p.value, nil
}
func (p *Literal) String() string {
switch v := p.value.(type) {
case string:
return fmt.Sprintf("%q", v)
case []byte:
return "BLOB"
case nil:
return "NULL"
default:
return fmt.Sprint(v)
}
}
func (p *Literal) DebugString() string {
typeStr := p.fieldType.String()
switch v := p.value.(type) {
case string:
return fmt.Sprintf("%s (%s)", v, typeStr)
case []byte:
return fmt.Sprintf("BLOB(%s)", string(v))
case nil:
return fmt.Sprintf("NULL (%s)", typeStr)
case int, uint, int8, uint8, int16, uint16, int32, uint32, int64, uint64:
return fmt.Sprintf("%d (%s)", v, typeStr)
case float32, float64:
return fmt.Sprintf("%f (%s)", v, typeStr)
default:
return fmt.Sprintf("%s (%s)", v, typeStr)
}
}
// WithChildren implements the Expression interface.
func (p *Literal) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 0 {
return nil, sql.ErrInvalidChildrenNumber.New(p, len(children), 0)
}
return p, nil
}
// Children implements the Expression interface.
func (*Literal) Children() []sql.Expression {
return nil
}
// Value returns the literal value.
func (p *Literal) Value() interface{} {
return p.value
} | sql/expression/literal.go | 0.560253 | 0.443359 | literal.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.