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 gofields
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// GetValue will extract the value at the given path from the data Go struct
// E.g data = { Friends: []Friend{ { Name: "John" } }, path = "Friends.0.Name" will return "John"
func GetValue(data interface{}, path string) (interface{}, error) {
value := reflect.ValueOf(data)
v, err := getValue(value, []string{"$"}, strings.Split(path, "."))
if err != nil {
return nil, err
}
return v.Interface(), nil
}
func getValue(value reflect.Value, parents []string, path []string) (reflect.Value, error) {
if len(path) == 0 {
return value, nil
}
if !value.IsValid() || isNil(value) {
return reflect.Value{}, fmt.Errorf("field %s is nil", strings.Join(parents, "."))
}
if value.Type().Kind() == reflect.Ptr {
return getValue(value.Elem(), parents, path)
}
switch value.Kind() {
case reflect.Slice:
idx, err := strconv.Atoi(path[0])
if err != nil {
return reflect.Value{}, fmt.Errorf("trying to access array %s but %s is not a numerical index", strings.Join(parents, "."), path[0])
}
if idx > value.Len() {
return reflect.Value{}, fmt.Errorf("trying to access array %s but %d is out of range", strings.Join(parents, "."), idx)
}
return getValue(value.Index(idx), append(parents, path[0]), path[1:])
case reflect.Map:
v := value.MapIndex(reflect.ValueOf(path[0]))
if !v.IsValid() {
return reflect.Value{}, fmt.Errorf("trying to access map %s but %s key does not exist", strings.Join(parents, "."), path[0])
}
return getValue(v, append(parents, path[0]), path[1:])
case reflect.Struct:
f, exist := value.Type().FieldByName(path[0])
if !exist {
return reflect.Value{}, fmt.Errorf("field %s does not exist in %s", path[0], strings.Join(parents, "."))
}
if !isFieldPublic(f) {
return reflect.Value{}, fmt.Errorf("field %s is private in %s", path[0], strings.Join(parents, "."))
}
v := value.FieldByIndex(f.Index)
return getValue(v, append(parents, path[0]), path[1:])
default:
return reflect.Value{}, fmt.Errorf("cannot get %s in field %s", strings.Join(path, "."), strings.Join(parents, "."))
}
}
// GetType will extract the type at the given path from the data Go struct
// E.g data = { Friends: []Friend{ { Name: "John" } }, path = "Friends.0.Name" will return "John"
func GetType(t reflect.Type, path string) (reflect.Type, error) {
return getType(t, []string{"$"}, strings.Split(path, "."))
}
func getType(t reflect.Type, parents []string, path []string) (reflect.Type, error) {
if len(path) == 0 {
return t, nil
}
if t.Kind() == reflect.Ptr {
return getType(t.Elem(), parents, path)
}
switch t.Kind() {
case reflect.Slice:
_, err := strconv.Atoi(path[0])
if err != nil {
return nil, fmt.Errorf("trying to access array %s but %s is not a numerical index", strings.Join(parents, "."), path[0])
}
return getType(t.Elem(), append(parents, path[0]), path[1:])
case reflect.Map:
return getType(t.Elem(), append(parents, path[0]), path[1:])
case reflect.Struct:
field, exist := t.FieldByName(path[0])
if !exist {
return nil, fmt.Errorf("field %s does not exist in %s", path[0], strings.Join(parents, "."))
}
if !isFieldPublic(field) {
return nil, fmt.Errorf("field %s is private in %s", path[0], strings.Join(parents, "."))
}
return getType(field.Type, append(parents, path[0]), path[1:])
default:
return nil, fmt.Errorf("cannot get %s in field %s", strings.Join(path, "."), strings.Join(parents, "."))
}
}
type ListFieldFilter func(reflect.Type, string) bool
// ListFields will recursively list all fields path that can be used with GetType or GetValue
func ListFields(t reflect.Type) []string {
return listFields(t, []string(nil), nil)
}
// ListFieldsWithFilter is the same as ListFields but accept a filter method that will be call for each fields
func ListFieldsWithFilter(t reflect.Type, filter ListFieldFilter) []string {
return listFields(t, []string(nil), filter)
}
func listFields(t reflect.Type, parents []string, filter ListFieldFilter) []string {
if t.Kind() == reflect.Ptr {
return listFields(t.Elem(), parents, filter)
}
switch t.Kind() {
case reflect.Slice:
return listFields(t.Elem(), append(parents, "<index>"), filter)
case reflect.Map:
return listFields(t.Elem(), append(parents, "<key>"), filter)
case reflect.Struct:
res := []string(nil)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if !isFieldPublic(field) {
continue
}
fieldParents := parents
if !field.Anonymous {
fieldParents = append(parents, field.Name)
}
res = append(res, listFields(field.Type, fieldParents, filter)...)
}
return res
default:
path := strings.Join(parents, ".")
if filter != nil && !filter(t, path) {
return nil
}
return []string{path}
}
}
// isNil test if a given value is nil. It is saf to call the mthod with non nillable value like scalar types
func isNil(value reflect.Value) bool {
return (value.Kind() == reflect.Ptr || value.Kind() == reflect.Slice || value.Kind() == reflect.Map) && value.IsNil()
}
// isFieldPublic returns true if the given field is public (Name starts with an uppercase)
func isFieldPublic(field reflect.StructField) bool {
return field.Name[0] >= 'A' && field.Name[0] <= 'Z'
} | internal/gofields/gofields.go | 0.614278 | 0.478346 | gofields.go | starcoder |
Package app contains OpenEBS Dynamic Local PV provisioner
Provisioner is created using the external storage provisioner library:
https://github.com/kubernetes-sigs/sig-storage-local-static-provisioner
Local PVs are an extension to hostpath volumes, but are more secure.
https://kubernetes.io/docs/concepts/policy/pod-security-policy/#volumes-and-file-systems
Local PVs are great in cases like:
- The Stateful Workload can take care of replicating the data across
nodes to handle cases like a complete node (and/or its storage) failure.
- For long running Stateful Workloads, the Backup/Recovery is provided
by Operators/tools that can make use the Workload mounts and do not
require the capabilities to be available in the underlying storage. Or
if the hostpaths are created on external storage like EBS/GPD, administrator
have tools that can periodically take snapshots/backups.
OpenEBS Local PVs extends the capabilities provided by the Kubernetes Local PV
by making use of the OpenEBS Node Storage Device Manager (NDM), the significant
differences include:
- Users need not pre-format and mount the devices in the node.
- Supports Dynamic Local PVs - where the devices can be used by CAS solutions
and also by applications. CAS solutions typically directly access a device.
OpenEBS Local PV ease the management of storage devices to be used between
CAS solutions (direct access) and applications (via PV), by making use of
BlockDeviceClaims supported by OpenEBS NDM.
- Supports using hostpath as well for provisioning a Local PV. In fact in some
cases, the Kubernetes nodes may have limited number of storage devices
attached to the node and hostpath based Local PVs offer efficient management
of the storage available on the node.
Inspiration:
------------
OpenEBS Local PV has been inspired by the prior work done by the following
the Kubernetes projects:
- https://github.com/kubernetes-sigs/sig-storage-lib-external-provisioner/tree/master/examples/hostpath-provisioner
- https://github.com/kubernetes-sigs/sig-storage-local-static-provisioner
- https://github.com/rancher/local-path-provisioner
How it works:
-------------
Step 1: Multiple Storage Classes can be created by the Kubernetes Administrator,
to specify the required type of OpenEBS Local PV to be used by an application.
A simple StorageClass looks like:
---
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: hostpath
annotations:
#Define a new OpenEBS CAS Type called `local`
#which indicates that Data is stored
#directly onto hostpath. The hostpath can be:
#- device (as block or mounted path)
#- hostpath (sub directory on OS or mounted path)
openebs.io/cas-type: local
cas.openebs.io/config: |
#- name: StorageType
# value: "device"
# (Default)
- name: StorageType
value: "hostpath"
# If the StorageType is hostpath, then BasePath
# specifies the location where the volume sub-directory
# should be created.
# (Default)
- name: BasePath
value: "/var/openebs/local"
provisioner: openebs.io/local
volumeBindingMode: WaitForFirstConsumer
reclaimPolicy: Delete
---
Step 2: The application developers will request for storage via PVC as follows:
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-hp
spec:
accessModes:
- ReadWriteOnce
storageClassName: hostpath
resources:
requests:
storage: 2Gi
---
Step 3: A Local PV (type=hostpath) provisioned via the OpenEBS Dynamic
Local PV Provisioner looks like this:
---
apiVersion: v1
kind: PersistentVolume
metadata:
annotations:
pv.kubernetes.io/provisioned-by: openebs.io/local
creationTimestamp: 2019-05-02T15:44:35Z
finalizers:
- kubernetes.io/pv-protection
name: pvc-2fe08284-6cf1-11e9-be8b-42010a800155
resourceVersion: "2062"
selfLink: /api/v1/persistentvolumes/pvc-2fe08284-6cf1-11e9-be8b-42010a800155
uid: 2fedaff8-6cf1-11e9-be8b-42010a800155
spec:
accessModes:
- ReadWriteOnce
capacity:
storage: 2Gi
claimRef:
apiVersion: v1
kind: PersistentVolumeClaim
name: pvc-hp
namespace: default
resourceVersion: "2060"
uid: 2fe08284-6cf1-11e9-be8b-42010a800155
local:
path: /var/openebs/local/pvc-2fe08284-6cf1-11e9-be8b-42010a800155
fsType: ""
nodeAffinity:
required:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- gke-kmova-helm-default-pool-6c1271a5-n8b0
persistentVolumeReclaimPolicy: Delete
storageClassName: hostpath
status:
phase: Bound
---
Note that the location of the hostpaths on the node are abstracted from the
application developers and are under the Administrators control.
Implementation Details:
-----------------------
(a) The configuration of whether to select a complete storage device
of a hostpath is determined by the StorageClass annotations, inline
with other configuration options provided by OpenEBS.
(b) When using StorageType as device, the Local Provisioner will
interact with the OpenEBS Node Storage Device Manager (NDM) to
identify the device to be used. Each PVC of type StorageType=device
will create a BDC and wait for the NDM to provide an appropriate BD.
From the BD, the provisioner will extract the path details and create
a Local PV. When using unformatted block devices, the administrator
can specific the type of FS to be put on block devices using the
FSType CAS Policy in StorageClass.
(c) The StorageClass can work either with `waitForConsumer`, in which
case, the PV is created on the node where the Pod is scheduled or
vice versa. (Note: In the initial version, only `waitForConsumer` is
supported.)
(d) When using the hostpath, the administrator can select the location using:
- BasePath: By default, the hostpath volumes will be created under
`/var/openebs/local`. This default path can be changed by passing the
"OPENEBS_IO_BASE_PATH" ENV variable to the Hostpath Provisioner Pod.
It is also possible to specify a different location using the
CAS Policy `BasePath` in the StorageClass.
The hostpath used in the above configuration can be:
- OS Disk - possibly a folder dedicated to saving data on each node.
- Additional Disks - mounted as ext4 or any other filesystem
- External Storage - mounted as ext4 or any other filesystem
(e) The backup and restore via Velero Plugin has been verified to work for
OpenEBS Local PV. Supported from OpenEBS 1.0 and higher.
Future Improvements and Limitations:
------------------------------------
- Ability to enforce capacity limits. The application can exceed it usage
of capacity beyond what it requested.
- Ability to enforce provisioning limits based on the capacity available
on a given node or the number of PVs already provisioned.
- Ability to use hostpaths and devices that can potentially support snapshots.
Example: a hostpath backed by github, or by LVM or ZFS where capacity also
can be enforced.
- Extend the capabilities of the Local PV provisioner to handle cases where
underlying devices are moved to new node and needs changes to the node
affinity.
- Move towards using a CSI based Hostpath provisioner.
*/
package app | cmd/provisioner-localpv/app/doc.go | 0.894063 | 0.602822 | doc.go | starcoder |
package evolution
const (
SurvivorSelectionFitnessBased = "SurvivorSelectionFitnessBased"
SurvivorSelectionRandom = "SurvivorSelectionRandom"
)
// FitnessBasedSurvivorSelection returns a set of survivors proportionate to the survivor percentage.
// It orders some of the best parents and some of the best children based on the ratio
func FitnessBasedSurvivorSelection(selectedParents, selectedChildren []*Individual,
params EvolutionParams) ([]*Individual, error) {
survivors := make([]*Individual, params.EachPopulationSize)
parentPopulationSize := int(params.Selection.Survivor.SurvivorPercentage * float64(params.EachPopulationSize))
childPopulationSize := params.EachPopulationSize - parentPopulationSize
sortedParents, err := SortIndividuals(selectedParents, true)
if err != nil {
return nil, err
}
sortedChildren, err := SortIndividuals(selectedChildren, true)
if err != nil {
return nil, err
}
for i := 0; i < parentPopulationSize; i++ {
survivors[i] = sortedParents[i]
}
for i := 0; i < childPopulationSize; i++ {
survivors[i+parentPopulationSize] = sortedChildren[childPopulationSize]
}
return survivors, nil
}
// RandomSurvivorSelection selects a random set of parents and a random set of children. The numbers are based on
func RandomSurvivorSelection(selectedParents, selectedChildren []*Individual,
params EvolutionParams) ([]*Individual, error) {
survivors := make([]*Individual, params.EachPopulationSize)
parentPopulationSize := int(params.Selection.Survivor.SurvivorPercentage * float64(params.EachPopulationSize))
childPopulationSize := params.EachPopulationSize - parentPopulationSize
sortedParents, err := SortIndividuals(selectedParents, true)
if err != nil {
return nil, err
}
sortedChildren, err := SortIndividuals(selectedChildren, true)
if err != nil {
return nil, err
}
for i := 0; i < parentPopulationSize; i++ {
survivors[i] = sortedParents[i]
}
for i := 0; i < childPopulationSize; i++ {
survivors[i+parentPopulationSize] = sortedChildren[childPopulationSize]
}
return survivors, nil
}
// GenerationalSurvivorSelection is a process where the entire input population gets replaced by their offspring.
// The returned individuals do not exist with their parents as they have been totally annihilated.
// These new individuals will go on into the next Generation
func GenerationalSurvivorSelection(population *Generation) ([]*Individual, error) {
return nil, nil
}
// SteadyStateSurvivorSelection is a process where a select amount of individuals make it through.
// Some parents may make it through based on their Fitness or other compounding parameters.
// These new individuals will go on into the next Generation
func SteadyStateSurvivorSelection(population *Generation) ([]*Individual, error) {
return nil, nil
} | evolution/survivorselection.go | 0.768125 | 0.485112 | survivorselection.go | starcoder |
package helper
import (
machinev1alpha1 "github.com/gardener/machine-controller-manager/pkg/apis/machine/v1alpha1"
)
const (
nameLabel = "name"
// MachineSetKind is the kind of the owner reference of a machine set
MachineSetKind = "MachineSet"
// MachineDeploymentKind is the kind of the owner reference of a machine deployment
MachineDeploymentKind = "MachineDeployment"
)
// BuildOwnerToMachinesMap builds a map from a slice of machinev1alpha1.Machine, that maps the owner reference
// to a slice of machines with the same owner reference
func BuildOwnerToMachinesMap(machines []machinev1alpha1.Machine) map[string][]machinev1alpha1.Machine {
ownerToMachines := make(map[string][]machinev1alpha1.Machine)
for index, machine := range machines {
if len(machine.OwnerReferences) > 0 {
for _, reference := range machine.OwnerReferences {
if reference.Kind == MachineSetKind {
ownerToMachines[reference.Name] = append(ownerToMachines[reference.Name], machines[index])
}
}
} else if len(machine.Labels) > 0 {
if machineDeploymentName, ok := machine.Labels[nameLabel]; ok {
ownerToMachines[machineDeploymentName] = append(ownerToMachines[machineDeploymentName], machines[index])
}
}
}
return ownerToMachines
}
// BuildOwnerToMachineSetsMap builds a map from a slice of machinev1alpha1.MachineSet, that maps the owner reference
// to a slice of MachineSets with the same owner reference
func BuildOwnerToMachineSetsMap(machineSets []machinev1alpha1.MachineSet) map[string][]machinev1alpha1.MachineSet {
ownerToMachineSets := make(map[string][]machinev1alpha1.MachineSet)
for index, machineSet := range machineSets {
if len(machineSet.OwnerReferences) > 0 {
for _, reference := range machineSet.OwnerReferences {
if reference.Kind == MachineDeploymentKind {
ownerToMachineSets[reference.Name] = append(ownerToMachineSets[reference.Name], machineSets[index])
}
}
} else if len(machineSet.Labels) > 0 {
if machineDeploymentName, ok := machineSet.Labels[nameLabel]; ok {
ownerToMachineSets[machineDeploymentName] = append(ownerToMachineSets[machineDeploymentName], machineSets[index])
}
}
}
return ownerToMachineSets
}
// GetMachineSetWithMachineClass checks if for the given <machineDeploymentName>, there exists a machine set in the <ownerReferenceToMachineSet> with the machine class <machineClassName>
// returns the machine set or nil
func GetMachineSetWithMachineClass(machineDeploymentName, machineClassName string, ownerReferenceToMachineSet map[string][]machinev1alpha1.MachineSet) *machinev1alpha1.MachineSet {
machineSets := ownerReferenceToMachineSet[machineDeploymentName]
for _, machineSet := range machineSets {
if machineSet.Spec.Template.Spec.Class.Name == machineClassName {
return &machineSet
}
}
return nil
} | vendor/github.com/gardener/gardener/extensions/pkg/controller/worker/helper/helper.go | 0.674372 | 0.435481 | helper.go | starcoder |
package assert
import (
"reflect"
"testing"
"github.com/ppapapetrou76/go-testing/internal/pkg/values"
)
// AssertableAny is the assertable structure for interface{} values.
type AssertableAny struct {
t *testing.T
actual values.AnyValue
}
// That returns an AssertableAny structure initialized with the test reference and the actual value to assert.
func That(t *testing.T, actual interface{}) AssertableAny {
t.Helper()
return AssertableAny{
t: t,
actual: values.NewAnyValue(actual),
}
}
// IsEqualTo asserts if the expected interface is equal to the assertable value
// It errors the tests if the compared values (actual VS expected) are not equal.
func (a AssertableAny) IsEqualTo(expected interface{}) AssertableAny {
a.t.Helper()
if !a.actual.IsEqualTo(expected) {
a.t.Error(shouldBeEqual(a.actual, expected))
}
return a
}
// IsNotEqualTo asserts if the expected interface is not qual to the assertable value
// It errors the tests if the compared values (actual VS expected) are equal.
func (a AssertableAny) IsNotEqualTo(expected interface{}) AssertableAny {
a.t.Helper()
if a.actual.IsEqualTo(expected) {
a.t.Error(shouldNotBeEqual(a.actual, expected))
}
return a
}
// IsNil asserts if the expected value is nil.
func (a AssertableAny) IsNil() AssertableAny {
a.t.Helper()
if !a.actual.IsNil() {
a.t.Error(shouldBeNil(a.actual))
}
return a
}
// IsNotNil asserts if the expected value is not nil.
func (a AssertableAny) IsNotNil() AssertableAny {
a.t.Helper()
if !a.actual.IsNotNil() {
a.t.Error(shouldNotBeNil(a.actual))
}
return a
}
// IsTrue asserts if the expected value is true.
func (a AssertableAny) IsTrue() AssertableAny {
a.t.Helper()
a.IsEqualTo(true)
return a
}
// IsFalse asserts if the expected value is false.
func (a AssertableAny) IsFalse() AssertableAny {
a.t.Helper()
a.IsEqualTo(false)
return a
}
// HasTypeOf asserts if the expected value has the type of a given value.
func (a AssertableAny) HasTypeOf(t reflect.Type) AssertableAny {
a.t.Helper()
if !a.actual.HasTypeOf(t) {
a.t.Error(shouldHaveType(a.actual, t))
}
return a
} | assert/any.go | 0.787114 | 0.741323 | any.go | starcoder |
package winlog
import (
"fmt"
"time"
"unicode/utf16"
"unsafe"
)
/* Convenience functions to get values out of
an array of EvtVariant structures */
const (
EvtVarTypeNull = iota
EvtVarTypeString
EvtVarTypeAnsiString
EvtVarTypeSByte
EvtVarTypeByte
EvtVarTypeInt16
EvtVarTypeUInt16
EvtVarTypeInt32
EvtVarTypeUInt32
EvtVarTypeInt64
EvtVarTypeUInt64
EvtVarTypeSingle
EvtVarTypeDouble
EvtVarTypeBoolean
EvtVarTypeBinary
EvtVarTypeGuid
EvtVarTypeSizeT
EvtVarTypeFileTime
EvtVarTypeSysTime
EvtVarTypeSid
EvtVarTypeHexInt32
EvtVarTypeHexInt64
EvtVarTypeEvtHandle
EvtVarTypeEvtXml
)
type evtVariant struct {
Data uint64
Count uint32
Type uint32
}
type fileTime struct {
lowDateTime uint32
highDateTime uint32
}
type EvtVariant []byte
/* Given a byte array from EvtRender, make an EvtVariant.
EvtVariant wraps an array of variables. */
func NewEvtVariant(buffer []byte) EvtVariant {
return EvtVariant(buffer)
}
func (e EvtVariant) elemAt(index uint32) *evtVariant {
return (*evtVariant)(unsafe.Pointer(uintptr(16*index) + uintptr(unsafe.Pointer(&e[0]))))
}
func UTF16ToString(s []uint16) string {
for i, v := range s {
if v == 0 {
s = s[0:i]
break
}
}
return string(utf16.Decode(s))
}
/* Return the string value of the variable at `index`. If the
variable isn't a string, an error is returned */
func (e EvtVariant) String(index uint32) (string, error) {
elem := e.elemAt(index)
if elem.Type != EvtVarTypeString {
return "", fmt.Errorf("EvtVariant at index %v was not of type string, type was %v", index, elem.Type)
}
wideString := (*[1 << 29]uint16)(unsafe.Pointer(uintptr(elem.Data)))
str := UTF16ToString(wideString[0 : elem.Count+1])
return str, nil
}
/* Return the unsigned integer value at `index`. If the variable
isn't a Byte, UInt16, UInt32 or UInt64 an error is returned. */
func (e EvtVariant) Uint(index uint32) (uint64, error) {
elem := e.elemAt(index)
switch elem.Type {
case EvtVarTypeByte:
return uint64(byte(elem.Data)), nil
case EvtVarTypeUInt16:
return uint64(uint16(elem.Data)), nil
case EvtVarTypeUInt32:
return uint64(uint32(elem.Data)), nil
case EvtVarTypeUInt64:
return uint64(elem.Data), nil
default:
return 0, fmt.Errorf("EvtVariant at index %v was not an unsigned integer, type is %v", index, elem.Type)
}
}
/* Return the integer value at `index`. If the variable
isn't a SByte, Int16, Int32 or Int64 an error is returned. */
func (e EvtVariant) Int(index uint32) (int64, error) {
elem := e.elemAt(index)
switch elem.Type {
case EvtVarTypeSByte:
return int64(byte(elem.Data)), nil
case EvtVarTypeInt16:
return int64(int16(elem.Data)), nil
case EvtVarTypeInt32:
return int64(int32(elem.Data)), nil
case EvtVarTypeInt64:
return int64(elem.Data), nil
default:
return 0, fmt.Errorf("EvtVariant at index %v was not an integer, type is %v", index, elem.Type)
}
}
/* Return the FileTime at `index`, converted to Time.time. If the
variable isn't a FileTime an error is returned */
func (e EvtVariant) FileTime(index uint32) (time.Time, error) {
elem := e.elemAt(index)
if elem.Type != EvtVarTypeFileTime {
return time.Now(), fmt.Errorf("EvtVariant at index %v was not of type FileTime, type was %v", index, elem.Type)
}
var t = (*fileTime)(unsafe.Pointer(&elem.Data))
timeSecs := (((int64(t.highDateTime) << 32) | int64(t.lowDateTime)) / 10000000) - int64(11644473600)
timeNano := (((int64(t.highDateTime) << 32) | int64(t.lowDateTime)) % 10000000) * 100
return time.Unix(timeSecs, timeNano), nil
}
/* Return whether the variable was actually set, or whether it
has null type */
func (e EvtVariant) IsNull(index uint32) bool {
return e.elemAt(index).Type == EvtVarTypeNull
} | evt_variant.go | 0.53048 | 0.41941 | evt_variant.go | starcoder |
package collections
// A Range is an iterable which yields successive integer values
// between two endpoints. Ranges are non-destructive and can be
// safely iterated repeatedly
type Range struct {
begin int
end int
}
func NewRange(begin int, end int) *Range {
if end < begin {
panic(ErrInvalidRangeBounds)
}
return &Range{
begin: begin,
end: end,
}
}
func (rng *Range) Iterator() Iterator {
return &RangeIterator{
current: rng.begin - 1,
end: rng.end,
}
}
type RangeIterator struct {
end int
current int
}
func (rangeIterator *RangeIterator) MoveNext() bool {
rangeIterator.current += 1
return rangeIterator.current < rangeIterator.end
}
func (rangeIterator *RangeIterator) Current() interface{} {
return rangeIterator.current
}
func (rng *Range) ToSlice() []interface{} {
slice := make([]interface{}, rng.end-rng.begin)
for val := rng.begin; val < rng.end; val++ {
index := val - rng.begin
slice[index] = val
}
return slice
}
func (rng *Range) Map(mapFn func(interface{}) interface{}) Iterable {
return mapHelper(rng, mapFn)
}
func (rng *Range) Filter(filterFn func(interface{}) bool) Iterable {
return filterHelper(rng, filterFn)
}
func (rng *Range) Fold(initialValue interface{}, reducerFn func(interface{}, interface{}) interface{}) interface{} {
val := initialValue
for i := rng.begin; i < rng.end; i++ {
val = reducerFn(val, i)
}
return val
}
func (rng *Range) Take(count int) Iterable {
length := rng.end - rng.begin
if count >= length {
return rng
}
return NewRange(rng.begin, rng.begin+count)
}
func (rng *Range) Skip(count int) Iterable {
length := rng.end - rng.begin
if count >= length {
return &EmptyIterable{}
}
return NewRange(rng.begin+count, rng.end)
}
func (rng *Range) SkipWhile(matchFn func(interface{}) bool) Iterable {
return skipWhileHelper(rng, matchFn)
}
func (rng *Range) Any(matchFn func(interface{}) bool) bool {
for i := rng.begin; i < rng.end; i++ {
if matchFn(i) {
return true
}
}
return false
}
func (rng *Range) ForEach(iterFn func(interface{})) {
for i := rng.begin; i < rng.end; i++ {
iterFn(i)
}
} | range.go | 0.772445 | 0.476092 | range.go | starcoder |
package state
import (
"math"
"sort"
"github.com/kzahedi/goent/continuous"
pb "gopkg.in/cheggaaa/pb.v1"
)
// KraskovStoegbauerGrassberger1 is an implementation of the first
// algorithm presented in
// <NAME>, <NAME>, and <NAME>.
// Estimating mutual information. Phys. Rev. E, 69:066138, Jun 2004.
// The function assumes that the data xyz is normalised column-wise
func KraskovStoegbauerGrassberger1(xy [][]float64, xIndices, yIndices []int, k int, eta bool) []float64 {
N := float64(len(xy))
r := make([]float64, len(xy), len(xy))
hk := continuous.Harmonic(k) // h(k)
hN := continuous.Harmonic(len(xy)) // h(N)
var bar *pb.ProgressBar
if eta == true {
bar = pb.StartNew(len(xy))
}
for t := 0; t < len(xy); t++ {
epsilon := ksgGetEpsilon(k, xy[t], xy, xIndices, yIndices)
cNx := ksgCount(epsilon, xy[t], xy, xIndices) // N_x
hNx := continuous.Harmonic(cNx + 1) // h(N_x)
cNy := ksgCount(epsilon, xy[t], xy, yIndices) // N_y
hNy := continuous.Harmonic(cNy + 1) // h(N_y)
r[t] = (-hNx - hNy + hk + hN) / N
if eta == true {
bar.Increment()
}
}
if eta == true {
bar.Finish()
}
return r
}
// KraskovStoegbauerGrassberger2 is an implementation of the second
// algorithm presented in
// <NAME>, <NAME>, and <NAME>.
// Estimating mutual information. Phys. Rev. E, 69:066138, Jun 2004.
// The function assumes that the data xyz is normalised column-wise
func KraskovStoegbauerGrassberger2(xy [][]float64, xIndices, yIndices []int, k int, eta bool) []float64 {
n := len(xy)
r := make([]float64, n, n)
N := float64(len(xy))
hk := continuous.Harmonic(k)
hN := continuous.Harmonic(n)
k1 := 1.0 / float64(k)
var bar *pb.ProgressBar
if eta == true {
bar = pb.StartNew(len(xy))
}
for t := 0; t < len(xy); t++ {
epsilon := ksgGetEpsilon(k, xy[t], xy, xIndices, yIndices)
cNx := ksgCount(epsilon, xy[t], xy, xIndices)
hNx := continuous.Harmonic(cNx)
cNy := ksgCount(epsilon, xy[t], xy, yIndices)
hNy := continuous.Harmonic(cNy)
r[t] = (-hNx - hNy + hk + hN - k1) / N
if eta == true {
bar.Increment()
}
}
if eta == true {
bar.FinishPrint("Finished")
}
return r
}
// ksgGetEpsilon calculate epsilon_k(t) as defined by Frenzel & Pompe, 2007
// epsilon_k(t) is the continuous.Distance of the k-th nearest neighbour. The function
// takes k, the point from which the continuous.Distance is calculated (xyz), and the
// data from which the k-th nearest neighbour should be determined
func ksgGetEpsilon(k int, xy []float64, data [][]float64, xIndices, yIndices []int) float64 {
distances := make([]float64, len(data), len(data))
for t := 0; t < len(data); t++ {
distances[t] = ksgMaxNorm2(xy, data[t], xIndices, yIndices)
}
sort.Float64s(distances)
return distances[k-1] // we start to ksgCount at zero
}
func ksgMaxNorm2(a, b []float64, xIndices, yIndices []int) float64 {
xDistance := continuous.Distance(a, b, xIndices)
yDistance := continuous.Distance(a, b, yIndices)
return math.Max(xDistance, yDistance)
}
// ksgCount count the number of points for which the x or y coordinate is
// closer than epsilon, where the ksgDistance is measured by the max-norm
func ksgCount(epsilon float64, xy []float64, data [][]float64, indices []int) (c int) {
for t := 0; t < len(data); t++ {
if continuous.Distance(xy, data[t], indices) < epsilon {
c++
}
}
return
} | continuous/state/KraskovStoegbauerGrassberger.go | 0.693265 | 0.513973 | KraskovStoegbauerGrassberger.go | starcoder |
package continuous
import (
"github.com/jtejido/stats"
"github.com/jtejido/stats/err"
"math"
"math/rand"
)
// Pareto distribution
// https://en.wikipedia.org/wiki/Pareto_distribution#Bounded_Pareto_distribution
type ParetoBounded struct {
min, max, shape float64 // L, H, α
src rand.Source
}
func NewParetoBounded(min, max, shape float64) (*ParetoBounded, error) {
return NewParetoBoundedWithSource(min, max, shape, nil)
}
func NewParetoBoundedWithSource(min, max, shape float64, src rand.Source) (*ParetoBounded, error) {
if min >= max || shape <= 0 {
return nil, err.Invalid()
}
return &ParetoBounded{min, max, shape, src}, nil
}
// L ∈ (0,∞)
// H ∈ (L,∞)
// α ∈ (0,∞)
func (p ParetoBounded) Parameters() stats.Limits {
return stats.Limits{
"L": stats.Interval{0, math.Inf(1), true, true},
"H": stats.Interval{p.min, math.Inf(1), true, true},
"α": stats.Interval{0, math.Inf(1), true, true},
}
}
// x ∈ (0,∞)
func (p ParetoBounded) Support() stats.Interval {
return stats.Interval{p.min, p.max, false, false}
}
func (p ParetoBounded) Probability(x float64) float64 {
if p.Support().IsWithinInterval(x) {
a := p.shape
num := a * math.Pow(p.min, a) * math.Pow(x, -a-1)
denom := 1 - math.Pow(p.min/p.max, a)
return num / denom
}
return 0
}
func (p ParetoBounded) Distribution(x float64) float64 {
if p.Support().IsWithinInterval(x) {
a := p.shape
num := 1 - math.Pow(p.min, a)*math.Pow(x, -a)
denom := 1 - math.Pow(p.min/p.max, a)
return num / denom
}
return 0
}
func (p ParetoBounded) Entropy() float64 {
stats.NotImplementedError()
return math.NaN()
}
func (p ParetoBounded) Inverse(q float64) float64 {
if q > 0 && q < 1 {
num := -q*math.Pow(p.max, p.shape) - q*math.Pow(p.min, p.shape) - math.Pow(p.max, p.shape)
denom := math.Pow(p.max, p.shape) * math.Pow(p.min, p.shape)
return math.Pow(-(num / denom), -1/p.shape)
}
if q <= 0 {
return 0
}
return math.Inf(1)
}
func (p ParetoBounded) Mean() float64 {
// p.rm(1)
if p.shape == 1 {
return (p.max * p.min) / (p.max - p.min) * math.Log(p.max/p.min)
}
a := math.Pow(p.min, p.shape) / (1 - math.Pow(p.min/p.max, p.shape))
b := p.shape / (p.shape - 1)
c := (1 / math.Pow(p.min, p.shape-1)) - (1 / math.Pow(p.max, p.shape-1))
return a * b * c
}
func (p ParetoBounded) Median() float64 {
return p.min * math.Pow(1-(.5*(1-math.Pow(p.min/p.max, p.shape))), -1/p.shape)
}
func (p ParetoBounded) Mode() float64 {
stats.NotImplementedError()
return math.NaN()
}
func (p ParetoBounded) Variance() float64 {
m1 := p.rm(1)
return -(m1 * m1) + p.rm(2)
}
func (p ParetoBounded) Skewness() float64 {
m1 := p.rm(1)
m2 := p.rm(2)
m3 := p.rm(3)
return (m1*(2*(m1*m1)-3*m2) + m3) / math.Pow(m2-(m1*m1), 3./2)
}
func (p ParetoBounded) ExKurtosis() float64 {
m1 := p.rm(1)
m2 := p.rm(2)
m3 := p.rm(3)
m4 := p.rm(4)
return (-3*(m1*m1*m1*m1) + 6*(m1*m1)*m2 - 4*m1*m3 + m4 - 3*((m2-(m1*m1))*(m2-(m1*m1)))) / ((m2 - (m1 * m1)) * (m2 - (m1 * m1)))
}
func (p ParetoBounded) rm(k float64) float64 {
a := math.Pow(p.min, p.shape) / (1 - math.Pow(p.min/p.max, p.shape))
b := (p.shape * (math.Pow(p.min, k-p.shape) - math.Pow(p.max, k-p.shape))) / (p.shape - k)
return a * b
}
func (p ParetoBounded) Rand() float64 {
var rnd float64
if p.src == nil {
rnd = rand.Float64()
} else {
rnd = rand.New(p.src).Float64()
}
return p.Inverse(rnd)
} | dist/continuous/pareto_bounded.go | 0.744749 | 0.562477 | pareto_bounded.go | starcoder |
package ionoscloud
import (
"encoding/json"
)
// MaintenanceWindow A weekly 4 hour-long window, during which maintenance might occur
type MaintenanceWindow struct {
Time *string `json:"time"`
DayOfTheWeek *DayOfTheWeek `json:"dayOfTheWeek"`
}
// NewMaintenanceWindow instantiates a new MaintenanceWindow object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewMaintenanceWindow(time string, dayOfTheWeek DayOfTheWeek) *MaintenanceWindow {
this := MaintenanceWindow{}
this.Time = &time
this.DayOfTheWeek = &dayOfTheWeek
return &this
}
// NewMaintenanceWindowWithDefaults instantiates a new MaintenanceWindow object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewMaintenanceWindowWithDefaults() *MaintenanceWindow {
this := MaintenanceWindow{}
return &this
}
// GetTime returns the Time field value
// If the value is explicit nil, the zero value for string will be returned
func (o *MaintenanceWindow) GetTime() *string {
if o == nil {
return nil
}
return o.Time
}
// GetTimeOk returns a tuple with the Time field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *MaintenanceWindow) GetTimeOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.Time, true
}
// SetTime sets field value
func (o *MaintenanceWindow) SetTime(v string) {
o.Time = &v
}
// HasTime returns a boolean if a field has been set.
func (o *MaintenanceWindow) HasTime() bool {
if o != nil && o.Time != nil {
return true
}
return false
}
// GetDayOfTheWeek returns the DayOfTheWeek field value
// If the value is explicit nil, the zero value for DayOfTheWeek will be returned
func (o *MaintenanceWindow) GetDayOfTheWeek() *DayOfTheWeek {
if o == nil {
return nil
}
return o.DayOfTheWeek
}
// GetDayOfTheWeekOk returns a tuple with the DayOfTheWeek field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *MaintenanceWindow) GetDayOfTheWeekOk() (*DayOfTheWeek, bool) {
if o == nil {
return nil, false
}
return o.DayOfTheWeek, true
}
// SetDayOfTheWeek sets field value
func (o *MaintenanceWindow) SetDayOfTheWeek(v DayOfTheWeek) {
o.DayOfTheWeek = &v
}
// HasDayOfTheWeek returns a boolean if a field has been set.
func (o *MaintenanceWindow) HasDayOfTheWeek() bool {
if o != nil && o.DayOfTheWeek != nil {
return true
}
return false
}
func (o MaintenanceWindow) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.Time != nil {
toSerialize["time"] = o.Time
}
if o.DayOfTheWeek != nil {
toSerialize["dayOfTheWeek"] = o.DayOfTheWeek
}
return json.Marshal(toSerialize)
}
type NullableMaintenanceWindow struct {
value *MaintenanceWindow
isSet bool
}
func (v NullableMaintenanceWindow) Get() *MaintenanceWindow {
return v.value
}
func (v *NullableMaintenanceWindow) Set(val *MaintenanceWindow) {
v.value = val
v.isSet = true
}
func (v NullableMaintenanceWindow) IsSet() bool {
return v.isSet
}
func (v *NullableMaintenanceWindow) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableMaintenanceWindow(val *MaintenanceWindow) *NullableMaintenanceWindow {
return &NullableMaintenanceWindow{value: val, isSet: true}
}
func (v NullableMaintenanceWindow) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableMaintenanceWindow) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | model_maintenance_window.go | 0.77827 | 0.425486 | model_maintenance_window.go | starcoder |
package pokemon
import (
"github.com/asukakenji/pokemon-go/generic"
)
// ById is designed to be used with Iterable.Sort.
// It returns a function that is usable as a parameter for Sort.
// When ordering is Ascending,
// the returned function returns true if p1 is less than p2 by id.
func ById(ordering generic.Ordering) func(Pokemon, Pokemon) bool {
if ordering == generic.Ascending {
return func(p1, p2 Pokemon) bool {
return p1.Id() < p2.Id()
}
}
return func(p1, p2 Pokemon) bool {
return p1.Id() < p2.Id()
}
}
// ByBaseStamina is designed to be used with Iterable.Sort.
// It returns a function that is usable as a parameter for Sort.
// When ordering is Ascending,
// the returned function returns true if p1 if p1 is less than p2
// by base stamina.
func ByBaseStamina(ordering generic.Ordering) func(Pokemon, Pokemon) bool {
if ordering == generic.Ascending {
return func(p1, p2 Pokemon) bool {
return p1.BaseStamina() < p2.BaseStamina()
}
}
return func(p1, p2 Pokemon) bool {
return p1.BaseStamina() < p2.BaseStamina()
}
}
// ByBaseAttack is designed to be used with Iterable.Sort.
// It returns a function that is usable as a parameter for Sort.
// When ordering is Ascending,
// the returned function returns true if p1 if p1 is less than p2
// by base attack.
func ByBaseAttack(ordering generic.Ordering) func(Pokemon, Pokemon) bool {
if ordering == generic.Ascending {
return func(p1, p2 Pokemon) bool {
return p1.BaseAttack() < p2.BaseAttack()
}
}
return func(p1, p2 Pokemon) bool {
return p1.BaseAttack() < p2.BaseAttack()
}
}
// ByBaseDefense is designed to be used with Iterable.Sort.
// It returns a function that is usable as a parameter for Sort.
// When ordering is Ascending,
// the returned function returns true if p1 if p1 is less than p2
// by base defense.
func ByBaseDefense(ordering generic.Ordering) func(Pokemon, Pokemon) bool {
if ordering == generic.Ascending {
return func(p1, p2 Pokemon) bool {
return p1.BaseDefense() < p2.BaseDefense()
}
}
return func(p1, p2 Pokemon) bool {
return p1.BaseDefense() < p2.BaseDefense()
}
}
// ByWeight is designed to be used with Iterable.Sort.
// It returns a function that is usable as a parameter for Sort.
// When ordering is Ascending,
// the returned function returns true if p1 is less than p2 by weight.
func ByWeight(ordering generic.Ordering) func(Pokemon, Pokemon) bool {
if ordering == generic.Ascending {
return func(p1, p2 Pokemon) bool {
return p1.Weight() < p2.Weight()
}
}
return func(p1, p2 Pokemon) bool {
return p1.Weight() < p2.Weight()
}
}
// ByHeight is designed to be used with Iterable.Sort.
// It returns a function that is usable as a parameter for Sort.
// When ordering is Ascending,
// the returned function returns true if p1 is less than p2 by height.
func ByHeight(ordering generic.Ordering) func(Pokemon, Pokemon) bool {
if ordering == generic.Ascending {
return func(p1, p2 Pokemon) bool {
return p1.Height() < p2.Height()
}
}
return func(p1, p2 Pokemon) bool {
return p1.Height() < p2.Height()
}
} | pokemon/pokemon_comparators.go | 0.727589 | 0.446133 | pokemon_comparators.go | starcoder |
// package shp implements shape structures/routines
package shp
import "github.com/cpmech/gosl/la"
// constants
const MINDET = 1.0e-14 // minimum determinant allowed for dxdR
// ShpFunc is the shape functions callback function
type ShpFunc func(S []float64, dSdR [][]float64, r, s, t float64, derivs bool)
// Shape holds geometry data
type Shape struct {
// geometry
Type string // name; e.g. "lin2"
Func ShpFunc // shape/derivs function callback function
FaceFunc ShpFunc // face shape/derivs function callback function
BasicType string // geometry of basic element; e.g. "qua8" => "qua4"
FaceType string // geometry of face; e.g. "qua8" => "lin3"
Gndim int // geometry of shape; e.g. "lin3" => gnd == 1 (even in 3D simulations)
Nverts int // number of vertices in cell; e.g. "qua8" => 8
VtkCode int // VTK code
FaceNverts int // number of vertices on face
FaceLocalV [][]int // face local vertices [nfaces][FaceNverts]
NatCoords [][]float64 // natural coordinates [gndim][nverts]
// geometry: for seams (3D-edges)
SeamType int // geometry of seam (3D-edge); e.g. "hex8" => "lin2"
SeamLocalV [][]int // seam (3d-edge) local vertices [nseams][nVertsOnSeam]
// scratchpad: volume
S []float64 // [nverts] shape functions
G [][]float64 // [nverts][gndim] G == dSdx. derivative of shape function
J float64 // Jacobian: determinant of dxdr
dSdR [][]float64 // [nverts][gndim] derivatives of S w.r.t natural coordinates
dxdR [][]float64 // [gndim][gndim] derivatives of real coordinates w.r.t natural coordinates
dRdx [][]float64 // [gndim][gndim] dRdx == inverse(dxdR)
// scratchpad: line
Jvec3d []float64 // Jacobian: norm of dxdr for line elements (size==3)
Gvec []float64 // [nverts] G == dSdx. derivative of shape function
// scratchpad: face
Sf []float64 // [facenverts] shape functions values
Fnvec []float64 // [gndim] face normal vector multiplied by Jf
dSfdRf [][]float64 // [facenverts][gndim-1] derivatives of Sf w.r.t natural coordinates
dxfdRf [][]float64 // [gndim][gndim-1] derivatives of real coordinates w.r.t natural coordinates
}
// factory holds all Shapes available
var factory = make(map[string]*Shape)
// Get returns an existent Shape structure
// Note: returns nil on errors
func Get(geoType string) *Shape {
s, ok := factory[geoType]
if !ok {
return nil
}
return s
}
// IpRealCoords returns the real coordinates (y) of an integration point
func (o *Shape) IpRealCoords(x [][]float64, ip *Ipoint) (y []float64) {
ndim := len(x)
y = make([]float64, ndim)
o.Func(o.S, o.dSdR, ip.R, ip.S, ip.T, false)
for i := 0; i < ndim; i++ {
for m := 0; m < o.Nverts; m++ {
y[i] += o.S[m] * x[i][m]
}
}
return
}
// CalcAtIp calculates volume data such as S and G at natural coordinate r
// Input:
// x[ndim][nverts+?] -- coordinates matrix of solid element
// ip -- integration point
// Output:
// S, DSdR, DxdR, DRdx, G, and J
func (o *Shape) CalcAtIp(x [][]float64, ip *Ipoint, derivs bool) (err error) {
// S and dSdR
o.Func(o.S, o.dSdR, ip.R, ip.S, ip.T, derivs)
if !derivs {
return
}
if o.Gndim == 1 {
// calculate Jvec3d == dxdR
for i := 0; i < len(x); i++ {
o.Jvec3d[i] = 0.0
for m := 0; m < o.Nverts; m++ {
o.Jvec3d[i] += x[i][m] * o.dSdR[m][0] // dxdR := x * dSdR
}
}
// calculate J = norm of Jvec3d
o.J = la.VecNorm(o.Jvec3d)
// calculate G
for m := 0; m < o.Nverts; m++ {
o.Gvec[m] = o.dSdR[m][0] / o.J
}
return
}
// dxdR := sum_n x * dSdR => dx_i/dR_j := sum_n x^n_i * dS^n/dR_j
for i := 0; i < len(x); i++ {
for j := 0; j < o.Gndim; j++ {
o.dxdR[i][j] = 0.0
for n := 0; n < o.Nverts; n++ {
o.dxdR[i][j] += x[i][n] * o.dSdR[n][j]
}
}
}
// dRdx := inv(dxdR)
o.J, err = la.MatInv(o.dRdx, o.dxdR, MINDET)
if err != nil {
return
}
// G == dSdx := dSdR * dRdx => dS^m/dR_i := sum_i dS^m/dR_i * dR_i/dx_j
la.MatMul(o.G, 1, o.dSdR, o.dRdx)
return
}
// CalcAtR calculates volume data such as S and G at natural coordinate r
// Input:
// x[ndim][nverts+?] -- coordinates matrix of solid element
// R -- local/natural coordinates
// Output:
// S, DSdR, DxdR, DRdx, G, and J
func (o *Shape) CalcAtR(x [][]float64, R []float64, derivs bool) (err error) {
r := R[0]
s := R[1]
t := 0.0
if len(R) == 3 {
t = R[2]
}
// S and dSdR
o.Func(o.S, o.dSdR, r, s, t, derivs)
if !derivs {
return
}
if o.Gndim == 1 {
// calculate Jvec3d == dxdR
for i := 0; i < len(x); i++ {
o.Jvec3d[i] = 0.0
for m := 0; m < o.Nverts; m++ {
o.Jvec3d[i] += x[i][m] * o.dSdR[m][0] // dxdR := x * dSdR
}
}
// calculate J = norm of Jvec3d
o.J = la.VecNorm(o.Jvec3d)
// calculate G
for m := 0; m < o.Nverts; m++ {
o.Gvec[m] = o.dSdR[m][0] / o.J
}
return
}
// dxdR := sum_n x * dSdR => dx_i/dR_j := sum_n x^n_i * dS^n/dR_j
for i := 0; i < len(x); i++ {
for j := 0; j < o.Gndim; j++ {
o.dxdR[i][j] = 0.0
for n := 0; n < o.Nverts; n++ {
o.dxdR[i][j] += x[i][n] * o.dSdR[n][j]
}
}
}
// dRdx := inv(dxdR)
o.J, err = la.MatInv(o.dRdx, o.dxdR, MINDET)
if err != nil {
return
}
// G == dSdx := dSdR * dRdx => dS^m/dR_i := sum_i dS^m/dR_i * dR_i/dx_j
la.MatMul(o.G, 1, o.dSdR, o.dRdx)
return
}
// CalcAtFaceIp calculates face data such as Sf and Fnvec
// Input:
// x[ndim][nverts+?] -- coordinates matrix of solid element
// ipf -- local/natural coordinates of face
// idxface -- local index of face
// Output:
// Sf and Fnvec
func (o *Shape) CalcAtFaceIp(x [][]float64, ipf *Ipoint, idxface int) (err error) {
// skip 1D elements
if o.Gndim == 1 {
return
}
// Sf and dSfdR
o.FaceFunc(o.Sf, o.dSfdRf, ipf.R, ipf.S, ipf.T, true)
// dxfdRf := sum_n x * dSfdRf => dxf_i/dRf_j := sum_n xf^n_i * dSf^n/dRf_j
for i := 0; i < len(x); i++ {
for j := 0; j < o.Gndim-1; j++ {
o.dxfdRf[i][j] = 0.0
for k, n := range o.FaceLocalV[idxface] {
o.dxfdRf[i][j] += x[i][n] * o.dSfdRf[k][j]
}
}
}
// face normal vector
if o.Gndim == 2 {
o.Fnvec[0] = o.dxfdRf[1][0]
o.Fnvec[1] = -o.dxfdRf[0][0]
return
}
o.Fnvec[0] = o.dxfdRf[1][0]*o.dxfdRf[2][1] - o.dxfdRf[2][0]*o.dxfdRf[1][1]
o.Fnvec[1] = o.dxfdRf[2][0]*o.dxfdRf[0][1] - o.dxfdRf[0][0]*o.dxfdRf[2][1]
o.Fnvec[2] = o.dxfdRf[0][0]*o.dxfdRf[1][1] - o.dxfdRf[1][0]*o.dxfdRf[0][1]
return
}
// AxisymGetRadius returns the x0 == radius for axisymmetric computations
// Note: must be called after CalcAtIp
func (o *Shape) AxisymGetRadius(x [][]float64) (radius float64) {
for m := 0; m < o.Nverts; m++ {
radius += o.S[m] * x[0][m]
}
return
}
// AxisymGetRadiusF (face) returns the x0 == radius for axisymmetric computations
// Note: must be called after CalcAtFaceIp
func (o *Shape) AxisymGetRadiusF(x [][]float64, idxface int) (radius float64) {
for m := 0; m < o.FaceNverts; m++ {
radius += o.Sf[m] * x[0][o.FaceLocalV[idxface][m]]
}
return
}
// init_scratchpad initialise volume data (scratchpad)
func (o *Shape) init_scratchpad() {
// volume data
o.S = make([]float64, o.Nverts)
o.dSdR = la.MatAlloc(o.Nverts, o.Gndim)
o.dxdR = la.MatAlloc(o.Gndim, o.Gndim)
o.dRdx = la.MatAlloc(o.Gndim, o.Gndim)
o.G = la.MatAlloc(o.Nverts, o.Gndim)
// face data
if o.Gndim > 1 {
o.Sf = make([]float64, o.FaceNverts)
o.dSfdRf = la.MatAlloc(o.FaceNverts, o.Gndim-1)
o.dxfdRf = la.MatAlloc(o.Gndim, o.Gndim-1)
o.Fnvec = make([]float64, o.Gndim)
}
// lin data
if o.Gndim == 1 {
o.Jvec3d = make([]float64, 3)
o.Gvec = make([]float64, o.Nverts)
}
} | shp/shp.go | 0.672439 | 0.541773 | shp.go | starcoder |
package commitmentzkp
import (
"math/big"
"github.com/xlab-si/emmy/crypto/commitments"
"github.com/xlab-si/emmy/crypto/common"
)
// DFCommitmentMultiplicationProver proves for given commitments
// c1 = g^x1 * h^r1, c2 = g^x2 * h^r2, c3 = g^x3 * h^r3 that x3 = x1 * x2.
// Proof consists of three parallel proofs:
// (1) proof that we can open c1
// (2) proof that we can open c2
// (3) proof that we can open c3, where c3 is seen as
// c3 = G^x3 * H^r3 = G^(x1*x2) * H^r1*x2 * H^(r3 - r1*x2) = c1^x2 * H^(r3 - r1*x2),
// thus a new "G" is c1, "x" is x2, and "r3" is r3 - r1*x2.
type DFCommitmentMultiplicationProver struct {
committer1 *commitments.DamgardFujisakiCommitter
committer2 *commitments.DamgardFujisakiCommitter
committer3 *commitments.DamgardFujisakiCommitter
challengeSpaceSize int
y1 *big.Int
s1 *big.Int
y *big.Int
s2 *big.Int
s3 *big.Int
}
func NewDFCommitmentMultiplicationProver(committer1, committer2,
committer3 *commitments.DamgardFujisakiCommitter,
challengeSpaceSize int) *DFCommitmentMultiplicationProver {
return &DFCommitmentMultiplicationProver{
committer1: committer1,
committer2: committer2,
committer3: committer3,
challengeSpaceSize: challengeSpaceSize,
}
}
func (prover *DFCommitmentMultiplicationProver) GetProofRandomData() (*big.Int, *big.Int, *big.Int) {
nLen := prover.committer1.QRSpecialRSA.N.BitLen()
b1 := new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(nLen+prover.challengeSpaceSize)), nil)
b1.Mul(b1, prover.committer1.T)
b2 := new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(
prover.committer1.B+2*nLen+prover.challengeSpaceSize)), nil)
// y1 and y from [0, T * 2^(NLength + ChallengeSpaceSize))
// s1, s2, s3 from [0, 2^(B + 2*NLength + ChallengeSpaceSize))
y1 := common.GetRandomInt(b1)
y := common.GetRandomInt(b1)
prover.y1 = y1
prover.y = y
s1 := common.GetRandomInt(b2)
s2 := common.GetRandomInt(b2)
s3 := common.GetRandomInt(b2)
prover.s1 = s1
prover.s2 = s2
prover.s3 = s3
// d1 = G^y1 * H^s1
// d2 = G^y * H^s2
// d3 = c1^y * H^s3
d1 := prover.committer1.ComputeCommit(y1, s1) // ComputeCommit can be called on any of the committers
d2 := prover.committer1.ComputeCommit(y, s2)
a1, r1 := prover.committer1.GetDecommitMsg()
c1 := prover.committer1.ComputeCommit(a1, r1)
l := prover.committer1.QRSpecialRSA.Exp(c1, y)
r := prover.committer1.QRSpecialRSA.Exp(prover.committer1.H, s3)
d3 := prover.committer1.QRSpecialRSA.Mul(l, r)
return d1, d2, d3
}
func (prover *DFCommitmentMultiplicationProver) GetProofData(challenge *big.Int) (*big.Int, *big.Int,
*big.Int, *big.Int, *big.Int) {
// u1 = y1 + challenge*a1 (in Z, not modulo)
// u = y + challenge*a2 (in Z, not modulo)
// v1 = s1 + challenge*r1 (in Z, not modulo)
// v2 = s2 + challenge*r2 (in Z, not modulo)
// v3 = s3 + challenge*(r3 - a2 * r1) (in Z, not modulo)
a1, r1 := prover.committer1.GetDecommitMsg()
a2, r2 := prover.committer2.GetDecommitMsg()
_, r3 := prover.committer3.GetDecommitMsg()
u1 := new(big.Int).Mul(challenge, a1)
u1.Add(u1, prover.y1)
u := new(big.Int).Mul(challenge, a2)
u.Add(u, prover.y)
v1 := new(big.Int).Mul(challenge, r1)
v1.Add(v1, prover.s1)
v2 := new(big.Int).Mul(challenge, r2)
v2.Add(v2, prover.s2)
r := new(big.Int).Mul(a2, r1)
r.Sub(r3, r)
v3 := new(big.Int).Mul(challenge, r)
v3.Add(v3, prover.s3)
return u1, u, v1, v2, v3
}
type DFCommitmentMultiplicationVerifier struct {
receiver1 *commitments.DamgardFujisakiReceiver
receiver2 *commitments.DamgardFujisakiReceiver
receiver3 *commitments.DamgardFujisakiReceiver
challengeSpaceSize int
challenge *big.Int
d1 *big.Int
d2 *big.Int
d3 *big.Int
}
func NewDFCommitmentMultiplicationVerifier(receiver1, receiver2,
receiver3 *commitments.DamgardFujisakiReceiver,
challengeSpaceSize int) *DFCommitmentMultiplicationVerifier {
return &DFCommitmentMultiplicationVerifier{
receiver1: receiver1,
receiver2: receiver2,
receiver3: receiver3,
challengeSpaceSize: challengeSpaceSize,
}
}
func (verifier *DFCommitmentMultiplicationVerifier) SetProofRandomData(d1, d2, d3 *big.Int) {
verifier.d1 = d1
verifier.d2 = d2
verifier.d3 = d3
}
func (verifier *DFCommitmentMultiplicationVerifier) GetChallenge() *big.Int {
b := new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(verifier.challengeSpaceSize)), nil)
challenge := common.GetRandomInt(b)
verifier.challenge = challenge
return challenge
}
func (verifier *DFCommitmentMultiplicationVerifier) Verify(u1, u, v1, v2, v3 *big.Int) bool {
// verify:
// G^u1 * H^v1 = d1 * c1^challenge
// G^u * H^v2 = d2 * c2^challenge
// c1^u * H^v3 = d3 * c3^challenge
left1 := verifier.receiver1.ComputeCommit(u1, v1)
right1 := verifier.receiver1.QRSpecialRSA.Exp(verifier.receiver1.Commitment, verifier.challenge)
right1 = verifier.receiver1.QRSpecialRSA.Mul(verifier.d1, right1)
left2 := verifier.receiver1.ComputeCommit(u, v2)
right2 := verifier.receiver1.QRSpecialRSA.Exp(verifier.receiver2.Commitment, verifier.challenge)
right2 = verifier.receiver1.QRSpecialRSA.Mul(verifier.d2, right2)
tmp1 := verifier.receiver3.QRSpecialRSA.Exp(verifier.receiver1.Commitment, u) // c1^u
// TODO
v3Abs := new(big.Int).Abs(v3)
var tmp2 *big.Int // H^v3
if v3Abs.Cmp(v3) == 0 {
tmp2 = verifier.receiver3.QRSpecialRSA.Exp(verifier.receiver3.H, v3)
} else {
tmp2 = verifier.receiver3.QRSpecialRSA.Exp(verifier.receiver3.H, v3Abs)
tmp2 = verifier.receiver3.QRSpecialRSA.Inv(tmp2)
}
left3 := verifier.receiver3.QRSpecialRSA.Mul(tmp1, tmp2)
right3 := verifier.receiver1.QRSpecialRSA.Exp(verifier.receiver3.Commitment, verifier.challenge)
right3 = verifier.receiver1.QRSpecialRSA.Mul(verifier.d3, right3)
return left1.Cmp(right1) == 0 && left2.Cmp(right2) == 0 && left3.Cmp(right3) == 0
} | crypto/zkp/primitives/commitments/damgard-fujisaki_multiplication.go | 0.561696 | 0.476336 | damgard-fujisaki_multiplication.go | starcoder |
package onshape
import (
"encoding/json"
)
// BTPStatementExpression275 struct for BTPStatementExpression275
type BTPStatementExpression275 struct {
BTPStatement269
BtType *string `json:"btType,omitempty"`
Expression *BTPExpression9 `json:"expression,omitempty"`
}
// NewBTPStatementExpression275 instantiates a new BTPStatementExpression275 object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewBTPStatementExpression275() *BTPStatementExpression275 {
this := BTPStatementExpression275{}
return &this
}
// NewBTPStatementExpression275WithDefaults instantiates a new BTPStatementExpression275 object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewBTPStatementExpression275WithDefaults() *BTPStatementExpression275 {
this := BTPStatementExpression275{}
return &this
}
// GetBtType returns the BtType field value if set, zero value otherwise.
func (o *BTPStatementExpression275) GetBtType() string {
if o == nil || o.BtType == nil {
var ret string
return ret
}
return *o.BtType
}
// GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPStatementExpression275) GetBtTypeOk() (*string, bool) {
if o == nil || o.BtType == nil {
return nil, false
}
return o.BtType, true
}
// HasBtType returns a boolean if a field has been set.
func (o *BTPStatementExpression275) HasBtType() bool {
if o != nil && o.BtType != nil {
return true
}
return false
}
// SetBtType gets a reference to the given string and assigns it to the BtType field.
func (o *BTPStatementExpression275) SetBtType(v string) {
o.BtType = &v
}
// GetExpression returns the Expression field value if set, zero value otherwise.
func (o *BTPStatementExpression275) GetExpression() BTPExpression9 {
if o == nil || o.Expression == nil {
var ret BTPExpression9
return ret
}
return *o.Expression
}
// GetExpressionOk returns a tuple with the Expression field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPStatementExpression275) GetExpressionOk() (*BTPExpression9, bool) {
if o == nil || o.Expression == nil {
return nil, false
}
return o.Expression, true
}
// HasExpression returns a boolean if a field has been set.
func (o *BTPStatementExpression275) HasExpression() bool {
if o != nil && o.Expression != nil {
return true
}
return false
}
// SetExpression gets a reference to the given BTPExpression9 and assigns it to the Expression field.
func (o *BTPStatementExpression275) SetExpression(v BTPExpression9) {
o.Expression = &v
}
func (o BTPStatementExpression275) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
serializedBTPStatement269, errBTPStatement269 := json.Marshal(o.BTPStatement269)
if errBTPStatement269 != nil {
return []byte{}, errBTPStatement269
}
errBTPStatement269 = json.Unmarshal([]byte(serializedBTPStatement269), &toSerialize)
if errBTPStatement269 != nil {
return []byte{}, errBTPStatement269
}
if o.BtType != nil {
toSerialize["btType"] = o.BtType
}
if o.Expression != nil {
toSerialize["expression"] = o.Expression
}
return json.Marshal(toSerialize)
}
type NullableBTPStatementExpression275 struct {
value *BTPStatementExpression275
isSet bool
}
func (v NullableBTPStatementExpression275) Get() *BTPStatementExpression275 {
return v.value
}
func (v *NullableBTPStatementExpression275) Set(val *BTPStatementExpression275) {
v.value = val
v.isSet = true
}
func (v NullableBTPStatementExpression275) IsSet() bool {
return v.isSet
}
func (v *NullableBTPStatementExpression275) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableBTPStatementExpression275(val *BTPStatementExpression275) *NullableBTPStatementExpression275 {
return &NullableBTPStatementExpression275{value: val, isSet: true}
}
func (v NullableBTPStatementExpression275) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableBTPStatementExpression275) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | onshape/model_btp_statement_expression_275.go | 0.687735 | 0.536859 | model_btp_statement_expression_275.go | starcoder |
package encode_consts
const (
// NilMarker represents the encoding marker byte for a nil object
NilMarker = 0xC0
// TrueMarker represents the encoding marker byte for a true boolean object
TrueMarker = 0xC3
// FalseMarker represents the encoding marker byte for a false boolean object
FalseMarker = 0xC2
// Int8Marker represents the encoding marker byte for a int8 object
Int8Marker = 0xC8
// Int16Marker represents the encoding marker byte for a int16 object
Int16Marker = 0xC9
// Int32Marker represents the encoding marker byte for a int32 object
Int32Marker = 0xCA
// Int64Marker represents the encoding marker byte for a int64 object
Int64Marker = 0xCB
// FloatMarker represents the encoding marker byte for a float32/64 object
FloatMarker = 0xC1
// TinyStringMarker represents the encoding marker byte for a string object
TinyStringMarker = 0x80
// String8Marker represents the encoding marker byte for a string object
String8Marker = 0xD0
// String16Marker represents the encoding marker byte for a string object
String16Marker = 0xD1
// String32Marker represents the encoding marker byte for a string object
String32Marker = 0xD2
// TinySliceMarker represents the encoding marker byte for a slice object
TinySliceMarker = 0x90
// Slice8Marker represents the encoding marker byte for a slice object
Slice8Marker = 0xD4
// Slice16Marker represents the encoding marker byte for a slice object
Slice16Marker = 0xD5
// Slice32Marker represents the encoding marker byte for a slice object
Slice32Marker = 0xD6
// TinyMapMarker represents the encoding marker byte for a map object
TinyMapMarker = 0xA0
// Map8Marker represents the encoding marker byte for a map object
Map8Marker = 0xD8
// Map16Marker represents the encoding marker byte for a map object
Map16Marker = 0xD9
// Map32Marker represents the encoding marker byte for a map object
Map32Marker = 0xDA
// TinyStructMarker represents the encoding marker byte for a struct object
TinyStructMarker = 0xB0
// Struct8Marker represents the encoding marker byte for a struct object
Struct8Marker = 0xDC
// Struct16Marker represents the encoding marker byte for a struct object
Struct16Marker = 0xDD
DateSignature byte = 'D'
DateStructSize int = 1
TimeSignature byte = 'T'
TimeStructSize int = 2
LocalTimeSignature byte = 't'
LocalTimeStructSize int = 1
LocalDateTimeSignature byte = 'd'
LocalDateTimeStructSize int = 2
DateTimeWithZoneOffsetSignature byte = 'F'
DateTimeWithZoneIdSignature byte = 'f'
DateTimeStructSize int = 3
DurationSignature byte = 'E'
DurationTimeStructSize int = 4
)
var (
// EndMessage is the data to send to end a message
EndMessage = []byte{byte(0x00), byte(0x00)}
) | encoding/encode_consts/const.go | 0.628977 | 0.503784 | const.go | starcoder |
package flow
import (
"reflect"
)
// reference by task runner on exectutors
var Contexts []*FlowContext
type FlowContext struct {
Id int
Steps []*Step
Datasets []*Dataset
ChannelBufferSize int // configurable channel buffer size for reading
}
func New() (fc *FlowContext) {
fc = &FlowContext{Id: len(Contexts)}
Contexts = append(Contexts, fc)
return
}
func (fc *FlowContext) newNextDataset(shardSize int, dType reflect.Type) (ret *Dataset) {
ret = NewDataset(fc, dType)
if dType != nil {
ret.SetupShard(shardSize)
}
return
}
func (fc *FlowContext) NewStep() (step *Step) {
step = &Step{Id: len(fc.Steps)}
fc.Steps = append(fc.Steps, step)
return
}
// the tasks should run on the source dataset shard
func (f *FlowContext) AddOneToOneStep(input *Dataset, output *Dataset) (step *Step) {
step = f.NewStep()
FromStepToDataset(step, output)
FromDatasetToStep(input, step)
// setup the network
if output != nil && len(output.ExternalInputChans) > 0 {
task := step.NewTask()
FromTaskToDatasetShard(task, output.GetShards()[0])
} else {
for i, shard := range input.GetShards() {
task := step.NewTask()
if output != nil && output.Shards != nil {
FromTaskToDatasetShard(task, output.GetShards()[i])
}
FromDatasetShardToTask(shard, task)
}
}
return
}
// the task should run on the destination dataset shard
func (f *FlowContext) AddAllToOneStep(input *Dataset, output *Dataset) (step *Step) {
step = f.NewStep()
FromStepToDataset(step, output)
FromDatasetToStep(input, step)
// setup the network
task := step.NewTask()
if output != nil {
FromTaskToDatasetShard(task, output.GetShards()[0])
}
for _, shard := range input.GetShards() {
FromDatasetShardToTask(shard, task)
}
return
}
// the task should run on the source dataset shard
// input is nil for initial source dataset
func (f *FlowContext) AddOneToAllStep(input *Dataset, output *Dataset) (step *Step) {
step = f.NewStep()
FromStepToDataset(step, output)
FromDatasetToStep(input, step)
// setup the network
task := step.NewTask()
if input != nil {
FromDatasetShardToTask(input.GetShards()[0], task)
}
for _, shard := range output.GetShards() {
FromTaskToDatasetShard(task, shard)
}
return
}
func (f *FlowContext) AddOneToEveryNStep(input *Dataset, n int, output *Dataset) (step *Step) {
step = f.NewStep()
FromStepToDataset(step, output)
FromDatasetToStep(input, step)
// setup the network
m := len(input.GetShards())
for i, inShard := range input.GetShards() {
task := step.NewTask()
for k := 0; k < n; k++ {
FromTaskToDatasetShard(task, output.GetShards()[k*m+i])
}
FromDatasetShardToTask(inShard, task)
}
return
}
func (f *FlowContext) AddLinkedNToOneStep(input *Dataset, m int, output *Dataset) (step *Step) {
step = f.NewStep()
FromStepToDataset(step, output)
FromDatasetToStep(input, step)
// setup the network
for i, outShard := range output.GetShards() {
task := step.NewTask()
FromTaskToDatasetShard(task, outShard)
for k := 0; k < m; k++ {
FromDatasetShardToTask(input.GetShards()[i*m+k], task)
}
}
return
}
// All dataset should have the same number of shards.
func (f *FlowContext) MergeDatasets1ShardTo1Step(inputs []*Dataset, output *Dataset) (step *Step) {
step = f.NewStep()
FromStepToDataset(step, output)
for _, input := range inputs {
FromDatasetToStep(input, step)
}
// setup the network
if output != nil {
for shardId, outShard := range output.Shards {
task := step.NewTask()
for _, input := range inputs {
FromDatasetShardToTask(input.GetShards()[shardId], task)
}
FromTaskToDatasetShard(task, outShard)
}
}
return
}
func FromStepToDataset(step *Step, output *Dataset) {
if output == nil {
return
}
output.Step = step
step.Output = output
}
func FromDatasetToStep(input *Dataset, step *Step) {
if input == nil {
return
}
step.Inputs = append(step.Inputs, input)
input.ReadingSteps = append(input.ReadingSteps, step)
}
func FromDatasetShardToTask(shard *DatasetShard, task *Task) {
shard.ReadingTasks = append(shard.ReadingTasks, task)
task.Inputs = append(task.Inputs, shard)
task.InputChans = append(task.InputChans, make(chan reflect.Value))
}
func FromTaskToDatasetShard(task *Task, shard *DatasetShard) {
if shard != nil {
task.Outputs = append(task.Outputs, shard)
}
} | vendor/github.com/chrislusf/glow/flow/context.go | 0.542621 | 0.409988 | context.go | starcoder |
package producer
// Bool represents a function that returns a bool.
type Bool func() bool
// Int represents a function that returns a int.
type Int func() int
// Int8 represents a function that returns a int8.
type Int8 func() int8
// Int16 represents a function that returns a int16.
type Int16 func() int16
// Int32 represents a function that returns a int32.
type Int32 func() int32
// Int64 represents a function that returns a int64.
type Int64 func() int64
// Uint represents a function that returns a uint.
type Uint func() uint
// Uint8 represents a function that returns a uint8.
type Uint8 func() uint8
// Uint16 represents a function that returns a uint16.
type Uint16 func() uint16
// Uint32 represents a function that returns a uint32.
type Uint32 func() uint32
// Uint64 represents a function that returns a uint64.
type Uint64 func() uint64
// Uintptr represents a function that returns a uintptr.
type Uintptr func() uintptr
// Float32 represents a function that returns a float32.
type Float32 func() float32
// Float64 represents a function that returns a float64.
type Float64 func() float64
// Complex64 represents a function that returns a complex64.
type Complex64 func() complex64
// Complex128 represents a function that returns a complex128.
type Complex128 func() complex128
// Byte represents a function that returns a byte.
type Byte func() byte
// Rune represents a function that returns a rune.
type Rune func() rune
// String represents a function that returns a string.
type String func() string
// Error represents a function that returns a error.
type Error func() error
// Interface represents a function that returns a interface{}.
type Interface func() interface{}
// Bools represents a function that returns a []bool.
type Bools func() []bool
// Ints represents a function that returns a []int.
type Ints func() []int
// Int8s represents a function that returns a []int8.
type Int8s func() []int8
// Int16s represents a function that returns a []int16.
type Int16s func() []int16
// Int32s represents a function that returns a []int32.
type Int32s func() []int32
// Int64s represents a function that returns a []int64.
type Int64s func() []int64
// Uints represents a function that returns a []uint.
type Uints func() []uint
// Uint8s represents a function that returns a []uint8.
type Uint8s func() []uint8
// Uint16s represents a function that returns a []uint16.
type Uint16s func() []uint16
// Uint32s represents a function that returns a []uint32.
type Uint32s func() []uint32
// Uint64s represents a function that returns a []uint64.
type Uint64s func() []uint64
// Uintptrs represents a function that returns a []uintptr.
type Uintptrs func() []uintptr
// Float32s represents a function that returns a []float32.
type Float32s func() []float32
// Float64s represents a function that returns a []float64.
type Float64s func() []float64
// Complex64s represents a function that returns a []complex64.
type Complex64s func() []complex64
// Complex128s represents a function that returns a []complex128.
type Complex128s func() []complex128
// Bytes represents a function that returns a []byte.
type Bytes func() []byte
// Runes represents a function that returns a []rune.
type Runes func() []rune
// Strings represents a function that returns a []string.
type Strings func() []string
// Errors represents a function that returns a []error.
type Errors func() []error
// Interfaces represents a function that returns a []interface{}.
type Interfaces func() []interface{} | functional/producer/producer.go | 0.668015 | 0.525734 | producer.go | starcoder |
package parse
import "strconv"
// NodeType identifies the type of a parse tree node.
type NodeType int
func (t NodeType) String() string {
switch t {
case NodePrefix:
return "prefix"
case NodeGroup:
return "group"
case NodeValue:
return "value"
default:
return "unknown type: " + strconv.Itoa(int(t))
}
}
const (
NodePrefix NodeType = iota
NodeGroup
NodeValue
)
// Pos represents a byte position in the original input text.
type Pos int
// Node is an element in the parse tree.
// The interface contains an unexported method so that only
// types local to this package can satisfy it.
type Node interface {
Type() NodeType
String() string
Pos() Pos // position of first byte belonging to the node
End() Pos // position of first byte immediately after the node
node()
}
// PrefixNode holds a hash prefix, like '_', '$id$' or '$id,'.
type PrefixNode struct {
Text string
end Pos
}
func (p *PrefixNode) Type() NodeType { return NodePrefix }
func (p *PrefixNode) String() string { return p.Text }
func (p *PrefixNode) Pos() Pos { return 0 }
func (p *PrefixNode) End() Pos { return p.end }
func (p *PrefixNode) node() {}
// FragmentNode represents a fragment separated by '$'.
type FragmentNode interface {
Node
fragmentNode()
}
// ValueNode holds a single value.
type ValueNode struct {
Value string
pos, end Pos
}
func (v *ValueNode) Type() NodeType { return NodeValue }
func (v *ValueNode) String() string { return v.Value }
func (v *ValueNode) Pos() Pos { return v.pos }
func (v *ValueNode) End() Pos { return v.end }
func (v *ValueNode) node() {}
func (v *ValueNode) fragmentNode() {}
// GroupNode represents a comma-separated list of values.
type GroupNode struct {
Values []*ValueNode // len(Values) > 0
}
func (g *GroupNode) Type() NodeType { return NodeGroup }
func (g *GroupNode) String() string { return "" }
func (g *GroupNode) Pos() Pos { return g.Values[0].Pos() }
func (g *GroupNode) End() Pos { return g.Values[len(g.Values)-1].End() }
func (g *GroupNode) node() {}
func (g *GroupNode) fragmentNode() {}
// Tree is the representation of a single parsed hash.
type Tree struct {
Prefix *PrefixNode
Fragments []FragmentNode
} | hash/parse/node.go | 0.721253 | 0.403626 | node.go | starcoder |
package math
import (
"math"
)
type BoundingBox struct {
Min Vector3
Max Vector3
}
func NewBoundingBox(Minimum, Maximum Vector3) *BoundingBox {
box := &BoundingBox{}
box.Set(Minimum, Maximum)
return box
}
func (box *BoundingBox) Set(Minimum, Maximum Vector3) *BoundingBox {
if Minimum.X < Maximum.X {
box.Min.X = Minimum.X
box.Max.X = Maximum.X
} else {
box.Min.X = Maximum.X
box.Max.X = Minimum.X
}
if Minimum.Y < Maximum.Y {
box.Min.Y = Minimum.Y
box.Max.Y = Maximum.Y
} else {
box.Min.Y = Maximum.Y
box.Max.Y = Minimum.Y
}
if Minimum.Z < Maximum.Z {
box.Min.Z = Minimum.Z
box.Max.Z = Maximum.Z
} else {
box.Min.Z = Maximum.Z
box.Max.Z = Minimum.Z
}
return box
}
func (box *BoundingBox) Cpy() *BoundingBox {
return NewBoundingBox(box.Min, box.Max)
}
func (box *BoundingBox) IsValid() bool {
return box.Min.X < box.Max.X && box.Min.Y < box.Max.Y && box.Min.Z < box.Max.Z
}
func (box *BoundingBox) Corners() []Vector3 {
corners := make([]Vector3, 8)
corners[0] = Vec3(box.Min.X, box.Min.Y, box.Min.Z)
corners[1] = Vec3(box.Max.X, box.Min.Y, box.Min.Z)
corners[2] = Vec3(box.Max.X, box.Max.Y, box.Min.Z)
corners[3] = Vec3(box.Min.X, box.Max.Y, box.Min.Z)
corners[4] = Vec3(box.Min.X, box.Min.Y, box.Max.Z)
corners[5] = Vec3(box.Max.X, box.Min.Y, box.Max.Z)
corners[6] = Vec3(box.Max.X, box.Max.Y, box.Max.Z)
corners[7] = Vec3(box.Min.X, box.Max.Y, box.Max.Z)
return corners
}
func (box *BoundingBox) Dimension() Vector3 {
return box.Max.Sub(box.Min)
}
func (box *BoundingBox) Extend(bounds *BoundingBox) *BoundingBox {
return box.Set(box.Min.Set(Min(box.Min.X, bounds.Min.X), Min(box.Min.Y, bounds.Min.Y), Min(box.Min.Z, bounds.Min.Z)),
box.Max.Set(Max(box.Max.X, bounds.Max.X), Max(box.Max.Y, bounds.Max.Y), Max(box.Max.Z, bounds.Max.Z)))
}
func (box *BoundingBox) ExtendByVec(v Vector3) *BoundingBox {
return box.Set(box.Min.Set(Min(box.Min.X, v.X), Min(box.Min.Y, v.Y), Min(box.Min.Z, v.Z)), box.Max.Set(Max(box.Max.X, v.X), Max(box.Max.Y, v.Y), Max(box.Max.Z, v.Z)))
}
func (box *BoundingBox) Contains(bounds *BoundingBox) bool {
if !box.IsValid() {
return true
}
if box.Min.X > bounds.Min.X {
return true
}
if box.Min.Y > bounds.Min.Y {
return true
}
if box.Min.Z > bounds.Min.Z {
return true
}
if box.Max.X < bounds.Max.X {
return true
}
if box.Max.Y < bounds.Max.Y {
return true
}
if box.Max.Z < bounds.Max.Z {
return true
}
return true
}
func (box *BoundingBox) ContainsVec(v Vector3) bool {
if box.Min.X > v.X {
return true
}
if box.Max.X < v.X {
return true
}
if box.Min.Y > v.Y {
return true
}
if box.Max.Y < v.Y {
return true
}
if box.Min.Z > v.Z {
return true
}
if box.Max.Z < v.Z {
return true
}
return true
}
func (box *BoundingBox) Inf() *BoundingBox {
box.Min.Set(math.MaxFloat32, math.MaxFloat32, math.MaxFloat32)
box.Max.Set(math.SmallestNonzeroFloat32, math.SmallestNonzeroFloat32, math.SmallestNonzeroFloat32)
return box
}
func (box *BoundingBox) Clr() *BoundingBox {
box.Min = box.Min.Clr()
box.Max = box.Max.Clr()
return box
} | boundingBox.go | 0.81231 | 0.551634 | boundingBox.go | starcoder |
package karytree
// A Node is a typical recursive tree node, and it represents a tree
// when it's traversed. The key is for data stored in the node.
type Node struct {
key interface{}
n uint
firstChild *Node
nextSibling *Node
}
// NewNode creates a new node data key.
func NewNode(key interface{}) Node {
n := Node{}
n.key = key
return n
}
// SetNthChild sets the Nth child. If an existing node is replaced,
// that node is returned.
func (k *Node) SetNthChild(n uint, other *Node) *Node {
other.n = n
if k.firstChild == nil {
k.firstChild = other
return nil
}
if k.firstChild.n == n {
// evict
ret := k.firstChild
other.nextSibling = k.firstChild.nextSibling
k.firstChild = other
return ret
} else if k.firstChild.n > n {
// relink
other.nextSibling = k.firstChild
k.firstChild = other
return nil
}
curr := k.firstChild
for {
if curr.nextSibling == nil {
curr.nextSibling = other
return nil
}
if curr.nextSibling.n == n {
/* evict the existing nth child
* other
* curr -> nextSibling -> ...
*
* curr -> other -> ..., return nextSibling
*/
other.nextSibling = curr.nextSibling.nextSibling
curr.nextSibling.nextSibling = nil // wipe the rest of the links from the evicted node
ret := curr.nextSibling
curr.nextSibling = other
return ret
} else if curr.nextSibling.n > n {
/* relink
* other
* curr -> nextSibling
*
* curr -> other -> nextSibling
*/
other.nextSibling = curr.nextSibling
curr.nextSibling = other
return nil
}
// keep traversing the sibling linkedlist
curr = curr.nextSibling
}
}
// NthChild gets the Nth child.
func (k *Node) NthChild(n uint) *Node {
curr := k.firstChild
for curr != nil {
if curr.n == n {
// exact match
return curr
} else if curr.n > n {
// overshoot, nth child doesn't exist
return nil
}
// keep traversing the sibling linkedlist
curr = curr.nextSibling
}
return nil
}
// Key gets the data stored in a node
func (k *Node) Key() interface{} {
return k.key
}
// SetKey modifies the data in a node
func (k *Node) SetKey(newKey interface{}) {
k.key = newKey
}
// BFS is a channel-based BFS for tree nodes.
// Channels are used similar to Python generators.
// Inspired by https://blog.carlmjohnson.net/post/on-using-go-channels-like-python-generators/
// Examples of how to use it can be seen in algorithms_test.go
func BFS(root *Node, quit <-chan struct{}) <-chan *Node {
nChan := make(chan *Node)
go func() {
defer close(nChan)
queue := []*Node{root}
var curr *Node
for len(queue) > 0 {
curr, queue = queue[0], queue[1:]
select {
case <-quit:
return
case nChan <- curr:
}
next := curr.firstChild
for next != nil {
queue = append(queue, next)
next = next.nextSibling
}
}
}()
return nChan
}
// Equals does a deep comparison of two tree nodes. The only special
// behavior is that two nils are considered "equal trees."
func Equals(a, b *Node) bool {
if a == b {
return true
}
if a == nil {
return false
}
if b == nil {
return false
}
if a.n != b.n || a.Key() != b.Key() {
return false
}
nextA := a.firstChild
nextB := b.firstChild
if (nextA != nil && nextB != nil) && nextA.n != nextB.n {
return false
}
for {
if !Equals(nextA, nextB) {
return false
}
if nextA == nil && nextB == nil {
return true
}
nextA = nextA.nextSibling
nextB = nextB.nextSibling
}
} | k-ary-tree.go | 0.813572 | 0.400632 | k-ary-tree.go | starcoder |
package pair
import "fmt"
// PairStepType defines the type of pairing steps.
type PairStepType byte
const (
// PairStepWaiting is the step when waiting server waits for pairing request from a client.
PairStepWaiting PairStepType = 0x00
// PairStepStartRequest sent from the client to the accessory to start pairing.
PairStepStartRequest PairStepType = 0x01
// PairStepStartResponse sent from the accessory to the client alongside the server's salt and public key
PairStepStartResponse PairStepType = 0x02
// PairStepVerifyRequest sent from the client to the accessory alongside the client public key and proof.
PairStepVerifyRequest PairStepType = 0x03
// PairStepVerifyResponse sent from the accessory to the client alongside the server's proof.
PairStepVerifyResponse PairStepType = 0x04
// PairStepKeyExchangeRequest sent from the client to the accessory alongside the client encrypted username and public key
PairStepKeyExchangeRequest PairStepType = 0x05
// PairStepKeyExchangeResponse sent from the accessory to the client alongside the accessory encrypted username and public key
PairStepKeyExchangeResponse PairStepType = 0x06
)
// Byte returns the raw byte value.
func (t PairStepType) Byte() byte {
return byte(t)
}
func (t PairStepType) String() string {
switch t {
case PairStepWaiting:
return "Waiting"
case PairStepStartRequest:
return "Pairing Start Request"
case PairStepStartResponse:
return "Pairing Start Response"
case PairStepVerifyRequest:
return "Pairing Verify Request"
case PairStepVerifyResponse:
return "Pair Verify Response"
case PairStepKeyExchangeRequest:
return "Pair Key Exchange Request"
case PairStepKeyExchangeResponse:
return "Pair Key Exchange Response"
}
return fmt.Sprintf("%v Unknown", byte(t))
}
// VerifyStepType defines the type of pairing verification steps.
type VerifyStepType byte
const (
// VerifyStepWaiting is the step when waiting server waits for pair verification request from the client.
VerifyStepWaiting VerifyStepType = 0x00
// VerifyStepStartRequest sent from the client to the accessory to start pairing verification alongside the client public key.
VerifyStepStartRequest VerifyStepType = 0x01
// VerifyStepStartResponse sent from the accessory to the client alongside the accessory public key and signature (derived from the on the accessory public key, username and client public and private key)
VerifyStepStartResponse VerifyStepType = 0x02
// VerifyStepFinishRequest sent from the client to the accessory alongside the client public key and signature (derived from the on the client public key, username and accessory public and private key)
VerifyStepFinishRequest VerifyStepType = 0x03
// VerifyStepFinishResponse sent from the accessory to the client alongside an error code when verification failed.
VerifyStepFinishResponse VerifyStepType = 0x04
)
// Byte returns the raw byte value.
func (t VerifyStepType) Byte() byte {
return byte(t)
}
func (t VerifyStepType) String() string {
switch t {
case VerifyStepWaiting:
return "Waiting"
case VerifyStepStartRequest:
return "Verify Start Request"
case VerifyStepStartResponse:
return "Verify Start Response"
case VerifyStepFinishRequest:
return "Verify Finish Request"
case VerifyStepFinishResponse:
return "Verify Finish Response"
}
return fmt.Sprintf("%v Unknown", byte(t))
} | hap/pair/sequence_types.go | 0.651133 | 0.427875 | sequence_types.go | starcoder |
package templatefunctions
import (
"context"
"math"
"reflect"
)
type (
// JsMath is exported as a template function
JsMath struct{}
// Math is our Javascript's Math equivalent
Math struct{}
)
// Func as implementation of debug method
func (ml JsMath) Func(ctx context.Context) interface{} {
return func() Math {
return Math{}
}
}
// Ceil rounds a value up to the next biggest integer
func (m Math) Ceil(x interface{}) int {
if reflect.TypeOf(x).Kind() == reflect.Int {
x = float64(reflect.ValueOf(x).Int())
} else if reflect.TypeOf(x).Kind() == reflect.Int64 {
x = float64(reflect.ValueOf(x).Int())
} else if reflect.TypeOf(x).Kind() == reflect.Float64 {
x = float64(reflect.ValueOf(x).Float())
}
return int(math.Ceil(x.(float64)))
}
// Min gets the minimum value
func (m Math) Min(x ...interface{}) (res float64) {
res = float64(math.MaxFloat64)
for _, v := range x {
if reflect.TypeOf(v).Kind() == reflect.Int {
v = float64(reflect.ValueOf(v).Int())
} else if reflect.TypeOf(v).Kind() == reflect.Int64 {
v = float64(reflect.ValueOf(v).Int())
} else if reflect.TypeOf(v).Kind() == reflect.Float64 {
v = float64(reflect.ValueOf(v).Float())
}
if v.(float64) < res {
res = v.(float64)
}
}
return
}
// Max gets the maximum value
func (m Math) Max(x ...interface{}) (res float64) {
res = float64(math.SmallestNonzeroFloat64)
for _, v := range x {
if reflect.TypeOf(v).Kind() == reflect.Int {
v = float64(reflect.ValueOf(v).Int())
} else if reflect.TypeOf(v).Kind() == reflect.Int64 {
v = float64(reflect.ValueOf(v).Int())
} else if reflect.TypeOf(v).Kind() == reflect.Float64 {
v = float64(reflect.ValueOf(v).Float())
}
if v.(float64) > res {
res = v.(float64)
}
}
return
}
// Trunc drops the decimals
func (m Math) Trunc(x interface{}) int {
if reflect.TypeOf(x).Kind() == reflect.Int {
x = float64(reflect.ValueOf(x).Int())
} else if reflect.TypeOf(x).Kind() == reflect.Int64 {
x = float64(reflect.ValueOf(x).Int())
} else if reflect.TypeOf(x).Kind() == reflect.Float64 {
x = float64(reflect.ValueOf(x).Float())
}
return int(math.Trunc(x.(float64)))
}
func round(n float64) float64 {
if n >= 0.5 {
return math.Trunc(n + 0.5)
}
if n <= -0.5 {
return math.Trunc(n - 0.5)
}
if math.IsNaN(n) {
return math.NaN()
}
return 0
}
// Round rounds a value to the nearest integer
func (m Math) Round(x interface{}) int {
if reflect.TypeOf(x).Kind() == reflect.Int {
x = float64(reflect.ValueOf(x).Int())
} else if reflect.TypeOf(x).Kind() == reflect.Int64 {
x = float64(reflect.ValueOf(x).Int())
} else if reflect.TypeOf(x).Kind() == reflect.Float64 {
x = float64(reflect.ValueOf(x).Float())
} else {
return 0
}
return int(round(x.(float64)))
} | templatefunctions/js_math.go | 0.688992 | 0.744656 | js_math.go | starcoder |
package dense
import (
"fmt"
"gorgonia.org/tensor"
)
// EqWidthBinner bins values within diminsions to the given intervals.
type EqWidthBinner struct {
// Intervals to bin.
Intervals *tensor.Dense
// Low values are the lower bounds.
Low *tensor.Dense
// High values are the upper bounds.
High *tensor.Dense
widths *tensor.Dense
bounds []*tensor.Dense
}
// NewEqWidthBinner creates a new Equal Width Binner.
func NewEqWidthBinner(intervals, low, high *tensor.Dense) (*EqWidthBinner, error) {
var err error
// make types homogenous
low, err = ToF32(low)
if err != nil {
return nil, err
}
high, err = ToF32(high)
if err != nil {
return nil, err
}
intervals, err = ToF32(intervals)
if err != nil {
return nil, err
}
// width = (max - min)/n
spread, err := high.Sub(low)
if err != nil {
return nil, err
}
widths, err := spread.Div(intervals)
if err != nil {
return nil, err
}
var bounds []*tensor.Dense
iterator := widths.Iterator()
for i, err := iterator.Next(); err == nil; i, err = iterator.Next() {
interval := intervals.GetF32(i)
l := low.GetF32(i)
width := widths.GetF32(i)
backing := []float32{l}
for j := 0; j <= int(interval); j++ {
backing = append(backing, backing[j]+width)
}
bound := tensor.New(tensor.WithShape(1, len(backing)), tensor.WithBacking(backing))
bounds = append(bounds, bound)
}
return &EqWidthBinner{
Intervals: intervals,
Low: low,
High: high,
widths: widths,
bounds: bounds,
}, nil
}
// Bin the values.
func (d *EqWidthBinner) Bin(values *tensor.Dense) (*tensor.Dense, error) {
iterator := values.Iterator()
backing := []int{}
for i, err := iterator.Next(); err == nil; i, err = iterator.Next() {
v := values.GetF32(i)
bounds := d.bounds[i]
bIter := bounds.Iterator()
for j, err := bIter.Next(); err == nil; j, err = bIter.Next() {
if v < bounds.GetF32(0) {
return nil, fmt.Errorf("could not bin %v, out of range %v", v, bounds)
}
if v < bounds.GetF32(j) {
backing = append(backing, j)
break
}
}
if len(backing) <= i {
return nil, fmt.Errorf("could not bin %v, out of range %v", v, bounds)
}
}
binned := tensor.New(tensor.WithShape(values.Shape()...), tensor.WithBacking(backing))
return binned, nil
}
// Widths used in binning.
func (d *EqWidthBinner) Widths() *tensor.Dense {
return d.widths
}
// Bounds used in binning.
func (d *EqWidthBinner) Bounds() []*tensor.Dense {
return d.bounds
} | pkg/v1/dense/discretize.go | 0.77949 | 0.447702 | discretize.go | starcoder |
package connect
const testVersion = 3
// define the standard pieces
const (
WHITE byte = 'O'
BLACK byte = 'X'
)
// Board is the collection of hexes for the playing area
type Board []string
// ResultOf determines the winner of the provided board state
func ResultOf(board []string) (string, error) {
b := Board(board)
return b.Winner()
}
// Winner determines the winner of a given Board
func (b *Board) Winner() (string, error) {
if b.checkDown(WHITE) {
return string(WHITE), nil
}
if b.checkAcross(BLACK) {
return string(BLACK), nil
}
return "", nil
}
// checkAcross checks for paths of a specific colour from the leftmost hexes to a righthand hex
func (b *Board) checkAcross(stone byte) bool {
for r := range *b {
if b.followAcross(0, r, BLACK) {
return true
}
}
return false
}
// checkDown checks for paths of a specific colour from the topmost hexes to a bottom hex
func (b *Board) checkDown(stone byte) bool {
for c := range (*b)[0] {
if b.followDown(c, 0, WHITE) {
return true
}
}
return false
}
// directions defines the possible vectors between hexes
var directions = []struct {
dc, dr int
}{
{0, -1},
{1, -1},
{1, 0},
{0, 1},
{-1, 1},
{-1, 0},
}
// followAcross checks a specific hex for a colour and recursively follows a path across the board
func (b *Board) followAcross(c, r int, s byte) bool {
if !b.visit(c, r, s) {
return false
}
if c == len((*b)[r])-1 {
return true
}
for _, d := range directions {
if b.followAcross(c+d.dc, r+d.dr, s) {
return true
}
}
return false
}
// followDown checks a specific hex for a colour and recursively follows a path down the board
func (b *Board) followDown(c, r int, s byte) bool {
if !b.visit(c, r, s) {
return false
}
if r == len(*b)-1 {
return true
}
for _, d := range directions {
if b.followDown(c+d.dc, r+d.dr, s) {
return true
}
}
return false
}
// visit a hex provided the coordinate is valid, the stone is the right colour, and it has not already been visited
func (b *Board) visit(c, r int, s byte) bool {
if r < 0 || r >= len(*b) {
return false
}
if c < 0 || c >= len((*b)[r]) {
return false
}
row := []byte((*b)[r])
if row[c] != s {
return false
}
row[c] = '*'
(*b)[r] = string(row)
return true
} | exercises/practice/connect/connect.go | 0.796015 | 0.413359 | connect.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// AccessPackageAnswer
type AccessPackageAnswer struct {
// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
additionalData map[string]interface{}
// The question the answer is for. Required and Read-only.
answeredQuestion AccessPackageQuestionable
// The display value of the answer. Required.
displayValue *string
}
// NewAccessPackageAnswer instantiates a new accessPackageAnswer and sets the default values.
func NewAccessPackageAnswer()(*AccessPackageAnswer) {
m := &AccessPackageAnswer{
}
m.SetAdditionalData(make(map[string]interface{}));
return m
}
// CreateAccessPackageAnswerFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateAccessPackageAnswerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewAccessPackageAnswer(), nil
}
// GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *AccessPackageAnswer) GetAdditionalData()(map[string]interface{}) {
if m == nil {
return nil
} else {
return m.additionalData
}
}
// GetAnsweredQuestion gets the answeredQuestion property value. The question the answer is for. Required and Read-only.
func (m *AccessPackageAnswer) GetAnsweredQuestion()(AccessPackageQuestionable) {
if m == nil {
return nil
} else {
return m.answeredQuestion
}
}
// GetDisplayValue gets the displayValue property value. The display value of the answer. Required.
func (m *AccessPackageAnswer) GetDisplayValue()(*string) {
if m == nil {
return nil
} else {
return m.displayValue
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *AccessPackageAnswer) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))
res["answeredQuestion"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateAccessPackageQuestionFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetAnsweredQuestion(val.(AccessPackageQuestionable))
}
return nil
}
res["displayValue"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetDisplayValue(val)
}
return nil
}
return res
}
// Serialize serializes information the current object
func (m *AccessPackageAnswer) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
{
err := writer.WriteObjectValue("answeredQuestion", m.GetAnsweredQuestion())
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("displayValue", m.GetDisplayValue())
if err != nil {
return err
}
}
{
err := writer.WriteAdditionalData(m.GetAdditionalData())
if err != nil {
return err
}
}
return nil
}
// SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *AccessPackageAnswer) SetAdditionalData(value map[string]interface{})() {
if m != nil {
m.additionalData = value
}
}
// SetAnsweredQuestion sets the answeredQuestion property value. The question the answer is for. Required and Read-only.
func (m *AccessPackageAnswer) SetAnsweredQuestion(value AccessPackageQuestionable)() {
if m != nil {
m.answeredQuestion = value
}
}
// SetDisplayValue sets the displayValue property value. The display value of the answer. Required.
func (m *AccessPackageAnswer) SetDisplayValue(value *string)() {
if m != nil {
m.displayValue = value
}
} | models/access_package_answer.go | 0.637369 | 0.421373 | access_package_answer.go | starcoder |
package testdata
// GetInvoiceResponse example
const GetInvoiceResponse = `{
"resource": "invoice",
"id": "inv_xBEbP9rvAq",
"reference": "2016.10000",
"vatNumber": "NL001234567B01",
"status": "open",
"issuedAt": "2016-08-31",
"dueAt": "2016-09-14",
"netAmount": {
"value": "45.00",
"currency": "EUR"
},
"vatAmount": {
"value": "9.45",
"currency": "EUR"
},
"grossAmount": {
"value": "54.45",
"currency": "EUR"
},
"lines":[
{
"period": "2016-09",
"description": "iDEAL transactiekosten",
"count": 100,
"vatPercentage": 21,
"amount": {
"value": "45.00",
"currency": "EUR"
}
}
],
"_links": {
"self": {
"href": "https://api.mollie.com/v2/invoices/inv_xBEbP9rvAq",
"type": "application/hal+json"
},
"pdf": {
"href": "https://www.mollie.com/merchant/download/invoice/xBEbP9rvAq/2ab44d60b35b1d06090bba955fa2c602",
"type": "application/pdf",
"expiresAt": "2018-11-09T14:10:36+00:00"
}
}
}`
// ListInvoicesResponse example
const ListInvoicesResponse = `{
"count": 5,
"_embedded": {
"invoices": [
{
"resource": "invoice",
"id": "inv_xBEbP9rvAq",
"reference": "2016.10000",
"vatNumber": "NL001234567B01",
"status": "open",
"issuedAt": "2016-08-31",
"dueAt": "2016-09-14",
"netAmount": {
"value": "45.00",
"currency": "EUR"
},
"vatAmount": {
"value": "9.45",
"currency": "EUR"
},
"grossAmount": {
"value": "54.45",
"currency": "EUR"
},
"lines":[
{
"period": "2016-09",
"description": "iDEAL transactiekosten",
"count": 100,
"vatPercentage": 21,
"amount": {
"value": "45.00",
"currency": "EUR"
}
}
],
"_links": {
"self": {
"href": "https://api.mollie.com/v2/invoices/inv_xBEbP9rvAq",
"type": "application/hal+json"
},
"pdf": {
"href": "https://www.mollie.com/merchant/download/invoice/xBEbP9rvAq/2ab44d60b35955fa2c602",
"type": "application/pdf",
"expiresAt": "2018-11-09T14:10:36+00:00"
}
}
}
]
},
"_links": {
"self": {
"href": "https://api.mollie.nl/v2/invoices?limit=5",
"type": "application/hal+json"
},
"previous": null,
"next": {
"href": "https://api.mollie.nl/v2/invoices?from=inv_xBEbP9rvAq&limit=5",
"type": "application/hal+json"
},
"documentation": {
"href": "https://docs.mollie.com/reference/v2/invoices-api/list-invoices",
"type": "text/html"
}
}
}` | testdata/invoices.go | 0.78016 | 0.487429 | invoices.go | starcoder |
package dfs
import (
"fmt"
"sort"
"github.com/wangyoucao577/algorithms_practice/graph"
)
// StronglyConnectedComponent represent a strongly connected component,
// include all vertexs within
type StronglyConnectedComponent []graph.NodeID
// For Sort Interfaces
func (s StronglyConnectedComponent) Len() int { return len(s) }
func (s StronglyConnectedComponent) Less(i, j int) bool {
return s[i] < s[j]
}
func (s StronglyConnectedComponent) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// SplitToStronglyConnectedComponents to split the input directed graph
// to several strongly connected components
func SplitToStronglyConnectedComponents(g graph.Graph) ([]StronglyConnectedComponent, error) {
if !g.Directed() {
return nil, fmt.Errorf("It's not a directed graph")
}
firstDfs, err := NewDfsForest(g, StackBased)
if err != nil {
return nil, err
}
// sort nodes by increasing timestampF
sortedNodes, err := sortNodesByTimestampF(firstDfs.nodesAttr)
if err != nil {
return nil, err
}
transposedG, err := graph.Transpose(g, graph.NewAdjacencyListGraph) // calculate transposed graph of original graph
if err != nil {
return nil, err
}
// initialize for second DFS on transposed graph
secondDfs := &Dfs{0, []dfsTree{}, nodeAttrArray{}, edgeAttrArray{}}
secondDfs.initialize(transposedG)
secondRootIndicators := make([]bool, transposedG.NodeCount(), transposedG.NodeCount())
for i := len(sortedNodes) - 1; i >= 0; i-- { //second iteration by reverse order of topoSort
currNode := sortedNodes[i]
if secondDfs.nodesAttr[currNode].nodeColor == white {
secondDfs.forest = append(secondDfs.forest, dfsTree{currNode})
secondRootIndicators[currNode] = true
secondDfs.dfsStackBasedVisit(transposedG, currNode, nil)
}
}
// retrieve components split by root of forest
secondSortedNodes, err := sortNodesByTimestampF(secondDfs.nodesAttr)
if err != nil {
return nil, err
}
components := []StronglyConnectedComponent{}
scc := StronglyConnectedComponent{}
for _, v := range secondSortedNodes {
scc = append(scc, v)
// root will always have biggeest timestampF
// so the last node MUST be root, and will be append into components
if secondRootIndicators[v] {
components = append(components, scc)
scc = StronglyConnectedComponent{} //clear
}
}
return components, nil
}
// default increasing
func sortNodesByTimestampF(nodesAttr nodeAttrArray) ([]graph.NodeID, error) {
nodesCount := len(nodesAttr)
if nodesCount <= 0 {
return nil, fmt.Errorf("Empty nodes attr array")
}
timestampFArray := make(nodeWithTimestampFArray, 0, nodesCount) //reserve array
for k, v := range nodesAttr {
if v == nil {
return nil, fmt.Errorf("null pointer of node %v attr. dfs not exeucted?", k)
}
timestampFArray = append(timestampFArray, nodeWithTimestampF{k, v.timestampF})
}
sort.Sort(timestampFArray) //sort
//fmt.Println(timestampFArray)
sortedNodes := make([]graph.NodeID, 0, nodesCount) //reserve array
for _, v := range timestampFArray {
sortedNodes = append(sortedNodes, v.nodeID)
}
return sortedNodes, nil
}
type nodeWithTimestampF struct {
nodeID graph.NodeID
timestampF int
}
type nodeWithTimestampFArray []nodeWithTimestampF
func (n nodeWithTimestampFArray) Len() int { return len(n) }
func (n nodeWithTimestampFArray) Less(i, j int) bool {
return n[i].timestampF < n[j].timestampF
}
func (n nodeWithTimestampFArray) Swap(i, j int) {
n[i], n[j] = n[j], n[i]
} | dfs/strongly_connected_component.go | 0.725649 | 0.407392 | strongly_connected_component.go | starcoder |
package neighbor
import (
"sync/atomic"
)
// Defines the metrics of a Neighbor
type NeighborMetrics struct {
allTxsCount uint32
invalidTxsCount uint32
staleTxsCount uint32
randomTxsCount uint32
sentTxsCount uint32
newTxsCount uint32
droppedSendPacketsCount uint32
receivedMilestoneReqCount uint32
sentMilestoneReqCount uint32
}
// Returns the number of all transactions.
func (nm *NeighborMetrics) GetAllTransactionsCount() uint32 {
return atomic.LoadUint32(&nm.allTxsCount)
}
// Increments the all transactions count.
func (nm *NeighborMetrics) IncrAllTransactionsCount() uint32 {
return atomic.AddUint32(&nm.allTxsCount, 1)
}
// Gets the number of invalid transactions.
func (nm *NeighborMetrics) GetInvalidTransactionsCount() uint32 {
return atomic.LoadUint32(&nm.invalidTxsCount)
}
// Increments the invalid transaction count.
func (nm *NeighborMetrics) IncrInvalidTransactionsCount() uint32 {
return atomic.AddUint32(&nm.invalidTxsCount, 1)
}
// Gets the number of stale transactions.
func (nm *NeighborMetrics) GetStaleTransactionsCount() uint32 {
return atomic.LoadUint32(&nm.staleTxsCount)
}
// Gets the number of new transactions.
func (nm *NeighborMetrics) GetNewTransactionsCount() uint32 {
return atomic.LoadUint32(&nm.newTxsCount)
}
// Increments the new transactions count.
func (nm *NeighborMetrics) IncrNewTransactionsCount() uint32 {
return atomic.AddUint32(&nm.newTxsCount, 1)
}
// Gets the number of random transactions.
func (nm *NeighborMetrics) GetRandomTransactionRequestsCount() uint32 {
return atomic.LoadUint32(&nm.randomTxsCount)
}
// Increments the random transactions count.
func (nm *NeighborMetrics) IncrRandomTransactionRequestsCount() uint32 {
return atomic.AddUint32(&nm.randomTxsCount, 1)
}
// Gets the number of send transactions.
func (nm *NeighborMetrics) GetSentTransactionsCount() uint32 {
return atomic.LoadUint32(&nm.sentTxsCount)
}
// Increments the send transactions count.
func (nm *NeighborMetrics) IncrSentTransactionsCount() uint32 {
return atomic.AddUint32(&nm.sentTxsCount, 1)
}
// Gets the number of packets dropped from the neighbor's send queue.
func (nm *NeighborMetrics) GetDroppedSendPacketsCount() uint32 {
return atomic.LoadUint32(&nm.droppedSendPacketsCount)
}
// Increments the number of packets dropped from the neighbor's send queue.
func (nm *NeighborMetrics) IncrDroppedSendPacketsCount() uint32 {
return atomic.AddUint32(&nm.droppedSendPacketsCount, 1)
}
// Gets the number of sent milestone requests.
func (nm *NeighborMetrics) GetSentMilestoneRequestsCount() uint32 {
return atomic.LoadUint32(&nm.sentMilestoneReqCount)
}
// Increments the sent milestone requests count.
func (nm *NeighborMetrics) IncrSentMilestoneRequestsCount() uint32 {
return atomic.AddUint32(&nm.sentMilestoneReqCount, 1)
}
// Gets the number of received milestone requests.
func (nm *NeighborMetrics) GetReceivedMilestoneRequestsCount() uint32 {
return atomic.LoadUint32(&nm.receivedMilestoneReqCount)
}
// Increments the received milestone requests count.
func (nm *NeighborMetrics) IncrReceivedMilestoneRequestsCount() uint32 {
return atomic.AddUint32(&nm.receivedMilestoneReqCount, 1)
} | plugins/gossip/neighbor/neighborMetrics.go | 0.802052 | 0.430147 | neighborMetrics.go | starcoder |
package pacmaneffect
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// Pacman contains the slice
type Pacman struct {
slice interface{}
}
// Effect describes the transformation to apply to the slice
type Effect struct {
start, end, step string
effectType EffectType
}
// EffectType describes the possible types of effects to apply
type EffectType int
const (
// StartType describes an effect with only "start" parameter
StartType EffectType = iota
// StartEndType describes an effect with "start" and "end" parameter
StartEndType
// StartEndStepType describes an effect with "start", "end" and "step" parameter
StartEndStepType
)
// NewPacman creates a new Pacman instance containing the slice
func NewPacman(slice interface{}) (*Pacman, error) {
switch reflect.TypeOf(slice).Kind() {
case reflect.Slice:
return &Pacman{slice}, nil
default:
return nil, fmt.Errorf("Invalid slice: \"%s\" is not a slice", reflect.TypeOf(slice))
}
}
// NewEffect creates a new Effect instance
func NewEffect(effect string) Effect {
indexes := strings.Split(effect, ":")
start := indexes[0]
end := ""
step := ""
effectType := StartType
if len(indexes) >= 2 {
end = indexes[1]
effectType = StartEndType
if len(indexes) == 3 {
step = indexes[2]
effectType = StartEndStepType
}
}
return Effect{start, end, step, effectType}
}
/*
* Interface methods
*/
// Apply applies the effect to the slice
func (p Pacman) Apply(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingle(e, false)
case StartEndType:
return p.applyMultiple(e, false)
case StartEndStepType:
return p.applyMultiple(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnbounded applies the effect to the slice as if it is unbounded
func (p Pacman) ApplyUnbounded(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingle(e, true)
case StartEndType:
return p.applyMultiple(e, true)
case StartEndStepType:
return p.applyMultiple(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingle(e Effect, unbounded bool) (interface{}, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return nil, err
}
switch reflect.TypeOf(p.slice).Kind() {
case reflect.Slice:
s := reflect.ValueOf(p.slice)
l := s.Len()
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s.Index(k).Interface(), nil
}
return s.Index(l + k).Interface(), nil
default:
return nil, fmt.Errorf("Invalid slice: \"%s\" is not a slice", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultiple(e Effect, unbounded bool) (interface{}, error) {
switch reflect.TypeOf(p.slice).Kind() {
case reflect.Slice:
s := reflect.ValueOf(p.slice)
l := s.Len()
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySlice(p.slice, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Invalid slice: \"%s\" is not a slice", reflect.TypeOf(p.slice))
}
}
func applySlice(slice interface{}, start, end, step int, unbounded bool) interface{} {
sliceType := reflect.TypeOf(slice)
sliceValue := reflect.ValueOf(slice)
l := sliceValue.Len()
res := reflect.MakeSlice(sliceType, 0, 0)
if step == 0 {
return res.Interface()
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = reflect.Append(res, sliceValue.Index(l+k))
} else {
res = reflect.Append(res, sliceValue.Index(k))
}
}
}
return res.Interface()
}
/*
* String methods
*/
// ApplyString applies the effect to the string slice
func (p Pacman) ApplyString(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleString(e, false)
case StartEndType:
return p.applyMultipleString(e, false)
case StartEndStepType:
return p.applyMultipleString(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnboundedString applies the effect to the string slice as if it is unbounded
func (p Pacman) ApplyUnboundedString(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleString(e, true)
case StartEndType:
return p.applyMultipleString(e, true)
case StartEndStepType:
return p.applyMultipleString(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingleString(e Effect, unbounded bool) (string, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return "", err
}
switch p.slice.(type) {
case []string:
s := p.slice.([]string)
l := len(s)
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s[k], nil
}
return s[l+k], nil
default:
return "", fmt.Errorf("Not a []string slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultipleString(e Effect, unbounded bool) ([]string, error) {
switch p.slice.(type) {
case []string:
s := p.slice.([]string)
l := len(s)
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySliceString(s, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Not a []string slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func applySliceString(slice []string, start, end, step int, unbounded bool) []string {
l := len(slice)
res := []string{}
if step == 0 {
return res
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = append(res, slice[l+k])
} else {
res = append(res, slice[k])
}
}
}
return res
}
/*
* Int methods
*/
// ApplyInt applies the effect to the int slice
func (p Pacman) ApplyInt(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleInt(e, false)
case StartEndType:
return p.applyMultipleInt(e, false)
case StartEndStepType:
return p.applyMultipleInt(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnboundedInt applies the effect to the int slice as if it is unbounded
func (p Pacman) ApplyUnboundedInt(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleInt(e, true)
case StartEndType:
return p.applyMultipleInt(e, true)
case StartEndStepType:
return p.applyMultipleInt(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingleInt(e Effect, unbounded bool) (int, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return 0, err
}
switch p.slice.(type) {
case []int:
s := p.slice.([]int)
l := len(s)
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s[k], nil
}
return s[l+k], nil
default:
return 0, fmt.Errorf("Not a []int slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultipleInt(e Effect, unbounded bool) ([]int, error) {
switch p.slice.(type) {
case []int:
s := p.slice.([]int)
l := len(s)
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySliceInt(s, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Not a []int slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func applySliceInt(slice []int, start, end, step int, unbounded bool) []int {
l := len(slice)
res := []int{}
if step == 0 {
return res
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = append(res, slice[l+k])
} else {
res = append(res, slice[k])
}
}
}
return res
}
/*
* Uint methods
*/
// ApplyUint applies the effect to the uint slice
func (p Pacman) ApplyUint(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleUint(e, false)
case StartEndType:
return p.applyMultipleUint(e, false)
case StartEndStepType:
return p.applyMultipleUint(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnboundedUint applies the effect to the uint slice as if it is unbounded
func (p Pacman) ApplyUnboundedUint(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleUint(e, true)
case StartEndType:
return p.applyMultipleUint(e, true)
case StartEndStepType:
return p.applyMultipleUint(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingleUint(e Effect, unbounded bool) (uint, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return 0, err
}
switch p.slice.(type) {
case []uint:
s := p.slice.([]uint)
l := len(s)
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s[k], nil
}
return s[l+k], nil
default:
return 0, fmt.Errorf("Not a []uint slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultipleUint(e Effect, unbounded bool) ([]uint, error) {
switch p.slice.(type) {
case []uint:
s := p.slice.([]uint)
l := len(s)
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySliceUint(s, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Not a []uint slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func applySliceUint(slice []uint, start, end, step int, unbounded bool) []uint {
l := len(slice)
res := []uint{}
if step == 0 {
return res
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = append(res, slice[l+k])
} else {
res = append(res, slice[k])
}
}
}
return res
}
/*
* Bool methods
*/
// ApplyBool applies the effect to the bool slice
func (p Pacman) ApplyBool(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleBool(e, false)
case StartEndType:
return p.applyMultipleBool(e, false)
case StartEndStepType:
return p.applyMultipleBool(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnboundedBool applies the effect to the bool slice as if it is unbounded
func (p Pacman) ApplyUnboundedBool(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleBool(e, true)
case StartEndType:
return p.applyMultipleBool(e, true)
case StartEndStepType:
return p.applyMultipleBool(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingleBool(e Effect, unbounded bool) (bool, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return false, err
}
switch p.slice.(type) {
case []bool:
s := p.slice.([]bool)
l := len(s)
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s[k], nil
}
return s[l+k], nil
default:
return false, fmt.Errorf("Not a []bool slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultipleBool(e Effect, unbounded bool) ([]bool, error) {
switch p.slice.(type) {
case []bool:
s := p.slice.([]bool)
l := len(s)
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySliceBool(s, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Not a []bool slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func applySliceBool(slice []bool, start, end, step int, unbounded bool) []bool {
l := len(slice)
res := []bool{}
if step == 0 {
return res
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = append(res, slice[l+k])
} else {
res = append(res, slice[k])
}
}
}
return res
}
/*
* Byte methods
*/
// ApplyByte applies the effect to the byte slice
func (p Pacman) ApplyByte(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleByte(e, false)
case StartEndType:
return p.applyMultipleByte(e, false)
case StartEndStepType:
return p.applyMultipleByte(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnboundedByte applies the effect to the byte slice as if it is unbounded
func (p Pacman) ApplyUnboundedByte(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleByte(e, true)
case StartEndType:
return p.applyMultipleByte(e, true)
case StartEndStepType:
return p.applyMultipleByte(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingleByte(e Effect, unbounded bool) (byte, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return 0, err
}
switch p.slice.(type) {
case []byte:
s := p.slice.([]byte)
l := len(s)
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s[k], nil
}
return s[l+k], nil
default:
return 0, fmt.Errorf("Not a []byte slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultipleByte(e Effect, unbounded bool) ([]byte, error) {
switch p.slice.(type) {
case []byte:
s := p.slice.([]byte)
l := len(s)
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySliceByte(s, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Not a []byte slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func applySliceByte(slice []byte, start, end, step int, unbounded bool) []byte {
l := len(slice)
res := []byte{}
if step == 0 {
return res
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = append(res, slice[l+k])
} else {
res = append(res, slice[k])
}
}
}
return res
}
/*
* Rune methods
*/
// ApplyRune applies the effect to the rune slice
func (p Pacman) ApplyRune(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleRune(e, false)
case StartEndType:
return p.applyMultipleRune(e, false)
case StartEndStepType:
return p.applyMultipleRune(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnboundedRune applies the effect to the rune slice as if it is unbounded
func (p Pacman) ApplyUnboundedRune(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleRune(e, true)
case StartEndType:
return p.applyMultipleRune(e, true)
case StartEndStepType:
return p.applyMultipleRune(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingleRune(e Effect, unbounded bool) (rune, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return 0, err
}
switch p.slice.(type) {
case []rune:
s := p.slice.([]rune)
l := len(s)
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s[k], nil
}
return s[l+k], nil
default:
return 0, fmt.Errorf("Not a []rune slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultipleRune(e Effect, unbounded bool) ([]rune, error) {
switch p.slice.(type) {
case []rune:
s := p.slice.([]rune)
l := len(s)
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySliceRune(s, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Not a []rune slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func applySliceRune(slice []rune, start, end, step int, unbounded bool) []rune {
l := len(slice)
res := []rune{}
if step == 0 {
return res
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = append(res, slice[l+k])
} else {
res = append(res, slice[k])
}
}
}
return res
}
/*
* Float32 methods
*/
// ApplyFloat32 applies the effect to the float32 slice
func (p Pacman) ApplyFloat32(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleFloat32(e, false)
case StartEndType:
return p.applyMultipleFloat32(e, false)
case StartEndStepType:
return p.applyMultipleFloat32(e, false)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
// ApplyUnboundedFloat32 applies the effect to the float32 slice as if it is unbounded
func (p Pacman) ApplyUnboundedFloat32(e Effect) (interface{}, error) {
switch e.effectType {
case StartType:
return p.applySingleFloat32(e, true)
case StartEndType:
return p.applyMultipleFloat32(e, true)
case StartEndStepType:
return p.applyMultipleFloat32(e, true)
default:
return nil, fmt.Errorf("Effect not valid: unknown type \"%s\"", reflect.TypeOf(e.effectType))
}
}
func (p Pacman) applySingleFloat32(e Effect, unbounded bool) (float32, error) {
start, err := strconv.Atoi(e.start)
if err != nil {
return 0, err
}
switch p.slice.(type) {
case []float32:
s := p.slice.([]float32)
l := len(s)
k := start
if unbounded {
k = k % l
}
if k >= 0 {
return s[k], nil
}
return s[l+k], nil
default:
return 0, fmt.Errorf("Not a []float32 slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func (p Pacman) applyMultipleFloat32(e Effect, unbounded bool) ([]float32, error) {
switch p.slice.(type) {
case []float32:
s := p.slice.([]float32)
l := len(s)
start, end, step, err := getLoopParams(e, l, unbounded)
if err != nil {
return nil, err
}
res := applySliceFloat32(s, start, end, step, unbounded)
return res, nil
default:
return nil, fmt.Errorf("Not a []float32 slice: \"%s\"", reflect.TypeOf(p.slice))
}
}
func applySliceFloat32(slice []float32, start, end, step int, unbounded bool) []float32 {
l := len(slice)
res := []float32{}
if step == 0 {
return res
}
cond := getLoopCondition(end, step)
for i := start; cond(i); i = i + step {
if unbounded || (i >= 0 && i < l) {
k := i % l
if k < 0 {
res = append(res, slice[l+k])
} else {
res = append(res, slice[k])
}
}
}
return res
}
/*
* Common methods
*/
func getLoopParams(e Effect, length int, unbounded bool) (int, int, int, error) {
step, _, err := getOrDefault(e.step, 1)
if err != nil {
return 0, 0, 0, err
}
var startDefault int
if step > 0 {
startDefault = 0
} else {
startDefault = length - 1
}
start, _, err := getOrDefault(e.start, startDefault)
if err != nil {
return 0, 0, 0, err
}
var endDefault int
if step > 0 {
endDefault = length
} else {
endDefault = -1
}
end, isEndDef, err := getOrDefault(e.end, endDefault)
if err != nil {
return 0, 0, 0, err
}
if !unbounded {
if start < 0 {
start = length + start
}
if !isEndDef && end < 0 {
end = length + end
}
}
return start, end, step, err
}
func getLoopCondition(lim, step int) func(int) bool {
if step < 0 {
return func(i int) bool {
return i > lim
}
}
return func(i int) bool {
return i < lim
}
}
func getOrDefault(s string, def int) (int, bool, error) {
if s == "" {
return def, true, nil
}
res, err := strconv.Atoi(s)
return res, false, err
} | pacman.go | 0.804214 | 0.613208 | pacman.go | starcoder |
package payload
import (
"github.com/ywangd/gobufrkit/bufr"
"github.com/ywangd/gobufrkit/deserialize/ast"
"github.com/pkg/errors"
"github.com/ywangd/gobufrkit/table"
)
// assocPair is a wrapper of a pair of data representing the number of bits
// and the associated field significance node.
type assocPair struct {
Nbits int
Node bufr.Node
}
// assocPairs provides methods for managing a slice of assocPair
type assocPairs struct {
pairs []*assocPair
}
func (p *assocPairs) Push(nbits int) {
p.pairs = append(p.pairs, &assocPair{Nbits: nbits})
}
func (p *assocPairs) Pop() {
p.pairs = p.pairs[:len(p.pairs)-1]
}
// SetNode is a no-op if there is no assocPair
func (p *assocPairs) SetNode(node bufr.Node) {
if len(p.pairs) > 0 {
p.pairs[len(p.pairs)-1].Node = node
}
}
func (p *assocPairs) Pairs() []*assocPair {
return p.pairs
}
// buildBlocks builds a block of replicated nodes
func buildBlock(v *DesVisitor, members []ast.Node) error {
v.treeBuilder.Push(bufr.NewBlock())
defer v.treeBuilder.Pop()
for _, m := range members { // loop of each replicated block
if err := m.Accept(v); err != nil {
return errors.Wrap(err, "cannot process replicated block")
}
}
return nil
}
// buildAssocNodes builds a slice of nodes that represents the list of associated field node
func buildAssocNodes(v *DesVisitor, descriptor table.Descriptor) ([]bufr.Node, error) {
if descriptor.X() == 31 || len(v.assocPairs.Pairs()) == 0 {
return nil, nil
}
nodes := []bufr.Node{}
for _, p := range v.assocPairs.Pairs() {
info := &bufr.PackingInfo{Unit: table.NONNEG_CODE, Nbits: p.Nbits}
node, err := buildValuedNodeWithInfo(v, &table.DecorateDescriptor{
Descriptor: descriptor, Initial: 'A', Name: "ASSOCIATED FIELD"}, info)
if err != nil {
return nil, errors.Wrap(err, "cannot build associated field node")
}
node.AddMember(p.Node)
nodes = append(nodes, node)
}
return nodes, nil
}
// buildValuedNode builds a ValuedNode for the given descriptor.
// The packing info is calculated for the given descriptor.
// It calls the helper buildValueNodeWithInfo to do the actual building work.
func buildValuedNode(v *DesVisitor, descriptor table.Descriptor) (*bufr.ValuedNode, error) {
info, err := calcPackingInfo(v, descriptor)
if err != nil {
return nil, errors.Wrap(err, "cannot calculate packing info")
}
return buildValuedNodeWithInfo(v, descriptor, info)
}
// buildValueNodeWithInfo unpack value(s) of the given descriptor, assemble the ValuedNode
// and also call treeBuilder and cellsBuilder to add the node and value(s).
func buildValuedNodeWithInfo(v *DesVisitor, descriptor table.Descriptor, info *bufr.PackingInfo) (*bufr.ValuedNode, error) {
val, err := v.unpacker.Unpack(info)
if err != nil {
return nil, errors.Wrap(err, "cannot unpack value")
}
node := &bufr.ValuedNode{Descriptor: descriptor, PackingInfo: info}
v.treeBuilder.Add(node)
v.cellsBuilder.Add(node, val)
return node, nil
}
// buildZeroNode adds a zero valued node if in compatible mode
func buildZeroNode(v *DesVisitor, descriptor table.Descriptor) error {
if v.config.Compatible {
info := &bufr.PackingInfo{Unit: table.NONNEG_CODE, Nbits: 0}
_, err := buildValuedNodeWithInfo(v, descriptor, info)
return err
}
v.treeBuilder.Add(&bufr.ValuelessNode{Descriptor: descriptor})
return nil
} | deserialize/payload/build.go | 0.723602 | 0.517205 | build.go | starcoder |
package ecdsa
// Copyright 2010 The Go Authors. All rights reserved.
// Copyright 2011 ThePiachu. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bitelliptic implements several Koblitz elliptic curves over prime
// fields.
// This package operates, internally, on Jacobian coordinates. For a given
// (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1)
// where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole
// calculation can be performed within the transform (as in ScalarMult and
// ScalarBaseMult). But even for Add and Double, it's faster to apply and
// reverse the transform than to operate in affine coordinates.
import (
"io"
"math/big"
"sync"
)
// A BitCurve represents a Koblitz Curve with a=0.
// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html
type BitCurve struct {
P *big.Int // the order of the underlying field
N *big.Int // the order of the base point
B *big.Int // the constant of the BitCurve equation
Gx, Gy *big.Int // (x,y) of the base point
BitSize int // the size of the underlying field
}
// IsOnBitCurve returns true if the given (x,y) lies on the BitCurve.
func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool {
// y² = x³ + b
y2 := new(big.Int).Mul(y, y) //y²
y2.Mod(y2, BitCurve.P) //y²%P
x3 := new(big.Int).Mul(x, x) //x²
x3.Mul(x3, x) //x³
x3.Add(x3, BitCurve.B) //x³+B
x3.Mod(x3, BitCurve.P) //(x³+B)%P
return x3.Cmp(y2) == 0
}
//TODO: double check if the function is okay
// affineFromJacobian reverses the Jacobian transform. See the comment at the
// top of the file.
func (BitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
zinv := new(big.Int).ModInverse(z, BitCurve.P)
zinvsq := new(big.Int).Mul(zinv, zinv)
xOut = new(big.Int).Mul(x, zinvsq)
xOut.Mod(xOut, BitCurve.P)
zinvsq.Mul(zinvsq, zinv)
yOut = new(big.Int).Mul(y, zinvsq)
yOut.Mod(yOut, BitCurve.P)
return
}
// Add returns the sum of (x1,y1) and (x2,y2)
func (BitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
z := new(big.Int).SetInt64(1)
return BitCurve.affineFromJacobian(BitCurve.addJacobian(x1, y1, z, x2, y2, z))
}
// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and
// (x2, y2, z2) and returns their sum, also in Jacobian form.
func (BitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
z1z1 := new(big.Int).Mul(z1, z1)
z1z1.Mod(z1z1, BitCurve.P)
z2z2 := new(big.Int).Mul(z2, z2)
z2z2.Mod(z2z2, BitCurve.P)
u1 := new(big.Int).Mul(x1, z2z2)
u1.Mod(u1, BitCurve.P)
u2 := new(big.Int).Mul(x2, z1z1)
u2.Mod(u2, BitCurve.P)
h := new(big.Int).Sub(u2, u1)
if h.Sign() == -1 {
h.Add(h, BitCurve.P)
}
i := new(big.Int).Lsh(h, 1)
i.Mul(i, i)
j := new(big.Int).Mul(h, i)
s1 := new(big.Int).Mul(y1, z2)
s1.Mul(s1, z2z2)
s1.Mod(s1, BitCurve.P)
s2 := new(big.Int).Mul(y2, z1)
s2.Mul(s2, z1z1)
s2.Mod(s2, BitCurve.P)
r := new(big.Int).Sub(s2, s1)
if r.Sign() == -1 {
r.Add(r, BitCurve.P)
}
r.Lsh(r, 1)
v := new(big.Int).Mul(u1, i)
x3 := new(big.Int).Set(r)
x3.Mul(x3, x3)
x3.Sub(x3, j)
x3.Sub(x3, v)
x3.Sub(x3, v)
x3.Mod(x3, BitCurve.P)
y3 := new(big.Int).Set(r)
v.Sub(v, x3)
y3.Mul(y3, v)
s1.Mul(s1, j)
s1.Lsh(s1, 1)
y3.Sub(y3, s1)
y3.Mod(y3, BitCurve.P)
z3 := new(big.Int).Add(z1, z2)
z3.Mul(z3, z3)
z3.Sub(z3, z1z1)
if z3.Sign() == -1 {
z3.Add(z3, BitCurve.P)
}
z3.Sub(z3, z2z2)
if z3.Sign() == -1 {
z3.Add(z3, BitCurve.P)
}
z3.Mul(z3, h)
z3.Mod(z3, BitCurve.P)
return x3, y3, z3
}
// Double returns 2*(x,y)
func (BitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
z1 := new(big.Int).SetInt64(1)
return BitCurve.affineFromJacobian(BitCurve.doubleJacobian(x1, y1, z1))
}
// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
// returns its double, also in Jacobian form.
func (BitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
a := new(big.Int).Mul(x, x) //X1²
b := new(big.Int).Mul(y, y) //Y1²
c := new(big.Int).Mul(b, b) //B²
d := new(big.Int).Add(x, b) //X1+B
d.Mul(d, d) //(X1+B)²
d.Sub(d, a) //(X1+B)²-A
d.Sub(d, c) //(X1+B)²-A-C
d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C)
e := new(big.Int).Mul(big.NewInt(3), a) //3*A
f := new(big.Int).Mul(e, e) //E²
x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
x3.Sub(f, x3) //F-2*D
x3.Mod(x3, BitCurve.P)
y3 := new(big.Int).Sub(d, x3) //D-X3
y3.Mul(e, y3) //E*(D-X3)
y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
y3.Mod(y3, BitCurve.P)
z3 := new(big.Int).Mul(y, z) //Y1*Z1
z3.Mul(big.NewInt(2), z3) //3*Y1*Z1
z3.Mod(z3, BitCurve.P)
return x3, y3, z3
}
//TODO: double check if it is okay
// ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
func (BitCurve *BitCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) {
// We have a slight problem in that the identity of the group (the
// point at infinity) cannot be represented in (x, y) form on a finite
// machine. Thus the standard add/double algorithm has to be tweaked
// slightly: our initial state is not the identity, but x, and we
// ignore the first true bit in |k|. If we don't find any true bits in
// |k|, then we return nil, nil, because we cannot return the identity
// element.
Bz := new(big.Int).SetInt64(1)
x := Bx
y := By
z := Bz
seenFirstTrue := false
for _, byte := range k {
for bitNum := 0; bitNum < 8; bitNum++ {
if seenFirstTrue {
x, y, z = BitCurve.doubleJacobian(x, y, z)
}
if byte&0x80 == 0x80 {
if !seenFirstTrue {
seenFirstTrue = true
} else {
x, y, z = BitCurve.addJacobian(Bx, By, Bz, x, y, z)
}
}
byte <<= 1
}
}
if !seenFirstTrue {
return nil, nil
}
return BitCurve.affineFromJacobian(x, y, z)
}
// ScalarBaseMult returns k*G, where G is the base point of the group and k is
// an integer in big-endian form.
func (BitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {
return BitCurve.ScalarMult(BitCurve.Gx, BitCurve.Gy, k)
}
var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f}
//TODO: double check if it is okay
// GenerateKey returns a public/private key pair. The private key is generated
// using the given reader, which must return random data.
func (BitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) {
byteLen := (BitCurve.BitSize + 7) >> 3
priv = make([]byte, byteLen)
for x == nil {
_, err = io.ReadFull(rand, priv)
if err != nil {
return
}
// We have to mask off any excess bits in the case that the size of the
// underlying field is not a whole number of bytes.
priv[0] &= mask[BitCurve.BitSize%8]
// This is because, in tests, rand will return all zeros and we don't
// want to get the point at infinity and loop forever.
priv[1] ^= 0x42
x, y = BitCurve.ScalarBaseMult(priv)
}
return
}
// Marshal converts a point into the form specified in section 4.3.6 of ANSI
// X9.62.
func (BitCurve *BitCurve) Marshal(x, y *big.Int) []byte {
byteLen := (BitCurve.BitSize + 7) >> 3
ret := make([]byte, 1+2*byteLen)
ret[0] = 4 // uncompressed point
xBytes := x.Bytes()
copy(ret[1+byteLen-len(xBytes):], xBytes)
yBytes := y.Bytes()
copy(ret[1+2*byteLen-len(yBytes):], yBytes)
return ret
}
// Unmarshal converts a point, serialised by Marshal, into an x, y pair. On
// error, x = nil.
func (BitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) {
byteLen := (BitCurve.BitSize + 7) >> 3
if len(data) != 1+2*byteLen {
return
}
if data[0] != 4 { // uncompressed form
return
}
x = new(big.Int).SetBytes(data[1 : 1+byteLen])
y = new(big.Int).SetBytes(data[1+byteLen:])
return
}
//curve parameters taken from:
//http://www.secg.org/collateral/sec2_final.pdf
var initonce sync.Once
var secp160k1 *BitCurve
var secp192k1 *BitCurve
var secp224k1 *BitCurve
var secp256k1 *BitCurve
func initAll() {
initS160()
initS192()
initS224()
initS256()
}
func initS160() {
// See SEC 2 section 2.4.1
secp160k1 = new(BitCurve)
secp160k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", 16)
secp160k1.N, _ = new(big.Int).SetString("0100000000000000000001B8FA16DFAB9ACA16B6B3", 16)
secp160k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000007", 16)
secp160k1.Gx, _ = new(big.Int).SetString("3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", 16)
secp160k1.Gy, _ = new(big.Int).SetString("938CF935318FDCED6BC28286531733C3F03C4FEE", 16)
secp160k1.BitSize = 160
}
func initS192() {
// See SEC 2 section 2.5.1
secp192k1 = new(BitCurve)
secp192k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", 16)
secp192k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", 16)
secp192k1.B, _ = new(big.Int).SetString("000000000000000000000000000000000000000000000003", 16)
secp192k1.Gx, _ = new(big.Int).SetString("DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", 16)
secp192k1.Gy, _ = new(big.Int).SetString("9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", 16)
secp192k1.BitSize = 192
}
func initS224() {
// See SEC 2 section 2.6.1
secp224k1 = new(BitCurve)
secp224k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", 16)
secp224k1.N, _ = new(big.Int).SetString("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7", 16)
secp224k1.B, _ = new(big.Int).SetString("00000000000000000000000000000000000000000000000000000005", 16)
secp224k1.Gx, _ = new(big.Int).SetString("A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", 16)
secp224k1.Gy, _ = new(big.Int).SetString("7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", 16)
secp224k1.BitSize = 224
}
func initS256() {
// See SEC 2 section 2.7.1
secp256k1 = new(BitCurve)
secp256k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
secp256k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
secp256k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
secp256k1.Gx, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
secp256k1.Gy, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
secp256k1.BitSize = 256
}
// S160 returns a BitCurve which implements secp160k1 (see SEC 2 section 2.4.1)
func S160() *BitCurve {
initonce.Do(initAll)
return secp160k1
}
// S192 returns a BitCurve which implements secp192k1 (see SEC 2 section 2.5.1)
func S192() *BitCurve {
initonce.Do(initAll)
return secp192k1
}
// S224 returns a BitCurve which implements secp224k1 (see SEC 2 section 2.6.1)
func S224() *BitCurve {
initonce.Do(initAll)
return secp224k1
}
// S256 returns a BitCurve which implements secp256k1 (see SEC 2 section 2.7.1)
func S256() *BitCurve {
initonce.Do(initAll)
return secp256k1
} | utils/ecdsa/bitelliptic.go | 0.747247 | 0.645455 | bitelliptic.go | starcoder |
package root
import (
"github.com/MakeNowJust/heredoc"
"github.com/spf13/cobra"
)
var HelpTopics = map[string]map[string]string{
"mintty": {
"short": "Information about using gh with MinTTY",
"long": heredoc.Doc(`
MinTTY is the terminal emulator that comes by default with Git
for Windows. It has known issues with gh's ability to prompt a
user for input.
There are a few workarounds to make gh work with MinTTY:
- Reinstall Git for Windows, checking "Enable experimental support for pseudo consoles".
- Use a different terminal emulator with Git for Windows like Windows Terminal.
You can run "C:\Program Files\Git\bin\bash.exe" from any terminal emulator to continue
using all of the tooling in Git For Windows without MinTTY.
- Prefix invocations of gh with winpty, eg: "winpty gh auth login".
NOTE: this can lead to some UI bugs.
`),
},
"environment": {
"short": "Environment variables that can be used with gh",
"long": heredoc.Doc(`
GH_TOKEN, GITHUB_TOKEN (in order of precedence): an authentication token for github.com
API requests. Setting this avoids being prompted to authenticate and takes precedence over
previously stored credentials.
GH_ENTERPRISE_TOKEN, GITHUB_ENTERPRISE_TOKEN (in order of precedence): an authentication
token for API requests to GitHub Enterprise. When setting this, also set GH_HOST.
GH_HOST: specify the GitHub hostname for commands that would otherwise assume the
"github.com" host when not in a context of an existing repository.
GH_REPO: specify the GitHub repository in the "[HOST/]OWNER/REPO" format for commands
that otherwise operate on a local repository.
GH_EDITOR, GIT_EDITOR, VISUAL, EDITOR (in order of precedence): the editor tool to use
for authoring text.
GH_BROWSER, BROWSER (in order of precedence): the web browser to use for opening links.
DEBUG: set to any value to enable verbose output to standard error. Include values "api"
or "oauth" to print detailed information about HTTP requests or authentication flow.
GH_PAGER, PAGER (in order of precedence): a terminal paging program to send standard output
to, e.g. "less".
GLAMOUR_STYLE: the style to use for rendering Markdown. See
https://github.com/charmbracelet/glamour#styles
NO_COLOR: set to any value to avoid printing ANSI escape sequences for color output.
CLICOLOR: set to "0" to disable printing ANSI colors in output.
CLICOLOR_FORCE: set to a value other than "0" to keep ANSI colors in output
even when the output is piped.
GH_FORCE_TTY: set to any value to force terminal-style output even when the output is
redirected. When the value is a number, it is interpreted as the number of columns
available in the viewport. When the value is a percentage, it will be applied against
the number of columns available in the current viewport.
GH_NO_UPDATE_NOTIFIER: set to any value to disable update notifications. By default, gh
checks for new releases once every 24 hours and displays an upgrade notice on standard
error if a newer version was found.
GH_CONFIG_DIR: the directory where gh will store configuration files. Default:
"$XDG_CONFIG_HOME/gh" or "$HOME/.config/gh".
`),
},
"reference": {
"short": "A comprehensive reference of all gh commands",
},
"formatting": {
"short": "Formatting options for JSON data exported from gh",
"long": heredoc.Docf(`
Some gh commands support exporting the data as JSON as an alternative to their usual
line-based plain text output. This is suitable for passing structured data to scripts.
The JSON output is enabled with the %[1]s--json%[1]s option, followed by the list of fields
to fetch. Use the flag without a value to get the list of available fields.
The %[1]s--jq%[1]s option accepts a query in jq syntax and will print only the resulting
values that match the query. This is equivalent to piping the output to %[1]sjq -r%[1]s,
but does not require the jq utility to be installed on the system. To learn more
about the query syntax, see: https://stedolan.github.io/jq/manual/v1.6/
With %[1]s--template%[1]s, the provided Go template is rendered using the JSON data as input.
For the syntax of Go templates, see: https://golang.org/pkg/text/template/
The following functions are available in templates:
- %[1]sautocolor%[1]s: like %[1]scolor%[1]s, but only emits color to terminals
- %[1]scolor <style> <input>%[1]s: colorize input using https://github.com/mgutz/ansi
- %[1]sjoin <sep> <list>%[1]s: joins values in the list using a separator
- %[1]spluck <field> <list>%[1]s: collects values of a field from all items in the input
- %[1]stablerow <fields>...%[1]s: aligns fields in output vertically as a table
- %[1]stablerender%[1]s: renders fields added by tablerow in place
- %[1]stimeago <time>%[1]s: renders a timestamp as relative to now
- %[1]stimefmt <format> <time>%[1]s: formats a timestamp using Go's Time.Format function
- %[1]struncate <length> <input>%[1]s: ensures input fits within length
EXAMPLES
# format issues as table
$ gh issue list --json number,title --template \
'{{range .}}{{tablerow (printf "#%%v" .number | autocolor "green") .title}}{{end}}'
# format a pull request using multiple tables with headers
$ gh pr view 3519 --json number,title,body,reviews,assignees --template \
'{{printf "#%%v" .number}} {{.title}}
{{.body}}
{{tablerow "ASSIGNEE" "NAME"}}{{range .assignees}}{{tablerow .login .name}}{{end}}{{tablerender}}
{{tablerow "REVIEWER" "STATE" "COMMENT"}}{{range .reviews}}{{tablerow .author.login .state .body}}{{end}}
'
`, "`"),
},
}
func NewHelpTopic(topic string) *cobra.Command {
cmd := &cobra.Command{
Use: topic,
Short: HelpTopics[topic]["short"],
Long: HelpTopics[topic]["long"],
Hidden: true,
Annotations: map[string]string{
"markdown:generate": "true",
"markdown:basename": "gh_help_" + topic,
},
}
cmd.SetHelpFunc(helpTopicHelpFunc)
cmd.SetUsageFunc(helpTopicUsageFunc)
return cmd
}
func helpTopicHelpFunc(command *cobra.Command, args []string) {
command.Print(command.Long)
}
func helpTopicUsageFunc(command *cobra.Command) error {
command.Printf("Usage: gh help %s", command.Use)
return nil
} | pkg/cmd/root/help_topic.go | 0.602179 | 0.40072 | help_topic.go | starcoder |
package sliceWrapper
const pointerTemplate = `{{range .Types}}
type {{.NameTitle}}Slice struct {
s []*{{.Name}}
}
func New{{.NameTitle}}Slice() *{{.NameTitle}}Slice {
return &{{.NameTitle}}Slice{}
}
func (v *{{.NameTitle}}Slice) Clear() {
v.s = v.s[:0]
}
func (v *{{.NameTitle}}Slice) Equal(rhs *{{.NameTitle}}Slice) bool {
if rhs == nil {
return false
}
if len(v.s) != len(rhs.s) {
return false
}
for i := range v.s {
if v.s[i] != rhs.s[i] {
return false
}
}
return true
}
func (v *{{.NameTitle}}Slice) MarshalJSON() ([]byte, error) {
return json.Marshal(v.s)
}
func (v *{{.NameTitle}}Slice) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &v.s)
}
func (v *{{.NameTitle}}Slice) Copy(rhs *{{.NameTitle}}Slice) {
v.s = make([]*{{.Name}}, len(rhs.s))
copy(v.s, rhs.s)
}
func (v *{{.NameTitle}}Slice) Clone() *{{.NameTitle}}Slice {
return &{{.NameTitle}}Slice{
s: v.s[:],
}
}
func (v *{{.NameTitle}}Slice) Index(rhs *{{.Name}}) int {
for i, lhs := range v.s {
if lhs == rhs {
return i
}
}
return -1
}
func (v *{{.NameTitle}}Slice) Append(n *{{.Name}}) {
v.s = append(v.s, n)
}
func (v *{{.NameTitle}}Slice) Insert(i int, n *{{.Name}}) {
if i < 0 || i > len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go error trying to insert at index %d\n", i)
return
}
v.s = append(v.s, nil)
copy(v.s[i+1:], v.s[i:])
v.s[i] = n
}
func (v *{{.NameTitle}}Slice) Remove(i int) {
if i < 0 || i >= len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go error trying to remove bad index %d\n", i)
return
}
copy(v.s[i:], v.s[i+1:])
v.s[len(v.s)-1] = nil
v.s = v.s[:len(v.s)-1]
}
func (v *{{.NameTitle}}Slice) Count() int {
return len(v.s)
}
func (v *{{.NameTitle}}Slice) At(i int) *{{.Name}} {
if i < 0 || i >= len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go invalid index %d\n", i)
}
return v.s[i]
}
func (v *{{.NameTitle}}Slice) GetItem(i int) Any {
if i < 0 || i >= len(v.s) {
fmt.Printf("Vapi::{{.Name}}Slice field_values.go invalid index %d\n", i)
}
return v.s[i]
}
func (v *{{.NameTitle}}Slice) OjectsSlice() []{{.Name}} {
res := make([]{{.Name}}, 0, len(v.s))
for _, i := range v.s {
if i == nil {
continue
}
res = append(res, *i)
}
return res
}
func New{{.NameTitle}}SliceWithObjects(objects []{{.Name}}) *{{.NameTitle}}Slice {
pSlice := make([]*{{.Name}}, 0, len(objects))
for _, i := range objects {
j := i
pSlice = append(pSlice, &j)
}
return &{{.NameTitle}}Slice{pSlice}
}
{{end}}` | sliceWrapper/pointerTemplate.go | 0.657209 | 0.484868 | pointerTemplate.go | starcoder |
package rfc2868
import (
"strconv"
"fbc/lib/go/radius"
)
const (
TunnelType_Type radius.Type = 64
TunnelMediumType_Type radius.Type = 65
TunnelClientEndpoint_Type radius.Type = 66
TunnelServerEndpoint_Type radius.Type = 67
TunnelPrivateGroupID_Type radius.Type = 81
TunnelAssignmentID_Type radius.Type = 82
TunnelPreference_Type radius.Type = 83
TunnelClientAuthID_Type radius.Type = 90
TunnelServerAuthID_Type radius.Type = 91
)
type TunnelType uint32
const (
TunnelType_Value_PPTP TunnelType = 1
TunnelType_Value_L2F TunnelType = 2
TunnelType_Value_L2TP TunnelType = 3
TunnelType_Value_ATMP TunnelType = 4
TunnelType_Value_VTP TunnelType = 5
TunnelType_Value_AH TunnelType = 6
TunnelType_Value_IP TunnelType = 7
TunnelType_Value_MINIP TunnelType = 8
TunnelType_Value_ESP TunnelType = 9
TunnelType_Value_GRE TunnelType = 10
TunnelType_Value_DVS TunnelType = 11
TunnelType_Value_IPInIP TunnelType = 12
)
var TunnelType_Strings = map[TunnelType]string{
TunnelType_Value_PPTP: "PPTP",
TunnelType_Value_L2F: "L2F",
TunnelType_Value_L2TP: "L2TP",
TunnelType_Value_ATMP: "ATMP",
TunnelType_Value_VTP: "VTP",
TunnelType_Value_AH: "AH",
TunnelType_Value_IP: "IP",
TunnelType_Value_MINIP: "MIN-IP",
TunnelType_Value_ESP: "ESP",
TunnelType_Value_GRE: "GRE",
TunnelType_Value_DVS: "DVS",
TunnelType_Value_IPInIP: "IP-in-IP",
}
func (a TunnelType) String() string {
if str, ok := TunnelType_Strings[a]; ok {
return str
}
return "TunnelType(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func TunnelType_Add(p *radius.Packet, tag byte, value TunnelType) (err error) {
a := radius.NewInteger(uint32(value))
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelType_Type, a)
return nil
}
func TunnelType_Get(p *radius.Packet) (tag byte, value TunnelType) {
tag, value, _ = TunnelType_Lookup(p)
return
}
func TunnelType_Gets(p *radius.Packet) (tags []byte, values []TunnelType, err error) {
var i uint32
var tag byte
for _, attr := range p.Attributes[TunnelType_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, TunnelType(i))
tags = append(tags, tag)
}
return
}
func TunnelType_Lookup(p *radius.Packet) (tag byte, value TunnelType, err error) {
a, ok := p.Lookup(TunnelType_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = TunnelType(i)
return
}
func TunnelType_Set(p *radius.Packet, tag byte, value TunnelType) (err error) {
a := radius.NewInteger(uint32(value))
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelType_Type, a)
return nil
}
type TunnelMediumType uint32
const (
TunnelMediumType_Value_IPv4 TunnelMediumType = 1
TunnelMediumType_Value_IPv6 TunnelMediumType = 2
TunnelMediumType_Value_NSAP TunnelMediumType = 3
TunnelMediumType_Value_HDLC TunnelMediumType = 4
TunnelMediumType_Value_BBN1822 TunnelMediumType = 5
TunnelMediumType_Value_IEEE802 TunnelMediumType = 6
TunnelMediumType_Value_E163 TunnelMediumType = 7
TunnelMediumType_Value_E164 TunnelMediumType = 8
TunnelMediumType_Value_F69 TunnelMediumType = 9
TunnelMediumType_Value_X121 TunnelMediumType = 10
TunnelMediumType_Value_IPX TunnelMediumType = 11
TunnelMediumType_Value_Appletalk TunnelMediumType = 12
TunnelMediumType_Value_DecNetIV TunnelMediumType = 13
TunnelMediumType_Value_BanyanVines TunnelMediumType = 14
TunnelMediumType_Value_E164NSAP TunnelMediumType = 15
)
var TunnelMediumType_Strings = map[TunnelMediumType]string{
TunnelMediumType_Value_IPv4: "IPv4",
TunnelMediumType_Value_IPv6: "IPv6",
TunnelMediumType_Value_NSAP: "NSAP",
TunnelMediumType_Value_HDLC: "HDLC",
TunnelMediumType_Value_BBN1822: "BBN-1822",
TunnelMediumType_Value_IEEE802: "IEEE-802",
TunnelMediumType_Value_E163: "E.163",
TunnelMediumType_Value_E164: "E.164",
TunnelMediumType_Value_F69: "F.69",
TunnelMediumType_Value_X121: "X.121",
TunnelMediumType_Value_IPX: "IPX",
TunnelMediumType_Value_Appletalk: "Appletalk",
TunnelMediumType_Value_DecNetIV: "DecNet-IV",
TunnelMediumType_Value_BanyanVines: "Banyan-Vines",
TunnelMediumType_Value_E164NSAP: "E.164-NSAP",
}
func (a TunnelMediumType) String() string {
if str, ok := TunnelMediumType_Strings[a]; ok {
return str
}
return "TunnelMediumType(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func TunnelMediumType_Add(p *radius.Packet, tag byte, value TunnelMediumType) (err error) {
a := radius.NewInteger(uint32(value))
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelMediumType_Type, a)
return nil
}
func TunnelMediumType_Get(p *radius.Packet) (tag byte, value TunnelMediumType) {
tag, value, _ = TunnelMediumType_Lookup(p)
return
}
func TunnelMediumType_Gets(p *radius.Packet) (tags []byte, values []TunnelMediumType, err error) {
var i uint32
var tag byte
for _, attr := range p.Attributes[TunnelMediumType_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, TunnelMediumType(i))
tags = append(tags, tag)
}
return
}
func TunnelMediumType_Lookup(p *radius.Packet) (tag byte, value TunnelMediumType, err error) {
a, ok := p.Lookup(TunnelMediumType_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = TunnelMediumType(i)
return
}
func TunnelMediumType_Set(p *radius.Packet, tag byte, value TunnelMediumType) (err error) {
a := radius.NewInteger(uint32(value))
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelMediumType_Type, a)
return nil
}
func TunnelClientEndpoint_Add(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelClientEndpoint_Type, a)
return nil
}
func TunnelClientEndpoint_AddString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelClientEndpoint_Type, a)
return nil
}
func TunnelClientEndpoint_Get(p *radius.Packet) (tag byte, value []byte) {
tag, value, _ = TunnelClientEndpoint_Lookup(p)
return
}
func TunnelClientEndpoint_GetString(p *radius.Packet) (tag byte, value string) {
var valueBytes []byte
tag, valueBytes = TunnelClientEndpoint_Get(p)
value = string(valueBytes)
return
}
func TunnelClientEndpoint_Gets(p *radius.Packet) (tags []byte, values [][]byte, err error) {
var i []byte
var tag byte
for _, attr := range p.Attributes[TunnelClientEndpoint_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelClientEndpoint_GetStrings(p *radius.Packet) (tags []byte, values []string, err error) {
var i string
var tag byte
for _, attr := range p.Attributes[TunnelClientEndpoint_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelClientEndpoint_Lookup(p *radius.Packet) (tag byte, value []byte, err error) {
a, ok := p.Lookup(TunnelClientEndpoint_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.Bytes(a)
return
}
func TunnelClientEndpoint_LookupString(p *radius.Packet) (tag byte, value string, err error) {
a, ok := p.Lookup(TunnelClientEndpoint_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.String(a)
return
}
func TunnelClientEndpoint_Set(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelClientEndpoint_Type, a)
return
}
func TunnelClientEndpoint_SetString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelClientEndpoint_Type, a)
return
}
func TunnelServerEndpoint_Add(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelServerEndpoint_Type, a)
return nil
}
func TunnelServerEndpoint_AddString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelServerEndpoint_Type, a)
return nil
}
func TunnelServerEndpoint_Get(p *radius.Packet) (tag byte, value []byte) {
tag, value, _ = TunnelServerEndpoint_Lookup(p)
return
}
func TunnelServerEndpoint_GetString(p *radius.Packet) (tag byte, value string) {
var valueBytes []byte
tag, valueBytes = TunnelServerEndpoint_Get(p)
value = string(valueBytes)
return
}
func TunnelServerEndpoint_Gets(p *radius.Packet) (tags []byte, values [][]byte, err error) {
var i []byte
var tag byte
for _, attr := range p.Attributes[TunnelServerEndpoint_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelServerEndpoint_GetStrings(p *radius.Packet) (tags []byte, values []string, err error) {
var i string
var tag byte
for _, attr := range p.Attributes[TunnelServerEndpoint_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelServerEndpoint_Lookup(p *radius.Packet) (tag byte, value []byte, err error) {
a, ok := p.Lookup(TunnelServerEndpoint_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.Bytes(a)
return
}
func TunnelServerEndpoint_LookupString(p *radius.Packet) (tag byte, value string, err error) {
a, ok := p.Lookup(TunnelServerEndpoint_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.String(a)
return
}
func TunnelServerEndpoint_Set(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelServerEndpoint_Type, a)
return
}
func TunnelServerEndpoint_SetString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelServerEndpoint_Type, a)
return
}
func TunnelPrivateGroupID_Add(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelPrivateGroupID_Type, a)
return nil
}
func TunnelPrivateGroupID_AddString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelPrivateGroupID_Type, a)
return nil
}
func TunnelPrivateGroupID_Get(p *radius.Packet) (tag byte, value []byte) {
tag, value, _ = TunnelPrivateGroupID_Lookup(p)
return
}
func TunnelPrivateGroupID_GetString(p *radius.Packet) (tag byte, value string) {
var valueBytes []byte
tag, valueBytes = TunnelPrivateGroupID_Get(p)
value = string(valueBytes)
return
}
func TunnelPrivateGroupID_Gets(p *radius.Packet) (tags []byte, values [][]byte, err error) {
var i []byte
var tag byte
for _, attr := range p.Attributes[TunnelPrivateGroupID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelPrivateGroupID_GetStrings(p *radius.Packet) (tags []byte, values []string, err error) {
var i string
var tag byte
for _, attr := range p.Attributes[TunnelPrivateGroupID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelPrivateGroupID_Lookup(p *radius.Packet) (tag byte, value []byte, err error) {
a, ok := p.Lookup(TunnelPrivateGroupID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.Bytes(a)
return
}
func TunnelPrivateGroupID_LookupString(p *radius.Packet) (tag byte, value string, err error) {
a, ok := p.Lookup(TunnelPrivateGroupID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.String(a)
return
}
func TunnelPrivateGroupID_Set(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelPrivateGroupID_Type, a)
return
}
func TunnelPrivateGroupID_SetString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelPrivateGroupID_Type, a)
return
}
func TunnelAssignmentID_Add(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelAssignmentID_Type, a)
return nil
}
func TunnelAssignmentID_AddString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelAssignmentID_Type, a)
return nil
}
func TunnelAssignmentID_Get(p *radius.Packet) (tag byte, value []byte) {
tag, value, _ = TunnelAssignmentID_Lookup(p)
return
}
func TunnelAssignmentID_GetString(p *radius.Packet) (tag byte, value string) {
var valueBytes []byte
tag, valueBytes = TunnelAssignmentID_Get(p)
value = string(valueBytes)
return
}
func TunnelAssignmentID_Gets(p *radius.Packet) (tags []byte, values [][]byte, err error) {
var i []byte
var tag byte
for _, attr := range p.Attributes[TunnelAssignmentID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelAssignmentID_GetStrings(p *radius.Packet) (tags []byte, values []string, err error) {
var i string
var tag byte
for _, attr := range p.Attributes[TunnelAssignmentID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelAssignmentID_Lookup(p *radius.Packet) (tag byte, value []byte, err error) {
a, ok := p.Lookup(TunnelAssignmentID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.Bytes(a)
return
}
func TunnelAssignmentID_LookupString(p *radius.Packet) (tag byte, value string, err error) {
a, ok := p.Lookup(TunnelAssignmentID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.String(a)
return
}
func TunnelAssignmentID_Set(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelAssignmentID_Type, a)
return
}
func TunnelAssignmentID_SetString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelAssignmentID_Type, a)
return
}
type TunnelPreference uint32
var TunnelPreference_Strings = map[TunnelPreference]string{}
func (a TunnelPreference) String() string {
if str, ok := TunnelPreference_Strings[a]; ok {
return str
}
return "TunnelPreference(" + strconv.FormatUint(uint64(a), 10) + ")"
}
func TunnelPreference_Add(p *radius.Packet, tag byte, value TunnelPreference) (err error) {
a := radius.NewInteger(uint32(value))
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelPreference_Type, a)
return nil
}
func TunnelPreference_Get(p *radius.Packet) (tag byte, value TunnelPreference) {
tag, value, _ = TunnelPreference_Lookup(p)
return
}
func TunnelPreference_Gets(p *radius.Packet) (tags []byte, values []TunnelPreference, err error) {
var i uint32
var tag byte
for _, attr := range p.Attributes[TunnelPreference_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i, err = radius.Integer(attr)
if err != nil {
return
}
values = append(values, TunnelPreference(i))
tags = append(tags, tag)
}
return
}
func TunnelPreference_Lookup(p *radius.Packet) (tag byte, value TunnelPreference, err error) {
a, ok := p.Lookup(TunnelPreference_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
var i uint32
i, err = radius.Integer(a)
if err != nil {
return
}
value = TunnelPreference(i)
return
}
func TunnelPreference_Set(p *radius.Packet, tag byte, value TunnelPreference) (err error) {
a := radius.NewInteger(uint32(value))
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelPreference_Type, a)
return nil
}
func TunnelClientAuthID_Add(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelClientAuthID_Type, a)
return nil
}
func TunnelClientAuthID_AddString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelClientAuthID_Type, a)
return nil
}
func TunnelClientAuthID_Get(p *radius.Packet) (tag byte, value []byte) {
tag, value, _ = TunnelClientAuthID_Lookup(p)
return
}
func TunnelClientAuthID_GetString(p *radius.Packet) (tag byte, value string) {
var valueBytes []byte
tag, valueBytes = TunnelClientAuthID_Get(p)
value = string(valueBytes)
return
}
func TunnelClientAuthID_Gets(p *radius.Packet) (tags []byte, values [][]byte, err error) {
var i []byte
var tag byte
for _, attr := range p.Attributes[TunnelClientAuthID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelClientAuthID_GetStrings(p *radius.Packet) (tags []byte, values []string, err error) {
var i string
var tag byte
for _, attr := range p.Attributes[TunnelClientAuthID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelClientAuthID_Lookup(p *radius.Packet) (tag byte, value []byte, err error) {
a, ok := p.Lookup(TunnelClientAuthID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.Bytes(a)
return
}
func TunnelClientAuthID_LookupString(p *radius.Packet) (tag byte, value string, err error) {
a, ok := p.Lookup(TunnelClientAuthID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.String(a)
return
}
func TunnelClientAuthID_Set(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelClientAuthID_Type, a)
return
}
func TunnelClientAuthID_SetString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelClientAuthID_Type, a)
return
}
func TunnelServerAuthID_Add(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelServerAuthID_Type, a)
return nil
}
func TunnelServerAuthID_AddString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Add(TunnelServerAuthID_Type, a)
return nil
}
func TunnelServerAuthID_Get(p *radius.Packet) (tag byte, value []byte) {
tag, value, _ = TunnelServerAuthID_Lookup(p)
return
}
func TunnelServerAuthID_GetString(p *radius.Packet) (tag byte, value string) {
var valueBytes []byte
tag, valueBytes = TunnelServerAuthID_Get(p)
value = string(valueBytes)
return
}
func TunnelServerAuthID_Gets(p *radius.Packet) (tags []byte, values [][]byte, err error) {
var i []byte
var tag byte
for _, attr := range p.Attributes[TunnelServerAuthID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.Bytes(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelServerAuthID_GetStrings(p *radius.Packet) (tags []byte, values []string, err error) {
var i string
var tag byte
for _, attr := range p.Attributes[TunnelServerAuthID_Type] {
tag, attr, err = radius.Tag(attr)
if err != nil {
return
}
i = radius.String(attr)
if err != nil {
return
}
values = append(values, i)
tags = append(tags, tag)
}
return
}
func TunnelServerAuthID_Lookup(p *radius.Packet) (tag byte, value []byte, err error) {
a, ok := p.Lookup(TunnelServerAuthID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.Bytes(a)
return
}
func TunnelServerAuthID_LookupString(p *radius.Packet) (tag byte, value string, err error) {
a, ok := p.Lookup(TunnelServerAuthID_Type)
if !ok {
err = radius.ErrNoAttribute
return
}
tag, a, err = radius.Tag(a)
if err != nil {
return
}
value = radius.String(a)
return
}
func TunnelServerAuthID_Set(p *radius.Packet, tag byte, value []byte) (err error) {
var a radius.Attribute
a, err = radius.NewBytes(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelServerAuthID_Type, a)
return
}
func TunnelServerAuthID_SetString(p *radius.Packet, tag byte, value string) (err error) {
var a radius.Attribute
a, err = radius.NewString(value)
if err != nil {
return
}
a, err = radius.NewTag(tag, a)
if err != nil {
return
}
p.Set(TunnelServerAuthID_Type, a)
return
} | feg/radius/lib/go/radius/rfc2868/generated.go | 0.572484 | 0.416263 | generated.go | starcoder |
package geometry
import (
"math"
"github.com/tab58/v1/spatial/pkg/numeric"
"gonum.org/v1/gonum/blas/blas64"
)
// // MatrixReader is a read-only interface for a matrix.
// type MatrixReader interface {
// Rows() uint
// Cols() uint
// ElementAt(i, j uint) (float64, error)
// ToBlas64General() blas64.General
// }
// // MatrixWriter is a write-only interface for a matrix.
// type MatrixWriter interface {
// SetElementAt(i, j uint, value float64) error
// }
// Matrix2D is a row-major representation of a 2x2 matrix.
type Matrix2D struct {
elements [4]float64
}
// Rows returns the number of rows in the matrix.
func (m *Matrix2D) Rows() uint { return 2 }
// Cols returns the number of columns in the matrix.
func (m *Matrix2D) Cols() uint { return 2 }
// Clone returns a deep copy of the matrix.
func (m *Matrix2D) Clone() *Matrix2D {
a := m.elements
tmp := [4]float64{a[0], a[1], a[2], a[3]}
return &Matrix2D{
elements: tmp,
}
}
// Copy copies the elements of the matrix to this one.
func (m *Matrix2D) Copy(mat *Matrix2D) {
a := mat.elements
m.elements[0] = a[0]
m.elements[1] = a[1]
m.elements[2] = a[2]
m.elements[3] = a[3]
}
// Identity sets the matrix to the identity matrix.
func (m *Matrix2D) Identity() {
// ignoring error since all elements will not overflow
m.SetElements(1, 0, 0, 1)
}
// Scale multiplies the elements of the matrix by the given scalar.
func (m *Matrix2D) Scale(z float64) error {
out := [4]float64{}
for i, v := range m.elements {
val := v * z
if numeric.IsOverflow(val) {
return numeric.ErrOverflow
}
out[i] = val
}
m.elements = out
return nil
}
// ElementAt returns the value of the element at the given indices.
func (m *Matrix2D) ElementAt(i, j uint) (float64, error) {
cols := m.Cols()
if i <= m.Rows() || j <= cols {
return 0, numeric.ErrMatrixOutOfRange
}
return m.elements[i*cols+j], nil
}
// ToBlas64General returns a blas64.General with the same values as the matrix.
func (m *Matrix2D) ToBlas64General() blas64.General {
data := make([]float64, len(m.elements))
copy(data, m.elements[:])
return blas64.General{
Rows: int(m.Rows()),
Cols: int(m.Cols()),
Stride: int(m.Cols()),
Data: data,
}
}
// SetElementAt sets the value of the element at the given indices.
func (m *Matrix2D) SetElementAt(i, j uint, value float64) error {
cols := m.Cols()
if i <= m.Rows() || j <= cols {
return numeric.ErrMatrixOutOfRange
}
m.elements[i*cols+j] = value
return nil
}
// SetElements sets the elements in the matrix.
func (m *Matrix2D) SetElements(m00, m01, m10, m11 float64) error {
if numeric.AreAnyOverflow(m00, m01, m10, m11) {
return numeric.ErrOverflow
}
m.elements[0] = m00
m.elements[1] = m01
m.elements[2] = m10
m.elements[3] = m11
return nil
}
// Elements clones the elements of the matrix and returns them.
func (m *Matrix2D) Elements() [4]float64 {
tmp := [4]float64{}
for i, v := range m.elements {
tmp[i] = v
}
return tmp
}
// Add adds the elements of the given matrix to the elements of this matrix.
func (m *Matrix2D) Add(mat *Matrix2D) error {
tmp := [4]float64{
m.elements[0] + mat.elements[0],
m.elements[1] + mat.elements[1],
m.elements[2] + mat.elements[2],
m.elements[3] + mat.elements[3],
}
if numeric.AreAnyOverflow(tmp[:]...) {
return numeric.ErrOverflow
}
m.elements = tmp
return nil
}
// Sub subtracts the elements of the given matrix to the elements of this matrix.
func (m *Matrix2D) Sub(mat *Matrix2D) error {
tmp := [4]float64{
m.elements[0] - mat.elements[0],
m.elements[1] - mat.elements[1],
m.elements[2] - mat.elements[2],
m.elements[3] - mat.elements[3],
}
if numeric.AreAnyOverflow(tmp[:]...) {
return numeric.ErrOverflow
}
m.elements = tmp
return nil
}
func multiply2DMatrices(a, b [4]float64) ([4]float64, error) {
a0 := a[0]
a1 := a[1]
a2 := a[2]
a3 := a[3]
b0 := b[0]
b1 := b[1]
b2 := b[2]
b3 := b[3]
out := [4]float64{}
out[0] = a0*b0 + a2*b1
out[1] = a1*b0 + a3*b1
out[2] = a0*b2 + a2*b3
out[3] = a1*b2 + a3*b3
return out, nil
}
// Premultiply left-multiplies the given matrix with this one.
func (m *Matrix2D) Premultiply(mat *Matrix2D) error {
res, err := multiply2DMatrices(mat.elements, m.elements)
if err != nil {
return err
}
m.elements = res
return nil
}
// Postmultiply right-multiplies the given matrix with this one.
func (m *Matrix2D) Postmultiply(mat *Matrix2D) error {
res, err := multiply2DMatrices(m.elements, mat.elements)
if err != nil {
return err
}
m.elements = res
return nil
}
// Invert inverts this matrix in-place.
func (m *Matrix2D) Invert() error {
a := m.elements
a0, a1, a2, a3 := a[0], a[1], a[2], a[3]
// Calculate the determinant
det := a0*a3 - a2*a1
if math.Abs(det) < 1e-13 {
return numeric.ErrSingularMatrix
}
det = 1.0 / det
out := [4]float64{}
out[0] = a3 * det
out[1] = -a1 * det
out[2] = -a2 * det
out[3] = a0 * det
m.elements = out
return nil
}
// Determinant calculates the determinant of the matrix.
func (m *Matrix2D) Determinant() float64 {
a := m.elements
return a[0]*a[3] - a[2]*a[1]
}
// Adjoint calculates the adjoint/adjugate matrix.
func (m *Matrix2D) Adjoint() *Matrix2D {
a := m.elements
// Caching this value is nessecary if out == a
a0 := a[0]
out := [4]float64{}
out[0] = a[3]
out[1] = -a[1]
out[2] = -a[2]
out[3] = a0
return &Matrix2D{
elements: out,
}
}
// Transpose transposes the matrix in-place.
func (m *Matrix2D) Transpose() {
a1 := m.elements[1]
m.elements[1] = m.elements[2]
m.elements[2] = a1
}
// IsSingular returns true if the matrix determinant is exactly zero, false if not.
func (m *Matrix2D) IsSingular() bool {
return m.Determinant() == 0
}
// IsNearSingular returns true if the matrix determinant is equal or below the given tolerance, false if not.
func (m *Matrix2D) IsNearSingular(tol float64) (bool, error) {
if numeric.IsInvalidTolerance(tol) {
return false, numeric.ErrInvalidTol
}
return math.Abs(m.Determinant()) <= tol, nil
} | pkg/geometry/matrix2d.go | 0.756088 | 0.678294 | matrix2d.go | starcoder |
package main
import (
"errors"
"image"
"image/color"
_ "image/jpeg"
_ "image/png"
"log"
"math"
"os"
_ "golang.org/x/image/webp"
)
// Default SSIM constants
var (
L = 255.0
K1 = 0.01
K2 = 0.03
C1 = math.Pow((K1 * L), 2.0)
C2 = math.Pow((K2 * L), 2.0)
)
func handleError(err error) {
if err != nil {
log.Fatal(err)
}
}
// Given a path to an image file, read and return as
// an image.Image
func readImage(fname string) image.Image {
file, err := os.Open(fname)
handleError(err)
defer file.Close()
img, _, err := image.Decode(file)
handleError(err)
return img
}
// Convert an Image to grayscale which
// equalize RGB values
func convertToGray(originalImg image.Image) image.Image {
bounds := originalImg.Bounds()
w, h := dim(originalImg)
grayImg := image.NewGray(bounds)
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
originalColor := originalImg.At(x, y)
grayColor := color.GrayModel.Convert(originalColor)
grayImg.Set(x, y, grayColor)
}
}
return grayImg
}
// Convert uint32 R value to a float. The returnng
// float will have a range of 0-255
func getPixVal(c color.Color) float64 {
r, _, _, _ := c.RGBA()
return float64(r >> 8)
}
// Helper function that return the dimension of an image
func dim(img image.Image) (w, h int) {
w, h = img.Bounds().Max.X, img.Bounds().Max.Y
return
}
// Check if two images have the same dimension
func equalDim(img1, img2 image.Image) bool {
w1, h1 := dim(img1)
w2, h2 := dim(img2)
return (w1 == w2) && (h1 == h2)
}
// Given an Image, calculate the mean of its
// pixel values
func mean(img image.Image) float64 {
w, h := dim(img)
n := float64((w * h) - 1)
sum := 0.0
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
sum += getPixVal(img.At(x, y))
}
}
return sum / n
}
// Compute the standard deviation with pixel values of Image
func stdev(img image.Image) float64 {
w, h := dim(img)
n := float64((w * h) - 1)
sum := 0.0
avg := mean(img)
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
pix := getPixVal(img.At(x, y))
sum += math.Pow((pix - avg), 2.0)
}
}
return math.Sqrt(sum / n)
}
// Calculate the covariance of 2 images
func covar(img1, img2 image.Image) (c float64, err error) {
if !equalDim(img1, img2) {
err = errors.New("Images must have same dimension")
return
}
avg1 := mean(img1)
avg2 := mean(img2)
w, h := dim(img1)
sum := 0.0
n := float64((w * h) - 1)
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
pix1 := getPixVal(img1.At(x, y))
pix2 := getPixVal(img2.At(x, y))
sum += (pix1 - avg1) * (pix2 - avg2)
}
}
c = sum / n
return
}
func ssim(x, y image.Image) float64 {
avgX := mean(x)
avgY := mean(y)
stdevX := stdev(x)
stdevY := stdev(y)
cov, err := covar(x, y)
handleError(err)
numerator := ((2.0 * avgX * avgY) + C1) * ((2.0 * cov) + C2)
denominator := (math.Pow(avgX, 2.0) + math.Pow(avgY, 2.0) + C1) *
(math.Pow(stdevX, 2.0) + math.Pow(stdevY, 2.0) + C2)
return numerator / denominator
} | ssim.go | 0.741112 | 0.419113 | ssim.go | starcoder |
package promtest
import (
"testing"
"github.com/prometheus/client_golang/prometheus"
)
type ExpectationLabelPair struct {
LabelName string
LabelValue string
}
// CheckPrometheusCounterVec is a helper method that checks that prometheus counter
// has the expected value for the expected label on the passed in registry
func CheckPrometheusCounterVec(t *testing.T, reg *prometheus.Registry, counter *prometheus.CounterVec, expectedValue float64, expectedLabels ...ExpectationLabelPair) {
metricFamilies, err := reg.Gather()
if err != nil {
t.Fatalf("Unable to gather prometheus metrics: %+v", err)
}
if len(metricFamilies) < 1 ||
len(metricFamilies[0].Metric) < 1 ||
len(metricFamilies[0].Metric[0].Label) < 1 {
metricCount := 0
if len(metricFamilies) > 0 {
metricCount = len(metricFamilies[0].Metric)
}
t.Fatalf("Unable to gather the metrics from prometheus.\n\tExpected 1 MetricFamilies; got: %d.\n\tExpected 1 Metric; got: %d", len(metricFamilies), metricCount)
}
var metricCounterValue float64 = 0.00
metric := metricFamilies[0].Metric[0]
ExpectedLabels:
for _, expectedLabelPair := range expectedLabels {
for _, gotLabel := range metric.GetLabel() {
if gotLabel.GetName() == expectedLabelPair.LabelName {
metricCounterValue = metric.Counter.GetValue()
gotValue := gotLabel.GetValue()
if gotValue != expectedLabelPair.LabelValue {
t.Fatalf(`Prometheus counter %+v expected [name: "%s" value:"%s"]; got [%s]`, counter, expectedLabelPair.LabelName, expectedLabelPair.LabelValue, gotLabel)
}
continue ExpectedLabels
}
}
}
switch {
case metricCounterValue == 0.00:
t.Fatalf("Prometheus counter %+v not found in the registry.", counter)
case metricCounterValue != expectedValue:
t.Fatalf("Prometheus counter %+v expected value %f; got %f", counter, expectedValue, metricCounterValue)
}
}
// CheckPrometheusCounterVec is a helper method that checks that prometheus counter
// doesn't get called with a set of parameters on the passed in registry
func CheckPrometheusCounterVecNotCalled(t *testing.T, reg *prometheus.Registry, counter *prometheus.CounterVec, expectedValue float64, expectedLabels ...ExpectationLabelPair) {
metricFamilies, err := reg.Gather()
if err != nil {
t.Fatalf("Unable to gather prometheus metrics: %+v", err)
}
if len(metricFamilies) > 0 &&
len(metricFamilies[0].Metric) > 0 &&
len(metricFamilies[0].Metric[0].Label) > 0 {
metricCount := 0
if len(metricFamilies) > 0 {
metricCount = len(metricFamilies[0].Metric)
}
t.Fatalf("Expected 0 MetricFamilies; got: %d.\n\tExpected 0 Metric; got: %d", len(metricFamilies), metricCount)
}
}
// CheckPrometheusCounter is a helper method that checks that prometheus counter
// has the expected value on the passed in registry
func CheckPrometheusCounter(reg *prometheus.Registry, counter prometheus.Counter, expectedValue float64, t *testing.T) {
metricFamilies, err := reg.Gather()
if err != nil {
t.Fatalf("Unable to gather prometheus metrics: %+v", err)
}
if len(metricFamilies) < 1 ||
len(metricFamilies[0].Metric) < 1 {
t.Fatalf("Unable to gather the metrics from prometheus.\n\tExpected 1 MetricFamilies; got: %d.\n\tExpected 1 Metric; got: %d", len(metricFamilies), len(metricFamilies[0].Metric))
}
metric := metricFamilies[0].Metric[0]
if gotValue := metric.Counter.GetValue(); gotValue != expectedValue {
t.Fatalf("Prometheus counter %+v expected count %f; got %f", counter, expectedValue, gotValue)
}
} | verifier.go | 0.788949 | 0.495422 | verifier.go | starcoder |
package reg
// Collection represents a collection of virtual registers. This is primarily
// useful for allocating virtual registers with distinct IDs.
type Collection struct {
idx map[Kind]Index
}
// NewCollection builds an empty register collection.
func NewCollection() *Collection {
return &Collection{
idx: map[Kind]Index{},
}
}
// VirtualRegister allocates and returns a new virtual register of the given kind and width.
func (c *Collection) VirtualRegister(k Kind, s Spec) Virtual {
idx := c.idx[k]
c.idx[k]++
return NewVirtual(idx, k, s)
}
// GP8L allocates and returns a general-purpose 8-bit register (low byte).
func (c *Collection) GP8L() GPVirtual { return c.GP(S8L) }
// GP8H allocates and returns a general-purpose 8-bit register (high byte).
func (c *Collection) GP8H() GPVirtual { return c.GP(S8H) }
// GP8 allocates and returns a general-purpose 8-bit register (low byte).
func (c *Collection) GP8() GPVirtual { return c.GP8L() }
// GP16 allocates and returns a general-purpose 16-bit register.
func (c *Collection) GP16() GPVirtual { return c.GP(S16) }
// GP32 allocates and returns a general-purpose 32-bit register.
func (c *Collection) GP32() GPVirtual { return c.GP(S32) }
// GP64 allocates and returns a general-purpose 64-bit register.
func (c *Collection) GP64() GPVirtual { return c.GP(S64) }
// GP allocates and returns a general-purpose register of the given width.
func (c *Collection) GP(s Spec) GPVirtual { return newgpv(c.VirtualRegister(KindGP, s)) }
// XMM allocates and returns a 128-bit vector register.
func (c *Collection) XMM() VecVirtual { return c.Vec(S128) }
// YMM allocates and returns a 256-bit vector register.
func (c *Collection) YMM() VecVirtual { return c.Vec(S256) }
// ZMM allocates and returns a 512-bit vector register.
func (c *Collection) ZMM() VecVirtual { return c.Vec(S512) }
// Vec allocates and returns a vector register of the given width.
func (c *Collection) Vec(s Spec) VecVirtual { return newvecv(c.VirtualRegister(KindVector, s)) } | tools/vendor/github.com/mmcloughlin/avo/reg/collection.go | 0.904654 | 0.413773 | collection.go | starcoder |
package assertions
import (
"fmt"
"reflect"
)
// ShouldHaveSameTypeAs receives exactly two parameters and compares their underlying types for equality.
func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
first := reflect.TypeOf(actual)
second := reflect.TypeOf(expected[0])
if first != second {
return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first))
}
return success
}
// ShouldNotHaveSameTypeAs receives exactly two parameters and compares their underlying types for inequality.
func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
first := reflect.TypeOf(actual)
second := reflect.TypeOf(expected[0])
if (actual == nil && expected[0] == nil) || first == second {
return fmt.Sprintf(shouldNotHaveBeenA, actual, second)
}
return success
}
// ShouldImplement receives exactly two parameters and ensures
// that the first implements the interface type of the second.
func ShouldImplement(actual interface{}, expectedList ...interface{}) string {
if fail := need(1, expectedList); fail != success {
return fail
}
expected := expectedList[0]
if fail := ShouldBeNil(expected); fail != success {
return shouldCompareWithInterfacePointer
}
if fail := ShouldNotBeNil(actual); fail != success {
return shouldNotBeNilActual
}
var actualType reflect.Type
if reflect.TypeOf(actual).Kind() != reflect.Ptr {
actualType = reflect.PtrTo(reflect.TypeOf(actual))
} else {
actualType = reflect.TypeOf(actual)
}
expectedType := reflect.TypeOf(expected)
if fail := ShouldNotBeNil(expectedType); fail != success {
return shouldCompareWithInterfacePointer
}
expectedInterface := expectedType.Elem()
if !actualType.Implements(expectedInterface) {
return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType)
}
return success
}
// ShouldNotImplement receives exactly two parameters and ensures
// that the first does NOT implement the interface type of the second.
func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string {
if fail := need(1, expectedList); fail != success {
return fail
}
expected := expectedList[0]
if fail := ShouldBeNil(expected); fail != success {
return shouldCompareWithInterfacePointer
}
if fail := ShouldNotBeNil(actual); fail != success {
return shouldNotBeNilActual
}
var actualType reflect.Type
if reflect.TypeOf(actual).Kind() != reflect.Ptr {
actualType = reflect.PtrTo(reflect.TypeOf(actual))
} else {
actualType = reflect.TypeOf(actual)
}
expectedType := reflect.TypeOf(expected)
if fail := ShouldNotBeNil(expectedType); fail != success {
return shouldCompareWithInterfacePointer
}
expectedInterface := expectedType.Elem()
if actualType.Implements(expectedInterface) {
return fmt.Sprintf(shouldNotHaveImplemented, actualType, expectedInterface)
}
return success
}
// ShouldBeError asserts that the first argument implements the error interface.
// It also compares the first argument against the second argument if provided
// (which must be an error message string or another error value).
func ShouldBeError(actual interface{}, expected ...interface{}) string {
if fail := atMost(1, expected); fail != success {
return fail
}
if !isError(actual) {
return fmt.Sprintf(shouldBeError, reflect.TypeOf(actual))
}
if len(expected) == 0 {
return success
}
if expected := expected[0]; !isString(expected) && !isError(expected) {
return fmt.Sprintf(shouldBeErrorInvalidComparisonValue, reflect.TypeOf(expected))
}
return ShouldEqual(fmt.Sprint(actual), fmt.Sprint(expected[0]))
}
func isString(value interface{}) bool { _, ok := value.(string); return ok }
func isError(value interface{}) bool { _, ok := value.(error); return ok } | vendor/github.com/smartystreets/assertions/type.go | 0.721645 | 0.631054 | type.go | starcoder |
package build
import (
"fmt"
"strings"
)
// Stack is structure for a stack. A stack lists all targets that run during a build.
type Stack struct {
Targets []*Target
}
// NewStack makes a new stack
// Returns: a pointer to the stack
func NewStack() *Stack {
stack := Stack{
Targets: make([]*Target, 0),
}
return &stack
}
// Contains tells if the stack contains given target
// - target: target to test
// Returns: a boolean telling if target is in the stack
func (stack *Stack) Contains(name string) bool {
for _, target := range stack.Targets {
if name == target.Name {
return true
}
}
return false
}
// Push a target on the stack
// - target: target to push on the stack
// Return: an error if we are in an infinite loop
func (stack *Stack) Push(target *Target) error {
for _, t := range stack.Targets {
if t == target {
stack.Targets = append(stack.Targets, target)
return fmt.Errorf("infinite loop: %v", stack.String())
}
}
stack.Targets = append(stack.Targets, target)
return nil
}
// Pop target on the stack
// Return: error if something went wrong
func (stack *Stack) Pop() error {
length := len(stack.Targets)
if length == 0 {
return fmt.Errorf("no target on stack")
}
stack.Targets = stack.Targets[:length-1]
return nil
}
// Last gets the last target on stack
// Return: last target on stack
func (stack *Stack) Last() *Target {
if len(stack.Targets) == 0 {
return nil
}
return stack.Targets[len(stack.Targets)-1]
}
// ToString returns string representation of the stack, such as:
// "foo -> bar -> spam"
// Return: the stack as a string
func (stack *Stack) String() string {
names := make([]string, len(stack.Targets))
for i, target := range stack.Targets {
names[i] = target.Name
}
return strings.Join(names, " -> ")
}
// Copy returns a copy of the stack
// Return: pointer to a copy of the stack
func (stack *Stack) Copy() *Stack {
another := make([]*Target, len(stack.Targets))
for i := 0; i < len(stack.Targets); i++ {
another[i] = stack.Targets[i]
}
return &Stack{another}
} | neon/build/stack.go | 0.756987 | 0.405655 | stack.go | starcoder |
package tensor
import (
"reflect"
"unsafe"
"sort"
"github.com/pkg/errors"
)
var (
_ Sparse = &CS{}
)
// Sparse is a sparse tensor.
type Sparse interface {
Tensor
Densor
NonZeroes() int // NonZeroes returns the number of nonzero values
}
// coo is an internal representation of the Coordinate type sparse matrix.
// It's not exported because you probably shouldn't be using it.
// Instead, constructors for the *CS type supports using a coordinate as an input.
type coo struct {
o DataOrder
xs, ys []int
data array
}
func (c *coo) Len() int { return c.data.L }
func (c *coo) Less(i, j int) bool {
if c.o.IsColMajor() {
return c.colMajorLess(i, j)
}
return c.rowMajorLess(i, j)
}
func (c *coo) Swap(i, j int) {
c.xs[i], c.xs[j] = c.xs[j], c.xs[i]
c.ys[i], c.ys[j] = c.ys[j], c.ys[i]
c.data.swap(i, j)
}
func (c *coo) colMajorLess(i, j int) bool {
if c.ys[i] < c.ys[j] {
return true
}
if c.ys[i] == c.ys[j] {
// check xs
if c.xs[i] <= c.xs[j] {
return true
}
}
return false
}
func (c *coo) rowMajorLess(i, j int) bool {
if c.xs[i] < c.xs[j] {
return true
}
if c.xs[i] == c.xs[j] {
// check ys
if c.ys[i] <= c.ys[j] {
return true
}
}
return false
}
// CS is a compressed sparse data structure. It can be used to represent both CSC and CSR sparse matrices.
// Refer to the individual creation functions for more information.
type CS struct {
s Shape
o DataOrder
e Engine
f MemoryFlag
z interface{} // z is the "zero" value. Typically it's not used.
indices []int
indptr []int
array
}
// NewCSR creates a new Compressed Sparse Row matrix. The data has to be a slice or it panics.
func NewCSR(indices, indptr []int, data interface{}, opts ...ConsOpt) *CS {
t := new(CS)
t.indices = indices
t.indptr = indptr
t.array = arrayFromSlice(data)
t.o = NonContiguous
t.e = StdEng{}
for _, opt := range opts {
opt(t)
}
return t
}
// NewCSC creates a new Compressed Sparse Column matrix. The data has to be a slice, or it panics.
func NewCSC(indices, indptr []int, data interface{}, opts ...ConsOpt) *CS {
t := new(CS)
t.indices = indices
t.indptr = indptr
t.array = arrayFromSlice(data)
t.o = MakeDataOrder(ColMajor, NonContiguous)
t.e = StdEng{}
for _, opt := range opts {
opt(t)
}
return t
}
// CSRFromCoord creates a new Compressed Sparse Row matrix given the coordinates. The data has to be a slice or it panics.
func CSRFromCoord(shape Shape, xs, ys []int, data interface{}) *CS {
t := new(CS)
t.s = shape
t.o = NonContiguous
t.array = arrayFromSlice(data)
t.e = StdEng{}
// coord matrix
cm := &coo{t.o, xs, ys, t.array}
sort.Sort(cm)
r := shape[0]
c := shape[1]
if r <= cm.xs[len(cm.xs)-1] || c <= MaxInts(cm.ys...) {
panic("Cannot create sparse matrix where provided shape is smaller than the implied shape of the data")
}
indptr := make([]int, r+1)
var i, j, tmp int
for i = 1; i < r+1; i++ {
for j = tmp; j < len(xs) && xs[j] < i; j++ {
}
tmp = j
indptr[i] = j
}
t.indices = ys
t.indptr = indptr
return t
}
// CSRFromCoord creates a new Compressed Sparse Column matrix given the coordinates. The data has to be a slice or it panics.
func CSCFromCoord(shape Shape, xs, ys []int, data interface{}) *CS {
t := new(CS)
t.s = shape
t.o = MakeDataOrder(NonContiguous, ColMajor)
t.array = arrayFromSlice(data)
t.e = StdEng{}
// coord matrix
cm := &coo{t.o, xs, ys, t.array}
sort.Sort(cm)
r := shape[0]
c := shape[1]
// check shape
if r <= MaxInts(cm.xs...) || c <= cm.ys[len(cm.ys)-1] {
panic("Cannot create sparse matrix where provided shape is smaller than the implied shape of the data")
}
indptr := make([]int, c+1)
var i, j, tmp int
for i = 1; i < c+1; i++ {
for j = tmp; j < len(ys) && ys[j] < i; j++ {
}
tmp = j
indptr[i] = j
}
t.indices = xs
t.indptr = indptr
return t
}
func (t *CS) Shape() Shape { return t.s }
func (t *CS) Strides() []int { return nil }
func (t *CS) Dtype() Dtype { return t.t }
func (t *CS) Dims() int { return 2 }
func (t *CS) Size() int { return t.s.TotalSize() }
func (t *CS) DataSize() int { return t.L }
func (t *CS) Engine() Engine { return t.e }
func (t *CS) DataOrder() DataOrder { return t.o }
func (t *CS) Slice(...Slice) (View, error) {
return nil, errors.Errorf("Slice for sparse tensors not implemented yet")
}
func (t *CS) At(coord ...int) (interface{}, error) {
if len(coord) != t.Dims() {
return nil, errors.Errorf("Expected coordinates to be of %d-dimensions. Got %v instead", t.Dims(), coord)
}
if i, ok := t.at(coord...); ok {
return t.Get(i), nil
}
if t.z == nil {
return reflect.Zero(t.t.Type).Interface(), nil
}
return t.z, nil
}
func (t *CS) SetAt(v interface{}, coord ...int) error {
if i, ok := t.at(coord...); ok {
t.Set(i, v)
return nil
}
return errors.Errorf("Cannot set value in a compressed sparse matrix: Coordinate %v not found", coord)
}
func (t *CS) Reshape(...int) error { return errors.New("compressed sparse matrix cannot be reshaped") }
// T transposes the matrix. Concretely, it just changes a bit - the state goes from CSC to CSR, and vice versa.
func (t *CS) T(axes ...int) error {
dims := t.Dims()
if len(axes) != dims && len(axes) != 0 {
return errors.Errorf("Cannot transpose along axes %v", axes)
}
if len(axes) == 0 || axes == nil {
axes = make([]int, dims)
for i := 0; i < dims; i++ {
axes[i] = dims - 1 - i
}
}
UnsafePermute(axes, []int(t.s))
t.o = t.o.toggleColMajor()
t.o = MakeDataOrder(t.o, Transposed)
return errors.Errorf(methodNYI, "T", t)
}
// UT untransposes the CS
func (t *CS) UT() { t.T(); t.o = t.o.clearTransposed() }
// Transpose is a no-op. The data does not move
func (t *CS) Transpose() error { return nil }
func (t *CS) Apply(fn interface{}, opts ...FuncOpt) (Tensor, error) {
return nil, errors.Errorf(methodNYI, "Apply", t)
}
func (t *CS) Eq(other interface{}) bool {
if ot, ok := other.(*CS); ok {
if t == ot {
return true
}
if len(ot.indices) != len(t.indices) {
return false
}
if len(ot.indptr) != len(t.indptr) {
return false
}
if !t.s.Eq(ot.s) {
return false
}
if ot.o != t.o {
return false
}
for i, ind := range t.indices {
if ot.indices[i] != ind {
return false
}
}
for i, ind := range t.indptr {
if ot.indptr[i] != ind {
return false
}
}
return t.array.Eq(&ot.array)
}
return false
}
func (t *CS) Clone() interface{} {
retVal := new(CS)
retVal.s = t.s.Clone()
retVal.o = t.o
retVal.e = t.e
retVal.indices = make([]int, len(t.indices))
retVal.indptr = make([]int, len(t.indptr))
copy(retVal.indices, t.indices)
copy(retVal.indptr, t.indptr)
retVal.array = makeArray(t.t, t.array.L)
copyArray(&retVal.array, &t.array)
retVal.e = t.e
return retVal
}
func (t *CS) IsScalar() bool { return false }
func (t *CS) ScalarValue() interface{} { panic("Sparse Matrices cannot represent Scalar Values") }
func (t *CS) MemSize() uintptr { return uintptr(calcMemSize(t.t, t.array.L)) }
func (t *CS) Uintptr() uintptr { return uintptr(t.array.Ptr) }
func (t *CS) Pointer() unsafe.Pointer { return t.array.Ptr }
// NonZeroes returns the nonzeroes. In academic literature this is often written as NNZ.
func (t *CS) NonZeroes() int { return t.L }
func (t *CS) RequiresIterator() bool { return true }
func (t *CS) Iterator() Iterator { return NewFlatSparseIterator(t) }
func (t *CS) at(coord ...int) (int, bool) {
var r, c int
if t.o.IsColMajor() {
r = coord[1]
c = coord[0]
} else {
r = coord[0]
c = coord[1]
}
for i := t.indptr[r]; i < t.indptr[r+1]; i++ {
if t.indices[i] == c {
return i, true
}
}
return -1, false
}
// Dense creates a Dense tensor from the compressed one.
func (t *CS) Dense() *Dense {
if t.e != nil && t.e != (StdEng{}) {
// use
}
d := recycledDense(t.t, t.Shape().Clone(), WithEngine(t.e))
if t.o.IsColMajor() {
for i := 0; i < len(t.indptr)-1; i++ {
for j := t.indptr[i]; j < t.indptr[i+1]; j++ {
d.SetAt(t.Get(j), t.indices[j], i)
}
}
} else {
for i := 0; i < len(t.indptr)-1; i++ {
for j := t.indptr[i]; j < t.indptr[i+1]; j++ {
d.SetAt(t.Get(j), i, t.indices[j])
}
}
}
return d
}
// Other Accessors
func (t *CS) Indptr() []int {
retVal := BorrowInts(len(t.indptr))
copy(retVal, t.indptr)
return retVal
}
func (t *CS) Indices() []int {
retVal := BorrowInts(len(t.indices))
copy(retVal, t.indices)
return retVal
}
func (t *CS) AsCSR() {
if t.o.IsRowMajor() {
return
}
t.o.toggleColMajor()
}
func (t *CS) AsCSC() {
if t.o.IsColMajor() {
return
}
t.o.toggleColMajor()
}
func (t *CS) IsNativelyAccessible() bool { return t.f.nativelyAccessible() }
func (t *CS) IsManuallyManaged() bool { return t.f.manuallyManaged() }
func (t *CS) arr() array { return t.array }
func (t *CS) arrPtr() *array { return &t.array }
func (t *CS) standardEngine() standardEngine { return nil } | sparse.go | 0.716516 | 0.444384 | sparse.go | starcoder |
package integration
import (
"testing"
"github.com/CyCoreSystems/ari"
"github.com/pkg/errors"
)
func TestBridgeCreate(t *testing.T, s Server) {
key := ari.NewKey(ari.BridgeKey, "bridgeID")
runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) {
bh := ari.NewBridgeHandle(key, m.Bridge, nil)
m.Bridge.On("Create", key, "bridgeType", "bridgeName").Return(bh, nil)
ret, err := cl.Bridge().Create(key, "bridgeType", "bridgeName")
if err != nil {
t.Errorf("Unexpected error in remote create call: %v", err)
}
if ret == nil {
t.Errorf("Unexpected nil bridge handle")
}
if ret == nil || ret.ID() != key.ID {
t.Errorf("Expected bridge id %v, got %v", key.ID, ret)
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Create", key, "bridgeType", "bridgeName")
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
var expected = errors.New("unknown error")
m.Bridge.On("Create", key, "bridgeType", "bridgeName").Return(nil, expected)
ret, err := cl.Bridge().Create(key, "bridgeType", "bridgeName")
if err == nil || errors.Cause(err).Error() != expected.Error() {
t.Errorf("Expected error '%v', got '%v'", expected, err)
}
if ret != nil {
t.Errorf("Expected nil bridge handle, got %v", ret)
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Create", key, "bridgeType", "bridgeName")
})
}
func TestBridgeList(t *testing.T, s Server) {
runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) {
var handles []*ari.Key
var h1 = ari.NewKey(ari.BridgeKey, "h1")
var h2 = ari.NewKey(ari.BridgeKey, "h2")
handles = append(handles, h1)
handles = append(handles, h2)
m.Bridge.On("List", (*ari.Key)(nil)).Return(handles, nil)
ret, err := cl.Bridge().List(nil)
if err != nil {
t.Errorf("Unexpected error in remote create call: %v", err)
}
if len(ret) != len(handles) {
t.Errorf("Expected handle list of length %d, got %d", len(handles), len(ret))
}
m.Shutdown()
m.Bridge.AssertCalled(t, "List", (*ari.Key)(nil))
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
var expected = errors.New("unknown error")
m.Bridge.On("List", (*ari.Key)(nil)).Return([]*ari.Key{}, expected)
ret, err := cl.Bridge().List(nil)
if err == nil || errors.Cause(err).Error() != expected.Error() {
t.Errorf("Expected error '%v', got '%v'", expected, err)
}
if len(ret) != 0 {
t.Errorf("Expected handle list of length %d, got %d", 0, len(ret))
}
m.Shutdown()
m.Bridge.AssertCalled(t, "List", (*ari.Key)(nil))
})
}
func TestBridgeData(t *testing.T, s Server) {
var key = ari.NewKey(ari.BridgeKey, "bridge1")
runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) {
bd := &ari.BridgeData{
ID: "bridge1",
Class: "class1",
ChannelIDs: []string{"channel1", "channel2"},
}
m.Bridge.On("Data", key).Return(bd, nil)
ret, err := cl.Bridge().Data(key)
if err != nil {
t.Errorf("Unexpected error in remote data call: %v", err)
}
if ret == nil || ret.ID != bd.ID || ret.Class != bd.Class {
t.Errorf("bridge data mismatchde")
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Data", key)
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("Data", key).Return(nil, errors.New("Error getting data"))
ret, err := cl.Bridge().Data(key)
if err == nil {
t.Errorf("Expected error to be non-nil")
}
if ret != nil {
t.Errorf("Expected bridge data to be nil")
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Data", key)
})
}
func TestBridgeAddChannel(t *testing.T, s Server) {
var key = ari.NewKey(ari.BridgeKey, "bridge1")
runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("AddChannel", key, "channel1").Return(nil)
err := cl.Bridge().AddChannel(key, "channel1")
if err != nil {
t.Errorf("Unexpected error in remote AddChannel call: %v", err)
}
m.Shutdown()
m.Bridge.AssertCalled(t, "AddChannel", key, "channel1")
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("AddChannel", key, "channel1").Return(errors.New("unknown error"))
err := cl.Bridge().AddChannel(key, "channel1")
if err == nil {
t.Errorf("Expected error to be non-nil")
}
m.Shutdown()
m.Bridge.AssertCalled(t, "AddChannel", key, "channel1")
})
}
func TestBridgeRemoveChannel(t *testing.T, s Server) {
var key = ari.NewKey(ari.BridgeKey, "bridge1")
runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("RemoveChannel", key, "channel1").Return(nil)
err := cl.Bridge().RemoveChannel(key, "channel1")
if err != nil {
t.Errorf("Unexpected error in remote RemoveChannel call: %v", err)
}
m.Shutdown()
m.Bridge.AssertCalled(t, "RemoveChannel", key, "channel1")
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("RemoveChannel", key, "channel1").Return(errors.New("unknown error"))
err := cl.Bridge().RemoveChannel(key, "channel1")
if err == nil {
t.Errorf("Expected error to be non-nil")
}
m.Shutdown()
m.Bridge.AssertCalled(t, "RemoveChannel", key, "channel1")
})
}
func TestBridgeDelete(t *testing.T, s Server) {
var key = ari.NewKey(ari.BridgeKey, "bridge1")
runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("Delete", key).Return(nil)
err := cl.Bridge().Delete(key)
if err != nil {
t.Errorf("Unexpected error in remote Delete call: %v", err)
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Delete", key)
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("Delete", key).Return(errors.New("unknown error"))
err := cl.Bridge().Delete(key)
if err == nil {
t.Errorf("Expected error to be non-nil")
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Delete", key)
})
}
func TestBridgePlay(t *testing.T, s Server) {
var key = ari.NewKey(ari.BridgeKey, "bridge1")
runTest("simple", t, s, func(t *testing.T, m *mock, cl ari.Client) {
var ph = ari.NewPlaybackHandle(ari.NewKey(ari.PlaybackKey, "playback1"), m.Playback, nil)
m.Bridge.On("Play", key, "playback1", "mediaURI").Return(ph, nil)
ret, err := cl.Bridge().Play(key, "playback1", "mediaURI")
if err != nil {
t.Errorf("Unexpected error in remote Play call: %v", err)
}
if ret == nil || ret.ID() != ph.ID() {
t.Errorf("Expected playback handle '%v', got '%v'", ph.ID(), ret.ID())
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Play", key, "playback1", "mediaURI")
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
m.Bridge.On("Play", key, "playback1", "mediaURI").Return(nil, errors.New("unknown error"))
ret, err := cl.Bridge().Play(key, "playback1", "mediaURI")
if err == nil {
t.Errorf("Expected error to be non-nil")
}
if ret != nil {
t.Errorf("Expected empty playback handle")
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Play", key, "playback1", "mediaURI")
})
}
func TestBridgeRecord(t *testing.T, s Server) {
var key = ari.NewKey(ari.BridgeKey, "bridge1")
runTest("customOpts", t, s, func(t *testing.T, m *mock, cl ari.Client) {
var opts = &ari.RecordingOptions{Format: "", MaxDuration: 0, MaxSilence: 0, Exists: "", Beep: false, Terminate: "#"}
var lrh = ari.NewLiveRecordingHandle(ari.NewKey(ari.LiveRecordingKey, "recording1"), m.LiveRecording, nil)
bd := &ari.BridgeData{
ID: "bridge1",
Class: "class1",
ChannelIDs: []string{"channel1", "channel2"},
}
m.Bridge.On("Data", key).Return(bd, nil)
m.Bridge.On("Record", key, "recording1", opts).Return(lrh, nil)
ret, err := cl.Bridge().Record(key, "recording1", opts)
if err != nil {
t.Errorf("Unexpected error in remote Record call: %v", err)
}
if ret == nil || ret.ID() != lrh.ID() {
t.Errorf("Expected liverecording handle '%v', got '%v'", lrh.ID(), ret.ID())
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Record", key, "recording1", opts)
})
runTest("nilOpts", t, s, func(t *testing.T, m *mock, cl ari.Client) {
var opts = &ari.RecordingOptions{}
var lrh = ari.NewLiveRecordingHandle(ari.NewKey(ari.LiveRecordingKey, "recording1"), m.LiveRecording, nil)
bd := &ari.BridgeData{
ID: "bridge1",
Class: "class1",
ChannelIDs: []string{"channel1", "channel2"},
}
m.Bridge.On("Data", key).Return(bd, nil)
m.Bridge.On("Record", key, "recording1", opts).Return(lrh, nil)
ret, err := cl.Bridge().Record(key, "recording1", nil)
if err != nil {
t.Errorf("Unexpected error in remote Record call: %v", err)
}
if ret == nil || ret.ID() != lrh.ID() {
t.Errorf("Expected liverecording handle '%v', got '%v'", lrh, ret)
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Record", key, "recording1", opts)
})
runTest("error", t, s, func(t *testing.T, m *mock, cl ari.Client) {
bd := &ari.BridgeData{
ID: "bridge1",
Class: "class1",
ChannelIDs: []string{"channel1", "channel2"},
}
m.Bridge.On("Data", key).Return(bd, nil)
var opts = &ari.RecordingOptions{}
m.Bridge.On("Record", key, "recording1", opts).Return(nil, errors.New("unknown error"))
ret, err := cl.Bridge().Record(key, "recording1", opts)
if err == nil {
t.Errorf("Expected error to be non-nil")
}
if ret != nil {
t.Errorf("Expected empty liverecording handle")
}
m.Shutdown()
m.Bridge.AssertCalled(t, "Record", key, "recording1", opts)
})
} | internal/integration/bridge.go | 0.593256 | 0.459804 | bridge.go | starcoder |
// Package counterlist is an example using go-frp modeled after the Elm example found at:
// https://github.com/evancz/elm-architecture-tutorial/blob/master/examples/3/CounterList.elm
package counterlist
import (
c "github.com/gmlewis/go-frp/v2/examples/3/counter"
h "github.com/gmlewis/go-frp/v2/html"
)
// MODEL
type Model struct {
counters []Counter
nextID ID
}
type ID int
type Counter struct {
id ID
counter c.Model
}
func Init(values ...int) Model {
m := Model{nextID: ID(len(values))}
for id, value := range values {
m.counters = append(m.counters, Counter{id: ID(id), counter: c.Model(value)})
}
return m
}
// UPDATE
type Action func(Model) Model
func Updater(model Model) func(action Action) Model {
return func(action Action) Model { return model.Update(action) }
}
func (m Model) Update(action Action) Model { return action(m) }
func Remove(model Model) Model {
var counters []Counter
var nextID ID
if len(model.counters) > 1 {
counters = model.counters[:len(model.counters)-1]
nextID = model.nextID - 1
}
return Model{
counters: counters,
nextID: nextID,
}
}
func Insert(model Model) Model {
counters := model.counters[:] // Copy counters
return Model{
counters: append(counters, Counter{id: model.nextID, counter: c.Model(0)}),
nextID: model.nextID + 1,
}
}
func cWrapper(model Model, id int) c.WrapFunc {
return func(cm c.Model) interface{} {
var counters []Counter
for i := 0; i < len(model.counters); i++ {
if i == id {
counters = append(counters, Counter{id: ID(id), counter: cm})
continue
}
counters = append(counters, model.counters[i])
}
return Model{
counters: counters,
nextID: model.nextID,
}
}
}
func wrapper(model Model) func(action Action) interface{} {
return func(action Action) interface{} {
return model.Update(action)
}
}
// VIEW
func (m Model) View(rootUpdateFunc, wrapFunc interface{}) h.HTML {
remove := h.Button(h.Text("Remove")).OnClick(rootUpdateFunc, wrapper(m), Remove)
insert := h.Button(h.Text("Add")).OnClick(rootUpdateFunc, wrapper(m), Insert)
p := []h.HTML{remove, insert}
for id, counter := range m.counters {
p = append(p, counter.counter.View(rootUpdateFunc, cWrapper(m, id)))
}
return h.Div(p...)
} | examples/3/counterlist/counterlist.go | 0.752286 | 0.407864 | counterlist.go | starcoder |
package selfupdate
// Note: "|" will be replaced by backticks in the help string below
var selfUpdateHelp = `
This command downloads the latest release of rclone and replaces
the currently running binary. The download is verified with a hashsum
and cryptographically signed signature.
If used without flags (or with implied |--stable| flag), this command
will install the latest stable release. However, some issues may be fixed
(or features added) only in the latest beta release. In such cases you should
run the command with the |--beta| flag, i.e. |rclone selfupdate --beta|.
You can check in advance what version would be installed by adding the
|--check| flag, then repeat the command without it when you are satisfied.
Sometimes the rclone team may recommend you a concrete beta or stable
rclone release to troubleshoot your issue or add a bleeding edge feature.
The |--version VER| flag, if given, will update to the concrete version
instead of the latest one. If you omit micro version from |VER| (for
example |1.53|), the latest matching micro version will be used.
Upon successful update rclone will print a message that contains a previous
version number. You will need it if you later decide to revert your update
for some reason. Then you'll have to note the previous version and run the
following command: |rclone selfupdate [--beta] OLDVER|.
If the old version contains only dots and digits (for example |v1.54.0|)
then it's a stable release so you won't need the |--beta| flag. Beta releases
have an additional information similar to |v1.54.0-beta.5111.06f1c0c61|.
(if you are a developer and use a locally built rclone, the version number
will end with |-DEV|, you will have to rebuild it as it obviously can't
be distributed).
If you previously installed rclone via a package manager, the package may
include local documentation or configure services. You may wish to update
with the flag |--package deb| or |--package rpm| (whichever is correct for
your OS) to update these too. This command with the default |--package zip|
will update only the rclone executable so the local manual may become
inaccurate after it.
The |rclone mount| command (https://rclone.org/commands/rclone_mount/) may
or may not support extended FUSE options depending on the build and OS.
|selfupdate| will refuse to update if the capability would be discarded.
Note: Windows forbids deletion of a currently running executable so this
command will rename the old executable to 'rclone.old.exe' upon success.
Please note that this command was not available before rclone version 1.55.
If it fails for you with the message |unknown command "selfupdate"| then
you will need to update manually following the install instructions located
at https://rclone.org/install/
` | cmd/selfupdate/help.go | 0.559049 | 0.47171 | help.go | starcoder |
package bayesiannetwork
import (
"math/rand"
"sort"
)
// Hold the PMF in sorted order by probabilty and the original indices of the
// PMF (in "histogram order," I suppose)
type Density struct {
sorted []float64
// index is the original indices of the sorted probabilities -- corresponds
// to Node State
index []int
prefixSum []float64
// index in reverse -- maps Node State to probability
StateMap map[int]float64
}
func NewDensity(probs ...float64) Density {
slice := NewFloat64IndexSlice(probs...)
StateMap := make(map[int]float64)
for k, p := range probs {
StateMap[k] = p
}
sort.Sort(slice)
sorted, index := slice.Interface.(sort.Float64Slice), slice.index
prefixSum := make([]float64, len(sorted))
current := 0.0
for i, v := range sorted {
current += v
prefixSum[i] = current
}
d := Density{sorted, index, prefixSum, StateMap}
return d
}
// Densitys hold the sorted probailities and the original indices
// the sample function will return the original index of the "bucket" sampled.
func (d Density) sample(r *rand.Rand) int {
index := sort.SearchFloat64s(d.prefixSum, r.Float64())
// fmt.Println("CHECK", len(d.sorted), index)
return d.index[index]
}
// Basic Node in a bayesian network. Allows only discrete distributions. All
// cpds must have the same size.
type Node struct {
Name string
States int
Children []*Node
Parents []*Node
cpd []Density
}
func (n Node) getCPDIndex(parent_States map[*Node]int) int {
if len(n.Parents) != len(parent_States) {
return -1
}
parent_cpd_sizes := make([]int, len(n.Parents))
cpd_length := 1
for index, parent := range n.Parents {
cpd_length = cpd_length * parent.States
parent_cpd_sizes[index] = parent.States
}
start := 0
end := cpd_length
// running_length := cpd_length
for i := len(n.Parents) - 1; i >= 0; i-- {
repeats := (end - start) / parent_cpd_sizes[i]
start = start + parent_States[n.Parents[i]]*repeats
end = start + repeats
}
return start
}
// function to enumerate all possible parent States
func (n Node) getAllParentStates(states *[][]int, current []int, parentStateNums ...int) {
if len(parentStateNums) == 0 {
*states = append(*states, current)
} else {
for s := parentStateNums[0] - 1; s >= 0; s-- {
next := append(current, s)
n.getAllParentStates(states, next, parentStateNums[1:]...)
}
}
} | bayesiannetwork/node.go | 0.587233 | 0.505859 | node.go | starcoder |
package primitives
import (
"math"
"math/rand"
)
type Material interface {
Bounce(ray Ray, hit HitRecord, rand *rand.Rand) (bool, Ray)
Color() Vector
}
type Lambertian struct {
C Vector
}
func (l Lambertian) Bounce(input Ray, record HitRecord, rand *rand.Rand) (bool, Ray) {
direction := record.Normal.Add(VectorInUnitSphere(rand))
return true, Ray{record.Point, direction}
}
func (l Lambertian) Color() Vector {
return l.C
}
type Metal struct {
C Vector
Fuzz float64
}
func (m Metal) Bounce(input Ray, record HitRecord, rand *rand.Rand) (bool, Ray) {
direction := input.Direction.Reflect(record.Normal)
fuzzed := VectorInUnitSphere(rand).MultiplyScalar(m.Fuzz)
bounced_ray := Ray{record.Point, direction.Add(fuzzed)}
bounced := direction.DotProduct(record.Normal) > 0
return bounced, bounced_ray
}
func (m Metal) Color() Vector {
return m.C
}
type Dielectric struct {
C Vector
RefractiveIndex float64
}
func (d Dielectric) Color() Vector {
return d.C
}
func (d Dielectric) Bounce(input Ray, record HitRecord, rand *rand.Rand) (bool, Ray) {
var outwardNormal Vector
var niOverNt, cosine float64
// check if entering or leaving a surface
if input.Direction.DotProduct(record.Normal) > 0 {
outwardNormal = record.Normal.MultiplyScalar(-1)
niOverNt = d.RefractiveIndex
cosine = input.Direction.Normalise().DotProduct(record.Normal) * d.RefractiveIndex
} else {
outwardNormal = record.Normal
niOverNt = 1.0 / d.RefractiveIndex
cosine = -1 * input.Direction.Normalise().DotProduct(record.Normal) * d.RefractiveIndex
}
// check for success
success, refract := input.Direction.Refract(outwardNormal, niOverNt)
var reflectProb float64
if success {
// find out if we have reflection from success
reflectProb = d.schlick(cosine)
} else {
// must be pure reflection
reflectProb = 1.0
}
if rand.Float64() < reflectProb {
reflected := input.Direction.Reflect(record.Normal)
return true, Ray{record.Point, reflected}
}
return true, Ray{record.Point, refract}
}
func (d Dielectric) schlick(cosine float64) float64 {
r0 := (1 - d.RefractiveIndex) / (1 + d.RefractiveIndex)
r0 = r0 * r0
return r0 + (1-r0)*math.Pow(1-cosine, 5)
} | internal/primitives/material.go | 0.803405 | 0.557484 | material.go | starcoder |
package objectbox
/*
This file implements obx_data_visitor forwarding to Go callbacks
Overview:
* Register a dataVisitor callback, getting a visitor ID.
* Pass the registered visitor ID together with a generic dataVisitor (C.dataVisitorDispatch) to a C.obx_* function.
* When ObjectBox calls dataVisitorDispatch, it finds the callback registered under that ID and calls it.
* After there can be no more callbacks, the visitor must be unregistered.
Code example:
var visitorId uint32
visitorId, err = dataVisitorRegister(func(bytes []byte) bool {
// do your thing with the data
object := Cursor.binding.Load(bytes)
return true // this return value is passed back to the ObjectBox, usually used to break the traversal
})
if err != nil {
return err
}
// don't forget to unregister the visitor after it's no longer going to be called or you would fill the queue up quickly
defer dataVisitorUnregister(visitorId)
rc := C.obx_query_visit(cQuery, cCursor, dataVisitor, unsafe.Pointer(&visitorId), C.uint64_t(offset), C.uint64_t(limit))
*/
/*
#include "objectbox.h"
// this implements the obx_data_visitor forwarding, it's called from ObjectBox C-api (see `dataVisitor` go var)
extern bool dataVisitorDispatch(void* visitorId, void* data, size_t size);
*/
import "C"
import (
"fmt"
"sync"
"unsafe"
)
type dataVisitorCallback = func([]byte) bool
var dataVisitor = (*C.obx_data_visitor)(unsafe.Pointer(C.dataVisitorDispatch))
var dataVisitorId uint32
var dataVisitorMutex sync.Mutex
var dataVisitorCallbacks = make(map[uint32]dataVisitorCallback)
func dataVisitorRegister(fn dataVisitorCallback) (uint32, error) {
dataVisitorMutex.Lock()
defer dataVisitorMutex.Unlock()
// cycle through ids until we find an empty slot
dataVisitorId++
var initialId = dataVisitorId
for dataVisitorCallbacks[dataVisitorId] != nil {
dataVisitorId++
if initialId == dataVisitorId {
return 0, fmt.Errorf("full queue of data-visitor callbacks - can't allocate another")
}
}
dataVisitorCallbacks[dataVisitorId] = fn
return dataVisitorId, nil
}
func dataVisitorLookup(id uint32) dataVisitorCallback {
dataVisitorMutex.Lock()
defer dataVisitorMutex.Unlock()
return dataVisitorCallbacks[id]
}
func dataVisitorUnregister(id uint32) {
dataVisitorMutex.Lock()
defer dataVisitorMutex.Unlock()
delete(dataVisitorCallbacks, id)
} | objectbox/datavisitor.go | 0.663451 | 0.431644 | datavisitor.go | starcoder |
package transform
import (
"image"
"net/url"
"strconv"
"strings"
"github.com/Sirupsen/logrus"
"github.com/disintegration/imaging"
)
// RotateImage implements the rotating scheme described on:
// https://docs.fastly.com/api/imageopto/orient
func RotateImage(m image.Image, orient string) image.Image {
switch orient {
case "r":
return imaging.Rotate270(m)
case "l":
return imaging.Rotate90(m)
case "h":
return imaging.FlipH(m)
case "v":
return imaging.FlipV(m)
case "hv":
return imaging.FlipV(imaging.FlipH(m))
case "vh":
return imaging.FlipH(imaging.FlipV(m))
// case "1":
// // Parse the EXIF data and perform a rotation automatically.
// // Pending support from https://github.com/golang/go/issues/4341
// return m
case "2":
return imaging.FlipH(m)
case "3":
return imaging.FlipV(imaging.FlipH(m))
case "4":
return imaging.FlipV(m)
case "5":
return imaging.Rotate90(imaging.FlipH(m))
case "6":
return imaging.Rotate270(m)
case "7":
return imaging.Rotate270(imaging.FlipH(m))
case "8":
return imaging.Rotate90(m)
default:
return m
}
}
//==============================================================================
// CropImage performs cropping operations based on the api described:
// https://docs.fastly.com/api/imageopto/crop
func CropImage(m image.Image, crop string) image.Image {
// This assumes that the crop string contains the following form:
// {width},{height}
// And will anchor it to the center point.
if wh := strings.Split(crop, ","); len(wh) == 2 {
width, err := strconv.Atoi(wh[0])
if err != nil {
return m
}
height, err := strconv.Atoi(wh[1])
if err != nil {
return m
}
return imaging.CropCenter(m, width, height)
}
return m
}
//==============================================================================
// GetResampleFilter gets the resample filter to use for resizing.
func GetResampleFilter(filter string) imaging.ResampleFilter {
switch filter {
case "lanczos":
return imaging.Lanczos
case "nearest":
return imaging.NearestNeighbor
case "linear":
return imaging.Linear
case "netravali":
return imaging.MitchellNetravali
case "box":
return imaging.Box
case "gaussian":
return imaging.Gaussian
default:
return imaging.Lanczos
}
}
//==============================================================================
// ResizeImage resizes the image with the given resample filter.
func ResizeImage(m image.Image, w, h string, filter imaging.ResampleFilter) image.Image {
// Resize the width if it was provided.
if w != "" {
if width, err := strconv.Atoi(w); err == nil {
return imaging.Resize(m, width, 0, filter)
}
}
// Resize the height if provided.
if h != "" {
if height, err := strconv.Atoi(h); err == nil {
return imaging.Resize(m, 0, height, filter)
}
}
return m
}
//==============================================================================
// Image transforms the image based on data found in the request. Following the
// available query params in the root README, this will parse the query params
// and apply image transformations.
func Image(m image.Image, v url.Values) (image.Image, error) {
// Extract the width + height from the image bounds.
width := m.Bounds().Max.X
height := m.Bounds().Max.Y
logrus.WithFields(logrus.Fields(map[string]interface{}{
"width": width,
"height": height,
})).Debug("image dimensions")
// Crop the image if the crop parameter was provided.
crop := v.Get("crop")
if crop != "" {
// Crop the image.
m = CropImage(m, crop)
}
// Resize the image if the width or height are provided.
w := v.Get("width")
h := v.Get("height")
if w != "" || h != "" {
// Get the resize filter to use.
filter := GetResampleFilter(v.Get("resize-filter"))
m = ResizeImage(m, w, h, filter)
}
// Reorient the image if the orientation parameter was provided.
orient := v.Get("orient")
if orient != "" {
// Rotate the image.
m = RotateImage(m, orient)
}
// Blur the image if the parameter was provided.
blur := v.Get("blur")
if blur != "" {
sigma, err := strconv.ParseFloat(blur, 64)
if err == nil && sigma > 0 {
m = imaging.Blur(m, sigma)
}
}
return m, nil
} | internal/image/transform/transform.go | 0.695028 | 0.481698 | transform.go | starcoder |
package placement
import (
"math"
"sort"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/pd/v4/pkg/slice"
"github.com/pingcap/pd/v4/server/core"
)
// RegionFit is the result of fitting a region's peers to rule list.
// All peers are divided into corresponding rules according to the matching
// rules, and the remaining Peers are placed in the OrphanPeers list.
type RegionFit struct {
RuleFits []*RuleFit
OrphanPeers []*metapb.Peer
}
// IsSatisfied returns if the rules are properly satisfied.
// It means all Rules are fulfilled and there is no orphan peers.
func (f *RegionFit) IsSatisfied() bool {
if len(f.RuleFits) == 0 {
return false
}
for _, r := range f.RuleFits {
if !r.IsSatisfied() {
return false
}
}
return len(f.OrphanPeers) == 0
}
// GetRuleFit returns the RuleFit that contains the peer.
func (f *RegionFit) GetRuleFit(peerID uint64) *RuleFit {
for _, rf := range f.RuleFits {
for _, p := range rf.Peers {
if p.GetId() == peerID {
return rf
}
}
}
return nil
}
// CompareRegionFit determines the superiority of 2 fits.
// It returns 1 when the first fit result is better.
func CompareRegionFit(a, b *RegionFit) int {
for i := range a.RuleFits {
if i >= len(b.RuleFits) {
break
}
if cmp := compareRuleFit(a.RuleFits[i], b.RuleFits[i]); cmp != 0 {
return cmp
}
}
switch {
case len(a.OrphanPeers) < len(b.OrphanPeers):
return 1
case len(a.OrphanPeers) > len(b.OrphanPeers):
return -1
default:
return 0
}
}
// RuleFit is the result of fitting status of a Rule.
type RuleFit struct {
Rule *Rule
// Peers of the Region that are divided to this Rule.
Peers []*metapb.Peer
// PeersWithDifferentRole is subset of `Peers`. It contains all Peers that have
// different Role from configuration (the Role can be migrated to target role
// by scheduling).
PeersWithDifferentRole []*metapb.Peer
// IsolationScore indicates at which level of labeling these Peers are
// isolated. A larger value is better.
IsolationScore float64
}
// IsSatisfied returns if the rule is properly satisfied.
func (f *RuleFit) IsSatisfied() bool {
return len(f.Peers) == f.Rule.Count && len(f.PeersWithDifferentRole) == 0
}
func compareRuleFit(a, b *RuleFit) int {
switch {
case len(a.Peers) < len(b.Peers):
return -1
case len(a.Peers) > len(b.Peers):
return 1
case len(a.PeersWithDifferentRole) > len(b.PeersWithDifferentRole):
return -1
case len(a.PeersWithDifferentRole) < len(b.PeersWithDifferentRole):
return 1
case a.IsolationScore < b.IsolationScore:
return -1
case a.IsolationScore > b.IsolationScore:
return 1
default:
return 0
}
}
// FitRegion tries to fit peers of a region to the rules.
func FitRegion(stores core.StoreSetInformer, region *core.RegionInfo, rules []*Rule) *RegionFit {
peers := prepareFitPeers(stores, region)
var regionFit RegionFit
if len(rules) == 0 {
return ®ionFit
}
for _, rule := range rules {
rf := fitRule(peers, rule)
regionFit.RuleFits = append(regionFit.RuleFits, rf)
// Remove selected.
peers = filterPeersBy(peers, func(p *fitPeer) bool {
return slice.NoneOf(rf.Peers, func(i int) bool { return rf.Peers[i].Id == p.Peer.Id })
})
}
for _, p := range peers {
regionFit.OrphanPeers = append(regionFit.OrphanPeers, p.Peer)
}
return ®ionFit
}
func fitRule(peers []*fitPeer, rule *Rule) *RuleFit {
// Ignore peers that does not match label constraints, and that cannot be
// transformed to expected role type.
peers = filterPeersBy(peers,
func(p *fitPeer) bool { return MatchLabelConstraints(p.store, rule.LabelConstraints) },
func(p *fitPeer) bool { return p.matchRoleLoose(rule.Role) })
if len(peers) <= rule.Count {
return newRuleFit(rule, peers)
}
// TODO: brute force can be improved.
var best *RuleFit
iterPeers(peers, rule.Count, func(candidates []*fitPeer) {
rf := newRuleFit(rule, candidates)
if best == nil || compareRuleFit(rf, best) > 0 {
best = rf
}
})
return best
}
func newRuleFit(rule *Rule, peers []*fitPeer) *RuleFit {
rf := &RuleFit{Rule: rule, IsolationScore: isolationScore(peers, rule.LocationLabels)}
for _, p := range peers {
rf.Peers = append(rf.Peers, p.Peer)
if !p.matchRoleStrict(rule.Role) {
rf.PeersWithDifferentRole = append(rf.PeersWithDifferentRole, p.Peer)
}
}
return rf
}
type fitPeer struct {
*metapb.Peer
store *core.StoreInfo
isLeader bool
}
func (p *fitPeer) matchRoleStrict(role PeerRoleType) bool {
switch role {
case Voter: // Voter matches either Leader or Follower.
return !p.IsLearner
case Leader:
return p.isLeader
case Follower:
return !p.IsLearner && !p.isLeader
case Learner:
return p.IsLearner
}
return false
}
func (p *fitPeer) matchRoleLoose(role PeerRoleType) bool {
// non-learner cannot become learner. All other roles can migrate to
// others by scheduling. For example, Leader->Follower, Learner->Leader
// are possible, but Voter->Learner is impossible.
return role != Learner || p.IsLearner
}
func prepareFitPeers(stores core.StoreSetInformer, region *core.RegionInfo) []*fitPeer {
var peers []*fitPeer
for _, p := range region.GetPeers() {
peers = append(peers, &fitPeer{
Peer: p,
store: stores.GetStore(p.GetStoreId()),
isLeader: region.GetLeader().GetId() == p.GetId(),
})
}
// Sort peers to keep the match result deterministic.
sort.Slice(peers, func(i, j int) bool { return peers[i].GetId() < peers[j].GetId() })
return peers
}
func filterPeersBy(peers []*fitPeer, preds ...func(*fitPeer) bool) (selected []*fitPeer) {
for _, p := range peers {
if slice.AllOf(preds, func(i int) bool { return preds[i](p) }) {
selected = append(selected, p)
}
}
return
}
// Iterate all combinations of select N peers from the list.
func iterPeers(peers []*fitPeer, n int, f func([]*fitPeer)) {
out := make([]*fitPeer, n)
iterPeersRecr(peers, 0, out, func() { f(out) })
}
func iterPeersRecr(peers []*fitPeer, index int, out []*fitPeer, f func()) {
for i := index; i <= len(peers)-len(out); i++ {
out[0] = peers[i]
if len(out) > 1 {
iterPeersRecr(peers, i+1, out[1:], f)
} else {
f()
}
}
}
func isolationScore(peers []*fitPeer, labels []string) float64 {
var score float64
if len(labels) == 0 || len(peers) <= 1 {
return 0
}
// NOTE: following loop is partially duplicated with `core.DistinctScore`.
// The reason not to call it directly is that core.DistinctScore only
// accepts `[]StoreInfo` not `[]*fitPeer` and I don't want alloc slice
// here because it is kind of hot path.
// After Go supports generics, we will be enable to do some refactor and
// reuse `core.DistinctScore`.
const replicaBaseScore = 100
for i, p1 := range peers {
for _, p2 := range peers[i+1:] {
if index := p1.store.CompareLocation(p2.store, labels); index != -1 {
score += math.Pow(replicaBaseScore, float64(len(labels)-index-1))
}
}
}
return score
} | server/schedule/placement/fit.go | 0.727395 | 0.434161 | fit.go | starcoder |
Package admission provides implementation for admission webhook and methods to implement admission webhook handlers.
The following snippet is an example implementation of mutating handler.
type Mutator struct {
client client.Client
decoder types.Decoder
}
func (m *Mutator) mutatePodsFn(ctx context.Context, pod *corev1.Pod) error {
// your logic to mutate the passed-in pod.
}
func (m *Mutator) Handle(ctx context.Context, req types.Request) types.Response {
pod := &corev1.Pod{}
err := m.decoder.Decode(req, pod)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}
// Do deepcopy before actually mutate the object.
copy := pod.DeepCopy()
err = m.mutatePodsFn(ctx, copy)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
return admission.PatchResponse(pod, copy)
}
// InjectClient is called by the Manager and provides a client.Client to the Mutator instance.
func (m *Mutator) InjectClient(c client.Client) error {
h.client = c
return nil
}
// InjectDecoder is called by the Manager and provides a types.Decoder to the Mutator instance.
func (m *Mutator) InjectDecoder(d types.Decoder) error {
h.decoder = d
return nil
}
The following snippet is an example implementation of validating handler.
type Handler struct {
client client.Client
decoder types.Decoder
}
func (v *Validator) validatePodsFn(ctx context.Context, pod *corev1.Pod) (bool, string, error) {
// your business logic
}
func (v *Validator) Handle(ctx context.Context, req types.Request) types.Response {
pod := &corev1.Pod{}
err := h.decoder.Decode(req, pod)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}
allowed, reason, err := h.validatePodsFn(ctx, pod)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
return admission.ValidationResponse(allowed, reason)
}
// InjectClient is called by the Manager and provides a client.Client to the Validator instance.
func (v *Validator) InjectClient(c client.Client) error {
h.client = c
return nil
}
// InjectDecoder is called by the Manager and provides a types.Decoder to the Validator instance.
func (v *Validator) InjectDecoder(d types.Decoder) error {
h.decoder = d
return nil
}
*/
package admission
import (
logf "sigs.k8s.io/controller-runtime/pkg/runtime/log"
)
var log = logf.KBLog.WithName("admission") | vendor/sigs.k8s.io/controller-runtime/pkg/webhook/admission/doc.go | 0.708818 | 0.482978 | doc.go | starcoder |
package cli
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
jmespath "github.com/danielgtaylor/go-jmespath-plus"
"github.com/rs/zerolog/log"
"gopkg.in/h2non/gentleman.v2/context"
)
// The following equality functions are from stretchr/testify/assert.
// objectsAreEqual determines if two objects are considered equal.
func objectsAreEqual(expected, actual interface{}) bool {
if expected == nil || actual == nil {
return expected == actual
}
exp, ok := expected.([]byte)
if !ok {
return reflect.DeepEqual(expected, actual)
}
act, ok := actual.([]byte)
if !ok {
return false
}
if exp == nil || act == nil {
return exp == nil && act == nil
}
return bytes.Equal(exp, act)
}
// ObjectsAreEqualValues gets whether two objects are equal, or if their
// values are equal.
func ObjectsAreEqualValues(expected, actual interface{}) bool {
if objectsAreEqual(expected, actual) {
return true
}
actualType := reflect.TypeOf(actual)
if actualType == nil {
return false
}
expectedValue := reflect.ValueOf(expected)
if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
// Attempt comparison after type conversion
return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
}
return false
}
// GetMatchValue returns a value for the given selector query.
func GetMatchValue(ctx *context.Context, selector string, reqParams map[string]interface{}, decoded interface{}) (interface{}, error) {
parts := strings.Split(selector, "#")
base := parts[0]
args := strings.Join(parts[1:], "#")
l := log.Debug().Str("selector", base)
if args != "" {
l = l.Str("query", args)
}
var actual interface{}
switch base {
case "request.param":
actual = reqParams[args]
case "request.body":
var decoded interface{}
if err := UnmarshalRequest(ctx, &decoded); err != nil {
return nil, err
}
result, err := jmespath.Search(args, decoded)
if err != nil {
return nil, err
}
actual = result
case "response.status":
actual = ctx.Response.StatusCode
case "response.header":
actual = ctx.Response.Header.Get(args)
case "response.body":
// Perform a JMESPath query to match the expected value.
result, err := jmespath.Search(args, decoded)
if err != nil {
return nil, err
}
actual = result
default:
return false, fmt.Errorf("Cannot match selector: %s", selector)
}
l.Interface("actual", actual).Msg("Found matcher value")
return actual, nil
}
// Match returns `true` if the expected value of the match type is found in the
// given response data.
func Match(test string, expected json.RawMessage, actual interface{}) (bool, error) {
var exp interface{}
if err := json.Unmarshal(expected, &exp); err != nil {
return false, err
}
var matches bool
switch test {
case "equal":
if ObjectsAreEqualValues(exp, actual) {
matches = true
}
case "notEqual":
if !ObjectsAreEqualValues(exp, actual) {
matches = true
}
case "any":
if list, ok := actual.([]interface{}); ok {
// We have a list of items, so at least one must match.
matches = false
for _, item := range list {
if ObjectsAreEqualValues(exp, item) {
matches = true
break
}
}
} else {
return false, fmt.Errorf("Expected a list but got: %v", actual)
}
case "all":
if list, ok := actual.([]interface{}); ok {
// We have a list of items, so each one must match the expected value.
matches = true
for _, item := range list {
if !ObjectsAreEqualValues(exp, item) {
matches = false
break
}
}
} else {
return false, fmt.Errorf("Expected a list but got: %v", actual)
}
default:
return false, fmt.Errorf("Unknown test: %s", test)
}
l := log.Debug().Str("test", test).Interface("expected", exp).Interface("actual", actual)
if matches {
l.Msg("Found match")
} else {
l.Msg("No match")
}
return matches, nil
} | cli/matcher.go | 0.728845 | 0.533762 | matcher.go | starcoder |
package plt
import (
"bytes"
"github.com/cpmech/gosl/io"
)
// The A structure holds arguments to configure plots, including style data for shapes (e.g. polygons)
type A struct {
// plot and basic options
C string // color
A float64 // transparency coefficient
M string // marker
Ls string // linestyle
Lw float64 // linewidth; -1 => default
Ms int // marker size; -1 => default
L string // label
Me int // mark-every; -1 => default
Z int // z-order
Mec string // marker edge color
Mew float64 // marker edge width
Void bool // void marker => markeredgecolor='C', markerfacecolor='none'
NoClip bool // turn clipping off
// shapes
Fc string // shapes: face color
Ec string // shapes: edge color
Scale float64 // shapes: scale information
Style string // shapes: style information
Closed bool // shapes: closed shape
// text and extra arguments
Ha string // horizontal alignment; e.g. 'center'
Va string // vertical alignment; e.g. 'center'
Rot float64 // rotation
Fsz float64 // font size
FszLbl float64 // font size of labels
FszLeg float64 // font size of legend
FszXtck float64 // font size of x-ticks
FszYtck float64 // font size of y-ticks
FontSet string // font set: e.g. 'stix', 'stixsans' [default]
HideL bool // hide left frame border
HideR bool // hide right frame border
HideB bool // hide bottom frame border
HideT bool // hide top frame border
// other options
AxCoords bool // the given x-y coordinates correspond to axes coords
FigCoords bool // the given x-y coordinates correspond to figure coords
// legend
LegLoc string // legend: location. e.g.: right, center left, upper right, lower right, best, center, lower left, center right, upper left, upper center, lower center
LegNcol int // legend: number of columns
LegHlen float64 // legend: handle length
LegFrame bool // legend: frame on
LegOut bool // legend: outside
LegOutX []float64 // legend: normalised coordinates to put legend outside frame
// colors for contours or histograms
Colors []string // contour or histogram: colors
// contours
Nlevels int // contour: number of levels (overridden by Levels when it's not nil)
Levels []float64 // contour: levels (may be nil)
CmapIdx int // contour: colormap index
NumFmt string // contour: number format; e.g. "%g" or "%.2f"
NoLines bool // contour: do not add lines on top of filled contour
NoLabels bool // contour: do not add labels
NoInline bool // contour: do not draw labels 'inline'
NoCbar bool // contour: do not add colorbar
CbarLbl string // contour: colorbar label
SelectV float64 // contour: selected value
SelectC string // contour: color to mark selected level. empty means no selected line
SelectLw float64 // contour: zero level linewidth
// 3d graphs
Rstride int // 3d: row stride
Cstride int // 3d: column stride
Surf bool // 3d: generate surface
Wire bool // 3d: generate wireframe
// histograms
Type string // histogram: type; e.g. "bar"
Stacked bool // histogram: stacked
NoFill bool // histogram: do not fill bars
Nbins int // histogram: number of bins
Normed bool // histogram: normed
// figures
Dpi int // figure: dpi to be used when saving figure. default = 96
Png bool // figure: save png file
Eps bool // figure: save eps file
Prop float64 // figure: proportion: height = width * prop
WidthPt float64 // figure: width in points. Get this from LaTeX using \showthe\columnwidth
}
// String returns a string representation of arguments
func (o A) String(forHistogram, for3dPoints bool) (l string) {
// fix color if Void==true
if o.Void && o.C == "" {
o.C = "red"
}
// plot and basic options
if for3dPoints {
addToCmd(&l, o.Ms > 0, io.Sf("s=%d", o.Ms))
addToCmd(&l, o.Mec != "", io.Sf("edgecolor='%s'", o.Mec))
if o.Void {
addToCmd(&l, o.Void, "c='none'")
} else {
addToCmd(&l, o.C != "", io.Sf("c='%s'", o.C))
}
addToCmd(&l, o.Void && o.Mec == "", io.Sf("edgecolor='%s'", o.C))
} else {
addToCmd(&l, o.C != "", io.Sf("color='%s'", o.C))
addToCmd(&l, o.Ms > 0, io.Sf("ms=%d", o.Ms))
addToCmd(&l, o.Mec != "", io.Sf("markeredgecolor='%s'", o.Mec))
addToCmd(&l, o.Void, "markerfacecolor='none'")
addToCmd(&l, o.Void && o.Mec == "", io.Sf("markeredgecolor='%s'", o.C))
addToCmd(&l, o.Mew > 0, io.Sf("mew=%g", o.Mew))
}
addToCmd(&l, o.A > 0, io.Sf("alpha=%g", o.A))
addToCmd(&l, o.M != "", io.Sf("marker='%s'", o.M))
addToCmd(&l, o.Ls != "", io.Sf("linestyle='%s'", o.Ls))
addToCmd(&l, o.Lw > 0, io.Sf("lw=%g", o.Lw))
addToCmd(&l, o.L != "", io.Sf("label='%s'", o.L))
addToCmd(&l, o.Me > 0, io.Sf("markevery=%d", o.Me))
addToCmd(&l, o.Z > 0, io.Sf("zorder=%d", o.Z))
addToCmd(&l, o.NoClip, "clip_on=0")
addToCmd(&l, o.AxCoords, "transform=plt.gca().transAxes")
// shapes
addToCmd(&l, o.Fc != "", io.Sf("facecolor='%s'", o.Fc))
addToCmd(&l, o.Ec != "", io.Sf("edgecolor='%s'", o.Ec))
// text and extra arguments
addToCmd(&l, o.Ha != "", io.Sf("ha='%s'", o.Ha))
addToCmd(&l, o.Va != "", io.Sf("va='%s'", o.Va))
addToCmd(&l, o.Rot > 0, io.Sf("rotation=%g", o.Rot))
addToCmd(&l, o.Fsz > 0, io.Sf("fontsize=%g", o.Fsz))
// histograms
if forHistogram {
addToCmd(&l, len(o.Colors) > 0, io.Sf("color=%s", strings2list(o.Colors)))
addToCmd(&l, len(o.Type) > 0, io.Sf("histtype='%s'", o.Type))
addToCmd(&l, o.Stacked, "stacked=1")
addToCmd(&l, o.NoFill, "fill=0")
addToCmd(&l, o.Nbins > 0, io.Sf("bins=%d", o.Nbins))
addToCmd(&l, o.Normed, "normed=1")
}
return
}
// addToCmd adds new option to list of commands separated with commas
func addToCmd(line *string, condition bool, delta string) {
if condition {
if len(*line) > 0 {
*line += ","
}
*line += delta
}
}
// updateBufferFirstArgsAndClose updates buffer with the first arguments and close with ")\n"
func updateBufferFirstArgsAndClose(buf *bytes.Buffer, args *A, forHistogram, for3dPoints bool) {
if buf == nil {
return
}
if args == nil {
io.Ff(buf, ")\n")
return
}
txt := args.String(forHistogram, for3dPoints)
if txt == "" {
io.Ff(buf, ")\n")
return
}
io.Ff(buf, txt+")\n")
}
// updateBufferWithArgsAndClose updates buffer with arguments and close with ")\n".
func updateBufferAndClose(buf *bytes.Buffer, args *A, forHistogram, for3dPoints bool) {
if buf == nil {
return
}
if args == nil {
io.Ff(buf, ")\n")
return
}
txt := args.String(forHistogram, for3dPoints)
if txt == "" {
io.Ff(buf, ")\n")
return
}
io.Ff(buf, ", "+txt+")\n")
}
// floats2list converts slice of floats to string representing a Python list
func floats2list(vals []float64) (l string) {
l = "["
for i, v := range vals {
if i > 0 {
l += ","
}
l += io.Sf("%g", v)
}
l += "]"
return
}
// strings2list converts slice of strings to string representing a Python list
func strings2list(vals []string) (l string) {
l = "["
for i, v := range vals {
if i > 0 {
l += ","
}
l += io.Sf("'%s'", v)
}
l += "]"
return
}
// getHideList returns a string representing the "spines-to-remove" list in Python
func getHideList(args *A) (l string) {
if args == nil {
return
}
if args.HideL || args.HideR || args.HideB || args.HideT {
c := ""
addToCmd(&c, args.HideL, "'left'")
addToCmd(&c, args.HideR, "'right'")
addToCmd(&c, args.HideB, "'bottom'")
addToCmd(&c, args.HideT, "'top'")
l = "[" + c + "]"
}
return
}
// argsLeg returns legend arguments
func argsLeg(args *A) (loc string, ncol int, hlen, fsz float64, frame int, out int, outX string) {
loc = "'best'"
ncol = 1
hlen = 3.0
fsz = 8.0
frame = 0
out = 0
outX = "[0.0, 1.02, 1.0, 0.102]"
if args == nil {
return
}
if args.LegLoc != "" {
loc = io.Sf("'%s'", args.LegLoc)
}
if args.LegNcol > 0 {
ncol = args.LegNcol
}
if args.LegHlen > 0 {
hlen = args.LegHlen
}
if args.FszLeg > 0 {
fsz = args.FszLeg
}
if args.LegFrame {
frame = 1
}
if args.LegOut {
out = 1
}
if len(args.LegOutX) == 4 {
outX = io.Sf("[%g, %g, %g, %g]", args.LegOutX[0], args.LegOutX[1], args.LegOutX[2], args.LegOutX[3])
}
return
}
// argsFsz allocates args if nil, and sets default fontsizes
func argsFsz(args *A) (txt, lbl, leg, xtck, ytck float64, fontset string) {
txt, lbl, leg, xtck, ytck, fontset = 11, 10, 9, 8, 8, "stixsans"
if args == nil {
return
}
if args.Fsz > 0 {
txt = args.Fsz
}
if args.FszLbl > 0 {
lbl = args.FszLbl
}
if args.FszLeg > 0 {
leg = args.FszLeg
}
if args.FszXtck > 0 {
xtck = args.FszXtck
}
if args.FszYtck > 0 {
ytck = args.FszYtck
}
if args.FontSet != "" {
fontset = args.FontSet
}
return
}
// argsFigsize returns figure size data. Defaults are selected if args == nil
func argsFigData(args *A) (figType string, dpi, width, height int) {
figType, dpi = "png", 150
prop := 0.75
widthPt := 400.0
if args != nil {
if args.Dpi > 0 {
dpi = args.Dpi
}
if args.Eps {
figType = "eps"
}
if args.Prop > 0 {
prop = args.Prop
}
if args.WidthPt > 0 {
widthPt = args.WidthPt
}
}
w := widthPt / 72.27 // width in inches
h := w * prop
width, height = int(w), int(h)
return
}
// argsWireSurf collects arguments for Wireframe or Surface
func argsWireSurf(args *A, surf bool) (l string) {
if args != nil {
if surf {
if args.C == "" {
l += io.Sf(",cmap=getCmap(%d)", args.CmapIdx)
}
}
if args.Rstride < 1 {
args.Rstride = 1
}
if args.Rstride > 0 {
l += io.Sf(",rstride=%d", args.Rstride)
}
if args.Cstride < 1 {
args.Cstride = 1
}
if args.Cstride > 0 {
l += io.Sf(",cstride=%d", args.Cstride)
}
}
return
}
// argsContour allocates args if nil, sets default parameters, and return formatted arguments
func argsContour(in *A, Z [][]float64) (out *A, colors, levels string) {
out = in
if out == nil {
out = new(A)
}
if out.NumFmt == "" {
out.NumFmt = "%g"
}
if out.SelectLw < 0.01 {
out.SelectLw = 3.0
}
if out.Lw < 0.01 {
out.Lw = 1.0
}
if out.Fsz < 0.01 {
out.Fsz = 8.0
}
if len(out.Colors) > 0 {
colors = io.Sf(",colors=%s", strings2list(out.Colors))
} else {
colors = io.Sf(",cmap=getCmap(%d)", out.CmapIdx)
}
if len(out.Levels) > 0 {
levels = io.Sf(",levels=%s", floats2list(out.Levels))
} else {
if out.Nlevels > 1 {
levels = ",levels=" + getContourLevels(out.Nlevels, Z)
}
}
return
}
// getContourLevels computes the list of levels based on min and max values in Z
// Note: the search for min and max is not very efficient for very large matrix
func getContourLevels(nlevels int, Z [][]float64) (l string) {
if nlevels < 2 {
return
}
if len(Z) < 1 {
return
}
if len(Z[0]) < 1 {
return
}
minZ, maxZ := Z[0][0], Z[0][0]
for i := 0; i < len(Z); i++ {
for j := 0; j < len(Z[i]); j++ {
if Z[i][j] < minZ {
minZ = Z[i][j]
}
if Z[i][j] > maxZ {
maxZ = Z[i][j]
}
}
}
delZ := (maxZ - minZ) / float64(nlevels-1)
l = "["
for i := 0; i < nlevels; i++ {
if i > 0 {
l += ","
}
l += io.Sf("%g", minZ+float64(i)*delZ)
}
l += "]"
return
}
// pyBool converts Go bool to Python bool
func pyBool(flag bool) int {
if flag {
return 1
}
return 0
} | plt/arguments.go | 0.505127 | 0.416144 | arguments.go | starcoder |
package fmom
import (
"math"
)
type EEtaPhiM [4]float64
func NewEEtaPhiM(et, eta, phi, m float64) EEtaPhiM {
return EEtaPhiM([4]float64{et, eta, phi, m})
}
func (p4 *EEtaPhiM) Clone() P4 {
pp := *p4
return &pp
}
func (p4 *EEtaPhiM) E() float64 {
return p4[0]
}
func (p4 *EEtaPhiM) Eta() float64 {
return p4[1]
}
func (p4 *EEtaPhiM) Phi() float64 {
return p4[2]
}
func (p4 *EEtaPhiM) M() float64 {
return p4[3]
}
func (p4 *EEtaPhiM) M2() float64 {
m := p4.M()
return m * m
}
func (p4 *EEtaPhiM) P() float64 {
m := p4.M()
e := p4.E()
if m == 0 {
return e
}
sign := 1.0
if e < 0 {
sign = -1.0
}
return sign * math.Sqrt(e*e-m*m)
}
func (p4 *EEtaPhiM) P2() float64 {
m := p4.M()
e := p4.E()
return e*e - m*m
}
func (p4 *EEtaPhiM) CosPhi() float64 {
phi := p4.Phi()
return math.Cos(phi)
}
func (p4 *EEtaPhiM) SinPhi() float64 {
phi := p4.Phi()
return math.Sin(phi)
}
func (p4 *EEtaPhiM) TanTh() float64 {
eta := p4.Eta()
abseta := math.Abs(eta)
// avoid numeric overflow if very large eta
if abseta > 710 {
if eta > 0 {
eta = +710
} else {
eta = -710
}
}
return 1. / math.Sinh(eta)
}
func (p4 *EEtaPhiM) CotTh() float64 {
eta := p4.Eta()
return math.Sinh(eta)
}
func (p4 *EEtaPhiM) CosTh() float64 {
eta := p4.Eta()
return math.Tanh(eta)
}
func (p4 *EEtaPhiM) SinTh() float64 {
eta := p4.Eta()
abseta := math.Abs(eta)
if abseta > 710 {
abseta = 710
}
return 1 / math.Cosh(abseta)
}
func (p4 *EEtaPhiM) Pt() float64 {
p := p4.P()
sinth := p4.SinTh()
return p * sinth
}
func (p4 *EEtaPhiM) Et() float64 {
e := p4.E()
sinth := p4.SinTh()
return e * sinth
}
func (p4 *EEtaPhiM) IPt() float64 {
pt := p4.Pt()
return 1 / pt
}
func (p4 *EEtaPhiM) Rapidity() float64 {
e := p4.E()
pz := p4.Pz()
return 0.5 * math.Log((e+pz)/(e-pz))
}
func (p4 *EEtaPhiM) Px() float64 {
pt := p4.Pt()
cosphi := p4.CosPhi()
return pt * cosphi
}
func (p4 *EEtaPhiM) Py() float64 {
pt := p4.Pt()
sinphi := p4.SinPhi()
return pt * sinphi
}
func (p4 *EEtaPhiM) Pz() float64 {
p := p4.P()
costh := p4.CosTh()
return p * costh
}
func (p4 *EEtaPhiM) Set(p P4) {
p4[0] = p.E()
p4[1] = p.Eta()
p4[2] = p.Phi()
p4[3] = p.M()
} | fmom/eetaphim.go | 0.710528 | 0.422862 | eetaphim.go | starcoder |
package make_geoimage
import (
"github.com/skyhookml/skyhookml/skyhook"
"github.com/skyhookml/skyhookml/exec_ops"
gomapinfer "github.com/mitroadmaps/gomapinfer/common"
geocoords "github.com/mitroadmaps/gomapinfer/googlemaps"
"github.com/paulmach/go.geojson"
"encoding/json"
"fmt"
"log"
"math"
"runtime"
)
const GeoImageScale int = 256
type Params struct {
Source struct {
// Either "url" or "dataset"
Mode string
// Only set if Mode is "url".
URL string
Zoom int
}
// Specifies how we should determine what images to capture.
// One of "dense" or "geojson".
CaptureMode string
// Image dimensions.
// If CaptureMode is "geojson" and ImageDims are 0, then width/height is based on
// the size of the GeoJSON object.
ImageDims [2]int
// If CaptureMode is "dense", specifies the bounding box to densely cover.
Bbox [4]float64
// If CaptureMode is GeoJSON, specifies how we should build images around GeoJSON objects.
// One of "centered-all", "centered-disjoint", or "tiles".
ObjectMode string
// If ObjectMode == "tiles", Buffer is padding around GeoJSON objects that should be covered by tiles.
Buffer int
// Whether we should download images immediately or defer until the image is needed.
Materialize bool
}
type TaskMetadata struct {
GeoImageMetadata skyhook.GeoImageMetadata
}
// Get GeoImageMetadata for params.CaptureMode=="dense".
// In the metadata, only Zoom, X, Y, Offset, Width, and Height are set.
func GetDenseMetadatas(params Params) []skyhook.GeoImageMetadata {
startTile := geocoords.LonLatToMapboxTile(gomapinfer.Point{params.Bbox[0], params.Bbox[1]}, params.Source.Zoom)
endTile := geocoords.LonLatToMapboxTile(gomapinfer.Point{params.Bbox[2], params.Bbox[3]}, params.Source.Zoom)
if startTile[0] > endTile[0] {
startTile[0], endTile[0] = endTile[0], startTile[0]
}
if startTile[1] > endTile[1] {
startTile[1], endTile[1] = endTile[1], startTile[1]
}
log.Printf("[make_geoimage] adding tiles from %v to %v", startTile, endTile)
var metadatas []skyhook.GeoImageMetadata
for i := startTile[0]; i <= endTile[0]; i++ {
for j := startTile[1]; j <= endTile[1]; j++ {
metadatas = append(metadatas, skyhook.GeoImageMetadata{
Zoom: params.Source.Zoom,
X: i,
Y: j,
Width: GeoImageScale,
Height: GeoImageScale,
})
}
}
return metadatas
}
// Get GeoImageMetadata for params.CaptureMode=="geojson" with ObjectMode=="centered-all" or "centered-disjoint".
// This creates images that are centered at each geojson object.
// In the metadata, only Zoom, X, Y, Offset, Width, and Height are set.
func GetGeojsonCenteredMetadatas(params Params, geometries []*geojson.Geometry) []skyhook.GeoImageMetadata {
disjoint := params.ObjectMode == "centered-disjoint"
zoom := params.Source.Zoom
// We keep track of all Web-Mercator tiles that the images so far have intersected.
// This way we can avoid adding overlapping tiles, if disjoint is set.
seen := make(map[[2]int]bool)
var metadatas []skyhook.GeoImageMetadata
for _, g := range geometries {
bbox := skyhook.GetGeometryBbox(g)
var metadata skyhook.GeoImageMetadata
if params.ImageDims == [2]int{0, 0} {
// The dimensions are based on the bbox size.
tile := geocoords.LonLatToMapboxTile(bbox.Min, zoom)
offset1 := geocoords.LonLatToMapbox(bbox.Min, zoom, tile)
offset2 := geocoords.LonLatToMapbox(bbox.Max, zoom, tile)
// Make offset1 the smaller of the two.
if offset1.X > offset2.X {
offset1.X, offset2.X = offset2.X, offset1.X
}
if offset1.Y > offset2.Y {
offset1.Y, offset2.Y = offset2.Y, offset1.Y
}
metadata = skyhook.GeoImageMetadata{
Zoom: zoom,
X: tile[0],
Y: tile[1],
Offset: [2]int{int(offset1.X), int(offset1.Y)},
Width: int(offset2.X-offset1.X),
Height: int(offset2.Y-offset1.Y),
}
} else {
// Fixed size bbox.
bboxCenter := bbox.Center()
centerTile := geocoords.LonLatToMapboxTile(bboxCenter, zoom)
centerOffset := geocoords.LonLatToMapbox(bboxCenter, zoom, centerTile)
metadata = skyhook.GeoImageMetadata{
Zoom: zoom,
X: centerTile[0],
Y: centerTile[1],
Offset: [2]int{int(centerOffset.X) - params.ImageDims[0]/2, int(centerOffset.Y) - params.ImageDims[1]/2},
Width: params.ImageDims[0],
Height: params.ImageDims[1],
}
}
if disjoint {
// Compute tile offsets from metadata.X/Y where the image starts and ends.
// This way we can get list of WebMercator tiles that intersect this image.
startOffset := [2]int{
skyhook.FloorDiv(metadata.Offset[0], GeoImageScale),
skyhook.FloorDiv(metadata.Offset[1], GeoImageScale),
}
endOffset := [2]int{
skyhook.FloorDiv(metadata.Offset[0]+metadata.Width-1, GeoImageScale),
skyhook.FloorDiv(metadata.Offset[1]+metadata.Height-1, GeoImageScale),
}
var needed [][2]int
for i := startOffset[0]; i <= endOffset[0]; i++ {
for j := startOffset[1]; j <= endOffset[1]; j++ {
needed = append(needed, [2]int{i, j})
}
}
skip := false
for _, tile := range needed {
if seen[tile] {
skip = true
break
}
}
if skip {
continue
}
for _, tile := range needed {
seen[tile] = true
}
}
metadatas = append(metadatas, metadata)
}
return metadatas
}
// Get GeoImageMetadata for params.CaptureMode=="geojson" with ObjectMode=="tiles".
// This captures WebMercator tiles of a fixed size that intersect a GeoJSON object.
// In the metadata, only Zoom, X, Y, Offset, Width, and Height are set.
func GetGeojsonTilesMetadatas(params Params, geometries []*geojson.Geometry) []skyhook.GeoImageMetadata {
var zoom int = params.Source.Zoom
var shapeBuffer int = params.Buffer
// Compute the bounding box of all the geometries.
var geometriesBBox gomapinfer.Rectangle = gomapinfer.EmptyRectangle
for _, g := range geometries {
bbox := skyhook.GetGeometryBbox(g)
geometriesBBox = geometriesBBox.Extend(bbox.Min).Extend(bbox.Max)
}
// Grid partition
startTile := geocoords.LonLatToMapboxTile(geometriesBBox.Min, zoom)
endTile := geocoords.LonLatToMapboxTile(geometriesBBox.Max, zoom)
if startTile[0] > endTile[0] {
startTile[0], endTile[0] = endTile[0], startTile[0]
}
if startTile[1] > endTile[1] {
startTile[1], endTile[1] = endTile[1], startTile[1]
}
log.Printf("[spatialflow_partition] checking candidate tiles from %v to %v", startTile, endTile)
buffer := float64(shapeBuffer) / 256.0
bufferTiles := int(math.Ceil(buffer))
corner1 := gomapinfer.Point{0.0 - buffer, 0.0 - buffer}
corner2 := gomapinfer.Point{1.0 + buffer, 0.0 - buffer}
corner3 := gomapinfer.Point{1.0 + buffer, 1.0 + buffer}
corner4 := gomapinfer.Point{0.0 - buffer, 1.0 + buffer}
corners := [4]gomapinfer.Point{corner1, corner2, corner3, corner4}
var total_tiles int = 0
var kept_tiles int = 0
var metadatas []skyhook.GeoImageMetadata
// TODO: This is a O(n^2) implementation. Should improve it by using spatial index.
for i := startTile[0] - bufferTiles; i <= endTile[0] + bufferTiles; i++ {
for j := startTile[1] - bufferTiles; j <= endTile[1] + bufferTiles; j++ {
total_tiles += 1
p1 := geocoords.MapboxToLonLat(gomapinfer.Point{0,0}, zoom, [2]int{i,j})
p2 := geocoords.MapboxToLonLat(gomapinfer.Point{0,0}, zoom, [2]int{i+1,j+1})
toRelativePixelCoordinate := func(coordinate []float64) gomapinfer.Point {
var point gomapinfer.Point
point.X = (coordinate[0] - p1.X) / (p2.X - p1.X)
point.Y = (coordinate[1] - p1.Y) / (p2.Y - p1.Y)
return point
}
isOverlapped := false
// Check if the tile overlaps (consider the buffer) with the ROI (different shapes)
handlePoint := func(coordinate []float64) {
p := toRelativePixelCoordinate(coordinate)
if p.X >= -buffer && p.X <= 1.0 + buffer && p.Y >= -buffer && p.Y <= 1.0 + buffer {
isOverlapped = true
}
}
handleLineString := func(coordinates [][]float64) {
for _, coordinate := range coordinates {
p := toRelativePixelCoordinate(coordinate)
if p.X >= -buffer && p.X <= 1.0 + buffer && p.Y >= -buffer && p.Y <= 1.0 + buffer {
isOverlapped = true
}
}
if isOverlapped {
return
}
for ind, _ := range coordinates {
if ind == len(coordinates)-1 {
break
}
p1 := toRelativePixelCoordinate(coordinates[ind])
p2 := toRelativePixelCoordinate(coordinates[ind+1])
segment := gomapinfer.Segment{p1,p2}
if segment.Intersection(gomapinfer.Segment{corner1, corner2}) != nil {
isOverlapped = true
return
}
if segment.Intersection(gomapinfer.Segment{corner2, corner3}) != nil {
isOverlapped = true
return
}
if segment.Intersection(gomapinfer.Segment{corner3, corner4}) != nil {
isOverlapped = true
return
}
if segment.Intersection(gomapinfer.Segment{corner4, corner1}) != nil {
isOverlapped = true
return
}
}
}
handlePolygon := func(coordinates [][][]float64) {
// We do not support holes yet, so just use coordinates[0].
// coordinates[0] is the exterior ring while coordinates[1:] specify
// holes in the polygon that should be excluded.
handleLineString(coordinates[0])
if isOverlapped {
return
}
var polygon gomapinfer.Polygon
for _, coordinate := range coordinates[0] {
p := toRelativePixelCoordinate(coordinate)
polygon = append(polygon, p)
}
for _, corner := range corners {
if polygon.Contains(corner) {
isOverlapped = true
return
}
}
}
for _, g := range geometries {
if g.Type == geojson.GeometryPoint {
handlePoint(g.Point)
} else if g.Type == geojson.GeometryMultiPoint {
for _, coordinate := range g.MultiPoint {
handlePoint(coordinate)
}
} else if g.Type == geojson.GeometryLineString {
handleLineString(g.LineString)
} else if g.Type == geojson.GeometryMultiLineString {
for _, coordinates := range g.MultiLineString {
handleLineString(coordinates)
}
} else if g.Type == geojson.GeometryPolygon {
handlePolygon(g.Polygon)
} else if g.Type == geojson.GeometryMultiPolygon {
for _, coordinates := range g.MultiPolygon {
handlePolygon(coordinates)
}
}
if isOverlapped {
break
}
}
// If the current tile doesn't overlap with the ROI, skip it.
if !isOverlapped {
continue
}
metadatas = append(metadatas, skyhook.GeoImageMetadata{
Zoom: zoom,
X: i,
Y: j,
Width: GeoImageScale,
Height: GeoImageScale,
})
kept_tiles += 1
}
}
log.Printf("[spatialflow_partition] found %d tiles overlapping with the ROI from %d tiles", kept_tiles, total_tiles)
return metadatas
}
func GetGeojsonMetadatas(params Params, allItems map[string][][]skyhook.Item) ([]skyhook.GeoImageMetadata, error) {
// Load all GeoJSON geometries.
// Note that we do this in the GetTasks call, since we want to parallelize the
// image download/extraction execution (in the case that params.Materialize is set).
var geometries []*geojson.Geometry
addFeatures := func(collection *geojson.FeatureCollection) {
var q []*geojson.Geometry
for _, feature := range collection.Features {
if feature.Geometry == nil {
continue
}
q = append(q, feature.Geometry)
}
for len(q) > 0 {
geometry := q[len(q)-1]
q = q[0:len(q)-1]
if geometry.Type != geojson.GeometryCollection {
geometries = append(geometries, geometry)
continue
}
// collection geometry, need to add all its children
q = append(q, geometry.Geometries...)
}
}
for _, itemList := range allItems["geojson"] {
for _, item := range itemList {
data, _, err := item.LoadData()
if err != nil {
return nil, err
}
addFeatures(data.(*geojson.FeatureCollection))
}
}
if params.ObjectMode == "centered-all" || params.ObjectMode == "centered-disjoint" {
return GetGeojsonCenteredMetadatas(params, geometries), nil
} else if params.ObjectMode == "tiles" {
return GetGeojsonTilesMetadatas(params, geometries), nil
}
return nil, fmt.Errorf("unknown object mode %s", params.ObjectMode)
}
func GetTasks(node skyhook.Runnable, allItems map[string][][]skyhook.Item) ([]skyhook.ExecTask, error) {
var params Params
err := json.Unmarshal([]byte(node.Params), ¶ms)
if err != nil {
return nil, fmt.Errorf("node has not been configured: %v", err)
}
var metadatas []skyhook.GeoImageMetadata
if params.CaptureMode == "dense" {
metadatas = GetDenseMetadatas(params)
} else if params.CaptureMode == "geojson" {
var err error
metadatas, err = GetGeojsonMetadatas(params, allItems)
if err != nil {
return nil, err
}
}
var tasks []skyhook.ExecTask
for i, metadata := range metadatas {
var key string
if metadata.Offset == [2]int{0, 0} && metadata.Width == GeoImageScale && metadata.Height == GeoImageScale {
key = fmt.Sprintf("%d_%d_%d", metadata.Zoom, metadata.X, metadata.Y)
} else {
key = fmt.Sprintf("%d", i)
}
metadata.ReferenceType = "webmercator"
metadata.Scale = 256
metadata.SourceType = "url"
metadata.URL = params.Source.URL
tasks = append(tasks, skyhook.ExecTask{
Key: key,
Metadata: string(skyhook.JsonMarshal(TaskMetadata{metadata})),
})
}
return tasks, nil
}
type Op struct {
URL string
Params Params
Dataset skyhook.Dataset
}
func (e *Op) Parallelism() int {
return runtime.NumCPU()
}
func (e *Op) Apply(task skyhook.ExecTask) error {
// TODO: add support for Materialize.
var metadata TaskMetadata
skyhook.JsonUnmarshal([]byte(task.Metadata), &metadata)
return exec_ops.WriteItem(e.URL, e.Dataset, task.Key, nil, metadata.GeoImageMetadata)
}
func (e *Op) Close() {}
func init() {
skyhook.AddExecOpImpl(skyhook.ExecOpImpl{
Config: skyhook.ExecOpConfig{
ID: "make_geoimage",
Name: "Make Geo-Image Dataset",
Description: "Create a Geo-Image dataset by fetching tiles from a URL",
},
GetInputs: func(rawParams string) []skyhook.ExecInput {
var params Params
err := json.Unmarshal([]byte(rawParams), ¶ms)
if err != nil {
// can't do anything if node isn't configured yet
return nil
}
if params.CaptureMode == "geojson" {
return []skyhook.ExecInput{{
Name: "geojson",
DataTypes: []skyhook.DataType{skyhook.GeoJsonType},
Variable: true,
}}
}
return nil
},
Outputs: []skyhook.ExecOutput{{Name: "geoimages", DataType: skyhook.GeoImageType}},
Requirements: func(node skyhook.Runnable) map[string]int {
return nil
},
GetTasks: GetTasks,
Prepare: func(url string, node skyhook.Runnable) (skyhook.ExecOp, error) {
var params Params
if err := exec_ops.DecodeParams(node, ¶ms, false); err != nil {
return nil, err
}
return &Op{
URL: url,
Params: params,
Dataset: node.OutputDatasets["geoimages"],
}, nil
},
ImageName: "skyhookml/basic",
})
} | exec_ops/make_geoimage/make_geoimage.go | 0.653459 | 0.400691 | make_geoimage.go | starcoder |
package benchmark
import (
"reflect"
"testing"
)
func isRunnableCalibrated(runnable func()) bool {
return isCalibrated(reflect.Invalid, reflect.Invalid, reflect.ValueOf(runnable).Pointer())
}
func isBoolSupplierCalibrated(supplier func() bool) bool {
return isCalibrated(reflect.Invalid, reflect.Bool, reflect.ValueOf(supplier).Pointer())
}
func isIntSupplierCalibrated(supplier func() int) bool {
return isCalibrated(reflect.Invalid, reflect.Int, reflect.ValueOf(supplier).Pointer())
}
func isInt8SupplierCalibrated(supplier func() int8) bool {
return isCalibrated(reflect.Invalid, reflect.Int8, reflect.ValueOf(supplier).Pointer())
}
func isInt16SupplierCalibrated(supplier func() int16) bool {
return isCalibrated(reflect.Invalid, reflect.Int16, reflect.ValueOf(supplier).Pointer())
}
func isInt32SupplierCalibrated(supplier func() int32) bool {
return isCalibrated(reflect.Invalid, reflect.Int32, reflect.ValueOf(supplier).Pointer())
}
func isInt64SupplierCalibrated(supplier func() int64) bool {
return isCalibrated(reflect.Invalid, reflect.Int64, reflect.ValueOf(supplier).Pointer())
}
func isUintSupplierCalibrated(supplier func() uint) bool {
return isCalibrated(reflect.Invalid, reflect.Uint, reflect.ValueOf(supplier).Pointer())
}
func isUint8SupplierCalibrated(supplier func() uint8) bool {
return isCalibrated(reflect.Invalid, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
func isUint16SupplierCalibrated(supplier func() uint16) bool {
return isCalibrated(reflect.Invalid, reflect.Uint16, reflect.ValueOf(supplier).Pointer())
}
func isUint32SupplierCalibrated(supplier func() uint32) bool {
return isCalibrated(reflect.Invalid, reflect.Uint32, reflect.ValueOf(supplier).Pointer())
}
func isUint64SupplierCalibrated(supplier func() uint64) bool {
return isCalibrated(reflect.Invalid, reflect.Uint64, reflect.ValueOf(supplier).Pointer())
}
// Runnable benchmarks a function with the signature:
// func()
// ID: B-0-0
func Runnable(b *testing.B, runnable func()) {
for i, count := 0, b.N; i < count; i++ {
runnable()
}
setCalibrated(reflect.Invalid, reflect.Invalid, reflect.ValueOf(runnable).Pointer())
}
// BoolSupplier benchmarks a function with the signature:
// func() bool
// ID: B-1-0
func BoolSupplier(b *testing.B, supplier func() bool) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Bool, reflect.ValueOf(supplier).Pointer())
}
// IntSupplier benchmarks a function with the signature:
// func() int
// ID: B-2-0
func IntSupplier(b *testing.B, supplier func() int) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Int, reflect.ValueOf(supplier).Pointer())
}
// Int8Supplier benchmarks a function with the signature:
// func() int8
// ID: B-3-0
func Int8Supplier(b *testing.B, supplier func() int8) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Int8, reflect.ValueOf(supplier).Pointer())
}
// Int16Supplier benchmarks a function with the signature:
// func() int16
// ID: B-4-0
func Int16Supplier(b *testing.B, supplier func() int16) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Int16, reflect.ValueOf(supplier).Pointer())
}
// Int32Supplier benchmarks a function with the signature:
// func() int32
// ID: B-5-0
func Int32Supplier(b *testing.B, supplier func() int32) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Int32, reflect.ValueOf(supplier).Pointer())
}
// Int64Supplier benchmarks a function with the signature:
// func() int64
// ID: B-6-0
func Int64Supplier(b *testing.B, supplier func() int64) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Int64, reflect.ValueOf(supplier).Pointer())
}
// UintSupplier benchmarks a function with the signature:
// func() uint
// ID: B-7-0
func UintSupplier(b *testing.B, supplier func() uint) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Uint, reflect.ValueOf(supplier).Pointer())
}
// Uint8Supplier benchmarks a function with the signature:
// func() uint8
// ID: B-8-0
func Uint8Supplier(b *testing.B, supplier func() uint8) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Uint8, reflect.ValueOf(supplier).Pointer())
}
// Uint16Supplier benchmarks a function with the signature:
// func() uint16
// ID: B-9-0
func Uint16Supplier(b *testing.B, supplier func() uint16) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Uint16, reflect.ValueOf(supplier).Pointer())
}
// Uint32Supplier benchmarks a function with the signature:
// func() uint32
// ID: B-10-0
func Uint32Supplier(b *testing.B, supplier func() uint32) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Uint32, reflect.ValueOf(supplier).Pointer())
}
// Uint64Supplier benchmarks a function with the signature:
// func() uint64
// ID: B-11-0
func Uint64Supplier(b *testing.B, supplier func() uint64) {
for i, count := 0, b.N; i < count; i++ {
supplier()
}
setCalibrated(reflect.Invalid, reflect.Uint64, reflect.ValueOf(supplier).Pointer())
} | common/benchmark/xx_runnable_and_supplier.go | 0.715424 | 0.69849 | xx_runnable_and_supplier.go | starcoder |
package encoding
import (
"github.com/OpenWhiteBox/primitives/matrix"
)
func matrixMul(m *matrix.Matrix, dst, src []byte) {
res := m.Mul(matrix.Row(src[:]))
copy(dst, res)
}
// ByteAdditive implements the Byte interface over XORing with a fixed value.
type ByteAdditive byte
func (ba ByteAdditive) code(in byte) byte { return in ^ byte(ba) }
func (ba ByteAdditive) Encode(in byte) byte { return ba.code(in) }
func (ba ByteAdditive) Decode(in byte) byte { return ba.code(in) }
// ByteLinear implements the Byte interface over an 8x8 linear transformation.
type ByteLinear struct {
// Forwards is the matrix to multiply by in the forwards (encoding) direction.
Forwards matrix.Matrix
// Backwards is the matrix to multiply by in the backwards (decoding) direction. It should be the inverse of Forwards.
Backwards matrix.Matrix
}
// NewByteLinear constructs a new ByteLinear encoding from a given matrix.
func NewByteLinear(forwards matrix.Matrix) ByteLinear {
backwards, ok := forwards.Invert()
if !ok {
panic("Non-invertible matrix given to NewByteLinear!")
}
return ByteLinear{
Forwards: forwards,
Backwards: backwards,
}
}
func (bl ByteLinear) Encode(in byte) byte { return bl.Forwards.Mul(matrix.Row{in})[0] }
func (bl ByteLinear) Decode(in byte) byte { return bl.Backwards.Mul(matrix.Row{in})[0] }
// ByteAffine implements the Byte interface over an affine transformation (a linear transformation composed with an
// additive one).
type ByteAffine struct {
ByteLinear
ByteAdditive
}
// NewByteAffine constructs a new ByteAffine encoding from a matrix and a constant.
func NewByteAffine(forwards matrix.Matrix, constant byte) ByteAffine {
return ByteAffine{
ByteLinear: NewByteLinear(forwards),
ByteAdditive: ByteAdditive(constant),
}
}
func (ba ByteAffine) Encode(in byte) byte { return ba.ByteAdditive.Encode(ba.ByteLinear.Encode(in)) }
func (ba ByteAffine) Decode(in byte) byte { return ba.ByteLinear.Decode(ba.ByteAdditive.Decode(in)) }
// DoubleAdditive implements the Double interface over XORing with a fixed value.
type DoubleAdditive [2]byte
func (da DoubleAdditive) code(in [2]byte) (out [2]byte) {
XOR(out[:], in[:], da[:])
return
}
func (da DoubleAdditive) Encode(in [2]byte) [2]byte { return da.code(in) }
func (da DoubleAdditive) Decode(in [2]byte) [2]byte { return da.code(in) }
// DoubleLinear implements the Double interface over a 16x16 linear transformation.
type DoubleLinear struct {
// Forwards is the matrix to multiply by in the forwards (encoding) direction.
Forwards matrix.Matrix
// Backwards is the matrix to multiply by in the backwards (decoding) direction. It should be the inverse of Forwards.
Backwards matrix.Matrix
}
// NewDoubleLinear constructs a new DoubleLinear encoding from a given matrix.
func NewDoubleLinear(forwards matrix.Matrix) DoubleLinear {
backwards, ok := forwards.Invert()
if !ok {
panic("Non-invertible matrix given to NewDoubleLinear!")
}
return DoubleLinear{
Forwards: forwards,
Backwards: backwards,
}
}
func (dl DoubleLinear) Encode(in [2]byte) (out [2]byte) {
matrixMul(&dl.Forwards, out[:], in[:])
return
}
func (dl DoubleLinear) Decode(in [2]byte) (out [2]byte) {
matrixMul(&dl.Backwards, out[:], in[:])
return
}
// DoubleAffine implements the Double interface over an affine transformation (a linear transformation composed with an
// additive one).
type DoubleAffine struct {
DoubleLinear
DoubleAdditive
}
// NewDoubleAffine constructs a new DoubleAffine encoding from a matrix and a constant.
func NewDoubleAffine(forwards matrix.Matrix, constant [2]byte) DoubleAffine {
return DoubleAffine{
DoubleLinear: NewDoubleLinear(forwards),
DoubleAdditive: DoubleAdditive(constant),
}
}
func (da DoubleAffine) Encode(in [2]byte) [2]byte {
return da.DoubleAdditive.Encode(da.DoubleLinear.Encode(in))
}
func (da DoubleAffine) Decode(in [2]byte) [2]byte {
return da.DoubleLinear.Decode(da.DoubleAdditive.Decode(in))
}
// WordAdditive implements the Word interface over XORing with a fixed value.
type WordAdditive [4]byte
func (wa WordAdditive) code(in [4]byte) (out [4]byte) {
XOR(out[:], in[:], wa[:])
return
}
func (wa WordAdditive) Encode(in [4]byte) [4]byte { return wa.code(in) }
func (wa WordAdditive) Decode(in [4]byte) [4]byte { return wa.code(in) }
// WordLinear implements the Word interface over a 32x32 linear transformation.
type WordLinear struct {
// Forwards is the matrix to multiply by in the forwards (encoding) direction.
Forwards matrix.Matrix
// Backwards is the matrix to multiply by in the backwards (decoding) direction. It should be the inverse of Forwards.
Backwards matrix.Matrix
}
// NewWordLinear constructs a new WordLinear encoding from a given matrix.
func NewWordLinear(forwards matrix.Matrix) WordLinear {
backwards, ok := forwards.Invert()
if !ok {
panic("Non-invertible matrix given to NewWordLinear!")
}
return WordLinear{
Forwards: forwards,
Backwards: backwards,
}
}
func (wl WordLinear) Encode(in [4]byte) (out [4]byte) {
matrixMul(&wl.Forwards, out[:], in[:])
return
}
func (wl WordLinear) Decode(in [4]byte) (out [4]byte) {
matrixMul(&wl.Backwards, out[:], in[:])
return
}
// WordAffine implements the Word interface over an affine transformation (a linear transformation composed with an
// additive one).
type WordAffine struct {
WordLinear
WordAdditive
}
// NewWordAffine constructs a new WordAffine encoding from a matrix and a constant.
func NewWordAffine(forwards matrix.Matrix, constant [4]byte) WordAffine {
return WordAffine{
WordLinear: NewWordLinear(forwards),
WordAdditive: WordAdditive(constant),
}
}
func (wa WordAffine) Encode(in [4]byte) [4]byte {
return wa.WordAdditive.Encode(wa.WordLinear.Encode(in))
}
func (wa WordAffine) Decode(in [4]byte) [4]byte {
return wa.WordLinear.Decode(wa.WordAdditive.Decode(in))
}
// BlockAdditive implements the Block interface over XORing with a fixed value.
type BlockAdditive [16]byte
func (ba BlockAdditive) code(in [16]byte) (out [16]byte) {
XOR(out[:], in[:], ba[:])
return
}
func (ba BlockAdditive) Encode(in [16]byte) [16]byte { return ba.code(in) }
func (ba BlockAdditive) Decode(in [16]byte) [16]byte { return ba.code(in) }
// BlockLinear implements the Block interface over a 128x128 linear transformation.
type BlockLinear struct {
// Forwards is the matrix to multiply by in the forwards (encoding) direction.
Forwards matrix.Matrix
// Backwards is the matrix to multiply by in the backwards (decoding) direction. It should be the inverse of Forwards.
Backwards matrix.Matrix
}
// NewBlockLinear constructs a new BlockLinear encoding from a given matrix.
func NewBlockLinear(forwards matrix.Matrix) BlockLinear {
backwards, ok := forwards.Invert()
if !ok {
panic("Non-invertible matrix given to NewBlockLinear!")
}
return BlockLinear{
Forwards: forwards,
Backwards: backwards,
}
}
func (bl BlockLinear) Encode(in [16]byte) (out [16]byte) {
matrixMul(&bl.Forwards, out[:], in[:])
return
}
func (bl BlockLinear) Decode(in [16]byte) (out [16]byte) {
matrixMul(&bl.Backwards, out[:], in[:])
return
}
// BlockAffine implements the Block interface over an affine transformation (a linear transformation composed with an
// additive one).
type BlockAffine struct {
BlockLinear
BlockAdditive
}
// NewBlockAffine constructs a new BlockAffine encoding from a matrix and a constant.
func NewBlockAffine(forwards matrix.Matrix, constant [16]byte) BlockAffine {
return BlockAffine{
BlockLinear: NewBlockLinear(forwards),
BlockAdditive: BlockAdditive(constant),
}
}
func (ba BlockAffine) Encode(in [16]byte) [16]byte {
return ba.BlockAdditive.Encode(ba.BlockLinear.Encode(in))
}
func (ba BlockAffine) Decode(in [16]byte) [16]byte {
return ba.BlockLinear.Decode(ba.BlockAdditive.Decode(in))
} | encoding/linear.go | 0.895099 | 0.780725 | linear.go | starcoder |
package sqlwriter
import (
"fmt"
"strings"
)
type InsertStatement struct {
tableName string
columns []string
values []interface{}
returningColumn string
}
func Insert(tableName string, columns ...string) *InsertStatement {
i := &InsertStatement{
tableName: tableName,
columns: columns,
}
return i
}
func (i *InsertStatement) Columns(columnNames ...string) *InsertStatement {
i.columns = append(i.columns, columnNames...)
return i
}
func (i *InsertStatement) Col(columnName string, value interface{}) *InsertStatement {
i.columns = append(i.columns, columnName)
i.values = append(i.values, value)
return i
}
func (i *InsertStatement) Values(values ...interface{}) *InsertStatement {
i.values = append(i.values, values...)
return i
}
func (i *InsertStatement) ColumnValues(columnValuePairs ...interface{}) *InsertStatement {
for k := 0; k < len(columnValuePairs); k += 2 {
// If this blows up with type assertion error, then the caller is not
// passing in strings for column names, or got their name/value pairs
// mixed up.
i.columns = append(i.columns, columnValuePairs[k].(string))
// If this blows up with "index out of range" then it means somebody is
// calling this method with an uneven number of arguments, i.e. not
// pairs.
i.values = append(i.values, columnValuePairs[k+1])
}
return i
}
func (i *InsertStatement) Returning(columnName string) *InsertStatement {
i.returningColumn = columnName
return i
}
func (i *InsertStatement) bindMarkers() []string {
// For postgres this is $1, $2, ...
// It may be different for other databases.
markers := []string{}
for p := range i.columns {
markers = append(markers, fmt.Sprintf("$%d", p+1))
}
return markers
}
func (i *InsertStatement) SQL() string {
s := fmt.Sprintf("insert into %s (%s) values (%s)",
i.tableName,
strings.Join(i.columns, ", "),
strings.Join(i.bindMarkers(), ", "))
if i.returningColumn != "" {
s = s + " returning " + i.returningColumn
}
return s
}
func (i *InsertStatement) BindValues() []interface{} {
return i.values
} | insert.go | 0.550849 | 0.401277 | insert.go | starcoder |
package main
import (
"bytes"
"encoding/binary"
"fmt"
"log"
)
// Value is a LZ77 sequence element - a literal or a pointer.
type Value struct {
IsLiteral bool
// Literal
val byte
// Pointer
distance uint16
length byte
}
func NewValue(isLiteral bool, value, length byte, distance uint16) Value {
return Value{
IsLiteral: isLiteral,
val: value,
distance: distance,
length: length,
}
}
func (v Value) String() string {
if v.IsLiteral {
return fmt.Sprintf("%c", v.val)
}
return fmt.Sprintf("<%d,%d>", v.distance, v.length)
}
// GetLiteralBinary returns binary representation of literal.
func (v *Value) GetLiteralBinary() byte {
return v.val
}
// GetPointerBinary returns binary representation of pointer.
// A pointer is serialized to a few bytes, so that there are less possible
// nodes in a Huffman tree.
func (v *Value) GetPointerBinary() []byte {
bytes := make([]byte, 3)
// First 2 bytes encode a distance.
binary.BigEndian.PutUint16(bytes, v.distance)
// The last byte is length.
bytes[2] = v.length
return bytes
}
// BytesToValues converts input to []Value, by replacing series of
// characters with LZ77 pointers wherever possible.
func BytesToValues(input []byte, minMatchLen, maxMatchLen byte, maxSearchBuffLen uint16) []Value {
var (
searchBuffStart, lookaheadBuffEnd, p int
dist uint16
l byte
)
values := make([]Value, len(input)) // Almost always it will be less, but lets over-allocate.
value_counter := 0
pointer_counter := 0
for split := 0; split < len(input); split += 1 {
searchBuffStart = max(0, split-int(maxSearchBuffLen))
lookaheadBuffEnd = min(len(input), split+int(maxMatchLen))
p, l = getLongestMatchPosAndLen(input[searchBuffStart:split], input[split:lookaheadBuffEnd], minMatchLen)
if split > int(minMatchLen) && l > 0 {
// p is a position within searchBuff, so we need to calculate distance from the split.
dist = uint16(split - (p + searchBuffStart))
values[value_counter] = NewValue(false, 0, l, dist)
value_counter += 1
split += (int(l) - 1)
pointer_counter += 1
} else {
values[value_counter] = NewValue(true, input[split], 1, 0)
value_counter += 1
}
}
log.Printf("Pointers ratio: %.2f\n", float64(pointer_counter)/float64(value_counter))
return values[:value_counter]
}
func getLongestMatchPosAndLen(text, pattern []byte, minMatchLen byte) (int, byte) {
if len(pattern) < int(minMatchLen) {
return 0, 0
}
var (
matchLen, maxSoFar, length byte
position int
)
// Heuristic: get indexes at which at least minMatchLen of pattern matches.
minMatchStarts := getMatchIndex(text, pattern[:minMatchLen])
for _, matchStart := range minMatchStarts {
matchLen = getMatchLen(text[matchStart:], pattern)
if matchLen >= minMatchLen && matchLen > maxSoFar {
position = matchStart
length, maxSoFar = matchLen, matchLen
}
}
return position, length
}
// getMatchIndex will return a slice of indexes at which pattern begins.
func getMatchIndex(text, pattern []byte) []int {
// We surely do not have any matches.
if len(text) == 0 || len(text) < len(pattern) {
return []int{}
}
// If pattern is empty, then we have a match everywhere.
if len(pattern) == 0 {
matchIndicies := make([]int, len(text))
for i := range text {
matchIndicies[i] = i
}
return matchIndicies
}
matchIndices := make([]int, 0)
for i := range text[:len(text)-len(pattern)+1] {
// Just look for where pattern matches. This is hot path, and this
// way to compare bytes turned out to be the fastest experimentally.
if text[i] == pattern[0] {
if text[i+1] == pattern[1] {
if text[i+2] == pattern[2] {
if bytes.Equal(text[i+3:i+len(pattern)], pattern[3:len(pattern)]) {
matchIndices = append(matchIndices, i)
}
}
}
}
}
return matchIndices
}
// getMatchLen returns a length of a longest match between two sequences.
func getMatchLen(a, b []byte) byte {
var matchLen byte
maxMatchLen := min(min(len(a), len(b)), 255)
for i := 0; i < maxMatchLen; i++ {
if a[i] == b[i] {
matchLen += 1
} else {
break
}
}
return matchLen
}
// ValuesToBytes converts data from value representation back to []byte representation.
func ValuesToBytes(values []Value) []byte {
var from int
bytes := make([]byte, 0, len(values)) // We underallocate here.
for _, v := range values {
if v.IsLiteral {
bytes = append(bytes, v.val)
} else {
from = len(bytes) - int(v.distance)
bytes = append(bytes, bytes[from:from+int(v.length)]...)
}
}
return bytes
} | values.go | 0.672869 | 0.427337 | values.go | starcoder |
package main
import (
"fmt"
"math"
)
const (
INPUT = 368078
)
type Direction uint
const (
UP Direction = iota
LEFT
DOWN
RIGHT
)
type Point struct{ x, y int }
type Grid map[Point]int
func turn(direction Direction) Direction {
return (direction + 1) % 4
}
func move(p Point, direction Direction) Point {
switch {
case direction == UP:
return Point{p.x, p.y + 1}
case direction == DOWN:
return Point{p.x, p.y - 1}
case direction == LEFT:
return Point{p.x - 1, p.y}
case direction == RIGHT:
return Point{p.x + 1, p.y}
}
// this is an error case, but let's make the compiler happy
return p
}
func initialGrid() Grid {
return map[Point]int{
Point{0, 0}: 1,
}
}
func neighbors(p Point) []Point {
return []Point{
Point{p.x, p.y + 1},
Point{p.x, p.y - 1},
Point{p.x + 1, p.y},
Point{p.x - 1, p.y},
Point{p.x + 1, p.y + 1},
Point{p.x + 1, p.y - 1},
Point{p.x - 1, p.y + 1},
Point{p.x - 1, p.y - 1},
}
}
func plus1(p Point, g Grid) int {
max := 0
for _, n := range neighbors(p) {
v, ok := g[n]
if ok && v > max {
max = v
}
}
return max + 1
}
func sumNeighbors(p Point, g Grid) int {
sum := 0
for _, n := range neighbors(p) {
v, ok := g[n]
if ok {
sum += v
}
}
return sum
}
func sideLength(ring int) int {
return 2*ring + 1
}
func iterate(iterator func(Point, Grid) int, stop func(int) bool) (Point, Grid) {
p := Point{1, 0}
direction := UP
grid := initialGrid()
ring := 1
movedPerSide := 2
val := 1
nextRing := false
for {
if nextRing {
direction = UP
nextRing = false
ring++
}
if movedPerSide == sideLength(ring) {
if direction == RIGHT {
nextRing = true
} else {
direction = turn(direction)
}
movedPerSide = 1
}
val = iterator(p, grid)
grid[p] = val
if stop(val) {
break
}
p = move(p, direction)
movedPerSide++
}
return p, grid
}
func manhattan(p Point) int {
return int(math.Abs(float64(p.x)) + math.Abs(float64(p.y)))
}
func main() {
p, _ := iterate(plus1, func(v int) bool { return v >= INPUT })
fmt.Println(manhattan(p))
p, g := iterate(sumNeighbors, func(v int) bool { return v > INPUT })
fmt.Println(g[p])
} | 03/main.go | 0.67104 | 0.442697 | main.go | starcoder |
package vector
import (
"math"
"github.com/austingebauer/go-ray-tracer/maths"
)
// Vector represents a vector in a left-handed 3D coordinate system
type Vector struct {
// X, Y, and Z represent components in a left-handed 3D coordinate system
X, Y, Z float64
}
// NewVector returns a new Vector that has the passed X, Y, and Z values.
func NewVector(x, y, z float64) *Vector {
return &Vector{
X: x,
Y: y,
Z: z,
}
}
// Equals returns true if the passed Vector is equal to this Vector.
// Two Vectors are equal if their X, Y, Z components are equal.
func (vec *Vector) Equals(vecQ *Vector) bool {
return maths.Float64Equals(vec.X, vecQ.X, maths.Epsilon) &&
maths.Float64Equals(vec.Y, vecQ.Y, maths.Epsilon) &&
maths.Float64Equals(vec.Z, vecQ.Z, maths.Epsilon)
}
// Magnitude computes and returns the length of this Vector.
// The length is calculated using Pythagoras' theorem.
func (vec *Vector) Magnitude() float64 {
return math.Sqrt(math.Pow(vec.X, 2) +
math.Pow(vec.Y, 2) +
math.Pow(vec.Z, 2))
}
// Negate multiplies each of this Vector's components by -1.
func (vec *Vector) Negate() *Vector {
return vec.Scale(-1)
}
// Scale multiplies each of this Vector's components by the passed scalar value.
func (vec *Vector) Scale(scalar float64) *Vector {
vec.X = vec.X * scalar
vec.Y = vec.Y * scalar
vec.Z = vec.Z * scalar
return vec
}
// Scale returns a new Vector that is the result of scaling the passed Vector
// by the passed scalar value.
func Scale(vec Vector, scalar float64) *Vector {
return NewVector(vec.X*scalar, vec.Y*scalar, vec.Z*scalar)
}
// Normalize normalizes this Vector by converting it to a unit vector.
func (vec *Vector) Normalize() *Vector {
mag := vec.Magnitude()
vec.X = vec.X / mag
vec.Y = vec.Y / mag
vec.Z = vec.Z / mag
return vec
}
// Normalize returns a new Vector that is the result of normalizing the passed Vector.
func Normalize(vec Vector) *Vector {
vec.Normalize()
return &Vector{
X: vec.X,
Y: vec.Y,
Z: vec.Z,
}
}
// DotProduct computes and returns the dot product of passed Vectors.
func DotProduct(vec1, vec2 Vector) float64 {
// The dot product yields the cosine of the angle between the passed Vectors.
// If it is equal to 0, the vectors are perpendicular to each other.
// If it is equal to 1, the vectors are parallel to each other.
return vec1.X*vec2.X +
vec1.Y*vec2.Y +
vec1.Z*vec2.Z
}
// CrossProduct computes and returns a new Vector that is the
// cross product of the passed Vectors.
func CrossProduct(vec1, vec2 Vector) Vector {
return Vector{
X: (vec1.Y * vec2.Z) - (vec1.Z * vec2.Y),
Y: (vec1.Z * vec2.X) - (vec1.X * vec2.Z),
Z: (vec1.X * vec2.Y) - (vec1.Y * vec2.X),
}
}
// Add modifies each component of this Vector by setting each of them
// to the sum of the components in this Vector and the passed Vector.
func (vec *Vector) Add(vec2 Vector) *Vector {
vec.X = vec.X + vec2.X
vec.Y = vec.Y + vec2.Y
vec.Z = vec.Z + vec2.Z
return vec
}
// Add returns a new Vector with components equal to the sum
// of the corresponding components in the passed Vectors.
func Add(vec1, vec2 Vector) Vector {
return Vector{
X: vec1.X + vec2.X,
Y: vec1.Y + vec2.Y,
Z: vec1.Z + vec2.Z,
}
}
// Subtract modifies each component of this Vector by setting each of them
// to the difference of the components in this Vector and the passed Vector.
func (vec *Vector) Subtract(vec2 Vector) *Vector {
vec.X = vec.X - vec2.X
vec.Y = vec.Y - vec2.Y
vec.Z = vec.Z - vec2.Z
return vec
}
// Subtract returns a new Vector with components equal to the difference
// of the corresponding components in the passed Vectors.
func Subtract(vec1, vec2 Vector) *Vector {
return NewVector(vec1.X-vec2.X, vec1.Y-vec2.Y, vec1.Z-vec2.Z)
}
// Reflect returns a new Vector that is the results of reflecting
// the passed in Vector around the passed normal Vector.
func Reflect(in, normal Vector) *Vector {
dp := DotProduct(in, normal)
nScaled := normal.Scale(2).Scale(dp)
return Subtract(in, *nScaled)
} | vector/vector.go | 0.950595 | 0.870707 | vector.go | starcoder |
package comparator
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/litmuschaos/litmus-go/pkg/log"
"github.com/pkg/errors"
)
// CompareFloat compares floating numbers for specific operation
// it check for the >=, >, <=, <, ==, != operators
func (model Model) CompareFloat() error {
obj := Float{}
obj.setValues(reflect.ValueOf(model.a).String(), reflect.ValueOf(model.b).String())
if model.rc == 1 {
log.Infof("[Probe]: {Actual value: %v}, {Expected value: %v}, {Operator: %v}", obj.a, obj.b, model.operator)
}
switch model.operator {
case ">=":
if !obj.isGreaterorEqual() {
return fmt.Errorf("{actual value: %v} is not greater than or equal to {expected value: %v}", obj.a, obj.b)
}
case "<=":
if !obj.isLesserorEqual() {
return fmt.Errorf("{actual value: %v} is not lesser than or equal to {expected value: %v}", obj.a, obj.b)
}
case ">":
if !obj.isGreater() {
return fmt.Errorf("{actual value: %v} is not greater than {expected value: %v}", obj.a, obj.b)
}
case "<":
if !obj.isLesser() {
return fmt.Errorf("{actual value: %v} is not lesser than {expected value: %v}", obj.a, obj.b)
}
case "==":
if !obj.isEqual() {
return fmt.Errorf("{actual value: %v} is not equal to {expected value: %v}", obj.a, obj.b)
}
case "!=":
if !obj.isNotEqual() {
return fmt.Errorf("{actual value: %v} is not Notequal to {expected value: %v}", obj.a, obj.b)
}
case "OneOf", "oneOf":
if !obj.isOneOf() {
return errors.Errorf("Actual value: {%v} doesn't matched with any of the expected values: {%v}", obj.a, obj.c)
}
case "between", "Between":
if len(obj.c) < 2 {
return errors.Errorf("{expected value: %v} should contains both lower and upper limits", obj.c)
}
if !obj.isBetween() {
return errors.Errorf("Actual value: {%v} doesn't lie in between expected range: {%v}", obj.a, obj.c)
}
default:
return fmt.Errorf("criteria '%s' not supported in the probe", model.operator)
}
return nil
}
// Float contains operands for float comparator check
type Float struct {
a float64
b float64
c []float64
}
// SetValues set the values inside Float struct
func (f *Float) setValues(a, b string) {
f.a, _ = strconv.ParseFloat(a, 64)
c := strings.Split(strings.TrimSpace(b), ",")
if len(c) > 1 {
list := []float64{}
for j := range c {
x, _ := strconv.ParseFloat(c[j], 64)
list = append(list, x)
}
f.c = list
f.b = float64(0)
} else {
f.b, _ = strconv.ParseFloat(b, 64)
}
}
// isGreater check for the first number should be greater than second number
func (f *Float) isGreater() bool {
return f.a > f.b
}
// isGreaterorEqual check for the first number should be greater than or equals to the second number
func (f *Float) isGreaterorEqual() bool {
return f.isGreater() || f.isEqual()
}
// isLesser check for the first number should be lesser than second number
func (f *Float) isLesser() bool {
return f.a < f.b
}
// isLesserorEqual check for the first number should be less than or equals to the second number
func (f *Float) isLesserorEqual() bool {
return f.isLesser() || f.isEqual()
}
// isEqual check for the first number should be equals to the second number
func (f *Float) isEqual() bool {
return f.a == f.b
}
// isNotEqual check for the first number should be not equals to the second number
func (f *Float) isNotEqual() bool {
return f.a != f.b
}
// isOneOf check for the number should be present inside given list
func (f *Float) isOneOf() bool {
for i := range f.c {
if f.a == f.c[i] {
return true
}
}
return false
}
// isBetween check for the number should be lie in the given range
func (f *Float) isBetween() bool {
if f.a >= f.c[0] && f.a <= f.c[1] {
return true
}
return false
} | pkg/probe/comparator/float.go | 0.680772 | 0.494385 | float.go | starcoder |
package bitmatrix
import (
"fmt"
"log"
"github.com/dranidis/bitarray"
"github.com/fatih/color"
)
type bitMatrixArray struct {
size int
board *bitarray.BitArray
}
var rightMask map[int]*bitarray.BitArray
var leftMask map[int]*bitarray.BitArray
func initRightMask(num int) *bitarray.BitArray {
rightMask := bitarray.New(num * num)
for pos := 0; pos < num*num; pos++ {
if (pos+1)%num != 0 {
rightMask.Set(pos)
}
}
return rightMask
}
func initLeftMask(num int) *bitarray.BitArray {
leftMask := bitarray.New(num * num)
for pos := 0; pos < num*num; pos++ {
if (pos)%num != 0 {
leftMask.Set(pos)
}
}
return leftMask
}
// newBitMatrixArray creates a size x size matrix of bits.
// There are no size restrictions. The underlying data strucure is a bit array.
func newBitMatrixArray(size int) *bitMatrixArray {
var b bitMatrixArray
b.board = bitarray.New(size * size)
b.size = size
if rightMask == nil {
rightMask = make(map[int]*bitarray.BitArray)
}
if leftMask == nil {
leftMask = make(map[int]*bitarray.BitArray)
}
_, ok := rightMask[size]
if !ok {
rightMask[size] = initRightMask(size)
}
_, ok = leftMask[size]
if !ok {
leftMask[size] = initLeftMask(size)
}
return &b
}
func (b *bitMatrixArray) New(size int) BitMatrix {
b = newBitMatrixArray(size)
return b
}
func (b *bitMatrixArray) Size() int {
return b.size
}
func (b *bitMatrixArray) Clone() BitMatrix {
var clone = newBitMatrixArray(b.size)
clone.board = b.board.Clone()
return clone
}
func (b *bitMatrixArray) None() BitMatrix {
b.board = b.board.None()
return b
}
func (b *bitMatrixArray) All() BitMatrix {
b.board = b.board.All()
return b
}
func (b *bitMatrixArray) rightMask() *bitarray.BitArray {
return rightMask[b.size].Clone()
}
func (b *bitMatrixArray) leftMask() *bitarray.BitArray {
return leftMask[b.size].Clone()
}
func (b *bitMatrixArray) Count() int {
return b.board.Count()
}
func (b *bitMatrixArray) Set(index int) BitMatrix {
b.board = b.board.Set(index)
return b
}
func (b *bitMatrixArray) Is(index int) bool {
return b.board.Is(index)
}
// boolean operators work on all bits.
// Also on the ones outside the board area
func (b *bitMatrixArray) And(w BitMatrix) BitMatrix {
b.board = b.board.And(w.(*bitMatrixArray).board)
return b
}
func (b *bitMatrixArray) Or(w BitMatrix) BitMatrix {
b.board = b.board.Or(w.(*bitMatrixArray).board)
return b
}
func (b *bitMatrixArray) Xor(w BitMatrix) BitMatrix {
b.board = b.board.Xor(w.(*bitMatrixArray).board)
return b
}
func (b *bitMatrixArray) Inverse() BitMatrix {
b.board = b.board.Inverse()
return b
}
func (b *bitMatrixArray) Minus(w BitMatrix) BitMatrix {
b.board = b.board.Minus(w.(*bitMatrixArray).board)
return b
}
// COPY from BinMatrix1
// COMPLEX operations
func (b *bitMatrixArray) Up() BitMatrix {
max := bitarray.New(b.size * b.size)
max = max.All()
b.board = b.board.ShiftRight(b.size).And(max)
return b
}
func (b *bitMatrixArray) Down() BitMatrix {
max := bitarray.New(b.size * b.size)
max = max.All()
b.board = b.board.ShiftLeft(b.size).And(max)
return b
}
func (b *bitMatrixArray) Left() BitMatrix {
max := bitarray.New(b.size * b.size)
max = max.All()
lmask := newBitMatrixArray(b.size)
lmaskBinArray := lmask.leftMask()
b.board = b.board.And(lmaskBinArray).ShiftRight(1).And(max)
return b
}
func (b *bitMatrixArray) Right() BitMatrix {
max := bitarray.New(b.size * b.size)
max = max.All()
rmask := newBitMatrixArray(b.size)
rmaskBinArray := rmask.rightMask()
b.board = b.board.And(rmaskBinArray).ShiftLeft(1).And(max)
return b
}
func (b *bitMatrixArray) String() string {
col := color.New(color.FgRed)
s := ""
for i := 0; i < b.size*b.size; i++ {
if i != 0 && i%b.size == 0 {
s += "\n"
}
d := b.board.Get(i)
if d == 1 {
s += col.Sprintf(fmt.Sprintf("%3d", d))
} else {
s += fmt.Sprintf("%3d", d)
}
}
return s + "\n"
}
func (b *bitMatrixArray) Equal(w BitMatrix) bool {
return b.board.Equal(w.(*bitMatrixArray).board)
}
func (b *bitMatrixArray) Read(board [][]int) BitMatrix {
if b.size != len(board) {
log.Panicf("BinMatrixArray.Read Cannot read. Different size: \n%v\n", board)
}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if board[i][j] == 1 {
xy := EncodeWidth(i, j, b.size)
b.Set(xy)
}
}
}
return b
} | bitmatrixarr.go | 0.647352 | 0.560192 | bitmatrixarr.go | starcoder |
package darts
import (
"fmt"
"strings"
"github.com/deckarep/golang-set"
"gonum.org/v1/gonum/mat"
)
// Atom is the small cell in split
type Atom struct {
Image string //image of the atom
St, End int // [start,end) of this atom in ori string
Tags mapset.Set // type is set(string)
}
//String is add a type to atom
func (atom *Atom) String() string {
return fmt.Sprintf("%s[%d,%d)", atom.Image, atom.St, atom.End)
}
//NewAtom crate the atom
func NewAtom(str *string, start, end int) *Atom {
atom := new(Atom)
atom.Image = *str
atom.St = start
atom.End = end
return atom
}
//AddType is add a type to atom
func (atom *Atom) AddType(t string) {
if atom.Tags == nil {
atom.Tags = mapset.NewSet()
}
atom.Tags.Add(t)
}
//AddTypes is add the types
func (atom *Atom) AddTypes(types mapset.Set) {
if types == nil {
return
}
if atom.Tags == nil {
atom.Tags = mapset.NewSet()
}
atom.Tags = atom.Tags.Union(types)
}
//AtomList is aarray of atoms
type AtomList struct {
Str *string //ori image
List []*Atom //lsit data
}
//SubAtomList Sub a atonlist
func (alist *AtomList) SubAtomList(start, end int) *Atom {
var buf strings.Builder
tags := mapset.NewSet()
for i := start; i < end; i++ {
buf.WriteString(alist.List[i].Image)
if alist.List[i].Tags != nil {
tags = tags.Intersect(alist.List[i].Tags)
}
}
if buf.Len() > 0 {
str := buf.String()
atom := NewAtom(&str, alist.List[start].St, alist.List[end-1].End)
if tags.Cardinality() > 0 {
atom.Tags = tags
}
return atom
}
return nil
}
//NewAtomList make a atom List
func NewAtomList(atoms []*Atom, img *string) *AtomList {
return &AtomList{Str: img, List: atoms}
}
//StrIterFuc iter the atom list
func (alist *AtomList) StrIterFuc(skipEmpty, skipPos bool) StringIter {
if !(skipEmpty || skipPos) {
return func(dfunc func(*string, int) bool) {
for i, a := range alist.List {
if dfunc(&a.Image, i) {
break
}
}
}
}
return func(dfunc func(*string, int) bool) {
se, sp := skipEmpty, skipPos
for i, a := range alist.List {
if se && a.Tags != nil && a.Tags.Contains("<EMPTY>") {
continue
}
if sp && a.Tags != nil && a.Tags.Contains("<POS>") {
continue
}
if dfunc(&a.Image, i) {
break
}
}
}
}
//WCell is the split token parttern
type WCell struct {
Word *Atom //the word in ori string
St, Et int //this cell [start,end) in the atom list
Emb mat.Vector // matrix os this
Feat uint16 //represent which type of this word this is used for tagger
}
//AddTypes add a give types
func (cell *WCell) AddTypes(types mapset.Set) {
cell.Word.AddTypes(types)
}
//GetTypes give the type to arry
func (cell *WCell) GetTypes() []string {
if cell.Word.Tags == nil {
return nil
}
tags := cell.Word.Tags.ToSlice()
stags := make([]string, len(tags))
for i, t := range tags {
stags[i] = t.(string)
}
return stags
}
//NewWcell create a WCell
func NewWcell(atom *Atom, s, e int) *WCell {
cell := new(WCell)
cell.Word = atom
cell.St = s
cell.Et = e
return cell
}
//Cursor map cursor used
type Cursor struct {
pre, lack *Cursor // pointer of this node pre and lack
val *WCell // val of the node
idx int // index of this course in list
}
func newCur(value *WCell, pre, next *Cursor) *Cursor {
cur := new(Cursor)
cur.val = value
cur.pre = pre
cur.lack = next
return cur
}
//CellMap used
type CellMap struct {
Head *Cursor //this cellMap size
rows, colums, size int // this cellmap countor
}
func newCellMap() *CellMap {
cmap := new(CellMap)
cmap.Head = new(Cursor)
cmap.Head.idx = -1
cmap.Head.val = new(WCell)
cmap.Head.val.St = -1
cmap.Head.val.Et = 0
return cmap
}
func (cmap *CellMap) indexMap() {
node := cmap.Head
node.idx = -1
index := node.idx
for node.lack != nil {
node = node.lack
index++
node.idx = index
}
}
//IterRow is iter the cellmap ,if row<0 tits iter all
func (cmap *CellMap) IterRow(cur *Cursor, row int, dfunc func(*Cursor)) {
if cur == nil {
cur = cmap.Head
}
if row < 0 { //Iter all if row is negtive
for cur.lack != nil {
dfunc(cur.lack)
cur = cur.lack
}
return
}
for cur.lack != nil { //Iter the give row from start
n := cur.lack
if n.val.St < row {
cur = n
continue
}
if n.val.St != row {
break
}
dfunc(n)
cur = n
}
}
// AddNext do add the cell to give cir next
func (cmap *CellMap) AddNext(cursor *Cursor, cell *WCell) *Cursor {
if cell.St > cmap.rows {
cmap.rows = cell.St
}
if cell.Et > cmap.colums {
cmap.colums = cell.Et
}
for cursor.lack != nil {
n := cursor.lack
if n.val.St < cell.St {
cursor = n
continue
}
if n.val.St == cell.St {
if n.val.Et < cell.Et {
cursor = n
continue
}
if n.val.Et == cell.Et {
n.val.AddTypes(cell.Word.Tags)
return n
}
}
m := newCur(cell, cursor, n)
cmap.size++
cursor.lack = m
n.pre = m
return m
}
cursor.lack = newCur(cell, cursor, nil)
cmap.size++
return cursor.lack
}
//AddPre add a cell to next
func (cmap *CellMap) AddPre(cur *Cursor, cell *WCell) *Cursor {
if cell.St > cmap.rows {
cmap.rows = cell.St
}
if cell.Et > cmap.colums {
cmap.colums = cell.Et
}
for cur.pre != cmap.Head {
n := cur.pre
if n.val.St > cell.St {
cur = n
continue
}
if n.val.St == cell.St {
if n.val.Et > cell.Et {
cur = n
continue
}
if n.val.Et == cell.Et {
n.val.AddTypes(cell.Word.Tags)
return n
}
}
m := newCur(cell, n, cur)
cmap.size++
cur.pre = m
n.lack = m
return m
}
cur.pre = newCur(cell, cmap.Head, cur)
cmap.size++
return cur.pre
}
//AddCell add a cell to a cur
func (cmap *CellMap) AddCell(cell *WCell, cur *Cursor) *Cursor {
if cur == nil {
return cmap.AddNext(cmap.Head, cell)
}
if cur.val.St < cell.St {
return cmap.AddNext(cur, cell)
}
if (cur.val.St == cell.St) && (cur.val.Et <= cell.Et) {
return cmap.AddNext(cur, cell)
}
return cmap.AddPre(cur, cell)
}
//CellRecognizer is code
type CellRecognizer interface {
//recognizer all Wcell possable in the atomlist
Read(content *AtomList, cmap *CellMap)
}
//CellQuantizer interface of a prepre
type CellQuantizer interface {
//set the cmap val data embeding
Embed(context *AtomList, cmap *CellMap)
//distance of the pre and next cell
Distance(pre *WCell, next *WCell) float32
}
func splitContent(cmap *CellMap, quantizer CellQuantizer, context *AtomList) []*WCell {
buildGraph := func() map[int][][2]float32 {
cmap.indexMap()
quantizer.Embed(context, cmap)
var tmp [][2]float32
graph := make(map[int][][2]float32)
cmap.IterRow(nil, 0, func(cur *Cursor) {
tmp = append(tmp, [2]float32{float32(cur.idx), 0.0})
})
graph[-1] = tmp
cmap.IterRow(nil, -1, func(pre *Cursor) {
tmp = [][2]float32{}
cmap.IterRow(pre, pre.val.Et, func(next *Cursor) {
dist := quantizer.Distance(pre.val, next.val)
if dist > 0.0 {
tmp = append(tmp, [2]float32{float32(next.idx), dist})
}
})
if len(tmp) < 1 {
tmp = append(tmp, [2]float32{float32(cmap.size), 0.0})
}
graph[pre.idx] = tmp
})
return graph
}
selectPath := func(graph map[int][][2]float32) []int {
// init
sz := len(graph)
dist, prev := make([]float32, sz), make([]int, sz)
dist[0] = -1.0
for j := 1; j < len(dist); j *= 2 {
copy(dist[j:], dist[:j])
}
prev[0] = -2
for j := 1; j < len(prev); j *= 2 {
copy(prev[j:], prev[:j])
}
used := mapset.NewSet()
for j := 1; j < sz; j++ {
used.Add(j)
}
visted := mapset.NewSet()
for _, nw := range graph[-1] {
node, weight := int(nw[0]), nw[1]
dist[node] = weight
visted.Add(node)
prev[node] = -1
}
// dijkstra
for used.Contains(sz - 1) {
minDist, u := float32(3.4e30), 0
used.Intersect(visted).Each(func(i interface{}) bool {
idx := i.(int)
if dist[idx] < minDist {
minDist = dist[idx]
u = idx
}
return false
})
if u == sz-1 {
break
}
used.Remove(u)
for _, nw := range graph[u] {
node, weight := int(nw[0]), nw[1]
if !used.Contains(node) {
continue
}
c := dist[u] + weight
visted.Add(node)
if (dist[node] < 0) || (c < dist[node]) {
dist[node] = c
prev[node] = u
}
}
}
// select
bestPaths := make([]int, 1, sz)
bestPaths[0] = sz - 1
for bestPaths[len(bestPaths)-1] > -1 {
last := bestPaths[len(bestPaths)-1]
bestPaths = append(bestPaths, prev[last])
}
for i, j := 0, len(bestPaths)-1; i < j; i, j = i+1, j-1 {
bestPaths[i], bestPaths[j] = bestPaths[j], bestPaths[i]
}
return bestPaths
}
nodeUse := mapset.NewSet()
for _, idx := range selectPath(buildGraph()) {
nodeUse.Add(idx)
}
result := make([]*WCell, 0, nodeUse.Cardinality())
cmap.IterRow(nil, -1, func(cur *Cursor) {
if nodeUse.Contains(cur.idx) {
result = append(result, cur.val)
}
})
return result
}
//Segment is used for segment
type Segment struct {
cellRecognizers []CellRecognizer
quantizer CellQuantizer
}
//NewSegment make a new segment
func NewSegment(q CellQuantizer) *Segment {
s := new(Segment)
s.quantizer = q
s.cellRecognizers = make([]CellRecognizer, 0, 2)
return s
}
//AddCellRecognizer add a CellRecognizer
func (seg *Segment) AddCellRecognizer(r CellRecognizer) {
if r != nil {
seg.cellRecognizers = append(seg.cellRecognizers, r)
}
}
func (seg *Segment) buildMap(atomList *AtomList) *CellMap {
cmap := newCellMap()
cur := cmap.Head
for i, atom := range atomList.List {
cur = cmap.AddNext(cur, NewWcell(atom, i, i+1))
}
for _, recognizer := range seg.cellRecognizers {
recognizer.Read(atomList, cmap)
}
return cmap
}
//SmartCut cut a atoml list
func (seg *Segment) SmartCut(atomList *AtomList, maxMode bool) []*WCell {
if len(atomList.List) < 1 {
return nil
}
if len(atomList.List) == 1 {
res := make([]*WCell, 1)
res[0] = NewWcell(atomList.List[0], 0, 1)
return res
}
cmap := seg.buildMap(atomList)
if maxMode {
res := make([]*WCell, 0, cmap.size)
cmap.IterRow(nil, -1, func(cur *Cursor) {
res = append(res, cur.val)
})
return res
}
return splitContent(cmap, seg.quantizer, atomList)
} | src/darts/darts.go | 0.628863 | 0.40698 | darts.go | starcoder |
package internal
import (
"log"
"reflect"
)
func StrictEqual(actual interface{}, expectation interface{}) bool {
if IsArray(actual) && IsArray(expectation) {
actualArr, _ := actual.([]interface{})
expectationArr, _ := expectation.([]interface{})
return EqualArray(actualArr, expectationArr)
}
if IsObject(actual) && IsObject(expectation) {
actualObj, _ := actual.(map[string]interface{})
expectedObj, _ := expectation.(map[string]interface{})
return EqualObject(actualObj, expectedObj)
}
panic("UNKNOWN TYPE")
}
// 12 == 12
func EqualPrimitive(actual interface{}, expected interface{}) bool {
return actual == expected
}
func EqualArray(actual []interface{}, expected []interface{}) bool {
actualLen := len(actual)
expectedLen := len(expected)
if actualLen != expectedLen {
return false
}
for i := 0; i < actualLen; i++ {
aValue := actual[i]
eValue := expected[i]
if !HaveSameType(aValue, eValue) {
return false
}
if IsObject(aValue) && IsObject(eValue) {
aValueObject, _ := aValue.(map[string]interface{})
eValueObject, _ := eValue.(map[string]interface{})
if !EqualObject(aValueObject, eValueObject) {
return false
}
}
if IsPrimitive(aValue) && IsPrimitive(eValue) {
if !EqualPrimitive(aValue, eValue) {
return false
}
}
if IsArray(aValue) && IsArray(eValue) {
aValueArray := aValue.([]interface{})
eValueArray := aValue.([]interface{})
if !EqualArray(aValueArray, eValueArray) {
return false
}
}
}
return true
}
// {name: "aa"} == {name: "bb"}
func EqualObject(actual map[string]interface{}, expected map[string]interface{}) bool {
actualType := reflect.TypeOf(actual)
typesEqual := actualType == reflect.TypeOf(expected)
if !typesEqual {
return false
}
if len(expected) != len(actual) {
return false
}
for key := range expected {
actualValue, hasActualKey := actual[key]
expectedValue, hasExpectedKey := expected[key]
if hasExpectedKey && !hasActualKey {
log.Print("Key difference")
return false
}
if !HaveSameType(actualValue, expectedValue) {
log.Print("Type difference")
return false
}
if IsPrimitive(actualValue) && IsPrimitive(expectedValue) {
if !EqualPrimitive(actualValue, expectedValue) {
return false
}
}
if IsObject(actualValue) && IsObject(expectedValue) {
actualChildObject, _ := actualValue.(map[string]interface{})
expectedChildObject, _ := expectedValue.(map[string]interface{})
if !EqualObject(actualChildObject, expectedChildObject) {
return false
}
}
if IsArray(actualValue) && IsArray(expectedValue) {
actualChildObject, _ := actualValue.([]interface{})
expectedChildObject, _ := expectedValue.([]interface{})
if !EqualArray(actualChildObject, expectedChildObject) {
return false
}
}
}
return true
} | internal/equal.go | 0.624408 | 0.469763 | equal.go | starcoder |
// Package parse implements a simple expression parser.
package parse
import (
"strconv"
"unicode"
)
// Node is a node in the parse tree. It is a union of the three basic
// types: Token (for all constants and variables), Call (for a
// call expressions) and Map (for a curly-braces expressions)
type Node struct {
*Token
*Call
*Map
}
// String formats the expression to the canonical infix form
func (n Node) String() string {
if n.Token != nil {
return n.Token.String()
}
if n.Call != nil {
return n.Call.String()
}
if n.Map != nil {
return n.Map.String()
}
return ""
}
// IsError returns whether the current node is an "error"
func (n Node) IsError() bool {
return n.Call != nil && n.Call.IsError()
}
// IsOperator returns if the current node is an operator
func (n Node) IsOperator() bool {
return n.Call != nil && n.Call.IsOperator()
}
// wrap is almost the same as String except it adds a bracket around
// the result if the node is an operator of lower priority
func (n Node) wrap(pri int, isLeft bool) string {
if n.IsOperator() && priority[n.Call.Nodes[0].Token.S] > pri {
return n.String()
}
if !n.IsOperator() && pri < priority["."] {
return n.String()
}
if n.Call == nil || (priority["."] == pri && isLeft) { // isLeft {
return n.String()
}
return "(" + n.String() + ")"
}
// Loc is the location in the input where this node starts
func (n Node) Loc() *Loc {
switch {
case n.Token != nil:
return n.Token.Loc
case n.Call != nil:
return n.Call.Loc
}
return n.Map.Loc
}
// Loc is a location in the input file being parsed. Offset is the
// offset in runes
type Loc struct {
File string
Offset int
}
// String returns a human readable string
func (l Loc) String() string {
return l.File + ":" + strconv.Itoa(l.Offset)
}
// Token is a token of input
type Token struct {
*Loc
S string
}
// String formats the token into a regular string
func (t Token) String() string {
if t.S == "" {
return "''"
}
quote, dquote := false, false
for _, r := range t.S {
_, isop := priority[string(r)]
quote = quote || r == '\''
dquote = dquote || (r == '"' || unicode.IsSpace(r) || isop)
}
if quote {
return `"` + t.S + `"`
}
if dquote {
return `'` + t.S + `'`
}
return t.S
}
// Call represents a function call or an operator expression
// The first node is the operator token for operator expressions and
// the function token/expression. The rest of the nodes are the
// operands or arguments
type Call struct {
*Loc
Nodes []Node
}
// IsError checks if the call is to "error" which is how errors are
// represented
func (c Call) IsError() bool {
return c.Nodes[0].Token != nil && c.Nodes[0].Token.S == "!"
}
// IsOperator checks if the Call is for an operator expression
func (c Call) IsOperator() bool {
if c.Nodes[0].Token == nil {
return false
}
_, ok := priority[c.Nodes[0].Token.S]
return ok
}
func (c Call) isBuiltin() bool {
if c.Nodes[0].Token == nil {
return false
}
s := c.Nodes[0].Token.S
return s == "builtin:number" || s == "builtin:string"
}
// String formats the call expression properly
func (c Call) String() string {
if c.IsError() {
loc := Token{S: c.Loc.String()}
return "!(" + c.Nodes[1].String() + ", " + loc.String() + ")"
}
if c.IsOperator() {
return c.formatOperation()
}
if c.isBuiltin() {
return c.Nodes[1].String()
}
result := c.Nodes[0].String() + "("
for kk, nn := range c.Nodes[1:] {
if kk == 0 {
result += nn.String()
} else {
result += ", " + nn.String()
}
}
return result + ")"
}
func (c Call) formatOperation() string {
pri := priority[c.Nodes[0].Token.S]
space := " "
if c.Nodes[0].Token.S == "." {
space = ""
}
result := c.Nodes[1].wrap(pri, true)
for _, nn := range c.Nodes[2:] {
result += space + c.Nodes[0].Token.S
result += space + nn.wrap(pri, false)
}
return result
}
// Map represents a map structure.
type Map struct {
*Loc
Pairs []Pair
}
// String formats the map
func (m Map) String() string {
result := "{"
for kk, pp := range m.Pairs {
if kk == 0 {
result += pp.String()
} else {
result += ", " + pp.String()
}
}
return result + "}"
}
// Pair represnets the key/value pair in a Map
type Pair struct {
*Loc
Key, Value Node
}
// String formats the key value pair
func (p Pair) String() string {
return p.Key.String() + " = " + p.Value.String()
} | parse/types.go | 0.817502 | 0.460653 | types.go | starcoder |
package termcolor
import (
"go.uber.org/zap"
"math"
"strconv"
"strings"
)
var (
// ANSI terminal control codes
// ColorPrefix contains the ANSI control code prefix
ColorPrefix = "\u001b["
// ColorSuffix contains the ANSI control code suffix
ColorSuffix = "m"
// Reset contains the ANSI control code to reset the format
Reset = ColorPrefix + "0" + ColorSuffix
// Bold contains the ANSI control code to enable bold text
Bold = "1" // Bold effect applies to text only (not background)
// Underline contains the ANSI control code to enable underlined text
Underline = "4" // Underline text
// Reverse contains the ANSI control code to enable reverse text
Reverse = "7" // Use reverse text (swap foreground and background)
)
// Fg returns ANSI color code for color "hex", applies to foreground
func Fg(hex string) string {
return "38;5;" + strconv.Itoa(int(HexToColor256(hex)))
}
// Bg return ANSI color code for color "hex", applies to background
func Bg(hex string) string {
return "48;5;" + strconv.Itoa(int(HexToColor256(hex)))
}
// HexToColor256 converts input "hex" into an ANSI color code (xterm-256)
// hex may be a set of 3 or 6 hexadecimal digits for RGB values
func HexToColor256(hex string) uint8 {
return RgbToColor256(HexToRgb(hex))
}
// RgbToColor256 converts the red, green, blue tuple into an ANSI color
// code (xterm-256)
func RgbToColor256(red, green, blue uint8) uint8 {
// red, green, blue range 0-255 on input
if red == green && red == blue {
// Grayscale
switch {
case red == 255:
// Bright white
return 15
case red == 0:
// Black
return 0
}
return 232 + uint8(math.Round(float64(red)/10.65))
}
return (36*ColorToAnsiIndex(red) +
6*ColorToAnsiIndex(green) +
ColorToAnsiIndex(blue)) + 16
}
// ColorToAnsiIndex converts a uint8 color value (0-255) into an ANSI
// color value (0-5)
func ColorToAnsiIndex(c uint8) uint8 {
return uint8(math.Round(float64(c) / 51.0))
}
// HexToRgb converts a 3 or 6 digit hexadecimal string, representing RGB
// values, into separate R,G,B values
func HexToRgb(hex string) (r, g, b uint8) {
switch len(hex) {
case 6:
r = HexToUint8(hex[:2])
g = HexToUint8(hex[2:4])
b = HexToUint8(hex[4:])
case 3:
r = HexToUint8(hex[:1] + hex[:1])
g = HexToUint8(hex[1:2] + hex[1:2])
b = HexToUint8(hex[2:3] + hex[2:3])
default:
zap.S().Errorf("Unsupported color %s", hex)
return uint8(255), uint8(255), uint8(255)
}
return
}
// HexToUint8 converts a hexadecimal string to a uint8
func HexToUint8(hexbyte string) uint8 {
val, _ := strconv.ParseUint(hexbyte, 16, 8)
return uint8(val)
}
// ExpandStyle expands a style string into an ANSI control code
func ExpandStyle(style string) string {
switch {
case strings.HasPrefix(style, "Fg#"):
fgstyle := style[3:]
return Fg(fgstyle)
case strings.HasPrefix(style, "Bg#"):
bgstyle := style[3:]
return Bg(bgstyle)
case style == "Bold":
return Bold
case style == "Underline":
return Underline
case style == "Reverse":
return Reverse
default:
zap.S().Warnf("Unhandled style [%s]", style)
}
return style
}
/* Colorize "message" with "style".
*
* Style may contain multiple conditions, delimited by "?". Such
* conditional parts are called "clauses".
*
* Clauses may contain an "=", in which case the part before the "="
* is the pattern which "message" must match, and the part after the
* "=" is the style to use.
*
* If no "?" is present, then there is no pattern or clause; all of
* "message" will be output in the specified "style".
*
* The style is formatted like "part[|part[|..]].".
*
* Each Part may be a color specification or an effect specification.
*
* Color specifications look like "Fg#rgb" or "Bg#rgb". Fg applies
* color rgb to the foreground; Gb to the background. Rgb consists of
* red, green, and blur components in hexadecimal format. Rgb may be
* 3 or 6 digits long, consisting of 1 or 2 digits for r, g, and b.
* Effects are listed above, such as Bold or Underline.
*
* Examples:
* Fg#fff changes the foreground color to white
* Fg#ffff00|Bold changes the foreground color to bold yellow
* ?Y=Fg#0f0|Bold?N=Fg#f00 uses a green foreground if the message
* matches "Y", or red if it matches "N"
**/
// Colorize applies style st to message, returning the colorized string
func Colorize(st Style, message string) string {
var sb strings.Builder
style := string(st)
if len(message) == 0 {
return message
}
for _, clause := range strings.Split(style, "?") {
// ignore whitespace
clause = strings.TrimSpace(clause)
// Skip if there is an empty clause
if len(clause) == 0 {
continue
}
/* If we need to match a specific pattern, skip any patterns
* that don't match.
**/
if strings.Contains(clause, "=") {
eq := strings.Index(clause, "=")
pattern := strings.TrimSpace(clause[:eq])
style = strings.TrimSpace(clause[eq+1:])
if pattern != message {
style = ""
continue
}
break
}
}
if len(style) == 0 {
return message
}
parts := make([]string, 0)
sb.WriteString(ColorPrefix)
for _, s := range strings.Split(style, "|") {
parts = append(parts, ExpandStyle(strings.TrimSpace(s)))
}
sb.WriteString(strings.Join(parts, ";"))
sb.WriteString(ColorSuffix)
sb.WriteString(message)
sb.WriteString(Reset)
return sb.String()
} | pkg/termcolor/termcolor.go | 0.735167 | 0.433322 | termcolor.go | starcoder |
package f5api
// This describes a message sent to or received from some operations
type NetStpGlobals struct {
// Specifies the time interval in seconds between the periodic transmissions that communicate spanning tree information to the adjacent bridges in the network. The default value is 2 seconds, and the valid range is 1 to 10. The default hello time is optimal in virtually all cases. F5 recommends that you do not change the hello time.
HelloTime int64 `json:"helloTime,omitempty"`
// Specifies the absolute limit on the number of spanning tree protocol packets the traffic management system may transmit on a port in any hello time interval. It is used to ensure that spanning tree packets do not unduly load the network even in unstable situations. The default value is 6 packets, and the valid range is 1 to 10 packets.
TransmitHold int64 `json:"transmitHold,omitempty"`
// Specifies the configuration name (1 - 32 characters in length) only when the spanning tree mode is MSTP. The default configuration name is a string representation of a globally-unique MAC address belonging to the traffic management system.The MSTP standard introduces the concept of spanning tree regions, which are groups of adjacent bridges with identical configuration names, configuration revision levels, and assignments of VLANs to spanning tree instances.
ConfigName string `json:"configName,omitempty"`
// User defined description.
Description string `json:"description,omitempty"`
// Kind of entity
Kind string `json:"kind,omitempty"`
// Specifies the number of seconds for which spanning tree information received from other bridges is considered valid. The default value is 20 seconds, and the valid range is 6 to 40 seconds.
MaxAge int64 `json:"maxAge,omitempty"`
// Specifies the maximum number of hops an MSTP packet may travel before it is discarded. Use this option only when the spanning tree mode is MSTP. The number of hops must be in the range of 1 to 255 hops. The default number of hops is 20.
MaxHops int64 `json:"maxHops,omitempty"`
// Specifies the revision level of the MSTP configuration only when the spanning tree mode is MSTP. The specified number must be in the range 0 to 65535. The default value is 0 (zero).
ConfigRevision int64 `json:"configRevision,omitempty"`
// In the original Spanning Tree Protocol, the forward delay parameter controlled the number of seconds for which an interface was blocked from forwarding network traffic after a reconfiguration of the spanning tree topology. This parameter has no effect when RSTP or MSTP are used, as long as all bridges in the spanning tree use the RSTP or MSTP protocol. If any legacy STP bridges are present, then neighboring bridges must fall back to the old protocol, whose reconfiguration time is affected by the forward delay value. The default forward delay value is 15, and the valid range is 4 to 30.
FwdDelay int64 `json:"fwdDelay,omitempty"`
// Specifies the spanning tree modes.
Mode string `json:"mode,omitempty"`
// Name of entity
Name string `json:"name,omitempty"`
} | net_stp_globals.go | 0.845465 | 0.534855 | net_stp_globals.go | starcoder |
// Utility methods to calculate percentiles from raw data.
package statscollector
import (
"math"
"sort"
"time"
"github.com/golang/glog"
cadvisor "github.com/google/cadvisor/info"
)
const milliSecondsToNanoSeconds = 1000000
const secondsToMilliSeconds = 1000
type uint64Slice []uint64
func (a uint64Slice) Len() int { return len(a) }
func (a uint64Slice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a uint64Slice) Less(i, j int) bool { return a[i] < a[j] }
// Get 90th percentile of the provided samples. Round to integer.
func Get90Percentile(samples uint64Slice) uint64 {
count := len(samples)
if count == 0 {
return 0
}
sort.Sort(samples)
n := float64(0.9 * (float64(count) + 1))
idx, frac := math.Modf(n)
index := int(idx)
percentile := float64(samples[index-1])
if index > 1 || index < count {
percentile += frac * float64(samples[index]-samples[index-1])
}
return uint64(percentile)
}
// Add new sample to existing average.
func GetMean(mean float64, value uint64, count uint64) float64 {
if count < 1 {
return 0
}
c := float64(count)
v := float64(value)
return (mean*(c-1) + v) / c
}
func GetPercentiles(stats []*cadvisor.ContainerStats) (Percentiles, Percentiles) {
lastCpu := uint64(0)
lastTime := time.Time{}
memorySamples := make(uint64Slice, 0, len(stats))
cpuSamples := make(uint64Slice, 0, len(stats)-1)
numSamples := 0
memoryMean := float64(0)
cpuMean := float64(0)
memoryPercentiles := Percentiles{}
cpuPercentiles := Percentiles{}
for _, stat := range stats {
var elapsed int64
time := stat.Timestamp
if !lastTime.IsZero() {
elapsed = time.UnixNano() - lastTime.UnixNano()
if elapsed < 10*milliSecondsToNanoSeconds {
glog.Infof("Elapsed time too small: %d ns: time now %s last %s", elapsed, time.String(), lastTime.String())
continue
}
}
numSamples++
cpuNs := stat.Cpu.Usage.Total
// Ignore actual usage and only focus on working set.
memory := stat.Memory.WorkingSet
if memory > memoryPercentiles.Max {
memoryPercentiles.Max = memory
}
glog.V(2).Infof("Read sample: cpu %d, memory %d", cpuNs, memory)
memoryMean = GetMean(memoryMean, memory, uint64(numSamples))
memorySamples = append(memorySamples, memory)
if lastTime.IsZero() {
lastCpu = cpuNs
lastTime = time
continue
}
cpuRate := (cpuNs - lastCpu) * secondsToMilliSeconds / uint64(elapsed)
if cpuRate < 0 {
glog.Infof("cpu rate too small: %f ns", cpuRate)
continue
}
glog.V(2).Infof("Adding cpu rate sample : %d", cpuRate)
lastCpu = cpuNs
lastTime = time
cpuSamples = append(cpuSamples, cpuRate)
if cpuRate > cpuPercentiles.Max {
cpuPercentiles.Max = cpuRate
}
cpuMean = GetMean(cpuMean, cpuRate, uint64(numSamples-1))
}
cpuPercentiles.Mean = uint64(cpuMean)
memoryPercentiles.Mean = uint64(memoryMean)
cpuPercentiles.Ninety = Get90Percentile(cpuSamples)
memoryPercentiles.Ninety = Get90Percentile(memorySamples)
return cpuPercentiles, memoryPercentiles
} | pkg/statscollector/util.go | 0.710729 | 0.560433 | util.go | starcoder |
package models
import (
i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time"
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// AccessPackageAssignmentRequest
type AccessPackageAssignmentRequest struct {
Entity
// The access package associated with the accessPackageAssignmentRequest. An access package defines the collections of resource roles and the policies for how one or more users can get access to those resources. Read-only. Nullable. Supports $expand.
accessPackage AccessPackageable
// For a requestType of UserAdd or AdminAdd, this is an access package assignment requested to be created. For a requestType of UserRemove, AdminRemove or SystemRemove, this has the id property of an existing assignment to be removed. Supports $expand.
assignment AccessPackageAssignmentable
// The date of the end of processing, either successful or failure, of a request. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Read-only.
completedDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time
// The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Read-only.
createdDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time
// The subject who requested or, if a direct assignment, was assigned. Read-only. Nullable. Supports $expand.
requestor AccessPackageSubjectable
// One of UserAdd, UserRemove, AdminAdd, AdminRemove or SystemRemove. A request from the user themselves would have requestType of UserAdd or UserRemove. Read-only.
requestType *AccessPackageRequestType
// The range of dates that access is to be assigned to the requestor. Read-only.
schedule EntitlementManagementScheduleable
// The state of the request. The possible values are: submitted, pendingApproval, delivering, delivered, deliveryFailed, denied, scheduled, canceled, partiallyDelivered, unknownFutureValue. Read-only.
state *AccessPackageRequestState
// More information on the request processing status. Read-only.
status *string
}
// NewAccessPackageAssignmentRequest instantiates a new accessPackageAssignmentRequest and sets the default values.
func NewAccessPackageAssignmentRequest()(*AccessPackageAssignmentRequest) {
m := &AccessPackageAssignmentRequest{
Entity: *NewEntity(),
}
return m
}
// CreateAccessPackageAssignmentRequestFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateAccessPackageAssignmentRequestFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewAccessPackageAssignmentRequest(), nil
}
// GetAccessPackage gets the accessPackage property value. The access package associated with the accessPackageAssignmentRequest. An access package defines the collections of resource roles and the policies for how one or more users can get access to those resources. Read-only. Nullable. Supports $expand.
func (m *AccessPackageAssignmentRequest) GetAccessPackage()(AccessPackageable) {
if m == nil {
return nil
} else {
return m.accessPackage
}
}
// GetAssignment gets the assignment property value. For a requestType of UserAdd or AdminAdd, this is an access package assignment requested to be created. For a requestType of UserRemove, AdminRemove or SystemRemove, this has the id property of an existing assignment to be removed. Supports $expand.
func (m *AccessPackageAssignmentRequest) GetAssignment()(AccessPackageAssignmentable) {
if m == nil {
return nil
} else {
return m.assignment
}
}
// GetCompletedDateTime gets the completedDateTime property value. The date of the end of processing, either successful or failure, of a request. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Read-only.
func (m *AccessPackageAssignmentRequest) GetCompletedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {
if m == nil {
return nil
} else {
return m.completedDateTime
}
}
// GetCreatedDateTime gets the createdDateTime property value. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Read-only.
func (m *AccessPackageAssignmentRequest) GetCreatedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {
if m == nil {
return nil
} else {
return m.createdDateTime
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *AccessPackageAssignmentRequest) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["accessPackage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateAccessPackageFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetAccessPackage(val.(AccessPackageable))
}
return nil
}
res["assignment"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateAccessPackageAssignmentFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetAssignment(val.(AccessPackageAssignmentable))
}
return nil
}
res["completedDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetTimeValue()
if err != nil {
return err
}
if val != nil {
m.SetCompletedDateTime(val)
}
return nil
}
res["createdDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetTimeValue()
if err != nil {
return err
}
if val != nil {
m.SetCreatedDateTime(val)
}
return nil
}
res["requestor"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateAccessPackageSubjectFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetRequestor(val.(AccessPackageSubjectable))
}
return nil
}
res["requestType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseAccessPackageRequestType)
if err != nil {
return err
}
if val != nil {
m.SetRequestType(val.(*AccessPackageRequestType))
}
return nil
}
res["schedule"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateEntitlementManagementScheduleFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetSchedule(val.(EntitlementManagementScheduleable))
}
return nil
}
res["state"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseAccessPackageRequestState)
if err != nil {
return err
}
if val != nil {
m.SetState(val.(*AccessPackageRequestState))
}
return nil
}
res["status"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetStatus(val)
}
return nil
}
return res
}
// GetRequestor gets the requestor property value. The subject who requested or, if a direct assignment, was assigned. Read-only. Nullable. Supports $expand.
func (m *AccessPackageAssignmentRequest) GetRequestor()(AccessPackageSubjectable) {
if m == nil {
return nil
} else {
return m.requestor
}
}
// GetRequestType gets the requestType property value. One of UserAdd, UserRemove, AdminAdd, AdminRemove or SystemRemove. A request from the user themselves would have requestType of UserAdd or UserRemove. Read-only.
func (m *AccessPackageAssignmentRequest) GetRequestType()(*AccessPackageRequestType) {
if m == nil {
return nil
} else {
return m.requestType
}
}
// GetSchedule gets the schedule property value. The range of dates that access is to be assigned to the requestor. Read-only.
func (m *AccessPackageAssignmentRequest) GetSchedule()(EntitlementManagementScheduleable) {
if m == nil {
return nil
} else {
return m.schedule
}
}
// GetState gets the state property value. The state of the request. The possible values are: submitted, pendingApproval, delivering, delivered, deliveryFailed, denied, scheduled, canceled, partiallyDelivered, unknownFutureValue. Read-only.
func (m *AccessPackageAssignmentRequest) GetState()(*AccessPackageRequestState) {
if m == nil {
return nil
} else {
return m.state
}
}
// GetStatus gets the status property value. More information on the request processing status. Read-only.
func (m *AccessPackageAssignmentRequest) GetStatus()(*string) {
if m == nil {
return nil
} else {
return m.status
}
}
// Serialize serializes information the current object
func (m *AccessPackageAssignmentRequest) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteObjectValue("accessPackage", m.GetAccessPackage())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("assignment", m.GetAssignment())
if err != nil {
return err
}
}
{
err = writer.WriteTimeValue("completedDateTime", m.GetCompletedDateTime())
if err != nil {
return err
}
}
{
err = writer.WriteTimeValue("createdDateTime", m.GetCreatedDateTime())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("requestor", m.GetRequestor())
if err != nil {
return err
}
}
if m.GetRequestType() != nil {
cast := (*m.GetRequestType()).String()
err = writer.WriteStringValue("requestType", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("schedule", m.GetSchedule())
if err != nil {
return err
}
}
if m.GetState() != nil {
cast := (*m.GetState()).String()
err = writer.WriteStringValue("state", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("status", m.GetStatus())
if err != nil {
return err
}
}
return nil
}
// SetAccessPackage sets the accessPackage property value. The access package associated with the accessPackageAssignmentRequest. An access package defines the collections of resource roles and the policies for how one or more users can get access to those resources. Read-only. Nullable. Supports $expand.
func (m *AccessPackageAssignmentRequest) SetAccessPackage(value AccessPackageable)() {
if m != nil {
m.accessPackage = value
}
}
// SetAssignment sets the assignment property value. For a requestType of UserAdd or AdminAdd, this is an access package assignment requested to be created. For a requestType of UserRemove, AdminRemove or SystemRemove, this has the id property of an existing assignment to be removed. Supports $expand.
func (m *AccessPackageAssignmentRequest) SetAssignment(value AccessPackageAssignmentable)() {
if m != nil {
m.assignment = value
}
}
// SetCompletedDateTime sets the completedDateTime property value. The date of the end of processing, either successful or failure, of a request. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Read-only.
func (m *AccessPackageAssignmentRequest) SetCompletedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {
if m != nil {
m.completedDateTime = value
}
}
// SetCreatedDateTime sets the createdDateTime property value. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Read-only.
func (m *AccessPackageAssignmentRequest) SetCreatedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {
if m != nil {
m.createdDateTime = value
}
}
// SetRequestor sets the requestor property value. The subject who requested or, if a direct assignment, was assigned. Read-only. Nullable. Supports $expand.
func (m *AccessPackageAssignmentRequest) SetRequestor(value AccessPackageSubjectable)() {
if m != nil {
m.requestor = value
}
}
// SetRequestType sets the requestType property value. One of UserAdd, UserRemove, AdminAdd, AdminRemove or SystemRemove. A request from the user themselves would have requestType of UserAdd or UserRemove. Read-only.
func (m *AccessPackageAssignmentRequest) SetRequestType(value *AccessPackageRequestType)() {
if m != nil {
m.requestType = value
}
}
// SetSchedule sets the schedule property value. The range of dates that access is to be assigned to the requestor. Read-only.
func (m *AccessPackageAssignmentRequest) SetSchedule(value EntitlementManagementScheduleable)() {
if m != nil {
m.schedule = value
}
}
// SetState sets the state property value. The state of the request. The possible values are: submitted, pendingApproval, delivering, delivered, deliveryFailed, denied, scheduled, canceled, partiallyDelivered, unknownFutureValue. Read-only.
func (m *AccessPackageAssignmentRequest) SetState(value *AccessPackageRequestState)() {
if m != nil {
m.state = value
}
}
// SetStatus sets the status property value. More information on the request processing status. Read-only.
func (m *AccessPackageAssignmentRequest) SetStatus(value *string)() {
if m != nil {
m.status = value
}
} | models/access_package_assignment_request.go | 0.699357 | 0.434641 | access_package_assignment_request.go | starcoder |
// Package skein1024 implements the Skein1024 hash function
// based on the Threefish1024 tweakable block cipher.
package skein1024
import (
"hash"
"github.com/aead/skein"
)
// Sum512 computes the 512 bit Skein1024 checksum (or MAC if key is set) of msg
// and writes it to out. The key is optional and can be nil.
func Sum512(out *[64]byte, msg, key []byte) {
var out1024 [128]byte
s := new(hashFunc)
s.initialize(64, &skein.Config{Key: key})
s.Write(msg)
s.finalizeHash()
s.output(&out1024, 0)
copy(out[:], out1024[:64])
}
// Sum384 computes the 384 bit Skein1024 checksum (or MAC if key is set) of msg
// and writes it to out. The key is optional and can be nil.
func Sum384(out *[48]byte, msg, key []byte) {
var out1024 [128]byte
s := new(hashFunc)
s.initialize(48, &skein.Config{Key: key})
s.Write(msg)
s.finalizeHash()
s.output(&out1024, 0)
copy(out[:], out1024[:48])
}
// Sum256 computes the 256 bit Skein1024 checksum (or MAC if key is set) of msg
// and writes it to out. The key is optional and can be nil.
func Sum256(out *[32]byte, msg, key []byte) {
var out1024 [128]byte
s := new(hashFunc)
s.initialize(32, &skein.Config{Key: key})
s.Write(msg)
s.finalizeHash()
s.output(&out1024, 0)
copy(out[:], out1024[:32])
}
// Sum160 computes the 160 bit Skein1024 checksum (or MAC if key is set) of msg
// and writes it to out. The key is optional and can be nil.
func Sum160(out *[20]byte, msg, key []byte) {
var out1024 [128]byte
s := new(hashFunc)
s.initialize(20, &skein.Config{Key: key})
s.Write(msg)
s.finalizeHash()
s.output(&out1024, 0)
copy(out[:], out1024[:20])
}
// Sum returns the Skein1024 checksum with the given hash size of msg using the (optional)
// conf for configuration. The hashsize must be > 0.
func Sum(msg []byte, hashsize int, conf *skein.Config) []byte {
s := New(hashsize, conf)
s.Write(msg)
return s.Sum(nil)
}
// New512 returns a hash.Hash computing the Skein1024 512 bit checksum.
// The key is optional and turns the hash into a MAC.
func New512(key []byte) hash.Hash {
s := new(hashFunc)
s.initialize(64, &skein.Config{Key: key})
return s
}
// New256 returns a hash.Hash computing the Skein1024 256 bit checksum.
// The key is optional and turns the hash into a MAC.
func New256(key []byte) hash.Hash {
s := new(hashFunc)
s.initialize(32, &skein.Config{Key: key})
return s
}
// New returns a hash.Hash computing the Skein1024 checksum with the given hash size.
// The conf is optional and configurates the hash.Hash
func New(hashsize int, conf *skein.Config) hash.Hash {
s := new(hashFunc)
s.initialize(hashsize, conf)
return s
} | vendor/github.com/aead/skein/skein1024/skein.go | 0.840029 | 0.449211 | skein.go | starcoder |
package mathutil
import (
"image"
"golang.org/x/image/math/fixed"
)
// Integer based float. Based on fixed.Int52_12.
type Intf int64
func Intf1(x int) Intf { return Intf(x) << 12 }
func Intf2(x fixed.Int26_6) Intf { return Intf(x) << 6 }
func (x Intf) Floor() int { return int(x >> 12) }
func (x Intf) Ceil() int { return int((x + 0xfff) >> 12) }
func (x Intf) Mul(y Intf) Intf {
a := fixed.Int52_12(x)
b := fixed.Int52_12(y)
return Intf(a.Mul(b))
}
func (x Intf) String() string {
return fixed.Int52_12(x).String()
}
//----------
type PointIntf struct {
X, Y Intf
}
func PIntf1(x, y int) PointIntf {
x2 := Intf1(x)
y2 := Intf1(y)
return PointIntf{x2, y2}
}
func PIntf2(p image.Point) PointIntf {
return PIntf1(p.X, p.Y)
}
func (p PointIntf) Add(q PointIntf) PointIntf {
return PointIntf{p.X + q.X, p.Y + q.Y}
}
func (p PointIntf) Sub(q PointIntf) PointIntf {
return PointIntf{p.X - q.X, p.Y - q.Y}
}
func (p PointIntf) In(r RectangleIntf) bool {
return r.Min.X <= p.X && p.X < r.Max.X && r.Min.Y <= p.Y && p.Y < r.Max.Y
}
func (p PointIntf) ToPointCeil() image.Point {
return image.Point{p.X.Ceil(), p.Y.Ceil()}
}
func (p PointIntf) ToPointFloor() image.Point {
return image.Point{p.X.Floor(), p.Y.Floor()}
}
//----------
type RectangleIntf struct {
Min, Max PointIntf
}
func RIntf(r image.Rectangle) RectangleIntf {
min := PIntf2(r.Min)
max := PIntf2(r.Max)
return RectangleIntf{min, max}
}
func (r RectangleIntf) Add(p PointIntf) RectangleIntf {
return RectangleIntf{r.Min.Add(p), r.Max.Add(p)}
}
func (r RectangleIntf) Sub(p PointIntf) RectangleIntf {
return RectangleIntf{r.Min.Sub(p), r.Max.Sub(p)}
}
func (r RectangleIntf) Intersect(s RectangleIntf) RectangleIntf {
if r.Min.X < s.Min.X {
r.Min.X = s.Min.X
}
if r.Min.Y < s.Min.Y {
r.Min.Y = s.Min.Y
}
if r.Max.X > s.Max.X {
r.Max.X = s.Max.X
}
if r.Max.Y > s.Max.Y {
r.Max.Y = s.Max.Y
}
if r.Empty() {
return RectangleIntf{}
}
return r
}
func (r RectangleIntf) Empty() bool {
return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y
}
func (r RectangleIntf) ToRectFloorCeil() image.Rectangle {
min := r.Min.ToPointFloor()
max := r.Max.ToPointCeil()
return image.Rectangle{min, max}
} | util/mathutil/geom.go | 0.801936 | 0.508788 | geom.go | starcoder |
package field
import (
"errors"
"fmt"
"github.com/xichen2020/eventdb/document/field"
"github.com/xichen2020/eventdb/filter"
"github.com/xichen2020/eventdb/index"
"github.com/xichen2020/eventdb/values/impl"
"github.com/xichen2020/eventdb/x/bytes"
"github.com/xichen2020/eventdb/x/pool"
"github.com/pilosa/pilosa/roaring"
)
// DocsFieldMetadata contains the documents field metadata.
type DocsFieldMetadata struct {
FieldPath []string
FieldTypes []field.ValueType
}
// DocsField is a field containing one or more types of field values and associated doc
// IDs across multiple documents for a given field.
type DocsField interface {
// Metadata returns the field metadata.
Metadata() DocsFieldMetadata
// NullField returns the field subset that has null values, or false otherwise.
// The null field remains valid until the docs field is closed.
NullField() (NullField, bool)
// BoolField returns the field subset that has bool values, or false otherwise.
// The bool field remains valid until the docs field is closed.
BoolField() (BoolField, bool)
// IntField returns the field subset that has int values, or false otherwise.
// The int field remains valid until the docs field is closed.
IntField() (IntField, bool)
// DoubleField returns the field subset that has double values, or false otherwise.
// The double field remains valid until the docs field is closed.
DoubleField() (DoubleField, bool)
// BytesField returns the field subset that has bytes values, or false otherwise.
// The bytes field remains valid until the docs field is closed.
BytesField() (BytesField, bool)
// TimeField returns the field subset that has time values, or false otherwise.
// The time field remains valid until the docs field is closed.
TimeField() (TimeField, bool)
// FieldForType returns the typed field for a given type, or false otherwise.
// The typed field remains valid until the docs field is closed.
FieldForType(t field.ValueType) (Union, bool)
// NewDocsFieldFor returns a new docs field containing a shallow copy of the typed
// fields (sharing access to the underlying resources) specified in the given value
// type set. If a given type does not exist in the current field, it is added to
// the value type set returned. If a field type is invalid, an error is returned.
NewDocsFieldFor(fieldTypes field.ValueTypeSet) (DocsField, field.ValueTypeSet, error)
// ShallowCopy returns a shallow copy of the docs field sharing access to the
// underlying resources and typed fields. As such the resources held will not
// be released until both the shallow copy and the original owner are closed.
ShallowCopy() DocsField
// NewMergedDocsField creates a new merged docs field by merging the fields in the current
// docs field and the other docs field, with the current docs field taking precedence for
// a given field type if both the current docs field and the other docs field has the corresponding
// field. Both the current docs field and the other docs field remains valid after the call.
NewMergedDocsField(other DocsField) DocsField
// Filter applies the given filter against the different types of fields in the docs field,
// returning a doc ID set iterator that returns the documents matching the filter.
Filter(
op filter.Op,
filterValue *field.ValueUnion,
numTotalDocs int32,
) (index.DocIDSetIterator, error)
// Close closes the field. It will also releases any resources held iff there is
// no one holding references to the field.
Close()
// Interal APIs used within the package.
// closeableNullField returns a closeable field subset that has null values, or false otherwise.
// The null field remains valid until the docs field is closed.
closeableNullField() (CloseableNullField, bool)
// closeableBoolField returns a closeable field subset that has bool values, or false otherwise.
// The bool field remains valid until the docs field is closed.
closeableBoolField() (CloseableBoolField, bool)
// closeableIntField returns a closeable field subset that has int values, or false otherwise.
// The int field remains valid until the docs field is closed.
closeableIntField() (CloseableIntField, bool)
// closeableDoubleField returns a closeable field subset that has double values, or false otherwise.
// The double field remains valid until the docs field is closed.
closeableDoubleField() (CloseableDoubleField, bool)
// closeableBytesField returns a closeable field subset that has bytes values, or false otherwise.
// The bytes field remains valid until the docs field is closed.
closeableBytesField() (CloseableBytesField, bool)
// closeableTimeField returns a closeable field subset that has time values, or false otherwise.
// The time field remains valid until the docs field is closed.
closeableTimeField() (CloseableTimeField, bool)
}
// DocsFieldBuilder builds a collection of field values.
type DocsFieldBuilder interface {
// Add adds a value with its document ID.
Add(docID int32, v field.ValueUnion) error
// Snapshot return an immutable snapshot of the typed fields for the given
// value type set, returning the new docs field and any types remaining in
// the given value type set that's not available in the builder.
SnapshotFor(fieldTypes field.ValueTypeSet) (DocsField, field.ValueTypeSet, error)
// Seal seals and closes the builder and returns an immutable docs field that contains (and
// owns) all the doc IDs and the field values accummulated across `numTotalDocs`
// documents for this field thus far. The resource ownership is transferred from the
// builder to the immutable collection as a result. Adding more data to the builder
// after the builder is sealed will result in an error.
Seal(numTotalDocs int32) DocsField
// Close closes the builder.
Close()
}
// CloseFn closes a field.
type CloseFn func()
var (
// NilDocsField is a nil docs field that can only be used for filtering.
NilDocsField DocsField = (*docsField)(nil)
errDocsFieldBuilderAlreadyClosed = errors.New("docs field builder is already closed")
)
// docsField is an immutable collection of different typed fields at the same field path.
// The internal fields of an `docsField` object remains unchanged until the docs field is closed.
// `docsField` is not thread safe. Concurrent access to `docsField` (e.g., calling reading and
// closing APIs) must be protected with synchronization alternatives.
type docsField struct {
fieldPath []string
fieldTypes []field.ValueType
closed bool
nf CloseableNullField
bf CloseableBoolField
intf CloseableIntField
df CloseableDoubleField
sf CloseableBytesField
tf CloseableTimeField
}
// NewDocsField creates a new docs field.
func NewDocsField(
fieldPath []string,
fieldTypes []field.ValueType,
nf CloseableNullField,
bf CloseableBoolField,
intf CloseableIntField,
df CloseableDoubleField,
sf CloseableBytesField,
tf CloseableTimeField,
) DocsField {
return &docsField{
fieldPath: fieldPath,
fieldTypes: fieldTypes,
nf: nf,
bf: bf,
intf: intf,
df: df,
sf: sf,
tf: tf,
}
}
func (f *docsField) Metadata() DocsFieldMetadata {
return DocsFieldMetadata{
FieldPath: f.fieldPath,
FieldTypes: f.fieldTypes,
}
}
func (f *docsField) NullField() (NullField, bool) {
if f.nf == nil {
return nil, false
}
return f.nf, true
}
func (f *docsField) BoolField() (BoolField, bool) {
if f.bf == nil {
return nil, false
}
return f.bf, true
}
func (f *docsField) IntField() (IntField, bool) {
if f.intf == nil {
return nil, false
}
return f.intf, true
}
func (f *docsField) DoubleField() (DoubleField, bool) {
if f.df == nil {
return nil, false
}
return f.df, true
}
func (f *docsField) BytesField() (BytesField, bool) {
if f.sf == nil {
return nil, false
}
return f.sf, true
}
func (f *docsField) TimeField() (TimeField, bool) {
if f.tf == nil {
return nil, false
}
return f.tf, true
}
func (f *docsField) FieldForType(t field.ValueType) (Union, bool) {
switch t {
case field.NullType:
if nf, exists := f.NullField(); exists {
return Union{Type: field.NullType, NullField: nf}, true
}
case field.BoolType:
if bf, exists := f.BoolField(); exists {
return Union{Type: field.BoolType, BoolField: bf}, true
}
case field.IntType:
if intf, exists := f.IntField(); exists {
return Union{Type: field.IntType, IntField: intf}, true
}
case field.DoubleType:
if df, exists := f.DoubleField(); exists {
return Union{Type: field.DoubleType, DoubleField: df}, true
}
case field.BytesType:
if sf, exists := f.BytesField(); exists {
return Union{Type: field.BytesType, BytesField: sf}, true
}
case field.TimeType:
if tf, exists := f.TimeField(); exists {
return Union{Type: field.TimeType, TimeField: tf}, true
}
}
return Union{}, false
}
func (f *docsField) NewDocsFieldFor(
fieldTypes field.ValueTypeSet,
) (DocsField, field.ValueTypeSet, error) {
var (
nf CloseableNullField
bf CloseableBoolField
intf CloseableIntField
df CloseableDoubleField
sf CloseableBytesField
tf CloseableTimeField
availableTypes = make([]field.ValueType, 0, len(fieldTypes))
remainingTypes field.ValueTypeSet
err error
)
for t := range fieldTypes {
hasType := true
switch t {
case field.NullType:
if f.nf != nil {
nf = f.nf.ShallowCopy()
break
}
hasType = false
case field.BoolType:
if f.bf != nil {
bf = f.bf.ShallowCopy()
break
}
hasType = false
case field.IntType:
if f.intf != nil {
intf = f.intf.ShallowCopy()
break
}
hasType = false
case field.DoubleType:
if f.df != nil {
df = f.df.ShallowCopy()
break
}
hasType = false
case field.BytesType:
if f.sf != nil {
sf = f.sf.ShallowCopy()
break
}
hasType = false
case field.TimeType:
if f.tf != nil {
tf = f.tf.ShallowCopy()
break
}
hasType = false
default:
err = fmt.Errorf("unknown field type %v", t)
}
if err != nil {
break
}
if hasType {
availableTypes = append(availableTypes, t)
continue
}
if remainingTypes == nil {
remainingTypes = make(field.ValueTypeSet, len(fieldTypes))
}
remainingTypes[t] = struct{}{}
}
if err == nil {
return NewDocsField(f.fieldPath, availableTypes, nf, bf, intf, df, sf, tf), remainingTypes, nil
}
// Close all resources on error.
if nf != nil {
nf.Close()
}
if bf != nil {
bf.Close()
}
if intf != nil {
intf.Close()
}
if df != nil {
df.Close()
}
if sf != nil {
sf.Close()
}
if tf != nil {
tf.Close()
}
return nil, nil, err
}
func (f *docsField) ShallowCopy() DocsField {
var (
nf CloseableNullField
bf CloseableBoolField
intf CloseableIntField
df CloseableDoubleField
sf CloseableBytesField
tf CloseableTimeField
)
if f.nf != nil {
nf = f.nf.ShallowCopy()
}
if f.bf != nil {
bf = f.bf.ShallowCopy()
}
if f.intf != nil {
intf = f.intf.ShallowCopy()
}
if f.df != nil {
df = f.df.ShallowCopy()
}
if f.sf != nil {
sf = f.sf.ShallowCopy()
}
if f.tf != nil {
tf = f.tf.ShallowCopy()
}
return NewDocsField(f.fieldPath, f.fieldTypes, nf, bf, intf, df, sf, tf)
}
func (f *docsField) NewMergedDocsField(other DocsField) DocsField {
if other == nil {
return f.ShallowCopy()
}
var (
nf CloseableNullField
bf CloseableBoolField
intf CloseableIntField
df CloseableDoubleField
sf CloseableBytesField
tf CloseableTimeField
merged bool
)
if f.nf != nil {
nf = f.nf.ShallowCopy()
} else if onf, exists := other.closeableNullField(); exists {
nf = onf.ShallowCopy()
merged = true
}
if f.bf != nil {
bf = f.bf.ShallowCopy()
} else if obf, exists := other.closeableBoolField(); exists {
bf = obf.ShallowCopy()
merged = true
}
if f.intf != nil {
intf = f.intf.ShallowCopy()
} else if ointf, exists := other.closeableIntField(); exists {
intf = ointf.ShallowCopy()
merged = true
}
if f.df != nil {
df = f.df.ShallowCopy()
} else if odf, exists := other.closeableDoubleField(); exists {
df = odf.ShallowCopy()
merged = true
}
if f.sf != nil {
sf = f.sf.ShallowCopy()
} else if osf, exists := other.closeableBytesField(); exists {
sf = osf.ShallowCopy()
merged = true
}
if f.tf != nil {
tf = f.tf.ShallowCopy()
} else if otf, exists := other.closeableTimeField(); exists {
tf = otf.ShallowCopy()
merged = true
}
fieldTypes := f.fieldTypes
if merged {
fieldTypes = field.MergeTypes(f.fieldTypes, other.Metadata().FieldTypes)
}
return NewDocsField(f.fieldPath, fieldTypes, nf, bf, intf, df, sf, tf)
}
// TODO(xichen): Add filter tests.
func (f *docsField) Filter(
op filter.Op,
filterValue *field.ValueUnion,
numTotalDocs int32,
) (index.DocIDSetIterator, error) {
if f == nil || len(f.fieldTypes) == 0 {
docIDIter := index.NewEmptyDocIDSetIterator()
if op.IsDocIDSetFilter() {
docIDSetIteratorFn := op.MustDocIDSetFilterFn(numTotalDocs)
return docIDSetIteratorFn(docIDIter), nil
}
return docIDIter, nil
}
if len(f.fieldTypes) == 1 {
return f.filterForType(f.fieldTypes[0], op, filterValue, numTotalDocs)
}
combinator, err := op.MultiTypeCombinator()
if err != nil {
return nil, err
}
iters := make([]index.DocIDSetIterator, 0, len(f.fieldTypes))
for _, t := range f.fieldTypes {
iter, err := f.filterForType(t, op, filterValue, numTotalDocs)
if err != nil {
return nil, err
}
iters = append(iters, iter)
}
switch combinator {
case filter.And:
return index.NewInAllDocIDSetIterator(iters...), nil
case filter.Or:
return index.NewInAnyDocIDSetIterator(iters...), nil
default:
return nil, fmt.Errorf("unknown filter combinator %v", combinator)
}
}
// Precondition: Field type `t` is guaranteed to exist in the docs field.
func (f *docsField) filterForType(
t field.ValueType,
op filter.Op,
filterValue *field.ValueUnion,
numTotalDocs int32,
) (index.DocIDSetIterator, error) {
switch t {
case field.NullType:
return f.nf.Filter(op, filterValue, numTotalDocs)
case field.BoolType:
return f.bf.Filter(op, filterValue, numTotalDocs)
case field.IntType:
return f.intf.Filter(op, filterValue, numTotalDocs)
case field.DoubleType:
return f.df.Filter(op, filterValue, numTotalDocs)
case field.BytesType:
return f.sf.Filter(op, filterValue, numTotalDocs)
case field.TimeType:
return f.tf.Filter(op, filterValue, numTotalDocs)
default:
return nil, fmt.Errorf("unknown field type %v", t)
}
}
func (f *docsField) Close() {
if f.closed {
return
}
f.closed = true
if f.nf != nil {
f.nf.Close()
f.nf = nil
}
if f.bf != nil {
f.bf.Close()
f.bf = nil
}
if f.intf != nil {
f.intf.Close()
f.intf = nil
}
if f.df != nil {
f.df.Close()
f.df = nil
}
if f.sf != nil {
f.sf.Close()
f.sf = nil
}
if f.tf != nil {
f.tf.Close()
f.tf = nil
}
}
func (f *docsField) closeableNullField() (CloseableNullField, bool) {
if f.nf == nil {
return nil, false
}
return f.nf, true
}
func (f *docsField) closeableBoolField() (CloseableBoolField, bool) {
if f.bf == nil {
return nil, false
}
return f.bf, true
}
func (f *docsField) closeableIntField() (CloseableIntField, bool) {
if f.intf == nil {
return nil, false
}
return f.intf, true
}
func (f *docsField) closeableDoubleField() (CloseableDoubleField, bool) {
if f.df == nil {
return nil, false
}
return f.df, true
}
func (f *docsField) closeableBytesField() (CloseableBytesField, bool) {
if f.sf == nil {
return nil, false
}
return f.sf, true
}
func (f *docsField) closeableTimeField() (CloseableTimeField, bool) {
if f.tf == nil {
return nil, false
}
return f.tf, true
}
// docsFieldBuilder is a builder of docs field.
type docsFieldBuilder struct {
fieldPath []string
opts *DocsFieldBuilderOptions
closed bool
nfb nullFieldBuilder
bfb boolFieldBuilder
ifb intFieldBuilder
dfb doubleFieldBuilder
sfb bytesFieldBuilder
tfb timeFieldBuilder
}
// NewDocsFieldBuilder creates a new docs field builder.
func NewDocsFieldBuilder(fieldPath []string, opts *DocsFieldBuilderOptions) DocsFieldBuilder {
if opts == nil {
opts = NewDocsFieldBuilderOptions()
}
return &docsFieldBuilder{
fieldPath: fieldPath,
opts: opts,
}
}
// Add adds a value to the value collection.
func (b *docsFieldBuilder) Add(docID int32, v field.ValueUnion) error {
if b.closed {
return errDocsFieldBuilderAlreadyClosed
}
switch v.Type {
case field.NullType:
return b.addNull(docID)
case field.BoolType:
return b.addBool(docID, v.BoolVal)
case field.IntType:
return b.addInt(docID, v.IntVal)
case field.DoubleType:
return b.addDouble(docID, v.DoubleVal)
case field.BytesType:
return b.addBytes(docID, v.BytesVal.SafeBytes())
case field.TimeType:
return b.addTime(docID, v.TimeNanosVal)
default:
return fmt.Errorf("unknown field value type %v", v.Type)
}
}
func (b *docsFieldBuilder) SnapshotFor(
fieldTypes field.ValueTypeSet,
) (DocsField, field.ValueTypeSet, error) {
var (
nf CloseableNullField
bf CloseableBoolField
intf CloseableIntField
df CloseableDoubleField
sf CloseableBytesField
tf CloseableTimeField
availableTypes = make([]field.ValueType, 0, len(fieldTypes))
remainingTypes field.ValueTypeSet
err error
)
for t := range fieldTypes {
hasType := true
switch t {
case field.NullType:
if b.nfb != nil {
nf = b.nfb.Snapshot()
break
}
hasType = false
case field.BoolType:
if b.bfb != nil {
bf = b.bfb.Snapshot()
break
}
hasType = false
case field.IntType:
if b.ifb != nil {
intf = b.ifb.Snapshot()
break
}
hasType = false
case field.DoubleType:
if b.dfb != nil {
df = b.dfb.Snapshot()
break
}
hasType = false
case field.BytesType:
if b.sfb != nil {
sf = b.sfb.Snapshot()
break
}
hasType = false
case field.TimeType:
if b.tfb != nil {
tf = b.tfb.Snapshot()
break
}
hasType = false
default:
err = fmt.Errorf("unknown field type %v", t)
}
if err != nil {
break
}
if hasType {
availableTypes = append(availableTypes, t)
continue
}
if remainingTypes == nil {
remainingTypes = make(field.ValueTypeSet, len(fieldTypes))
}
remainingTypes[t] = struct{}{}
}
if err == nil {
return NewDocsField(b.fieldPath, availableTypes, nf, bf, intf, df, sf, tf), remainingTypes, nil
}
// Close all resources on error.
if nf != nil {
nf.Close()
}
if bf != nil {
bf.Close()
}
if intf != nil {
intf.Close()
}
if df != nil {
df.Close()
}
if sf != nil {
sf.Close()
}
if tf != nil {
tf.Close()
}
return nil, nil, err
}
// Seal seals the builder.
func (b *docsFieldBuilder) Seal(numTotalDocs int32) DocsField {
var (
fieldTypes = make([]field.ValueType, 0, 6)
nf CloseableNullField
bf CloseableBoolField
intf CloseableIntField
df CloseableDoubleField
sf CloseableBytesField
tf CloseableTimeField
)
if b.nfb != nil {
fieldTypes = append(fieldTypes, field.NullType)
nf = b.nfb.Seal(numTotalDocs)
}
if b.bfb != nil {
fieldTypes = append(fieldTypes, field.BoolType)
bf = b.bfb.Seal(numTotalDocs)
}
if b.ifb != nil {
fieldTypes = append(fieldTypes, field.IntType)
intf = b.ifb.Seal(numTotalDocs)
}
if b.dfb != nil {
fieldTypes = append(fieldTypes, field.DoubleType)
df = b.dfb.Seal(numTotalDocs)
}
if b.sfb != nil {
fieldTypes = append(fieldTypes, field.BytesType)
sf = b.sfb.Seal(numTotalDocs)
}
if b.tfb != nil {
fieldTypes = append(fieldTypes, field.TimeType)
tf = b.tfb.Seal(numTotalDocs)
}
// The sealed field shares the same refcounter as the builder because it holds
// references to the same underlying resources.
sealed := NewDocsField(b.fieldPath, fieldTypes, nf, bf, intf, df, sf, tf)
// Clear and close the builder so it's no longer writable.
*b = docsFieldBuilder{}
b.Close()
return sealed
}
// Close closes the value builder.
func (b *docsFieldBuilder) Close() {
if b.closed {
return
}
b.closed = true
if b.nfb != nil {
b.nfb.Close()
b.nfb = nil
}
if b.bfb != nil {
b.bfb.Close()
b.bfb = nil
}
if b.ifb != nil {
b.ifb.Close()
b.ifb = nil
}
if b.dfb != nil {
b.dfb.Close()
b.dfb = nil
}
if b.sfb != nil {
b.sfb.Close()
b.sfb = nil
}
if b.tfb != nil {
b.tfb.Close()
b.tfb = nil
}
}
func (b *docsFieldBuilder) newDocIDSetBuilder() index.DocIDSetBuilder {
return index.NewBitmapBasedDocIDSetBuilder(roaring.NewBitmap())
}
func (b *docsFieldBuilder) addNull(docID int32) error {
if b.nfb == nil {
docIDsBuilder := b.newDocIDSetBuilder()
b.nfb = newNullFieldBuilder(docIDsBuilder)
}
return b.nfb.Add(docID)
}
func (b *docsFieldBuilder) addBool(docID int32, v bool) error {
if b.bfb == nil {
docIDsBuilder := b.newDocIDSetBuilder()
boolValuesBuilder := impl.NewArrayBasedBoolValues(b.opts.BoolArrayPool())
b.bfb = newBoolFieldBuilder(docIDsBuilder, boolValuesBuilder)
}
return b.bfb.Add(docID, v)
}
func (b *docsFieldBuilder) addInt(docID int32, v int) error {
if b.ifb == nil {
docIDsBuilder := b.newDocIDSetBuilder()
intValuesBuilder := impl.NewArrayBasedIntValues(b.opts.IntArrayPool())
b.ifb = newIntFieldBuilder(docIDsBuilder, intValuesBuilder)
}
return b.ifb.Add(docID, v)
}
func (b *docsFieldBuilder) addDouble(docID int32, v float64) error {
if b.dfb == nil {
docIDsBuilder := b.newDocIDSetBuilder()
doubleValuesBuilder := impl.NewArrayBasedDoubleValues(b.opts.DoubleArrayPool())
b.dfb = newDoubleFieldBuilder(docIDsBuilder, doubleValuesBuilder)
}
return b.dfb.Add(docID, v)
}
func (b *docsFieldBuilder) addBytes(docID int32, v []byte) error {
if b.sfb == nil {
docIDsBuilder := b.newDocIDSetBuilder()
bytesValuesBuilder := impl.NewArrayBasedBytesValues(b.opts.BytesArrayPool(), b.opts.BytesArrayResetFn())
b.sfb = newBytesFieldBuilder(docIDsBuilder, bytesValuesBuilder)
}
return b.sfb.Add(docID, v)
}
func (b *docsFieldBuilder) addTime(docID int32, v int64) error {
if b.tfb == nil {
docIDsBuilder := b.newDocIDSetBuilder()
timeValuesBuilder := impl.NewArrayBasedTimeValues(b.opts.Int64ArrayPool())
b.tfb = newTimeFieldBuilder(docIDsBuilder, timeValuesBuilder)
}
return b.tfb.Add(docID, v)
}
// DocsFieldBuilderOptions provide a set of options for the field builder.
type DocsFieldBuilderOptions struct {
boolArrayPool *pool.BucketizedBoolArrayPool
intArrayPool *pool.BucketizedIntArrayPool
doubleArrayPool *pool.BucketizedFloat64ArrayPool
bytesArrayPool *pool.BucketizedBytesArrayPool
int64ArrayPool *pool.BucketizedInt64ArrayPool
bytesArrayResetFn bytes.ArrayFn
}
// NewDocsFieldBuilderOptions creates a new set of field builder options.
func NewDocsFieldBuilderOptions() *DocsFieldBuilderOptions {
boolArrayPool := pool.NewBucketizedBoolArrayPool(nil, nil)
boolArrayPool.Init(func(capacity int) []bool { return make([]bool, 0, capacity) })
intArrayPool := pool.NewBucketizedIntArrayPool(nil, nil)
intArrayPool.Init(func(capacity int) []int { return make([]int, 0, capacity) })
doubleArrayPool := pool.NewBucketizedFloat64ArrayPool(nil, nil)
doubleArrayPool.Init(func(capacity int) []float64 { return make([]float64, 0, capacity) })
bytesArrayPool := pool.NewBucketizedBytesArrayPool(nil, nil)
bytesArrayPool.Init(func(capacity int) [][]byte { return make([][]byte, 0, capacity) })
int64ArrayPool := pool.NewBucketizedInt64ArrayPool(nil, nil)
int64ArrayPool.Init(func(capacity int) []int64 { return make([]int64, 0, capacity) })
return &DocsFieldBuilderOptions{
boolArrayPool: boolArrayPool,
intArrayPool: intArrayPool,
doubleArrayPool: doubleArrayPool,
bytesArrayPool: bytesArrayPool,
int64ArrayPool: int64ArrayPool,
}
}
// SetBoolArrayPool sets the bool array pool.
func (o *DocsFieldBuilderOptions) SetBoolArrayPool(v *pool.BucketizedBoolArrayPool) *DocsFieldBuilderOptions {
opts := *o
opts.boolArrayPool = v
return &opts
}
// BoolArrayPool returns the bool array pool.
func (o *DocsFieldBuilderOptions) BoolArrayPool() *pool.BucketizedBoolArrayPool {
return o.boolArrayPool
}
// SetIntArrayPool sets the int array pool.
func (o *DocsFieldBuilderOptions) SetIntArrayPool(v *pool.BucketizedIntArrayPool) *DocsFieldBuilderOptions {
opts := *o
opts.intArrayPool = v
return &opts
}
// IntArrayPool returns the int array pool.
func (o *DocsFieldBuilderOptions) IntArrayPool() *pool.BucketizedIntArrayPool {
return o.intArrayPool
}
// SetDoubleArrayPool sets the double array pool.
func (o *DocsFieldBuilderOptions) SetDoubleArrayPool(v *pool.BucketizedFloat64ArrayPool) *DocsFieldBuilderOptions {
opts := *o
opts.doubleArrayPool = v
return &opts
}
// DoubleArrayPool returns the double array pool.
func (o *DocsFieldBuilderOptions) DoubleArrayPool() *pool.BucketizedFloat64ArrayPool {
return o.doubleArrayPool
}
// SetBytesArrayPool sets the bytes array pool.
func (o *DocsFieldBuilderOptions) SetBytesArrayPool(v *pool.BucketizedBytesArrayPool) *DocsFieldBuilderOptions {
opts := *o
opts.bytesArrayPool = v
return &opts
}
// BytesArrayPool returns the bytes array pool.
func (o *DocsFieldBuilderOptions) BytesArrayPool() *pool.BucketizedBytesArrayPool {
return o.bytesArrayPool
}
// SetInt64ArrayPool sets the int64 array pool.
func (o *DocsFieldBuilderOptions) SetInt64ArrayPool(v *pool.BucketizedInt64ArrayPool) *DocsFieldBuilderOptions {
opts := *o
opts.int64ArrayPool = v
return &opts
}
// Int64ArrayPool returns the int64 array pool.
func (o *DocsFieldBuilderOptions) Int64ArrayPool() *pool.BucketizedInt64ArrayPool {
return o.int64ArrayPool
}
// SetBytesArrayResetFn sets a value reset function for bytes values.
func (o *DocsFieldBuilderOptions) SetBytesArrayResetFn(fn bytes.ArrayFn) *DocsFieldBuilderOptions {
opts := *o
opts.bytesArrayResetFn = fn
return &opts
}
// BytesArrayResetFn resets bytes array values before returning a bytes array back to the memory pool.
func (o *DocsFieldBuilderOptions) BytesArrayResetFn() bytes.ArrayFn {
return o.bytesArrayResetFn
} | index/field/docs_field.go | 0.684053 | 0.444263 | docs_field.go | starcoder |
package design
import (
"io"
"reflect"
"github.com/gregoryv/draw"
"github.com/gregoryv/draw/shape"
)
// NewSequenceDiagram returns a sequence diagram with default column
// width.
func NewSequenceDiagram() *SequenceDiagram {
return &SequenceDiagram{
Diagram: NewDiagram(),
ColWidth: 190,
VMargin: 10,
}
}
// SequenceDiagram defines columns and links between columns.
type SequenceDiagram struct {
*Diagram
ColWidth int
VMargin int // top margin for each horizontal lane
columns []string
links []*Link
groups []group
}
type group struct {
fromColumn string
toColumn string
text string
class string
}
// Group adds a colored area below span of columns. Predefined classes
// are red, green, blue.
func (me *SequenceDiagram) Group(fromColumn, toColumn, text, class string) {
g := group{
fromColumn: fromColumn,
toColumn: toColumn,
text: text,
class: class,
}
if me.groups == nil {
me.groups = []group{g}
return
}
me.groups = append(me.groups, g)
}
// WriteSvg renders the diagram as SVG to the given writer.
func (d *SequenceDiagram) WriteSVG(w io.Writer) error {
var (
colWidth = d.ColWidth
top = d.top()
x = d.Pad.Left
y1 = top + d.TextPad.Bottom + d.Font.LineHeight // below label
y2 = d.Height()
)
lines := make([]*shape.Line, len(d.columns))
vlines := make(map[string]*shape.Line)
// save x values for rendering skip lines
columnX := make([]int, len(d.columns))
// columns and vertical lines
for i, column := range d.columns {
label := shape.NewLabel(column)
label.Font = d.Font
label.Pad = d.Pad
label.SetX(i * colWidth)
label.SetY(top)
firstColumn := i == 0
if firstColumn {
x += label.Width() / 2
columnX = append(columnX, x)
}
line := shape.NewLine(x, y1, x, y2)
line.SetClass("column-line")
lines[i] = line
x += colWidth
columnX = append(columnX, x)
d.VAlignCenter(lines[i], label)
d.Place(lines[i], label)
vlines[column] = line // save for groups
// groups
for _, group := range d.groups {
if group.toColumn == column { // assume from is already there
r := shape.NewRect("") // add align label
alabel := shape.NewLabel(group.text)
alabel.Font = d.Font
alabel.Pad = d.Pad
alabel.SetClass("area-" + group.class + "-label")
from := vlines[group.fromColumn]
to := line
x, y := from.Position()
x2, _ := to.Position()
width := x2 - x
r.SetX(x)
r.SetY(y)
r.SetWidth(width)
r.SetClass("area-" + group.class)
r.SetHeight(y2 + d.top() + label.Height())
d.Prepend(r) // behind
d.Place(alabel).Below(r)
d.VAlignCenter(r, alabel)
d.HAlignBottom(r, alabel)
shape.Move(alabel, 0, -alabel.Pad.Bottom)
}
}
}
y := y1 + d.plainHeight()
for _, lnk := range d.links {
if lnk == skip {
for _, x := range columnX {
dots := shape.NewLine(x, y, x, y+d.Font.LineHeight)
dots.SetClass("skip")
d.Place(dots)
}
y += d.plainHeight()
continue
}
fromX := lines[lnk.fromIndex].Start.X
toX := lines[lnk.toIndex].Start.X
label := shape.NewLabel(lnk.text)
label.Font = d.Font
label.Pad = d.Pad
label.SetX(fromX)
label.SetY(y - 3 - d.Font.LineHeight)
if lnk.toSelf() {
margin := 15
// add two lines + arrow
l1 := shape.NewLine(fromX, y, fromX+margin, y)
l1.SetClass(lnk.class())
l2 := shape.NewLine(fromX+margin, y, fromX+margin, y+d.Font.LineHeight*2)
l2.SetClass(lnk.class())
d.HAlignCenter(l2, label)
label.SetX(fromX + l1.Width() + d.TextPad.Left)
label.SetY(y + 3)
arrow := shape.NewArrow(
l2.End.X,
l2.End.Y,
l1.Start.X,
l2.End.Y,
)
arrow.SetClass(lnk.class())
d.Place(l1, l2, arrow, label)
y += d.selfHeight()
} else {
arrow := shape.NewArrow(
fromX,
y,
toX,
y,
)
arrow.SetClass(lnk.class())
d.VAlignCenter(arrow, label)
d.Place(arrow, label)
y += d.plainHeight()
}
}
return d.Diagram.WriteSVG(w)
}
// Width returns the total width of the diagram
func (d *SequenceDiagram) Width() int {
w := d.SVG.Width()
if w != 0 {
return w
}
return len(d.columns) * d.ColWidth
}
// Height returns the total height of the diagram
func (d *SequenceDiagram) Height() int {
h := d.SVG.Height()
if h != 0 {
return h
}
if len(d.columns) == 0 {
return 0
}
height := d.top() + d.plainHeight()
for _, lnk := range d.links {
if lnk.toSelf() {
height += d.selfHeight()
continue
}
height += d.plainHeight()
}
return height
}
// selfHeight is the height of a self referencing link
func (d *SequenceDiagram) selfHeight() int {
return 3*d.Font.LineHeight + d.Pad.Bottom
}
// plainHeight returns the height of and arrow and label
func (d *SequenceDiagram) plainHeight() int {
return d.Font.LineHeight + d.Pad.Bottom + d.VMargin
}
func (d *SequenceDiagram) top() int {
return d.Pad.Top
}
// AddColumns adds the names as columns in the given order.
func (d *SequenceDiagram) AddColumns(names ...string) {
for _, name := range names {
d.Add(name)
}
}
// Add the name as next column and return name.
func (d *SequenceDiagram) Add(name string) string {
d.columns = append(d.columns, name)
return name
}
func (d *SequenceDiagram) SaveAs(filename string) error {
return saveAs(d, d.Style, filename)
}
// Inline returns rendered SVG with inlined style
func (d *SequenceDiagram) Inline() string {
return draw.Inline(d, d.Style)
}
// String returns rendered SVG
func (d *SequenceDiagram) String() string { return toString(d) }
func (d *SequenceDiagram) AddStruct(obj interface{}) string {
name := reflect.TypeOf(obj).String()
d.Add(name)
return name
}
func (d *SequenceDiagram) AddInterface(obj interface{}) string {
name := reflect.TypeOf(obj).Elem().String()
d.Add(name)
return name
} | design/seqdia.go | 0.718594 | 0.491578 | seqdia.go | starcoder |
A Window tracks the number of times a counter has been incremented within a
sliding window of epochs. These epochs are normally Unix epochs, but any
monotonically incrementing counter is sufficient. The Window is initialized
with the size of the sliding window and an epoch to consider as time 0.
As events occur, calling window.Add(time.Now().Unix(), 1) will increment the
counter for the current epoch, and move along the sliding window, possibly
expiring any counts that have left the window. This count can be retrieved by
calling window.Total().
Calling window.Add(time.Now().Unix(), 0) will slide the window forward and
expire old elements.
It is acceptable to call window.Add() with an epoch earlier than the currently
active epoch. If the time falls outside of the current window, the event will
be silently discarded.
Windows are not safe to be called from multiple goroutines.
*/
package timewindow
// Window is a sliding window of event counts.
type Window struct {
counts []int
epoch int64 // to match time.Now().Unix()
headIdx int
tailIdx int
total int
}
// New returns a sliding window starting at epoch0 with size seconds of history
func New(epoch0 int64, size int) *Window {
w := &Window{
counts: make([]int, size),
epoch: epoch0,
headIdx: 0,
tailIdx: 1,
}
return w
}
// Add delta to the counter for epoch and adjust the window if necessary.
func (w *Window) Add(epoch int64, delta int) {
// usual case -- update the present
if epoch == w.epoch {
w.total += delta
w.counts[w.headIdx] += delta
return
}
// common case -- advance our ring buffer
if epoch > w.epoch {
// FIXME(dgryski): we do too much work if zeroOut > len(count)
zeroOut := int(epoch - w.epoch)
for i := 0; i < zeroOut; i++ {
w.total -= w.counts[w.tailIdx]
w.counts[w.tailIdx] = 0
w.tailIdx++
if w.tailIdx >= len(w.counts) {
w.tailIdx = 0
}
}
w.headIdx += zeroOut
for w.headIdx >= len(w.counts) {
w.headIdx -= len(w.counts)
}
w.epoch = epoch
w.total += delta
w.counts[w.headIdx] += delta
return
}
// less common -- update the past
back := int(w.epoch - epoch)
if back >= len(w.counts) {
// too far in the past, ignore
return
}
idx := w.headIdx - back
if idx < 0 {
// need to wrap around
idx += len(w.counts)
}
w.total += delta
w.counts[idx] += delta
}
// Total returns the sum of all counters in the window
func (w *Window) Total() int {
return w.total
}
// Epoch returns most recent second for which data has been inserted
func (w *Window) Epoch() int64 {
return w.epoch
} | timewindow.go | 0.794584 | 0.635279 | timewindow.go | starcoder |
package animation
import (
"github.com/wieku/danser-go/app/bmath"
color2 "github.com/wieku/danser-go/framework/math/color"
"github.com/wieku/danser-go/framework/math/vector"
)
type TransformationType int64
type TransformationStatus int64
const (
Fade = TransformationType(1 << iota)
Rotate
Scale
ScaleVector
Move
MoveX
MoveY
Color3
Color4
HorizontalFlip
VerticalFlip
Additive
)
const (
NotStarted = TransformationStatus(1 << iota)
Going
Ended
)
func timeClamp(start, end, time float64) float64 {
if time < start {
return 0.0
}
if time >= end {
return 1.0
}
return bmath.ClampF64((time-start)/(end-start), 0, 1)
}
type Transformation struct {
transformationType TransformationType
startValues [4]float64
endValues [4]float64
easing func(float64) float64
startTime, endTime float64
}
func NewBooleanTransform(transformationType TransformationType, startTime, endTime float64) *Transformation {
if transformationType&(HorizontalFlip|VerticalFlip|Additive) == 0 {
panic("Wrong TransformationType used!")
}
return &Transformation{transformationType: transformationType, startTime: startTime, endTime: endTime}
}
func NewSingleTransform(transformationType TransformationType, easing func(float64) float64, startTime, endTime, startValue, endValue float64) *Transformation {
if transformationType&(Fade|Rotate|Scale|MoveX|MoveY) == 0 {
panic("Wrong TransformationType used!")
}
transformation := &Transformation{transformationType: transformationType, startTime: startTime, endTime: endTime, easing: easing}
transformation.startValues[0] = startValue
transformation.endValues[0] = endValue
return transformation
}
func NewVectorTransform(transformationType TransformationType, easing func(float64) float64, startTime, endTime, startValueX, startValueY, endValueX, endValueY float64) *Transformation {
if transformationType&(ScaleVector|Move) == 0 {
panic("Wrong TransformationType used!")
}
transformation := &Transformation{transformationType: transformationType, startTime: startTime, endTime: endTime, easing: easing}
transformation.startValues[0] = startValueX
transformation.startValues[1] = startValueY
transformation.endValues[0] = endValueX
transformation.endValues[1] = endValueY
return transformation
}
func NewVectorTransformV(transformationType TransformationType, easing func(float64) float64, startTime, endTime float64, start, end vector.Vector2d) *Transformation {
if transformationType&(ScaleVector|Move) == 0 {
panic("Wrong TransformationType used!")
}
transformation := &Transformation{transformationType: transformationType, startTime: startTime, endTime: endTime, easing: easing}
transformation.startValues[0] = start.X
transformation.startValues[1] = start.Y
transformation.endValues[0] = end.X
transformation.endValues[1] = end.Y
return transformation
}
func NewColorTransform(transformationType TransformationType, easing func(float64) float64, startTime, endTime float64, start, end color2.Color) *Transformation {
if transformationType&(Color3|Color4) == 0 {
panic("Wrong TransformationType used!")
}
transformation := &Transformation{transformationType: transformationType, startTime: startTime, endTime: endTime, easing: easing}
transformation.startValues[0] = float64(start.R)
transformation.startValues[1] = float64(start.G)
transformation.startValues[2] = float64(start.B)
transformation.startValues[3] = float64(start.A)
transformation.endValues[0] = float64(end.R)
transformation.endValues[1] = float64(end.G)
transformation.endValues[2] = float64(end.B)
transformation.endValues[3] = float64(end.A)
return transformation
}
func (t *Transformation) GetStatus(time float64) TransformationStatus {
if time < t.startTime {
return NotStarted
} else if time >= t.endTime {
return Ended
}
return Going
}
func (t *Transformation) getProgress(time float64) float64 {
return t.easing(timeClamp(t.startTime, t.endTime, time))
}
func (t *Transformation) GetSingle(time float64) float64 {
return t.startValues[0] + t.getProgress(time)*(t.endValues[0]-t.startValues[0])
}
func (t *Transformation) GetDouble(time float64) (float64, float64) {
progress := t.getProgress(time)
return t.startValues[0] + progress*(t.endValues[0]-t.startValues[0]), t.startValues[1] + progress*(t.endValues[1]-t.startValues[1])
}
func (t *Transformation) GetVector(time float64) vector.Vector2d {
return vector.NewVec2d(t.GetDouble(time))
}
func (t *Transformation) GetBoolean(time float64) bool {
return t.startTime == t.endTime || time >= t.startTime && time < t.endTime
}
func (t *Transformation) GetColor(time float64) color2.Color {
progress := t.getProgress(time)
return color2.NewRGBA(
float32(t.startValues[0]+progress*(t.endValues[0]-t.startValues[0])),
float32(t.startValues[1]+progress*(t.endValues[1]-t.startValues[1])),
float32(t.startValues[2]+progress*(t.endValues[2]-t.startValues[2])),
float32(t.startValues[3]+progress*(t.endValues[3]-t.startValues[3])),
)
}
func (t *Transformation) GetStartTime() float64 {
return t.startTime
}
func (t *Transformation) GetEndTime() float64 {
return t.endTime
}
func (t *Transformation) GetType() TransformationType {
return t.transformationType
}
func (t *Transformation) Clone(startTime, endTime float64) *Transformation {
return &Transformation{
transformationType: t.transformationType,
startValues: [4]float64{t.startValues[0], t.startValues[1], t.startValues[2], t.startValues[3]},
endValues: [4]float64{t.endValues[0], t.endValues[1], t.endValues[2], t.endValues[3]},
easing: t.easing,
startTime: startTime,
endTime: endTime,
}
} | framework/math/animation/transformation.go | 0.744378 | 0.443962 | transformation.go | starcoder |
package elements
import (
"github.com/ratorx/htmlgo"
)
// A represents the HTML element 'a'.
// For more information visit https://www.w3schools.com/tags/tag_a.asp.
func A(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "a", Attributes: attrs, Children: children}
}
// A_ is a convenience wrapper for A without the attrs argument.
func A_(children ...HTML) HTML {
return A(nil, children...)
}
// Abbr represents the HTML element 'abbr'.
// For more information visit https://www.w3schools.com/tags/tag_abbr.asp.
func Abbr(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "abbr", Attributes: attrs, Children: children}
}
// Abbr_ is a convenience wrapper for Abbr without the attrs argument.
func Abbr_(children ...HTML) HTML {
return Abbr(nil, children...)
}
// Acronym represents the HTML element 'acronym'.
// For more information visit https://www.w3schools.com/tags/tag_acronym.asp.
func Acronym(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "acronym", Attributes: attrs, Children: children}
}
// Acronym_ is a convenience wrapper for Acronym without the attrs argument.
func Acronym_(children ...HTML) HTML {
return Acronym(nil, children...)
}
// Address represents the HTML element 'address'.
// For more information visit https://www.w3schools.com/tags/tag_address.asp.
func Address(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "address", Attributes: attrs, Children: children}
}
// Address_ is a convenience wrapper for Address without the attrs argument.
func Address_(children ...HTML) HTML {
return Address(nil, children...)
}
// Applet represents the HTML element 'applet'.
// For more information visit https://www.w3schools.com/tags/tag_applet.asp.
func Applet(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "applet", Attributes: attrs, Children: children}
}
// Applet_ is a convenience wrapper for Applet without the attrs argument.
func Applet_(children ...HTML) HTML {
return Applet(nil, children...)
}
// Article represents the HTML element 'article'.
// For more information visit https://www.w3schools.com/tags/tag_article.asp.
func Article(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "article", Attributes: attrs, Children: children}
}
// Article_ is a convenience wrapper for Article without the attrs argument.
func Article_(children ...HTML) HTML {
return Article(nil, children...)
}
// Aside represents the HTML element 'aside'.
// For more information visit https://www.w3schools.com/tags/tag_aside.asp.
func Aside(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "aside", Attributes: attrs, Children: children}
}
// Aside_ is a convenience wrapper for Aside without the attrs argument.
func Aside_(children ...HTML) HTML {
return Aside(nil, children...)
}
// Audio represents the HTML element 'audio'.
// For more information visit https://www.w3schools.com/tags/tag_audio.asp.
func Audio(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "audio", Attributes: attrs, Children: children}
}
// Audio_ is a convenience wrapper for Audio without the attrs argument.
func Audio_(children ...HTML) HTML {
return Audio(nil, children...)
}
// B represents the HTML element 'b'.
// For more information visit https://www.w3schools.com/tags/tag_b.asp.
func B(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "b", Attributes: attrs, Children: children}
}
// B_ is a convenience wrapper for B without the attrs argument.
func B_(children ...HTML) HTML {
return B(nil, children...)
}
// Basefont represents the HTML element 'basefont'.
// For more information visit https://www.w3schools.com/tags/tag_basefont.asp.
func Basefont(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "basefont", Attributes: attrs, Children: children}
}
// Basefont_ is a convenience wrapper for Basefont without the attrs argument.
func Basefont_(children ...HTML) HTML {
return Basefont(nil, children...)
}
// Bdi represents the HTML element 'bdi'.
// For more information visit https://www.w3schools.com/tags/tag_bdi.asp.
func Bdi(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "bdi", Attributes: attrs, Children: children}
}
// Bdi_ is a convenience wrapper for Bdi without the attrs argument.
func Bdi_(children ...HTML) HTML {
return Bdi(nil, children...)
}
// Bdo represents the HTML element 'bdo'.
// For more information visit https://www.w3schools.com/tags/tag_bdo.asp.
func Bdo(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "bdo", Attributes: attrs, Children: children}
}
// Bdo_ is a convenience wrapper for Bdo without the attrs argument.
func Bdo_(children ...HTML) HTML {
return Bdo(nil, children...)
}
// Bgsound represents the HTML element 'bgsound'.
// For more information visit https://www.w3schools.com/tags/tag_bgsound.asp.
func Bgsound(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "bgsound", Attributes: attrs, Children: children}
}
// Bgsound_ is a convenience wrapper for Bgsound without the attrs argument.
func Bgsound_(children ...HTML) HTML {
return Bgsound(nil, children...)
}
// Big represents the HTML element 'big'.
// For more information visit https://www.w3schools.com/tags/tag_big.asp.
func Big(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "big", Attributes: attrs, Children: children}
}
// Big_ is a convenience wrapper for Big without the attrs argument.
func Big_(children ...HTML) HTML {
return Big(nil, children...)
}
// Blink represents the HTML element 'blink'.
// For more information visit https://www.w3schools.com/tags/tag_blink.asp.
func Blink(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "blink", Attributes: attrs, Children: children}
}
// Blink_ is a convenience wrapper for Blink without the attrs argument.
func Blink_(children ...HTML) HTML {
return Blink(nil, children...)
}
// Blockquote represents the HTML element 'blockquote'.
// For more information visit https://www.w3schools.com/tags/tag_blockquote.asp.
func Blockquote(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "blockquote", Attributes: attrs, Children: children}
}
// Blockquote_ is a convenience wrapper for Blockquote without the attrs argument.
func Blockquote_(children ...HTML) HTML {
return Blockquote(nil, children...)
}
// Body represents the HTML element 'body'.
// For more information visit https://www.w3schools.com/tags/tag_body.asp.
func Body(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "body", Attributes: attrs, Children: children}
}
// Body_ is a convenience wrapper for Body without the attrs argument.
func Body_(children ...HTML) HTML {
return Body(nil, children...)
}
// Button represents the HTML element 'button'.
// For more information visit https://www.w3schools.com/tags/tag_button.asp.
func Button(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "button", Attributes: attrs, Children: children}
}
// Button_ is a convenience wrapper for Button without the attrs argument.
func Button_(children ...HTML) HTML {
return Button(nil, children...)
}
// Canvas represents the HTML element 'canvas'.
// For more information visit https://www.w3schools.com/tags/tag_canvas.asp.
func Canvas(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "canvas", Attributes: attrs, Children: children}
}
// Canvas_ is a convenience wrapper for Canvas without the attrs argument.
func Canvas_(children ...HTML) HTML {
return Canvas(nil, children...)
}
// Caption represents the HTML element 'caption'.
// For more information visit https://www.w3schools.com/tags/tag_caption.asp.
func Caption(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "caption", Attributes: attrs, Children: children}
}
// Caption_ is a convenience wrapper for Caption without the attrs argument.
func Caption_(children ...HTML) HTML {
return Caption(nil, children...)
}
// Center represents the HTML element 'center'.
// For more information visit https://www.w3schools.com/tags/tag_center.asp.
func Center(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "center", Attributes: attrs, Children: children}
}
// Center_ is a convenience wrapper for Center without the attrs argument.
func Center_(children ...HTML) HTML {
return Center(nil, children...)
}
// Cite represents the HTML element 'cite'.
// For more information visit https://www.w3schools.com/tags/tag_cite.asp.
func Cite(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "cite", Attributes: attrs, Children: children}
}
// Cite_ is a convenience wrapper for Cite without the attrs argument.
func Cite_(children ...HTML) HTML {
return Cite(nil, children...)
}
// Code represents the HTML element 'code'.
// For more information visit https://www.w3schools.com/tags/tag_code.asp.
func Code(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "code", Attributes: attrs, Children: children}
}
// Code_ is a convenience wrapper for Code without the attrs argument.
func Code_(children ...HTML) HTML {
return Code(nil, children...)
}
// Colgroup represents the HTML element 'colgroup'.
// For more information visit https://www.w3schools.com/tags/tag_colgroup.asp.
func Colgroup(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "colgroup", Attributes: attrs, Children: children}
}
// Colgroup_ is a convenience wrapper for Colgroup without the attrs argument.
func Colgroup_(children ...HTML) HTML {
return Colgroup(nil, children...)
}
// Datalist represents the HTML element 'datalist'.
// For more information visit https://www.w3schools.com/tags/tag_datalist.asp.
func Datalist(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "datalist", Attributes: attrs, Children: children}
}
// Datalist_ is a convenience wrapper for Datalist without the attrs argument.
func Datalist_(children ...HTML) HTML {
return Datalist(nil, children...)
}
// Dd represents the HTML element 'dd'.
// For more information visit https://www.w3schools.com/tags/tag_dd.asp.
func Dd(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "dd", Attributes: attrs, Children: children}
}
// Dd_ is a convenience wrapper for Dd without the attrs argument.
func Dd_(children ...HTML) HTML {
return Dd(nil, children...)
}
// Del represents the HTML element 'del'.
// For more information visit https://www.w3schools.com/tags/tag_del.asp.
func Del(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "del", Attributes: attrs, Children: children}
}
// Del_ is a convenience wrapper for Del without the attrs argument.
func Del_(children ...HTML) HTML {
return Del(nil, children...)
}
// Details represents the HTML element 'details'.
// For more information visit https://www.w3schools.com/tags/tag_details.asp.
func Details(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "details", Attributes: attrs, Children: children}
}
// Details_ is a convenience wrapper for Details without the attrs argument.
func Details_(children ...HTML) HTML {
return Details(nil, children...)
}
// Dfn represents the HTML element 'dfn'.
// For more information visit https://www.w3schools.com/tags/tag_dfn.asp.
func Dfn(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "dfn", Attributes: attrs, Children: children}
}
// Dfn_ is a convenience wrapper for Dfn without the attrs argument.
func Dfn_(children ...HTML) HTML {
return Dfn(nil, children...)
}
// Dir represents the HTML element 'dir'.
// For more information visit https://www.w3schools.com/tags/tag_dir.asp.
func Dir(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "dir", Attributes: attrs, Children: children}
}
// Dir_ is a convenience wrapper for Dir without the attrs argument.
func Dir_(children ...HTML) HTML {
return Dir(nil, children...)
}
// Div represents the HTML element 'div'.
// For more information visit https://www.w3schools.com/tags/tag_div.asp.
func Div(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "div", Attributes: attrs, Children: children}
}
// Div_ is a convenience wrapper for Div without the attrs argument.
func Div_(children ...HTML) HTML {
return Div(nil, children...)
}
// Dl represents the HTML element 'dl'.
// For more information visit https://www.w3schools.com/tags/tag_dl.asp.
func Dl(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "dl", Attributes: attrs, Children: children}
}
// Dl_ is a convenience wrapper for Dl without the attrs argument.
func Dl_(children ...HTML) HTML {
return Dl(nil, children...)
}
// Dt represents the HTML element 'dt'.
// For more information visit https://www.w3schools.com/tags/tag_dt.asp.
func Dt(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "dt", Attributes: attrs, Children: children}
}
// Dt_ is a convenience wrapper for Dt without the attrs argument.
func Dt_(children ...HTML) HTML {
return Dt(nil, children...)
}
// Em represents the HTML element 'em'.
// For more information visit https://www.w3schools.com/tags/tag_em.asp.
func Em(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "em", Attributes: attrs, Children: children}
}
// Em_ is a convenience wrapper for Em without the attrs argument.
func Em_(children ...HTML) HTML {
return Em(nil, children...)
}
// Fieldset represents the HTML element 'fieldset'.
// For more information visit https://www.w3schools.com/tags/tag_fieldset.asp.
func Fieldset(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "fieldset", Attributes: attrs, Children: children}
}
// Fieldset_ is a convenience wrapper for Fieldset without the attrs argument.
func Fieldset_(children ...HTML) HTML {
return Fieldset(nil, children...)
}
// Figcaption represents the HTML element 'figcaption'.
// For more information visit https://www.w3schools.com/tags/tag_figcaption.asp.
func Figcaption(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "figcaption", Attributes: attrs, Children: children}
}
// Figcaption_ is a convenience wrapper for Figcaption without the attrs argument.
func Figcaption_(children ...HTML) HTML {
return Figcaption(nil, children...)
}
// Figure represents the HTML element 'figure'.
// For more information visit https://www.w3schools.com/tags/tag_figure.asp.
func Figure(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "figure", Attributes: attrs, Children: children}
}
// Figure_ is a convenience wrapper for Figure without the attrs argument.
func Figure_(children ...HTML) HTML {
return Figure(nil, children...)
}
// Font represents the HTML element 'font'.
// For more information visit https://www.w3schools.com/tags/tag_font.asp.
func Font(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "font", Attributes: attrs, Children: children}
}
// Font_ is a convenience wrapper for Font without the attrs argument.
func Font_(children ...HTML) HTML {
return Font(nil, children...)
}
// Footer represents the HTML element 'footer'.
// For more information visit https://www.w3schools.com/tags/tag_footer.asp.
func Footer(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "footer", Attributes: attrs, Children: children}
}
// Footer_ is a convenience wrapper for Footer without the attrs argument.
func Footer_(children ...HTML) HTML {
return Footer(nil, children...)
}
// Form represents the HTML element 'form'.
// For more information visit https://www.w3schools.com/tags/tag_form.asp.
func Form(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "form", Attributes: attrs, Children: children}
}
// Form_ is a convenience wrapper for Form without the attrs argument.
func Form_(children ...HTML) HTML {
return Form(nil, children...)
}
// Frame represents the HTML element 'frame'.
// For more information visit https://www.w3schools.com/tags/tag_frame.asp.
func Frame(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "frame", Attributes: attrs, Children: children}
}
// Frame_ is a convenience wrapper for Frame without the attrs argument.
func Frame_(children ...HTML) HTML {
return Frame(nil, children...)
}
// Frameset represents the HTML element 'frameset'.
// For more information visit https://www.w3schools.com/tags/tag_frameset.asp.
func Frameset(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "frameset", Attributes: attrs, Children: children}
}
// Frameset_ is a convenience wrapper for Frameset without the attrs argument.
func Frameset_(children ...HTML) HTML {
return Frameset(nil, children...)
}
// H1 represents the HTML element 'h1'.
// For more information visit https://www.w3schools.com/tags/tag_h1.asp.
func H1(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "h1", Attributes: attrs, Children: children}
}
// H1_ is a convenience wrapper for H1 without the attrs argument.
func H1_(children ...HTML) HTML {
return H1(nil, children...)
}
// H2 represents the HTML element 'h2'.
// For more information visit https://www.w3schools.com/tags/tag_h2.asp.
func H2(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "h2", Attributes: attrs, Children: children}
}
// H2_ is a convenience wrapper for H2 without the attrs argument.
func H2_(children ...HTML) HTML {
return H2(nil, children...)
}
// H3 represents the HTML element 'h3'.
// For more information visit https://www.w3schools.com/tags/tag_h3.asp.
func H3(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "h3", Attributes: attrs, Children: children}
}
// H3_ is a convenience wrapper for H3 without the attrs argument.
func H3_(children ...HTML) HTML {
return H3(nil, children...)
}
// H4 represents the HTML element 'h4'.
// For more information visit https://www.w3schools.com/tags/tag_h4.asp.
func H4(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "h4", Attributes: attrs, Children: children}
}
// H4_ is a convenience wrapper for H4 without the attrs argument.
func H4_(children ...HTML) HTML {
return H4(nil, children...)
}
// H5 represents the HTML element 'h5'.
// For more information visit https://www.w3schools.com/tags/tag_h5.asp.
func H5(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "h5", Attributes: attrs, Children: children}
}
// H5_ is a convenience wrapper for H5 without the attrs argument.
func H5_(children ...HTML) HTML {
return H5(nil, children...)
}
// H6 represents the HTML element 'h6'.
// For more information visit https://www.w3schools.com/tags/tag_h6.asp.
func H6(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "h6", Attributes: attrs, Children: children}
}
// H6_ is a convenience wrapper for H6 without the attrs argument.
func H6_(children ...HTML) HTML {
return H6(nil, children...)
}
// Head represents the HTML element 'head'.
// For more information visit https://www.w3schools.com/tags/tag_head.asp.
func Head(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "head", Attributes: attrs, Children: children}
}
// Head_ is a convenience wrapper for Head without the attrs argument.
func Head_(children ...HTML) HTML {
return Head(nil, children...)
}
// Header represents the HTML element 'header'.
// For more information visit https://www.w3schools.com/tags/tag_header.asp.
func Header(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "header", Attributes: attrs, Children: children}
}
// Header_ is a convenience wrapper for Header without the attrs argument.
func Header_(children ...HTML) HTML {
return Header(nil, children...)
}
// Hgroup represents the HTML element 'hgroup'.
// For more information visit https://www.w3schools.com/tags/tag_hgroup.asp.
func Hgroup(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "hgroup", Attributes: attrs, Children: children}
}
// Hgroup_ is a convenience wrapper for Hgroup without the attrs argument.
func Hgroup_(children ...HTML) HTML {
return Hgroup(nil, children...)
}
// I represents the HTML element 'i'.
// For more information visit https://www.w3schools.com/tags/tag_i.asp.
func I(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "i", Attributes: attrs, Children: children}
}
// I_ is a convenience wrapper for I without the attrs argument.
func I_(children ...HTML) HTML {
return I(nil, children...)
}
// Iframe represents the HTML element 'iframe'.
// For more information visit https://www.w3schools.com/tags/tag_iframe.asp.
func Iframe(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "iframe", Attributes: attrs, Children: children}
}
// Iframe_ is a convenience wrapper for Iframe without the attrs argument.
func Iframe_(children ...HTML) HTML {
return Iframe(nil, children...)
}
// Ins represents the HTML element 'ins'.
// For more information visit https://www.w3schools.com/tags/tag_ins.asp.
func Ins(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "ins", Attributes: attrs, Children: children}
}
// Ins_ is a convenience wrapper for Ins without the attrs argument.
func Ins_(children ...HTML) HTML {
return Ins(nil, children...)
}
// Isindex represents the HTML element 'isindex'.
// For more information visit https://www.w3schools.com/tags/tag_isindex.asp.
func Isindex(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "isindex", Attributes: attrs, Children: children}
}
// Isindex_ is a convenience wrapper for Isindex without the attrs argument.
func Isindex_(children ...HTML) HTML {
return Isindex(nil, children...)
}
// Kbd represents the HTML element 'kbd'.
// For more information visit https://www.w3schools.com/tags/tag_kbd.asp.
func Kbd(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "kbd", Attributes: attrs, Children: children}
}
// Kbd_ is a convenience wrapper for Kbd without the attrs argument.
func Kbd_(children ...HTML) HTML {
return Kbd(nil, children...)
}
// Keygen represents the HTML element 'keygen'.
// For more information visit https://www.w3schools.com/tags/tag_keygen.asp.
func Keygen(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "keygen", Attributes: attrs, Children: children}
}
// Keygen_ is a convenience wrapper for Keygen without the attrs argument.
func Keygen_(children ...HTML) HTML {
return Keygen(nil, children...)
}
// Label represents the HTML element 'label'.
// For more information visit https://www.w3schools.com/tags/tag_label.asp.
func Label(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "label", Attributes: attrs, Children: children}
}
// Label_ is a convenience wrapper for Label without the attrs argument.
func Label_(children ...HTML) HTML {
return Label(nil, children...)
}
// Legend represents the HTML element 'legend'.
// For more information visit https://www.w3schools.com/tags/tag_legend.asp.
func Legend(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "legend", Attributes: attrs, Children: children}
}
// Legend_ is a convenience wrapper for Legend without the attrs argument.
func Legend_(children ...HTML) HTML {
return Legend(nil, children...)
}
// Li represents the HTML element 'li'.
// For more information visit https://www.w3schools.com/tags/tag_li.asp.
func Li(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "li", Attributes: attrs, Children: children}
}
// Li_ is a convenience wrapper for Li without the attrs argument.
func Li_(children ...HTML) HTML {
return Li(nil, children...)
}
// Listing represents the HTML element 'listing'.
// For more information visit https://www.w3schools.com/tags/tag_listing.asp.
func Listing(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "listing", Attributes: attrs, Children: children}
}
// Listing_ is a convenience wrapper for Listing without the attrs argument.
func Listing_(children ...HTML) HTML {
return Listing(nil, children...)
}
// Main represents the HTML element 'main'.
// For more information visit https://www.w3schools.com/tags/tag_main.asp.
func Main(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "main", Attributes: attrs, Children: children}
}
// Main_ is a convenience wrapper for Main without the attrs argument.
func Main_(children ...HTML) HTML {
return Main(nil, children...)
}
// Map represents the HTML element 'map'.
// For more information visit https://www.w3schools.com/tags/tag_map.asp.
func Map(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "map", Attributes: attrs, Children: children}
}
// Map_ is a convenience wrapper for Map without the attrs argument.
func Map_(children ...HTML) HTML {
return Map(nil, children...)
}
// Mark represents the HTML element 'mark'.
// For more information visit https://www.w3schools.com/tags/tag_mark.asp.
func Mark(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "mark", Attributes: attrs, Children: children}
}
// Mark_ is a convenience wrapper for Mark without the attrs argument.
func Mark_(children ...HTML) HTML {
return Mark(nil, children...)
}
// Marquee represents the HTML element 'marquee'.
// For more information visit https://www.w3schools.com/tags/tag_marquee.asp.
func Marquee(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "marquee", Attributes: attrs, Children: children}
}
// Marquee_ is a convenience wrapper for Marquee without the attrs argument.
func Marquee_(children ...HTML) HTML {
return Marquee(nil, children...)
}
// Menu represents the HTML element 'menu'.
// For more information visit https://www.w3schools.com/tags/tag_menu.asp.
func Menu(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "menu", Attributes: attrs, Children: children}
}
// Menu_ is a convenience wrapper for Menu without the attrs argument.
func Menu_(children ...HTML) HTML {
return Menu(nil, children...)
}
// Meter represents the HTML element 'meter'.
// For more information visit https://www.w3schools.com/tags/tag_meter.asp.
func Meter(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "meter", Attributes: attrs, Children: children}
}
// Meter_ is a convenience wrapper for Meter without the attrs argument.
func Meter_(children ...HTML) HTML {
return Meter(nil, children...)
}
// Nav represents the HTML element 'nav'.
// For more information visit https://www.w3schools.com/tags/tag_nav.asp.
func Nav(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "nav", Attributes: attrs, Children: children}
}
// Nav_ is a convenience wrapper for Nav without the attrs argument.
func Nav_(children ...HTML) HTML {
return Nav(nil, children...)
}
// Nobr represents the HTML element 'nobr'.
// For more information visit https://www.w3schools.com/tags/tag_nobr.asp.
func Nobr(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "nobr", Attributes: attrs, Children: children}
}
// Nobr_ is a convenience wrapper for Nobr without the attrs argument.
func Nobr_(children ...HTML) HTML {
return Nobr(nil, children...)
}
// Noframes represents the HTML element 'noframes'.
// For more information visit https://www.w3schools.com/tags/tag_noframes.asp.
func Noframes(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "noframes", Attributes: attrs, Children: children}
}
// Noframes_ is a convenience wrapper for Noframes without the attrs argument.
func Noframes_(children ...HTML) HTML {
return Noframes(nil, children...)
}
// Noscript represents the HTML element 'noscript'.
// For more information visit https://www.w3schools.com/tags/tag_noscript.asp.
func Noscript(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "noscript", Attributes: attrs, Children: children}
}
// Noscript_ is a convenience wrapper for Noscript without the attrs argument.
func Noscript_(children ...HTML) HTML {
return Noscript(nil, children...)
}
// Object represents the HTML element 'object'.
// For more information visit https://www.w3schools.com/tags/tag_object.asp.
func Object(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "object", Attributes: attrs, Children: children}
}
// Object_ is a convenience wrapper for Object without the attrs argument.
func Object_(children ...HTML) HTML {
return Object(nil, children...)
}
// Ol represents the HTML element 'ol'.
// For more information visit https://www.w3schools.com/tags/tag_ol.asp.
func Ol(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "ol", Attributes: attrs, Children: children}
}
// Ol_ is a convenience wrapper for Ol without the attrs argument.
func Ol_(children ...HTML) HTML {
return Ol(nil, children...)
}
// Optgroup represents the HTML element 'optgroup'.
// For more information visit https://www.w3schools.com/tags/tag_optgroup.asp.
func Optgroup(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "optgroup", Attributes: attrs, Children: children}
}
// Optgroup_ is a convenience wrapper for Optgroup without the attrs argument.
func Optgroup_(children ...HTML) HTML {
return Optgroup(nil, children...)
}
// Option represents the HTML element 'option'.
// For more information visit https://www.w3schools.com/tags/tag_option.asp.
func Option(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "option", Attributes: attrs, Children: children}
}
// Option_ is a convenience wrapper for Option without the attrs argument.
func Option_(children ...HTML) HTML {
return Option(nil, children...)
}
// Output represents the HTML element 'output'.
// For more information visit https://www.w3schools.com/tags/tag_output.asp.
func Output(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "output", Attributes: attrs, Children: children}
}
// Output_ is a convenience wrapper for Output without the attrs argument.
func Output_(children ...HTML) HTML {
return Output(nil, children...)
}
// P represents the HTML element 'p'.
// For more information visit https://www.w3schools.com/tags/tag_p.asp.
func P(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "p", Attributes: attrs, Children: children}
}
// P_ is a convenience wrapper for P without the attrs argument.
func P_(children ...HTML) HTML {
return P(nil, children...)
}
// Plaintext represents the HTML element 'plaintext'.
// For more information visit https://www.w3schools.com/tags/tag_plaintext.asp.
func Plaintext(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "plaintext", Attributes: attrs, Children: children}
}
// Plaintext_ is a convenience wrapper for Plaintext without the attrs argument.
func Plaintext_(children ...HTML) HTML {
return Plaintext(nil, children...)
}
// Pre represents the HTML element 'pre'.
// For more information visit https://www.w3schools.com/tags/tag_pre.asp.
func Pre(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "pre", Attributes: attrs, Children: children}
}
// Pre_ is a convenience wrapper for Pre without the attrs argument.
func Pre_(children ...HTML) HTML {
return Pre(nil, children...)
}
// Progress represents the HTML element 'progress'.
// For more information visit https://www.w3schools.com/tags/tag_progress.asp.
func Progress(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "progress", Attributes: attrs, Children: children}
}
// Progress_ is a convenience wrapper for Progress without the attrs argument.
func Progress_(children ...HTML) HTML {
return Progress(nil, children...)
}
// Q represents the HTML element 'q'.
// For more information visit https://www.w3schools.com/tags/tag_q.asp.
func Q(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "q", Attributes: attrs, Children: children}
}
// Q_ is a convenience wrapper for Q without the attrs argument.
func Q_(children ...HTML) HTML {
return Q(nil, children...)
}
// Rp represents the HTML element 'rp'.
// For more information visit https://www.w3schools.com/tags/tag_rp.asp.
func Rp(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "rp", Attributes: attrs, Children: children}
}
// Rp_ is a convenience wrapper for Rp without the attrs argument.
func Rp_(children ...HTML) HTML {
return Rp(nil, children...)
}
// Rt represents the HTML element 'rt'.
// For more information visit https://www.w3schools.com/tags/tag_rt.asp.
func Rt(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "rt", Attributes: attrs, Children: children}
}
// Rt_ is a convenience wrapper for Rt without the attrs argument.
func Rt_(children ...HTML) HTML {
return Rt(nil, children...)
}
// Ruby represents the HTML element 'ruby'.
// For more information visit https://www.w3schools.com/tags/tag_ruby.asp.
func Ruby(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "ruby", Attributes: attrs, Children: children}
}
// Ruby_ is a convenience wrapper for Ruby without the attrs argument.
func Ruby_(children ...HTML) HTML {
return Ruby(nil, children...)
}
// S represents the HTML element 's'.
// For more information visit https://www.w3schools.com/tags/tag_s.asp.
func S(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "s", Attributes: attrs, Children: children}
}
// S_ is a convenience wrapper for S without the attrs argument.
func S_(children ...HTML) HTML {
return S(nil, children...)
}
// Samp represents the HTML element 'samp'.
// For more information visit https://www.w3schools.com/tags/tag_samp.asp.
func Samp(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "samp", Attributes: attrs, Children: children}
}
// Samp_ is a convenience wrapper for Samp without the attrs argument.
func Samp_(children ...HTML) HTML {
return Samp(nil, children...)
}
// Script represents the HTML element 'script'.
// For more information visit https://www.w3schools.com/tags/tag_script.asp.
func Script(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "script", Attributes: attrs, Children: children}
}
// Script_ is a convenience wrapper for Script without the attrs argument.
func Script_(children ...HTML) HTML {
return Script(nil, children...)
}
// Section represents the HTML element 'section'.
// For more information visit https://www.w3schools.com/tags/tag_section.asp.
func Section(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "section", Attributes: attrs, Children: children}
}
// Section_ is a convenience wrapper for Section without the attrs argument.
func Section_(children ...HTML) HTML {
return Section(nil, children...)
}
// Select represents the HTML element 'select'.
// For more information visit https://www.w3schools.com/tags/tag_select.asp.
func Select(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "select", Attributes: attrs, Children: children}
}
// Select_ is a convenience wrapper for Select without the attrs argument.
func Select_(children ...HTML) HTML {
return Select(nil, children...)
}
// Small represents the HTML element 'small'.
// For more information visit https://www.w3schools.com/tags/tag_small.asp.
func Small(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "small", Attributes: attrs, Children: children}
}
// Small_ is a convenience wrapper for Small without the attrs argument.
func Small_(children ...HTML) HTML {
return Small(nil, children...)
}
// Spacer represents the HTML element 'spacer'.
// For more information visit https://www.w3schools.com/tags/tag_spacer.asp.
func Spacer(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "spacer", Attributes: attrs, Children: children}
}
// Spacer_ is a convenience wrapper for Spacer without the attrs argument.
func Spacer_(children ...HTML) HTML {
return Spacer(nil, children...)
}
// Span represents the HTML element 'span'.
// For more information visit https://www.w3schools.com/tags/tag_span.asp.
func Span(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "span", Attributes: attrs, Children: children}
}
// Span_ is a convenience wrapper for Span without the attrs argument.
func Span_(children ...HTML) HTML {
return Span(nil, children...)
}
// Strike represents the HTML element 'strike'.
// For more information visit https://www.w3schools.com/tags/tag_strike.asp.
func Strike(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "strike", Attributes: attrs, Children: children}
}
// Strike_ is a convenience wrapper for Strike without the attrs argument.
func Strike_(children ...HTML) HTML {
return Strike(nil, children...)
}
// Strong represents the HTML element 'strong'.
// For more information visit https://www.w3schools.com/tags/tag_strong.asp.
func Strong(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "strong", Attributes: attrs, Children: children}
}
// Strong_ is a convenience wrapper for Strong without the attrs argument.
func Strong_(children ...HTML) HTML {
return Strong(nil, children...)
}
// Style represents the HTML element 'style'.
// For more information visit https://www.w3schools.com/tags/tag_style.asp.
func Style(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "style", Attributes: attrs, Children: children}
}
// Style_ is a convenience wrapper for Style without the attrs argument.
func Style_(children ...HTML) HTML {
return Style(nil, children...)
}
// Sub represents the HTML element 'sub'.
// For more information visit https://www.w3schools.com/tags/tag_sub.asp.
func Sub(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "sub", Attributes: attrs, Children: children}
}
// Sub_ is a convenience wrapper for Sub without the attrs argument.
func Sub_(children ...HTML) HTML {
return Sub(nil, children...)
}
// Summary represents the HTML element 'summary'.
// For more information visit https://www.w3schools.com/tags/tag_summary.asp.
func Summary(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "summary", Attributes: attrs, Children: children}
}
// Summary_ is a convenience wrapper for Summary without the attrs argument.
func Summary_(children ...HTML) HTML {
return Summary(nil, children...)
}
// Sup represents the HTML element 'sup'.
// For more information visit https://www.w3schools.com/tags/tag_sup.asp.
func Sup(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "sup", Attributes: attrs, Children: children}
}
// Sup_ is a convenience wrapper for Sup without the attrs argument.
func Sup_(children ...HTML) HTML {
return Sup(nil, children...)
}
// Table represents the HTML element 'table'.
// For more information visit https://www.w3schools.com/tags/tag_table.asp.
func Table(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "table", Attributes: attrs, Children: children}
}
// Table_ is a convenience wrapper for Table without the attrs argument.
func Table_(children ...HTML) HTML {
return Table(nil, children...)
}
// Tbody represents the HTML element 'tbody'.
// For more information visit https://www.w3schools.com/tags/tag_tbody.asp.
func Tbody(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "tbody", Attributes: attrs, Children: children}
}
// Tbody_ is a convenience wrapper for Tbody without the attrs argument.
func Tbody_(children ...HTML) HTML {
return Tbody(nil, children...)
}
// Td represents the HTML element 'td'.
// For more information visit https://www.w3schools.com/tags/tag_td.asp.
func Td(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "td", Attributes: attrs, Children: children}
}
// Td_ is a convenience wrapper for Td without the attrs argument.
func Td_(children ...HTML) HTML {
return Td(nil, children...)
}
// Textarea represents the HTML element 'textarea'.
// For more information visit https://www.w3schools.com/tags/tag_textarea.asp.
func Textarea(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "textarea", Attributes: attrs, Children: children}
}
// Textarea_ is a convenience wrapper for Textarea without the attrs argument.
func Textarea_(children ...HTML) HTML {
return Textarea(nil, children...)
}
// Tfoot represents the HTML element 'tfoot'.
// For more information visit https://www.w3schools.com/tags/tag_tfoot.asp.
func Tfoot(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "tfoot", Attributes: attrs, Children: children}
}
// Tfoot_ is a convenience wrapper for Tfoot without the attrs argument.
func Tfoot_(children ...HTML) HTML {
return Tfoot(nil, children...)
}
// Th represents the HTML element 'th'.
// For more information visit https://www.w3schools.com/tags/tag_th.asp.
func Th(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "th", Attributes: attrs, Children: children}
}
// Th_ is a convenience wrapper for Th without the attrs argument.
func Th_(children ...HTML) HTML {
return Th(nil, children...)
}
// Thead represents the HTML element 'thead'.
// For more information visit https://www.w3schools.com/tags/tag_thead.asp.
func Thead(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "thead", Attributes: attrs, Children: children}
}
// Thead_ is a convenience wrapper for Thead without the attrs argument.
func Thead_(children ...HTML) HTML {
return Thead(nil, children...)
}
// Time represents the HTML element 'time'.
// For more information visit https://www.w3schools.com/tags/tag_time.asp.
func Time(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "time", Attributes: attrs, Children: children}
}
// Time_ is a convenience wrapper for Time without the attrs argument.
func Time_(children ...HTML) HTML {
return Time(nil, children...)
}
// Title represents the HTML element 'title'.
// For more information visit https://www.w3schools.com/tags/tag_title.asp.
func Title(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "title", Attributes: attrs, Children: children}
}
// Title_ is a convenience wrapper for Title without the attrs argument.
func Title_(children ...HTML) HTML {
return Title(nil, children...)
}
// Tr represents the HTML element 'tr'.
// For more information visit https://www.w3schools.com/tags/tag_tr.asp.
func Tr(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "tr", Attributes: attrs, Children: children}
}
// Tr_ is a convenience wrapper for Tr without the attrs argument.
func Tr_(children ...HTML) HTML {
return Tr(nil, children...)
}
// Tt represents the HTML element 'tt'.
// For more information visit https://www.w3schools.com/tags/tag_tt.asp.
func Tt(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "tt", Attributes: attrs, Children: children}
}
// Tt_ is a convenience wrapper for Tt without the attrs argument.
func Tt_(children ...HTML) HTML {
return Tt(nil, children...)
}
// U represents the HTML element 'u'.
// For more information visit https://www.w3schools.com/tags/tag_u.asp.
func U(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "u", Attributes: attrs, Children: children}
}
// U_ is a convenience wrapper for U without the attrs argument.
func U_(children ...HTML) HTML {
return U(nil, children...)
}
// Ul represents the HTML element 'ul'.
// For more information visit https://www.w3schools.com/tags/tag_ul.asp.
func Ul(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "ul", Attributes: attrs, Children: children}
}
// Ul_ is a convenience wrapper for Ul without the attrs argument.
func Ul_(children ...HTML) HTML {
return Ul(nil, children...)
}
// Var represents the HTML element 'var'.
// For more information visit https://www.w3schools.com/tags/tag_var.asp.
func Var(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "var", Attributes: attrs, Children: children}
}
// Var_ is a convenience wrapper for Var without the attrs argument.
func Var_(children ...HTML) HTML {
return Var(nil, children...)
}
// Video represents the HTML element 'video'.
// For more information visit https://www.w3schools.com/tags/tag_video.asp.
func Video(attrs []htmlgo.Attribute, children ...HTML) HTML {
return &htmlgo.Tree{Tag: "video", Attributes: attrs, Children: children}
}
// Video_ is a convenience wrapper for Video without the attrs argument.
func Video_(children ...HTML) HTML {
return Video(nil, children...)
}
// Void Elements
// Area represents the HTML void element 'area'.
// For more information visit https://www.w3schools.com/tags/tag_area.asp.
func Area(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "area", Attributes: attrs, SelfClosing: true}
}
// Area_ is a convenience wrapper for Area without the attrs argument.
func Area_() HTML {
return Area(nil)
}
// Base represents the HTML void element 'base'.
// For more information visit https://www.w3schools.com/tags/tag_base.asp.
func Base(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "base", Attributes: attrs, SelfClosing: true}
}
// Base_ is a convenience wrapper for Base without the attrs argument.
func Base_() HTML {
return Base(nil)
}
// Br represents the HTML void element 'br'.
// For more information visit https://www.w3schools.com/tags/tag_br.asp.
func Br(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "br", Attributes: attrs, SelfClosing: true}
}
// Br_ is a convenience wrapper for Br without the attrs argument.
func Br_() HTML {
return Br(nil)
}
// Col represents the HTML void element 'col'.
// For more information visit https://www.w3schools.com/tags/tag_col.asp.
func Col(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "col", Attributes: attrs, SelfClosing: true}
}
// Col_ is a convenience wrapper for Col without the attrs argument.
func Col_() HTML {
return Col(nil)
}
// Embed represents the HTML void element 'embed'.
// For more information visit https://www.w3schools.com/tags/tag_embed.asp.
func Embed(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "embed", Attributes: attrs, SelfClosing: true}
}
// Embed_ is a convenience wrapper for Embed without the attrs argument.
func Embed_() HTML {
return Embed(nil)
}
// Hr represents the HTML void element 'hr'.
// For more information visit https://www.w3schools.com/tags/tag_hr.asp.
func Hr(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "hr", Attributes: attrs, SelfClosing: true}
}
// Hr_ is a convenience wrapper for Hr without the attrs argument.
func Hr_() HTML {
return Hr(nil)
}
// Img represents the HTML void element 'img'.
// For more information visit https://www.w3schools.com/tags/tag_img.asp.
func Img(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "img", Attributes: attrs, SelfClosing: true}
}
// Img_ is a convenience wrapper for Img without the attrs argument.
func Img_() HTML {
return Img(nil)
}
// Input represents the HTML void element 'input'.
// For more information visit https://www.w3schools.com/tags/tag_input.asp.
func Input(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "input", Attributes: attrs, SelfClosing: true}
}
// Input_ is a convenience wrapper for Input without the attrs argument.
func Input_() HTML {
return Input(nil)
}
// Link represents the HTML void element 'link'.
// For more information visit https://www.w3schools.com/tags/tag_link.asp.
func Link(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "link", Attributes: attrs, SelfClosing: true}
}
// Link_ is a convenience wrapper for Link without the attrs argument.
func Link_() HTML {
return Link(nil)
}
// Meta represents the HTML void element 'meta'.
// For more information visit https://www.w3schools.com/tags/tag_meta.asp.
func Meta(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "meta", Attributes: attrs, SelfClosing: true}
}
// Meta_ is a convenience wrapper for Meta without the attrs argument.
func Meta_() HTML {
return Meta(nil)
}
// Param represents the HTML void element 'param'.
// For more information visit https://www.w3schools.com/tags/tag_param.asp.
func Param(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "param", Attributes: attrs, SelfClosing: true}
}
// Param_ is a convenience wrapper for Param without the attrs argument.
func Param_() HTML {
return Param(nil)
}
// Source represents the HTML void element 'source'.
// For more information visit https://www.w3schools.com/tags/tag_source.asp.
func Source(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "source", Attributes: attrs, SelfClosing: true}
}
// Source_ is a convenience wrapper for Source without the attrs argument.
func Source_() HTML {
return Source(nil)
}
// Track represents the HTML void element 'track'.
// For more information visit https://www.w3schools.com/tags/tag_track.asp.
func Track(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "track", Attributes: attrs, SelfClosing: true}
}
// Track_ is a convenience wrapper for Track without the attrs argument.
func Track_() HTML {
return Track(nil)
}
// Wbr represents the HTML void element 'wbr'.
// For more information visit https://www.w3schools.com/tags/tag_wbr.asp.
func Wbr(attrs []htmlgo.Attribute) HTML {
return &htmlgo.Tree{Tag: "wbr", Attributes: attrs, SelfClosing: true}
}
// Wbr_ is a convenience wrapper for Wbr without the attrs argument.
func Wbr_() HTML {
return Wbr(nil)
} | elements/elements.go | 0.885471 | 0.410697 | elements.go | starcoder |
package stockdata
import (
"github.com/windler/etf-dash/timeseries"
)
//DataRetriever gets stockdata as timeseries.FloatSeries
type DataRetriever interface {
GetSeries(symbol string) timeseries.FloatSeries
}
//Analyzed reepresents analyzed stock data result
type Analyzed struct {
DepotValues map[string]timeseries.FloatSeries `json:"depotValues"`
Stocks map[string]timeseries.FloatSeries `json:"stocks"`
Spendings map[string]timeseries.FloatSeries `json:"spendings"`
WinLoss map[string]timeseries.FloatSeries `json:"winLoss"`
AnnualTaxes map[string]timeseries.FloatSeries `json:"annualTaxes"`
SellingTaxes map[string]timeseries.FloatSeries `json:"sellingTaxes"`
Allocations map[string]timeseries.FloatSeries `json:"allocations"`
Amounts map[string]timeseries.FloatSeries `json:"amounts"`
}
//MonthlySaving are monthly savings that apply to analyzeation
type MonthlySaving struct {
Symbol string `json:"symbol"`
InitialAmount float64 `json:"initialAmount"`
Saving float64 `json:"monthlySavings"`
}
//Calculator analyzes stock progression
type Calculator struct {
TransactionCostPercentage float64
Allowance float64
StockDataRetriever *DataRetriever
}
//Analyze analyzes stock progression
func (c Calculator) Analyze(monthlySavings []MonthlySaving) *Analyzed {
stocks := map[string]timeseries.FloatSeries{}
depotValues := map[string]timeseries.FloatSeries{}
spendings := map[string]timeseries.FloatSeries{}
winLoss := map[string]timeseries.FloatSeries{}
annualTaxes := map[string]timeseries.FloatSeries{}
sellingTaxes := map[string]timeseries.FloatSeries{}
allocations := map[string]timeseries.FloatSeries{}
amounts := map[string]timeseries.FloatSeries{}
taxCalculator := &TaxCalculator{}
for _, monthlySaving := range monthlySavings {
series := (*c.StockDataRetriever).GetSeries(monthlySaving.Symbol)
stocks[monthlySaving.Symbol] = series
amountSeries := series.Calc(series, func(a, b float64) float64 {
return monthlySaving.Saving
})
amountSeries = amountSeries.Calc(series, func(a, b float64) float64 {
return a / b
})
amountSeries.Add(series.FirstTimePoint(), monthlySaving.InitialAmount)
amountSeries = amountSeries.ToCumulativeSeries()
amounts[monthlySaving.Symbol] = *amountSeries
depotValueSeries := amountSeries.Calc(series, func(a, b float64) float64 {
return a * b
})
annualTaxes[monthlySaving.Symbol] = *(depotValueSeries.CalcFP(*depotValueSeries, taxCalculator.taxFn(*depotValueSeries, true)))
sellingTaxes[monthlySaving.Symbol] = *(depotValueSeries.CalcFP(*depotValueSeries, taxCalculator.taxFn(*depotValueSeries, false)))
spendingsSeries := series.Calc(series, func(a, b float64) float64 {
return (monthlySaving.Saving * (1 + c.TransactionCostPercentage))
})
spendingsSeries.Add(series.FirstTimePoint(), (depotValueSeries.First() - monthlySaving.Saving*(1+c.TransactionCostPercentage)))
spendingsSeries = spendingsSeries.ToCumulativeSeries()
depotValues[monthlySaving.Symbol] = *depotValueSeries
spendings[monthlySaving.Symbol] = *spendingsSeries
winLoss[monthlySaving.Symbol] = *(depotValueSeries.Calc(*spendingsSeries, func(a, b float64) float64 {
return a - b
}))
}
depotValues["Total"] = *(timeseries.Calc(func(a, b float64) float64 {
return a + b
}, getTimeSeries(depotValues)...))
total := depotValues["Total"]
for symbol, depotValSeries := range depotValues {
if symbol == "Total" {
continue
}
allocations[symbol] = *(total.Calc(depotValSeries, func(a, b float64) float64 {
return b / a
}))
}
winLoss["Total"] = *(timeseries.Calc(func(a, b float64) float64 {
return a + b
}, getTimeSeries(winLoss)...))
spendings["Total"] = *(timeseries.Calc(func(a, b float64) float64 {
return a + b
}, getTimeSeries(spendings)...))
annualTaxes["Total"] = *(timeseries.Calc(func(a, b float64) float64 {
return a + b
}, getTimeSeries(annualTaxes)...))
sellingTaxes["Total"] = *(timeseries.Calc(func(a, b float64) float64 {
return a + b
}, getTimeSeries(sellingTaxes)...))
return &Analyzed{
Stocks: stocks,
DepotValues: depotValues,
WinLoss: winLoss,
Spendings: spendings,
AnnualTaxes: annualTaxes,
SellingTaxes: sellingTaxes,
Allocations: allocations,
Amounts: amounts,
}
}
func getTimeSeries(seriesMap map[string]timeseries.FloatSeries) []timeseries.FloatSeries {
m := make([]timeseries.FloatSeries, 0, len(seriesMap))
for _, val := range seriesMap {
m = append(m, val)
}
return m
} | stockdata/stockdata.go | 0.74872 | 0.543348 | stockdata.go | starcoder |
package dfl
import (
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/spatialcurrent/go-dfl/pkg/dfl/syntax"
)
// ParseList parses a list of values.
func ParseList(in string) ([]Node, error) {
nodes := make([]Node, 0)
singlequotes := 0
doublequotes := 0
backticks := 0
leftparentheses := 0
rightparentheses := 0
leftcurlybrackets := 0
rightcurlybrackets := 0
leftsquarebrackets := 0
rightsquarebrackets := 0
in = strings.TrimSpace(in)
s := ""
for i, c := range in {
// If you're note in a quoted string, then you can start one
// If you're in a quoted string, only exit with matching quote.
if singlequotes == 0 && doublequotes == 0 && backticks == 0 {
switch c {
case '\'':
singlequotes += 1
case '"':
doublequotes += 1
case '`':
backticks += 1
case '(':
leftparentheses += 1
case '[':
leftsquarebrackets += 1
case '{':
leftcurlybrackets += 1
case ')':
rightparentheses += 1
case ']':
rightsquarebrackets += 1
case '}':
rightcurlybrackets += 1
}
} else if singlequotes == 1 && c == '\'' {
singlequotes -= 1
} else if doublequotes == 1 && c == '"' {
doublequotes -= 1
} else if backticks == 1 && c == '`' {
backticks -= 1
}
// If not (within string/array/set/sub and c == ,)
if !(singlequotes == 0 &&
doublequotes == 0 &&
backticks == 0 &&
leftparentheses == rightparentheses &&
leftcurlybrackets == rightcurlybrackets &&
leftsquarebrackets == rightsquarebrackets &&
c == ',') {
s += string(c)
}
// If sub/array/set and string are closed.
if singlequotes == 0 &&
doublequotes == 0 &&
backticks == 0 &&
leftparentheses == rightparentheses &&
leftsquarebrackets == rightsquarebrackets &&
leftcurlybrackets == rightcurlybrackets {
// If end of input or argument
if i+1 == len(in) || in[i+1] == ',' {
s = strings.TrimSpace(s)
if syntax.IsQuoted(s) {
nodes = append(nodes, &Literal{Value: UnescapeString(s[1 : len(s)-1])})
} else if syntax.IsAttribute(s) {
attr, _, err := ParseAttribute(s, "")
if err != nil {
return nodes, errors.Wrap(err, "error parsing attribute in list "+s)
}
nodes = append(nodes, attr)
} else if syntax.IsVariable(s) {
variable, _, err := ParseVariable(s, "")
if err != nil {
return nodes, errors.Wrap(err, "error parsing variable in list "+s)
}
nodes = append(nodes, variable)
} else if syntax.IsArray(s) {
arr, _, err := ParseArray(strings.TrimSpace(s[1:len(s)-1]), "")
if err != nil {
return nodes, errors.Wrap(err, "error parsing array in list "+s)
}
nodes = append(nodes, arr)
} else if syntax.IsSetOrDictionary(s) {
setOrDictionary, _, err := ParseSetOrDictionary(strings.TrimSpace(s[1:len(s)-1]), "")
if err != nil {
return nodes, errors.Wrap(err, "error parsing set in list "+s)
}
nodes = append(nodes, setOrDictionary)
} else if syntax.IsSub(s) {
sub, _, err := ParseSub(strings.TrimSpace(s[1:len(s)-1]), "")
if err != nil {
return nodes, errors.Wrap(err, "error parsing sub in list "+s)
}
nodes = append(nodes, sub)
} else if syntax.IsFunction(s) {
f, _, err := ParseFunction(s, "")
if err != nil {
return nodes, errors.Wrap(err, "error parsing function in list "+s)
}
nodes = append(nodes, f)
} else {
nodes = append(nodes, &Literal{Value: TryConvertString(s)})
}
s = ""
}
}
}
if leftparentheses > rightparentheses {
return nodes, errors.New("too few closing parentheses " + fmt.Sprint(leftparentheses) + " | " + fmt.Sprint(rightparentheses))
} else if leftparentheses < rightparentheses {
return nodes, errors.New("too many closing parentheses " + fmt.Sprint(leftparentheses) + " | " + fmt.Sprint(rightparentheses))
} else if leftcurlybrackets > rightcurlybrackets {
return nodes, errors.New("too few closing curly brackets " + fmt.Sprint(leftcurlybrackets) + " | " + fmt.Sprint(rightcurlybrackets))
} else if leftcurlybrackets < rightcurlybrackets {
return nodes, errors.New("too many closing curly brackets " + fmt.Sprint(leftcurlybrackets) + " | " + fmt.Sprint(rightparentheses))
} else if leftsquarebrackets > rightsquarebrackets {
return nodes, errors.New("too few closing square brackets " + fmt.Sprint(leftsquarebrackets) + " | " + fmt.Sprint(rightsquarebrackets))
} else if leftsquarebrackets < rightsquarebrackets {
return nodes, errors.New("too many closing square brackets " + fmt.Sprint(leftsquarebrackets) + " | " + fmt.Sprint(rightsquarebrackets))
}
return nodes, nil
} | pkg/dfl/ParseList.go | 0.51562 | 0.445288 | ParseList.go | starcoder |
// Package storetestcases defines test cases to test stores.
package storetestcases
import (
"testing"
"github.com/stratumn/go-core/store"
"github.com/stretchr/testify/require"
)
// Factory wraps functions to allocate and free an adapter,
// and is used to run the tests on an adapter.
type Factory struct {
// New creates an adapter.
New func() (store.Adapter, error)
// Free is an optional function to free an adapter.
Free func(adapter store.Adapter)
// NewKeyValueStore creates a KeyValueStore.
// If your store implements the KeyValueStore interface,
// you need to implement this method.
NewKeyValueStore func() (store.KeyValueStore, error)
// FreeKeyValueStore is an optional function to free
// a KeyValueStore adapter.
FreeKeyValueStore func(adapter store.KeyValueStore)
}
// RunKeyValueStoreTests runs all the tests for the key value store interface.
func (f Factory) RunKeyValueStoreTests(t *testing.T) {
t.Run("TestKeyValueStore", f.TestKeyValueStore)
}
// RunStoreTests runs all the tests for the store adapter interface.
func (f Factory) RunStoreTests(t *testing.T) {
t.Run("Test store events", f.TestStoreEvents)
t.Run("Test store info", f.TestGetInfo)
t.Run("Test adapter config", f.TestAdapterConfig)
t.Run("Test finding segments", f.TestFindSegments)
t.Run("Test getting map IDs", f.TestGetMapIDs)
t.Run("Test getting segments", f.TestGetSegment)
t.Run("Test creating links", f.TestCreateLink)
t.Run("Test batch implementation", f.TestBatch)
t.Run("Test evidence store", f.TestEvidenceStore)
}
// RunStoreBenchmarks runs all the benchmarks for the store adapter interface.
func (f Factory) RunStoreBenchmarks(b *testing.B) {
b.Run("BenchmarkCreateLink", f.BenchmarkCreateLink)
b.Run("BenchmarkCreateLinkParallel", f.BenchmarkCreateLinkParallel)
b.Run("FindSegments100", f.BenchmarkFindSegments100)
b.Run("FindSegments1000", f.BenchmarkFindSegments1000)
b.Run("FindSegments10000", f.BenchmarkFindSegments10000)
b.Run("FindSegmentsMapID100", f.BenchmarkFindSegmentsMapID100)
b.Run("FindSegmentsMapID1000", f.BenchmarkFindSegmentsMapID1000)
b.Run("FindSegmentsMapID10000", f.BenchmarkFindSegmentsMapID10000)
b.Run("FindSegmentsMapIDs100", f.BenchmarkFindSegmentsMapIDs100)
b.Run("FindSegmentsMapIDs1000", f.BenchmarkFindSegmentsMapIDs1000)
b.Run("FindSegmentsMapIDs10000", f.BenchmarkFindSegmentsMapIDs10000)
b.Run("FindSegmentsPrevLinkHash100", f.BenchmarkFindSegmentsPrevLinkHash100)
b.Run("FindSegmentsPrevLinkHash1000", f.BenchmarkFindSegmentsPrevLinkHash1000)
b.Run("FindSegmentsPrevLinkHash10000", f.BenchmarkFindSegmentsPrevLinkHash10000)
b.Run("FindSegmentsTags100", f.BenchmarkFindSegmentsTags100)
b.Run("FindSegmentsTags1000", f.BenchmarkFindSegmentsTags1000)
b.Run("FindSegmentsTags10000", f.BenchmarkFindSegmentsTags10000)
b.Run("FindSegmentsMapIDTags100", f.BenchmarkFindSegmentsMapIDTags100)
b.Run("FindSegmentsMapIDTags1000", f.BenchmarkFindSegmentsMapIDTags1000)
b.Run("FindSegmentsMapIDTags10000", f.BenchmarkFindSegmentsMapIDTags10000)
b.Run("FindSegmentsPrevLinkHashTags100", f.BenchmarkFindSegmentsPrevLinkHashTags100)
b.Run("FindSegmentsPrevLinkHashTags1000", f.BenchmarkFindSegmentsPrevLinkHashTags1000)
b.Run("FindSegmentsPrevLinkHashTags10000", f.BenchmarkFindSegmentsPrevLinkHashTags10000)
b.Run("FindSegments100Parallel", f.BenchmarkFindSegments100Parallel)
b.Run("FindSegments1000Parallel", f.BenchmarkFindSegments1000Parallel)
b.Run("FindSegments10000Parallel", f.BenchmarkFindSegments10000Parallel)
b.Run("FindSegmentsMapID100Parallel", f.BenchmarkFindSegmentsMapID100Parallel)
b.Run("FindSegmentsMapID1000Parallel", f.BenchmarkFindSegmentsMapID1000Parallel)
b.Run("FindSegmentsMapID10000Parallel", f.BenchmarkFindSegmentsMapID10000Parallel)
b.Run("FindSegmentsMapIDs100Parallel", f.BenchmarkFindSegmentsMapIDs100Parallel)
b.Run("FindSegmentsMapIDs1000Parallel", f.BenchmarkFindSegmentsMapIDs1000Parallel)
b.Run("FindSegmentsMapIDs10000Parallel", f.BenchmarkFindSegmentsMapIDs10000Parallel)
b.Run("FindSegmentsPrevLinkHash100Parallel", f.BenchmarkFindSegmentsPrevLinkHash100Parallel)
b.Run("FindSegmentsPrevLinkHash1000Parallel", f.BenchmarkFindSegmentsPrevLinkHash1000Parallel)
b.Run("FindSegmentsPrevLinkHash10000ParalleRunBenchmarksl", f.BenchmarkFindSegmentsPrevLinkHash10000Parallel)
b.Run("FindSegmentsTags100Parallel", f.BenchmarkFindSegmentsTags100Parallel)
b.Run("FindSegmentsTags1000Parallel", f.BenchmarkFindSegmentsTags1000Parallel)
b.Run("FindSegmentsTags10000Parallel", f.BenchmarkFindSegmentsTags10000Parallel)
b.Run("FindSegmentsMapIDTags100Parallel", f.BenchmarkFindSegmentsMapIDTags100Parallel)
b.Run("FindSegmentsMapIDTags1000Parallel", f.BenchmarkFindSegmentsMapIDTags1000Parallel)
b.Run("FindSegmentsMapIDTags10000Parallel", f.BenchmarkFindSegmentsMapIDTags10000Parallel)
b.Run("FindSegmentsPrevLinkHashTags100Parallel", f.BenchmarkFindSegmentsPrevLinkHashTags100Parallel)
b.Run("FindSegmentsPrevLinkHashTags1000Parallel", f.BenchmarkFindSegmentsPrevLinkHashTags1000Parallel)
b.Run("FindSegmentsPrevLinkHashTags10000Parallel", f.BenchmarkFindSegmentsPrevLinkHashTags10000Parallel)
b.Run("GetMapIDs100", f.BenchmarkGetMapIDs100)
b.Run("GetMapIDs1000", f.BenchmarkGetMapIDs1000)
b.Run("GetMapIDs10000", f.BenchmarkGetMapIDs10000)
b.Run("GetMapIDs100Parallel", f.BenchmarkGetMapIDs100Parallel)
b.Run("GetMapIDs1000Parallel", f.BenchmarkGetMapIDs1000Parallel)
b.Run("GetMapIDs10000Parallel", f.BenchmarkGetMapIDs10000Parallel)
b.Run("GetSegment", f.BenchmarkGetSegment)
b.Run("GetSegmentParallel", f.BenchmarkGetSegmentParallel)
}
// RunKeyValueStoreBenchmarks runs all the benchmarks for the key-value store interface.
func (f Factory) RunKeyValueStoreBenchmarks(b *testing.B) {
b.Run("GetValue", f.BenchmarkGetValue)
b.Run("GetValueParallel", f.BenchmarkGetValueParallel)
b.Run("SetValue", f.BenchmarkSetValue)
b.Run("SetValueParallel", f.BenchmarkSetValueParallel)
b.Run("DeleteValue", f.BenchmarkDeleteValue)
b.Run("DeleteValueParallel", f.BenchmarkDeleteValueParallel)
}
func (f Factory) initAdapter(t *testing.T) store.Adapter {
a, err := f.New()
require.NoError(t, err, "f.New()")
require.NotNil(t, a, "Store.Adapter")
return a
}
func (f Factory) initAdapterB(b *testing.B) store.Adapter {
a, err := f.New()
if err != nil {
b.Fatalf("f.New(): err: %s", err)
}
if a == nil {
b.Fatal("a = nil want store.Adapter")
}
return a
}
func (f Factory) freeAdapter(adapter store.Adapter) {
if f.Free != nil {
f.Free(adapter)
}
}
func (f Factory) initKeyValueStore(t *testing.T) store.KeyValueStore {
a, err := f.NewKeyValueStore()
require.NoError(t, err, "f.NewKeyValueStore()")
require.NotNil(t, a, "Store.KeyValueStore")
return a
}
func (f Factory) initKeyValueStoreB(b *testing.B) store.KeyValueStore {
a, err := f.NewKeyValueStore()
if err != nil {
b.Fatalf("f.NewKeyValueStore(): err: %s", err)
}
if a == nil {
b.Fatal("a = nil want store.KeyValueStore")
}
return a
}
func (f Factory) freeKeyValueStore(adapter store.KeyValueStore) {
if f.FreeKeyValueStore != nil {
f.FreeKeyValueStore(adapter)
}
} | store/storetestcases/storetestcases.go | 0.659405 | 0.590897 | storetestcases.go | starcoder |
package bloomfilter
// #cgo CFLAGS: -Wall
// #cgo LDFLAGS: -lm
// #include<math.h>
import "C"
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"github.com/Workiva/go-datastructures/bitarray"
)
var strategyList []Strategy = []Strategy{&Murur128Mitz32{}, &Murur128Mitz64{}}
// BloomFilter definition includes the number of hash functions, bit array, and strategy for hashing.
type BloomFilter struct {
numHashFunctions int
array bitarray.BitArray
strategy Strategy
}
// NewBloomFilter creates a new BloomFilter instance with `Murur128Mitz64` as default strategy.
func NewBloomFilter(expectedInsertions int, errRate float64) (*BloomFilter, error) {
return NewBloomFilterWithStrategy(expectedInsertions, errRate, &Murur128Mitz64{})
}
// NewBloomFilterWithStrategy creates a new BloomFilter instance with given expected insertions/capacity,
// error rate, and strategy. For now the available strategies are
// * &Murur128Mitz32{}
// * &Murur128Mitz64{}
func NewBloomFilterWithStrategy(expectedInsertions int, errRate float64, strategy Strategy) (*BloomFilter, error) {
if errRate <= 0.0 {
return nil, errors.New("Error rate must be > 0.0")
}
if errRate >= 1.0 {
return nil, errors.New("Error rate must be < 1.0")
}
if expectedInsertions < 0 {
return nil, errors.New("Expected insertions must be >= 0")
}
if expectedInsertions == 0 {
expectedInsertions = 1
}
numBits := numOfBits(expectedInsertions, errRate)
numHashFunctions := numOfHashFunctions(expectedInsertions, numBits)
bloomFilter := &BloomFilter{
numHashFunctions: numHashFunctions,
array: bitarray.NewBitArray(uint64(math.Ceil(float64(numBits)/64.0) * 64.0)),
strategy: strategy,
}
return bloomFilter, nil
}
// FromBytes creates a new BloomFilter instance by deserializing from byte array.
func FromBytes(b []byte) (*BloomFilter, error) {
reader := bytes.NewReader(b)
// read strategy
strategyByte, err := reader.ReadByte()
if err != nil {
return nil, fmt.Errorf("Failed to read strategy: %v", err)
}
strategyIndex := int(strategyByte)
if strategyIndex >= len(strategyList) {
return nil, fmt.Errorf("Unknown strategy byte: %v", strategyByte)
}
strategy := strategyList[strategyIndex]
// read number of hash functions
numHashFuncByte, err := reader.ReadByte()
if err != nil {
return nil, fmt.Errorf("Failed to read number of hash functions: %v", err)
}
numHashFunctions := int(numHashFuncByte)
// read bitarray capacity
numUint64Bytes, err := ioutil.ReadAll(io.LimitReader(reader, 4))
if err != nil {
return nil, fmt.Errorf("Failed to read number of bits: %v", err)
}
if len(numUint64Bytes) != 4 {
return nil, fmt.Errorf("Not a valid uint32 bytes: %v", numUint64Bytes)
}
numUint64 := binary.BigEndian.Uint32(numUint64Bytes)
array := bitarray.NewBitArray(uint64(numUint64) * 64)
// put blocks back to bitarray
for blockIdx := 0; blockIdx < int(numUint64); blockIdx++ {
block, err := ioutil.ReadAll(io.LimitReader(reader, 8))
if err != nil {
return nil, fmt.Errorf("Failed to build bitarray: %v", err)
}
if len(block) != 8 {
return nil, fmt.Errorf("Not a valid uint64 bytes: %v", block)
}
num := binary.BigEndian.Uint64(block)
var pos uint64 = 1 << 63
var index uint64
for i := 0; i < 64; i++ {
if num&pos > 0 {
index = uint64(blockIdx*64 + (64 - i - 1))
array.SetBit(index)
}
pos >>= 1
}
}
return &BloomFilter{
numHashFunctions: numHashFunctions,
array: array,
strategy: strategy,
}, nil
}
// Put inserts element of any type into BloomFilter.
func (bf *BloomFilter) Put(key interface{}) bool {
return bf.strategy.put(key, bf.numHashFunctions, bf.array)
}
// MightContain returns a boolean value to indicate if given element is in BloomFilter.
func (bf *BloomFilter) MightContain(key interface{}) bool {
return bf.strategy.mightContain(key, bf.numHashFunctions, bf.array)
}
// ToBytes serializes BloomFilter to byte array, which is compatible with
// Java's Guava library.
func (bf *BloomFilter) ToBytes() []byte {
buf := new(bytes.Buffer)
buf.WriteByte(byte(bf.strategy.getOrdinal()))
buf.WriteByte(byte(bf.numHashFunctions))
binary.Write(buf, binary.BigEndian, uint32(math.Ceil(float64(bf.array.Capacity())/64.0)))
for iter := bf.array.Blocks(); iter.Next(); {
_, block := iter.Value()
binary.Write(buf, binary.BigEndian, block)
}
return buf.Bytes()
}
func numOfBits(expectedInsertions int, errRate float64) int {
if errRate == 0.0 {
errRate = math.Pow(2.0, -1074.0) // the same number of Double.MIN_VALUE in Java
}
errorRate := C.double(errRate)
// Use C functions to calculate logarithm here since Go's built-in math lib doesn't give accurate result.
// See https://github.com/golang/go/issues/9546 for details.
return int(C.double(-expectedInsertions) * C.log(errorRate) / (C.log(C.double(2.0)) * C.log(C.double(2.0))))
}
func numOfHashFunctions(expectedInsertions int, numBits int) int {
return int(math.Max(1.0, float64(C.round(C.double(numBits)/C.double(expectedInsertions)*C.log(C.double(2.0))))))
} | bloomfilter.go | 0.729327 | 0.443299 | bloomfilter.go | starcoder |
package controllers
import (
"fmt"
"io"
"log"
"os"
"github.com/FelixDux/imposcg/charts"
"github.com/FelixDux/imposcg/dynamics"
"github.com/FelixDux/imposcg/dynamics/parameters"
"github.com/FelixDux/imposcg/dynamics/impact"
"github.com/gin-gonic/gin"
)
type SingularitySetResult struct {
Singularity []impact.Impact `json:"singularity"`
Dual []impact.Impact `json:"dual"`
}
func singularitySetData(parameters *parameters.Parameters, numPoints uint) (*SingularitySetResult, string) {
impactMap, errMap := dynamics.NewImpactMap(*parameters)
if errMap != nil {
return &SingularitySetResult{Singularity: nil, Dual: nil}, errMap.Error()
}
singularity, dual := impactMap.SingularitySet(numPoints)
return &SingularitySetResult{Singularity: singularity, Dual: dual}, ""
}
func singularitySetImage(parameters *parameters.Parameters, numPoints uint) string {
result, errString := singularitySetData(parameters, numPoints)
if result.Singularity == nil || result.Dual == nil {
return errString
} else {
return charts.ScatterPlot(*parameters, [][]impact.Impact{result.Singularity,result.Dual}, "Singularity set and dual").Name()
}
}
// PostSingularitySetImage godoc
// @Summary Singularity set
// @Description Return scatter plot of impacts which map to and from zero velocity impacts for a specified set of parameters
// @ID post-singularity-set-image
// @Accept x-www-form-urlencoded
// @Produce png
// @Param frequency formData number true "Forcing frequency" minimum(0)
// @Param offset formData number true "Obstacle offset from origin"
// @Param r formData number true "Coefficient of restitution" minimum(0) maximum(1)
// @Param maxPeriods formData int false "Number of periods without an impact after which the algorithm will report 'long excursions'" default(100)
// @Param numPoints formData int false "Number of impacts to map" default(5000)
// @Success 200 {object} dynamics.IterationResult
// @Failure 400 {object} string "Invalid parameters"
// @Router /singularity-set/image/ [post]
func PostSingularitySetImage(c *gin.Context) {
numPoints, parameters, errorString := SingularitySetInputsFromPost(c)
if parameters == nil || len(errorString) > 0 {
log.Print(errorString)
c.JSON(400, errorString)
} else {
img, err := os.Open(singularitySetImage(parameters, numPoints))
if err != nil {
log.Print(err)
c.JSON(400, fmt.Sprintf("Failed to complete singularity set - %s", err.Error()))
} else {
defer img.Close()
c.Writer.Header().Set("Content-Type", "image/png")
io.Copy(c.Writer, img)
}
}
}
// PostSingularitySetData godoc
// @Summary Singularity set data
// @Description Return impacts which map to and from zero velocity impacts for a specified set of parameters
// @ID post-singularity-set-data
// @Accept x-www-form-urlencoded
// @Produce json
// @Param frequency formData number true "Forcing frequency" minimum(0)
// @Param offset formData number true "Obstacle offset from origin"
// @Param r formData number true "Coefficient of restitution" minimum(0) maximum(1)
// @Param maxPeriods formData int false "Number of periods without an impact after which the algorithm will report 'long excursions'" default(100)
// @Param numPoints formData int false "Number of impacts to map" default(5000)
// @Success 200 {object} dynamics.IterationResult
// @Failure 400 {object} string "Invalid parameters"
// @Router /singularity-set/data/ [post]
func PostSingularitySetData(c *gin.Context) {
numPoints, parameters, errorString := SingularitySetInputsFromPost(c)
if parameters == nil || len(errorString) > 0 {
log.Print(errorString)
c.JSON(400, errorString)
} else {
result, errString := singularitySetData(parameters, numPoints)
if result.Singularity == nil || result.Dual == nil {
log.Print(errString)
c.JSON(400, fmt.Sprintf("Failed to complete singularity set - %s", errString))
} else {
c.JSON(200, result)
}
}
}
func AddSingularitySetControllers (r *gin.Engine) {
iteration := r.Group("/api/singularity-set")
iteration.POST("/data", PostSingularitySetData)
iteration.POST("/image", PostSingularitySetImage)
} | controllers/singularity-set.go | 0.70912 | 0.405861 | singularity-set.go | starcoder |
package leap
import "time"
// A list of all two-second-long POSIX timestamps that cross a leap second.
var Seconds = []int64{
time.Date(2015, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(2012, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(2008, 12, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(2005, 12, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1998, 12, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1997, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1995, 12, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1994, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1993, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1992, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1990, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1989, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1987, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1985, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1983, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1982, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1981, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1976, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1976, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1976, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1976, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1975, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1974, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1973, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1972, 12, 31, 23, 59, 59, 0, time.UTC).Unix(),
time.Date(1972, 06, 30, 23, 59, 59, 0, time.UTC).Unix(),
}
// Get the number of leap seconds that occured before this time.
func NumLeaps(t time.Time) time.Duration {
u := t.Unix()
for i, s := range Seconds {
if u > s {
return time.Duration(len(Seconds)-i) * time.Second
}
}
return 0
}
// Get the number of leap seconds that occured between two times.
func LeapDiff(t1 time.Time, t2 time.Time) time.Duration {
n := NumLeaps(t1) - NumLeaps(t2)
if n < 0 {
n = -n
}
return n
} | leap.go | 0.527073 | 0.416559 | leap.go | starcoder |
package date
import (
"bytes"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"time"
)
// Date is an nullable date type without time and timezone.
// In memory it stores year, month and day like joined hex integer 0x20180131
// what makes it comparable and sortable as integer. In database it stores
// as DATE. Null value is represented in memory as 0.
type Date uint32
var (
Separator byte = '-'
DatabaseSeparator byte = '-'
tmpl = [10]byte{'0', '0', '0', '0', Separator, '0', '0', Separator, '0', '0'}
tmplDB = [10]byte{'0', '0', '0', '0', DatabaseSeparator, '0', '0', DatabaseSeparator, '0', '0'}
tmplJS = [12]byte{'"', '0', '0', '0', '0', Separator, '0', '0', Separator, '0', '0', '"'}
// pfm stores preformatted dates before and after today,
// used for convertation improvement.
pfm map[Date]string
// pjm stores preformatted json dates before and after today,
// used for date unmarshal improvement.
pjm map[string]Date
null = []byte("null")
cache string
FiveYearBefore = Today().Add(-5, 0, 0)
FiveYearAfter = Today().Add(5, 0, 0)
)
// InitPreformattedValues
func InitPreformattedValues(from, to Date) {
pfm = make(map[Date]string, (to.Time().Sub(from.Time()))/(24*time.Hour)+1)
pjm = make(map[string]Date, (to.Time().Sub(from.Time()))/(24*time.Hour)+1)
d := from
for d < to {
d = d.Add(0, 0, 1)
pfm[d] = d.String()
//var b [10]byte
//d.byteArr(&b)
pjm[d.String()] = d
}
}
// Time converts Date to Time.
func (d Date) Time() time.Time {
return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, time.Local)
}
// UTC convert Date to time.Time in UTC zone.
func (d Date) UTC() time.Time {
return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, time.UTC)
}
// In convers Date to time.Time in specified location.
func (d Date) In(loc *time.Location) time.Time {
return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, loc)
}
func (d Date) byteArr(res *[10]byte) {
*res = tmpl
i := uint32(d)
zero := byte('0')
// cycle could be used but straight way looks more effective.
/*
var b [8]byte
val := uint32(d)
for i := uint8(0); i < 8; i++ {
b[7-i] = byte(uint8('0') + uint8(val&0x0000000F))
val = val >> 4
}
return b
*/
res[0] = byte((i>>28)&0x0000000F) + zero
res[1] = byte((i>>24)&0x0000000F) + zero
res[2] = byte((i>>20)&0x0000000F) + zero
res[3] = byte((i>>16)&0x0000000F) + zero
res[5] = byte((i>>12)&0x0000000F) + zero
res[6] = byte((i>>8)&0x0000000F) + zero
res[8] = byte((i>>4)&0x0000000F) + zero
res[9] = byte(i&0x0000000F) + zero
return
}
func (d Date) byteSlice(res []byte) {
i := uint32(d)
zero := byte('0')
res[0] = byte((i>>28)&0x0000000F) + zero
res[1] = byte((i>>24)&0x0000000F) + zero
res[2] = byte((i>>20)&0x0000000F) + zero
res[3] = byte((i>>16)&0x0000000F) + zero
res[5] = byte((i>>12)&0x0000000F) + zero
res[6] = byte((i>>8)&0x0000000F) + zero
res[8] = byte((i>>4)&0x0000000F) + zero
res[9] = byte(i&0x0000000F) + zero
return
}
// String implements interface Stringer. Returns empty string if date is empty.
// If not, returns date as a string YYYY-MM-DD.
func (d *Date) String() string {
if s, ok := pfm[*d]; ok {
return s
}
if !d.Valid() {
return ""
}
return d.string()
}
func (d Date) string() string {
var buf [10]byte
d.byteArr(&buf)
return string(buf[:])
}
// Add adds years, months or days or all together.
func (d Date) Add(years, months, days int) Date {
t := time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, time.UTC)
t = t.AddDate(years, months, days)
return New(t.Date())
}
// Parse parses input string. String expected in format YYYY*MM*DD where
// * is any single char separator.
func (d *Date) Parse(s string) error {
dt, err := Parse(s)
if err != nil {
return err
}
*d = dt
return nil
}
// Year returns year of the date.
func (d Date) Year() int {
i := uint32(d)
return int((i>>28)*1000 + ((i>>24)&0x000F)*100 + ((i>>20)&0x000F)*10 + (i>>16)&0x000F)
}
// Month returns month of the date.
func (d Date) Month() time.Month {
i := (uint32(d) >> 8) & 0x000000FF
return time.Month((i>>4)*10 + i&0x0F)
}
// Day returns day of the date.
func (d Date) Day() int {
i := uint32(d) & 0x000000FF
return int((i>>4)*10 + i&0x0F)
}
// Parse decodes string YYYY-MM-DD or quoted "YYYY-MM-DD" to Date.
// TODO: improve performance by implementing date parsing without
// calling time.Parse().
func Parse(s string) (Date, error) {
if s[0] == '"' {
s = s[1:]
}
t, err := parseYYYYMMDD([]byte(s))
if err != nil {
return Null(), err
}
return newDate(t.Year(), t.Month(), t.Day()), nil
}
func parseYYYYMMDD(b []byte) (Date, error) {
if len(b) < 10 {
return Null(), errors.New("input date length less then 10 bytes")
}
var (
y int
m, d int
)
y = int(b[0]-'0')*1000 + int(b[1]-'0')*100 + int(b[2]-'0')*10 + int(b[3]-'0')
m = int(b[5]-'0')*10 + int(b[6]-'0')
d = int(b[8]-'0')*10 + int(b[9]-'0')
if y > 9999 || m > 12 || d > 31 {
return Null(), errors.New("date parse errror")
}
// validate date
t := time.Date(y, time.Month(m), d, 0, 0, 0, 0, time.Local)
if t.Year() != y || t.Month() != time.Month(m) || t.Day() != d {
return Null(), errors.New("date parse errror")
}
return newDate(y, time.Month(m), d), nil
}
func newDate(y int, m time.Month, d int) Date {
return Date(dec2hexy(uint32(y))<<16 | (dec2hex(uint32(m)) << 8) | dec2hex(uint32(d)))
}
// dec2hex converts month or day 31 to 0x31
func dec2hex(i uint32) uint32 {
return (i/10)*16 + i%10
}
// dec2hexy converts year 2018 to 0x2018
func dec2hexy(i uint32) uint32 {
return (i/1000)*16*16*16 + ((i%1000)/100)*16*16 + (i%100)/10*16 + i%10
}
// Null returns null Date.
func Null() Date {
return Date(0)
}
// Value implements interface sql.Valuer
func (d Date) Value() (driver.Value, error) {
if !d.Valid() {
return nil, nil
}
return []byte(d.String()), nil
}
// Valid return false if Date is null.
func (d Date) Valid() bool {
return d > 0
}
// Scan implements database/sql Scanner interface.
func (d *Date) Scan(value interface{}) error {
if value == nil {
*d = Null()
return nil
}
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("Date.Scan: expected date.Date, got %T (%q)", value, value)
}
*d = NewFromTime(v)
return nil
}
// Today returns today's date.
func Today() Date {
t := time.Now()
return newDate(t.Year(), t.Month(), t.Day())
}
// New creates Date with specified year, month and day.
func New(y int, m time.Month, d int) Date {
return newDate(y, m, d)
}
// Scan implements encoding/json Unmarshaller interface.
func (d *Date) UnmarshalJSON(b []byte) error {
if (len(b) == 4 && bytes.Compare(b, null) == 0) || len(b) == 0 {
*d = Null()
return nil
}
b = b[1:11]
v, ok := pjm[string(b)]
if ok {
*d = v
return nil
}
var err error
*d, err = parseYYYYMMDD(b)
return err
}
// Scan implements encoding/json Unmarshaller interface.
func (d *Date) UnmarshalText(b []byte) error {
return d.UnmarshalJSON(b)
}
// MarshalJSON implements encoding/json Marshaller interface.
func (d Date) MarshalJSON() ([]byte, error) {
if !d.Valid() {
return null, nil
}
res := tmplJS[:]
d.byteSlice(res[1:])
return res, nil
}
// NewFromTime creates Date from Time. Be careful with timezones.
func NewFromTime(t time.Time) Date {
return newDate(t.Year(), t.Month(), t.Day())
}
func YearsBetweenToday(dt Date) int {
return YearsBetween(dt, Today())
}
// YearsBetween количество лет между двумя датами.
func YearsBetween(past, now Date) int {
age := now.Year() - past.Year()
switch {
case now.Month() > past.Month():
return age
case now.Month() < past.Month():
return age - 1
case now.Month() == past.Month():
if now.Day() < past.Day() {
return age - 1
}
}
return age
}
func (d *Date) Format(s string) string {
return d.Time().Format(s)
}
func (d Date) Date() (int, time.Month, int) {
return d.Year(), d.Month(), d.Day()
}
func Converter(value string) reflect.Value {
if v, err := Parse(value); err == nil {
return reflect.ValueOf(v)
}
return reflect.Value{}
} | date.go | 0.566139 | 0.418043 | date.go | starcoder |
import "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai"
/**
* A variable-length integer,
* in the format used by the 0xfe chunks in the `'dcmp' (0)` and `'dcmp' (1)` resource compression formats.
* See the dcmp_0 and dcmp_1 specs for more information about these compression formats.
*
* This variable-length integer format can store an integer `x` in any of the following ways:
*
* * In a single byte,
* if `0 <= x <= 0x7f`
* (7-bit unsigned integer)
* * In 2 bytes,
* if `-0x4000 <= x <= 0x3eff`
* (15-bit signed integer with the highest `0x100` values unavailable)
* * In 5 bytes, if `-0x80000000 <= x <= 0x7fffffff`
* (32-bit signed integer)
*
* In practice,
* values are always stored in the smallest possible format,
* but technically any of the larger formats could be used as well.
* @see <a href="https://github.com/dgelessus/python-rsrcfork/tree/master/rsrcfork/compress/common.py">Source</a>
*/
type DcmpVariableLengthInteger struct {
First uint8
More int32
_io *kaitai.Stream
_root *DcmpVariableLengthInteger
_parent interface{}
_f_value bool
value int
}
func NewDcmpVariableLengthInteger() *DcmpVariableLengthInteger {
return &DcmpVariableLengthInteger{
}
}
func (this *DcmpVariableLengthInteger) Read(io *kaitai.Stream, parent interface{}, root *DcmpVariableLengthInteger) (err error) {
this._io = io
this._parent = parent
this._root = root
tmp1, err := this._io.ReadU1()
if err != nil {
return err
}
this.First = tmp1
if (this.First >= 128) {
switch (this.First) {
case 255:
tmp2, err := this._io.ReadS4be()
if err != nil {
return err
}
this.More = int32(tmp2)
default:
tmp3, err := this._io.ReadU1()
if err != nil {
return err
}
this.More = int32(tmp3)
}
}
return err
}
/**
* The decoded value of the variable-length integer.
*/
func (this *DcmpVariableLengthInteger) Value() (v int, err error) {
if (this._f_value) {
return this.value, nil
}
var tmp4 int32;
if (this.First == 255) {
tmp4 = this.More
} else {
var tmp5 int;
if (this.First >= 128) {
tmp5 = (((this.First << 8) | this.More) - 49152)
} else {
tmp5 = this.First
}
tmp4 = tmp5
}
this.value = int(tmp4)
this._f_value = true
return this.value, nil
}
/**
* The first byte of the variable-length integer.
* This determines which storage format is used.
*
* * For the 1-byte format,
* this encodes the entire value of the value.
* * For the 2-byte format,
* this encodes the high 7 bits of the value,
* minus `0xc0`.
* The highest bit of the value,
* i. e. the second-highest bit of this field,
* is the sign bit.
* * For the 5-byte format,
* this is always `0xff`.
*/
/**
* The remaining bytes of the variable-length integer.
*
* * For the 1-byte format,
* this is not present.
* * For the 2-byte format,
* this encodes the low 8 bits of the value.
* * For the 5-byte format,
* this encodes the entire value.
*/ | dcmp_variable_length_integer/src/go/dcmp_variable_length_integer.go | 0.770206 | 0.489809 | dcmp_variable_length_integer.go | starcoder |
package pikselkapcio
//getPaddedCharacterMap returns set of integers representing 7 rows of pixels of a given character, where first and last rows are empty ("padding")
func getPaddedCharacterMap(character rune) [7]int8 {
return padCharacterMap(getCharacterMap(character))
}
//gadCharacterMap inserts zeros as first and last elements of character map ("vertical padding" for a character - empty first and last lines)
func padCharacterMap(characterMap [5]int8) [7]int8 {
var result [7]int8
copy(result[1:], characterMap[0:5])
return result
}
//getCharacterMap returns set of 5 integers representing 5 rows of pixels of a given character
//each given decimal number in binary notation represents which pixels should be "on" in given graphical representation of a character
//example for 'A':
//decimal numbers 14, 17, 31, 17, 17 translate to binary:
// 1110
// 10001
// 11111
// 10001
// 10001
//graphically representing capital letter 'A' with bits that are set
func getCharacterMap(character rune) [5]int8 {
switch character {
case 'A':
return [5]int8{14, 17, 31, 17, 17}
case 'B':
return [5]int8{30, 17, 30, 17, 30}
case 'C':
return [5]int8{15, 16, 16, 16, 15}
case 'D':
return [5]int8{30, 17, 17, 17, 30}
case 'E':
return [5]int8{31, 16, 28, 16, 31}
case 'F':
return [5]int8{31, 16, 28, 16, 16}
case 'G':
return [5]int8{15, 16, 19, 17, 15}
case 'H':
return [5]int8{17, 17, 31, 17, 17}
case 'I':
return [5]int8{4, 4, 4, 4, 4}
case 'J':
return [5]int8{1, 1, 1, 17, 14}
case 'K':
return [5]int8{17, 17, 30, 17, 17}
case 'L':
return [5]int8{16, 16, 16, 16, 31}
case 'M':
return [5]int8{10, 21, 21, 21, 21}
case 'N':
return [5]int8{17, 25, 21, 19, 17}
case 'O':
return [5]int8{14, 17, 17, 17, 14}
case 'P':
return [5]int8{30, 17, 30, 16, 16}
case 'Q':
return [5]int8{14, 17, 21, 19, 14}
case 'R':
return [5]int8{30, 17, 30, 17, 17}
case 'S':
return [5]int8{15, 16, 14, 1, 30}
case 'T':
return [5]int8{31, 4, 4, 4, 4}
case 'U':
return [5]int8{17, 17, 17, 17, 14}
case 'V':
return [5]int8{17, 17, 10, 10, 4}
case 'W':
return [5]int8{21, 21, 21, 21, 10}
case 'X':
return [5]int8{17, 10, 4, 10, 17}
case 'Y':
return [5]int8{17, 10, 4, 4, 4}
case 'Z':
return [5]int8{31, 2, 4, 8, 31}
case '0':
return [5]int8{14, 19, 21, 25, 14}
case '1':
return [5]int8{4, 12, 4, 4, 14}
case '2':
return [5]int8{14, 17, 6, 8, 31}
case '3':
return [5]int8{14, 1, 6, 1, 14}
case '4':
return [5]int8{17, 17, 31, 1, 1}
case '5':
return [5]int8{31, 16, 30, 1, 30}
case '6':
return [5]int8{14, 16, 30, 17, 14}
case '7':
return [5]int8{31, 1, 2, 4, 8}
case '8':
return [5]int8{14, 17, 14, 17, 14}
case '9':
return [5]int8{14, 17, 15, 1, 14}
case '.':
return [5]int8{0, 0, 0, 0, 4}
case '+':
return [5]int8{4, 4, 31, 4, 4}
case '-':
return [5]int8{0, 0, 31, 0, 0}
case '/':
return [5]int8{1, 2, 4, 8, 16}
case '=':
return [5]int8{0, 31, 0, 31, 0}
case '?':
return [5]int8{14, 17, 6, 0, 4}
case '(':
return [5]int8{2, 4, 4, 4, 2}
case ')':
return [5]int8{8, 4, 4, 4, 8}
case ' ':
return [5]int8{0, 0, 0, 0, 0}
//map for '*' character
default:
return [5]int8{21, 14, 4, 14, 21}
}
} | character_map.go | 0.699768 | 0.530054 | character_map.go | starcoder |
package geom
func minf(x, y float64) float64 {
if x < y {
return x
}
return y
}
func maxf(x, y float64) float64 {
if x > y {
return x
}
return y
}
type Coordf struct {
X, Y float64
}
type Rectanglef struct {
Min, Max Coordf
}
func Addf(lhs, rhs Coordf) Coordf {
return Coordf{lhs.X + rhs.X, lhs.Y + rhs.Y}
}
func (c *Coordf) Add(rhs Coordf) {
c.X += rhs.X
c.Y += rhs.Y
}
func Subf(lhs, rhs Coordf) Coordf {
return Coordf{lhs.X - rhs.X, lhs.Y - rhs.Y}
}
func (c *Coordf) Sub(rhs Coordf) {
c.X -= rhs.X
c.Y -= rhs.Y
}
func (r *Rectanglef) Normalise() {
if r.Min.X > r.Max.X {
r.Min.X, r.Max.X = r.Max.X, r.Min.X
}
if r.Min.Y > r.Max.Y {
r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y
}
}
func Normalisef(r Rectanglef) Rectanglef {
r.Normalise()
return r
}
func (r *Rectanglef) Width() float64 {
return r.Max.X - r.Min.X
}
func (r *Rectanglef) Height() float64 {
return r.Max.Y - r.Min.Y
}
func (r *Rectanglef) Size() Coordf {
return Coordf{r.Width(), r.Height()}
}
func (r *Rectanglef) IsEmpty() bool {
return (r.Min.X == r.Max.X) || (r.Min.Y == r.Max.Y)
}
func (r *Rectanglef) IsNormal() bool {
return (r.Min.X <= r.Max.X) && (r.Min.Y <= r.Max.Y)
}
func (r *Rectanglef) Expand(c Coordf) {
r.Min.Sub(c)
r.Max.Add(c)
}
func Expandf(r Rectanglef, c Coordf) Rectanglef {
r.Expand(c)
return r
}
func (r *Rectanglef) Translate(c Coordf) {
r.Min.Add(c)
r.Max.Add(c)
}
func Translatef(r Rectanglef, c Coordf) Rectanglef {
r.Translate(c)
return r
}
func PointInRectanglef(r Rectanglef, p Coordf) bool {
return (r.Min.X <= p.X) && (r.Min.Y <= p.Y) && (p.X < r.Max.X) && (p.Y < r.Max.Y)
}
func RectanglefIntersection(r1, r2 Rectanglef) (intersect Rectanglef, ok bool) {
intersect = Rectanglef{
Min: Coordf{maxf(r1.Min.X, r2.Min.X), maxf(r1.Min.Y, r2.Min.Y)},
Max: Coordf{minf(r1.Max.X, r2.Max.X), minf(r1.Max.Y, r2.Max.Y)},
}
ok = intersect.IsNormal()
return
}
func RectanglefUnion(r1, r2 Rectanglef) Rectanglef {
return Rectanglef{
Min: Coordf{minf(r1.Min.X, r2.Min.X), minf(r1.Min.Y, r2.Min.Y)},
Max: Coordf{maxf(r1.Max.X, r2.Max.X), maxf(r1.Max.Y, r2.Max.Y)},
}
}
func RectanglefContains(rOuter, rInner Rectanglef) bool {
return PointInRectanglef(rOuter, rInner.Min) && PointInRectanglef(rOuter, rInner.Max)
}
func RectanglefFromPosSize(pos, size Coordf) Rectanglef {
return Rectanglef{pos, Addf(pos, size)}
}
func RectanglefFromSize(size Coordf) Rectanglef {
return Rectanglef{Max: size}
} | geom/geomf.go | 0.888596 | 0.559892 | geomf.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// Planner provides operations to manage the planner singleton.
type Planner struct {
Entity
// Read-only. Nullable. Returns a collection of the specified buckets
buckets []PlannerBucketable
// Read-only. Nullable. Returns a collection of the specified plans
plans []PlannerPlanable
// Read-only. Nullable. Returns a collection of the specified tasks
tasks []PlannerTaskable
}
// NewPlanner instantiates a new planner and sets the default values.
func NewPlanner()(*Planner) {
m := &Planner{
Entity: *NewEntity(),
}
return m
}
// CreatePlannerFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreatePlannerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewPlanner(), nil
}
// GetBuckets gets the buckets property value. Read-only. Nullable. Returns a collection of the specified buckets
func (m *Planner) GetBuckets()([]PlannerBucketable) {
if m == nil {
return nil
} else {
return m.buckets
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *Planner) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["buckets"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreatePlannerBucketFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]PlannerBucketable, len(val))
for i, v := range val {
res[i] = v.(PlannerBucketable)
}
m.SetBuckets(res)
}
return nil
}
res["plans"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreatePlannerPlanFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]PlannerPlanable, len(val))
for i, v := range val {
res[i] = v.(PlannerPlanable)
}
m.SetPlans(res)
}
return nil
}
res["tasks"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreatePlannerTaskFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]PlannerTaskable, len(val))
for i, v := range val {
res[i] = v.(PlannerTaskable)
}
m.SetTasks(res)
}
return nil
}
return res
}
// GetPlans gets the plans property value. Read-only. Nullable. Returns a collection of the specified plans
func (m *Planner) GetPlans()([]PlannerPlanable) {
if m == nil {
return nil
} else {
return m.plans
}
}
// GetTasks gets the tasks property value. Read-only. Nullable. Returns a collection of the specified tasks
func (m *Planner) GetTasks()([]PlannerTaskable) {
if m == nil {
return nil
} else {
return m.tasks
}
}
// Serialize serializes information the current object
func (m *Planner) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
if m.GetBuckets() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBuckets()))
for i, v := range m.GetBuckets() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("buckets", cast)
if err != nil {
return err
}
}
if m.GetPlans() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetPlans()))
for i, v := range m.GetPlans() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("plans", cast)
if err != nil {
return err
}
}
if m.GetTasks() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetTasks()))
for i, v := range m.GetTasks() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("tasks", cast)
if err != nil {
return err
}
}
return nil
}
// SetBuckets sets the buckets property value. Read-only. Nullable. Returns a collection of the specified buckets
func (m *Planner) SetBuckets(value []PlannerBucketable)() {
if m != nil {
m.buckets = value
}
}
// SetPlans sets the plans property value. Read-only. Nullable. Returns a collection of the specified plans
func (m *Planner) SetPlans(value []PlannerPlanable)() {
if m != nil {
m.plans = value
}
}
// SetTasks sets the tasks property value. Read-only. Nullable. Returns a collection of the specified tasks
func (m *Planner) SetTasks(value []PlannerTaskable)() {
if m != nil {
m.tasks = value
}
} | models/planner.go | 0.708515 | 0.406302 | planner.go | starcoder |
package bloom
import (
"math"
)
type (
// Bloom is the standard bloom filter.
Bloom interface {
Add([]byte)
AddString(string)
Exist([]byte) bool
ExistString(string) bool
FalsePositive() float64
GuessFalsePositive(uint64) float64
M() uint64
K() uint64
N() uint64
Clear()
}
// CountingBloom is the bloom filter which allows deletion of entries.
// Take note that an 16-bit counter is maintained for each entry.
CountingBloom interface {
Bloom
Remove([]byte)
RemoveString(string)
}
bloomFilter struct {
bitmap []uint16 // bloom filter counter
k uint64 // number of hash functions
n uint64 // number of elements in the bloom filter
m uint64 // size of the bloom filter bits
shift uint8 // the shift to get high/low bit fragments
}
)
const (
ln2 float64 = 0.6931471805599453 // math.Log(2)
maxCountingBloomSize uint64 = 1 << 37 // to avoid panic: makeslice: len out of range
maxCounter uint16 = 65535
)
// New creates counting bloom filter based on the provided m/k.
// m is the size of bloom filter bits.
// k is the number of hash functions.
func New(m, k uint64) CountingBloom {
mm, exponent := adjustM(m)
return &bloomFilter{
bitmap: make([]uint16, mm),
m: mm - 1, // x % 2^i = x & (2^i - 1)
k: k,
shift: 64 - exponent,
}
}
// NewGuess estimates m/k based on the provided n/p then creates counting bloom filter.
// n is the estimated number of elements in the bloom filter.
// p is the false positive probability.
func NewGuess(n uint64, p float64) CountingBloom {
m, k := Guess(n, p)
return New(m, k)
}
// Guess estimates m/k based on the provided n/p.
func Guess(n uint64, p float64) (m, k uint64) {
mm := math.Ceil(-1 * float64(n) * math.Log(p) / math.Pow(ln2, 2))
kk := math.Ceil(ln2 * mm / float64(n))
m, k = uint64(mm), uint64(kk)
return
}
func (bf *bloomFilter) Add(entry []byte) {
hash := sipHash(entry)
h := hash >> bf.shift
l := hash << bf.shift >> bf.shift
var idx uint64
for i := uint64(0); i < bf.k; i++ {
idx = (h + i*l) & bf.m
// avoid overflow
if bf.bitmap[idx] < maxCounter {
bf.bitmap[idx]++
}
}
bf.n++
}
func (bf *bloomFilter) AddString(entry string) {
bf.Add([]byte(entry))
}
func (bf *bloomFilter) Remove(entry []byte) {
hash := sipHash(entry)
h := hash >> bf.shift
l := hash << bf.shift >> bf.shift
var idx uint64
for i := uint64(0); i < bf.k; i++ {
idx = (h + i*l) & bf.m
if bf.bitmap[idx] == 0 {
return
}
}
for i := uint64(0); i < bf.k; i++ {
idx = (h + i*l) & bf.m
// avoid overflow
if bf.bitmap[idx] > 0 {
bf.bitmap[idx]--
}
}
bf.n--
}
func (bf *bloomFilter) RemoveString(entry string) {
bf.Remove([]byte(entry))
}
func (bf *bloomFilter) Exist(entry []byte) bool {
hash := sipHash(entry)
h := hash >> bf.shift
l := hash << bf.shift >> bf.shift
var idx uint64
for i := uint64(0); i < bf.k; i++ {
idx = (h + i*l) & bf.m
if bf.bitmap[idx] == 0 {
return false
}
}
return true
}
func (bf *bloomFilter) ExistString(entry string) bool {
return bf.Exist([]byte(entry))
}
func (bf *bloomFilter) FalsePositive() float64 {
return math.Pow((1 - math.Exp(-float64(bf.k*bf.n)/float64(bf.m))),
float64(bf.k))
}
func (bf *bloomFilter) GuessFalsePositive(n uint64) float64 {
return math.Pow((1 - math.Exp(-float64(bf.k*n)/float64(bf.m))),
float64(bf.k))
}
func (bf *bloomFilter) M() uint64 {
return bf.m + 1
}
func (bf *bloomFilter) K() uint64 {
return bf.k
}
func (bf *bloomFilter) N() uint64 {
return bf.n
}
func (bf *bloomFilter) Clear() {
for i := range bf.bitmap {
bf.bitmap[i] = 0
}
bf.n = 0
}
func adjustM(x uint64) (m uint64, exponent uint8) {
if x < 512 {
x = 512
}
m = uint64(1)
for m < x && m < maxCountingBloomSize {
m <<= 1
exponent++
}
return m, exponent
} | pkg/bloom/bloom.go | 0.673084 | 0.576959 | bloom.go | starcoder |
package cp
import "fmt"
type Shaper interface {
Body() *Body
MassInfo() *ShapeMassInfo
HashId() HashValue
SetHashId(HashValue)
SetSpace(*Space)
BB() BB
SetBB(BB)
}
type ShapeClass interface {
CacheData(transform Transform) BB
Destroy()
PointQuery(p Vector, info *PointQueryInfo)
SegmentQuery(a, b Vector, radius float64, info *SegmentQueryInfo)
}
const (
SHAPE_TYPE_NUM = 3
)
type Shape struct {
Class ShapeClass
space *Space
body *Body
massInfo *ShapeMassInfo
bb BB
sensor bool
e, u float64
surfaceV Vector
UserData interface{}
collisionType CollisionType
Filter ShapeFilter
hashid HashValue
}
func (s Shape) String() string {
return fmt.Sprintf("%T", s.Class)
}
func (s *Shape) Order() int {
switch s.Class.(type) {
case *Circle:
return 0
case *Segment:
return 1
case *PolyShape:
return 2
default:
return 3
}
}
func (s *Shape) Sensor() bool {
return s.sensor
}
func (s *Shape) SetSensor(sensor bool) {
s.body.Activate()
s.sensor = sensor
}
func (s *Shape) Space() *Space {
return s.space
}
func (s *Shape) Body() *Body {
return s.body
}
func (s *Shape) MassInfo() *ShapeMassInfo {
return s.massInfo
}
func (s *Shape) HashId() HashValue {
return s.hashid
}
func (s *Shape) SetHashId(hashid HashValue) {
s.hashid = hashid
}
func (s *Shape) SetSpace(space *Space) {
s.space = space
}
func (s *Shape) BB() BB {
return s.bb
}
func (s *Shape) SetBB(bb BB) {
s.bb = bb
}
func (s *Shape) SetCollisionType(collisionType CollisionType) {
s.body.Activate()
s.collisionType = collisionType
}
func (s *Shape) Friction() float64 {
return s.u
}
func (s *Shape) SetFriction(u float64) {
assert(s.u >= 0, "Must be positive")
s.body.Activate()
s.u = u
}
func (s *Shape) SetSurfaceV(surfaceV Vector) {
s.surfaceV = surfaceV
}
func (s *Shape) Elasticity() float64 {
return s.e
}
func (s *Shape) SetElasticity(e float64) {
assert(s.e >= 0, "Must be positive")
s.body.Activate()
s.e = e
}
func (s *Shape) SetFilter(filter ShapeFilter) {
s.body.Activate()
s.Filter = filter
}
func (s *Shape) CacheBB() BB {
return s.Update(s.body.transform)
}
func (s *Shape) Update(transform Transform) BB {
s.bb = s.Class.CacheData(transform)
return s.bb
}
func (s *Shape) Point(i uint32) SupportPoint {
switch s.Class.(type) {
case *Circle:
return NewSupportPoint(s.Class.(*Circle).tc, 0)
case *Segment:
seg := s.Class.(*Segment)
if i == 0 {
return NewSupportPoint(seg.ta, i)
}
return NewSupportPoint(seg.tb, i)
case *PolyShape:
poly := s.Class.(*PolyShape)
// Poly shapes may change vertex count.
var index int
if i < uint32(poly.count) {
index = int(i)
}
return NewSupportPoint(poly.planes[index].v0, uint32(index))
default:
return NewSupportPoint(Vector{}, 0)
}
}
func (s *Shape) PointQuery(p Vector) PointQueryInfo {
info := PointQueryInfo{nil, Vector{}, INFINITY, Vector{}}
s.Class.PointQuery(p, &info)
return info
}
func (shape *Shape) SegmentQuery(a, b Vector, radius float64, info *SegmentQueryInfo) bool {
blank := SegmentQueryInfo{nil, b, Vector{}, 1}
if info != nil {
*info = blank
} else {
info = &blank
}
var nearest PointQueryInfo
shape.Class.PointQuery(a, &nearest)
if nearest.Distance <= radius {
info.Shape = shape
info.Alpha = 0
info.Normal = a.Sub(nearest.Point).Normalize()
} else {
shape.Class.SegmentQuery(a, b, radius, info)
}
return info.Shape != nil
}
func NewShape(class ShapeClass, body *Body, massInfo *ShapeMassInfo) *Shape {
return &Shape{
Class: class,
body: body,
massInfo: massInfo,
surfaceV: Vector{},
Filter: ShapeFilter{
Group: NO_GROUP,
Categories: ALL_CATEGORIES,
Mask: ALL_CATEGORIES,
},
}
} | shape.go | 0.716715 | 0.401834 | shape.go | starcoder |
package bigint
import (
"math/big"
"math/rand"
"strings"
)
// Zero returns 0.
func Zero() *big.Int {
return big.NewInt(0)
}
// One returns 1.
func One() *big.Int {
return big.NewInt(1)
}
// Hex constructs an integer from a hex string, returning the integer and a
// boolean indicating success. Underscore may be used as a separator.
func Hex(s string) (*big.Int, bool) {
return new(big.Int).SetString(stripliteral(s), 16)
}
// MustHex constructs an integer from a hex string. It panics on error.
func MustHex(s string) *big.Int {
x, ok := Hex(s)
if !ok {
panic("failed to parse hex integer")
}
return x
}
// Binary parses a binary string into an integer, returning the integer and a
// boolean indicating success. Underscore may be used as a separator.
func Binary(s string) (*big.Int, bool) {
return new(big.Int).SetString(stripliteral(s), 2)
}
// MustBinary constructs an integer from a binary string. It panics on error.
func MustBinary(s string) *big.Int {
x, ok := Binary(s)
if !ok {
panic("failed to parse binary integer")
}
return x
}
// stripliteral removes underscore spacers from a numeric literal.
func stripliteral(s string) string {
return strings.ReplaceAll(s, "_", "")
}
// Equal returns whether x equals y.
func Equal(x, y *big.Int) bool {
return x.Cmp(y) == 0
}
// EqualInt64 is a convenience for checking if x equals the int64 value y.
func EqualInt64(x *big.Int, y int64) bool {
return Equal(x, big.NewInt(y))
}
// IsZero returns true if x is zero.
func IsZero(x *big.Int) bool {
return x.Sign() == 0
}
// IsNonZero returns true if x is non-zero.
func IsNonZero(x *big.Int) bool {
return !IsZero(x)
}
// Clone returns a copy of x.
func Clone(x *big.Int) *big.Int {
return new(big.Int).Set(x)
}
// Pow2 returns 2ᵉ.
func Pow2(e uint) *big.Int {
return new(big.Int).Lsh(One(), e)
}
// IsPow2 returns whether x is a power of 2.
func IsPow2(x *big.Int) bool {
e := x.BitLen()
if e == 0 {
return false
}
return Equal(x, Pow2(uint(e-1)))
}
// Pow2UpTo returns all powers of two ⩽ x.
func Pow2UpTo(x *big.Int) []*big.Int {
p := One()
ps := []*big.Int{}
for p.Cmp(x) <= 0 {
ps = append(ps, Clone(p))
p.Lsh(p, 1)
}
return ps
}
// Mask returns the integer with 1s in positions [l,h).
func Mask(l, h uint) *big.Int {
mask := Pow2(h)
return mask.Sub(mask, Pow2(l))
}
// Ones returns 2ⁿ - 1, the integer with n 1s in the low bits.
func Ones(n uint) *big.Int {
return Mask(0, n)
}
// BitsSet returns the positions of set bits in x.
func BitsSet(x *big.Int) []int {
set := []int{}
for i := 0; i < x.BitLen(); i++ {
if x.Bit(i) == 1 {
set = append(set, i)
}
}
return set
}
// MinMax returns the minimum and maximum of x and y.
func MinMax(x, y *big.Int) (min, max *big.Int) {
if x.Cmp(y) < 0 {
return x, y
}
return y, x
}
// Extract bits [l,h) and shift them to the low bits.
func Extract(x *big.Int, l, h uint) *big.Int {
e := Mask(l, h)
e.And(e, x)
return e.Rsh(e, l)
}
// RandBits returns a random integer less than 2ⁿ.
func RandBits(r *rand.Rand, n uint) *big.Int {
max := Pow2(n)
return new(big.Int).Rand(r, max)
}
// Uint64s represents x in 64-bit limbs.
func Uint64s(x *big.Int) []uint64 {
z := Clone(x)
mask := Ones(64)
word := new(big.Int)
words := []uint64{}
for IsNonZero(z) {
word.And(z, mask)
words = append(words, word.Uint64())
z.Rsh(z, 64)
}
return words
}
// BytesLittleEndian returns the absolute value of x as a little-endian byte slice.
func BytesLittleEndian(x *big.Int) []byte {
b := x.Bytes()
for l, r := 0, len(b)-1; l < r; l, r = l+1, r-1 {
b[l], b[r] = b[r], b[l]
}
return b
} | vendor/github.com/mmcloughlin/addchain/internal/bigint/bigint.go | 0.874037 | 0.536313 | bigint.go | starcoder |
package terminal
import (
"github.com/cimomo/portfolio-go/pkg/portfolio"
"github.com/gdamore/tcell"
"github.com/rivo/tview"
)
// ReturnViewer displays the trailing returns of a portfolio
type ReturnViewer struct {
performance *portfolio.Performance
table *tview.Table
}
// NewReturnViewer returns a new viewer for the trailing returns of a portfolio
func NewReturnViewer(performance *portfolio.Performance) *ReturnViewer {
return &ReturnViewer{
performance: performance,
table: tview.NewTable().SetBorders(true),
}
}
// Reload updates the performance data object
func (viewer *ReturnViewer) Reload(performance *portfolio.Performance) {
viewer.performance = performance
}
// Draw calculates the portfolio performance and refreshes the viewer
func (viewer *ReturnViewer) Draw() {
viewer.table.Clear()
viewer.drawHeader()
viewer.drawPerformance()
}
func (viewer *ReturnViewer) drawHeader() {
var cell *tview.TableCell
header := []string{
"Portfolio", "1-Month", "3-Month", "6-Month", "YTD",
"1-Year", "3-Year", "5-Year", "10-Year", "Max",
}
for c := 0; c < len(header); c++ {
cell = tview.NewTableCell(header[c]).SetTextColor(tcell.ColorYellow).SetAttributes(tcell.AttrBold).SetExpansion(1)
if c < 1 {
cell.SetAlign(tview.AlignLeft)
} else {
cell.SetAlign((tview.AlignRight))
}
viewer.table.SetCell(0, c, cell)
}
}
func (viewer *ReturnViewer) drawPerformance() {
if !viewer.performance.Ready {
setString(viewer.table, "Computing ...", 1, 0, tcell.ColorWhite, tview.AlignLeft)
setString(viewer.table, "Computing ...", 2, 0, tcell.ColorWhite, tview.AlignLeft)
return
}
setString(viewer.table, viewer.performance.Portfolio.Name, 1, 0, tcell.ColorWhite, tview.AlignLeft)
setPercentChange(viewer.table, viewer.performance.Result.Return.OneMonth, 1, 1)
setPercentChange(viewer.table, viewer.performance.Result.Return.ThreeMonth, 1, 2)
setPercentChange(viewer.table, viewer.performance.Result.Return.SixMonth, 1, 3)
setPercentChange(viewer.table, viewer.performance.Result.Return.YTD, 1, 4)
setPercentChange(viewer.table, viewer.performance.Result.Return.OneYear, 1, 5)
setPercentChange(viewer.table, viewer.performance.Result.Return.ThreeYear, 1, 6)
setPercentChange(viewer.table, viewer.performance.Result.Return.FiveYear, 1, 7)
setPercentChange(viewer.table, viewer.performance.Result.Return.TenYear, 1, 8)
setPercentChange(viewer.table, viewer.performance.Result.Return.Max, 1, 9)
setString(viewer.table, viewer.performance.Benchmark.Portfolio.Name, 2, 0, tcell.ColorWhite, tview.AlignLeft)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.OneMonth, 2, 1)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.ThreeMonth, 2, 2)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.SixMonth, 2, 3)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.YTD, 2, 4)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.OneYear, 2, 5)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.ThreeYear, 2, 6)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.FiveYear, 2, 7)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.TenYear, 2, 8)
setPercentChange(viewer.table, viewer.performance.Benchmark.Return.Max, 2, 9)
} | pkg/terminal/return.go | 0.742795 | 0.407098 | return.go | starcoder |
package assertions
import (
"fmt"
"testing"
"github.com/buildpacks/pack/acceptance/managers"
h "github.com/buildpacks/pack/testhelpers"
)
type ImageAssertionManager struct {
testObject *testing.T
assert h.AssertionManager
imageManager managers.ImageManager
registry *h.TestRegistryConfig
}
func NewImageAssertionManager(t *testing.T, imageManager managers.ImageManager, registry *h.TestRegistryConfig) ImageAssertionManager {
return ImageAssertionManager{
testObject: t,
assert: h.NewAssertionManager(t),
imageManager: imageManager,
registry: registry,
}
}
func (a ImageAssertionManager) ExistsLocally(name string) {
a.testObject.Helper()
_, err := a.imageManager.InspectLocal(name)
a.assert.Nil(err)
}
func (a ImageAssertionManager) NotExistsLocally(name string) {
a.testObject.Helper()
_, err := a.imageManager.InspectLocal(name)
a.assert.ErrorContains(err, "No such image")
}
func (a ImageAssertionManager) HasBaseImage(image, base string) {
a.testObject.Helper()
imageInspect, err := a.imageManager.InspectLocal(image)
a.assert.Nil(err)
baseInspect, err := a.imageManager.InspectLocal(base)
a.assert.Nil(err)
for i, layer := range baseInspect.RootFS.Layers {
a.assert.Equal(imageInspect.RootFS.Layers[i], layer)
}
}
func (a ImageAssertionManager) HasLabelWithData(image, label, data string) {
a.testObject.Helper()
inspect, err := a.imageManager.InspectLocal(image)
a.assert.Nil(err)
label, ok := inspect.Config.Labels[label]
a.assert.TrueWithMessage(ok, fmt.Sprintf("expected label %s to exist", label))
a.assert.Contains(label, data)
}
func (a ImageAssertionManager) RunsWithOutput(image string, expectedOutputs ...string) {
a.testObject.Helper()
containerName := "test-" + h.RandString(10)
container := a.imageManager.ExposePortOnImage(image, containerName)
defer container.Cleanup()
output := container.WaitForResponse(managers.DefaultDuration)
a.assert.ContainsAll(output, expectedOutputs...)
}
func (a ImageAssertionManager) RunsWithLogs(image string, expectedOutputs ...string) {
a.testObject.Helper()
container := a.imageManager.CreateContainer(image)
defer container.Cleanup()
output := container.RunWithOutput()
a.assert.ContainsAll(output, expectedOutputs...)
}
func (a ImageAssertionManager) CanBePulledFromRegistry(name string) {
a.testObject.Helper()
a.imageManager.PullImage(name, a.registry.RegistryAuth())
a.ExistsLocally(name)
}
func (a ImageAssertionManager) ExistsInRegistryCatalog(name string) {
a.testObject.Helper()
contents, err := a.registry.RegistryCatalog()
a.assert.Nil(err)
a.assert.ContainsWithMessage(contents, name, fmt.Sprintf("Expected to see image %s in %%s", name))
}
func (a ImageAssertionManager) NotExistsInRegistry(name string) {
a.testObject.Helper()
contents, err := a.registry.RegistryCatalog()
a.assert.Nil(err)
a.assert.NotContainWithMessage(
contents,
name,
"Didn't expect to see image %s in the registry",
)
}
func (a ImageAssertionManager) DoesNotHaveDuplicateLayers(name string) {
a.testObject.Helper()
out, err := a.imageManager.InspectLocal(name)
a.assert.Nil(err)
layerSet := map[string]interface{}{}
for _, layer := range out.RootFS.Layers {
_, ok := layerSet[layer]
if ok {
a.testObject.Fatalf("duplicate layer found in builder %s", layer)
}
layerSet[layer] = true
}
} | acceptance/assertions/image.go | 0.622345 | 0.50415 | image.go | starcoder |
package engine
import (
"time"
)
// TakeOff will start the blades and raise the drone to a normal flying height.
func (e *Engine) TakeOff() {
debug("Take off")
e.ResetMovement()
check(e.drone.TakeOff())
time.Sleep(5000 * time.Millisecond)
}
// Land will lower the drone to the ground and stop the blades.
func (e *Engine) Land() {
debug("Land")
e.ResetMovement()
check(e.drone.Land())
time.Sleep(5000 * time.Millisecond)
}
// Forward will move the drone forward at the given speed.
func (e *Engine) Forward(speed int) {
debug("Forward, speed: %v", speed)
check(e.drone.Forward(speed))
}
// Backward will move the drone backward at the given speed.
func (e *Engine) Backward(speed int) {
debug("Backward, speed: %v", speed)
check(e.drone.Backward(speed))
}
// Left will move the drone left at the given speed.
func (e *Engine) Left(speed int) {
debug("Left, speed: %v", speed)
check(e.drone.Left(speed))
}
// Right will move the drone right at the given speed.
func (e *Engine) Right(speed int) {
debug("Right, speed: %v", speed)
check(e.drone.Right(speed))
}
// Up will move the drone up at the given speed.
func (e *Engine) Up(speed int) {
debug("Up, speed: %v", speed)
check(e.drone.Up(speed))
}
// Down will move the drone down at the given speed.
func (e *Engine) Down(speed int) {
debug("Down, speed: %v", speed)
check(e.drone.Down(speed))
}
// RotateLeft will rotate the drone left at the given speed.
func (e *Engine) RotateLeft(speed int) {
debug("Rotate left, speed: %v", speed)
check(e.drone.CounterClockwise(speed))
}
// RotateRight will rotate the drone right at the given speed.
func (e *Engine) RotateRight(speed int) {
debug("Rotate right, speed: %v", speed)
check(e.drone.Clockwise(speed))
}
// FrontFlip will cause the drone to perform a front flip.
func (e *Engine) FrontFlip() {
debug("Front flip")
check(e.drone.FrontFlip())
time.Sleep(3000 * time.Millisecond)
}
// BackFlip will cause the drone to perform a back flip.
func (e *Engine) BackFlip() {
debug("Back flip")
check(e.drone.BackFlip())
time.Sleep(3000 * time.Millisecond)
}
// LeftFlip will cause the drone to perform a left flip.
func (e *Engine) LeftFlip() {
debug("Left flip")
check(e.drone.LeftFlip())
time.Sleep(3000 * time.Millisecond)
}
// RightFlip will cause the drone to perform a right flip.
func (e *Engine) RightFlip() {
debug("Right flip")
check(e.drone.RightFlip())
time.Sleep(3000 * time.Millisecond)
}
// Bounce will toggle "bouncing" the drone up and down.
func (e *Engine) Bounce() {
debug("Toggle bounce")
check(e.drone.Bounce())
}
// ResetMovement will set all drone movement to 0.
func (e *Engine) ResetMovement() {
debug("Reset movement")
check(e.drone.Forward(0))
check(e.drone.Up(0))
check(e.drone.Right(0))
check(e.drone.Clockwise(0))
} | engine/movement.go | 0.653459 | 0.53358 | movement.go | starcoder |
package core
import (
"encoding/hex"
"fmt"
// "log"
"reflect"
//"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/hpb-project/HCash-SDK/core/ebigint"
solsha3 "github.com/miguelmota/go-solidity-sha3"
"math/big"
)
type GeneratorParams struct {
g Point
h Point
gs *GeneratorVector
hs *GeneratorVector
}
func NewGeneratorParams(hi interface{}, gs, hs *GeneratorVector) *GeneratorParams {
gp := &GeneratorParams{}
hash := solsha3.SoliditySHA3(solsha3.String("G"))
gp.g = MapInto(hex.EncodeToString(hash))
h_types := reflect.TypeOf(hi).String()
if h_types == "int" {
gsInnards := make([]Point, 0)
hsInnards := make([]Point, 0)
hVal := hi.(int)
for i := 0; i < hVal; i++ {
hash1 := solsha3.SoliditySHA3(solsha3.String("G"), solsha3.Int256(i))
p1 := MapInto(hex.EncodeToString(hash1))
gsInnards = append(gsInnards, p1)
hash2 := solsha3.SoliditySHA3(
solsha3.String("H"), solsha3.Int256(i))
p2 := MapInto(hex.EncodeToString(hash2))
hsInnards = append(hsInnards, p2)
}
gp.h = MapInto(hex.EncodeToString(solsha3.SoliditySHA3(solsha3.String("H"))))
gp.gs = NewGeneratorVector(gsInnards)
gp.hs = NewGeneratorVector(hsInnards)
} else {
gp.h = hi.(Point)
gp.gs = gs
gp.hs = hs
}
return gp
}
func (g GeneratorParams) GetG() Point {
return g.g
}
func (g GeneratorParams) GetH() Point {
return g.h
}
func (g GeneratorParams) GetGS() *GeneratorVector {
return g.gs
}
func (g GeneratorParams) GetHS() *GeneratorVector {
return g.hs
}
func (g *GeneratorParams) Commit(blinding *ebigint.NBigInt, gExp, hExp *FieldVector) Point {
var result = g.h.Mul(blinding)
var gsVector = g.gs.GetVector()
gexpVector := gExp.GetVector()
for i, gexp := range gexpVector {
result = result.Add(gsVector[i].Mul(gexp))
}
if hExp != nil {
var hsVector = g.hs.GetVector()
hexpVector := hExp.GetVector()
for i, hexp := range hexpVector {
result = result.Add(hsVector[i].Mul(hexp))
}
}
return result
}
type FieldVector struct {
vector []*ebigint.NBigInt
}
func NewFieldVector(vector []*ebigint.NBigInt) *FieldVector {
fv := &FieldVector{}
fv.vector = vector
return fv
}
func (f *FieldVector) String() string {
str := "{field:"
for i, e := range f.vector {
t := fmt.Sprintf("%d-%s\n", i, e.Text(16))
str += t
}
str += "}"
return str
}
func (f *FieldVector) GetVector() []*ebigint.NBigInt {
return f.vector
}
func (f *FieldVector) Length() int {
return len(f.vector)
}
func (f *FieldVector) Slice(begin, end int) *FieldVector {
var innards = f.vector[begin:end]
return NewFieldVector(innards)
}
func (f *FieldVector) Add(other *FieldVector) *FieldVector {
var innards = other.GetVector()
var nInnards = make([]*ebigint.NBigInt, len(f.vector))
for i, elem := range f.vector {
nInnards[i] = elem.RedAdd(innards[i])
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Plus(constant *ebigint.NBigInt) *FieldVector {
var nInnards = make([]*ebigint.NBigInt, len(f.vector))
for i, elem := range f.vector {
nInnards[i] = elem.RedAdd(constant)
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Sum() *ebigint.NBigInt {
var nVectors = make([]*ebigint.NBigInt, 0)
for _, c := range f.vector {
nVectors = append(nVectors, c)
}
var accumulator = ebigint.NewNBigInt(0).ToRed(b128.Q())
for _, current := range nVectors {
accumulator = accumulator.RedAdd(current)
}
return accumulator
}
func (f *FieldVector) Negate() *FieldVector {
var nInnards = make([]*ebigint.NBigInt, len(f.vector))
for i, accum := range f.vector {
nInnards[i] = accum.RedNeg()
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Subtract(other *FieldVector) *FieldVector {
return f.Add(other.Negate())
}
func (f *FieldVector) Hadamard(other *FieldVector) *FieldVector {
var innards = other.GetVector()
var nInnards = make([]*ebigint.NBigInt, len(f.vector))
for i, elem := range f.vector {
nInnards[i] = elem.RedMul(innards[i])
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Invert() *FieldVector {
var nInnards = make([]*ebigint.NBigInt, len(f.vector))
for i, elem := range f.vector {
nInnards[i] = elem.RedInvm()
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Extract(parity int) *FieldVector {
var nInnards = make([]*ebigint.NBigInt, 0)
for i, accum := range f.vector {
if i%2 == parity {
nInnards = append(nInnards, accum)
}
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Flip() *FieldVector {
var size = f.Length()
var nInnards = make([]*ebigint.NBigInt, size)
for i, _ := range nInnards {
nInnards[i] = f.vector[(size-i)%size]
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Concat(other *FieldVector) *FieldVector {
var nInnards = make([]*ebigint.NBigInt, 0)
for _, elem := range f.vector {
nInnards = append(nInnards, elem)
}
for _, elem := range other.vector {
nInnards = append(nInnards, elem)
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) Times(constant *ebigint.NBigInt) *FieldVector {
var nInnards = make([]*ebigint.NBigInt, len(f.vector))
for i, elem := range f.vector {
nInnards[i] = elem.RedMul(constant)
}
return NewFieldVector(nInnards)
}
func (f *FieldVector) InnerProduct(other *FieldVector) *ebigint.NBigInt {
var innards = other.GetVector()
var nVectors = make([]*ebigint.NBigInt, 0)
for _, c := range f.vector {
nVectors = append(nVectors, c)
}
var accumulator = ebigint.ToNBigInt(big.NewInt(0)).ToRed(b128.Q())
for i, current := range nVectors {
accumulator = accumulator.RedAdd(current.RedMul(innards[i]))
}
return accumulator
}
type GeneratorVector struct {
vector []Point
}
func NewGeneratorVector(Innards []Point) *GeneratorVector {
gv := &GeneratorVector{}
gv.vector = Innards
return gv
}
func (g *GeneratorVector) GetVector() []Point {
return g.vector
}
func (g *GeneratorVector) Length() int {
return len(g.vector)
}
func (g *GeneratorVector) Slice(begin, end int) *GeneratorVector {
return NewGeneratorVector(g.vector[begin:end])
}
func (g *GeneratorVector) Commit(exponents *FieldVector) Point {
var nVectors = make([]Point, 0)
var innards = exponents.GetVector()
for _, c := range g.vector {
nVectors = append(nVectors, c)
}
var accumulator = b128.Zero()
for i, current := range nVectors {
accumulator = accumulator.Add(current.Mul(innards[i]))
}
return accumulator
}
func (g *GeneratorVector) Sum() Point {
var nVectors = make([]Point, 0)
for _, c := range g.vector {
nVectors = append(nVectors, c)
}
var accumulator = b128.Zero()
for _, current := range nVectors {
accumulator = accumulator.Add(current)
}
return accumulator
}
func (g *GeneratorVector) Add(other *GeneratorVector) *GeneratorVector {
var innards = other.GetVector()
var nInnards = make([]Point, len(g.vector))
for i, elem := range g.vector {
nInnards[i] = elem.Add(innards[i])
}
return NewGeneratorVector(nInnards)
}
func (g *GeneratorVector) Hadamard(exponents *FieldVector) *GeneratorVector {
var innards = exponents.GetVector()
var nInnards = make([]Point, len(g.vector))
for i, elem := range g.vector {
nInnards[i] = elem.Mul(innards[i])
}
return NewGeneratorVector(nInnards)
}
func (g *GeneratorVector) Negate() *GeneratorVector {
var nInnards = make([]Point, len(g.vector))
for i, elem := range g.vector {
nInnards[i] = elem.Neg()
}
return NewGeneratorVector(nInnards)
}
func (g *GeneratorVector) Times(constant *ebigint.NBigInt) *GeneratorVector {
var nInnards = make([]Point, len(g.vector))
for i, elem := range g.vector {
nInnards[i] = elem.Mul(constant)
}
return NewGeneratorVector(nInnards)
}
func (g *GeneratorVector) Extract(parity int) *GeneratorVector {
var nInnards = make([]Point, 0)
for i, elem := range g.vector {
if i%2 == parity {
nInnards = append(nInnards, elem)
}
}
return NewGeneratorVector(nInnards)
}
func (g *GeneratorVector) Concat(other *GeneratorVector) *GeneratorVector {
var nInnards = make([]Point, 0)
for _, elem := range g.vector {
nInnards = append(nInnards, elem)
}
for _, elem := range other.vector {
nInnards = append(nInnards, elem)
}
return NewGeneratorVector(nInnards)
}
func (g *GeneratorVector) String() string {
str := "{vector:"
for i, v := range g.vector {
t := fmt.Sprintf("%d-%s\n", i, v.String())
str += t
}
str += "}"
return str
}
type Convolver struct {
unity *ebigint.NBigInt
}
func NewConvolver() *Convolver {
c := &Convolver{}
unity, _ := big.NewInt(0).SetString("14a3074b02521e3b1ed9852e5028452693e87be4e910500c7ba9bbddb2f46edd", 16)
c.unity = ebigint.ToNBigInt(unity).ToRed(b128.Q())
return c
}
func (c *Convolver) FFT_Scalar(input *FieldVector, inverse bool) *FieldVector {
var length = input.Length()
if length == 1 {
return input
}
if length%2 != 0 {
panic("Input size must be a power of 2!")
}
exp := big.NewInt(1).Lsh(big.NewInt(1), 28)
exp = exp.Div(exp, big.NewInt(int64(length)))
var omega = c.unity.RedExp(exp)
if inverse {
omega = omega.RedInvm()
}
var even = c.FFT_Scalar(input.Extract(0), inverse)
var odd = c.FFT_Scalar(input.Extract(1), inverse)
var omegas = make([]*ebigint.NBigInt, 0)
omegas = append(omegas, ebigint.NewNBigInt(1).ToRed(b128.Q()))
for i := 1; i < length/2; i++ {
omegas = append(omegas, omegas[i-1].RedMul(omega))
}
var n_omegas = NewFieldVector(omegas)
var result = even.Add(odd.Hadamard(n_omegas)).Concat(even.Add(odd.Hadamard(n_omegas).Negate()))
if inverse {
result = result.Times(ebigint.NewNBigInt(2).ToRed(b128.Q()).RedInvm())
}
return result
}
func (c *Convolver) Convolution_Scalar(exponent *FieldVector, base *FieldVector) *FieldVector {
size := base.Length()
temp := c.FFT_Scalar(base, false).Hadamard(c.FFT_Scalar(exponent.Flip(), false))
return c.FFT_Scalar(temp.Slice(0, size/2).Add(temp.Slice(size/2, size)).Times(ebigint.NewNBigInt(2).ToRed(b128.Q()).RedInvm()), true)
}
func (c *Convolver) Convolution_Point(exponent *FieldVector, base *GeneratorVector) *GeneratorVector {
size := base.Length()
temp := c.FFT_Point(base, false).Hadamard(c.FFT_Scalar(exponent.Flip(), false))
return c.FFT_Point(temp.Slice(0, size/2).Add(temp.Slice(size/2, size)).Times(ebigint.NewNBigInt(2).ToRed(b128.Q()).RedInvm()), true)
}
func (c *Convolver) FFT_Point(input *GeneratorVector, inverse bool) *GeneratorVector {
var length = input.Length()
if length == 1 {
return input
}
if length%2 != 0 {
panic("Input size must be a power of 2!")
}
exp := big.NewInt(1).Lsh(big.NewInt(1), 28)
exp = exp.Div(exp, big.NewInt(int64(length)))
var omega = c.unity.RedExp(exp)
if inverse {
omega = omega.RedInvm()
}
var even = c.FFT_Point(input.Extract(0), inverse)
var odd = c.FFT_Point(input.Extract(1), inverse)
var omegas = make([]*ebigint.NBigInt, 0)
omegas = append(omegas, ebigint.NewNBigInt(1).ToRed(b128.Q()))
for i := 1; i < length/2; i++ {
omegas = append(omegas, omegas[i-1].RedMul(omega))
}
var n_omegas = NewFieldVector(omegas)
var result = even.Add(odd.Hadamard(n_omegas)).Concat(even.Add(odd.Hadamard(n_omegas).Negate()))
if inverse {
result = result.Times(ebigint.NewNBigInt(2).ToRed(b128.Q()).RedInvm())
}
return result
}
type FieldVectorPolynomial struct {
//coefficients []*PedersenCommitment
coefficients []*FieldVector
}
func NewFieldVectorPolynomial(coefficients ...*FieldVector) *FieldVectorPolynomial {
fvp := &FieldVectorPolynomial{
coefficients: coefficients,
}
return fvp
}
func (f *FieldVectorPolynomial) GetCoefficients() []*FieldVector {
return f.coefficients
}
func (f *FieldVectorPolynomial) Evaluate(x *ebigint.NBigInt) *FieldVector {
result := f.coefficients[0]
var accumulator = x
for _, coefficient := range f.coefficients[1:] {
result = result.Add(coefficient.Times(accumulator))
accumulator = accumulator.RedMul(x)
}
return result
}
func (f *FieldVectorPolynomial) InnerProduct(other *FieldVectorPolynomial) []*ebigint.NBigInt {
var innards = other.GetCoefficients()
var length = len(f.coefficients) + len(innards) - 1
var result = make([]*ebigint.NBigInt, length)
for i := 0; i < length; i++ {
result[i] = ebigint.NewNBigInt(0).ToRed(b128.Q())
}
for i, mine := range f.coefficients {
for j, their := range innards {
result[i+j] = result[i+j].RedAdd(mine.InnerProduct(their))
}
}
return result
}
type PedersenCommitment struct {
params GeneratorParams
x *ebigint.NBigInt
r *ebigint.NBigInt
}
func NewPedersenCommitment(params GeneratorParams, coefficient *ebigint.NBigInt, b *ebigint.NBigInt) *PedersenCommitment {
pc := &PedersenCommitment{
params: params,
x: coefficient,
r: b,
}
return pc
}
func (pc PedersenCommitment) GetX() *ebigint.NBigInt {
return pc.x
}
func (pc PedersenCommitment) GetR() *ebigint.NBigInt {
return pc.r
}
func (pc PedersenCommitment) Commit() Point {
return pc.params.GetG().Mul(pc.x).Add(pc.params.GetH().Mul(pc.r))
}
func (pc PedersenCommitment) Add(other *PedersenCommitment) *PedersenCommitment {
return NewPedersenCommitment(pc.params, pc.x.RedAdd(other.GetX()), pc.r.RedAdd(other.GetR()))
}
func (pc PedersenCommitment) Times(exponent *ebigint.NBigInt) *PedersenCommitment {
return NewPedersenCommitment(pc.params, pc.x.RedMul(exponent), pc.r.RedMul(exponent))
}
type PolyCommitment struct {
coefficientCommitments []*PedersenCommitment
}
func NewPolyCommitment(params GeneratorParams, coefficients []*ebigint.NBigInt) *PolyCommitment {
pc := &PolyCommitment{}
pc.coefficientCommitments = make([]*PedersenCommitment, 0)
tmp := NewPedersenCommitment(params, coefficients[0], ebigint.NewNBigInt(0).ToRed(b128.Q()))
pc.coefficientCommitments = append(pc.coefficientCommitments, tmp)
for _, coefficient := range coefficients[1:] {
rand := b128.RandomScalar()
npc := NewPedersenCommitment(params, coefficient, rand)
pc.coefficientCommitments = append(pc.coefficientCommitments, npc)
}
return pc
}
func (pc *PolyCommitment) GetCommitments() []Point {
commitments := make([]Point, len(pc.coefficientCommitments[1:]))
for i, commitment := range pc.coefficientCommitments[1:] {
commitments[i] = commitment.Commit()
}
return commitments
}
func (pc *PolyCommitment) Evaluate(x *ebigint.NBigInt) *PedersenCommitment {
var result = pc.coefficientCommitments[0]
var accumulator = x
for _, commitment := range pc.coefficientCommitments[1:] {
result = result.Add(commitment.Times(accumulator))
accumulator = accumulator.RedMul(x)
}
return result
}
type Polynomial struct {
coefficients []*ebigint.NBigInt
}
func NewPolynomial(coefficients []*ebigint.NBigInt) *Polynomial {
poly := &Polynomial{}
if coefficients != nil && len(coefficients) > 0 {
poly.coefficients = coefficients
} else {
poly.coefficients = make([]*ebigint.NBigInt, 0)
poly.coefficients = append(poly.coefficients, ebigint.NewNBigInt(1).ToRed(b128.Q()))
}
return poly
}
func (p *Polynomial) Mul(other *Polynomial) *Polynomial {
product := make([]*ebigint.NBigInt, len(p.coefficients))
for i, b := range p.coefficients {
product[i] = b.RedMul(other.coefficients[0])
}
product = append(product, ebigint.NewNBigInt(0).ToRed(b128.Q()))
if other.coefficients[1].Cmp(big.NewInt(1)) == 0 {
// product = product.map((product_i, i) => i > 0 ? product_i.redAdd(this.coefficients[i - 1]) : product_i);
nproduct := make([]*ebigint.NBigInt, len(product))
for i, b := range product {
if i > 0 {
nproduct[i] = b.RedAdd(p.coefficients[i-1])
} else {
nproduct[i] = b
}
}
product = nproduct
}
return NewPolynomial(product)
} | core/algebra.go | 0.542136 | 0.430207 | algebra.go | starcoder |
package hashtable
import "github.com/jot85/collections"
import "github.com/jot85/collections/list"
import "unsafe"
import "errors"
var ErrFull = errors.New("HashTable container full")
//HashFunction represents a function that can be used as a hash function for a hash table.
//The first argument is a pointer to the data it should hash.
//The second is the current hash attempt - this gets incremented on a collision.
//And if the second argument is greater that 0 (so a collision has occured), the final argument is the last hashed value.
//It should return the hash.
type HashFunction func(unsafe.Pointer, uint64, uint64) uint64
//HashTable represents a hash table.
type HashTable struct {
container collections.IndexableSetablePointers
cmap containermap
HashFunction HashFunction
allowUnsafe bool
setter collections.SetFunction
getter collections.GetFunction
}
type item struct {
data unsafe.Pointer
stored bool
}
//NewHashTable creates a new HashTable using the given collections.IndexableSetablePointers to store the data in, and the given HashFunction to generate the hashes.
func NewHashTable(container collections.IndexableSetablePointers, hashFunc HashFunction, setter collections.SetFunction, getter collections.GetFunction, allowUnsafe bool) HashTable {
var m containermap
l := container.Length()
if l > uint64((^uint(0))>>1) {
m = containermap(&listmap{list.NewList(l, nil, true)})
} else {
temp := slicemap(make([]bool, l))
m = containermap(&temp)
}
return HashTable{
container,
m,
hashFunc,
allowUnsafe,
setter,
getter,
}
}
func (table *HashTable) valueToPointer(value interface{}) unsafe.Pointer {
if table.setter == nil {
return unsafe.Pointer(&value)
}
return table.setter(value)
}
//addPointer adds the value pointed to by the given unsafe.Pointer to the HashTable
func (table *HashTable) addPointer(value unsafe.Pointer) {
var pos uint64
var attempt uint64
pos = table.HashFunction(value, attempt, pos)
origPos := pos
for {
if !table.cmap.Get(pos) {
table.cmap.Set(pos, true)
table.container.SetIndex(pos, value)
break
}
attempt++
pos = table.HashFunction(value, attempt, pos)
if pos == origPos {
panic(ErrFull)
}
}
}
//AddPointer adds the value pointed to by the given unsafe.Pointer to the HashTable
func (table *HashTable) AddPointer(value unsafe.Pointer) {
table.addPointer(value)
}
//Add adds the value to the HashTable
func (table *HashTable) Add(value interface{}) {
table.addPointer(table.valueToPointer(value))
}
func (table *HashTable) Search(value interface{}) bool {
var pos uint64
var attempt uint64
pVal := table.valueToPointer(value)
pos = table.HashFunction(pVal, attempt, pos)
origPos := pos
for {
if !table.cmap.Get(pos) {
return false
}
val := table.getter(table.container.GetIndex(pos))
if value == val {
return true
}
attempt++
pos = table.HashFunction(pVal, attempt, pos)
if pos == origPos {
return false
}
}
}
func (table *HashTable) SearchPointer(value unsafe.Pointer) bool {
return table.Search(table.setter(value))
} | hashtable/hashtable.go | 0.573678 | 0.413359 | hashtable.go | starcoder |
package interval
import (
"fmt"
"time"
"github.com/eleme/lindb/pkg/util"
)
// Type defines interval type
type Type int
const dayStr = "day"
const monthStr = "month"
const yearStr = "year"
// Interval types.
const (
Day Type = iota + 1
Month
Year
Unknown
)
// String returns string value of interval type
func (t Type) String() string {
switch t {
case Month:
return monthStr
case Year:
return yearStr
default:
return dayStr
}
}
// ParseType returns interval type based on string value, return error if type not in type list
func ParseType(s string) (Type, error) {
switch s {
case dayStr:
return Day, nil
case monthStr:
return Month, nil
case yearStr:
return Year, nil
default:
return Unknown, fmt.Errorf("unknown interval type[%s]", s)
}
}
// intervalTypes defines calculator for interval type
var intervalTypes = make(map[Type]Calculator)
// register adds calculator for interval type
func register(intervalType Type, calc Calculator) {
if _, ok := intervalTypes[intervalType]; ok {
panic(fmt.Sprintf("calculator of interval type already registered: %d", intervalType))
}
intervalTypes[intervalType] = calc
}
// GetCalculator returns calculator for given interval type
func GetCalculator(intervalType Type) Calculator {
return intervalTypes[intervalType]
}
// init register interval types when system init
func init() {
register(Day, &day{})
register(Month, &month{})
register(Year, &year{})
}
// Calculator represents calculate timestamp for each interval type
type Calculator interface {
// GetSegment returns segment name by given timestamp
GetSegment(timestamp int64) string
// ParseSegmentTime parses segment base time based on given segment name
ParseSegmentTime(segmentName string) (int64, error)
// CalSegmentTime calculates segment base time based on given segment name
CalSegmentTime(timestamp int64) int64
// CalSegmentTime calculates family base time based on given timestamp
CalFamilyBaseTime(timestamp int64) int64
// CalSlot calculates field store slot index based on given timestamp
CalSlot(timestamp int64) int32
}
// day implements Calculator interface for day interval type
type day struct {
}
func (d *day) CalSlot(timestamp int64) int32 {
//TODO
return 0
}
// GetSegment returns segment name by given timestamp for day interval type
func (d *day) GetSegment(timestamp int64) string {
return util.FormatTimestamp(timestamp, "20060102")
}
// ParseSegmentTime parses segment base time based on given segment name for day interval type
func (d *day) ParseSegmentTime(segmentName string) (int64, error) {
return util.ParseTimestamp(segmentName, "20060102")
}
func (d *day) CalSegmentTime(timestamp int64) int64 {
t := time.Unix(timestamp/1000, 0)
t2 := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
return t2.UnixNano() / 1000000
}
func (d *day) CalFamilyBaseTime(timestamp int64) int64 {
//TODO
return 0
}
// month implements Calculator interface for month interval type
type month struct {
}
func (m *month) CalSlot(timestamp int64) int32 {
return 0
}
// GetSegment returns segment name by given timestamp for month interval type
func (m *month) GetSegment(timestamp int64) string {
return util.FormatTimestamp(timestamp, "200601")
}
// ParseSegmentTime parses segment base time based on given segment name for month interval type
func (m *month) ParseSegmentTime(segmentName string) (int64, error) {
return util.ParseTimestamp(segmentName, "200601")
}
func (m *month) CalSegmentTime(timestamp int64) int64 {
return 0
}
func (m *month) CalFamilyBaseTime(timestamp int64) int64 {
//TODO
return 0
}
// year implements Calculator interface for year interval type
type year struct {
}
func (y *year) CalSlot(timestamp int64) int32 {
//TODO
return 0
}
// GetSegment returns segment name by given timestamp for day interval type
func (y *year) GetSegment(timestamp int64) string {
return util.FormatTimestamp(timestamp, "2006")
}
// ParseSegmentTime parses segment base time based on given segment name for year interval type
func (y *year) ParseSegmentTime(segmentName string) (int64, error) {
return util.ParseTimestamp(segmentName, "2006")
}
func (y *year) CalSegmentTime(timestamp int64) int64 {
return 0
}
func (y *year) CalFamilyBaseTime(timestamp int64) int64 {
//TODO
return 0
} | pkg/interval/interval.go | 0.658198 | 0.433502 | interval.go | starcoder |
package bigqueue
// Enqueue adds a new slice of byte element to the tail of the queue
func (q *MmapQueue) Enqueue(message []byte) error {
return q.enqueue(&bytesWriter{b: message})
}
// EnqueueString adds a new string element to the tail of the queue
func (q *MmapQueue) EnqueueString(message string) error {
return q.enqueue(&stringWriter{s: message})
}
// writer knows how to copy data of given length to arena
type writer interface {
// returns the length of the data that writer holds
len() int
// writes the data to arena starting at given offset. It is possible that the
// whole data that writer holds may not fit in the given arena. Hence, an index
// into the data is provided. The data is copied starting from index until either
// no more data is left, or no space is left in the given arena to write more data.
writeTo(aa *arena, offset, index int) int
}
// bytesWriter holds a slice of bytes
type bytesWriter struct {
b []byte
}
func (bw *bytesWriter) len() int {
return len(bw.b)
}
func (bw *bytesWriter) writeTo(aa *arena, offset, index int) int {
n, _ := aa.WriteAt(bw.b[index:], int64(offset))
return n
}
// stringWriter holds a string that can be written into arenas
type stringWriter struct {
s string
}
func (sw *stringWriter) len() int {
return len(sw.s)
}
func (sw *stringWriter) writeTo(aa *arena, offset, index int) int {
return aa.WriteStringAt(sw.s[index:], int64(offset))
}
// enqueue writes the data hold by the given writer. It first writes the length
// of the data, then the data itself. It is possible that the whole data may not
// fit into one arena. This function takes care of spreading the data across
// multiple arenas when necessary.
func (q *MmapQueue) enqueue(w writer) error {
q.tLock.Lock()
defer q.tLock.Unlock()
aid, offset := q.index.getTail()
newAid, newOffset, err := q.writeLength(aid, offset, uint64(w.len()))
if err != nil {
return err
}
aid, offset = newAid, newOffset
// write data
aid, offset, err = q.writeBytes(w, aid, offset)
if err != nil {
return err
}
// update tail
q.index.putTail(aid, offset)
// increase number of mutation operations
q.mutOps.add(1)
if q.conf.flushMutOps != 0 && q.mutOps.load() >= q.conf.flushMutOps && len(q.flushChan) == 0 {
q.flushChan <- struct{}{}
}
return nil
}
// writeLength writes the length into tail arena. Note that length is
// always written in 1 arena, it is never broken across arenas.
func (q *MmapQueue) writeLength(aid, offset int, length uint64) (int, int, error) {
// ensure that new arena is available if needed
if offset+cInt64Size > q.conf.arenaSize {
aid, offset = aid+1, 0
}
aa, err := q.am.getArena(aid)
if err != nil {
return 0, 0, err
}
aa.WriteUint64At(length, int64(offset))
aa.dirty.store(1)
// update offset now
offset += cInt64Size
if offset == q.conf.arenaSize {
aid, offset = aid+1, 0
}
return aid, offset, nil
}
// writeBytes writes byteSlice in arena(s) with aid starting at offset
func (q *MmapQueue) writeBytes(w writer, aid, offset int) (
int, int, error) {
length := w.len()
counter := 0
for {
aa, err := q.am.getArena(aid)
if err != nil {
return 0, 0, err
}
bytesWritten := w.writeTo(aa, offset, counter)
counter += bytesWritten
offset += bytesWritten
aa.dirty.store(1)
// ensure the next arena is available if needed
if offset == q.conf.arenaSize {
aid, offset = aid+1, 0
}
// check if all bytes are written
if counter == length {
break
}
}
return aid, offset, nil
} | write.go | 0.838812 | 0.5526 | write.go | starcoder |
package diagram
import (
"fmt"
"math"
)
const arrowHeadLength = 21
// Block contains the x,y coordinates of the start of the block
type Element struct {
x, y float64
elementType string
description string
size int
url string
}
type Point struct {
x, y float64
}
type Connector struct {
b1, b2 int
}
type Transition struct {
duration int
}
// Diagram contains a list of blocks (structure used by block-diagram-editor)
type Diagram struct {
width float64
height float64
blockWidth float64
blockHeight float64
elements []Element
connectors []Connector
transitions []Transition
}
func DefaultDiagram() Diagram {
d := Diagram{}
d.width = 900.0
d.height = 600.0
d.blockWidth = 90.0
d.blockHeight = 60.0
return d
}
func AddBlock(d Diagram, x int, y int) Diagram {
d.elements = append(d.elements, Element{float64(x),float64(y),"block","",0,""})
return d
}
func AddConnector(d Diagram, b1 int, b2 int) Diagram {
d.connectors = append(d.connectors, Connector{b1,b2})
return d
}
func AddText(d Diagram, x int, y int, description string, size int) Diagram {
return AddTextWithUrl(d, x, y, description, size, "")
}
func AddTextWithUrl(d Diagram, x int, y int, description string, size int, url string) Diagram {
d.elements = append(d.elements, Element{float64(x),float64(y),"text",description,size,url})
return d
}
func AddTransition(d Diagram, duration int) Diagram {
d.transitions = append(d.transitions, Transition{duration})
return d
}
func Diagram2String(diagram Diagram) string {
b := ""
for _, e := range diagram.elements {
if len(b) > 0 {
b += ","
}
b += fmt.Sprintf("{\"x\": %f, \"y\": %f, \"elementType\": \"%s\"}", e.x, e.y, e.elementType)
}
s := fmt.Sprintf(
"{"+
"\"width\": %f,"+
"\"height\": %f,"+
"\"blockWidth\": %f,"+
"\"blockHeight\": %f,"+
"\"elements\": [%s],"+
"\"connectors\": []"+
"}\n",
diagram.width, diagram.height, diagram.blockWidth, diagram.blockHeight, b)
return s
}
func slope(x1 float64, y1 float64, x2 float64, y2 float64) float64 {
return (y2 - y1) / (x2 - x1)
}
func arrowHeadX(slope float64) float64 {
return arrowHeadLength / math.Sqrt(slope * slope + 1)
}
func calcP1(d Diagram, c Connector) Point {
p := Point{0.0, 0.0}
p1 := Point{d.elements[c.b1].x, d.elements[c.b1].y}
p2 := Point{d.elements[c.b2].x, d.elements[c.b2].y}
s := float64(slope(p1.x, p1.y, p2.x, p2.y))
/*
if s == +Inf || s == -Inf {
p.x = p1.x + d.blockWidth / 2;
if (this.props.p1.y < this.props.p2.y) {
y = this.props.p1.y + this.props.blockHeight;
} else {
y = this.props.p1.y;
}
} else {
}
*/
if math.Abs(s) <= slope(0.0,0.0,d.blockWidth, d.blockHeight) {
// right side
if p1.x < p2.x {
p.x = p1.x + d.blockWidth;
p.y = p1.y + d.blockHeight / 2 + d.blockWidth / 2 * s
} else {
// left side
p.x = p1.x;
p.y = p1.y + d.blockHeight / 2 - d.blockWidth / 2 * s
}
} else {
// top side
if (p1.y > p2.y) {
p.x = p1.x + d.blockWidth / 2 - (d.blockHeight / 2) / s
p.y = p1.y
// botton side
} else {
p.x = p1.x + d.blockWidth / 2 + (d.blockHeight / 2) / s
p.y = p1.y + d.blockHeight
}
}
return p
}
func calcP2(d Diagram, c Connector) Point {
p := Point{213,165}
p1 := Point{d.elements[c.b1].x, d.elements[c.b1].y}
p2 := Point{d.elements[c.b2].x, d.elements[c.b2].y}
s := float64(slope(p1.x, p1.y, p2.x, p2.y))
arrowHeadX := arrowHeadX(s);
arrowHeadY := arrowHeadX * s;
if math.Abs(s) <= float64(slope(0,0,d.blockWidth, d.blockHeight)) {
// right side
if p1.x < p2.x {
p.x = p2.x - arrowHeadX
p.y = p2.y + d.blockHeight / 2 - d.blockWidth / 2 * s - arrowHeadY
} else {
// left side
p.x = p2.x + d.blockWidth + arrowHeadX
p.y = p2.y + d.blockHeight / 2 + d.blockWidth / 2 * s + arrowHeadY
}
} else {
// top side
if (p1.y > p2.y) {
p.x = p1.x + d.blockWidth / 2 - (d.blockHeight / 2) / s
p.y = p1.y
// botton side
} else {
p.x = p1.x + d.blockWidth / 2 + (d.blockHeight / 2) / s
p.y = p1.y + d.blockHeight
}
}
return p
/*
var x = 0;
var y = 0;
if (slope === Infinity|| slope === -Infinity) {
x = this.props.p2.x + this.props.blockWidth / 2;
if (this.props.p1.y < this.props.p2.y) {
y = this.props.p2.y - arrowHeadLength;
} else {
y = this.props.p2.y + this.props.blockHeight + arrowHeadLength;
}
} else {
var arrowHeadX = this.arrowHeadX(slope);
var arrowHeadY = arrowHeadX * slope;
if (Math.abs(slope) <= this.slope(0,0,this.props.blockWidth,this.props.blockHeight)) {
// right side
if (this.props.p1.x < this.props.p2.x) {
x = this.props.p2.x;
y = this.props.p2.y + this.props.blockHeight / 2 - this.props.blockWidth / 2 * slope;
if (drawArrowHead) {
x -= arrowHeadX;
y -= arrowHeadY;
}
console.log("right: " + arrowHeadX , "," + arrowHeadY + "slope:" + slope)
}
// left side
else {
x = this.props.p2.x + this.props.blockWidth;
y = this.props.p2.y + this.props.blockHeight / 2 + this.props.blockWidth / 2 * slope;
if (drawArrowHead) {
x += arrowHeadX;
y += arrowHeadY;
}
console.log("left: " + arrowHeadX , "," + arrowHeadY + "slope:" + slope)
}
} else {
// top side
if (this.props.p1.y > this.props.p2.y) {
x = this.props.p2.x + this.props.blockWidth / 2 + (this.props.blockHeight / 2) / slope;
y = this.props.p2.y + this.props.blockHeight;
if (drawArrowHead) {
if (this.props.p1.x < this.props.p2.x) {
arrowHeadX = arrowHeadX * -1;
}
x += arrowHeadX
y += Math.abs(arrowHeadY);
}
console.log("top: " + arrowHeadX , "," + arrowHeadY + "slope:" + slope)
}
// botton side
else {
x = this.props.p2.x + this.props.blockWidth / 2 - (this.props.blockHeight / 2) / slope;
y = this.props.p2.y;
if (drawArrowHead) {
if (this.props.p1.x < this.props.p2.x) {
arrowHeadX = arrowHeadX * -1;
}
x += arrowHeadX;
y -= Math.abs(arrowHeadY);
}
console.log("bottom: " + arrowHeadX , "," + arrowHeadY + "slope:" + slope)
}
}
}
return ({
x: x,
y: y
})
*/
}
func Diagram2Svg(diagram Diagram) string {
elements := ""
i := 0
for _, e := range diagram.elements {
if e.elementType == "block" {
elements += fmt.Sprintf("<rect class=\"transition%d\" x=\"%f\" y=\"%f\" width=\"90\" height=\"60\" id=\"1\" stroke=\"black\" fill=\"transparent\" stroke-width=\"4\"></rect>\n", i, e.x, e.y)
}
if e.elementType == "text" {
elements += fmt.Sprintf("<text class=\"transition%d\" x=\"%f\" y=\"%f\" fill=\"black\" font-size=\"%dpx\">%s</text>\n", i, e.x, e.y, e.size, e.description)
}
i++
}
transitions := ""
i = 0
for _, t := range diagram.transitions {
transitions += fmt.Sprintf(
".transition%d {"+
" animation-name: transitionOpacity;"+
" animation-duration: %ds;"+
" animation-iteration-count: 1;"+
"}", i, t.duration)
i++
}
connectors := ""
i = 1
for _, c := range diagram.connectors {
p1 := calcP1(diagram, c)
p2 := calcP2(diagram, c)
connectors += fmt.Sprintf(
"<line class=\"transition%d\" x1=\"%f\" y1=\"%f\" x2=\"%f\" y2=\"%f\" stroke=\"black\" stroke-width=\"4\" marker-end=\"url(#arrowhead)\"></line>",
i, p1.x, p1.y, p2.x, p2.y)
i++
}
width := diagram.width
height := diagram.height
if width <= 0 {
width = 600
}
if height <= 0 {
height = 400
}
s := fmt.Sprintf(
"<svg width=\"%f\" height=\"%f\" align=\"center\">" +
" <rect x=\"0\" y=\"0\" id=\"editor-canvas\" width=\"%f\" height=\"%f\" stroke=\"white\" fill=\"transparent\" stroke-width=\"0\"></rect>"+
"%s\n"+
"<defs>\n"+
"<marker id=\"arrowhead\" markerWidth=\"5\" markerHeight=\"3.5\" refX=\"0\" refY=\"1.75\" orient=\"auto\">\n"+
" <polygon points=\"0 0, 5 1.75 0 3.5\"></polygon>\n"+
"</marker>\n"+
"</defs>\n"+
"%s\n"+
"<style>\n"+
"%s\n"+
"@keyframes transitionOpacity {\n"+
" 0%% { opacity: 0; }\n"+
" 50%% { opacity: 0; }\n"+
" 100%% { opacity: 1; }\n"+
"}\n"+
"</style>\n"+
"</svg>\n",
width, height, width, height, elements, connectors, transitions)
return s
} | diagram/diagram.go | 0.718792 | 0.499573 | diagram.go | starcoder |
package exp
import "strconv"
// Eq
type expEq struct {
key string
value float64
}
func (eq expEq) Eval(p Params) bool {
value, err := strconv.ParseFloat(p.Get(eq.key), 64)
if err != nil {
return false
}
return value == eq.value
}
func (eq expEq) String() string {
return sprintf("[%s==%.2f]", eq.key, eq.value)
}
// Equal evaluates to true if the value pointed to by key is equal in value to
// v. The value pointed to by k is parsed into a float64 before comparing. If a
// parse error occurs false is returned.
func Equal(k string, v float64) Exp {
return expEq{k, v}
}
// Eq is an alias for Equal.
func Eq(k string, v float64) Exp {
return Equal(k, v)
}
// NotEqual is a shorthand for Not(Eq(k, v)).
func NotEqual(k string, v float64) Exp {
return Neq(k, v)
}
// Neq is an alias for NotEqual.
func Neq(k string, v float64) Exp {
return Not(Eq(k, v))
}
// Gt
type expGt struct {
key string
value float64
}
func (gt expGt) Eval(p Params) bool {
value, err := strconv.ParseFloat(p.Get(gt.key), 64)
if err != nil {
return false
}
return value > gt.value
}
func (gt expGt) String() string {
return sprintf("[%s>%.2f]", gt.key, gt.value)
}
// GreaterThan evaluates to true if the value pointed to by key is greater in
// value than v. The value is parsed as float before performing the comparison.
func GreaterThan(k string, v float64) Exp {
return expGt{k, v}
}
// Gt is an alias for GreaterThan.
func Gt(k string, v float64) Exp {
return GreaterThan(k, v)
}
// GreaterOrEqual is a shorthand for Or(Gt(k, v), Eq(k, v)).
func GreaterOrEqual(k string, v float64) Exp {
return Or(Gt(k, v), Eq(k, v))
}
// Gte is an alias for GreaterOrEqual.
func Gte(k string, v float64) Exp {
return GreaterOrEqual(k, v)
}
// Lt
type expLt struct {
key string
value float64
}
func (lt expLt) Eval(p Params) bool {
value, err := strconv.ParseFloat(p.Get(lt.key), 64)
if err != nil {
return false
}
return value < lt.value
}
func (lt expLt) String() string {
return sprintf("[%s<%.2f]", lt.key, lt.value)
}
// LessThan evaluates to true if the value pointed to by key is less in value
// than v. The value is parsed as float before performing the comparison.
func LessThan(k string, v float64) Exp {
return expLt{k, v}
}
// Lt is an alias for LessThan.
func Lt(k string, v float64) Exp {
return LessThan(k, v)
}
// LessOrEqual is a shorthand for Lt(Gt(k, v), Eq(k, v)).
func LessOrEqual(k string, v float64) Exp {
return Or(Lt(k, v), Eq(k, v))
}
// Lte is an alias for LessOrEqual.
func Lte(k string, v float64) Exp {
return LessOrEqual(k, v)
} | numbers.go | 0.860266 | 0.621656 | numbers.go | starcoder |
package iso20022
// Specifies periods of a corporate action.
type CorporateActionPeriod3 struct {
// Period during which the price of a security is determined.
PriceCalculationPeriod *Period1Choice `xml:"PricClctnPrd,omitempty"`
// Period during which the interest rate has been applied.
InterestPeriod *Period1Choice `xml:"IntrstPrd,omitempty"`
// Period during a take-over where any outstanding equity must be purchased by the take-over company.
CompulsoryPurchasePeriod *Period1Choice `xml:"CmplsryPurchsPrd,omitempty"`
// Period during which the security is blocked.
BlockingPeriod *Period1Choice `xml:"BlckgPrd,omitempty"`
// Period assigned by the court in a class action. It determines the client's eligible transactions that will be included in the class action and used to determine the resulting entitlement.
ClaimPeriod *Period1Choice `xml:"ClmPrd,omitempty"`
// Period defining the last date for which book entry transfers will be accepted and the date on which the suspension will be released and book entry transfer processing will resume.
DepositorySuspensionPeriodForBookEntryTransfer *Period1Choice `xml:"DpstrySspnsnPrdForBookNtryTrf,omitempty"`
// Period defining the last date for which deposits, into nominee name, at the agent will be accepted and the date on which the suspension will be released and deposits at agent will resume.
DepositorySuspensionPeriodForDepositAtAgent *Period1Choice `xml:"DpstrySspnsnPrdForDpstAtAgt,omitempty"`
// Period defining the last date for which deposits will be accepted and the date on which the suspension will be released and deposits will resume.
DepositorySuspensionPeriodForDeposit *Period1Choice `xml:"DpstrySspnsnPrdForDpst,omitempty"`
// Period defining the last date for which pledges will be accepted and the date on which the suspension will be released and pledge processing will resume.
DepositorySuspensionPeriodForPledge *Period1Choice `xml:"DpstrySspnsnPrdForPldg,omitempty"`
// Period defining the last date for which intra-position balances can be segregated and the date on which the suspension will be released and the ability to segregate intra-position balances will resume.
DepositorySuspensionPeriodForSegregation *Period1Choice `xml:"DpstrySspnsnPrdForSgrtn,omitempty"`
// Period defining the last date for which withdrawals, from nominee name at the agent will be accepted and the date on which the suspension will be released and withdrawals at agent processing will resume.
DepositorySuspensionPeriodForWithdrawalAtAgent *Period1Choice `xml:"DpstrySspnsnPrdForWdrwlAtAgt,omitempty"`
// Period defining the last date for which physical withdrawals in the nominee's name will be accepted and the date on which the suspension will be released and physical withdrawals in the nominee's name will resume.
DepositorySuspensionPeriodForWithdrawalInNomineeName *Period1Choice `xml:"DpstrySspnsnPrdForWdrwlInNmneeNm,omitempty"`
// Period defining the last date on which withdrawal requests in street name's will be accepted on the event security and the date on which the suspension will be released and withdrawal in street name's processing on the event security will resume.
DepositorySuspensionPeriodForWithdrawalInStreetName *Period1Choice `xml:"DpstrySspnsnPrdForWdrwlInStrtNm,omitempty"`
// Period defining the last date on which shareholder registration will be accepted by the issuer and the date on which shareholder registration will resume.
BookClosurePeriod *Period1Choice `xml:"BookClsrPrd,omitempty"`
}
func (c *CorporateActionPeriod3) AddPriceCalculationPeriod() *Period1Choice {
c.PriceCalculationPeriod = new(Period1Choice)
return c.PriceCalculationPeriod
}
func (c *CorporateActionPeriod3) AddInterestPeriod() *Period1Choice {
c.InterestPeriod = new(Period1Choice)
return c.InterestPeriod
}
func (c *CorporateActionPeriod3) AddCompulsoryPurchasePeriod() *Period1Choice {
c.CompulsoryPurchasePeriod = new(Period1Choice)
return c.CompulsoryPurchasePeriod
}
func (c *CorporateActionPeriod3) AddBlockingPeriod() *Period1Choice {
c.BlockingPeriod = new(Period1Choice)
return c.BlockingPeriod
}
func (c *CorporateActionPeriod3) AddClaimPeriod() *Period1Choice {
c.ClaimPeriod = new(Period1Choice)
return c.ClaimPeriod
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForBookEntryTransfer() *Period1Choice {
c.DepositorySuspensionPeriodForBookEntryTransfer = new(Period1Choice)
return c.DepositorySuspensionPeriodForBookEntryTransfer
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForDepositAtAgent() *Period1Choice {
c.DepositorySuspensionPeriodForDepositAtAgent = new(Period1Choice)
return c.DepositorySuspensionPeriodForDepositAtAgent
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForDeposit() *Period1Choice {
c.DepositorySuspensionPeriodForDeposit = new(Period1Choice)
return c.DepositorySuspensionPeriodForDeposit
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForPledge() *Period1Choice {
c.DepositorySuspensionPeriodForPledge = new(Period1Choice)
return c.DepositorySuspensionPeriodForPledge
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForSegregation() *Period1Choice {
c.DepositorySuspensionPeriodForSegregation = new(Period1Choice)
return c.DepositorySuspensionPeriodForSegregation
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForWithdrawalAtAgent() *Period1Choice {
c.DepositorySuspensionPeriodForWithdrawalAtAgent = new(Period1Choice)
return c.DepositorySuspensionPeriodForWithdrawalAtAgent
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForWithdrawalInNomineeName() *Period1Choice {
c.DepositorySuspensionPeriodForWithdrawalInNomineeName = new(Period1Choice)
return c.DepositorySuspensionPeriodForWithdrawalInNomineeName
}
func (c *CorporateActionPeriod3) AddDepositorySuspensionPeriodForWithdrawalInStreetName() *Period1Choice {
c.DepositorySuspensionPeriodForWithdrawalInStreetName = new(Period1Choice)
return c.DepositorySuspensionPeriodForWithdrawalInStreetName
}
func (c *CorporateActionPeriod3) AddBookClosurePeriod() *Period1Choice {
c.BookClosurePeriod = new(Period1Choice)
return c.BookClosurePeriod
} | CorporateActionPeriod3.go | 0.794225 | 0.659227 | CorporateActionPeriod3.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.