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 integration
// EqualsAST does deep equals between the two objects.
func EqualsAST(inA, inB AST) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case BasicType:
b, ok := inB.(BasicType)
if !ok {
return false
}
return a == b
case Bytes:
b, ok := inB.(Bytes)
if !ok {
return false
}
return EqualsBytes(a, b)
case InterfaceContainer:
b, ok := inB.(InterfaceContainer)
if !ok {
return false
}
return EqualsInterfaceContainer(a, b)
case InterfaceSlice:
b, ok := inB.(InterfaceSlice)
if !ok {
return false
}
return EqualsInterfaceSlice(a, b)
case *Leaf:
b, ok := inB.(*Leaf)
if !ok {
return false
}
return EqualsRefOfLeaf(a, b)
case LeafSlice:
b, ok := inB.(LeafSlice)
if !ok {
return false
}
return EqualsLeafSlice(a, b)
case *NoCloneType:
b, ok := inB.(*NoCloneType)
if !ok {
return false
}
return EqualsRefOfNoCloneType(a, b)
case *RefContainer:
b, ok := inB.(*RefContainer)
if !ok {
return false
}
return EqualsRefOfRefContainer(a, b)
case *RefSliceContainer:
b, ok := inB.(*RefSliceContainer)
if !ok {
return false
}
return EqualsRefOfRefSliceContainer(a, b)
case *SubImpl:
b, ok := inB.(*SubImpl)
if !ok {
return false
}
return EqualsRefOfSubImpl(a, b)
case ValueContainer:
b, ok := inB.(ValueContainer)
if !ok {
return false
}
return EqualsValueContainer(a, b)
case ValueSliceContainer:
b, ok := inB.(ValueSliceContainer)
if !ok {
return false
}
return EqualsValueSliceContainer(a, b)
default:
// this should never happen
return false
}
}
// CloneAST creates a deep clone of the input.
func CloneAST(in AST) AST {
if in == nil {
return nil
}
switch in := in.(type) {
case BasicType:
return in
case Bytes:
return CloneBytes(in)
case InterfaceContainer:
return CloneInterfaceContainer(in)
case InterfaceSlice:
return CloneInterfaceSlice(in)
case *Leaf:
return CloneRefOfLeaf(in)
case LeafSlice:
return CloneLeafSlice(in)
case *NoCloneType:
return CloneRefOfNoCloneType(in)
case *RefContainer:
return CloneRefOfRefContainer(in)
case *RefSliceContainer:
return CloneRefOfRefSliceContainer(in)
case *SubImpl:
return CloneRefOfSubImpl(in)
case ValueContainer:
return CloneValueContainer(in)
case ValueSliceContainer:
return CloneValueSliceContainer(in)
default:
// this should never happen
return nil
}
}
// VisitAST will visit all parts of the AST
func VisitAST(in AST, f Visit) error {
if in == nil {
return nil
}
switch in := in.(type) {
case BasicType:
return VisitBasicType(in, f)
case Bytes:
return VisitBytes(in, f)
case InterfaceContainer:
return VisitInterfaceContainer(in, f)
case InterfaceSlice:
return VisitInterfaceSlice(in, f)
case *Leaf:
return VisitRefOfLeaf(in, f)
case LeafSlice:
return VisitLeafSlice(in, f)
case *NoCloneType:
return VisitRefOfNoCloneType(in, f)
case *RefContainer:
return VisitRefOfRefContainer(in, f)
case *RefSliceContainer:
return VisitRefOfRefSliceContainer(in, f)
case *SubImpl:
return VisitRefOfSubImpl(in, f)
case ValueContainer:
return VisitValueContainer(in, f)
case ValueSliceContainer:
return VisitValueSliceContainer(in, f)
default:
// this should never happen
return nil
}
}
// EqualsBytes does deep equals between the two objects.
func EqualsBytes(a, b Bytes) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// CloneBytes creates a deep clone of the input.
func CloneBytes(n Bytes) Bytes {
res := make(Bytes, 0, len(n))
copy(res, n)
return res
}
// VisitBytes will visit all parts of the AST
func VisitBytes(in Bytes, f Visit) error {
_, err := f(in)
return err
}
// EqualsInterfaceContainer does deep equals between the two objects.
func EqualsInterfaceContainer(a, b InterfaceContainer) bool {
return true
}
// CloneInterfaceContainer creates a deep clone of the input.
func CloneInterfaceContainer(n InterfaceContainer) InterfaceContainer {
return *CloneRefOfInterfaceContainer(&n)
}
// VisitInterfaceContainer will visit all parts of the AST
func VisitInterfaceContainer(in InterfaceContainer, f Visit) error {
if cont, err := f(in); err != nil || !cont {
return err
}
return nil
}
// EqualsInterfaceSlice does deep equals between the two objects.
func EqualsInterfaceSlice(a, b InterfaceSlice) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsAST(a[i], b[i]) {
return false
}
}
return true
}
// CloneInterfaceSlice creates a deep clone of the input.
func CloneInterfaceSlice(n InterfaceSlice) InterfaceSlice {
res := make(InterfaceSlice, 0, len(n))
for _, x := range n {
res = append(res, CloneAST(x))
}
return res
}
// VisitInterfaceSlice will visit all parts of the AST
func VisitInterfaceSlice(in InterfaceSlice, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
for _, el := range in {
if err := VisitAST(el, f); err != nil {
return err
}
}
return nil
}
// EqualsRefOfLeaf does deep equals between the two objects.
func EqualsRefOfLeaf(a, b *Leaf) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.v == b.v
}
// CloneRefOfLeaf creates a deep clone of the input.
func CloneRefOfLeaf(n *Leaf) *Leaf {
if n == nil {
return nil
}
out := *n
return &out
}
// VisitRefOfLeaf will visit all parts of the AST
func VisitRefOfLeaf(in *Leaf, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
return nil
}
// EqualsLeafSlice does deep equals between the two objects.
func EqualsLeafSlice(a, b LeafSlice) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfLeaf(a[i], b[i]) {
return false
}
}
return true
}
// CloneLeafSlice creates a deep clone of the input.
func CloneLeafSlice(n LeafSlice) LeafSlice {
res := make(LeafSlice, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfLeaf(x))
}
return res
}
// VisitLeafSlice will visit all parts of the AST
func VisitLeafSlice(in LeafSlice, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
for _, el := range in {
if err := VisitRefOfLeaf(el, f); err != nil {
return err
}
}
return nil
}
// EqualsRefOfNoCloneType does deep equals between the two objects.
func EqualsRefOfNoCloneType(a, b *NoCloneType) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.v == b.v
}
// CloneRefOfNoCloneType creates a deep clone of the input.
func CloneRefOfNoCloneType(n *NoCloneType) *NoCloneType {
return n
}
// VisitRefOfNoCloneType will visit all parts of the AST
func VisitRefOfNoCloneType(in *NoCloneType, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
return nil
}
// EqualsRefOfRefContainer does deep equals between the two objects.
func EqualsRefOfRefContainer(a, b *RefContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.NotASTType == b.NotASTType &&
EqualsAST(a.ASTType, b.ASTType) &&
EqualsRefOfLeaf(a.ASTImplementationType, b.ASTImplementationType)
}
// CloneRefOfRefContainer creates a deep clone of the input.
func CloneRefOfRefContainer(n *RefContainer) *RefContainer {
if n == nil {
return nil
}
out := *n
out.ASTType = CloneAST(n.ASTType)
out.ASTImplementationType = CloneRefOfLeaf(n.ASTImplementationType)
return &out
}
// VisitRefOfRefContainer will visit all parts of the AST
func VisitRefOfRefContainer(in *RefContainer, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
if err := VisitAST(in.ASTType, f); err != nil {
return err
}
if err := VisitRefOfLeaf(in.ASTImplementationType, f); err != nil {
return err
}
return nil
}
// EqualsRefOfRefSliceContainer does deep equals between the two objects.
func EqualsRefOfRefSliceContainer(a, b *RefSliceContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSliceOfAST(a.ASTElements, b.ASTElements) &&
EqualsSliceOfInt(a.NotASTElements, b.NotASTElements) &&
EqualsSliceOfRefOfLeaf(a.ASTImplementationElements, b.ASTImplementationElements)
}
// CloneRefOfRefSliceContainer creates a deep clone of the input.
func CloneRefOfRefSliceContainer(n *RefSliceContainer) *RefSliceContainer {
if n == nil {
return nil
}
out := *n
out.ASTElements = CloneSliceOfAST(n.ASTElements)
out.NotASTElements = CloneSliceOfInt(n.NotASTElements)
out.ASTImplementationElements = CloneSliceOfRefOfLeaf(n.ASTImplementationElements)
return &out
}
// VisitRefOfRefSliceContainer will visit all parts of the AST
func VisitRefOfRefSliceContainer(in *RefSliceContainer, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
for _, el := range in.ASTElements {
if err := VisitAST(el, f); err != nil {
return err
}
}
for _, el := range in.ASTImplementationElements {
if err := VisitRefOfLeaf(el, f); err != nil {
return err
}
}
return nil
}
// EqualsRefOfSubImpl does deep equals between the two objects.
func EqualsRefOfSubImpl(a, b *SubImpl) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSubIface(a.inner, b.inner) &&
EqualsRefOfBool(a.field, b.field)
}
// CloneRefOfSubImpl creates a deep clone of the input.
func CloneRefOfSubImpl(n *SubImpl) *SubImpl {
if n == nil {
return nil
}
out := *n
out.inner = CloneSubIface(n.inner)
out.field = CloneRefOfBool(n.field)
return &out
}
// VisitRefOfSubImpl will visit all parts of the AST
func VisitRefOfSubImpl(in *SubImpl, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
if err := VisitSubIface(in.inner, f); err != nil {
return err
}
return nil
}
// EqualsValueContainer does deep equals between the two objects.
func EqualsValueContainer(a, b ValueContainer) bool {
return a.NotASTType == b.NotASTType &&
EqualsAST(a.ASTType, b.ASTType) &&
EqualsRefOfLeaf(a.ASTImplementationType, b.ASTImplementationType)
}
// CloneValueContainer creates a deep clone of the input.
func CloneValueContainer(n ValueContainer) ValueContainer {
return *CloneRefOfValueContainer(&n)
}
// VisitValueContainer will visit all parts of the AST
func VisitValueContainer(in ValueContainer, f Visit) error {
if cont, err := f(in); err != nil || !cont {
return err
}
if err := VisitAST(in.ASTType, f); err != nil {
return err
}
if err := VisitRefOfLeaf(in.ASTImplementationType, f); err != nil {
return err
}
return nil
}
// EqualsValueSliceContainer does deep equals between the two objects.
func EqualsValueSliceContainer(a, b ValueSliceContainer) bool {
return EqualsSliceOfAST(a.ASTElements, b.ASTElements) &&
EqualsSliceOfInt(a.NotASTElements, b.NotASTElements) &&
EqualsSliceOfRefOfLeaf(a.ASTImplementationElements, b.ASTImplementationElements)
}
// CloneValueSliceContainer creates a deep clone of the input.
func CloneValueSliceContainer(n ValueSliceContainer) ValueSliceContainer {
return *CloneRefOfValueSliceContainer(&n)
}
// VisitValueSliceContainer will visit all parts of the AST
func VisitValueSliceContainer(in ValueSliceContainer, f Visit) error {
if cont, err := f(in); err != nil || !cont {
return err
}
for _, el := range in.ASTElements {
if err := VisitAST(el, f); err != nil {
return err
}
}
for _, el := range in.ASTImplementationElements {
if err := VisitRefOfLeaf(el, f); err != nil {
return err
}
}
return nil
}
// EqualsSubIface does deep equals between the two objects.
func EqualsSubIface(inA, inB SubIface) bool {
if inA == nil && inB == nil {
return true
}
if inA == nil || inB == nil {
return false
}
switch a := inA.(type) {
case *SubImpl:
b, ok := inB.(*SubImpl)
if !ok {
return false
}
return EqualsRefOfSubImpl(a, b)
default:
// this should never happen
return false
}
}
// CloneSubIface creates a deep clone of the input.
func CloneSubIface(in SubIface) SubIface {
if in == nil {
return nil
}
switch in := in.(type) {
case *SubImpl:
return CloneRefOfSubImpl(in)
default:
// this should never happen
return nil
}
}
// VisitSubIface will visit all parts of the AST
func VisitSubIface(in SubIface, f Visit) error {
if in == nil {
return nil
}
switch in := in.(type) {
case *SubImpl:
return VisitRefOfSubImpl(in, f)
default:
// this should never happen
return nil
}
}
// VisitBasicType will visit all parts of the AST
func VisitBasicType(in BasicType, f Visit) error {
_, err := f(in)
return err
}
// EqualsRefOfInterfaceContainer does deep equals between the two objects.
func EqualsRefOfInterfaceContainer(a, b *InterfaceContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return true
}
// CloneRefOfInterfaceContainer creates a deep clone of the input.
func CloneRefOfInterfaceContainer(n *InterfaceContainer) *InterfaceContainer {
if n == nil {
return nil
}
out := *n
out.v = n.v
return &out
}
// VisitRefOfInterfaceContainer will visit all parts of the AST
func VisitRefOfInterfaceContainer(in *InterfaceContainer, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
return nil
}
// EqualsSliceOfAST does deep equals between the two objects.
func EqualsSliceOfAST(a, b []AST) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsAST(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfAST creates a deep clone of the input.
func CloneSliceOfAST(n []AST) []AST {
res := make([]AST, 0, len(n))
for _, x := range n {
res = append(res, CloneAST(x))
}
return res
}
// EqualsSliceOfInt does deep equals between the two objects.
func EqualsSliceOfInt(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
// CloneSliceOfInt creates a deep clone of the input.
func CloneSliceOfInt(n []int) []int {
res := make([]int, 0, len(n))
copy(res, n)
return res
}
// EqualsSliceOfRefOfLeaf does deep equals between the two objects.
func EqualsSliceOfRefOfLeaf(a, b []*Leaf) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if !EqualsRefOfLeaf(a[i], b[i]) {
return false
}
}
return true
}
// CloneSliceOfRefOfLeaf creates a deep clone of the input.
func CloneSliceOfRefOfLeaf(n []*Leaf) []*Leaf {
res := make([]*Leaf, 0, len(n))
for _, x := range n {
res = append(res, CloneRefOfLeaf(x))
}
return res
}
// EqualsRefOfBool does deep equals between the two objects.
func EqualsRefOfBool(a, b *bool) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
// CloneRefOfBool creates a deep clone of the input.
func CloneRefOfBool(n *bool) *bool {
if n == nil {
return nil
}
out := *n
return &out
}
// EqualsRefOfValueContainer does deep equals between the two objects.
func EqualsRefOfValueContainer(a, b *ValueContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return a.NotASTType == b.NotASTType &&
EqualsAST(a.ASTType, b.ASTType) &&
EqualsRefOfLeaf(a.ASTImplementationType, b.ASTImplementationType)
}
// CloneRefOfValueContainer creates a deep clone of the input.
func CloneRefOfValueContainer(n *ValueContainer) *ValueContainer {
if n == nil {
return nil
}
out := *n
out.ASTType = CloneAST(n.ASTType)
out.ASTImplementationType = CloneRefOfLeaf(n.ASTImplementationType)
return &out
}
// VisitRefOfValueContainer will visit all parts of the AST
func VisitRefOfValueContainer(in *ValueContainer, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
if err := VisitAST(in.ASTType, f); err != nil {
return err
}
if err := VisitRefOfLeaf(in.ASTImplementationType, f); err != nil {
return err
}
return nil
}
// EqualsRefOfValueSliceContainer does deep equals between the two objects.
func EqualsRefOfValueSliceContainer(a, b *ValueSliceContainer) bool {
if a == b {
return true
}
if a == nil || b == nil {
return false
}
return EqualsSliceOfAST(a.ASTElements, b.ASTElements) &&
EqualsSliceOfInt(a.NotASTElements, b.NotASTElements) &&
EqualsSliceOfRefOfLeaf(a.ASTImplementationElements, b.ASTImplementationElements)
}
// CloneRefOfValueSliceContainer creates a deep clone of the input.
func CloneRefOfValueSliceContainer(n *ValueSliceContainer) *ValueSliceContainer {
if n == nil {
return nil
}
out := *n
out.ASTElements = CloneSliceOfAST(n.ASTElements)
out.NotASTElements = CloneSliceOfInt(n.NotASTElements)
out.ASTImplementationElements = CloneSliceOfRefOfLeaf(n.ASTImplementationElements)
return &out
}
// VisitRefOfValueSliceContainer will visit all parts of the AST
func VisitRefOfValueSliceContainer(in *ValueSliceContainer, f Visit) error {
if in == nil {
return nil
}
if cont, err := f(in); err != nil || !cont {
return err
}
for _, el := range in.ASTElements {
if err := VisitAST(el, f); err != nil {
return err
}
}
for _, el := range in.ASTImplementationElements {
if err := VisitRefOfLeaf(el, f); err != nil {
return err
}
}
return nil
} | go/tools/asthelpergen/integration/ast_helper.go | 0.619586 | 0.562297 | ast_helper.go | starcoder |
// Package syscall contains an interface to the low-level operating system
// primitives. The details vary depending on the underlying system.
// Its primary use is inside other packages that provide a more portable
// interface to the system, such as "os", "time" and "net". Use those
// packages rather than this one if you can.
// For details of the functions and data types in this package consult
// the manuals for the appropriate operating system.
// These calls return errno == 0 to indicate success; otherwise
// errno is an operating system error number describing the failure.
package syscall
import (
"sync"
"unsafe"
)
// StringByteSlice returns a NUL-terminated slice of bytes
// containing the text of s.
func StringByteSlice(s string) []byte {
a := make([]byte, len(s)+1)
copy(a, s)
return a
}
// StringBytePtr returns a pointer to a NUL-terminated array of bytes
// containing the text of s.
func StringBytePtr(s string) *byte { return &StringByteSlice(s)[0] }
// Single-word zero for use when we need a valid pointer to 0 bytes.
// See mksyscall.sh.
var _zero uintptr
// Mmap manager, for use by operating system-specific implementations.
type mmapper struct {
sync.Mutex
active map[*byte][]byte // active mappings; key is last byte in mapping
mmap func(addr, length uintptr, prot, flags, fd int, offset int64) (uintptr, int)
munmap func(addr uintptr, length uintptr) int
}
func (m *mmapper) Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, errno int) {
if length <= 0 {
return nil, EINVAL
}
// Map the requested memory.
addr, errno := m.mmap(0, uintptr(length), prot, flags, fd, offset)
if errno != 0 {
return nil, errno
}
// Slice memory layout
var sl = struct {
addr uintptr
len int
cap int
}{addr, length, length}
// Use unsafe to turn sl into a []byte.
b := *(*[]byte)(unsafe.Pointer(&sl))
// Register mapping in m and return it.
p := &b[cap(b)-1]
m.Lock()
defer m.Unlock()
m.active[p] = b
return b, 0
}
func (m *mmapper) Munmap(data []byte) (errno int) {
if len(data) == 0 || len(data) != cap(data) {
return EINVAL
}
// Find the base of the mapping.
p := &data[cap(data)-1]
m.Lock()
defer m.Unlock()
b := m.active[p]
if b == nil || &b[0] != &data[0] {
return EINVAL
}
// Unmap the memory and update m.
if errno := m.munmap(uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))); errno != 0 {
return errno
}
m.active[p] = nil, false
return 0
} | src/pkg/syscall/syscall.go | 0.613352 | 0.503357 | syscall.go | starcoder |
package proj
import (
"fmt"
"math"
"reflect"
"strings"
"gonum.org/v1/gonum/floats"
)
// A Transformer takes input coordinates and returns output coordinates and an error.
type Transformer func(X, Y float64) (x, y float64, err error)
// A TransformerFunc creates forward and inverse Transformers from a projection.
type TransformerFunc func(*SR) (forward, inverse Transformer, err error)
var projections map[string]TransformerFunc
// SR holds information about a spatial reference (projection).
type SR struct {
Name, Title string
SRSCode string
DatumCode string
Rf float64
Lat0, Lat1, Lat2, LatTS float64
Long0, Long1, Long2, LongC float64
Alpha float64
X0, Y0, K0, K float64
A, A2, B, B2 float64
Ra bool
Zone float64
UTMSouth bool
DatumParams []float64
ToMeter float64
Units string
FromGreenwich float64
NADGrids string
Axis string
local bool
sphere bool
Ellps string
EllipseName string
Es float64
E float64
Ep2 float64
DatumName string
NoDefs bool
datum *datum
Czech bool
}
// NewSR initializes a SR object and sets fields to default values.
func NewSR() *SR {
p := new(SR)
// Initialize floats to NaN.
v := reflect.ValueOf(p).Elem()
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
ft := f.Type().Kind()
if ft == reflect.Float64 {
f.SetFloat(math.NaN())
}
}
p.ToMeter = 1.
return p
}
func registerTrans(proj TransformerFunc, names ...string) {
if projections == nil {
projections = make(map[string]TransformerFunc)
}
for _, n := range names {
projections[strings.ToLower(n)] = proj
}
}
// Transformers returns forward and inverse transformation functions for
// this projection.
func (sr *SR) Transformers() (forward, inverse Transformer, err error) {
t, ok := projections[strings.ToLower(sr.Name)]
if !ok {
err = fmt.Errorf("in proj.Proj.TransformFuncs, could not find "+
"transformer for %s", sr.Name)
return
}
forward, inverse, err = t(sr)
return
}
// Equal determines whether spatial references sr and sr2 are equal to within ulp
// floating point units in the last place.
func (sr *SR) Equal(sr2 *SR, ulp uint) bool {
v1 := reflect.ValueOf(sr).Elem()
v2 := reflect.ValueOf(sr2).Elem()
return equal(v1, v2, ulp)
}
// equal determines whether two values are equal to each other within ulp
func equal(v1, v2 reflect.Value, ulp uint) bool {
for i := 0; i < v1.NumField(); i++ {
f1 := v1.Field(i)
f2 := v2.Field(i)
ft := f1.Type().Kind()
switch ft {
case reflect.Float64:
fv1 := f1.Float()
fv2 := f2.Float()
if math.IsNaN(fv1) != math.IsNaN(fv2) {
return false
}
if !math.IsNaN(fv1) && !floats.EqualWithinULP(fv1, fv2, ulp) {
return false
}
case reflect.Int:
if f1.Int() != f2.Int() {
return false
}
case reflect.Bool:
if f1.Bool() != f2.Bool() {
return false
}
case reflect.Ptr:
if !equal(reflect.Indirect(f1), reflect.Indirect(f2), ulp) {
return false
}
case reflect.String:
if f1.String() != f2.String() {
return false
}
case reflect.Slice:
for i := 0; i < f1.Len(); i++ {
if !floats.EqualWithinULP(f1.Index(i).Float(), f2.Index(i).Float(), ulp) {
return false
}
}
default:
panic(fmt.Errorf("unsupported type %s", ft))
}
}
return true
} | proj/Proj.go | 0.701406 | 0.400837 | Proj.go | starcoder |
package tetra3d
import (
"sort"
"github.com/kvartborg/vector"
"github.com/takeyourhatoff/bitset"
)
// Model represents a singular visual instantiation of a Mesh. A Mesh contains the vertex information (what to draw); a Model references the Mesh to draw it with a specific
// Position, Rotation, and/or Scale (where and how to draw).
type Model struct {
*NodeBase
Mesh *Mesh
FrustumCulling bool // Whether the Model is culled when it leaves the frustum.
BackfaceCulling bool // Whether the Model's backfaces are culled.
closestTris []*Triangle
Color Color // The overall color of the Model.
BoundingSphere *BoundingSphere
SortTrisBackToFront bool // Whether the Model's triangles are sorted back-to-front or not.
}
// NewModel creates a new Model (or instance) of the Mesh and Name provided. A Model represents a singular visual instantiation of a Mesh.
func NewModel(mesh *Mesh, name string) *Model {
model := &Model{
NodeBase: NewNodeBase(name),
Mesh: mesh,
FrustumCulling: true,
BackfaceCulling: true,
Color: NewColor(1, 1, 1, 1),
SortTrisBackToFront: true,
}
dimensions := 0.0
if mesh != nil {
dimensions = mesh.Dimensions.Max()
}
model.BoundingSphere = NewBoundingSphere(model, vector.Vector{0, 0, 0}, dimensions)
return model
}
// Clone creates a clone of the Model.
func (model *Model) Clone() Node {
newModel := NewModel(model.Mesh, model.name)
newModel.BoundingSphere = model.BoundingSphere.Clone()
newModel.BoundingSphere.Node = newModel
newModel.FrustumCulling = model.FrustumCulling
newModel.BackfaceCulling = model.BackfaceCulling
newModel.visible = model.visible
newModel.Color = model.Color.Clone()
newModel.SortTrisBackToFront = model.SortTrisBackToFront
return newModel
}
// Merge merges the provided models into the calling Model. You can use this to merge several objects initially dynamically placed into the calling Model's mesh,
// thereby saving on draw calls. Note that the finished Mesh still only uses one Image for texturing, so this is best done between objects that share textures or
// tilemaps.
func (model *Model) Merge(models ...*Model) {
for _, other := range models {
p, s, r := model.Transform().Decompose()
op, os, or := other.Transform().Decompose()
inverted := NewMatrix4Scale(os[0], os[1], os[2])
scaleMatrix := NewMatrix4Scale(s[0], s[1], s[2])
inverted = inverted.Mult(scaleMatrix)
inverted = inverted.Mult(r.Transposed().Mult(or))
inverted = inverted.Mult(NewMatrix4Translate(op[0]-p[0], op[1]-p[1], op[2]-p[2]))
verts := []*Vertex{}
for i := 0; i < len(other.Mesh.Vertices); i += 3 {
v0 := other.Mesh.Vertices[i].Clone()
v0.Position = inverted.MultVec(v0.Position)
v1 := other.Mesh.Vertices[i+1].Clone()
v1.Position = inverted.MultVec(v1.Position)
v2 := other.Mesh.Vertices[i+2].Clone()
v2.Position = inverted.MultVec(v2.Position)
verts = append(verts, v0, v1, v2)
}
model.Mesh.AddTriangles(verts...)
}
model.Mesh.UpdateBounds()
model.BoundingSphere.LocalPosition = model.Mesh.Dimensions.Center()
model.BoundingSphere.LocalRadius = model.Mesh.Dimensions.Max()
}
// TransformedVertices returns the vertices of the Model, as transformed by the (provided) Camera's view matrix, sorted by distance to the (provided) Camera's position.
func (model *Model) TransformedVertices(vpMatrix Matrix4, viewPos vector.Vector) []*Triangle {
mvp := model.Transform().Mult(vpMatrix)
for _, vert := range model.Mesh.sortedVertices {
vert.transformed = mvp.MultVecW(vert.Position)
}
model.closestTris = model.closestTris[:0]
if model.SortTrisBackToFront {
sort.SliceStable(model.Mesh.sortedVertices, func(i, j int) bool {
return fastSub(model.Mesh.sortedVertices[i].transformed, viewPos).Magnitude() > fastSub(model.Mesh.sortedVertices[j].transformed, viewPos).Magnitude()
})
} else {
sort.SliceStable(model.Mesh.sortedVertices, func(i, j int) bool {
return fastSub(model.Mesh.sortedVertices[i].transformed, viewPos).Magnitude() < fastSub(model.Mesh.sortedVertices[j].transformed, viewPos).Magnitude()
})
}
// By using a bitset.Set, we can avoid putting triangles in the closestTris slice multiple times and avoid the time cost by looping over the slice / checking
// a map to see if the triangle's been added.
set := bitset.Set{}
for _, v := range model.Mesh.sortedVertices {
if !set.Test(v.triangle.ID) {
model.closestTris = append(model.closestTris, v.triangle)
set.Add(v.triangle.ID)
}
}
return model.closestTris
}
// AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph
// hierarchy. If the children are already parented to other Nodes, they are unparented before doing so.
func (model *Model) AddChildren(children ...Node) {
// We do this manually so that addChildren() parents the children to the Model, rather than to the Model.NodeBase.
model.addChildren(model, children...)
} | model.go | 0.852629 | 0.64937 | model.go | starcoder |
package forGraphBLASGo
import (
"github.com/intel/forGoParallel/parallel"
"github.com/intel/forGoParallel/pipeline"
)
type matrixEWiseMultBinaryOp[DC, DA, DB any] struct {
op BinaryOp[DC, DA, DB]
A *matrixReference[DA]
B *matrixReference[DB]
}
func newMatrixEWiseMultBinaryOp[DC, DA, DB any](
op BinaryOp[DC, DA, DB],
A *matrixReference[DA],
B *matrixReference[DB],
) computeMatrixT[DC] {
return matrixEWiseMultBinaryOp[DC, DA, DB]{
op: op,
A: A,
B: B,
}
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) resize(newNRows, newNCols int) computeMatrixT[DC] {
var a *matrixReference[DA]
var b *matrixReference[DB]
parallel.Do(func() {
a = compute.A.resize(newNRows, newNCols)
}, func() {
b = compute.B.resize(newNRows, newNCols)
})
return newMatrixEWiseMultBinaryOp[DC, DA, DB](compute.op, a, b)
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) computeElement(row, col int) (result DC, ok bool) {
if aValue, aok := compute.A.extractElement(row, col); aok {
if bValue, bok := compute.B.extractElement(row, col); bok {
return compute.op(aValue, bValue), true
}
}
return
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) computePipeline() *pipeline.Pipeline[any] {
ap := compute.A.getPipeline()
if ap == nil {
return nil
}
bp := compute.B.getPipeline()
if bp == nil {
return nil
}
return makeMatrix2SourcePipeline(ap, bp,
func(_, _ int, aValue DA, aok bool, bValue DB, bok bool) (result DC, ok bool) {
if aok && bok {
return compute.op(aValue, bValue), true
}
return
})
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) computeRowPipeline(row int) *pipeline.Pipeline[any] {
ap := compute.A.getRowPipeline(row)
if ap == nil {
return nil
}
bp := compute.B.getRowPipeline(row)
if bp == nil {
return nil
}
return makeVector2SourcePipeline(ap, bp,
func(_ int, aValue DA, aok bool, bValue DB, bok bool) (result DC, ok bool) {
if aok && bok {
return compute.op(aValue, bValue), true
}
return
})
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) computeColPipeline(col int) *pipeline.Pipeline[any] {
ap := compute.A.getColPipeline(col)
if ap == nil {
return nil
}
bp := compute.B.getColPipeline(col)
if bp == nil {
return nil
}
return makeVector2SourcePipeline(ap, bp,
func(_ int, aValue DA, aok bool, bValue DB, bok bool) (result DC, ok bool) {
if aok && bok {
return compute.op(aValue, bValue), true
}
return
})
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) mergePipelines(aps, bps []matrix1Pipeline) (result []matrix1Pipeline) {
for {
if len(aps) == 0 || len(bps) == 0 {
return
}
if aps[0].index == bps[0].index {
result = append(result, matrix1Pipeline{
index: aps[0].index,
p: makeVector2SourcePipeline(aps[0].p, bps[0].p,
func(_ int, aValue DA, aok bool, bValue DB, bok bool) (result DC, ok bool) {
if aok && bok {
return compute.op(aValue, bValue), true
}
return
}),
})
} else if aps[0].index < bps[0].index {
aps = aps[1:]
} else {
bps = bps[1:]
}
}
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) computeRowPipelines() []matrix1Pipeline {
return compute.mergePipelines(compute.A.getRowPipelines(), compute.B.getRowPipelines())
}
func (compute matrixEWiseMultBinaryOp[DC, DA, DB]) computeColPipelines() []matrix1Pipeline {
return compute.mergePipelines(compute.A.getColPipelines(), compute.B.getColPipelines())
}
type matrixEWiseAddBinaryOp[D any] struct {
op BinaryOp[D, D, D]
A, B *matrixReference[D]
}
func newMatrixEWiseAddBinaryOp[D any](
op BinaryOp[D, D, D],
A, B *matrixReference[D],
) computeMatrixT[D] {
return matrixEWiseAddBinaryOp[D]{
op: op,
A: A,
B: B,
}
}
func (compute matrixEWiseAddBinaryOp[D]) resize(newNRows, newNCols int) computeMatrixT[D] {
var a, b *matrixReference[D]
parallel.Do(func() {
a = compute.A.resize(newNRows, newNCols)
}, func() {
b = compute.B.resize(newNRows, newNCols)
})
return newMatrixEWiseAddBinaryOp[D](compute.op, a, b)
}
func (compute matrixEWiseAddBinaryOp[D]) computeElement(row, col int) (result D, ok bool) {
var aValue, bValue D
var aok, bok bool
parallel.Do(func() {
aValue, aok = compute.A.extractElement(row, col)
}, func() {
bValue, bok = compute.B.extractElement(row, col)
})
if aok {
if bok {
return compute.op(aValue, bValue), true
}
return aValue, true
}
if bok {
return bValue, true
}
return
}
func (compute matrixEWiseAddBinaryOp[D]) computePipeline() *pipeline.Pipeline[any] {
ap := compute.A.getPipeline()
bp := compute.B.getPipeline()
if ap == nil {
return bp
}
if bp == nil {
return ap
}
return makeMatrix2SourcePipeline(ap, bp,
func(_, _ int, aValue D, aok bool, bValue D, bok bool) (result D, ok bool) {
if aok {
if bok {
return compute.op(aValue, bValue), true
}
return aValue, true
}
return bValue, bok
})
}
func (compute matrixEWiseAddBinaryOp[D]) computeRowPipeline(row int) *pipeline.Pipeline[any] {
ap := compute.A.getRowPipeline(row)
bp := compute.B.getRowPipeline(row)
if ap == nil {
return bp
}
if bp == nil {
return ap
}
return makeVector2SourcePipeline(ap, bp,
func(_ int, aValue D, aok bool, bValue D, bok bool) (result D, ok bool) {
if aok {
if bok {
return compute.op(aValue, bValue), true
}
return aValue, true
}
return bValue, bok
})
}
func (compute matrixEWiseAddBinaryOp[D]) computeColPipeline(col int) *pipeline.Pipeline[any] {
ap := compute.A.getColPipeline(col)
bp := compute.B.getColPipeline(col)
if ap == nil {
return bp
}
if bp == nil {
return ap
}
return makeVector2SourcePipeline(ap, bp,
func(_ int, aValue D, aok bool, bValue D, bok bool) (result D, ok bool) {
if aok {
if bok {
return compute.op(aValue, bValue), true
}
return aValue, true
}
return bValue, bok
})
}
func (compute matrixEWiseAddBinaryOp[D]) mergePipelines(aps, bps []matrix1Pipeline) (result []matrix1Pipeline) {
for {
if len(aps) == 0 {
return append(result, bps...)
}
if len(bps) == 0 {
return append(result, aps...)
}
if aps[0].index == bps[0].index {
result = append(result, matrix1Pipeline{
index: aps[0].index,
p: makeVector2SourcePipeline(aps[0].p, bps[0].p,
func(_ int, aValue D, aok bool, bValue D, bok bool) (result D, ok bool) {
if aok {
if bok {
return compute.op(aValue, bValue), true
}
return aValue, true
}
return bValue, bok
}),
})
} else if aps[0].index < bps[0].index {
result = append(result, aps[0])
aps = aps[1:]
} else {
result = append(result, bps[0])
bps = bps[1:]
}
}
}
func (compute matrixEWiseAddBinaryOp[D]) computeRowPipelines() []matrix1Pipeline {
return compute.mergePipelines(compute.A.getRowPipelines(), compute.B.getRowPipelines())
}
func (compute matrixEWiseAddBinaryOp[D]) computeColPipelines() []matrix1Pipeline {
return compute.mergePipelines(compute.A.getColPipelines(), compute.B.getColPipelines())
} | functional_Matrix_ComputedEWise.go | 0.655336 | 0.477554 | functional_Matrix_ComputedEWise.go | starcoder |
package dyjson
import (
"encoding/json"
"strconv"
)
type jsonDataType uint8
const (
errorDataType jsonDataType = iota
nullDataType
objectDataType
arrayDataType
stringDataType
numberDataType
booleanDataType
)
// JSONValue represents a JSON value, independently of its data type.
type JSONValue struct {
json.RawMessage
valObject map[string]*JSONValue
valArray []*JSONValue
valString string
valNumber float64
valBoolean bool
dataType jsonDataType
}
// Parse parses the value into a new JSONValue.
func Parse(value []byte) *JSONValue {
return &JSONValue{
RawMessage: value,
}
}
// ParseString parses the value (as a string) into a new JSONValue.
func ParseString(value string) *JSONValue {
return Parse([]byte(value))
}
// IsNull checks if the value is null.
func (v *JSONValue) IsNull() bool {
v.parseNull()
return v.dataType == nullDataType
}
// IsObject checks if the value is a JSON object.
func (v *JSONValue) IsObject() bool {
v.parseObject()
return v.dataType == objectDataType
}
// IsArray checks if the value is a JSON array.
func (v *JSONValue) IsArray() bool {
v.parseArray()
return v.dataType == arrayDataType
}
// IsString checks if the value is a string.
func (v *JSONValue) IsString() bool {
v.parseString()
return v.dataType == stringDataType
}
// IsNumber checks if the value is a number.
func (v *JSONValue) IsNumber() bool {
v.parseNumber()
return v.dataType == numberDataType
}
// IsBoolean checks if the value is a boolean.
func (v *JSONValue) IsBoolean() bool {
v.parseBoolean()
return v.dataType == booleanDataType
}
// Object returns the value parsed as a JSON object (JSONValue).
func (v *JSONValue) Object() map[string]*JSONValue {
v.parseObject()
return v.valObject
}
// Array returns the value parsed as a JSON array (JSONValue array).
func (v *JSONValue) Array() []*JSONValue {
v.parseArray()
return v.valArray
}
// String returns the value parsed as a string.
func (v *JSONValue) String() string {
v.parseString()
return v.valString
}
// Number returns the value parsed as a number (float64).
func (v *JSONValue) Number() float64 {
v.parseNumber()
return v.valNumber
}
// Boolean returns the value parsed as a boolean (bool).
func (v *JSONValue) Boolean() bool {
v.parseBoolean()
return v.valBoolean
}
// Set sets the value as the internal JSON value.
// Useful to update itself when any child's value changes.
func (v *JSONValue) Set() {
switch {
case v.IsNull():
v.SetNull()
case v.IsObject():
v.SetObject(v.valObject)
case v.IsArray():
v.SetArray(v.valArray)
case v.IsString():
v.SetString(v.valString)
case v.IsNumber():
v.SetNumber(v.valNumber)
case v.IsBoolean():
v.SetBoolean(v.valBoolean)
}
}
// SetNull sets the value as a JSON null.
func (v *JSONValue) SetNull() {
v.RawMessage = []byte("null")
v.dataType = nullDataType
}
// SetObject sets the value as a JSON object.
func (v *JSONValue) SetObject(val map[string]*JSONValue) {
var i int
v.RawMessage = []byte{'{'}
for key, value := range val {
if i != 0 {
v.RawMessage = append(v.RawMessage, ',')
}
i++
v.RawMessage = append(v.RawMessage, '"')
v.RawMessage = append(v.RawMessage, key...)
v.RawMessage = append(v.RawMessage, '"', ':')
v.RawMessage = append(v.RawMessage, value.RawMessage...)
}
v.RawMessage = append(v.RawMessage, '}')
v.valObject = val
v.dataType = objectDataType
}
// SetArray sets the value as a JSON array.
func (v *JSONValue) SetArray(val []*JSONValue) {
v.RawMessage = []byte{'['}
for i, value := range val {
if i != 0 {
v.RawMessage = append(v.RawMessage, ',')
}
v.RawMessage = append(v.RawMessage, value.RawMessage...)
}
v.RawMessage = append(v.RawMessage, ']')
v.valArray = val
v.dataType = arrayDataType
}
// SetString sets the value as a JSON string.
func (v *JSONValue) SetString(val string) {
v.RawMessage = []byte{'"'}
v.RawMessage = append(v.RawMessage, val...)
v.RawMessage = append(v.RawMessage, '"')
v.valString = val
v.dataType = stringDataType
}
// SetNumber sets the value as a JSON number.
func (v *JSONValue) SetNumber(val float64) {
v.RawMessage = []byte(strconv.FormatFloat(val, 'f', -1, 64))
v.valNumber = val
v.dataType = numberDataType
}
// SetBoolean sets the value as a JSON boolean.
func (v *JSONValue) SetBoolean(val bool) {
if val {
v.RawMessage = []byte("true")
} else {
v.RawMessage = []byte("false")
}
v.valBoolean = val
v.dataType = booleanDataType
}
func (v *JSONValue) parseNull() {
if v.dataType != 0 {
return
}
var val interface{}
if json.Unmarshal(v.RawMessage, &val) == nil && val == nil {
v.dataType = nullDataType
}
}
func (v *JSONValue) parseObject() {
if v.dataType != 0 {
return
}
if json.Unmarshal(v.RawMessage, &v.valObject) == nil && v.valObject != nil {
v.dataType = objectDataType
}
}
func (v *JSONValue) parseArray() {
if v.dataType != 0 {
return
}
if json.Unmarshal(v.RawMessage, &v.valArray) == nil && v.valArray != nil {
v.dataType = arrayDataType
}
}
func (v *JSONValue) parseString() {
if v.dataType != 0 {
return
}
if json.Unmarshal(v.RawMessage, &v.valString) == nil {
v.dataType = stringDataType
}
}
func (v *JSONValue) parseNumber() {
if v.dataType != 0 {
return
}
if json.Unmarshal(v.RawMessage, &v.valNumber) == nil {
v.dataType = numberDataType
}
}
func (v *JSONValue) parseBoolean() {
if v.dataType != 0 {
return
}
if json.Unmarshal(v.RawMessage, &v.valBoolean) == nil {
v.dataType = booleanDataType
}
} | dyjson.go | 0.680454 | 0.434341 | dyjson.go | starcoder |
package findthenearest
import (
"fmt"
"math"
"sort"
"strconv"
)
type xSort [][]float64
func (s xSort) Len() int {
return len(s)
}
func (s xSort) Less(i, j int) bool {
return s[i][0] < s[j][0]
}
func (s xSort) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type ySort [][]float64
func (s ySort) Len() int {
return len(s)
}
func (s ySort) Less(i, j int) bool {
return s[i][1] < s[j][1]
}
func (s ySort) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// findthenearest return the index of the nearest point between two points
func findTheNearest(in [][]float64) ([]float64, []float64, float64) {
sort.Sort(xSort(in))
return nearestDistance(in)
}
// in := [][]float64{
// {1, 3},
// {4, 10},
// {5, 6},
// {7, 7},
// {10, 2},
// {30, 10},
// }
func nearestDistance(in [][]float64) (a []float64, b []float64, dmin float64) {
if 2 == len(in) {
return in[0], in[1], distance(in[0], in[1])
} else if len(in) < 2 {
return nil, nil, math.MaxFloat64
}
p := 0
r := len(in) - 1
// q is the middle point
q := (p + r) / 2
left := make([][]float64, q-p+1)
sort.Sort(xSort(in))
copy(left, in[p:q+1])
right := make([][]float64, r-q)
copy(right, in[q+1:r+1])
sort.Sort(ySort(right))
// calculate the distance in the left side
a1, b1, d1 := nearestDistance(left)
// calculate the distance in the right side
a2, b2, d2 := nearestDistance(right)
a, b, dmin = a1, b1, d1
if d1 > d2 {
a, b, dmin = a2, b2, d2
}
/* consider points in the left side which the distance is less than dmin */
xidx := bsearch(left, in[q][0]-dmin, 0)
yidx := bsearch(right, in[q][1]-dmin, 1)
if xidx < 0 || yidx < 0 {
return a, b, dmin
}
for i := xidx; i < len(left); i++ {
// there are only 6 point at most in the right side of in
for j := yidx; j < 7 && j < len(right); j++ {
d3 := distance(left[i], right[j])
if d3 < dmin {
a, b, dmin = left[i], right[j], d3
}
}
}
return a, b, Decimal(dmin)
}
// bruteForce return the index of the nearest point between two points
func bruteForce(in [][]float64) ([]float64, []float64, float64) {
a, b := -1, -1
tmp := math.MaxFloat64
length := len(in)
for i := 0; i < length; i++ {
for j := i + 1; j < length; j++ {
d := distance(in[i], in[j])
if d < tmp {
tmp = d
a, b = i, j
}
}
}
return in[a], in[b], Decimal(tmp)
}
func distance(x, y []float64) float64 {
return math.Sqrt(math.Pow(x[0]-y[0], 2) + math.Pow(x[1]-y[1], 2))
}
// bsearch lookup the first value which is greater than value in a, return the index of target
func bsearch(a [][]float64, value float64, dimension int) int {
length := len(a)
if 0 == length {
return -1
}
if dimension >= len(a[0]) {
return -1
}
low, high := 0, length-1
for low <= high {
mid := low + ((high - low) >> 1)
if value >= a[mid][dimension] {
if mid == length-1 {
return -1
}
if a[mid+1][dimension] > value {
return mid + 1
}
low = mid + 1
} else {
if 0 == mid || a[mid-1][dimension] < value {
return mid
}
high = mid - 1
}
}
return -1
}
// Decimal return decimal value
func Decimal(value float64) float64 {
value, _ = strconv.ParseFloat(fmt.Sprintf("%.3f", value), 64)
return value
} | pkg/divide_and_conquer/negative_sequence_degree/find_the_nearest/find_the_nearest.go | 0.586049 | 0.4881 | find_the_nearest.go | starcoder |
package refer
type References struct {
references []*Reference
}
func NewEmptyReferences() *References {
return &References{
references: make([]*Reference, 0, 10),
}
}
func NewReferences(tuples []interface{}) *References {
c := NewEmptyReferences()
for index := 0; index < len(tuples); index += 2 {
if index+1 >= len(tuples) {
break
}
c.Put(tuples[index], tuples[index+1])
}
return c
}
func (c *References) Put(locator interface{}, component interface{}) {
if component == nil {
panic("Component cannot be null")
}
reference := NewReference(locator, component)
c.references = append(c.references, reference)
}
func (c *References) Remove(locator interface{}) interface{} {
if locator == nil {
return nil
}
for index := len(c.references) - 1; index >= 0; index-- {
reference := c.references[index]
if reference.Match(locator) {
c.references = append(c.references[:index], c.references[index+1:]...)
return reference.Component()
}
}
return nil
}
func (c *References) RemoveAll(locator interface{}) []interface{} {
components := make([]interface{}, 0, 5)
if locator == nil {
return components
}
for index := len(c.references) - 1; index >= 0; index-- {
reference := c.references[index]
if reference.Match(locator) {
c.references = append(c.references[:index], c.references[index+1:]...)
components = append(components, reference.Component())
}
}
return components
}
func (c *References) GetAllLocators() []interface{} {
components := make([]interface{}, len(c.references), len(c.references))
for index, reference := range c.references {
components[index] = reference.Locator()
}
return components
}
func (c *References) GetAll() []interface{} {
components := make([]interface{}, len(c.references), len(c.references))
for index, reference := range c.references {
components[index] = reference.Component()
}
return components
}
func (c *References) GetOneOptional(locator interface{}) interface{} {
components, err := c.Find(locator, true)
if err != nil || len(components) == 0 {
return nil
}
return components[0]
}
func (c *References) GetOneRequired(locator interface{}) (interface{}, error) {
components, err := c.Find(locator, true)
if err != nil || len(components) == 0 {
return nil, err
}
return components[0], nil
}
func (c *References) GetOptional(locator interface{}) []interface{} {
components, _ := c.Find(locator, false)
return components
}
func (c *References) GetRequired(locator interface{}) ([]interface{}, error) {
return c.Find(locator, true)
}
func (c *References) Find(locator interface{}, required bool) ([]interface{}, error) {
if locator == nil {
panic("Locator cannot be null")
}
components := make([]interface{}, 0, 2)
// Search all references
for index := len(c.references) - 1; index >= 0; index-- {
reference := c.references[index]
if reference.Match(locator) {
component := reference.Component()
components = append(components, component)
}
}
if len(components) == 0 && required {
err := NewReferenceError("", locator)
return components, err
}
return components, nil
}
func NewReferencesFromTuples(tuples ...interface{}) *References {
return NewReferences(tuples)
} | refer/References.go | 0.750461 | 0.448185 | References.go | starcoder |
package native
type State = int
const (
NEXT State = iota + 1
SKIP
FINISH
)
type MapContainer struct {
data map[string]bool
Next func(index string, value bool) (string, bool, State)
}
func MapIterator(data map[string]bool) *MapContainer {
return &MapContainer{
data: data,
Next: func(index string, value bool) (string, bool, State) {
return index, value, NEXT
},
}
}
func (o *MapContainer) Filter(f func(string, bool) bool) *MapContainer {
next := o.Next
o.Next = func(i string, v bool) (index string, value bool, state State) {
if index, value, state = next(i, v); state == NEXT && !f(index, value) {
state = SKIP
}
return
}
return o
}
func (o *MapContainer) Take(count int) *MapContainer {
next := o.Next
counter := 0
o.Next = func(i string, v bool) (index string, value bool, state State) {
if index, value, state = next(i, v); state == NEXT {
if counter >= count {
state = FINISH
}
counter++
}
return
}
return o
}
func (o *MapContainer) Range(fn func(index string, value bool)) {
for index, value := range o.data {
switch index, value, status := o.Next(index, value); status {
case SKIP:
continue
case FINISH:
return
case NEXT:
fn(index, value)
}
}
}
func (o *MapContainer) Len() (count int) {
o.Range(func(_ string, _ bool) {
count++
})
return
}
type UintContainer struct {
data []uint
Next func(index int, value uint) (int, uint, State)
}
func UintIterator(data []uint) *UintContainer {
return &UintContainer{
data: data,
Next: func(index int, value uint) (int, uint, State) {
return index, value, NEXT
},
}
}
func (o *UintContainer) Filter(f func(int, uint) bool) *UintContainer {
next := o.Next
o.Next = func(i int, v uint) (index int, value uint, state State) {
if index, value, state = next(i, v); state == NEXT && !f(index, value) {
state = SKIP
}
return
}
return o
}
func (o *UintContainer) Take(count int) *UintContainer {
next := o.Next
counter := 0
o.Next = func(i int, v uint) (index int, value uint, state State) {
if index, value, state = next(i, v); state == NEXT {
if counter >= count {
state = FINISH
}
counter++
}
return
}
return o
}
func (o *UintContainer) Range(fn func(index int, value uint)) {
for index, value := range o.data {
switch index, value, status := o.Next(index, value); status {
case SKIP:
continue
case FINISH:
return
case NEXT:
fn(index, value)
}
}
}
func (o *UintContainer) Mul() (mul uint) {
mul = 1
o.Range(func(index int, value uint) {
mul *= value
})
return
}
func (o *UintContainer) Len() (count int) {
o.Range(func(_ int, _ uint) {
count++
})
return
}
func Range(begin, end int) <-chan int {
yield := make(chan int)
go func() {
for ; begin < end; begin++ {
yield <- begin
}
close(yield)
}()
return yield
} | iterator.go | 0.631026 | 0.489809 | iterator.go | starcoder |
package datatype
import (
"fmt"
"github.com/i-sevostyanov/NanoDB/internal/sql"
)
type Text struct {
value string
}
func NewText(v string) Text {
return Text{value: v}
}
func (t Text) Raw() interface{} {
return t.value
}
func (t Text) DataType() sql.DataType {
return sql.Text
}
func (t Text) Compare(v sql.Value) (sql.CompareType, error) {
switch value := v.Raw().(type) {
case string:
switch {
case t.value < value:
return sql.Less, nil
case t.value > value:
return sql.Greater, nil
default:
return sql.Equal, nil
}
case nil:
return sql.Greater, nil
default:
return sql.Equal, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) UnaryPlus() (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) UnaryMinus() (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) Add(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case string:
return Text{value: t.value + value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) Sub(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) Mul(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) Div(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) Pow(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) Mod(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) Equal(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case string:
return Boolean{value: t.value == value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) NotEqual(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case string:
return Boolean{value: t.value != value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) GreaterThan(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case string:
return Boolean{value: t.value > value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) LessThan(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case string:
return Boolean{value: t.value < value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) GreaterOrEqual(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case string:
return Boolean{value: t.value > value || t.value == value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) LessOrEqual(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case string:
return Boolean{value: t.value < value || t.value == value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (t Text) And(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (t Text) Or(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
} | internal/sql/datatype/text.go | 0.689201 | 0.486636 | text.go | starcoder |
package interpreter
import (
"fmt"
"github.com/smackem/ylang/internal/lang"
"reflect"
)
type Number lang.Number
func (n Number) Compare(other Value) (Value, error) {
if r, ok := other.(Number); ok {
return n - r, nil
}
return nil, nil
}
func (n Number) Add(other Value) (Value, error) {
switch r := other.(type) {
case Number:
return Number(n + r), nil
case Point:
return Point{int(n + Number(r.X) + 0.5), int(n + Number(r.Y) + 0.5)}, nil
case Color:
nn := lang.Number(n)
return Color(lang.NewRgba(nn+r.R, nn+r.G, nn+r.B, r.A)), nil
}
return nil, fmt.Errorf("type mismatch: expected number + number or number + color, found number + %s", reflect.TypeOf(other))
}
func (n Number) Sub(other Value) (Value, error) {
switch r := other.(type) {
case Number:
return Number(n - r), nil
case Point:
return Point{int(n - Number(r.X) + 0.5), int(n - Number(r.Y) + 0.5)}, nil
case Color:
nn := lang.Number(n)
return Color(lang.NewRgba(nn-r.R, nn-r.G, nn-r.B, r.A)), nil
}
return nil, fmt.Errorf("type mismatch: expected number - number or number - color, found number - %s", reflect.TypeOf(other))
}
func (n Number) Mul(other Value) (Value, error) {
switch r := other.(type) {
case Number:
return Number(n * r), nil
case Point:
return Point{int(n*Number(r.X) + 0.5), int(n*Number(r.Y) + 0.5)}, nil
case Color:
rc := lang.Color(r)
nn := lang.Number(n)
return Color(lang.NewSrgba(nn*rc.ScR(), nn*rc.ScG(), nn*rc.ScB(), rc.ScA())), nil
}
return nil, fmt.Errorf("type mismatch: expected number * number or number * color, found number + %s", reflect.TypeOf(other))
}
func (n Number) Div(other Value) (Value, error) {
switch r := other.(type) {
case Number:
return Number(n / r), nil
case Point:
return Point{int(n/Number(r.X) + 0.5), int(n/Number(r.Y) + 0.5)}, nil
case Color:
nn := lang.Number(n)
return Color(lang.NewRgba(nn/r.R, nn/r.G, nn/r.B, r.A)), nil
}
return nil, fmt.Errorf("type mismatch: expected number / number, found number / %s", reflect.TypeOf(other))
}
func (n Number) Mod(other Value) (Value, error) {
if r, ok := other.(Number); ok {
return Number(int(n+0.5) % int(r+0.5)), nil
}
return nil, fmt.Errorf("type mismatch: expected number / number, found number / %s", reflect.TypeOf(other))
}
func (n Number) In(other Value) (Value, error) {
if k, ok := other.(Kernel); ok {
for _, kn := range k.Values {
if kn == lang.Number(n) {
return Boolean(true), nil
}
}
return falseVal, nil
}
return nil, fmt.Errorf("type mismatch: 'number In %s' Not supported", reflect.TypeOf(other))
}
func (n Number) Neg() (Value, error) {
return Number(-n), nil
}
func (n Number) Not() (Value, error) {
return nil, fmt.Errorf("type mismatch: found 'Not number' instead of 'Not bool'")
}
func (n Number) At(bitmap BitmapContext) (Value, error) {
return nil, fmt.Errorf("type mismatch: found '@number' instead of '@point'")
}
func (n Number) Property(ident string) (Value, error) {
return baseProperty(n, ident)
}
func (n Number) PrintStr() string {
return fmt.Sprintf("%g", n)
}
func (n Number) Iterate(visit func(Value) error) error {
return fmt.Errorf("cannot Iterate over number")
}
func (n Number) Index(index Value) (Value, error) {
return nil, fmt.Errorf("type mismatch: number[Index] Not supported")
}
func (n Number) IndexRange(lower, upper Value) (Value, error) {
return nil, fmt.Errorf("type mismatch: number[lower..upper] Not supported")
}
// implement sort.Interface for number slice
type numberSlice []Number
func (p numberSlice) Len() int { return len(p) }
func (p numberSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p numberSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (n Number) IndexAssign(index Value, val Value) error {
return fmt.Errorf("type mismatch: number[%s] Not supported", reflect.TypeOf(index))
}
func (n Number) RuntimeTypeName() string {
return "number"
}
func (n Number) Concat(val Value) (Value, error) {
return nil, fmt.Errorf("type mismatch: number :: [%s] Not supported", reflect.TypeOf(val))
} | internal/interpreter/number.go | 0.819388 | 0.42913 | number.go | starcoder |
package newznab
import (
"fmt"
"strconv"
"strings"
)
// Parameters added to the URL to make a query.
type Param struct {
Name string
Value string
}
// Album returns a Param that restricts the search of music to a specific album title.
func Album(a string) Param {
return Param{
Name: "album",
Value: a,
}
}
// Apikey returns a Param that defines the key used to access the API.
func Apikey(k string) Param {
return Param{
Name: "apikey",
Value: k,
}
}
// Artist returns a Param that restricts the search of music to a specific artist.
func Artist(a string) Param {
return Param{
Name: "artist",
Value: a,
}
}
// Author returns a Param that restricts the search of e-books to a specific author.
func Author(a string) Param {
return Param{
Name: "author",
Value: a,
}
}
// Categories returns a Param that defines the media categories to restrict the search within.
func Categories(cats ...Category) Param {
c := make([]string, len(cats))
for i := range cats {
c[i] = cats[i].id
}
return Param{
Name: "cat",
Value: strings.Join(c, ","),
}
}
// Episode returns a Param that restricts the search of TV shows to a specific episode
func Episode(e int) Param {
return Param{
Name: "episode",
Value: fmt.Sprintf("E%02d", e),
}
}
// Genre returns a Param that restricts the search to a specific genre of media
func Genre(g string) Param {
return Param{
Name: "genre",
Value: g,
}
}
// ImdbId returns a Param that contains the IMDB ID of the media to search for.
func ImdbId(i int) Param {
return Param{
Name: "imdbid",
Value: strconv.Itoa(i),
}
}
// Json returns a Param that directs the service to produce JSON formatted output.
func Json() Param {
return Param{
Name: "o",
Value: "json",
}
}
// Label returns a Param that restricts the search of music to a specific publisher or label name.
func Label(l string) Param {
return Param{
Name: "label",
Value: l,
}
}
// Limit returns a Param that defines the maximum number of results to return.
func Limit(l int) Param {
return Param{
Name: "limit",
Value: strconv.Itoa(l),
}
}
// MaxAge returns a Param that directs the service to return only results that were uploaded in the last "m" days.
func MaxAge(m int) Param {
return Param{
Name: "maxage",
Value: strconv.Itoa(m),
}
}
// Offset returns a Param that directs the service to return results starting a the specified offset. This is useful
// when a query would return more results than the service is able to provide in a single response. The consumer of
// this library can retrieve the next batch by re-running the same query, but with an offset.
func Offset(o int) Param {
return Param{
Name: "offset",
Value: strconv.Itoa(o),
}
}
// Query returns a Param with the term to search for.
func Query(q string) Param {
return Param{
Name: "q",
Value: q,
}
}
// Season returns a Param that restricts the search of TV shows to a specific season
func Season(s int) Param {
return Param{
Name: "season",
Value: fmt.Sprintf("S%02d", s),
}
}
// Title returns a Param that restricts the search of e-books to a specific title.
func Title(t string) Param {
return Param{
Name: "title",
Value: t,
}
}
// Track returns a Param that restricts the search of music to a specific track name.
func Track(t string) Param {
return Param{
Name: "track",
Value: t,
}
}
// Type returns a Param that defines the type of request being made.
func Type(t string) Param {
return Param{
Name: "t",
Value: t,
}
}
// Xml returns a Param that directs the service to produce XML formatted output.
func Xml() Param {
return Param{
Name: "o",
Value: "xml",
}
}
// Year returns a Param that restricts the search of music to a specific year.
func Year(y string) Param {
return Param{
Name: "year",
Value: y,
}
} | param.go | 0.778102 | 0.684027 | param.go | starcoder |
package main
import (
"github.com/gen2brain/raylib-go/raylib"
)
var (
maxBuildings int = 100
)
func main() {
screenWidth := int32(800)
screenHeight := int32(450)
raylib.InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera")
player := raylib.NewRectangle(400, 280, 40, 40)
buildings := make([]raylib.Rectangle, maxBuildings)
buildColors := make([]raylib.Color, maxBuildings)
spacing := float32(0)
for i := 0; i < maxBuildings; i++ {
r := raylib.Rectangle{}
r.Width = float32(raylib.GetRandomValue(50, 200))
r.Height = float32(raylib.GetRandomValue(100, 800))
r.Y = float32(screenHeight) - 130 - r.Height
r.X = -6000 + spacing
spacing += r.Width
c := raylib.NewColor(byte(raylib.GetRandomValue(200, 240)), byte(raylib.GetRandomValue(200, 240)), byte(raylib.GetRandomValue(200, 250)), byte(255))
buildings[i] = r
buildColors[i] = c
}
camera := raylib.Camera2D{}
camera.Target = raylib.NewVector2(float32(player.X+20), float32(player.Y+20))
camera.Offset = raylib.NewVector2(0, 0)
camera.Rotation = 0.0
camera.Zoom = 1.0
raylib.SetTargetFPS(30)
for !raylib.WindowShouldClose() {
if raylib.IsKeyDown(raylib.KeyRight) {
player.X += 2 // Player movement
camera.Offset.X -= 2 // Camera displacement with player movement
} else if raylib.IsKeyDown(raylib.KeyLeft) {
player.X -= 2 // Player movement
camera.Offset.X += 2 // Camera displacement with player movement
}
// Camera target follows player
camera.Target = raylib.NewVector2(float32(player.X+20), float32(player.Y+20))
// Camera rotation controls
if raylib.IsKeyDown(raylib.KeyA) {
camera.Rotation--
} else if raylib.IsKeyDown(raylib.KeyS) {
camera.Rotation++
}
// Limit camera rotation to 80 degrees (-40 to 40)
if camera.Rotation > 40 {
camera.Rotation = 40
} else if camera.Rotation < -40 {
camera.Rotation = -40
}
// Camera zoom controls
camera.Zoom += float32(raylib.GetMouseWheelMove()) * 0.05
if camera.Zoom > 3.0 {
camera.Zoom = 3.0
} else if camera.Zoom < 0.1 {
camera.Zoom = 0.1
}
// Camera reset (zoom and rotation)
if raylib.IsKeyPressed(raylib.KeyR) {
camera.Zoom = 1.0
camera.Rotation = 0.0
}
raylib.BeginDrawing()
raylib.ClearBackground(raylib.RayWhite)
raylib.BeginMode2D(camera)
raylib.DrawRectangle(-6000, 320, 13000, 8000, raylib.DarkGray)
for i := 0; i < maxBuildings; i++ {
raylib.DrawRectangleRec(buildings[i], buildColors[i])
}
raylib.DrawRectangleRec(player, raylib.Red)
raylib.DrawRectangle(int32(camera.Target.X), -500, 1, screenHeight*4, raylib.Green)
raylib.DrawRectangle(-500, int32(camera.Target.Y), screenWidth*4, 1, raylib.Green)
raylib.EndMode2D()
raylib.DrawText("SCREEN AREA", 640, 10, 20, raylib.Red)
raylib.DrawRectangle(0, 0, screenWidth, 5, raylib.Red)
raylib.DrawRectangle(0, 5, 5, screenHeight-10, raylib.Red)
raylib.DrawRectangle(screenWidth-5, 5, 5, screenHeight-10, raylib.Red)
raylib.DrawRectangle(0, screenHeight-5, screenWidth, 5, raylib.Red)
raylib.DrawRectangle(10, 10, 250, 113, raylib.Fade(raylib.SkyBlue, 0.5))
raylib.DrawRectangleLines(10, 10, 250, 113, raylib.Blue)
raylib.DrawText("Free 2d camera controls:", 20, 20, 10, raylib.Black)
raylib.DrawText("- Right/Left to move Offset", 40, 40, 10, raylib.DarkGray)
raylib.DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, raylib.DarkGray)
raylib.DrawText("- A / S to Rotate", 40, 80, 10, raylib.DarkGray)
raylib.DrawText("- R to reset Zoom and Rotation", 40, 100, 10, raylib.DarkGray)
raylib.EndDrawing()
}
raylib.CloseWindow()
} | examples/core/2d_camera/main.go | 0.556641 | 0.41182 | main.go | starcoder |
package domain
import (
"fmt"
"net/http"
"github.com/dynastymasra/cartographer/config"
"github.com/labstack/gommon/random"
scalar "github.com/dynastymasra/cookbook/graphql"
"github.com/graphql-go/graphql"
)
var (
countryField = graphql.Fields{
"id": &graphql.Field{
Type: scalar.UUID,
},
"name": &graphql.Field{
Type: graphql.String,
},
"dialCode": &graphql.Field{
Type: graphql.String,
},
"ISO3166Alpha2": &graphql.Field{
Type: graphql.String,
},
"ISO3166Alpha3": &graphql.Field{
Type: graphql.String,
},
"ISO3166Numeric": &graphql.Field{
Type: graphql.String,
},
"flags": &graphql.Field{
Type: flagType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var country Country
switch c := p.Source.(type) {
case *Country:
country = *c
case Country:
country = c
}
if err := country.Unmarshal(); err != nil {
return nil, config.NewError(http.StatusInternalServerError, "", err.Error())
}
return country.Flag, nil
},
},
"currencies": &graphql.Field{
Type: graphql.NewList(CurrencyType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var currencies []*Currency
switch country := p.Source.(type) {
case *Country:
currencies = country.Currencies
case Country:
currencies = country.Currencies
}
return currencies, nil
},
},
"createdAt": &graphql.Field{
Type: graphql.DateTime,
},
"updatedAt": &graphql.Field{
Type: graphql.DateTime,
},
"provinces": &graphql.Field{
Type: graphql.NewList(RegionType(ProvinceNode)),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var provinces []*Region
switch country := p.Source.(type) {
case Country:
provinces = country.Provinces
case *Country:
provinces = country.Provinces
}
return provinces, nil
},
},
}
flagType = graphql.NewObject(graphql.ObjectConfig{
Name: "Flag",
Description: "Country flags",
Fields: graphql.Fields{
"flat": &graphql.Field{
Type: sizeType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var size Size
switch flag := p.Source.(type) {
case *Flag:
size = flag.Flat
case Flag:
size = flag.Flat
}
return size, nil
},
},
"shiny": &graphql.Field{
Type: sizeType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var size Size
switch flag := p.Source.(type) {
case *Flag:
size = flag.Shiny
case Flag:
size = flag.Shiny
}
return size, nil
},
},
},
})
sizeType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Size",
Description: "Size of countries flags",
Fields: graphql.Fields{
"sixteen": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var sixteen string
switch size := p.Source.(type) {
case *Size:
sixteen = size.Sixteen
case Size:
sixteen = size.Sixteen
}
return sixteen, nil
},
},
"twentyFour": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var twentyFour string
switch size := p.Source.(type) {
case *Size:
twentyFour = size.TwentyFour
case Size:
twentyFour = size.TwentyFour
}
return twentyFour, nil
},
},
"thirtyTwo": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var thirtyTwo string
switch size := p.Source.(type) {
case *Size:
thirtyTwo = size.ThirtyTwo
case Size:
thirtyTwo = size.ThirtyTwo
}
return thirtyTwo, nil
},
},
"fortyEight": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var fortyEight string
switch size := p.Source.(type) {
case *Size:
fortyEight = size.FortyEight
case Size:
fortyEight = size.FortyEight
}
return fortyEight, nil
},
},
"sixtyFour": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var sixtyFour string
switch size := p.Source.(type) {
case *Size:
sixtyFour = size.SixtyFour
case Size:
sixtyFour = size.SixtyFour
}
return sixtyFour, nil
},
},
},
})
currencyField = graphql.Fields{
"id": &graphql.Field{
Type: scalar.UUID,
},
"ISO4217Name": &graphql.Field{
Type: graphql.String,
},
"ISO4217Alphabetic": &graphql.Field{
Type: graphql.String,
},
"ISO4217Numeric": &graphql.Field{
Type: graphql.String,
},
"ISO4217MinorUnit": &graphql.Field{
Type: graphql.String,
},
"createdAt": &graphql.Field{
Type: graphql.DateTime,
},
"updatedAt": &graphql.Field{
Type: graphql.DateTime,
},
}
RegionArgs = graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: scalar.UUID,
},
"code": &graphql.ArgumentConfig{
Type: graphql.String,
},
}
ListRegionArgs = graphql.FieldConfigArgument{
"code": &graphql.ArgumentConfig{
Type: graphql.String,
},
"limit": &graphql.ArgumentConfig{
Type: graphql.Int,
DefaultValue: config.Limit,
},
"offset": &graphql.ArgumentConfig{
Type: graphql.Int,
DefaultValue: config.Offset,
},
"province": &graphql.ArgumentConfig{
Type: RegionInput(ProvinceNode),
},
"city": &graphql.ArgumentConfig{
Type: RegionInput(CityNode),
},
"regency": &graphql.ArgumentConfig{
Type: RegionInput(RegencyNode),
},
"district": &graphql.ArgumentConfig{
Type: RegionInput(DistrictNode),
},
"country": &graphql.ArgumentConfig{
Type: CountryInput,
},
}
regionFields = graphql.Fields{
"id": &graphql.Field{
Type: scalar.UUID,
},
"name": &graphql.Field{
Type: graphql.String,
},
"code": &graphql.Field{
Type: graphql.String,
},
"createdAt": &graphql.Field{
Type: graphql.DateTime,
},
"updatedAt": &graphql.Field{
Type: graphql.DateTime,
},
"provinces": &graphql.Field{
Type: graphql.NewList(RegionType(ProvinceNode)),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var provinces []*Region
switch region := p.Source.(type) {
case *Region:
provinces = region.Provinces
case Region:
provinces = region.Provinces
}
return provinces, nil
},
},
"cities": &graphql.Field{
Type: graphql.NewList(RegionType(CityNode)),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var cities []*Region
switch region := p.Source.(type) {
case *Region:
cities = region.Cities
case Region:
cities = region.Cities
}
return cities, nil
},
},
"regencies": &graphql.Field{
Type: graphql.NewList(RegionType(RegencyNode)),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var regencies []*Region
switch region := p.Source.(type) {
case *Region:
regencies = region.Regencies
case Region:
regencies = region.Regencies
}
return regencies, nil
},
},
"districts": &graphql.Field{
Type: graphql.NewList(RegionType(DistrictNode)),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var districts []*Region
switch region := p.Source.(type) {
case *Region:
districts = region.Districts
case Region:
districts = region.Districts
}
return districts, nil
},
},
"villages": &graphql.Field{
Type: graphql.NewList(RegionType(VillageNode)),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
var villages []*Region
switch region := p.Source.(type) {
case *Region:
villages = region.Villages
case Region:
villages = region.Villages
}
return villages, nil
},
},
}
ProvinceType = graphql.NewObject(graphql.ObjectConfig{
Name: ProvinceNode,
Description: "Province administrative division",
Fields: regionFields,
})
CityType = graphql.NewObject(graphql.ObjectConfig{
Name: CityNode,
Description: "City administrative division",
Fields: regionFields,
})
RegencyType = graphql.NewObject(graphql.ObjectConfig{
Name: RegencyNode,
Description: "Regency administrative division",
Fields: regionFields,
})
DistrictType = graphql.NewObject(graphql.ObjectConfig{
Name: DistrictNode,
Description: "District administrative division",
Fields: regionFields,
})
VillageType = graphql.NewObject(graphql.ObjectConfig{
Name: VillageNode,
Description: "Village administrative division",
Fields: regionFields,
})
CurrencyType = graphql.NewObject(graphql.ObjectConfig{
Name: "Currency",
Description: "Currency information with ISO 4217",
Fields: currencyField,
})
CurrencyInput = graphql.NewInputObject(graphql.InputObjectConfig{
Name: fmt.Sprintf("Currency_%s", random.String(5, random.Alphabetic)),
Description: "Currency input arguments",
Fields: graphql.InputObjectConfigFieldMap{
"id": &graphql.InputObjectFieldConfig{
Type: scalar.UUID,
},
"ISO4217Name": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"ISO4217Alphabetic": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"ISO4217Numeric": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"ISO4217MinorUnit": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
},
})
CountryType = graphql.NewObject(graphql.ObjectConfig{
Name: "Country",
Description: "Country information with ISO 3166",
Fields: countryField,
})
CountryInput = graphql.NewInputObject(graphql.InputObjectConfig{
Name: "Country",
Description: "Country input arguments",
Fields: graphql.InputObjectConfigFieldMap{
"id": &graphql.InputObjectFieldConfig{
Type: scalar.UUID,
},
"name": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"dialCode": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"ISO3166Alpha2": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"ISO3166Alpha3": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"ISO3166Numeric": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"currency": &graphql.InputObjectFieldConfig{
Type: CurrencyInput,
},
},
})
CountryArgs = graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: scalar.UUID,
},
"ISO3166Alpha2": &graphql.ArgumentConfig{
Type: graphql.String,
},
"ISO3166Alpha3": &graphql.ArgumentConfig{
Type: graphql.String,
},
"ISO3166Numeric": &graphql.ArgumentConfig{
Type: graphql.String,
},
}
ListCountryArgs = graphql.FieldConfigArgument{
"limit": &graphql.ArgumentConfig{
Type: graphql.Int,
DefaultValue: config.Limit,
},
"offset": &graphql.ArgumentConfig{
Type: graphql.Int,
DefaultValue: config.Offset,
},
"dialCode": &graphql.ArgumentConfig{
Type: graphql.String,
},
"currencies": &graphql.ArgumentConfig{
Type: graphql.NewList(CurrencyInput),
},
}
)
func RegionInput(name string) *graphql.InputObject {
return graphql.NewInputObject(graphql.InputObjectConfig{
Name: fmt.Sprintf("%s_%s", name, random.New().String(5, random.Alphabetic)),
Description: fmt.Sprintf("Region type of %s", name),
Fields: graphql.InputObjectConfigFieldMap{
"id": &graphql.InputObjectFieldConfig{
Type: scalar.UUID,
},
"name": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
"code": &graphql.InputObjectFieldConfig{
Type: graphql.String,
},
},
})
}
func RegionType(name string) *graphql.Object {
return graphql.NewObject(graphql.ObjectConfig{
Name: fmt.Sprintf("%s_%s", name, random.New().String(5, random.Alphabetic)),
Description: fmt.Sprintf("Region type of %s", name),
Fields: graphql.Fields{
"id": &graphql.Field{
Type: scalar.UUID,
},
"name": &graphql.Field{
Type: graphql.String,
},
"code": &graphql.Field{
Type: graphql.String,
},
"createdAt": &graphql.Field{
Type: graphql.DateTime,
},
"updatedAt": &graphql.Field{
Type: graphql.DateTime,
},
},
})
} | domain/graphql.go | 0.554229 | 0.437884 | graphql.go | starcoder |
package brotli
/* Copyright 2015 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
/* Greedy block splitter for one block category (literal, command or distance).
*/
type blockSplitterDistance struct {
alphabet_size_ uint
min_block_size_ uint
split_threshold_ float64
num_blocks_ uint
split_ *blockSplit
histograms_ []histogramDistance
histograms_size_ *uint
target_block_size_ uint
block_size_ uint
curr_histogram_ix_ uint
last_histogram_ix_ [2]uint
last_entropy_ [2]float64
merge_last_count_ uint
}
func initBlockSplitterDistance(self *blockSplitterDistance, alphabet_size uint, min_block_size uint, split_threshold float64, num_symbols uint, split *blockSplit, histograms *[]histogramDistance, histograms_size *uint) {
var max_num_blocks uint = num_symbols/min_block_size + 1
var max_num_types uint = brotli_min_size_t(max_num_blocks, maxNumberOfBlockTypes+1)
/* We have to allocate one more histogram than the maximum number of block
types for the current histogram when the meta-block is too big. */
self.alphabet_size_ = alphabet_size
self.min_block_size_ = min_block_size
self.split_threshold_ = split_threshold
self.num_blocks_ = 0
self.split_ = split
self.histograms_size_ = histograms_size
self.target_block_size_ = min_block_size
self.block_size_ = 0
self.curr_histogram_ix_ = 0
self.merge_last_count_ = 0
brotli_ensure_capacity_uint8_t(&split.types, &split.types_alloc_size, max_num_blocks)
brotli_ensure_capacity_uint32_t(&split.lengths, &split.lengths_alloc_size, max_num_blocks)
self.split_.num_blocks = max_num_blocks
*histograms_size = max_num_types
if histograms == nil || cap(*histograms) < int(*histograms_size) {
*histograms = make([]histogramDistance, *histograms_size)
} else {
*histograms = (*histograms)[:*histograms_size]
}
self.histograms_ = *histograms
/* Clear only current histogram. */
histogramClearDistance(&self.histograms_[0])
self.last_histogram_ix_[1] = 0
self.last_histogram_ix_[0] = self.last_histogram_ix_[1]
}
/* Does either of three things:
(1) emits the current block with a new block type;
(2) emits the current block with the type of the second last block;
(3) merges the current block with the last block. */
func blockSplitterFinishBlockDistance(self *blockSplitterDistance, is_final bool) {
var split *blockSplit = self.split_
var last_entropy []float64 = self.last_entropy_[:]
var histograms []histogramDistance = self.histograms_
self.block_size_ = brotli_max_size_t(self.block_size_, self.min_block_size_)
if self.num_blocks_ == 0 {
/* Create first block. */
split.lengths[0] = uint32(self.block_size_)
split.types[0] = 0
last_entropy[0] = bitsEntropy(histograms[0].data_[:], self.alphabet_size_)
last_entropy[1] = last_entropy[0]
self.num_blocks_++
split.num_types++
self.curr_histogram_ix_++
if self.curr_histogram_ix_ < *self.histograms_size_ {
histogramClearDistance(&histograms[self.curr_histogram_ix_])
}
self.block_size_ = 0
} else if self.block_size_ > 0 {
var entropy float64 = bitsEntropy(histograms[self.curr_histogram_ix_].data_[:], self.alphabet_size_)
var combined_histo [2]histogramDistance
var combined_entropy [2]float64
var diff [2]float64
var j uint
for j = 0; j < 2; j++ {
var last_histogram_ix uint = self.last_histogram_ix_[j]
combined_histo[j] = histograms[self.curr_histogram_ix_]
histogramAddHistogramDistance(&combined_histo[j], &histograms[last_histogram_ix])
combined_entropy[j] = bitsEntropy(combined_histo[j].data_[0:], self.alphabet_size_)
diff[j] = combined_entropy[j] - entropy - last_entropy[j]
}
if split.num_types < maxNumberOfBlockTypes && diff[0] > self.split_threshold_ && diff[1] > self.split_threshold_ {
/* Create new block. */
split.lengths[self.num_blocks_] = uint32(self.block_size_)
split.types[self.num_blocks_] = byte(split.num_types)
self.last_histogram_ix_[1] = self.last_histogram_ix_[0]
self.last_histogram_ix_[0] = uint(byte(split.num_types))
last_entropy[1] = last_entropy[0]
last_entropy[0] = entropy
self.num_blocks_++
split.num_types++
self.curr_histogram_ix_++
if self.curr_histogram_ix_ < *self.histograms_size_ {
histogramClearDistance(&histograms[self.curr_histogram_ix_])
}
self.block_size_ = 0
self.merge_last_count_ = 0
self.target_block_size_ = self.min_block_size_
} else if diff[1] < diff[0]-20.0 {
split.lengths[self.num_blocks_] = uint32(self.block_size_)
split.types[self.num_blocks_] = split.types[self.num_blocks_-2]
/* Combine this block with second last block. */
var tmp uint = self.last_histogram_ix_[0]
self.last_histogram_ix_[0] = self.last_histogram_ix_[1]
self.last_histogram_ix_[1] = tmp
histograms[self.last_histogram_ix_[0]] = combined_histo[1]
last_entropy[1] = last_entropy[0]
last_entropy[0] = combined_entropy[1]
self.num_blocks_++
self.block_size_ = 0
histogramClearDistance(&histograms[self.curr_histogram_ix_])
self.merge_last_count_ = 0
self.target_block_size_ = self.min_block_size_
} else {
/* Combine this block with last block. */
split.lengths[self.num_blocks_-1] += uint32(self.block_size_)
histograms[self.last_histogram_ix_[0]] = combined_histo[0]
last_entropy[0] = combined_entropy[0]
if split.num_types == 1 {
last_entropy[1] = last_entropy[0]
}
self.block_size_ = 0
histogramClearDistance(&histograms[self.curr_histogram_ix_])
self.merge_last_count_++
if self.merge_last_count_ > 1 {
self.target_block_size_ += self.min_block_size_
}
}
}
if is_final {
*self.histograms_size_ = split.num_types
split.num_blocks = self.num_blocks_
}
}
/* Adds the next symbol to the current histogram. When the current histogram
reaches the target size, decides on merging the block. */
func blockSplitterAddSymbolDistance(self *blockSplitterDistance, symbol uint) {
histogramAddDistance(&self.histograms_[self.curr_histogram_ix_], symbol)
self.block_size_++
if self.block_size_ == self.target_block_size_ {
blockSplitterFinishBlockDistance(self, false) /* is_final = */
}
} | vendor/github.com/andybalholm/brotli/metablock_distance.go | 0.693473 | 0.477737 | metablock_distance.go | starcoder |
package data
import (
"reflect"
"github.com/zeroshade/go-drill/internal/rpc/proto/exec/shared"
)
// Int64 vector
type Int64Vector struct {
vector
values []int64
meta *shared.SerializedField
}
func (Int64Vector) Type() reflect.Type {
return reflect.TypeOf(int64(0))
}
func (Int64Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Int64Vector) Len() int {
return int(len(v.values))
}
func (v *Int64Vector) Get(index uint) int64 {
return v.values[index]
}
func (v *Int64Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewInt64Vector(data []byte, meta *shared.SerializedField) *Int64Vector {
return &Int64Vector{
vector: vector{rawData: data},
values: Int64Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableInt64Vector struct {
*Int64Vector
nullByteMap
}
func (nv *NullableInt64Vector) Get(index uint) *int64 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableInt64Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableInt64Vector(data []byte, meta *shared.SerializedField) *NullableInt64Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableInt64Vector{
NewInt64Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Int32 vector
type Int32Vector struct {
vector
values []int32
meta *shared.SerializedField
}
func (Int32Vector) Type() reflect.Type {
return reflect.TypeOf(int32(0))
}
func (Int32Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Int32Vector) Len() int {
return int(len(v.values))
}
func (v *Int32Vector) Get(index uint) int32 {
return v.values[index]
}
func (v *Int32Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewInt32Vector(data []byte, meta *shared.SerializedField) *Int32Vector {
return &Int32Vector{
vector: vector{rawData: data},
values: Int32Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableInt32Vector struct {
*Int32Vector
nullByteMap
}
func (nv *NullableInt32Vector) Get(index uint) *int32 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableInt32Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableInt32Vector(data []byte, meta *shared.SerializedField) *NullableInt32Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableInt32Vector{
NewInt32Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Float64 vector
type Float64Vector struct {
vector
values []float64
meta *shared.SerializedField
}
func (Float64Vector) Type() reflect.Type {
return reflect.TypeOf(float64(0))
}
func (Float64Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Float64Vector) Len() int {
return int(len(v.values))
}
func (v *Float64Vector) Get(index uint) float64 {
return v.values[index]
}
func (v *Float64Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewFloat64Vector(data []byte, meta *shared.SerializedField) *Float64Vector {
return &Float64Vector{
vector: vector{rawData: data},
values: Float64Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableFloat64Vector struct {
*Float64Vector
nullByteMap
}
func (nv *NullableFloat64Vector) Get(index uint) *float64 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableFloat64Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableFloat64Vector(data []byte, meta *shared.SerializedField) *NullableFloat64Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableFloat64Vector{
NewFloat64Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Uint64 vector
type Uint64Vector struct {
vector
values []uint64
meta *shared.SerializedField
}
func (Uint64Vector) Type() reflect.Type {
return reflect.TypeOf(uint64(0))
}
func (Uint64Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Uint64Vector) Len() int {
return int(len(v.values))
}
func (v *Uint64Vector) Get(index uint) uint64 {
return v.values[index]
}
func (v *Uint64Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewUint64Vector(data []byte, meta *shared.SerializedField) *Uint64Vector {
return &Uint64Vector{
vector: vector{rawData: data},
values: Uint64Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableUint64Vector struct {
*Uint64Vector
nullByteMap
}
func (nv *NullableUint64Vector) Get(index uint) *uint64 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableUint64Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableUint64Vector(data []byte, meta *shared.SerializedField) *NullableUint64Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableUint64Vector{
NewUint64Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Uint32 vector
type Uint32Vector struct {
vector
values []uint32
meta *shared.SerializedField
}
func (Uint32Vector) Type() reflect.Type {
return reflect.TypeOf(uint32(0))
}
func (Uint32Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Uint32Vector) Len() int {
return int(len(v.values))
}
func (v *Uint32Vector) Get(index uint) uint32 {
return v.values[index]
}
func (v *Uint32Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewUint32Vector(data []byte, meta *shared.SerializedField) *Uint32Vector {
return &Uint32Vector{
vector: vector{rawData: data},
values: Uint32Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableUint32Vector struct {
*Uint32Vector
nullByteMap
}
func (nv *NullableUint32Vector) Get(index uint) *uint32 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableUint32Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableUint32Vector(data []byte, meta *shared.SerializedField) *NullableUint32Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableUint32Vector{
NewUint32Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Float32 vector
type Float32Vector struct {
vector
values []float32
meta *shared.SerializedField
}
func (Float32Vector) Type() reflect.Type {
return reflect.TypeOf(float32(0))
}
func (Float32Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Float32Vector) Len() int {
return int(len(v.values))
}
func (v *Float32Vector) Get(index uint) float32 {
return v.values[index]
}
func (v *Float32Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewFloat32Vector(data []byte, meta *shared.SerializedField) *Float32Vector {
return &Float32Vector{
vector: vector{rawData: data},
values: Float32Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableFloat32Vector struct {
*Float32Vector
nullByteMap
}
func (nv *NullableFloat32Vector) Get(index uint) *float32 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableFloat32Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableFloat32Vector(data []byte, meta *shared.SerializedField) *NullableFloat32Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableFloat32Vector{
NewFloat32Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Int16 vector
type Int16Vector struct {
vector
values []int16
meta *shared.SerializedField
}
func (Int16Vector) Type() reflect.Type {
return reflect.TypeOf(int16(0))
}
func (Int16Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Int16Vector) Len() int {
return int(len(v.values))
}
func (v *Int16Vector) Get(index uint) int16 {
return v.values[index]
}
func (v *Int16Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewInt16Vector(data []byte, meta *shared.SerializedField) *Int16Vector {
return &Int16Vector{
vector: vector{rawData: data},
values: Int16Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableInt16Vector struct {
*Int16Vector
nullByteMap
}
func (nv *NullableInt16Vector) Get(index uint) *int16 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableInt16Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableInt16Vector(data []byte, meta *shared.SerializedField) *NullableInt16Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableInt16Vector{
NewInt16Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Uint16 vector
type Uint16Vector struct {
vector
values []uint16
meta *shared.SerializedField
}
func (Uint16Vector) Type() reflect.Type {
return reflect.TypeOf(uint16(0))
}
func (Uint16Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Uint16Vector) Len() int {
return int(len(v.values))
}
func (v *Uint16Vector) Get(index uint) uint16 {
return v.values[index]
}
func (v *Uint16Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewUint16Vector(data []byte, meta *shared.SerializedField) *Uint16Vector {
return &Uint16Vector{
vector: vector{rawData: data},
values: Uint16Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableUint16Vector struct {
*Uint16Vector
nullByteMap
}
func (nv *NullableUint16Vector) Get(index uint) *uint16 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableUint16Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableUint16Vector(data []byte, meta *shared.SerializedField) *NullableUint16Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableUint16Vector{
NewUint16Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Int8 vector
type Int8Vector struct {
vector
values []int8
meta *shared.SerializedField
}
func (Int8Vector) Type() reflect.Type {
return reflect.TypeOf(int8(0))
}
func (Int8Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Int8Vector) Len() int {
return int(len(v.values))
}
func (v *Int8Vector) Get(index uint) int8 {
return v.values[index]
}
func (v *Int8Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewInt8Vector(data []byte, meta *shared.SerializedField) *Int8Vector {
return &Int8Vector{
vector: vector{rawData: data},
values: Int8Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableInt8Vector struct {
*Int8Vector
nullByteMap
}
func (nv *NullableInt8Vector) Get(index uint) *int8 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableInt8Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableInt8Vector(data []byte, meta *shared.SerializedField) *NullableInt8Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableInt8Vector{
NewInt8Vector(remaining, meta),
nullByteMap{byteMap},
}
}
// Uint8 vector
type Uint8Vector struct {
vector
values []uint8
meta *shared.SerializedField
}
func (Uint8Vector) Type() reflect.Type {
return reflect.TypeOf(uint8(0))
}
func (Uint8Vector) TypeLen() (int64, bool) {
return 0, false
}
func (v *Uint8Vector) Len() int {
return int(len(v.values))
}
func (v *Uint8Vector) Get(index uint) uint8 {
return v.values[index]
}
func (v *Uint8Vector) Value(index uint) interface{} {
return v.Get(index)
}
func NewUint8Vector(data []byte, meta *shared.SerializedField) *Uint8Vector {
return &Uint8Vector{
vector: vector{rawData: data},
values: Uint8Traits.CastFromBytes(data),
meta: meta,
}
}
type NullableUint8Vector struct {
*Uint8Vector
nullByteMap
}
func (nv *NullableUint8Vector) Get(index uint) *uint8 {
if nv.IsNull(index) {
return nil
}
return &nv.values[index]
}
func (nv *NullableUint8Vector) Value(index uint) interface{} {
val := nv.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableUint8Vector(data []byte, meta *shared.SerializedField) *NullableUint8Vector {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &NullableUint8Vector{
NewUint8Vector(remaining, meta),
nullByteMap{byteMap},
}
} | internal/data/vector_numeric.gen.go | 0.708213 | 0.651258 | vector_numeric.gen.go | starcoder |
package processor
import (
"time"
"github.com/Jeffail/benthos/lib/log"
"github.com/Jeffail/benthos/lib/message"
"github.com/Jeffail/benthos/lib/metrics"
"github.com/Jeffail/benthos/lib/types"
"github.com/Jeffail/benthos/lib/util/text"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeInsertPart] = TypeSpec{
constructor: NewInsertPart,
description: `
Insert a new message into a batch at an index. If the specified index is greater
than the length of the existing batch it will be appended to the end.
The index can be negative, and if so the message will be inserted from the end
counting backwards starting from -1. E.g. if index = -1 then the new message
will become the last of the batch, if index = -2 then the new message will be
inserted before the last message, and so on. If the negative index is greater
than the length of the existing batch it will be inserted at the beginning.
The new message will have metadata copied from the first pre-existing message of
the batch.
This processor will interpolate functions within the 'content' field, you can
find a list of functions [here](../config_interpolation.md#functions).`,
}
}
//------------------------------------------------------------------------------
// InsertPartConfig contains configuration fields for the InsertPart processor.
type InsertPartConfig struct {
Index int `json:"index" yaml:"index"`
Content string `json:"content" yaml:"content"`
}
// NewInsertPartConfig returns a InsertPartConfig with default values.
func NewInsertPartConfig() InsertPartConfig {
return InsertPartConfig{
Index: -1,
Content: "",
}
}
//------------------------------------------------------------------------------
// InsertPart is a processor that inserts a new message part at a specific
// index.
type InsertPart struct {
interpolate bool
part []byte
conf Config
log log.Modular
stats metrics.Type
mCount metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
}
// NewInsertPart returns a InsertPart processor.
func NewInsertPart(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
part := []byte(conf.InsertPart.Content)
interpolate := text.ContainsFunctionVariables(part)
return &InsertPart{
part: part,
interpolate: interpolate,
conf: conf,
log: log,
stats: stats,
mCount: stats.GetCounter("count"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
}, nil
}
//------------------------------------------------------------------------------
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (p *InsertPart) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
p.mCount.Incr(1)
var newPartBytes []byte
if p.interpolate {
newPartBytes = text.ReplaceFunctionVariables(msg, p.part)
} else {
newPartBytes = p.part
}
index := p.conf.InsertPart.Index
msgLen := msg.Len()
if index < 0 {
index = msgLen + index + 1
if index < 0 {
index = 0
}
} else if index > msgLen {
index = msgLen
}
newMsg := message.New(nil)
newPart := msg.Get(0).Copy()
newPart.Set(newPartBytes)
msg.Iter(func(i int, p types.Part) error {
if i == index {
newMsg.Append(newPart)
}
newMsg.Append(p.Copy())
return nil
})
if index == msg.Len() {
newMsg.Append(newPart)
}
p.mBatchSent.Incr(1)
p.mSent.Incr(int64(newMsg.Len()))
msgs := [1]types.Message{newMsg}
return msgs[:], nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (p *InsertPart) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (p *InsertPart) WaitForClose(timeout time.Duration) error {
return nil
}
//------------------------------------------------------------------------------ | lib/processor/insert_part.go | 0.675978 | 0.553988 | insert_part.go | starcoder |
package bootstrap
import (
"bytes"
"io"
)
type Redactor struct {
replacement []byte
// Current offset from the start of the next input segment
offset int
// Minimum and maximum length of redactable string
minlen int
maxlen int
// Table of Boyer-Moore skip distances, and values to redact matching this end byte
table [255]struct {
skip int
needles [][]byte
}
// Internal buffer for building redacted input into
// Also holds the final portion of the previous Write call, in case of
// sensitive values that cross Write boundaries
outbuf []byte
// Wrapped Writer that we'll send redacted output to
output io.Writer
}
// Construct a new Redactor, and pre-compile the Boyer-Moore skip table
func NewRedactor(output io.Writer, replacement string, needles []string) *Redactor {
redactor := &Redactor{
replacement: []byte(replacement),
output: output,
}
redactor.Reset(needles)
return redactor
}
// We re-use the same Redactor between different hooks and the command
// We need to reset and update the list of needles between each phase
func (redactor *Redactor) Reset(needles []string) {
minNeedleLen := 0
maxNeedleLen := 0
for _, needle := range needles {
if len(needle) < minNeedleLen || minNeedleLen == 0 {
minNeedleLen = len(needle)
}
if len(needle) > maxNeedleLen {
maxNeedleLen = len(needle)
}
}
if redactor.outbuf == nil {
// Linux pipes can buffer up to 65536 bytes before flushing, so there's
// a reasonable chance that's how much we'll get in a single Write().
// maxNeedleLen is added since we may retain that many bytes to handle
// matches crossing Write boundaries.
// It's a reasonable starting capacity which hopefully means we don't
// have to reallocate the array, but append() will grow it if necessary
redactor.outbuf = make([]byte, 0, 65536+maxNeedleLen)
} else {
redactor.outbuf = redactor.outbuf[:0]
}
// Since Boyer-Moore looks for the end of substrings, we can safely offset
// processing by the length of the shortest string we're checking for
// Since Boyer-Moore looks for the end of substrings, only bytes further
// behind the iterator than the longest search string are guaranteed to not
// be part of a match
redactor.minlen = minNeedleLen
redactor.maxlen = maxNeedleLen
redactor.offset = minNeedleLen - 1
// For bytes that don't appear in any of the substrings we're searching
// for, it's safe to skip forward the length of the shortest search
// string.
// Start by setting this as a default for all bytes
for i := range redactor.table {
redactor.table[i].skip = minNeedleLen
redactor.table[i].needles = nil
}
for _, needle := range needles {
for i, ch := range needle {
// For bytes that do exist in search strings, find the shortest distance
// between that byte appearing to the end of the same search string
skip := len(needle) - i - 1
if skip < redactor.table[ch].skip {
redactor.table[ch].skip = skip
}
// Build a cache of which search substrings end in which bytes
if skip == 0 {
redactor.table[ch].needles = append(redactor.table[ch].needles, []byte(needle))
}
}
}
}
func (redactor *Redactor) Write(input []byte) (int, error) {
if len(input) == 0 {
return 0, nil
}
// Current iterator index, which may be a safe offset from 0
cursor := redactor.offset
// Current index which is guaranteed to be completely redacted
// May lag behind cursor by up to the length of the longest search string
doneTo := 0
for cursor < len(input) {
ch := input[cursor]
skip := redactor.table[ch].skip
// If the skip table tells us that there is no search string ending in
// the current byte, skip forward by the indicated distance.
if skip != 0 {
cursor += skip
// Also copy any content behind the cursor which is guaranteed not
// to fall under a match
confirmedTo := cursor - redactor.maxlen
if confirmedTo > len(input) {
confirmedTo = len(input)
}
if confirmedTo > doneTo {
redactor.outbuf = append(redactor.outbuf, input[doneTo:confirmedTo]...)
doneTo = confirmedTo
}
continue
}
// We'll check for matching search strings here, but we'll still need
// to move the cursor forward
// Since Go slice syntax is not inclusive of the end index, moving it
// forward now reduces the need to use `cursor-1` everywhere
cursor++
for _, needle := range redactor.table[ch].needles {
// Since we're working backwards from what may be the end of a
// string, it's possible that the start would be out of bounds
startSubstr := cursor - len(needle)
var candidate []byte
if startSubstr >= 0 {
// If the candidate string falls entirely within input, then just slice into input
candidate = input[startSubstr:cursor]
} else if -startSubstr <= len(redactor.outbuf) {
// If the candidate crosses the Write boundary, we need to
// concatenate the two sections to compare against
candidate = make([]byte, 0, len(needle))
candidate = append(candidate, redactor.outbuf[len(redactor.outbuf)+startSubstr:]...)
candidate = append(candidate, input[:cursor]...)
} else {
// Final case is that the start index is out of bounds, and
// it's impossible for it to match. Just move on to the next
// search substring
continue
}
if bytes.Equal(needle, candidate) {
if startSubstr < 0 {
// If we accepted a negative startSubstr, the output buffer
// needs to be truncated to remove the partial match
redactor.outbuf = redactor.outbuf[:len(redactor.outbuf)+startSubstr]
} else if startSubstr > doneTo {
// First, copy over anything behind the matched substring unmodified
redactor.outbuf = append(redactor.outbuf, input[doneTo:startSubstr]...)
}
// Then, write a fixed string into the output, and move doneTo past the redaction
redactor.outbuf = append(redactor.outbuf, redactor.replacement...)
doneTo = cursor
// The next end-of-string will be at least this far away so
// it's safe to skip forward a bit
cursor += redactor.minlen - 1
break
}
}
}
// We buffer the end of the input in order to catch passwords that fall over Write boundaries.
// In the case of line-buffered input, that means we would hold back the
// end of the line in a user-visible way. For this reason, we push through
// any line endings immediately rather than hold them back.
// The \r case should help to handle progress bars/spinners that use \r to
// overwrite the current line.
// Technically this means that passwords containing newlines aren't
// guarateed to get redacted, but who does that anyway?
for i := doneTo; i < len(input); i++ {
if input[i] == byte('\r') || input[i] == byte('\n') {
redactor.outbuf = append(redactor.outbuf, input[doneTo:i+1]...)
doneTo = i + 1
}
}
var err error
if doneTo > 0 {
// Push the output buffer down
_, err = redactor.output.Write(redactor.outbuf)
// There will probably be a segment at the end of the input which may be a
// partial match crossing the Write boundary. This is retained in the
// output buffer to compare against on the next call
// Flush() needs to be called after the final Write(), or this bit won't
// get written
redactor.outbuf = append(redactor.outbuf[:0], input[doneTo:]...)
} else {
// If nothing was done, just add what we got to the buffer to be
// processed on the next run
redactor.outbuf = append(redactor.outbuf, input...)
}
// We can offset the next Write processing by how far cursor is ahead of
// the end of this input segment
redactor.offset = cursor - len(input)
return len(input), err
}
// Flush should be called after the final Write. This will Write() anything
// retained in case of a partial match and reset the output buffer.
func (redactor *Redactor) Flush() error {
_, err := redactor.output.Write(redactor.outbuf)
redactor.outbuf = redactor.outbuf[:0]
return err
} | bootstrap/redactor.go | 0.631708 | 0.416144 | redactor.go | starcoder |
package defaults
import "time"
// IntIfZero returns the value deflt if actual is zero, otherwise returns actual.
func IntIfZero(actual, deflt int) int {
if actual == 0 {
return deflt
}
return actual
}
// Int8IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Int8IfZero(actual, deflt int8) int8 {
if actual == 0 {
return deflt
}
return actual
}
// Int16IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Int16IfZero(actual, deflt int16) int16 {
if actual == 0 {
return deflt
}
return actual
}
// Int32IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Int32IfZero(actual, deflt int32) int32 {
if actual == 0 {
return deflt
}
return actual
}
// Int64IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Int64IfZero(actual, deflt int64) int64 {
if actual == 0 {
return deflt
}
return actual
}
// UintIfZero returns the value deflt if actual is zero, otherwise returns actual.
func UintIfZero(actual, deflt uint) uint {
if actual == 0 {
return deflt
}
return actual
}
// Uint8IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Uint8IfZero(actual, deflt uint8) uint8 {
if actual == 0 {
return deflt
}
return actual
}
// Uint16IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Uint16IfZero(actual, deflt uint16) uint16 {
if actual == 0 {
return deflt
}
return actual
}
// Uint32IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Uint32IfZero(actual, deflt uint32) uint32 {
if actual == 0 {
return deflt
}
return actual
}
// Uint64IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Uint64IfZero(actual, deflt uint64) uint64 {
if actual == 0 {
return deflt
}
return actual
}
// Float32IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Float32IfZero(actual, deflt float32) float32 {
if actual == 0 {
return deflt
}
return actual
}
// Float64IfZero returns the value deflt if actual is zero, otherwise returns actual.
func Float64IfZero(actual, deflt float64) float64 {
if actual == 0 {
return deflt
}
return actual
}
// TimeIfZero returns the value deflt if actual is empty, otherwise returns actual.
func StringIfEmpty(actual, deflt string) string {
if actual == "" {
return deflt
}
return actual
}
// DurationIfZero returns the value deflt if actual is zero, otherwise returns actual.
func DurationIfZero(actual, deflt time.Duration) time.Duration {
if actual == 0 {
return deflt
}
return actual
}
// TimeIfZero returns the value deflt if actual is zero, otherwise returns actual.
func TimeIfZero(actual, deflt time.Time) time.Time {
if actual.IsZero() {
return deflt
}
return actual
} | defaults/zero.go | 0.757705 | 0.416263 | zero.go | starcoder |
package plaid
import (
"encoding/json"
)
// ExternalPaymentScheduleBase The schedule that the payment will be executed on. If a schedule is provided, the payment is automatically set up as a standing order. If no schedule is specified, the payment will be executed only once.
type ExternalPaymentScheduleBase struct {
Interval *PaymentScheduleInterval `json:"interval,omitempty"`
// The day of the interval on which to schedule the payment. If the payment interval is weekly, `interval_execution_day` should be an integer from 1 (Monday) to 7 (Sunday). If the payment interval is monthly, `interval_execution_day` should be an integer indicating which day of the month to make the payment on. Integers from 1 to 28 can be used to make a payment on that day of the month. Negative integers from -1 to -5 can be used to make a payment relative to the end of the month. To make a payment on the last day of the month, use -1; to make the payment on the second-to-last day, use -2, and so on.
IntervalExecutionDay *int32 `json:"interval_execution_day,omitempty"`
// A date in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). Standing order payments will begin on the first `interval_execution_day` on or after the `start_date`. If the first `interval_execution_day` on or after the start date is also the same day that `/payment_initiation/payment/create` was called, the bank *may* make the first payment on that day, but it is not guaranteed to do so.
StartDate *string `json:"start_date,omitempty"`
// A date in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). Standing order payments will end on the last `interval_execution_day` on or before the `end_date`. If the only `interval_execution_day` between the start date and the end date (inclusive) is also the same day that `/payment_initiation/payment/create` was called, the bank *may* make a payment on that day, but it is not guaranteed to do so.
EndDate NullableString `json:"end_date,omitempty"`
// The start date sent to the bank after adjusting for holidays or weekends. Will be provided in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD). If the start date did not require adjustment, this field will be `null`.
AdjustedStartDate NullableString `json:"adjusted_start_date,omitempty"`
AdditionalProperties map[string]interface{}
}
type _ExternalPaymentScheduleBase ExternalPaymentScheduleBase
// NewExternalPaymentScheduleBase instantiates a new ExternalPaymentScheduleBase 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 NewExternalPaymentScheduleBase() *ExternalPaymentScheduleBase {
this := ExternalPaymentScheduleBase{}
return &this
}
// NewExternalPaymentScheduleBaseWithDefaults instantiates a new ExternalPaymentScheduleBase 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 NewExternalPaymentScheduleBaseWithDefaults() *ExternalPaymentScheduleBase {
this := ExternalPaymentScheduleBase{}
return &this
}
// GetInterval returns the Interval field value if set, zero value otherwise.
func (o *ExternalPaymentScheduleBase) GetInterval() PaymentScheduleInterval {
if o == nil || o.Interval == nil {
var ret PaymentScheduleInterval
return ret
}
return *o.Interval
}
// GetIntervalOk returns a tuple with the Interval field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ExternalPaymentScheduleBase) GetIntervalOk() (*PaymentScheduleInterval, bool) {
if o == nil || o.Interval == nil {
return nil, false
}
return o.Interval, true
}
// HasInterval returns a boolean if a field has been set.
func (o *ExternalPaymentScheduleBase) HasInterval() bool {
if o != nil && o.Interval != nil {
return true
}
return false
}
// SetInterval gets a reference to the given PaymentScheduleInterval and assigns it to the Interval field.
func (o *ExternalPaymentScheduleBase) SetInterval(v PaymentScheduleInterval) {
o.Interval = &v
}
// GetIntervalExecutionDay returns the IntervalExecutionDay field value if set, zero value otherwise.
func (o *ExternalPaymentScheduleBase) GetIntervalExecutionDay() int32 {
if o == nil || o.IntervalExecutionDay == nil {
var ret int32
return ret
}
return *o.IntervalExecutionDay
}
// GetIntervalExecutionDayOk returns a tuple with the IntervalExecutionDay field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ExternalPaymentScheduleBase) GetIntervalExecutionDayOk() (*int32, bool) {
if o == nil || o.IntervalExecutionDay == nil {
return nil, false
}
return o.IntervalExecutionDay, true
}
// HasIntervalExecutionDay returns a boolean if a field has been set.
func (o *ExternalPaymentScheduleBase) HasIntervalExecutionDay() bool {
if o != nil && o.IntervalExecutionDay != nil {
return true
}
return false
}
// SetIntervalExecutionDay gets a reference to the given int32 and assigns it to the IntervalExecutionDay field.
func (o *ExternalPaymentScheduleBase) SetIntervalExecutionDay(v int32) {
o.IntervalExecutionDay = &v
}
// GetStartDate returns the StartDate field value if set, zero value otherwise.
func (o *ExternalPaymentScheduleBase) GetStartDate() string {
if o == nil || o.StartDate == nil {
var ret string
return ret
}
return *o.StartDate
}
// GetStartDateOk returns a tuple with the StartDate field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ExternalPaymentScheduleBase) GetStartDateOk() (*string, bool) {
if o == nil || o.StartDate == nil {
return nil, false
}
return o.StartDate, true
}
// HasStartDate returns a boolean if a field has been set.
func (o *ExternalPaymentScheduleBase) HasStartDate() bool {
if o != nil && o.StartDate != nil {
return true
}
return false
}
// SetStartDate gets a reference to the given string and assigns it to the StartDate field.
func (o *ExternalPaymentScheduleBase) SetStartDate(v string) {
o.StartDate = &v
}
// GetEndDate returns the EndDate field value if set, zero value otherwise (both if not set or set to explicit null).
func (o *ExternalPaymentScheduleBase) GetEndDate() string {
if o == nil || o.EndDate.Get() == nil {
var ret string
return ret
}
return *o.EndDate.Get()
}
// GetEndDateOk returns a tuple with the EndDate field value if set, nil otherwise
// 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 *ExternalPaymentScheduleBase) GetEndDateOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.EndDate.Get(), o.EndDate.IsSet()
}
// HasEndDate returns a boolean if a field has been set.
func (o *ExternalPaymentScheduleBase) HasEndDate() bool {
if o != nil && o.EndDate.IsSet() {
return true
}
return false
}
// SetEndDate gets a reference to the given NullableString and assigns it to the EndDate field.
func (o *ExternalPaymentScheduleBase) SetEndDate(v string) {
o.EndDate.Set(&v)
}
// SetEndDateNil sets the value for EndDate to be an explicit nil
func (o *ExternalPaymentScheduleBase) SetEndDateNil() {
o.EndDate.Set(nil)
}
// UnsetEndDate ensures that no value is present for EndDate, not even an explicit nil
func (o *ExternalPaymentScheduleBase) UnsetEndDate() {
o.EndDate.Unset()
}
// GetAdjustedStartDate returns the AdjustedStartDate field value if set, zero value otherwise (both if not set or set to explicit null).
func (o *ExternalPaymentScheduleBase) GetAdjustedStartDate() string {
if o == nil || o.AdjustedStartDate.Get() == nil {
var ret string
return ret
}
return *o.AdjustedStartDate.Get()
}
// GetAdjustedStartDateOk returns a tuple with the AdjustedStartDate field value if set, nil otherwise
// 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 *ExternalPaymentScheduleBase) GetAdjustedStartDateOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.AdjustedStartDate.Get(), o.AdjustedStartDate.IsSet()
}
// HasAdjustedStartDate returns a boolean if a field has been set.
func (o *ExternalPaymentScheduleBase) HasAdjustedStartDate() bool {
if o != nil && o.AdjustedStartDate.IsSet() {
return true
}
return false
}
// SetAdjustedStartDate gets a reference to the given NullableString and assigns it to the AdjustedStartDate field.
func (o *ExternalPaymentScheduleBase) SetAdjustedStartDate(v string) {
o.AdjustedStartDate.Set(&v)
}
// SetAdjustedStartDateNil sets the value for AdjustedStartDate to be an explicit nil
func (o *ExternalPaymentScheduleBase) SetAdjustedStartDateNil() {
o.AdjustedStartDate.Set(nil)
}
// UnsetAdjustedStartDate ensures that no value is present for AdjustedStartDate, not even an explicit nil
func (o *ExternalPaymentScheduleBase) UnsetAdjustedStartDate() {
o.AdjustedStartDate.Unset()
}
func (o ExternalPaymentScheduleBase) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.Interval != nil {
toSerialize["interval"] = o.Interval
}
if o.IntervalExecutionDay != nil {
toSerialize["interval_execution_day"] = o.IntervalExecutionDay
}
if o.StartDate != nil {
toSerialize["start_date"] = o.StartDate
}
if o.EndDate.IsSet() {
toSerialize["end_date"] = o.EndDate.Get()
}
if o.AdjustedStartDate.IsSet() {
toSerialize["adjusted_start_date"] = o.AdjustedStartDate.Get()
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *ExternalPaymentScheduleBase) UnmarshalJSON(bytes []byte) (err error) {
varExternalPaymentScheduleBase := _ExternalPaymentScheduleBase{}
if err = json.Unmarshal(bytes, &varExternalPaymentScheduleBase); err == nil {
*o = ExternalPaymentScheduleBase(varExternalPaymentScheduleBase)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "interval")
delete(additionalProperties, "interval_execution_day")
delete(additionalProperties, "start_date")
delete(additionalProperties, "end_date")
delete(additionalProperties, "adjusted_start_date")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableExternalPaymentScheduleBase struct {
value *ExternalPaymentScheduleBase
isSet bool
}
func (v NullableExternalPaymentScheduleBase) Get() *ExternalPaymentScheduleBase {
return v.value
}
func (v *NullableExternalPaymentScheduleBase) Set(val *ExternalPaymentScheduleBase) {
v.value = val
v.isSet = true
}
func (v NullableExternalPaymentScheduleBase) IsSet() bool {
return v.isSet
}
func (v *NullableExternalPaymentScheduleBase) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableExternalPaymentScheduleBase(val *ExternalPaymentScheduleBase) *NullableExternalPaymentScheduleBase {
return &NullableExternalPaymentScheduleBase{value: val, isSet: true}
}
func (v NullableExternalPaymentScheduleBase) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableExternalPaymentScheduleBase) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | plaid/model_external_payment_schedule_base.go | 0.825167 | 0.540681 | model_external_payment_schedule_base.go | starcoder |
package universe
import (
"context"
"fmt"
"math"
"regexp"
"sort"
"github.com/influxdata/flux"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/execute"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/interpreter"
"github.com/influxdata/flux/plan"
"github.com/influxdata/flux/runtime"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
)
const HistogramKind = "histogram"
type HistogramOpSpec struct {
Column string `json:"column"`
UpperBoundColumn string `json:"upperBoundColumn"`
CountColumn string `json:"countColumn"`
Bins []float64 `json:"bins"`
Normalize bool `json:"normalize"`
}
func init() {
histogramSignature := runtime.MustLookupBuiltinType("universe", "histogram")
runtime.RegisterPackageValue("universe", HistogramKind, flux.MustValue(flux.FunctionValue(HistogramKind, createHistogramOpSpec, histogramSignature)))
runtime.RegisterPackageValue("universe", "linearBins", linearBins{})
runtime.RegisterPackageValue("universe", "logarithmicBins", logarithmicBins{})
flux.RegisterOpSpec(HistogramKind, newHistogramOp)
plan.RegisterProcedureSpec(HistogramKind, newHistogramProcedure, HistogramKind)
execute.RegisterTransformation(HistogramKind, createHistogramTransformation)
}
func createHistogramOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) {
if err := a.AddParentFromArgs(args); err != nil {
return nil, err
}
spec := new(HistogramOpSpec)
if col, ok, err := args.GetString("column"); err != nil {
return nil, err
} else if ok {
spec.Column = col
} else {
spec.Column = execute.DefaultValueColLabel
}
if col, ok, err := args.GetString("upperBoundColumn"); err != nil {
return nil, err
} else if ok {
spec.UpperBoundColumn = col
} else {
spec.UpperBoundColumn = DefaultUpperBoundColumnLabel
}
if col, ok, err := args.GetString("countColumn"); err != nil {
return nil, err
} else if ok {
spec.CountColumn = col
} else {
spec.CountColumn = execute.DefaultValueColLabel
}
binsArry, err := args.GetRequiredArray("bins", semantic.Float)
if err != nil {
return nil, err
}
spec.Bins, err = interpreter.ToFloatArray(binsArry)
if err != nil {
return nil, err
}
if normalize, ok, err := args.GetBool("normalize"); err != nil {
return nil, err
} else if ok {
spec.Normalize = normalize
}
return spec, nil
}
func newHistogramOp() flux.OperationSpec {
return new(HistogramOpSpec)
}
func (s *HistogramOpSpec) Kind() flux.OperationKind {
return HistogramKind
}
type HistogramProcedureSpec struct {
plan.DefaultCost
HistogramOpSpec
}
func newHistogramProcedure(qs flux.OperationSpec, pa plan.Administration) (plan.ProcedureSpec, error) {
spec, ok := qs.(*HistogramOpSpec)
if !ok {
return nil, errors.Newf(codes.Internal, "invalid spec type %T", qs)
}
return &HistogramProcedureSpec{
HistogramOpSpec: *spec,
}, nil
}
func (s *HistogramProcedureSpec) Kind() plan.ProcedureKind {
return HistogramKind
}
func (s *HistogramProcedureSpec) Copy() plan.ProcedureSpec {
ns := new(HistogramProcedureSpec)
*ns = *s
if len(s.Bins) > 0 {
ns.Bins = make([]float64, len(s.Bins))
copy(ns.Bins, s.Bins)
}
return ns
}
func createHistogramTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) {
s, ok := spec.(*HistogramProcedureSpec)
if !ok {
return nil, nil, errors.Newf(codes.Internal, "invalid spec type %T", spec)
}
cache := execute.NewTableBuilderCache(a.Allocator())
d := execute.NewDataset(id, mode, cache)
t := NewHistogramTransformation(d, cache, s)
return t, d, nil
}
type histogramTransformation struct {
execute.ExecutionNode
d execute.Dataset
cache execute.TableBuilderCache
spec HistogramProcedureSpec
}
func NewHistogramTransformation(d execute.Dataset, cache execute.TableBuilderCache, spec *HistogramProcedureSpec) *histogramTransformation {
sort.Float64s(spec.Bins)
return &histogramTransformation{
d: d,
cache: cache,
spec: *spec,
}
}
func (t *histogramTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error {
return t.d.RetractTable(key)
}
func (t *histogramTransformation) Process(id execute.DatasetID, tbl flux.Table) error {
builder, created := t.cache.TableBuilder(tbl.Key())
if !created {
return errors.Newf(codes.FailedPrecondition, "histogram found duplicate table with key: %v", tbl.Key())
}
valueIdx := execute.ColIdx(t.spec.Column, tbl.Cols())
if valueIdx < 0 {
return errors.Newf(codes.FailedPrecondition, "column %q is missing", t.spec.Column)
}
if col := tbl.Cols()[valueIdx]; col.Type != flux.TFloat {
return errors.Newf(codes.FailedPrecondition, "column %q must be a float got %v", t.spec.Column, col.Type)
}
err := execute.AddTableKeyCols(tbl.Key(), builder)
if err != nil {
return err
}
boundIdx, err := builder.AddCol(flux.ColMeta{
Label: t.spec.UpperBoundColumn,
Type: flux.TFloat,
})
if err != nil {
return err
}
countIdx, err := builder.AddCol(flux.ColMeta{
Label: t.spec.CountColumn,
Type: flux.TFloat,
})
if err != nil {
return err
}
totalRows := 0.0
counts := make([]float64, len(t.spec.Bins))
err = tbl.Do(func(cr flux.ColReader) error {
vs := cr.Floats(valueIdx)
totalRows += float64(vs.Len() - vs.NullN())
for i := 0; i < vs.Len(); i++ {
if vs.IsNull(i) {
continue
}
v := vs.Value(i)
idx := sort.Search(len(t.spec.Bins), func(i int) bool {
return v <= t.spec.Bins[i]
})
if idx >= len(t.spec.Bins) {
// Greater than highest bin, or not found
return fmt.Errorf("found value greater than any bin, %d %d %f %f", idx, len(t.spec.Bins), v, t.spec.Bins[len(t.spec.Bins)-1])
}
// Increment counter
counts[idx]++
}
return nil
})
if err != nil {
return err
}
// Add records making counts cumulative
total := 0.0
for i, v := range counts {
if err := execute.AppendKeyValues(tbl.Key(), builder); err != nil {
return err
}
count := v + total
if t.spec.Normalize {
count /= totalRows
}
if err := builder.AppendFloat(countIdx, count); err != nil {
return err
}
if err := builder.AppendFloat(boundIdx, t.spec.Bins[i]); err != nil {
return err
}
total += v
}
return nil
}
func (t *histogramTransformation) UpdateWatermark(id execute.DatasetID, mark execute.Time) error {
return t.d.UpdateWatermark(mark)
}
func (t *histogramTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error {
return t.d.UpdateProcessingTime(pt)
}
func (t *histogramTransformation) Finish(id execute.DatasetID, err error) {
t.d.Finish(err)
}
// linearBins is a helper function for creating bins spaced linearly
type linearBins struct{}
var linearBinsType = runtime.MustLookupBuiltinType("universe", "linearBins")
func (b linearBins) Type() semantic.MonoType {
return linearBinsType
}
func (b linearBins) IsNull() bool {
return false
}
func (b linearBins) Str() string {
panic(values.UnexpectedKind(semantic.String, semantic.Function))
}
func (b linearBins) Bytes() []byte {
panic(values.UnexpectedKind(semantic.Function, semantic.Bytes))
}
func (b linearBins) Int() int64 {
panic(values.UnexpectedKind(semantic.Int, semantic.Function))
}
func (b linearBins) UInt() uint64 {
panic(values.UnexpectedKind(semantic.UInt, semantic.Function))
}
func (b linearBins) Float() float64 {
panic(values.UnexpectedKind(semantic.Float, semantic.Function))
}
func (b linearBins) Bool() bool {
panic(values.UnexpectedKind(semantic.Bool, semantic.Function))
}
func (b linearBins) Time() values.Time {
panic(values.UnexpectedKind(semantic.Time, semantic.Function))
}
func (b linearBins) Duration() values.Duration {
panic(values.UnexpectedKind(semantic.Duration, semantic.Function))
}
func (b linearBins) Regexp() *regexp.Regexp {
panic(values.UnexpectedKind(semantic.Regexp, semantic.Function))
}
func (b linearBins) Array() values.Array {
panic(values.UnexpectedKind(semantic.Array, semantic.Function))
}
func (b linearBins) Object() values.Object {
panic(values.UnexpectedKind(semantic.Object, semantic.Function))
}
func (b linearBins) Function() values.Function {
return b
}
func (b linearBins) Dict() values.Dictionary {
panic(values.UnexpectedKind(semantic.Dictionary, semantic.Function))
}
func (b linearBins) Equal(rhs values.Value) bool {
if b.Type() != rhs.Type() {
return false
}
_, ok := rhs.(linearBins)
return ok
}
func (b linearBins) HasSideEffect() bool {
return false
}
func (b linearBins) Call(ctx context.Context, args values.Object) (values.Value, error) {
startV, ok := args.Get("start")
if !ok {
return nil, errors.New(codes.Invalid, "start is required")
}
if startV.Type().Nature() != semantic.Float {
return nil, errors.New(codes.Invalid, "start must be a float")
}
widthV, ok := args.Get("width")
if !ok {
return nil, errors.New(codes.Invalid, "width is required")
}
if widthV.Type().Nature() != semantic.Float {
return nil, errors.New(codes.Invalid, "width must be a float")
}
countV, ok := args.Get("count")
if !ok {
return nil, errors.New(codes.Invalid, "count is required")
}
if countV.Type().Nature() != semantic.Int {
return nil, errors.New(codes.Invalid, "count must be an int")
}
infV, ok := args.Get("infinity")
if !ok {
infV = values.NewBool(true)
}
if infV.Type().Nature() != semantic.Bool {
return nil, errors.New(codes.Invalid, "infinity must be a bool")
}
start := startV.Float()
width := widthV.Float()
count := countV.Int()
inf := infV.Bool()
l := int(count)
if inf {
l++
}
elements := make([]values.Value, l)
bound := start
for i := 0; i < l; i++ {
elements[i] = values.NewFloat(bound)
bound += width
}
if inf {
elements[l-1] = values.NewFloat(math.Inf(1))
}
counts := values.NewArrayWithBacking(semantic.NewArrayType(semantic.BasicFloat), elements)
return counts, nil
}
// logarithmicBins is a helper function for creating bins spaced by an logarithmic factor.
type logarithmicBins struct{}
var logarithmicBinsType = runtime.MustLookupBuiltinType("universe", "logarithmicBins")
func (b logarithmicBins) Type() semantic.MonoType {
return logarithmicBinsType
}
func (b logarithmicBins) IsNull() bool {
return false
}
func (b logarithmicBins) Str() string {
panic(values.UnexpectedKind(semantic.String, semantic.Function))
}
func (b logarithmicBins) Bytes() []byte {
panic(values.UnexpectedKind(semantic.Function, semantic.Bytes))
}
func (b logarithmicBins) Int() int64 {
panic(values.UnexpectedKind(semantic.Int, semantic.Function))
}
func (b logarithmicBins) UInt() uint64 {
panic(values.UnexpectedKind(semantic.UInt, semantic.Function))
}
func (b logarithmicBins) Float() float64 {
panic(values.UnexpectedKind(semantic.Float, semantic.Function))
}
func (b logarithmicBins) Bool() bool {
panic(values.UnexpectedKind(semantic.Bool, semantic.Function))
}
func (b logarithmicBins) Time() values.Time {
panic(values.UnexpectedKind(semantic.Time, semantic.Function))
}
func (b logarithmicBins) Duration() values.Duration {
panic(values.UnexpectedKind(semantic.Duration, semantic.Function))
}
func (b logarithmicBins) Regexp() *regexp.Regexp {
panic(values.UnexpectedKind(semantic.Regexp, semantic.Function))
}
func (b logarithmicBins) Array() values.Array {
panic(values.UnexpectedKind(semantic.Array, semantic.Function))
}
func (b logarithmicBins) Object() values.Object {
panic(values.UnexpectedKind(semantic.Object, semantic.Function))
}
func (b logarithmicBins) Function() values.Function {
return b
}
func (b logarithmicBins) Dict() values.Dictionary {
panic(values.UnexpectedKind(semantic.Dictionary, semantic.Function))
}
func (b logarithmicBins) Equal(rhs values.Value) bool {
if b.Type() != rhs.Type() {
return false
}
_, ok := rhs.(logarithmicBins)
return ok
}
func (b logarithmicBins) HasSideEffect() bool {
return false
}
func (b logarithmicBins) Call(ctx context.Context, args values.Object) (values.Value, error) {
startV, ok := args.Get("start")
if !ok {
return nil, errors.New(codes.Invalid, "start is required")
}
if startV.Type().Nature() != semantic.Float {
return nil, errors.New(codes.Invalid, "start must be a float")
}
factorV, ok := args.Get("factor")
if !ok {
return nil, errors.New(codes.Invalid, "factor is required")
}
if factorV.Type().Nature() != semantic.Float {
return nil, errors.New(codes.Invalid, "factor must be a float")
}
countV, ok := args.Get("count")
if !ok {
return nil, errors.New(codes.Invalid, "count is required")
}
if countV.Type().Nature() != semantic.Int {
return nil, errors.New(codes.Invalid, "count must be an int")
}
infV, ok := args.Get("infinity")
if !ok {
infV = values.NewBool(true)
}
if infV.Type().Nature() != semantic.Bool {
return nil, errors.New(codes.Invalid, "infinity must be a bool")
}
start := startV.Float()
factor := factorV.Float()
count := countV.Int()
inf := infV.Bool()
l := int(count)
if inf {
l++
}
elements := make([]values.Value, l)
bound := start
for i := 0; i < l; i++ {
elements[i] = values.NewFloat(bound)
bound *= factor
}
if inf {
elements[l-1] = values.NewFloat(math.Inf(1))
}
counts := values.NewArrayWithBacking(semantic.NewArrayType(semantic.BasicFloat), elements)
return counts, nil
} | stdlib/universe/histogram.go | 0.682362 | 0.438184 | histogram.go | starcoder |
Noise Generator Module
https://noisehack.com/generate-noise-web-audio-api/
http://www.musicdsp.org/files/pink.txt
https://en.wikipedia.org/wiki/Pink_noise
https://en.wikipedia.org/wiki/White_noise
https://en.wikipedia.org/wiki/Brownian_noise
*/
//-----------------------------------------------------------------------------
package osc
import (
"fmt"
"github.com/deadsy/babi/core"
"github.com/deadsy/babi/utils/log"
)
//-----------------------------------------------------------------------------
var noiseOscInfo = core.ModuleInfo{
Name: "noiseOsc",
In: nil,
Out: []core.PortInfo{
{"out", "output", core.PortTypeAudio, nil},
},
}
// Info returns the module information.
func (m *noiseOsc) Info() *core.ModuleInfo {
return &m.info
}
//-----------------------------------------------------------------------------
type noiseType int
const (
noiseTypeNull noiseType = iota
noiseTypePink1
noiseTypePink2
noiseTypeWhite
noiseTypeBrown
)
type noiseOsc struct {
info core.ModuleInfo // module info
ntype noiseType // noise type
rand *core.Rand32 // random state
b0, b1, b2, b3 float32 // state variables
b4, b5, b6 float32 // state variables
}
func newNoise(s *core.Synth, ntype noiseType) core.Module {
m := &noiseOsc{
info: noiseOscInfo,
ntype: ntype,
rand: core.NewRand32(0),
}
return s.Register(m)
}
// NewNoiseWhite returns a white noise generator module.
// white noise (spectral density = k)
func NewNoiseWhite(s *core.Synth) core.Module {
log.Info.Printf("")
return newNoise(s, noiseTypeWhite)
}
// NewNoiseBrown returns a brown noise generator module.
// brown noise (spectral density = k/f*f)
func NewNoiseBrown(s *core.Synth) core.Module {
log.Info.Printf("")
return newNoise(s, noiseTypeBrown)
}
// NewNoisePink1 returns a pink noise generator module.
// pink noise (spectral density = k/f): fast, inaccurate version
func NewNoisePink1(s *core.Synth) core.Module {
log.Info.Printf("")
return newNoise(s, noiseTypePink1)
}
// NewNoisePink2 returns a pink noise generator module.
// pink noise (spectral density = k/f): slow, accurate version
func NewNoisePink2(s *core.Synth) core.Module {
log.Info.Printf("")
return newNoise(s, noiseTypePink2)
}
// Return the child modules.
func (m *noiseOsc) Child() []core.Module {
return nil
}
// Stop and performs any cleanup of a module.
func (m *noiseOsc) Stop() {
}
//-----------------------------------------------------------------------------
// Port Events
//-----------------------------------------------------------------------------
func (m *noiseOsc) generateWhite(out *core.Buf) {
for i := 0; i < len(out); i++ {
out[i] = m.rand.Float32()
}
}
func (m *noiseOsc) generateBrown(out *core.Buf) {
b0 := m.b0
for i := 0; i < len(out); i++ {
white := m.rand.Float32()
b0 = (b0 + (0.02 * white)) * (1.0 / 1.02)
out[i] = b0 * (1.0 / 0.38)
}
m.b0 = b0
}
func (m *noiseOsc) generatePink1(out *core.Buf) {
b0 := m.b0
b1 := m.b1
b2 := m.b2
for i := 0; i < len(out); i++ {
white := m.rand.Float32()
b0 = 0.99765*b0 + white*0.0990460
b1 = 0.96300*b1 + white*0.2965164
b2 = 0.57000*b2 + white*1.0526913
pink := b0 + b1 + b2 + white*0.1848
out[i] = pink * (1.0 / 10.4)
}
m.b0 = b0
m.b1 = b1
m.b2 = b2
}
func (m *noiseOsc) generatePink2(out *core.Buf) {
b0 := m.b0
b1 := m.b1
b2 := m.b2
b3 := m.b3
b4 := m.b4
b5 := m.b5
b6 := m.b6
for i := 0; i < len(out); i++ {
white := m.rand.Float32()
b0 = 0.99886*b0 + white*0.0555179
b1 = 0.99332*b1 + white*0.0750759
b2 = 0.96900*b2 + white*0.1538520
b3 = 0.86650*b3 + white*0.3104856
b4 = 0.55000*b4 + white*0.5329522
b5 = -0.7616*b5 - white*0.0168980
pink := b0 + b1 + b2 + b3 + b4 + b5 + b6 + white*0.5362
b6 = white * 0.115926
out[i] = pink * (1.0 / 10.2)
}
m.b0 = b0
m.b1 = b1
m.b2 = b2
m.b3 = b3
m.b4 = b4
m.b5 = b5
m.b6 = b6
}
// Process runs the module DSP.
func (m *noiseOsc) Process(buf ...*core.Buf) bool {
out := buf[0]
switch m.ntype {
case noiseTypeWhite:
m.generateWhite(out)
case noiseTypePink1:
m.generatePink1(out)
case noiseTypePink2:
m.generatePink2(out)
case noiseTypeBrown:
m.generateBrown(out)
default:
panic(fmt.Sprintf("bad noise type %d", m.ntype))
}
return true
}
//----------------------------------------------------------------------------- | module/osc/noise.go | 0.745306 | 0.516656 | noise.go | starcoder |
package output
import (
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/output/writer"
"github.com/Jeffail/benthos/v3/lib/types"
"github.com/Jeffail/benthos/v3/lib/util/aws/session"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeAWSSNS] = TypeSpec{
constructor: NewAWSSNS,
Version: "3.36.0",
Summary: `
Sends messages to an AWS SNS topic.`,
Description: `
### Credentials
By default Benthos will use a shared credentials file when connecting to AWS
services. It's also possible to set them explicitly at the component level,
allowing you to transfer data across accounts. You can find out more
[in this document](/docs/guides/aws).`,
Async: true,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("topic_arn", "The topic to publish to."),
docs.FieldCommon("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."),
docs.FieldAdvanced("timeout", "The maximum period to wait on an upload before abandoning it and reattempting."),
}.Merge(session.FieldSpecs()),
Categories: []Category{
CategoryServices,
CategoryAWS,
},
}
Constructors[TypeSNS] = TypeSpec{
constructor: NewAmazonSNS,
Status: docs.StatusDeprecated,
Summary: `
Sends messages to an AWS SNS topic.`,
Description: `
## Alternatives
This output has been renamed to ` + "[`aws_sns`](/docs/components/outputs/aws_sns)" + `.
### Credentials
By default Benthos will use a shared credentials file when connecting to AWS
services. It's also possible to set them explicitly at the component level,
allowing you to transfer data across accounts. You can find out more
[in this document](/docs/guides/aws).`,
Async: true,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("topic_arn", "The topic to publish to."),
docs.FieldCommon("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."),
docs.FieldAdvanced("timeout", "The maximum period to wait on an upload before abandoning it and reattempting."),
}.Merge(session.FieldSpecs()),
Categories: []Category{
CategoryServices,
CategoryAWS,
},
}
}
//------------------------------------------------------------------------------
// NewAWSSNS creates a new AmazonSNS output type.
func NewAWSSNS(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
return newAmazonSNS(TypeAWSSNS, conf.AWSSNS, mgr, log, stats)
}
// NewAmazonSNS creates a new AmazonSNS output type.
func NewAmazonSNS(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
return newAmazonSNS(TypeSNS, conf.SNS, mgr, log, stats)
}
func newAmazonSNS(name string, conf writer.SNSConfig, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
s, err := writer.NewSNS(conf, log, stats)
if err != nil {
return nil, err
}
if conf.MaxInFlight == 1 {
return NewWriter(name, s, log, stats)
}
return NewAsyncWriter(name, conf.MaxInFlight, s, log, stats)
}
//------------------------------------------------------------------------------ | lib/output/aws_sns.go | 0.744006 | 0.442275 | aws_sns.go | starcoder |
package g3
type BoundingBox struct {
Min, Max Vec3
}
type BoundingSphere struct {
Position Vec3
Radius float32
}
type BoundingVolume interface {
ClassifyPoint(v *Vec3) bool
ClassifyPlane(p *Plane) int
}
type HasBoundingBox interface {
GetBoundingBox() *BoundingBox
}
type HasBoundingSphere interface {
GetBoundingSphere() *BoundingSphere
}
type HasBoundingVolume interface {
GetBoundingVolume() BoundingVolume
}
func MakeUndefinedBoundingBox() BoundingBox {
return BoundingBox{Vec3{MathMax, MathMax, MathMax}, Vec3{-MathMax, -MathMax, -MathMax}}
}
func MakeBoundingBoxFromBoxes(boxes []BoundingBox) BoundingBox {
bbox := MakeUndefinedBoundingBox()
for _, b := range boxes {
bbox.Min.X = Min(bbox.Min.X, b.Min.X)
bbox.Min.Y = Min(bbox.Min.Y, b.Min.Y)
bbox.Min.Z = Min(bbox.Min.Z, b.Min.Z)
bbox.Max.X = Max(bbox.Max.X, b.Max.X)
bbox.Max.Y = Max(bbox.Max.Y, b.Max.Y)
bbox.Max.Z = Max(bbox.Max.Z, b.Max.Z)
}
return bbox
}
func MakeBoundingBoxFromPoints(points []Vec3) BoundingBox {
bbox := MakeUndefinedBoundingBox()
for _, p := range points {
bbox.Min.X = Min(bbox.Min.X, p.X)
bbox.Min.Y = Min(bbox.Min.Y, p.Y)
bbox.Min.Z = Min(bbox.Min.Z, p.Z)
bbox.Max.X = Max(bbox.Max.X, p.X)
bbox.Max.Y = Max(bbox.Max.Y, p.Y)
bbox.Max.Z = Max(bbox.Max.Z, p.Z)
}
return bbox
}
func (bbox *BoundingBox) ClassifyPoint(v *Vec3) bool {
if v.X > bbox.Min.X && v.X < bbox.Max.X &&
v.Y > bbox.Min.Y && v.Y < bbox.Max.Y &&
v.Z > bbox.Min.Z && v.Z < bbox.Max.Z {
return true
}
return false
}
func (bbox *BoundingBox) ClassifyPlane(p *Plane) int {
inside := 0
v := Vec3{bbox.Min.X, bbox.Min.Y, bbox.Min.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
v = Vec3{bbox.Min.X, bbox.Min.Y, bbox.Max.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
v = Vec3{bbox.Min.X, bbox.Max.Y, bbox.Min.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
v = Vec3{bbox.Min.X, bbox.Max.Y, bbox.Max.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
v = Vec3{bbox.Max.X, bbox.Min.Y, bbox.Min.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
v = Vec3{bbox.Max.X, bbox.Min.Y, bbox.Max.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
v = Vec3{bbox.Max.X, bbox.Max.Y, bbox.Min.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
v = Vec3{bbox.Max.X, bbox.Max.Y, bbox.Max.Z}
if p.DistanceToPoint(&v) >= 0.0 {
inside++
}
if inside == 8 {
return 1
} else if inside == 0 {
return 0
}
return -1
}
func (bbox *BoundingBox) CalculateCenter() Vec3 {
return Vec3{(bbox.Min.X+bbox.Max.X)/2, (bbox.Min.Y+bbox.Max.Y)/2, (bbox.Min.Z+bbox.Max.Z)/2}
} | src/pkg/g3/bbox.go | 0.751283 | 0.50293 | bbox.go | starcoder |
package mathcat
import (
"errors"
"fmt"
"math"
"math/big"
)
type association int
type operator struct {
prec int
assoc association
unary bool
}
const (
AssocLeft association = iota
AssocRight
)
var ErrDivisionByZero = errors.New("Division by zero")
var operators = map[TokenType]operator{
// Assignment operators
Eq: {0, AssocRight, false}, // =
AddEq: {0, AssocRight, false}, // +=
SubEq: {0, AssocRight, false}, // -=
DivEq: {0, AssocRight, false}, // /=
MulEq: {0, AssocRight, false}, // *=
PowEq: {0, AssocRight, false}, // **=
RemEq: {0, AssocRight, false}, // %=
AndEq: {0, AssocRight, false}, // &=
OrEq: {0, AssocRight, false}, // |=
XorEq: {0, AssocRight, false}, // ^=
LshEq: {0, AssocRight, false}, // <<=
RshEq: {0, AssocRight, false}, // >>=
// Relational operators
EqEq: {1, AssocRight, false}, // ==
NotEq: {1, AssocRight, false}, // !=
Gt: {1, AssocRight, false}, // >
GtEq: {1, AssocRight, false}, // >=
Lt: {1, AssocRight, false}, // <
LtEq: {1, AssocRight, false}, // <=
// Bitwise operators
Or: {2, AssocRight, false}, // |
Xor: {3, AssocRight, false}, // ^
And: {4, AssocRight, false}, // &
Lsh: {5, AssocRight, false}, // <<
Rsh: {5, AssocRight, false}, // >>
Not: {9, AssocLeft, true}, // ~
// Mathematical operators
Add: {6, AssocLeft, false}, // +
Sub: {6, AssocLeft, false}, // -
Mul: {7, AssocLeft, false}, // *
Div: {7, AssocLeft, false}, // /
Pow: {8, AssocLeft, false}, // **
Rem: {7, AssocLeft, false}, // %
UnaryMin: {10, AssocLeft, true}, // -
}
// Determine if operator 1 has higher precedence than operator 2
func (o1 operator) hasHigherPrecThan(o2 operator) bool {
return (o2.assoc == AssocLeft && o2.prec <= o1.prec) ||
(o2.assoc == AssocRight && o2.prec < o1.prec)
}
// Execute a binary or unary expression
func executeExpression(operator *Token, lhs, rhs *big.Rat) (*big.Rat, error) {
result := new(big.Rat)
// Both lhs and rhs have to be integers for bitwise operations
if operator.IsBitwise() {
if (lhs == nil && !rhs.IsInt()) || (lhs != nil && (!rhs.IsInt() || !lhs.IsInt())) {
return nil, fmt.Errorf("Expecting integers for β%sβ", operator)
}
}
switch operator.Type {
case Add, AddEq:
result.Add(lhs, rhs)
case Sub, SubEq:
result.Sub(lhs, rhs)
case UnaryMin:
result.Neg(rhs)
case Div, DivEq:
if rhs.Sign() == 0 {
return nil, ErrDivisionByZero
}
result.Quo(lhs, rhs)
case Mul, MulEq:
result.Mul(lhs, rhs)
case Pow, PowEq:
if lhs.IsInt() && rhs.IsInt() {
intResult := new(big.Int)
intResult.Set(lhs.Num())
intResult.Exp(intResult, rhs.Num(), nil)
result.SetInt(intResult)
} else {
lhsFloat, _ := lhs.Float64()
rhsFloat, _ := rhs.Float64()
result.SetFloat64(math.Pow(lhsFloat, rhsFloat))
}
case Rem, RemEq:
if rhs.Sign() == 0 {
return nil, ErrDivisionByZero
}
result.Set(Mod(lhs, rhs))
case And, AndEq:
result.SetInt(new(big.Int).And(lhs.Num(), rhs.Num()))
case Or, OrEq:
result.SetInt(new(big.Int).Or(lhs.Num(), rhs.Num()))
case Xor, XorEq:
result.SetInt(new(big.Int).Xor(lhs.Num(), rhs.Num()))
case Lsh, LshEq:
shift := uint(rhs.Num().Uint64())
result.SetInt(new(big.Int).Lsh(lhs.Num(), shift))
case Rsh, RshEq:
shift := uint(rhs.Num().Uint64())
result.SetInt(new(big.Int).Rsh(lhs.Num(), shift))
case Not:
result.SetInt(new(big.Int).Not(rhs.Num()))
case Eq:
result = rhs
case EqEq:
result = boolToRat(lhs.Cmp(rhs) == 0)
case NotEq:
result = boolToRat(lhs.Cmp(rhs) != 0)
case Gt:
result = boolToRat(lhs.Cmp(rhs) == 1)
case GtEq:
result = boolToRat(lhs.Cmp(rhs) == 1 || lhs.Cmp(rhs) == 0)
case Lt:
result = boolToRat(lhs.Cmp(rhs) == -1)
case LtEq:
result = boolToRat(lhs.Cmp(rhs) == -1 || lhs.Cmp(rhs) == 0)
default:
return nil, fmt.Errorf("Invalid operator β%sβ", operator)
}
return result, nil
}
func boolToRat(b bool) *big.Rat {
if b {
return RatTrue
}
return RatFalse
} | operators.go | 0.655226 | 0.42668 | operators.go | starcoder |
package yaml
import (
"errors"
yaml "gopkg.in/yaml.v3"
)
// RemoveKey will remove a given key and value from a MappingNode.
func (n *Node) RemoveKey(key string) bool {
idx := n.KeyIndex(key)
if idx == -1 {
return false
}
// Removing the index of the target node twice should drop the key and
// value.
n.Content = remove(n.Content, idx)
n.Content = remove(n.Content, idx)
return true
}
// EnsureOptions are optional settings when using Node.EnsureKey.
type EnsureOptions struct {
// Comment lets you specify a comment for this node, if it's added.
Comment string
// Force will add the key if it doesn't exist and replace it if it does. If
// Force is used, the comment will always be overridden.
Force bool
}
// EnsureKey ensures that a given key exists. If it doesn't, it adds it with the
// value pointing to newNode.
func (n *Node) EnsureKey(key string, newNode *Node, opts *EnsureOptions) (*Node, bool) {
if opts == nil {
opts = &EnsureOptions{}
}
valNode := n.ValueNode(key)
if valNode == nil {
n.Content = append(
n.Content,
&yaml.Node{
Kind: yaml.ScalarNode,
Value: key,
HeadComment: opts.Comment,
},
newNode.Node,
)
return newNode, true
}
if opts.Force {
// Replace the node and update the comment
*(valNode.Node) = *(newNode.Node)
valNode.HeadComment = opts.Comment
return valNode, true
}
return valNode, false
}
// AppendNode will append a value to a SequenceNode.
func (n *Node) AppendNode(newNode *Node) {
n.Content = append(n.Content, newNode.Node)
}
// AppendNode will append a scalar to a SequenceNode if it does not already
// exist.
func (n *Node) AppendUniqueScalar(newNode *Node) bool {
for _, iterNode := range n.Content {
if iterNode.Kind != yaml.ScalarNode {
continue
}
if iterNode.Value == newNode.Value {
return false
}
}
n.AppendNode(newNode)
return true
}
// EnsureDocument takes data from a yaml file and ensures a basic document
// structure. It returns the root node, the root content node, or an error if
// the yaml document isn't in a valid format.
func EnsureDocument(data []byte) (*Node, *Node, error) {
rootNode := &yaml.Node{
Kind: yaml.DocumentNode,
}
// We explicitly ignore this error so we can manually make a tree
_ = yaml.Unmarshal(data, rootNode)
if len(rootNode.Content) == 0 {
rootNode.Content = append(rootNode.Content, &yaml.Node{
Kind: yaml.MappingNode,
})
}
if len(rootNode.Content) != 1 || rootNode.Content[0].Kind != yaml.MappingNode {
return nil, nil, errors.New("root is not a valid yaml document")
}
targetNode := rootNode.Content[0]
return &Node{rootNode}, &Node{targetNode}, nil
} | internal/yaml/operations.go | 0.820254 | 0.449272 | operations.go | starcoder |
package services
import (
"fmt"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/parse"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
)
// TraitsToRoles maps the supplied traits to a list of teleport role names.
// Returns the list of roles mapped from traits.
// `warnings` optionally contains the list of warnings potentially interesting to the user.
func TraitsToRoles(ms TraitMappingSet, traits map[string][]string) (warnings []string, roles []string) {
warnings = traitsToRoles(ms, traits, func(role string, expanded bool) {
roles = append(roles, role)
})
return warnings, utils.Deduplicate(roles)
}
// TraitsToRoleMatchers maps the supplied traits to a list of role matchers. Prefer calling
// this function directly rather than calling TraitsToRoles and then building matchers from
// the resulting list since this function forces any roles which include substitutions to
// be literal matchers.
func TraitsToRoleMatchers(ms TraitMappingSet, traits map[string][]string) ([]parse.Matcher, error) {
var matchers []parse.Matcher
var firstErr error
traitsToRoles(ms, traits, func(role string, expanded bool) {
if expanded || utils.ContainsExpansion(role) {
// mapping process included variable expansion; we therefore
// "escape" normal matcher syntax and look only for exact matches.
// (note: this isn't about combatting maliciously constructed traits,
// traits are from trusted identity sources, this is just
// about avoiding unnecessary footguns).
matchers = append(matchers, literalMatcher{
value: role,
})
return
}
m, err := parse.NewMatcher(role)
if err != nil {
if firstErr == nil {
firstErr = err
}
return
}
matchers = append(matchers, m)
})
if firstErr != nil {
return nil, trace.Wrap(firstErr)
}
return matchers, nil
}
// traitsToRoles maps the supplied traits to teleport role names and passes them to a collector.
func traitsToRoles(ms TraitMappingSet, traits map[string][]string, collect func(role string, expanded bool)) (warnings []string) {
for _, mapping := range ms {
for traitName, traitValues := range traits {
if traitName != mapping.Trait {
continue
}
TraitLoop:
for _, traitValue := range traitValues {
for _, role := range mapping.Roles {
// Run the initial replacement case-insensitively. Doing so will filter out all literal non-matches
// but will match on case discrepancies. We do another case-sensitive match below to see if the
// case is different
outRole, err := utils.ReplaceRegexpWithConfig(mapping.Value, role, traitValue, utils.RegexpConfig{IgnoreCase: true})
switch {
case err != nil:
if trace.IsNotFound(err) {
log.WithError(err).Debugf("Failed to match expression %q, replace with: %q input: %q.", mapping.Value, role, traitValue)
}
// this trait value clearly did not match, move on to another
continue TraitLoop
case outRole == "":
case outRole != "":
// Run the replacement case-sensitively to see if it matches.
// If there's no match, the trait specifies a mapping which is case-sensitive;
// we should log a warning but return an error.
// See https://github.com/gravitational/teleport/issues/6016 for details.
if _, err := utils.ReplaceRegexp(mapping.Value, role, traitValue); err != nil {
warnings = append(warnings, fmt.Sprintf("trait %q matches value %q case-insensitively and would have yielded %q role", traitValue, mapping.Value, outRole))
continue
}
// skip empty replacement or empty role
collect(outRole, outRole != role)
}
}
}
}
}
return warnings
}
// literalMatcher is used to "escape" values which are not allowed to
// take advantage of normal matcher syntax by limiting them to only
// literal matches.
type literalMatcher struct {
value string
}
func (m literalMatcher) Match(in string) bool { return m.value == in } | lib/services/traits.go | 0.778691 | 0.45944 | traits.go | starcoder |
package z
import (
"fmt"
"math"
"strings"
)
// Creates bounds for an histogram. The bounds are powers of two of the form
// [2^min_exponent, ..., 2^max_exponent].
func HistogramBounds(minExponent, maxExponent uint32) []float64 {
var bounds []float64
for i := minExponent; i <= maxExponent; i++ {
bounds = append(bounds, float64(int(1)<<i))
}
return bounds
}
// HistogramData stores the information needed to represent the sizes of the keys and values
// as a histogram.
type HistogramData struct {
Bounds []float64
Count int64
CountPerBucket []int64
Min int64
Max int64
Sum int64
}
// NewHistogramData returns a new instance of HistogramData with properly initialized fields.
func NewHistogramData(bounds []float64) *HistogramData {
return &HistogramData{
Bounds: bounds,
CountPerBucket: make([]int64, len(bounds)+1),
Max: 0,
Min: math.MaxInt64,
}
}
func (histogram *HistogramData) Copy() *HistogramData {
if histogram == nil {
return nil
}
return &HistogramData{
Bounds: append([]float64{}, histogram.Bounds...),
CountPerBucket: append([]int64{}, histogram.CountPerBucket...),
Count: histogram.Count,
Min: histogram.Min,
Max: histogram.Max,
Sum: histogram.Sum,
}
}
// Update changes the Min and Max fields if value is less than or greater than the current values.
func (histogram *HistogramData) Update(value int64) {
if histogram == nil {
return
}
if value > histogram.Max {
histogram.Max = value
}
if value < histogram.Min {
histogram.Min = value
}
histogram.Sum += value
histogram.Count++
for index := 0; index <= len(histogram.Bounds); index++ {
// Allocate value in the last buckets if we reached the end of the Bounds array.
if index == len(histogram.Bounds) {
histogram.CountPerBucket[index]++
break
}
if value < int64(histogram.Bounds[index]) {
histogram.CountPerBucket[index]++
break
}
}
}
// String converts the histogram data into human-readable string.
func (histogram *HistogramData) String() string {
if histogram == nil {
return ""
}
var b strings.Builder
b.WriteString(" -- Histogram: ")
b.WriteString(fmt.Sprintf("Min value: %d ", histogram.Min))
b.WriteString(fmt.Sprintf("Max value: %d ", histogram.Max))
b.WriteString(fmt.Sprintf("Mean: %.2f ",
float64(histogram.Sum)/float64(histogram.Count)))
numBounds := len(histogram.Bounds)
for index, count := range histogram.CountPerBucket {
if count == 0 {
continue
}
// The last bucket represents the bucket that contains the range from
// the last bound up to infinity so it's processed differently than the
// other buckets.
if index == len(histogram.CountPerBucket)-1 {
lowerBound := int(histogram.Bounds[numBounds-1])
b.WriteString(fmt.Sprintf("[%d, %s) %d %.2f%% ", lowerBound, "infinity",
count, float64(count*100)/float64(histogram.Count)))
continue
}
upperBound := int(histogram.Bounds[index])
lowerBound := 0
if index > 0 {
lowerBound = int(histogram.Bounds[index-1])
}
b.WriteString(fmt.Sprintf("[%d, %d) %d %.2f%% ", lowerBound, upperBound,
count, float64(count*100)/float64(histogram.Count)))
}
b.WriteString(" --")
return b.String()
} | z/histogram.go | 0.737631 | 0.589007 | histogram.go | starcoder |
package Game
import "github.com/golang/The-Lagorinth/Labyrinth"
import "github.com/golang/The-Lagorinth/Characters"
import "github.com/golang/The-Lagorinth/Point"
import "time"
import "fmt"
import "math/rand"
//triggerDamageTrap handles the event when a character steps on a damage trap.
func (game *Game) triggerDamageTrap(trap *Character.Trap, character *Character.NPC) {
damage := trap.DamageTrap()
if rand.Intn(100) < character.Evasion {
game.avoidAttackMessage(character.Name, Character.TrapTypes[0])
} else {
character.TakeDamage(damage)
game.takeDamageFromTrapMessage(damage, Character.TrapTypes[0], character)
}
if game.isCharacterDefeted(character) {
game.CharacterDefeted(character, -1)
}
}
//findEmptyTile receives 2 coordinates and find the nearest empty tile next to them.
func (game *Game) findEmptyTile(centerX int, centerY int) Point.Point {
for e := 0; true; e++ {
for i := centerX - 1 - e; i <= centerX+1+e; i++ {
for j := centerY - 1 - e; j <= centerY+1+e; j++ {
if i > -1 && j > -1 && game.labyrinth.Labyrinth[i][j] == Labyrinth.Pass {
return Point.Point{i, j, nil}
}
}
}
}
return Point.Point{}
}
//triggerTabulaRasaTrap handles the event when a character steps on a trap.
func (game *Game) triggerTabulaRasaTrap(trap *Character.Trap, hero *Character.Hero) {
game.triggerMemoryWhipeTrap(trap, hero)
game.triggerTeleportTrap(trap, hero.Base)
}
//triggerMemoryWhipeTrap handles the event when a character steps on a trap.
func (game *Game) triggerMemoryWhipeTrap(trap *Character.Trap, hero *Character.Hero) {
fmt.Println("MEMORY TRAP")
time.Sleep(2000 * time.Millisecond)
trap.WhipeMemory(hero)
}
//triggerTeleportTrap handles the event when a character steps on a teleportation trap.
func (game *Game) triggerTeleportTrap(trap *Character.Trap, character *Character.NPC) {
fmt.Println("TELEPORT TRAP")
time.Sleep(2000 * time.Millisecond)
location := trap.NewLocation(game.labyrinth.Width, game.labyrinth.Height)
if game.labyrinth.Labyrinth[location.X][location.Y] == Labyrinth.Pass {
character.Location.X = location.X
character.Location.Y = location.Y
} else {
location = game.findEmptyTile(location.X, location.Y)
character.Location.X = location.X
character.Location.Y = location.Y
}
game.cameraReset()
}
//triggerSpawnTrap handles the event when a character steps on a trap that spawn new monsters.
func (game *Game) triggerSpawnTrap(trap *Character.Trap) {
fmt.Println("SPAWNTRAP ACTIVATED")
time.Sleep(2000 * time.Millisecond)
location := trap.NewLocation(game.labyrinth.Width, game.labyrinth.Height)
if game.labyrinth.Labyrinth[location.X][location.Y] == Labyrinth.Pass {
newMonster := game.createMonster(location.X, location.Y)
game.monsterList = append(game.monsterList, &newMonster)
} else {
location = game.findEmptyTile(location.X, location.Y)
newMonster := game.createMonster(location.X, location.Y)
game.monsterList = append(game.monsterList, &newMonster)
}
fmt.Printf("Monster Spawned at %v,%v", location.X, location.Y)
time.Sleep(2000 * time.Millisecond)
}
//triggerTrap determines the type of the trap that the character steps on and the event that follows.
func (game *Game) triggerTrap(trap *Character.Trap, character *Character.Hero) {
switch trap.TrapType {
case Character.TrapTypes[0]:
game.triggerDamageTrap(trap, character.Base)
case Character.TrapTypes[1]:
game.triggerSpawnTrap(trap)
case Character.TrapTypes[2]:
game.triggerTeleportTrap(trap, character.Base)
game.player.MemorizeLabyrinth(game.labyrinth, game.player.Base.Location)
game.draw()
case Character.TrapTypes[3]:
game.triggerMemoryWhipeTrap(trap, character)
game.player.MemorizeLabyrinth(game.labyrinth, game.player.Base.Location)
game.draw()
case Character.TrapTypes[4]:
game.triggerTabulaRasaTrap(trap, character)
game.player.MemorizeLabyrinth(game.labyrinth, game.player.Base.Location)
game.draw()
}
}
//checkTraps if a trap has been triggered,
func (game *Game) checkTraps() {
if trap, ok := game.isTrapTriggered(game.player.Base); ok {
game.triggerTrap(trap, game.player)
}
}
//isTrapTriggered checks if a trap is triggered by the player.
func (game *Game) isTrapTriggered(character *Character.NPC) (*Character.Trap, bool) {
if trap, ok := game.trapList[Point.Point{character.Location.X, character.Location.Y, nil}]; ok {
return trap, true
}
return &Character.Trap{}, false
}
//removeTrap removes a trap from the list of traps.
func (game *Game) removeTrap(trap *Character.Trap) {
game.restoreTile(trap.Location.X, trap.Location.Y)
delete(game.trapList, *trap.Location)
}
//calculateOddsVsTraps calculates the odd of a character detecting and disarming traps.
func (game *Game) calculateOddsVsTraps(difficulty int, trapHandlingSkill int) int {
return 100 - difficulty*10 + trapHandlingSkill*5
}
//attempDisarmTrap determines if a trap is successfully disarmed by randomness.
func (game *Game) attempDisarmTrap(trap *Character.Trap, character *Character.NPC) {
chance := game.calculateOddsVsTraps(trap.DisarmDifficulty, character.TrapHandling)
if rand.Intn(100) < chance {
fmt.Println("TRAP DISARMED!. HELL YEAH!!!!!!!!!!")
time.Sleep(2000 * time.Millisecond)
trap.IsDisarmed = true
trap.CanBeDisarmed = false
game.trapsDisarmed++
game.removeTrap(trap)
} else {
fmt.Println("YOU ARE SUCH A DISAPPOINTMENT")
time.Sleep(2000 * time.Millisecond)
trap.CanBeDisarmed = false
}
}
//attempDetectTrap determines if a trap is successfully detected by randomness.
func (game *Game) attempDetectTrap(trap *Character.Trap, character *Character.NPC) {
chance := game.calculateOddsVsTraps(trap.DetectDifficulty, character.TrapHandling)
if rand.Intn(100) < chance {
fmt.Println("TRAP DETECTED!!!!!!!")
time.Sleep(2000 * time.Millisecond)
trap.IsDetected = true
trap.CanBeDetected = false
} else {
fmt.Println("TRAP NOT DETECTED :(")
time.Sleep(2000 * time.Millisecond)
trap.CanBeDetected = false
}
}
//encounterTrap handles the interaction event between the player and a detected trap.
func (game *Game) encounterTrap(character *Character.NPC, x int, y int) {
trap := game.trapList[Point.Point{x, y, nil}]
if trap.CanBeDetected && !trap.IsDetected {
game.attempDetectTrap(trap, character)
if !trap.IsDetected {
game.characterMoveTo(character, x, y)
}
} else if trap.IsDetected && trap.CanBeDisarmed {
fmt.Println("Do you want to disarm the trap(y/n)")
answer := game.detectKeyPress()
if answer == "y" {
game.attempDisarmTrap(trap, character)
} else if answer == "n" {
game.characterMoveTo(character, x, y)
}
} else if !trap.IsDetected || !trap.IsDisarmed {
game.characterMoveTo(character, x, y)
} else {
game.characterMoveTo(character, x, y)
}
} | Game/gameTraps.go | 0.622689 | 0.415729 | gameTraps.go | starcoder |
package models
import (
"bufio"
"fmt"
"io"
"math"
"strconv"
"strings"
)
// Point2D : a struct that stores X and Y coordinate values
type Point2D struct {
XValue float64
YValue float64
}
// Graph2D : list of all 2D points
type Graph2D struct {
Points []Point2D
//numPoints int
}
// Line : linear equation Ax + By + C = 0
type Line struct {
A float64
B float64
C float64
}
// FloatToString : converts float value to string
// https://stackoverflow.com/questions/19101419/formatfloat-convert-float-number-to-string
func FloatToString(floatVal float64) string {
return strconv.FormatFloat(floatVal, 'f', 6, 64)
}
func (g *Graph2D) Print() {
fmt.Println(g.Points[0])
}
func (g *Graph2D) IsEmpty() bool {
if g.Points == nil {
return true
}
return false
}
func (p *Point2D) Print() {
fmt.Println(p)
}
func (g *Graph2D) ExtractXY() ([]float64, []float64) {
var xArray, yArray []float64
for _, ele := range g.Points {
xArray = append(xArray, ele.XValue)
yArray = append(yArray, ele.YValue)
}
return xArray, yArray
}
// Create : from points p and q, solves for A, B, C of standard linear form
// mx - y - mx_1 + y_1 = 0
func (l *Line) Create(p *Point2D, q *Point2D) {
m := (p.YValue - q.YValue) / (p.XValue - q.XValue)
l.A = m
l.B = -1
l.C = -m * p.XValue + p.YValue
}
// PerpendicularDistance : calculates the perpendicular distance between a point and line
// https://www.intmath.com/plane-analytic-geometry/perpendicular-distance-point-line.php
func (l *Line) PerpendicularDistance(p *Point2D) float64 {
return math.Abs(l.A * p.XValue + l.B * p.YValue + l.C) / math.Sqrt(l.A * l.A + l.B * l.B)
}
// RightSide : determines whether a point r is on the left or right side of a line between points p and q
// Return 1 = on the right side
// 0 = on the left side
// -1 = on the line
// https://math.stackexchange.com/questions/274712/calculate-on-which-side-of-a-straight-line-is-a-given-point-located
// https://stackoverflow.com/questions/1560492/how-to-tell-whether-a-point-is-to-the-right-or-left-side-of-a-line#3461533
func RightSide(p *Point2D, q *Point2D, r *Point2D) int {
d := (r.XValue - p.XValue) * (q.YValue - p.YValue) - (r.YValue - p.YValue) * (q.XValue - p.XValue)
if 0 > d {
return 0
} else if d == 0 {
return -1
}
return 1
}
func Import(reader io.Reader) (*Graph2D, error) {
scanner := bufio.NewScanner(reader)
var numPoints int
scanner.Scan()
numPoints, err := strconv.Atoi(scanner.Text())
if err != nil {
return nil, err
}
g := Graph2D{make([]Point2D, numPoints)}
for i := 0; scanner.Scan(); i++ {
v := &g.Points[i]
coordinates := strings.Split(scanner.Text(), ",")
valueX, err := strconv.ParseFloat(coordinates[0], 64)
if err != nil {
return nil, err
}
v.XValue = valueX
valueY, err := strconv.ParseFloat(coordinates[1], 64)
if err != nil {
return nil, err
}
v.YValue = valueY
}
return &g, nil
}
func (g *Graph2D) Export(writer io.Writer) error {
// write number of points
_, err := io.WriteString(writer, strconv.Itoa(len(g.Points)) + "\n")
if err != nil {
return err
}
// write each point
for _, point := range g.Points {
s := FloatToString(point.XValue)
s += ","
s += FloatToString(point.YValue)
s += "\n"
_, err = io.WriteString(writer, s)
if err != nil {
return err
}
}
return nil
} | src/models/2d.go | 0.748995 | 0.555013 | 2d.go | starcoder |
package deepcopy
import (
"reflect"
"github.com/sirupsen/logrus"
)
// DeepCopyInterface can be implemented by types to have custom deep copy logic.
type DeepCopyInterface interface {
DeepCopy() interface{}
}
// DeepCopy returns a deep copy of x.
// Supports everything except Chan, Func and UnsafePointer.
func DeepCopy(x interface{}) interface{} {
return copyRecursively(reflect.ValueOf(x)).Interface()
}
func copyRecursively(xV reflect.Value) reflect.Value {
if !xV.IsValid() {
logrus.Debugf("invalid value given to copy recursively value: %+v", xV)
return xV
}
if xV.CanInterface() {
if deepCopyAble, ok := xV.Interface().(DeepCopyInterface); ok {
yV := reflect.ValueOf(deepCopyAble.DeepCopy())
if !yV.IsValid() {
return xV
}
return yV
}
}
xT := xV.Type()
xK := xV.Kind()
switch xK {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String:
return xV
case reflect.Array:
yV := reflect.New(xT).Elem()
for i := 0; i < xV.Len(); i++ {
yV.Index(i).Set(copyRecursively(xV.Index(i)))
}
return yV
case reflect.Slice:
if xK == reflect.Slice && xV.IsNil() {
return xV
}
yV := reflect.MakeSlice(xT, xV.Len(), xV.Cap())
for i := 0; i < xV.Len(); i++ {
yV.Index(i).Set(copyRecursively(xV.Index(i)))
}
return yV
case reflect.Interface:
if xV.IsNil() {
return xV
}
return copyRecursively(xV.Elem())
case reflect.Map:
if xV.IsNil() {
return xV
}
yV := reflect.MakeMapWithSize(xT, xV.Len())
for _, key := range xV.MapKeys() {
yV.SetMapIndex(copyRecursively(key), copyRecursively(xV.MapIndex(key)))
}
return yV
case reflect.Ptr:
if xV.IsNil() {
return xV
}
yV := reflect.New(xV.Elem().Type())
yV.Elem().Set(copyRecursively(xV.Elem()))
return yV
case reflect.Struct:
yV := reflect.New(xT).Elem()
for i := 0; i < xV.NumField(); i++ {
if !yV.Field(i).CanSet() {
continue
}
yV.Field(i).Set(copyRecursively(xV.Field(i)))
}
return yV
default:
logrus.Debugf("unsupported for deep copy kind: %+v type: %+v value: %+v", xK, xT, xV)
return xV
}
} | common/deepcopy/deepcopy.go | 0.539226 | 0.414306 | deepcopy.go | starcoder |
package annotation
type EntityEqualer struct {
}
func NewEntityEqualer() *EntityEqualer {
return &EntityEqualer{}
}
func (c *EntityEqualer) Equal(x interface{}, y interface{}) bool {
switch x := x.(type) {
case *SimpleSpec:
if yValue, ok := y.(*SimpleSpec); ok {
return c.equalSimpleSpec(x, yValue)
}
case *ArraySpec:
if yValue, ok := y.(*ArraySpec); ok {
return c.equalArraySpec(x, yValue)
}
case *MapSpec:
if yValue, ok := y.(*MapSpec); ok {
return c.equalMapSpec(x, yValue)
}
case *Field:
if yValue, ok := y.(*Field); ok {
return c.equalField(x, yValue)
}
case *FuncSpec:
if yValue, ok := y.(*FuncSpec); ok {
return c.equalFuncSpec(x, yValue)
}
case *InterfaceSpec:
if yValue, ok := y.(*InterfaceSpec); ok {
return c.equalInterfaceSpec(x, yValue)
}
case *StructSpec:
if yValue, ok := y.(*StructSpec); ok {
return c.equalStructSpec(x, yValue)
}
case *Import:
if yValue, ok := y.(*Import); ok {
return c.equalImport(x, yValue)
}
case *ImportGroup:
if yValue, ok := y.(*ImportGroup); ok {
return c.equalImportGroup(x, yValue)
}
case *Const:
if yValue, ok := y.(*Const); ok {
return c.equalConst(x, yValue)
}
case *ConstGroup:
if yValue, ok := y.(*ConstGroup); ok {
return c.equalConstGroup(x, yValue)
}
case *Var:
if yValue, ok := y.(*Var); ok {
return c.equalVar(x, yValue)
}
case *VarGroup:
if yValue, ok := y.(*VarGroup); ok {
return c.equalVarGroup(x, yValue)
}
case *Type:
if yValue, ok := y.(*Type); ok {
return c.equalType(x, yValue)
}
case *TypeGroup:
if yValue, ok := y.(*TypeGroup); ok {
return c.equalTypeGroup(x, yValue)
}
case *Func:
if yValue, ok := y.(*Func); ok {
return c.equalFunc(x, yValue)
}
}
return false
}
func (c *EntityEqualer) equalSimpleSpec(x *SimpleSpec, y *SimpleSpec) bool {
return y.PackageName == x.PackageName && y.TypeName == x.TypeName && y.IsPointer == x.IsPointer
}
func (c *EntityEqualer) equalArraySpec(x *ArraySpec, y *ArraySpec) bool {
return y.Length == x.Length && c.Equal(x.Value, y.Value)
}
func (c *EntityEqualer) equalMapSpec(x *MapSpec, y *MapSpec) bool {
return c.Equal(x.Key, y.Key) && c.Equal(x.Value, y.Value)
}
func (c *EntityEqualer) equalField(x *Field, y *Field) bool {
return x.Name == y.Name && x.Tag == y.Tag && c.Equal(x.Spec, y.Spec)
}
func (c *EntityEqualer) equalFuncSpec(x *FuncSpec, y *FuncSpec) bool {
if x.IsVariadic != y.IsVariadic || len(x.Params) != len(y.Params) || len(x.Results) != len(y.Results) {
return false
}
for i, field := range x.Params {
if !c.Equal(field, y.Params[i]) {
return false
}
}
for i, field := range x.Results {
if !c.Equal(field, y.Results[i]) {
return false
}
}
return true
}
func (c *EntityEqualer) equalInterfaceSpec(x *InterfaceSpec, y *InterfaceSpec) bool {
if len(x.Fields) != len(y.Fields) {
return false
}
checkedYFields := make([]bool, len(x.Fields))
for _, field := range x.Fields {
fieldEqual := false
for j, yField := range y.Fields {
if checkedYFields[j] {
continue
}
if c.Equal(field, yField) {
fieldEqual = true
checkedYFields[j] = true
break
}
}
if !fieldEqual {
return false
}
}
return true
}
func (c *EntityEqualer) equalStructSpec(x *StructSpec, y *StructSpec) bool {
if len(x.Fields) != len(y.Fields) {
return false
}
checkedYFields := make([]bool, len(x.Fields))
for _, field := range x.Fields {
fieldEqual := false
for j, yField := range y.Fields {
if checkedYFields[j] {
continue
}
if c.Equal(field, yField) {
fieldEqual = true
checkedYFields[j] = true
break
}
}
if !fieldEqual {
return false
}
}
return true
}
func (c *EntityEqualer) equalImport(x *Import, y *Import) bool {
return y.RealAlias() == x.RealAlias() && y.Namespace == x.Namespace
}
func (c *EntityEqualer) equalImportGroup(x *ImportGroup, y *ImportGroup) bool {
if len(x.Imports) != len(y.Imports) {
return false
}
checkedYElements := make([]bool, len(x.Imports))
for _, element := range x.Imports {
elementEqual := false
for j, yElement := range y.Imports {
if checkedYElements[j] {
continue
}
if c.Equal(element, yElement) {
elementEqual = true
checkedYElements[j] = true
break
}
}
if !elementEqual {
return false
}
}
return true
}
func (c *EntityEqualer) equalConst(x *Const, y *Const) bool {
if y.Name != x.Name || y.Value != x.Value || ((x.Spec == nil) != (y.Spec == nil)) {
return false
}
if x.Spec != nil && !c.Equal(x.Spec, y.Spec) {
return false
}
return true
}
func (c *EntityEqualer) equalConstGroup(x *ConstGroup, y *ConstGroup) bool {
if len(x.Consts) != len(y.Consts) {
return false
}
for i, element := range x.Consts {
if !c.Equal(element, y.Consts[i]) {
return false
}
}
return true
}
func (c *EntityEqualer) equalVar(x *Var, y *Var) bool {
if y.Name != x.Name || y.Value != x.Value || ((x.Spec == nil) != (y.Spec == nil)) {
return false
}
if x.Spec != nil && !c.Equal(x.Spec, y.Spec) {
return false
}
return true
}
func (c *EntityEqualer) equalVarGroup(x *VarGroup, y *VarGroup) bool {
if len(x.Vars) != len(y.Vars) {
return false
}
checkedYElements := make([]bool, len(x.Vars))
for _, element := range x.Vars {
elementEqual := false
for j, yElement := range y.Vars {
if checkedYElements[j] {
continue
}
if c.Equal(element, yElement) {
elementEqual = true
checkedYElements[j] = true
break
}
}
if !elementEqual {
return false
}
}
return true
}
func (c *EntityEqualer) equalType(x *Type, y *Type) bool {
if y.Name != x.Name {
return false
}
return c.Equal(x.Spec, y.Spec)
}
func (c *EntityEqualer) equalTypeGroup(x *TypeGroup, y *TypeGroup) bool {
if len(x.Types) != len(y.Types) {
return false
}
checkedYElements := make([]bool, len(x.Types))
for _, element := range x.Types {
elementEqual := false
for j, yElement := range y.Types {
if checkedYElements[j] {
continue
}
if c.Equal(element, yElement) {
elementEqual = true
checkedYElements[j] = true
break
}
}
if !elementEqual {
return false
}
}
return true
}
func (c *EntityEqualer) equalFunc(x *Func, y *Func) bool {
if y.Name != x.Name ||
y.Content != x.Content ||
((x.Spec == nil) != (y.Spec == nil)) ||
((x.Related == nil) != (y.Related == nil)) {
return false
}
if x.Spec != nil && !c.Equal(x.Spec, y.Spec) {
return false
}
if x.Related != nil && !c.Equal(x.Related, y.Related) {
return false
}
return true
} | annotation/entity_equaler.go | 0.692538 | 0.592077 | entity_equaler.go | starcoder |
package fp
func (l BoolList) DropRight(n int) BoolList { return l.Reverse().Drop(n).Reverse() }
func (l StringList) DropRight(n int) StringList { return l.Reverse().Drop(n).Reverse() }
func (l IntList) DropRight(n int) IntList { return l.Reverse().Drop(n).Reverse() }
func (l Int64List) DropRight(n int) Int64List { return l.Reverse().Drop(n).Reverse() }
func (l ByteList) DropRight(n int) ByteList { return l.Reverse().Drop(n).Reverse() }
func (l RuneList) DropRight(n int) RuneList { return l.Reverse().Drop(n).Reverse() }
func (l Float32List) DropRight(n int) Float32List { return l.Reverse().Drop(n).Reverse() }
func (l Float64List) DropRight(n int) Float64List { return l.Reverse().Drop(n).Reverse() }
func (l AnyList) DropRight(n int) AnyList { return l.Reverse().Drop(n).Reverse() }
func (l Tuple2List) DropRight(n int) Tuple2List { return l.Reverse().Drop(n).Reverse() }
func (l BoolArrayList) DropRight(n int) BoolArrayList { return l.Reverse().Drop(n).Reverse() }
func (l StringArrayList) DropRight(n int) StringArrayList { return l.Reverse().Drop(n).Reverse() }
func (l IntArrayList) DropRight(n int) IntArrayList { return l.Reverse().Drop(n).Reverse() }
func (l Int64ArrayList) DropRight(n int) Int64ArrayList { return l.Reverse().Drop(n).Reverse() }
func (l ByteArrayList) DropRight(n int) ByteArrayList { return l.Reverse().Drop(n).Reverse() }
func (l RuneArrayList) DropRight(n int) RuneArrayList { return l.Reverse().Drop(n).Reverse() }
func (l Float32ArrayList) DropRight(n int) Float32ArrayList { return l.Reverse().Drop(n).Reverse() }
func (l Float64ArrayList) DropRight(n int) Float64ArrayList { return l.Reverse().Drop(n).Reverse() }
func (l AnyArrayList) DropRight(n int) AnyArrayList { return l.Reverse().Drop(n).Reverse() }
func (l Tuple2ArrayList) DropRight(n int) Tuple2ArrayList { return l.Reverse().Drop(n).Reverse() }
func (l BoolOptionList) DropRight(n int) BoolOptionList { return l.Reverse().Drop(n).Reverse() }
func (l StringOptionList) DropRight(n int) StringOptionList { return l.Reverse().Drop(n).Reverse() }
func (l IntOptionList) DropRight(n int) IntOptionList { return l.Reverse().Drop(n).Reverse() }
func (l Int64OptionList) DropRight(n int) Int64OptionList { return l.Reverse().Drop(n).Reverse() }
func (l ByteOptionList) DropRight(n int) ByteOptionList { return l.Reverse().Drop(n).Reverse() }
func (l RuneOptionList) DropRight(n int) RuneOptionList { return l.Reverse().Drop(n).Reverse() }
func (l Float32OptionList) DropRight(n int) Float32OptionList { return l.Reverse().Drop(n).Reverse() }
func (l Float64OptionList) DropRight(n int) Float64OptionList { return l.Reverse().Drop(n).Reverse() }
func (l AnyOptionList) DropRight(n int) AnyOptionList { return l.Reverse().Drop(n).Reverse() }
func (l Tuple2OptionList) DropRight(n int) Tuple2OptionList { return l.Reverse().Drop(n).Reverse() }
func (l BoolListList) DropRight(n int) BoolListList { return l.Reverse().Drop(n).Reverse() }
func (l StringListList) DropRight(n int) StringListList { return l.Reverse().Drop(n).Reverse() }
func (l IntListList) DropRight(n int) IntListList { return l.Reverse().Drop(n).Reverse() }
func (l Int64ListList) DropRight(n int) Int64ListList { return l.Reverse().Drop(n).Reverse() }
func (l ByteListList) DropRight(n int) ByteListList { return l.Reverse().Drop(n).Reverse() }
func (l RuneListList) DropRight(n int) RuneListList { return l.Reverse().Drop(n).Reverse() }
func (l Float32ListList) DropRight(n int) Float32ListList { return l.Reverse().Drop(n).Reverse() }
func (l Float64ListList) DropRight(n int) Float64ListList { return l.Reverse().Drop(n).Reverse() }
func (l AnyListList) DropRight(n int) AnyListList { return l.Reverse().Drop(n).Reverse() }
func (l Tuple2ListList) DropRight(n int) Tuple2ListList { return l.Reverse().Drop(n).Reverse() } | fp/bootstrap_list_dropright.go | 0.683314 | 0.456591 | bootstrap_list_dropright.go | starcoder |
package diff3
import (
"fmt"
"strings"
"github.com/sergi/go-diff/diffmatchpatch"
)
const (
// Sep1 signifies the start of a conflict.
Sep1 = "<<<<<<<"
// Sep2 signifies the middle of a conflict.
Sep2 = "======="
// Sep3 signifies the end of a conflict.
Sep3 = ">>>>>>>"
)
// DiffMatchPatch contains the diff algorithm settings.
var DiffMatchPatch = diffmatchpatch.New()
// Merge implements the diff3 algorithm to merge two texts into a common base.
func Merge(textO, textA, textB string) string {
runesO, runesA, linesA := DiffMatchPatch.DiffLinesToRunes(textO, textA)
_, runesB, linesB := DiffMatchPatch.DiffLinesToRunes(textO, textB)
diffsA := DiffMatchPatch.DiffMainRunes(runesO, runesA, false)
diffsB := DiffMatchPatch.DiffMainRunes(runesO, runesB, false)
matchesA := matches(diffsA, runesA)
matchesB := matches(diffsB, runesB)
var result strings.Builder
indexO, indexA, indexB := 0, 0, 0
for {
i := nextMismatch(indexO, indexA, indexB, runesA, runesB, matchesA, matchesB)
o, a, b := 0, 0, 0
if i == 1 {
o, a, b = nextMatch(indexO, runesO, matchesA, matchesB)
} else if i > 1 {
o, a, b = indexO+i, indexA+i, indexB+i
}
if o == 0 || a == 0 || b == 0 {
break
}
chunk(indexO, indexA, indexB, o-1, a-1, b-1, runesO, runesA, runesB, linesA, linesB, &result)
indexO, indexA, indexB = o-1, a-1, b-1
}
chunk(indexO, indexA, indexB, len(runesO), len(runesA), len(runesB), runesO, runesA, runesB, linesA, linesB, &result)
return result.String()
}
// matches returns a map of the non-crossing matches.
func matches(diffs []diffmatchpatch.Diff, runes []rune) map[int]int {
matches := make(map[int]int)
for _, d := range diffs {
if d.Type != diffmatchpatch.DiffEqual {
continue
}
for _, r := range d.Text {
matches[int(r)] = indexOf(runes, r) + 1
}
}
return matches
}
// nextMismatch searches for the next index where a or b is not equal to o.
func nextMismatch(indexO, indexA, indexB int, runesA, runesB []rune, matchesA, matchesB map[int]int) int {
for i := 1; i <= len(runesA) && i <= len(runesB); i++ {
a, okA := matchesA[indexO+i]
b, okB := matchesB[indexO+i]
if !okA || a != indexA+i || !okB || b != indexB+i {
return i
}
}
return 0
}
// nextMatch searches for the next index where a and b are equal to o.
func nextMatch(indexO int, runesO []rune, matchesA, matchesB map[int]int) (int, int, int) {
for o := indexO + 1; o <= len(runesO); o++ {
a, okA := matchesA[o]
b, okB := matchesB[o]
if okA && okB {
return o, a, b
}
}
return 0, 0, 0
}
// chunk merges the lines from o, a, and b into a single text.
func chunk(indexO, indexA, indexB, o, a, b int, runesO, runesA, runesB []rune, linesA, linesB []string, result *strings.Builder) {
chunkO := buildChunk(linesA, runesO[indexO:o])
chunkA := buildChunk(linesA, runesA[indexA:a])
chunkB := buildChunk(linesB, runesB[indexB:b])
switch {
case chunkA == chunkB:
fmt.Fprint(result, chunkO)
case chunkO == chunkA:
fmt.Fprint(result, chunkB)
case chunkO == chunkB:
fmt.Fprint(result, chunkA)
default:
fmt.Fprintf(result, "%s\n%s%s\n%s%s\n", Sep1, chunkA, Sep2, chunkB, Sep3)
}
}
// indexOf returns the index of the first occurance of the given value.
func indexOf(runes []rune, value rune) int {
for i, r := range runes {
if r == value {
return i
}
}
return -1
}
// buildChunk assembles the lines of the chunk into a string.
func buildChunk(lines []string, runes []rune) string {
var chunk strings.Builder
for _, r := range runes {
fmt.Fprint(&chunk, lines[int(r)])
}
return chunk.String()
} | diff3.go | 0.507568 | 0.52476 | diff3.go | starcoder |
package dmmf
import (
"github.com/prisma/prisma-client-go/generator/types"
)
// FieldKind describes a scalar, object or enum.
type FieldKind string
// FieldKind values
const (
FieldKindScalar FieldKind = "scalar"
FieldKindObject FieldKind = "object"
FieldKindEnum FieldKind = "enum"
)
// IncludeInStruct shows whether to include a field in a model struct.
func (v FieldKind) IncludeInStruct() bool {
return v == FieldKindScalar || v == FieldKindEnum
}
// IsRelation returns whether field is a relation
func (v FieldKind) IsRelation() bool {
return v == FieldKindObject
}
// DatamodelFieldKind describes a scalar, object or enum.
type DatamodelFieldKind string
// DatamodelFieldKind values
const (
DatamodelFieldKindScalar DatamodelFieldKind = "scalar"
DatamodelFieldKindRelation DatamodelFieldKind = "relation"
DatamodelFieldKindEnum DatamodelFieldKind = "enum"
)
// IncludeInStruct shows whether to include a field in a model struct.
func (v DatamodelFieldKind) IncludeInStruct() bool {
return v == DatamodelFieldKindScalar || v == DatamodelFieldKindEnum
}
// IsRelation returns whether field is a relation
func (v DatamodelFieldKind) IsRelation() bool {
return v == DatamodelFieldKindRelation
}
// Document describes the root of the AST.
type Document struct {
Datamodel Datamodel `json:"datamodel"`
Schema Schema `json:"schema"`
}
// Operator describes a query operator such as NOT, OR, etc.
type Operator struct {
Name string
Action string
}
// Operators returns a list of all query operators such as NOT, OR, etc.
func (Document) Operators() []Operator {
return []Operator{{
Name: "Not",
Action: "NOT",
}, {
Name: "Or",
Action: "OR",
}}
}
// Action describes a CRUD operation.
type Action struct {
// Type describes a query or a mutation
Type string
Name types.String
}
// ActionType describes a CRUD operation type.
type ActionType struct {
Name types.String
InnerName types.String
List bool
ReturnList bool
}
// Variations contains different query capabilities such as Unique, First and Many
func (Document) Variations() []ActionType {
return []ActionType{{
Name: "Unique",
InnerName: "One",
}, {
Name: "First",
List: true,
InnerName: "One",
}, {
Name: "Many",
List: true,
ReturnList: true,
InnerName: "Many",
}}
}
// Actions returns all possible CRUD operations.
func (Document) Actions() []Action {
return []Action{{
"query",
"Find",
}, {
"mutation",
"Create",
}, {
"mutation",
"Update",
}, {
"mutation",
"Delete",
}}
}
// Method defines the method for the virtual types method
type Method struct {
Name string
Action string
}
// Type defines the data struct for the virtual types method
type Type struct {
Name string
Methods []Method
}
func (Document) WriteTypes() []Type {
number := []Method{{
Name: "Increment",
Action: "increment",
}, {
Name: "Decrement",
Action: "decrement",
}, {
Name: "Multiply",
Action: "multiply",
}, {
Name: "Divide",
Action: "divide",
}}
return []Type{{
Name: "Int",
Methods: number,
}, {
Name: "Float",
Methods: number,
}}
}
// ReadTypes provides virtual types and their actions
func (Document) ReadTypes() []Type {
number := []Method{{
Name: "LT",
Action: "lt",
}, {
Name: "GT",
Action: "gt",
}, {
Name: "LTE",
Action: "lte",
}, {
Name: "GTE",
Action: "gte",
}}
return []Type{{
Name: "String",
Methods: []Method{{
Name: "Contains",
Action: "contains",
}, {
Name: "HasPrefix",
Action: "starts_with",
}, {
Name: "HasSuffix",
Action: "ends_with",
}},
}, {
Name: "Boolean",
Methods: []Method{},
}, {
Name: "Int",
Methods: number,
}, {
Name: "Float",
Methods: number,
}, {
Name: "DateTime",
Methods: []Method{{
Name: "Before",
Action: "lt",
}, {
Name: "After",
Action: "gt",
}, {
Name: "BeforeEquals",
Action: "lte",
}, {
Name: "AfterEquals",
Action: "gte",
}},
}}
}
// SchemaEnum describes an enumerated type.
type SchemaEnum struct {
Name types.String `json:"name"`
Values []types.String `json:"values"`
// DBName (optional)
DBName types.String `json:"dBName"`
}
// Enum describes an enumerated type.
type Enum struct {
Name types.String `json:"name"`
Values []EnumValue `json:"values"`
// DBName (optional)
DBName types.String `json:"dBName"`
}
// EnumValue contains detailed information about an enum type.
type EnumValue struct {
Name types.String `json:"name"`
// DBName (optional)
DBName types.String `json:"dBName"`
}
// Datamodel contains all types of the Prisma Datamodel.
type Datamodel struct {
Models []Model `json:"models"`
Enums []Enum `json:"enums"`
}
type UniqueIndex struct {
InternalName types.String `json:"name"`
Fields []types.String `json:"fields"`
}
func (m *UniqueIndex) Name() types.String {
if m.InternalName != "" {
return m.InternalName
}
var name string
for _, f := range m.Fields {
name += f.GoCase()
}
return types.String(name)
}
func (m *UniqueIndex) ASTName() types.String {
if m.InternalName != "" {
return m.InternalName
}
return concatFieldsToName(m.Fields)
}
// Model describes a Prisma type model, which usually maps to a database table or collection.
type Model struct {
// Name describes the singular name of the model.
Name types.String `json:"name"`
IsEmbedded bool `json:"isEmbedded"`
// DBName (optional)
DBName types.String `json:"dbName"`
Fields []Field `json:"fields"`
UniqueIndexes []UniqueIndex `json:"uniqueIndexes"`
IDFields []types.String `json:"idFields"`
}
func (m Model) Actions() []string {
return []string{"Set", "Equals"}
}
func (m Model) CompositeIndexes() []UniqueIndex {
var indexes []UniqueIndex
indexes = append(indexes, m.UniqueIndexes...)
if len(m.IDFields) > 0 {
indexes = append(indexes, UniqueIndex{
InternalName: concatFieldsToName(m.IDFields),
Fields: m.IDFields,
})
}
return indexes
}
// RelationFieldsPlusOne returns all fields plus an empty one, so it's easier to iterate through it in some gotpl files
func (m Model) RelationFieldsPlusOne() []Field {
var fields []Field
for _, field := range m.Fields {
if field.Kind.IsRelation() {
fields = append(fields, field)
}
}
fields = append(fields, Field{})
return fields
}
// Field describes properties of a single model field.
type Field struct {
Kind FieldKind `json:"kind"`
Name types.String `json:"name"`
IsRequired bool `json:"isRequired"`
IsList bool `json:"isList"`
IsUnique bool `json:"isUnique"`
IsReadOnly bool `json:"isReadOnly"`
IsID bool `json:"isId"`
Type types.Type `json:"type"`
// DBName (optional)
DBName types.String `json:"dBName"`
IsGenerated bool `json:"isGenerated"`
IsUpdatedAt bool `json:"isUpdatedAt"`
// RelationToFields (optional)
RelationToFields []interface{} `json:"relationToFields"`
// RelationOnDelete (optional)
RelationOnDelete types.String `json:"relationOnDelete"`
// RelationName (optional)
RelationName types.String `json:"relationName"`
// HasDefaultValue
HasDefaultValue bool `json:"hasDefaultValue"`
}
func (f Field) RequiredOnCreate() bool {
if !f.IsRequired || f.IsUpdatedAt || f.HasDefaultValue || f.IsReadOnly {
return false
}
if f.RelationName != "" && f.IsList {
return false
}
return true
}
// RelationMethod describes a method for relations
type RelationMethod struct {
Name string
Action string
}
// RelationMethods returns a mapping for the PQL methods provided for relations
func (f Field) RelationMethods() []RelationMethod {
if f.IsList {
return []RelationMethod{{
Name: "Some",
Action: "some",
}, {
Name: "Every",
Action: "every",
}}
}
return []RelationMethod{{
Name: "Where",
Action: "is",
}}
}
// Schema provides the GraphQL/PQL AST.
type Schema struct {
// RootQueryType (optional)
RootQueryType types.String `json:"rootQueryType"`
// RootMutationType (optional)
RootMutationType types.String `json:"rootMutationType"`
InputObjectTypes InputObjectType `json:"inputObjectTypes"`
OutputObjectTypes OutputObjectType `json:"outputObjectTypes"`
Enums []SchemaEnum `json:"enums"`
}
type InputObjectType struct {
Prisma []InputType `json:"prisma"`
}
type OutputObjectType struct {
Prisma []OutputType `json:"prisma"`
}
// SchemaArg provides the arguments of a given field.
type SchemaArg struct {
Name types.String `json:"name"`
InputTypes []SchemaInputType `json:"inputTypes"`
// IsRelationFilter (optional)
IsRelationFilter bool `json:"isRelationFilter"`
}
// SchemaInputType describes an input type of a given field.
type SchemaInputType struct {
IsRequired bool `json:"isRequired"`
IsList bool `json:"isList"`
Type types.Type `json:"type"` // this was declared as ArgType
Kind FieldKind `json:"kind"`
}
// OutputType describes a GraphQL/PQL return type.
type OutputType struct {
Name types.String `json:"name"`
Fields []SchemaField `json:"fields"`
// IsEmbedded (optional)
IsEmbedded bool `json:"isEmbedded"`
}
// SchemaField describes the information of an output type field.
type SchemaField struct {
Name types.String `json:"name"`
OutputType SchemaOutputType `json:"outputType"`
Args []SchemaArg `json:"args"`
}
// SchemaOutputType describes an output type of a given field.
type SchemaOutputType struct {
Type types.String `json:"type"`
IsList bool `json:"isList"`
IsRequired bool `json:"isRequired"`
Kind FieldKind `json:"kind"`
}
// InputType describes a GraphQL/PQL input type.
type InputType struct {
Name types.String `json:"name"`
// IsWhereType (optional)
IsWhereType bool `json:"isWhereType"`
// IsOrderType (optional)
IsOrderType bool `json:"isOrderType"`
// AtLeastOne (optional)
AtLeastOne bool `json:"atLeastOne"`
// AtMostOne (optional)
AtMostOne bool `json:"atMostOne"`
Fields []SchemaArg `json:"fields"`
}
func concatFieldsToName(fields []types.String) types.String {
var name types.String
for i, f := range fields {
if i > 0 {
name += "_"
}
name += f
}
return name
} | generator/dmmf/dmmf.go | 0.794425 | 0.401923 | dmmf.go | starcoder |
package executor
import "github.com/xichen2020/eventdb/document/field"
type docIDValues struct {
DocID int32
Values field.Values
}
// cloneDocIDValues clones the incoming (doc ID, values) pair.
func cloneDocIDValues(v docIDValues) docIDValues {
// TODO(xichen): Should pool and reuse the value array here.
v.Values = v.Values.Clone(field.ValueCloneOptions{DeepCloneBytes: true})
return v
}
// cloneDocIDValuesTo clones the (doc ID, values) pair from `src` to `target`.
// Precondition: `target` values are guaranteed to have the same length as `src` and can be reused.
func cloneDocIDValuesTo(src docIDValues, target *docIDValues) {
target.DocID = src.DocID
for i := 0; i < len(src.Values); i++ {
cloned := src.Values[i].Clone(field.ValueCloneOptions{DeepCloneBytes: true})
target.Values[i] = cloned
}
}
type docIDValuesByDocIDAsc []docIDValues
func (a docIDValuesByDocIDAsc) Len() int { return len(a) }
func (a docIDValuesByDocIDAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a docIDValuesByDocIDAsc) Less(i, j int) bool { return a[i].DocID < a[j].DocID }
// docIDValuesIterator iterates over a sequence of (doc ID, values) pairs.
type docIDValuesIterator struct {
data []docIDValues
currIdx int
}
// newDocIDValuesIterator creates a new doc ID values iterator.
func newDocIDValuesIterator(data []docIDValues) *docIDValuesIterator {
return &docIDValuesIterator{
data: data,
currIdx: -1,
}
}
// Next returns true if there are more pairs to be iterated over.
func (it *docIDValuesIterator) Next() bool {
if it.currIdx >= len(it.data) {
return false
}
it.currIdx++
return it.currIdx < len(it.data)
}
// DocID returns the doc ID of the current pair.
func (it *docIDValuesIterator) DocID() int32 { return it.data[it.currIdx].DocID }
// Values returns the current collection of values.
func (it *docIDValuesIterator) Values() field.Values { return it.data[it.currIdx].Values }
// Err returns errors if any.
func (it *docIDValuesIterator) Err() error { return nil }
// Close closes the iterator.
func (it *docIDValuesIterator) Close() { it.data = nil }
type docIDValuesLessThanFn func(v1, v2 docIDValues) bool
func newDocIDValuesLessThanFn(fn field.ValuesLessThanFn) docIDValuesLessThanFn {
return func(v1, v2 docIDValues) bool {
return fn(v1.Values, v2.Values)
}
} | query/executor/doc_id_values.go | 0.506591 | 0.409339 | doc_id_values.go | starcoder |
package ascii
import "strings"
// Filter represents a byte filter fucntion type.
type Filter func(byte) bool
// Range creates a filter that will match any byte in between (inclusive).
func Range(begin, end byte) Filter {
return func(c byte) bool { return begin <= c && c <= end }
}
// Is creates a filter that will match only the given byte.
func Is(b byte) Filter { return func(c byte) bool { return b == c } }
// Contains creates a filter that will match one of the given bytes.
func Contains(p []byte) Filter {
s := string(p)
return func(c byte) bool { return strings.IndexByte(s, c) >= 0 }
}
// AsFilter attempts to create an optimized filter for the given arguments.
func AsFilter(args ...byte) Filter {
switch len(args) {
case 0:
return Filter(func(byte) bool { return true })
case 1:
return Is(args[0])
default:
return Contains(args)
}
}
// Or will match if any one of the given filters match.
func Or(filters ...Filter) Filter {
return func(c byte) bool {
for _, filter := range filters {
if filter(c) {
return true
}
}
return false
}
}
// Not will invert the given filter.
func Not(filter Filter) Filter {
return func(c byte) bool { return !filter(c) }
}
// Filters for ASCII character sets.
var (
IsNullFilter = AsFilter(0)
IsGraphicFilter = Range(32, 126)
IsControlFilter = Not(IsGraphicFilter)
IsSpaceFilter = Contains(Space)
IsQuoteFilter = Contains(Quote)
IsUpperFilter = Range('A', 'Z')
IsLowerFilter = Range('a', 'z')
IsLetterFilter = Or(IsUpperFilter, IsLowerFilter)
IsDigitFilter = Range('0', '9')
IsNonZeroFilter = Range('1', '9')
IsBinaryFilter = Or(AsFilter('0'), AsFilter('1'))
IsOctalFilter = Range('0', '7')
IsHexFilter = Or(IsDigitFilter, Range('A', 'F'), Range('a', 'f'))
IsLatinFilter = Or(IsLetterFilter, IsDigitFilter)
IsSnakeFilter = Or(IsLatinFilter, AsFilter('_'))
IsASCIIFilter = Range(0, 127)
IsByteFilter = Filter(func(byte) bool { return true })
)
// False will always return false.
func False(c byte) bool { return false }
// IsNull matches a null byte.
func IsNull(c byte) bool { return IsNullFilter(c) }
// IsGraphic matches a graphic character.
func IsGraphic(c byte) bool { return IsGraphicFilter(c) }
// IsControl matches a control byte.
func IsControl(c byte) bool { return IsControlFilter(c) }
// IsSpace matches a whitespace character.
func IsSpace(c byte) bool { return IsSpaceFilter(c) }
// IsQuote matches a quote character.
func IsQuote(c byte) bool { return IsQuoteFilter(c) }
// IsUpper matches an uppercase letter.
func IsUpper(c byte) bool { return IsUpperFilter(c) }
// IsLower matches a lowercase letter.
func IsLower(c byte) bool { return IsLowerFilter(c) }
// IsLetter matches an uppercase or lowercase letter.
func IsLetter(c byte) bool { return IsLetterFilter(c) }
// IsDigit matches a digit character.
func IsDigit(c byte) bool { return IsDigitFilter(c) }
// IsBinary matches a binary digit character.
func IsBinary(c byte) bool { return IsBinaryFilter(c) }
// IsOctal matches a octal digit character.
func IsOctal(c byte) bool { return IsOctalFilter(c) }
// IsHex matches a hexadecimal digit character.
func IsHex(c byte) bool { return IsHexFilter(c) }
// IsNonZero matches a non-zero digit character.
func IsNonZero(c byte) bool { return IsNonZeroFilter(c) }
// IsLatin matches a letter or a digit character.
func IsLatin(c byte) bool { return IsLatinFilter(c) }
// IsSnake matches a latin character or an underscore.
func IsSnake(c byte) bool { return IsSnakeFilter(c) }
// IsASCII matches any ASCII character.
func IsASCII(c byte) bool { return IsASCIIFilter(c) }
// IsByte matches any Byte.
func IsByte(c byte) bool { return IsByteFilter(c) } | filters.go | 0.875774 | 0.695151 | filters.go | starcoder |
package information
import (
"cloud.google.com/go/spanner"
"cloud.google.com/go/spanner/spansql"
)
type (
// Indexes is a collection of Index
Indexes []*Index
// Index is a row in information_schema.indexes (see: https://cloud.google.com/spanner/docs/information-schema#indexes)
Index struct {
// The name of the catalog. Always an empty string.
TableCatalog string `spanner:"TABLE_CATALOG"`
// The name of the schema. An empty string if unnamed.
TableSchema string `spanner:"TABLE_SCHEMA"`
// The name of the table.
TableName string `spanner:"TABLE_NAME"`
// The name of the index. Tables with a PRIMARY KEY specification have a pseudo-index entry generated with the name PRIMARY_KEY, which allows the fields of the primary key to be determined.
IndexName string `spanner:"INDEX_NAME"`
// The type of the index. The type is INDEX or PRIMARY_KEY.
IndexType string `spanner:"INDEX_TYPE"`
// Secondary indexes can be interleaved in a parent table, as discussed in Creating a secondary index. This column holds the name of that parent table, or NULL if the index is not interleaved.
ParentTableName string `spanner:"PARENT_TABLE_NAME"`
// Whether the index keys must be unique.
IsUnique bool `spanner:"IS_UNIQUE"`
// Whether the index includes entries with NULL values.
IsNullFiltered bool `spanner:"IS_NULL_FILTERED"`
// The current state of the index. Possible values and the states they represent are:
// PREPARE: creating empty tables for a new index.
// WRITE_ONLY: backfilling data for a new index.
// WRITE_ONLY_CLEANUP: cleaning up a new index.
// WRITE_ONLY_VALIDATE_UNIQUE: checking uniqueness of data in a new index.
// READ_WRITE: normal index operation.
IndexState string `spanner:"INDEX_STATE"`
// True if the index is managed by Cloud Spanner; Otherwise, False. Secondary backing indexes for foreign keys are managed by Cloud Spanner.
SpannerIsManaged bool `spanner:"SPANNER_IS_MANAGED"`
}
)
// sql query
const getIndexSqlstr = `SELECT ` +
`INDEX_NAME, IS_UNIQUE, IS_NULL_FILTERED, INDEX_STATE ` +
`FROM INFORMATION_SCHEMA.INDEXES ` +
`WHERE TABLE_SCHEMA = "" ` +
`AND INDEX_NAME != "PRIMARY_KEY" ` +
`AND TABLE_NAME = @table_name ` +
`AND SPANNER_IS_MANAGED = FALSE `
var (
// getIndexesForTableQuery renders a query for fetching all indexes for a table from information_schema.indexes
getIndexesForTableQuery = spansql.Query{
Select: spansql.Select{
List: []spansql.Expr{
spansql.ID("TABLE_CATALOG"),
spansql.ID("TABLE_SCHEMA"),
spansql.ID("TABLE_NAME"),
spansql.ID("INDEX_NAME"),
spansql.ID("INDEX_TYPE"),
spansql.ID("PARENT_TABLE_NAME"),
spansql.ID("IS_UNIQUE"),
spansql.ID("IS_NULL_FILTERED"),
spansql.ID("INDEX_STATE"),
spansql.ID("SPANNER_IS_MANAGED"),
},
From: []spansql.SelectFrom{
spansql.SelectFromTable{
Table: "information_schema.indexes",
},
},
Where: spansql.LogicalOp{
Op: spansql.And,
LHS: spansql.ComparisonOp{
Op: spansql.Eq,
LHS: spansql.ID("table_schema"),
RHS: spansql.StringLiteral(""),
},
RHS: spansql.ComparisonOp{
Op: spansql.Eq,
LHS: spansql.ID("table_name"),
RHS: spansql.Param("table_name"),
},
},
},
Order: []spansql.Order{
{Expr: spansql.ID("INDEX_NAME")},
},
}
)
// GetIndexesQuery returns a spanner statement for fetching index information for a table
func GetIndexesQuery(table string) spanner.Statement {
// st := spanner.NewStatement(getIndexesForTableQuery.SQL())
st := spanner.NewStatement(getIndexSqlstr)
st.Params["table_name"] = table
return st
} | pkg/schema/information/index.go | 0.560012 | 0.430985 | index.go | starcoder |
package ncolumn
/*
Package ncolumn contains a "null implementation" of the Column interface. It is typeless and of size 0.
It is for example used when reading zero row CSVs without type hints.
*/
import (
"github.com/tobgu/qframe/config/rolling"
"github.com/tobgu/qframe/internal/column"
"github.com/tobgu/qframe/internal/index"
"github.com/tobgu/qframe/qerrors"
"github.com/tobgu/qframe/types"
)
type Column struct{}
func (c Column) String() string {
return "[]"
}
func (c Column) Filter(index index.Int, comparator interface{}, comparatee interface{}, bIndex index.Bool) error {
return nil
}
func (c Column) Subset(index index.Int) column.Column {
return c
}
func (c Column) Equals(index index.Int, other column.Column, otherIndex index.Int) bool {
return false
}
func (c Column) Comparable(reverse, equalNull, nullLast bool) column.Comparable {
return Comparable{}
}
func (c Column) Aggregate(indices []index.Int, fn interface{}) (column.Column, error) {
return c, nil
}
func (c Column) StringAt(i uint32, naRep string) string {
return naRep
}
func (c Column) AppendByteStringAt(buf []byte, i uint32) []byte {
return buf
}
func (c Column) ByteSize() int {
return 0
}
func (c Column) Len() int {
return 0
}
func (c Column) Apply1(fn interface{}, ix index.Int) (interface{}, error) {
return c, nil
}
func (c Column) Apply2(fn interface{}, s2 column.Column, ix index.Int) (column.Column, error) {
return c, nil
}
func (c Column) Rolling(fn interface{}, ix index.Int, config rolling.Config) (column.Column, error) {
return c, nil
}
func (c Column) FunctionType() types.FunctionType {
return types.FunctionTypeUndefined
}
func (c Column) DataType() types.DataType {
return types.Undefined
}
type Comparable struct{}
func (c Comparable) Compare(i, j uint32) column.CompareResult {
return column.NotEqual
}
func (c Comparable) Hash(i uint32, seed uint64) uint64 {
return 0
}
func (c Column) Append(cols ...column.Column) (column.Column, error) {
// TODO Append
return nil, qerrors.New("Append", "Not implemented yet")
} | internal/ncolumn/column.go | 0.668123 | 0.400603 | column.go | starcoder |
package shamir
import (
"errors"
"math/rand"
"time"
)
const (
// ShareOverhead is the byte size overhead of each share when using
// Split on a secret. This is caused by appending a one byte tag to
// the share.
ShareOverhead = 1
)
// Split takes an arbitrarily long secret and generates a `parts` number
// of shares, `threshold` of which are required to reconstruct the secret.
// The parts and threshold must be at least 2, and less than 256. The returned
// shares are each one byte longer than the secret as they attach a tag used
// to reconstruct the secret.
func Split(secret []byte, parts, threshold int) ([][]byte, error) {
// Sanity check the input
if parts < threshold {
return nil, errors.New("parts cannot be less than threshold")
}
if parts > 255 {
return nil, errors.New("parts cannot exceed 255")
}
if threshold < 2 {
return nil, errors.New("threshold must be at least 2")
}
if threshold > 255 {
return nil, errors.New("threshold cannot exceed 255")
}
if len(secret) == 0 {
return nil, errors.New("cannot split an empty secret")
}
// Generate random list of x coordinates
rand.Seed(time.Now().UnixNano())
xCoordinates := rand.Perm(255)
// Allocate the output array, initialize the final byte
// of the output with the offset. The representation of each
// output is {y1, y2, .., yN, x}.
out := make([][]byte, parts)
for idx := range out {
out[idx] = make([]byte, len(secret)+1)
out[idx][len(secret)] = uint8(xCoordinates[idx]) + 1
}
// Construct a random polynomial for each byte of the secret.
// Because we are using a field of size 256, we can only represent
// a single byte as the intercept of the polynomial, so we must
// use a new polynomial for each byte.
for idx, val := range secret {
p, err := makePolynomial(val, uint8(threshold-1))
if err != nil {
return nil, errors.New("failed to generate polynomial")
}
// Generate a `parts` number of (x,y) pairs
// We cheat by encoding the x value once as the final index,
// so that it only needs to be stored once.
for i := 0; i < parts; i++ {
x := uint8(xCoordinates[i]) + 1
y := p.evaluate(x)
out[i][idx] = y
}
}
// Return the encoded secrets
return out, nil
}
// Combine is used to reverse a Split and reconstruct a secret once a
// `threshold` number of parts are available.
func Combine(parts [][]byte) ([]byte, error) {
// Verify enough parts provided
if len(parts) < 2 {
return nil, errors.New("less than two parts cannot be used to reconstruct the secret")
}
// Verify the parts are all the same length
firstPartLen := len(parts[0])
if firstPartLen < 2 {
return nil, errors.New("parts must be at least two bytes")
}
for i := 1; i < len(parts); i++ {
if len(parts[i]) != firstPartLen {
return nil, errors.New("all parts must be the same length")
}
}
// Create a buffer to store the reconstructed secret
secret := make([]byte, firstPartLen-1)
// Buffer to store the samples
xSamples := make([]uint8, len(parts))
ySamples := make([]uint8, len(parts))
// Set the x value for each sample and ensure no x sample values are the same,
// otherwise div() can be unhappy
checkMap := make(map[byte]bool)
for i, part := range parts {
samp := part[firstPartLen-1]
if exists := checkMap[samp]; exists {
return nil, errors.New("duplicate part detected")
}
checkMap[samp] = true
xSamples[i] = samp
}
// Reconstruct each byte
for idx := range secret {
// Set the y value for each sample
for i, part := range parts {
ySamples[i] = part[idx]
}
// Interpolate the polynomial and compute the value at 0
val := interpolatePolynomial(xSamples, ySamples, 0)
// Evaluate the 0th value to get the intercept
secret[idx] = val
}
return secret, nil
} | crypto/shamir/main.go | 0.812682 | 0.55911 | main.go | starcoder |
package input
import (
"github.com/benthosdev/benthos/v4/internal/component/input"
"github.com/benthosdev/benthos/v4/internal/component/metrics"
"github.com/benthosdev/benthos/v4/internal/docs"
"github.com/benthosdev/benthos/v4/internal/interop"
"github.com/benthosdev/benthos/v4/internal/log"
"github.com/benthosdev/benthos/v4/internal/old/input/reader"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeGCPPubSub] = TypeSpec{
constructor: fromSimpleConstructor(NewGCPPubSub),
Summary: `
Consumes messages from a GCP Cloud Pub/Sub subscription.`,
Description: `
For information on how to set up credentials check out
[this guide](https://cloud.google.com/docs/authentication/production).
### Metadata
This input adds the following metadata fields to each message:
` + "``` text" + `
- gcp_pubsub_publish_time_unix
- All message attributes
` + "```" + `
You can access these metadata fields using
[function interpolation](/docs/configuration/interpolation#metadata).`,
Categories: []string{
"Services",
"GCP",
},
Config: docs.FieldComponent().WithChildren(
docs.FieldString("project", "The project ID of the target subscription."),
docs.FieldString("subscription", "The target subscription ID."),
docs.FieldBool("sync", "Enable synchronous pull mode."),
docs.FieldInt("max_outstanding_messages", "The maximum number of outstanding pending messages to be consumed at a given time."),
docs.FieldInt("max_outstanding_bytes", "The maximum number of outstanding pending messages to be consumed measured in bytes."),
),
}
}
//------------------------------------------------------------------------------
// NewGCPPubSub creates a new GCP Cloud Pub/Sub input type.
func NewGCPPubSub(conf Config, mgr interop.Manager, log log.Modular, stats metrics.Type) (input.Streamed, error) {
var c reader.Async
var err error
if c, err = reader.NewGCPPubSub(conf.GCPPubSub, log, stats); err != nil {
return nil, err
}
return NewAsyncReader(TypeGCPPubSub, true, c, log, stats)
}
//------------------------------------------------------------------------------ | internal/old/input/gcp_pubsub.go | 0.773002 | 0.622086 | gcp_pubsub.go | starcoder |
package circuit
import (
"github.com/consensys/gnark-crypto/ecc"
bls12377fr "github.com/consensys/gnark-crypto/ecc/bls12-377/fr"
bls12379fr "github.com/consensys/gnark-crypto/ecc/bls12-379/fr"
bls12381fr "github.com/consensys/gnark-crypto/ecc/bls12-381/fr"
bls24315fr "github.com/consensys/gnark-crypto/ecc/bls24-315/fr"
bn254fr "github.com/consensys/gnark-crypto/ecc/bn254/fr"
bw6633fr "github.com/consensys/gnark-crypto/ecc/bw6-633/fr"
bw6672fr "github.com/consensys/gnark-crypto/ecc/bw6-672/fr"
bw6761fr "github.com/consensys/gnark-crypto/ecc/bw6-761/fr"
bw6764fr "github.com/consensys/gnark-crypto/ecc/bw6-764/fr"
"github.com/consensys/gnark/frontend"
)
var BenchCircuits map[string]BenchCircuit
type BenchCircuit interface {
Circuit(size int) frontend.Circuit
Witness(size int, curveID ecc.ID) frontend.Circuit
}
func init() {
BenchCircuits = make(map[string]BenchCircuit)
BenchCircuits["expo"] = &defaultCircuit{}
}
type defaultCircuit struct {
}
func (d *defaultCircuit) Circuit(size int) frontend.Circuit {
return &benchCircuit{n: size}
}
func (d *defaultCircuit) Witness(size int, curveID ecc.ID) frontend.Circuit {
witness := benchCircuit{n: size}
witness.X.Assign(2)
switch curveID {
case ecc.BN254:
// compute expected Y
var expectedY bn254fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BLS12_381:
// compute expected Y
var expectedY bls12381fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BLS12_377:
// compute expected Y
var expectedY bls12377fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BLS12_379:
// compute expected Y
var expectedY bls12379fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BLS24_315:
// compute expected Y
var expectedY bls24315fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BW6_764:
// compute expected Y
var expectedY bw6764fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BW6_761:
// compute expected Y
var expectedY bw6761fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BW6_672:
// compute expected Y
var expectedY bw6672fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
case ecc.BW6_633:
// compute expected Y
var expectedY bw6633fr.Element
expectedY.SetInterface(2)
for i := 0; i < size; i++ {
expectedY.Mul(&expectedY, &expectedY)
}
witness.Y.Assign(expectedY)
default:
panic("not implemented")
}
return &witness
}
// benchCircuit is a simple circuit that checks X*X*X*X*X... == Y
type benchCircuit struct {
X frontend.Variable
Y frontend.Variable `gnark:",public"`
n int
}
func (circuit *benchCircuit) Define(curveID ecc.ID, cs *frontend.ConstraintSystem) error {
for i := 0; i < circuit.n; i++ {
circuit.X = cs.Mul(circuit.X, circuit.X)
}
cs.AssertIsEqual(circuit.X, circuit.Y)
return nil
} | circuit/circuit.go | 0.712032 | 0.454109 | circuit.go | starcoder |
This package is an implementation of section 3 of "Detecting Near-Duplicates
for Web Crawling" by Manku, Jain, and Sarma,
http://www2007.org/papers/paper215.pdf
It is hard-coded for hamming distance 3 or 6.
*/
package simstore
import (
"runtime"
"sort"
"sync"
"github.com/dgryski/go-bits"
)
type entry struct {
hash uint64
docid uint64
}
type table []entry
func (t table) Len() int { return len(t) }
func (t table) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
func (t table) Less(i, j int) bool { return t[i].hash < t[j].hash }
const mask3 = 0xfffffff000000000
func (t table) find(sig uint64) []uint64 {
i := sort.Search(len(t), func(i int) bool { return t[i].hash >= sig })
var ids []uint64
for i < len(t) && t[i].hash == sig {
ids = append(ids, t[i].docid)
i++
}
return ids
}
func NewU64Slice(hashes int) u64store {
u := make(u64slice, 0, hashes)
return &u
}
type u64store interface {
add(hash uint64)
find(sig uint64, mask uint64, d int) []uint64
finish()
}
// a store for uint64s
type u64slice []uint64
func (u u64slice) Len() int { return len(u) }
func (u u64slice) Less(i int, j int) bool { return u[i] < u[j] }
func (u u64slice) Swap(i int, j int) { u[i], u[j] = u[j], u[i] }
func (u u64slice) find(sig, mask uint64, d int) []uint64 {
prefix := sig & mask
i := sort.Search(len(u), func(i int) bool { return u[i] >= prefix })
var ids []uint64
for i < len(u) && u[i]&mask == prefix {
if distance(u[i], sig) <= d {
ids = append(ids, u[i])
}
i++
}
return ids
}
func (u *u64slice) add(p uint64) {
*u = append(*u, p)
}
func (u u64slice) finish() {
sort.Sort(u)
}
// Store is a storage engine for 64-bit hashes
type Store struct {
docids table
rhashes []u64store
}
// New3 returns a Store for searching hamming distance <= 3
func New3(hashes int, newStore func(int) u64store) *Store {
s := Store{}
s.rhashes = make([]u64store, 16)
if hashes != 0 {
s.docids = make(table, 0, hashes)
for i := range s.rhashes {
s.rhashes[i] = newStore(hashes)
}
}
return &s
}
// Add inserts a signature and document id into the store
func (s *Store) Add(sig uint64, docid uint64) {
var t int
s.docids = append(s.docids, entry{hash: sig, docid: docid})
for i := 0; i < 4; i++ {
p := sig
s.rhashes[t].add(p)
t++
p = (sig & 0xffff000000ffffff) | (sig & 0x0000fff000000000 >> 12) | (sig & 0x0000000fff000000 << 12)
s.rhashes[t].add(p)
t++
p = (sig & 0xffff000fff000fff) | (sig & 0x0000fff000000000 >> 24) | (sig & 0x0000000000fff000 << 24)
s.rhashes[t].add(p)
t++
p = (sig & 0xffff000ffffff000) | (sig & 0x0000fff000000000 >> 36) | (sig & 0x0000000000000fff << 36)
s.rhashes[t].add(p)
t++
sig = (sig << 16) | (sig >> (64 - 16))
}
}
func (*Store) unshuffle(sig uint64, t int) uint64 {
const m2 = 0x0000fff000000000
t4 := t % 4
shift := 12 * uint64(t4)
m3 := uint64(m2 >> shift)
m1 := ^uint64(0) &^ (m2 | m3)
sig = (sig & m1) | (sig & m2 >> shift) | (sig & m3 << shift)
sig = (sig >> (16 * (uint64(t) / 4))) | (sig << (64 - (16 * (uint64(t) / 4))))
return sig
}
func (s *Store) unshuffleList(sigs []uint64, t int) []uint64 {
for i := range sigs {
sigs[i] = s.unshuffle(sigs[i], t)
}
return sigs
}
type limiter chan struct{}
func (l limiter) enter() { l <- struct{}{} }
func (l limiter) leave() { <-l }
// Finish prepares the store for searching. This must be called once after all
// the signatures have been added via Add().
func (s *Store) Finish() {
// empty store
if len(s.docids) == 0 {
return
}
l := make(limiter, runtime.GOMAXPROCS(0))
var wg sync.WaitGroup
sort.Sort(s.docids)
for i := range s.rhashes {
l.enter()
wg.Add(1)
go func(i int) {
s.rhashes[i].finish()
l.leave()
wg.Done()
}(i)
}
wg.Wait()
}
// Find searches the store for all hashes hamming distance 3 or less from the
// query signature. It returns the associated list of document ids.
func (s *Store) Find(sig uint64) []uint64 {
// empty store
if len(s.docids) == 0 {
return nil
}
var ids []uint64
// TODO(dgryski): search in parallel
var t int
for i := 0; i < 4; i++ {
p := sig
ids = append(ids, s.unshuffleList(s.rhashes[t].find(p, mask3, 3), t)...)
t++
p = (sig & 0xffff000000ffffff) | (sig & 0x0000fff000000000 >> 12) | (sig & 0x0000000fff000000 << 12)
ids = append(ids, s.unshuffleList(s.rhashes[t].find(p, mask3, 3), t)...)
t++
p = (sig & 0xffff000fff000fff) | (sig & 0x0000fff000000000 >> 24) | (sig & 0x0000000000fff000 << 24)
ids = append(ids, s.unshuffleList(s.rhashes[t].find(p, mask3, 3), t)...)
t++
p = (sig & 0xffff000ffffff000) | (sig & 0x0000fff000000000 >> 36) | (sig & 0x0000000000000fff << 36)
ids = append(ids, s.unshuffleList(s.rhashes[t].find(p, mask3, 3), t)...)
t++
sig = (sig << 16) | (sig >> (64 - 16))
}
ids = unique(ids)
var docids []uint64
for _, v := range ids {
docids = append(docids, s.docids.find(v)...)
}
return docids
}
// SmallStore3 is a simstore for distance k=3 with smaller memory requirements
type SmallStore3 struct {
tables [4][1 << 16]table
}
func New3Small(hashes int) *SmallStore3 {
return &SmallStore3{}
}
func (s *SmallStore3) Add(sig uint64, docid uint64) {
for i := 0; i < 4; i++ {
prefix := (sig & 0xffff000000000000) >> (64 - 16)
s.tables[i][prefix] = append(s.tables[i][prefix], entry{hash: sig, docid: docid})
sig = (sig << 16) | (sig >> (64 - 16))
}
}
func (s *SmallStore3) Find(sig uint64) []uint64 {
var ids []uint64
for i := 0; i < 4; i++ {
prefix := (sig & 0xffff000000000000) >> (64 - 16)
t := s.tables[i][prefix]
for i := range t {
if distance(t[i].hash, sig) <= 3 {
ids = append(ids, t[i].docid)
}
}
sig = (sig << 16) | (sig >> (64 - 16))
}
return unique(ids)
}
func (s *SmallStore3) Finish() {
for i := range s.tables {
for p := range s.tables[i] {
sort.Sort(s.tables[i][p])
}
}
}
func unique(ids []uint64) []uint64 {
// dedup ids
uniq := make(map[uint64]struct{})
for _, id := range ids {
uniq[id] = struct{}{}
}
ids = ids[:0]
for k := range uniq {
ids = append(ids, k)
}
return ids
}
// distance returns the hamming distance between v1 and v2
func distance(v1 uint64, v2 uint64) int {
return int(bits.Popcnt(v1 ^ v2))
} | simstore.go | 0.657978 | 0.454896 | simstore.go | starcoder |
package common
type GraphLabyrinth struct {
nodes []Node
maxLoc Location
}
func NewLabyrinth(maxLoc Location) Labyrinth {
if maxLoc == nil {
return nil
}
graphLabyrinth := GraphLabyrinth{}
graphLabyrinth.nodes = make([]Node, 0)
maxX, maxY, maxZ := maxLoc.As3DCoordinates()
for z := uint(0); z <= maxZ; z++ {
for y := uint(0); y <= maxY; y++ {
for x := uint(0); x <= maxX; x++ {
graphLabyrinth.nodes = append(graphLabyrinth.nodes, newNode(NewLocation(x, y, z)))
}
}
}
graphLabyrinth.maxLoc = maxLoc
return graphLabyrinth
}
func (g GraphLabyrinth) GetMaxLocation() Location {
return g.maxLoc
}
func (g GraphLabyrinth) GetNeighbors(loc Location) []Location {
if loc == nil {
return nil
}
x, y, z := loc.As3DCoordinates()
maxX, maxY, maxZ := g.GetMaxLocation().As3DCoordinates()
if !g.CheckLocation(loc) {
return nil
}
neighbors := make([]Location, 0)
if x != 0 {
neighbors = append(neighbors, g.nodes[GetIndex(x-gridStep, y, z, g.maxLoc)].getLocation())
}
if x != maxX {
neighbors = append(neighbors, g.nodes[GetIndex(x+gridStep, y, z, g.maxLoc)].getLocation())
}
if y != 0 {
neighbors = append(neighbors, g.nodes[GetIndex(x, y-gridStep, z, g.maxLoc)].getLocation())
}
if y != maxY {
neighbors = append(neighbors, g.nodes[GetIndex(x, y+gridStep, z, g.maxLoc)].getLocation())
}
if z != 0 {
neighbors = append(neighbors, g.nodes[GetIndex(x, y, z-gridStep, g.maxLoc)].getLocation())
}
if z != maxZ {
neighbors = append(neighbors, g.nodes[GetIndex(x, y, z+gridStep, g.maxLoc)].getLocation())
}
return neighbors
}
func (g GraphLabyrinth) Connect(loc1 Location, loc2 Location) bool {
node1 := g.getNode(loc1)
node2 := g.getNode(loc2)
if node1 == nil || node2 == nil ||
!g.CheckLocation(loc1) ||
!g.CheckLocation(loc1) {
return false
}
wasSuccessful, node1, node2 := node1.connect(node2)
x1, y1, z1 := node1.getLocation().As3DCoordinates()
g.nodes[GetIndex(x1, y1, z1, g.GetMaxLocation())] = node1
x2, y2, z2 := node2.getLocation().As3DCoordinates()
g.nodes[GetIndex(x2, y2, z2, g.GetMaxLocation())] = node2
return wasSuccessful
}
func (g GraphLabyrinth) Disconnect(loc1 Location, loc2 Location) bool {
node1 := g.getNode(loc1)
node2 := g.getNode(loc2)
if node1 == nil || node2 == nil ||
!g.CheckLocation(loc1) ||
!g.CheckLocation(loc1) {
return false
}
wasSuccessful, node1, node2 := node1.disconnect(node2)
x1, y1, z1 := node1.getLocation().As3DCoordinates()
g.nodes[GetIndex(x1, y1, z1, g.GetMaxLocation())] = node1
x2, y2, z2 := node2.getLocation().As3DCoordinates()
g.nodes[GetIndex(x2, y2, z2, g.GetMaxLocation())] = node2
return wasSuccessful
}
func (g GraphLabyrinth) GetConnected(loc Location) []Location {
node := g.getNode(loc)
if node == nil || !g.CheckLocation(loc) {
return nil
}
connected := node.getConnected()
conLoc := make([]Location, 0)
for _, con := range connected {
conLoc = append(conLoc, con.getLocation())
}
return conLoc
}
func (g GraphLabyrinth) IsConnected(loc1 Location, loc2 Location) bool {
node1 := g.getNode(loc1)
node2 := g.getNode(loc2)
if node1 == nil || node2 == nil || !g.CheckLocation(loc1) || !g.CheckLocation(loc2) {
return false
}
connected := node1.getConnected()
for _, con := range connected {
if con.compare(node2) {
return true
}
}
return false
}
func (g GraphLabyrinth) Compare(that Labyrinth) bool {
if that == nil {
return false
}
// all nodes should be equal
for _, n := range g.nodes {
thatNode := that.getNode(n.getLocation())
if thatNode == nil || !thatNode.hardCompare(n) {
return false
}
}
// both should not have further nodes
maxX, maxY, maxZ := g.maxLoc.As3DCoordinates()
locX := NewLocation(maxX+gridStep, maxY, maxZ)
lastTestNodeX := g.getNode(locX)
thatNodeX := that.getNode(locX)
locY := NewLocation(maxX, maxY+gridStep, maxZ)
lastTestNodeY := g.getNode(locY)
thatNodeY := that.getNode(locY)
locZ := NewLocation(maxX, maxY, maxZ+gridStep)
lastTestNodeZ := g.getNode(locZ)
thatNodeZ := that.getNode(locZ)
return thatNodeX == nil &&
thatNodeX == lastTestNodeX &&
thatNodeY == nil &&
thatNodeY == lastTestNodeY &&
thatNodeZ == nil &&
thatNodeZ == lastTestNodeZ
}
func (g GraphLabyrinth) getNode(location Location) Node {
if g.CheckLocation(location) {
x, y, z := location.As3DCoordinates()
return g.nodes[GetIndex(x, y, z, g.maxLoc)]
}
return nil
} | common/graphLabyrinth.go | 0.654784 | 0.555375 | graphLabyrinth.go | starcoder |
package graphics
import (
"github.com/hajimehoshi/ebiten/v2/internal/web"
)
const (
ShaderImageNum = 4
// PreservedUniformVariablesNum represents the number of preserved uniform variables.
// Any shaders in Ebiten must have these uniform variables.
PreservedUniformVariablesNum = 1 + // the destination texture size
1 + // the texture sizes array
1 + // the texture destination region's origin
1 + // the texture destination region's size
1 + // the offsets array of the second and the following images
1 + // the texture source region's origin
1 // the texture source region's size
DestinationTextureSizeUniformVariableIndex = 0
TextureSizesUniformVariableIndex = 1
TextureDestinationRegionOriginUniformVariableIndex = 2
TextureDestinationRegionSizeUniformVariableIndex = 3
TextureSourceOffsetsUniformVariableIndex = 4
TextureSourceRegionOriginUniformVariableIndex = 5
TextureSourceRegionSizeUniformVariableIndex = 6
)
const (
IndicesNum = (1 << 16) / 3 * 3 // Adjust num for triangles.
VertexFloatNum = 8
)
var (
quadIndices = []uint16{0, 1, 2, 1, 2, 3}
)
func QuadIndices() []uint16 {
return quadIndices
}
var (
theVerticesBackend = &verticesBackend{
backend: make([]float32, VertexFloatNum*1024),
}
)
type verticesBackend struct {
backend []float32
head int
}
func (v *verticesBackend) slice(n int, last bool) []float32 {
// As this is called only on browsers, mutex is not required.
need := n * VertexFloatNum
if l := len(v.backend); v.head+need > l {
for v.head+need > l {
l *= 2
}
v.backend = make([]float32, l)
v.head = 0
}
s := v.backend[v.head : v.head+need]
if last {
// If last is true, the vertices backend is sent to GPU and it is fine to reuse the slice.
v.head = 0
} else {
v.head += need
}
return s
}
func vertexSlice(n int, last bool) []float32 {
if web.IsBrowser() {
// In Wasm, allocating memory by make is expensive. Use the backend instead.
return theVerticesBackend.slice(n, last)
}
return make([]float32, n*VertexFloatNum)
}
func QuadVertices(sx0, sy0, sx1, sy1 float32, a, b, c, d, tx, ty float32, cr, cg, cb, ca float32, last bool) []float32 {
x := sx1 - sx0
y := sy1 - sy0
ax, by, cx, dy := a*x, b*y, c*x, d*y
u0, v0, u1, v1 := float32(sx0), float32(sy0), float32(sx1), float32(sy1)
// This function is very performance-sensitive and implement in a very dumb way.
vs := vertexSlice(4, last)
_ = vs[:32]
vs[0] = tx
vs[1] = ty
vs[2] = u0
vs[3] = v0
vs[4] = cr
vs[5] = cg
vs[6] = cb
vs[7] = ca
vs[8] = ax + tx
vs[9] = cx + ty
vs[10] = u1
vs[11] = v0
vs[12] = cr
vs[13] = cg
vs[14] = cb
vs[15] = ca
vs[16] = by + tx
vs[17] = dy + ty
vs[18] = u0
vs[19] = v1
vs[20] = cr
vs[21] = cg
vs[22] = cb
vs[23] = ca
vs[24] = ax + by + tx
vs[25] = cx + dy + ty
vs[26] = u1
vs[27] = v1
vs[28] = cr
vs[29] = cg
vs[30] = cb
vs[31] = ca
return vs
} | internal/graphics/vertex.go | 0.716417 | 0.542379 | vertex.go | starcoder |
package ptr
import (
"time"
)
// Bool returns a pointer value for the bool value passed in.
func Bool(v bool) *bool {
return &v
}
// BoolSlice returns a slice of bool pointers from the values
// passed in.
func BoolSlice(vs []bool) []*bool {
ps := make([]*bool, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// BoolMap returns a map of bool pointers from the values
// passed in.
func BoolMap(vs map[string]bool) map[string]*bool {
ps := make(map[string]*bool, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Byte returns a pointer value for the byte value passed in.
func Byte(v byte) *byte {
return &v
}
// ByteSlice returns a slice of byte pointers from the values
// passed in.
func ByteSlice(vs []byte) []*byte {
ps := make([]*byte, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// ByteMap returns a map of byte pointers from the values
// passed in.
func ByteMap(vs map[string]byte) map[string]*byte {
ps := make(map[string]*byte, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// String returns a pointer value for the string value passed in.
func String(v string) *string {
return &v
}
// StringSlice returns a slice of string pointers from the values
// passed in.
func StringSlice(vs []string) []*string {
ps := make([]*string, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// StringMap returns a map of string pointers from the values
// passed in.
func StringMap(vs map[string]string) map[string]*string {
ps := make(map[string]*string, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Int returns a pointer value for the int value passed in.
func Int(v int) *int {
return &v
}
// IntSlice returns a slice of int pointers from the values
// passed in.
func IntSlice(vs []int) []*int {
ps := make([]*int, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// IntMap returns a map of int pointers from the values
// passed in.
func IntMap(vs map[string]int) map[string]*int {
ps := make(map[string]*int, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Int8 returns a pointer value for the int8 value passed in.
func Int8(v int8) *int8 {
return &v
}
// Int8Slice returns a slice of int8 pointers from the values
// passed in.
func Int8Slice(vs []int8) []*int8 {
ps := make([]*int8, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Int8Map returns a map of int8 pointers from the values
// passed in.
func Int8Map(vs map[string]int8) map[string]*int8 {
ps := make(map[string]*int8, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Int16 returns a pointer value for the int16 value passed in.
func Int16(v int16) *int16 {
return &v
}
// Int16Slice returns a slice of int16 pointers from the values
// passed in.
func Int16Slice(vs []int16) []*int16 {
ps := make([]*int16, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Int16Map returns a map of int16 pointers from the values
// passed in.
func Int16Map(vs map[string]int16) map[string]*int16 {
ps := make(map[string]*int16, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Int32 returns a pointer value for the int32 value passed in.
func Int32(v int32) *int32 {
return &v
}
// Int32Slice returns a slice of int32 pointers from the values
// passed in.
func Int32Slice(vs []int32) []*int32 {
ps := make([]*int32, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Int32Map returns a map of int32 pointers from the values
// passed in.
func Int32Map(vs map[string]int32) map[string]*int32 {
ps := make(map[string]*int32, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Int64 returns a pointer value for the int64 value passed in.
func Int64(v int64) *int64 {
return &v
}
// Int64Slice returns a slice of int64 pointers from the values
// passed in.
func Int64Slice(vs []int64) []*int64 {
ps := make([]*int64, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Int64Map returns a map of int64 pointers from the values
// passed in.
func Int64Map(vs map[string]int64) map[string]*int64 {
ps := make(map[string]*int64, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Uint returns a pointer value for the uint value passed in.
func Uint(v uint) *uint {
return &v
}
// UintSlice returns a slice of uint pointers from the values
// passed in.
func UintSlice(vs []uint) []*uint {
ps := make([]*uint, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// UintMap returns a map of uint pointers from the values
// passed in.
func UintMap(vs map[string]uint) map[string]*uint {
ps := make(map[string]*uint, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Uint8 returns a pointer value for the uint8 value passed in.
func Uint8(v uint8) *uint8 {
return &v
}
// Uint8Slice returns a slice of uint8 pointers from the values
// passed in.
func Uint8Slice(vs []uint8) []*uint8 {
ps := make([]*uint8, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Uint8Map returns a map of uint8 pointers from the values
// passed in.
func Uint8Map(vs map[string]uint8) map[string]*uint8 {
ps := make(map[string]*uint8, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Uint16 returns a pointer value for the uint16 value passed in.
func Uint16(v uint16) *uint16 {
return &v
}
// Uint16Slice returns a slice of uint16 pointers from the values
// passed in.
func Uint16Slice(vs []uint16) []*uint16 {
ps := make([]*uint16, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Uint16Map returns a map of uint16 pointers from the values
// passed in.
func Uint16Map(vs map[string]uint16) map[string]*uint16 {
ps := make(map[string]*uint16, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Uint32 returns a pointer value for the uint32 value passed in.
func Uint32(v uint32) *uint32 {
return &v
}
// Uint32Slice returns a slice of uint32 pointers from the values
// passed in.
func Uint32Slice(vs []uint32) []*uint32 {
ps := make([]*uint32, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Uint32Map returns a map of uint32 pointers from the values
// passed in.
func Uint32Map(vs map[string]uint32) map[string]*uint32 {
ps := make(map[string]*uint32, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Uint64 returns a pointer value for the uint64 value passed in.
func Uint64(v uint64) *uint64 {
return &v
}
// Uint64Slice returns a slice of uint64 pointers from the values
// passed in.
func Uint64Slice(vs []uint64) []*uint64 {
ps := make([]*uint64, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Uint64Map returns a map of uint64 pointers from the values
// passed in.
func Uint64Map(vs map[string]uint64) map[string]*uint64 {
ps := make(map[string]*uint64, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Float32 returns a pointer value for the float32 value passed in.
func Float32(v float32) *float32 {
return &v
}
// Float32Slice returns a slice of float32 pointers from the values
// passed in.
func Float32Slice(vs []float32) []*float32 {
ps := make([]*float32, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Float32Map returns a map of float32 pointers from the values
// passed in.
func Float32Map(vs map[string]float32) map[string]*float32 {
ps := make(map[string]*float32, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Float64 returns a pointer value for the float64 value passed in.
func Float64(v float64) *float64 {
return &v
}
// Float64Slice returns a slice of float64 pointers from the values
// passed in.
func Float64Slice(vs []float64) []*float64 {
ps := make([]*float64, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// Float64Map returns a map of float64 pointers from the values
// passed in.
func Float64Map(vs map[string]float64) map[string]*float64 {
ps := make(map[string]*float64, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Time returns a pointer value for the time.Time value passed in.
func Time(v time.Time) *time.Time {
return &v
}
// TimeSlice returns a slice of time.Time pointers from the values
// passed in.
func TimeSlice(vs []time.Time) []*time.Time {
ps := make([]*time.Time, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// TimeMap returns a map of time.Time pointers from the values
// passed in.
func TimeMap(vs map[string]time.Time) map[string]*time.Time {
ps := make(map[string]*time.Time, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
}
// Duration returns a pointer value for the time.Duration value passed in.
func Duration(v time.Duration) *time.Duration {
return &v
}
// DurationSlice returns a slice of time.Duration pointers from the values
// passed in.
func DurationSlice(vs []time.Duration) []*time.Duration {
ps := make([]*time.Duration, len(vs))
for i, v := range vs {
vv := v
ps[i] = &vv
}
return ps
}
// DurationMap returns a map of time.Duration pointers from the values
// passed in.
func DurationMap(vs map[string]time.Duration) map[string]*time.Duration {
ps := make(map[string]*time.Duration, len(vs))
for k, v := range vs {
vv := v
ps[k] = &vv
}
return ps
} | vendor/github.com/aws/smithy-go/ptr/to_ptr.go | 0.851027 | 0.559651 | to_ptr.go | starcoder |
// Package pair provides oh's cons cell type.
package pair
import (
"fmt"
"github.com/michaelmacinnis/oh/internal/common"
"github.com/michaelmacinnis/oh/internal/common/interface/cell"
"github.com/michaelmacinnis/oh/internal/common/interface/literal"
)
const name = "cons"
//nolint:gochecknoglobals
var (
// Null is the empty list. It is also used to mark the end of a list.
Null cell.I
)
// T (pair) is a cons cell.
type T struct {
car cell.I
cdr cell.I
}
type pair = T
// Equal returns true if c is a pair with elements that are equal to p's.
func (p *pair) Equal(c cell.I) bool {
if p == Null && c == Null {
return true
}
return p.car.Equal(Car(c)) && p.cdr.Equal(Cdr(c))
}
// Literal returns the literal representation of the pair p.
func (p *pair) Literal() string {
return p.string(literal.String)
}
// Name returns the name for a pair type.
func (p *pair) Name() string {
return name
}
// String returns the text representation of the pair p.
func (p *pair) String() string {
return p.string(common.String)
}
func (p *pair) string(toString func(cell.I) string) string {
s := ""
improper := false
tail := Cdr(p)
if !Is(tail) {
improper = true
s += "(|" + name + " "
}
sublist := false
head := Car(p)
if Is(head) && Is(Cdr(head)) {
sublist = true
s += "("
}
if head == nil {
s += "()"
} else if head != Null {
s += toString(head)
}
if sublist {
s += ")"
}
if !improper && tail == Null {
return s
}
s += " "
if tail == nil {
s += "()"
} else {
s += toString(tail)
}
if improper {
s += "|)"
}
return s
}
// Functions specific to pair.
// Car returns the car/head/first member of the pair c.
// If c is not a pair, this function will panic.
func Car(c cell.I) cell.I {
return To(c).car
}
// Cdr returns the cdr/tail/rest member of the pair c.
// If c is not a pair, this function will panic.
func Cdr(c cell.I) cell.I {
return To(c).cdr
}
// Caar returns the car of the car of the pair c.
// A non-pair value where a pair is expected will cause a panic.
func Caar(c cell.I) cell.I {
return To(To(c).car).car
}
// Cadr returns the car of the cdr of the pair c.
// A non-pair value where a pair is expected will cause a panic.
func Cadr(c cell.I) cell.I {
return To(To(c).cdr).car
}
// Cdar returns the cdr of the car of the pair c.
// A non-pair value where a pair is expected will cause a panic.
func Cdar(c cell.I) cell.I {
return To(To(c).car).cdr
}
// Cddr returns the cdr of the cdr of the pair c.
// A non-pair value where a pair is expected will cause a panic.
func Cddr(c cell.I) cell.I {
return To(To(c).cdr).cdr
}
// Caddr returns the car of the cdr of the cdr of the pair c.
// A non-pair value where a pair is expected will cause a panic.
func Caddr(c cell.I) cell.I {
return To(To(To(c).cdr).cdr).car
}
// Cons conses h and t together to form a new pair.
func Cons(h, t cell.I) cell.I {
return &pair{car: h, cdr: t}
}
// SetCar sets the car/head/first of the pair c to value.
// If c is not a pair, this function will panic.
func SetCar(c, value cell.I) {
To(c).car = value
}
// SetCdr sets the cdr/tail/rest of the pair c to value.
// If c is not a pair, this function will panic.
func SetCdr(c, value cell.I) {
To(c).cdr = value
}
// A compiler-checked list of interfaces this type satisfies. Never called.
func implements() { //nolint:deadcode,unused
var t pair
// The pair type is a cell.
_ = cell.I(&t)
// The pair type has a literal representation.
_ = literal.I(&t)
// The pair type is a stringer.
_ = fmt.Stringer(&t)
}
func init() { //nolint:gochecknoinits
pair := &pair{}
pair.car = pair
pair.cdr = pair
Null = cell.I(pair)
} | internal/common/type/pair/pair.go | 0.716417 | 0.445288 | pair.go | starcoder |
package model
func predict0(features []float64) float64 {
if (features[2] < 0.5) || (features[2] == -1) {
if (features[1] < 0.5) || (features[1] == -1) {
if (features[0] < 0.5) || (features[0] == -1) {
if (features[7] < 0.108870044) || (features[7] == -1) {
if (features[9] < 0.264320642) || (features[9] == -1) {
if (features[6] < 0.741639555) || (features[6] == -1) {
if (features[13] < 0.338543236) || (features[13] == -1) {
return 7.53046131
} else {
return 1.16959524
}
} else {
return 66.677475
}
} else {
if (features[15] < 0.0908528864) || (features[15] == -1) {
if (features[3] < 0.366575122) || (features[3] == -1) {
return 5.02030754
} else {
return 0.730997026
}
} else {
if (features[3] < 0.0536817461) || (features[3] == -1) {
return 0.730997026
} else {
return 79.6467667
}
}
}
} else {
if (features[16] < 0.594482124) || (features[16] == -1) {
if (features[7] < 0.711652517) || (features[7] == -1) {
if (features[6] < 0.104887083) || (features[6] == -1) {
return 5.6051054
} else {
return 52.235836
}
} else {
if (features[17] < 0.630156219) || (features[17] == -1) {
return 35.6895027
} else {
return 9.78621387
}
}
} else {
if (features[15] < 0.559699059) || (features[15] == -1) {
if (features[14] < 0.281556785) || (features[14] == -1) {
return 5.36788464
} else {
return 40.2028084
}
} else {
if (features[11] < 0.0317210704) || (features[11] == -1) {
return 66.677475
} else {
return 4.85689306
}
}
}
}
} else {
return 9.99302959
}
} else {
return 1.45519412
}
} else {
return 99.5574265
}
} | examples/xgboost/XGBRegressor/booster0.go | 0.541166 | 0.490602 | booster0.go | starcoder |
package dbr
import (
"database/sql"
"reflect"
)
// Iterator is an interface to iterate over the result of a sql query
// and scan each row one at a time instead of getting all into one slice.
// The principe is similar to the standard sql.Rows type.
type Iterator interface {
Next() bool
Scan(interface{}) error
Close() error
Err() error
}
// recordMeta holds target struct's reflect metadata cache
type recordMeta struct {
ptr []interface{}
elemType reflect.Type
isSlice bool
isMap bool
isMapOfSlices bool
ts *tagStore
columns []string
}
func (m *recordMeta) scan(rows *sql.Rows, value interface{}) (err error) {
var v, elem, keyElem reflect.Value
if il, ok := value.(interfaceLoader); ok {
v = reflect.ValueOf(il.v)
} else {
v = reflect.ValueOf(value)
}
if m.elemType != nil {
elem = reflectAlloc(m.elemType)
} else if m.isMapOfSlices {
elem = reflectAlloc(v.Type().Elem().Elem())
} else if m.isSlice || m.isMap {
elem = reflectAlloc(v.Type().Elem())
} else {
elem = v
}
if m.isMap {
err = m.ts.findPtr(elem, m.columns[1:], m.ptr[1:])
if err != nil {
return
}
keyElem = reflectAlloc(v.Type().Key())
err = m.ts.findPtr(keyElem, m.columns[:1], m.ptr[:1])
if err != nil {
return
}
} else {
err = m.ts.findPtr(elem, m.columns, m.ptr)
if err != nil {
return
}
}
// Before scanning, set nil pointer to dummy dest.
// After that, reset pointers to nil for the next batch.
for i := range m.ptr {
if m.ptr[i] == nil {
m.ptr[i] = dummyDest
}
}
err = rows.Scan(m.ptr...)
if err != nil {
return
}
for i := range m.ptr {
m.ptr[i] = nil
}
if m.isSlice {
v.Set(reflect.Append(v, elem))
} else if m.isMapOfSlices {
s := v.MapIndex(keyElem)
if !s.IsValid() {
s = reflect.Zero(v.Type().Elem())
}
v.SetMapIndex(keyElem, reflect.Append(s, elem))
} else if m.isMap {
v.SetMapIndex(keyElem, elem)
}
return
}
func newRecordMeta(column []string, value interface{}) (meta *recordMeta, err error) {
ptr := make([]interface{}, len(column))
var v reflect.Value
var elemType reflect.Type
if il, ok := value.(interfaceLoader); ok {
v = reflect.ValueOf(il.v)
elemType = il.typ
} else {
v = reflect.ValueOf(value)
}
if v.Kind() != reflect.Ptr || v.IsNil() {
return nil, ErrInvalidPointer
}
v = v.Elem()
isScanner := v.Addr().Type().Implements(typeScanner)
isSlice := v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 && !isScanner
isMap := v.Kind() == reflect.Map && !isScanner
isMapOfSlices := isMap && v.Type().Elem().Kind() == reflect.Slice && v.Type().Elem().Elem().Kind() != reflect.Uint8
if isMap {
v.Set(reflect.MakeMap(v.Type()))
}
s := newTagStore()
return &recordMeta{
elemType: elemType,
isSlice: isSlice,
isMap: isMap,
isMapOfSlices: isMapOfSlices,
ts: s,
ptr: ptr,
columns: column,
}, nil
}
// iteratorInternals is the Iterator implementation (hidden)
type iteratorInternals struct {
rows *sql.Rows
recordMeta *recordMeta
columns []string
}
// Next prepares the next result row for reading with the Scan method.
// It returns false is case of error or if there are not more data to fetch.
// If the end of the resultset is reached, it automaticaly free resources like
// the Close method.
func (i *iteratorInternals) Next() bool {
return i.rows.Next()
}
// Scan fill the given struct with the current row.
func (i *iteratorInternals) Scan(value interface{}) (err error) {
// First scan
if i.recordMeta == nil {
i.recordMeta, err = newRecordMeta(i.columns, value)
if err != nil {
return err
}
}
return i.recordMeta.scan(i.rows, value)
}
// Close frees ressources created by the request execution.
func (i *iteratorInternals) Close() error {
if err := i.Err(); err != nil {
i.rows.Close()
return err
}
return i.rows.Close()
}
// Err returns the error that was encountered during iteration, or nil.
// Always check Err after an iteration, like with the standard sql.Err method.
func (i *iteratorInternals) Err() error {
return i.rows.Err()
} | iterator.go | 0.540196 | 0.422207 | iterator.go | starcoder |
package series
import (
"sort"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/grafana/loki/pkg/prom1/storage/metric"
)
// ConcreteSeriesSet implements storage.SeriesSet.
type ConcreteSeriesSet struct {
cur int
series []storage.Series
}
// NewConcreteSeriesSet instantiates an in-memory series set from a series
// Series will be sorted by labels.
func NewConcreteSeriesSet(series []storage.Series) storage.SeriesSet {
sort.Sort(byLabels(series))
return &ConcreteSeriesSet{
cur: -1,
series: series,
}
}
// Next iterates through a series set and implements storage.SeriesSet.
func (c *ConcreteSeriesSet) Next() bool {
c.cur++
return c.cur < len(c.series)
}
// At returns the current series and implements storage.SeriesSet.
func (c *ConcreteSeriesSet) At() storage.Series {
return c.series[c.cur]
}
// Err implements storage.SeriesSet.
func (c *ConcreteSeriesSet) Err() error {
return nil
}
// Warnings implements storage.SeriesSet.
func (c *ConcreteSeriesSet) Warnings() storage.Warnings {
return nil
}
// ConcreteSeries implements storage.Series.
type ConcreteSeries struct {
labels labels.Labels
samples []model.SamplePair
}
// NewConcreteSeries instantiates an in memory series from a list of samples & labels
func NewConcreteSeries(ls labels.Labels, samples []model.SamplePair) *ConcreteSeries {
return &ConcreteSeries{
labels: ls,
samples: samples,
}
}
// Labels implements storage.Series
func (c *ConcreteSeries) Labels() labels.Labels {
return c.labels
}
// Iterator implements storage.Series
func (c *ConcreteSeries) Iterator() chunkenc.Iterator {
return NewConcreteSeriesIterator(c)
}
// concreteSeriesIterator implements chunkenc.Iterator.
type concreteSeriesIterator struct {
cur int
series *ConcreteSeries
}
// NewConcreteSeriesIterator instaniates an in memory chunkenc.Iterator
func NewConcreteSeriesIterator(series *ConcreteSeries) chunkenc.Iterator {
return &concreteSeriesIterator{
cur: -1,
series: series,
}
}
func (c *concreteSeriesIterator) Seek(t int64) bool {
c.cur = sort.Search(len(c.series.samples), func(n int) bool {
return c.series.samples[n].Timestamp >= model.Time(t)
})
return c.cur < len(c.series.samples)
}
func (c *concreteSeriesIterator) At() (t int64, v float64) {
s := c.series.samples[c.cur]
return int64(s.Timestamp), float64(s.Value)
}
func (c *concreteSeriesIterator) Next() bool {
c.cur++
return c.cur < len(c.series.samples)
}
func (c *concreteSeriesIterator) Err() error {
return nil
}
// NewErrIterator instantiates an errIterator
func NewErrIterator(err error) chunkenc.Iterator {
return errIterator{err}
}
// errIterator implements chunkenc.Iterator, just returning an error.
type errIterator struct {
err error
}
func (errIterator) Seek(int64) bool {
return false
}
func (errIterator) Next() bool {
return false
}
func (errIterator) At() (t int64, v float64) {
return 0, 0
}
func (e errIterator) Err() error {
return e.err
}
// MatrixToSeriesSet creates a storage.SeriesSet from a model.Matrix
// Series will be sorted by labels.
func MatrixToSeriesSet(m model.Matrix) storage.SeriesSet {
series := make([]storage.Series, 0, len(m))
for _, ss := range m {
series = append(series, &ConcreteSeries{
labels: metricToLabels(ss.Metric),
samples: ss.Values,
})
}
return NewConcreteSeriesSet(series)
}
// MetricsToSeriesSet creates a storage.SeriesSet from a []metric.Metric
func MetricsToSeriesSet(ms []metric.Metric) storage.SeriesSet {
series := make([]storage.Series, 0, len(ms))
for _, m := range ms {
series = append(series, &ConcreteSeries{
labels: metricToLabels(m.Metric),
samples: nil,
})
}
return NewConcreteSeriesSet(series)
}
func metricToLabels(m model.Metric) labels.Labels {
ls := make(labels.Labels, 0, len(m))
for k, v := range m {
ls = append(ls, labels.Label{
Name: string(k),
Value: string(v),
})
}
// PromQL expects all labels to be sorted! In general, anyone constructing
// a labels.Labels list is responsible for sorting it during construction time.
sort.Sort(ls)
return ls
}
type byLabels []storage.Series
func (b byLabels) Len() int { return len(b) }
func (b byLabels) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b byLabels) Less(i, j int) bool { return labels.Compare(b[i].Labels(), b[j].Labels()) < 0 }
type DeletedSeries struct {
series storage.Series
deletedIntervals []model.Interval
}
func NewDeletedSeries(series storage.Series, deletedIntervals []model.Interval) storage.Series {
return &DeletedSeries{
series: series,
deletedIntervals: deletedIntervals,
}
}
func (d DeletedSeries) Labels() labels.Labels {
return d.series.Labels()
}
func (d DeletedSeries) Iterator() chunkenc.Iterator {
return NewDeletedSeriesIterator(d.series.Iterator(), d.deletedIntervals)
}
type DeletedSeriesIterator struct {
itr chunkenc.Iterator
deletedIntervals []model.Interval
}
func NewDeletedSeriesIterator(itr chunkenc.Iterator, deletedIntervals []model.Interval) chunkenc.Iterator {
return &DeletedSeriesIterator{
itr: itr,
deletedIntervals: deletedIntervals,
}
}
func (d DeletedSeriesIterator) Seek(t int64) bool {
if found := d.itr.Seek(t); !found {
return false
}
seekedTs, _ := d.itr.At()
if d.isDeleted(seekedTs) {
// point we have seeked into is deleted, Next() should find a new non-deleted sample which is after t and seekedTs
return d.Next()
}
return true
}
func (d DeletedSeriesIterator) At() (t int64, v float64) {
return d.itr.At()
}
func (d DeletedSeriesIterator) Next() bool {
for d.itr.Next() {
ts, _ := d.itr.At()
if d.isDeleted(ts) {
continue
}
return true
}
return false
}
func (d DeletedSeriesIterator) Err() error {
return d.itr.Err()
}
// isDeleted removes intervals which are past ts while checking for whether ts happens to be in one of the deleted intervals
func (d *DeletedSeriesIterator) isDeleted(ts int64) bool {
mts := model.Time(ts)
for _, interval := range d.deletedIntervals {
if mts > interval.End {
d.deletedIntervals = d.deletedIntervals[1:]
continue
} else if mts < interval.Start {
return false
}
return true
}
return false
}
type emptySeries struct {
labels labels.Labels
}
func NewEmptySeries(labels labels.Labels) storage.Series {
return emptySeries{labels}
}
func (e emptySeries) Labels() labels.Labels {
return e.labels
}
func (emptySeries) Iterator() chunkenc.Iterator {
return NewEmptySeriesIterator()
}
type emptySeriesIterator struct {
}
func NewEmptySeriesIterator() chunkenc.Iterator {
return emptySeriesIterator{}
}
func (emptySeriesIterator) Seek(t int64) bool {
return false
}
func (emptySeriesIterator) At() (t int64, v float64) {
return 0, 0
}
func (emptySeriesIterator) Next() bool {
return false
}
func (emptySeriesIterator) Err() error {
return nil
}
type seriesSetWithWarnings struct {
wrapped storage.SeriesSet
warnings storage.Warnings
}
func NewSeriesSetWithWarnings(wrapped storage.SeriesSet, warnings storage.Warnings) storage.SeriesSet {
return seriesSetWithWarnings{
wrapped: wrapped,
warnings: warnings,
}
}
func (s seriesSetWithWarnings) Next() bool {
return s.wrapped.Next()
}
func (s seriesSetWithWarnings) At() storage.Series {
return s.wrapped.At()
}
func (s seriesSetWithWarnings) Err() error {
return s.wrapped.Err()
}
func (s seriesSetWithWarnings) Warnings() storage.Warnings {
return append(s.wrapped.Warnings(), s.warnings...)
} | pkg/querier/series/series_set.go | 0.881487 | 0.463566 | series_set.go | starcoder |
package optimization
import (
"fmt"
. "github.com/jakecoffman/graph"
"strings"
)
type World struct {
width, height int
world []Node
}
// NewWorld is the World constructor. Takes a serialized World as input.
func NewWorld(input string) *World {
str := strings.TrimSpace(input)
rows := strings.Split(str, "\n")
g := &World{
width: len(rows[0]),
height: len(rows),
}
g.world = make([]Node, g.width*g.height)
for y, row := range rows {
for x, raw := range row {
kind, ok := Kinds[raw]
if !ok {
panic("Unknown rune: " + string(raw))
} else {
node := g.At(x, y)
node.Kind = kind
node.Pos = Pos{x, y}
}
}
}
for y := 0; y < g.height; y++ {
for x := 0; x < g.width; x++ {
node := g.At(x, y)
if node.Kind == Wall {
continue
}
WalkNeighbors(Pos{x, y}, func(nX, nY int) {
if nX >= g.width {
nX -= g.width
}
if nX < 0 {
nX += g.width
}
if nY < 0 || nY >= g.height {
return
}
neighbor := g.At(nX, nY)
if neighbor.Kind != Wall {
node.Neighbors = append(node.Neighbors, neighbor)
}
})
}
}
return g
}
// RenderPath serializes a path in a human readable way.
func (w *World) RenderPath(path []*Node) string {
pathLocs := map[Pos]bool{}
for _, p := range path {
pathLocs[p.Pos] = true
}
rows := make([]string, w.height)
for x := 0; x < w.width; x++ {
for y := 0; y < w.height; y++ {
t := w.At(x, y)
r := ' '
if pathLocs[Pos{x, y}] {
r = 'x'
} else if t != nil {
r = Symbols[t.Kind]
}
rows[y] += string(r)
}
}
return strings.Join(rows, "\n")
}
func (w *World) At(x, y int) *Node {
return &w.world[w.width*y+x]
}
func (w *World) FindOne(kind Kind) *Node {
for y := 0; y < w.height; y++ {
for x := 0; x < w.width; x++ {
node := w.At(x, y)
if node.Kind == kind {
return node
}
}
}
return nil
}
func (w *World) FindAll(kind Kind) (nodes []*Node) {
for y := 0; y < w.height; y++ {
for x := 0; x < w.width; x++ {
node := w.At(x, y)
if node.Kind == kind {
nodes = append(nodes, node)
}
}
}
return
}
type Node struct {
Kind
Pos
Neighbors []*Node
Visited int
}
func (n *Node) String() string {
return fmt.Sprintf(`[Node %v,%v %v]`, n.X, n.Y, Symbols[n.Kind])
}
type Kind rune
const (
Plain = Kind(iota)
Wall
Start
Goal
)
var Kinds = map[rune]Kind{
' ': Plain,
'#': Wall,
'S': Start,
'G': Goal,
}
var Symbols = map[Kind]rune{
Plain: ' ',
Wall: '#',
Start: 'S',
Goal: 'G',
} | optimization/world.go | 0.642096 | 0.422564 | world.go | starcoder |
package maidenhead
import (
"fmt"
"math"
)
const (
// Earth radius
r = 6371
)
var compassBearing = []struct {
label string
start, ended float64
}{
{"N", 000.00, 011.25}, {"NNE", 011.25, 033.75}, {"NE", 033.75, 056.25}, {"ENE", 056.25, 078.75},
{"E", 078.75, 101.25}, {"ESE", 101.25, 123.75}, {"SE", 123.75, 146.25}, {"SSE", 146.25, 168.75},
{"S", 168.75, 191.25}, {"SSW", 191.25, 213.75}, {"SW", 213.75, 236.25}, {"WSW", 236.25, 258.75},
{"W", 258.75, 281.25}, {"WNW", 281.25, 303.75}, {"NW", 303.75, 326.25}, {"NNW", 326.25, 348.75},
{"N", 348.75, 360.00},
}
// Point is a geographical point on the map.
type Point struct {
Latitude float64
Longitude float64
}
// NewPoint returns a new Point structure with given latitude and longitude.
func NewPoint(latitude, longitude float64) Point {
return Point{latitude, longitude}
}
// ParseLocator parses a Maidenhead Locator with permissive rule matching.
func ParseLocator(locator string) (Point, error) {
return parseLocator(locator, false, false)
}
// ParseLocatorStrict parses a Maidenhead Locator with strict rule matching.
func ParseLocatorStrict(locator string) (Point, error) {
return parseLocator(locator, true, false)
}
// ParseLocatorCentered parses a Maidenhead Locator with permissive rule matching.
// Returns Points structure with coordinates of the square center
func ParseLocatorCentered(locator string) (Point, error) {
return parseLocator(locator, false, true)
}
// ParseLocatorStrictCentered parses a Maidenhead Locator with strict rule matching.
// Returns Points structure with coordinates of the square center
func ParseLocatorStrictCentered(locator string) (Point, error) {
return parseLocator(locator, true, true)
}
// EqualTo returns true if the coordinates point to the same geographical location.
func (p Point) EqualTo(other Point) bool {
var (
dlat = p.Latitude - other.Latitude
dlng = p.Longitude - other.Longitude
)
for dlat < -180.0 {
dlat += 360.0
}
for dlat > 180.0 {
dlat -= 360.0
}
for dlng < -90.0 {
dlng += 90.0
}
for dlng > 90.0 {
dlng -= 90.0
}
return dlat == 0.0 && dlng == 0.0
}
// Bearing calculates the (approximate) bearing to another heading.
func (p Point) Bearing(heading Point) float64 {
var (
hn = p.Latitude / 180 * math.Pi
he = p.Longitude / 180 * math.Pi
n = heading.Latitude / 180 * math.Pi
e = heading.Longitude / 180 * math.Pi
co = math.Cos(he-e)*math.Cos(hn)*math.Cos(n) + math.Sin(hn)*math.Sin(n)
ca = math.Atan(math.Abs(math.Sqrt(1-co*co) / co))
)
if co < 0.0 {
ca = math.Pi - ca
}
var si = math.Sin(e-he) * math.Cos(n) * math.Cos(hn)
co = math.Sin(n) - math.Sin(hn)*math.Cos(ca)
var az = math.Atan(math.Abs(si / co))
if co < 0.0 {
az = math.Pi - az
}
if si < 0.0 {
az = -az
}
if az < 0.0 {
az = az + 2.0*math.Pi
}
return az * 180 / math.Pi
}
// CompassBearing returns the compass bearing to a heading.
func (p Point) CompassBearing(heading Point) string {
bearing := p.Bearing(heading)
for bearing < 0.0 {
bearing += 360.0
}
for bearing > 360.0 {
bearing -= 360.0
}
for _, compass := range compassBearing {
if bearing >= compass.start && bearing <= compass.ended {
return compass.label
}
}
// Should never reach
return ""
}
// Distance calculates the (approximate) distance to another point in km.
func (p Point) Distance(other Point) float64 {
var (
hn = p.Latitude / 180 * math.Pi
he = p.Longitude / 180 * math.Pi
n = other.Latitude / 180 * math.Pi
e = other.Longitude / 180 * math.Pi
co = math.Cos(he-e)*math.Cos(hn)*math.Cos(n) + math.Sin(hn)*math.Sin(n)
ca = math.Atan(math.Abs(math.Sqrt(1-co*co) / co))
)
if co < 0.0 {
ca = math.Pi - ca
}
return r * ca
}
// GridSquare returns a Maidenhead Locator for the point coordinates.
func (p Point) GridSquare() (string, error) {
return locator(p, SubSquarePrecision)
}
// Locator returns a Maidenhead Locator for the point coordinates with
// specified precision
func (p Point) Locator(precision int) (string, error) {
return locator(p, precision)
}
// String returns a stringified Point structure.
func (p Point) String() string {
return fmt.Sprintf("Point(%f, %f)", p.Latitude, p.Longitude)
} | point.go | 0.853608 | 0.539954 | point.go | starcoder |
package iso20022
// Execution of a subscription order.
type SubscriptionExecution4 struct {
// Unique and unambiguous identifier for an order, as assigned by the instructing party.
OrderReference *Max35Text `xml:"OrdrRef"`
// Unique and unambiguous identifier for an order execution, as assigned by a confirming party.
DealReference *Max35Text `xml:"DealRef"`
// Specifies the category of the investment fund order.
OrderType []*FundOrderType1 `xml:"OrdrTp,omitempty"`
// Investment fund class to which an investment fund order execution is related.
FinancialInstrumentDetails *FinancialInstrument6 `xml:"FinInstrmDtls"`
// Number of investment fund units subscribed.
UnitsNumber *FinancialInstrumentQuantity1 `xml:"UnitsNb"`
// Indicates the rounding direction applied to nearest unit.
Rounding *RoundingDirection2Code `xml:"Rndg,omitempty"`
// Net amount of money invested in a specific financial instrument by an investor, expressed in the currency requested by the investor.
NetAmount *ActiveCurrencyAndAmount `xml:"NetAmt"`
// Amount of money invested in a specific financial instrument by an investor, including all charges, commissions, and tax, expressed in the currency requested by the investor.
GrossAmount *ActiveCurrencyAndAmount `xml:"GrssAmt,omitempty"`
// Date and time at which a price is applied, according to the terms stated in the prospectus.
TradeDateTime *DateAndDateTimeChoice `xml:"TradDtTm"`
// Price at which the order was executed.
PriceDetails *UnitPrice5 `xml:"PricDtls"`
// Indicates whether the order has been partially executed, ie, the confirmed quantity does not match the ordered quantity for a given financial instrument.
PartiallyExecutedIndicator *YesNoIndicator `xml:"PrtlyExctdInd"`
// Indicates whether the dividend is included, ie, cum-dividend, in the executed price. When the dividend is not included, the price will be ex-dividend.
CumDividendIndicator *YesNoIndicator `xml:"CumDvddInd"`
// Part of the price deemed as accrued income or profit rather than capital. The interim profit amount is used for tax purposes.
InterimProfitAmount *ProfitAndLoss1Choice `xml:"IntrmPrftAmt,omitempty"`
// Information needed to process a currency exchange or conversion.
ForeignExchangeDetails []*ForeignExchangeTerms4 `xml:"FXDtls,omitempty"`
// Dividend option chosen by the account owner based on the options offered in the prospectus.
IncomePreference *IncomePreference1Code `xml:"IncmPref,omitempty"`
// Reference of a letter of intent program, in which sales commissions are reduced based on the aggregate of a customer's actual purchase and anticipated purchases, over a specific period of time, and as agreed by the customer. A letter of intent program is mainly used in the US market.
LetterIntentReference *Max35Text `xml:"LttrInttRef,omitempty"`
// Reference of an accumulation right program, in which sales commissions are based on a customer's present purchases of shares and the aggregate quantity previously purchased by the customer. An accumulation rights program is mainly used in the US market.
AccumulationRightReference *Max35Text `xml:"AcmltnRghtRef,omitempty"`
// Amount of money associated with a service.
ChargeGeneralDetails *TotalCharges2 `xml:"ChrgGnlDtls,omitempty"`
// Amount of money due to a party as compensation for a service.
CommissionGeneralDetails *TotalCommissions2 `xml:"ComssnGnlDtls,omitempty"`
// Tax related to an investment fund order.
TaxGeneralDetails *TotalTaxes2 `xml:"TaxGnlDtls,omitempty"`
// Parameters used to execute the settlement of an investment fund order.
SettlementAndCustodyDetails *FundSettlementParameters3 `xml:"SttlmAndCtdyDtls,omitempty"`
// Indicates whether the financial instrument is to be physically delivered.
PhysicalDeliveryIndicator *YesNoIndicator `xml:"PhysDlvryInd"`
// Information related to physical delivery of the securities.
PhysicalDeliveryDetails *DeliveryParameters3 `xml:"PhysDlvryDtls,omitempty"`
// Currency requested for settlement of cash proceeds.
RequestedSettlementCurrency *CurrencyCode `xml:"ReqdSttlmCcy,omitempty"`
// Currency to be used for pricing the fund. This currency must be among the set of currencies in which the price may be expressed, as stated in the prospectus.
RequestedNAVCurrency *CurrencyCode `xml:"ReqdNAVCcy,omitempty"`
// Return of cash that has been overpaid for a subscription.
Refund *ActiveCurrencyAndAmount `xml:"Rfnd,omitempty"`
// Interest received when a subscription amount is paid in advance and then invested by the fund.
SubscriptionInterest *ActiveCurrencyAndAmount `xml:"SbcptIntrst,omitempty"`
// Payment transaction resulting from the investment fund order execution.
CashSettlementDetails *PaymentTransaction13 `xml:"CshSttlmDtls,omitempty"`
}
func (s *SubscriptionExecution4) SetOrderReference(value string) {
s.OrderReference = (*Max35Text)(&value)
}
func (s *SubscriptionExecution4) SetDealReference(value string) {
s.DealReference = (*Max35Text)(&value)
}
func (s *SubscriptionExecution4) AddOrderType() *FundOrderType1 {
newValue := new(FundOrderType1)
s.OrderType = append(s.OrderType, newValue)
return newValue
}
func (s *SubscriptionExecution4) AddFinancialInstrumentDetails() *FinancialInstrument6 {
s.FinancialInstrumentDetails = new(FinancialInstrument6)
return s.FinancialInstrumentDetails
}
func (s *SubscriptionExecution4) AddUnitsNumber() *FinancialInstrumentQuantity1 {
s.UnitsNumber = new(FinancialInstrumentQuantity1)
return s.UnitsNumber
}
func (s *SubscriptionExecution4) SetRounding(value string) {
s.Rounding = (*RoundingDirection2Code)(&value)
}
func (s *SubscriptionExecution4) SetNetAmount(value, currency string) {
s.NetAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SubscriptionExecution4) SetGrossAmount(value, currency string) {
s.GrossAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SubscriptionExecution4) AddTradeDateTime() *DateAndDateTimeChoice {
s.TradeDateTime = new(DateAndDateTimeChoice)
return s.TradeDateTime
}
func (s *SubscriptionExecution4) AddPriceDetails() *UnitPrice5 {
s.PriceDetails = new(UnitPrice5)
return s.PriceDetails
}
func (s *SubscriptionExecution4) SetPartiallyExecutedIndicator(value string) {
s.PartiallyExecutedIndicator = (*YesNoIndicator)(&value)
}
func (s *SubscriptionExecution4) SetCumDividendIndicator(value string) {
s.CumDividendIndicator = (*YesNoIndicator)(&value)
}
func (s *SubscriptionExecution4) AddInterimProfitAmount() *ProfitAndLoss1Choice {
s.InterimProfitAmount = new(ProfitAndLoss1Choice)
return s.InterimProfitAmount
}
func (s *SubscriptionExecution4) AddForeignExchangeDetails() *ForeignExchangeTerms4 {
newValue := new(ForeignExchangeTerms4)
s.ForeignExchangeDetails = append(s.ForeignExchangeDetails, newValue)
return newValue
}
func (s *SubscriptionExecution4) SetIncomePreference(value string) {
s.IncomePreference = (*IncomePreference1Code)(&value)
}
func (s *SubscriptionExecution4) SetLetterIntentReference(value string) {
s.LetterIntentReference = (*Max35Text)(&value)
}
func (s *SubscriptionExecution4) SetAccumulationRightReference(value string) {
s.AccumulationRightReference = (*Max35Text)(&value)
}
func (s *SubscriptionExecution4) AddChargeGeneralDetails() *TotalCharges2 {
s.ChargeGeneralDetails = new(TotalCharges2)
return s.ChargeGeneralDetails
}
func (s *SubscriptionExecution4) AddCommissionGeneralDetails() *TotalCommissions2 {
s.CommissionGeneralDetails = new(TotalCommissions2)
return s.CommissionGeneralDetails
}
func (s *SubscriptionExecution4) AddTaxGeneralDetails() *TotalTaxes2 {
s.TaxGeneralDetails = new(TotalTaxes2)
return s.TaxGeneralDetails
}
func (s *SubscriptionExecution4) AddSettlementAndCustodyDetails() *FundSettlementParameters3 {
s.SettlementAndCustodyDetails = new(FundSettlementParameters3)
return s.SettlementAndCustodyDetails
}
func (s *SubscriptionExecution4) SetPhysicalDeliveryIndicator(value string) {
s.PhysicalDeliveryIndicator = (*YesNoIndicator)(&value)
}
func (s *SubscriptionExecution4) AddPhysicalDeliveryDetails() *DeliveryParameters3 {
s.PhysicalDeliveryDetails = new(DeliveryParameters3)
return s.PhysicalDeliveryDetails
}
func (s *SubscriptionExecution4) SetRequestedSettlementCurrency(value string) {
s.RequestedSettlementCurrency = (*CurrencyCode)(&value)
}
func (s *SubscriptionExecution4) SetRequestedNAVCurrency(value string) {
s.RequestedNAVCurrency = (*CurrencyCode)(&value)
}
func (s *SubscriptionExecution4) SetRefund(value, currency string) {
s.Refund = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SubscriptionExecution4) SetSubscriptionInterest(value, currency string) {
s.SubscriptionInterest = NewActiveCurrencyAndAmount(value, currency)
}
func (s *SubscriptionExecution4) AddCashSettlementDetails() *PaymentTransaction13 {
s.CashSettlementDetails = new(PaymentTransaction13)
return s.CashSettlementDetails
} | SubscriptionExecution4.go | 0.846768 | 0.400456 | SubscriptionExecution4.go | starcoder |
package neuralnet
import (
"github.com/gonum/matrix/mat64"
"math"
"math/rand"
)
type Matrix interface {
mat64.Matrix
mat64.Vectorer
mat64.VectorSetter
mat64.RowViewer
mat64.ColViewer
mat64.Augmenter
mat64.Muler
mat64.Sumer
mat64.Suber
mat64.Adder
mat64.ElemMuler
mat64.ElemDiver
mat64.Equaler
mat64.Applyer
}
func Prepend(sl []float64, val float64) []float64 {
valSl := []float64{val}
return append(valSl, sl...)
}
func NewZeroes(rows, cols int) Matrix {
zeroes := make([]float64, rows*cols)
for i, _ := range zeroes {
zeroes[i] = 0
}
m := mat64.NewDense(rows, cols, zeroes)
return m
}
func NewOnes(rows, cols int) Matrix {
ones := make([]float64, rows*cols)
for i, _ := range ones {
ones[i] = 1
}
m := mat64.NewDense(rows, cols, ones)
return m
}
func NewRand(rows, cols int) Matrix {
rands := make([]float64, rows*cols)
for i, _ := range rands {
rands[i] = (rand.Float64() * 2) - 1.0
}
m := mat64.NewDense(rows, cols, rands)
return m
}
// TODO: turn this into a function that returns a function (via closure)
func NewForValue(rows, cols int, val float64) Matrix {
vals := make([]float64, rows*cols)
for i, _ := range vals {
vals[i] = val
}
m := mat64.NewDense(rows, cols, vals)
return m
}
// TODO: Test this
func MatrixToSlice(m Matrix) [][]float64 {
rows, _ := m.Dims()
sl := make([][]float64, rows)
for i := 0; i < rows; i++ {
var dst []float64
sl[i] = m.Row(dst, i)
}
return sl
}
// The following functions can be passed to a mat64.Applyer as an ApplyFunc
// Calculate the sigmoid of a matrix cell
func Sigmoid(r, c int, z float64) float64 {
return 1.0 / (1.0 + math.Exp(-z))
}
// Calculate the gradient of the sigmoid of a matrix cell
func SigmoidGradient(r, c int, z float64) float64 {
s := Sigmoid(r, c, z)
return s * (1 - s)
}
// Calculate the log of a matrix cell
func Log(r, c int, z float64) float64 {
return math.Log(z)
}
// Calculate the square of a matrix cell
func Square(r, c int, z float64) float64 {
return math.Pow(z, 2)
} | matrix.go | 0.640861 | 0.608041 | matrix.go | starcoder |
package businessdays
import (
"time"
"github.com/mgmayfield/GoHolidayCalendar/holidays"
)
// The United States has 10 business days / federal holidays
// New Years, MLK, President's Day, Memorial Day, Independence Day
// Labor Day, Columbus Day, Veterans Day, Thanksgiving, Christmas
// IsNewYears falls on the 1st of January
// It is an observed holiday on Friday Dec 31 or Monday Jan 2
func IsNewYears(input time.Time) bool {
if input.Month() == time.January {
if input.Day() == 1 {
return true
}
if input.Day() == 2 && input.Weekday() == time.Monday {
return true
}
}
if input.Month() == time.December {
if input.Day() == 31 && input.Weekday() == time.Friday {
return true
}
}
return false
}
// IsMLK falls on the third Monday of January
func IsMLK(input time.Time) bool {
return holidays.IsMLK(input)
}
// IsPresidentsDay falls on the third Monday of February
func IsPresidentsDay(input time.Time) bool {
return holidays.IsPresidentsDay(input)
}
// IsMemorialDay falls on the last Monday of May
func IsMemorialDay(input time.Time) bool {
return holidays.IsMemorialDay(input)
}
// IsIndependenceDay falls on the 4th of July
// It is an observed holiday on Friday July 3 or Monday July 5
func IsIndependenceDay(input time.Time) bool {
if input.Month() == time.July {
if input.Day() == 4 {
return true
}
if input.Day() == 3 && input.Weekday() == time.Friday {
return true
}
if input.Day() == 5 && input.Weekday() == time.Monday {
return true
}
}
return false
}
// IsLaborDay falls on the first Monday of September
func IsLaborDay(input time.Time) bool {
return holidays.IsLaborDay(input)
}
// IsColumbusDay falls on the second Monday of October
func IsColumbusDay(input time.Time) bool {
return holidays.IsColumbusDay(input)
}
// IsVeteransDay falls on the 11th of November
// It is an observed holiday on Friday Nov 10 or Monday Nov 12
func IsVeteransDay(input time.Time) bool {
if input.Month() == time.November {
if input.Day() == 11 {
return true
}
if input.Day() == 10 && input.Weekday() == time.Friday {
return true
}
if input.Day() == 12 && input.Weekday() == time.Monday {
return true
}
}
return false
}
// IsThanksgiving falls on the fourth Thursday of November
func IsThanksgiving(input time.Time) bool {
return holidays.IsThanksgiving(input)
}
// IsChristmas falls on the 25th of December
// It is an observed holiday on Friday Dec 24 or Monday Dec 26
func IsChristmas(input time.Time) bool {
if input.Month() == time.December {
if input.Day() == 25 {
return true
}
if input.Day() == 24 && input.Weekday() == time.Friday {
return true
}
if input.Day() == 26 && input.Weekday() == time.Monday {
return true
}
}
return false
} | businessDays/businessDays.go | 0.5769 | 0.566498 | businessDays.go | starcoder |
package gogrid
import (
"errors"
"fmt"
"strings"
)
type Alignment int
const (
Left Alignment = iota
Center
Right
)
type Grid struct {
data [][]string // data[row][column] => cell
colors []string // color to use for a row
ColumnAlignments []Alignment // controls column alignment for each column
ColumnWidths []int // 0 implies use as many text columns as required for fields
dataWidths []int // tracks widest cell for each numbered column
Delimiter string // Delimiter allows specifying a string to put between each column other than a single space.
HeaderColor string // empty implies no special header colorization
DefaultRowColor string
DefaultAlignment Alignment
DefaultWidth int
}
// AppendColumn appends the specified column to the grid, specifying the new
// column's alignment and maximum width.
func (g *Grid) AppendColumn(alignment Alignment, maxWidth int, column []string) error {
gridRowCount := len(g.data)
var dataWidthsMax int
if gridRowCount > 0 {
if thisColumnRowCount := len(column); thisColumnRowCount != gridRowCount {
return fmt.Errorf("cannot append column with different number of rows than already in grid: %d != %d", thisColumnRowCount, gridRowCount)
}
for ri, cell := range column {
g.data[ri] = append(g.data[ri], cell)
if dw := len(cell); dw > dataWidthsMax {
dataWidthsMax = dw
}
}
} else {
// grid has no data yet; append one row for each cell provided
for _, cell := range column {
g.data = append(g.data, []string{cell})
g.colors = append(g.colors, g.DefaultRowColor)
if dw := len(cell); dw > dataWidthsMax {
dataWidthsMax = dw
}
}
}
g.ColumnAlignments = append(g.ColumnAlignments, alignment)
g.ColumnWidths = append(g.ColumnWidths, maxWidth)
g.dataWidths = append(g.dataWidths, dataWidthsMax)
return nil
}
// AppendRow appends the specified columrow
func (g *Grid) AppendRow(column []string) error {
if len(g.data) > 0 {
if lc, le := len(column), len(g.data[0]); lc != le {
return fmt.Errorf("cannot append row when it has different number of columns than existing: %d != %d", lc, le)
}
for ci, cell := range column {
if l := len(cell); l > g.dataWidths[ci] {
g.dataWidths[ci] = l
}
}
} else {
// grid has no data yet
for _, cell := range column {
g.ColumnAlignments = append(g.ColumnAlignments, g.DefaultAlignment)
g.ColumnWidths = append(g.ColumnWidths, g.DefaultWidth)
g.dataWidths = append(g.dataWidths, len(cell))
}
}
g.colors = append(g.colors, g.DefaultRowColor)
g.data = append(g.data, column)
return nil
}
func (g *Grid) ColumnCount() int {
return len(g.ColumnAlignments)
}
func (g *Grid) ColumnDataWidth(i int) (int, error) {
if i < len(g.dataWidths) {
return g.dataWidths[i], nil
}
return 0, errors.New("No such column")
}
func (g *Grid) RowCount() int {
return len(g.data)
}
// Requires each row to have same number of columns.
func (g *Grid) Format() []string {
lines := make([]string, len(g.data))
var delim string
if g.Delimiter == "" {
delim = " "
} else {
delim = g.Delimiter
}
for ri, row := range g.data {
var pre, post string
if color := g.colors[ri]; color != "" {
switch strings.ToLower(color) {
case "bold":
pre = "\033[1m"
case "underscore":
pre = "\033[1;4m"
case "reverse":
pre = "\033[1;7m"
case "red":
pre = "\033[1;31m"
case "green":
pre = "\033[1;32m"
case "yellow":
pre = "\033[1;33m"
case "purple":
pre = "\033[1;34m"
case "magenta":
pre = "\033[1;35m"
case "teal":
pre = "\033[1;36m"
case "white":
pre = "\033[1;37m"
default:
pre = g.colors[ri]
}
post = "\033[0m"
}
fields := make([]string, len(row))
for ci, cell := range row {
dataWidths := g.dataWidths[ci]
if columnWidth := g.ColumnWidths[ci]; columnWidth > 0 {
dataWidths = columnWidth
}
fields[ci] = align(g.ColumnAlignments[ci], dataWidths, pre, cell, post)
}
lines[ri] = strings.Join(fields, delim)
}
return lines
}
func align(alignment Alignment, width int, pre, field, post string) string {
text := pre + field + post
if width == 0 {
return text
}
needed := width - len(field)
if needed < 0 {
return pre + field[:width] + post // trim upstream field
}
switch alignment {
case Left:
return text + strings.Repeat(" ", needed)
case Center:
half := needed >> 1
double := half << 1
ws := strings.Repeat(" ", half)
if double == needed {
return ws + text + ws
}
return ws + text + ws + " " // need extra whitespace on one of the sides
case Right:
return strings.Repeat(" ", needed) + text
}
panic("NOTREACHED")
} | gogrid.go | 0.612657 | 0.455017 | gogrid.go | starcoder |
* SOURCE:
* namespace.avsc
*/
package avro
import (
"io"
"fmt"
"github.com/actgardner/gogen-avro/vm"
"github.com/actgardner/gogen-avro/vm/types"
)
type UnionNullBodyworksDataTypeEnum int
const (
UnionNullBodyworksDataTypeEnumNull UnionNullBodyworksDataTypeEnum = 0
UnionNullBodyworksDataTypeEnumBodyworksData UnionNullBodyworksDataTypeEnum = 1
)
type UnionNullBodyworksData struct {
Null *types.NullVal
BodyworksData *BodyworksData
UnionType UnionNullBodyworksDataTypeEnum
}
func writeUnionNullBodyworksData(r *UnionNullBodyworksData, w io.Writer) error {
err := vm.WriteLong(int64(r.UnionType), w)
if err != nil {
return err
}
switch r.UnionType{
case UnionNullBodyworksDataTypeEnumNull:
return vm.WriteNull(r.Null, w)
case UnionNullBodyworksDataTypeEnumBodyworksData:
return writeBodyworksData(r.BodyworksData, w)
}
return fmt.Errorf("invalid value for *UnionNullBodyworksData")
}
func NewUnionNullBodyworksData() *UnionNullBodyworksData {
return &UnionNullBodyworksData{}
}
func (_ *UnionNullBodyworksData) SetBoolean(v bool) { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) SetInt(v int32) { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) SetFloat(v float32) { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) SetDouble(v float64) { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) SetBytes(v []byte) { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) SetString(v string) { panic("Unsupported operation") }
func (r *UnionNullBodyworksData) SetLong(v int64) {
r.UnionType = (UnionNullBodyworksDataTypeEnum)(v)
}
func (r *UnionNullBodyworksData) Get(i int) types.Field {
switch (i) {
case 0:
return r.Null
case 1:
r.BodyworksData = NewBodyworksData()
return r.BodyworksData
}
panic("Unknown field index")
}
func (_ *UnionNullBodyworksData) SetDefault(i int) { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) AppendMap(key string) types.Field { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) AppendArray() types.Field { panic("Unsupported operation") }
func (_ *UnionNullBodyworksData) Finalize() { } | test/namespace-short/union_null_bodyworks_data.go | 0.654453 | 0.464355 | union_null_bodyworks_data.go | starcoder |
package game
import (
"image/color"
"runtime/interrupt"
"github.com/danmrichards/gba-pong/internal/display"
"github.com/danmrichards/gba-pong/internal/input"
"tinygo.org/x/drivers"
"tinygo.org/x/tinydraw"
)
var (
// Using a load of package level variables here because the compiler and
// resulting ROM acts weirdly if using structs and receiver methods (e.g.
// incorrect colours). Possibly something to do with alignment and memory
// mapping.
// Screen is the display where the game will draw pixels.
Screen drivers.Displayer
// Background is the background colour of the game.
Background color.RGBA
// PaddleWidth is the width of the player paddle.
PaddleWidth = int16(10)
// PaddleHeight is the height of the player paddle.
PaddleHeight = int16(50)
// PaddleColour is the colour of the player paddle.
PaddleColour color.RGBA
// BallWidth is the width of the ball.
BallWidth = int16(8)
// BallHeight is the height of the ball.
BallHeight = int16(8)
// BallColour is the colour of the ball.
BallColour color.RGBA
// Paddle positional variables.
paddleX = int16(10)
paddleY = int16(10)
// Ball positional variables.
ballX int16
ballY int16
ballXVelocity int16
ballDown = int16(1)
ballUp = int16(-1)
ballYVelocity = ballUp
ballLastYVelocity int16
ballMaxX = display.Width - BallWidth
ballMaxY = display.Height - BallHeight
// Paddle miss indicator and frame timer. The time package does not work
// well in tinygo, so instead we just wait for a number of frames.
miss bool
missFrames int
)
// Init initialises the game state.
func Init() {
display.Clear(Screen, Background)
resetBall(true, true)
}
// Update updates the current game state, intended to be called for each frame.
func Update(interrupt.Interrupt) {
clearPrevFrame()
// The last shot missed the paddle, reset the ball position and wait for
// the remaining frames before starting again.
if miss {
if missFrames > 0 {
missFrames--
} else {
miss = false
resetBall(true, true)
}
}
handleInput()
updatePaddle()
updateBall()
}
// resetBall resets the position and/or velocity of the ball to the default
// values.
func resetBall(position, velocity bool) {
if position {
ballX = (display.Width / 2) - (BallWidth / 2)
ballY = (display.Height / 2) - (BallHeight / 2)
}
if velocity {
ballXVelocity = int16(-2)
// Alternate ball direction on each new shot.
if ballLastYVelocity == ballDown {
ballYVelocity = ballUp
ballLastYVelocity = ballUp
} else {
ballYVelocity = ballDown
ballLastYVelocity = ballDown
}
}
}
// clearPrevFrame clears the previous frame drawn pixels.
func clearPrevFrame() {
// Clear previous paddle position.
tinydraw.FilledRectangle(
Screen,
paddleX,
paddleY,
PaddleWidth,
PaddleHeight,
Background,
)
// Clear previous ball position.
tinydraw.FilledRectangle(
Screen,
ballX,
ballY,
BallWidth,
BallHeight,
Background,
)
}
// handleInput handles input from the keypad, updating game state accordingly.
func handleInput() {
// Update paddle position.
switch {
case input.KeyPressed(input.KeyUp):
paddleY -= 5
case input.KeyPressed(input.KeyDown):
paddleY += 5
}
}
// updatePaddle updates the position of the paddle.
func updatePaddle() {
// Stop the paddle from going off screen.
paddleY = clamp(paddleY, 10, display.Height-PaddleHeight-10)
// Draw paddle.
tinydraw.FilledRectangle(
Screen,
10,
paddleY,
PaddleWidth,
PaddleHeight,
PaddleColour,
)
}
// updateBall updates the position of the ball.
func updateBall() {
collideEdge()
collidePaddle()
ballX = clamp(ballX+ballXVelocity, 0, ballMaxX)
ballY = clamp(ballY+ballYVelocity, 0, ballMaxY)
// Draw ball.
tinydraw.FilledRectangle(
Screen,
ballX,
ballY,
BallWidth,
BallHeight,
BallColour,
)
}
// collideEdge detects if the ball has collided with the edge of the screen.
func collideEdge() {
if ballY == 0 || ballY == ballMaxY {
// Top or bottom of screen bounce.
ballYVelocity = -ballYVelocity
} else if ballX == ballMaxX {
// Right hand side bounce.
ballXVelocity = -ballXVelocity
} else if ballX == 0 {
// Paddle missed, stop the ball and set the miss frame counter.
ballXVelocity = 0
ballYVelocity = 0
resetBall(true, false)
missFrames = 10
miss = true
}
}
// collidePaddle detects if the ball has collided with the paddle and updates
// the direction accordingly.
func collidePaddle() {
if (ballX >= paddleX && ballX <= paddleX+PaddleWidth) &&
(ballY >= paddleY && ballY <= paddleY+PaddleHeight) {
ballX = paddleX + PaddleWidth
ballXVelocity = -ballXVelocity
}
}
// clamp returns n normalised to the range min <= n <= max.
func clamp(n, min, max int16) int16 {
if n < min {
return min
} else if n > max {
return max
}
return n
} | internal/game/game.go | 0.609524 | 0.490724 | game.go | starcoder |
package gocolor
import (
"github.com/Nguyen-Hoang-Nam/go-color/terminal"
"github.com/lucasb-eyer/go-colorful"
)
const (
DistanceRgb = iota
DistanceLab
DistanceLuv
DistanceCIE94
DistanceCIEDE2000
)
func minDistanceRbg(color colorful.Color, limit int) int {
minDistance := color.DistanceRgb(terminal.Xterm256[0])
minKey := 0
for key, value := range terminal.Xterm256 {
if key == limit {
break
}
valueDistance := color.DistanceRgb(value)
if valueDistance < minDistance {
minDistance = valueDistance
minKey = key
}
}
return minKey
}
func minDistanceLab(color colorful.Color, limit int) int {
minDistance := color.DistanceLab(terminal.Xterm256[0])
minKey := 0
for key, value := range terminal.Xterm256 {
if key == limit {
break
}
valueDistance := color.DistanceLab(value)
if valueDistance < minDistance {
minDistance = valueDistance
minKey = key
}
}
return minKey
}
func minDistanceLuv(color colorful.Color, limit int) int {
minDistance := color.DistanceLuv(terminal.Xterm256[0])
minKey := 0
for key, value := range terminal.Xterm256 {
if key == limit {
break
}
valueDistance := color.DistanceLuv(value)
if valueDistance < minDistance {
minDistance = valueDistance
minKey = key
}
}
return minKey
}
func minDistanceCIE94(color colorful.Color, limit int) int {
minDistance := color.DistanceCIE94(terminal.Xterm256[0])
minKey := 0
for key, value := range terminal.Xterm256 {
if key == limit {
break
}
valueDistance := color.DistanceCIE94(value)
if valueDistance < minDistance {
minDistance = valueDistance
minKey = key
}
}
return minKey
}
func minDistanceCIEDE2000(color colorful.Color, limit int) int {
minDistance := color.DistanceCIEDE2000(terminal.Xterm256[0])
minKey := 0
for key, value := range terminal.Xterm256 {
if key == limit {
break
}
valueDistance := color.DistanceCIEDE2000(value)
if valueDistance < minDistance {
minDistance = valueDistance
minKey = key
}
}
return minKey
}
func minDistance(color colorful.Color, distance int, limit int) int {
switch distance {
case DistanceRgb:
return minDistanceRbg(color, limit)
case DistanceLab:
return minDistanceLab(color, limit)
case DistanceLuv:
return minDistanceLuv(color, limit)
case DistanceCIE94:
return minDistanceCIE94(color, limit)
case DistanceCIEDE2000:
return minDistanceCIEDE2000(color, limit)
default:
return 0
}
} | distance.go | 0.676299 | 0.5564 | distance.go | starcoder |
package types
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
var (
_ Value = BoolValue(false)
_ Value = IntValue(0)
_ Value = FloatValue(0.0)
_ Value = DateValue(time.Unix(0, 0))
_ Value = StringValue("")
_ Value = TableValue{}
_ Value = ArrayValue{}
_ Value = &FormattedValue{}
// Null value specifies a non-existing value.
Null Value = NullValue{}
)
const (
defaultFloatFormat = "%g"
)
// Value implements expression values.
type Value interface {
Type() Type
Date() (time.Time, error)
Bool() (bool, error)
Int() (int64, error)
Float() (float64, error)
String() string
}
// Equal tests if the argument values are equal.
func Equal(value1, value2 Value) (bool, error) {
switch v1 := value1.(type) {
case BoolValue:
v2, err := value2.Bool()
if err != nil {
return false, nil
}
return v1 == BoolValue(v2), nil
case IntValue:
v2, err := value2.Int()
if err != nil {
return false, nil
}
return v1 == IntValue(v2), nil
case FloatValue:
v2, err := value2.Float()
if err != nil {
return false, nil
}
return v1 == FloatValue(v2), nil
case DateValue:
v2, err := value2.Date()
if err != nil {
return false, nil
}
return v1.Equal(DateValue(v2)), nil
case StringValue:
return v1 == StringValue(value2.String()), nil
default:
return false, fmt.Errorf("types.Equal: invalid type: %T", value1)
}
}
// Compare compares two values. It returns -1, 0, 1 if the value 1 is
// smaller, equal, or greater than the value 2 respectively.
func Compare(value1, value2 Value) (int, error) {
_, n1 := value1.(NullValue)
_, n2 := value2.(NullValue)
if n1 && n2 {
return 0, nil
} else if n1 {
return -1, nil
} else if n2 {
return 1, nil
}
switch v1 := value1.(type) {
case BoolValue:
v2, ok := value2.(BoolValue)
if !ok {
return -1, nil
}
if v1 == v2 {
return 0, nil
}
if !v1 {
return -1, nil
}
return 1, nil
case IntValue:
v2, ok := value2.(IntValue)
if !ok {
return -1, nil
}
if v1 < v2 {
return -1, nil
}
if v1 > v2 {
return 1, nil
}
return 0, nil
case FloatValue:
v2, ok := value2.(FloatValue)
if !ok {
return -1, nil
}
if v1 < v2 {
return -1, nil
}
if v1 > v2 {
return 1, nil
}
return 0, nil
case DateValue:
v2, ok := value2.(DateValue)
if !ok {
return -1, nil
}
if v1.Equal(v2) {
return 0, nil
}
if v1.Before(v2) {
return -1, nil
}
return 1, nil
case StringValue:
v2, ok := value2.(StringValue)
if !ok {
return -1, nil
}
return strings.Compare(v1.String(), v2.String()), nil
default:
return -1, fmt.Errorf("types.Compare: invalid type: %T", value1)
}
}
// BoolValue implements boolean values.
type BoolValue bool
// Type implements the Value.Type().
func (v BoolValue) Type() Type {
return Bool
}
// Date implements the Value.Date().
func (v BoolValue) Date() (time.Time, error) {
return time.Time{}, fmt.Errorf("bool used as date")
}
// Bool implements the Value.Bool().
func (v BoolValue) Bool() (bool, error) {
return bool(v), nil
}
// Int implements the Value.Int().
func (v BoolValue) Int() (int64, error) {
return 0, fmt.Errorf("bool used as int")
}
// Float implements the Value.Float().
func (v BoolValue) Float() (float64, error) {
return 0, fmt.Errorf("bool used as float")
}
func (v BoolValue) String() string {
return fmt.Sprintf("%v", bool(v))
}
// IntValue implements integer values.
type IntValue int64
// Type implements the Value.Type().
func (v IntValue) Type() Type {
return Int
}
// Date implements the Value.Date().
func (v IntValue) Date() (time.Time, error) {
return time.Unix(0, int64(v)), nil
}
// Bool implements the Value.Bool().
func (v IntValue) Bool() (bool, error) {
return false, fmt.Errorf("int used as bool")
}
// Int implements the Value.Int().
func (v IntValue) Int() (int64, error) {
return int64(v), nil
}
// Float implements the Value.Float().
func (v IntValue) Float() (float64, error) {
return float64(v), nil
}
func (v IntValue) String() string {
return fmt.Sprintf("%d", v)
}
// FloatValue implements floating point values.
type FloatValue float64
// Type implements the Value.Type().
func (v FloatValue) Type() Type {
return Float
}
// Date implements the Value.Date().
func (v FloatValue) Date() (time.Time, error) {
return time.Time{}, fmt.Errorf("float used as date")
}
// Bool implements the Value.Bool().
func (v FloatValue) Bool() (bool, error) {
return false, fmt.Errorf("float used as bool")
}
// Int implements the Value.Int().
func (v FloatValue) Int() (int64, error) {
return int64(v), nil
}
// Float implements the Value.Float().
func (v FloatValue) Float() (float64, error) {
return float64(v), nil
}
func (v FloatValue) String() string {
return fmt.Sprintf(defaultFloatFormat, float64(v))
}
// DateValue implements datetime values.
type DateValue time.Time
// Equal tests if the values are equal.
func (v DateValue) Equal(o DateValue) bool {
return time.Time(v).Equal(time.Time(o))
}
// Before tests if the value v is before the argument value o.
func (v DateValue) Before(o DateValue) bool {
return time.Time(v).Before(time.Time(o))
}
// Type implements the Value.Type().
func (v DateValue) Type() Type {
return Date
}
// Date implements the Value.Date().
func (v DateValue) Date() (time.Time, error) {
return time.Time(v), nil
}
// Bool implements the Value.Bool().
func (v DateValue) Bool() (bool, error) {
return false, fmt.Errorf("datetime used as bool")
}
// Int implements the Value.Int().
func (v DateValue) Int() (int64, error) {
return time.Time(v).UnixNano(), nil
}
// Float implements the Value.Float().
func (v DateValue) Float() (float64, error) {
return 0, fmt.Errorf("datetime used as float")
}
func (v DateValue) String() string {
return time.Time(v).Format(DateTimeLayout)
}
// StringValue implements string values.
type StringValue string
// Type implements the Value.Type().
func (v StringValue) Type() Type {
return String
}
// Date implements the Value.Date().
func (v StringValue) Date() (time.Time, error) {
return ParseDate(string(v))
}
// Bool implements the Value.Bool().
func (v StringValue) Bool() (bool, error) {
return false, fmt.Errorf("string used as bool")
}
// Int implements the Value.Int().
func (v StringValue) Int() (int64, error) {
return strconv.ParseInt(string(v), 10, 64)
}
// Float implements the Value.Float().
func (v StringValue) Float() (float64, error) {
return strconv.ParseFloat(string(v), 64)
}
func (v StringValue) String() string {
return string(v)
}
// TableValue implements table values for sources.
type TableValue struct {
Source Source
}
// Type implements the Value.Type().
func (v TableValue) Type() Type {
return Table
}
// Date implements the Value.Date().
func (v TableValue) Date() (time.Time, error) {
return time.Time{}, fmt.Errorf("table used as date")
}
// Bool implements the Value.Bool().
func (v TableValue) Bool() (bool, error) {
return false, fmt.Errorf("table used as bool")
}
// Int implements the Value.Int().
func (v TableValue) Int() (int64, error) {
rows, err := v.Source.Get()
if err != nil {
return 0, err
}
return int64(len(rows)), nil
}
// Float implements the Value.Float().
func (v TableValue) Float() (float64, error) {
return 0, fmt.Errorf("table used as float")
}
func (v TableValue) String() string {
// XXX source names
return "table"
}
// ArrayValue implements arrays.
type ArrayValue struct {
ElemType Type
Data []Value
}
// NewArray creates a new array value with the type and data.
func NewArray(t Type, data []Value) Value {
return ArrayValue{
ElemType: t,
Data: data,
}
}
// Type implements the Value.Type().
func (v ArrayValue) Type() Type {
return Array
}
// Date implements the Value.Date().
func (v ArrayValue) Date() (time.Time, error) {
return time.Time{}, fmt.Errorf("array used as date")
}
// Bool implements the Value.Bool().
func (v ArrayValue) Bool() (bool, error) {
return false, fmt.Errorf("array used as bool")
}
// Int implements the Value.Int().
func (v ArrayValue) Int() (int64, error) {
return int64(len(v.Data)), nil
}
// Float implements the Value.Float().
func (v ArrayValue) Float() (float64, error) {
return 0, fmt.Errorf("array used as float")
}
func (v ArrayValue) String() string {
return fmt.Sprintf("%v", v.Data)
}
// NullValue implements non-existing value.
type NullValue struct {
}
// Type implements the Value.Type().
func (v NullValue) Type() Type {
return Any
}
// Date implements the Value.Date().
func (v NullValue) Date() (time.Time, error) {
return time.Time{}, fmt.Errorf("null used as date")
}
// Bool implements the Value.Bool().
func (v NullValue) Bool() (bool, error) {
return false, nil
}
// Int implements the Value.Int().
func (v NullValue) Int() (int64, error) {
return 0, errors.New("null used as int")
}
// Float implements the Value.Float().
func (v NullValue) Float() (float64, error) {
return 0, errors.New("null used as float")
}
func (v NullValue) String() string {
return "null"
}
// Format implements value formatting options.
type Format struct {
Float string
}
// FormattedValue implements value by wrapping another value type with
// formatting options.
type FormattedValue struct {
value Value
format *Format
}
// NewFormattedValue creates a new formatted value from the argument
// value and format.
func NewFormattedValue(v Value, f *Format) *FormattedValue {
return &FormattedValue{
value: v,
format: f,
}
}
// Type implements the Value.Type().
func (v *FormattedValue) Type() Type {
return v.value.Type()
}
// Date implements the Value.Date().
func (v *FormattedValue) Date() (time.Time, error) {
return v.value.Date()
}
// Bool implements the Value.Bool().
func (v *FormattedValue) Bool() (bool, error) {
return v.value.Bool()
}
// Int implements the Value.Int().
func (v *FormattedValue) Int() (int64, error) {
return v.value.Int()
}
// Float implements the Value.Float().
func (v *FormattedValue) Float() (float64, error) {
return v.value.Float()
}
func (v *FormattedValue) String() string {
switch val := v.value.(type) {
case FloatValue:
format := v.format.Float
if len(format) == 0 {
format = defaultFloatFormat
}
return fmt.Sprintf(format, float64(val))
default:
return v.value.String()
}
} | types/value.go | 0.755005 | 0.454714 | value.go | starcoder |
package draw2d
import (
"bosun.org/_third_party/code.google.com/p/freetype-go/freetype/raster"
"math"
)
type MatrixTransform [6]float64
const (
epsilon = 1e-6
)
func (tr MatrixTransform) Determinant() float64 {
return tr[0]*tr[3] - tr[1]*tr[2]
}
func (tr MatrixTransform) Transform(points ...*float64) {
for i, j := 0, 1; j < len(points); i, j = i+2, j+2 {
x := *points[i]
y := *points[j]
*points[i] = x*tr[0] + y*tr[2] + tr[4]
*points[j] = x*tr[1] + y*tr[3] + tr[5]
}
}
func (tr MatrixTransform) TransformArray(points []float64) {
for i, j := 0, 1; j < len(points); i, j = i+2, j+2 {
x := points[i]
y := points[j]
points[i] = x*tr[0] + y*tr[2] + tr[4]
points[j] = x*tr[1] + y*tr[3] + tr[5]
}
}
func (tr MatrixTransform) TransformRectangle(x0, y0, x2, y2 *float64) {
x1 := *x2
y1 := *y0
x3 := *x0
y3 := *y2
tr.Transform(x0, y0, &x1, &y1, x2, y2, &x3, &y3)
*x0, x1 = minMax(*x0, x1)
*x2, x3 = minMax(*x2, x3)
*y0, y1 = minMax(*y0, y1)
*y2, y3 = minMax(*y2, y3)
*x0 = min(*x0, *x2)
*y0 = min(*y0, *y2)
*x2 = max(x1, x3)
*y2 = max(y1, y3)
}
func (tr MatrixTransform) TransformRasterPoint(points ...*raster.Point) {
for _, point := range points {
x := float64(point.X) / 256
y := float64(point.Y) / 256
point.X = raster.Fix32((x*tr[0] + y*tr[2] + tr[4]) * 256)
point.Y = raster.Fix32((x*tr[1] + y*tr[3] + tr[5]) * 256)
}
}
func (tr MatrixTransform) InverseTransform(points ...*float64) {
d := tr.Determinant() // matrix determinant
for i, j := 0, 1; j < len(points); i, j = i+2, j+2 {
x := *points[i]
y := *points[j]
*points[i] = ((x-tr[4])*tr[3] - (y-tr[5])*tr[2]) / d
*points[j] = ((y-tr[5])*tr[0] - (x-tr[4])*tr[1]) / d
}
}
// ******************** Vector transformations ********************
func (tr MatrixTransform) VectorTransform(points ...*float64) {
for i, j := 0, 1; j < len(points); i, j = i+2, j+2 {
x := *points[i]
y := *points[j]
*points[i] = x*tr[0] + y*tr[2]
*points[j] = x*tr[1] + y*tr[3]
}
}
// ******************** Transformations creation ********************
/** Creates an identity transformation. */
func NewIdentityMatrix() MatrixTransform {
return [6]float64{1, 0, 0, 1, 0, 0}
}
/**
* Creates a transformation with a translation, that,
* transform point1 into point2.
*/
func NewTranslationMatrix(tx, ty float64) MatrixTransform {
return [6]float64{1, 0, 0, 1, tx, ty}
}
/**
* Creates a transformation with a sx, sy scale factor
*/
func NewScaleMatrix(sx, sy float64) MatrixTransform {
return [6]float64{sx, 0, 0, sy, 0, 0}
}
/**
* Creates a rotation transformation.
*/
func NewRotationMatrix(angle float64) MatrixTransform {
c := math.Cos(angle)
s := math.Sin(angle)
return [6]float64{c, s, -s, c, 0, 0}
}
/**
* Creates a transformation, combining a scale and a translation, that transform rectangle1 into rectangle2.
*/
func NewMatrixTransform(rectangle1, rectangle2 [4]float64) MatrixTransform {
xScale := (rectangle2[2] - rectangle2[0]) / (rectangle1[2] - rectangle1[0])
yScale := (rectangle2[3] - rectangle2[1]) / (rectangle1[3] - rectangle1[1])
xOffset := rectangle2[0] - (rectangle1[0] * xScale)
yOffset := rectangle2[1] - (rectangle1[1] * yScale)
return [6]float64{xScale, 0, 0, yScale, xOffset, yOffset}
}
// ******************** Transformations operations ********************
/**
* Returns a transformation that is the inverse of the given transformation.
*/
func (tr MatrixTransform) GetInverseTransformation() MatrixTransform {
d := tr.Determinant() // matrix determinant
return [6]float64{
tr[3] / d,
-tr[1] / d,
-tr[2] / d,
tr[0] / d,
(tr[2]*tr[5] - tr[3]*tr[4]) / d,
(tr[1]*tr[4] - tr[0]*tr[5]) / d}
}
func (tr1 MatrixTransform) Multiply(tr2 MatrixTransform) MatrixTransform {
return [6]float64{
tr1[0]*tr2[0] + tr1[1]*tr2[2],
tr1[1]*tr2[3] + tr1[0]*tr2[1],
tr1[2]*tr2[0] + tr1[3]*tr2[2],
tr1[3]*tr2[3] + tr1[2]*tr2[1],
tr1[4]*tr2[0] + tr1[5]*tr2[2] + tr2[4],
tr1[5]*tr2[3] + tr1[4]*tr2[1] + tr2[5]}
}
func (tr *MatrixTransform) Scale(sx, sy float64) *MatrixTransform {
tr[0] = sx * tr[0]
tr[1] = sx * tr[1]
tr[2] = sy * tr[2]
tr[3] = sy * tr[3]
return tr
}
func (tr *MatrixTransform) Translate(tx, ty float64) *MatrixTransform {
tr[4] = tx*tr[0] + ty*tr[2] + tr[4]
tr[5] = ty*tr[3] + tx*tr[1] + tr[5]
return tr
}
func (tr *MatrixTransform) Rotate(angle float64) *MatrixTransform {
c := math.Cos(angle)
s := math.Sin(angle)
t0 := c*tr[0] + s*tr[2]
t1 := s*tr[3] + c*tr[1]
t2 := c*tr[2] - s*tr[0]
t3 := c*tr[3] - s*tr[1]
tr[0] = t0
tr[1] = t1
tr[2] = t2
tr[3] = t3
return tr
}
func (tr MatrixTransform) GetTranslation() (x, y float64) {
return tr[4], tr[5]
}
func (tr MatrixTransform) GetScaling() (x, y float64) {
return tr[0], tr[3]
}
func (tr MatrixTransform) GetScale() float64 {
x := 0.707106781*tr[0] + 0.707106781*tr[1]
y := 0.707106781*tr[2] + 0.707106781*tr[3]
return math.Sqrt(x*x + y*y)
}
func (tr MatrixTransform) GetMaxAbsScaling() (s float64) {
sx := math.Abs(tr[0])
sy := math.Abs(tr[3])
if sx > sy {
return sx
}
return sy
}
func (tr MatrixTransform) GetMinAbsScaling() (s float64) {
sx := math.Abs(tr[0])
sy := math.Abs(tr[3])
if sx > sy {
return sy
}
return sx
}
// ******************** Testing ********************
/**
* Tests if a two transformation are equal. A tolerance is applied when
* comparing matrix elements.
*/
func (tr1 MatrixTransform) Equals(tr2 MatrixTransform) bool {
for i := 0; i < 6; i = i + 1 {
if !fequals(tr1[i], tr2[i]) {
return false
}
}
return true
}
/**
* Tests if a transformation is the identity transformation. A tolerance
* is applied when comparing matrix elements.
*/
func (tr MatrixTransform) IsIdentity() bool {
return fequals(tr[4], 0) && fequals(tr[5], 0) && tr.IsTranslation()
}
/**
* Tests if a transformation is is a pure translation. A tolerance
* is applied when comparing matrix elements.
*/
func (tr MatrixTransform) IsTranslation() bool {
return fequals(tr[0], 1) && fequals(tr[1], 0) && fequals(tr[2], 0) && fequals(tr[3], 1)
}
/**
* Compares two floats.
* return true if the distance between the two floats is less than epsilon, false otherwise
*/
func fequals(float1, float2 float64) bool {
return math.Abs(float1-float2) <= epsilon
}
// this VertexConverter apply the Matrix transformation tr
type VertexMatrixTransform struct {
tr MatrixTransform
Next VertexConverter
}
func NewVertexMatrixTransform(tr MatrixTransform, converter VertexConverter) *VertexMatrixTransform {
return &VertexMatrixTransform{tr, converter}
}
// Vertex Matrix Transform
func (vmt *VertexMatrixTransform) NextCommand(command VertexCommand) {
vmt.Next.NextCommand(command)
}
func (vmt *VertexMatrixTransform) Vertex(x, y float64) {
u := x*vmt.tr[0] + y*vmt.tr[2] + vmt.tr[4]
v := x*vmt.tr[1] + y*vmt.tr[3] + vmt.tr[5]
vmt.Next.Vertex(u, v)
}
// this adder apply a Matrix transformation to points
type MatrixTransformAdder struct {
tr MatrixTransform
next raster.Adder
}
func NewMatrixTransformAdder(tr MatrixTransform, adder raster.Adder) *MatrixTransformAdder {
return &MatrixTransformAdder{tr, adder}
}
// Start starts a new curve at the given point.
func (mta MatrixTransformAdder) Start(a raster.Point) {
mta.tr.TransformRasterPoint(&a)
mta.next.Start(a)
}
// Add1 adds a linear segment to the current curve.
func (mta MatrixTransformAdder) Add1(b raster.Point) {
mta.tr.TransformRasterPoint(&b)
mta.next.Add1(b)
}
// Add2 adds a quadratic segment to the current curve.
func (mta MatrixTransformAdder) Add2(b, c raster.Point) {
mta.tr.TransformRasterPoint(&b, &c)
mta.next.Add2(b, c)
}
// Add3 adds a cubic segment to the current curve.
func (mta MatrixTransformAdder) Add3(b, c, d raster.Point) {
mta.tr.TransformRasterPoint(&b, &c, &d)
mta.next.Add3(b, c, d)
} | _third_party/code.google.com/p/draw2d/draw2d/transform.go | 0.756897 | 0.613613 | transform.go | starcoder |
package stringorslice
import (
"encoding/json"
"strings"
)
// StringOrSlice is a type that holds a []string, but marshals to a []string or a string.
type StringOrSlice struct {
values []string
forceEncodeAsArray bool
}
func (s *StringOrSlice) IsEmpty() bool {
return len(s.values) == 0
}
// Slice will build a value that marshals to a JSON array
func Slice(v []string) StringOrSlice {
return StringOrSlice{values: v, forceEncodeAsArray: true}
}
// Of will build a value that marshals to a JSON array if len(v) > 1,
// otherwise to a single string
func Of(v ...string) StringOrSlice {
if v == nil {
v = []string{}
}
return StringOrSlice{values: v}
}
// String will build a value that marshals to a single string
func String(v string) StringOrSlice {
return StringOrSlice{values: []string{v}, forceEncodeAsArray: false}
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (s *StringOrSlice) UnmarshalJSON(value []byte) error {
if value[0] == '[' {
s.forceEncodeAsArray = true
if err := json.Unmarshal(value, &s.values); err != nil {
return nil
}
return nil
}
s.forceEncodeAsArray = false
var stringValue string
if err := json.Unmarshal(value, &stringValue); err != nil {
return err
}
s.values = []string{stringValue}
return nil
}
// String returns the string value, or the Itoa of the int value.
func (s StringOrSlice) String() string {
return strings.Join(s.values, ",")
}
func (v *StringOrSlice) Value() []string {
return v.values
}
func (l StringOrSlice) Equal(r StringOrSlice) bool {
if len(l.values) != len(r.values) {
return false
}
for i := 0; i < len(l.values); i++ {
if l.values[i] != r.values[i] {
return false
}
}
return true
}
// MarshalJSON implements the json.Marshaller interface.
func (v StringOrSlice) MarshalJSON() ([]byte, error) {
encodeAsJSONArray := v.forceEncodeAsArray
if len(v.values) > 1 {
encodeAsJSONArray = true
}
values := v.values
if values == nil {
values = []string{}
}
if encodeAsJSONArray {
return json.Marshal(values)
} else if len(v.values) == 1 {
s := v.values[0]
return json.Marshal(&s)
} else {
return json.Marshal(values)
}
} | pkg/util/stringorslice/stringorslice.go | 0.632843 | 0.437103 | stringorslice.go | starcoder |
// Package vm provides a compiler and virtual machine environment for executing
// mtail programs.
package vm
import "fmt"
type opcode int
const (
bad opcode = iota // Invalid instruction, indicates a bug in the generator.
match // Match a regular expression against input, and set the match register.
smatch // Match a regular expression against top of stack, and set the match register.
cmp // Compare two values on the stack and set the match register.
jnm // Jump if no match.
jm // Jump if match.
jmp // Unconditional jump
inc // Increment a variable value
strptime // Parse into the timestamp register
timestamp // Return value of timestamp register onto TOS.
settime // Set timestamp register to value at TOS.
push // Push operand onto stack
capref // Push capture group reference at operand onto stack
str // Push string constant at operand onto stack
sset // Set a string variable value.
iset // Set a variable value
iadd // Add top values on stack and push to stack
isub // Subtract top value from second top value on stack, and push to stack.
imul // Multiply top values on stack and push to stack
idiv // Divide top value into second top on stack, and push
imod // Integer divide top value into second top on stack, and push remainder
ipow // Put second TOS to power of TOS, and push.
and // Bitwise AND the 2 at top of stack, and push result
or // Bitwise OR the 2 at top of stack, and push result
xor // Bitwise XOR the 2 at top of stack, and push result
neg // Bitwise NOT the top of stack, and push result
not // Boolean NOT the top of stack, and push result
shl // Shift TOS left, push result
shr // Shift TOS right, push result
mload // Load metric at operand onto top of stack
dload // Pop `operand` keys and metric off stack, and push datum at metric[key,...] onto stack.
iget // Pop a datum off the stack, and push its integer value back on the stack.
fget // Pop a datum off the stack, and push its float value back on the stack.
sget // Pop a datum off the stack, and push its string value back on the stack.
tolower // Convert the string at the top of the stack to lowercase.
length // Compute the length of a string.
cat // string concatenation
setmatched // Set "matched" flag
otherwise // Only match if "matched" flag is false.
del // Pop `operand` keys and metric off stack, and remove the datum at metric[key,...] from memory
// Floating point ops
fadd
fsub
fmul
fdiv
fmod
fpow
fset // Floating point assignment
getfilename // Push input.Filename onto the stack.
// Conversions
i2f // int to float
s2i // string to int
s2f // string to float
i2s // int to string
f2s // float to string
// Typed comparisons, behave the same as cmp but do no conversion.
icmp // integer compare
fcmp // floating point compare
scmp // string compare
sendhep
)
var opNames = map[opcode]string{
match: "match",
smatch: "smatch",
cmp: "cmp",
jnm: "jnm",
jm: "jm",
jmp: "jmp",
inc: "inc",
strptime: "strptime",
timestamp: "timestamp",
settime: "settime",
push: "push",
capref: "capref",
str: "str",
sset: "sset",
iset: "iset",
iadd: "iadd",
isub: "isub",
imul: "imul",
idiv: "idiv",
imod: "imod",
ipow: "ipow",
shl: "shl",
shr: "shr",
and: "and",
or: "or",
xor: "xor",
not: "not",
neg: "neg",
mload: "mload",
dload: "dload",
iget: "iget",
fget: "fget",
sget: "sget",
tolower: "tolower",
length: "length",
cat: "cat",
setmatched: "setmatched",
otherwise: "otherwise",
del: "del",
fadd: "fadd",
fsub: "fsub",
fmul: "fmul",
fdiv: "fdiv",
fmod: "fmod",
fpow: "fpow",
fset: "fset",
getfilename: "getfilename",
i2f: "i2f",
s2i: "s2i",
s2f: "s2f",
i2s: "i2s",
f2s: "f2s",
icmp: "icmp",
fcmp: "fcmp",
scmp: "scmp",
sendhep: "sendhep",
}
var builtin = map[string]opcode{
"getfilename": getfilename,
"len": length,
"settime": settime,
"strptime": strptime,
"strtol": s2i,
"timestamp": timestamp,
"tolower": tolower,
"sendhep": sendhep,
}
type instr struct {
op opcode
opnd interface{}
}
// debug print for instructions
func (i instr) String() string {
return fmt.Sprintf("{%s %v}", opNames[i.op], i.opnd)
} | vm/bytecode.go | 0.651355 | 0.433742 | bytecode.go | starcoder |
package kdtree
// k-d tree implementation adopted from <NAME>'s 1975 paper:
// Multidimensional Binary Search Trees Used for Associative Searching
// https://dl.acm.org/doi/10.1145/361002.361007
import "sort"
const K = 2 // Number of dimensions
type T = uint // dimension type. minT and maxT functions MUST match T
func minT() T {
return 0
}
func maxT() T {
return ^T(0)
}
type bounds [2][K]T
type Node struct {
val [K]T
lo, hi *Node
}
// Inserts value starting from the root node of the kd-tree. Returns nil
// on success. If root is nil or val already exists, returns the node
func (root *Node) Insert(val [K]T) *Node {
// I1
if root == nil {
return &Node{val, nil, nil}
}
n := root
for d := 0; ; d = (d + 1) % K {
// I2
match := true
for i := 0; i < K; i++ {
match = match && (val[i] == n.val[i])
}
if match {
return n
}
var child **Node
if val[d] > n.val[d] {
child = &n.hi
} else {
child = &n.lo
}
if *child != nil {
// I3
n = *child
} else {
// I4
*child = &Node{val, nil, nil}
return nil
}
}
}
// Returns address of node containing val or nil if val does not exist
func (n *Node) Search(val [K]T) *Node {
if n == nil {
return nil
}
for d := 0; n != nil; d = (d + 1) % K {
match := true
for i := 0; i < K; i++ {
match = match && (val[i] == n.val[i])
}
if match {
return n
}
if val[d] > n.val[d] {
n = n.hi
} else {
n = n.lo
}
}
return nil
}
// Return true if the current node's value is within the given bounds
func (n *Node) inRegion(b bounds) bool {
for d := 0; d < K; d++ {
if n.val[d] < b[0][d] || n.val[d] > b[1][d] {
return false
}
}
return true
}
// Returns true if the bounds overlap in every dimension
func intersects(b0, b1 bounds) bool {
for d := 0; d < K; d++ {
if b1[0][d] > b0[1][d] || b1[1][d] < b0[0][d] {
return false
}
}
return true
}
func (n *Node) regionSearch(target, b bounds, r []*Node, d int) []*Node {
// R1
if n.inRegion(target) {
r = append(r, n)
}
// R2
bl := bounds{b[0], b[1]}
bh := bounds{b[0], b[1]}
bl[1][d] = n.val[d]
bh[0][d] = n.val[d]
// R3
if n.lo != nil && intersects(target, bl) {
r = n.lo.regionSearch(target, bl, r, (d+1)%K)
}
// R4
if n.hi != nil && intersects(target, bh) {
r = n.hi.regionSearch(target, bh, r, (d+1)%K)
}
return r
}
// Return a list of *Node's that are within the given bounds
func (n *Node) RegionSearch(b bounds) []*Node {
if n == nil {
return nil
}
var everywhere bounds
for i := 0; i < K; i++ {
everywhere[0][i] = minT()
everywhere[1][i] = maxT()
}
results := make([]*Node, 0)
return n.regionSearch(b, everywhere, results, 0)
}
// Return the absolute value distance between the node and the given value
func (n *Node) distance(val [K]T) T {
var acc T
for d := 0; d < K; d++ {
if val[d] >= n.val[d] {
acc += val[d] - n.val[d]
} else {
acc += n.val[d] - val[d]
}
}
return acc
}
// Returns the node with the smallest value at index j. Requires d,
// which is the current discriminator level for n
func jmin(n **Node, j, d int) **Node {
if j == d {
// Smallest values must be in LO
if (*n).lo == nil {
return n
}
l := jmin(&(*n).lo, j, (d+1)%K)
if (*n).val[j] <= (*l).val[j] {
return n
} else {
return l
}
} else {
if (*n).lo == nil && (*n).hi == nil {
return n
}
var l, h **Node
if (*n).lo != nil {
l = jmin(&(*n).lo, j, (d+1)%K)
}
if (*n).hi != nil {
h = jmin(&(*n).hi, j, (d+1)%K)
}
if l != nil && *l != nil &&
(h != nil && *h != nil && (*l).val[j] <= (*h).val[j]) &&
(n != nil && *n != nil && (*l).val[j] <= (*n).val[j]) {
return l
} else if h != nil && *h != nil &&
(l != nil && *l != nil && (*h).val[j] <= (*l).val[j]) &&
(n != nil && *n != nil && (*h).val[j] <= (*h).val[j]) {
return n
} else { // we know: (*n).val[j] <= (*l).val[j] && (*n).val[j] <= (*h).val[j]
return n
}
}
}
// Returns the node with the largest value at index j. Requires d,
// which is the current discriminator level for n
func jmax(n **Node, j, d int) **Node {
if j == d {
// Largest values must be in HI
if (*n).hi == nil {
return n
}
h := jmax(&(*n).hi, j, (d+1)%K)
if (*n).val[j] >= (*h).val[j] {
return n
} else {
return h
}
} else {
if (*n).lo == nil && (*n).hi == nil {
return n
}
var l, h **Node
if (*n).lo != nil {
l = jmax(&(*n).lo, j, (d+1)%K)
}
if (*n).hi != nil {
h = jmax(&(*n).hi, j, (d+1)%K)
}
if l != nil && *l != nil &&
(h != nil && *h != nil && (*l).val[j] >= (*h).val[j]) &&
(n != nil && *n != nil && (*l).val[j] >= (*n).val[j]) {
return l
} else if h != nil && *h != nil &&
(l != nil && *l != nil && (*h).val[j] >= (*l).val[j]) &&
(n != nil && *n != nil && (*h).val[j] >= (*h).val[j]) {
return h
} else { // we know: (*n).val[j] >= (*l).val[j] && (*n).val[j] >= (*h).val[j]
return n
}
}
}
// Returns a new tree with the old root deleted. Requires j, the root's
// discriminator, which increments every level of the tree and is mod K
// Repeated deletes will unbalance tree since hi is removed before lo
func (P *Node) Delete(j int) *Node {
if P == nil {
return nil
}
var child **Node
var Q Node // Q will take P's place as the new root
// D1
if P.hi == nil && P.lo == nil {
return nil
}
if P.hi != nil {
// D3
child = jmin(&P.hi, j, (j+1)%K)
} else {
// D4
child = jmax(&P.lo, j, (j+1)%K)
}
// D5
Q = **child
*child = (*child).Delete((j + 1) % K)
// D6
Q.hi = P.hi
Q.lo = P.lo
return &Q
}
// Destructively flattens a kd-tree into a slice of Node's
func (n *Node) flatten() []Node {
if n == nil {
return nil
}
lo, hi := n.lo.flatten(), n.hi.flatten()
n.lo, n.hi = nil, nil
if lo != nil && hi != nil {
return append(lo, append(hi, *n)...)
} else if lo != nil {
return append(lo, *n)
} else if hi != nil { // hi != nil
return append(hi, *n)
} else {
return []Node{*n}
}
}
// Returns a new tree that is balanced. Requires j, the root's discriminator
func optimize(j int, a []Node) *Node {
// O1
if a == nil || len(a) == 0 {
return nil
}
// O2: find j-median element of a
sort.Slice(a[:], func(m, n int) bool {
return a[m].val[j] < a[n].val[j]
})
m := len(a) / 2
P := a[m]
// O3, O4
P.lo = optimize((j+1)%K, a[:m])
P.hi = optimize((j+1)%K, a[m+1:])
return &P
}
func (n *Node) Optimize() *Node {
if n == nil {
return nil
}
return optimize(0, n.flatten())
} | kdtree/kdtree.go | 0.82559 | 0.563318 | kdtree.go | starcoder |
package day2
import "fmt"
/*
Based on your calculations, the planned course doesn't seem to make any sense.
You find the submarine manual and discover that the process is actually slightly
more complicated.
In addition to horizontal position and depth, you'll also need to track a third
value, aim, which also starts at 0. The commands also mean something entirely
different than you first thought:
down X increases your aim by X units.
up X decreases your aim by X units.
forward X does two things:
It increases your horizontal position by X units.
It increases your depth by your aim multiplied by X.
Again note that since you're on a submarine, down and up do the opposite of what
you might expect: "down" means aiming in the positive direction.
Now, the above example does something different:
forward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change.
down 5 adds 5 to your aim, resulting in a value of 5.
forward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40.
up 3 decreases your aim by 3, resulting in a value of 2.
down 8 adds 8 to your aim, resulting in a value of 10.
forward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60.
After following these new instructions, you would have a horizontal position of
15 and a depth of 60. (Multiplying these produces 900.)
Using this new interpretation of the commands, calculate the horizontal position
and depth you would have after following the planned course. What do you get if
you multiply your final horizontal position by your final depth?
*/
func Part2(path string) (int, error) {
commands, err := ParseCommands(path)
if err != nil {
return 0, err
}
aim := 0
position := 0
depth := 0
for _, cmd := range commands {
switch cmd.operation {
case Forward:
position += cmd.arg
depth += cmd.arg * aim
case Up:
aim -= cmd.arg
case Down:
aim += cmd.arg
default:
return 0, fmt.Errorf("unknown operation %v", cmd.operation)
}
}
return position * depth, nil
} | day2/part2.go | 0.708818 | 0.6137 | part2.go | starcoder |
package graph
import (
i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization"
)
// PrinterDefaults
type PrinterDefaults 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 default color mode to use when printing the document. Valid values are described in the following table.
colorMode *PrintColorMode;
// The default content (MIME) type to use when processing documents.
contentType *string;
// The default number of copies printed per job.
copiesPerJob *int32;
// The default resolution in DPI to use when printing the job.
dpi *int32;
// The default duplex (double-sided) configuration to use when printing a document. Valid values are described in the following table.
duplexMode *PrintDuplexMode;
// The default set of finishings to apply to print jobs. Valid values are described in the following table.
finishings []PrintFinishing;
// The default fitPdfToPage setting. True to fit each page of a PDF document to a physical sheet of media; false to let the printer decide how to lay out impressions.
fitPdfToPage *bool;
// The default input bin that serves as the paper source.
inputBin *string;
// The default media (such as paper) color to print the document on.
mediaColor *string;
// The default media size to use. Supports standard size names for ISO and ANSI media sizes. Valid values are listed in the printerCapabilities topic.
mediaSize *string;
// The default media (such as paper) type to print the document on.
mediaType *string;
// The default direction to lay out pages when multiple pages are being printed per sheet. Valid values are described in the following table.
multipageLayout *PrintMultipageLayout;
// The default orientation to use when printing the document. Valid values are described in the following table.
orientation *PrintOrientation;
// The default output bin to place completed prints into. See the printer's capabilities for a list of supported output bins.
outputBin *string;
// The default number of document pages to print on each sheet.
pagesPerSheet *int32;
// The default quality to use when printing the document. Valid values are described in the following table.
quality *PrintQuality;
// Specifies how the printer scales the document data to fit the requested media. Valid values are described in the following table.
scaling *PrintScaling;
}
// NewPrinterDefaults instantiates a new printerDefaults and sets the default values.
func NewPrinterDefaults()(*PrinterDefaults) {
m := &PrinterDefaults{
}
m.SetAdditionalData(make(map[string]interface{}));
return m
}
// 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 *PrinterDefaults) GetAdditionalData()(map[string]interface{}) {
if m == nil {
return nil
} else {
return m.additionalData
}
}
// GetColorMode gets the colorMode property value. The default color mode to use when printing the document. Valid values are described in the following table.
func (m *PrinterDefaults) GetColorMode()(*PrintColorMode) {
if m == nil {
return nil
} else {
return m.colorMode
}
}
// GetContentType gets the contentType property value. The default content (MIME) type to use when processing documents.
func (m *PrinterDefaults) GetContentType()(*string) {
if m == nil {
return nil
} else {
return m.contentType
}
}
// GetCopiesPerJob gets the copiesPerJob property value. The default number of copies printed per job.
func (m *PrinterDefaults) GetCopiesPerJob()(*int32) {
if m == nil {
return nil
} else {
return m.copiesPerJob
}
}
// GetDpi gets the dpi property value. The default resolution in DPI to use when printing the job.
func (m *PrinterDefaults) GetDpi()(*int32) {
if m == nil {
return nil
} else {
return m.dpi
}
}
// GetDuplexMode gets the duplexMode property value. The default duplex (double-sided) configuration to use when printing a document. Valid values are described in the following table.
func (m *PrinterDefaults) GetDuplexMode()(*PrintDuplexMode) {
if m == nil {
return nil
} else {
return m.duplexMode
}
}
// GetFinishings gets the finishings property value. The default set of finishings to apply to print jobs. Valid values are described in the following table.
func (m *PrinterDefaults) GetFinishings()([]PrintFinishing) {
if m == nil {
return nil
} else {
return m.finishings
}
}
// GetFitPdfToPage gets the fitPdfToPage property value. The default fitPdfToPage setting. True to fit each page of a PDF document to a physical sheet of media; false to let the printer decide how to lay out impressions.
func (m *PrinterDefaults) GetFitPdfToPage()(*bool) {
if m == nil {
return nil
} else {
return m.fitPdfToPage
}
}
// GetInputBin gets the inputBin property value. The default input bin that serves as the paper source.
func (m *PrinterDefaults) GetInputBin()(*string) {
if m == nil {
return nil
} else {
return m.inputBin
}
}
// GetMediaColor gets the mediaColor property value. The default media (such as paper) color to print the document on.
func (m *PrinterDefaults) GetMediaColor()(*string) {
if m == nil {
return nil
} else {
return m.mediaColor
}
}
// GetMediaSize gets the mediaSize property value. The default media size to use. Supports standard size names for ISO and ANSI media sizes. Valid values are listed in the printerCapabilities topic.
func (m *PrinterDefaults) GetMediaSize()(*string) {
if m == nil {
return nil
} else {
return m.mediaSize
}
}
// GetMediaType gets the mediaType property value. The default media (such as paper) type to print the document on.
func (m *PrinterDefaults) GetMediaType()(*string) {
if m == nil {
return nil
} else {
return m.mediaType
}
}
// GetMultipageLayout gets the multipageLayout property value. The default direction to lay out pages when multiple pages are being printed per sheet. Valid values are described in the following table.
func (m *PrinterDefaults) GetMultipageLayout()(*PrintMultipageLayout) {
if m == nil {
return nil
} else {
return m.multipageLayout
}
}
// GetOrientation gets the orientation property value. The default orientation to use when printing the document. Valid values are described in the following table.
func (m *PrinterDefaults) GetOrientation()(*PrintOrientation) {
if m == nil {
return nil
} else {
return m.orientation
}
}
// GetOutputBin gets the outputBin property value. The default output bin to place completed prints into. See the printer's capabilities for a list of supported output bins.
func (m *PrinterDefaults) GetOutputBin()(*string) {
if m == nil {
return nil
} else {
return m.outputBin
}
}
// GetPagesPerSheet gets the pagesPerSheet property value. The default number of document pages to print on each sheet.
func (m *PrinterDefaults) GetPagesPerSheet()(*int32) {
if m == nil {
return nil
} else {
return m.pagesPerSheet
}
}
// GetQuality gets the quality property value. The default quality to use when printing the document. Valid values are described in the following table.
func (m *PrinterDefaults) GetQuality()(*PrintQuality) {
if m == nil {
return nil
} else {
return m.quality
}
}
// GetScaling gets the scaling property value. Specifies how the printer scales the document data to fit the requested media. Valid values are described in the following table.
func (m *PrinterDefaults) GetScaling()(*PrintScaling) {
if m == nil {
return nil
} else {
return m.scaling
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *PrinterDefaults) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) {
res := make(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error))
res["colorMode"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParsePrintColorMode)
if err != nil {
return err
}
if val != nil {
m.SetColorMode(val.(*PrintColorMode))
}
return nil
}
res["contentType"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetContentType(val)
}
return nil
}
res["copiesPerJob"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetCopiesPerJob(val)
}
return nil
}
res["dpi"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetDpi(val)
}
return nil
}
res["duplexMode"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParsePrintDuplexMode)
if err != nil {
return err
}
if val != nil {
m.SetDuplexMode(val.(*PrintDuplexMode))
}
return nil
}
res["finishings"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetCollectionOfEnumValues(ParsePrintFinishing)
if err != nil {
return err
}
if val != nil {
res := make([]PrintFinishing, len(val))
for i, v := range val {
res[i] = *(v.(*PrintFinishing))
}
m.SetFinishings(res)
}
return nil
}
res["fitPdfToPage"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetFitPdfToPage(val)
}
return nil
}
res["inputBin"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetInputBin(val)
}
return nil
}
res["mediaColor"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetMediaColor(val)
}
return nil
}
res["mediaSize"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetMediaSize(val)
}
return nil
}
res["mediaType"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetMediaType(val)
}
return nil
}
res["multipageLayout"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParsePrintMultipageLayout)
if err != nil {
return err
}
if val != nil {
m.SetMultipageLayout(val.(*PrintMultipageLayout))
}
return nil
}
res["orientation"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParsePrintOrientation)
if err != nil {
return err
}
if val != nil {
m.SetOrientation(val.(*PrintOrientation))
}
return nil
}
res["outputBin"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetOutputBin(val)
}
return nil
}
res["pagesPerSheet"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetPagesPerSheet(val)
}
return nil
}
res["quality"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParsePrintQuality)
if err != nil {
return err
}
if val != nil {
m.SetQuality(val.(*PrintQuality))
}
return nil
}
res["scaling"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParsePrintScaling)
if err != nil {
return err
}
if val != nil {
m.SetScaling(val.(*PrintScaling))
}
return nil
}
return res
}
func (m *PrinterDefaults) IsNil()(bool) {
return m == nil
}
// Serialize serializes information the current object
func (m *PrinterDefaults) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) {
if m.GetColorMode() != nil {
cast := (*m.GetColorMode()).String()
err := writer.WriteStringValue("colorMode", &cast)
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("contentType", m.GetContentType())
if err != nil {
return err
}
}
{
err := writer.WriteInt32Value("copiesPerJob", m.GetCopiesPerJob())
if err != nil {
return err
}
}
{
err := writer.WriteInt32Value("dpi", m.GetDpi())
if err != nil {
return err
}
}
if m.GetDuplexMode() != nil {
cast := (*m.GetDuplexMode()).String()
err := writer.WriteStringValue("duplexMode", &cast)
if err != nil {
return err
}
}
if m.GetFinishings() != nil {
err := writer.WriteCollectionOfStringValues("finishings", SerializePrintFinishing(m.GetFinishings()))
if err != nil {
return err
}
}
{
err := writer.WriteBoolValue("fitPdfToPage", m.GetFitPdfToPage())
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("inputBin", m.GetInputBin())
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("mediaColor", m.GetMediaColor())
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("mediaSize", m.GetMediaSize())
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("mediaType", m.GetMediaType())
if err != nil {
return err
}
}
if m.GetMultipageLayout() != nil {
cast := (*m.GetMultipageLayout()).String()
err := writer.WriteStringValue("multipageLayout", &cast)
if err != nil {
return err
}
}
if m.GetOrientation() != nil {
cast := (*m.GetOrientation()).String()
err := writer.WriteStringValue("orientation", &cast)
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("outputBin", m.GetOutputBin())
if err != nil {
return err
}
}
{
err := writer.WriteInt32Value("pagesPerSheet", m.GetPagesPerSheet())
if err != nil {
return err
}
}
if m.GetQuality() != nil {
cast := (*m.GetQuality()).String()
err := writer.WriteStringValue("quality", &cast)
if err != nil {
return err
}
}
if m.GetScaling() != nil {
cast := (*m.GetScaling()).String()
err := writer.WriteStringValue("scaling", &cast)
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 *PrinterDefaults) SetAdditionalData(value map[string]interface{})() {
if m != nil {
m.additionalData = value
}
}
// SetColorMode sets the colorMode property value. The default color mode to use when printing the document. Valid values are described in the following table.
func (m *PrinterDefaults) SetColorMode(value *PrintColorMode)() {
if m != nil {
m.colorMode = value
}
}
// SetContentType sets the contentType property value. The default content (MIME) type to use when processing documents.
func (m *PrinterDefaults) SetContentType(value *string)() {
if m != nil {
m.contentType = value
}
}
// SetCopiesPerJob sets the copiesPerJob property value. The default number of copies printed per job.
func (m *PrinterDefaults) SetCopiesPerJob(value *int32)() {
if m != nil {
m.copiesPerJob = value
}
}
// SetDpi sets the dpi property value. The default resolution in DPI to use when printing the job.
func (m *PrinterDefaults) SetDpi(value *int32)() {
if m != nil {
m.dpi = value
}
}
// SetDuplexMode sets the duplexMode property value. The default duplex (double-sided) configuration to use when printing a document. Valid values are described in the following table.
func (m *PrinterDefaults) SetDuplexMode(value *PrintDuplexMode)() {
if m != nil {
m.duplexMode = value
}
}
// SetFinishings sets the finishings property value. The default set of finishings to apply to print jobs. Valid values are described in the following table.
func (m *PrinterDefaults) SetFinishings(value []PrintFinishing)() {
if m != nil {
m.finishings = value
}
}
// SetFitPdfToPage sets the fitPdfToPage property value. The default fitPdfToPage setting. True to fit each page of a PDF document to a physical sheet of media; false to let the printer decide how to lay out impressions.
func (m *PrinterDefaults) SetFitPdfToPage(value *bool)() {
if m != nil {
m.fitPdfToPage = value
}
}
// SetInputBin sets the inputBin property value. The default input bin that serves as the paper source.
func (m *PrinterDefaults) SetInputBin(value *string)() {
if m != nil {
m.inputBin = value
}
}
// SetMediaColor sets the mediaColor property value. The default media (such as paper) color to print the document on.
func (m *PrinterDefaults) SetMediaColor(value *string)() {
if m != nil {
m.mediaColor = value
}
}
// SetMediaSize sets the mediaSize property value. The default media size to use. Supports standard size names for ISO and ANSI media sizes. Valid values are listed in the printerCapabilities topic.
func (m *PrinterDefaults) SetMediaSize(value *string)() {
if m != nil {
m.mediaSize = value
}
}
// SetMediaType sets the mediaType property value. The default media (such as paper) type to print the document on.
func (m *PrinterDefaults) SetMediaType(value *string)() {
if m != nil {
m.mediaType = value
}
}
// SetMultipageLayout sets the multipageLayout property value. The default direction to lay out pages when multiple pages are being printed per sheet. Valid values are described in the following table.
func (m *PrinterDefaults) SetMultipageLayout(value *PrintMultipageLayout)() {
if m != nil {
m.multipageLayout = value
}
}
// SetOrientation sets the orientation property value. The default orientation to use when printing the document. Valid values are described in the following table.
func (m *PrinterDefaults) SetOrientation(value *PrintOrientation)() {
if m != nil {
m.orientation = value
}
}
// SetOutputBin sets the outputBin property value. The default output bin to place completed prints into. See the printer's capabilities for a list of supported output bins.
func (m *PrinterDefaults) SetOutputBin(value *string)() {
if m != nil {
m.outputBin = value
}
}
// SetPagesPerSheet sets the pagesPerSheet property value. The default number of document pages to print on each sheet.
func (m *PrinterDefaults) SetPagesPerSheet(value *int32)() {
if m != nil {
m.pagesPerSheet = value
}
}
// SetQuality sets the quality property value. The default quality to use when printing the document. Valid values are described in the following table.
func (m *PrinterDefaults) SetQuality(value *PrintQuality)() {
if m != nil {
m.quality = value
}
}
// SetScaling sets the scaling property value. Specifies how the printer scales the document data to fit the requested media. Valid values are described in the following table.
func (m *PrinterDefaults) SetScaling(value *PrintScaling)() {
if m != nil {
m.scaling = value
}
} | models/microsoft/graph/printer_defaults.go | 0.666062 | 0.418103 | printer_defaults.go | starcoder |
package image_conversions
import (
"fmt"
"image"
"image/color"
"github.com/TheZoraiz/ascii-image-converter/aic_package/winsize"
"github.com/disintegration/imaging"
gookitColor "github.com/gookit/color"
"github.com/makeworld-the-better-one/dither/v2"
)
func ditherImage(img image.Image) image.Image {
palette := []color.Color{
color.Black,
color.White,
}
d := dither.NewDitherer(palette)
d.Matrix = dither.FloydSteinberg
return d.DitherCopy(img)
}
func resizeImage(img image.Image, full, isBraille bool, dimensions []int, width, height int) (image.Image, error) {
var asciiWidth, asciiHeight int
var smallImg image.Image
imgWidth := float64(img.Bounds().Dx())
imgHeight := float64(img.Bounds().Dy())
aspectRatio := imgWidth / imgHeight
if full {
terminalWidth, _, err := winsize.GetTerminalSize()
if err != nil {
return nil, err
}
asciiWidth = terminalWidth - 1
asciiHeight = int(float64(asciiWidth) / aspectRatio)
asciiHeight = int(0.5 * float64(asciiHeight))
} else if (width != 0 || height != 0) && len(dimensions) == 0 {
// If either width or height is set and dimensions aren't given
if width != 0 && height == 0 {
// If width is set and height is not set, use width to calculate aspect ratio
asciiWidth = width
asciiHeight = int(float64(asciiWidth) / aspectRatio)
asciiHeight = int(0.5 * float64(asciiHeight))
if asciiHeight == 0 {
asciiHeight = 1
}
} else if height != 0 && width == 0 {
// If height is set and width is not set, use height to calculate aspect ratio
asciiHeight = height
asciiWidth = int(float64(asciiHeight) * aspectRatio)
asciiWidth = int(2 * float64(asciiWidth))
if asciiWidth == 0 {
asciiWidth = 1
}
} else {
return nil, fmt.Errorf("error: both width and height can't be set. Use dimensions instead")
}
} else if len(dimensions) == 0 {
// This condition calculates aspect ratio according to terminal height
terminalWidth, terminalHeight, err := winsize.GetTerminalSize()
if err != nil {
return nil, err
}
asciiHeight = terminalHeight - 1
asciiWidth = int(float64(asciiHeight) * aspectRatio)
asciiWidth = int(2 * float64(asciiWidth))
// If ascii width exceeds terminal width, change ratio with respect to terminal width
if asciiWidth >= terminalWidth {
asciiWidth = terminalWidth - 1
asciiHeight = int(float64(asciiWidth) / aspectRatio)
asciiHeight = int(0.5 * float64(asciiHeight))
}
} else {
// Else, set passed dimensions
asciiWidth = dimensions[0]
asciiHeight = dimensions[1]
}
// Because one braille character has 8 dots (4 rows and 2 columns)
if isBraille {
asciiWidth *= 2
asciiHeight *= 4
}
smallImg = imaging.Resize(img, asciiWidth, asciiHeight, imaging.Lanczos)
return smallImg, nil
}
func reverse(imgSet [][]AsciiPixel, flipX, flipY bool) [][]AsciiPixel {
if flipX {
for _, row := range imgSet {
for i, j := 0, len(row)-1; i < j; i, j = i+1, j-1 {
row[i], row[j] = row[j], row[i]
}
}
}
if flipY {
for i, j := 0, len(imgSet)-1; i < j; i, j = i+1, j-1 {
imgSet[i], imgSet[j] = imgSet[j], imgSet[i]
}
}
return imgSet
}
var termColorLevel string = gookitColor.TermColorLevel().String()
// This functions calculates terminal color level between rgb colors and 256-colors
// and returns the character with escape codes appropriately
func getColoredCharForTerm(r, g, b uint8, char string, background bool) (string, error) {
var coloredChar string
if termColorLevel == "millions" {
colorRenderer := gookitColor.RGB(uint8(r), uint8(g), uint8(b), background)
coloredChar = colorRenderer.Sprintf("%v", char)
} else if termColorLevel == "hundreds" {
colorRenderer := gookitColor.RGB(uint8(r), uint8(g), uint8(b), background).C256()
coloredChar = colorRenderer.Sprintf("%v", char)
} else {
return "", fmt.Errorf("your terminal supports neither 24-bit nor 8-bit colors. Other coloring options aren't available")
}
return coloredChar, nil
} | image_manipulation/util.go | 0.692434 | 0.546254 | util.go | starcoder |
package main
// Note: Adjacency list representation of graph was already implemented by me in previous graphs section. Hence I have
// modified few things which converts this adjacency list to adjacency matrix and then the floyd warshall algorithm is
// implemented. However you can directly take user inputs and add it in adjacency matrix.
import (
"fmt"
"math"
)
type vertexNumber struct {
value int
name string
}
var adjacencyMatrix [][]float64
var vertices map[string]int
// FloydWarshall calculates all points shortest path from adjacency matrix of a graph
func FloydWarshall() {
for k := range adjacencyMatrix {
for i := range adjacencyMatrix {
for j := range adjacencyMatrix {
adjacencyMatrix[i][j] = math.Min(adjacencyMatrix[i][j], adjacencyMatrix[i][k]+adjacencyMatrix[k][j])
}
}
}
fmt.Println("\n-- Final Adjacency Matrix --")
for i := range adjacencyMatrix {
fmt.Println(adjacencyMatrix[i])
}
}
func init() {
vertices = make(map[string]int)
}
func main() {
fmt.Println("\n-- Floyd Warshall's Algorithm --")
i := 0
for i == 0 {
fmt.Println("\n1. ADD A VERTEX")
fmt.Println("2. ADD AN EDGE")
fmt.Println("3. SIMPLE DISPLAY")
fmt.Println("4. RUN FLOYD WARSHALL")
fmt.Println("5. EXIT")
var choice int
fmt.Print("Enter your choice: ")
fmt.Scanf("%d\n", &choice)
switch choice {
case 1:
addVertex()
case 2:
addEdge()
case 3:
simpleDisplay()
case 4:
constructMatrix()
FloydWarshall()
case 5:
i = 1
default:
fmt.Println("Command not recognized.")
}
}
}
// generates a adjacency matrix from adjacency list
func constructMatrix() {
count := 0
adjacencyMatrix = make([][]float64, len(vertices))
for i := range graph {
adjacencyMatrix[vertices[i]] = make([]float64, len(vertices))
for j := range graph[i] {
adjacencyMatrix[vertices[i]][vertices[graph[i][j].name]] = float64(graph[i][j].value)
}
count++
}
for i := range adjacencyMatrix {
for j := range adjacencyMatrix[i] {
if i != j && adjacencyMatrix[i][j] == 0 {
adjacencyMatrix[i][j] = math.Inf(0)
}
}
}
fmt.Println("\n-- Initial Adjacency Matrix --")
for i := range adjacencyMatrix {
fmt.Println(adjacencyMatrix[i])
}
}
func simpleDisplay() {
fmt.Println("")
for i := range graph {
fmt.Print(i, " => ")
for j := range graph[i] {
fmt.Print(graph[i][j])
}
fmt.Println("")
}
}
// addVertexToGraph("a")
// addVertexToGraph("b")
// addVertexToGraph("c")
// addVertexToGraph("d")
// addVertexToGraph("e")
// addVertexToGraph("f")
// addEdgeToGraph("a", "b", 18)
// addEdgeToGraph("a", "c", 20)
// addEdgeToGraph("b", "d", 4)
// addEdgeToGraph("c", "e", 10)
// addEdgeToGraph("d", "e", 15)
// addEdgeToGraph("d", "f", 23)
// addEdgeToGraph("e", "f", 7)
// addEdgeToGraph("d", "a", 5)
// addEdgeToGraph("e", "a", 17)
// addEdgeToGraph("b", "e", 21) | algorithms/graphs/floyd_warshall/floyd_warshall.go | 0.577853 | 0.433022 | floyd_warshall.go | starcoder |
package dgopcore
import (
"errors"
"fmt"
"github.com/lyraproj/dgo/dgo"
"github.com/lyraproj/dgo/typ"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
)
// ToPcore converts a dgo.Value into its corresponding px.Value.
func ToPcore(v dgo.Value) px.Value {
var cv px.Value
switch v := v.(type) {
case dgo.String:
cv = types.WrapString(v.GoString())
case dgo.Integer:
cv = types.WrapInteger(v.GoInt())
case dgo.Float:
cv = types.WrapFloat(v.GoFloat())
case dgo.Boolean:
cv = types.WrapBoolean(v.GoBool())
case dgo.Array:
cv = toArray(v)
case dgo.Map:
cv = toMap(v)
case dgo.Binary:
cv = types.WrapBinary(v.GoBytes())
case dgo.Native:
cv = toNative(v)
case dgo.Regexp:
cv = types.WrapRegexp2(v.GoRegexp())
case dgo.Sensitive:
cv = types.WrapSensitive(ToPcore(v.Unwrap()))
case dgo.Time:
cv = types.WrapTimestamp(v.GoTime())
case dgo.Nil:
cv = px.Undef
case dgo.Type:
cv = toType(v)
default:
panic(fmt.Errorf(`unable to create a px.Value from a dgo %s`, v.Type()))
}
return cv
}
func toArray(a dgo.Array) px.List {
ps := make([]px.Value, a.Len())
a.EachWithIndex(func(v dgo.Value, i int) { ps[i] = ToPcore(v) })
return types.WrapValues(ps)
}
func toNative(v dgo.Native) *types.RuntimeValue {
return types.WrapRuntime(v.GoValue())
}
func toMap(v dgo.Map) px.OrderedMap {
hs := make([]*types.HashEntry, 0, v.Len())
v.EachEntry(func(e dgo.MapEntry) { hs = append(hs, types.WrapHashEntry(ToPcore(e.Key()), ToPcore(e.Value()))) })
return types.WrapHash(hs)
}
func toTypes(ts dgo.Array) []px.Type {
ps := make([]px.Type, ts.Len())
ts.EachWithIndex(func(v dgo.Value, i int) { ps[i] = toType(v.(dgo.Type)) })
return ps
}
func toIntegerType(min, max int) *types.IntegerType {
return types.NewIntegerType(int64(min), int64(max))
}
func toType(t dgo.Type) (pt px.Type) {
if f, ok := toTypeFuncs[t.TypeIdentifier()]; ok {
return f(t)
}
panic(fmt.Errorf(`unable to create pcore Type from a '%s'`, t))
}
func toStruct(st dgo.StructMapType) px.Type {
if st.Additional() {
panic(errors.New(`unable to create pcore Struct that allows additional entries`))
}
es := make([]*types.StructElement, st.Len())
i := 0
st.Each(func(e dgo.StructMapEntry) {
kt := toType(e.Key().(dgo.Type))
if !e.Required() {
kt = types.NewOptionalType(kt)
}
es[i] = types.NewStructElement(kt, toType(e.Value().(dgo.Type)))
i++
})
return types.NewStructType(es)
}
type toTypeFunc func(dgo.Type) px.Type
var toTypeFuncs map[dgo.TypeIdentifier]toTypeFunc
func init() {
toTypeFuncs = map[dgo.TypeIdentifier]toTypeFunc{
dgo.TiBoolean: func(t dgo.Type) px.Type {
return types.DefaultBooleanType()
},
dgo.TiTrue: func(t dgo.Type) px.Type {
return types.NewBooleanType(true)
},
dgo.TiFalse: func(t dgo.Type) px.Type {
return types.NewBooleanType(false)
},
dgo.TiFloat: func(t dgo.Type) px.Type {
return types.DefaultFloatType()
},
dgo.TiFloatExact: func(t dgo.Type) px.Type {
rt := t.(dgo.FloatRangeType)
return types.NewFloatType(rt.Min(), rt.Max())
},
dgo.TiFloatRange: func(t dgo.Type) px.Type {
rt := t.(dgo.FloatRangeType)
if !rt.Inclusive() {
panic(errors.New(`unable to create non inclusive pcore Float type`))
}
return types.NewFloatType(rt.Min(), rt.Max())
},
dgo.TiInteger: func(t dgo.Type) px.Type {
return types.DefaultIntegerType()
},
dgo.TiIntegerExact: func(t dgo.Type) px.Type {
rt := t.(dgo.IntegerRangeType)
return types.NewIntegerType(rt.Min(), rt.Max())
},
dgo.TiIntegerRange: func(t dgo.Type) px.Type {
rt := t.(dgo.IntegerRangeType)
mx := rt.Max()
if !rt.Inclusive() {
mx--
}
return types.NewIntegerType(rt.Min(), mx)
},
dgo.TiString: func(t dgo.Type) px.Type {
return types.DefaultStringType()
},
dgo.TiStringExact: func(t dgo.Type) px.Type {
return types.NewStringType(nil, t.(dgo.ExactType).Value().(dgo.String).GoString())
},
dgo.TiStringSized: func(t dgo.Type) px.Type {
st := t.(dgo.StringType)
return types.NewStringType(toIntegerType(st.Min(), st.Max()), ``)
},
dgo.TiStringPattern: func(t dgo.Type) px.Type {
rx := t.(dgo.ExactType).Value().(dgo.Regexp)
return types.NewPatternType([]*types.RegexpType{types.NewRegexpTypeR(rx.GoRegexp())})
},
dgo.TiCiString: func(t dgo.Type) px.Type {
v := t.(dgo.ExactType).Value().(dgo.String)
return types.NewEnumType([]string{v.GoString()}, true)
},
dgo.TiAny: func(t dgo.Type) px.Type {
return types.DefaultAnyType()
},
dgo.TiAnyOf: func(t dgo.Type) px.Type {
return types.NewVariantType(toTypes(t.(dgo.TernaryType).Operands())...)
},
dgo.TiArray: func(t dgo.Type) px.Type {
at := t.(dgo.ArrayType)
return types.NewArrayType(toType(at.ElementType()), toIntegerType(at.Min(), at.Max()))
},
dgo.TiArrayExact: func(t dgo.Type) px.Type {
return toArray(t.(dgo.ExactType).Value().(dgo.Array)).PType()
},
dgo.TiTuple: func(t dgo.Type) px.Type {
es := toTypes(t.(dgo.TupleType).ElementTypes())
tc := len(es)
if tc == 0 {
return types.DefaultTupleType()
}
return types.NewTupleType(es, toIntegerType(tc, tc))
},
dgo.TiMap: func(t dgo.Type) px.Type {
mt := t.(dgo.MapType)
return types.NewHashType(toType(mt.KeyType()), toType(mt.ValueType()), toIntegerType(mt.Min(), mt.Max()))
},
dgo.TiMapExact: func(t dgo.Type) px.Type {
return toMap(t.(dgo.ExactType).Value().(dgo.Map)).PType()
},
dgo.TiStruct: func(t dgo.Type) px.Type {
return toStruct(t.(dgo.StructMapType))
},
dgo.TiBinary: func(t dgo.Type) px.Type {
return types.DefaultBinaryType()
},
dgo.TiMeta: func(t dgo.Type) px.Type {
ct := t.(dgo.UnaryType).Operand()
var pt px.Type
if ct == nil {
pt = types.DefaultTypeType().PType()
} else {
pt = toType(ct)
}
return types.NewTypeType(pt)
},
dgo.TiNative: func(t dgo.Type) px.Type {
rt := t.(dgo.NativeType).GoType()
if rt == nil {
return types.DefaultRuntimeType()
}
return types.NewGoRuntimeType(rt)
},
dgo.TiRegexp: func(t dgo.Type) px.Type {
return types.DefaultRegexpType()
},
dgo.TiRegexpExact: func(t dgo.Type) px.Type {
return types.NewRegexpTypeR(t.(dgo.ExactType).Value().(dgo.Regexp).GoRegexp())
},
dgo.TiSensitive: func(t dgo.Type) px.Type {
if op := t.(dgo.UnaryType).Operand(); typ.Any != op {
return types.NewSensitiveType(toType(op))
}
return types.DefaultSensitiveType()
},
dgo.TiTime: func(t dgo.Type) px.Type {
return types.DefaultTimestampType()
},
dgo.TiTimeExact: func(t dgo.Type) px.Type {
tm := t.(dgo.ExactType).Value().(dgo.Time).GoTime()
return types.NewTimestampType(tm, tm)
},
}
} | topcore.go | 0.545528 | 0.420808 | topcore.go | starcoder |
package game
const (
motionByteSize = 1341
motionByteActualSize = motionByteSize - headerSize
wheelDataSize = 16
carMotionCount = 20
wheelDataCount = 5
)
// CarMotion provides the motion data for a single car
type CarMotion struct {
WorldPositionX float32
WorldPositionY float32
WorldPositionZ float32
WorldVelocityX float32
WorldVelocityY float32
WorldVelocityZ float32
WorldForwardDirX int16
WorldForwardDirY int16
WorldForwardDirZ int16
WorldRightDirX int16
WorldRightDirY int16
WorldRightDirZ int16
GForceLateral float32
GForceLongitudinal float32
GForceVertical float32
Yaw float32
Pitch float32
Roll float32
}
func newCarMotion(b []byte, next int) (CarMotion, int) {
var m CarMotion
m.WorldPositionX, next = bsfloat32(b, next)
m.WorldPositionY, next = bsfloat32(b, next)
m.WorldPositionZ, next = bsfloat32(b, next)
m.WorldVelocityX, next = bsfloat32(b, next)
m.WorldVelocityY, next = bsfloat32(b, next)
m.WorldVelocityZ, next = bsfloat32(b, next)
m.WorldForwardDirX, next = bsint16(b, next)
m.WorldForwardDirY, next = bsint16(b, next)
m.WorldForwardDirZ, next = bsint16(b, next)
m.WorldRightDirX, next = bsint16(b, next)
m.WorldRightDirY, next = bsint16(b, next)
m.WorldRightDirZ, next = bsint16(b, next)
m.GForceLateral, next = bsfloat32(b, next)
m.GForceLongitudinal, next = bsfloat32(b, next)
m.GForceVertical, next = bsfloat32(b, next)
m.Yaw, next = bsfloat32(b, next)
m.Pitch, next = bsfloat32(b, next)
m.Roll, next = bsfloat32(b, next)
return m, next
}
// WheelData provides data for all wheels of a single car
type WheelData struct {
RearLeft float32
RearRight float32
FrontLeft float32
FrontRight float32
}
func newWheelData(b []byte, next int) (WheelData, int) {
var w WheelData
w.RearLeft, next = bsfloat32(b, next)
w.RearRight, next = bsfloat32(b, next)
w.FrontLeft, next = bsfloat32(b, next)
w.FrontRight, next = bsfloat32(b, next)
return w, next
}
// MotionData provides motion data for all cars plus additional data for the driver's car
type MotionData struct {
CarMotion [carMotionCount]CarMotion
SuspensionVelocity WheelData
SuspensionPosition WheelData
SuspensionAcceleration WheelData
WheelSpeed WheelData
WheelSlip WheelData
LocalVelocityX float32
LocalVelocityY float32
LocalVelocityZ float32
AngularVelocityX float32
AngularVelocityY float32
AngularVelocityZ float32
AngularAccelerationX float32
AngularAccelerationY float32
AngularAccelerationZ float32
FrontWheelsAngle float32
}
func newMotionData(b []byte, next int) MotionData {
var m MotionData
for i := range m.CarMotion {
m.CarMotion[i], next = newCarMotion(b, next)
}
m.SuspensionVelocity, next = newWheelData(b, next)
m.SuspensionPosition, next = newWheelData(b, next)
m.SuspensionAcceleration, next = newWheelData(b, next)
m.WheelSpeed, next = newWheelData(b, next)
m.WheelSlip, next = newWheelData(b, next)
m.LocalVelocityX, next = bsfloat32(b, next)
m.LocalVelocityY, next = bsfloat32(b, next)
m.LocalVelocityZ, next = bsfloat32(b, next)
m.AngularVelocityX, next = bsfloat32(b, next)
m.AngularVelocityY, next = bsfloat32(b, next)
m.AngularVelocityZ, next = bsfloat32(b, next)
m.AngularAccelerationX, next = bsfloat32(b, next)
m.AngularAccelerationY, next = bsfloat32(b, next)
m.AngularAccelerationZ, next = bsfloat32(b, next)
m.FrontWheelsAngle, next = bsfloat32(b, next)
return m
} | game/motion.go | 0.674694 | 0.435001 | motion.go | starcoder |
package main
/*
Programming Assignment 4, accessed 10 May 2019, from:
Stanford Online Lagunita, Algorithms: Design and Analysis, Part 1.
The file, SCC.txt, contains the edges of a directed graph. Vertices are
labeled as positive integers from 1 to 875714. Every row indicates an
edge, the vertex label in first column is the tail and the vertex label
in second column is the head (recall the graph is directed, and the
edges are directed from the first column vertex to the second column
vertex). So for example, the 11th row looks liks : "2 47646". This just
means that the vertex with label 2 has an outgoing edge to the vertex
with label 47646.
Your task is to code up the algorithm from the video lectures,
Kosaraju's Two-Pass Algorithm, for computing strongly connected
components (SCCs), and to run this algorithm on the given graph.
*/
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
func main() {
fmt.Println("This program demonstrates Kosaraju's Two-Pass algorithm on a directed graph.")
nodeEdges, initFinishOrder, maxNode := setup("SCC.txt")
// Step 1: Given a directed graph, reverse the graph.
// That is, a --> b becomes a <-- b.
reversedNodeEdges := reverseGraph(nodeEdges)
// Step 2, Pass 1: Run a topological sort using the reversed graph.
// This step gives the order to search nodes in the next step.
finishOrder, _ := topologicalSort(reversedNodeEdges, maxNode, initFinishOrder)
// Step 3, Pass 2: Run a topological sort with the original graph.
// This step discovers the SCCs.
_, stronglyConnected := topologicalSort(nodeEdges, maxNode, finishOrder)
output := top5(stronglyConnected, maxNode)
fmt.Print(output)
}
func setup(fileName string) (map[int][]int, map[int]int, int) {
// converts the SCC.txt file into a Go useable format.
file, err := os.Open(fileName)
defer file.Close()
if err != nil {
fmt.Println(err)
return nil, nil, 0
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
// For node edges the key will be a node at the tail and the values
// will be the nodes at the heads of the directed section.
// So, (a, b) = a --> b and the key would be a with a value of b.
nodeEdges := make(map[int][]int)
var maxNode int
for scanner.Scan() {
xLine := strings.Split(scanner.Text(), " ")
// The last space character leaves a zero value in the slice,
// remove it.
xLine = xLine[0 : len(xLine)-1]
v := make([]int, len(xLine))
for idx, value := range xLine {
val, _ := strconv.Atoi(value)
v[idx] = val
}
nodeEdges[v[0]] = append(nodeEdges[v[0]], v[1])
if v[0] > maxNode {
maxNode = v[0]
}
}
// Some nodes are only tails and must be accounted for.
ascendingFinishOrder := make(map[int]int)
for node := 1; node <= maxNode; node++ {
ascendingFinishOrder[node] = node
if _, head := nodeEdges[node]; !head {
nodeEdges[node] = []int{node}
}
}
return nodeEdges, ascendingFinishOrder, maxNode
}
func reverseGraph(originalGraph map[int][]int) map[int][]int {
// Reverses node relationships in a graph.
reversedGraph := make(map[int][]int)
for head, tails := range originalGraph {
for _, tail := range tails {
reversedGraph[tail] = append(reversedGraph[tail], head)
}
}
// Some nodes are only sources in the original graph and will not
// be represented in the reversed graph if they do not have self-
// references.
for node := 1; node <= len(originalGraph); node++ {
if _, ok := reversedGraph[node]; !ok {
reversedGraph[node] = []int{node}
}
}
return reversedGraph
}
func topologicalSort(nodeEdges map[int][]int, maxNode int, finishOrder map[int]int) (map[int]int, map[int][]int) {
// Outer loop for depth first search to keep track of a vertex's
// order of finishing, that is, when the inner loop,
// depthFirstSearch(), cannot recurse any further.
// Mark all nodes as unexplored.
isExplored := make(map[int]bool)
for node := 1; node <= len(nodeEdges); node++ {
isExplored[node] = false
}
// finishingOrder, a lower value means the node processed first
var finishingOrder, leadNode int
stronglyConnected := make(map[int][]int)
// Have to make a true copy without changing the original map.
finishOrderCopy := make(map[int]int)
for key, value := range finishOrder {
finishOrderCopy[key] = value
}
for i := len(finishOrder); i > 0; i-- {
u := finishOrder[i]
if !isExplored[u] {
leadNode = u
finishingOrder = depthFirstSearch(nodeEdges, stronglyConnected,
finishOrderCopy, isExplored, u, finishingOrder, leadNode)
}
}
return finishOrderCopy, stronglyConnected
}
func depthFirstSearch(nodeEdges, stronglyConnected map[int][]int,
finishOrderCopy map[int]int, isExplored map[int]bool, u, finishingOrder,
leadNode int) int {
// Depth first search implementation. Searches a directed graph
// until the search hits an explored node and returns where the
// node is in relation to other vertices.
isExplored[u] = true
stronglyConnected[leadNode] = append(stronglyConnected[leadNode], u)
for _, v := range nodeEdges[u] {
if !isExplored[v] {
finishingOrder = depthFirstSearch(nodeEdges, stronglyConnected,
finishOrderCopy, isExplored, v, finishingOrder, leadNode)
}
}
finishingOrder++
finishOrderCopy[finishingOrder] = u
return finishingOrder
}
func top5(stronglyConnected map[int][]int, maxNode int) string {
var output string
maxConnections := make([]int, 0)
for node := 1; node <= maxNode; node++ {
if len(stronglyConnected[node]) > 0 {
maxConnections = append(maxConnections, len(stronglyConnected[node]))
}
}
sort.Sort(sort.Reverse(sort.IntSlice(maxConnections)))
if len(maxConnections) < 5 {
output = fmt.Sprintln("max Connections:", maxConnections)
} else {
output = fmt.Sprintln("max Connections:", maxConnections[:5])
}
return output
} | Stanford/ProgrammingQuestion4_FindStronglyConnectedComponents/main.go | 0.657648 | 0.613005 | main.go | starcoder |
package protocol
// TransformMap store the configured crypto suite
// NOTE that this cannot be used to parse incoming list of transforms
// incoming list can have many Transforms of same type in 1 proposal
type TransformMap map[TransformType]*SaTransform
func ProposalFromTransform(prot ProtocolID, trs TransformMap, spi []byte) Proposals {
return Proposals{
&SaProposal{
IsLast: true,
Number: 1,
ProtocolID: prot,
Spi: append([]byte{}, spi...),
Transforms: trs.AsList(),
},
}
}
// AsList converts transforms to flat list
func (t TransformMap) AsList() (trs []*SaTransform) {
for _, trsVal := range t {
trs = append(trs, trsVal)
}
return
}
// Within checks if the configured set of transforms occurs within list of proposed transforms
func (t TransformMap) Within(proposed []*SaTransform) bool {
listHas := func(proposed []*SaTransform, target *SaTransform) bool {
for _, tr := range proposed {
if target.IsEqual(tr) {
return true
}
}
return false
}
for _, transform := range t {
if listHas(proposed, transform) {
return true
}
}
return false
}
func (t TransformMap) GetType(ty TransformType) *Transform {
trs, ok := t[ty]
if !ok {
return nil
}
return &trs.Transform
}
// IkeTransform builds a IKE cipher suite
func IkeTransform(encr EncrTransformId, keyBits uint16, auth AuthTransformId, prf PrfTransformId, dh DhTransformId) TransformMap {
return TransformMap{
TRANSFORM_TYPE_ENCR: &SaTransform{
Transform: Transform{
Type: TRANSFORM_TYPE_ENCR,
TransformId: uint16(encr),
},
KeyLength: keyBits,
},
TRANSFORM_TYPE_INTEG: &SaTransform{
Transform: Transform{
Type: TRANSFORM_TYPE_INTEG,
TransformId: uint16(auth),
},
},
TRANSFORM_TYPE_PRF: &SaTransform{
Transform: Transform{
Type: TRANSFORM_TYPE_PRF,
TransformId: uint16(prf),
},
},
TRANSFORM_TYPE_DH: &SaTransform{
Transform: Transform{
Type: TRANSFORM_TYPE_DH,
TransformId: uint16(dh),
},
IsLast: true,
},
}
}
// EspTransform builds an ESP cipher suite
func EspTransform(encr EncrTransformId, keyBits uint16, auth AuthTransformId, esn EsnTransformId) TransformMap {
return TransformMap{
TRANSFORM_TYPE_ENCR: &SaTransform{
Transform: Transform{
Type: TRANSFORM_TYPE_ENCR,
TransformId: uint16(encr),
}, KeyLength: keyBits},
TRANSFORM_TYPE_INTEG: &SaTransform{
Transform: Transform{
Type: TRANSFORM_TYPE_INTEG,
TransformId: uint16(auth),
},
},
TRANSFORM_TYPE_ESN: &SaTransform{
Transform: Transform{
Type: TRANSFORM_TYPE_ESN,
TransformId: uint16(esn),
},
IsLast: true,
},
}
} | protocol/transforms.go | 0.721351 | 0.475788 | transforms.go | starcoder |
package year2021
import (
"fmt"
"strings"
"github.com/lanphiergm/adventofcodego/internal/utils"
)
// Transparent Origami Part 1 computes the number of visible dots after one fold
func TransparentOrigamiPart1(filename string) interface{} {
coords, folds := parseOrigamiData(filename)
coords = performFolds(coords, folds[:1])
return len(coords)
}
// Transparent Origami Part 2 computes the activation code
func TransparentOrigamiPart2(filename string) interface{} {
coords, folds := parseOrigamiData(filename)
coords = performFolds(coords, folds)
//printCoords(coords)
return translateCoords(coords)
}
func performFolds(coords map[utils.Coord]struct{}, folds []string) map[utils.Coord]struct{} {
foldAt := utils.Atoi(strings.Split(folds[0], "=")[1])
if strings.HasPrefix(folds[0], "fold along x=") {
coords = performFoldX(coords, foldAt)
} else {
coords = performFoldY(coords, foldAt)
}
if len(folds) > 1 {
coords = performFolds(coords, folds[1:])
}
return coords
}
func performFoldX(coords map[utils.Coord]struct{}, foldAt int) map[utils.Coord]struct{} {
for c := range coords {
if c.X == foldAt {
delete(coords, c)
} else if c.X > foldAt {
coords[utils.Coord{X: 2*foldAt - c.X, Y: c.Y}] = struct{}{}
delete(coords, c)
}
}
return coords
}
func performFoldY(coords map[utils.Coord]struct{}, foldAt int) map[utils.Coord]struct{} {
for c := range coords {
if c.Y == foldAt {
delete(coords, c)
} else if c.Y > foldAt {
coords[utils.Coord{X: c.X, Y: 2*foldAt - c.Y}] = struct{}{}
delete(coords, c)
}
}
return coords
}
func printCoords(coords map[utils.Coord]struct{}) {
maxX := 0
maxY := 0
for c := range coords {
if c.X > maxX {
maxX = c.X
}
if c.Y > maxY {
maxY = c.Y
}
}
toPrint := make([][]bool, maxY+1)
for i := 0; i <= maxY; i++ {
toPrint[i] = make([]bool, maxX+1)
}
for c := range coords {
toPrint[c.Y][c.X] = true
}
for _, row := range toPrint {
for _, v := range row {
if v {
fmt.Printf("#")
} else {
fmt.Printf(".")
}
}
fmt.Printf("\n")
}
}
func translateCoords(coords map[utils.Coord]struct{}) string {
var grid [6][39]bool
for c := range coords {
grid[c.Y][c.X] = true
}
code := ""
for i := 0; i < 39; i += 5 {
for key, val := range letters {
isMatch := true
for j := 0; j < 6; j++ {
for k := 0; k < 4; k++ {
if key[j][k] != grid[j][i+k] {
isMatch = false
break
}
}
if !isMatch {
break
}
}
if isMatch {
code += val
break
}
}
}
return code
}
var letterE = [6][4]bool{{true, true, true, true}, {true, false, false, false}, {true, true, true, false},
{true, false, false, false}, {true, false, false, false}, {true, true, true, true}}
var letterG = [6][4]bool{{false, true, true, false}, {true, false, false, true}, {true, false, false, false},
{true, false, true, true}, {true, false, false, true}, {false, true, true, true}}
var letterH = [6][4]bool{{true, false, false, true}, {true, false, false, true}, {true, true, true, true},
{true, false, false, true}, {true, false, false, true}, {true, false, false, true}}
var letterJ = [6][4]bool{{false, false, true, true}, {false, false, false, true}, {false, false, false, true},
{false, false, false, true}, {true, false, false, true}, {false, true, true, false}}
var letterL = [6][4]bool{{true, false, false, false}, {true, false, false, false}, {true, false, false, false},
{true, false, false, false}, {true, false, false, false}, {true, true, true, true}}
var letterU = [6][4]bool{{true, false, false, true}, {true, false, false, true}, {true, false, false, true},
{true, false, false, true}, {true, false, false, true}, {false, true, true, false}}
var letters = map[[6][4]bool]string{letterE: "E", letterG: "G", letterH: "H", letterJ: "J", letterL: "L", letterU: "U"}
func parseOrigamiData(filename string) (map[utils.Coord]struct{}, []string) {
data := utils.ReadStrings(filename)
coords := make(map[utils.Coord]struct{})
foldStart := 0
for i, c := range data {
if c == "" {
foldStart = i + 1
break
}
tmp := strings.Split(c, ",")
coords[utils.Coord{X: utils.Atoi(tmp[0]), Y: utils.Atoi(tmp[1])}] = struct{}{}
}
return coords, data[foldStart:]
} | internal/puzzles/year2021/day_13_transparent_origami.go | 0.572962 | 0.431524 | day_13_transparent_origami.go | starcoder |
package glmatrix
import (
"fmt"
"math"
"math/rand"
)
// NewVec3 creates a new, empty Vec3
func NewVec3() []float64 {
return []float64{0., 0., 0.}
}
// Vec3Create creates a new Vec3 initialized with values from an existing vector
func Vec3Create() []float64 {
return NewVec3()
}
// Vec3Clone creates a new Vec3 initialized with the given values
func Vec3Clone(a []float64) []float64 {
return []float64{a[0], a[1], a[2]}
}
// Vec3FromValues creates a new Vec3 initialized with the given values
func Vec3FromValues(x, y, z float64) []float64 {
return []float64{x, y, z}
}
// Vec3Copy copy the values from one Vec3 to another
func Vec3Copy(out, a []float64) []float64 {
out[0] = a[0]
out[1] = a[1]
out[2] = a[2]
return out
}
// Vec3Set set the components of a Vec3 to the given values
func Vec3Set(out []float64, x, y, z float64) []float64 {
out[0] = x
out[1] = y
out[2] = z
return out
}
// Vec3Add adds two Vec3's
func Vec3Add(out, a, b []float64) []float64 {
out[0] = a[0] + b[0]
out[1] = a[1] + b[1]
out[2] = a[2] + b[2]
return out
}
// Vec3Subtract subtracts vector b from vector a
func Vec3Subtract(out, a, b []float64) []float64 {
out[0] = a[0] - b[0]
out[1] = a[1] - b[1]
out[2] = a[2] - b[2]
return out
}
// Vec3Multiply multiplies two Vec3's
func Vec3Multiply(out, a, b []float64) []float64 {
out[0] = a[0] * b[0]
out[1] = a[1] * b[1]
out[2] = a[2] * b[2]
return out
}
// Vec3Divide divides two Vec3's
func Vec3Divide(out, a, b []float64) []float64 {
out[0] = a[0] / b[0]
out[1] = a[1] / b[1]
out[2] = a[2] / b[2]
return out
}
// Vec3Ceil math.ceil the components of a Vec3
func Vec3Ceil(out, a []float64) []float64 {
out[0] = math.Ceil(a[0])
out[1] = math.Ceil(a[1])
out[2] = math.Ceil(a[2])
return out
}
// Vec3Floor math.floor the components of a Vec3
func Vec3Floor(out, a []float64) []float64 {
out[0] = math.Floor(a[0])
out[1] = math.Floor(a[1])
out[2] = math.Floor(a[2])
return out
}
// Vec3Min returns the minimum of two Vec3's
func Vec3Min(out, a, b []float64) []float64 {
out[0] = math.Min(a[0], b[0])
out[1] = math.Min(a[1], b[1])
out[2] = math.Min(a[2], b[2])
return out
}
// Vec3Max returns the maximum of two Vec3's
func Vec3Max(out, a, b []float64) []float64 {
out[0] = math.Max(a[0], b[0])
out[1] = math.Max(a[1], b[1])
out[2] = math.Max(a[2], b[2])
return out
}
// Vec3Round math.round the components of a Vec3
func Vec3Round(out, a []float64) []float64 {
out[0] = math.Round(a[0])
out[1] = math.Round(a[1])
out[2] = math.Round(a[2])
return out
}
// Vec3Scale scales a Vec3 by a scalar number
func Vec3Scale(out, a []float64, scale float64) []float64 {
out[0] = a[0] * scale
out[1] = a[1] * scale
out[2] = a[2] * scale
return out
}
// Vec3ScaleAndAdd adds two Vec3's after scaling the second operand by a scalar value
func Vec3ScaleAndAdd(out, a, b []float64, scale float64) []float64 {
out[0] = a[0] + b[0]*scale
out[1] = a[1] + b[1]*scale
out[2] = a[2] + b[2]*scale
return out
}
// Vec3Distance calculates the euclidian distance between two Vec3's
func Vec3Distance(a, b []float64) float64 {
x := b[0] - a[0]
y := b[1] - a[1]
z := b[2] - a[2]
return hypot(x, y, z)
}
// Vec3SquaredDistance calculates the squared euclidian distance between two Vec3's
func Vec3SquaredDistance(a, b []float64) float64 {
x := b[0] - a[0]
y := b[1] - a[1]
z := b[2] - a[2]
return x*x + y*y + z*z
}
// Vec3Length calculates the length of a Vec3
func Vec3Length(out []float64) float64 {
x := out[0]
y := out[1]
z := out[2]
return hypot(x, y, z)
}
// Vec3SquaredLength calculates the squared length of a Vec3
func Vec3SquaredLength(out []float64) float64 {
x := out[0]
y := out[1]
z := out[2]
return x*x + y*y + z*z
}
// Vec3Negate negates the components of a Vec3
func Vec3Negate(out, a []float64) []float64 {
out[0] = -a[0]
out[1] = -a[1]
out[2] = -a[2]
return out
}
// Vec3Inverse returns the inverse of the components of a Vec3
func Vec3Inverse(out, a []float64) []float64 {
out[0] = 1. / a[0]
out[1] = 1. / a[1]
out[2] = 1. / a[2]
return out
}
// Vec3Normalize normalize a Vec3
func Vec3Normalize(out, a []float64) []float64 {
len := Vec3Length(a)
if 0 < len {
len = 1. / len
}
out[0] = a[0] * len
out[1] = a[1] * len
out[2] = a[2] * len
return out
}
// Vec3Dot calculates the dot product of two Vec3's
func Vec3Dot(a, b []float64) float64 {
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
}
// Vec3Cross computes the cross product of two Vec3's
func Vec3Cross(out, a, b []float64) []float64 {
ax := a[0]
ay := a[1]
az := a[2]
bx := b[0]
by := b[1]
bz := b[2]
out[0] = ay*bz - az*by
out[1] = az*bx - ax*bz
out[2] = ax*by - ay*bx
return out
}
// Vec3Lerp performs a linear interpolation between two Vec3's
func Vec3Lerp(out, a, b []float64, t float64) []float64 {
ax := a[0]
ay := a[1]
az := a[2]
out[0] = ax + t*(b[0]-ax)
out[1] = ay + t*(b[1]-ay)
out[2] = az + t*(b[2]-az)
return out
}
// Vec3Slerp performs a spherical linear interpolation between two vec3's
func Vec3Slerp(out, a, b []float64, t float64) []float64 {
angle := math.Acos(math.Min(math.Max(Vec3Dot(a, b), -1), 1))
sinTotal := math.Sin(angle)
ratioA := math.Sin((1-t)*angle) / sinTotal
ratioB := math.Sin(t*angle) / sinTotal
out[0] = ratioA*a[0] + ratioB*b[0]
out[1] = ratioA*a[1] + ratioB*b[1]
out[2] = ratioA*a[2] + ratioB*b[2]
return out
}
// Vec3Hermite performs a hermite interpolation with two control points
func Vec3Hermite(out, a, b, c, d []float64, t float64) []float64 {
factorTimes2 := t * t
factor1 := factorTimes2*(2*t-3) + 1
factor2 := factorTimes2*(t-2) + t
factor3 := factorTimes2 * (t - 1)
factor4 := factorTimes2 * (3 - 2*t)
out[0] = a[0]*factor1 + b[0]*factor2 + c[0]*factor3 + d[0]*factor4
out[1] = a[1]*factor1 + b[1]*factor2 + c[1]*factor3 + d[1]*factor4
out[2] = a[2]*factor1 + b[2]*factor2 + c[2]*factor3 + d[2]*factor4
return out
}
// Vec3Bezier performs a bezier interpolation with two control points
func Vec3Bezier(out, a, b, c, d []float64, t float64) []float64 {
inverseFactor := 1 - t
inverseFactorTimesTwo := inverseFactor * inverseFactor
factorTimes2 := t * t
factor1 := inverseFactorTimesTwo * inverseFactor
factor2 := 3 * t * inverseFactorTimesTwo
factor3 := 3 * factorTimes2 * inverseFactor
factor4 := factorTimes2 * t
out[0] = a[0]*factor1 + b[0]*factor2 + c[0]*factor3 + d[0]*factor4
out[1] = a[1]*factor1 + b[1]*factor2 + c[1]*factor3 + d[1]*factor4
out[2] = a[2]*factor1 + b[2]*factor2 + c[2]*factor3 + d[2]*factor4
return out
}
// Vec3Random generates a random vector with the given scale
func Vec3Random(out []float64, scale float64) []float64 {
r := rand.Float64() * 2.0 * math.Pi
z := rand.Float64()*2.0 - 1.0
zScale := math.Sqrt(1.-z*z) * scale
out[0] = math.Cos(r) * zScale
out[1] = math.Sin(r) * zScale
out[2] = z * scale
return out
}
// Vec3TransformMat3 transforms the vec3 with a mat3
func Vec3TransformMat3(out, a, m []float64) []float64 {
x := a[0]
y := a[1]
z := a[2]
out[0] = x*m[0] + y*m[3] + z*m[6]
out[1] = x*m[1] + y*m[4] + z*m[7]
out[2] = x*m[2] + y*m[5] + z*m[8]
return out
}
// Vec3TransformMat4 transforms the vec3 with a mat4
func Vec3TransformMat4(out, a, m []float64) []float64 {
x := a[0]
y := a[1]
z := a[2]
w := m[3]*x + m[7]*y + m[11]*z + m[15]
if w == 0. {
w = 1.
}
out[0] = (m[0]*x + m[4]*y + m[8]*z + m[12]) / w
out[1] = (m[1]*x + m[5]*y + m[9]*z + m[13]) / w
out[2] = (m[2]*x + m[6]*y + m[10]*z + m[14]) / w
return out
}
// Vec3TransformQuat transforms the vec3 with a quat
// Can also be used for dual quaternions. (Multiply it with the real part)
func Vec3TransformQuat(out, a, q []float64) []float64 {
qx := q[0]
qy := q[1]
qz := q[2]
qw := q[3]
x := a[0]
y := a[1]
z := a[2]
uvx := qy*z - qz*y
uvy := qz*x - qx*z
uvz := qx*y - qy*x
uuvx := qy*uvz - qz*uvy
uuvy := qz*uvx - qx*uvz
uuvz := qx*uvy - qy*uvx
w2 := qw * 2
uvx *= w2
uvy *= w2
uvz *= w2
uuvx *= 2
uuvy *= 2
uuvz *= 2
out[0] = x + uvx + uuvx
out[1] = y + uvy + uuvy
out[2] = z + uvz + uuvz
return out
}
// Vec3RotateX rotate a 3D vector around the x-axis
func Vec3RotateX(out, a, b []float64, rad float64) []float64 {
p := []float64{
a[0] - b[0],
a[1] - b[1],
a[2] - b[2],
}
r := []float64{
p[0],
p[1]*math.Cos(rad) - p[2]*math.Sin(rad),
p[1]*math.Sin(rad) + p[2]*math.Cos(rad),
}
out[0] = r[0] + b[0]
out[1] = r[1] + b[1]
out[2] = r[2] + b[2]
return out
}
// Vec3RotateY rotate a 3D vector around the y-axis
func Vec3RotateY(out, a, b []float64, rad float64) []float64 {
p := []float64{
a[0] - b[0],
a[1] - b[1],
a[2] - b[2],
}
r := []float64{
p[2]*math.Cos(rad) - p[0]*math.Sin(rad),
p[1],
p[2]*math.Sin(rad) + p[0]*math.Cos(rad),
}
out[0] = r[0] + b[0]
out[1] = r[1] + b[1]
out[2] = r[2] + b[2]
return out
}
// Vec3RotateZ rotate a 3D vector around the z-axis
func Vec3RotateZ(out, a, b []float64, rad float64) []float64 {
p := []float64{
a[0] - b[0],
a[1] - b[1],
a[2] - b[2],
}
r := []float64{
p[0]*math.Cos(rad) - p[1]*math.Sin(rad),
p[0]*math.Sin(rad) + p[1]*math.Cos(rad),
p[2],
}
out[0] = r[0] + b[0]
out[1] = r[1] + b[1]
out[2] = r[2] + b[2]
return out
}
// Vec3Angle get the angle between two 2D vectors
func Vec3Angle(a, b []float64) float64 {
ax := a[0]
ay := a[1]
az := a[2]
bx := b[0]
by := b[1]
bz := b[2]
mag1 := math.Sqrt(ax*ax + ay*ay + az*az)
mag2 := math.Sqrt(bx*bx + by*by + bz*bz)
mag := mag1 * mag2
cosine := mag
if cosine != 0 {
cosine = Vec3Dot(a, b) / mag
}
return math.Acos(math.Min(math.Max(cosine, -1), 1))
}
// Vec3Zero set the components of a Vec3 to zero
func Vec3Zero(out []float64) []float64 {
out[0] = 0.
out[1] = 0.
out[2] = 0.
return out
}
// Vec3Str returns a string representation of a vector
func Vec3Str(out []float64) string {
return fmt.Sprintf("vec3(%v, %v, %v)", out[0], out[1], out[2])
}
// Vec3ExactEquals returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
func Vec3ExactEquals(a, b []float64) bool {
return a[0] == b[0] && a[1] == b[1] && a[2] == b[2]
}
// Vec3Equals returns whether or not the vectors have approximately the same elements in the same position.
func Vec3Equals(a, b []float64) bool {
return equals(a[0], b[0]) && equals(a[1], b[1]) && equals(a[2], b[2])
}
// Vec3Len alias for Vec3Length
var Vec3Len = Vec3Length
// Vec3Sub alias for Vec3Subtract
var Vec3Sub = Vec3Subtract
// Vec3Mul alias for Vec3Multiply
var Vec3Mul = Vec3Multiply
// Vec3Div alias for Vec3Divide
var Vec3Div = Vec3Divide
// Vec3Dist alias for Vec3Distance
var Vec3Dist = Vec3Distance
// Vec3SqrDist alias for Vec3SquaredDistance
var Vec3SqrDist = Vec3SquaredDistance
// Vec3SqrLen alias for Vec3SquaredLength
var Vec3SqrLen = Vec3SquaredLength
// Vec3ForEach perform some operation over an array of Vec3s.
func Vec3ForEach(a []float64, stride, offset, count int, fn func([]float64, []float64, []float64), arg []float64) []float64 {
if stride <= 0 {
stride = 3
}
if offset <= 0 {
offset = 0
}
var l int
if 0 < count {
l = int(math.Min(float64(count*stride+offset), float64(len(a))))
} else {
l = len(a)
}
for i := offset; i < l; i += stride {
vec := []float64{a[i], a[i+1], a[i+2]}
fn(vec, vec, arg)
a[i] = vec[0]
a[i+1] = vec[1]
a[i+2] = vec[2]
}
return a
} | vec3.go | 0.878053 | 0.649224 | vec3.go | starcoder |
Package schwift is a client library for OpenStack Swift
(https://github.com/openstack/swift, https://openstack.org).
Authentication with Gophercloud
Schwift does not implement authentication (neither Keystone nor Swift v1), but
can be plugged into any library that does. The most common choice is
Gophercloud (https://github.com/gophercloud/gophercloud).
When using Gophercloud, you usually start by obtaining a
gophercloud.ServiceClient for Swift like so:
import (
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/utils/openstack/clientconfig"
)
//option 1: build a gophercloud.AuthOptions instance yourself
provider, err := openstack.AuthenticatedClient(authOptions)
client, err := openstack.NewObjectStorageV1(provider, gophercloud.EndpointOpts{})
//option 2: have Gophercloud read the standard OS_* environment variables
provider, err := clientConfig.AuthenticatedClient(nil)
client, err := openstack.NewObjectStorageV1(provider, gophercloud.EndpointOpts{})
//option 3: if you're using Swift's builtin authentication instead of Keystone
provider, err := openstack.NewClient("http://swift.example.com:8080")
client, err := swauth.NewObjectStorageV1(provider, swauth.AuthOpts {
User: "project:user",
Key: "password",
})
Then, in all these cases, you use gopherschwift to convert the
gophercloud.ServiceClient into a schwift.Account instance, from which point you
have access to all of schwift's API:
import "github.com/majewsky/schwift/gopherschwift"
account, err := gopherschwift.Wrap(client)
For example, to download an object's contents into a string:
text, err := account.Container("foo").Object("bar.txt").Download(nil).AsString()
Authentication with a different OpenStack library
If you use a different Go library to handle Keystone/Swift authentication, take
the client object that it provides and wrap it into something that implements
the schwift.Backend interface. Then use schwift.InitializeAccount() to obtain a
schwift.Account.
Caching
When a GET or HEAD request is sent by an Account, Container or Object instance,
the headers associated with that thing will be stored in that instance and not
retrieved again.
obj := account.Container("foo").Object("bar")
hdr, err := obj.Headers() //sends HTTP request "HEAD <storage-url>/foo/bar"
...
hdr, err = obj.Headers() //returns cached values immediately
If this behavior is not desired, the Invalidate() method can be used to clear
caches on any Account, Container or Object instance. Some methods that modify
the instance on the server call Invalidate() automatically, e.g. Object.Upload(),
Update() or Delete(). This will be indicated in the method's documentation.
Error handling
When a method on an Account, Container or Object instance makes a HTTP request
to Swift and Swift returns an unexpected status code, a
schwift.UnexpectedStatusCodeError will be returned. Schwift provides the
convenience function Is() to check the status code of these errors to detect
common failure situations:
obj := account.Container("foo").Object("bar")
err := obj.Upload(bytes.NewReader(data), nil)
if schwift.Is(err, http.StatusRequestEntityTooLarge) {
log.Print("quota exceeded for container foo!")
} else if err != nil {
log.Fatal("unexpected error: " + err.Error())
}
The documentation for a method may indicate certain common error conditions
that can be detected this way by stating that "This method fails with
http.StatusXXX if ...". Because of the wide variety of failure modes in Swift,
this information is not guaranteed to be exhaustive.
*/
package schwift | vendor/github.com/majewsky/schwift/doc.go | 0.733738 | 0.432003 | doc.go | starcoder |
package graph
import (
"errors"
)
//Graph represents a graph
type Graph struct {
isDirected bool
nodes map[*Node]bool
}
//SetDirection to the graph
func (g *Graph) SetDirection(directed bool) error {
if g.nodes != nil && len(g.nodes) != 0 {
return errors.New("Direction cannot be set, nodes already exist")
}
g.isDirected = directed
return nil
}
//Nodes of the graph
func (g *Graph) Nodes() []*Node {
nodes := make([]*Node, len(g.nodes))
i := 0
for n := range g.nodes {
nodes[i] = n
i++
}
return nodes
}
//AddNode to the graph
func (g *Graph) AddNode(n *Node) {
if g.nodes == nil {
g.nodes = make(map[*Node]bool)
}
if _, isInGraph := g.nodes[n]; isInGraph {
return
}
n.graph = g
g.nodes[n] = false
}
//AddEdgeDefaultWeight from node a to node b, and vise versa if the graph is undirected with default weight 1
func (g *Graph) AddEdgeDefaultWeight(a, b *Node) error {
return g.addEdge(a, b, 1)
}
//AddEdge from node a to node b, and vise versa if the graph is undirected with weight
func (g *Graph) AddEdge(a, b *Node, w float64) error {
return g.addEdge(a, b, w)
}
func (g *Graph) addEdge(a, b *Node, w float64) error {
if e := a.addEdge(b, w); e != nil {
return e
}
if !g.isDirected {
if e := b.addEdge(a, w); e != nil {
return e
}
}
return nil
}
//RemoveEdge from node a to node b, and vise versa if the graph is undirected
func (g *Graph) RemoveEdge(a, b *Node) error {
if e := a.removeEdge(b); e != nil {
return e
}
if !g.isDirected {
if e := b.removeEdge(a); e != nil {
return e
}
}
return nil
}
//IsConnected if for every pair of nodes, there is a path between them
func (g *Graph) IsConnected() bool {
if !g.isDirected {
for n := range g.nodes {
if !n.HasEdges() {
return false
}
}
return true
}
for n := range g.nodes {
if len(n.bfs()) == len(g.nodes) {
return true
}
}
return false
}
//Distance of the path from node a to node b
func (g *Graph) Distance(a, b *Node) int {
if d, reached := a.bfs()[b]; reached {
return d
}
return -1
} | graph/graph.go | 0.716119 | 0.405743 | graph.go | starcoder |
package rule
const (
tipA = `-A, --append chain rule-specification
Append one or more rules to the end of the selected chain. When the source and/or destination names resolve to more than one address, a
rule will be added for each possible address combination.
-4, --ipv4
This option has no effect in iptables and iptables-restore. If a rule using the -4 option is inserted with (and only with) ip6tables-
restore, it will be silently ignored. Any other uses will throw an error. This option allows to put both IPv4 and IPv6 rules in a single
rule file for use with both iptables-restore and ip6tables-restore.`
tip6 = `-6, --ipv6
If a rule using the -6 option is inserted with (and only with) iptables-restore, it will be silently ignored. Any other uses will throw an
error. This option allows to put both IPv4 and IPv6 rules in a single rule file for use with both iptables-restore and ip6tables-restore.
This option has no effect in ip6tables and ip6tables-restore.`
tipp = `[!] -p, --protocol protocol
The protocol of the rule or of the packet to check. The specified protocol can be one of tcp, udp, udplite, icmp, icmpv6,esp, ah, sctp, mh
or the special keyword "all", or it can be a numeric value, representing one of these protocols or a different one. A protocol name from
/etc/protocols is also allowed. A "!" argument before the protocol inverts the test. The number zero is equivalent to all. "all" will
match with all protocols and is taken as default when this option is omitted. Note that, in ip6tables, IPv6 extension headers except esp
are not allowed. esp and ipv6-nonext can be used with Kernel version 2.6.11 or later. The number zero is equivalent to all, which means
that you cannot test the protocol field for the value 0 directly. To match on a HBH header, even if it were the last, you cannot use -p 0,
but always need -m hbh.`
tips = `[!] -s, --source address[/mask][,...]
Source specification. Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address. Hostnames
will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote
query such as DNS is a really bad idea. The mask can be either an ipv4 network mask (for iptables) or a plain number, specifying the number
of 1's at the left side of the network mask. Thus, an iptables mask of 24 is equivalent to 255.255.255.0. A "!" argument before the
address specification inverts the sense of the address. The flag --src is an alias for this option. Multiple addresses can be specified,
but this will expand to multiple rules (when adding with -A), or will cause multiple rules to be deleted (with -D).`
tipd = `[!] -d, --destination address[/mask][,...]
Destination specification. See the description of the -s (source) flag for a detailed description of the syntax. The flag --dst is an
alias for this option.`
tipm = `-m, --match match
Specifies a match to use, that is, an extension module that tests for a specific property. The set of matches make up the condition under
which a target is invoked. Matches are evaluated first to last as specified on the command line and work in short-circuit fashion, i.e. if
one extension yields false, evaluation will stop.`
tipj = `-j, --jump target
This specifies the target of the rule; i.e., what to do if the packet matches it. The target can be a user-defined chain (other than the
one this rule is in), one of the special builtin targets which decide the fate of the packet immediately, or an extension (see EXTENSIONS
below). If this option is omitted in a rule (and -g is not used), then matching the rule will have no effect on the packet's fate, but the
counters on the rule will be incremented.`
tipg = `-g, --goto chain
This specifies that the processing should continue in a user specified chain. Unlike the --jump option return will not continue processing
in this chain but instead in the chain that called us via --jump.`
tipi = `[!] -i, --in-interface name
Name of an interface via which a packet was received (only for packets entering the INPUT, FORWARD and PREROUTING chains). When the "!"
argument is used before the interface name, the sense is inverted. If the interface name ends in a "+", then any interface which begins
with this name will match. If this option is omitted, any interface name will match.`
tipo = `[!] -o, --out-interface name
Name of an interface via which a packet is going to be sent (for packets entering the FORWARD, OUTPUT and POSTROUTING chains). When the "!"
argument is used before the interface name, the sense is inverted. If the interface name ends in a "+", then any interface which begins
with this name will match. If this option is omitted, any interface name will match.`
tipf = `[!] -f, --fragment
This means that the rule only refers to second and further IPv4 fragments of fragmented packets. Since there is no way to tell the source
or destination ports of such a packet (or ICMP type), such a packet will not match any rules which specify them. When the "!" argument preβ
cedes the "-f" flag, the rule will only match head fragments, or unfragmented packets. This option is IPv4 specific, it is not available in
ip6tables.`
tipc = `-c, --set-counters packets bytes
This enables the administrator to initialize the packet and byte counters of a rule (during INSERT, APPEND, REPLACE operations).`
)
var tooltip = map[string]string{
"A": tipA, "append": tipA,
"6": tip6, "ipv6": tip6,
"p": tipp, "protocol": tipp,
"s": tips, "source": tips,
"d": tipd, "destination": tipd,
"m": tipm, "match": tipm,
"j": tipj, "jump": tipj,
"g": tipg, "goto": tipg,
"i": tipi, "ininterface": tipi,
"o": tipo, "outinterface": tipo,
"f": tipf, "fragment": tipf,
"c": tipc, "setcounters": tipc,
} | rule/tooltip.go | 0.637821 | 0.543348 | tooltip.go | starcoder |
package missing_build_infrastructure
import (
"github.com/threagile/threagile/model"
)
func Category() model.RiskCategory {
return model.RiskCategory{
Id: "missing-build-infrastructure",
Title: "Missing Build Infrastructure",
Description: "The modeled architecture does not contain a build infrastructure (devops-client, sourcecode-repo, build-pipeline, etc.), " +
"which might be the risk of a model missing critical assets (and thus not seeing their risks). " +
"If the architecture contains custom-developed parts, the pipeline where code gets developed " +
"and built needs to be part of the model.",
Impact: "If this risk is unmitigated, attackers might be able to exploit risks unseen in this threat model due to " +
"critical build infrastructure components missing in the model.",
ASVS: "V1 - Architecture, Design and Threat Modeling Requirements",
CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html",
Action: "Build Pipeline Hardening",
Mitigation: "Include the build infrastructure in the model.",
Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?",
Function: model.Architecture,
STRIDE: model.Tampering,
DetectionLogic: "Models with in-scope custom-developed parts missing in-scope development (code creation) and build infrastructure " +
"components (devops-client, sourcecode-repo, build-pipeline, etc.).",
RiskAssessment: "The risk rating depends on the highest sensitivity of the in-scope assets running custom-developed parts.",
FalsePositives: "Models not having any custom-developed parts " +
"can be considered as false positives after individual review.",
ModelFailurePossibleReason: true,
CWE: 1127,
}
}
func SupportedTags() []string {
return []string{}
}
func GenerateRisks() []model.Risk {
risks := make([]model.Risk, 0)
hasCustomDevelopedParts, hasBuildPipeline, hasSourcecodeRepo, hasDevOpsClient := false, false, false, false
impact := model.LowImpact
var mostRelevantAsset model.TechnicalAsset
for _, id := range model.SortedTechnicalAssetIDs() { // use the sorted one to always get the same tech asset with highest sensitivity as example asset
technicalAsset := model.ParsedModelRoot.TechnicalAssets[id]
if technicalAsset.CustomDevelopedParts && !technicalAsset.OutOfScope {
hasCustomDevelopedParts = true
if impact == model.LowImpact {
mostRelevantAsset = technicalAsset
if technicalAsset.HighestConfidentiality() >= model.Restricted ||
technicalAsset.HighestIntegrity() >= model.Critical ||
technicalAsset.HighestAvailability() >= model.Critical {
impact = model.MediumImpact
}
}
if technicalAsset.Confidentiality >= model.Restricted ||
technicalAsset.Integrity >= model.Critical ||
technicalAsset.Availability >= model.Critical {
impact = model.MediumImpact
}
// just for referencing the most interesting asset
if technicalAsset.HighestSensitivityScore() > mostRelevantAsset.HighestSensitivityScore() {
mostRelevantAsset = technicalAsset
}
}
if technicalAsset.Technology == model.BuildPipeline {
hasBuildPipeline = true
}
if technicalAsset.Technology == model.SourcecodeRepository {
hasSourcecodeRepo = true
}
if technicalAsset.Technology == model.DevOpsClient {
hasDevOpsClient = true
}
}
hasBuildInfrastructure := hasBuildPipeline && hasSourcecodeRepo && hasDevOpsClient
if hasCustomDevelopedParts && !hasBuildInfrastructure {
risks = append(risks, createRisk(mostRelevantAsset, impact))
}
return risks
}
func createRisk(technicalAsset model.TechnicalAsset, impact model.RiskExploitationImpact) model.Risk {
title := "<b>Missing Build Infrastructure</b> in the threat model (referencing asset <b>" + technicalAsset.Title + "</b> as an example)"
risk := model.Risk{
Category: Category(),
Severity: model.CalculateSeverity(model.Unlikely, impact),
ExploitationLikelihood: model.Unlikely,
ExploitationImpact: impact,
Title: title,
MostRelevantTechnicalAssetId: technicalAsset.Id,
DataBreachProbability: model.Improbable,
DataBreachTechnicalAssetIDs: []string{},
}
risk.SyntheticId = risk.Category.Id + "@" + technicalAsset.Id
return risk
} | risks/built-in/missing-build-infrastructure/missing-build-infrastructure-rule.go | 0.642881 | 0.427158 | missing-build-infrastructure-rule.go | starcoder |
package canvas
import (
"image/color"
"math"
"github.com/jesseduffield/fyne"
)
// Declare conformity with CanvasObject interface
var _ fyne.CanvasObject = (*Line)(nil)
// Line describes a colored line primitive in a Fyne canvas.
// Lines are special as they can have a negative width or height to indicate
// an inverse slope (i.e. slope up vs down).
type Line struct {
Position1 fyne.Position // The current top-left position of the Line
Position2 fyne.Position // The current bottomright position of the Line
Hidden bool // Is this Line currently hidden
StrokeColor color.Color // The line stroke color
StrokeWidth float32 // The stroke width of the line
}
// Size returns the current size of bounding box for this line object
func (l *Line) Size() fyne.Size {
return fyne.NewSize(int(math.Abs(float64(l.Position2.X)-float64(l.Position1.X))),
int(math.Abs(float64(l.Position2.Y)-float64(l.Position1.Y))))
}
// Resize sets a new bottom-right position for the line object
func (l *Line) Resize(size fyne.Size) {
l.Position2 = fyne.NewPos(l.Position1.X+size.Width, l.Position1.Y+size.Height)
}
// Position gets the current top-left position of this line object, relative to its parent / canvas
func (l *Line) Position() fyne.Position {
return fyne.NewPos(fyne.Min(l.Position1.X, l.Position2.X), fyne.Min(l.Position1.Y, l.Position2.Y))
}
// Move the line object to a new position, relative to its parent / canvas
func (l *Line) Move(pos fyne.Position) {
size := l.Size()
l.Position1 = pos
l.Position2 = fyne.NewPos(l.Position1.X+size.Width, l.Position1.Y+size.Height)
}
// MinSize for a Line simply returns Size{1, 1} as there is no
// explicit content
func (l *Line) MinSize() fyne.Size {
return fyne.NewSize(1, 1)
}
// Visible returns true if this line// Show will set this circle to be visible is visible, false otherwise
func (l *Line) Visible() bool {
return !l.Hidden
}
// Show will set this line to be visible
func (l *Line) Show() {
l.Hidden = false
l.Refresh()
}
// Hide will set this line to not be visible
func (l *Line) Hide() {
l.Hidden = true
l.Refresh()
}
// Refresh causes this object to be redrawn in it's current state
func (l *Line) Refresh() {
Refresh(l)
}
// NewLine returns a new Line instance
func NewLine(color color.Color) *Line {
return &Line{
StrokeColor: color,
StrokeWidth: 1,
}
} | canvas/line.go | 0.830078 | 0.469885 | line.go | starcoder |
package bloom
import (
"math"
"github.com/andy2046/bitmap"
)
type (
bloomFilterBit struct {
bitmap *bitmap.Bitmap // bloom filter bitmap
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
}
)
// NewB creates standard bloom filter based on the provided m/k.
// m is the size of bloom filter bits.
// k is the number of hash functions.
func NewB(m, k uint64) Bloom {
mm, exponent := adjustM(m)
return &bloomFilterBit{
bitmap: bitmap.New(mm),
m: mm - 1, // x % 2^i = x & (2^i - 1)
k: k,
shift: 64 - exponent,
}
}
// NewBGuess estimates m/k based on the provided n/p then creates standard bloom filter.
// n is the estimated number of elements in the bloom filter.
// p is the false positive probability.
func NewBGuess(n uint64, p float64) Bloom {
m, k := Guess(n, p)
return NewB(m, k)
}
func (bf *bloomFilterBit) Add(entry []byte) {
hash := sipHash(entry)
h := hash >> bf.shift
l := hash << bf.shift >> bf.shift
for i := uint64(0); i < bf.k; i++ {
bf.bitmap.SetBit((h+i*l)&bf.m, true)
}
bf.n++
}
func (bf *bloomFilterBit) AddString(entry string) {
bf.Add([]byte(entry))
}
func (bf *bloomFilterBit) Exist(entry []byte) bool {
hash := sipHash(entry)
h := hash >> bf.shift
l := hash << bf.shift >> bf.shift
for i := uint64(0); i < bf.k; i++ {
if !bf.bitmap.GetBit((h + i*l) & bf.m) {
return false
}
}
return true
}
func (bf *bloomFilterBit) ExistString(entry string) bool {
return bf.Exist([]byte(entry))
}
func (bf *bloomFilterBit) FalsePositive() float64 {
return math.Pow((1 - math.Exp(-float64(bf.k*bf.n)/float64(bf.m))),
float64(bf.k))
}
func (bf *bloomFilterBit) GuessFalsePositive(n uint64) float64 {
return math.Pow((1 - math.Exp(-float64(bf.k*n)/float64(bf.m))),
float64(bf.k))
}
func (bf *bloomFilterBit) M() uint64 {
return bf.m + 1
}
func (bf *bloomFilterBit) K() uint64 {
return bf.k
}
func (bf *bloomFilterBit) N() uint64 {
return bf.n
}
func (bf *bloomFilterBit) Clear() {
s := bf.bitmap.Size()
for i := uint64(0); i < s; i++ {
bf.bitmap.SetBit(i, false)
}
bf.n = 0
}
func (bf *bloomFilterBit) estimatedFillRatio() float64 {
return 1 - math.Exp(-float64(bf.n)/math.Ceil(float64(bf.m)/float64(bf.k)))
} | pkg/bloom/bloombit.go | 0.732879 | 0.568775 | bloombit.go | starcoder |
package iso20022
// Specifies periods.
type CorporateActionPeriod2 struct {
// Period during which the assented line is available.
AssentedLinePeriod *Period1 `xml:"AssntdLinePrd,omitempty"`
// Period during which the specified option, or all options of the event, remains valid, eg, offer period.
ActionPeriod *Period1 `xml:"ActnPrd,omitempty"`
// Period during which the privilege is not available, eg, this can happen whenever a meeting takes place or whenever a coupon payment is due.
PrivilegeSuspensionPeriod *Period1 `xml:"PrvlgSspnsnPrd,omitempty"`
// Period during which both old and new equity may be traded simultaneously, eg, consolidation of equity or splitting of equity.
ParallelTradingPeriod *Period1 `xml:"ParllTradgPrd,omitempty"`
// Period (last day included) during which an account owner can surrender or sell securities to the issuer and receive the sale proceeds.
SellThruIssuerPeriod *Period1 `xml:"SellThruIssrPrd,omitempty"`
// Period during which the shareholder can revoke, change or withdraw its instruction.
RevocabilityPeriod *Period1 `xml:"RvcbltyPrd,omitempty"`
// Period during which the price of a security is determined (for outturn securities).
PriceCalculationPeriod *Period1 `xml:"PricClctnPrd,omitempty"`
}
func (c *CorporateActionPeriod2) AddAssentedLinePeriod() *Period1 {
c.AssentedLinePeriod = new(Period1)
return c.AssentedLinePeriod
}
func (c *CorporateActionPeriod2) AddActionPeriod() *Period1 {
c.ActionPeriod = new(Period1)
return c.ActionPeriod
}
func (c *CorporateActionPeriod2) AddPrivilegeSuspensionPeriod() *Period1 {
c.PrivilegeSuspensionPeriod = new(Period1)
return c.PrivilegeSuspensionPeriod
}
func (c *CorporateActionPeriod2) AddParallelTradingPeriod() *Period1 {
c.ParallelTradingPeriod = new(Period1)
return c.ParallelTradingPeriod
}
func (c *CorporateActionPeriod2) AddSellThruIssuerPeriod() *Period1 {
c.SellThruIssuerPeriod = new(Period1)
return c.SellThruIssuerPeriod
}
func (c *CorporateActionPeriod2) AddRevocabilityPeriod() *Period1 {
c.RevocabilityPeriod = new(Period1)
return c.RevocabilityPeriod
}
func (c *CorporateActionPeriod2) AddPriceCalculationPeriod() *Period1 {
c.PriceCalculationPeriod = new(Period1)
return c.PriceCalculationPeriod
} | CorporateActionPeriod2.go | 0.843766 | 0.422862 | CorporateActionPeriod2.go | starcoder |
package main
// importing fmt package
import (
"fmt"
)
// add method
func add(matrix1 [2][2]int, matrix2 [2][2]int) [2][2]int {
var m int
var l int
var sum [2][2]int
for l = 0; l < 2; l++ {
for m = 0; m < 2; m++ {
sum[l][m] = matrix1[l][m] + matrix2[l][m]
}
}
return sum
}
// subtract method
func subtract(matrix1 [2][2]int, matrix2 [2][2]int) [2][2]int {
var m int
var l int
var difference [2][2]int
for l = 0; l < 2; l++ {
for m = 0; m < 2; m++ {
difference[l][m] = matrix1[l][m] - matrix2[l][m]
}
}
return difference
}
// multiply method
func multiply(matrix1 [2][2]int, matrix2 [2][2]int) [2][2]int {
var m int
var l int
var n int
var product [2][2]int
for l = 0; l < 2; l++ {
for m = 0; m < 2; m++ {
var productSum int = 0
for n = 0; n < 2; n++ {
productSum = productSum + matrix1[l][n]*matrix2[n][m]
}
product[l][m] = productSum
}
}
return product
}
// transpose method
func transpose(matrix1 [2][2]int) [2][2]int {
var m int
var l int
var transMatrix [2][2]int
for l = 0; l < 2; l++ {
for m = 0; m < 2; m++ {
transMatrix[l][m] = matrix1[m][l]
}
}
return transMatrix
}
// determinant method
func determinant(matrix1 [2][2]int) float64 {
var det float64
det = det + float64(((matrix1[0][0] * matrix1[1][1]) - (matrix1[0][1] * matrix1[1][0])))
return det
}
// inverse method
func inverse(matrix [2][2]int) [][]float64 {
var det float64
det = determinant(matrix)
var invmatrix float64
invmatrix[0][0] = matrix[1][1] / det
invmatrix[0][1] = -1 * matrix[0][1] / det
invmatrix[1][0] = -1 * matrix[1][0] / det
invmatrix[1][1] = matrix[0][0] / det
return invmatrix
}
//main method
func main() {
var matrix1 = [2][2]int{
{4, 5},
{1, 2}}
var matrix2 = [2][2]int{
{6, 7},
{3, 4}}
var sum [2][2]int
sum = add(matrix1, matrix2)
fmt.Println(sum)
var difference [2][2]int
difference = subtract(matrix1, matrix2)
fmt.Println(difference)
var product [2][2]int
product = multiply(matrix1, matrix2)
fmt.Println(product)
} | Chapter05/twodmatrix.go | 0.553988 | 0.425187 | twodmatrix.go | starcoder |
package grid
import "github.com/xwjdsh/2048-ai/utils"
type Direction int
const (
UP Direction = iota
RIGHT
DOWN
LEFT
NONE
)
type Grid struct {
Data [4][4]int `json:"data"`
}
func (g *Grid) Clone() *Grid {
gridClone := &Grid{}
*gridClone = *g
return gridClone
}
func (g *Grid) Max() int {
max := 0
for _, row := range g.Data {
for _, value := range row {
if value > max {
max = value
}
}
}
return max
}
func (g *Grid) VacantPoints() []utils.Point {
points := []utils.Point{}
for x, row := range g.Data {
for y, value := range row {
if value == 0 {
points = append(points, utils.Point{X: x, Y: y})
}
}
}
return points
}
func (g *Grid) Move(d Direction) bool {
originData := g.Data
data := &g.Data
switch d {
case UP:
for y := 0; y < 4; y++ {
for x := 0; x < 3; x++ {
for nx := x + 1; nx <= 3; nx++ {
if data[nx][y] > 0 {
if data[x][y] <= 0 {
data[x][y] = data[nx][y]
data[nx][y] = 0
x -= 1
} else if data[x][y] == data[nx][y] {
data[x][y] += data[nx][y]
data[nx][y] = 0
}
break
}
}
}
}
case DOWN:
for y := 0; y < 4; y++ {
for x := 3; x > 0; x-- {
for nx := x - 1; nx >= 0; nx-- {
if data[nx][y] > 0 {
if data[x][y] <= 0 {
data[x][y] = data[nx][y]
data[nx][y] = 0
x += 1
} else if data[x][y] == data[nx][y] {
data[x][y] += data[nx][y]
data[nx][y] = 0
}
break
}
}
}
}
case LEFT:
for x := 0; x < 4; x++ {
for y := 0; y < 3; y++ {
for ny := y + 1; ny <= 3; ny++ {
if data[x][ny] > 0 {
if data[x][y] <= 0 {
data[x][y] = data[x][ny]
data[x][ny] = 0
y -= 1
} else if data[x][y] == data[x][ny] {
data[x][y] += data[x][ny]
data[x][ny] = 0
}
break
}
}
}
}
case RIGHT:
for x := 0; x < 4; x++ {
for y := 3; y > 0; y-- {
for ny := y - 1; ny >= 0; ny-- {
if data[x][ny] > 0 {
if data[x][y] <= 0 {
data[x][y] = data[x][ny]
data[x][ny] = 0
y += 1
} else if data[x][y] == data[x][ny] {
data[x][y] += data[x][ny]
data[x][ny] = 0
}
break
}
}
}
}
}
return utils.Diff(*data, originData)
} | grid/grid.go | 0.5 | 0.454048 | grid.go | starcoder |
package elements
import (
. "github.com/drbrain/go-unicornify/unicornify/core"
. "github.com/drbrain/go-unicornify/unicornify/rendering"
"math"
)
type Bone struct {
Balls [2]*Ball
XFunc, YFunc func(float64) float64 // may be nil
}
func NewBone(b1, b2 *Ball) *Bone {
return NewNonLinBone(b1, b2, nil, nil)
}
func NewShadedBone(b1, b2 *Ball, shading float64) *Bone {
return NewShadedNonLinBone(b1, b2, nil, nil, shading)
}
const defaultShading = 0.25
func NewNonLinBone(b1, b2 *Ball, xFunc, yFunc func(float64) float64) *Bone {
return NewShadedNonLinBone(b1, b2, xFunc, yFunc, defaultShading)
}
func NewShadedNonLinBone(b1, b2 *Ball, xFunc, yFunc func(float64) float64, shading float64) *Bone {
return &Bone{[2]*Ball{b1, b2}, xFunc, yFunc}
}
func reverse(f func(float64) float64) func(float64) float64 {
return func(v float64) float64 {
return 1 - f(1-v)
}
}
func (b *Bone) GetTracer(wv WorldView) Tracer {
b1 := b.Balls[0]
b2 := b.Balls[1]
proj1 := ProjectBall(wv, b1)
proj2 := ProjectBall(wv, b2)
if b.XFunc == nil && b.YFunc == nil {
return NewBoneTracer(proj1, proj2)
} else {
c1 := b1.Color
c2 := b2.Color
v := b2.Center.Minus(b1.Center)
length := v.Length()
vx, vy := CrossAxes(v.Times(1 / length))
parts := 255
calcBall := func(factor float64) BallProjection {
col := MixColors(c1, c2, factor)
fx, fy := factor, factor
if f := b.XFunc; f != nil {
fx = f(fx)
}
if f := b.YFunc; f != nil {
fy = f(fy)
}
c := b1.Center.Plus(v.Times(factor)).Plus(vx.Times((fx - factor) * length)).Plus(vy.Times((fy - factor) * length))
r := MixFloats(b1.Radius, b2.Radius, factor)
ballp := ProjectBall(wv, NewBallP(c, r, col))
return ballp
}
prevBall := proj1
result := NewGroupTracer()
nextBall := calcBall(1 / float64(parts))
for i := 1; i <= parts; i++ {
curBall := nextBall
if i < parts {
nextBall = calcBall(float64(i+1) / float64(parts))
seg1 := curBall.BaseBall.Center.Minus(prevBall.BaseBall.Center)
seg2 := nextBall.BaseBall.Center.Minus(curBall.BaseBall.Center)
if seg1.ScalarProd(seg2)/(seg1.Length()*seg2.Length()) > 0.999848 { // cosine of 1Β°
continue
}
}
tracer := NewBoneTracer(prevBall, curBall)
result.Add(tracer)
prevBall = curBall
}
return result
}
}
type BoneTracer struct {
w1, w2, w3, a1, a2, a3, ra, dr float64
c2, c4, c6, c8, c9, c11, c14, c2i float64
b1, b2 BallProjection
bounds Bounds
}
func (t *BoneTracer) GetBounds() Bounds {
return t.bounds
}
func (t *BoneTracer) Trace(x, y float64, ray Vector) (bool, float64, Vector, Color) {
return t.traceImpl(x, y, ray, false)
}
func (t *BoneTracer) traceImpl(x, y float64, ray Vector, backside bool) (bool, float64, Vector, Color) {
v1, v2, v3 := ray.Decompose()
c3 := -2 * (v1*t.w1 + v2*t.w2 + v3*t.w3)
c5 := -2 * (v1*t.a1 + v2*t.a2 + v3*t.a3)
var z, f float64
if t.c2 == 0 {
if t.dr > 0 {
f = 1
} else {
f = 0
}
} else {
c7 := c3 * t.c2i
c10 := c5 * t.c2i
c12i := 1 / (Sqr(c7)/4 - t.c9)
c13 := c7*t.c8/2 - c10
pz := c13 * c12i
qz := t.c14 * c12i
discz := Sqr(pz)/4 - qz
if discz < 0 {
return false, 0, NoDirection, Color{}
}
rdiscz := math.Sqrt(discz)
z1 := -pz/2 + rdiscz
z2 := -pz/2 - rdiscz
f1 := -(c3*z1 + t.c4) / (2 * t.c2)
f2 := -(c3*z2 + t.c4) / (2 * t.c2)
g1 := t.ra+f1*t.dr >= 0
g2 := t.ra+f2*t.dr >= 0
if !g1 {
z1, f1 = z2, f2
if t.dr > 0 {
f2 = 1
} else {
f2 = 0
}
}
if !g2 {
z2, f2 = z1, f1
if t.dr > 0 {
f1 = 1
} else {
f1 = 0
}
}
if backside {
z = z1
f = f1
} else {
z = z2
f = f2
}
}
if f <= 0 || f >= 1 {
f = math.Min(1, math.Max(0, f))
pz := c3*f + c5
qz := t.c2*Sqr(f) + t.c4*f + t.c6
discz := Sqr(pz)/4 - qz
if discz < 0 {
f = 1 - f
pz = c3*f + c5
qz = t.c2*Sqr(f) + t.c4*f + t.c6
discz = Sqr(pz)/4 - qz
if discz < 0 {
return false, 0, NoDirection, Color{}
}
}
if backside {
z = -pz/2 + math.Sqrt(discz)
} else {
z = -pz/2 - math.Sqrt(discz)
}
}
m1 := t.a1 + f*t.w1
m2 := t.a2 + f*t.w2
m3 := t.a3 + f*t.w3
p := Vector{v1, v2, v3}.Times(z)
dir := p.Minus(Vector{m1, m2, m3})
return true, z, dir, MixColors(t.b1.BaseBall.Color, t.b2.BaseBall.Color, f)
}
func (t *BoneTracer) TraceDeep(x, y float64, ray Vector) (bool, TraceIntervals) {
ok1, z1, dir1, col1 := t.traceImpl(x, y, ray, false)
ok2, z2, dir2, col2 := t.traceImpl(x, y, ray, true)
if ok1 {
if !ok2 { // this can happen because of rounding errors
return false, TraceIntervals{}
}
return true, TraceIntervals{
TraceInterval{
Start: TraceResult{z1, dir1, col1},
End: TraceResult{z2, dir2, col2},
},
}
}
return false, TraceIntervals{}
}
func (t *BoneTracer) Pruned(rp RenderingParameters) Tracer {
return SimplyPruned(t, rp)
}
func NewBoneTracer(b1, b2 BallProjection) *BoneTracer {
t := &BoneTracer{b1: b1, b2: b2}
cx1, cy1, cz1, r1 := b1.CenterCS.X(), b1.CenterCS.Y(), b1.CenterCS.Z(), b1.BaseBall.Radius
cx2, cy2, cz2, r2 := b2.CenterCS.X(), b2.CenterCS.Y(), b2.CenterCS.Z(), b2.BaseBall.Radius
t.bounds = RenderingBoundsForBalls(b1, b2)
t.w1 = float64(cx2 - cx1)
t.w2 = float64(cy2 - cy1)
t.w3 = float64(cz2 - cz1)
t.a1 = float64(cx1)
t.a2 = float64(cy1)
t.a3 = float64(cz1)
t.ra = float64(r1)
t.dr = float64(r2 - r1)
t.c2 = -Sqr(t.dr) + Sqr(t.w1) + Sqr(t.w2) + Sqr(t.w3)
if t.c2 != 0 {
t.c2i = 1 / t.c2
}
t.c4 = -2*t.ra*t.dr + 2*(t.a1*t.w1+t.a2*t.w2+t.a3*t.w3)
t.c6 = -Sqr(t.ra) + Sqr(t.a1) + Sqr(t.a2) + Sqr(t.a3)
t.c8 = t.c4 / t.c2
t.c9 = 1 / t.c2
t.c11 = t.c6 / t.c2
t.c14 = Sqr(t.c8)/4 - t.c11
return t
} | unicornify/elements/bone.go | 0.666822 | 0.419826 | bone.go | starcoder |
package flags
import (
"fmt"
"strconv"
)
// BoolValue represents a boolean argument value.
type BoolValue bool
// NewBoolValue creates a new BoolValue.
func NewBoolValue(init bool) *BoolValue {
p := new(bool)
*p = init
return (*BoolValue)(p)
}
// Set will attempt to convert the given string to a value.
func (p *BoolValue) Set(s string) error {
v, err := strconv.ParseBool(s)
if err != nil {
return fmt.Errorf("`%s` cannot be interpreted as %T", s, v)
}
*p = BoolValue(v)
return nil
}
// String satisfies the fmt.Stringer interface.
func (p BoolValue) String() string {
return strconv.FormatBool(bool(p))
}
// IntValue represents a integer argument value.
type IntValue int
// NewIntValue creates a new IntValue.
func NewIntValue(init int) *IntValue {
p := new(int)
*p = init
return (*IntValue)(p)
}
// Set will attempt to convert the given string to a value.
func (p *IntValue) Set(s string) error {
v, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("`%s` cannot be interpreted as %T", s, v)
}
*p = IntValue(v)
return nil
}
// String satisfies the fmt.Stringer interface.
func (p IntValue) String() string {
return strconv.Itoa(int(p))
}
// FloatValue represents a float argument value.
type FloatValue float64
// NewFloatValue creates a new FloatValue.
func NewFloatValue(init float64) *FloatValue {
p := new(float64)
*p = init
return (*FloatValue)(p)
}
// Set will attempt to convert the given string to a value.
func (p *FloatValue) Set(s string) error {
v, err := strconv.ParseFloat(s, 64)
if err != nil {
return fmt.Errorf("`%s` cannot be interpreted as %T", s, v)
}
*p = FloatValue(v)
return nil
}
// String satisfies the fmt.Stringer interface.
func (p FloatValue) String() string {
return strconv.FormatFloat(float64(p), 'g', -1, 64)
}
// StringValue represents a string argument value.
type StringValue string
// NewStringValue creates a new StringValue.
func NewStringValue(init string) *StringValue {
p := new(string)
*p = init
return (*StringValue)(p)
}
// Set will attempt to convert the given string to a value.
func (p *StringValue) Set(s string) error {
*p = StringValue(s)
return nil
}
// String satisfies the fmt.Stringer interface.
func (p StringValue) String() string {
return string(p)
}
// IntSliceValue represents a variable number int argument value.
type IntSliceValue []int
// NewIntSliceValue creates a new IntSliceValue.
func NewIntSliceValue(init []int) *IntSliceValue {
p := new([]int)
*p = init
return (*IntSliceValue)(p)
}
// Len will return the length of the slice value.
func (p IntSliceValue) Len() int { return len(p) }
// Set will attempt to convert and append the given string to the slice.
func (p *IntSliceValue) Set(s string) error {
ii := []int(*p)
v, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("`%s` cannot be interpreted as %T", s, p)
}
ii = append(ii, v)
*p = IntSliceValue(ii)
return nil
}
// String satisfies the fmt.Stringer interface.
func (p IntSliceValue) String() string {
return fmt.Sprintf("%v", []int(p))
}
// FloatSliceValue represents a variable number float argument value.
type FloatSliceValue []float64
// NewFloatSliceValue creates a new FloatSliceValue.
func NewFloatSliceValue(init []float64) *FloatSliceValue {
p := new([]float64)
*p = init
return (*FloatSliceValue)(p)
}
// Len will return the length of the slice value.
func (p FloatSliceValue) Len() int { return len(p) }
// Set will attempt to convert and append the given string to the slice.
func (p *FloatSliceValue) Set(s string) error {
ff := []float64(*p)
v, err := strconv.ParseFloat(s, 64)
if err != nil {
return fmt.Errorf("`%s` cannot be interpreted as %T", s, v)
}
ff = append(ff, v)
*p = FloatSliceValue(ff)
return nil
}
// String satisfies the fmt.Stringer interface.
func (p FloatSliceValue) String() string {
return fmt.Sprintf("%v", []float64(p))
}
// StringSliceValue represents a variable number string argument value.
type StringSliceValue []string
// NewStringSliceValue creates a new StringSliceValue.
func NewStringSliceValue(init []string) *StringSliceValue {
p := new([]string)
*p = init
return (*StringSliceValue)(p)
}
// Len will return the length of the slice value.
func (p StringSliceValue) Len() int { return len(p) }
// Set will attempt to convert and append the given string to the slice.
func (p *StringSliceValue) Set(s string) error {
ss := []string(*p)
ss = append(ss, s)
*p = StringSliceValue(ss)
return nil
}
// String satisfies the fmt.Stringer interface.
func (p StringSliceValue) String() string {
return fmt.Sprintf("%v", []string(p))
} | values.go | 0.786213 | 0.422266 | values.go | starcoder |
package freejson
import (
"github.com/nanwanwang/stardust/encodingx/jsonx"
"time"
)
type Array []interface{}
func (a Array) Len() int {
return len(a)
}
func (a Array) Has(index int) bool {
return index >= 0 && index < len(a)
}
func (a Array) Each(f func(index int, v interface{})) {
for i, v := range a {
f(i, v)
}
}
func (a Array) EachIndex(f func(index int)) {
for i, _ := range a {
f(i)
}
}
func (a Array) EachElem(f func(v interface{})) {
for _, v := range a {
f(v)
}
}
func (a Array) Filter(result Array, pred func(v interface{}) bool) Array {
if result == nil {
result = make(Array, 0, 4)
}
for _, v := range a {
if pred(v) {
result = append(result, v)
}
}
return result
}
func (a Array) FieldType(index int) ValueType {
if a == nil {
return NoField
}
if !a.Has(index) {
return NoField
}
return TypeOf(a[index])
}
func (a Array) IntfAt(index int, def interface{}) interface{} {
if !a.Has(index) {
return def
}
return a[index]
}
func (a Array) StrAt(index int, def string) string {
return ToStr(a.IntfAt(index, nil), def)
}
func (a Array) AsStrAt(index int, def string) string {
return AsStr(a.IntfAt(index, nil), def)
}
func (a Array) BoolAt(index int, def bool) bool {
return ToBool(a.IntfAt(index, nil), def)
}
func (a Array) IntAt(index, def int) int {
return ToInt(a.IntfAt(index, nil), def)
}
func (a Array) Int64At(index int, def int64) int64 {
return ToInt64(a.IntfAt(index, nil), def)
}
func (a Array) Float64At(index int, def float64) float64 {
return ToFloat64(a.IntfAt(index, nil), def)
}
func (a Array) ObjectAt(index int, def Object) Object {
return ToObject(a.IntfAt(index, nil), def)
}
func (a Array) ArrayAt(index int, def Array) Array {
return ToArray(a.IntfAt(index, nil), def)
}
func (a Array) AsArrayAt(index int, def Array) Array {
return AsArray(a.IntfAt(index, nil), def)
}
func (a Array) AsStringArrayAt(index int, def []string) []string {
return AsStringArray(a.IntfAt(index, nil), def)
}
func (a Array) TimeAt(index int, def time.Time) time.Time {
return ToTime(a.IntfAt(index, nil), def)
}
func (a Array) AsTimeAt(index int, def time.Time) time.Time {
return AsTime(a.IntfAt(index, nil), def)
}
func (a Array) Set(index int, v interface{}) {
if a == nil {
return
}
a[index] = v
}
func (a Array) Clear() Array {
if a == nil {
return nil
}
return Array(a[:0])
}
func (a Array) Add(vs ...interface{}) Array {
return Array(append(a, vs...))
}
func (a Array) RemoveIf(pred func(index int, v interface{}) bool) Array {
if a == nil {
return nil
}
a1 := make(Array, 0, len(a))
for i, v := range a {
if pred(i, v) {
a1 = append(a1, v)
}
}
return a1
}
func (a Array) String() string {
return jsonx.MarshalIndentString(a, "")
} | encodingx/jsonx/freejson/array.go | 0.63114 | 0.440289 | array.go | starcoder |
package math
import "math"
type Vector4 struct {
X float64
Y float64
Z float64
W float64
}
func NewVector4( x, y, z float64) *Vector4 {
v := &Vector4{ X:x, Y:y , Z:z, W:1 }
return v
}
func (v *Vector4) Set( x, y, z, w float64 ) *Vector4 {
v.X = x
v.Y = y
v.Z = z
v.W = w
return v
}
func (v *Vector4) SetScalar( scalar float64 ) *Vector4 {
v.X = scalar
v.Y = scalar
v.Z = scalar
v.W = scalar
return v
}
func (v *Vector4) SetX( x float64 ) *Vector4 {
v.X = x
return v
}
func (v *Vector4) SetY( y float64 ) *Vector4 {
v.Y = y
return v
}
func (v *Vector4) SetZ( z float64 ) *Vector4 {
v.Z = z
return v
}
func (v *Vector4) SetW( w float64 ) *Vector4 {
v.W = w
return v
}
func (v *Vector4) SetComponent( index int, value float64) {
switch index {
case 0:
v.X = value
case 1:
v.Y = value
case 2:
v.Z = value
case 3:
v.W = value
}
}
func (v *Vector4) GetComponent( index int, value float64 ) float64 {
switch index {
case 0:
return v.X
case 1:
return v.Y
case 2:
return v.Z
case 3:
return v.W
}
return 0
}
func (v *Vector4) Clone() *Vector4 {
v1 := &Vector4{ X:v.X, Y:v.Y, Z:v.Z, W:v.W }
return v1
}
func (v *Vector4) Copy( other *Vector4 ) *Vector4 {
v.X = other.X
v.Y = other.Y
v.Z = other.Z
v.W = other.W
return v
}
func (v *Vector4) Add( other *Vector4 ) *Vector4 {
v.X += other.X
v.Y += other.Y
v.Z += other.Z
v.W += other.W
return v
}
func (v *Vector4) AddScalar( scalar float64 ) *Vector4 {
v.X += scalar
v.Y += scalar
v.Z += scalar
v.W += scalar
return v
}
func (v *Vector4) AddVectors( a, b Vector4) *Vector4 {
v.X = a.X + b.X
v.Y = a.Y + b.Y
v.Z = a.Z + b.Z
v.W = a.W + b.W
return v
}
func (v *Vector4) AddScaledVector( other Vector4, s float64 ) *Vector4 {
v.X += other.X * s
v.Y += other.Y * s
v.Z += other.Z * s
v.W += other.W * s
return v
}
func (v *Vector4) Sub( other *Vector4 ) *Vector4 {
v.X -= other.X
v.Y -= other.Y
v.Z -= other.Z
v.W -= other.W
return v
}
func (v *Vector4) SubScalar( scalar float64 ) *Vector4 {
v.X -= scalar
v.Y -= scalar
v.Z -= scalar
v.W -= scalar
return v
}
func (v *Vector4) SubVectors( a, b *Vector4) *Vector4 {
v.X = a.X - b.X
v.Y = a.Y - b.Y
v.Z = a.Z - b.Z
v.W = a.W - b.W
return v
}
func (v *Vector4) MultiplyScalar( scalar float64 ) *Vector4 {
v.X *= scalar
v.Y *= scalar
v.Z *= scalar
v.W *= scalar
return v
}
func (v *Vector4) ApplyMatrix4() {
// TODO After Matrix4
}
func (v *Vector4) DivideScalar( scalar float64 ) *Vector4 {
v.X /= scalar
v.Y /= scalar
v.Z /= scalar
v.W /= scalar
return v
}
func (v *Vector4) SetAxisAngleFromQuaternion() {
// TODO After Quaternion
}
func (v *Vector4) SetAxisAngleFromRotationMatrix() {
// TODO After Matrix
}
func (v *Vector4) Min( other *Vector4 ) *Vector4 {
v.X = math.Min( v.X, other.X )
v.Y = math.Min( v.Y, other.Y )
v.Z = math.Min( v.Z, other.Z )
v.W = math.Min( v.W, other.W )
return v
}
func (v *Vector4) Max( other *Vector4) *Vector4 {
v.X = math.Max( v.X, other.X )
v.Y = math.Max( v.Y, other.Y )
v.Z = math.Max( v.Z, other.Z )
v.W = math.Max( v.W, other.W )
return v
}
func (v *Vector4) Clamp( min, max *Vector4 ) *Vector4 {
v.X = math.Max( min.X, math.Min( max.X, v.X) )
v.Y = math.Max( min.Y, math.Min( max.Y, v.Y) )
v.Z = math.Max( min.Z, math.Min( max.Z, v.Z) )
v.W = math.Max( min.W, math.Min( max.W, v.W) )
return v
}
func (v *Vector4) ClampScalar( minVal, maxVal float64) *Vector4 {
min := &Vector4{ X:minVal, Y:minVal, Z:minVal, W:minVal }
max := &Vector4{ X:maxVal, Y:maxVal, Z:maxVal, W:maxVal }
return v.Clamp( min, max)
}
func (v *Vector4) Floor() *Vector4 {
v.X = math.Floor( v.X )
v.Y = math.Floor( v.Y )
v.Z = math.Floor( v.Z )
v.W = math.Floor( v.W )
return v
}
func (v *Vector4) Ceil() *Vector4 {
v.X = math.Ceil( v.X )
v.Y = math.Ceil( v.Y )
v.Z = math.Ceil( v.Z )
v.W = math.Ceil( v.W )
return v
}
func (v *Vector4) Round() *Vector4 {
v.X = math.Floor( v.X + .5 )
v.Y = math.Floor( v.Y + .5 )
v.Z = math.Floor( v.Z + .5 )
v.W = math.Floor( v.W + .5 )
return v
}
func (v *Vector4) RoundToZero() *Vector4 {
if v.X < 0 {
v.X = math.Ceil( v.X )
} else {
v.X = math.Floor( v.X )
}
if v.Y < 0 {
v.Y = math.Ceil( v.Y )
} else {
v.Y = math.Floor( v.Y )
}
if v.Z < 0 {
v.Z = math.Ceil( v.Z )
} else {
v.Z = math.Floor( v.Z )
}
if v.W < 0 {
v.W = math.Ceil( v.W )
} else {
v.W = math.Floor( v.W )
}
return v
}
func (v *Vector4) Negate() *Vector4 {
v.X = -v.X
v.Y = -v.Y
v.Z = -v.Z
v.W = -v.W
return v
}
func (v *Vector4) Dot( other *Vector4 ) float64 {
return v.X * other.X + v.Y * other.Y + v.Z * other.Z + v.W * other.W
}
func (v *Vector4) LengthSq() float64 {
return v.X * v.X + v.Y * v.Y + v.Z * v.Z + v.W * v.W
}
func (v *Vector4) Length() float64 {
return math.Sqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z + v.W * v.W)
}
func (v *Vector4) LengthManhattan() float64 {
return math.Abs( v.X ) + math.Abs( v.Y ) + math.Abs( v.Z ) + math.Abs( v.W )
}
func (v *Vector4) Normalize() *Vector4 {
return v.DivideScalar( v.Length() )
}
func (v *Vector4) SetLength( length float64 ) *Vector4 {
orgLength := v.Length()
v.MultiplyScalar( length )
v.DivideScalar( orgLength )
return v
}
func (v *Vector4) Lerp( other *Vector4, alpha float64 ) *Vector4 {
v.X += ( other.X - v.X ) * alpha
v.Y += ( other.Y - v.Y ) * alpha
v.Z += ( other.Z - v.Z ) * alpha
v.W += ( other.W - v.W ) * alpha
return v
}
func (v *Vector4) LerpVectors( v1, v2 *Vector4, alpha float64) *Vector4 {
return v.SubVectors(v2,v1).MultiplyScalar( alpha ).Add( v1 )
}
func (v *Vector4) Equals( other *Vector4 ) bool {
return ( (v.X == other.X) && (v.Y == other.Y) && (v.Z == other.Z) && (v.W == other.W) )
}
func (v *Vector4) FromArray( array []float64 ) *Vector4 {
v.X = array[0]
v.Y = array[1]
v.Z = array[2]
v.W = array[3]
return v
}
func (v *Vector4) ToArray( array []float64) []float64 {
array[0] = v.X
array[1] = v.Y
array[2] = v.Z
array[3] = v.W
return array
}
func (v *Vector4) FromAttribute() {
// TODO After Attribute
} | math/vector4.go | 0.782787 | 0.706553 | vector4.go | starcoder |
package leader
import (
"math"
)
/*
A zero-indexed array A consisting of N integers is given. The dominator of array A is
the value that occurs in more than half of the elements of A.
For example, consider array A such that
A[0] = 3 A[1] = 4 A[2] = 3
A[3] = 2 A[4] = 3 A[5] = -1
A[6] = 3 A[7] = 3
The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those
with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.
Write a function
func Solution(A []int) int
that, given a zero-indexed array A consisting of N integers, returns index of any element of
array A in which the dominator of A occurs. The function should return β1 if array A does not have a dominator.
Assume that:
N is an integer within the range [0..100,000];
each element of array A is an integer within the range [β2,147,483,648..2,147,483,647].
For example, given array A such that
A[0] = 3 A[1] = 4 A[2] = 3
A[3] = 2 A[4] = 3 A[5] = -1
A[6] = 3 A[7] = 3
the function may return 0, 2, 4, 6 or 7, as explained above.
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
*/
func FindIndex(limit int, predicate func(i int) bool) int {
for i := 0; i < limit; i++ {
if predicate(i) {
return i
}
}
return -1
}
func Dominator(A []int) int {
// O(N)
arrayLen := len(A)
if arrayLen == 1 {
return 0
}
l := NewIntStack(arrayLen)
candidate := -1
leader := -1
count := 0
for _, value := range (A) {
//O(n)
if l.size == 0 {
l.Push(value)
} else {
if value != l.Front() {
l.Pop()
} else {
l.Push(value)
}
}
}
if l.size > 0 {
candidate = l.Front()
} else {
return -1
}
for _, value := range (A) {
if value == candidate {
count += 1
}
}
if count > int(math.Floor(float64(arrayLen) / 2.0)) {
leader = candidate
} else {
return -1
}
return FindIndex(arrayLen, func(i int) bool { return A[i] == leader })
} | leader/Dominator.go | 0.744006 | 0.72911 | Dominator.go | starcoder |
package day20
import (
"fmt"
"io"
"math"
)
const MaxTicks = 1000
type Coord struct {
X, Y, Z int
}
type Particle struct {
Position, Velocity, Acceleration Coord
Destroyed bool
}
func (p *Particle) Tick() {
p.Velocity.X += p.Acceleration.X
p.Velocity.Y += p.Acceleration.Y
p.Velocity.Z += p.Acceleration.Z
p.Position.X += p.Velocity.X
p.Position.Y += p.Velocity.Y
p.Position.Z += p.Velocity.Z
}
func (p Particle) Distance() float64 {
return math.Abs(float64(p.Position.X)) +
math.Abs(float64(p.Position.Y)) +
math.Abs(float64(p.Position.Z))
}
func Parse(input io.Reader) ([]Particle, error) {
var particles []Particle
for {
var particle Particle
_, err := fmt.Fscanf(input, "p=<%d,%d,%d>, v=<%d,%d,%d>, a=<%d,%d,%d>\n",
&particle.Position.X,
&particle.Position.Y,
&particle.Position.Z,
&particle.Velocity.X,
&particle.Velocity.Y,
&particle.Velocity.Z,
&particle.Acceleration.X,
&particle.Acceleration.Y,
&particle.Acceleration.Z,
)
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
if err != nil {
return []Particle{}, err
}
particles = append(particles, particle)
}
return particles, nil
}
type Score struct {
Index int
Value float64
Found bool
}
func Nearest(particles []Particle) int {
score := Score{}
for i := 0; i < len(particles); i++ {
if particles[i].Destroyed {
continue
}
if dist := particles[i].Distance(); dist < score.Value || !score.Found {
score.Index = i
score.Value = dist
score.Found = true
}
}
return score.Index
}
func Part1(input io.Reader) (int, error) {
particles, err := Parse(input)
if err != nil {
return -1, err
}
for tick := 0; tick < MaxTicks; tick++ {
for i := 0; i < len(particles); i++ {
particles[i].Tick()
}
}
return Nearest(particles), nil
}
func Part2(input io.Reader) (int, error) {
particles, err := Parse(input)
if err != nil {
return -1, err
}
for tick := 0; tick < MaxTicks; tick++ {
positions := map[Coord]*Particle{}
for i := 0; i < len(particles); i++ {
if particles[i].Destroyed {
continue
}
particles[i].Tick()
position := particles[i].Position
if existing, collided := positions[position]; collided {
existing.Destroyed = true
particles[i].Destroyed = true
} else {
positions[position] = &particles[i]
}
}
}
var notDestroyed int
for i := 0; i < len(particles); i++ {
if !particles[i].Destroyed {
notDestroyed++
}
}
return notDestroyed, nil
} | 2017/day20/day20.go | 0.627267 | 0.491334 | day20.go | starcoder |
package game
import "github.com/nsf/termbox-go"
// Direction is the type that reppresents the current direction of the snake
type Direction uint8
// UP means that the snake is going up
// RIGHT means that the snake is going right
// DOWN means that the snake is going down
// LEFT means that the snake is going left
const (
UP Direction = 0
RIGHT Direction = 1
DOWN Direction = 2
LEFT Direction = 3
)
// Snake contains all the snake information
type Snake struct {
Direction Direction
Length int
Positions []Coordinates
}
// Move is the function that moves a snake
func (s *Snake) Move(deleteTail bool, options Options) bool {
previousPosition := Coordinates{
X: s.Positions[0].X,
Y: s.Positions[0].Y,
}
termbox.SetCell(s.Positions[0].X, s.Positions[0].Y, rune('β’'), termbox.ColorGreen, termbox.ColorDefault)
// Delete tail
if deleteTail {
termbox.SetCell(s.Positions[s.Length-1].X, s.Positions[s.Length-1].Y, rune(' '), termbox.ColorGreen, termbox.ColorDefault)
}
crushedAgainstWall := false
// Move head
switch s.Direction {
case UP:
s.Positions[0].Y--
if s.Positions[0].Y == 0 {
if options.PacmanEffect {
s.Positions[0].Y = termHeight - 2
} else {
crushedAgainstWall = true
}
}
termbox.SetCell(s.Positions[0].X, s.Positions[0].Y, rune('β΄'), termbox.ColorGreen, termbox.ColorDefault)
case DOWN:
s.Positions[0].Y++
if s.Positions[0].Y == termHeight-1 {
if options.PacmanEffect {
s.Positions[0].Y = 1
} else {
crushedAgainstWall = true
}
}
termbox.SetCell(s.Positions[0].X, s.Positions[0].Y, rune('βΎ'), termbox.ColorGreen, termbox.ColorDefault)
case LEFT:
s.Positions[0].X--
if s.Positions[0].X == 0 {
if options.PacmanEffect {
s.Positions[0].X = termWidth - 2
} else {
crushedAgainstWall = true
}
}
termbox.SetCell(s.Positions[0].X, s.Positions[0].Y, rune('β'), termbox.ColorGreen, termbox.ColorDefault)
case RIGHT:
s.Positions[0].X++
if s.Positions[0].X == termWidth-1 {
if options.PacmanEffect {
s.Positions[0].X = 1
} else {
crushedAgainstWall = true
}
}
termbox.SetCell(s.Positions[0].X, s.Positions[0].Y, rune('βΈ'), termbox.ColorGreen, termbox.ColorDefault)
}
termbox.Flush()
if crushedAgainstWall {
return false
}
// Update coordinates
length := s.Length
if deleteTail {
length--
}
for i := 1; i < s.Length; i++ {
partCurrentPosition := Coordinates{
X: s.Positions[i].X,
Y: s.Positions[i].Y,
}
s.Positions[i].X = previousPosition.X
s.Positions[i].Y = previousPosition.Y
previousPosition.X = partCurrentPosition.X
previousPosition.Y = partCurrentPosition.Y
if s.Positions[0].X == s.Positions[i].X && s.Positions[0].Y == s.Positions[i].Y {
return false
}
}
return true
}
// Grow is the functions that makes the snake growing
func (s *Snake) Grow() {
x := s.Positions[s.Length-1].X
y := s.Positions[s.Length-1].Y
s.Positions = append(s.Positions, Coordinates{X: x, Y: y})
s.Length++
termbox.Flush()
}
// Init initializes the snake's head
func (s *Snake) Init() {
s.Length = 1
s.Positions = append(s.Positions, Coordinates{X: termWidth / 2, Y: termHeight / 2})
termbox.SetCell(s.Positions[0].X, s.Positions[0].Y, rune('β’'), termbox.ColorGreen, termbox.ColorDefault)
termbox.Flush()
} | game/player.go | 0.530966 | 0.433502 | player.go | starcoder |
package main
import (
"fmt"
"strconv"
"time"
)
func main() {
start := time.Now()
one, two := CheckPasswords(254032, 789860)
end := time.Since(start)
fmt.Printf("[PART ONE] passwords that meet criteria: %d\n", one)
fmt.Printf("[PART TWO] passwords that meet criteria: %d\n", two)
fmt.Printf("took %s\n", end)
}
// CheckPasswords checks for each password in the given range of passwords whether they meet both sets of criteria.
// For both criteria, it returns the number of passwords that meet them.
func CheckPasswords(start int, end int) (a int, b int) {
for i := start; i < end; i++ {
if PasswordMeetsCriteria(i) {
a++
}
if PasswordMeetsCriteria2(i) {
b++
}
}
return a, b
}
// PasswordMeetsCriteria checks the given password for the following criteria:
// - Must have exactly 6 digits
// - Must have two adjacent digits that are the same
// - Going from left to right, the digits never decrease
func PasswordMeetsCriteria(password int) bool {
digits := toDigits(password)
if len(digits) != 6 {
return false
}
if !isAscending(digits) {
return false
}
return anyMatch(countDigits(digits), func(k, v int) bool {
return v >= 2
})
}
// PasswordMeetsCriteria2 checks the given password for the following criteria:
// - Must have exactly 6 digits
// - Must have a group of exactly two adjacent digits that are the same
// - Going from left to right, the digits never decrease
func PasswordMeetsCriteria2(password int) bool {
digits := toDigits(password)
if len(digits) != 6 {
return false
}
if !isAscending(digits) {
return false
}
return anyMatch(countDigits(digits), func(k, v int) bool {
return v == 2
})
}
// toDigits converts the given password to a list of digits.
// Example: 12345 => [1, 2, 3, 4, 5]
func toDigits(password int) []int {
str := strconv.Itoa(password)
digits := make([]int, len(str))
for i := range str {
digits[i], _ = strconv.Atoi(string(str[i]))
}
return digits
}
// isAscending checks if the given list of digits never descends.
func isAscending(digits []int) bool {
for i := 1; i < len(digits); i++ {
if digits[i-1] > digits[i] {
return false
}
}
return true
}
// countDigits counts occurrences of each digit the given list, and returns a map of digits and their respective counts.
func countDigits(digits []int) map[int]int {
count := make(map[int]int)
for _, d := range digits {
count[d]++
}
return count
}
// anyMatch checks each key-value pair of the given map and returns true if any of them match the given predicate. If none match, it returns false.
func anyMatch(count map[int]int, pred func(k, v int) bool) bool {
for k, v := range count {
if pred(k, v) {
return true
}
}
return false
} | 2019/go/04/main.go | 0.764012 | 0.448487 | main.go | starcoder |
package hre
import (
"fmt"
"regexp/syntax"
"strings"
)
var (
// ^^
reLeftEdge = re(`\^+`)
// $$
reRightEdge = re(`\$+`)
// {...}
// βββ΄β (1)
reZeroWidth = re(`
--- open brace
\{
--- inside of brace
( [^}]+ )
--- close brace
\}
`)
// {...}$$
// β β ββ΄β (2)
// βββ΄β (1)
reLookahead = re(`
--- zero-width
(?:
\{
( [^}]+ )
\}
)?
--- right-edge
( \$* )
--- end of string
$
`)
// ^^{...}
// ββ βββ΄β (2)
// ββ΄β (1)
reLookbehind = re(`
--- start of string
^
--- left-edge
( \^* )
--- zero-width
(?:
\{
( [^}]+ )
\}
)?
`)
)
func expandLookaround(expr string) (string, string, string, int, int, error) {
posExpr, negAExpr, negAWidth := expandLookahead(expr)
posExpr, negBExpr, negBWidth := expandLookbehind(posExpr)
err := mustNoZeroWidth(posExpr)
if err != nil {
return ``, ``, ``, 0, 0, err
}
return posExpr, negAExpr, negBExpr, negAWidth, negBWidth, nil
}
func dissolveLookaround(
format string,
lookExpr string,
hasEdge bool,
) (string, string, int, bool) {
// No Lookaround
if lookExpr == `` {
return ``, ``, 0, true
}
// Negative Lookaround
isNeg := strings.HasPrefix(lookExpr, `~`)
if isNeg {
var (
negExpr string
negWidth int
)
if !hasEdge {
negExpr = fmt.Sprintf(format, lookExpr[1:])
re, err := syntax.Parse(negExpr, syntax.Perl)
if err != nil {
return ``, ``, 0, false
}
negWidth = RegexpMaxWidth(re)
}
return ``, negExpr, negWidth, true
}
// Positive Lookaround
if hasEdge {
// Positive lookaround with edge has a paradox.
// It wouldn't match on anything.
return ``, ``, 0, false
}
return lookExpr, ``, 0, true
}
// Lookahead: {...} on the right-side.
// negExpr should be passed from expandLookbehind.
func expandLookahead(expr string) (string, string, int) {
// han{gul}$
// β β ββ edge
// β ββ look
// ββ other
posExpr := expr
// This pattern always matches.
m := reLookahead.FindStringSubmatchIndex(posExpr)
start := m[0]
otherExpr := posExpr[:start]
edgeExpr := captured(posExpr, m, 2)
lookExpr := captured(posExpr, m, 1)
// Don't allow capturing groups in zero-width matches.
edgeExpr = noCapture(edgeExpr)
lookExpr = noCapture(lookExpr)
// Dissolve lookahead.
lookExpr, negAExpr, negAWidth, ok :=
dissolveLookaround(`^(%s)`, lookExpr, edgeExpr != ``)
if !ok {
return `.^^`, ``, 0
}
// Replace lookahead with 2 parentheses:
// han(gul)($)
posExpr = fmt.Sprintf(`%s(%s)(%s)`, otherExpr, lookExpr, edgeExpr)
return posExpr, negAExpr, negAWidth
}
// Lookbehind: {...} on the left-side.
func expandLookbehind(expr string) (string, string, int) {
// ^{han}gul
// β β ββ other
// β ββ look
// ββ edge
posExpr := expr
// This pattern always matches.
m := reLookbehind.FindStringSubmatchIndex(posExpr)
stop := m[1]
otherExpr := posExpr[stop:]
edgeExpr := captured(posExpr, m, 1)
lookExpr := captured(posExpr, m, 2)
// Don't allow capturing groups in zero-width matches.
edgeExpr = noCapture(edgeExpr)
lookExpr = noCapture(lookExpr)
// Dissolve lookbehind.
lookExpr, negBExpr, negBWidth, ok :=
dissolveLookaround(`(%s)$`, lookExpr, edgeExpr != ``)
if !ok {
return `.^^`, ``, 0
}
// Replace lookbehind with 2 parentheses:
// (^)(han)gul
posExpr = fmt.Sprintf(`(%s)(%s)%s`, edgeExpr, lookExpr, otherExpr)
return posExpr, negBExpr, negBWidth
}
func mustNoZeroWidth(expr string) error {
if reZeroWidth.MatchString(expr) {
return fmt.Errorf("zero-width group found in middle: %#v", expr)
}
return nil
}
func expandEdges(expr string) string {
expr = reLeftEdge.ReplaceAllStringFunc(expr, func(e string) string {
if e == `^` {
// "{}" is a zero-width space which is injected by an RPattern.
return `(?:^|\s+|{})`
}
// ^^...
return `^`
})
expr = reRightEdge.ReplaceAllStringFunc(expr, func(e string) string {
if e == `$` {
// "{}" is a zero-width space which is injected by an RPattern.
return `(?:$|\s+|{})`
}
// $$...
return `$`
})
return expr
} | assertions.go | 0.530723 | 0.49707 | assertions.go | starcoder |
package jsonlogic
func opEqual(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
if isNumeric(leftValue) && isNumeric(rightValue) {
return interfaceToFloat(leftValue) == interfaceToFloat(rightValue), nil
}
return leftValue == rightValue, nil
}
func opEqualStrict(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
return leftValue == rightValue, nil
}
func opNotEqual(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
if isNumeric(leftValue) && isNumeric(rightValue) {
return interfaceToFloat(leftValue) != interfaceToFloat(rightValue), nil
}
return leftValue != rightValue, nil
}
func opNotEqualStrict(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
return leftValue != rightValue, nil
}
func opSmallerThan(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
val := interfaceToFloat(leftValue)
secVal := interfaceToFloat(rightValue)
if len(valuearray) == 3 {
thirdValue, err := ApplyJSONInterfaces(valuearray[2], data)
if err != nil {
return nil, err
}
thirdVal := interfaceToFloat(thirdValue)
return (val < secVal) && (secVal < thirdVal), nil
}
return (val < secVal), nil
}
func opGreaterThan(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
val := interfaceToFloat(leftValue)
secVal := interfaceToFloat(rightValue)
if len(valuearray) == 3 {
thirdValue, err := ApplyJSONInterfaces(valuearray[2], data)
if err != nil {
return nil, err
}
thirdVal := interfaceToFloat(thirdValue)
return (val > secVal) && (secVal > thirdVal), nil
}
return (val > secVal), nil
}
func opSmallerEqThan(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
val := interfaceToFloat(leftValue)
secVal := interfaceToFloat(rightValue)
if len(valuearray) == 3 {
thirdValue, err := ApplyJSONInterfaces(valuearray[2], data)
if err != nil {
return nil, err
}
thirdVal := interfaceToFloat(thirdValue)
return (val <= secVal) && (secVal <= thirdVal), nil
}
return (val <= secVal), nil
}
func opGreaterEqThan(value interface{}, data interface{}) (interface{}, error) {
var leftValue, rightValue interface{}
var err error
var valuearray []interface{}
switch value.(type) {
case []interface{}:
valuearray = value.([]interface{})
case interface{}:
leftValue = value
}
if len(valuearray) > 0 {
leftValue, err = ApplyJSONInterfaces(valuearray[0], data)
if err != nil {
return nil, err
}
if len(valuearray) > 1 {
rightValue, err = ApplyJSONInterfaces(valuearray[1], data)
if err != nil {
return nil, err
}
}
}
val := interfaceToFloat(leftValue)
secVal := interfaceToFloat(rightValue)
if len(valuearray) == 3 {
thirdValue, err := ApplyJSONInterfaces(valuearray[2], data)
if err != nil {
return nil, err
}
thirdVal := interfaceToFloat(thirdValue)
return (val >= secVal) && (secVal >= thirdVal), nil
}
return (val >= secVal), nil
} | op_compare.go | 0.521715 | 0.47098 | op_compare.go | starcoder |
package main
import (
"fmt"
"math"
)
type Shape interface {
Perimeter() float64
}
type Circle struct {
radius float64
}
func (c Circle) Circumference() float64 {
return 2 * math.Pi * c.radius
}
func (c Circle) Perimeter() float64 {
return c.Circumference()
}
type ConvexPolygon interface {
NumSides() int
}
func NumDiagonals(poly ConvexPolygon) int {
return poly.NumSides() * (poly.NumSides() - 3) / 2
}
const Quad = 4
type Quadrilateral struct{}
func (Quadrilateral) NumSides() int {
return Quad
}
type Rectangle struct {
Quadrilateral
width, height float64
}
func (r Rectangle) Width() float64 {
return r.width
}
func (r Rectangle) Height() float64 {
return r.height
}
func (r Rectangle) Perimeter() float64 {
return (r.width + r.height) * 2
}
func (r Rectangle) Circumscribe() Circle {
return Circle{radius: math.Hypot(r.Width(), r.Height()) / 2}
}
type Equilateral interface {
NumSides() int
SideLength() float64
}
func Perimeter(this Equilateral) float64 {
return this.SideLength() * float64(this.NumSides())
}
type Square struct {
Rectangle
sideLength float64
}
func (sq Square) SideLength() float64 {
return sq.sideLength
}
func (sq Square) Width() float64 {
return sq.SideLength()
}
func (sq Square) Height() float64 {
return sq.SideLength()
}
func (sq Square) Perimeter() float64 {
return Perimeter(sq)
}
// Create a new square whose sides are exactly twice the length of this circle's radius.
func (c Circle) Inscribe() Square {
return Square{sideLength: c.radius * 2}
}
func main() {
round := Circle{radius: 1}
fmt.Println("The perimeter of a circle with unit radius is", round.Perimeter())
rect := Rectangle{width: 16, height: 9}
fmt.Println("The perimeter of a 16x9 rectangle is", rect.Perimeter())
box := Square{sideLength: 1}
fmt.Println("The perimeter of a unit square is", box.Perimeter())
fmt.Println("A square has", NumDiagonals(box), "diagonals.")
fmt.Println("The square that inscribes the unit circle has a perimeter of ",
round.Inscribe().Perimeter())
round = box.Circumscribe()
fmt.Println("The circle that circumscribes the unit square has a circumference of ",
round.Circumference())
round = rect.Circumscribe()
fmt.Println("The circle that circumscribes a 16x9 rectangle has a circumference of ",
round.Circumference())
} | Go/euclidean_geometry.go | 0.853104 | 0.50293 | euclidean_geometry.go | starcoder |
package main
import (
"math"
"os"
"github.com/EliCDavis/mango"
"github.com/EliCDavis/vector"
)
func Cylinder(
sides int,
height float64,
bottomRadius float64,
topRadius float64,
bottomOffset vector.Vector3,
topOffset vector.Vector3,
) mango.Mesh {
shaft := mango.BuildRing(sides, height, bottomRadius, topRadius, bottomOffset, topOffset)
top := mango.BuildRing(
sides,
0,
topRadius,
0,
bottomOffset.
Add(topOffset).
Add(vector.NewVector3(0, height, 0)),
vector.Vector3Zero(),
)
bottom := mango.BuildRing(
sides,
0,
0,
bottomRadius,
bottomOffset,
vector.Vector3Zero(),
)
return shaft.Add(top).Add(bottom)
}
func ThiccRing(
sides int,
height float64,
bottomRadius float64,
topRadius float64,
bottomOffset vector.Vector3,
topOffset vector.Vector3,
thickness float64,
) mango.Mesh {
shaft := mango.BuildRing(sides, height, bottomRadius, topRadius, bottomOffset, topOffset)
top := mango.BuildRing(
sides,
0,
topRadius,
topRadius-thickness,
bottomOffset.
Add(topOffset).
Add(vector.NewVector3(0, height, 0)),
vector.Vector3Zero(),
)
shaftDown := mango.BuildRing(
sides,
-height,
bottomRadius-thickness,
topRadius-thickness,
bottomOffset.Add(vector.Vector3Up().MultByConstant(height)),
topOffset,
)
return shaft.Add(top).Add(shaftDown)
}
func CakeTier(radiues, height float64, offset vector.Vector3) mango.Mesh {
thiccConst := .15
cakeSides := 30
plate := Cylinder(
cakeSides,
thiccConst,
radiues,
radiues,
vector.Vector3Up().MultByConstant(0).Add(offset),
vector.Vector3Zero(),
)
cake := Cylinder(
cakeSides,
height-thiccConst,
radiues-thiccConst,
radiues-thiccConst,
vector.Vector3Up().MultByConstant(thiccConst).Add(offset),
vector.Vector3Zero(),
)
icing := ThiccRing(
cakeSides,
thiccConst,
radiues-thiccConst-thiccConst,
radiues-thiccConst-thiccConst,
vector.Vector3Up().MultByConstant(height).Add(offset),
vector.Vector3Zero(),
thiccConst,
)
return plate.Add(cake).Add(icing)
}
func CakeColumn(radiues, height float64, numColumns int, offset vector.Vector3) mango.Mesh {
resultingColumns := mango.NewEmptyMesh()
columnSideConstant := 18
angle := (math.Pi * 2.0) / float64(numColumns)
for i := 0; i < numColumns; i++ {
resultingColumns = resultingColumns.Add(Cylinder(
columnSideConstant,
height,
.1,
.1,
offset.Add(vector.NewVector3(
math.Sin(angle*float64(i))*radiues,
0,
math.Cos(angle*float64(i))*radiues,
)),
vector.Vector3Zero(),
))
}
return resultingColumns
}
func main() {
bottomLayer := CakeTier(3.0, 1.0, vector.Vector3Zero())
bottomColumns := CakeColumn(1.7, .5, 6, vector.Vector3Up())
middleLayer := CakeTier(2.1, 1.0, vector.Vector3Up().MultByConstant(1.5))
middleColumns := CakeColumn(1, .5, 4, vector.Vector3Up().MultByConstant(2.5))
topLayer := CakeTier(1.4, 1.0, vector.Vector3Up().MultByConstant(3))
bottomLayer.
Add(bottomColumns).
Add(middleLayer).
Add(middleColumns).
Add(topLayer).
ToOBJ(os.Stdout)
} | cmd/cake1/main.go | 0.662141 | 0.481454 | main.go | starcoder |
package search
import (
"fmt"
"net/url"
"strings"
)
// ParseQuery provides an alternative to url.ParseQuery when the order of parameters must be retained. ParseQuery
// parses the URL-encoded query string and returns a URLQueryParameters object that can be used to get the ordered list
// of parameters, a map of the parameters, or parameters by name. ParseQuery always returns a non-nil
// URLQueryParameters object containing all the valid query parameters found; err describes the first decoding error
// encountered, if any.
func ParseQuery(query string) (u URLQueryParameters, err error) {
// Replace ";" with "&" so we can split on a single character
query = strings.Replace(query, ";", "&", -1)
// Split it into parts (e.g., "foo=bar" is a part)
parts := strings.Split(query, "&")
// iterate the parts and add them to the URLQueryParameters
for _, part := range parts {
if i := strings.Index(part, "="); i >= 0 {
key, value := part[:i], part[i+1:]
key, keyErr := url.QueryUnescape(key)
if keyErr != nil {
if err == nil {
err = keyErr
}
continue
}
value, valueErr := url.QueryUnescape(value)
if valueErr != nil {
if err == nil {
err = valueErr
}
continue
}
u.Add(key, value)
}
}
return
}
// URLQueryParameter represents a query parameter as a key/value pair.
type URLQueryParameter struct {
Key string
Value string
}
// URLQueryParameters represents an ordered list of query parameters that can be manipulated in several different ways.
type URLQueryParameters struct {
params []URLQueryParameter
}
// Add adds a key/value pair to the end of the list of URLQueryParameters. If the key already exists, the key/value is
// still added to the end of the list, as URLQueryParameters permite duplicate keys. To replace existing values, use
// Set instead.
func (u *URLQueryParameters) Add(Key string, value string) {
u.params = append(u.params, URLQueryParameter{Key: Key, Value: value})
}
// Set sets the value for the query parameter with the specified key. If a query parameter with the specified key
// already exists, it overwrites the existing value. If multiple query parameters with the specified key exist, it
// overwrites the value of the first matching query parameter and removes the remaining query parameters from the
// list. If no query parameters exist with the given key, the key/value pair are added as a new query parameter at
// the end of the list.
func (u *URLQueryParameters) Set(key string, value string) {
var dups []int
var found bool
for i := range u.params {
if u.params[i].Key == key {
if !found {
u.params[i].Value = value
found = true
} else {
dups = append(dups, i)
}
}
}
if !found {
u.Add(key, value)
} else {
for i := range dups {
j := dups[i] - i
u.params = append(u.params[:j], u.params[j+1:]...)
}
}
}
// Get returns the value of the first query parameter with the specified key. If no query parameters have the specified
// key, an empty string is returned.
func (u *URLQueryParameters) Get(key string) string {
for i := range u.params {
if u.params[i].Key == key {
return u.params[i].Value
}
}
return ""
}
// GetMulti returns a slice containing the values of all the query parameters with the specified key, in the order in which
// they were originally specified. If no query parameters have the specified key, an empty slice is returned.
func (u *URLQueryParameters) GetMulti(key string) []string {
var multi []string
for i := range u.params {
if u.params[i].Key == key {
multi = append(multi, u.params[i].Value)
}
}
return multi
}
// All returns a copy of the slice containing all of the URLQueryParameters in the original order.
func (u *URLQueryParameters) All() []URLQueryParameter {
all := make([]URLQueryParameter, len(u.params))
copy(all, u.params)
return all
}
// Values returns a map similar to the map that would be returned by url.ParseQuery(). The url.Values object does not
// guarantee that order is preserved. If order must be preserved, use on of the other functions.
func (u *URLQueryParameters) Values() url.Values {
values := url.Values{}
for _, param := range u.params {
values.Add(param.Key, param.Value)
}
return values
}
// Encode returns a URL-encoded string representing the query parameters in the original order.
func (u *URLQueryParameters) Encode() string {
if len(u.params) == 0 {
return ""
}
parts := make([]string, len(u.params))
for i, param := range u.params {
parts[i] = fmt.Sprintf("%s=%s", url.QueryEscape(param.Key), url.QueryEscape(param.Value))
}
return strings.Join(parts, "&")
} | search/url_query_parser.go | 0.700383 | 0.400661 | url_query_parser.go | starcoder |
package cview
import "github.com/gdamore/tcell/v2"
// Theme defines the colors used when primitives are initialized.
type Theme struct {
// Title, border and other lines
TitleColor tcell.Color // Box titles.
BorderColor tcell.Color // Box borders.
GraphicsColor tcell.Color // Graphics.
// Text
PrimaryTextColor tcell.Color // Primary text.
SecondaryTextColor tcell.Color // Secondary text (e.g. labels).
TertiaryTextColor tcell.Color // Tertiary text (e.g. subtitles, notes).
InverseTextColor tcell.Color // Text on primary-colored backgrounds.
ContrastPrimaryTextColor tcell.Color // Primary text for contrasting elements.
ContrastSecondaryTextColor tcell.Color // Secondary text on ContrastBackgroundColor-colored backgrounds.
// Background
PrimitiveBackgroundColor tcell.Color // Main background color for primitives.
ContrastBackgroundColor tcell.Color // Background color for contrasting elements.
MoreContrastBackgroundColor tcell.Color // Background color for even more contrasting elements.
// Button
ButtonCursorRune rune // The symbol to draw at the end of button labels when focused.
// Check box
CheckBoxCheckedRune rune
CheckBoxCursorRune rune // The symbol to draw within the checkbox when focused.
// Context menu
ContextMenuPaddingTop int
ContextMenuPaddingBottom int
ContextMenuPaddingLeft int
ContextMenuPaddingRight int
// Drop down
DropDownAbbreviationChars string // The chars to show when the option's text gets shortened.
DropDownSymbol rune // The symbol to draw at the end of the field when closed.
DropDownOpenSymbol rune // The symbol to draw at the end of the field when opened.
// Scroll bar
ScrollBarColor tcell.Color
// Window
WindowMinWidth int
WindowMinHeight int
}
// Styles defines the appearance of an application. The default is for a black
// background and some basic colors: black, white, yellow, green, cyan, and
// blue.
var Styles = Theme{
TitleColor: tcell.ColorWhite.TrueColor(),
BorderColor: tcell.ColorWhite.TrueColor(),
GraphicsColor: tcell.ColorWhite.TrueColor(),
PrimaryTextColor: tcell.ColorWhite.TrueColor(),
SecondaryTextColor: tcell.ColorYellow.TrueColor(),
TertiaryTextColor: tcell.ColorLimeGreen.TrueColor(),
InverseTextColor: tcell.ColorBlack.TrueColor(),
ContrastPrimaryTextColor: tcell.ColorBlack.TrueColor(),
ContrastSecondaryTextColor: tcell.ColorLightSlateGray.TrueColor(),
PrimitiveBackgroundColor: tcell.ColorBlack.TrueColor(),
ContrastBackgroundColor: tcell.ColorGreen.TrueColor(),
MoreContrastBackgroundColor: tcell.ColorDarkGreen.TrueColor(),
ButtonCursorRune: 'β',
CheckBoxCheckedRune: 'X',
CheckBoxCursorRune: 'β',
ContextMenuPaddingTop: 0,
ContextMenuPaddingBottom: 0,
ContextMenuPaddingLeft: 1,
ContextMenuPaddingRight: 1,
DropDownAbbreviationChars: "...",
DropDownSymbol: 'β',
DropDownOpenSymbol: 'βΌ',
ScrollBarColor: tcell.ColorWhite.TrueColor(),
WindowMinWidth: 4,
WindowMinHeight: 3,
} | styles.go | 0.603348 | 0.450662 | styles.go | starcoder |
package bradleyterry
import (
"math"
"math/rand"
)
// Pair is a struct combining the outcome of a single match, and contains the name of the
// winner and the name of the loser.
type Pair struct {
Winner string
Loser string
}
const convergenceErr = 1e-15
const maxIter = 10e8
// Model takes in a dataset of Pairs that describe the winner and loser of multiple match-ups.
// The model will return a map[string]float64 that contains the preference/relevance of each
// given element.
func Model(data []Pair) map[string]float64 {
elements := getElements(data)
out := map[string]float64{}
coeffVec := map[string]float64{}
interVec := map[string]float64{}
for _, x := range elements {
coeffVec[x] = rand.Float64()
interVec[x] = 0
}
playWins := map[string]int{}
playPairings := map[string]map[string]int{}
for _, pair := range data {
win := pair.Winner
lose := pair.Loser
playWins[win]++
if _, ok := playPairings[win]; !ok {
playPairings[win] = map[string]int{}
}
if _, ok := playPairings[lose]; !ok {
playPairings[lose] = map[string]int{}
}
playPairings[win][lose]++
playPairings[lose][win]++
}
for i := 0; i < maxIter; i++ {
for play := range coeffVec {
ew := playWins[play]
weightedNumPairings := 0.0
for oe, c := range playPairings[play] {
weightedNumPairings += float64(c) / (coeffVec[play] + coeffVec[oe])
}
interVec[play] = float64(ew) / weightedNumPairings
}
s := 0.0
for _, v := range interVec {
s += v
}
for e, coef := range interVec {
interVec[e] = coef / s
}
errSum := 0.0
for k := range coeffVec {
v := coeffVec[k] - interVec[k]
errSum += math.Pow(v, 2)
}
for k, v := range interVec {
coeffVec[k] = v
}
if errSum < convergenceErr {
return coeffVec
}
}
return out
}
func getElements(input []Pair) []string {
found := map[string]bool{}
for _, d := range input {
found[d.Winner] = true
found[d.Loser] = true
}
elements := []string{}
for k := range found {
elements = append(elements, k)
}
return elements
} | model.go | 0.599837 | 0.452778 | model.go | starcoder |
package evt
import "github.com/shasderias/ilysa/chroma"
// WithNameFilter causes event to only affect rings with the name filter (e.g.
// SmallTrackLaneRings, BigTrackLaneRings).
func WithNameFilter(filter string) withNameFilterOpt {
return withNameFilterOpt{filter}
}
type withNameFilterOpt struct {
nameFilter string
}
func (o withNameFilterOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withNameFilterOpt) applyPreciseRotation(e *PreciseRotation) {
e.NameFilter = o.nameFilter
}
// WithReset resets the rings when set to true (overwrites other values below)
func WithReset(r bool) withResetOpt {
return withResetOpt{r}
}
type withResetOpt struct {
reset bool
}
func (o withResetOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withResetOpt) applyPreciseRotation(e *PreciseRotation) {
e.Reset = o.reset
}
// WithRotation dictates how far the first ring will spin
func WithRotation(r float64) withRotationOpt {
return withRotationOpt{r}
}
type withRotationOpt struct {
rotation float64
}
func (o withRotationOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withRotationOpt) applyPreciseRotation(e *PreciseRotation) {
e.Rotation = o.rotation
}
// WithRotationStep dictates how much rotation is added between each ring
func WithRotationStep(s float64) withRotationStepOpt {
return withRotationStepOpt{s}
}
type withRotationStepOpt struct {
step float64
}
func (o withRotationStepOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withRotationStepOpt) applyPreciseRotation(e *PreciseRotation) {
e.Step = o.step
}
// WithProp dictates the rate at which rings behind the first one have physics
// applied to them. High value makes all rings move simultaneously, low value
// gives them significant delay.
func WithProp(p float64) withPropOpt {
return withPropOpt{p}
}
type withPropOpt struct {
prop float64
}
func (o withPropOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withPropOpt) applyPreciseRotation(e *PreciseRotation) {
e.Prop = o.prop
}
// WithRotationSpeed dictates the s multiplier of the rings
func WithRotationSpeed(s float64) withRotationSpeedOpt {
return withRotationSpeedOpt{s}
}
type withRotationSpeedOpt struct {
s float64
}
func (o withRotationSpeedOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withRotationSpeedOpt) applyPreciseRotation(e *PreciseRotation) {
e.Speed = o.s
}
// WithRotationDirection dictates the direction to spin the rings
func WithRotationDirection(d chroma.SpinDirection) withRotationDirectionOpt {
return withRotationDirectionOpt{d}
}
type withRotationDirectionOpt struct {
d chroma.SpinDirection
}
func (o withRotationDirectionOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withRotationDirectionOpt) applyPreciseRotation(e *PreciseRotation) {
e.Direction = o.d
}
// WithCounterSpin causes the smaller ring to spin in the opposite direction
func WithCounterSpin(c bool) withCounterSpinOpt {
return withCounterSpinOpt{c}
}
type withCounterSpinOpt struct {
counterSpin bool
}
func (o withCounterSpinOpt) apply(e Event) {
pr, ok := e.(*PreciseRotation)
if !ok {
return
}
o.applyPreciseRotation(pr)
}
func (o withCounterSpinOpt) applyPreciseRotation(e *PreciseRotation) {
e.CounterSpin = o.counterSpin
} | evt/rotation_opt.go | 0.852522 | 0.473049 | rotation_opt.go | starcoder |
package network
import (
"fmt"
"github.com/benjohns1/neural-net-go/matutil"
"github.com/benjohns1/neural-net-go/network/activation"
"gonum.org/v1/gonum/mat"
)
// Config network constructor.
type Config struct {
InputCount int
LayerCounts []int
Activation ActivationType
Rate float64
RandSeed uint64
RandState uint64
Trained uint64
}
type ActivationType int
const (
ActivationTypeNone ActivationType = iota
ActivationTypeSigmoid
ActivationTypeTanh
)
// Network struct.
type Network struct {
cfg Config
activation activationFunc
activationMatrixDerivative activationMatrixDerivativeFunc
weights []*mat.Dense // hidden and output layers
}
// NewRandom constructs a new network with random weights from a config.
func NewRandom(cfg Config) (*Network, error) {
src := Rand{cfg.RandSeed, cfg.RandState}.GetSource()
weights := make([]*mat.Dense, 0, len(cfg.LayerCounts))
count := cfg.InputCount
for _, nextCount := range cfg.LayerCounts {
next, err := matutil.New(nextCount, count, matutil.RandomArray(nextCount*count, float64(count), matutil.OptRandomArraySource(src)))
if err != nil {
return nil, fmt.Errorf("creating random matrix with %d rows and %d columns: %v", nextCount, count, err)
}
weights = append(weights, next)
count = nextCount
}
return New(cfg, weights)
}
// New constructs a new network with the specified layer weights.
func New(cfg Config, weights []*mat.Dense) (*Network, error) {
if len(weights) != len(cfg.LayerCounts) {
return nil, fmt.Errorf("layer weight count '%d' must be equal configured layer count '%d'", len(weights), len(cfg.LayerCounts))
}
previousCount := cfg.InputCount
for i, weight := range weights {
currentCount := cfg.LayerCounts[i]
rc, cc := weight.Dims()
if rc*cc != previousCount*currentCount {
return nil, fmt.Errorf("layer %d size %d must equal layer 0 weight count %d", i, previousCount*currentCount, rc*cc)
}
previousCount = currentCount
}
af, amdf, err := newActivationFuncs(cfg)
if err != nil {
return nil, err
}
return &Network{
cfg: cfg,
activation: af,
activationMatrixDerivative: amdf,
weights: weights,
}, nil
}
type activationFunc func(_, _ int, v float64) float64
type activationMatrixDerivativeFunc func(outputs mat.Matrix) (*mat.Dense, error)
type Activation interface {
Value(float64) float64
MatrixDerivative(outputs mat.Matrix) (*mat.Dense, error)
}
func newActivationFuncs(cfg Config) (activationFunc, activationMatrixDerivativeFunc, error) {
var a Activation
switch cfg.Activation {
case ActivationTypeNone:
fallthrough
case ActivationTypeSigmoid:
a = activation.Sigmoid{}
case ActivationTypeTanh:
a = activation.Tanh{}
default:
return nil, nil, fmt.Errorf("unknown activation type %v", cfg.Activation)
}
return func(_, _ int, v float64) float64 { return a.Value(v) }, a.MatrixDerivative, nil
}
// Config gets the networks configuration.
func (n Network) Config() Config {
return n.cfg
}
// Predict outputs from a trained network.
func (n Network) Predict(inputData []float64) (*mat.Dense, error) {
inputs, err := matutil.FromVector(inputData)
if err != nil {
return nil, fmt.Errorf("creating matrix from input data: %v", err)
}
outputs, err := propagateForwards(inputs, n.weights, n.activation)
if err != nil {
return nil, err
}
return outputs[len(outputs)-1], nil
}
// Train the network with a single set of inputs and target outputs.
func (n *Network) Train(input []float64, target []float64) error {
inputs, err := matutil.FromVector(input)
if err != nil {
return fmt.Errorf("creating input matrix: %v", err)
}
targets, err := matutil.FromVector(target)
if err != nil {
return fmt.Errorf("creating target matrix: %v", err)
}
layerOutputs, err := propagateForwards(inputs, n.weights, n.activation)
if err != nil {
return err
}
finalOutputs := layerOutputs[len(layerOutputs)-1]
errors, err := findErrors(targets, finalOutputs, n.weights)
if err != nil {
return fmt.Errorf("finding errors: %v", err)
}
n.weights, err = propagateBackwards(n.weights, errors, layerOutputs, inputs, n.cfg.Rate, n.activationMatrixDerivative)
if err != nil {
return err
}
n.cfg.Trained++
return nil
}
// Trained returns the number of training runs.
func (n Network) Trained() uint64 {
return n.cfg.Trained
}
func propagateBackwards(weights, errors, outputs []*mat.Dense, inputs mat.Matrix, rate float64, activationDer activationMatrixDerivativeFunc) ([]*mat.Dense, error) {
adjustedWeights := make([]*mat.Dense, len(weights))
var err error
for i := len(weights) - 1; i >= 1; i-- {
adjustedWeights[i], err = backward(outputs[i], errors[i], weights[i], outputs[i-1], rate, activationDer)
if err != nil {
return nil, err
}
}
adjustedWeights[0], err = backward(outputs[0], errors[0], weights[0], inputs, rate, activationDer)
if err != nil {
return nil, err
}
return adjustedWeights, nil
}
func propagateForwards(inputs mat.Matrix, weights []*mat.Dense, activation activationFunc) ([]*mat.Dense, error) {
outputs := make([]*mat.Dense, 0, len(weights))
for _, weight := range weights {
layerOutput, err := forward(inputs, weight, activation)
if err != nil {
return nil, err
}
outputs = append(outputs, layerOutput)
inputs = layerOutput
}
return outputs, nil
}
func backward(outputs, errors, weights, inputs mat.Matrix, learningRate float64, activationDer activationMatrixDerivativeFunc) (*mat.Dense, error) {
actDer, err := activationDer(outputs)
if err != nil {
return nil, fmt.Errorf("applying activation derivative: %v", err)
}
multiply, err := matutil.MulElem(errors, actDer)
if err != nil {
return nil, fmt.Errorf("applying errors to activation derivative: %v", err)
}
dot, err := matutil.Dot(multiply, inputs.T())
if err != nil {
return nil, fmt.Errorf("applying activated errors to inputs: %v", err)
}
scale, err := matutil.Scale(learningRate, dot)
if err != nil {
return nil, fmt.Errorf("scaling by learning rate: %v", err)
}
adjusted, err := matutil.Add(weights, scale)
if err != nil {
return nil, fmt.Errorf("adding scaled corrections to weights: %v", err)
}
return adjusted, nil
}
func findErrors(targets mat.Matrix, finalOutputs mat.Matrix, weights []*mat.Dense) ([]*mat.Dense, error) {
errors := make([]*mat.Dense, len(weights))
lastErrors, err := matutil.Sub(targets, finalOutputs)
if err != nil {
return nil, fmt.Errorf("subtracting target from final outputs: %v", err)
}
for i := len(weights) - 1; i >= 1; i-- {
errors[i] = lastErrors
lastErrors, err = matutil.Dot(weights[i].T(), lastErrors)
if err != nil {
return nil, err
}
}
errors[0] = lastErrors
return errors, nil
}
func forward(inputs mat.Matrix, weights mat.Matrix, activation activationFunc) (*mat.Dense, error) {
rawOutputs, err := matutil.Dot(weights, inputs)
if err != nil {
return nil, fmt.Errorf("applying weights: %v", err)
}
outputs, err := matutil.Apply(activation, rawOutputs)
if err != nil {
return nil, fmt.Errorf("applying activation function: %v", err)
}
return outputs, nil
} | network/network.go | 0.786746 | 0.441432 | network.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.