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 models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// CrossTenantAccessPolicyConfigurationPartner
type CrossTenantAccessPolicyConfigurationPartner struct {
// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
additionalData map[string]interface{}
// Defines your partner-specific configuration for users from other organizations accessing your resources via Azure AD B2B collaboration.
b2bCollaborationInbound CrossTenantAccessPolicyB2BSettingable
// Defines your partner-specific configuration for users in your organization going outbound to access resources in another organization via Azure AD B2B collaboration.
b2bCollaborationOutbound CrossTenantAccessPolicyB2BSettingable
// Defines your partner-specific configuration for users from other organizations accessing your resources via Azure B2B direct connect.
b2bDirectConnectInbound CrossTenantAccessPolicyB2BSettingable
// Defines your partner-specific configuration for users in your organization going outbound to access resources in another organization via Azure AD B2B direct connect.
b2bDirectConnectOutbound CrossTenantAccessPolicyB2BSettingable
// Determines the partner-specific configuration for trusting other Conditional Access claims from external Azure AD organizations.
inboundTrust CrossTenantAccessPolicyInboundTrustable
// Identifies whether the partner-specific configuration is a Cloud Service Provider for your organization.
isServiceProvider *bool
// The tenant identifier for the partner Azure AD organization. Read-only. Key.
tenantId *string
}
// NewCrossTenantAccessPolicyConfigurationPartner instantiates a new crossTenantAccessPolicyConfigurationPartner and sets the default values.
func NewCrossTenantAccessPolicyConfigurationPartner()(*CrossTenantAccessPolicyConfigurationPartner) {
m := &CrossTenantAccessPolicyConfigurationPartner{
}
m.SetAdditionalData(make(map[string]interface{}));
return m
}
// CreateCrossTenantAccessPolicyConfigurationPartnerFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateCrossTenantAccessPolicyConfigurationPartnerFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewCrossTenantAccessPolicyConfigurationPartner(), nil
}
// GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetAdditionalData()(map[string]interface{}) {
if m == nil {
return nil
} else {
return m.additionalData
}
}
// GetB2bCollaborationInbound gets the b2bCollaborationInbound property value. Defines your partner-specific configuration for users from other organizations accessing your resources via Azure AD B2B collaboration.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetB2bCollaborationInbound()(CrossTenantAccessPolicyB2BSettingable) {
if m == nil {
return nil
} else {
return m.b2bCollaborationInbound
}
}
// GetB2bCollaborationOutbound gets the b2bCollaborationOutbound property value. Defines your partner-specific configuration for users in your organization going outbound to access resources in another organization via Azure AD B2B collaboration.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetB2bCollaborationOutbound()(CrossTenantAccessPolicyB2BSettingable) {
if m == nil {
return nil
} else {
return m.b2bCollaborationOutbound
}
}
// GetB2bDirectConnectInbound gets the b2bDirectConnectInbound property value. Defines your partner-specific configuration for users from other organizations accessing your resources via Azure B2B direct connect.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetB2bDirectConnectInbound()(CrossTenantAccessPolicyB2BSettingable) {
if m == nil {
return nil
} else {
return m.b2bDirectConnectInbound
}
}
// GetB2bDirectConnectOutbound gets the b2bDirectConnectOutbound property value. Defines your partner-specific configuration for users in your organization going outbound to access resources in another organization via Azure AD B2B direct connect.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetB2bDirectConnectOutbound()(CrossTenantAccessPolicyB2BSettingable) {
if m == nil {
return nil
} else {
return m.b2bDirectConnectOutbound
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *CrossTenantAccessPolicyConfigurationPartner) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))
res["b2bCollaborationInbound"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateCrossTenantAccessPolicyB2BSettingFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetB2bCollaborationInbound(val.(CrossTenantAccessPolicyB2BSettingable))
}
return nil
}
res["b2bCollaborationOutbound"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateCrossTenantAccessPolicyB2BSettingFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetB2bCollaborationOutbound(val.(CrossTenantAccessPolicyB2BSettingable))
}
return nil
}
res["b2bDirectConnectInbound"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateCrossTenantAccessPolicyB2BSettingFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetB2bDirectConnectInbound(val.(CrossTenantAccessPolicyB2BSettingable))
}
return nil
}
res["b2bDirectConnectOutbound"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateCrossTenantAccessPolicyB2BSettingFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetB2bDirectConnectOutbound(val.(CrossTenantAccessPolicyB2BSettingable))
}
return nil
}
res["inboundTrust"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateCrossTenantAccessPolicyInboundTrustFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetInboundTrust(val.(CrossTenantAccessPolicyInboundTrustable))
}
return nil
}
res["isServiceProvider"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetIsServiceProvider(val)
}
return nil
}
res["tenantId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetTenantId(val)
}
return nil
}
return res
}
// GetInboundTrust gets the inboundTrust property value. Determines the partner-specific configuration for trusting other Conditional Access claims from external Azure AD organizations.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetInboundTrust()(CrossTenantAccessPolicyInboundTrustable) {
if m == nil {
return nil
} else {
return m.inboundTrust
}
}
// GetIsServiceProvider gets the isServiceProvider property value. Identifies whether the partner-specific configuration is a Cloud Service Provider for your organization.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetIsServiceProvider()(*bool) {
if m == nil {
return nil
} else {
return m.isServiceProvider
}
}
// GetTenantId gets the tenantId property value. The tenant identifier for the partner Azure AD organization. Read-only. Key.
func (m *CrossTenantAccessPolicyConfigurationPartner) GetTenantId()(*string) {
if m == nil {
return nil
} else {
return m.tenantId
}
}
// Serialize serializes information the current object
func (m *CrossTenantAccessPolicyConfigurationPartner) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
{
err := writer.WriteObjectValue("b2bCollaborationInbound", m.GetB2bCollaborationInbound())
if err != nil {
return err
}
}
{
err := writer.WriteObjectValue("b2bCollaborationOutbound", m.GetB2bCollaborationOutbound())
if err != nil {
return err
}
}
{
err := writer.WriteObjectValue("b2bDirectConnectInbound", m.GetB2bDirectConnectInbound())
if err != nil {
return err
}
}
{
err := writer.WriteObjectValue("b2bDirectConnectOutbound", m.GetB2bDirectConnectOutbound())
if err != nil {
return err
}
}
{
err := writer.WriteObjectValue("inboundTrust", m.GetInboundTrust())
if err != nil {
return err
}
}
{
err := writer.WriteBoolValue("isServiceProvider", m.GetIsServiceProvider())
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("tenantId", m.GetTenantId())
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 *CrossTenantAccessPolicyConfigurationPartner) SetAdditionalData(value map[string]interface{})() {
if m != nil {
m.additionalData = value
}
}
// SetB2bCollaborationInbound sets the b2bCollaborationInbound property value. Defines your partner-specific configuration for users from other organizations accessing your resources via Azure AD B2B collaboration.
func (m *CrossTenantAccessPolicyConfigurationPartner) SetB2bCollaborationInbound(value CrossTenantAccessPolicyB2BSettingable)() {
if m != nil {
m.b2bCollaborationInbound = value
}
}
// SetB2bCollaborationOutbound sets the b2bCollaborationOutbound property value. Defines your partner-specific configuration for users in your organization going outbound to access resources in another organization via Azure AD B2B collaboration.
func (m *CrossTenantAccessPolicyConfigurationPartner) SetB2bCollaborationOutbound(value CrossTenantAccessPolicyB2BSettingable)() {
if m != nil {
m.b2bCollaborationOutbound = value
}
}
// SetB2bDirectConnectInbound sets the b2bDirectConnectInbound property value. Defines your partner-specific configuration for users from other organizations accessing your resources via Azure B2B direct connect.
func (m *CrossTenantAccessPolicyConfigurationPartner) SetB2bDirectConnectInbound(value CrossTenantAccessPolicyB2BSettingable)() {
if m != nil {
m.b2bDirectConnectInbound = value
}
}
// SetB2bDirectConnectOutbound sets the b2bDirectConnectOutbound property value. Defines your partner-specific configuration for users in your organization going outbound to access resources in another organization via Azure AD B2B direct connect.
func (m *CrossTenantAccessPolicyConfigurationPartner) SetB2bDirectConnectOutbound(value CrossTenantAccessPolicyB2BSettingable)() {
if m != nil {
m.b2bDirectConnectOutbound = value
}
}
// SetInboundTrust sets the inboundTrust property value. Determines the partner-specific configuration for trusting other Conditional Access claims from external Azure AD organizations.
func (m *CrossTenantAccessPolicyConfigurationPartner) SetInboundTrust(value CrossTenantAccessPolicyInboundTrustable)() {
if m != nil {
m.inboundTrust = value
}
}
// SetIsServiceProvider sets the isServiceProvider property value. Identifies whether the partner-specific configuration is a Cloud Service Provider for your organization.
func (m *CrossTenantAccessPolicyConfigurationPartner) SetIsServiceProvider(value *bool)() {
if m != nil {
m.isServiceProvider = value
}
}
// SetTenantId sets the tenantId property value. The tenant identifier for the partner Azure AD organization. Read-only. Key.
func (m *CrossTenantAccessPolicyConfigurationPartner) SetTenantId(value *string)() {
if m != nil {
m.tenantId = value
}
} | models/cross_tenant_access_policy_configuration_partner.go | 0.661486 | 0.435601 | cross_tenant_access_policy_configuration_partner.go | starcoder |
package engine
import (
"fmt"
"github.com/ajeetdsouza/tracy/pkg/config"
"gonum.org/v1/gonum/floats"
"gonum.org/v1/gonum/mat"
)
const (
wPoint = 1.0
wVector = 0.0
)
type Tuple struct {
data mat.Vector
}
func NewTuple(x, y, z, w float64) Tuple {
return Tuple{mat.NewVecDense(4, []float64{x, y, z, w})}
}
func NewPoint(x, y, z float64) Tuple {
return NewTuple(x, y, z, wPoint)
}
func NewVector(x, y, z float64) Tuple {
return NewTuple(x, y, z, wVector)
}
func (tuple Tuple) X() float64 {
return tuple.data.AtVec(0)
}
func (tuple Tuple) Y() float64 {
return tuple.data.AtVec(1)
}
func (tuple Tuple) Z() float64 {
return tuple.data.AtVec(2)
}
func (tuple Tuple) W() float64 {
return tuple.data.AtVec(3)
}
func (tuple Tuple) String() string {
return fmt.Sprintf("Tuple(%.1f,%.1f,%.1f,%.1f)", tuple.X(), tuple.Y(), tuple.Z(), tuple.W())
}
func (tuple Tuple) IsPoint() bool {
return floats.EqualWithinAbsOrRel(tuple.W(), wPoint, config.EPSILON, config.EPSILON)
}
func (tuple Tuple) IsVector() bool {
return floats.EqualWithinAbsOrRel(tuple.W(), wVector, config.EPSILON, config.EPSILON)
}
func (tuple Tuple) Equal(other Tuple) bool {
return mat.EqualApprox(tuple.data, other.data, config.EPSILON)
}
func (tuple Tuple) Add(other Tuple) Tuple {
var result mat.VecDense
result.AddVec(tuple.data, other.data)
return Tuple{&result}
}
func (tuple Tuple) Sub(other Tuple) Tuple {
var result mat.VecDense
result.SubVec(tuple.data, other.data)
return Tuple{&result}
}
func (tuple Tuple) Mul(k float64) Tuple {
var result mat.VecDense
result.ScaleVec(k, tuple.data)
return Tuple{&result}
}
func (tuple Tuple) Div(k float64) Tuple {
var result mat.VecDense
result.ScaleVec(1/k, tuple.data)
return Tuple{&result}
}
func (tuple Tuple) Neg() Tuple {
return tuple.Mul(-1)
}
func (tuple Tuple) Magnitude() float64 {
return mat.Norm(tuple.data, 2)
}
func (tuple Tuple) Normalize() Tuple {
r := tuple.Magnitude()
return tuple.Div(r)
}
func (tuple Tuple) Dot(other Tuple) float64 {
return mat.Dot(tuple.data, other.data)
}
func (tuple Tuple) Cross(other Tuple) Tuple {
return NewVector(
tuple.Y()*other.Z()-tuple.Z()*other.Y(),
tuple.Z()*other.X()-tuple.X()*other.Z(),
tuple.X()*other.Y()-tuple.Y()*other.X(),
)
}
func (tuple Tuple) Reflect(normal Tuple) Tuple {
return tuple.Sub(normal.Mul(2 * tuple.Dot(normal)))
}
func (tuple Tuple) ApplyTransform(transform Transform) Tuple {
var result mat.VecDense
result.MulVec(transform.data, tuple.data)
return Tuple{&result}
} | pkg/engine/tuple.go | 0.788339 | 0.564219 | tuple.go | starcoder |
package websocket
import (
"math/rand"
)
func (c *Chain) RandMove(playerColor string) (int, int) {
validSquares := make([][2]int, 0)
for y, v := range c.Squares {
for x, color := range v.Color {
if color == "" || color == playerColor {
validSquares = append(validSquares, [2]int{x, y})
}
}
}
sq := validSquares[rand.Intn(len(validSquares))]
return sq[0], sq[1]
}
// Heuristic from https://brilliant.org/wiki/chain-reaction-game/
func BrillHeuristic(board []*Squares, color string) int {
score := 0
myCircles, enemyCircles := 0, 0
for y := 0; y < len(board); y++ {
for x := 0; x < board[0].Len; x++ {
if board[y].Color[x] == color {
myCircles += board[y].Cur[x]
safe := true
total, coords := findneighbors(x, y, board[0].Len, len(board))
for _, coord := range coords {
nx, ny := coord[0], coord[1]
if board[ny].Color[nx] != color && board[ny].Cur[nx] == board[ny].Max[nx]-1 {
adjTotal, _ := findneighbors(nx, ny, board[0].Len, len(board))
score -= 5 - adjTotal
safe = false
}
}
if safe {
if total == 3 {
score += 2
} else if total == 2 {
score += 3
}
if board[y].Cur[x] == total-1 {
score += 2
}
}
} else {
enemyCircles += board[y].Cur[x]
}
}
}
score += myCircles
// A player can only win when they have more than one circle
if enemyCircles == 0 && myCircles > 1 {
return 10000
} else if myCircles == 0 && enemyCircles > 1 {
return -10000
}
for _, length := range findChains(board, color) {
if length > 1 {
score += 2 * length
}
}
return score
}
// getChains tries to find optimizations to ignore reprocessing redundant squares
func getChains(oldBoard []*Squares, color string, x, y int) [][]int {
board := copyBoard(oldBoard)
visiting := [][]int{{x, y}}
if board[y].Cur[x] == board[y].Max[x]-1 && board[y].Color[x] == color {
for len(visiting) > 0 {
last := len(visiting) - 1
nx, ny := visiting[last][0], visiting[last][1]
board[ny].Cur[nx] = 0
total, coords := findneighbors(nx, ny, board[0].Len, len(board))
for _, coord := range coords {
newX, newY := coord[0], coord[1]
if board[newY].Cur[newX] == total-1 {
visiting = append(visiting, coord)
}
}
}
}
return visiting
}
func findChains(oldBoard []*Squares, color string) []int {
board := copyBoard(oldBoard)
lengths := make([]int, 0)
for y := 0; y < len(board); y++ {
for x := 0; x < board[0].Len; x++ {
if board[y].Cur[x] == board[y].Max[x]-1 && board[y].Color[x] == color {
amount := 0
visiting := [][]int{{x, y}}
for len(visiting) > 0 {
last := len(visiting) - 1
nx, ny := visiting[last][0], visiting[last][1]
visiting = visiting[:last]
board[ny].Cur[nx] = 0
amount++
total, coords := findneighbors(nx, ny, board[0].Len, len(board))
for _, coord := range coords {
newX, newY := coord[0], coord[1]
if board[newY].Cur[newX] == total-1 && board[newY].Color[newX] == color {
visiting = append(visiting, coord)
}
}
}
lengths = append(lengths, amount)
}
}
}
return lengths
}
func (c *Chain) signiMoves(color string) [][]int {
validMoves := make([][]int, 0, c.Squares[0].Len*c.Len)
redundant := make(map[[2]int]bool, 0)
// heuristic for ignoring moves that will lead to the same outcome
// redundant acting as a set to account for already seen squares
for y := 0; y < c.Len; y++ {
for x := 0; x < c.Squares[0].Len; x++ {
if (c.Squares[y].Color[x] == "" || c.Squares[y].Color[x] == color) && redundant[[2]int{x, y}] == false {
chained := getChains(c.Squares, color, x, y)
redundant[[2]int{x, y}] = true
validMoves = append(validMoves, chained[0])
for _, sq := range chained {
nx, ny := sq[0], sq[1]
// objects can get chained into other people's circles.
redundant[[2]int{nx, ny}] = true
}
}
}
}
return validMoves
}
// defaultMoves grabs all legal moves that are possible
func (c *Chain) defaultMoves(color string, rows, cols int) [][]int {
moves := make([][]int, 0, rows*cols)
for y := 0; y < cols; y++ {
for x := 0; x < rows; x++ {
if c.Squares[y].Color[x] == "" || c.Squares[y].Color[x] == color {
moves = append(moves, []int{x, y})
}
}
}
return moves
}
// Maximizing player
// Return greatest number possible
func (c *Chain) Max(color, nextColor string, depth, alpha, beta, movedx, movedy int) (int, [2]int) {
//counter++
sq := [2]int{movedx, movedy}
//println(depth, " In depth and Max ", counter)
if depth == 0 {
// use because we are evaluating previous player's move
boardValue := BrillHeuristic(c.Squares, color)
return boardValue, sq
}
newBoard := copyBoard(c.Squares)
newClients := copyClients(c.Hub.Clients)
players := make([]string, len(c.Hub.Colors))
for ind, player := range c.Hub.Colors {
players[ind] = player
}
//validMoves := c.signiMoves(color)
validMoves := c.defaultMoves(color, c.Squares[0].Len, c.Len)
for _, pos := range validMoves {
x, y := pos[0], pos[1]
c.MovePiece(x, y, color)
// revert side effects from MovePiece
maxVal, _ := c.Min(nextColor, color, depth-1, alpha, beta, x, y)
for client, squares := range newClients {
c.Hub.Clients[client] = squares
}
length := len(players)
c.Hub.Colors = make([]string, length, length)
for index, color := range players {
c.Hub.Colors[index] = color
}
replaceBoard(c.Squares, newBoard)
if maxVal > alpha {
sq = [2]int{x, y}
alpha = maxVal
if alpha >= beta {
return alpha, sq
}
}
}
return alpha, sq
}
// Minimizing player
// Return smallest number possible
// Look at Max() for more documentation
func (c *Chain) Min(color, nextColor string, depth, alpha, beta, movedx, movedy int) (int, [2]int) {
//counter++
//println(depth, " In depth and Min ", counter)
sq := [2]int{movedx, movedy}
if depth == 0 {
// nextColor is actually our original color
boardValue := BrillHeuristic(c.Squares, nextColor)
return boardValue, sq
}
players := make([]string, len(c.Hub.Colors))
for ind, player := range c.Hub.Colors {
players[ind] = player
}
newBoard := copyBoard(c.Squares)
newClients := copyClients(c.Hub.Clients)
validMoves := c.defaultMoves(color, c.Squares[0].Len, c.Len)
for _, pos := range validMoves {
x, y := pos[0], pos[1]
c.MovePiece(x, y, color)
minVal, _ := c.Max(nextColor, color, depth-1, alpha, beta, x, y)
for client, squares := range newClients {
c.Hub.Clients[client] = squares
}
length := len(players)
c.Hub.Colors = make([]string, length, length)
for index, color := range players {
c.Hub.Colors[index] = color
}
replaceBoard(c.Squares, newBoard)
if minVal < beta {
sq = [2]int{x, y}
beta = minVal
if alpha >= beta {
return beta, sq
}
}
}
return beta, sq
}
func copyBoard(oldBoard []*Squares) []*Squares {
newBoard := make([]*Squares, len(oldBoard))
for y, valy := range oldBoard {
newBoard[y] = &Squares{
Len: valy.Len,
Color: make([]string, valy.Len),
Cur: make([]int, valy.Len),
Max: make([]int, valy.Len),
}
for x := 0; x < valy.Len; x++ {
newBoard[y].Color[x] = valy.Color[x]
newBoard[y].Cur[x] = valy.Cur[x]
newBoard[y].Max[x] = valy.Max[x]
}
}
return newBoard
}
func copyClients(oldClients map[*Client]int) map[*Client]int {
newClients := make(map[*Client]int)
for client, val := range oldClients {
newClients[client] = val
}
return newClients
}
// Put contents of newboard into oldboard in-place
func replaceBoard(oldboard []*Squares, newboard []*Squares) {
for y, squares := range newboard {
for x := 0; x < squares.Len; x++ {
oldboard[y].Color[x] = newboard[y].Color[x]
oldboard[y].Cur[x] = newboard[y].Cur[x]
oldboard[y].Max[x] = newboard[y].Max[x]
}
}
} | websocket/bot.go | 0.525856 | 0.446434 | bot.go | starcoder |
package raytracer
import (
"fmt"
"gonum.org/v1/gonum/spatial/r3"
"math"
"reflect"
)
type hitRecord struct {
t float64
p r3.Vec
normal r3.Vec
shape Shape
material Material
}
type Shape interface {
// rotation vector is in degrees
Rotate(rv r3.Vec)
Scale(c float64)
Translate(tv r3.Vec)
hit(r *ray, tMin float64, tMax float64) hitRecord
computeSquareBounds() (lowest r3.Vec, highest r3.Vec)
centroid() r3.Vec
// u, v must be between [0, 1]
textureMap(point r3.Vec, normal r3.Vec) (u, v float64)
description() string
}
type Sphere struct {
Center r3.Vec
Radius float64
Mat Material
}
type TrianglePlane struct {
PointA r3.Vec
PointB r3.Vec
PointC r3.Vec
SingleSided bool
Mat Material
}
func (s Sphere) hit(r *ray, tMin float64, tMax float64) hitRecord {
oc := r3.Sub(r.p, s.Center)
a := r3.Dot(r.normalizedDirection, r.normalizedDirection)
b := r3.Dot(oc, r.normalizedDirection)
c := r3.Dot(oc, oc) - s.Radius*s.Radius
discriminant := b*b - a*c
if discriminant > 0 {
firstPoint := (-b - math.Sqrt(b*b-a*c)) / a
if firstPoint > tMin && firstPoint <= tMax {
return hitRecord{
t: firstPoint,
p: r.PointAtT(firstPoint),
normal: r3.Scale(1/s.Radius, r3.Sub(r.PointAtT(firstPoint), s.Center)),
shape: &s,
material: s.Mat,
}
}
secondPoint := (-b - math.Sqrt(b*b-a*c)) / a
if secondPoint > tMin && firstPoint <= tMax {
return hitRecord{
t: secondPoint,
p: r.PointAtT(secondPoint),
normal: r3.Scale(1/s.Radius, r3.Sub(r.PointAtT(secondPoint), s.Center)),
shape: &s,
material: s.Mat,
}
}
}
return hitRecord{
t: -1,
}
}
func (s *Sphere) Translate(tv r3.Vec) {
s.Center = r3.Add(tv, s.Center)
}
func (s *Sphere) Scale(c float64) {
s.Radius *= c
}
func (s *Sphere) Rotate(rv r3.Vec) {
}
func (s Sphere) computeSquareBounds() (lowest r3.Vec, highest r3.Vec) {
return r3.Sub(s.Center, r3.Vec{X: s.Radius, Y: s.Radius, Z: s.Radius}), r3.Add(s.Center, r3.Vec{X: s.Radius, Y: s.Radius, Z: s.Radius})
}
func (s Sphere) centroid() r3.Vec {
return s.Center
}
// https://people.cs.clemson.edu/~dhouse/courses/405/notes/texture-maps.pdf
func (s Sphere) textureMap(point r3.Vec, normal r3.Vec) (u, v float64) {
pointWhenSphereAtOrigin := r3.Sub(point, s.Center)
theta := math.Atan2(-1*pointWhenSphereAtOrigin.Z, pointWhenSphereAtOrigin.X)
phi := math.Acos(-1 * pointWhenSphereAtOrigin.Y / s.Radius)
return (theta + math.Pi) / (2 * math.Pi), phi / math.Pi
}
func (s Sphere) description() string {
return fmt.Sprintf(
"%s - Center: %v, Radius %f, Material: %s",
reflect.TypeOf(s),
s.Center,
s.Radius,
reflect.TypeOf(s.Mat),
)
}
func (tr TrianglePlane) hit(r *ray, tMin float64, tMax float64) hitRecord {
// moller-trumbore ray triangle intersection algorithm
dir := r.normalizedDirection
bMinusA := r3.Sub(tr.PointB, tr.PointA)
cMinusA := r3.Sub(tr.PointC, tr.PointA)
normal := r3.Unit(r3.Cross(bMinusA, cMinusA))
pvec := r3.Cross(dir, cMinusA)
det := r3.Dot(bMinusA, pvec)
if tr.SingleSided {
if det < 0.0 {
return hitRecord{t: -1}
}
} else {
// check for parallelism
if math.Abs(det) < 0.0 {
return hitRecord{t: -1}
}
}
invDet := 1 / det
tvec := r3.Sub(r.p, tr.PointA)
u := r3.Dot(tvec, pvec) * invDet
if u < 0 || u > 1 {
return hitRecord{t: -1}
}
qvec := r3.Cross(tvec, bMinusA)
v := r3.Dot(dir, qvec) * invDet
if v < 0 || u+v > 1 {
return hitRecord{t: -1}
}
t := r3.Dot(cMinusA, qvec) * invDet
if t < tMin || t > tMax {
return hitRecord{t: -1}
}
return hitRecord{
t: t,
p: r.PointAtT(t),
normal: normal,
shape: &tr,
material: tr.Mat,
}
}
func (t *TrianglePlane) Translate(tv r3.Vec) {
t.PointA = r3.Add(tv, t.PointA)
t.PointB = r3.Add(tv, t.PointB)
t.PointC = r3.Add(tv, t.PointC)
}
func (t *TrianglePlane) Scale(c float64) {
t.PointA = r3.Scale(c, t.PointA)
t.PointB = r3.Scale(c, t.PointB)
t.PointC = r3.Scale(c, t.PointC)
}
func (t *TrianglePlane) Rotate(rv r3.Vec) {
t.PointA = rotatePoint(t.PointA, rv)
t.PointB = rotatePoint(t.PointB, rv)
t.PointC = rotatePoint(t.PointC, rv)
}
func (tr TrianglePlane) computeSquareBounds() (lowest r3.Vec, highest r3.Vec) {
pMin := r3.Vec{X: math.MaxFloat64, Y: math.MaxFloat64, Z: math.MaxFloat64}
pMax := r3.Vec{X: float64(math.MinInt64), Y: float64(math.MinInt64), Z: float64(math.MinInt64)}
pMin.X = math.Min(pMin.X, tr.PointA.X)
pMin.X = math.Min(pMin.X, tr.PointB.X)
pMin.X = math.Min(pMin.X, tr.PointC.X)
pMin.Y = math.Min(pMin.Y, tr.PointA.Y)
pMin.Y = math.Min(pMin.Y, tr.PointB.Y)
pMin.Y = math.Min(pMin.Y, tr.PointC.Y)
pMin.Z = math.Min(pMin.Z, tr.PointA.Z)
pMin.Z = math.Min(pMin.Z, tr.PointB.Z)
pMin.Z = math.Min(pMin.Z, tr.PointC.Z)
pMax.X = math.Max(pMax.X, tr.PointA.X)
pMax.X = math.Max(pMax.X, tr.PointB.X)
pMax.X = math.Max(pMax.X, tr.PointC.X)
pMax.Y = math.Max(pMax.Y, tr.PointA.Y)
pMax.Y = math.Max(pMax.Y, tr.PointB.Y)
pMax.Y = math.Max(pMax.Y, tr.PointC.Y)
pMax.Z = math.Max(pMax.Z, tr.PointA.Z)
pMax.Z = math.Max(pMax.Z, tr.PointB.Z)
pMax.Z = math.Max(pMax.Z, tr.PointC.Z)
return pMin, pMax
}
func (tr TrianglePlane) centroid() r3.Vec {
return r3.Scale(1/3.0, r3.Add(tr.PointA, r3.Add(tr.PointB, tr.PointC)))
}
func (tr TrianglePlane) textureMap(point r3.Vec, normal r3.Vec) (u, v float64) {
// Compute barycentric coordinates (u, v, w) for
// point p with respect to triangle (a, b, c)
v0 := r3.Sub(tr.PointB, tr.PointA)
v1 := r3.Sub(tr.PointC, tr.PointA)
v2 := r3.Sub(point, tr.PointA)
d00 := r3.Dot(v0, v0)
d01 := r3.Dot(v0, v1)
d11 := r3.Dot(v1, v1)
d20 := r3.Dot(v2, v0)
d21 := r3.Dot(v2, v1)
denom := d00*d11 - d01*d01
w := (d00*d21 - d01*d20) / denom
return 1.0 - v - w, (d11*d20 - d01*d21) / denom
}
func (tr TrianglePlane) description() string {
return fmt.Sprintf(
"%s - Point A: %v, Point B: %v, Point C: %v, Material: %s",
reflect.TypeOf(tr),
tr.PointA,
tr.PointB,
tr.PointC,
reflect.TypeOf(tr.Mat),
)
}
func rotatePoint(point r3.Vec, rv r3.Vec) r3.Vec {
piDivide180 := math.Pi / 180.0
rotatedPoint := point
// around z axis
x := rotatedPoint.X*math.Cos(piDivide180*rv.Z) - rotatedPoint.Y*math.Sin(piDivide180*rv.Z)
y := rotatedPoint.X*math.Sin(piDivide180*rv.Z) + rotatedPoint.Y*math.Cos(piDivide180*rv.Z)
rotatedPoint.X = x
rotatedPoint.Y = y
// around x axis
y = rotatedPoint.Y*math.Cos(piDivide180*rv.X) - rotatedPoint.Z*math.Sin(piDivide180*rv.X)
z := rotatedPoint.Y*math.Sin(piDivide180*rv.X) + rotatedPoint.Z*math.Cos(piDivide180*rv.X)
rotatedPoint.Y = y
rotatedPoint.Z = z
// around y axis
x = rotatedPoint.X*math.Cos(piDivide180*rv.Y) + rotatedPoint.Z*math.Sin(piDivide180*rv.Y)
z = -1*rotatedPoint.X*math.Sin(piDivide180*rv.Y) + rotatedPoint.Z*math.Cos(piDivide180*rv.Y)
rotatedPoint.X = x
rotatedPoint.Z = z
return rotatedPoint
} | raytracer/shape.go | 0.838911 | 0.55652 | shape.go | starcoder |
package game
import (
"math"
"sort"
)
// NewEngine initializes a new physics engine
func NewEngine(width, height int, circles []*Circle, capsules []*Capsule, rectangles []*collisionRect) *Engine {
e := &Engine{
minArea: 99999999,
steps: 10,
inverseSteps: 1 / 10,
selectedCapsule: capsuleSelection{-1, true},
capsules: capsules,
collisionRects: rectangles,
}
for _, circle := range circles {
e.addCircle(circle)
}
return e
}
type collisionRect struct {
upperLeft Vec2
lowerRight Vec2
}
// Engine handles collisions
type Engine struct {
checks int
minArea float64
maxArea float64
maxRadius float64
maxSpeed float64
steps int
inverseSteps float64
selectedCircle circleSelection
selectedCapsule capsuleSelection
circles []*Circle
capsules []*Capsule
collisionRects []*collisionRect
collidingPairs []collidingPair
collidingCapsules []collidingCapsule
}
type capsuleSelection struct {
index int
start bool
}
type circleSelection struct {
pointer *Circle
isDynamic bool
}
func (e *Engine) addCircle(circle *Circle) {
for i := range e.circles {
if e.circles[i].pos.X == circle.pos.X && e.circles[i].pos.Y == circle.pos.Y {
circle.pos.X += 0.1
circle.pos.Y += 0.1
}
}
e.circles = append(e.circles, circle)
e.maxRadius = math.Max(e.maxRadius, circle.radius)
e.minArea = math.Min(e.minArea, circle.area)
e.maxArea = math.Max(e.maxArea, circle.area)
circle.id = len(e.circles)
}
func (e *Engine) selectAtPostion(pos Vec2) {
circle := e.circleAtPosition(pos)
e.selectedCircle.pointer = circle
if circle != nil {
circle.selected = true
e.selectedCircle.isDynamic = false
}
}
func (e *Engine) dynamicAtPosition(pos Vec2) {
circle := e.circleAtPosition(pos)
e.selectedCircle.pointer = circle
if circle != nil {
circle.selected = true
e.selectedCircle.isDynamic = true
}
}
func (e *Engine) selectNearestPostion(pos Vec2) {
circle := e.circleNearestPosition(pos)
e.selectedCircle.pointer = circle
if circle != nil {
circle.selected = true
e.selectedCircle.isDynamic = false
}
}
func (e *Engine) dynamicNearestPosition(pos Vec2) {
circle := e.circleNearestPosition(pos)
e.selectedCircle.pointer = circle
if circle != nil {
circle.selected = true
e.selectedCircle.isDynamic = true
}
}
func (e *Engine) circleNearestPosition(pos Vec2) *Circle {
minDistance := math.MaxFloat64
var closest *Circle
for i := range e.circles {
cx := e.circles[i].pos.X
cy := e.circles[i].pos.Y
cr := e.circles[i].radius
d := (cx-pos.X)*(cx-pos.X) + (cy-pos.Y)*(cy-pos.Y)
if d < (cr * cr) {
return e.circles[i]
}
if d < minDistance {
minDistance = d
closest = e.circles[i]
}
}
return closest
}
func (e *Engine) circleAtPosition(pos Vec2) *Circle {
for i := range e.circles {
cx := e.circles[i].pos.X
cy := e.circles[i].pos.Y
cr := e.circles[i].radius
if (cx-pos.X)*(cx-pos.X)+(cy-pos.Y)*(cy-pos.Y) < (cr * cr) {
return e.circles[i]
}
}
return nil
}
func (e *Engine) moveSelectedTo(pos Vec2) {
if e.selectedCircle.pointer != nil {
e.selectedCircle.pointer.pos = pos
}
}
func (e *Engine) applyForceToSelected(pos Vec2, speed float64) {
circle := e.selectedCircle.pointer
if circle != nil {
force := pos.Sub(circle.pos)
circle.acc = force.Scaled(0.03).Scaled(speed)
}
}
func (e *Engine) deselect() {
if e.selectedCircle.pointer != nil {
e.selectedCircle.pointer.selected = false
e.selectedCircle.pointer = nil
}
}
func (e *Engine) dynamicRelease(pos Vec2) {
circle := e.selectedCircle.pointer
if circle != nil {
circle.selected = false
force := circle.pos.Sub(pos)
s := remap(circle.area, e.minArea, e.maxArea, 0.225, 0.04)
circle.acc = force.Scaled(s)
circle.activity += force.Len() * 0.1
}
e.selectedCircle.pointer = nil
e.selectedCircle.isDynamic = false
}
func (e *Engine) getSelected() *Circle {
if e.selectedCircle.pointer != nil && !e.selectedCircle.isDynamic {
return e.selectedCircle.pointer
}
return nil
}
func (e *Engine) getSelectedPosition() (Vec2, bool) {
circle := e.selectedCircle.pointer
if circle != nil && !e.selectedCircle.isDynamic {
return circle.pos, true
}
return Vec2{0, 0}, false
}
func (e *Engine) getDynamic() *Circle {
circle := e.selectedCircle.pointer
if circle != nil && e.selectedCircle.isDynamic {
return circle
}
return nil
}
func (e *Engine) selectCapsuleAtPostion(pos Vec2) bool {
for i := range e.capsules {
v := e.capsules[i].start
r := e.circles[i].radius
if (v.X-pos.X)*(v.X-pos.X)+(v.Y-pos.Y)*(v.Y-pos.Y) < (r * r) {
e.selectedCapsule.index = i
e.selectedCapsule.start = true
return true
}
v = e.capsules[i].end
if (v.X-pos.X)*(v.X-pos.X)+(v.Y-pos.Y)*(v.Y-pos.Y) < (r * r) {
e.selectedCapsule.index = i
e.selectedCapsule.start = false
return true
}
}
e.selectedCapsule.index = -1
return false
}
func (e *Engine) moveSelectedCapsuleTo(pos Vec2) bool {
if e.selectedCapsule.index >= 0 {
if e.selectedCapsule.start {
e.capsules[e.selectedCapsule.index].start = pos
} else {
e.capsules[e.selectedCapsule.index].end = pos
}
return true
}
return false
}
func (e *Engine) deselectCapsule() {
e.selectedCapsule.index = -1
}
func (e *Engine) overlap(i, j int) bool {
// This looks ugly, but here it is without all the index lookups
// (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2) < (r1+r2)*(r1+r2)
return (e.circles[i].pos.X-e.circles[j].pos.X)*(e.circles[i].pos.X-e.circles[j].pos.X)+(e.circles[i].pos.Y-e.circles[j].pos.Y)*(e.circles[i].pos.Y-e.circles[j].pos.Y) < (e.circles[i].radius+e.circles[j].radius)*(e.circles[i].radius+e.circles[j].radius)
}
type collidingPair struct {
a int
b int
}
type collidingCapsule struct {
i int
r float64
d float64
pos Vec2
}
func (e *Engine) update(width, height int, speed, elapsedTime float64) {
e.checks = 0
// set previous position
for i := range e.circles {
e.circles[i].prevPos = e.circles[i].pos
}
stepSpeed := speed / float64(e.steps)
for step := e.steps; step > 0; step-- {
e.updateCirclePositions(width, height, stepSpeed, elapsedTime)
e.sortCircles()
e.resolveStaticCollisions()
e.resolveDynamicCollisions()
}
// find max speed
e.maxSpeed = 0
for i := range e.circles {
e.circles[i].postUpdate()
e.maxSpeed = math.Max(e.maxSpeed, e.circles[i].speed)
}
}
func (e *Engine) updateCirclePositions(width, height int, speed, elapsedTime float64) {
// Update ball positions
for i := range e.circles {
// apply friction
frictionAmount := remap(e.circles[i].area, e.minArea, e.maxArea, 0.015, 0.007)
friction := e.circles[i].acc.Sub(e.circles[i].vel.Scaled(frictionAmount).Scaled(speed))
// update velocity and position
e.circles[i].vel = e.circles[i].vel.Add(friction)
posChange := e.circles[i].vel.Scaled(elapsedTime).Scaled(speed)
e.circles[i].pos = e.circles[i].pos.Add(posChange)
e.circles[i].acc = Vec2{0, 0}
}
}
func (e *Engine) sortCircles() {
// sort by x position
sort.Slice(e.circles, func(i, j int) bool {
return e.circles[i].pos.X < e.circles[j].pos.X
})
}
func (e *Engine) resolveStaticCollisions() {
// Resolve static collisions
e.collidingPairs = e.collidingPairs[:0] // clear slice but keep capacity
e.collidingCapsules = e.collidingCapsules[:0] // clear slice but keep capacity
for i := range e.circles {
for j := i + 1; j < len(e.circles); j++ {
e.checks++
if e.overlap(i, j) {
e.collidingPairs = append(e.collidingPairs, collidingPair{i, j})
// distance between ball centers
r1 := e.circles[i].radius
r2 := e.circles[j].radius
v := e.circles[i].pos.Sub(e.circles[j].pos)
distance := v.Len()
unit := v.Scaled(1.0 / distance)
if e.selectedCircle.pointer != nil && e.circles[i].id == e.selectedCircle.pointer.id {
// displace target circle away from collision
amount := distance - r1 - r2
e.circles[j].pos = e.circles[j].pos.Add(unit.Scaled(amount))
} else {
// Make displace amount depend on area
totalAmount := distance - r1 - r2
a1 := e.circles[i].area
a2 := e.circles[j].area
areaSumM := 1.0 / (a1 + a2)
amount1 := totalAmount * a2 * areaSumM
amount2 := totalAmount * a1 * areaSumM
// displace current circle away from the collision
e.circles[i].pos = e.circles[i].pos.Sub(unit.Scaled(amount1))
// displace target circle away from collision
e.circles[j].pos = e.circles[j].pos.Add(unit.Scaled(amount2))
// boose circle activity based on speed of collision
energy := e.circles[i].speed + e.circles[j].speed
e.circles[i].addCollisionEnergy(energy * e.inverseSteps)
e.circles[j].addCollisionEnergy(energy * e.inverseSteps)
}
} else {
if e.circles[j].pos.X > e.circles[i].pos.X+e.circles[i].radius+e.maxRadius {
break
}
}
}
// line collisions
for j := range e.capsules {
lx1 := e.capsules[j].start.X
ly1 := e.capsules[j].start.Y
lx2 := e.capsules[j].end.X
ly2 := e.capsules[j].end.Y
lr := e.capsules[j].radius
cx := e.circles[i].pos.X
cy := e.circles[i].pos.Y
cr := e.circles[i].radius
// Line vector
lineX1 := lx2 - lx1
lineY1 := ly2 - ly1
// Vector from circle to start of the line
lineX2 := cx - lx1
lineY2 := cy - ly1
lineLen := lineX1*lineX1 + lineY1*lineY1
// t represents the closest point on the line segment, normalized between 0 and 1
// where zero is the start, and one is end of the line.
t := math.Max(0, math.Min(lineLen, (lineX1*lineX2+lineY1*lineY2))) / lineLen
// Closest point
closestPointX := lx1 + t*lineX1
closestPointY := ly1 + t*lineY1
// Distance betwen closest point and circle center
dist := math.Sqrt((cx-closestPointX)*(cx-closestPointX) + (cy-closestPointY)*(cy-closestPointY))
// Check for collision
if dist <= (cr + lr) {
e.collidingCapsules = append(
e.collidingCapsules,
collidingCapsule{i, lr, dist, Vec2{closestPointX, closestPointY}},
)
// Calculate displacement required
amount := dist - cr - lr
// displace circle away from collision
distanceM := 1.0 / dist // Can be used to multiply instead of divide by dist
e.circles[i].pos.X -= amount * (cx - closestPointX) * distanceM
e.circles[i].pos.Y -= amount * (cy - closestPointY) * distanceM
// TODO: Add ball and line pair to dynamic collisions
}
}
// Rectangle collisions
for j := range e.collisionRects {
upperLeft := e.collisionRects[j].upperLeft
lowerRight := e.collisionRects[j].lowerRight
// nearest point
x := clamp(e.circles[i].pos.X, upperLeft.X, lowerRight.X)
y := clamp(e.circles[i].pos.Y, upperLeft.Y, lowerRight.Y)
nearest := Vec2{x, y}
v := e.circles[i].pos.To(nearest)
dist := v.Len()
if dist < e.circles[i].radius {
// If circle is mostly inside, push nearest point out to nearest edge
// TODO: Move this to dynamic collision resolution section
dTp := math.Abs(upperLeft.Y - y)
dBt := math.Abs(lowerRight.Y - y)
dLf := math.Abs(upperLeft.X - x)
dRt := math.Abs(lowerRight.X - x)
if dTp <= dBt && dTp <= dLf && dTp <= dRt {
y = upperLeft.Y
e.circles[i].vel.Y = -e.circles[i].vel.Y
} else if dBt <= dTp && dBt <= dLf && dBt <= dRt {
y = lowerRight.Y
e.circles[i].vel.Y = -e.circles[i].vel.Y
} else if dLf <= dTp && dLf <= dBt && dLf <= dRt {
x = upperLeft.X
e.circles[i].vel.X = -e.circles[i].vel.X
} else if dRt <= dTp && dRt <= dBt && dRt <= dLf {
x = lowerRight.X
e.circles[i].vel.X = -e.circles[i].vel.X
} else {
x = lowerRight.X
e.circles[i].vel.X = -e.circles[i].vel.X
}
if dist > 0 {
// Circle is mostly outside
// Calculate displacement required
amount := dist - e.circles[i].radius
// displace circle away from collision
e.circles[i].pos = e.circles[i].pos.Add(v.Unit().Scaled(amount))
} else {
nearest = Vec2{x, y}
v = e.circles[i].pos.To(nearest)
dist = v.Len()
// Calculate displacement required
amount := dist + e.circles[i].radius
// displace circle away from collision
e.circles[i].pos = e.circles[i].pos.Add(v.Unit().Scaled(amount))
}
}
}
}
}
func (e *Engine) resolveDynamicCollisions() {
// dynamic collisions
for _, cap := range e.collidingCapsules {
a1 := e.circles[cap.i].area
v2 := e.circles[cap.i].vel.Scaled(-1.0)
a2 := a1
// Normalized
nV := e.circles[cap.i].pos.To(cap.pos).Unit()
// Calculate new velocities from elastic collision
// https://en.wikipedia.org/wiki/Elastic_collision
kV := e.circles[cap.i].vel.Sub(v2)
p := 2.0 * nV.Dot(kV) / (a1 + a2)
e.circles[cap.i].vel = e.circles[cap.i].vel.Sub(nV.Scaled(p).Scaled(a2))
}
for _, pair := range e.collidingPairs {
a1 := e.circles[pair.a].area
a2 := e.circles[pair.b].area
// Normalized
nV := e.circles[pair.a].pos.To(e.circles[pair.b].pos).Unit()
// Calculate new velocities from elastic collision
// https://en.wikipedia.org/wiki/Elastic_collision
kV := e.circles[pair.a].vel.Sub(e.circles[pair.b].vel)
p := 2.0 * nV.Dot(kV) / (a1 + a2)
e.circles[pair.a].vel = e.circles[pair.a].vel.Sub(nV.Scaled(p).Scaled(a2))
e.circles[pair.b].vel = e.circles[pair.b].vel.Add(nV.Scaled(p).Scaled(a1))
}
} | game/physics.go | 0.710528 | 0.474814 | physics.go | starcoder |
package mlpack
/*
#cgo CFLAGS: -I./capi -Wall
#cgo LDFLAGS: -L. -lmlpack_go_adaboost
#include <capi/adaboost.h>
#include <stdlib.h>
*/
import "C"
import "gonum.org/v1/gonum/mat"
type AdaboostOptionalParam struct {
InputModel *adaBoostModel
Iterations int
Labels *mat.Dense
Test *mat.Dense
Tolerance float64
Training *mat.Dense
Verbose bool
WeakLearner string
}
func AdaboostOptions() *AdaboostOptionalParam {
return &AdaboostOptionalParam{
InputModel: nil,
Iterations: 1000,
Labels: nil,
Test: nil,
Tolerance: 1e-10,
Training: nil,
Verbose: false,
WeakLearner: "decision_stump",
}
}
/*
This program implements the AdaBoost (or Adaptive Boosting) algorithm. The
variant of AdaBoost implemented here is AdaBoost.MH. It uses a weak learner,
either decision stumps or perceptrons, and over many iterations, creates a
strong learner that is a weighted ensemble of weak learners. It runs these
iterations until a tolerance value is crossed for change in the value of the
weighted training error.
For more information about the algorithm, see the paper "Improved Boosting
Algorithms Using Confidence-Rated Predictions", by <NAME> and <NAME>.
This program allows training of an AdaBoost model, and then application of
that model to a test dataset. To train a model, a dataset must be passed with
the "Training" option. Labels can be given with the "Labels" option; if no
labels are specified, the labels will be assumed to be the last column of the
input dataset. Alternately, an AdaBoost model may be loaded with the
"InputModel" option.
Once a model is trained or loaded, it may be used to provide class predictions
for a given test dataset. A test dataset may be specified with the "Test"
parameter. The predicted classes for each point in the test dataset are
output to the "Predictions" output parameter. The AdaBoost model itself is
output to the "OutputModel" output parameter.
Note: the following parameter is deprecated and will be removed in mlpack
4.0.0: "Output".
Use "Predictions" instead of "Output".
For example, to run AdaBoost on an input dataset data with labels labelsand
perceptrons as the weak learner type, storing the trained model in model, one
could use the following command:
// Initialize optional parameters for Adaboost().
param := mlpack.AdaboostOptions()
param.Training = data
param.Labels = labels
param.WeakLearner = "perceptron"
_, model, _, _ := mlpack.Adaboost(param)
Similarly, an already-trained model in model can be used to provide class
predictions from test data test_data and store the output in predictions with
the following command:
// Initialize optional parameters for Adaboost().
param := mlpack.AdaboostOptions()
param.InputModel = &model
param.Test = test_data
_, _, predictions, _ := mlpack.Adaboost(param)
Input parameters:
- InputModel (adaBoostModel): Input AdaBoost model.
- Iterations (int): The maximum number of boosting iterations to be run
(0 will run until convergence.) Default value 1000.
- Labels (mat.Dense): Labels for the training set.
- Test (mat.Dense): Test dataset.
- Tolerance (float64): The tolerance for change in values of the
weighted error during training. Default value 1e-10.
- Training (mat.Dense): Dataset for training AdaBoost.
- Verbose (bool): Display informational messages and the full list of
parameters and timers at the end of execution.
- WeakLearner (string): The type of weak learner to use:
'decision_stump', or 'perceptron'. Default value 'decision_stump'.
Output parameters:
- output (mat.Dense): Predicted labels for the test set.
- outputModel (adaBoostModel): Output trained AdaBoost model.
- predictions (mat.Dense): Predicted labels for the test set.
- probabilities (mat.Dense): Predicted class probabilities for each
point in the test set.
*/
func Adaboost(param *AdaboostOptionalParam) (*mat.Dense, adaBoostModel, *mat.Dense, *mat.Dense) {
resetTimers()
enableTimers()
disableBacktrace()
disableVerbose()
restoreSettings("AdaBoost")
// Detect if the parameter was passed; set if so.
if param.InputModel != nil {
setAdaBoostModel("input_model", param.InputModel)
setPassed("input_model")
}
// Detect if the parameter was passed; set if so.
if param.Iterations != 1000 {
setParamInt("iterations", param.Iterations)
setPassed("iterations")
}
// Detect if the parameter was passed; set if so.
if param.Labels != nil {
gonumToArmaUrow("labels", param.Labels)
setPassed("labels")
}
// Detect if the parameter was passed; set if so.
if param.Test != nil {
gonumToArmaMat("test", param.Test)
setPassed("test")
}
// Detect if the parameter was passed; set if so.
if param.Tolerance != 1e-10 {
setParamDouble("tolerance", param.Tolerance)
setPassed("tolerance")
}
// Detect if the parameter was passed; set if so.
if param.Training != nil {
gonumToArmaMat("training", param.Training)
setPassed("training")
}
// Detect if the parameter was passed; set if so.
if param.Verbose != false {
setParamBool("verbose", param.Verbose)
setPassed("verbose")
enableVerbose()
}
// Detect if the parameter was passed; set if so.
if param.WeakLearner != "decision_stump" {
setParamString("weak_learner", param.WeakLearner)
setPassed("weak_learner")
}
// Mark all output options as passed.
setPassed("output")
setPassed("output_model")
setPassed("predictions")
setPassed("probabilities")
// Call the mlpack program.
C.mlpackAdaboost()
// Initialize result variable and get output.
var outputPtr mlpackArma
output := outputPtr.armaToGonumUrow("output")
var outputModel adaBoostModel
outputModel.getAdaBoostModel("output_model")
var predictionsPtr mlpackArma
predictions := predictionsPtr.armaToGonumUrow("predictions")
var probabilitiesPtr mlpackArma
probabilities := probabilitiesPtr.armaToGonumMat("probabilities")
// Clear settings.
clearSettings()
// Return output(s).
return output, outputModel, predictions, probabilities
} | adaboost.go | 0.756717 | 0.464234 | adaboost.go | starcoder |
package optimization
import "fmt"
type (
Grid struct {
NumX int `json:"num_x"`
NumY int `json:"num_y"`
NumZ int `json:"num_z"`
MinX float64 `json:"min_x"`
MinY float64 `json:"min_y"`
MinZ float64 `json:"min_z"`
SizX float64 `json:"siz_x"`
SizY float64 `json:"siz_y"`
SizZ float64 `json:"siz_z"`
gridcnt int
}
)
func (this *Grid) adjust4gslib() {
this.MinX = this.SizX / 2.0
this.MinY = this.SizY / 2.0
this.MinZ = this.SizZ / 2.0
}
/**
* Params:
* k = The one dimensional Grid index.
* Returns: The Grid index in the x direction
*/
func (this *Grid) gridIx(k int) int {
return (k % (this.NumX * this.NumY)) % this.NumX
}
/**
* Params:
* k = The one dimensional Grid index.
* Returns: The Grid index in the y direction
*/
func (this *Grid) gridIy(k int) int {
return (k % (this.NumX * this.NumY)) / this.NumX
}
/**
* Params:
* k = The one dimensional Grid index.
* Returns: The Grid index in the z direction
*/
func (this *Grid) gridIz(k int) int {
return k / (this.NumX * this.NumY)
}
/**
* Params:
* ix = The Grid index in the x direction
* iy = The Grid index in the y direction
* iz = The Grid index in the z direction
* Returns: The one dimensional Grid index.
*/
func (this *Grid) gridIndex(ix, iy, iz int) int {
return (ix + iy*this.NumX + iz*this.NumX*this.NumY)
}
func (this *Grid) gridIndex2(ids []int) int {
return this.gridIndex(ids[0], ids[1], ids[2])
}
/**
* Params:
* k = The one dimensional Grid index.
* x = The test point x coordinate
* y = The test point y coordinate
* z = The test point z coordinate
* Returns: True if x, y, z is within the block.
*/
func (this *Grid) gridPointInCell(k int, x, y, z float64) bool {
xn := x - (float64(this.gridIx(k))*this.SizX + this.MinX)
yn := y - (float64(this.gridIy(k))*this.SizY + this.MinY)
zn := z - (float64(this.gridIz(k))*this.SizZ + this.MinZ)
retval := ((0.0 <= xn) && (xn < this.SizX))
retval = retval && ((0.0 <= yn) && (yn < this.SizY))
retval = retval && ((0.0 <= zn) && (zn < this.SizZ))
return retval
}
// Write the Grid definition to standard output.
func (this *Grid) String() string {
retval := fmt.Sprintf("x =%7d %12.1f %10.1f\n", this.NumX, this.MinX, this.SizX)
retval += fmt.Sprintf("y =%7d %12.1f %10.1f\n", this.NumY, this.MinY, this.SizY)
retval += fmt.Sprintf("z =%7d %12.1f %10.1f", this.NumZ, this.MinZ, this.SizZ)
return retval
}
// The number of blocks
func (this *Grid) gridCount() int {
if this.gridcnt <= 0 {
this.gridcnt = this.NumX * this.NumY * this.NumZ
}
return this.gridcnt
}
// The Grid's bounding axis aligned bounding box
func (this *Grid) aabb() [6]float64 {
retval := [6]float64{
this.MinX,
this.MinY,
this.MinZ,
this.MinX + float64(this.NumX)*this.SizX,
this.MinY + float64(this.NumY)*this.SizY,
this.MinZ + float64(this.NumZ)*this.SizZ,
}
return retval
}
func (this *Grid) blockAABB(k int) [6]float64 {
centroid := this.blockCentroid2(k)
halfsiz_x := this.SizX / 2.0
halfsiz_y := this.SizY / 2.0
halfsiz_z := this.SizZ / 2.0
AABB := [6]float64{
centroid[0] - halfsiz_x,
centroid[1] - halfsiz_y,
centroid[2] - halfsiz_z,
centroid[0] + halfsiz_x,
centroid[1] + halfsiz_y,
centroid[2] + halfsiz_z,
}
return AABB
}
/**
* Params:
* k = The one dimensional Grid index.
* Returns: The centroid as [x, y, z]
*/
func (this *Grid) blockCentroid(i, j, k int) [3]float64 {
return [3]float64{
float64(i)*this.SizX + this.MinX + this.SizX/2.0,
float64(j)*this.SizY + this.MinY + this.SizY/2.0,
float64(k)*this.SizZ + this.MinZ + this.SizZ/2.0,
}
}
func (this *Grid) blockCentroid2(k int) [3]float64 {
return this.blockCentroid(this.gridIx(k), this.gridIy(k), this.gridIz(k))
} | optimization/grid.go | 0.85814 | 0.484258 | grid.go | starcoder |
package main
import (
"fmt"
"log"
"math/rand"
"time"
ui "github.com/gizak/termui"
"github.com/gizak/termui/widgets"
)
const (
// Number of agents in the market
numOfAgents = 10
// Initial amount of money that each agent owns
initialWealth = 100.0
// How many trades to simulate
rounds = 10000
// If the poorer agent gains wealth it is this percentage of their total wealth.
percentGain = 0.20
// If the poorer agent loses wealth, it is this percentage of their total wealth.
percentLoss = 0.17
)
// Agents are defined by the amount of money, or wealth, they have.
type agents []float64
// pickTwoRandomAgents generates two random numbers `sender` and `receiver` between 0 and numOfAgents-1
// and ensures that `sender` and `receiver` are not equal. (After all, agents would not trade with themselves.)
// Note the use of named return values that saves an extra declaration of `receiver` outside the loop
// (to avoid that `receiver` exists only in the scope of the loop).
func pickTwoRandomAgents() (sender, receiver int) {
sender = rand.Intn(numOfAgents)
receiver = sender
// Generate a random`receiver`. Repeat until `receiver` != `sender`
for receiver == sender {
receiver = rand.Intn(numOfAgents)
}
return sender, receiver
}
// The trading formula assumes that agents sometimes pay either more or less than the traded good is worth.
// Because of this, wealth flows from one agent to another.
// As both agents `sender`, `receiver` were already chosen randomly, we can decide at this point that agent `sender` always loses
// wealth, and agent `receiver` always gains wealth in this transaction.
// Note: the agents
func trade(a agents, sender, receiver int) {
// Wealth flows from sender to `receiver` in this transaction.
// The amount that flows from sender to `receiver` is always a given percentage of the poorer agent.
// If`receiver` is the poorer agent, the gain is `percentGain` of `receiver`'s total wealth.
transfer := a[receiver] * percentGain
// If `sender` is the poorer agent, the loss is `percentLoss` of `sender`'s total wealth.
if a[sender] < a[receiver] {
transfer = a[sender] * percentLoss
}
// It's a deal!
a[sender] -= transfer
a[receiver] += transfer
}
// Draw a bar chart of the current wealth of all agents
func drawChart(a agents, bc *widgets.BarChart) {
bc.Data = a
// Scale the bar chart dynamically, to better see
// the distribution when the current maximum wealth is
// much smaller than the maximum possible wealth.
maxPossibleWealth := initialWealth * numOfAgents
currentMaxWealth, _ := ui.GetMaxFloat64FromSlice(a)
bc.MaxVal = currentMaxWealth + (maxPossibleWealth-currentMaxWealth)*0.05
ui.Render(bc)
}
// Run the simulation
func run(a agents, bc *widgets.BarChart, done <-chan struct{}) {
for n := 0; n < rounds; n++ {
// Pick two different agents.
sender, receiver := pickTwoRandomAgents()
// Have them do a trade.
trade(a, sender, receiver)
// Update the chart
drawChart(a, bc)
// Try to read a value from channel `done`.
// The read shall not block, hence it is enclosed in a
// select block with a default clause.
select {
case <-done:
// At this point, the done channel has unblocked and emitted a zero value. Leave the simulation loop.
return
default:
}
}
}
func main() {
// Setup
// Pre-allocate the slice, to avoid allocations during the simulation
a := make(agents, numOfAgents)
// Set a random seed
rand.Seed(time.Now().UnixNano())
for i := range a {
// All agents start with the same amount of money.
a[i] = initialWealth
}
// UI setup. `gizak/termui` makes rendering a bar chart in a terminal super easy.
err := ui.Init()
if err != nil {
log.Fatalln(err)
}
defer ui.Close()
bc := widgets.NewBarChart()
bc.Title = "Agents' Wealth"
bc.BarWidth = 5
bc.SetRect(5, 5, 10+(bc.BarWidth+1)*numOfAgents, 25)
bc.LabelStyles = []ui.Style{ui.NewStyle(ui.ColorBlue)}
bc.NumStyles = []ui.Style{ui.NewStyle(ui.ColorBlack)}
bc.NumFormatter = func(n float64) string {
return fmt.Sprintf("%3.1f", n)
}
// Start rendering.
ui.Render(bc)
// `termui` has its own event polling.
// We use this here to watch for a key press
// to end the simulation
done := make(chan struct{})
go func(done chan<- struct{}) {
for e := range ui.PollEvents() {
if e.Type == ui.KeyboardEvent {
// Unblock the channel by closing it
// After closing the channel, it emits zero values upon reading.
close(done)
return
}
}
}(done)
// Start the simulation!
run(a, bc, done)
// After the simulation, wait for a key press
// so that the final chart remains visible.
<-done
} | rich.go | 0.674158 | 0.480113 | rich.go | starcoder |
package main
import (
"fmt"
"log"
"math"
"os"
"github.com/millere/nonlinear"
)
func main() {
maxIterations := 10000
useBisection(maxIterations)
useChord(maxIterations)
useNewton(maxIterations)
useSecant(maxIterations)
useShamanskii(maxIterations, 3)
}
// fns is a slice containing each function, its derivative, and the given x0.
var fns = []struct {
f, df func(float64) float64
x0 float64
}{
{func(x float64) float64 { return sin(x) }, func(x float64) float64 { return cos(x) }, 2.9},
{func(x float64) float64 { return x - cos(x) }, func(x float64) float64 { return 1 + sin(x) }, 1},
{func(x float64) float64 { return atan(x) }, func(x float64) float64 { return 1 / (sq(x) + 1) }, 1},
{func(x float64) float64 { return atan(x) }, func(x float64) float64 { return 1 / (sq(x) + 1) }, 12},
{func(x float64) float64 { return sq(x) + 3 }, func(x float64) float64 { return 2 * x }, 10},
{func(x float64) float64 { return math.Pow(x-2, 3) }, func(x float64) float64 { return 3 * sq(x-2) }, 1.5},
}
// because some methods require multiple initial iterates, x2s holds those.
// x2s[i] is x1 for the ith equation in fns
var x2s = []float64{3.5, 0.0, -1.0, -1.0, -1.0, 3.0}
func useBisection(maxIterations int) {
fmt.Println("Using Bisection Method")
for i, c := range fns {
x, xs, evals := nonlinear.Bisect(c.f, c.x0, x2s[i], math.Pow(10, -12), maxIterations)
convergenceRate := nonlinear.ConvergenceRate(evals)
fmt.Printf("%c: %E (converging at %f)\n", i+'A', x, convergenceRate)
f, err := os.Create(fmt.Sprintf("bisection-%c.csv", i+'A'))
if err != nil {
log.Println("Unable to create", i+'A', err)
}
if err := writeResults(f, xs, evals); err != nil {
log.Println("Unable to write", i+'A', err)
}
}
}
func useChord(maxIterations int) {
fmt.Println("Using Chord Method")
for i, c := range fns {
x, xs, evals := nonlinear.Chord(c.f, c.df, c.x0, math.Pow(10, -12), maxIterations)
convergenceRate := nonlinear.ConvergenceRate(evals)
fmt.Printf("%c: %E (converging at %f)\n", i+'A', x, convergenceRate)
f, err := os.Create(fmt.Sprintf("chord-%c.csv", i+'A'))
if err != nil {
log.Println("Unable to create", i+'A', err)
}
if err := writeResults(f, xs, evals); err != nil {
log.Println("Unable to write", i+'A', err)
}
}
}
func useNewton(maxIterations int) {
fmt.Println("Using Newton's Method")
for i, c := range fns {
x, xs, evals := nonlinear.Newton(c.f, c.df, c.x0, math.Pow(10, -12), maxIterations)
convergenceRate := nonlinear.ConvergenceRate(evals)
fmt.Printf("%c: %E (converging at %f)\n", i+'A', x, convergenceRate)
f, err := os.Create(fmt.Sprintf("newton-%c.csv", i+'A'))
if err != nil {
log.Println("Unable to create", i+'A', err)
}
if err := writeResults(f, xs, evals); err != nil {
log.Println("Unable to write", i+'A', err)
}
}
}
func useSecant(maxIterations int) {
fmt.Println("Using Secant Method")
for i, c := range fns {
x, xs, evals := nonlinear.Secant(c.f, c.x0, x2s[i], math.Pow(10, -12), maxIterations)
convergenceRate := nonlinear.ConvergenceRate(evals)
fmt.Printf("%c: %E (converging at %f)\n", i+'A', x, convergenceRate)
f, err := os.Create(fmt.Sprintf("secant-%c.csv", i+'A'))
if err != nil {
log.Println("Unable to create", i+'A', err)
}
if err := writeResults(f, xs, evals); err != nil {
log.Println("Unable to write", i+'A', err)
}
}
}
func useShamanskii(maxIterations, n int) {
fmt.Println("Using Shamanskii's Method (n = 3)")
for i, c := range fns {
x, xs, evals := nonlinear.Shamanskii(c.f, c.df, n, c.x0, math.Pow(10, -12), maxIterations)
convergenceRate := nonlinear.ConvergenceRate(evals)
fmt.Printf("%c: %E (converging at %f)\n", i+'A', x, convergenceRate)
f, err := os.Create(fmt.Sprintf("shamanskii-%c.csv", i+'A'))
if err != nil {
log.Println("Unable to create", i+'A', err)
}
if err := writeResults(f, xs, evals); err != nil {
log.Println("Unable to write", i+'A', err)
}
}
} | project/main.go | 0.511473 | 0.407274 | main.go | starcoder |
package math
import "github.com/g3n/engine/math32"
type Line2 struct {
A *math32.Vector2
B *math32.Vector2
}
func NewLine2(a, b *math32.Vector2) *Line2 {
return &Line2{
A: a,
B: b,
}
}
func (l *Line2) Intersects(other *Line2) (bool, *math32.Vector2) {
a1 := l.B.Y - l.A.Y
b1 := l.A.X - l.B.X
c1 := a1*l.A.X + b1*l.A.Y
a2 := other.B.Y - other.A.Y
b2 := other.A.X - other.B.X
c2 := a2*other.A.X + b2*other.A.Y
denominator := a1*b2 - a2*b1
if denominator == 0 {
// parallel or collinear
return false, nil
}
minX := math32.Min(l.A.X, l.B.X)
maxX := math32.Max(l.A.X, l.B.X)
minY := math32.Min(l.A.Y, l.B.Y)
maxY := math32.Max(l.A.Y, l.B.Y)
intersectX := (b2*c1 - b1*c2) / denominator
intersectY := (a1*c2 - a2*c1) / denominator
rx0 := (intersectX - l.A.X) / (l.B.X - l.A.X)
ry0 := (intersectY - l.A.Y) / (l.B.Y - l.A.Y)
rx1 := (intersectX - other.A.X) / (other.B.X - other.A.X)
ry1 := (intersectY - other.A.Y) / (other.B.Y - other.A.Y)
if ((rx0 >= 0 && rx0 <= 1) || (ry0 >= 0 && ry0 <= 1)) &&
((rx1 >= 0 && rx1 <= 1) || (ry1 >= 0 && ry1 <= 1)) &&
intersectX >= minX && intersectX <= maxX &&
intersectY >= minY && intersectY <= maxY {
return true, math32.NewVector2(intersectX, intersectY)
}
return false, nil
}
// Checks if Line intersects triangle and returns the collision vectors
func (l *Line2) IntersectsTriangle(triangle *Triangle2) (intersects bool, collisions []*math32.Vector2) {
l1 := Line2{
A: triangle.A,
B: triangle.B,
}
l2 := Line2{
A: triangle.B,
B: triangle.C,
}
l3 := Line2{
A: triangle.A,
B: triangle.C,
}
intersectsL1, p1 := l.Intersects(&l1)
intersectsL2, p2 := l.Intersects(&l2)
intersectsL3, p3 := l.Intersects(&l3)
intersects = intersectsL1 || intersectsL2 || intersectsL3
if p1 != nil {
collisions = append(collisions, p1)
}
if p2 != nil {
collisions = append(collisions, p2)
}
if p3 != nil {
collisions = append(collisions, p3)
}
return
}
// Checks if Line intersects rectangle and returns the collision vectors
func (l *Line2) IntersectsRectangle(rect *Rectangle) (intersects bool, collisions []*math32.Vector2) {
vertices := rect.Vertices()
/*
1---3
| |
0---2
*/
l1 := Line2{
A: vertices[0],
B: vertices[1],
}
l2 := Line2{
A: vertices[0],
B: vertices[2],
}
l3 := Line2{
A: vertices[1],
B: vertices[3],
}
l4 := Line2{
A: vertices[2],
B: vertices[3],
}
intersectsL1, p1 := l.Intersects(&l1)
intersectsL2, p2 := l.Intersects(&l2)
intersectsL3, p3 := l.Intersects(&l3)
intersectsL4, p4 := l.Intersects(&l4)
intersects = intersectsL1 || intersectsL2 || intersectsL3 || intersectsL4
if p1 != nil {
collisions = append(collisions, p1)
}
if p2 != nil {
collisions = append(collisions, p2)
}
if p3 != nil {
collisions = append(collisions, p3)
}
if p4 != nil {
collisions = append(collisions, p4)
}
return
} | math/line.go | 0.848031 | 0.607925 | line.go | starcoder |
package il
import (
"fmt"
)
// Builder is used for building function bodies in a programmatic way.
type Builder struct {
strings *StringTable
body []uint32
labels map[string]uint32
fixups map[string][]uint32
}
// NewBuilder creates a new Builder instance. It uses the given StringTable when it needs to
// allocate ids for strings.
func NewBuilder(s *StringTable) *Builder {
return &Builder{
strings: s,
body: make([]uint32, 0, 32),
// labels maps the label name to the target address. If the position is not set yet, then
// the label position should be marked as 0, and any usages of the labels needs to be
// fixed up.
labels: make(map[string]uint32),
// fixups holds the bytecode locations that needs to be updated once a label position is set.
fixups: make(map[string][]uint32),
}
}
// Build completes building a function body and returns the accumulated byte code.
func (f *Builder) Build() []uint32 {
return f.body
}
// Nop appends the "nop" instruction to the byte code.
func (f *Builder) Nop() {
f.op0(Nop)
}
// Ret appends the "ret" instruction to the byte code.
func (f *Builder) Ret() {
f.op0(Ret)
}
// Call appends the "call" instruction to the byte code.
func (f *Builder) Call(fnName string) {
f.op1(Call, f.id(fnName))
}
// ResolveInt appends the "resolve_i" instruction to the byte code.
func (f *Builder) ResolveInt(n string) {
f.op1(ResolveI, f.id(n))
}
// TResolveInt appends the "tresolve_i" instruction to the byte code.
func (f *Builder) TResolveInt(n string) {
f.op1(TResolveI, f.id(n))
}
// ResolveString appends the "resolve_s" instruction to the byte code.
func (f *Builder) ResolveString(n string) {
f.op1(ResolveS, f.id(n))
}
// TResolveString appends the "tresolve_s" instruction to the byte code.
func (f *Builder) TResolveString(n string) {
f.op1(TResolveS, f.id(n))
}
// ResolveBool appends the "resolve_b" instruction to the byte code.
func (f *Builder) ResolveBool(n string) {
f.op1(ResolveB, f.id(n))
}
// TResolveBool appends the "tresolve_b" instruction to the byte code.
func (f *Builder) TResolveBool(n string) {
f.op1(TResolveB, f.id(n))
}
// ResolveDouble appends the "resolve_d" instruction to the byte code.
func (f *Builder) ResolveDouble(n string) {
f.op1(ResolveD, f.id(n))
}
// TResolveDouble appends the "tresolve_d" instruction to the byte code.
func (f *Builder) TResolveDouble(n string) {
f.op1(TResolveD, f.id(n))
}
// ResolveInterface appends the "resolve_f" instruction to the byte code.
func (f *Builder) ResolveInterface(n string) {
f.op1(ResolveF, f.id(n))
}
// TResolveInterface appends the "tresolve_f" instruction to the byte code.
func (f *Builder) TResolveInterface(n string) {
f.op1(TResolveF, f.id(n))
}
// APushBool appends the "apush_b" instruction to the byte code.
func (f *Builder) APushBool(b bool) {
f.op1(APushB, BoolToByteCode(b))
}
// APushStr appends the "apush_s" instruction to the byte code.
func (f *Builder) APushStr(s string) {
f.op1(APushS, f.id(s))
}
// APushInt appends the "apush_i" instruction to the byte code.
func (f *Builder) APushInt(i int64) {
a1, a2 := IntegerToByteCode(i)
f.op2(APushI, a1, a2)
}
// APushDouble appends the "apush_d" instruction to the byte code.
func (f *Builder) APushDouble(n float64) {
a1, a2 := DoubleToByteCode(n)
f.op2(APushD, a1, a2)
}
// Xor appends the "xor" instruction to the byte code.
func (f *Builder) Xor() {
f.op0(Xor)
}
// EQString appends the "eq_s" instruction to the byte code.
func (f *Builder) EQString() {
f.op0(EqS)
}
// AEQString appends the "ieq_s" instruction to the byte code.
func (f *Builder) AEQString(v string) {
f.op1(AEqS, f.id(v))
}
// LTString appends the "lt_s" instruction to the byte code.
func (f *Builder) LTString() {
f.op0(LtS)
}
// LTInteger appends the "lt_i" instruction to the byte code.
func (f *Builder) LTInteger() {
f.op0(LtI)
}
// LTDouble appends the "lt_d" instruction to the byte code.
func (f *Builder) LTDouble() {
f.op0(LtD)
}
// ALTString appends the "alt_s" instruction to the byte code.
func (f *Builder) ALTString(v string) {
f.op1(ALtS, f.id(v))
}
// ALTInteger appends the "alt_i" instruction to the byte code.
func (f *Builder) ALTInteger(v int64) {
a1, a2 := IntegerToByteCode(v)
f.op2(ALtI, a1, a2)
}
// ALTDouble appends the "alt_d" instruction to the byte code.
func (f *Builder) ALTDouble(v float64) {
a1, a2 := DoubleToByteCode(v)
f.op2(ALtD, a1, a2)
}
// LEString appends the "le_s" instruction to the byte code.
func (f *Builder) LEString() {
f.op0(LeS)
}
// LEInteger appends the "le_i" instruction to the byte code.
func (f *Builder) LEInteger() {
f.op0(LeI)
}
// LEDouble appends the "le_d" instruction to the byte code.
func (f *Builder) LEDouble() {
f.op0(LeD)
}
// ALEString appends the "ale_s" instruction to the byte code.
func (f *Builder) ALEString(v string) {
f.op1(ALeS, f.id(v))
}
// ALEInteger appends the "ale_i" instruction to the byte code.
func (f *Builder) ALEInteger(v int64) {
a1, a2 := IntegerToByteCode(v)
f.op2(ALeI, a1, a2)
}
// ALEDouble appends the "ale_d" instruction to the byte code.
func (f *Builder) ALEDouble(v float64) {
a1, a2 := DoubleToByteCode(v)
f.op2(ALeD, a1, a2)
}
// GTString appends the "gt_s" instruction to the byte code.
func (f *Builder) GTString() {
f.op0(GtS)
}
// GTInteger appends the "gt_i" instruction to the byte code.
func (f *Builder) GTInteger() {
f.op0(GtI)
}
// GTDouble appends the "gt_d" instruction to the byte code.
func (f *Builder) GTDouble() {
f.op0(GtD)
}
// AGTString appends the "agt_s" instruction to the byte code.
func (f *Builder) AGTString(v string) {
f.op1(AGtS, f.id(v))
}
// AGTInteger appends the "agt_i" instruction to the byte code.
func (f *Builder) AGTInteger(v int64) {
a1, a2 := IntegerToByteCode(v)
f.op2(AGtI, a1, a2)
}
// AGTDouble appends the "agt_d" instruction to the byte code.
func (f *Builder) AGTDouble(v float64) {
a1, a2 := DoubleToByteCode(v)
f.op2(AGtD, a1, a2)
}
// GEString appends the "ge_s" instruction to the byte code.
func (f *Builder) GEString() {
f.op0(GeS)
}
// GEInteger appends the "ge_i" instruction to the byte code.
func (f *Builder) GEInteger() {
f.op0(GeI)
}
// GEDouble appends the "ge_d" instruction to the byte code.
func (f *Builder) GEDouble() {
f.op0(GeD)
}
// AGEString appends the "age_s" instruction to the byte code.
func (f *Builder) AGEString(v string) {
f.op1(AGeS, f.id(v))
}
// AGEInteger appends the "age_d" instruction to the byte code.
func (f *Builder) AGEInteger(v int64) {
a1, a2 := IntegerToByteCode(v)
f.op2(AGeI, a1, a2)
}
// AGEDouble appends the "age_i" instruction to the byte code.
func (f *Builder) AGEDouble(v float64) {
a1, a2 := DoubleToByteCode(v)
f.op2(AGeD, a1, a2)
}
// EQBool appends the "eq_b" instruction to the byte code.
func (f *Builder) EQBool() {
f.op0(EqB)
}
// AEQBool appends the "ieq_b" instruction to the byte code.
func (f *Builder) AEQBool(v bool) {
f.op1(AEqB, BoolToByteCode(v))
}
// EQInteger appends the "eq_i" instruction to the byte code.
func (f *Builder) EQInteger() {
f.op0(EqI)
}
// AEQInteger appends the "eq_i" instruction to the byte code.
func (f *Builder) AEQInteger(v int64) {
a1, a2 := IntegerToByteCode(v)
f.op2(AEqI, a1, a2)
}
// EQDouble appends the "eq_d" instruction to the byte code.
func (f *Builder) EQDouble() {
f.op0(EqD)
}
// AEQDouble appends the "ieq_d" instruction to the byte code.
func (f *Builder) AEQDouble(v float64) {
a1, a2 := DoubleToByteCode(v)
f.op2(AEqD, a1, a2)
}
// Not appends the "not" instruction to the byte code.
func (f *Builder) Not() {
f.op0(Not)
}
// Or appends the "or" instruction to the byte code.
func (f *Builder) Or() {
f.op0(Or)
}
// And appends the "and" instruction to the byte code.
func (f *Builder) And() {
f.op0(And)
}
// Lookup appends the "lookup" instruction to the byte code.
func (f *Builder) Lookup() {
f.op0(Lookup)
}
// NLookup appends the "nlookup" instruction to the byte code.
func (f *Builder) NLookup() {
f.op0(NLookup)
}
// TLookup appends the "tlookup" instruction to the byte code.
func (f *Builder) TLookup() {
f.op0(TLookup)
}
// ALookup appends the "alookup" instruction to the byte code.
func (f *Builder) ALookup(v string) {
f.op1(ALookup, f.id(v))
}
// ANLookup appends the "anlookup" instruction to the byte code.
func (f *Builder) ANLookup(v string) {
f.op1(ANLookup, f.id(v))
}
// AllocateLabel allocates a new label value for use within the code.
func (f *Builder) AllocateLabel() string {
l := fmt.Sprintf("L%d", len(f.labels)+len(f.fixups))
f.fixups[l] = []uint32{}
return l
}
// SetLabelPos puts the label position at the current bytecode point that builder is pointing at.
// Panics if the label position was already set.
func (f *Builder) SetLabelPos(label string) {
if _, exists := f.labels[label]; exists {
panic("il.Builder: setting the label position twice.")
}
adr := uint32(len(f.body))
f.labels[label] = adr
if fixups, found := f.fixups[label]; found {
for _, fixup := range fixups {
f.body[fixup] = adr
}
delete(f.fixups, label)
}
}
// Jz appends the "jz" instruction to the byte code, against the given label.
func (f *Builder) Jz(label string) {
f.jump(Jz, label)
}
// Jnz appends the "jnz" instruction to the byte code, against the given label.
func (f *Builder) Jnz(label string) {
f.jump(Jnz, label)
}
// Jmp appends the "jmp" instruction to the byte code, against the given label.
func (f *Builder) Jmp(label string) {
f.jump(Jmp, label)
}
// AddString appends the "add_s" instruction to the byte code.
func (f *Builder) AddString() {
f.op0(AddS)
}
// AddDouble appends the "add_d" instruction to the byte code.
func (f *Builder) AddDouble() {
f.op0(AddD)
}
// AddInteger appends the "add_i" instruction to the byte code.
func (f *Builder) AddInteger() {
f.op0(AddI)
}
// SizeString appends the "size_s" instruction to the byte code.
func (f *Builder) SizeString() {
f.op0(SizeS)
}
func (f *Builder) jump(op Opcode, label string) {
adr, exists := f.labels[label]
if !exists {
adr = 0
}
f.op1(op, adr)
if adr == 0 {
fixup := uint32(len(f.body) - 1)
f.fixups[label] = append(f.fixups[label], fixup)
}
}
// op0 inserts a 0-arg opcode into the body.
func (f *Builder) op0(op Opcode) {
f.body = append(f.body, uint32(op))
}
// op1 inserts a 1-arg opcode into the body.
func (f *Builder) op1(op Opcode, p1 uint32) {
f.body = append(f.body, uint32(op), p1)
}
// op2 inserts a 2-arg opcode into the body.
func (f *Builder) op2(op Opcode, p1 uint32, p2 uint32) {
f.body = append(f.body, uint32(op), p1, p2)
}
func (f *Builder) id(s string) uint32 {
return f.strings.Add(s)
} | mixer/pkg/il/builder.go | 0.675229 | 0.41401 | builder.go | starcoder |
package characterdisplay
// Controller is an interface that describes the basic functionality of a character
// display controller.
type Controller interface {
DisplayOff() error // turns the display off
DisplayOn() error // turns the display on
CursorOff() error // sets the cursor visibility to off
CursorOn() error // sets the cursor visibility to on
BlinkOff() error // sets the cursor blink off
BlinkOn() error // sets the cursor blink on
ShiftLeft() error // moves the cursor and text one column to the left
ShiftRight() error // moves the cursor and text one column to the right
BacklightOff() error // turns the display backlight off
BacklightOn() error // turns the display backlight on
Home() error // moves the cursor to the home position
Clear() error // clears the display and moves the cursor to the home position
WriteChar(byte) error // writes a character to the display
SetCursor(col, row int) error // sets the cursor position
Close() error // closes the controller resources
}
// Display represents an abstract character display and provides a
// ease-of-use layer on top of a character display controller.
type Display struct {
Controller
cols, rows int
p *position
}
type position struct {
col int
row int
}
// New creates a new Display
func New(controller Controller, cols, rows int) *Display {
return &Display{
Controller: controller,
cols: cols,
rows: rows,
p: &position{0, 0},
}
}
// Home moves the cursor and all characters to the home position.
func (disp *Display) Home() error {
disp.setCurrentPosition(0, 0)
return disp.Controller.Home()
}
// Clear clears the display, preserving the mode settings and setting the correct home.
func (disp *Display) Clear() error {
disp.setCurrentPosition(0, 0)
return disp.Controller.Clear()
}
// Message prints the given string on the display, including interpreting newline
// characters and wrapping at the end of lines.
func (disp *Display) Message(message string) error {
bytes := []byte(message)
for _, b := range bytes {
if b == byte('\n') {
err := disp.Newline()
if err != nil {
return err
}
continue
}
err := disp.WriteChar(b)
if err != nil {
return err
}
disp.p.col++
if disp.p.col >= disp.cols || disp.p.col < 0 {
err := disp.Newline()
if err != nil {
return err
}
}
}
return nil
}
// Newline moves the input cursor to the beginning of the next line.
func (disp *Display) Newline() error {
return disp.SetCursor(0, disp.p.row+1)
}
// SetCursor sets the input cursor to the given position.
func (disp *Display) SetCursor(col, row int) error {
if row >= disp.rows {
row = disp.rows - 1
}
disp.setCurrentPosition(col, row)
return disp.Controller.SetCursor(col, row)
}
func (disp *Display) setCurrentPosition(col, row int) {
disp.p.col = col
disp.p.row = row
} | interface/display/characterdisplay/characterdisplay.go | 0.721253 | 0.4184 | characterdisplay.go | starcoder |
package probe
import (
"aoc2021/pkg/io"
"aoc2021/pkg/numbers"
"strconv"
"strings"
)
type Probe struct {
Position numbers.Vector2
Velocity numbers.Vector2
}
type TargetArea struct {
Start numbers.Vector2
End numbers.Vector2
}
type ProbeData struct {
Target TargetArea
}
func ReadProbeData(file string) ProbeData {
var pd ProbeData
for _, line := range io.ReadLines(file) {
data := strings.SplitN(line, ": ", 2)
if data[0] == "target area" {
data = strings.SplitN(data[1], ", ", 2)
// Let's just assume fixed layout to make this quicker
xd := strings.SplitN(data[0][2:], "..", 2)
yd := strings.SplitN(data[1][2:], "..", 2)
pd.Target.Start.X, _ = strconv.Atoi(xd[0])
pd.Target.Start.Y, _ = strconv.Atoi(yd[0])
pd.Target.End.X, _ = strconv.Atoi(xd[1])
pd.Target.End.Y, _ = strconv.Atoi(yd[1])
}
}
return pd
}
func (pd *ProbeData) FindMaxHeight() int {
// For maximum height you'd want maximum velocity
// Perfect Parabola: Since there's no drag/resistance, v_launch = v_impact (crossing y = 0)
// -> Highest velocity goes from 0 to min_y in 1 step, x velocity doesn't matter
// -> Vertical launch velocity is -min_y
// -> height_max = v + (v - 1) + (v - 2) + ... + 1
// -> height_max = v * (v + 1) / 2
// Inserted and with swapped signs (orientation)...
// -> height_max = -min_y * (-min_y - 1) / 2
return -pd.Target.Start.Y * (-pd.Target.Start.Y - 1) / 2
}
func (pd *ProbeData) FindLaunchVelocities() []numbers.Vector2 {
var launches []numbers.Vector2
// Similar approach, but swapped axes, maximum width here:
// reach = vx * (vx - 1) / 2
// Now just find all within range first
vx_min := 0 // Don't think we'd have to shoot to the left :P
// Find the first vx that will actually reach the target area
// This is basically a maximum height (now: width) thing again
for ; vx_min*(vx_min+1)/2 < pd.Target.Start.X; vx_min++ {
}
vx_max := pd.Target.End.X // More would be a guaranteed overshoot
// Again, assuming that anything slower/faster will just under-overshoot
vy_min := pd.Target.Start.Y
vy_max := -pd.Target.Start.Y
for vy := vy_min; vy <= vy_max; vy++ {
for vx := vx_min; vx <= vx_max; vx++ {
valid := false
for x, y, tvx, tvy := 0, 0, vx, vy; x <= pd.Target.End.X && y >= pd.Target.Start.Y; {
if x >= pd.Target.Start.X && x <= pd.Target.End.X && y >= pd.Target.Start.Y && y <= pd.Target.End.Y {
valid = true
break
}
x += tvx
y += tvy
if tvx > 0 {
tvx--
} else if tvx < 0 {
tvx++
}
tvy--
}
if valid {
launches = append(launches, numbers.Vector2{X: vx, Y: vy})
}
}
}
return launches
} | pkg/probe/probe.go | 0.584508 | 0.420183 | probe.go | starcoder |
package cp
import "math"
type PolyLine struct {
Verts []Vector
}
type PolyLineSet struct {
Lines []*PolyLine
}
func Next(i, count int) int {
return (i + 1) % count
}
func Sharpness(a, b, c Vector) float64 {
return a.Sub(b).Normalize().Dot(c.Sub(b).Normalize())
}
func (pl *PolyLine) Push(v Vector) *PolyLine {
pl.Verts = append(pl.Verts, v)
return pl
}
func (pl *PolyLine) Enqueue(v Vector) *PolyLine {
pl.Verts = append([]Vector{v}, pl.Verts...)
return pl
}
func (pl *PolyLine) IsClosed() bool {
return len(pl.Verts) > 1 && pl.Verts[0].Equal(pl.Verts[len(pl.Verts)-1])
}
func (pl *PolyLine) IsShort(count, start, end int, min float64) bool {
var length float64
for i := start; i != end; Next(i, count) {
length += pl.Verts[i].Distance(pl.Verts[Next(i, count)])
if length > min {
return false
}
}
return true
}
// Join similar adjacent line segments together. Works well for hard edged shapes.
// 'tol' is the minimum anglular difference in radians of a vertex.
func (pl *PolyLine) SimplifyVertexes(tol float64) *PolyLine {
reduced := PolyLine{Verts: []Vector{pl.Verts[0], pl.Verts[1]}}
minSharp := -math.Cos(tol)
for i := 2; i < len(pl.Verts); i++ {
vert := pl.Verts[i]
sharp := Sharpness(reduced.Verts[len(reduced.Verts)-2], reduced.Verts[len(reduced.Verts)-1], vert)
if sharp <= minSharp {
reduced.Verts[len(reduced.Verts)-1] = vert
} else {
reduced.Push(vert)
}
}
if pl.IsClosed() && Sharpness(reduced.Verts[len(reduced.Verts)-2], reduced.Verts[0], reduced.Verts[1]) < minSharp {
reduced.Verts[0] = reduced.Verts[len(reduced.Verts)-2]
}
return &reduced
}
// Recursive function used by cpPolylineSimplifyCurves().
func DouglasPeucker(verts []Vector, reduced *PolyLine, length, start, end int, min, tol float64) *PolyLine {
// Early exit if the points are adjacent
if (end-start+length)%length < 2 {
return reduced
}
a := verts[start]
b := verts[end]
// Check if the length is below the threshold
if a.Near(b, min) && reduced.IsShort(length, start, end, min) {
return reduced
}
// Find the maximal vertex to split and recurse on
var max float64
maxi := start
n := b.Sub(a).Perp().Normalize()
d := n.Dot(a)
for i := Next(start, length); i != end; i = Next(i, length) {
dist := math.Abs(n.Dot(verts[i]) - d)
if dist > max {
max = dist
maxi = i
}
}
if max > tol {
reduced = DouglasPeucker(verts, reduced, length, start, maxi, min, tol)
reduced.Push(verts[maxi])
reduced = DouglasPeucker(verts, reduced, length, maxi, end, min, tol)
}
return reduced
}
// Recursively reduce the vertex count on a polyline. Works best for smooth shapes.
// 'tol' is the maximum error for the reduction.
// The reduced polyline will never be farther than this distance from the original polyline.
func (pl *PolyLine) SimplifyCurves(tol float64) *PolyLine {
reduced := &PolyLine{}
min := tol / 2.0
if pl.IsClosed() {
start, end := LoopIndexes(pl.Verts, len(pl.Verts)-1)
reduced = reduced.Push(pl.Verts[start])
reduced = DouglasPeucker(pl.Verts, reduced, len(pl.Verts)-1, start, end, min, tol)
reduced = reduced.Push(pl.Verts[end])
reduced = DouglasPeucker(pl.Verts, reduced, len(pl.Verts)-1, end, start, min, tol)
reduced = reduced.Push(pl.Verts[start])
} else {
reduced = reduced.Push(pl.Verts[0])
reduced = DouglasPeucker(pl.Verts, reduced, len(pl.Verts), 0, len(pl.Verts)-1, min, tol)
reduced = reduced.Push(pl.Verts[len(pl.Verts)-1])
}
return reduced
}
// Find the polyline that ends with v.
func (pls *PolyLineSet) FindEnds(v Vector) int {
for i, line := range pls.Lines {
if line.Verts != nil && line.Verts[len(line.Verts)-1].Equal(v) {
return i
}
}
return -1
}
// Find the polyline that starts with v.
func (pls *PolyLineSet) FindStarts(v Vector) int {
for i, line := range pls.Lines {
if line.Verts != nil && line.Verts[0].Equal(v) {
return i
}
}
return -1
}
// Add a new polyline to a polyline set.
func (pls *PolyLineSet) Push(v *PolyLine) {
pls.Lines = append(pls.Lines, v)
}
// Join two cpPolylines in a polyline set together.
// this may deletion could be slow? https://yourbasic.org/golang/delete-element-slice/
func (pls *PolyLineSet) Join(before, after int) {
pls.Lines[before].Verts = append(pls.Lines[before].Verts, pls.Lines[after].Verts...)
copy(pls.Lines[after:], pls.Lines[after+1:])
pls.Lines = pls.Lines[:len(pls.Lines)-1]
}
// Add a segment to a polyline set.
// A segment will either start a new polyline, join two others, or add to or loop an existing polyline.
func PolyLineCollectSegment(v0, v1 Vector, pls *PolyLineSet) {
before := pls.FindEnds(v0)
after := pls.FindStarts(v1)
if before >= 0 && after >= 0 {
if before == after {
pls.Lines[before].Push(v1)
} else {
pls.Join(before, after)
}
} else if before >= 0 {
pls.Lines[before].Push(v1)
} else if after >= 0 {
pls.Lines[after].Enqueue(v0)
} else {
pls.Push(&PolyLine{Verts: []Vector{v0, v1}})
}
} | polyline.go | 0.735167 | 0.607343 | polyline.go | starcoder |
package accounting
import (
"encoding/json"
"time"
)
// InvoiceReadResponse The invoice data stored in HubSpot
type InvoiceReadResponse struct {
// The invoice number. Note that this is _not_ the ID of the invoice, but the number that the billed customer will see.
ExternalInvoiceNumber *string `json:"externalInvoiceNumber,omitempty"`
// The total amount that this invoice is for.
TotalAmountBilled float32 `json:"totalAmountBilled"`
// The remaining balance due for the invoice.
BalanceDue float32 `json:"balanceDue"`
// The ISO 4217 currency code that represents the currency of the invoice.
CurrencyCode string `json:"currencyCode"`
// The due date of the invoice
DueDate string `json:"dueDate"`
// The id of the customer in the external accounting system that the invoice was sent to.
ExternalRecipientId string `json:"externalRecipientId"`
// The datetime that that invoice was sent to the customer.
ReceivedByRecipientDate *int64 `json:"receivedByRecipientDate,omitempty"`
// The datetime that the invoice was created in the external accounting system.
ExternalCreateDateTime *int64 `json:"externalCreateDateTime,omitempty"`
// Indicated is the invoice has been voided or not.
IsVoided bool `json:"isVoided"`
// The datetime that the invoice was created in HubSpot.
CreatedAt time.Time `json:"createdAt"`
// The datetime that the invoice was last updated in HubSpot.
UpdatedAt time.Time `json:"updatedAt"`
ArchivedAt *time.Time `json:"archivedAt,omitempty"`
Archived bool `json:"archived"`
// The id of the account in the external accounting system that this invoice is related to.
ExternalAccountId string `json:"externalAccountId"`
// The status of the invoice
InvoiceStatus string `json:"invoiceStatus"`
// The id of this invoice in the external accounting system.
Id string `json:"id"`
}
// NewInvoiceReadResponse instantiates a new InvoiceReadResponse 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 NewInvoiceReadResponse(totalAmountBilled float32, balanceDue float32, currencyCode string, dueDate string, externalRecipientId string, isVoided bool, createdAt time.Time, updatedAt time.Time, archived bool, externalAccountId string, invoiceStatus string, id string) *InvoiceReadResponse {
this := InvoiceReadResponse{}
this.TotalAmountBilled = totalAmountBilled
this.BalanceDue = balanceDue
this.CurrencyCode = currencyCode
this.DueDate = dueDate
this.ExternalRecipientId = externalRecipientId
this.IsVoided = isVoided
this.CreatedAt = createdAt
this.UpdatedAt = updatedAt
this.Archived = archived
this.ExternalAccountId = externalAccountId
this.InvoiceStatus = invoiceStatus
this.Id = id
return &this
}
// NewInvoiceReadResponseWithDefaults instantiates a new InvoiceReadResponse 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 NewInvoiceReadResponseWithDefaults() *InvoiceReadResponse {
this := InvoiceReadResponse{}
return &this
}
// GetExternalInvoiceNumber returns the ExternalInvoiceNumber field value if set, zero value otherwise.
func (o *InvoiceReadResponse) GetExternalInvoiceNumber() string {
if o == nil || o.ExternalInvoiceNumber == nil {
var ret string
return ret
}
return *o.ExternalInvoiceNumber
}
// GetExternalInvoiceNumberOk returns a tuple with the ExternalInvoiceNumber field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetExternalInvoiceNumberOk() (*string, bool) {
if o == nil || o.ExternalInvoiceNumber == nil {
return nil, false
}
return o.ExternalInvoiceNumber, true
}
// HasExternalInvoiceNumber returns a boolean if a field has been set.
func (o *InvoiceReadResponse) HasExternalInvoiceNumber() bool {
if o != nil && o.ExternalInvoiceNumber != nil {
return true
}
return false
}
// SetExternalInvoiceNumber gets a reference to the given string and assigns it to the ExternalInvoiceNumber field.
func (o *InvoiceReadResponse) SetExternalInvoiceNumber(v string) {
o.ExternalInvoiceNumber = &v
}
// GetTotalAmountBilled returns the TotalAmountBilled field value
func (o *InvoiceReadResponse) GetTotalAmountBilled() float32 {
if o == nil {
var ret float32
return ret
}
return o.TotalAmountBilled
}
// GetTotalAmountBilledOk returns a tuple with the TotalAmountBilled field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetTotalAmountBilledOk() (*float32, bool) {
if o == nil {
return nil, false
}
return &o.TotalAmountBilled, true
}
// SetTotalAmountBilled sets field value
func (o *InvoiceReadResponse) SetTotalAmountBilled(v float32) {
o.TotalAmountBilled = v
}
// GetBalanceDue returns the BalanceDue field value
func (o *InvoiceReadResponse) GetBalanceDue() float32 {
if o == nil {
var ret float32
return ret
}
return o.BalanceDue
}
// GetBalanceDueOk returns a tuple with the BalanceDue field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetBalanceDueOk() (*float32, bool) {
if o == nil {
return nil, false
}
return &o.BalanceDue, true
}
// SetBalanceDue sets field value
func (o *InvoiceReadResponse) SetBalanceDue(v float32) {
o.BalanceDue = v
}
// GetCurrencyCode returns the CurrencyCode field value
func (o *InvoiceReadResponse) GetCurrencyCode() string {
if o == nil {
var ret string
return ret
}
return o.CurrencyCode
}
// GetCurrencyCodeOk returns a tuple with the CurrencyCode field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetCurrencyCodeOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.CurrencyCode, true
}
// SetCurrencyCode sets field value
func (o *InvoiceReadResponse) SetCurrencyCode(v string) {
o.CurrencyCode = v
}
// GetDueDate returns the DueDate field value
func (o *InvoiceReadResponse) GetDueDate() string {
if o == nil {
var ret string
return ret
}
return o.DueDate
}
// GetDueDateOk returns a tuple with the DueDate field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetDueDateOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.DueDate, true
}
// SetDueDate sets field value
func (o *InvoiceReadResponse) SetDueDate(v string) {
o.DueDate = v
}
// GetExternalRecipientId returns the ExternalRecipientId field value
func (o *InvoiceReadResponse) GetExternalRecipientId() string {
if o == nil {
var ret string
return ret
}
return o.ExternalRecipientId
}
// GetExternalRecipientIdOk returns a tuple with the ExternalRecipientId field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetExternalRecipientIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ExternalRecipientId, true
}
// SetExternalRecipientId sets field value
func (o *InvoiceReadResponse) SetExternalRecipientId(v string) {
o.ExternalRecipientId = v
}
// GetReceivedByRecipientDate returns the ReceivedByRecipientDate field value if set, zero value otherwise.
func (o *InvoiceReadResponse) GetReceivedByRecipientDate() int64 {
if o == nil || o.ReceivedByRecipientDate == nil {
var ret int64
return ret
}
return *o.ReceivedByRecipientDate
}
// GetReceivedByRecipientDateOk returns a tuple with the ReceivedByRecipientDate field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetReceivedByRecipientDateOk() (*int64, bool) {
if o == nil || o.ReceivedByRecipientDate == nil {
return nil, false
}
return o.ReceivedByRecipientDate, true
}
// HasReceivedByRecipientDate returns a boolean if a field has been set.
func (o *InvoiceReadResponse) HasReceivedByRecipientDate() bool {
if o != nil && o.ReceivedByRecipientDate != nil {
return true
}
return false
}
// SetReceivedByRecipientDate gets a reference to the given int64 and assigns it to the ReceivedByRecipientDate field.
func (o *InvoiceReadResponse) SetReceivedByRecipientDate(v int64) {
o.ReceivedByRecipientDate = &v
}
// GetExternalCreateDateTime returns the ExternalCreateDateTime field value if set, zero value otherwise.
func (o *InvoiceReadResponse) GetExternalCreateDateTime() int64 {
if o == nil || o.ExternalCreateDateTime == nil {
var ret int64
return ret
}
return *o.ExternalCreateDateTime
}
// GetExternalCreateDateTimeOk returns a tuple with the ExternalCreateDateTime field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetExternalCreateDateTimeOk() (*int64, bool) {
if o == nil || o.ExternalCreateDateTime == nil {
return nil, false
}
return o.ExternalCreateDateTime, true
}
// HasExternalCreateDateTime returns a boolean if a field has been set.
func (o *InvoiceReadResponse) HasExternalCreateDateTime() bool {
if o != nil && o.ExternalCreateDateTime != nil {
return true
}
return false
}
// SetExternalCreateDateTime gets a reference to the given int64 and assigns it to the ExternalCreateDateTime field.
func (o *InvoiceReadResponse) SetExternalCreateDateTime(v int64) {
o.ExternalCreateDateTime = &v
}
// GetIsVoided returns the IsVoided field value
func (o *InvoiceReadResponse) GetIsVoided() bool {
if o == nil {
var ret bool
return ret
}
return o.IsVoided
}
// GetIsVoidedOk returns a tuple with the IsVoided field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetIsVoidedOk() (*bool, bool) {
if o == nil {
return nil, false
}
return &o.IsVoided, true
}
// SetIsVoided sets field value
func (o *InvoiceReadResponse) SetIsVoided(v bool) {
o.IsVoided = v
}
// GetCreatedAt returns the CreatedAt field value
func (o *InvoiceReadResponse) GetCreatedAt() time.Time {
if o == nil {
var ret time.Time
return ret
}
return o.CreatedAt
}
// GetCreatedAtOk returns a tuple with the CreatedAt field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetCreatedAtOk() (*time.Time, bool) {
if o == nil {
return nil, false
}
return &o.CreatedAt, true
}
// SetCreatedAt sets field value
func (o *InvoiceReadResponse) SetCreatedAt(v time.Time) {
o.CreatedAt = v
}
// GetUpdatedAt returns the UpdatedAt field value
func (o *InvoiceReadResponse) GetUpdatedAt() time.Time {
if o == nil {
var ret time.Time
return ret
}
return o.UpdatedAt
}
// GetUpdatedAtOk returns a tuple with the UpdatedAt field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetUpdatedAtOk() (*time.Time, bool) {
if o == nil {
return nil, false
}
return &o.UpdatedAt, true
}
// SetUpdatedAt sets field value
func (o *InvoiceReadResponse) SetUpdatedAt(v time.Time) {
o.UpdatedAt = v
}
// GetArchivedAt returns the ArchivedAt field value if set, zero value otherwise.
func (o *InvoiceReadResponse) GetArchivedAt() time.Time {
if o == nil || o.ArchivedAt == nil {
var ret time.Time
return ret
}
return *o.ArchivedAt
}
// GetArchivedAtOk returns a tuple with the ArchivedAt field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetArchivedAtOk() (*time.Time, bool) {
if o == nil || o.ArchivedAt == nil {
return nil, false
}
return o.ArchivedAt, true
}
// HasArchivedAt returns a boolean if a field has been set.
func (o *InvoiceReadResponse) HasArchivedAt() bool {
if o != nil && o.ArchivedAt != nil {
return true
}
return false
}
// SetArchivedAt gets a reference to the given time.Time and assigns it to the ArchivedAt field.
func (o *InvoiceReadResponse) SetArchivedAt(v time.Time) {
o.ArchivedAt = &v
}
// GetArchived returns the Archived field value
func (o *InvoiceReadResponse) GetArchived() bool {
if o == nil {
var ret bool
return ret
}
return o.Archived
}
// GetArchivedOk returns a tuple with the Archived field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetArchivedOk() (*bool, bool) {
if o == nil {
return nil, false
}
return &o.Archived, true
}
// SetArchived sets field value
func (o *InvoiceReadResponse) SetArchived(v bool) {
o.Archived = v
}
// GetExternalAccountId returns the ExternalAccountId field value
func (o *InvoiceReadResponse) GetExternalAccountId() string {
if o == nil {
var ret string
return ret
}
return o.ExternalAccountId
}
// GetExternalAccountIdOk returns a tuple with the ExternalAccountId field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetExternalAccountIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ExternalAccountId, true
}
// SetExternalAccountId sets field value
func (o *InvoiceReadResponse) SetExternalAccountId(v string) {
o.ExternalAccountId = v
}
// GetInvoiceStatus returns the InvoiceStatus field value
func (o *InvoiceReadResponse) GetInvoiceStatus() string {
if o == nil {
var ret string
return ret
}
return o.InvoiceStatus
}
// GetInvoiceStatusOk returns a tuple with the InvoiceStatus field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetInvoiceStatusOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.InvoiceStatus, true
}
// SetInvoiceStatus sets field value
func (o *InvoiceReadResponse) SetInvoiceStatus(v string) {
o.InvoiceStatus = v
}
// GetId returns the Id field value
func (o *InvoiceReadResponse) GetId() string {
if o == nil {
var ret string
return ret
}
return o.Id
}
// GetIdOk returns a tuple with the Id field value
// and a boolean to check if the value has been set.
func (o *InvoiceReadResponse) GetIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Id, true
}
// SetId sets field value
func (o *InvoiceReadResponse) SetId(v string) {
o.Id = v
}
func (o InvoiceReadResponse) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.ExternalInvoiceNumber != nil {
toSerialize["externalInvoiceNumber"] = o.ExternalInvoiceNumber
}
if true {
toSerialize["totalAmountBilled"] = o.TotalAmountBilled
}
if true {
toSerialize["balanceDue"] = o.BalanceDue
}
if true {
toSerialize["currencyCode"] = o.CurrencyCode
}
if true {
toSerialize["dueDate"] = o.DueDate
}
if true {
toSerialize["externalRecipientId"] = o.ExternalRecipientId
}
if o.ReceivedByRecipientDate != nil {
toSerialize["receivedByRecipientDate"] = o.ReceivedByRecipientDate
}
if o.ExternalCreateDateTime != nil {
toSerialize["externalCreateDateTime"] = o.ExternalCreateDateTime
}
if true {
toSerialize["isVoided"] = o.IsVoided
}
if true {
toSerialize["createdAt"] = o.CreatedAt
}
if true {
toSerialize["updatedAt"] = o.UpdatedAt
}
if o.ArchivedAt != nil {
toSerialize["archivedAt"] = o.ArchivedAt
}
if true {
toSerialize["archived"] = o.Archived
}
if true {
toSerialize["externalAccountId"] = o.ExternalAccountId
}
if true {
toSerialize["invoiceStatus"] = o.InvoiceStatus
}
if true {
toSerialize["id"] = o.Id
}
return json.Marshal(toSerialize)
}
type NullableInvoiceReadResponse struct {
value *InvoiceReadResponse
isSet bool
}
func (v NullableInvoiceReadResponse) Get() *InvoiceReadResponse {
return v.value
}
func (v *NullableInvoiceReadResponse) Set(val *InvoiceReadResponse) {
v.value = val
v.isSet = true
}
func (v NullableInvoiceReadResponse) IsSet() bool {
return v.isSet
}
func (v *NullableInvoiceReadResponse) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableInvoiceReadResponse(val *InvoiceReadResponse) *NullableInvoiceReadResponse {
return &NullableInvoiceReadResponse{value: val, isSet: true}
}
func (v NullableInvoiceReadResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableInvoiceReadResponse) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | generated/accounting/model_invoice_read_response.go | 0.752922 | 0.440289 | model_invoice_read_response.go | starcoder |
package utility
import (
"fmt"
"math/big"
)
type (
// EllipticCurve represents the parameters of a short Weierstrass equation elliptic
// curve.
EllipticCurve struct {
A *big.Int
B *big.Int
P *big.Int
G EllipticCurvePoint
N *big.Int
H *big.Int
ma ModularArithmetic
}
)
// NewEllipticCurve creates a new EllipticCurve struct.
func NewEllipticCurve() EllipticCurve {
return EllipticCurve{
ma: NewModularArithmetic(),
}
}
// Add computes R = P + Q on EllipticCurve ec.
func (e *EllipticCurve) Add(P, Q EllipticCurvePoint) (*EllipticCurvePoint, error) {
var resultPoint EllipticCurvePoint
if e.isInfinity(P) && e.isInfinity(Q) {
resultPoint.X = nil
resultPoint.Y = nil
} else if e.isInfinity(P) {
resultPoint.X = new(big.Int).Set(Q.X)
resultPoint.Y = new(big.Int).Set(Q.Y)
} else if e.isInfinity(Q) {
resultPoint.X = new(big.Int).Set(P.X)
resultPoint.Y = new(big.Int).Set(P.Y)
} else if P.X.Cmp(Q.X) == 0 && e.ma.Add(P.Y, Q.Y, e.P).Sign() == 0 {
resultPoint.X = nil
resultPoint.Y = nil
} else if P.X.Cmp(Q.X) == 0 && P.Y.Cmp(Q.Y) == 0 && P.Y.Sign() != 0 {
num := e.ma.Add(
e.ma.Mul(
big.NewInt(3),
e.ma.Mul(P.X, P.X, e.P),
e.P,
),
e.A,
e.P,
)
den := e.ma.Inverse(e.ma.Mul(big.NewInt(2), P.Y, e.P), e.P)
lambda := e.ma.Mul(num, den, e.P)
resultPoint.X = e.ma.Sub(
e.ma.Mul(lambda, lambda, e.P),
e.ma.Mul(big.NewInt(2), P.X, e.P),
e.P,
)
resultPoint.Y = e.ma.Sub(
e.ma.Mul(lambda, e.ma.Sub(P.X, resultPoint.X, e.P), e.P),
P.Y,
e.P,
)
} else if P.X.Cmp(Q.X) != 0 {
num := e.ma.Sub(Q.Y, P.Y, e.P)
den := e.ma.Inverse(e.ma.Sub(Q.X, P.X, e.P), e.P)
lambda := e.ma.Mul(num, den, e.P)
resultPoint.X = e.ma.Sub(
e.ma.Sub(
e.ma.Mul(lambda, lambda, e.P),
P.X,
e.P,
),
Q.X,
e.P,
)
resultPoint.Y = e.ma.Sub(
e.ma.Mul(
lambda,
e.ma.Sub(P.X, resultPoint.X, e.P),
e.P,
),
P.Y,
e.P,
)
} else {
return nil, fmt.Errorf("Unsupported point addition: %v + %v", P.Format(), Q.Format())
}
return &resultPoint, nil
}
// IsOnCurve checks if point P is on EllipticCurve ec.
func (e *EllipticCurve) IsOnCurve(point EllipticCurvePoint) bool {
if e.isInfinity(point) {
return false
}
lhs := e.ma.Mul(point.Y, point.Y, e.P)
rhs := e.ma.Add(
e.ma.Add(
e.ma.Exp(point.X, big.NewInt(3), e.P),
e.ma.Mul(e.A, point.X, e.P),
e.P,
),
e.B,
e.P,
)
if lhs.Cmp(rhs) == 0 {
return true
}
return false
}
// ScalarBaseMult computes Q = k * G on EllipticCurve ec.
func (e *EllipticCurve) ScalarBaseMult(k *big.Int) (*EllipticCurvePoint, error) {
return e.ScalarMult(k, e.G)
}
// ScalarMult computes Q = k * P on EllipticCurve ec.
func (e *EllipticCurve) ScalarMult(k *big.Int, P EllipticCurvePoint) (*EllipticCurvePoint, error) {
var R0 EllipticCurvePoint
var R1 EllipticCurvePoint
R0.X = nil
R0.Y = nil
R1.X = new(big.Int).Set(P.X)
R1.Y = new(big.Int).Set(P.Y)
for i := e.N.BitLen() - 1; i >= 0; i-- {
if k.Bit(i) == 0 {
x, err := e.Add(R0, R1)
if err != nil {
return nil, err
}
R1 = *x
x, err = e.Add(R0, R0)
if err != nil {
return nil, err
}
R0 = *x
} else {
x, err := e.Add(R0, R1)
if err != nil {
return nil, err
}
R0 = *x
x, err = e.Add(R1, R1)
if err != nil {
return nil, err
}
R1 = *x
}
}
return &R0, nil
}
func (e EllipticCurve) isInfinity(point EllipticCurvePoint) bool {
if point.X == nil && point.Y == nil {
return true
}
return false
} | utility/elliptic_curve.go | 0.750095 | 0.664506 | elliptic_curve.go | starcoder |
package librato
// Aggregate provides a means for aggregating metrics on the client side, and pushing the
// the calculated value to librato.
type Aggregate struct {
// Each metric has a name that is unique to its class of metrics e.g. a gauge name must be unique among gauges. The name
// identifies a metric in subsequent API calls to store/query individual measurements and can be up to 255 characters in
// length. Valid characters for metric names are A-Za-z0-9.:-_. The metric namespace is case insensitive.
Name string `json:"name"`
// Source is an optional property that can be used to subdivide a common gauge/counter among multiple members of a population.
// For example the number of requests/second serviced by an application could be broken up among a group of server instances in
// a scale-out tier by setting the hostname as the value of source.
Source string `json:"source,omitempty"`
// The epoch time at which an individual measurement occurred with a maximum resolution of seconds.
MeasureTime int64 `json:"measure_time,omitempty"`
values []float64
}
// Add a new value to the aggregate
// The method returns itself to allow chaining
func (a *Aggregate) Add(v float64) *Aggregate {
a.values = append(a.values, v)
return a
}
// Count is the number of measurements that have been recorded
func (a Aggregate) Count() int {
return len(a.values)
}
// Sum is the sum of the measurements
func (a Aggregate) Sum() float64 {
var total float64
for _, v := range a.values {
total += v
}
return total
}
// Min is the minimum measurement value, or zero if no measurements exist.
func (a Aggregate) Min() float64 {
if len(a.values) == 0 {
return 0
}
m := a.values[0]
for _, v := range a.values {
if v < m {
m = v
}
}
return m
}
// Max is the maximum measurement value, or zero if no measurements exist.
func (a Aggregate) Max() float64 {
if len(a.values) == 0 {
return 0
}
m := a.values[0]
for _, v := range a.values {
if v > m {
m = v
}
}
return m
}
// SumSquares is used to determine the standard deviation for the published measurements.
func (a Aggregate) SumSquares() float64 {
if len(a.values) == 0 {
return 0
}
var sum, sumOfSquares float64
for _, v := range a.values {
sum += v
sumOfSquares += v * v
}
x := (sum * sum) / float64(len(a.values))
return sumOfSquares - x
}
func (a Aggregate) ToGauge() Gauge {
return Gauge{
Name: a.Name,
Source: a.Source,
Count: a.Count(),
Sum: a.Sum(),
Min: a.Min(),
Max: a.Max(),
SumSquares: a.SumSquares(),
}
}
type Gauge struct {
// Each metric has a name that is unique to its class of metrics e.g. a gauge name must be unique among gauges. The name
// identifies a metric in subsequent API calls to store/query individual measurements and can be up to 255 characters in
// length. Valid characters for metric names are A-Za-z0-9.:-_. The metric namespace is case insensitive.
Name string `json:"name"`
// The numeric value of an individual measurement. Multiple formats are supported (e.g. integer, floating point, etc) but the value must be numeric.
Value interface{} `json:"value"`
// Source is an optional property that can be used to subdivide a common gauge/counter among multiple members of a population.
// For example the number of requests/second serviced by an application could be broken up among a group of server instances in
// a scale-out tier by setting the hostname as the value of source.
Source string `json:"source,omitempty"`
// The epoch time at which an individual measurement occurred with a maximum resolution of seconds.
MeasureTime int64 `json:"measure_time,omitempty"`
// The following fields are used to publish aggregations
// They are public to allow serialization, but should not be used directly.
Count int `json:"count,omitempty"`
Sum interface{} `json:"sum,omitempty"`
Min interface{} `json:"min,omitempty"`
Max interface{} `json:"max,omitempty"`
SumSquares interface{} `json:"sum_squares,omitempty"`
}
type Counter struct {
Name string `json:"name"`
Value interface{} `json:"value"`
Source string `json:"source,omitempty"`
MeasureTime int64 `json:"measure_time,omitempty"`
} | metric.go | 0.863751 | 0.550426 | metric.go | starcoder |
package coldata
import (
"fmt"
"github.com/cockroachdb/apd"
"github.com/cockroachdb/cockroach/pkg/col/coltypes"
)
// column is an interface that represents a raw array of a Go native type.
type column interface{}
// SliceArgs represents the arguments passed in to Vec.Append and Nulls.set.
type SliceArgs struct {
// ColType is the type of both the destination and source slices.
ColType coltypes.T
// Src is the data being appended.
Src Vec
// Sel is an optional slice specifying indices to append to the destination
// slice. Note that Src{Start,End}Idx apply to Sel.
Sel []uint16
// DestIdx is the first index that Append will append to.
DestIdx uint64
// SrcStartIdx is the index of the first element in Src that Append will
// append.
SrcStartIdx uint64
// SrcEndIdx is the exclusive end index of Src. i.e. the element in the index
// before SrcEndIdx is the last element appended to the destination slice,
// similar to Src[SrcStartIdx:SrcEndIdx].
SrcEndIdx uint64
}
// CopySliceArgs represents the extension of SliceArgs that is passed in to
// Vec.Copy.
type CopySliceArgs struct {
SliceArgs
// Sel64 overrides Sel. Used when the amount of data being copied exceeds the
// representation capabilities of a []uint16.
Sel64 []uint64
// SelOnDest, if true, uses the selection vector as a lens into the
// destination as well as the source. Normally, when SelOnDest is false, the
// selection vector is applied to the source vector, but the results are
// copied densely into the destination vector.
SelOnDest bool
}
// Vec is an interface that represents a column vector that's accessible by
// Go native types.
type Vec interface {
// Type returns the type of data stored in this Vec.
Type() coltypes.T
// TODO(jordan): is a bitmap or slice of bools better?
// Bool returns a bool list.
Bool() []bool
// Int8 returns an int8 slice.
Int8() []int8
// Int16 returns an int16 slice.
Int16() []int16
// Int32 returns an int32 slice.
Int32() []int32
// Int64 returns an int64 slice.
Int64() []int64
// Float32 returns a float32 slice.
Float32() []float32
// Float64 returns a float64 slice.
Float64() []float64
// Bytes returns a flat Bytes representation.
Bytes() *Bytes
// TODO(jordan): should this be [][]byte?
// Decimal returns an apd.Decimal slice.
Decimal() []apd.Decimal
// Col returns the raw, typeless backing storage for this Vec.
Col() interface{}
// SetCol sets the member column (in the case of mutable columns).
SetCol(interface{})
// TemplateType returns an []interface{} and is used for operator templates.
// Do not call this from normal code - it'll always panic.
_TemplateType() []interface{}
// Append uses SliceArgs to append elements of a source Vec into this Vec.
// It is logically equivalent to:
// destVec = append(destVec[:args.DestIdx], args.Src[args.SrcStartIdx:args.SrcEndIdx])
// An optional Sel slice can also be provided to apply a filter on the source
// Vec.
// Refer to the SliceArgs comment for specifics and TestAppend for examples.
Append(SliceArgs)
// Copy uses CopySliceArgs to copy elements of a source Vec into this Vec. It is
// logically equivalent to:
// copy(destVec[args.DestIdx:], args.Src[args.SrcStartIdx:args.SrcEndIdx])
// An optional Sel slice can also be provided to apply a filter on the source
// Vec.
// Refer to the CopySliceArgs comment for specifics and TestCopy for examples.
Copy(CopySliceArgs)
// Slice returns a new Vec representing a slice of the current Vec from
// [start, end).
Slice(colType coltypes.T, start uint64, end uint64) Vec
// PrettyValueAt returns a "pretty"value for the idx'th value in this Vec.
// It uses the reflect package and is not suitable for calling in hot paths.
PrettyValueAt(idx uint16, colType coltypes.T) string
// MaybeHasNulls returns true if the column possibly has any null values, and
// returns false if the column definitely has no null values.
MaybeHasNulls() bool
// Nulls returns the nulls vector for the column.
Nulls() *Nulls
// SetNulls sets the nulls vector for this column.
SetNulls(*Nulls)
}
var _ Vec = &memColumn{}
// memColumn is a simple pass-through implementation of Vec that just casts
// a generic interface{} to the proper type when requested.
type memColumn struct {
t coltypes.T
col column
nulls Nulls
}
// NewMemColumn returns a new memColumn, initialized with a length.
func NewMemColumn(t coltypes.T, n int) Vec {
nulls := NewNulls(n)
switch t {
case coltypes.Bool:
return &memColumn{t: t, col: make([]bool, n), nulls: nulls}
case coltypes.Bytes:
return &memColumn{t: t, col: NewBytes(n), nulls: nulls}
case coltypes.Int8:
return &memColumn{t: t, col: make([]int8, n), nulls: nulls}
case coltypes.Int16:
return &memColumn{t: t, col: make([]int16, n), nulls: nulls}
case coltypes.Int32:
return &memColumn{t: t, col: make([]int32, n), nulls: nulls}
case coltypes.Int64:
return &memColumn{t: t, col: make([]int64, n), nulls: nulls}
case coltypes.Float32:
return &memColumn{t: t, col: make([]float32, n), nulls: nulls}
case coltypes.Float64:
return &memColumn{t: t, col: make([]float64, n), nulls: nulls}
case coltypes.Decimal:
return &memColumn{t: t, col: make([]apd.Decimal, n), nulls: nulls}
default:
panic(fmt.Sprintf("unhandled type %s", t))
}
}
func (m *memColumn) Type() coltypes.T {
return m.t
}
func (m *memColumn) SetCol(col interface{}) {
m.col = col
}
func (m *memColumn) Bool() []bool {
return m.col.([]bool)
}
func (m *memColumn) Int8() []int8 {
return m.col.([]int8)
}
func (m *memColumn) Int16() []int16 {
return m.col.([]int16)
}
func (m *memColumn) Int32() []int32 {
return m.col.([]int32)
}
func (m *memColumn) Int64() []int64 {
return m.col.([]int64)
}
func (m *memColumn) Float32() []float32 {
return m.col.([]float32)
}
func (m *memColumn) Float64() []float64 {
return m.col.([]float64)
}
func (m *memColumn) Bytes() *Bytes {
return m.col.(*Bytes)
}
func (m *memColumn) Decimal() []apd.Decimal {
return m.col.([]apd.Decimal)
}
func (m *memColumn) Col() interface{} {
return m.col
}
func (m *memColumn) _TemplateType() []interface{} {
panic("don't call this from non template code")
}
func (m *memColumn) MaybeHasNulls() bool {
return m.nulls.maybeHasNulls
}
func (m *memColumn) Nulls() *Nulls {
return &m.nulls
}
func (m *memColumn) SetNulls(n *Nulls) {
m.nulls = *n
} | pkg/col/coldata/vec.go | 0.633637 | 0.531696 | vec.go | starcoder |
package crypto11
import (
"crypto/elliptic"
"math/big"
)
var p256k1 p256k1Curve
type p256k1Curve struct {
*elliptic.CurveParams
}
func P256K1() elliptic.Curve {
p256k1.CurveParams = &elliptic.CurveParams{Name: "P-256K1"}
p256k1.P, _ = new(big.Int).SetString("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 0)
p256k1.N, _ = new(big.Int).SetString("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 0)
p256k1.B, _ = new(big.Int).SetString("0x0000000000000000000000000000000000000000000000000000000000000007", 0)
p256k1.Gx, _ = new(big.Int).SetString("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 0)
p256k1.Gy, _ = new(big.Int).SetString("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 0)
p256k1.BitSize = 256
return p256k1
}
func (curve p256k1Curve) Params() *elliptic.CurveParams {
return curve.CurveParams
}
func (curve p256k1Curve) IsOnCurve(x, y *big.Int) bool {
// y² = x³ + b
y2 := new(big.Int).Mul(y, y) //y²
y2.Mod(y2, curve.Params().P) //y²%P
x3 := new(big.Int).Mul(x, x) //x²
x3.Mul(x3, x) //x³
x3.Add(x3, curve.Params().B) //x³+B
x3.Mod(x3, curve.Params().P) //(x³+B)%P
return x3.Cmp(y2) == 0
}
//TODO: double check if the function is okay
// affineFromJacobian reverses the Jacobian transform. See the comment at the
// top of the file.
func (curve p256k1Curve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) {
zinv := new(big.Int).ModInverse(z, curve.Params().P)
zinvsq := new(big.Int).Mul(zinv, zinv)
xOut = new(big.Int).Mul(x, zinvsq)
xOut.Mod(xOut, curve.Params().P)
zinvsq.Mul(zinvsq, zinv)
yOut = new(big.Int).Mul(y, zinvsq)
yOut.Mod(yOut, curve.Params().P)
return
}
// Add returns the sum of (x1,y1) and (x2,y2)
func (curve p256k1Curve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {
z := new(big.Int).SetInt64(1)
return curve.affineFromJacobian(curve.addJacobian(x1, y1, z, x2, y2, z))
}
// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and
// (x2, y2, z2) and returns their sum, also in Jacobian form.
func (curve p256k1Curve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) {
// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl
z1z1 := new(big.Int).Mul(z1, z1)
z1z1.Mod(z1z1, curve.Params().P)
z2z2 := new(big.Int).Mul(z2, z2)
z2z2.Mod(z2z2, curve.Params().P)
u1 := new(big.Int).Mul(x1, z2z2)
u1.Mod(u1, curve.Params().P)
u2 := new(big.Int).Mul(x2, z1z1)
u2.Mod(u2, curve.Params().P)
h := new(big.Int).Sub(u2, u1)
if h.Sign() == -1 {
h.Add(h, curve.Params().P)
}
i := new(big.Int).Lsh(h, 1)
i.Mul(i, i)
j := new(big.Int).Mul(h, i)
s1 := new(big.Int).Mul(y1, z2)
s1.Mul(s1, z2z2)
s1.Mod(s1, curve.Params().P)
s2 := new(big.Int).Mul(y2, z1)
s2.Mul(s2, z1z1)
s2.Mod(s2, curve.Params().P)
r := new(big.Int).Sub(s2, s1)
if r.Sign() == -1 {
r.Add(r, curve.Params().P)
}
r.Lsh(r, 1)
v := new(big.Int).Mul(u1, i)
x3 := new(big.Int).Set(r)
x3.Mul(x3, x3)
x3.Sub(x3, j)
x3.Sub(x3, v)
x3.Sub(x3, v)
x3.Mod(x3, curve.Params().P)
y3 := new(big.Int).Set(r)
v.Sub(v, x3)
y3.Mul(y3, v)
s1.Mul(s1, j)
s1.Lsh(s1, 1)
y3.Sub(y3, s1)
y3.Mod(y3, curve.Params().P)
z3 := new(big.Int).Add(z1, z2)
z3.Mul(z3, z3)
z3.Sub(z3, z1z1)
if z3.Sign() == -1 {
z3.Add(z3, curve.Params().P)
}
z3.Sub(z3, z2z2)
if z3.Sign() == -1 {
z3.Add(z3, curve.Params().P)
}
z3.Mul(z3, h)
z3.Mod(z3, curve.Params().P)
return x3, y3, z3
}
// Double returns 2*(x,y)
func (curve p256k1Curve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {
z1 := new(big.Int).SetInt64(1)
return curve.affineFromJacobian(curve.doubleJacobian(x1, y1, z1))
}
// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and
// returns its double, also in Jacobian form.
func (curve p256k1Curve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) {
// See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l
a := new(big.Int).Mul(x, x) //X1²
b := new(big.Int).Mul(y, y) //Y1²
c := new(big.Int).Mul(b, b) //B²
d := new(big.Int).Add(x, b) //X1+B
d.Mul(d, d) //(X1+B)²
d.Sub(d, a) //(X1+B)²-A
d.Sub(d, c) //(X1+B)²-A-C
d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C)
e := new(big.Int).Mul(big.NewInt(3), a) //3*A
f := new(big.Int).Mul(e, e) //E²
x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D
x3.Sub(f, x3) //F-2*D
x3.Mod(x3, curve.Params().P)
y3 := new(big.Int).Sub(d, x3) //D-X3
y3.Mul(e, y3) //E*(D-X3)
y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C
y3.Mod(y3, curve.Params().P)
z3 := new(big.Int).Mul(y, z) //Y1*Z1
z3.Mul(big.NewInt(2), z3) //3*Y1*Z1
z3.Mod(z3, curve.Params().P)
return x3, y3, z3
}
//TODO: double check if it is okay
// ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
func (curve p256k1Curve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) {
// We have a slight problem in that the identity of the group (the
// point at infinity) cannot be represented in (x, y) form on a finite
// machine. Thus the standard add/double algorithm has to be tweaked
// slightly: our initial state is not the identity, but x, and we
// ignore the first true bit in |k|. If we don't find any true bits in
// |k|, then we return nil, nil, because we cannot return the identity
// element.
Bz := new(big.Int).SetInt64(1)
x := Bx
y := By
z := Bz
seenFirstTrue := false
for _, byte := range k {
for bitNum := 0; bitNum < 8; bitNum++ {
if seenFirstTrue {
x, y, z = curve.doubleJacobian(x, y, z)
}
if byte&0x80 == 0x80 {
if !seenFirstTrue {
seenFirstTrue = true
} else {
x, y, z = curve.addJacobian(Bx, By, Bz, x, y, z)
}
}
byte <<= 1
}
}
if !seenFirstTrue {
return nil, nil
}
return curve.affineFromJacobian(x, y, z)
}
// ScalarBaseMult returns k*G, where G is the base point of the group and k is
// an integer in big-endian form.
func (curve p256k1Curve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {
return curve.ScalarMult(curve.Params().Gx, curve.Params().Gy, k)
}
// func Unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) {
// byteLen := (curve.Params().BitSize + 7) / 8
// if len(data) != 1+2*byteLen {
// return nil, nil
// }
// if data[0] != 4 { // uncompressed form
// return nil, nil
// }
// p := curve.Params().P
// x = new(big.Int).SetBytes(data[1 : 1+byteLen])
// y = new(big.Int).SetBytes(data[1+byteLen:])
// if x.Cmp(p) >= 0 || y.Cmp(p) >= 0 {
// log.Printf("Comparison failed for x or y")
// return nil, nil
// }
// if !curve.IsOnCurve(x, y) {
// log.Printf("IsOnCurve failed!")
// return nil, nil
// }
// return
// } | 256k1.go | 0.602529 | 0.548371 | 256k1.go | starcoder |
package sqlite
import (
"github.com/go-vela/server/database/sqlite/dml"
"github.com/go-vela/types/constants"
"github.com/go-vela/types/library"
"github.com/sirupsen/logrus"
)
// GetBuildStepCount gets a count of all steps by build ID from the database.
func (c *client) GetBuildStepCount(b *library.Build) (int64, error) {
logrus.Tracef("getting count of steps for build %d from the database", b.GetNumber())
// variable to store query results
var s int64
// send query to the database and store result in variable
err := c.Sqlite.
Table(constants.TableStep).
Raw(dml.SelectBuildStepsCount, b.GetID()).
Pluck("count", &s).Error
return s, err
}
// GetStepImageCount gets a count of all step images
// and the count of their occurrence in the database.
func (c *client) GetStepImageCount() (map[string]float64, error) {
logrus.Tracef("getting count of all images for steps from the database")
type imageCount struct {
Image string
Count int
}
// variable to store query results
images := new([]imageCount)
counts := make(map[string]float64)
// send query to the database and store result in variable
err := c.Sqlite.
Table(constants.TableStep).
Raw(dml.SelectStepImagesCount).
Scan(images).Error
for _, image := range *images {
counts[image.Image] = float64(image.Count)
}
return counts, err
}
// GetStepStatusCount gets a list of all step statuses
// and the count of their occurrence in the database.
func (c *client) GetStepStatusCount() (map[string]float64, error) {
logrus.Trace("getting count of all statuses for steps from the database")
type statusCount struct {
Status string
Count int
}
// variable to store query results
s := new([]statusCount)
counts := map[string]float64{
"pending": 0,
"failure": 0,
"killed": 0,
"running": 0,
"success": 0,
}
// send query to the database and store result in variable
err := c.Sqlite.
Table(constants.TableStep).
Raw(dml.SelectStepStatusesCount).
Scan(s).Error
for _, status := range *s {
counts[status.Status] = float64(status.Count)
}
return counts, err
} | database/sqlite/step_count.go | 0.542136 | 0.418519 | step_count.go | starcoder |
package ir
// Constant is the interface implemented by constant values (e.g. numbers,
// strings, but also code chunks).
type Constant interface {
ProcessConstant(p ConstantProcessor)
}
// A ConstantProcessor is able to process all the different types of constant
// using the various ProcessXXX methods.
type ConstantProcessor interface {
ProcessFloat(Float)
ProcessInt(Int)
ProcessBool(Bool)
ProcessString(String)
ProcessNil(NilType)
ProcessCode(Code)
}
// A Float is a constant representing a literal floating point number.
type Float float64
// ProcessConstant uses the given ConstantProcessor to process the receiver.
func (f Float) ProcessConstant(p ConstantProcessor) {
p.ProcessFloat(f)
}
// An Int is a constant representing an integer literal.
type Int int64
// ProcessConstant uses the given ConstantProcessor to process the receiver.
func (n Int) ProcessConstant(p ConstantProcessor) {
p.ProcessInt(n)
}
// A Bool is a constant representing a boolean literal.
type Bool bool
// ProcessConstant uses the given ConstantProcessor to process the receiver.
func (b Bool) ProcessConstant(p ConstantProcessor) {
p.ProcessBool(b)
}
// A String is a constant representing a string literal.
type String string
// ProcessConstant uses the given ConstantProcessor to process the receiver.
func (s String) ProcessConstant(p ConstantProcessor) {
p.ProcessString(s)
}
// NilType is the type of the nil literal.
type NilType struct{}
// ProcessConstant uses the given ConstantProcessor to process the receiver.
func (n NilType) ProcessConstant(p ConstantProcessor) {
p.ProcessNil(n)
}
// Code is the type of code literals (i.e. function definitions).
type Code struct {
Instructions []Instruction
Lines []int
Constants []Constant
UpvalueDests []Register
Registers []RegData
UpNames []string
Name string
}
// ProcessConstant uses the given ConstantProcessor to process the receiver.
func (c Code) ProcessConstant(p ConstantProcessor) {
p.ProcessCode(c)
}
// A ConstantPool accumulates constants and associates a stable integer with
// each constant.
type ConstantPool struct {
constants []Constant
kmap map[Constant]uint // Makes a difference for large number of constants
}
func NewConstantPool() *ConstantPool {
return &ConstantPool{
kmap: map[Constant]uint{},
}
}
// GetConstantIndex returns the index associated with a given constant. If
// there is none, the constant is registered in the pool and the new index is
// returned.
func (c *ConstantPool) GetConstantIndex(k Constant) uint {
i, ok := c.kmap[k]
if !ok {
i = uint(len(c.constants))
c.kmap[k] = i
c.constants = append(c.constants, k)
}
return i
}
// Constants returns the list of all constants registered with this pool.
func (c *ConstantPool) Constants() []Constant {
return c.constants
} | ir/code.go | 0.797281 | 0.609379 | code.go | starcoder |
package eval
import (
"golang.org/x/xerrors"
"github.com/mmcloughlin/ec3/arith/ir"
"github.com/mmcloughlin/ec3/internal/errutil"
)
// Value is a value stored in a register.
type Value interface {
// Bits returns the number of bits required to represent the value.
Bits() uint
}
// Processor is an implementation of the arithmetic instruction set.
type Processor interface {
// Bits returns the word size of the processor.
Bits() uint
// Const builds the n-bit constant with value x.
Const(x uint64, n uint) Value
// ITE returns x if l≡r else y.
ITE(l, r, x, y Value) Value
// ADD is addition with carry in/out.
ADD(x, y, cin Value) (sum, cout Value)
// SUB is subtraction with borrow in/out.
SUB(x, y, bin Value) (diff, bout Value)
// MUL is multiply with upper/lower parts of the result.
MUL(x, y Value) (hi, lo Value)
// SHL shifts left by s.
SHL(x Value, s uint) Value
// SHR shifts right by s.
SHR(x Value, s uint) Value
// Errors returns any accumulated errors.
Errors() []error
}
// Evaluator evaluates an arithmetic program.
type Evaluator struct {
proc Processor
mem map[string]Value
errs errutil.Errors
}
// NewEvaluator constructs an evaluator with empty state.
func NewEvaluator(proc Processor) *Evaluator {
return &Evaluator{
proc: proc,
mem: map[string]Value{},
}
}
// SetRegister sets register r to value x.
func (e *Evaluator) SetRegister(r ir.Register, x Value) {
e.setregister(r, x)
}
// Register returns the value in the given register.
func (e *Evaluator) Register(r ir.Register) (Value, error) {
defer e.reseterror()
return e.register(r), e.err()
}
// Execute the program p.
func (e *Evaluator) Execute(p *ir.Program) error {
defer e.reseterror()
for _, i := range p.Instructions {
if err := e.instruction(i); err != nil {
return err
}
}
return nil
}
// instruction executes a single instruction.
func (e *Evaluator) instruction(inst ir.Instruction) error {
switch i := inst.(type) {
case ir.MOV:
e.setregister(i.Destination, e.operand(i.Source))
case ir.CMOV:
src := e.operand(i.Source)
dst := e.operand(i.Destination)
flag := e.flag(i.Flag)
eq := e.flag(i.Equals)
result := e.proc.ITE(flag, eq, src, dst)
e.setregister(i.Destination, result)
case ir.ADD:
x := e.operand(i.X)
y := e.operand(i.Y)
cin := e.flag(i.CarryIn)
sum, cout := e.proc.ADD(x, y, cin)
e.setregister(i.Sum, sum)
e.setflag(i.CarryOut, cout)
case ir.SUB:
x := e.operand(i.X)
y := e.operand(i.Y)
bin := e.flag(i.BorrowIn)
diff, bout := e.proc.SUB(x, y, bin)
e.setregister(i.Diff, diff)
e.setflag(i.BorrowOut, bout)
case ir.MUL:
x := e.operand(i.X)
y := e.operand(i.Y)
hi, lo := e.proc.MUL(x, y)
e.setregister(i.High, hi)
e.setregister(i.Low, lo)
case ir.SHL:
x := e.operand(i.X)
e.setregister(i.Result, e.proc.SHL(x, uint(i.Shift)))
case ir.SHR:
x := e.operand(i.X)
e.setregister(i.Result, e.proc.SHR(x, uint(i.Shift)))
default:
return errutil.UnexpectedType(i)
}
return e.err()
}
// operand returns the value of the given operand.
func (e *Evaluator) operand(operand ir.Operand) Value {
switch op := operand.(type) {
case ir.Register:
return e.register(op)
case ir.Constant:
return e.proc.Const(uint64(op), e.proc.Bits())
case ir.Flag:
return e.proc.Const(uint64(op), 1)
default:
e.adderror(errutil.UnexpectedType(op))
return nil
}
}
// register loads the value in register r.
func (e *Evaluator) register(r ir.Register) Value {
return e.load(string(r))
}
// flag loads the value in the given flag operand.
func (e *Evaluator) flag(op ir.Operand) Value {
b := e.operand(op)
e.assertwidth(b, 1)
return b
}
// load named value from memory.
func (e *Evaluator) load(name string) Value {
x, ok := e.mem[name]
if !ok {
e.errorf("operand %q undefined", name)
return nil
}
return x
}
// setregister sets register r to value x.
func (e *Evaluator) setregister(r ir.Register, x Value) {
if r == ir.Discard {
return
}
e.store(string(r), x)
}
// setflag sets register r to the flab bit b.
func (e *Evaluator) setflag(r ir.Register, b Value) {
e.assertwidth(b, 1)
e.setregister(r, b)
}
// store x at name.
func (e *Evaluator) store(name string, x Value) {
e.mem[name] = x
}
// assertwidth sets an error if x is not a w-bit value.
func (e *Evaluator) assertwidth(x Value, w uint) {
if x.Bits() > w {
e.errorf("expected to be %d-bit value", w)
}
}
// err returns any accumulated errors.
func (e *Evaluator) err() error {
var errs errutil.Errors
errs.Add(e.errs...)
errs.Add(e.proc.Errors()...)
return errs.Err()
}
// reseterror sets internal error state to nil.
func (e *Evaluator) reseterror() { e.errs = nil }
// adderror adds an error to the internal error list.
func (e *Evaluator) adderror(err error) { e.errs.Add(err) }
// errorf is a convenience for adding a formatted error to the internal list.
func (e *Evaluator) errorf(format string, args ...interface{}) {
e.adderror(xerrors.Errorf(format, args...))
} | arith/eval/eval.go | 0.649912 | 0.462837 | eval.go | starcoder |
package xls
import (
"math"
"time"
)
const mjd0 float64 = 2400000.5
const mjdDJ2000 float64 = 51544.5
func shiftJulianToNoon(julianDays, julianFraction float64) (float64, float64) {
switch {
case -0.5 < julianFraction && julianFraction < 0.5:
julianFraction += 0.5
case julianFraction >= 0.5:
julianDays += 1
julianFraction -= 0.5
case julianFraction <= -0.5:
julianDays -= 1
julianFraction += 1.5
}
return julianDays, julianFraction
}
// Return the integer values for hour, minutes, seconds and
// nanoseconds that comprised a given fraction of a day.
func fractionOfADay(fraction float64) (hours, minutes, seconds, nanoseconds int) {
f := 5184000000000000 * fraction
nanoseconds = int(math.Mod(f, 1000000000))
f = f / 1000000000
seconds = int(math.Mod(f, 60))
f = f / 3600
minutes = int(math.Mod(f, 60))
f = f / 60
hours = int(f)
return hours, minutes, seconds, nanoseconds
}
func julianDateToGregorianTime(part1, part2 float64) time.Time {
part1I, part1F := math.Modf(part1)
part2I, part2F := math.Modf(part2)
julianDays := part1I + part2I
julianFraction := part1F + part2F
julianDays, julianFraction = shiftJulianToNoon(julianDays, julianFraction)
day, month, year := doTheFliegelAndVanFlandernAlgorithm(int(julianDays))
hours, minutes, seconds, nanoseconds := fractionOfADay(julianFraction)
return time.Date(year, time.Month(month), day, hours, minutes, seconds, nanoseconds, time.UTC)
}
// By this point generations of programmers have repeated the
// algorithm sent to the editor of "Communications of the ACM" in 1968
// (published in CACM, volume 11, number 10, October 1968, p.657).
// None of those programmers seems to have found it necessary to
// explain the constants or variable names set out by <NAME>
// and <NAME>. Maybe one day I'll buy that jounal and
// expand an explanation here - that day is not today.
func doTheFliegelAndVanFlandernAlgorithm(jd int) (day, month, year int) {
l := jd + 68569
n := (4 * l) / 146097
l = l - (146097*n+3)/4
i := (4000 * (l + 1)) / 1461001
l = l - (1461*i)/4 + 31
j := (80 * l) / 2447
d := l - (2447*j)/80
l = j / 11
m := j + 2 - (12 * l)
y := 100*(n-49) + i + l
return d, m, y
}
// Convert an excelTime representation (stored as a floating point number) to a time.Time.
func timeFromExcelTime(excelTime float64, date1904 bool) time.Time {
var date time.Time
var intPart int64 = int64(excelTime)
// Excel uses Julian dates prior to March 1st 1900, and
// Gregorian thereafter.
if intPart <= 61 {
const OFFSET1900 = 15018.0
const OFFSET1904 = 16480.0
var date time.Time
if date1904 {
date = julianDateToGregorianTime(mjd0+OFFSET1904, excelTime)
} else {
date = julianDateToGregorianTime(mjd0+OFFSET1900, excelTime)
}
return date
}
var floatPart float64 = excelTime - float64(intPart)
var dayNanoSeconds float64 = 24 * 60 * 60 * 1000 * 1000 * 1000
if date1904 {
date = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC)
} else {
date = time.Date(1899, 12, 30, 0, 0, 0, 0, time.UTC)
}
durationDays := time.Duration(intPart) * time.Hour * 24
durationPart := time.Duration(dayNanoSeconds * floatPart)
return date.Add(durationDays).Add(durationPart)
} | date.go | 0.69035 | 0.506408 | date.go | starcoder |
package image3d
import (
"errors"
"fmt"
_ "image/jpeg"
"path/filepath"
"strings"
"unsafe"
gl "github.com/adrianderstroff/pbr/pkg/core/gl"
"github.com/adrianderstroff/pbr/pkg/view/image/image2d"
)
// Image3D stores the dimensions, data format and it's pixel data.
// It can be used to manipulate single pixels and is used to
// upload it's data to a texture.
type Image3D struct {
width int
height int
slices int
channels int
bytedepth int
pixelType uint32
data []image2d.Image2D
}
// Make constructs an image of the specified length, width, height and with all
// pixels set to the specified rgba value.
func Make(width, height, slices, channels int) (Image3D, error) {
// create image data
var data []image2d.Image2D
for i := 0; i < slices; i++ {
image, err := image2d.Make(width, height, channels)
if err != nil {
return Image3D{}, err
}
data = append(data, image)
}
return Image3D{
width: width,
height: height,
slices: slices,
channels: channels,
bytedepth: 1,
pixelType: data[0].GetPixelType(),
data: data,
}, nil
}
// MakeFromData constructs an image of the specified width, height, slices and
// the specified data.
func MakeFromData(width, height, slices, channels int, data []uint8) (Image3D, error) {
// determine number of channels
bytedepth := len(data) / (width * height * slices * channels)
// create the individual images
var images []image2d.Image2D
size := width * height * channels
for i := 0; i < slices; i++ {
s, e := i*size, (i+1)*size
image, err := image2d.MakeFromData(width, height, channels, data[s:e])
if err != nil {
return Image3D{}, err
}
images = append(images, image)
}
pixeltype, err := getPixelTypeFromByteDepth(bytedepth)
if err != nil {
return Image3D{}, err
}
return Image3D{
width: width,
height: height,
slices: slices,
channels: channels,
bytedepth: bytedepth,
pixelType: uint32(pixeltype),
data: images,
}, nil
}
// MakeFromPath constructs the image data from the specified paths.
// If there is no image at the specified path an error is returned instead.
// The dimensions of all images must match.
func MakeFromPath(paths []string) (Image3D, error) {
// early exit if no path had been provided
if len(paths) == 0 {
return Image3D{}, errors.New("No image paths provided")
}
// get the first path
first, err := image2d.MakeFromPath(paths[0])
if err != nil {
return Image3D{}, err
}
// load multiple images for each path
var images []image2d.Image2D
images = append(images, first)
for _, path := range paths[1:] {
// load current image
image, err := image2d.MakeFromPath(path)
if err != nil {
return Image3D{}, err
}
// check if dimensions and formats match
if first.GetWidth() != image.GetWidth() ||
first.GetHeight() != image.GetHeight() ||
first.GetChannels() != image.GetChannels() ||
first.GetPixelType() != image.GetPixelType() ||
first.GetByteDepth() != image.GetByteDepth() {
return Image3D{}, errors.New("image dimensions or formats don't match")
}
// append images
images = append(images, image)
}
return Image3D{
width: first.GetWidth(),
height: first.GetHeight(),
slices: len(paths),
channels: first.GetChannels(),
bytedepth: first.GetByteDepth(),
pixelType: first.GetPixelType(),
data: images,
}, nil
}
// SaveToPath saves all slices as png images to the specified path.
// All images will be enumerated starting with 0.
// The file names will look like the following: dir/filename<NUMBER>.png
func (image *Image3D) SaveToPath(path string) error {
ext := filepath.Ext(path)
pathnoext := strings.TrimSuffix(path, ext)
for i := 0; i < image.slices; i++ {
curpath := pathnoext + fmt.Sprint(i) + ext
err := image.data[i].SaveToPath(curpath)
if err != nil {
return err
}
}
return nil
}
// FlipX flips all slices horizontally.
func (image *Image3D) FlipX() {
for _, slice := range image.data {
slice.FlipX()
}
}
// FlipY flips all slices vertically.
func (image *Image3D) FlipY() {
for _, slice := range image.data {
slice.FlipY()
}
}
// GetWidth returns the width of the image.
func (image *Image3D) GetWidth() int {
return image.width
}
// GetHeight returns the height of the image.
func (image *Image3D) GetHeight() int {
return image.height
}
// GetSlices returns the number of slices of the image.
func (image *Image3D) GetSlices() int {
return image.slices
}
// GetChannels return the number of the channels of the image.
func (image *Image3D) GetChannels() int {
return image.channels
}
// GetByteDepth returns the number of bytes a channel consists of.
func (image *Image3D) GetByteDepth() int {
return image.bytedepth
}
// GetPixelType gets the data type of the pixel data.
func (image *Image3D) GetPixelType() uint32 {
return image.pixelType
}
// GetDataPointer returns an pointer to the beginning of the image data.
func (image *Image3D) GetDataPointer() unsafe.Pointer {
return gl.Ptr(image.data)
}
// GetData returns a copy of the images data.
func (image *Image3D) GetData() []uint8 {
// collect data of all slices
var data []uint8
for _, slice := range image.data {
data = append(data, slice.GetData()...)
}
return data
}
// GetR returns the red value of the pixel at (x,y) in slice z.
func (image *Image3D) GetR(x, y, z int) uint8 {
return image.data[z].GetR(x, y)
}
// GetG returns the green value of the pixel at (x,y) in slice z.
func (image *Image3D) GetG(x, y, z int) uint8 {
return image.data[z].GetG(x, y)
}
// GetB returns the blue value of the pixel at (x,y) in slice z.
func (image *Image3D) GetB(x, y, z int) uint8 {
return image.data[z].GetB(x, y)
}
// GetA returns the alpha value of the pixel at (x,y) in slice z.
func (image *Image3D) GetA(x, y, z int) uint8 {
return image.data[z].GetA(x, y)
}
// GetRGB returns the RGB values of the pixel at (x,y) in slice z.
func (image *Image3D) GetRGB(x, y, z int) (uint8, uint8, uint8) {
return image.data[z].GetRGB(x, y)
}
// GetRGBA returns the RGBA value of the pixel at (x,y) in slice z.
func (image *Image3D) GetRGBA(x, y, z int) (uint8, uint8, uint8, uint8) {
return image.data[z].GetRGBA(x, y)
}
// SetR sets the red value of the pixel at (x,y) in slice z.
func (image *Image3D) SetR(x, y, z int, r uint8) {
image.data[z].SetR(x, y, r)
}
// SetG sets the green value of the pixel at (x,y) in slice z.
func (image *Image3D) SetG(x, y, z int, g uint8) {
image.data[z].SetG(x, y, g)
}
// SetB sets the blue value of the pixel at (x,y) in slice z.
func (image *Image3D) SetB(x, y, z int, b uint8) {
image.data[z].SetB(x, y, b)
}
// SetA sets the alpha value of the pixel at (x,y) in slice z.
func (image *Image3D) SetA(x, y, z int, a uint8) {
image.data[z].SetA(x, y, a)
}
// SetRGB sets the RGB values of the pixel at (x,y) in slice z.
func (image *Image3D) SetRGB(x, y, z int, r, g, b uint8) {
image.data[z].SetRGB(x, y, r, g, b)
}
// SetRGBA sets the RGBA values of the pixel at (x,y) in slice z.
func (image *Image3D) SetRGBA(x, y, z int, r, g, b, a uint8) {
image.data[z].SetRGBA(x, y, r, g, b, a)
}
// String pretty prints information about the image.
func (image Image3D) String() string {
c := getChannelsName(image.channels)
d := image.bytedepth * 8
return fmt.Sprintf("Image3D (%v,%v,%v) %v %vbit", image.width, image.height,
image.slices, c, d)
}
func getChannelsName(channels int) string {
c := "Unknown Channel Number"
switch channels {
case 1:
c = "RED"
break
case 2:
c = "RG"
break
case 3:
c = "RGB"
break
case 4:
c = "RGBA"
break
}
return c
}
// getPixelTypeFromByteDepth returns the appropriate pixel type for the given
// bytedepth. So far online a bytedepth of 1 and 4 is supported.
func getPixelTypeFromByteDepth(bytedepth int) (int, error) {
switch bytedepth {
case 1:
return gl.UNSIGNED_BYTE, nil
case 4:
return gl.FLOAT, nil
}
return 0, errors.New("bytedepth not supported")
} | pkg/view/image/image3d/image3d.go | 0.761095 | 0.466299 | image3d.go | starcoder |
// Package operators provides all operators used by WebAssembly bytecode,
// together with their parameter and return type(s).
package operators
import (
"fmt"
"github.com/go-interpreter/wagon/wasm"
)
var (
ops [256]Op // an array of Op values mapped by wasm opcodes, used by New().
noReturn = wasm.ValueType(wasm.BlockTypeEmpty)
)
// Op describes a WASM operator.
type Op struct {
Code byte // The single-byte opcode
Name string // The name of the operator
// Whether this operator is polymorphic.
// A polymorphic operator has a variable arity. call, call_indirect, and
// drop are examples of polymorphic operators.
Polymorphic bool
Args []wasm.ValueType // an array of value types used by the operator as arguments, is nil for polymorphic operators
Returns wasm.ValueType // the value returned (pushed) by the operator, is 0 for polymorphic operators
}
func (o Op) IsValid() bool {
return o.Name != ""
}
func newOp(code byte, name string, args []wasm.ValueType, returns wasm.ValueType) byte {
if ops[code].IsValid() {
panic(fmt.Errorf("Opcode %#x is already assigned to %s", code, ops[code].Name))
}
op := Op{
Code: code,
Name: name,
Polymorphic: false,
Args: args,
Returns: returns,
}
ops[code] = op
return code
}
func newPolymorphicOp(code byte, name string) byte {
if ops[code].IsValid() {
panic(fmt.Errorf("Opcode %#x is already assigned to %s", code, ops[code].Name))
}
op := Op{
Code: code,
Name: name,
Polymorphic: true,
}
ops[code] = op
return code
}
type InvalidOpcodeError byte
func (e InvalidOpcodeError) Error() string {
return fmt.Sprintf("Invalid opcode: %#x", byte(e))
}
// New returns the Op object for a valid given opcode.
// If code is invalid, an ErrInvalidOpcode is returned.
func New(code byte) (Op, error) {
var op Op
if int(code) >= len(ops) {
return op, InvalidOpcodeError(code)
}
op = ops[code]
if !op.IsValid() {
return op, InvalidOpcodeError(code)
}
return op, nil
} | wasm/operators/op.go | 0.772531 | 0.435841 | op.go | starcoder |
package plaid
import (
"encoding/json"
)
// TransactionStreamAmount Object with data pertaining to an amount on the transaction stream.
type TransactionStreamAmount struct {
// represents the numerical value of an amount.
Amount *float32 `json:"amount,omitempty"`
// The ISO-4217 currency code of the amount. Always `null` if `unofficial_currency_code` is non-`null`. See the [currency code schema](https://plaid.com/docs/api/accounts#currency-code-schema) for a full listing of supported `iso_currency_code`s.
IsoCurrencyCode NullableString `json:"iso_currency_code,omitempty"`
// The unofficial currency code of the amount. Always `null` if `iso_currency_code` is non-`null`. Unofficial currency codes are used for currencies that do not have official ISO currency codes, such as cryptocurrencies and the currencies of certain countries.
UnofficialCurrencyCode NullableString `json:"unofficial_currency_code,omitempty"`
AdditionalProperties map[string]interface{}
}
type _TransactionStreamAmount TransactionStreamAmount
// NewTransactionStreamAmount instantiates a new TransactionStreamAmount 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 NewTransactionStreamAmount() *TransactionStreamAmount {
this := TransactionStreamAmount{}
return &this
}
// NewTransactionStreamAmountWithDefaults instantiates a new TransactionStreamAmount 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 NewTransactionStreamAmountWithDefaults() *TransactionStreamAmount {
this := TransactionStreamAmount{}
return &this
}
// GetAmount returns the Amount field value if set, zero value otherwise.
func (o *TransactionStreamAmount) GetAmount() float32 {
if o == nil || o.Amount == nil {
var ret float32
return ret
}
return *o.Amount
}
// GetAmountOk returns a tuple with the Amount field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *TransactionStreamAmount) GetAmountOk() (*float32, bool) {
if o == nil || o.Amount == nil {
return nil, false
}
return o.Amount, true
}
// HasAmount returns a boolean if a field has been set.
func (o *TransactionStreamAmount) HasAmount() bool {
if o != nil && o.Amount != nil {
return true
}
return false
}
// SetAmount gets a reference to the given float32 and assigns it to the Amount field.
func (o *TransactionStreamAmount) SetAmount(v float32) {
o.Amount = &v
}
// GetIsoCurrencyCode returns the IsoCurrencyCode field value if set, zero value otherwise (both if not set or set to explicit null).
func (o *TransactionStreamAmount) GetIsoCurrencyCode() string {
if o == nil || o.IsoCurrencyCode.Get() == nil {
var ret string
return ret
}
return *o.IsoCurrencyCode.Get()
}
// GetIsoCurrencyCodeOk returns a tuple with the IsoCurrencyCode 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 *TransactionStreamAmount) GetIsoCurrencyCodeOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.IsoCurrencyCode.Get(), o.IsoCurrencyCode.IsSet()
}
// HasIsoCurrencyCode returns a boolean if a field has been set.
func (o *TransactionStreamAmount) HasIsoCurrencyCode() bool {
if o != nil && o.IsoCurrencyCode.IsSet() {
return true
}
return false
}
// SetIsoCurrencyCode gets a reference to the given NullableString and assigns it to the IsoCurrencyCode field.
func (o *TransactionStreamAmount) SetIsoCurrencyCode(v string) {
o.IsoCurrencyCode.Set(&v)
}
// SetIsoCurrencyCodeNil sets the value for IsoCurrencyCode to be an explicit nil
func (o *TransactionStreamAmount) SetIsoCurrencyCodeNil() {
o.IsoCurrencyCode.Set(nil)
}
// UnsetIsoCurrencyCode ensures that no value is present for IsoCurrencyCode, not even an explicit nil
func (o *TransactionStreamAmount) UnsetIsoCurrencyCode() {
o.IsoCurrencyCode.Unset()
}
// GetUnofficialCurrencyCode returns the UnofficialCurrencyCode field value if set, zero value otherwise (both if not set or set to explicit null).
func (o *TransactionStreamAmount) GetUnofficialCurrencyCode() string {
if o == nil || o.UnofficialCurrencyCode.Get() == nil {
var ret string
return ret
}
return *o.UnofficialCurrencyCode.Get()
}
// GetUnofficialCurrencyCodeOk returns a tuple with the UnofficialCurrencyCode 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 *TransactionStreamAmount) GetUnofficialCurrencyCodeOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.UnofficialCurrencyCode.Get(), o.UnofficialCurrencyCode.IsSet()
}
// HasUnofficialCurrencyCode returns a boolean if a field has been set.
func (o *TransactionStreamAmount) HasUnofficialCurrencyCode() bool {
if o != nil && o.UnofficialCurrencyCode.IsSet() {
return true
}
return false
}
// SetUnofficialCurrencyCode gets a reference to the given NullableString and assigns it to the UnofficialCurrencyCode field.
func (o *TransactionStreamAmount) SetUnofficialCurrencyCode(v string) {
o.UnofficialCurrencyCode.Set(&v)
}
// SetUnofficialCurrencyCodeNil sets the value for UnofficialCurrencyCode to be an explicit nil
func (o *TransactionStreamAmount) SetUnofficialCurrencyCodeNil() {
o.UnofficialCurrencyCode.Set(nil)
}
// UnsetUnofficialCurrencyCode ensures that no value is present for UnofficialCurrencyCode, not even an explicit nil
func (o *TransactionStreamAmount) UnsetUnofficialCurrencyCode() {
o.UnofficialCurrencyCode.Unset()
}
func (o TransactionStreamAmount) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.Amount != nil {
toSerialize["amount"] = o.Amount
}
if o.IsoCurrencyCode.IsSet() {
toSerialize["iso_currency_code"] = o.IsoCurrencyCode.Get()
}
if o.UnofficialCurrencyCode.IsSet() {
toSerialize["unofficial_currency_code"] = o.UnofficialCurrencyCode.Get()
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *TransactionStreamAmount) UnmarshalJSON(bytes []byte) (err error) {
varTransactionStreamAmount := _TransactionStreamAmount{}
if err = json.Unmarshal(bytes, &varTransactionStreamAmount); err == nil {
*o = TransactionStreamAmount(varTransactionStreamAmount)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "amount")
delete(additionalProperties, "iso_currency_code")
delete(additionalProperties, "unofficial_currency_code")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableTransactionStreamAmount struct {
value *TransactionStreamAmount
isSet bool
}
func (v NullableTransactionStreamAmount) Get() *TransactionStreamAmount {
return v.value
}
func (v *NullableTransactionStreamAmount) Set(val *TransactionStreamAmount) {
v.value = val
v.isSet = true
}
func (v NullableTransactionStreamAmount) IsSet() bool {
return v.isSet
}
func (v *NullableTransactionStreamAmount) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableTransactionStreamAmount(val *TransactionStreamAmount) *NullableTransactionStreamAmount {
return &NullableTransactionStreamAmount{value: val, isSet: true}
}
func (v NullableTransactionStreamAmount) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableTransactionStreamAmount) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | plaid/model_transaction_stream_amount.go | 0.859752 | 0.566918 | model_transaction_stream_amount.go | starcoder |
package executor
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"meerkat/internal/storage"
"meerkat/internal/storage/vector"
"meerkat/internal/util/sliceutil"
"strings"
)
func selectStringOpFn(op ComparisonOperation) func(x []byte, y string) bool {
var v func(x []byte, y string) bool
switch op {
case Eq:
v = func(x []byte, y string) bool {
return sliceutil.BS2S(x) == y
}
case Gt:
v = func(x []byte, y string) bool {
return sliceutil.BS2S(x) > y
}
case Ge:
v = func(x []byte, y string) bool {
return sliceutil.BS2S(x) >= y
}
case Le:
v = func(x []byte, y string) bool {
return sliceutil.BS2S(x) <= y
}
case Lt:
v = func(x []byte, y string) bool {
return sliceutil.BS2S(x) < y
}
case Ne:
v = func(x []byte, y string) bool {
return sliceutil.BS2S(x) != y
}
case Contains:
v = func(x []byte, y string) bool {
return strings.Contains(sliceutil.BS2S(x), y)
}
case IsNull:
v = nil
default:
panic("Operator Not found.")
}
return v
}
// NewColumnScanOperator creates a ColumnScanOperator
func NewStringColumnScanOperator(ctx Context, op ComparisonOperation, value string, col storage.ByteSliceColumn) Uint32Operator {
v := &StringColumnScanOperator{
ctx: ctx,
opFn: selectStringOpFn(op),
value: value,
col: col,
log: log.With().Str("src", "IntColumnScanOperator").Logger(),
}
if col.HasNulls() {
v.processFn = v.processNullVector
} else {
v.processFn = v.processVector
}
return v
}
type StringColumnScanOperator struct {
ctx Context
opFn func(x []byte, y string) bool
col storage.ByteSliceColumn
value string
sz int
iterator storage.ByteSliceIterator
lastRid uint32
resultLeft []uint32
lastCheckedId int
lastValuePos int
lastVector *vector.ByteSliceVector
processFn func(lastValuePos, lastCheckedId int, r []uint32) []uint32
log zerolog.Logger
}
func (op *StringColumnScanOperator) Next() []uint32 {
r := make([]uint32, 0, op.ctx.Sz())
if op.lastVector != nil {
r = append(r, op.resultLeft...)
r = op.processVector(op.lastValuePos, op.lastCheckedId, r)
if len(r) >= op.ctx.Sz() {
op.resultLeft = r[op.ctx.Sz():]
return r[:op.ctx.Sz()]
}
}
for op.iterator.HasNext() {
v := op.iterator.Next()
op.lastVector = &v
r = op.processVector(op.lastValuePos, op.lastCheckedId, r)
if len(r) >= op.ctx.Sz() {
op.resultLeft = r[op.ctx.Sz():]
return r[:op.ctx.Sz()]
}
}
op.lastVector = nil
op.lastCheckedId = 0
op.lastValuePos = 0
if len(r) > 0 {
return r
} else {
return nil
}
}
func (op *StringColumnScanOperator) Init() {
op.iterator = op.col.Iterator()
}
func (op *StringColumnScanOperator) Destroy() {
}
func (op *StringColumnScanOperator) processVector(lastValuePos, lastCheckedId int, r []uint32) []uint32 {
i := lastValuePos
x := lastCheckedId
for ; x < op.lastVector.Len(); x++ {
if op.opFn(op.lastVector.Get(x), op.value) {
r = append(r, op.lastRid)
i++
}
op.lastRid++
}
if len(r) >= op.ctx.Sz() {
op.lastCheckedId = x
op.lastValuePos = i
return r
}
return r
}
func (op *StringColumnScanOperator) processNullVector(lastValuePos, lastCheckedId int, r []uint32) []uint32 {
i := lastValuePos
x := lastCheckedId
for ; x < op.lastVector.Len(); x++ {
if op.lastVector.IsValid(x) {
if op.opFn(op.lastVector.Get(x), op.value) {
r = append(r, op.lastRid)
i++
}
}
op.lastRid++
}
if len(r) >= op.ctx.Sz() {
op.lastCheckedId = x
op.lastValuePos = i
return r
}
return r
}
func selectInt64OpFn(op ComparisonOperation) func(x, y int64) bool {
var v func(x, y int64) bool
switch op {
case Eq:
v = func(x, y int64) bool {
return x == y
}
case Gt:
v = func(x, y int64) bool {
return x > y
}
case Ge:
v = func(x, y int64) bool {
return x >= y
}
case Le:
v = func(x, y int64) bool {
return x <= y
}
case Lt:
v = func(x, y int64) bool {
return x < y
}
case Ne:
v = func(x, y int64) bool {
return x != y
}
case IsNull:
v = nil
default:
panic("Operator Not found.")
}
return v
}
// NewColumnScanOperator creates a ColumnScanOperator
func NewIntColumnScanOperator(ctx Context, op ComparisonOperation, value int64, col storage.Int64Column) Uint32Operator {
v := &IntColumnScanOperator{
ctx: ctx,
opFn: selectInt64OpFn(op),
value: value,
col: col,
log: log.With().Str("src", "IntColumnScanOperator").Logger(),
}
if col.HasNulls() {
v.processFn = v.processNullVector
} else {
v.processFn = v.processVector
}
return v
}
type IntColumnScanOperator struct {
ctx Context
opFn func(x, y int64) bool
col storage.Int64Column
value int64
iterator storage.Int64Iterator
lastRid uint32
lastCheckedId int
lastValuePos int
lastVector *vector.Int64Vector
processFn func(lastValuePos, lastCheckedId int, r []uint32) []uint32
log zerolog.Logger
}
func (op *IntColumnScanOperator) Init() {
op.iterator = op.col.Iterator()
}
func (op *IntColumnScanOperator) Destroy() {
}
func (op *IntColumnScanOperator) processVector(lastValuePos, lastCheckedId int, r []uint32) []uint32 {
i := lastValuePos
x := lastCheckedId
for ; x < op.lastVector.Len() && len(r) < op.ctx.Sz(); x++ {
if op.opFn(op.lastVector.Values()[x], op.value) {
r = append(r, op.lastRid)
i++
}
op.lastRid++
}
if len(r) == op.ctx.Sz() {
op.lastCheckedId = x
op.lastValuePos = i
return r
}
return r
}
func (op *IntColumnScanOperator) processNullVector(lastValuePos, lastCheckedId int, r []uint32) []uint32 {
i := lastValuePos
x := lastCheckedId
for ; x < op.lastVector.Len() && len(r) < op.ctx.Sz(); x++ {
if op.lastVector.IsValid(x) {
if op.opFn(op.lastVector.Values()[x], op.value) {
r = append(r, op.lastRid)
i++
}
}
op.lastRid++
}
if len(r) == op.ctx.Sz() {
op.lastCheckedId = x
op.lastValuePos = i
return r
}
return r
}
func (op *IntColumnScanOperator) Next() []uint32 {
r := make([]uint32, 0, op.ctx.Sz())
if op.lastVector != nil {
r = op.processFn(op.lastValuePos, op.lastCheckedId, r)
if len(r) == op.ctx.Sz() {
return r
}
}
for op.iterator.HasNext() {
v := op.iterator.Next()
op.lastVector = &v
r = op.processFn(op.lastValuePos, op.lastCheckedId, r)
if len(r) == op.ctx.Sz() {
return r
}
}
op.lastVector = nil
op.lastCheckedId = 0
op.lastValuePos = 0
if len(r) > 0 {
return r
} else {
return nil
}
}
func selectTimeOpFn(op ComparisonOperation) func(x, y, z int64) bool {
var v func(x, y, z int64) bool
switch op {
case Eq:
v = func(x, y, z int64) bool {
return x == y
}
case Gt:
v = func(x, y, z int64) bool {
return x > y
}
case Between:
v = func(x, y, z int64) bool {
return x > y && x < z
}
case Ge:
v = func(x, y, z int64) bool {
return x >= y
}
case Le:
v = func(x, y, z int64) bool {
return x <= y
}
case Lt:
v = func(x, y, z int64) bool {
return x < y
}
case Ne:
v = func(x, y, z int64) bool {
return x != y
}
case IsNull:
v = nil
default:
panic("Operator Not found.")
}
return v
}
// NewTimeColumnScanOperator creates a TimeColumnScanOperator
func NewTimeColumnScanOperator(ctx Context, op ComparisonOperation, valueFrom, valueTo int64, col storage.TimeColumn) Uint32Operator {
v := &TimeColumnScanOperator{
ctx: ctx,
opFn: selectTimeOpFn(op),
value: valueFrom,
valueTo: valueTo,
col: col,
log: log.With().Str("src", "TimeColumnScanOperator").Logger(),
}
return v
}
type TimeColumnScanOperator struct {
ctx Context
opFn func(x, y, z int64) bool
col storage.TimeColumn
value int64
valueTo int64
sz int
iterator storage.Int64Iterator
lastRid uint32
resultLeft []uint32
lastCheckedId int
lastValuePos int
lastVector *vector.Int64Vector
processFn func(lastValuePos, lastCheckedId int, r []uint32) []uint32
log zerolog.Logger
}
func (op *TimeColumnScanOperator) Init() {
op.iterator = op.col.Iterator()
}
func (op *TimeColumnScanOperator) Destroy() {
}
func (op *TimeColumnScanOperator) processVector(lastValuePos, lastCheckedId int, r []uint32) []uint32 {
i := lastValuePos
x := lastCheckedId
for ; x < op.lastVector.Len(); x++ {
if op.opFn(op.lastVector.Values()[x], op.value, op.valueTo) {
r = append(r, op.lastRid)
i++
}
op.lastRid++
}
if len(r) >= op.ctx.Sz() {
op.lastCheckedId = x
op.lastValuePos = i
return r
}
return r
}
func (op *TimeColumnScanOperator) Next() []uint32 {
r := make([]uint32, 0, op.ctx.Sz())
if op.lastVector != nil {
r = append(r, op.resultLeft...)
r = op.processVector(op.lastValuePos, op.lastCheckedId, r)
if len(r) >= op.ctx.Sz() {
op.resultLeft = r[op.ctx.Sz():]
return r[:op.ctx.Sz()]
}
}
for op.iterator.HasNext() {
v := op.iterator.Next()
op.lastVector = &v
r = op.processVector(op.lastValuePos, op.lastCheckedId, r)
if len(r) >= op.ctx.Sz() {
op.resultLeft = r[op.ctx.Sz():]
return r[:op.ctx.Sz()]
}
}
op.lastVector = nil
op.lastCheckedId = 0
op.lastValuePos = 0
if len(r) > 0 {
return r
} else {
return nil
}
} | internal/executor/full_scan_operator.go | 0.560012 | 0.607023 | full_scan_operator.go | starcoder |
package matchers
import (
"fmt"
"reflect"
"github.com/ptcar2009/gomega/format"
"github.com/ptcar2009/gomega/matchers/support/goraph/bipartitegraph"
)
type ConsistOfMatcher struct {
Elements []interface{}
missingElements []interface{}
extraElements []interface{}
}
func (matcher *ConsistOfMatcher) Match(actual interface{}) (success bool, err error) {
if !isArrayOrSlice(actual) && !isMap(actual) {
return false, fmt.Errorf("ConsistOf matcher expects an array/slice/map. Got:\n%s", format.Object(actual, 1))
}
matchers := matchers(matcher.Elements)
values := valuesOf(actual)
bipartiteGraph, err := bipartitegraph.NewBipartiteGraph(values, matchers, neighbours)
if err != nil {
return false, err
}
edges := bipartiteGraph.LargestMatching()
if len(edges) == len(values) && len(edges) == len(matchers) {
return true, nil
}
var missingMatchers []interface{}
matcher.extraElements, missingMatchers = bipartiteGraph.FreeLeftRight(edges)
matcher.missingElements = equalMatchersToElements(missingMatchers)
return false, nil
}
func neighbours(value, matcher interface{}) (bool, error) {
match, err := matcher.(omegaMatcher).Match(value)
return match && err == nil, nil
}
func equalMatchersToElements(matchers []interface{}) (elements []interface{}) {
for _, matcher := range matchers {
equalMatcher, ok := matcher.(*EqualMatcher)
if ok {
matcher = equalMatcher.Expected
}
elements = append(elements, matcher)
}
return
}
func matchers(expectedElems []interface{}) (matchers []interface{}) {
elems := expectedElems
if len(expectedElems) == 1 && isArrayOrSlice(expectedElems[0]) {
elems = []interface{}{}
value := reflect.ValueOf(expectedElems[0])
for i := 0; i < value.Len(); i++ {
elems = append(elems, value.Index(i).Interface())
}
}
for _, e := range elems {
matcher, isMatcher := e.(omegaMatcher)
if !isMatcher {
matcher = &EqualMatcher{Expected: e}
}
matchers = append(matchers, matcher)
}
return
}
func valuesOf(actual interface{}) []interface{} {
value := reflect.ValueOf(actual)
values := []interface{}{}
if isMap(actual) {
keys := value.MapKeys()
for i := 0; i < value.Len(); i++ {
values = append(values, value.MapIndex(keys[i]).Interface())
}
} else {
for i := 0; i < value.Len(); i++ {
values = append(values, value.Index(i).Interface())
}
}
return values
}
func (matcher *ConsistOfMatcher) FailureMessage(actual interface{}) (message string) {
message = format.Message(actual, "to consist of", matcher.Elements)
message = appendMissingElements(message, matcher.missingElements)
if len(matcher.extraElements) > 0 {
message = fmt.Sprintf("%s\nthe extra elements were\n%s", message,
format.Object(matcher.extraElements, 1))
}
return
}
func appendMissingElements(message string, missingElements []interface{}) string {
if len(missingElements) == 0 {
return message
}
return fmt.Sprintf("%s\nthe missing elements were\n%s", message,
format.Object(missingElements, 1))
}
func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return format.Message(actual, "not to consist of", matcher.Elements)
} | matchers/consist_of.go | 0.67694 | 0.446434 | consist_of.go | starcoder |
package engine
import (
"unicode"
)
// utils.go contains various utility functions used throughout the engine.
var CharToPieceType map[rune]uint8 = map[rune]uint8{
'N': Knight,
'B': Bishop,
'R': Rook,
'Q': Queen,
'K': King,
}
// Convert a string board coordinate to its position
// number.
func CoordinateToPos(coordinate string) uint8 {
file := coordinate[0] - 'a'
rank := int(coordinate[1]-'0') - 1
return uint8(rank*8 + int(file))
}
// Convert a position number to a string board coordinate.
func posToCoordinate(pos uint8) string {
file := FileOf(pos)
rank := RankOf(pos)
return string(rune('a'+file)) + string(rune('0'+rank+1))
}
// Given a board square, return it's file.
func FileOf(sq uint8) uint8 {
return sq % 8
}
// Given a board square, return it's rank.
func RankOf(sq uint8) uint8 {
return sq / 8
}
// Get the absolute value of a number.
func abs16(n int16) int16 {
if n < 0 {
return -n
}
return n
}
// Get the maximum between two signed 8-bit numbers.
func max8(a, b int8) int8 {
if a > b {
return a
}
return b
}
// Determine if a square is dark.
func sqIsDark(sq uint8) bool {
fileNo := FileOf(sq)
rankNo := RankOf(sq)
return ((fileNo + rankNo) % 2) == 0
}
// Convert a move in short algebraic notation, to the long algebraic notation used
// by the UCI protocol.
func ConvertSANToLAN(pos *Position, moveStr string) Move {
if moveStr == "O-O" && pos.SideToMove == White {
return NewMove(E1, G1, Castle, NoFlag)
} else if moveStr == "O-O" && pos.SideToMove == Black {
return NewMove(E8, G8, Castle, NoFlag)
} else if moveStr == "O-O-O" && pos.SideToMove == White {
return NewMove(E1, C1, Castle, NoFlag)
} else if moveStr == "O-O-O" && pos.SideToMove == Black {
return NewMove(E8, C8, Castle, NoFlag)
}
coords := ""
pieceType := Pawn
for _, char := range moveStr {
switch char {
case 'N', 'B', 'R', 'Q', 'K':
pieceType = CharToPieceType[char]
case '1', '2', '3', '4', '5', '6', '7', '8':
coords += string(char)
case 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h':
coords += string(char)
}
}
moves := GenMoves(pos)
matchingMove := NullMove
for i := 0; i < int(moves.Count); i++ {
move := moves.Moves[i]
moved := pos.Squares[move.FromSq()].Type
captured := pos.Squares[move.ToSq()].Type
if len(coords) == 2 {
if len(moveStr) == 4 && moveStr[2] == '=' {
promotionType := pieceType - 1
toSq := CoordinateToPos(coords[0:2])
if move.ToSq() == toSq && move.MoveType() == Promotion && move.Flag() == promotionType {
matchingMove = move
}
} else {
toSq := CoordinateToPos(coords)
if toSq == move.ToSq() && pieceType == moved {
matchingMove = move
}
}
} else if len(coords) == 3 {
if len(moveStr) == 6 && moveStr[4] == '=' {
promotionType := pieceType - 1
toSq := CoordinateToPos(coords[1:])
if captured != NoType &&
move.MoveType() == Promotion &&
move.Flag() == promotionType &&
move.ToSq() == toSq {
matchingMove = move
}
} else {
toSq := CoordinateToPos(coords[1:])
fileOrRank := coords[0]
moveCoords := move.String()
if unicode.IsLetter(rune(fileOrRank)) {
if toSq == move.ToSq() && fileOrRank == moveCoords[0] && moved == pieceType {
matchingMove = move
}
} else {
if toSq == move.ToSq() && fileOrRank == moveCoords[1] && moved == pieceType {
matchingMove = move
}
}
}
} else if len(coords) == 4 {
toSq := CoordinateToPos(coords[0:2])
fromSq := CoordinateToPos(coords[2:4])
if toSq == move.ToSq() && fromSq == move.FromSq() {
matchingMove = move
}
}
if matchingMove != NullMove {
if !pos.MakeMove(matchingMove) {
pos.UnmakeMove(matchingMove)
continue
}
pos.UnmakeMove(matchingMove)
break
}
}
return matchingMove
} | engine/utils.go | 0.687945 | 0.429669 | utils.go | starcoder |
package literalcircuit
import (
"github.com/xyproto/bits"
"bytes"
"fmt"
"io/ioutil"
"strings"
)
// Circuit is a collection of components (truth tables that act as functions, such as "xor"),
// a collection of connections between components (gate table expressions)
// and the name of the main list of gate table expressions, if there are several disconnected circuits.
type Circuit struct {
gateMap map[string]*bits.TruthTable
connMap map[string]*GateTable
mainGateTable *GateTable // pointer to the main GateTable of the circuit
testTruthTable *bits.TruthTable // pointer to the TruthTable that is used for testing the circuit
}
// New creates a new circuit, which can have several available components and several named collections of connections (circuits / gate table collections)
func New() *Circuit {
var c Circuit
c.gateMap = make(map[string]*bits.TruthTable)
c.connMap = make(map[string]*GateTable)
return &c
}
// RegisterTruthTable registers a gate, like "and" or "or", by using a name and a truth table
func (c *Circuit) RegisterTruthTable(name string, tt *bits.TruthTable) {
// If this panics, the circuit must be made with NewCircuit instead of &Circuit{}
c.gateMap[name] = tt
if c.testTruthTable == nil || name == "test" {
c.testTruthTable = tt
}
}
// RegisterGateTable registers connections between gates, with a name and a gate table
func (c *Circuit) RegisterGateTable(name string, gt *GateTable) {
// If this panics, the circuit must be made with NewCircuit instead of &Circuit{}
c.connMap[name] = gt
// Use this as the main circuit if no others are defined, or if this name is "main"
if c.mainGateTable == nil || name == "main" {
c.mainGateTable = gt
}
}
// SetMain selects one of the registered GateTable names as the main GateTable of the circuit
func (c *Circuit) SetMain(name string) {
if gt, ok := c.connMap[name]; ok {
c.mainGateTable = gt
} else {
panic(name + " does not exist in the list of connections/GateTables")
}
}
// Load a circuit file (literal circuit file: both Markdown and a circuit)
func Load(filename string, verbose bool) (*Circuit, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var (
inGateTable bool
inTruthTable bool
name string
)
truthTable := &bits.TruthTable{}
gateTable := &GateTable{}
c := New()
// Appending "# done" to the data is a sneaky way of not having an
// additional check after the for loop for unprocessed items that were
// gathered but not registered.
data = append(data, []byte("# done")...)
for _, byteLine := range bytes.Split(data, []byte("\n")) {
line := string(byteLine)
if strings.HasPrefix(line, " ") && strings.Contains(line, "->") {
// This is a line in a truth table or gate table
if !inGateTable && !inTruthTable && strings.Contains(line, ":") {
inGateTable = true
} else if !inGateTable && !inTruthTable {
inTruthTable = true
}
if inGateTable {
*gateTable = append(*gateTable, strings.TrimSpace(line))
} else if inTruthTable {
*truthTable = append(*truthTable, strings.TrimSpace(line))
}
} else if strings.HasPrefix(line, "# ") {
// Use the results that has been gathered so far
if inTruthTable {
// Register all the names for the truthTable
if strings.Contains(name, ":") {
firstName := strings.Split(name, ":")[0]
if verbose {
fmt.Println("Registering a truth table for " + firstName)
}
c.RegisterTruthTable(strings.TrimSpace(firstName), truthTable)
aliases := strings.Split(strings.Split(name, ":")[1], ",")
for _, alias := range aliases {
if verbose {
fmt.Println("Registering a truth table for alias " + strings.TrimSpace(alias))
}
c.RegisterTruthTable(strings.TrimSpace(alias), truthTable)
}
} else {
if verbose {
fmt.Println("Registering a truth table for " + name)
}
c.RegisterTruthTable(name, truthTable)
}
} else if inGateTable {
if verbose {
fmt.Println("Registering a gate table for " + name)
}
c.RegisterGateTable(name, gateTable)
}
// Reset the fields
if inTruthTable || inGateTable {
inTruthTable = false
inGateTable = false
name = ""
truthTable = &bits.TruthTable{}
gateTable = &GateTable{}
}
// Assign a new name
name = strings.TrimSpace(line[2:])
}
}
return &Circuit{}, nil
} | circuit.go | 0.629547 | 0.451568 | circuit.go | starcoder |
package processor
import (
"database/sql"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/Jeffail/benthos/v3/internal/bloblang/field"
"github.com/Jeffail/benthos/v3/internal/bloblang/mapping"
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/internal/interop"
"github.com/Jeffail/benthos/v3/internal/tracing"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/types"
// SQL Drivers
_ "github.com/ClickHouse/clickhouse-go"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeSQL] = TypeSpec{
constructor: NewSQL,
Categories: []Category{
CategoryIntegration,
},
Status: docs.StatusDeprecated,
Summary: `
Runs an SQL prepared query against a target database for each message and, for
queries that return rows, replaces it with the result according to a
[codec](#result-codecs).`,
Description: `
## Alternatives
Use either the ` + "[`sql_insert`](/docs/components/processors/sql_insert)" + ` or the ` + "[`sql_select`](/docs/components/processors/sql_select)" + ` processor instead.
If a query contains arguments they can be set as an array of strings supporting
[interpolation functions](/docs/configuration/interpolation#bloblang-queries) in
the ` + "`args`" + ` field.
## Drivers
The following is a list of supported drivers and their respective DSN formats:
| Driver | Data Source Name Format |
|---|---|
` + "| `clickhouse` | [`tcp://[netloc][:port][?param1=value1&...¶mN=valueN]`](https://github.com/ClickHouse/clickhouse-go#dsn)" + `
` + "| `mysql` | `[username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]` |" + `
` + "| `postgres` | `postgres://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]` |" + `
` + "| `mssql` | `sqlserver://[user[:password]@][netloc][:port][?database=dbname¶m1=value1&...]` |" + `
Please note that the ` + "`postgres`" + ` driver enforces SSL by default, you
can override this with the parameter ` + "`sslmode=disable`" + ` if required.`,
Examples: []docs.AnnotatedExample{
{
Title: "Table Insert (MySQL)",
Summary: `
The following example inserts rows into the table footable with the columns foo,
bar and baz populated with values extracted from messages:`,
Config: `
pipeline:
processors:
- sql:
driver: mysql
data_source_name: foouser:foopassword@tcp(localhost:3306)/foodb
query: "INSERT INTO footable (foo, bar, baz) VALUES (?, ?, ?);"
args_mapping: '[ document.foo, document.bar, meta("kafka_topic") ]'
`,
},
{
Title: "Table Query (PostgreSQL)",
Summary: `
Here we query a database for columns of footable that share a ` + "`user_id`" + `
with the message ` + "`user.id`" + `. The ` + "`result_codec`" + ` is set to
` + "`json_array`" + ` and a ` + "[`branch` processor](/docs/components/processors/branch)" + `
is used in order to insert the resulting array into the original message at the
path ` + "`foo_rows`" + `:`,
Config: `
pipeline:
processors:
- branch:
processors:
- sql:
driver: postgres
result_codec: json_array
data_source_name: postgres://foouser:foopass@localhost:5432/testdb?sslmode=disable
query: "SELECT * FROM footable WHERE user_id = $1;"
args_mapping: '[ this.user.id ]'
result_map: 'root.foo_rows = this'
`,
},
},
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon(
"driver",
"A database [driver](#drivers) to use.",
).HasOptions("mysql", "postgres", "clickhouse", "mssql"),
docs.FieldCommon(
"data_source_name", "A Data Source Name to identify the target database.",
"tcp://host1:9000?username=user&password=<PASSWORD>&database=clicks&read_timeout=10&write_timeout=20&alt_hosts=host2:9000,host3:9000",
"foouser:foopassword@tcp(localhost:3306)/foodb",
"postgres://foouser:foopass@localhost:5432/foodb?sslmode=disable",
),
docs.FieldDeprecated("dsn", ""),
docs.FieldCommon(
"query", "The query to run against the database.",
"INSERT INTO footable (foo, bar, baz) VALUES (?, ?, ?);",
),
docs.FieldBool(
"unsafe_dynamic_query",
"Whether to enable dynamic queries that support interpolation functions. WARNING: This feature opens up the possibility of SQL injection attacks and is considered unsafe.",
).Advanced().HasDefault(false),
docs.FieldDeprecated(
"args",
"A list of arguments for the query to be resolved for each message.",
).IsInterpolated().Array(),
docs.FieldBloblang(
"args_mapping",
"A [Bloblang mapping](/docs/guides/bloblang/about) that produces the arguments for the query. The mapping must return an array containing the number of arguments in the query.",
`[ this.foo, this.bar.not_empty().catch(null), meta("baz") ]`,
`root = [ uuid_v4() ].merge(this.document.args)`,
).AtVersion("3.47.0"),
docs.FieldCommon(
"result_codec",
"A [codec](#result-codecs) to determine how resulting rows are converted into messages.",
).HasOptions("none", "json_array"),
},
Footnotes: `
## Result Codecs
When a query returns rows they are serialised according to a chosen codec, and
the message contents are replaced with the serialised result.
### ` + "`none`" + `
The result of the query is ignored and the message remains unchanged. If your
query does not return rows then this is the appropriate codec.
### ` + "`json_array`" + `
The resulting rows are serialised into an array of JSON objects, where each
object represents a row, where the key is the column name and the value is that
columns value in the row.`,
}
}
//------------------------------------------------------------------------------
// SQLConfig contains configuration fields for the SQL processor.
type SQLConfig struct {
Driver string `json:"driver" yaml:"driver"`
DataSourceName string `json:"data_source_name" yaml:"data_source_name"`
DSN string `json:"dsn" yaml:"dsn"`
Query string `json:"query" yaml:"query"`
UnsafeDynamicQuery bool `json:"unsafe_dynamic_query" yaml:"unsafe_dynamic_query"`
Args []string `json:"args" yaml:"args"`
ArgsMapping string `json:"args_mapping" yaml:"args_mapping"`
ResultCodec string `json:"result_codec" yaml:"result_codec"`
}
// NewSQLConfig returns a SQLConfig with default values.
func NewSQLConfig() SQLConfig {
return SQLConfig{
Driver: "mysql",
DataSourceName: "",
DSN: "",
Query: "",
UnsafeDynamicQuery: false,
Args: []string{},
ArgsMapping: "",
ResultCodec: "none",
}
}
//------------------------------------------------------------------------------
// Some SQL drivers (such as clickhouse) require prepared inserts to be local to
// a transaction, rather than general.
func insertRequiresTransactionPrepare(driver string) bool {
_, exists := map[string]struct{}{
"clickhouse": {},
}[driver]
return exists
}
//------------------------------------------------------------------------------
// SQL is a processor that executes an SQL query for each message.
type SQL struct {
log log.Modular
stats metrics.Type
conf SQLConfig
db *sql.DB
dbMux sync.RWMutex
args []*field.Expression
argsMapping *mapping.Executor
resCodec sqlResultCodec
// TODO: V4 Remove this
deprecated bool
resCodecDeprecated sqlResultCodecDeprecated
queryStr string
dynQuery *field.Expression
query *sql.Stmt
closeChan chan struct{}
closedChan chan struct{}
closeOnce sync.Once
mCount metrics.StatCounter
mErr metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
}
// NewSQL returns a SQL processor.
func NewSQL(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
deprecated := false
dsn := conf.SQL.DataSourceName
if len(conf.SQL.DSN) > 0 {
if len(dsn) > 0 {
return nil, errors.New("specified both a deprecated `dsn` as well as a `data_source_name`")
}
dsn = conf.SQL.DSN
deprecated = true
}
if len(conf.SQL.Args) > 0 && conf.SQL.ArgsMapping != "" {
return nil, errors.New("cannot specify both `args` and an `args_mapping` in the same processor")
}
var argsMapping *mapping.Executor
if conf.SQL.ArgsMapping != "" {
if deprecated {
return nil, errors.New("the field `args_mapping` cannot be used when running the `sql` processor in deprecated mode (using the `dsn` field), use the `data_source_name` field instead")
}
log.Warnln("using unsafe_dynamic_query leaves you vulnerable to SQL injection attacks")
var err error
if argsMapping, err = interop.NewBloblangMapping(mgr, conf.SQL.ArgsMapping); err != nil {
return nil, fmt.Errorf("failed to parse `args_mapping`: %w", err)
}
}
var args []*field.Expression
for i, v := range conf.SQL.Args {
expr, err := interop.NewBloblangField(mgr, v)
if err != nil {
return nil, fmt.Errorf("failed to parse arg %v expression: %v", i, err)
}
args = append(args, expr)
}
if conf.SQL.Driver == "mssql" {
// For MSSQL, if the user part of the connection string is in the
// `DOMAIN\username` format, then the backslash character needs to be
// URL-encoded.
conf.SQL.DataSourceName = strings.ReplaceAll(conf.SQL.DataSourceName, `\`, "%5C")
}
s := &SQL{
log: log,
stats: stats,
conf: conf.SQL,
args: args,
argsMapping: argsMapping,
queryStr: conf.SQL.Query,
deprecated: deprecated,
closeChan: make(chan struct{}),
closedChan: make(chan struct{}),
mCount: stats.GetCounter("count"),
mErr: stats.GetCounter("error"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
}
var err error
if deprecated {
s.log.Warnln("Using deprecated SQL functionality due to use of field 'dsn'. To switch to the new processor use the field 'data_source_name' instead. The new processor is not backwards compatible due to differences in how message batches are processed. For more information check out the docs at https://www.benthos.dev/docs/components/processors/sql.")
if conf.SQL.Driver != "mysql" && conf.SQL.Driver != "postgres" && conf.SQL.Driver != "mssql" {
return nil, fmt.Errorf("driver '%v' is not supported with deprecated SQL features (using field 'dsn')", conf.SQL.Driver)
}
if s.resCodecDeprecated, err = strToSQLResultCodecDeprecated(conf.SQL.ResultCodec); err != nil {
return nil, err
}
} else if s.resCodec, err = strToSQLResultCodec(conf.SQL.ResultCodec); err != nil {
return nil, err
}
if s.db, err = sql.Open(conf.SQL.Driver, dsn); err != nil {
return nil, err
}
if conf.SQL.UnsafeDynamicQuery {
if deprecated {
return nil, errors.New("cannot use dynamic queries when running in deprecated mode")
}
if s.dynQuery, err = interop.NewBloblangField(mgr, s.queryStr); err != nil {
return nil, fmt.Errorf("failed to parse dynamic query expression: %v", err)
}
}
isSelectQuery := s.resCodecDeprecated != nil || s.resCodec != nil
// Some drivers only support transactional prepared inserts.
if s.dynQuery == nil && (isSelectQuery || !insertRequiresTransactionPrepare(conf.SQL.Driver)) {
if s.query, err = s.db.Prepare(s.queryStr); err != nil {
s.db.Close()
return nil, fmt.Errorf("failed to prepare query: %v", err)
}
}
go func() {
defer func() {
s.dbMux.Lock()
s.db.Close()
if s.query != nil {
s.query.Close()
}
s.dbMux.Unlock()
close(s.closedChan)
}()
<-s.closeChan
}()
return s, nil
}
//------------------------------------------------------------------------------
type sqlResultCodec func(rows *sql.Rows, part types.Part) error
func sqlResultJSONArrayCodec(rows *sql.Rows, part types.Part) error {
columnNames, err := rows.Columns()
if err != nil {
return err
}
jArray := []interface{}{}
for rows.Next() {
values := make([]interface{}, len(columnNames))
valuesWrapped := make([]interface{}, len(columnNames))
for i := range values {
valuesWrapped[i] = &values[i]
}
if err := rows.Scan(valuesWrapped...); err != nil {
return err
}
jObj := map[string]interface{}{}
for i, v := range values {
switch t := v.(type) {
case string:
jObj[columnNames[i]] = t
case []byte:
jObj[columnNames[i]] = string(t)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
jObj[columnNames[i]] = t
case float32, float64:
jObj[columnNames[i]] = t
case bool:
jObj[columnNames[i]] = t
default:
jObj[columnNames[i]] = t
}
}
jArray = append(jArray, jObj)
}
if err := rows.Err(); err != nil {
return err
}
return part.SetJSON(jArray)
}
func strToSQLResultCodec(codec string) (sqlResultCodec, error) {
switch codec {
case "json_array":
return sqlResultJSONArrayCodec, nil
case "none":
return nil, nil
}
return nil, fmt.Errorf("unrecognised result codec: %v", codec)
}
//------------------------------------------------------------------------------
func (s *SQL) doExecute(argSets [][]interface{}) (errs []error) {
var err error
defer func() {
if err != nil {
if len(errs) == 0 {
errs = make([]error, len(argSets))
}
for i := range errs {
if errs[i] == nil {
errs[i] = err
}
}
}
}()
var tx *sql.Tx
if tx, err = s.db.Begin(); err != nil {
return
}
stmt := s.query
if stmt == nil {
if stmt, err = tx.Prepare(s.queryStr); err != nil {
return
}
defer stmt.Close()
} else {
stmt = tx.Stmt(stmt)
}
for i, args := range argSets {
if len(args) == 0 {
continue
}
if _, serr := stmt.Exec(args...); serr != nil {
if len(errs) == 0 {
errs = make([]error, len(argSets))
}
errs[i] = serr
}
}
err = tx.Commit()
return
}
func (s *SQL) getArgs(index int, msg types.Message) ([]interface{}, error) {
if len(s.args) > 0 {
args := make([]interface{}, len(s.args))
for i, v := range s.args {
args[i] = v.String(index, msg)
}
return args, nil
}
if s.argsMapping == nil {
return nil, nil
}
pargs, err := s.argsMapping.MapPart(index, msg)
if err != nil {
return nil, err
}
iargs, err := pargs.JSON()
if err != nil {
return nil, fmt.Errorf("mapping returned non-structured result: %w", err)
}
args, ok := iargs.([]interface{})
if !ok {
return nil, fmt.Errorf("mapping returned non-array result: %T", iargs)
}
return args, nil
}
// ProcessMessage logs an event and returns the message unchanged.
func (s *SQL) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
s.dbMux.RLock()
defer s.dbMux.RUnlock()
if s.deprecated {
return s.processMessageDeprecated(msg)
}
s.mCount.Incr(1)
newMsg := msg.Copy()
if s.resCodec == nil && s.dynQuery == nil {
argSets := make([][]interface{}, newMsg.Len())
newMsg.Iter(func(index int, p types.Part) error {
args, err := s.getArgs(index, msg)
if err != nil {
s.mErr.Incr(1)
s.log.Errorf("Args mapping error: %v\n", err)
FlagErr(newMsg.Get(index), err)
return nil
}
argSets[index] = args
return nil
})
for i, err := range s.doExecute(argSets) {
if err != nil {
s.mErr.Incr(1)
s.log.Errorf("SQL error: %v\n", err)
FlagErr(newMsg.Get(i), err)
}
}
} else {
IteratePartsWithSpanV2(TypeSQL, nil, newMsg, func(index int, span *tracing.Span, part types.Part) error {
args, err := s.getArgs(index, msg)
if err != nil {
s.mErr.Incr(1)
s.log.Errorf("Args mapping error: %v\n", err)
return err
}
if s.resCodec == nil {
if s.dynQuery != nil {
queryStr := s.dynQuery.String(index, msg)
_, err = s.db.Exec(queryStr, args...)
} else {
_, err = s.query.Exec(args...)
}
if err != nil {
return fmt.Errorf("failed to execute query: %w", err)
}
return nil
}
var rows *sql.Rows
if s.dynQuery != nil {
queryStr := s.dynQuery.String(index, msg)
rows, err = s.db.Query(queryStr, args...)
} else {
rows, err = s.query.Query(args...)
}
if err == nil {
defer rows.Close()
if err = s.resCodec(rows, part); err != nil {
err = fmt.Errorf("failed to apply result codec: %v", err)
}
} else {
err = fmt.Errorf("failed to execute query: %v", err)
}
if err != nil {
s.mErr.Incr(1)
s.log.Errorf("SQL error: %v\n", err)
return err
}
return nil
})
}
s.mBatchSent.Incr(1)
s.mSent.Incr(int64(newMsg.Len()))
msgs := [1]types.Message{newMsg}
return msgs[:], nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (s *SQL) CloseAsync() {
s.closeOnce.Do(func() {
close(s.closeChan)
})
}
// WaitForClose blocks until the processor has closed down.
func (s *SQL) WaitForClose(timeout time.Duration) error {
select {
case <-time.After(timeout):
return types.ErrTimeout
case <-s.closedChan:
}
return nil
}
//------------------------------------------------------------------------------ | lib/processor/sql.go | 0.719285 | 0.435241 | sql.go | starcoder |
package flightdb
import(
"fmt"
"regexp"
"strconv"
)
/* Callsigns, as used in ADS-B broadcasts
1. Many airlines use the ICAO flight number: SWA3848
2. Many private aircraft use their registration: N839AL
3. Some (private ?) aircraft use just their equipment type:
4. Annoyingly, some airlines use a bare flight number:
1106 - was FFT 1106 (F9 Frontier)
4517 - was SWA 4517 (WN Southwest)
948 - was SWA 948 (WN Southwest)
210 - was AAY 210 (G4 Allegiant Air)
We can use the airframe cache to fix most of these up
5. Various kinds of null idenitifiers:
00000000 - was A69C72 (a Cessna Citation)
???????? - was A85D50 (a Virgin America A320, flying as VX938 !!)
'' - sometimes a MSG,1 will contain an empty string for the callsign
6. Data from TRACON frequently has a suffix latter attached to the callsign
*/
// https://en.wikipedia.org/wiki/Airline_codes#Call_signs_.28flight_identification_or_flight_ID.29
type CallsignType int
const(
Undefined CallsignType = iota
JunkCallsign
Registration // Callsign Type A
// Callsign Type B - we never see it, and it's useless anyway
IcaoFlightNumber // Callsign Type C
BareFlightNumber // Some airlines omit the Icao carrier code, grr
// EquipType // We sometime see this, but it's useless
)
type Callsign struct {
Raw string
CallsignType
Registration string
IcaoPrefix string
ATCSuffix string // should be one char, really
Number int64
}
func (c Callsign)String() string {
switch c.CallsignType {
case IcaoFlightNumber:
return fmt.Sprintf("%s%d", c.IcaoPrefix, c.Number) // Strips leading zeroes and ATC suffix
default:
return c.Raw
}
}
func (c *Callsign)MaybeAddPrefix(prefix string) {
if c.CallsignType == BareFlightNumber {
c.IcaoPrefix = prefix
c.CallsignType = IcaoFlightNumber
}
}
func (c1 Callsign)Equal(c2 Callsign) bool {
return c1.String() == c2.String()
}
func CallsignStringsEqual(c1,c2 string) bool {
return NewCallsign(c1).Equal(NewCallsign(c2))
}
func NewCallsign(callsign string) (ret Callsign) {
ret.Raw = callsign
// Registration (e.g. N23ST). Wikipedia:
// An N-number may only consist of one to five characters, must
// start with a digit other than zero, and cannot end in a run of
// more than two letters. In addition, N-numbers may not contain the
// letters I or O
reg := regexp.MustCompile("^(N[1-9][0-9A-HJ-NP-Z]{0,4})$").FindStringSubmatch(callsign)
if reg != nil && len(reg)==2 {
ret.Registration = callsign
ret.CallsignType = Registration
return
}
icao := regexp.MustCompile("^([A-Z]{3})([0-9]{1,4})([A-Z]?)$").FindStringSubmatch(callsign)
if icao != nil && len(icao)==4 {
ret.Number,_ = strconv.ParseInt(icao[2], 10, 64) // no errors here :)
ret.IcaoPrefix = icao[1]
ret.ATCSuffix = icao[3]
ret.CallsignType = IcaoFlightNumber
return
}
bare := regexp.MustCompile("^([0-9]{2,4})$").FindStringSubmatch(callsign)
if bare != nil && len(bare)==2 {
ret.Number,_ = strconv.ParseInt(bare[1], 10, 64) // no errors here :)
ret.CallsignType = BareFlightNumber
return
}
ret.CallsignType = JunkCallsign
return
} | callsign.go | 0.539469 | 0.400632 | callsign.go | starcoder |
package ent
import (
"fmt"
"strings"
"time"
"github.com/empiricaly/recruitment/internal/ent/run"
"github.com/empiricaly/recruitment/internal/ent/step"
"github.com/empiricaly/recruitment/internal/ent/steprun"
"github.com/facebook/ent/dialect/sql"
)
// StepRun is the model entity for the StepRun schema.
type StepRun struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Status holds the value of the "status" field.
Status steprun.Status `json:"status,omitempty"`
// StartedAt holds the value of the "startedAt" field.
StartedAt *time.Time `json:"startedAt,omitempty"`
// EndedAt holds the value of the "endedAt" field.
EndedAt *time.Time `json:"endedAt,omitempty"`
// Index holds the value of the "index" field.
Index int `json:"index,omitempty"`
// ParticipantsCount holds the value of the "participantsCount" field.
ParticipantsCount int `json:"participantsCount,omitempty"`
// HitID holds the value of the "hitID" field.
HitID *string `json:"hitID,omitempty"`
// UrlToken holds the value of the "urlToken" field.
UrlToken string `json:"urlToken,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the StepRunQuery when eager-loading is set.
Edges StepRunEdges `json:"edges"`
run_steps *string
}
// StepRunEdges holds the relations/edges for other nodes in the graph.
type StepRunEdges struct {
// CreatedParticipants holds the value of the createdParticipants edge.
CreatedParticipants []*Participant
// Participants holds the value of the participants edge.
Participants []*Participant
// Participations holds the value of the participations edge.
Participations []*Participation
// Step holds the value of the step edge.
Step *Step
// Run holds the value of the run edge.
Run *Run
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [5]bool
}
// CreatedParticipantsOrErr returns the CreatedParticipants value or an error if the edge
// was not loaded in eager-loading.
func (e StepRunEdges) CreatedParticipantsOrErr() ([]*Participant, error) {
if e.loadedTypes[0] {
return e.CreatedParticipants, nil
}
return nil, &NotLoadedError{edge: "createdParticipants"}
}
// ParticipantsOrErr returns the Participants value or an error if the edge
// was not loaded in eager-loading.
func (e StepRunEdges) ParticipantsOrErr() ([]*Participant, error) {
if e.loadedTypes[1] {
return e.Participants, nil
}
return nil, &NotLoadedError{edge: "participants"}
}
// ParticipationsOrErr returns the Participations value or an error if the edge
// was not loaded in eager-loading.
func (e StepRunEdges) ParticipationsOrErr() ([]*Participation, error) {
if e.loadedTypes[2] {
return e.Participations, nil
}
return nil, &NotLoadedError{edge: "participations"}
}
// StepOrErr returns the Step value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e StepRunEdges) StepOrErr() (*Step, error) {
if e.loadedTypes[3] {
if e.Step == nil {
// The edge step was loaded in eager-loading,
// but was not found.
return nil, &NotFoundError{label: step.Label}
}
return e.Step, nil
}
return nil, &NotLoadedError{edge: "step"}
}
// RunOrErr returns the Run value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e StepRunEdges) RunOrErr() (*Run, error) {
if e.loadedTypes[4] {
if e.Run == nil {
// The edge run was loaded in eager-loading,
// but was not found.
return nil, &NotFoundError{label: run.Label}
}
return e.Run, nil
}
return nil, &NotLoadedError{edge: "run"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*StepRun) scanValues() []interface{} {
return []interface{}{
&sql.NullString{}, // id
&sql.NullTime{}, // created_at
&sql.NullTime{}, // updated_at
&sql.NullString{}, // status
&sql.NullTime{}, // startedAt
&sql.NullTime{}, // endedAt
&sql.NullInt64{}, // index
&sql.NullInt64{}, // participantsCount
&sql.NullString{}, // hitID
&sql.NullString{}, // urlToken
}
}
// fkValues returns the types for scanning foreign-keys values from sql.Rows.
func (*StepRun) fkValues() []interface{} {
return []interface{}{
&sql.NullString{}, // run_steps
}
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the StepRun fields.
func (sr *StepRun) assignValues(values ...interface{}) error {
if m, n := len(values), len(steprun.Columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
if value, ok := values[0].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field id", values[0])
} else if value.Valid {
sr.ID = value.String
}
values = values[1:]
if value, ok := values[0].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[0])
} else if value.Valid {
sr.CreatedAt = value.Time
}
if value, ok := values[1].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[1])
} else if value.Valid {
sr.UpdatedAt = value.Time
}
if value, ok := values[2].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[2])
} else if value.Valid {
sr.Status = steprun.Status(value.String)
}
if value, ok := values[3].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field startedAt", values[3])
} else if value.Valid {
sr.StartedAt = new(time.Time)
*sr.StartedAt = value.Time
}
if value, ok := values[4].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field endedAt", values[4])
} else if value.Valid {
sr.EndedAt = new(time.Time)
*sr.EndedAt = value.Time
}
if value, ok := values[5].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field index", values[5])
} else if value.Valid {
sr.Index = int(value.Int64)
}
if value, ok := values[6].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field participantsCount", values[6])
} else if value.Valid {
sr.ParticipantsCount = int(value.Int64)
}
if value, ok := values[7].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field hitID", values[7])
} else if value.Valid {
sr.HitID = new(string)
*sr.HitID = value.String
}
if value, ok := values[8].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field urlToken", values[8])
} else if value.Valid {
sr.UrlToken = value.String
}
values = values[9:]
if len(values) == len(steprun.ForeignKeys) {
if value, ok := values[0].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field run_steps", values[0])
} else if value.Valid {
sr.run_steps = new(string)
*sr.run_steps = value.String
}
}
return nil
}
// QueryCreatedParticipants queries the createdParticipants edge of the StepRun.
func (sr *StepRun) QueryCreatedParticipants() *ParticipantQuery {
return (&StepRunClient{config: sr.config}).QueryCreatedParticipants(sr)
}
// QueryParticipants queries the participants edge of the StepRun.
func (sr *StepRun) QueryParticipants() *ParticipantQuery {
return (&StepRunClient{config: sr.config}).QueryParticipants(sr)
}
// QueryParticipations queries the participations edge of the StepRun.
func (sr *StepRun) QueryParticipations() *ParticipationQuery {
return (&StepRunClient{config: sr.config}).QueryParticipations(sr)
}
// QueryStep queries the step edge of the StepRun.
func (sr *StepRun) QueryStep() *StepQuery {
return (&StepRunClient{config: sr.config}).QueryStep(sr)
}
// QueryRun queries the run edge of the StepRun.
func (sr *StepRun) QueryRun() *RunQuery {
return (&StepRunClient{config: sr.config}).QueryRun(sr)
}
// Update returns a builder for updating this StepRun.
// Note that, you need to call StepRun.Unwrap() before calling this method, if this StepRun
// was returned from a transaction, and the transaction was committed or rolled back.
func (sr *StepRun) Update() *StepRunUpdateOne {
return (&StepRunClient{config: sr.config}).UpdateOne(sr)
}
// Unwrap unwraps the entity that was returned from a transaction after it was closed,
// so that all next queries will be executed through the driver which created the transaction.
func (sr *StepRun) Unwrap() *StepRun {
tx, ok := sr.config.driver.(*txDriver)
if !ok {
panic("ent: StepRun is not a transactional entity")
}
sr.config.driver = tx.drv
return sr
}
// String implements the fmt.Stringer.
func (sr *StepRun) String() string {
var builder strings.Builder
builder.WriteString("StepRun(")
builder.WriteString(fmt.Sprintf("id=%v", sr.ID))
builder.WriteString(", created_at=")
builder.WriteString(sr.CreatedAt.Format(time.ANSIC))
builder.WriteString(", updated_at=")
builder.WriteString(sr.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", status=")
builder.WriteString(fmt.Sprintf("%v", sr.Status))
if v := sr.StartedAt; v != nil {
builder.WriteString(", startedAt=")
builder.WriteString(v.Format(time.ANSIC))
}
if v := sr.EndedAt; v != nil {
builder.WriteString(", endedAt=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", index=")
builder.WriteString(fmt.Sprintf("%v", sr.Index))
builder.WriteString(", participantsCount=")
builder.WriteString(fmt.Sprintf("%v", sr.ParticipantsCount))
if v := sr.HitID; v != nil {
builder.WriteString(", hitID=")
builder.WriteString(*v)
}
builder.WriteString(", urlToken=")
builder.WriteString(sr.UrlToken)
builder.WriteByte(')')
return builder.String()
}
// StepRuns is a parsable slice of StepRun.
type StepRuns []*StepRun
func (sr StepRuns) config(cfg config) {
for _i := range sr {
sr[_i].config = cfg
}
} | internal/ent/steprun.go | 0.600071 | 0.407186 | steprun.go | starcoder |
package geocube
//go:generate enumer -json -sql -type Resampling -trimprefix Resampling
import (
"fmt"
"regexp"
pb "github.com/airbusgeo/geocube/internal/pb"
"github.com/airbusgeo/godal"
"github.com/google/uuid"
)
// Resampling defines how the raster is resampled when its size has to be changed
type Resampling int32
// Supported values for resampling (gdal resampling methods)
const (
_ Resampling = iota // For compatibility with protobuf whose 0 is undefined
ResamplingNEAR
ResamplingBILINEAR
ResamplingCUBIC
ResamplingCUBICSPLINE
ResamplingLANCZOS
ResamplingAVERAGE
ResamplingMODE
ResamplingMAX
ResamplingMIN
ResamplingMED
ResamplingQ1
ResamplingQ3
)
// CanInterpolate returns true if the resampling may interpolate values
func (r Resampling) CanInterpolate() bool {
switch r {
case ResamplingBILINEAR, ResamplingCUBIC, ResamplingCUBICSPLINE, ResamplingLANCZOS, ResamplingAVERAGE:
return true
default:
return false
}
}
func (r Resampling) ToGDAL() godal.ResamplingAlg {
switch r {
default:
return godal.Nearest
case ResamplingBILINEAR:
return godal.Bilinear
case ResamplingCUBIC:
return godal.Cubic
case ResamplingCUBICSPLINE:
return godal.CubicSpline
case ResamplingLANCZOS:
return godal.Lanczos
case ResamplingAVERAGE:
return godal.Average
case ResamplingMODE:
return godal.Mode
case ResamplingMAX:
return godal.Max
case ResamplingMIN:
return godal.Min
case ResamplingMED:
return godal.Median
case ResamplingQ1:
return godal.Q1
case ResamplingQ3:
return godal.Q3
}
}
// VariableInstance is an instance of the VariableDefinition
type VariableInstance struct {
persistenceState
ID string
Name string
Metadata Metadata
}
// Variable described data
type Variable struct {
persistenceState
ID string
Name string
Instances map[string]*VariableInstance
Unit string
// Description [mutable]
Description string
// Storage [immutable]
Bands []string
DFormat DataFormat
// Views [mutable]
Palette string
// Default resampling algorithm [mutable]
Resampling Resampling
// Consolidation parameters
ConsolidationParams ConsolidationParams
}
// NewInstance creates a variable instance and validates it
func NewInstance(name string, metadata map[string]string) (*VariableInstance, error) {
vi := VariableInstance{
persistenceState: persistenceStateNEW,
ID: uuid.New().String(),
Name: name,
Metadata: Metadata(metadata),
}
if err := vi.validate(); err != nil {
return nil, err
}
return &vi, nil
}
// NewVariableFromProtobuf creates a variable from protobuf and validates it
// Only returns validationError
func NewVariableFromProtobuf(pbv *pb.Variable) (*Variable, error) {
dformat := NewDataFormatFromProtobuf(pbv.GetDformat())
if pbv.GetResamplingAlg() == pb.Resampling_UNDEFINED {
return nil, NewValidationError("Resampling algorithm cannot be undefined")
}
v := Variable{
persistenceState: persistenceStateNEW,
ID: uuid.New().String(),
Name: pbv.GetName(),
Unit: pbv.GetUnit(),
Description: pbv.GetDescription(),
Bands: pbv.GetBands(),
DFormat: *dformat,
Palette: pbv.GetPalette(),
Resampling: Resampling(pbv.GetResamplingAlg()),
}
if err := v.validate(); err != nil {
return nil, err
}
return &v, nil
}
// ToProtobuf converts a variable to a protobuf
func (v *Variable) ToProtobuf() *pb.Variable {
pbvar := &pb.Variable{
Id: v.ID,
Name: v.Name,
Unit: v.Unit,
Description: v.Description,
Dformat: v.DFormat.ToProtobuf(),
Bands: v.Bands,
Palette: v.Palette,
ResamplingAlg: pb.Resampling(v.Resampling),
Instances: make([]*pb.Instance, 0, len(v.Instances)),
}
for _, instance := range v.Instances {
pbvar.Instances = append(pbvar.Instances, &pb.Instance{
Id: instance.ID,
Name: instance.Name,
Metadata: instance.Metadata,
})
}
return pbvar
}
// Clean sets the status Clean to the variable and (if "all") all its instances
func (v *Variable) Clean(all bool) {
if all {
for _, vi := range v.Instances {
vi.Clean()
}
v.ConsolidationParams.Clean()
}
v.persistenceState.Clean()
}
// ToDelete sets the status ToDelete to one instance or to all instances and the variable itselfs
func (v *Variable) ToDelete(instanceID string) {
if instanceID == "" {
for _, vi := range v.Instances {
vi.toDelete()
}
v.ConsolidationParams.toDelete()
v.toDelete()
} else {
for _, vi := range v.Instances {
if vi.ID == instanceID {
vi.toDelete()
}
}
}
}
// Update updates the variable
func (v *Variable) Update(name, unit, description, palette *string, resampling *Resampling) error {
if name != nil && v.Name != *name {
v.Name = *name
v.dirty()
}
if unit != nil && v.Unit != *unit {
v.Unit = *unit
v.dirty()
}
if description != nil && v.Description != *description {
v.Description = *description
v.dirty()
}
if palette != nil && v.Palette != *palette {
v.Palette = *palette
v.dirty()
}
if resampling != nil && v.Resampling != *resampling {
v.Resampling = *resampling
v.dirty()
}
if v.IsDirty() {
return v.validate()
}
return nil
}
// SetConsolidationParams sets the consolidation parameters
// Only returns ValidationError
func (v *Variable) SetConsolidationParams(params ConsolidationParams) error {
v.ConsolidationParams = params
if !v.DFormat.canCastTo(¶ms.DFormat) || !params.DFormat.canCastTo(&v.DFormat) {
return NewValidationError("ConsolidationParams: DataFormats are not compatible")
}
return nil
}
// CheckInstanceExists checks that the instance belongs to the variable
func (v *Variable) CheckInstanceExists(instanceID string) error {
if _, ok := v.Instances[instanceID]; !ok {
return NewEntityNotFound("Instance", "id", instanceID, fmt.Sprintf("Instance %s does not belong to the variable %s (%s)", instanceID, v.Name, v.ID))
}
return nil
}
// checkInstanceDoesNotExist checks that no other instance has the same name
func (v *Variable) checkInstanceDoesNotExist(name, exceptInstanceID string) error {
for _, instance := range v.Instances {
if instance.ID != exceptInstanceID && instance.Name == name {
return NewEntityAlreadyExists("Instance", "name", v.Name+":"+name, "")
}
}
return nil
}
// AddInstance adds a new instance if possible
func (v *Variable) AddInstance(vi *VariableInstance) error {
// Search whether an instance with the same name already exists
if err := v.checkInstanceDoesNotExist(vi.Name, ""); err != nil {
return err
}
v.Instances[vi.ID] = vi
return nil
}
// UpdateInstance updates an instance of the variable
func (v *Variable) UpdateInstance(instanceID string, name *string, newMetadata map[string]string, delMetadataKeys []string) error {
instance := v.Instances[instanceID]
if name != nil && instance.Name != *name {
// Search whether an instance with the same name already exists
if err := v.checkInstanceDoesNotExist(*name, instanceID); err != nil {
return err
}
instance.Name = *name
instance.dirty()
}
// Insert or update new keys
for key, newVal := range newMetadata {
if val, ok := instance.Metadata[key]; !ok || val != newVal {
instance.Metadata[key] = newVal
instance.dirty()
}
}
// Delete keys
for _, key := range delMetadataKeys {
delete(instance.Metadata, key)
instance.dirty()
}
return instance.validate()
}
func (vi *VariableInstance) validate() error {
if _, err := uuid.Parse(vi.ID); err != nil {
return NewValidationError("Invalid uuid: " + vi.ID)
}
if m, err := regexp.MatchString("^[a-zA-Z0-9-:_]+$", vi.Name); err != nil || !m {
return NewValidationError("Invalid Name: " + vi.Name)
}
return nil
}
func (v *Variable) validate() error {
if _, err := uuid.Parse(v.ID); err != nil {
return NewValidationError("Invalid uuid: " + v.ID)
}
if !isValidURN(v.Name) {
return NewValidationError("Incorrect name: " + v.Name)
}
if v.Palette != "" && !isValidURN(v.Palette) {
return NewValidationError("Incorrect palette name: " + v.Palette)
}
if v.Palette != "" && len(v.Bands) != 1 {
return NewValidationError("Cannot define a palette to a multi-bands variable")
}
if err := v.DFormat.validate(); err != nil {
return NewValidationError("Incorrect data format: " + err.Error())
}
if len(v.Bands) == 0 {
return NewValidationError("Bands definition must have at least one band")
}
if len(v.Bands) > 1 {
for _, name := range v.Bands {
if name == "" {
return NewValidationError("Band name cannot be empty")
}
}
}
return nil
} | internal/geocube/variable.go | 0.666388 | 0.460532 | variable.go | starcoder |
package plaid
import (
"encoding/json"
)
// NumbersACH Identifying information for transferring money to or from a US account via ACH or wire transfer.
type NumbersACH struct {
// The Plaid account ID associated with the account numbers
AccountId string `json:"account_id"`
// The ACH account number for the account. Note that when using OAuth with Chase Bank (`ins_56`), Chase will issue \"tokenized\" routing and account numbers, which are not the user's actual account and routing numbers. These tokenized numbers should work identically to normal account and routing numbers. The digits returned in the `mask` field will continue to reflect the actual account number, rather than the tokenized account number; for this reason, when displaying account numbers to the user to help them identify their account in your UI, always use the `mask` rather than truncating the `account` number. If a user revokes their permissions to your app, the tokenized numbers will continue to work for ACH deposits, but not withdrawals.
Account string `json:"account"`
// The ACH routing number for the account. If the institution is `ins_56`, this may be a tokenized routing number. For more information, see the description of the `account` field.
Routing string `json:"routing"`
// The wire transfer routing number for the account, if available
WireRouting NullableString `json:"wire_routing"`
AdditionalProperties map[string]interface{}
}
type _NumbersACH NumbersACH
// NewNumbersACH instantiates a new NumbersACH 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 NewNumbersACH(accountId string, account string, routing string, wireRouting NullableString) *NumbersACH {
this := NumbersACH{}
this.AccountId = accountId
this.Account = account
this.Routing = routing
this.WireRouting = wireRouting
return &this
}
// NewNumbersACHWithDefaults instantiates a new NumbersACH 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 NewNumbersACHWithDefaults() *NumbersACH {
this := NumbersACH{}
return &this
}
// GetAccountId returns the AccountId field value
func (o *NumbersACH) GetAccountId() string {
if o == nil {
var ret string
return ret
}
return o.AccountId
}
// GetAccountIdOk returns a tuple with the AccountId field value
// and a boolean to check if the value has been set.
func (o *NumbersACH) GetAccountIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.AccountId, true
}
// SetAccountId sets field value
func (o *NumbersACH) SetAccountId(v string) {
o.AccountId = v
}
// GetAccount returns the Account field value
func (o *NumbersACH) GetAccount() string {
if o == nil {
var ret string
return ret
}
return o.Account
}
// GetAccountOk returns a tuple with the Account field value
// and a boolean to check if the value has been set.
func (o *NumbersACH) GetAccountOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Account, true
}
// SetAccount sets field value
func (o *NumbersACH) SetAccount(v string) {
o.Account = v
}
// GetRouting returns the Routing field value
func (o *NumbersACH) GetRouting() string {
if o == nil {
var ret string
return ret
}
return o.Routing
}
// GetRoutingOk returns a tuple with the Routing field value
// and a boolean to check if the value has been set.
func (o *NumbersACH) GetRoutingOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Routing, true
}
// SetRouting sets field value
func (o *NumbersACH) SetRouting(v string) {
o.Routing = v
}
// GetWireRouting returns the WireRouting field value
// If the value is explicit nil, the zero value for string will be returned
func (o *NumbersACH) GetWireRouting() string {
if o == nil || o.WireRouting.Get() == nil {
var ret string
return ret
}
return *o.WireRouting.Get()
}
// GetWireRoutingOk returns a tuple with the WireRouting field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *NumbersACH) GetWireRoutingOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.WireRouting.Get(), o.WireRouting.IsSet()
}
// SetWireRouting sets field value
func (o *NumbersACH) SetWireRouting(v string) {
o.WireRouting.Set(&v)
}
func (o NumbersACH) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["account_id"] = o.AccountId
}
if true {
toSerialize["account"] = o.Account
}
if true {
toSerialize["routing"] = o.Routing
}
if true {
toSerialize["wire_routing"] = o.WireRouting.Get()
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *NumbersACH) UnmarshalJSON(bytes []byte) (err error) {
varNumbersACH := _NumbersACH{}
if err = json.Unmarshal(bytes, &varNumbersACH); err == nil {
*o = NumbersACH(varNumbersACH)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "account_id")
delete(additionalProperties, "account")
delete(additionalProperties, "routing")
delete(additionalProperties, "wire_routing")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableNumbersACH struct {
value *NumbersACH
isSet bool
}
func (v NullableNumbersACH) Get() *NumbersACH {
return v.value
}
func (v *NullableNumbersACH) Set(val *NumbersACH) {
v.value = val
v.isSet = true
}
func (v NullableNumbersACH) IsSet() bool {
return v.isSet
}
func (v *NullableNumbersACH) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableNumbersACH(val *NumbersACH) *NullableNumbersACH {
return &NullableNumbersACH{value: val, isSet: true}
}
func (v NullableNumbersACH) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableNumbersACH) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | plaid/model_numbers_ach.go | 0.755276 | 0.426979 | model_numbers_ach.go | starcoder |
package sql
import (
"database/sql"
"database/sql/driver"
"fmt"
"reflect"
"strings"
)
// ColumnScanner is the interface that wraps the
// four sql.Rows methods used for scanning.
type ColumnScanner interface {
Next() bool
Scan(...interface{}) error
Columns() ([]string, error)
Err() error
}
// ScanOne scans one row to the given value. It fails if the rows holds more than 1 row.
func ScanOne(rows ColumnScanner, v interface{}) error {
columns, err := rows.Columns()
if err != nil {
return fmt.Errorf("sql/scan: failed getting column names: %v", err)
}
if n := len(columns); n != 1 {
return fmt.Errorf("sql/scan: unexpected number of columns: %d", n)
}
if !rows.Next() {
if err := rows.Err(); err != nil {
return err
}
return sql.ErrNoRows
}
if err := rows.Scan(v); err != nil {
return err
}
if rows.Next() {
return fmt.Errorf("sql/scan: expect exactly one row in result set")
}
return rows.Err()
}
// ScanInt64 scans and returns an int64 from the rows columns.
func ScanInt64(rows ColumnScanner) (int64, error) {
var n int64
if err := ScanOne(rows, &n); err != nil {
return 0, err
}
return n, nil
}
// ScanInt scans and returns an int from the rows columns.
func ScanInt(rows ColumnScanner) (int, error) {
n, err := ScanInt64(rows)
if err != nil {
return 0, err
}
return int(n), nil
}
// ScanString scans and returns a string from the rows columns.
func ScanString(rows ColumnScanner) (string, error) {
var s string
if err := ScanOne(rows, &s); err != nil {
return "", err
}
return s, nil
}
// ScanValue scans and returns a driver.Value from the rows columns.
func ScanValue(rows ColumnScanner) (driver.Value, error) {
var v driver.Value
if err := ScanOne(rows, &v); err != nil {
return "", err
}
return v, nil
}
// ScanSlice scans the given ColumnScanner (basically, sql.Row or sql.Rows) into the given slice.
func ScanSlice(rows ColumnScanner, v interface{}) error {
columns, err := rows.Columns()
if err != nil {
return fmt.Errorf("sql/scan: failed getting column names: %v", err)
}
rv := reflect.ValueOf(v)
switch {
case rv.Kind() != reflect.Ptr:
if t := reflect.TypeOf(v); t != nil {
return fmt.Errorf("sql/scan: ScanSlice(non-pointer %s)", t)
}
fallthrough
case rv.IsNil():
return fmt.Errorf("sql/scan: ScanSlice(nil)")
}
rv = reflect.Indirect(rv)
if k := rv.Kind(); k != reflect.Slice {
return fmt.Errorf("sql/scan: invalid type %s. expected slice as an argument", k)
}
scan, err := scanType(rv.Type().Elem(), columns)
if err != nil {
return err
}
if n, m := len(columns), len(scan.columns); n > m {
return fmt.Errorf("sql/scan: columns do not match (%d > %d)", n, m)
}
for rows.Next() {
values := scan.values()
if err := rows.Scan(values...); err != nil {
return fmt.Errorf("sql/scan: failed scanning rows: %v", err)
}
vv := reflect.Append(rv, scan.value(values...))
rv.Set(vv)
}
return rows.Err()
}
// rowScan is the configuration for scanning one sql.Row.
type rowScan struct {
// column types of a row.
columns []reflect.Type
// value functions that converts the row columns (result) to a reflect.Value.
value func(v ...interface{}) reflect.Value
}
// values returns a []interface{} from the configured column types.
func (r *rowScan) values() []interface{} {
values := make([]interface{}, len(r.columns))
for i := range r.columns {
values[i] = reflect.New(r.columns[i]).Interface()
}
return values
}
// scanType returns rowScan for the given reflect.Type.
func scanType(typ reflect.Type, columns []string) (*rowScan, error) {
switch k := typ.Kind(); {
case assignable(typ):
return &rowScan{
columns: []reflect.Type{typ},
value: func(v ...interface{}) reflect.Value {
return reflect.Indirect(reflect.ValueOf(v[0]))
},
}, nil
case k == reflect.Ptr:
return scanPtr(typ, columns)
case k == reflect.Struct:
return scanStruct(typ, columns)
default:
return nil, fmt.Errorf("sql/scan: unsupported type ([]%s)", k)
}
}
var scannerType = reflect.TypeOf((*sql.Scanner)(nil)).Elem()
// assignable reports if the given type can be assigned directly by `Rows.Scan`.
func assignable(typ reflect.Type) bool {
switch k := typ.Kind(); {
case typ.Implements(scannerType):
case k == reflect.Interface && typ.NumMethod() == 0:
case k == reflect.String || k >= reflect.Bool && k <= reflect.Float64:
case (k == reflect.Slice || k == reflect.Array) && typ.Elem().Kind() == reflect.Uint8:
default:
return false
}
return true
}
// scanStruct returns the a configuration for scanning an sql.Row into a struct.
func scanStruct(typ reflect.Type, columns []string) (*rowScan, error) {
var (
scan = &rowScan{}
idx = make([]int, 0, typ.NumField())
names = make(map[string]int, typ.NumField())
)
for i := 0; i < typ.NumField(); i++ {
f := typ.Field(i)
// Skip unexported fields.
if f.PkgPath != "" {
continue
}
name := strings.ToLower(f.Name)
if tag, ok := f.Tag.Lookup("sql"); ok {
name = tag
} else if tag, ok := f.Tag.Lookup("json"); ok {
name = strings.Split(tag, ",")[0]
}
names[name] = i
}
for _, c := range columns {
// Normalize columns if necessary, for example: COUNT(*) => count.
name := strings.ToLower(strings.Split(c, "(")[0])
i, ok := names[name]
if !ok {
return nil, fmt.Errorf("sql/scan: missing struct field for column: %s (%s)", c, name)
}
idx = append(idx, i)
scan.columns = append(scan.columns, typ.Field(i).Type)
}
scan.value = func(vs ...interface{}) reflect.Value {
st := reflect.New(typ).Elem()
for i, v := range vs {
st.Field(idx[i]).Set(reflect.Indirect(reflect.ValueOf(v)))
}
return st
}
return scan, nil
}
// scanPtr wraps the underlying type with rowScan.
func scanPtr(typ reflect.Type, columns []string) (*rowScan, error) {
typ = typ.Elem()
scan, err := scanType(typ, columns)
if err != nil {
return nil, err
}
wrap := scan.value
scan.value = func(vs ...interface{}) reflect.Value {
v := wrap(vs...)
pt := reflect.PtrTo(v.Type())
pv := reflect.New(pt.Elem())
pv.Elem().Set(v)
return pv
}
return scan, nil
} | dialect/sql/scan.go | 0.684897 | 0.464537 | scan.go | starcoder |
package cassgowary
import (
"fmt"
)
type Term struct {
Variable *Variable
Coefficient float64
}
type Terms []*Term
func NewTerm(v *Variable, coefficient float64) *Term {
return &Term{
Variable: v,
Coefficient: coefficient,
}
}
func NewTermFrom(variable *Variable) *Term {
return NewTerm(variable, 1.0)
}
func (t *Term) Value() float64 {
return t.Coefficient * t.Value()
}
func (t *Term) String() string {
return fmt.Sprintf(
`variable: (%s) coefficient:%f`,
t.Variable, t.Coefficient,
)
}
func (t *Term) Multiply(coefficient float64) *Term {
return NewTerm(t.Variable, t.Coefficient*coefficient)
}
func (t *Term) Divide(denominator float64) *Term {
return t.Multiply(1 / denominator)
}
func (t *Term) Negate() *Term {
return t.Multiply(-1)
}
func (t *Term) AddExpression(e *Expression) *Expression {
return e.AddTerm(t)
}
func (t *Term) Add(other *Term) *Expression {
terms := Terms{t, other}
return NewExpressionFrom(terms...)
}
func (t *Term) AddVariable(v *Variable) *Expression {
return t.Add(NewTermFrom(v))
}
func (t *Term) AddFloat(constant float64) *Expression {
return NewExpression(constant, t)
}
func (t *Term) SubtractExpression(e *Expression) *Expression {
return e.Negate().AddTerm(t)
}
func (t *Term) Subtract(other *Term) *Expression {
return t.Add(other.Negate())
}
func (t *Term) subtract(v *Variable) *Expression {
return t.Add(v.Negate())
}
func (t *Term) SubtractFloat(constant float64) *Expression {
return t.AddFloat(-constant)
}
func (t *Term) EqualsExpression(e *Expression) *Constraint {
return e.EqualsTerm(t)
}
func (t *Term) Equals(other *Term) *Constraint {
e := NewExpressionFrom(t)
c := e.EqualsTerm(other)
return c
}
func (t *Term) EqualsVariable(v *Variable) *Constraint {
return NewExpressionFrom(t).EqualsVariable(v)
}
func (t *Term) EqualsFloat(constant float64) *Constraint {
e := NewExpressionFrom(t)
c := e.EqualsFloat(constant)
return c
}
func (t *Term) LessThanOrEqualToExpression(e *Expression) *Constraint {
te := NewExpressionFrom(t)
c := te.LessThanOrEqualTo(e)
return c
}
func (t *Term) LessThanOrEqualTo(other *Term) *Constraint {
e := NewExpressionFrom(t)
c := e.LessThanOrEqualToTerm(other)
return c
}
func (t *Term) LessThanOrEqualToVariable(v *Variable) *Constraint {
e := NewExpressionFrom(t)
c := e.LessThanOrEqualToVariable(v)
return c
}
func (t *Term) LessThanOrEqualToFloat(constant float64) *Constraint {
e := NewExpressionFrom(t)
c := e.LessThanOrEqualToFloat(constant)
return c
}
func (t *Term) GreaterThanOrEqualToExpression(e *Expression) *Constraint {
te := NewExpressionFrom(t)
c := te.GreaterThanOrEqualTo(e)
return c
}
func (t *Term) GreaterThanOrEqualTo(other *Term) *Constraint {
e := NewExpressionFrom(t)
c := e.GreaterThanOrEqualToTerm(other)
return c
}
func (t *Term) GreaterThanOrEqualToVariable(v *Variable) *Constraint {
e := NewExpressionFrom(t)
c := e.GreaterThanOrEqualToVariable(v)
return c
}
func (t *Term) GreaterThanOrEqualToFloat(constant float64) *Constraint {
e := NewExpressionFrom(t)
c := e.GreaterThanOrEqualToFloat(constant)
return c
} | term.go | 0.8119 | 0.444384 | term.go | starcoder |
package schema
const ModelSchema = `{
"$id": "docs/spec/metricsets/metricset.json",
"type": "object",
"description": "Data captured by an agent representing an event occurring in a monitored service",
"allOf": [
{ "$id": "doc/spec/timestamp_epoch.json",
"title": "Timestamp Epoch",
"description": "Object with 'timestamp' property.",
"type": ["object"],
"properties": {
"timestamp": {
"description": "Recorded time of the event, UTC based and formatted as microseconds since Unix epoch",
"type": ["integer", "null"]
}
}},
{ "$id": "docs/spec/span_type.json",
"title": "Span Type",
"type": ["object"],
"properties": {
"type": {
"type": "string",
"description": "Keyword of specific relevance in the service's domain (eg: 'db.postgresql.query', 'template.erb', etc)",
"maxLength": 1024
}
} },
{ "$id": "docs/spec/span_subtype.json",
"title": "Span Subtype",
"type": ["object"],
"properties": {
"subtype": {
"type": ["string", "null"],
"description": "A further sub-division of the type (e.g. postgresql, elasticsearch)",
"maxLength": 1024
}
} },
{ "$id": "docs/spec/transaction_name.json",
"title": "Transaction Name",
"type": ["object"],
"properties": {
"name": {
"type": ["string","null"],
"description": "Generic designation of a transaction in the scope of a single service (eg: 'GET /users/:id')",
"maxLength": 1024
}
} },
{ "$id": "docs/spec/transaction_type.json",
"title": "Transaction Type",
"type": ["object"],
"properties": {
"type": {
"type": "string",
"description": "Keyword of specific relevance in the service's domain (eg: 'request', 'backgroundjob', etc)",
"maxLength": 1024
}
} },
{
"properties": {
"samples": {
"type": [
"object"
],
"description": "Sampled application metrics collected from the agent.",
"patternProperties": {
"^[^*\"]*$": {
"$schema": "http://json-schema.org/draft-04/schema#",
"$id": "docs/spec/metricsets/sample.json",
"type": ["object", "null"],
"description": "A single metric sample.",
"properties": {
"value": {"type": "number"}
},
"required": ["value"]
}
},
"additionalProperties": false
},
"tags": {
"$id": "doc/spec/tags.json",
"title": "Tags",
"type": ["object", "null"],
"description": "A flat mapping of user-defined tags with string, boolean or number values.",
"patternProperties": {
"^[^.*\"]*$": {
"type": ["string", "boolean", "number", "null"],
"maxLength": 1024
}
},
"additionalProperties": false
}
},
"required": ["samples"]
},
{"required": ["timestamp"], "properties": {"timestamp": { "type": "integer" }}}
]
}
` | model/metricset/generated/schema/metricset.go | 0.780286 | 0.562417 | metricset.go | starcoder |
package s11n
import (
"strconv"
"strings"
"gopkg.in/yaml.v3"
)
// MatchOne returns the yaml node that matches the provided path.
// If zero or more than one node matches the provided path,
// MatchOne will return nil
func MatchOne(node *yaml.Node, path string) *yaml.Node {
results := make([]*yaml.Node, 0)
for n := range MatchAll(node, path) {
results = append(results, n)
}
if len(results) != 1 {
return nil
}
return results[0]
}
// MatchAll returns all yaml nodes that match the provided path.
// The path is a `/`-separated string that describes a path into the template's tree.
// Wildcard elements (which can be map keys or array indices) are represented by a `*`.
// Matching an arbitrary number (including zero) of descendents can be done with `**`.
func MatchAll(node *yaml.Node, path string) <-chan *yaml.Node {
ch := make(chan *yaml.Node)
go func() {
matchPath(ch, node, strings.Split(path, "/"))
close(ch)
}()
return ch
}
func matchPath(ch chan<- *yaml.Node, n *yaml.Node, path []string) {
if n.Kind == yaml.DocumentNode {
for _, doc := range n.Content {
matchPath(ch, doc, path)
}
return
}
if len(path) == 0 {
ch <- n
return
}
head, tail := path[0], path[1:]
query := make([]string, 0)
// Deal with recursive descent
if head == "**" {
matchPath(ch, n, tail)
if n.Kind == yaml.MappingNode {
for i := 0; i < len(n.Content); i += 2 {
matchPath(ch, n.Content[i+1], path)
}
} else if n.Kind == yaml.SequenceNode {
for _, child := range n.Content {
matchPath(ch, child, path)
}
}
}
// Parse out any query
parts := strings.Split(head, "|")
if len(parts) == 2 {
head = parts[0]
query = parts[1:]
}
if n.Kind == yaml.MappingNode {
for i := 0; i < len(n.Content); i += 2 {
key := n.Content[i]
if head == "*" || key.Value == head {
value := n.Content[i+1]
if filter(value, query) {
matchPath(ch, value, tail)
}
}
}
} else if n.Kind == yaml.SequenceNode {
if head == "*" {
for _, child := range n.Content {
if filter(child, query) {
matchPath(ch, child, tail)
}
}
} else {
i, err := strconv.Atoi(head)
if err == nil && i < len(n.Content) {
value := n.Content[i]
if filter(value, query) {
matchPath(ch, value, tail)
}
}
}
}
}
func filter(n *yaml.Node, query []string) bool {
for _, q := range query {
parts := strings.Split(q, "==")
var value *yaml.Node
if n.Kind == yaml.MappingNode {
for i := 0; i < len(n.Content); i += 2 {
if n.Content[i].Value == parts[0] {
value = n.Content[i+1]
break
}
}
if value == nil {
return false
}
} else if n.Kind == yaml.SequenceNode {
i, err := strconv.Atoi(parts[0])
if err != nil || i >= len(n.Content) {
return false
}
value = n.Content[i]
} else {
return false
}
if len(parts) == 2 && value.Value != parts[1] {
if value.Kind != yaml.ScalarNode {
return false
}
return false
}
}
return true
} | internal/s11n/match.go | 0.761627 | 0.443239 | match.go | starcoder |
package stripe
import "encoding/json"
// Retrieves the promotion code with the given ID. In order to retrieve a promotion code by the customer-facing code use [list](https://stripe.com/docs/api/promotion_codes/list) with the desired code.
type PromotionCodeParams struct {
Params `form:"*"`
// Whether the promotion code is currently active.
Active *bool `form:"active"`
// The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for a specific customer. If left blank, we will generate one automatically.
Code *string `form:"code"`
// The coupon for this promotion code.
Coupon *string `form:"coupon"`
// The customer that this promotion code can be used by. If not set, the promotion code can be used by all customers.
Customer *string `form:"customer"`
// The timestamp at which this promotion code will expire. If the coupon has specified a `redeems_by`, then this value cannot be after the coupon's `redeems_by`.
ExpiresAt *int64 `form:"expires_at"`
// A positive integer specifying the number of times the promotion code can be redeemed. If the coupon has specified a `max_redemptions`, then this value cannot be greater than the coupon's `max_redemptions`.
MaxRedemptions *int64 `form:"max_redemptions"`
// Settings that restrict the redemption of the promotion code.
Restrictions *PromotionCodeRestrictionsParams `form:"restrictions"`
}
// Settings that restrict the redemption of the promotion code.
type PromotionCodeRestrictionsParams struct {
// A Boolean indicating if the Promotion Code should only be redeemed for Customers without any successful payments or invoices
FirstTimeTransaction *bool `form:"first_time_transaction"`
// Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work).
MinimumAmount *int64 `form:"minimum_amount"`
// Three-letter [ISO code](https://stripe.com/docs/currencies) for minimum_amount
MinimumAmountCurrency *string `form:"minimum_amount_currency"`
}
// Returns a list of your promotion codes.
type PromotionCodeListParams struct {
ListParams `form:"*"`
// Filter promotion codes by whether they are active.
Active *bool `form:"active"`
// Only return promotion codes that have this case-insensitive code.
Code *string `form:"code"`
// Only return promotion codes for this coupon.
Coupon *string `form:"coupon"`
// A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options.
Created *int64 `form:"created"`
// A filter on the list, based on the object `created` field. The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options.
CreatedRange *RangeQueryParams `form:"created"`
// Only return promotion codes that are restricted to this customer.
Customer *string `form:"customer"`
}
type PromotionCodeRestrictions struct {
// A Boolean indicating if the Promotion Code should only be redeemed for Customers without any successful payments or invoices
FirstTimeTransaction bool `json:"first_time_transaction"`
// Minimum amount required to redeem this Promotion Code into a Coupon (e.g., a purchase must be $100 or more to work).
MinimumAmount int64 `json:"minimum_amount"`
// Three-letter [ISO code](https://stripe.com/docs/currencies) for minimum_amount
MinimumAmountCurrency Currency `json:"minimum_amount_currency"`
}
// A Promotion Code represents a customer-redeemable code for a coupon. It can be used to
// create multiple codes for a single coupon.
type PromotionCode struct {
APIResource
// Whether the promotion code is currently active. A promotion code is only active if the coupon is also valid.
Active bool `json:"active"`
// The customer-facing code. Regardless of case, this code must be unique across all active promotion codes for each customer.
Code string `json:"code"`
// A coupon contains information about a percent-off or amount-off discount you
// might want to apply to a customer. Coupons may be applied to [invoices](https://stripe.com/docs/api#invoices) or
// [orders](https://stripe.com/docs/api#create_order_legacy-coupon). Coupons do not work with conventional one-off [charges](https://stripe.com/docs/api#create_charge).
Coupon *Coupon `json:"coupon"`
// Time at which the object was created. Measured in seconds since the Unix epoch.
Created int64 `json:"created"`
// The customer that this promotion code can be used by.
Customer *Customer `json:"customer"`
// Date at which the promotion code can no longer be redeemed.
ExpiresAt int64 `json:"expires_at"`
// Unique identifier for the object.
ID string `json:"id"`
// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
Livemode bool `json:"livemode"`
// Maximum number of times this promotion code can be redeemed.
MaxRedemptions int64 `json:"max_redemptions"`
// Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
Metadata map[string]string `json:"metadata"`
// String representing the object's type. Objects of the same type share the same value.
Object string `json:"object"`
Restrictions *PromotionCodeRestrictions `json:"restrictions"`
// Number of times this promotion code has been used.
TimesRedeemed int64 `json:"times_redeemed"`
}
// PromotionCodeList is a list of PromotionCodes as retrieved from a list endpoint.
type PromotionCodeList struct {
APIResource
ListMeta
Data []*PromotionCode `json:"data"`
}
// UnmarshalJSON handles deserialization of a PromotionCode.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (p *PromotionCode) UnmarshalJSON(data []byte) error {
if id, ok := ParseID(data); ok {
p.ID = id
return nil
}
type promotionCode PromotionCode
var v promotionCode
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*p = PromotionCode(v)
return nil
} | promotioncode.go | 0.852168 | 0.477006 | promotioncode.go | starcoder |
package types
import (
"errors"
"fmt"
"hash"
"github.com/spaolacci/murmur3"
)
// MalType - the root type of all mal values
type MalType interface{}
// Counted - collections that have finite, known size
type Counted interface {
Count() int
}
// Seqable - collections that can produce a traversing sequence, or are empty
type Seqable interface {
Seq() Seq
}
// Sequential - collections that have an order
type Sequential interface {
Seqable
Sequential()
}
// Seq - a traversal of a sequence
type Seq interface {
// Next returns a tuple of emptiness, the first item if non-empty, and the tail seq
Next() (bool, MalType, Seq)
}
// HasSimpleValueEquality - is a type which can compare itself to other values
type HasSimpleValueEquality interface {
ValueEquals(MalType) bool
hashBytes() []byte
}
// HasMetadata - the type has metadata
type HasMetadata interface {
Metadata() Map
WithMetadata(m Map) HasMetadata
}
// Applicable - a list-y form that applies the rest to the first when evaluated
type Applicable interface {
Sequential
Applicable()
}
// Conjable - collection supports conjoining
type Conjable interface {
Conj(MalType) (Conjable, error)
}
// Indexed - collection supports lookup by key
type Indexed interface {
Lookup(MalType) (MalType, bool)
}
func hashAnyValue(hash *hash.Hash32, value *MalType) {
switch cast := (*value).(type) {
case HasSimpleValueEquality:
(*hash).Write(cast.hashBytes())
case Sequential:
seq := cast.Seq()
for {
empty, head, tail := seq.Next()
if empty {
break
}
hashAnyValue(hash, &head)
seq = tail
}
case Map:
(*hash).Write([]byte("{}"))
seq := cast.Seq()
for {
empty, head, tail := seq.Next()
if empty {
break
}
hashAnyValue(hash, &head)
seq = tail
}
default:
// TODO hash the pointer address for instance identity
}
}
// Hash computes a murmur3 hash of the given value
func Hash(value MalType) uint32 {
hash := murmur3.New32()
hashAnyValue(&hash, &value)
return hash.Sum32()
}
type hasher struct{}
func (h hasher) Hash(key interface{}) uint32 {
return Hash(key)
}
func (h hasher) Equal(a, b interface{}) bool {
return Equals(a, b)
}
// Equals compares values
func Equals(this MalType, that MalType) bool {
switch cast := this.(type) {
case HasSimpleValueEquality:
return cast.ValueEquals(that)
case Map:
thatMap, valid := that.(Map)
if !valid {
return false
}
thisImm := cast.Imm
thatImm := thatMap.Imm
if thisImm.Len() != thatImm.Len() {
return false
}
itr := thisImm.Iterator()
for !itr.Done() {
k, v := itr.Next()
v2, found := thatImm.Get(k)
if !found {
return false
}
if !Equals(v, v2) {
return false
}
}
return true
case Sequential:
thatSequential, valid := that.(Sequential)
if !valid {
return false
}
thisSeq := cast.Seq()
thatSeq := thatSequential.Seq()
for {
thisEmpty, thisHead, thisTail := thisSeq.Next()
thatEmpty, thatHead, thatTail := thatSeq.Next()
if thisEmpty && thatEmpty {
return true
}
if thisEmpty || thatEmpty {
return false
}
if !Equals(thisHead, thatHead) {
return false
}
thisSeq = thisTail
thatSeq = thatTail
}
default:
return false
}
}
// Compare compares values
func Compare(this MalType, that MalType) (int8, error) {
switch cast := this.(type) {
case Integer:
thatInt, valid := that.(Integer)
if !valid {
return 0, errors.New("Incomparable values")
}
delta := cast - thatInt
if delta > 0 {
return 1, nil
} else if delta == 0 {
return 0, nil
}
return -1, nil
default:
return 0, errors.New("Incomparable values")
}
}
// MalError contains any mal reason
type MalError struct {
Reason MalType
}
func (err MalError) Error() string {
return fmt.Sprintf("%v", err.Reason)
}
// Undefined errors
type Undefined struct {
Name string
}
func (err Undefined) Error() string {
return fmt.Sprintf("'%v' not found", err.Name)
} | types/types.go | 0.607663 | 0.432782 | types.go | starcoder |
package common
import (
"fmt"
"math"
)
// This is an improved version of Viterbi map matching, where we handle sparse traces by
// applying multiple transitions based on the distance between observations. For example,
// if two consecutive samples are k*VITERBI2_GRANULARITY apart, then we will apply (k-1)
// transitions prior to a transition+emission pair.
// Additionally, Viterbi2 takes an edgeWeights map so that some edges being more likely
// than other edges can be taken into account in the model. If edgeWeights is nil, then
// the weights are determined based on the angle between the segments, similar to the
// process in the old Viterbi function.
const VITERBI2_GRANULARITY = 50
const VITERBI2_SIGMA = 30
const VITERBI2_START_TOLERANCE = 100
// Map match each trace in traces to the road network specified by graph.
// edgeWeights: a map from edge IDs to weight of the ID. If nil, the transition probabilities
// are weighted based on the angle difference between the source and destination edges.
// hitsOnly: only compute edgeHits, do not store the map-matched data.
// Returns edgeHits, a map from edge ID to the number of times the edge is passed by a trace.
func Viterbi2(traces []*Trace, graph *Graph, edgeWeights map[int]float64, hitsOnly bool) (edgeHits map[int]int) {
// precompute transition probabilities
transitionProbs := make([]map[int]float64, len(graph.Edges))
for _, edge := range graph.Edges {
probs := make(map[int]float64)
transitionProbs[edge.ID] = probs
var adjacentEdges []*Edge
for _, other := range edge.Dst.Out {
adjacentEdges = append(adjacentEdges, other)
}
// on all edges there is 0.5 self loop
probs[edge.ID] = 0.5
var totalProb float64 = 0.5
// compute weights to adjacent edges if needed
weights := edgeWeights
if weights == nil {
weights = make(map[int]float64)
for _, other := range adjacentEdges {
negAngle := math.Pi / 2 - edge.AngleTo(other)
if negAngle < 0 {
negAngle = 0
}
weights[other.ID] = negAngle * negAngle + 0.05
}
}
// extract probabilities from the weights
// we force the average probability to be at most 0.05
// any additional probability mass is discarded (essentially it is directed to an
// impossible state)
var totalWeight float64 = 0
for _, other := range adjacentEdges {
totalWeight += weights[other.ID]
}
averageWeight := totalWeight / float64(len(adjacentEdges))
averageProb := 0.05
if averageProb * float64(len(adjacentEdges)) + totalProb > 0.9 {
averageProb = (0.9 - totalProb) / float64(len(adjacentEdges))
}
for _, other := range adjacentEdges {
prob := averageProb * weights[other.ID] / averageWeight
probs[other.ID] = prob
totalProb += prob
}
}
rtree := graph.Rtree()
// get conditional emission probabilities
emissionProbs := func(point Point, tolerance float64) map[int]float64 {
candidates := rtree.Search(point.RectangleTol(tolerance))
if len(candidates) == 0 {
return nil
}
scores := make(map[int]float64)
var totalScore float64 = 0
for _, edge := range candidates {
distance := edge.Segment().Distance(point)
score := math.Exp(-0.5 * distance * distance / VITERBI2_SIGMA / VITERBI2_SIGMA)
scores[edge.ID] = score
totalScore += score
}
for i := range scores {
scores[i] /= totalScore
}
return scores
}
// match a single trace
matchTrace := func(trace *Trace, edgeHits map[int]int) {
if len(trace.Observations) < 5 {
fmt.Printf("viterbi: warning: too few observations, skipping trace (%d)", len(trace.Observations))
return
}
// initial probability is uniform across candidates
probs := make(map[int]float64)
for _, edge := range rtree.Search(trace.Observations[0].Point.RectangleTol(VITERBI2_START_TOLERANCE)) {
probs[edge.ID] = 0
}
backpointers := make([][]map[int]int, len(trace.Observations))
for i := 1; i < len(trace.Observations); i++ {
obs := trace.Observations[i]
// apply extra transitions in case the vehicle traveled a large distance from the
// previous observation
distance := obs.Point.Distance(trace.Observations[i - 1].Point)
for distance > VITERBI2_GRANULARITY {
nextProbs := make(map[int]float64)
nextBackpointers := make(map[int]int)
for prevEdgeID := range probs {
transitions := transitionProbs[prevEdgeID]
for nextEdgeID := range transitions {
prob := probs[prevEdgeID] + math.Log(transitions[nextEdgeID])
if curProb, ok := nextProbs[nextEdgeID]; !ok || prob > curProb {
nextProbs[nextEdgeID] = prob
nextBackpointers[nextEdgeID] = prevEdgeID
}
}
}
backpointers[i] = append(backpointers[i], nextBackpointers)
probs = nextProbs
distance -= VITERBI2_GRANULARITY
}
var nextProbs map[int]float64
var nextBackpointers map[int]int
// find the most likely to match the emission+transition
// we use an increasing factor in case there are no edges within a reasonable distance
// from the observed point
for factor := float64(1); len(nextProbs) < 2 && factor <= 4; factor *= 2 {
nextProbs = make(map[int]float64)
nextBackpointers = make(map[int]int)
emissions := emissionProbs(obs.Point, VITERBI2_START_TOLERANCE * factor)
if factor > 1 {
//fmt.Printf("viterbi: warning: factor=%f at i=%d, point=%v\n", factor, i, obs.Point)
}
for prevEdgeID := range probs {
transitions := transitionProbs[prevEdgeID]
for nextEdgeID := range transitions {
if emissions[nextEdgeID] == 0 {
continue
}
prob := probs[prevEdgeID] + math.Log(transitions[nextEdgeID]) + math.Log(emissions[nextEdgeID])
if curProb, ok := nextProbs[nextEdgeID]; !ok || prob > curProb {
nextProbs[nextEdgeID] = prob
nextBackpointers[nextEdgeID] = prevEdgeID
}
}
}
}
backpointers[i] = append(backpointers[i], nextBackpointers)
if len(nextProbs) == 0 {
fmt.Printf("viterbi: warning: failed to find edge, skipping trace: i=%d, point=%v\n", i, obs.Point)
return
}
probs = nextProbs
}
// collect state sequence and annotate trace with map matched data
var bestEdgeID *int
for edgeID := range probs {
if bestEdgeID == nil || probs[edgeID] > probs[*bestEdgeID] {
bestEdgeID = &edgeID
}
}
curEdge := *bestEdgeID
for i := len(trace.Observations) - 1; i >= 0; i-- {
if !hitsOnly {
edge := graph.Edges[curEdge]
position := edge.Segment().Project(trace.Observations[i].Point, false)
trace.Observations[i].SetMetadata("viterbi", EdgePos{edge, position})
}
for j := len(backpointers[i]) - 1; j >= 0; j-- {
prevEdge := backpointers[i][j][curEdge]
if prevEdge != curEdge {
edgeHits[curEdge]++
curEdge = prevEdge
}
}
}
}
traceCh := make(chan *Trace)
n := 48
doneCh := make(chan map[int]int)
for i := 0; i < n; i++ {
go func() {
edgeHits := make(map[int]int)
for trace := range traceCh {
matchTrace(trace, edgeHits)
}
doneCh <- edgeHits
}()
}
for traceIdx, trace := range traces {
if traceIdx % 100 == 0 {
fmt.Printf("progress: %d/%d\n", traceIdx, len(traces))
}
traceCh <- trace
}
close(traceCh)
edgeHits = make(map[int]int)
for i := 0; i < n; i++ {
threadEdgeHits := <- doneCh
for edgeID, hits := range threadEdgeHits {
edgeHits[edgeID] += hits
}
}
return
} | fbastani-solution/common/viterbi2.go | 0.734881 | 0.693674 | viterbi2.go | starcoder |
package engine
import (
"softchess/internal/softchess.types"
)
// Tests found in board_test.go
// boardEvaluator calculates the board value
type boardEvaluator struct {
board *Board
}
// newBoardEvaluator creates a new boardEvaluator for the board
func newBoardEvaluator(board *Board) *boardEvaluator {
b := new(boardEvaluator)
b.board = board
return b
}
// getBoardValue returns the board value
func (e *boardEvaluator) getBoardValue() int {
var pieceValues map[string]int
pieceValues = make(map[string]int, 16)
var posValues map[string]int
posValues = make(map[string]int, 16)
value := 0
pos := types.NewPosXY(0, 0)
for y := 8; y >= 1; y-- {
for x := 1; x <= 8; x++ {
pos.SetXY(x, y)
if !e.board.HasPiece(pos) {
continue
}
pieceValue := 0
posValue := 0
if e.board.Color(pos) == types.ColorWhite {
pieceValue += e.getBasePieceValue(pos)
posValue += e.getPiecePositionBonus(pos)
} else {
pieceValue += e.getBasePieceValue(pos)
posValue += e.getPiecePositionBonus(pos)
}
value += posValue + pieceValue
pieceValues[pos.String()] = pieceValue
posValues[pos.String()] = posValue
}
}
return value
}
// getBasePieceValue returns the base value for the piece at position pos
func (e *boardEvaluator) getBasePieceValue(pos *types.Position) int {
piece := e.board.Piece(pos)
color := e.board.Color(pos)
value := 0
switch piece {
case types.PieceTypePawn:
value = 100
case types.PieceTypeBishop:
value = 330
case types.PieceTypeKnight:
value = 320
case types.PieceTypeRook:
value = 500
case types.PieceTypeQueen:
value = 900
case types.PieceTypeKing:
value = 20000.0
}
if color == types.ColorBlack {
value *= -1
}
return value
}
// getPiecePositionBonus returns the position bonus for the piece
// at position pos.
func (e *boardEvaluator) getPiecePositionBonus(pos *types.Position) int {
var bonusTable [8][8]int
switch e.board.Piece(pos) {
case types.PieceTypePawn:
bonusTable = pawnPositionFactor
case types.PieceTypeKnight:
bonusTable = knightPositionFactor
case types.PieceTypeBishop:
bonusTable = bishopPositionFactor
case types.PieceTypeRook:
bonusTable = rookPositionFactor
case types.PieceTypeQueen:
bonusTable = queenPositionFactor
case types.PieceTypeKing:
if e.isEndGame() {
bonusTable = kingPositionFactorEnd
} else {
bonusTable = kingPositionFactorEarlyMid
}
default:
return 0
}
x, y := pos.XY()
if e.board.Color(pos) == types.ColorBlack {
return -bonusTable[y-1][x-1]
}
return bonusTable[8-y][x-1]
}
// TODO : Fix is end game (https://www.chessprogramming.org/Simplified_Evaluation_Function)
// 1. Both sides have no queens or
// 2. Every side which has a queen has additionally no other pieces or one minor piece maximum.
// isEndGame currently returns true
func (e *boardEvaluator) isEndGame() bool {
return false
} | internal/softchess.engine/boardEvaluator.go | 0.642881 | 0.434341 | boardEvaluator.go | starcoder |
package num
import (
"math"
"strconv"
"strings"
)
// Int is the default value used in Sets and Matrices in this package
type Int int64
func init() {
// populate atoi map for Abc func
for i, v := range abc {
atoi[v] = Int(i + 1)
}
}
// String returns n as a base 10 string and satisfies the stringer interface
func (n Int) String() string {
return strconv.FormatInt(int64(n), 10)
}
// ToSet returns n as a set of its digits
func (n Int) ToSet() Set {
var (
res Set
s = strconv.FormatInt(int64(n), 10)
)
for _, v := range s {
i, _ := strconv.ParseInt(string(v), 10, 64)
res = append(res, Int(i))
}
return res
}
// Divisors returns a Set of divisors of n
func (n Int) Divisors() Set {
var (
div Set
lim = Int(math.Sqrt(float64(n)))
)
for i := Int(1); i <= lim; i++ {
if n%i == 0 {
div = append(div, i)
if i*i != n {
div = append(div, n/i)
}
}
}
return div.Dedupe()
}
// PrimeFactors returns the Set of prime factors of n
func (n Int) PrimeFactors() Set {
pf := Set{}
for _, v := range n.Divisors() {
if v.Is(PRIME) {
pf = append(pf, v)
}
}
return pf
}
// Factorial returns n!
func (n Int) Factorial() Int {
if n == 0 {
return Int(1)
}
res := n
for i := n - 1; i > 0; i-- {
res *= i
}
return res
}
// Totient returns the result of Eulers Totient or Phi function of value n
func (n Int) Totient() Int {
ans := n
for _, prime := range n.PrimeFactors() {
ans = ans * (prime - 1) / prime
}
return ans
}
// CfSqrt returns the recurring pattern of the infinite continued fraction of Sqrt(n).
// Returns nil if n is square
func (n Int) CfSqrt() Set {
var res Set
if _, frac := math.Modf(math.Sqrt(float64(n))); frac == 0 {
return nil
}
m := Int(math.Floor(math.Sqrt(float64(n))))
res = append(res, m)
for x, y := Int(1), m; ; {
x = (n - y*y) / x
res = append(res, (m+y)/x)
y = m - (m+y)%x
if x <= 1 {
break
}
}
return res
}
// ADP returns A(bundant), D(eficient) or P(erfect) depending on the value of n,
// reutrns E if an error occurred (theoretically impossible)
func (n Int) ADP() string {
d := n.Divisors()
s := d[:len(d)-1].Sum()
switch {
case s == n:
return "P"
case s < n:
return "D"
case s > n:
return "A"
}
return "E"
}
// Rotations returns a sequence of rotations of n.
// I.e Rotations(123) = 123 -> 312 -> 231
func (n Int) Rotations() chan Int {
c := make(chan Int, 1)
go func() {
defer close(c)
s := n.ToSet()
for i := 0; i < len(s); i++ {
rt := append(Set{s[len(s)-1]}, s[:len(s)-1]...)
c <- rt.ToInt()
s = rt
}
}()
return c
}
// Truncate returns a channel of Int slices that contain the
// truncation sequence of n from the left and the right simultaneously.
// I.e Truncate(123) = [123, 123] -> [23, 12] -> [3, 1]
func (n Int) Truncate() chan Set {
c := make(chan Set, 1)
go func() {
defer close(c)
s := n.ToSet()
for i := range s {
c <- Set{s[i:].ToInt(), s[:len(s)-i].ToInt()}
}
}()
return c
}
// Partition returns the number of partitions of n with m parts. See https://en.wikipedia.org/wiki/Partition_(number_theory)
func Partition(n, m Int) Int {
if m < 2 {
return m
}
if n < m {
return 0
}
var memo Matrix
for i := Int(0); i <= n-m; i++ {
memo = append(memo, make(Set, m))
}
var p func(n, m Int) Int
p = func(n, m Int) Int {
if n <= m+1 {
return 1
}
if memo[n-m][m-2] != 0 {
return memo[n-m][m-2]
}
max := n / m
if m == 2 {
return max
}
count := Int(0)
for ; max > 0; max, n = max-1, n-m {
memo[n-m][m-3] = p(n-1, m-1)
count += memo[n-m][m-3]
}
return count
}
return p(n, m)
}
var abc = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
var atoi = make(map[byte]Int)
// AbcToInt returns the a = 1, b = 2 etc score for string s
func AbcToInt(s string) Int {
s = strings.ToUpper(s)
score := Int(0)
for _, v := range []byte(s) {
score += atoi[v]
}
return score
} | num.go | 0.798619 | 0.409398 | num.go | starcoder |
package main
import (
"fmt"
"strconv"
"github.com/grmpflh27/aoc_2019/aoc2019_shared"
)
type Coord struct {
X int
Y int
}
type Move struct {
from Coord
to Coord
direction string
}
func (m Move) distance() int {
return Abs(m.to.Y-m.from.Y) + Abs(m.to.X-m.from.X)
}
func parseMoves(strMoves []string) []Move {
moves := make([]Move, len(strMoves))
curCoord := Coord{0, 0}
for i := range strMoves {
nextCoord, direction := parseCoord(strMoves[i], curCoord)
moves[i] = Move{
curCoord,
nextCoord,
direction,
}
curCoord = nextCoord
}
return moves
}
func parseCoord(strMove string, coord Coord) (Coord, string) {
dir := string(strMove[0])
num, _ := strconv.Atoi(strMove[1:])
x, y := 0, 0
switch dir {
case "L":
x = coord.X - num
y = coord.Y
case "R":
x = coord.X + num
y = coord.Y
case "U":
y = coord.Y + num
x = coord.X
case "D":
y = coord.Y - num
x = coord.X
}
return Coord{x, y}, dir
}
type Board [][]int
func initBoard(stitched []Move) (Board, Coord) {
// create rightly sized board
minX, maxX, minY, maxY := 0, 0, 0, 0
for _, move := range stitched {
coord := move.to
if minX > coord.X {
minX = coord.X
}
if maxX < coord.X {
maxX = coord.X
}
if minY > coord.Y {
minY = coord.Y
}
if maxY < coord.Y {
maxY = coord.Y
}
}
originOffset := Coord{-1 * minX, -1 * minY}
fmt.Printf("Origin offset: %v\n", originOffset)
sizeX := maxX - minX + 1
sizeY := maxY - minY + 1
fmt.Printf("Building board %v x %v\n", sizeX, sizeY)
board := make(Board, sizeY)
for i := range board {
board[i] = make([]int, sizeX)
}
return board, originOffset
}
func transposeMoves(moves []Move, originOffset Coord) {
idx, end := 0, len(moves)
for idx < end {
m := &moves[idx]
m.from.X = m.from.X + originOffset.X
m.from.Y = m.from.Y + originOffset.Y
m.to.X = m.to.X + originOffset.X
m.to.Y = m.to.Y + originOffset.Y
idx++
}
}
func Min(x, y int) int {
if x < y {
return x
}
return y
}
func Max(x, y int) int {
if x > y {
return x
}
return y
}
func Abs(x int) int {
if x < 0 {
x *= -1
}
return x
}
func placeFootsteps(moves []Move, board Board) {
for _, move := range moves {
switch move.direction {
case "L", "R":
start := Min(move.from.X, move.to.X)
end := Max(move.from.X, move.to.X)
for i := start; i <= end; i++ {
if board[move.from.Y][i] != 1 {
board[move.from.Y][i] = 1
}
}
case "U", "D":
start := Min(move.from.Y, move.to.Y)
end := Max(move.from.Y, move.to.Y)
for i := start; i <= end; i++ {
if board[i][move.from.X] != 1 {
board[i][move.from.X] = 1
}
}
}
}
}
func findIntersections(board1 Board, board2 Board, originOffset Coord) []Coord {
intersections := []Coord{}
for rowIdx := range board1 {
for colIdx := range board1[rowIdx] {
if board1[rowIdx][colIdx] == 1 && board2[rowIdx][colIdx] == 1 {
cur := Coord{colIdx, rowIdx}
if cur != originOffset {
intersections = append(intersections, cur)
}
}
}
}
return intersections
}
func manhattanDistance(from Coord, to Coord) int {
return Abs(to.X-from.X) + Abs(to.Y-from.Y)
}
func minManhattanDistance(intersections []Coord, origin Coord) (int, Coord) {
manh := 100000
minCoord := origin
for _, inter := range intersections {
if inter != origin {
curDistance := manhattanDistance(origin, inter)
if manh > curDistance {
manh = curDistance
minCoord = inter
}
}
}
return manh, minCoord
}
func countStepsToMinIntersection(moves []Move, intersections []Coord) []int {
stepCounts := make([]int, len(intersections))
for i, inter := range intersections {
stepCounts[i] = countStepsTo(moves, inter)
}
return stepCounts
}
func countStepsTo(moves []Move, intersection Coord) int {
var steps int = 0
for _, move := range moves {
switch move.direction {
case "R":
start := Min(move.from.X, move.to.X)
end := Max(move.from.X, move.to.X)
for i := start + 1; i <= end; i++ {
if move.to.Y == intersection.Y && i == intersection.X {
steps++
return steps
}
steps++
}
case "L":
start := Min(move.from.X, move.to.X) - 1
end := Max(move.from.X, move.to.X) - 1
for i := end; i > start; i-- {
if move.to.Y == intersection.Y && i == intersection.X {
steps++
return steps
}
steps++
}
case "U":
start := Min(move.from.Y, move.to.Y)
end := Max(move.from.Y, move.to.Y)
for i := start + 1; i <= end; i++ {
if i == intersection.Y && move.to.X == intersection.X {
steps++
return steps
}
steps++
}
case "D":
start := Min(move.from.Y, move.to.Y) - 1
end := Max(move.from.Y, move.to.Y) - 1
for i := end; i > start; i-- {
if i == intersection.Y && move.to.X == intersection.X {
steps++
return steps
}
steps++
}
}
}
return steps
}
func main() {
var day = 3
fmt.Println("==========")
fmt.Println("Day ", day)
fmt.Println("==========")
words := aoc2019_shared.LoadStr(day, ",")
//1
moves1 := parseMoves(words[0])
moves2 := parseMoves(words[1])
stitched := append(moves1, moves2...)
board1, _ := initBoard(stitched)
board2, originOffset := initBoard(stitched)
transposeMoves(moves1, originOffset)
transposeMoves(moves2, originOffset)
placeFootsteps(moves1, board1)
placeFootsteps(moves2, board2)
intersections := findIntersections(board1, board2, originOffset)
minDistance, _ := minManhattanDistance(intersections, originOffset)
fmt.Printf("Answer 1: %v\n", minDistance)
// 2
cnt1 := countStepsToMinIntersection(moves1, intersections)
cnt2 := countStepsToMinIntersection(moves2, intersections)
sums := make([]int, len(cnt1))
for i := range cnt1 {
sums[i] = cnt1[i] + cnt2[i]
}
minSum := sums[0]
for _, curSum := range sums[1:] {
if curSum < minSum {
minSum = curSum
}
}
fmt.Printf("Answer 2: %v\n", minSum)
} | day_3/day_3.go | 0.610686 | 0.418875 | day_3.go | starcoder |
package ubiquity
// In this file, we include chain ranking functions based on security and performance
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"crypto/x509"
"time"
"github.com/cloudflare/cfssl/helpers"
)
// Compute the priority of different hash algorithm based on security
// SHA2 > SHA1 >> MD = Others = Unknown
func hashPriority(cert *x509.Certificate) int {
switch cert.SignatureAlgorithm {
case x509.ECDSAWithSHA1, x509.DSAWithSHA1, x509.SHA1WithRSA:
return 10
case x509.ECDSAWithSHA256, x509.ECDSAWithSHA384, x509.ECDSAWithSHA512,
x509.DSAWithSHA256, x509.SHA256WithRSA, x509.SHA384WithRSA,
x509.SHA512WithRSA:
return 100
default:
return 0
}
}
// Compute the priority of different key algorithm based performance and security
// ECDSA>RSA>DSA>Unknown
func keyAlgoPriority(cert *x509.Certificate) int {
switch cert.PublicKeyAlgorithm {
case x509.ECDSA:
switch cert.PublicKey.(*ecdsa.PublicKey).Curve {
case elliptic.P256():
return 100
case elliptic.P384():
return 120
case elliptic.P521():
return 140
default:
return 100
}
case x509.RSA:
switch cert.PublicKey.(*rsa.PublicKey).N.BitLen() {
case 4096:
return 70
case 3072:
return 50
case 2048:
return 30
// key size <= 1024 are discouraged.
default:
return 0
}
// we do not want to bundle a DSA cert.
case x509.DSA:
return 0
default:
return 0
}
}
// HashPriority returns the hash priority of the chain as the average of hash priority of certs in it.
func HashPriority(certs []*x509.Certificate) int {
ret := 0.0
for i, cert := range certs {
f1 := 1.0 / (float64(i) + 1.0)
f2 := 1.0 - f1
ret = ret*f2 + float64(hashPriority(cert))*f1
}
return int(ret)
}
// KeyAlgoPriority returns the key algorithm priority of the chain as the average of key algorithm priority of certs in it.
func KeyAlgoPriority(certs []*x509.Certificate) int {
ret := 0.0
for i, cert := range certs {
f1 := 1.0 / (float64(i) + 1.0)
f2 := 1.0 - f1
ret = float64(keyAlgoPriority(cert))*f1 + ret*f2
}
return int(ret)
}
// CompareChainHashPriority ranks chains with more current hash functions higher.
func CompareChainHashPriority(chain1, chain2 []*x509.Certificate) int {
hp1 := HashPriority(chain1)
hp2 := HashPriority(chain2)
return hp1 - hp2
}
// CompareChainKeyAlgoPriority ranks chains with more current key algorithm higher.
func CompareChainKeyAlgoPriority(chain1, chain2 []*x509.Certificate) int {
kap1 := KeyAlgoPriority(chain1)
kap2 := KeyAlgoPriority(chain2)
return kap1 - kap2
}
// CompareChainCryptoSuite ranks chains with more current crypto suite higher.
func CompareChainCryptoSuite(chain1, chain2 []*x509.Certificate) int {
cs1 := HashPriority(chain1) + KeyAlgoPriority(chain1)
cs2 := HashPriority(chain2) + KeyAlgoPriority(chain2)
return cs1 - cs2
}
// CompareChainLength ranks shorter chain higher.
func CompareChainLength(chain1, chain2 []*x509.Certificate) int {
return len(chain2) - len(chain1)
}
func compareTime(t1, t2 *time.Time) int {
if t1.After(*t2) {
return 1
} else if t1.Before(*t2) {
return -1
}
return 0
}
// CompareChainExpiry ranks chain that lasts longer higher.
func CompareChainExpiry(chain1, chain2 []*x509.Certificate) int {
t1 := helpers.ExpiryTime(chain1)
t2 := helpers.ExpiryTime(chain2)
return compareTime(t1, t2)
} | ubiquity/performance.go | 0.731059 | 0.467453 | performance.go | starcoder |
package v2
/*
All hard-coded default values for configurable aspects of objects in our API should go here.
However, hard-coded values that are not (yet) configurable in the API can live with the code.
These values are materialized into the object before processing begins.
This prevents defaults from being scattered throughout the processing code,
and in the future will allow us to associate defaults with specific API versions.
***COMPATIBILITY RULES***
* DO NOT change existing default values.
* DO NOT make these API-level default values configurable (e.g. by command-line flag).
* DO NOT add defaults that are only relevant to a specific user of the CRD.
New default values may only be added as new fields are added to the API Version (planetscale.com/v2),
and defaults for existing fields may only be changed along with the introduction of a new API Version
(e.g. `apiVersion: planetscale.com/v3`, but see below for a caveat). The defaults for that new API Version
will live in a different file in a different package (pkg/apis/planetscale/v3).
This rule, among other compatibility guarantees expected of all Kubernetes-style APIS, provides a contract
that makes it safe for users to upgrade without worrying about their configuration being changed silently
and in unpredictable ways.
CAVEAT: We CANNOT yet support adding a new API Version (e.g. planetscale.com/v3).
Currently, we only fill in these defaults in-memory, each time the controller processes an object.
Before we can add planetscale.com/v3, we'll need to do the following:
* Write a mutating admission webhook to materialize the v2 defaults into the actual data stored
in the Kubernetes API server. This prevents the object's configuration from changing when the
controller is updated to use v3.
* Write a CRD conversion webhook to translate objects back and forth between v2 and v3.
*/
const (
// Mi is the scale factor for Mebi (2**20)
Mi = 1 << 20
// Gi is the scale factor for Gibi (2**30)
Gi = 1 << 30
defaultEtcdImage = "quay.io/coreos/etcd:v3.3.13"
defaultEtcdStorageRequestBytes = 1 * Gi
defaultEtcdCPUMillis = 100
defaultEtcdMemoryBytes = 256 * Mi
defaultEtcdCreatePDB = true
defaultEtcdCreateClientService = true
defaultEtcdCreatePeerService = true
defaultVtctldReplicas = 1
defaultVtctldCPUMillis = 100
defaultVtctldMemoryBytes = 128 * Mi
defaultVtgateReplicas = 2
defaultVtgateCPUMillis = 500
defaultVtgateMemoryBytes = 1 * Gi
defaultBackupIntervalHours = 24
defaultBackupMinRetentionHours = 72
defaultBackupMinRetentionCount = 1
defaultBackupEngine = VitessBackupEngineBuiltIn
// DefaultWebPort is the port for debug status pages and dashboard UIs.
DefaultWebPort = 15000
// DefaultGrpcPort is the port for RPCs.
DefaultGrpcPort = 15999
// DefaultMysqlPort is the port for MySQL client connections.
DefaultMysqlPort = 3306
// DefaultWebPortName is the name for the web port.
DefaultWebPortName = "web"
// DefaultGrpcPortName is the name for the RPC port.
DefaultGrpcPortName = "grpc"
// DefaultMysqlPortName is the name for the MySQL port.
DefaultMysqlPortName = "mysql"
defaultVitessLiteImage = "us.gcr.io/planetscale-vitess/lite:2020-03-19.771aa75d"
)
/*
defaultVitessImages are the default images used for this API Version (planetscale.com/v2).
As discussed in the comment at the top of this file, we cannot change these
after planetscale.com/v2 is released. Anyone using the operator in production
should set these images explicitly in the CRD anyway, so they know what they're
getting and when they need to upgrade.
These API-level defaults exist merely to support a friendly "kick the tires"
experience when trying out the operator.
*/
var defaultVitessImages = &VitessImages{
Vtctld: defaultVitessLiteImage,
Vtgate: defaultVitessLiteImage,
Vttablet: defaultVitessLiteImage,
// Note: The vtbackup image is only used for the vtbackup binary itself,
// which is copied over during Pod initialization. The vtbackup container
// actually runs with the mysqld image specified below. This mirrors the way
// that the mysqld container in a vttablet Pod runs the mysqld image with a
// mysqlctld binary injected (copied from the vttablet image) at Pod
// initialization, since vtbackup is effectively a modified mysqlctl(d).
Vtbackup: defaultVitessLiteImage,
// Note: We used to use a mysql-only image, but it's better to use the
// same image as the vttablet container since vttablet now uses the
// local mysqld binary in its container to do version detection, so the
// binary needs to match what we use in the mysqld container. Using the
// Vitess image rather than a mysql-only image also means the vtbackup Pod
// has easy access to other programs we include in the Vitess image, like
// Percona XtraBackup.
Mysqld: &MysqldImage{
Mysql56Compatible: defaultVitessLiteImage,
},
MysqldExporter: "prom/mysqld-exporter:v0.11.0",
} | pkg/apis/planetscale/v2/defaults.go | 0.622459 | 0.503235 | defaults.go | starcoder |
package gohm
const LUA_SAVE string = `
-- This script receives four parameters, all encoded with
-- MessagePack. The decoded values are used for saving a model
-- instance in Redis, creating or updating a hash as needed and
-- updating zero or more sets (indices) and zero or more hashes
-- (unique indices).
--
-- # model
--
-- Table with one or two attributes:
-- name (model name)
-- id (model instance id, optional)
--
-- If the id is not provided, it is treated as a new record.
--
-- # attrs
--
-- Array with attribute/value pairs.
--
-- # indices
--
-- Fields and values to be indexed. Each key in the indices
-- table is mapped to an array of values. One index is created
-- for each field/value pair.
--
-- # uniques
--
-- Fields and values to be indexed as unique. Unlike indices,
-- values are not enumerable. If a field/value pair is not unique
-- (i.e., if there was already a hash entry for that field and
-- value), an error is returned with the UniqueIndexViolation
-- message and the field that triggered the error.
--
local model = cmsgpack.unpack(ARGV[1])
local attrs = cmsgpack.unpack(ARGV[2])
local indices = cmsgpack.unpack(ARGV[3])
local uniques = cmsgpack.unpack(ARGV[4])
local function save(model, attrs)
if model.id == nil then
model.id = redis.call("INCR", model.name .. ":id")
end
model.key = model.name .. ":" .. model.id
redis.call("SADD", model.name .. ":all", model.id)
redis.call("DEL", model.key)
if math.mod(#attrs, 2) == 1 then
error("Wrong number of attribute/value pairs")
end
if #attrs > 0 then
redis.call("HMSET", model.key, unpack(attrs))
end
end
local function index(model, indices)
for field, enum in pairs(indices) do
for _, val in ipairs(enum) do
local key = model.name .. ":indices:" .. field .. ":" .. tostring(val)
redis.call("SADD", model.key .. ":_indices", key)
redis.call("SADD", key, model.id)
end
end
end
local function remove_indices(model)
local memo = model.key .. ":_indices"
local existing = redis.call("SMEMBERS", memo)
for _, key in ipairs(existing) do
redis.call("SREM", key, model.id)
redis.call("SREM", memo, key)
end
end
local function unique(model, uniques)
for field, value in pairs(uniques) do
local key = model.name .. ":uniques:" .. field
redis.call("HSET", model.key .. ":_uniques", key, value)
redis.call("HSET", key, value, model.id)
end
end
local function remove_uniques(model)
local memo = model.key .. ":_uniques"
for _, key in pairs(redis.call("HKEYS", memo)) do
redis.call("HDEL", key, redis.call("HGET", memo, key))
redis.call("HDEL", memo, key)
end
end
local function verify(model, uniques)
local duplicates = {}
for field, value in pairs(uniques) do
local key = model.name .. ":uniques:" .. field
local id = redis.call("HGET", key, tostring(value))
if id and id ~= tostring(model.id) then
duplicates[#duplicates + 1] = field
end
end
return duplicates, #duplicates ~= 0
end
local duplicates, err = verify(model, uniques)
if err then
error("UniqueIndexViolation: " .. duplicates[1])
end
save(model, attrs)
remove_indices(model)
index(model, indices)
remove_uniques(model, uniques)
unique(model, uniques)
return tostring(model.id)
` | lua_save.go | 0.674801 | 0.588741 | lua_save.go | starcoder |
package environment
import (
)
func makeTerrainField(size int) TerrainField {
logNormal := getLogNormalConverter(0.0, 0.5, 10000)
field := TerrainField{
SolidityCurrent: zeroSquare(size),
SolidityConstant: applyGridDistribution(randomSquare(size), logNormal),
SolidityAmplitude: applyGridDistribution(randomSquare(size), logNormal),
SolidityPhase: applyGridDistribution(randomSquare(size), uniformConverter),
HardnessCurrent: zeroSquare(size),
HardnessConstant: applyGridDistribution(randomSquare(size), logNormal),
HardnessAmplitude: applyGridDistribution(randomSquare(size), logNormal),
HardnessPhase: applyGridDistribution(randomSquare(size), uniformConverter),
ChemicalCapacityCurrent: zeroSquare(size),
ChemicalCapacityConstant: applyGridDistribution(randomSquare(size), logNormal),
ChemicalCapacityAmplitude: applyGridDistribution(randomSquare(size), logNormal),
ChemicalCapacityPhase: applyGridDistribution(randomSquare(size), uniformConverter),
}
return field
}
func makePressureField(size int) PressureField {
logNormal := getLogNormalConverter(0.0, 0.5, 10000)
field := PressureField{
PressureBiasCurrent: zeroSquare(size),
PressureBiasConstant: applyGridDistribution(randomSquare(size), logNormal),
PressureBiasAmplitude: applyGridDistribution(randomSquare(size), logNormal),
PressureBiasPhase: applyGridDistribution(randomSquare(size), uniformConverter),
}
return field
}
func makeEnergyField(size int) EnergyField {
logNormal := getLogNormalConverter(0.0, 0.5, 10000)
field := EnergyField{
PowerCurrent: zeroSquare(size),
PowerConstant: applyGridDistribution(randomSquare(size), logNormal),
PowerAmplitude: applyGridDistribution(randomSquare(size), logNormal),
PowerPhase: applyGridDistribution(randomSquare(size), uniformConverter),
}
return field
}
func makeBlocks(size int, terrain TerrainField, constants PhysicalConstants) [][]Block {
solidThreshold := gridPercentile(terrain.SolidityConstant, 1.0-constants.RockPortion)
blocks := make([][]Block, size)
for i:=0; i<size; i++ {
blocks[i] = make([]Block, size)
for j:=0; j<size; j++ {
if terrain.SolidityConstant[i][j] > solidThreshold {
blocks[i][j] = Block{
Solid: true,
ChemicalCapacity: constants.BaseCapacity*terrain.ChemicalCapacityConstant[i][j],
Rock: rock{
Health: constants.BaseHealth*terrain.HardnessConstant[i][j],
},
}
} else {
blocks[i][j] = Block{
Solid: false,
ChemicalCapacity: 1.0,
Water: water{},
}
}
}
}
logNormal := getLogNormalConverter(0.0, 0.5, 10000)
for _, c := range []int{0, 1, 2} {
concentrations := applyGridDistribution(randomSquare(size), logNormal)
for i, row := range blocks {
for j, block := range row {
block.Chemicals[c] = block.ChemicalCapacity*concentrations[i][j]
}
}
}
return blocks
}
func makeWorld(size int, constants PhysicalConstants) World {
world := World{
Size: size,
TerrainField: makeTerrainField(size),
PressureField: makePressureField(size),
EnergyField: makeEnergyField(size),
Season: 0.0,
}
world.Blocks = makeBlocks(size, world.TerrainField, constants)
return world
} | environment/initialization.go | 0.702122 | 0.729014 | initialization.go | starcoder |
package ui
import (
"math"
"wireworld/resources"
"wireworld/sim"
"wireworld/util"
"github.com/go-gl/gl/v3.3-core/gl"
)
const (
ZoomMin = 1
ZoomMax = 30
ZoomDefault = 15
)
// Canvas facilitates panning and zooming and tracks mouse input.
type Canvas struct {
mousePosition [2]int
mouseDelta [2]int
origin [2]int
viewport [2]int
zoom int
panning bool
}
// NewCanvas creates a new canvas
func NewCanvas() *Canvas {
return &Canvas{
mousePosition: [2]int{0, 0},
mouseDelta: [2]int{0, 0},
origin: [2]int{0, 0},
viewport: [2]int{1, 1},
zoom: ZoomDefault,
panning: false,
}
}
func (c *Canvas) Draw(mp *util.Mat4) {
s := resources.GetShader("CellRenderer")
s.Use()
s.Set1f("alpha", 1.0)
c.setCellMVP(s, mp, c.origin[0], c.origin[1])
m := resources.GetMesh("CellRenderer")
// Upload cell data if it has changed.
if sim.CellsChanged() {
m.Commitiv(sim.Cells(), gl.STREAM_DRAW)
}
m.Draw()
}
// setCellMVP computes the cell MVP matrix for the given shader
// and position.
func (c *Canvas) setCellMVP(s *resources.Shader, mp *util.Mat4, x, y int) {
w, h := c.viewport[0], c.viewport[1]
z := float32(c.zoom)
mvp := mp.Copy()
mvp.Mul(util.Mat4Translate(float32(x), float32(y), 0))
mvp.Mul(util.Mat4Scale(z, z, 0))
s.SetMat16("mvp", (*mvp)[:])
s.Set2f("cellSize", z/float32(w)*2, z/float32(h)*2)
}
// MouseDelta returns the current mouse delta.
func (c *Canvas) MouseDelta() (int, int) {
return c.mouseDelta[0], c.mouseDelta[1]
}
// MousePosition returns the current mouse position.
func (c *Canvas) MousePosition() (int, int) {
return c.mousePosition[0], c.mousePosition[1]
}
// Viewport returns the viewport width and height.
func (c *Canvas) Viewport() (int, int) {
return c.viewport[0], c.viewport[1]
}
// SetPanning sets the panning flag. Meaning we are either dragging
// the scene around or not.
func (c *Canvas) SetPanning(v bool) {
c.panning = v
}
// ScrollTo scrolls the viewport to the given, absolute position.
func (c *Canvas) ScrollTo(x, y int) {
c.origin[0] = x
c.origin[1] = y
}
// Zoom returns the current zoom factor.
func (c *Canvas) Zoom() int {
return c.zoom
}
// SetZoom sets the current zoom factor.
func (c *Canvas) SetZoom(v int) {
c.zoom = util.Clampi(v, ZoomMin, ZoomMax)
}
func (c *Canvas) Resize(w, h int) {
c.viewport[0] = w
c.viewport[1] = h
}
func (c *Canvas) Scroll(x, y float64) {
ox, oy := float32(c.origin[0]), float32(c.origin[1])
zf := float32(c.zoom)
zd := float32(y / math.Abs(y))
fx := float32(c.mousePosition[0]) - ox
fy := float32(c.mousePosition[1]) - oy
oldfx := fx / zf
oldfy := fy / zf
c.zoom = util.Clampi(int(zf+zd), ZoomMin, ZoomMax)
zf = float32(c.zoom)
c.origin[0] = int(fx - ((oldfx * zf) - ox))
c.origin[1] = int(fy - ((oldfy * zf) - oy))
}
func (c *Canvas) MouseMove(x, y float64) {
c.mouseDelta[0] = c.mousePosition[0] - int(x)
c.mouseDelta[1] = c.mousePosition[1] - int(y)
c.mousePosition[0] = int(x)
c.mousePosition[1] = int(y)
if c.panning {
c.origin[0] -= c.mouseDelta[0]
c.origin[1] -= c.mouseDelta[1]
}
} | ui/canvas.go | 0.672439 | 0.424949 | canvas.go | starcoder |
package main
import (
"github.com/gen2brain/raylib-go/raylib"
)
func main() {
screenWidth := int32(800)
screenHeight := int32(450)
rl.InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo animation")
logoPositionX := screenWidth/2 - 128
logoPositionY := screenHeight/2 - 128
framesCounter := 0
lettersCount := int32(0)
topSideRecWidth := int32(16)
leftSideRecHeight := int32(16)
bottomSideRecWidth := int32(16)
rightSideRecHeight := int32(16)
state := 0 // Tracking animation states (State Machine)
alpha := float32(1.0) // Useful for fading
rl.SetTargetFPS(60)
for !rl.WindowShouldClose() {
if state == 0 { // State 0: Small box blinking
framesCounter++
if framesCounter == 120 {
state = 1
framesCounter = 0 // Reset counter... will be used later...
}
} else if state == 1 { // State 1: Top and left bars growing
topSideRecWidth += 4
leftSideRecHeight += 4
if topSideRecWidth == 256 {
state = 2
}
} else if state == 2 { // State 2: Bottom and right bars growing
bottomSideRecWidth += 4
rightSideRecHeight += 4
if bottomSideRecWidth == 256 {
state = 3
}
} else if state == 3 { // State 3: Letters appearing (one by one)
framesCounter++
if framesCounter%12 == 0 { // Every 12 frames, one more letter!
lettersCount++
framesCounter = 0
}
if lettersCount >= 6 { // When all letters have appeared, just fade out everything
alpha -= 0.02
if alpha <= 0.0 {
alpha = 0.0
state = 4
}
}
} else if state == 4 { // State 4: Reset and Replay
if rl.IsKeyPressed(rl.KeyR) {
framesCounter = 0
lettersCount = 0
topSideRecWidth = 16
leftSideRecHeight = 16
bottomSideRecWidth = 16
rightSideRecHeight = 16
alpha = 1.0
state = 0 // Return to State 0
}
}
rl.BeginDrawing()
rl.ClearBackground(rl.RayWhite)
if state == 0 {
if (framesCounter/15)%2 == 0 {
rl.DrawRectangle(logoPositionX, logoPositionY, 16, 16, rl.Black)
}
} else if state == 1 {
rl.DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, rl.Black)
rl.DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, rl.Black)
} else if state == 2 {
rl.DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, rl.Black)
rl.DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, rl.Black)
rl.DrawRectangle(logoPositionX+240, logoPositionY, 16, rightSideRecHeight, rl.Black)
rl.DrawRectangle(logoPositionX, logoPositionY+240, bottomSideRecWidth, 16, rl.Black)
} else if state == 3 {
rl.DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, rl.Fade(rl.Black, alpha))
rl.DrawRectangle(logoPositionX, logoPositionY+16, 16, leftSideRecHeight-32, rl.Fade(rl.Black, alpha))
rl.DrawRectangle(logoPositionX+240, logoPositionY+16, 16, rightSideRecHeight-32, rl.Fade(rl.Black, alpha))
rl.DrawRectangle(logoPositionX, logoPositionY+240, bottomSideRecWidth, 16, rl.Fade(rl.Black, alpha))
rl.DrawRectangle(screenWidth/2-112, screenHeight/2-112, 224, 224, rl.Fade(rl.RayWhite, alpha))
text := "raylib"
length := int32(len(text))
if lettersCount > length {
lettersCount = length
}
rl.DrawText(text[0:lettersCount], screenWidth/2-44, screenHeight/2+48, 50, rl.Fade(rl.Black, alpha))
} else if state == 4 {
rl.DrawText("[R] REPLAY", 340, 200, 20, rl.Gray)
}
rl.EndDrawing()
}
rl.CloseWindow()
} | examples/shapes/logo_raylib_anim/main.go | 0.507812 | 0.450964 | main.go | starcoder |
package main
import (
"fmt"
"math"
"github.com/ByteArena/box2d"
"github.com/wdevore/Ranger-Go-IGE/api"
"github.com/wdevore/Ranger-Go-IGE/engine/geometry"
"github.com/wdevore/Ranger-Go-IGE/engine/maths"
"github.com/wdevore/Ranger-Go-IGE/engine/rendering/color"
"github.com/wdevore/Ranger-Go-IGE/extras/shapes"
)
// TrackingComponent is a box
type TrackingComponent struct {
parent api.INode
visual api.INode
b2Body *box2d.B2Body
beginContactColor api.IPalette
endContactColor api.IPalette
scale float64
algorithm int
trackingAlgorithm int
stopping bool
targetingRate float64
targetPosition api.IPoint
thrustEnabled bool
thrustStrength float64
categoryBits uint16 // I am a...
maskBits uint16 // I can collide with a...
}
// NewTrackingComponent constructs a component
func NewTrackingComponent(name string, parent api.INode) *TrackingComponent {
o := new(TrackingComponent)
o.parent = parent
o.algorithm = 1
o.trackingAlgorithm = 5
o.targetingRate = 10.0 // default is medium
o.thrustEnabled = false
o.thrustStrength = 5.0
return o
}
// Configure component
func (t *TrackingComponent) Configure(scale float64, categoryBits, maskBits uint16, b2World *box2d.B2World) error {
t.scale = scale
t.targetPosition = geometry.NewPoint()
t.categoryBits = categoryBits
t.maskBits = maskBits
t.beginContactColor = color.NewPaletteInt64(color.White)
t.endContactColor = color.NewPaletteInt64(color.Pink)
var err error
t.visual, err = shapes.NewMonoTriangleNode("Triangle", api.FILLED, t.parent.World(), t.parent)
if err != nil {
return err
}
t.visual.SetID(1001)
t.visual.SetScale(float32(t.scale))
t.visual.SetPosition(0.0, 0.0)
gt := t.visual.(*shapes.MonoTriangleNode)
gt.SetFilledColor(t.endContactColor)
buildComp(t, b2World)
return nil
}
// SetColor sets the visual's color
func (t *TrackingComponent) SetColor(color api.IPalette) {
gr := t.visual.(*shapes.MonoTriangleNode)
gr.SetOutlineColor(color)
}
// SetTargetPosition sets the target position. The position is in
// view-space.
func (t *TrackingComponent) SetTargetPosition(p api.IPoint) {
t.targetPosition.SetByPoint(p)
}
// SetPosition sets component's location.
func (t *TrackingComponent) SetPosition(x, y float32) {
t.visual.SetPosition(x, y)
t.b2Body.SetTransform(box2d.MakeB2Vec2(float64(x), float64(y)), t.b2Body.GetAngle())
}
// GetPosition returns the body's position
func (t *TrackingComponent) GetPosition() box2d.B2Vec2 {
return t.b2Body.GetPosition()
}
// EnableGravity enables/disables gravity for this component
func (t *TrackingComponent) EnableGravity(enable bool) {
if enable {
t.b2Body.SetGravityScale(1.0)
} else {
t.b2Body.SetGravityScale(0.0)
}
}
// Reset configures the component back to defaults
func (t *TrackingComponent) Reset(x, y float32) {
t.visual.SetPosition(x, y)
t.b2Body.SetTransform(box2d.MakeB2Vec2(float64(x), float64(y)), 0.0)
t.b2Body.SetLinearVelocity(box2d.MakeB2Vec2(0.0, 0.0))
t.b2Body.SetAngularVelocity(0.0)
t.b2Body.SetAwake(true)
}
// SetTrackingAlgo changes the tracking style
func (t *TrackingComponent) SetTrackingAlgo(style int) {
t.trackingAlgorithm = style
}
// SetTargetingRate changes the how fast the tracking locks on.
func (t *TrackingComponent) SetTargetingRate(rate float64) {
t.targetingRate = rate
}
// SetVelocityAlgo changes the velocity style
func (t *TrackingComponent) SetVelocityAlgo(style int) {
t.algorithm = style
}
// Stop set linear velocity to 0
func (t *TrackingComponent) Stop() {
t.stopping = !t.stopping
if t.stopping {
fmt.Println("Stopping...")
}
}
// MoveLeft applies linear force to box center
func (t *TrackingComponent) MoveLeft(dx float64) {
velocity := t.b2Body.GetLinearVelocity()
switch t.algorithm {
case 1:
velocity.X -= dx
case 2:
velocity.X = math.Max(velocity.X-0.1, -5.0)
}
t.b2Body.SetLinearVelocity(velocity)
}
// MoveRight applies linear force to box center
func (t *TrackingComponent) MoveRight(dx float64) {
velocity := t.b2Body.GetLinearVelocity()
switch t.algorithm {
case 1:
velocity.X += dx
case 2:
velocity.X = math.Max(velocity.X+0.1, 5.0)
}
t.b2Body.SetLinearVelocity(velocity)
}
// MoveUp applies linear force to box center
func (t *TrackingComponent) MoveUp(dy float64) {
velocity := t.b2Body.GetLinearVelocity()
switch t.algorithm {
case 1:
velocity.Y -= dy
case 2:
velocity.Y = math.Max(velocity.Y-0.1, -5.0)
}
t.b2Body.SetLinearVelocity(velocity)
}
// MoveDown applies linear force to box center
func (t *TrackingComponent) MoveDown(dy float64) {
velocity := t.b2Body.GetLinearVelocity()
switch t.algorithm {
case 1:
velocity.Y += dy
case 2:
velocity.Y = math.Max(velocity.Y+0.1, 5.0)
}
t.b2Body.SetLinearVelocity(velocity)
}
// Thrust applies force in the direction of the ray
func (t *TrackingComponent) Thrust() {
t.thrustEnabled = !t.thrustEnabled
}
// ApplyForce applies linear force to box center
func (t *TrackingComponent) ApplyForce(dirX, dirY float64) {
t.b2Body.ApplyForce(box2d.B2Vec2{X: dirX, Y: dirY}, t.b2Body.GetWorldCenter(), true)
}
// ApplyImpulse applies linear impulse to box center
func (t *TrackingComponent) ApplyImpulse(dirX, dirY float64) {
t.b2Body.ApplyLinearImpulse(box2d.B2Vec2{X: dirX, Y: dirY}, t.b2Body.GetWorldCenter(), true)
}
// ApplyImpulseToCorner applies linear impulse to 1,1 box corner
// As the box rotates the 1,1 corner rotates which means impulses
// could change the rotation to either CW or CCW.
func (t *TrackingComponent) ApplyImpulseToCorner(dirX, dirY float64) {
t.b2Body.ApplyLinearImpulse(box2d.B2Vec2{X: dirX, Y: dirY}, t.b2Body.GetWorldPoint(box2d.B2Vec2{X: 1.0, Y: 1.0}), true)
}
// ApplyTorque applies torgue to box center
func (t *TrackingComponent) ApplyTorque(torgue float64) {
t.b2Body.ApplyTorque(torgue, true)
}
// ApplyAngularImpulse applies angular impulse to box center
func (t *TrackingComponent) ApplyAngularImpulse(impulse float64) {
t.b2Body.ApplyAngularImpulse(impulse, true)
}
// Update component
func (t *TrackingComponent) Update() {
if t.b2Body.IsActive() {
pos := t.b2Body.GetPosition()
t.visual.SetPosition(float32(pos.X), float32(pos.Y))
rot := t.b2Body.GetAngle()
t.visual.SetRotation(rot)
}
bodyPos := t.b2Body.GetPosition()
ray := box2d.MakeB2Vec2(float64(t.targetPosition.X())-bodyPos.X, float64(t.targetPosition.Y())-bodyPos.Y)
targetAngle := math.Atan2(-ray.X, ray.Y)
switch t.trackingAlgorithm {
case 1:
// Instant targeting.
t.b2Body.SetTransform(t.b2Body.GetPosition(), targetAngle)
case 2:
// This is slow and constantly overshoots
// Torque unchecked
nAngle := math.Mod(t.b2Body.GetAngle(), math.Pi*2.0)
totalRotation := targetAngle - nAngle
if totalRotation < -math.Pi {
totalRotation += math.Pi * 2.0
} else if totalRotation > math.Pi {
totalRotation -= math.Pi * 2.0
}
torque := 10.0
if totalRotation < 0 {
torque = -10.0
}
t.b2Body.ApplyTorque(torque, true)
case 3:
// This is slow but eventually locks on.
// look ahead more than one time step to adjust the rate
// at which the correct angle is reached. Here I'm looking ahead
// 1/3 second forward in time.
nAngle := math.Mod(t.b2Body.GetAngle(), math.Pi*2.0)
nextAngle := nAngle + t.b2Body.GetAngularVelocity()/t.targetingRate
totalRotation := targetAngle - nextAngle
if totalRotation < -math.Pi {
totalRotation += math.Pi * 2.0
} else if totalRotation > math.Pi {
totalRotation -= math.Pi * 2.0
}
torque := 10.0
if totalRotation < 0 {
torque = -10.0
}
t.b2Body.ApplyTorque(torque, true)
case 4:
// This locks on instantly but includes some jittering in the
// last few frames.
nAngle := math.Mod(t.b2Body.GetAngle(), math.Pi*2.0)
nextAngle := nAngle + t.b2Body.GetAngularVelocity()/t.targetingRate
totalRotation := targetAngle - nextAngle
if totalRotation < -math.Pi {
totalRotation += math.Pi * 2.0
} else if totalRotation > math.Pi {
totalRotation -= math.Pi * 2.0
}
desiredAngularVelocity := totalRotation * t.targetingRate
torque := t.b2Body.GetInertia() * desiredAngularVelocity / (1 / t.targetingRate)
t.b2Body.ApplyTorque(torque, true)
case 5:
// This is equivalent as case 4 but without the "time" element
// This locks on instantly but includes some jittering in the
// last few frames.
nAngle := math.Mod(t.b2Body.GetAngle(), math.Pi*2.0)
nextAngle := nAngle + t.b2Body.GetAngularVelocity()/t.targetingRate
totalRotation := targetAngle - nextAngle
if totalRotation < -math.Pi {
totalRotation += math.Pi * 2.0
} else if totalRotation > math.Pi {
totalRotation -= math.Pi * 2.0
}
desiredAngularVelocity := totalRotation * t.targetingRate
impulse := t.b2Body.GetInertia() * desiredAngularVelocity
t.b2Body.ApplyAngularImpulse(impulse, true)
case 6:
nAngle := math.Mod(t.b2Body.GetAngle(), math.Pi*2.0)
nextAngle := nAngle + t.b2Body.GetAngularVelocity()/t.targetingRate
totalRotation := targetAngle - nextAngle
if totalRotation < -math.Pi {
totalRotation += math.Pi * 2.0
} else if totalRotation > math.Pi {
totalRotation -= math.Pi * 2.0
}
desiredAngularVelocity := totalRotation * t.targetingRate
change := 5.0 * maths.DegreeToRadians //allow 1 degree rotation per time step
desiredAngularVelocity = math.Min(change, math.Max(-change, desiredAngularVelocity))
impulse := t.b2Body.GetInertia() * desiredAngularVelocity
t.b2Body.ApplyAngularImpulse(impulse, true)
}
if t.thrustEnabled {
bodyPos := t.b2Body.GetPosition()
ray := box2d.MakeB2Vec2(float64(t.targetPosition.X())-bodyPos.X, float64(t.targetPosition.Y())-bodyPos.Y)
t.ApplyForce(ray.X*t.thrustStrength, ray.Y*t.thrustStrength)
}
}
// HandleBeginContact processes BeginContact events
func (t *TrackingComponent) HandleBeginContact(nodeA, nodeB api.INode) bool {
n, ok := nodeA.(*shapes.MonoTriangleNode)
if !ok {
n, ok = nodeB.(*shapes.MonoTriangleNode)
}
if ok {
n.SetOutlineColor(t.beginContactColor)
}
return false
}
// HandleEndContact processes EndContact events
func (t *TrackingComponent) HandleEndContact(nodeA, nodeB api.INode) bool {
n, ok := nodeA.(*shapes.MonoTriangleNode)
if !ok {
n, ok = nodeB.(*shapes.MonoTriangleNode)
}
if ok {
n.SetOutlineColor(t.endContactColor)
}
return false
}
func buildComp(t *TrackingComponent, b2World *box2d.B2World) {
// A body def used to create bodies
bDef := box2d.MakeB2BodyDef()
bDef.Type = box2d.B2BodyType.B2_dynamicBody
// Note: +Y points down in Ranger verses Upward in Box2D's GUI.
vertices := []box2d.B2Vec2{}
// Sync the visual's vertices to this physic object
tr := t.visual.(*shapes.MonoTriangleNode)
// Box2D expects polygon edges to be defined at full length, not
// half-side
scale := tr.SideLength()
verts := tr.Vertices()
for i := 0; i < len(*verts); i += api.XYZComponentCount {
vertices = append(vertices, box2d.B2Vec2{X: float64((*verts)[i] * scale), Y: float64((*verts)[i+1] * scale)})
}
// An instance of a body to contain Fixture
t.b2Body = b2World.CreateBody(&bDef)
// Every Fixture has a shape
b2Shape := box2d.MakeB2PolygonShape()
b2Shape.Set(vertices, len(vertices))
fd := box2d.MakeB2FixtureDef()
fd.Shape = &b2Shape
fd.Density = 1.0
fd.UserData = t.visual
fd.Filter.CategoryBits = t.categoryBits
fd.Filter.MaskBits = t.maskBits
t.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body
} | examples/complex/physics/complex/c4_lava/tracking_component.go | 0.831006 | 0.404243 | tracking_component.go | starcoder |
package matrix
import "runtime"
func (A *DenseMatrix) Plus(B MatrixRO) (Matrix, error) {
C := A.Copy()
err := C.Add(B)
return C, err
}
func (A *DenseMatrix) PlusDense(B *DenseMatrix) (*DenseMatrix, error) {
C := A.Copy()
err := C.AddDense(B)
return C, err
}
func (A *DenseMatrix) Minus(B MatrixRO) (Matrix, error) {
C := A.Copy()
err := C.Subtract(B)
return C, err
}
func (A *DenseMatrix) MinusDense(B *DenseMatrix) (*DenseMatrix, error) {
C := A.Copy()
err := C.SubtractDense(B)
return C, err
}
func (A *DenseMatrix) Add(B MatrixRO) error {
if A.cols != B.Cols() || A.rows != B.Rows() {
return ErrorDimensionMismatch
}
for i := 0; i < A.rows; i++ {
index := i * A.step
for j := 0; j < A.cols; j++ {
A.elements[index] += B.Get(i, j)
index++
}
}
return nil
}
func (A *DenseMatrix) AddDense(B *DenseMatrix) error {
if A.cols != B.cols || A.rows != B.rows {
return ErrorDimensionMismatch
}
for i := 0; i < A.rows; i++ {
for j := 0; j < A.cols; j++ {
A.elements[i*A.step+j] += B.elements[i*B.step+j]
}
}
return nil
}
func (A *DenseMatrix) Subtract(B MatrixRO) error {
if Bd, ok := B.(*DenseMatrix); ok {
return A.SubtractDense(Bd)
}
if A.cols != B.Cols() || A.rows != B.Rows() {
return ErrorDimensionMismatch
}
for i := 0; i < A.rows; i++ {
index := i * A.step
for j := 0; j < A.cols; j++ {
A.elements[index] -= B.Get(i, j)
index++
}
}
return nil
}
func (A *DenseMatrix) SubtractDense(B *DenseMatrix) error {
if A.cols != B.cols || A.rows != B.rows {
return ErrorDimensionMismatch
}
for i := 0; i < A.rows; i++ {
indexA := i * A.step
indexB := i * B.step
for j := 0; j < A.cols; j++ {
A.elements[indexA] -= B.elements[indexB]
indexA++
indexB++
}
}
return nil
}
func (A *DenseMatrix) Times(B MatrixRO) (Matrix, error) {
if Bd, ok := B.(*DenseMatrix); ok {
return A.TimesDense(Bd)
}
if A.cols != B.Rows() {
return nil, ErrorDimensionMismatch
}
C := Zeros(A.rows, B.Cols())
for i := 0; i < A.rows; i++ {
for j := 0; j < B.Cols(); j++ {
sum := float64(0)
for k := 0; k < A.cols; k++ {
sum += A.elements[i*A.step+k] * B.Get(k, j)
}
C.elements[i*C.step+j] = sum
}
}
return C, nil
}
type parJob struct {
start, finish int
}
func parTimes1(A, B, C *DenseMatrix) {
C = Zeros(A.rows, B.cols)
mp := runtime.GOMAXPROCS(0)
jobChan := make(chan box, 1+mp)
go func() {
rowCount := A.rows / mp
for startRow := 0; startRow < A.rows; startRow += rowCount {
start := startRow
finish := startRow + rowCount
if finish >= A.rows {
finish = A.rows
}
jobChan <- parJob{start: start, finish: finish}
}
close(jobChan)
}()
wait := parFor(jobChan, func(iBox box) {
job := iBox.(parJob)
for i := job.start; i < job.finish; i++ {
sums := C.elements[i*C.step : (i+1)*C.step]
for k := 0; k < A.cols; k++ {
for j := 0; j < B.cols; j++ {
sums[j] += A.elements[i*A.step+k] * B.elements[k*B.step+j]
}
}
}
})
wait()
return
}
//this is an adaptation of code from a go-nuts post made by <NAME>
func parTimes2(A, B, C *DenseMatrix) {
const threshold = 8
currentGoroutineCount := 1
maxGoroutines := runtime.GOMAXPROCS(0) + 2
var aux func(sync chan bool, A, B, C *DenseMatrix, rs, re, cs, ce, ks, ke int)
aux = func(sync chan bool, A, B, C *DenseMatrix, rs, re, cs, ce, ks, ke int) {
dr := re - rs
dc := ce - cs
dk := ke - ks
switch {
case currentGoroutineCount < maxGoroutines && dr >= dc && dr >= dk && dr >= threshold:
sync0 := make(chan bool, 1)
rm := (rs + re) / 2
currentGoroutineCount++
go aux(sync0, A, B, C, rs, rm, cs, ce, ks, ke)
aux(nil, A, B, C, rm, re, cs, ce, ks, ke)
<-sync0
currentGoroutineCount--
case currentGoroutineCount < maxGoroutines && dc >= dk && dc >= dr && dc >= threshold:
sync0 := make(chan bool, 1)
cm := (cs + ce) / 2
currentGoroutineCount++
go aux(sync0, A, B, C, rs, re, cs, cm, ks, ke)
aux(nil, A, B, C, rs, re, cm, ce, ks, ke)
<-sync0
currentGoroutineCount--
case currentGoroutineCount < maxGoroutines && dk >= dc && dk >= dr && dk >= threshold:
km := (ks + ke) / 2
aux(nil, A, B, C, rs, re, cs, ce, ks, km)
aux(nil, A, B, C, rs, re, cs, ce, km, ke)
default:
for row := rs; row < re; row++ {
sums := C.elements[row*C.step : (row+1)*C.step]
for k := ks; k < ke; k++ {
for col := cs; col < ce; col++ {
sums[col] += A.elements[row*A.step+k] * B.elements[k*B.step+col]
}
}
}
}
if sync != nil {
sync <- true
}
}
aux(nil, A, B, C, 0, A.rows, 0, B.cols, 0, A.cols)
return
}
var (
WhichParMethod = 2
WhichSyncMethod = 1
)
func (A *DenseMatrix) TimesDense(B *DenseMatrix) (C *DenseMatrix, err error) {
C = Zeros(A.rows, B.cols)
err = A.TimesDenseFill(B, C)
return
}
func (A *DenseMatrix) TimesDenseFill(B, C *DenseMatrix) (err error) {
if C.rows != A.rows || C.cols != B.cols || A.cols != B.rows {
err = ErrorDimensionMismatch
return
}
if WhichParMethod > 0 && runtime.GOMAXPROCS(0) > 1 && A.rows > 50 {
switch WhichParMethod {
case 1:
parTimes1(A, B, C)
case 2:
parTimes2(A, B, C)
}
} else {
switch {
case A.cols > 100 && WhichSyncMethod == 2:
transposeTimes(A, B, C)
default:
for i := 0; i < A.rows; i++ {
sums := C.elements[i*C.step : (i+1)*C.step]
for k, a := range A.elements[i*A.step : i*A.step+A.cols] {
for j, b := range B.elements[k*B.step : k*B.step+B.cols] {
sums[j] += a * b
}
}
}
}
}
return
}
func transposeTimes(A, B, C *DenseMatrix) {
Bt := B.Transpose()
Bcols := Bt.Arrays()
for i := 0; i < A.rows; i++ {
Arow := A.elements[i*A.step : i*A.step+A.cols]
for j := 0; j < B.cols; j++ {
Bcol := Bcols[j]
for k := range Arow {
C.elements[i*C.step+j] += Arow[k] * Bcol[k]
}
}
}
return
}
func (A *DenseMatrix) ElementMult(B MatrixRO) (Matrix, error) {
C := A.Copy()
err := C.ScaleMatrix(B)
return C, err
}
func (A *DenseMatrix) ElementMultDense(B *DenseMatrix) (*DenseMatrix, error) {
C := A.Copy()
err := C.ScaleMatrixDense(B)
return C, err
}
func (A *DenseMatrix) Scale(f float64) {
for i := 0; i < A.rows; i++ {
index := i * A.step
for j := 0; j < A.cols; j++ {
A.elements[index] *= f
index++
}
}
}
func (A *DenseMatrix) ScaleMatrix(B MatrixRO) error {
if Bd, ok := B.(*DenseMatrix); ok {
return A.ScaleMatrixDense(Bd)
}
if A.rows != B.Rows() || A.cols != B.Cols() {
return ErrorDimensionMismatch
}
for i := 0; i < A.rows; i++ {
indexA := i * A.step
for j := 0; j < A.cols; j++ {
A.elements[indexA] *= B.Get(i, j)
indexA++
}
}
return nil
}
func (A *DenseMatrix) ScaleMatrixDense(B *DenseMatrix) error {
if A.rows != B.rows || A.cols != B.cols {
return ErrorDimensionMismatch
}
for i := 0; i < A.rows; i++ {
indexA := i * A.step
indexB := i * B.step
for j := 0; j < A.cols; j++ {
A.elements[indexA] *= B.elements[indexB]
indexA++
indexB++
}
}
return nil
} | dense_arithmetic.go | 0.666714 | 0.439447 | dense_arithmetic.go | starcoder |
package r2
import "math"
// Vec is a 2D vector.
type Vec struct {
X, Y float64
}
// Add returns the vector sum of p and q.
func Add(p, q Vec) Vec {
return Vec{
X: p.X + q.X,
Y: p.Y + q.Y,
}
}
// Sub returns the vector sum of p and -q.
func Sub(p, q Vec) Vec {
return Vec{
X: p.X - q.X,
Y: p.Y - q.Y,
}
}
// Scale returns the vector p scaled by f.
func Scale(f float64, p Vec) Vec {
return Vec{
X: f * p.X,
Y: f * p.Y,
}
}
// Dot returns the dot product p·q.
func Dot(p, q Vec) float64 {
return p.X*q.X + p.Y*q.Y
}
// Cross returns the cross product p×q.
func Cross(p, q Vec) float64 {
return p.X*q.Y - p.Y*q.X
}
// Rotate returns a new vector, rotated by alpha around the provided point, q.
func Rotate(p Vec, alpha float64, q Vec) Vec {
return NewRotation(alpha, q).Rotate(p)
}
// Norm returns the Euclidean norm of p
// |p| = sqrt(p_x^2 + p_y^2).
func Norm(p Vec) float64 {
return math.Hypot(p.X, p.Y)
}
// Norm2 returns the Euclidean squared norm of p
// |p|^2 = p_x^2 + p_y^2.
func Norm2(p Vec) float64 {
return p.X*p.X + p.Y*p.Y
}
// Unit returns the unit vector colinear to p.
// Unit returns {NaN,NaN} for the zero vector.
func Unit(p Vec) Vec {
if p.X == 0 && p.Y == 0 {
return Vec{X: math.NaN(), Y: math.NaN()}
}
return Scale(1/Norm(p), p)
}
// Cos returns the cosine of the opening angle between p and q.
func Cos(p, q Vec) float64 {
return Dot(p, q) / (Norm(p) * Norm(q))
}
// Box is a 2D bounding box.
type Box struct {
Min, Max Vec
}
// Rotation describes a rotation in 2D.
type Rotation struct {
sin, cos float64
p Vec
}
// NewRotation creates a rotation by alpha, around p.
func NewRotation(alpha float64, p Vec) Rotation {
if alpha == 0 {
return Rotation{sin: 0, cos: 1, p: p}
}
sin, cos := math.Sincos(alpha)
return Rotation{sin: sin, cos: cos, p: p}
}
// Rotate returns p rotated according to the parameters used to construct
// the receiver.
func (r Rotation) Rotate(p Vec) Vec {
if r.isIdentity() {
return p
}
o := Sub(p, r.p)
return Add(Vec{
X: (o.X*r.cos - o.Y*r.sin),
Y: (o.X*r.sin + o.Y*r.cos),
}, r.p)
}
func (r Rotation) isIdentity() bool {
return r.sin == 0 && r.cos == 1
} | spatial/r2/vector.go | 0.930868 | 0.777638 | vector.go | starcoder |
package types
import (
"fmt"
sdk "github.com/ci123chain/ci123chain/pkg/abci/types"
)
type Minter struct {
Inflation sdk.Dec `json:"inflation"` //current annual inflation rate
AnnualProvisions sdk.Dec `json:"annual_provisions"` //current annual expected provisions
}
func NewMinter(inflation, annualProvisions sdk.Dec) Minter {
return Minter{
Inflation: inflation,
AnnualProvisions: annualProvisions,
}
}
func InitialMinter(inflation, annual_provisions sdk.Dec) Minter {
return NewMinter(inflation, annual_provisions)
}
func DefaultInitialMinter() Minter {
return InitialMinter(
sdk.NewDecWithPrec(13, 2),
sdk.NewDecWithPrec(1, 2),
)
}
func ValidateMinter(minter Minter) error {
if minter.Inflation.IsNegative() {
return fmt.Errorf("mint parameter Inflation should be positive, is %s",
minter.Inflation.String())
}
return nil
}
func (m Minter) NextInflationRate(params Params, bondedRatio sdk.Dec) sdk.Dec {
// The target annual inflation rate is recalculated for each previsions cycle. The
// inflation is also subject to a rate change (positive or negative) depending on
// the distance from the desired ratio (67%). The maximum rate change possible is
// defined to be 13% per year, however the annual inflation is capped as between
// 7% and 20%.
// (1 - bondedRatio/GoalBonded) * InflationRateChange
inflationRateChangePerYear := sdk.OneDec().
Sub(bondedRatio.Quo(params.GoalBonded)).
Mul(params.InflationRateChange)
inflationRateChange := inflationRateChangePerYear.Quo(sdk.NewDec(int64(params.BlocksPerYear)))
// adjust the new annual inflation for this next cycle
inflation := m.Inflation.Add(inflationRateChange) // note inflationRateChange may be negative
if inflation.GT(params.InflationMax) {
inflation = params.InflationMax
}
if inflation.LT(params.InflationMin) {
inflation = params.InflationMin
}
return inflation
}
// NextAnnualProvisions returns the annual provisions based on current total
// supply and inflation rate.
func (m Minter) NextAnnualProvisions(_ Params, totalSupply sdk.Int) sdk.Dec {
return m.Inflation.MulInt(totalSupply)
}
// BlockProvision returns the provisions for a block based on the annual
// provisions rate.
func (m Minter) BlockProvision(params Params) sdk.Coin {
provisionAmt := m.AnnualProvisions.QuoInt(sdk.NewInt(int64(params.BlocksPerYear)))
return sdk.NewChainCoin(provisionAmt.TruncateInt())
} | pkg/mint/types/minter.go | 0.761804 | 0.410225 | minter.go | starcoder |
package main
import "strings"
/**
* Get the type from a documentation command line
* @param {string} [line] The comment line to parse
* @returns {string,string}
*/
func GetType(line string) (string, string) {
array := Split(line, " ")
Type := ""
for _, word := range array {
if StartsWith(word, "{") && EndsWith(word, "}") {
Type = Remove(Remove(word, "{"), "}")
}
}
line = Replace(line, "{"+Type+"}", "")
return Type, line
}
/**
* Get the name from a documentation command line
* @param {string} [line] The comment line to parse
* @returns {string,string}
*/
func GetName(line string) (string, string) {
array := Split(line, " ")
Name := ""
for _, word := range array {
if StartsWith(word, "[") && EndsWith(word, "]") {
Name = Remove(Remove(word, "["), "]")
}
}
line = Replace(line, "["+Name+"]", "")
return Name, line
}
/**
* Split a line by a seperator
* @param {string} [line] The comment line to split
* @param {string} [seperator] The seperator to split line with
* @returns {[]string}
*/
func Split(line string, seperator string) []string {
return strings.Split(line, seperator)
}
/**
* Check if a line by starts with a prefix
* @param {string} [line] The comment line to check
* @param {string} [prefix] The prefix to check
* @returns {bool}
*/
func StartsWith(line string, prefix string) bool {
return strings.HasPrefix(line, prefix)
}
/**
* Check if a line by ends with a suffix
* @param {string} [line] The comment line to check
* @param {string} [suffix] The suffix to check
* @returns {bool}
*/
func EndsWith(line string, suffix string) bool {
return strings.HasSuffix(line, suffix)
}
/**
* Replace a word by another one
* @param {string} [line] The comment line to replace the word in
* @param {string} [replace] The word to replace
* @param {string} [with] The word to replace with
* @returns {string}
*/
func Replace(line string, replace string, with string) string {
return strings.ReplaceAll(line, replace, with)
}
/**
* Replace a word by another one
* @param {string} [line] The comment line to replace the word in
* @param {string} [replace] The word to remove
* @returns {string}
*/
func Remove(line string, remove string) string {
return strings.ReplaceAll(line, remove, "")
}
/**
* Trim spaces from a line
* @param {string} [line] The comment line to trim
* @returns {string}
*/
func Trim(line string) string {
return strings.TrimSpace(line)
}
/**
* Check if given line starts with func
* @param {string} [data] The comment line to check
* @returns {bool}
*/
func IsFunctionLine(data string) bool {
return strings.HasPrefix(data, "func")
}
/**
* Check if given line starts with type
* @param {string} [data] The comment line to check
* @returns {bool}
*/
func IsStructureLine(data string) bool {
return strings.HasPrefix(data, "type")
}
/**
* Check if given comment documents a function of structure
* @param {string} [data] The comment to check
* @returns {string}
*/
func IsFunctionOfStructureLine(data string) bool {
array := Split(Trim(Remove(data, "func")), " ")
if len(array) == 0 {
return false
}
return StartsWith(array[0], "(") && EndsWith(array[1], ")")
}
/**
* Check if given comment documents a function
* @param {string} [data] The comment to check
* @returns {bool}
*/
func IsFunction(data string) bool {
array := strings.Split(data, "\n")
return IsFunctionLine(array[len(array)-1])
}
/**
* Check if given comment documents a structure
* @param {string} [data] The comment to check
* @returns {bool}
*/
func IsStructure(data string) bool {
array := strings.Split(data, "\n")
return IsStructureLine(array[len(array)-1])
} | util.go | 0.768125 | 0.4081 | util.go | starcoder |
package cfxaddress
import (
"github.com/pkg/errors"
)
/*
Base32-encode address:
To create the payload, first, concatenate the version-byte with addr to get a 21-byte array. Then, encode it left-to-right, mapping each 5-bit sequence to the corresponding ASCII character (see alphabet below). Pad to the right with zero bits to complete any unfinished chunk at the end. In our case, 21-byte payload + 2 bit 0-padding will result in a 34-byte base32-encoded string.
We use the following alphabet: abcdefghjkmnprstuvwxyz0123456789 (i, l, o, q removed).
0x00 => a 0x08 => j 0x10 => u 0x18 => 2
0x01 => b 0x09 => k 0x11 => v 0x19 => 3
0x02 => c 0x0a => m 0x12 => w 0x1a => 4
0x03 => d 0x0b => n 0x13 => x 0x1b => 5
0x04 => e 0x0c => p 0x14 => y 0x1c => 6
0x05 => f 0x0d => r 0x15 => z 0x1d => 7
0x06 => g 0x0e => s 0x16 => 0 0x1e => 8
0x07 => h 0x0f => t 0x17 => 1 0x1f => 9
*/
// Body reperents 5bits byte array of concating version byte with hex address
type Body []byte
// NewBodyByString creates body by base32 string which contains version byte and hex address
func NewBodyByString(base32Str string) (body Body, err error) {
for _, v := range base32Str {
index, ok := alphabetToIndexMap[v]
if !ok {
err = errors.New("invalid base32 string for body")
}
body = append(body, index)
}
return
}
// NewBodyByHexAddress convert concat of version type and hex address to 5 bits slice
func NewBodyByHexAddress(vrsByte VersionByte, hexAddress []byte) (b Body, err error) {
vb, err := vrsByte.ToByte()
if err != nil {
err = errors.Wrapf(err, "failed to encode version type %#v", vrsByte)
return
}
concatenate := append([]byte{vb}, hexAddress[:]...)
bits5, err := convert(concatenate, 8, 5)
if err != nil {
err = errors.Wrapf(err, "failed to convert %x from 8 to 5 bits array", concatenate)
return
}
b = bits5
return
}
// ToHexAddress decode bits5 array to version byte and hex address
func (b Body) ToHexAddress() (vrsType VersionByte, hexAddress []byte, err error) {
if len(b) == 0 {
err = errors.New("invalid base32 body")
}
val, err := convert(b, 5, 8)
vrsType = NewVersionByte(val[0])
hexAddress = val[1:]
return
}
// String return base32 string
func (b Body) String() string {
return bits5sToString(b)
} | vendor/github.com/Conflux-Chain/go-conflux-sdk/types/cfxaddress/body.go | 0.628065 | 0.483709 | body.go | starcoder |
// Package datatypes/dictionary provides an easy dictionary (key => value) homogeneous
// struct management, making the iteration of a unique-key lists more powerful,
// simple and clean, accepting primitives types and complex user structs as well.
// This part of package contains the core behaviour
package dictionary
import "reflect"
// KeyElement represents Key in Key-Value object
type KeyElement interface{}
// ValueElement represents Value in Key-Value object
type ValueElement interface{}
// KeyValueElement represents a Key-Value object
type KeyValueElement struct {
Key KeyElement
Value ValueElement
}
// KeyValueMap represents a map of Key-Vale elements
type KeyValueMap map[KeyElement]ValueElement
// Dictionary represents a simple dictionary (key => value) struct
type Dictionary struct {
keyDefinition reflect.Type
valueDefinition reflect.Type
elements KeyValueMap
}
// Add a key-value element to the dictionary
// Dictionary must to be homogeneous in key and in value as well so the specified elements
// should be the same type such the other elements already stored in the dictionary.
// If the dictionary is empty and have no elements, it will take the type of
// the first element as type definition
func (dic *Dictionary) Add(key KeyElement, value ValueElement) error {
if dic.IsEmpty() {
dic.keyDefinition = reflect.TypeOf(key)
dic.valueDefinition = reflect.TypeOf(value)
} else if !dic.isHomogeneousWith(key, value) {
return ErrInvalidKeyValueElementType
}
if dic.Contains(key) {
return ErrDuplicatedKey
}
dic.elements[key] = value
return nil
}
// AddKeyValueElement adds an composed element KeyValueElement to the dictionary
func (dic *Dictionary) AddKeyValueElement(element KeyValueElement) error {
return dic.Add(element.Key, element.Value)
}
// AddRange inserts a range (slice) of KeyValueElement inside the dictionary
// If the parameter can't be converted to a iterable data type it's return an error
func (dic *Dictionary) AddRange(elements []KeyValueElement) error {
for _, element := range elements {
if err := dic.AddKeyValueElement(element); err != nil {
return err
}
}
return nil
}
// Element returns the specified key element in the dictionary
func (dic *Dictionary) Element(key KeyElement) (*ValueElement, error) {
element, exists := dic.elements[key]
if !exists {
return nil, ErrElementNotFound
}
return &element, nil
}
// Elements returns the stored elements as slice of this elements
// This is the proper way to iterate over all the elements inside de dicionary
// treating them as a normal range
func (dic *Dictionary) Elements() *KeyValueMap {
return &dic.elements
}
// Keys returns all the keys in the dicionary as a list of KeyElement
func (dic *Dictionary) Keys() []KeyElement {
keys := []KeyElement{}
for current := range dic.elements {
keys = append(keys, current)
}
return keys
}
// Values returns all the values in the dicionary as a list of ValueElement
func (dic *Dictionary) Values() []ValueElement {
values := []ValueElement{}
for _, current := range dic.elements {
values = append(values, current)
}
return values
}
// Extract the first element and return it
// Keep in mind that this method will modify the dictionary elements subtracting that element
func (dic *Dictionary) Extract() *KeyValueElement {
for key, value := range dic.elements {
dic.Delete(key)
return &KeyValueElement{key, value}
}
return nil
}
// ExtractKey extracts the specified key element and return it
// Keep in mind that this method will modify the dictionary elements subtracting that element
func (dic *Dictionary) ExtractKey(key KeyElement) (*KeyValueElement, error) {
if dic.Contains(key) {
element := &KeyValueElement{key, dic.elements[key]}
dic.Delete(key)
return element, nil
}
return nil, ErrElementNotFound
}
// Set a new value for a specified index element
func (dic *Dictionary) Set(key KeyElement, value ValueElement) error {
if !dic.isHomogeneousWith(key, value) {
return ErrInvalidKeyValueElementType
}
if !dic.Contains(key) {
return ErrElementNotFound
}
dic.elements[key] = value
return nil
}
// Delete an specified already stored element
// If it's not found the method will return an error
func (dic *Dictionary) Delete(key KeyElement) error {
if !dic.Contains(key) {
return ErrElementNotFound
}
delete(dic.elements, key)
return nil
}
// Contains checks if the specified key element is already existing in the dictionary
func (dic *Dictionary) Contains(element KeyElement) bool {
_, exists := dic.elements[element]
return exists
}
// ContainsValue checks if the specified value element exists in the dictionary
func (dic *Dictionary) ContainsValue(element ValueElement) bool {
for _, value := range dic.elements {
if reflect.DeepEqual(value, element) {
return true
}
}
return false
}
// Filter returns a element colecction filtering the elements with a function
// If the functions return true the element will be filtered
func (dic *Dictionary) Filter(f func(KeyValueElement) bool) *KeyValueMap {
results := make(KeyValueMap)
for key, value := range *dic.Elements() {
elem := KeyValueElement{key, value}
if !f(elem) {
continue
}
results[key] = value
}
return &results
}
// Size returns the number of elements inside the dicionary
func (dic *Dictionary) Size() int {
return len(dic.elements)
}
// IsEmpty checks if the dictionary is empty or not
func (dic *Dictionary) IsEmpty() bool {
return dic.Size() == 0
}
func (dic *Dictionary) isHomogeneousWith(key KeyElement, value ValueElement) bool {
return dic.keyDefinition == reflect.TypeOf(key) &&
dic.valueDefinition == reflect.TypeOf(value)
}
// NewEmptyDictionary instances a new empty dictionary
func NewEmptyDictionary() *Dictionary {
dic := new(Dictionary)
dic.elements = make(KeyValueMap)
return dic
}
// NewDictionary allows to instance a new Dictionary with a group of key-value elements
func NewDictionary(elements []KeyValueElement) (*Dictionary, error) {
dictionary := NewEmptyDictionary()
err := dictionary.AddRange(elements)
return dictionary, err
} | dictionary/dictionary.go | 0.81637 | 0.535281 | dictionary.go | starcoder |
Package smart provides details about a particular disk device which includes both
basic details such as vendor, model, serial, etc as well as smart details such as
Raw_Read_Error_Rate, Temperature_Celsius, Spin_Up_Time, etc by parsing various disk
pages such as inquiry page, ata command set page ,etc using various SCSI commands such
as scsi inquiry, read device capacity, mode sense, etc.
NOTE : For now, the implementation is only for getting the basic details (not smart details)
of SCSI disks such as vendor,serial, model, firmware revision, logical sector size,etc.
Usage:
import "github.com/openebs/node-disk-manager/pkg/smart"
S.M.A.R.T. (Self-Monitoring, Analysis and Reporting Technology; often written as SMART) is
a monitoring system included in computer hard disk drives (HDDs), solid-state drives (SSDs),
and eMMC drives. Its primary function is to detect and report various indicators of drive
reliability with the intent of anticipating imminent hardware failures.
When S.M.A.R.T. data indicates a possible imminent drive failure, software running on the
host system may notify the user so preventative action can be taken to prevent data loss,
and the failing drive can be replaced and data integrity maintained.
This smart go library provides functionality to get the list of all the SCSI disk devices
attached to it and a list of disk smart attributes along with the basic disk attributes
such as serial no, sector size, wwn, rpm, vendor, etc.
For getting the basic SCSI disk details, one should import this library and then a call to
function SCSIBasicDiskInfo("device-path") where device-path is the devpath of the scsi device
e.g. /dev/sda, /dev/sdb, etc for which we want to fetch the basic disk details such as vendor,
model, serial, wwn, logical and physical sector size, etc is to be fetched.
This function would return a struct of disk details alongwith errors if any, filled by smart
library for the particular disk device whose devpath has been given.
If a user wants to only get the detail of a particular disk attribute such as vendor, serial,
etc for a particular SCSI device then function SCSIBasicDiskInfoByAttrName(attrName string)
(where attrName refers to the attribute whose value is to be fetched such as Vendor)
should be called which will return the detail or value of that particular attribute only
alongwith the errors if any occurred while fetching the detail.
An example usage can be like this -
package smartusageexample
import (
"fmt"
"github.com/golang/glog"
"github.com/openebs/node-disk-manager/pkg/smart"
)
func main() {
deviceBasicSCSIInfo, err := smart.SCSIBasicDiskInfo("/dev/sda")
if err != nil {
glog.Fatal(err)
}
fmt.Printf("Vendor :%s \n",deviceBasicSCSIInfo.Vendor)
fmt.Printf("Compliance :%s \n",deviceBasicSCSIInfo.Compliance)
fmt.Printf("FirmwareRevision :%s \n",deviceBasicSCSIInfo.FirmwareRevision)
fmt.Printf("Capacity :%d \n",deviceBasicSCSIInfo.Capacity)
}
NOTE : This document will remain in continuous updation whenever more features and
functionalities are implemented.
Please refer to the design doc here -
https://docs.google.com/document/d/1avZrFI3j1AOmWIY_43oyK9Nkj5IYT37fzIhAAbp0Bxs/edit?usp=sharing
*/
package smart | pkg/smart/doc.go | 0.572842 | 0.525856 | doc.go | starcoder |
package kit
import (
"github.com/SirMetathyst/zinc"
)
// Velocity2Key ...
const Velocity2Key uint = 2475506976
// Velocity2Data ...
type Velocity2Data struct {
X float32
Y float32
}
// Velocity2Component ...
type Velocity2Component struct {
ctx zinc.CTX
data map[zinc.EntityID]Velocity2Data
}
// NewVelocity2Component ...
func NewVelocity2Component() *Velocity2Component {
return &Velocity2Component{
data: make(map[zinc.EntityID]Velocity2Data),
}
}
// RegisterVelocity2ComponentWith ...
func RegisterVelocity2ComponentWith(e *zinc.EntityManager) {
x := NewVelocity2Component()
ctx := e.RegisterComponent(Velocity2Key, x)
x.SetContext(ctx)
}
// RegisterVelocity2Component ...
func RegisterVelocity2Component() {
x := NewVelocity2Component()
ctx := zinc.Default().RegisterComponent(Velocity2Key, x)
x.SetContext(ctx)
}
// SetContext ...
func (c *Velocity2Component) SetContext(ctx zinc.CTX) {
if c.ctx == nil {
c.ctx = ctx
}
}
func init() {
RegisterVelocity2Component()
}
// DeleteEntity ...
func (c *Velocity2Component) DeleteEntity(id zinc.EntityID) {
delete(c.data, id)
c.ctx.ComponentDeleted(Velocity2Key, id)
}
// HasEntity ...
func (c *Velocity2Component) HasEntity(id zinc.EntityID) bool {
_, ok := c.data[id]
return ok
}
// SetVelocity2 ...
func (c *Velocity2Component) SetVelocity2(id zinc.EntityID, velocity2 Velocity2Data) {
if c.ctx.HasEntity(id) {
if c.HasEntity(id) {
c.data[id] = velocity2
c.ctx.ComponentUpdated(Velocity2Key, id)
} else {
c.data[id] = velocity2
c.ctx.ComponentAdded(Velocity2Key, id)
}
}
}
// Velocity2 ...
func (c *Velocity2Component) Velocity2(id zinc.EntityID) Velocity2Data {
return c.data[id]
}
// SetVelocity2X ...
func SetVelocity2X(e *zinc.EntityManager, id zinc.EntityID, velocity2 Velocity2Data) {
v, _ := e.Component(Velocity2Key)
c := v.(*Velocity2Component)
c.SetVelocity2(id, velocity2)
}
// SetVelocity2 ...
func SetVelocity2(id zinc.EntityID, velocity2 Velocity2Data) {
SetVelocity2X(zinc.Default(), id, velocity2)
}
// Velocity2X ...
func Velocity2X(e *zinc.EntityManager, id zinc.EntityID) Velocity2Data {
v, _ := e.Component(Velocity2Key)
c := v.(*Velocity2Component)
return c.Velocity2(id)
}
// Velocity2 ...
func Velocity2(id zinc.EntityID) Velocity2Data {
return Velocity2X(zinc.Default(), id)
}
// DeleteVelocity2X ...
func DeleteVelocity2X(e *zinc.EntityManager, id zinc.EntityID) {
v, _ := e.Component(LocalPosition2Key)
v.DeleteEntity(id)
}
// DeleteVelocity2 ...
func DeleteVelocity2(id zinc.EntityID) {
DeleteVelocity2X(zinc.Default(), id)
}
// HasVelocity2X ...
func HasVelocity2X(e *zinc.EntityManager, id zinc.EntityID) bool {
v, _ := e.Component(Velocity2Key)
return v.HasEntity(id)
}
// HasVelocity2 ...
func HasVelocity2(id zinc.EntityID) bool {
return HasVelocity2X(zinc.Default(), id)
} | kit/zinc_Velocity2.go | 0.621081 | 0.485661 | zinc_Velocity2.go | starcoder |
package lsdp
// DistanceMeasurer provides measurement of the distance between 2 strings
type DistanceMeasurer interface {
Distance(string, string) float64
}
// Lsd returns standard Levenshtein distance
func Lsd(a, b string) int {
wd := &Weights{1, 1, 1}
return int(wd.Distance(a, b))
}
// Weights represents cost parameters for weighted Levenshtein distance
type Weights struct {
Insert float64
Delete float64
Replace float64
}
// Distance returns weighted Levenshtein distance
func (w Weights) Distance(a, b string) float64 {
result := accumulateCost(a, b, func(_, _ int, ar, br rune, diagonal, above, left float64) (float64, float64, float64) {
if ar != br {
diagonal += w.Replace
}
above += w.Insert
left += w.Delete
return diagonal, above, left
}, minCost)
return result
}
// ByRune returns weighted levenshtein distance by rune
func ByRune(w *Weights) *WeightsByRune {
return &WeightsByRune{
w: w,
insRune: make(map[rune]float64),
delRune: make(map[rune]float64),
repRune: make(map[[2]rune]float64),
}
}
// WeightsByRune represents weighted levenshtein distance by rune
type WeightsByRune struct {
w *Weights
insRune map[rune]float64
delRune map[rune]float64
repRune map[[2]rune]float64
}
// Distance returns weighted levenshtein distance by rune
func (wr *WeightsByRune) Distance(a, b string) float64 {
ret := accumulateCost(a, b, func(_, _ int, ar, br rune, diagonal, above, left float64) (float64, float64, float64) {
if rw, ok := wr.repRune[[2]rune{ar, br}]; ok {
diagonal += rw
} else if ar != br {
diagonal += wr.w.Replace
}
if rw, ok := wr.insRune[br]; ok {
above += rw
} else {
above += wr.w.Insert
}
if rw, ok := wr.delRune[ar]; ok {
left += rw
} else {
left += wr.w.Delete
}
return diagonal, above, left
}, minCost)
return ret
}
// Insert specify cost by insert rune
func (wr *WeightsByRune) Insert(runeGroup string, insCost float64) *WeightsByRune {
for _, r := range runeGroup {
wr.insRune[r] = insCost
}
return wr
}
// Delete specify cost by delete rune
func (wr *WeightsByRune) Delete(runeGroup string, delCost float64) *WeightsByRune {
for _, r := range runeGroup {
wr.delRune[r] = delCost
}
return wr
}
// Replace specify cost by replace rune
func (wr *WeightsByRune) Replace(runeGroupSrc, runeGroupDest string, repCost float64) *WeightsByRune {
for _, rs := range runeGroupSrc {
for _, rd := range runeGroupDest {
wr.repRune[[2]rune{rs, rd}] = repCost
}
}
return wr
}
// Normalized returns what wrapped the DistanceMeasurer with nomalize by string length
func Normalized(dm DistanceMeasurer) DistanceMeasurer {
return normalizedParam{wrapped: dm}
}
type normalizedParam struct {
wrapped DistanceMeasurer
}
func (p normalizedParam) Distance(a, b string) float64 {
d := p.wrapped.Distance(a, b)
l := len([]rune(a))
if lb := len([]rune(b)); l < lb {
l = lb
}
if l == 0 {
return d
}
return d / float64(l)
}
// DistanceFunc type is an adapter to allow the use of ordinary functions as DistanceMeasurer.
// Similar to http.HandlerFunc.
type DistanceFunc func(string, string) float64
// Distance calls f(a,b)
func (f DistanceFunc) Distance(a, b string) float64 {
return f(a, b)
}
type costFunc func(ai, bi int, ar, br rune, diagonal, above, left float64) (rep, ins, del float64)
type minFunc func(a, b, c float64) (min float64)
func accumulateCost(a, b string, costf costFunc, min minFunc) float64 {
ar, br := []rune(a), []rune(b)
costRow := make([]float64, len(ar)+1)
for i := 1; i < len(costRow); i++ {
_, _, costRow[i] = costf(i, 0, ar[i-1], 0, 0, 0, costRow[i-1])
}
var left float64
for bc := 1; bc < len(br)+1; bc++ {
_, left, _ = costf(0, bc, 0, br[bc-1], 0, costRow[0], 0)
for i := 1; i < len(costRow); i++ {
rep, ins, del := costf(i, bc, ar[i-1], br[bc-1], costRow[i-1], costRow[i], left)
costRow[i-1] = left
left = min(rep, ins, del)
}
costRow[len(costRow)-1] = left
}
return costRow[len(costRow)-1]
}
func minCost(a, b, c float64) (min float64) {
min = a
if b < min {
min = b
}
if c < min {
min = c
}
return
} | lsd.go | 0.887844 | 0.666944 | lsd.go | starcoder |
package pazu
import (
"fmt"
"strconv"
"unicode"
)
type List struct {
Elements []interface{} // Elements may be Atoms or Lists
}
type Atom struct {
Value interface{}
}
type Symbol string
// Parse takes an s-expression of string tokens and returns an abstract syntax tree. It returns
// a single item which may be an Atom (int, string, symbol) or a List.
func Parse(tokens []string) (interface{}, error) {
if len(tokens) == 0 {
return List{}, nil
}
if len(tokens) == 1 {
return parseAtom(tokens[0])
}
if tokens[0] == "(" && tokens[len(tokens)-1] == ")" {
ast, remainder, err := parseList(tokens)
if len(remainder) != 0 {
fmt.Printf("REMAINDER: %v", remainder) // FIXME
}
return ast, err
}
return nil, fmt.Errorf("invalid expression")
}
func parseAtom(token string) (interface{}, error) {
switch {
case isString(token):
return parseString(token)
case isInt(token):
return parseInt(token)
case token == "(" || token == ")":
return nil, fmt.Errorf("invalid symbol: %s", token)
}
return Atom{Symbol(token)}, nil
}
func isString(token string) bool {
first := []rune(token)[0]
last := []rune(token)[len(token)-1]
return first == '"' && last == '"'
}
func isInt(token string) bool {
return unicode.IsDigit([]rune(token)[0]) // TODO: This could be more robust
}
func parseString(token string) (Atom, error) {
s, err := strconv.Unquote(token)
if err != nil {
return Atom{}, fmt.Errorf("quote mismatch")
}
return Atom{s}, nil
}
func parseInt(token string) (Atom, error) {
i, err := strconv.Atoi(token)
if err != nil {
return Atom{}, fmt.Errorf("could not '%s' convert to integer", token)
}
return Atom{i}, nil
}
func parseList(tokens []string) (List, []string, error) {
tokens = tokens[1:]
li := List{}
var (
err error
el interface{}
)
for len(tokens) > 0 {
head := tokens[0]
tail := tokens[1:]
switch head {
case "(":
el, tokens, err = parseList(tokens)
case ")":
return li, tail, nil
default:
el, err = parseAtom(head)
tokens = tail
}
if err != nil {
return List{}, []string{}, err
}
li.Elements = append(li.Elements, el)
}
return li, tokens, fmt.Errorf("parenthesis mismatch")
} | pkg/pazu/parser.go | 0.555918 | 0.467453 | parser.go | starcoder |
package heap
type
// A HeapInt is an effient data structure to find the minimum element in a collection
HeapInt interface {
Peek() (int, bool)
Pop() (int, bool)
Push(int)
}
type
// A HeapInt8 is an effient data structure to find the minimum element in a collection
HeapInt8 interface {
Peek() (int8, bool)
Pop() (int8, bool)
Push(int8)
}
type
// A HeapInt16 is an effient data structure to find the minimum element in a collection
HeapInt16 interface {
Peek() (int16, bool)
Pop() (int16, bool)
Push(int16)
}
type
// A HeapInt32 is an effient data structure to find the minimum element in a collection
HeapInt32 interface {
Peek() (int32, bool)
Pop() (int32, bool)
Push(int32)
}
type
// A HeapInt64 is an effient data structure to find the minimum element in a collection
HeapInt64 interface {
Peek() (int64, bool)
Pop() (int64, bool)
Push(int64)
}
type
// A HeapUint is an effient data structure to find the minimum element in a collection
HeapUint interface {
Peek() (uint, bool)
Pop() (uint, bool)
Push(uint)
}
type
// A HeapUint8 is an effient data structure to find the minimum element in a collection
HeapUint8 interface {
Peek() (uint8, bool)
Pop() (uint8, bool)
Push(uint8)
}
type
// A HeapUint16 is an effient data structure to find the minimum element in a collection
HeapUint16 interface {
Peek() (uint16, bool)
Pop() (uint16, bool)
Push(uint16)
}
type
// A HeapUint32 is an effient data structure to find the minimum element in a collection
HeapUint32 interface {
Peek() (uint32, bool)
Pop() (uint32, bool)
Push(uint32)
}
type
// A HeapUint64 is an effient data structure to find the minimum element in a collection
HeapUint64 interface {
Peek() (uint64, bool)
Pop() (uint64, bool)
Push(uint64)
}
type
// A HeapFloat32 is an effient data structure to find the minimum element in a collection
HeapFloat32 interface {
Peek() (float32, bool)
Pop() (float32, bool)
Push(float32)
}
type
// A HeapFloat64 is an effient data structure to find the minimum element in a collection
HeapFloat64 interface {
Peek() (float64, bool)
Pop() (float64, bool)
Push(float64)
}
type
// A HeapComplex64 is an effient data structure to find the minimum element in a collection
HeapComplex64 interface {
Peek() (complex64, bool)
Pop() (complex64, bool)
Push(complex64)
}
type
// A HeapComplex128 is an effient data structure to find the minimum element in a collection
HeapComplex128 interface {
Peek() (complex128, bool)
Pop() (complex128, bool)
Push(complex128)
}
type
// A HeapString is an effient data structure to find the minimum element in a collection
HeapString interface {
Peek() (string, bool)
Pop() (string, bool)
Push(string)
} | heap/reified_heap.go | 0.575707 | 0.512754 | reified_heap.go | starcoder |
package blockchain
const wrapperABI = `[
{
"constant": true,
"inputs": [
{
"name": "x",
"type": "bytes14"
},
{
"name": "byteInd",
"type": "uint256"
}
],
"name": "getInt8FromByte",
"outputs": [
{
"name": "",
"type": "int8"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "reserve",
"type": "address"
},
{
"name": "tokens",
"type": "address[]"
}
],
"name": "getBalances",
"outputs": [
{
"name": "",
"type": "uint256[]"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "ratesContract",
"type": "address"
},
{
"name": "tokenList",
"type": "address[]"
}
],
"name": "getTokenIndicies",
"outputs": [
{
"name": "",
"type": "uint256[]"
},
{
"name": "",
"type": "uint256[]"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "reserve",
"type": "address"
},
{
"name": "srcs",
"type": "address[]"
},
{
"name": "dests",
"type": "address[]"
}
],
"name": "getReserveRate",
"outputs": [
{
"name": "",
"type": "uint256[]"
},
{
"name": "",
"type": "uint256[]"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "x",
"type": "bytes14"
},
{
"name": "byteInd",
"type": "uint256"
}
],
"name": "getByteFromBytes14",
"outputs": [
{
"name": "",
"type": "bytes1"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "network",
"type": "address"
},
{
"name": "srcs",
"type": "address[]"
},
{
"name": "dests",
"type": "address[]"
},
{
"name": "qty",
"type": "uint256[]"
}
],
"name": "getExpectedRates",
"outputs": [
{
"name": "",
"type": "uint256[]"
},
{
"name": "",
"type": "uint256[]"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "ratesContract",
"type": "address"
},
{
"name": "tokenList",
"type": "address[]"
}
],
"name": "getTokenRates",
"outputs": [
{
"name": "",
"type": "uint256[]"
},
{
"name": "",
"type": "uint256[]"
},
{
"name": "",
"type": "int8[]"
},
{
"name": "",
"type": "int8[]"
},
{
"name": "",
"type": "uint256[]"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]` | blockchain/wrapper_abi.go | 0.622574 | 0.444143 | wrapper_abi.go | starcoder |
package gohome
import (
"github.com/PucklaMotzer09/mathgl/mgl32"
"github.com/PucklaMotzer09/tmx"
"image/color"
)
type sprite2DConfiguration struct {
TextureName string
Flip uint8
Region TextureRegion
}
// A tmx map as a RenderObject
type TiledMap struct {
Sprite2D
*tmx.Map
layers []Texture
}
// Converts a hex character to its decimal value
func HEXToUint4(str byte) uint8 {
switch str {
case '0':
return 0
case '1':
return 1
case '2':
return 2
case '3':
return 3
case '4':
return 4
case '5':
return 5
case '6':
return 6
case '7':
return 7
case '8':
return 8
case '9':
return 9
case 'a', 'A':
return 10
case 'b', 'B':
return 11
case 'c', 'C':
return 12
case 'd', 'D':
return 13
case 'e', 'E':
return 14
case 'f', 'F':
return 15
}
return 0
}
// Converts to hex characters to its integer value
func HEXToUint8(str string) uint8 {
var first, second uint8
first = HEXToUint4(str[0])
second = HEXToUint4(str[1])
return (first << 4) | second
}
// Converts a hex color value into a real color
func HEXToColor(str string) color.Color {
col := &Color{}
col.R = HEXToUint8(str[1:3])
col.G = HEXToUint8(str[3:5])
col.B = HEXToUint8(str[5:7])
col.A = 255
return col
}
// Initialises the TiledMap with a tmx map file stored in the resource manager
func (this *TiledMap) Init(tmxmapname string) {
tmxmap := ResourceMgr.GetTMXMap(tmxmapname)
if tmxmap == nil {
ErrorMgr.Warning("TiledMap", tmxmapname, "Has not been loaded!")
return
}
this.Map = tmxmap
this.Texture = Render.CreateRenderTexture("TMXMapTexture", int(this.Width*this.TileWidth), int(this.Height*this.TileHeight), 1, false, false, false, false)
rt := this.Texture.(RenderTexture)
rt.SetFiltering(FILTERING_NEAREST)
rt.SetAsTarget()
var backCol color.Color
back := this.BackgroundColor
if back != nil {
backCol = HEXToColor(*back)
} else {
backCol = Color{0, 0, 0, 255}
}
Render.ClearScreen(backCol)
rt.UnsetAsTarget()
this.Sprite2D.commonInit()
this.generateTextures()
}
func getTextureRegionFromID(ts *tmx.TileSet, id int) TextureRegion {
tilesWidth := int(ts.Columns)
x := id % tilesWidth
y := (id - x) / tilesWidth
var region TextureRegion
region.Min[0] = float32(x*int(ts.TileWidth+ts.Spacing) + int(ts.Margin))
region.Min[1] = float32(y*int(ts.TileHeight+ts.Spacing) + int(ts.Margin))
region.Max[0] = region.Min[0] + float32(ts.TileWidth)
region.Max[1] = region.Min[1] + float32(ts.TileHeight)
return region
}
func getFlip(tile tmx.TileInstance) uint8 {
if tile.FlippedHorizontally() {
return FLIP_HORIZONTAL
} else if tile.FlippedVertically() {
return FLIP_VERTICAL
} else if tile.FlippedDiagonally() {
return FLIP_DIAGONALLY
} else {
return FLIP_NONE
}
}
func (this *TiledMap) getSprite2DConfiguration(tile tmx.TileInstance) sprite2DConfiguration {
gid := int(tile.GID())
var ts *tmx.TileSet
var config sprite2DConfiguration
if len(this.TileSets) == 1 {
ts = this.TileSets[0]
} else {
for i := 0; i < len(this.TileSets); i++ {
t := this.TileSets[i]
if gid >= int(t.FirstGID) && gid <= int(t.FirstGID+(t.TileCount-1)) {
ts = t
break
}
}
if ts == nil {
if len(this.TileSets) == 0 {
return config
} else {
ts = this.TileSets[len(this.TileSets)-1]
}
}
}
id := gid - int(ts.FirstGID)
config.Region = getTextureRegionFromID(ts, id)
config.TextureName = ts.Name
config.Flip = getFlip(tile)
return config
}
func (this *TiledMap) renderConfiguration(config sprite2DConfiguration, pos mgl32.Vec2, rt RenderTexture) {
if config.TextureName == "" {
return
}
texture := ResourceMgr.GetTexture(config.TextureName)
if texture == nil {
ErrorMgr.Error("TiledMap", config.TextureName, "Couldn't get texture from tile!")
return
}
texture.SetFiltering(FILTERING_NEAREST)
var spr Sprite2D
spr.InitTexture(texture)
spr.TextureRegion = config.Region
spr.Transform.Size[0] = float32(config.Region.Width())
spr.Transform.Size[1] = float32(config.Region.Height())
spr.Transform.Position = pos
spr.Flip = config.Flip
RenderMgr.RenderRenderObjectAdv(&spr, -1, -1)
}
func (this *TiledMap) loadTileLayer(l *tmx.Layer) {
data := l.Data
iter, err := data.Iter()
if err != nil {
ErrorMgr.Error("TiledMap", l.Name, "Couldn't get the TileIterator!")
return
}
texture := Render.CreateRenderTexture(l.Name+" RenderTexture", int(this.Width*this.TileWidth), int(this.Height*this.TileHeight), 1, false, false, false, false)
if texture == nil {
ErrorMgr.Error("TiledMap", l.Name, "Couldn't create the RenderTexture for the layer")
return
}
texture.SetFiltering(FILTERING_NEAREST)
var pos mgl32.Vec2
texture.SetAsTarget()
for iter.Next() {
tile := iter.Get()
if tile.GID() == 0 {
continue
}
config := this.getSprite2DConfiguration(tile)
counter := iter.GetIndex()
pos[0] = float32((counter % this.Width) * this.TileWidth)
pos[1] = float32(((counter - (counter % this.Width)) / this.Width) * this.TileHeight)
this.renderConfiguration(config, pos, texture)
}
texture.UnsetAsTarget()
if l.Opacity != nil {
alpha := uint8(*l.Opacity * 255.0)
texture.SetModColor(Color{255, 255, 255, alpha})
}
this.layers = append(this.layers, texture)
}
func (this *TiledMap) loadImageLayer(l *tmx.Layer) {
}
func (this *TiledMap) loadObjectGroup(l *tmx.Layer) {
texture := Render.CreateRenderTexture(l.Name+" RenderTexture", int(this.Width*this.TileWidth), int(this.Height*this.TileHeight), 1, false, false, false, false)
var pos mgl32.Vec2
objs := l.Objects
texture.SetAsTarget()
for i := 0; i < len(objs); i++ {
o := objs[i]
if o.GID != nil {
config := this.getSprite2DConfiguration(tmx.TileInstance(*o.GID))
pos[0] = float32(o.X)
pos[1] = float32(o.Y) - float32(this.TileHeight)
this.renderConfiguration(config, pos, texture)
}
}
texture.UnsetAsTarget()
texture.SetFiltering(FILTERING_NEAREST)
this.layers = append(this.layers, texture)
}
func (this *TiledMap) generateTextures() {
for i := 0; i < len(this.TileSets); i++ {
t := this.TileSets[i]
img := t.Image
if img == nil {
continue
}
prevPaths := TEXTURE_PATHS
TEXTURE_PATHS = append(TEXTURE_PATHS, TMX_MAP_PATHS[:]...)
ResourceMgr.LoadTexture(t.Name, img.Source)
TEXTURE_PATHS = prevPaths
if t.TileCount == 0 {
tex := ResourceMgr.GetTexture(t.Name)
rows := (uint32(tex.GetHeight()) - 2*t.Margin + t.Spacing) / (t.Spacing + t.TileHeight)
if t.Columns == 0 {
t.Columns = (uint32(tex.GetWidth()) - 2*t.Margin + t.Spacing) / (t.Spacing + t.TileWidth)
}
t.TileCount = rows * t.Columns
}
}
for i := 0; i < len(this.TileSets); i++ {
img := this.TileSets[i].Image
if img == nil || img.Trans == nil {
continue
}
tex := ResourceMgr.GetTexture(this.TileSets[i].Name)
if tex == nil {
continue
}
keyCol := *img.Trans
if keyCol[0] != '#' {
keyCol = "#" + keyCol
}
col := HEXToColor(keyCol)
tex.SetKeyColor(col)
}
rt := this.Texture.(RenderTexture)
prev := RenderMgr.Projection2D
RenderMgr.SetProjection2DToTexture(rt)
for i := 0; i < len(this.Layers); i++ {
l := this.Layers[i]
if l.Data != nil {
this.loadTileLayer(l)
} else if len(l.Objects) > 0 {
this.loadObjectGroup(l)
} else {
this.loadImageLayer(l)
}
}
rt.SetAsTarget()
for i := 0; i < len(this.layers); i++ {
l := this.layers[i]
var spr Sprite2D
spr.InitTexture(l)
RenderMgr.RenderRenderObjectAdv(&spr, -1, -1)
}
rt.UnsetAsTarget()
RenderMgr.Projection2D = prev
} | src/gohome/tiledmap.go | 0.627723 | 0.403978 | tiledmap.go | starcoder |
package roaring
import (
"bytes"
"io"
"strconv"
)
// RoaringBitmap represents a compressed bitmap where you can add integers.
type RoaringBitmap struct {
highlowcontainer roaringArray
}
// Write out a serialized version of this bitmap to stream
func (b *RoaringBitmap) WriteTo(stream io.Writer) (int, error) {
return b.highlowcontainer.writeTo(stream)
}
// Read a serialized version of this bitmap from stream
func (b *RoaringBitmap) ReadFrom(stream io.Reader) (int, error) {
return b.highlowcontainer.readFrom(stream)
}
// NewRoaringBitmap creates a new empty RoaringBitmap
func NewRoaringBitmap() *RoaringBitmap {
return &RoaringBitmap{*newRoaringArray()}
}
// Clear removes all content from the RoaringBitmap and frees the memory
func (rb *RoaringBitmap) Clear() {
rb.highlowcontainer = *newRoaringArray()
}
// ToArray creates a new slice containing all of the integers stored in the RoaringBitmap in sorted order
func (rb *RoaringBitmap) ToArray() []int {
array := make([]int, rb.GetCardinality())
pos := 0
pos2 := 0
for pos < rb.highlowcontainer.size() {
hs := toIntUnsigned(rb.highlowcontainer.getKeyAtIndex(pos)) << 16
c := rb.highlowcontainer.getContainerAtIndex(pos)
pos++
c.fillLeastSignificant16bits(array, pos2, hs)
pos2 += c.getCardinality()
}
return array
}
// GetSizeInBytes estimates the memory usage of the RoaringBitmap. Note that this
// might differ slightly from the amount of bytes required for persistent storage
func (rb *RoaringBitmap) GetSizeInBytes() int {
size := 8
for i := 0; i < rb.highlowcontainer.size(); i++ {
c := rb.highlowcontainer.getContainerAtIndex(i)
size += 2 + c.getSizeInBytes()
}
return size
}
// GetSerializedSizeInBytes computes the serialized size in bytes the RoaringBitmap. It should correspond to the
// number of bytes written when invoking WriteTo
func (rb *RoaringBitmap) GetSerializedSizeInBytes() int {
return rb.highlowcontainer.serializedSizeInBytes()
}
// IntIterable allows you to iterate over the values in a RoaringBitmap
type IntIterable interface {
HasNext() bool
Next() int
}
type intIterator struct {
pos int
hs int
iter shortIterable
highlowcontainer *roaringArray
}
// HasNext returns true if there are more integers to iterate over
func (ii *intIterator) HasNext() bool {
return ii.pos < ii.highlowcontainer.size()
}
func (ii *intIterator) init() {
if ii.highlowcontainer.size() > ii.pos {
ii.iter = ii.highlowcontainer.getContainerAtIndex(ii.pos).getShortIterator()
ii.hs = toIntUnsigned(ii.highlowcontainer.getKeyAtIndex(ii.pos)) << 16
}
}
// Next returns the next integer
func (ii *intIterator) Next() int {
x := toIntUnsigned(ii.iter.next()) | ii.hs
if !ii.iter.hasNext() {
ii.pos = ii.pos + 1
ii.init()
}
return x
}
func newIntIterator(a *RoaringBitmap) *intIterator {
p := new(intIterator)
p.pos = 0
p.highlowcontainer = &a.highlowcontainer
p.init()
return p
}
// String creates a string representation of the RoaringBitmap
func (rb *RoaringBitmap) String() string {
// inspired by https://github.com/fzandona/goroar/blob/master/roaringbitmap.go
var buffer bytes.Buffer
start := []byte("{")
buffer.Write(start)
i := rb.Iterator()
for i.HasNext() {
buffer.WriteString(strconv.Itoa(int(i.Next())))
if i.HasNext() { // todo: optimize
buffer.WriteString(",")
}
}
buffer.WriteString("}")
return buffer.String()
}
// Iterator creates a new IntIterable to iterate over the integers contained in the bitmap, in sorted order
func (rb *RoaringBitmap) Iterator() IntIterable {
return newIntIterator(rb)
}
// Clone creates a copy of the RoaringBitmap
func (rb *RoaringBitmap) Clone() *RoaringBitmap {
ptr := new(RoaringBitmap)
ptr.highlowcontainer = *rb.highlowcontainer.clone()
return ptr
}
// Contains returns true if the integer is contained in the bitmap
func (rb *RoaringBitmap) Contains(x int) bool {
hb := highbits(x)
c := rb.highlowcontainer.getContainer(hb)
return c != nil && c.contains(lowbits(x))
}
// Equals returns true if the two bitmaps contain the same integers
func (rb *RoaringBitmap) Equals(o interface{}) bool {
srb, ok := o.(*RoaringBitmap)
if ok {
return srb.highlowcontainer.equals(rb.highlowcontainer)
}
return false
}
// Add the integer x to the bitmap
func (rb *RoaringBitmap) Add(x int) {
hb := highbits(x)
i := rb.highlowcontainer.getIndex(hb)
if i >= 0 {
rb.highlowcontainer.setContainerAtIndex(i, rb.highlowcontainer.getContainerAtIndex(i).add(lowbits(x)))
} else {
newac := newArrayContainer()
rb.highlowcontainer.insertNewKeyValueAt(-i-1, hb, newac.add(lowbits(x)))
}
}
// Remove the integer x from the bitmap
func (rb *RoaringBitmap) Remove(x int) {
hb := highbits(x)
i := rb.highlowcontainer.getIndex(hb)
if i >= 0 {
rb.highlowcontainer.setContainerAtIndex(i, rb.highlowcontainer.getContainerAtIndex(i).remove(lowbits(x)))
if rb.highlowcontainer.getContainerAtIndex(i).getCardinality() == 0 {
rb.highlowcontainer.removeAtIndex(i)
}
}
}
// IsEmpty returns true if the RoaringBitmap is empty (it is faster than doing (GetCardinality() == 0))
func (rb *RoaringBitmap) IsEmpty() bool {
return rb.highlowcontainer.size() == 0
}
// GetCardinality returns the number of integers contained in the bitmap
func (rb *RoaringBitmap) GetCardinality() int {
size := 0
for i := 0; i < rb.highlowcontainer.size(); i++ {
size += rb.highlowcontainer.getContainerAtIndex(i).getCardinality()
}
return size
}
// Rank returns the number of integers that are smaller or equal to x (Rank(infinity) would be GetCardinality())
func (rb *RoaringBitmap) Rank(x int) int {
size := 0
for i := 0; i < rb.highlowcontainer.size(); i++ {
key := rb.highlowcontainer.getKeyAtIndex(i)
if key > highbits(x) {
return size
}
if key < highbits(x) {
size += rb.highlowcontainer.getContainerAtIndex(i).getCardinality()
} else {
return size + rb.highlowcontainer.getContainerAtIndex(i).rank(lowbits(x))
}
}
return size
}
// And computes the intersection between two bitmaps and store the result in the current bitmap
func (rb *RoaringBitmap) And(x2 *RoaringBitmap) *RoaringBitmap {
results := And(rb, x2) // Todo: could be computed in-place for reduced memory usage
rb.highlowcontainer = results.highlowcontainer
return rb
}
// Xor computes the symmetric difference between two bitmaps and store the result in the current bitmap
func (rb *RoaringBitmap) Xor(x2 *RoaringBitmap) *RoaringBitmap {
results := Xor(rb, x2) // Todo: could be computed in-place for reduced memory usage
rb.highlowcontainer = results.highlowcontainer
return rb
}
// Or computes the union between two bitmaps and store the result in the current bitmap
func (rb *RoaringBitmap) Or(x2 *RoaringBitmap) *RoaringBitmap {
results := Or(rb, x2) // Todo: could be computed in-place for reduced memory usage
rb.highlowcontainer = results.highlowcontainer
return rb
}
// AndNot computes the difference between two bitmaps and store the result in the current bitmap
func (rb *RoaringBitmap) AndNot(x2 *RoaringBitmap) *RoaringBitmap {
results := AndNot(rb, x2) // Todo: could be computed in-place for reduced memory usage
rb.highlowcontainer = results.highlowcontainer
return rb
}
// Or computes the union between two bitmaps and returns the result
func Or(x1, x2 *RoaringBitmap) *RoaringBitmap {
answer := NewRoaringBitmap()
pos1 := 0
pos2 := 0
length1 := x1.highlowcontainer.size()
length2 := x2.highlowcontainer.size()
main:
for {
if (pos1 < length1) && (pos2 < length2) {
s1 := x1.highlowcontainer.getKeyAtIndex(pos1)
s2 := x2.highlowcontainer.getKeyAtIndex(pos2)
for {
if s1 < s2 {
answer.highlowcontainer.appendCopy(x1.highlowcontainer, pos1)
pos1++
if pos1 == length1 {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
} else if s1 > s2 {
answer.highlowcontainer.appendCopy(x2.highlowcontainer, pos2)
pos2++
if pos2 == length2 {
break main
}
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
} else {
answer.highlowcontainer.append(s1, x1.highlowcontainer.getContainerAtIndex(pos1).or(x2.highlowcontainer.getContainerAtIndex(pos2)))
pos1++
pos2++
if (pos1 == length1) || (pos2 == length2) {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
}
}
} else {
break
}
}
if pos1 == length1 {
answer.highlowcontainer.appendCopyMany(x2.highlowcontainer, pos2, length2)
} else if pos2 == length2 {
answer.highlowcontainer.appendCopyMany(x1.highlowcontainer, pos1, length1)
}
return answer
}
// And computes the intersection between two bitmaps and returns the result
func And(x1, x2 *RoaringBitmap) *RoaringBitmap {
answer := NewRoaringBitmap()
pos1 := 0
pos2 := 0
length1 := x1.highlowcontainer.size()
length2 := x2.highlowcontainer.size()
main:
for {
if pos1 < length1 && pos2 < length2 {
s1 := x1.highlowcontainer.getKeyAtIndex(pos1)
s2 := x2.highlowcontainer.getKeyAtIndex(pos2)
for {
if s1 < s2 {
pos1++
if pos1 == length1 {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
} else if s1 > s2 {
pos2++
if pos2 == length2 {
break main
}
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
} else {
C := x1.highlowcontainer.getContainerAtIndex(pos1)
C = C.and(x2.highlowcontainer.getContainerAtIndex(pos2))
if C.getCardinality() > 0 {
answer.highlowcontainer.append(s1, C)
}
pos1++
pos2++
if (pos1 == length1) || (pos2 == length2) {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
}
}
} else {
break
}
}
return answer
}
// Xor computes the symmetric difference between two bitmaps and returns the result
func Xor(x1, x2 *RoaringBitmap) *RoaringBitmap {
answer := NewRoaringBitmap()
pos1 := 0
pos2 := 0
length1 := x1.highlowcontainer.size()
length2 := x2.highlowcontainer.size()
main:
for {
if (pos1 < length1) && (pos2 < length2) {
s1 := x1.highlowcontainer.getKeyAtIndex(pos1)
s2 := x2.highlowcontainer.getKeyAtIndex(pos2)
if s1 < s2 {
answer.highlowcontainer.appendCopy(x1.highlowcontainer, pos1)
pos1++
if pos1 == length1 {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
} else if s1 > s2 {
answer.highlowcontainer.appendCopy(x2.highlowcontainer, pos2)
pos2++
if pos2 == length2 {
break main
}
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
} else {
c := x1.highlowcontainer.getContainerAtIndex(pos1).xor(x2.highlowcontainer.getContainerAtIndex(pos2))
if c.getCardinality() > 0 {
answer.highlowcontainer.append(s1, c)
}
pos1++
pos2++
if (pos1 == length1) || (pos2 == length2) {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
}
} else {
break
}
}
if pos1 == length1 {
answer.highlowcontainer.appendCopyMany(x2.highlowcontainer, pos2, length2)
} else if pos2 == length2 {
answer.highlowcontainer.appendCopyMany(x1.highlowcontainer, pos1, length1)
}
return answer
}
// AndNot computes the difference between two bitmaps and returns the result
func AndNot(x1, x2 *RoaringBitmap) *RoaringBitmap {
answer := NewRoaringBitmap()
pos1 := 0
pos2 := 0
length1 := x1.highlowcontainer.size()
length2 := x2.highlowcontainer.size()
main:
for {
if pos1 < length1 && pos2 < length2 {
s1 := x1.highlowcontainer.getKeyAtIndex(pos1)
s2 := x2.highlowcontainer.getKeyAtIndex(pos2)
for {
if s1 < s2 {
answer.highlowcontainer.appendCopy(x1.highlowcontainer, pos1)
pos1++
if pos1 == length1 {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
} else if s1 > s2 {
pos2++
if pos2 == length2 {
break main
}
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
} else {
C := x1.highlowcontainer.getContainerAtIndex(pos1)
C.andNot(x2.highlowcontainer.getContainerAtIndex(pos2))
if C.getCardinality() > 0 {
answer.highlowcontainer.append(s1, C)
}
pos1++
pos2++
if (pos1 == length1) || (pos2 == length2) {
break main
}
s1 = x1.highlowcontainer.getKeyAtIndex(pos1)
s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
}
}
} else {
break
}
}
if pos2 == length2 {
answer.highlowcontainer.appendCopyMany(x1.highlowcontainer, pos1, length1)
}
return answer
}
// BitmapOf generates a new bitmap filled with the specified integer
func BitmapOf(dat ...int) *RoaringBitmap {
ans := NewRoaringBitmap()
for _, i := range dat {
ans.Add(i)
}
return ans
}
// Flip negates the bits in the given range, any integer present in this range and in the bitmap is removed,
// and any integer present in the range and not in the bitmap is added
func (rb *RoaringBitmap) Flip(rangeStart, rangeEnd int) *RoaringBitmap {
results := Flip(rb, rangeStart, rangeEnd) //Todo: the computation could be done in-place to reduce memory usage
rb.highlowcontainer = results.highlowcontainer
return rb
}
// Flip negates the bits in the given range, any integer present in this range and in the bitmap is removed,
// and any integer present in the range and not in the bitmap is added, a new bitmap is returned leaving
// the current bitmap unchanged
func Flip(bm *RoaringBitmap, rangeStart, rangeEnd int) *RoaringBitmap {
if rangeStart >= rangeEnd {
return bm.Clone()
}
answer := NewRoaringBitmap()
hbStart := highbits(rangeStart)
lbStart := lowbits(rangeStart)
hbLast := highbits(rangeEnd - 1)
lbLast := lowbits(rangeEnd - 1)
// copy the containers before the active area
answer.highlowcontainer.appendCopiesUntil(bm.highlowcontainer, hbStart)
max := toIntUnsigned(maxLowBit())
for hb := hbStart; hb <= hbLast; hb++ {
containerStart := 0
if hb == hbStart {
containerStart = toIntUnsigned(lbStart)
}
containerLast := max
if hb == hbLast {
containerLast = toIntUnsigned(lbLast)
}
i := bm.highlowcontainer.getIndex(hb)
j := answer.highlowcontainer.getIndex(hb)
if i >= 0 {
c := bm.highlowcontainer.getContainerAtIndex(i).not(containerStart, containerLast)
if c.getCardinality() > 0 {
answer.highlowcontainer.insertNewKeyValueAt(-j-1, hb, c)
}
} else { // *think* the range of ones must never be
// empty.
answer.highlowcontainer.insertNewKeyValueAt(-j-1, hb,
rangeOfOnes(containerStart, containerLast))
}
}
// copy the containers after the active area.
answer.highlowcontainer.appendCopiesAfter(bm.highlowcontainer, hbLast)
return answer
} | roaring.go | 0.806281 | 0.406332 | roaring.go | starcoder |
package ofbx
import "github.com/oakmound/oak/v2/alg/floatgeom"
func resolveEnumProperty(object Obj, name string, defaultVal int) int {
element := resolveProperty(object, name)
if element == nil {
return defaultVal
}
x := element.getProperty(4)
if x == nil {
return defaultVal
}
return int(x.value.toInt32())
}
func resolveVec3Property(object Obj, name string, defaultVal floatgeom.Point3) floatgeom.Point3 {
element := resolveProperty(object, name)
if element == nil {
return defaultVal
}
if len(element.Properties) < 6 {
return defaultVal
}
return floatgeom.Point3{
element.getProperty(4).value.toDouble(),
element.getProperty(5).value.toDouble(),
element.getProperty(6).value.toDouble(),
}
}
func splatVec2(mapping VertexDataMapping, data []floatgeom.Point2, indices []int, origIndices []int) (out []floatgeom.Point2) {
if mapping == ByPolygonVertex {
if len(indices) == 0 {
out = make([]floatgeom.Point2, len(data))
copy(out, data)
} else {
out = make([]floatgeom.Point2, len(indices))
for i := 0; i < len(indices); i++ {
if indices[i] < len(data) {
out[i] = data[indices[i]]
} else {
out[i] = floatgeom.Point2{}
}
}
}
} else if mapping == ByVertex {
// v0 v1 ...
// uv0 uv1 ...
out := make([]floatgeom.Point2, len(origIndices))
for i := 0; i < len(origIndices); i++ {
idx := origIndices[i]
if idx < 0 {
idx = -idx - 1
}
if idx < len(data) {
out[i] = data[idx]
} else {
out[i] = floatgeom.Point2{}
}
}
} else {
panic("oh no")
}
return out
}
func splatVec3(mapping VertexDataMapping, data []floatgeom.Point3, indices []int, origIndices []int) (out []floatgeom.Point3) {
if mapping == ByPolygonVertex {
if len(indices) == 0 {
out = make([]floatgeom.Point3, len(data))
copy(out, data)
} else {
out = make([]floatgeom.Point3, len(indices))
for i := 0; i < len(indices); i++ {
if indices[i] < len(data) {
out[i] = data[indices[i]]
} else {
out[i] = floatgeom.Point3{}
}
}
}
} else if mapping == ByVertex {
// v0 v1 ...
// uv0 uv1 ...
out := make([]floatgeom.Point3, len(origIndices))
for i := 0; i < len(origIndices); i++ {
idx := origIndices[i]
if idx < 0 {
idx = -idx - 1
}
if idx < len(data) {
out[i] = data[idx]
} else {
out[i] = floatgeom.Point3{}
}
}
} else {
panic("oh no")
}
return out
}
func splatVec4(mapping VertexDataMapping, data []floatgeom.Point4, indices []int, origIndices []int) (out []floatgeom.Point4) {
if mapping == ByPolygonVertex {
if len(indices) == 0 {
out = make([]floatgeom.Point4, len(data))
copy(out, data)
} else {
out = make([]floatgeom.Point4, len(indices))
for i := 0; i < len(indices); i++ {
if indices[i] < len(data) {
out[i] = data[indices[i]]
} else {
out[i] = floatgeom.Point4{}
}
}
}
} else if mapping == ByVertex {
// v0 v1 ...
// uv0 uv1 ...
out := make([]floatgeom.Point4, len(origIndices))
for i := 0; i < len(origIndices); i++ {
idx := origIndices[i]
if idx < 0 {
idx = -idx - 1
}
if idx < len(data) {
out[i] = data[idx]
} else {
out[i] = floatgeom.Point4{}
}
}
} else {
panic("oh no")
}
return out
}
func remapVec2(out *[]floatgeom.Point2, m []int) {
if len(*out) == 0 {
return
}
old := make([]floatgeom.Point2, len(*out))
copy(old, *out)
for i := 0; i < len(m); i++ {
if m[i] < len(old) {
*out = append(*out, old[m[i]])
} else {
*out = append(*out, floatgeom.Point2{})
}
}
}
func remapVec3(out *[]floatgeom.Point3, m []int) {
if len(*out) == 0 {
return
}
old := make([]floatgeom.Point3, len(*out))
copy(old, *out)
for i := 0; i < len(m); i++ {
if m[i] < len(old) {
*out = append(*out, old[m[i]])
} else {
*out = append(*out, floatgeom.Point3{})
}
}
}
func remapVec4(out *[]floatgeom.Point4, m []int) {
if len(*out) == 0 {
return
}
old := make([]floatgeom.Point4, len(*out))
copy(old, *out)
for i := 0; i < len(m); i++ {
if m[i] < len(old) {
*out = append(*out, old[m[i]])
} else {
*out = append(*out, floatgeom.Point4{})
}
}
} | misc.go | 0.527803 | 0.493164 | misc.go | starcoder |
package ent
import (
"fmt"
"strings"
"entgo.io/ent/dialect/sql"
"github.com/vorteil/direktiv/pkg/secrets/ent/namespacesecret"
)
// NamespaceSecret is the model entity for the NamespaceSecret schema.
type NamespaceSecret struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Ns holds the value of the "ns" field.
Ns string `json:"ns,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Secret holds the value of the "secret" field.
Secret []byte `json:"secret,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*NamespaceSecret) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case namespacesecret.FieldSecret:
values[i] = new([]byte)
case namespacesecret.FieldID:
values[i] = new(sql.NullInt64)
case namespacesecret.FieldNs, namespacesecret.FieldName:
values[i] = new(sql.NullString)
default:
return nil, fmt.Errorf("unexpected column %q for type NamespaceSecret", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the NamespaceSecret fields.
func (ns *NamespaceSecret) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case namespacesecret.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
ns.ID = int(value.Int64)
case namespacesecret.FieldNs:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field ns", values[i])
} else if value.Valid {
ns.Ns = value.String
}
case namespacesecret.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
ns.Name = value.String
}
case namespacesecret.FieldSecret:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field secret", values[i])
} else if value != nil {
ns.Secret = *value
}
}
}
return nil
}
// Update returns a builder for updating this NamespaceSecret.
// Note that you need to call NamespaceSecret.Unwrap() before calling this method if this NamespaceSecret
// was returned from a transaction, and the transaction was committed or rolled back.
func (ns *NamespaceSecret) Update() *NamespaceSecretUpdateOne {
return (&NamespaceSecretClient{config: ns.config}).UpdateOne(ns)
}
// Unwrap unwraps the NamespaceSecret entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (ns *NamespaceSecret) Unwrap() *NamespaceSecret {
tx, ok := ns.config.driver.(*txDriver)
if !ok {
panic("ent: NamespaceSecret is not a transactional entity")
}
ns.config.driver = tx.drv
return ns
}
// String implements the fmt.Stringer.
func (ns *NamespaceSecret) String() string {
var builder strings.Builder
builder.WriteString("NamespaceSecret(")
builder.WriteString(fmt.Sprintf("id=%v", ns.ID))
builder.WriteString(", ns=")
builder.WriteString(ns.Ns)
builder.WriteString(", name=")
builder.WriteString(ns.Name)
builder.WriteString(", secret=")
builder.WriteString(fmt.Sprintf("%v", ns.Secret))
builder.WriteByte(')')
return builder.String()
}
// NamespaceSecrets is a parsable slice of NamespaceSecret.
type NamespaceSecrets []*NamespaceSecret
func (ns NamespaceSecrets) config(cfg config) {
for _i := range ns {
ns[_i].config = cfg
}
} | pkg/secrets/ent/namespacesecret.go | 0.661267 | 0.403684 | namespacesecret.go | starcoder |
package stalecucumber
/**
Opcode: BINBYTES8 (0x8e)
Push a Python bytes object.
There are two arguments: the first is an 8-byte unsigned int giving
the number of bytes in the string, and the second is that many bytes,
which are taken literally as the string content.
**
Stack before: []
Stack after: [bytes]
**/
func (pm *PickleMachine) opcode_BINBYTES8 () error {
return ErrOpcodeNotImplemented
}
/**
Opcode: SHORT_BINUNICODE (0x8c)
Push a Python Unicode string object.
There are two arguments: the first is a 1-byte little-endian signed int
giving the number of bytes in the string. The second is that many
bytes, and is the UTF-8 encoding of the Unicode string.
**
Stack before: []
Stack after: [str]
**/
func (pm *PickleMachine) opcode_SHORT_BINUNICODE () error {
var l int8
err := pm.readBinaryInto(&l, false)
if err != nil {
return err
}
str, err := pm.readFixedLengthString(int64(l))
if err != nil {
return err
}
pm.push(str)
return nil
}
/**
Opcode: BINUNICODE8 (0x8d)
Push a Python Unicode string object.
There are two arguments: the first is an 8-byte little-endian signed int
giving the number of bytes in the string. The second is that many
bytes, and is the UTF-8 encoding of the Unicode string.
**
Stack before: []
Stack after: [str]
**/
func (pm *PickleMachine) opcode_BINUNICODE8 () error {
var l int64
err := pm.readBinaryInto(&l, false)
if err != nil {
return err
}
str, err := pm.readFixedLengthString(l)
if err != nil {
return err
}
pm.push(str)
return nil
}
/**
Opcode: EMPTY_SET (0x8f)
Push an empty set.**
Stack before: []
Stack after: [set]
**/
func (pm *PickleMachine) opcode_EMPTY_SET () error {
return pm.opcode_EMPTY_LIST()
}
/**
Opcode: ADDITEMS (0x90)
Add an arbitrary number of items to an existing set.
The slice of the stack following the topmost markobject is taken as
a sequence of items, added to the set immediately under the topmost
markobject. Everything at and after the topmost markobject is popped,
leaving the mutated set at the top of the stack.
Stack before: ... pyset markobject item_1 ... item_n
Stack after: ... pyset
where pyset has been modified via pyset.add(item_i) = item_i for i in
1, 2, ..., n, and in that order.
**
Stack before: [set, mark, stackslice]
Stack after: [set]
**/
func (pm *PickleMachine) opcode_ADDITEMS () error {
return pm.opcode_APPENDS()
}
/**
Opcode: FROZENSET (0x91)
Build a frozenset out of the topmost slice, after markobject.
All the stack entries following the topmost markobject are placed into
a single Python frozenset, which single frozenset object replaces all
of the stack from the topmost markobject onward. For example,
Stack before: ... markobject 1 2 3
Stack after: ... frozenset({1, 2, 3})
**
Stack before: [mark, stackslice]
Stack after: [frozenset]
**/
func (pm *PickleMachine) opcode_FROZENSET () error {
markIndex, err := pm.findMark()
if err != nil {
return err
}
v := pm.Stack[markIndex+1:]
pm.popAfterIndex(markIndex)
pm.push(v)
return nil
}
/**
Opcode: MEMOIZE (0x94)
Store the stack top into the memo. The stack is not popped.
The index of the memo location to write is the number of
elements currently present in the memo.
**
Stack before: [any]
Stack after: [any]
**/
func (pm *PickleMachine) opcode_MEMOIZE () error {
v, err := pm.readFromStack(0)
if err != nil {
return err
}
pm.storeMemo(pm.memoIndex, v)
return nil
}
/**
Opcode: STACK_GLOBAL (0x93)
Push a global object (module.attr) on the stack.
**
Stack before: [str, str]
Stack after: [any]
**/
func (pm *PickleMachine) opcode_STACK_GLOBAL () error {
v1, err := pm.pop()
if err != nil {
return err
}
v2, err := pm.pop()
if err != nil {
return err
}
// Push a sentinel object representing the type
pm.push(globalSentinel{Package: v2.(string), Name: v1.(string)})
return nil
}
/**
Opcode: NEWOBJ_EX (0x92)
Build an object instance.
The stack before should be thought of as containing a class
object followed by an argument tuple and by a keyword argument dict
(the dict being the stack top). Call these cls and args. They are
popped off the stack, and the value returned by
cls.__new__(cls, *args, *kwargs) is pushed back onto the stack.
**
Stack before: [any, any, any]
Stack after: [any]
**/
func (pm *PickleMachine) opcode_NEWOBJ_EX () error {
return ErrOpcodeNotImplemented
}
/**
Opcode: FRAME (0x95)
Indicate the beginning of a new frame.
The unpickler may use this opcode to safely prefetch data from its
underlying stream.
**
Stack before: []
Stack after: []
**/
func (pm *PickleMachine) opcode_FRAME () error {
// Frame size is read and discarded so that reader advances
var l uint64
err := pm.readBinaryInto(&l, false)
if err != nil {
return err
}
return nil
} | protocol_4.go | 0.709925 | 0.436322 | protocol_4.go | starcoder |
package dynago
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"time"
)
/*
BinarySet stores a set of binary blobs in dynamo.
While implemented as a list in Go, DynamoDB does not preserve ordering on set
types and so may come back in a different order on retrieval. Use dynago.List
if ordering is important.
*/
type BinarySet [][]byte
/*
List represents DynamoDB lists, which are functionally very similar to JSON
lists. Like JSON lists, these lists are heterogeneous, which means that the
elements of the list can be any valid value type, which includes other lists,
documents, numbers, strings, etc.
*/
type List []interface{}
/*
Return a copy of this list with all elements coerced as Documents.
It's very common to use lists in dynago where all elements in the list are
a Document. For that reason, this method is provided as a convenience to
get back your list as a list of documents.
If any element in the List is not a document, this will error.
As a convenience, even when it errors, a slice containing any elements
preceding the one which errored as documents will be given.
*/
func (l List) AsDocumentList() ([]Document, error) {
docs := make([]Document, len(l))
for i, listItem := range l {
if doc, ok := listItem.(Document); !ok {
return docs[:i], fmt.Errorf("item at index %d was not a Document", i)
} else {
docs[i] = doc
}
}
return docs, nil
}
/*
A Number.
DynamoDB returns numbers as a string representation because they have a single
high-precision number type that can take the place of integers, floats, and
decimals for the majority of types.
This method has helpers to get the value of this number as one of various
Golang numeric types.
*/
type Number string
// IntVal interprets this number as an integer in base-10.
// error is returned if this is not a valid number or is too large.
func (n Number) IntVal() (int, error) {
return strconv.Atoi(string(n))
}
// Int64Val interprets this number as an integer in base-10.
// error is returned if this string cannot be parsed as base 10 or is too large.
func (n Number) Int64Val() (int64, error) {
return strconv.ParseInt(string(n), 10, 64)
}
// Uint64Val interprets this number as an unsigned integer.
// error is returned if this is not a valid positive integer or cannot fit.
func (n Number) Uint64Val() (uint64, error) {
return strconv.ParseUint(string(n), 10, 64)
}
// FloatVal interprets this number as a floating point.
// error is returned if this number is not well-formed.
func (n Number) FloatVal() (float64, error) {
return strconv.ParseFloat(string(n), 64)
}
/*
NumberSet is an un-ordered set of numbers.
Sets in DynamoDB do not guarantee any ordering, so storing and retrieving a
NumberSet may not give you back the same order you put it in. The main
advantage of using sets in DynamoDB is using atomic updates with ADD and DELETE
in your UpdateExpression.
*/
type NumberSet []string
/*
Document is the core type for many dynamo operations on documents.
It is used to represent the root-level document, maps values, and
can also be used to supply expression parameters to queries.
*/
type Document map[string]interface{}
// MarshalJSON is used for encoding Document into wire representation.
func (d Document) MarshalJSON() ([]byte, error) {
output := make(map[string]interface{}, len(d))
for key, val := range d {
if v := reflect.ValueOf(val); !isEmptyValue(v) {
output[key] = wireEncode(val)
}
}
return json.Marshal(output)
}
// UnmarshalJSON is used for unmarshaling Document from the wire representation.
func (d *Document) UnmarshalJSON(buf []byte) error {
raw := make(map[string]interface{})
err := json.Unmarshal(buf, &raw)
if err != nil {
return err
}
if *d == nil {
*d = make(Document)
}
dd := *d
for key, val := range raw {
dd[key] = wireDecode(val)
}
return nil
}
/*
GetList gets the value at key as a List.
If value at key is nil, returns a nil list.
If value at key is not a List, will panic.
*/
func (d Document) GetList(key string) List {
if d[key] != nil {
return d[key].(List)
} else {
return nil
}
}
/*
GetString gets the value at key as a String.
If the value at key is nil, returns an empty string.
If the value at key is not nil or a string, will panic.
*/
func (d Document) GetString(key string) string {
if d[key] != nil {
return d[key].(string)
} else {
return ""
}
}
/*
GetNumber gets the value at key as a Number.
If the value at key is nil, returns a number containing the empty string.
If the value is not a Number or nil, will panic.
*/
func (d Document) GetNumber(key string) Number {
if d[key] != nil {
return d[key].(Number)
} else {
return Number("")
}
}
/*
GetStringSet gets the value specified by key a StringSet.
If value at key is nil; returns an empty StringSet.
If it exists but is not a StringSet, panics.
*/
func (d Document) GetStringSet(key string) StringSet {
if d[key] != nil {
return d[key].(StringSet)
} else {
return StringSet{}
}
}
/*
Helper to get a Time from a document.
If the value is omitted from the DB, or an empty string, then the return
is nil. If the value fails to parse as iso8601, then this method panics.
*/
func (d Document) GetTime(key string) (t *time.Time) {
val := d[key]
if val != nil {
s := val.(string)
parsed, err := time.ParseInLocation(iso8601compact, s, time.UTC)
if err != nil {
panic(err)
}
t = &parsed
}
return t
}
// AsParams makes Document satisfy the Params interface.
func (d Document) AsParams() (params []Param) {
for key, val := range d {
params = append(params, Param{key, val})
}
return
}
/*
GetBool gets the value specified by key as a boolean.
If the value does not exist in this Document, returns false.
If the value is the nil interface, also returns false.
If the value is a bool, returns the value of the bool.
If the value is a Number, returns true if value is non-zero.
For any other values, panics.
*/
func (d Document) GetBool(key string) bool {
if v := d[key]; v != nil {
switch val := v.(type) {
case bool:
return val
case Number:
if res, err := val.IntVal(); err != nil {
panic(err)
} else if res == 0 {
return false
} else {
return true
}
default:
panic(v)
}
} else {
return false
}
}
// HashKey is a shortcut to building keys used for various item operations.
func HashKey(name string, value interface{}) Document {
return Document{name: value}
}
// HashRangeKey is a shortcut for building keys used for various item operations.
func HashRangeKey(hashName string, hashVal interface{}, rangeName string, rangeVal interface{}) Document {
return Document{
hashName: hashVal,
rangeName: rangeVal,
}
}
// Param can be used as a single parameter.
type Param struct {
Key string
Value interface{}
}
// AsParsms allows a solo Param to also satisfy the Params interface
func (p Param) AsParams() []Param {
return []Param{p}
}
// P is a shortcut to create a single dynago Param.
// This is mainly for brevity especially with cross-package imports.
func P(key string, value interface{}) Params {
return Param{key, value}
}
/*
Params encapsulates anything which can be used as expression parameters for
dynamodb expressions.
DynamoDB item queries using expressions can be provided parameters in a number
of handy ways:
.Param(":k1", v1).Param(":k2", v2)
-or-
.Params(P(":k1", v1), P(":k2", v2))
-or-
.FilterExpression("...", P(":k1", v1), P(":k2", v2))
-or-
.FilterExpression("...", Document{":k1": v1, ":k2": v2})
Or any combination of Param, Document, or potentially other custom types which
provide the Params interface.
*/
type Params interface {
AsParams() []Param
}
/*
StringSet is an un-ordered collection of distinct strings.
Sets in DynamoDB do not guarantee any ordering, so storing and retrieving a
StringSet may not give you back the same order you put it in. The main
advantage of using sets in DynamoDB is using atomic updates with ADD and DELETE
in your UpdateExpression.
*/
type StringSet []string
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
case reflect.Invalid:
return true
}
return false
} | types.go | 0.700075 | 0.432423 | types.go | starcoder |
package binding
import (
"fmt"
"reflect"
"github.com/phlashdev/sherlock/codeanalysis/syntax"
)
var (
binaryOperators []boundBinaryOperator = []boundBinaryOperator{
*newBoundBinaryOperator(syntax.PlusToken, Addition, reflect.TypeOf(0)),
*newBoundBinaryOperator(syntax.MinusToken, Subtraction, reflect.TypeOf(0)),
*newBoundBinaryOperator(syntax.StarToken, Multiplication, reflect.TypeOf(0)),
*newBoundBinaryOperator(syntax.SlashToken, Division, reflect.TypeOf(0)),
*newBoundBinaryOperatorWithSameOperandType(syntax.EqualsEqualsToken, Equals, reflect.TypeOf(0), reflect.TypeOf(false)),
*newBoundBinaryOperatorWithSameOperandType(syntax.BangEqualsToken, NotEquals, reflect.TypeOf(0), reflect.TypeOf(false)),
*newBoundBinaryOperatorWithDifferentTypes(syntax.AmpersandAmpersandToken, LogicalAnd, reflect.TypeOf(false), reflect.TypeOf(false), reflect.TypeOf(false)),
*newBoundBinaryOperatorWithDifferentTypes(syntax.PipePipeToken, LogicalOr, reflect.TypeOf(false), reflect.TypeOf(false), reflect.TypeOf(false)),
*newBoundBinaryOperator(syntax.EqualsEqualsToken, Equals, reflect.TypeOf(false)),
*newBoundBinaryOperator(syntax.BangEqualsToken, NotEquals, reflect.TypeOf(false)),
}
)
type boundBinaryOperator struct {
syntaxKind syntax.SyntaxKind
kind boundBinaryOperatorKind
leftType reflect.Type
rightType reflect.Type
resultType reflect.Type
}
func newBoundBinaryOperator(syntaxKind syntax.SyntaxKind, kind boundBinaryOperatorKind, operatorType reflect.Type) *boundBinaryOperator {
return newBoundBinaryOperatorWithDifferentTypes(syntaxKind, kind, operatorType, operatorType, operatorType)
}
func newBoundBinaryOperatorWithSameOperandType(syntaxKind syntax.SyntaxKind, kind boundBinaryOperatorKind, operandType reflect.Type, resultType reflect.Type) *boundBinaryOperator {
return newBoundBinaryOperatorWithDifferentTypes(syntaxKind, kind, operandType, operandType, resultType)
}
func newBoundBinaryOperatorWithDifferentTypes(syntaxKind syntax.SyntaxKind, kind boundBinaryOperatorKind, leftType reflect.Type, rightType reflect.Type, resultType reflect.Type) *boundBinaryOperator {
return &boundBinaryOperator{
syntaxKind: syntaxKind,
kind: kind,
leftType: leftType,
rightType: rightType,
resultType: resultType,
}
}
func (b *boundBinaryOperator) SyntaxKind() syntax.SyntaxKind {
return b.syntaxKind
}
func (b *boundBinaryOperator) Kind() boundBinaryOperatorKind {
return b.kind
}
func (b *boundBinaryOperator) LeftType() reflect.Type {
return b.leftType
}
func (b *boundBinaryOperator) RightType() reflect.Type {
return b.rightType
}
func (b *boundBinaryOperator) ResultType() reflect.Type {
return b.resultType
}
func bindBinaryOperator(syntaxKind syntax.SyntaxKind, leftType reflect.Type, rightType reflect.Type) (boundBinaryOperator, error) {
for _, op := range binaryOperators {
if op.syntaxKind == syntaxKind && op.leftType == leftType && op.rightType == rightType {
return op, nil
}
}
return boundBinaryOperator{}, fmt.Errorf("operator not found")
} | codeanalysis/binding/boundbinaryoperator.go | 0.650911 | 0.500671 | boundbinaryoperator.go | starcoder |
package minecraft
import (
"fmt"
math2 "github.com/itay2805/mcserver/math"
"log"
"math"
)
type Position struct {
X, Y, Z int
}
func (p Position) String() string {
return fmt.Sprintf("Position{X: %d, Y: %d, Z: %d}", p.X, p.Y, p.Z)
}
func (p Position) ToPoint() math2.Point {
return math2.NewPoint(float64(p.X), float64(p.Y), float64(p.Z))
}
func (p Position) ApplyFace(face Face) Position {
switch face {
case FaceBottom:
return Position{
X: p.X,
Y: p.Y - 1,
Z: p.Z,
}
case FaceTop:
return Position{
X: p.X,
Y: p.Y + 1,
Z: p.Z,
}
case FaceNorth:
return Position{
X: p.X,
Y: p.Y,
Z: p.Z - 1,
}
case FaceSouth:
return Position{
X: p.X,
Y: p.Y,
Z: p.Z + 1,
}
case FaceWest:
return Position{
X: p.X - 1,
Y: p.Y,
Z: p.Z,
}
case FaceEast:
return Position{
X: p.X + 1,
Y: p.Y,
Z: p.Z,
}
}
log.Panicln("Invalid face", face)
return Position{}
}
func ParsePosition(val uint64) Position {
p := Position{
X: int((val >> 38) & 0x3FFFFFF),
Y: int(val & 0xFFF),
Z: int((val >> 12) & 0x3FFFFFF),
}
if p.X > 33554432 {
p.X -= 67108864
}
if p.Z > 33554432 {
p.Z -= 67108864
}
if p.Y > 2048 {
p.Y -= 4096
}
return p
}
func (p Position) Pack() uint64 {
return uint64(((p.X & 0x3FFFFFF) << 38) | ((p.Z & 0x3FFFFFF) << 12) | (p.Y & 0xFFF))
}
type Angle uint8
func ToAngle(v float32) Angle {
return Angle(v * 256.0 / 360.0)
}
func (a Angle) ToRadians() float64 {
return float64(a) * math.Pi / 128.0
}
type Face int
const (
FaceBottom = Face(iota)
FaceTop
FaceNorth
FaceSouth
FaceWest
FaceEast
)
func (f Face) Invert() Face {
switch f {
case FaceBottom: return FaceTop
case FaceTop: return FaceBottom
case FaceNorth: return FaceSouth
case FaceSouth: return FaceNorth
case FaceWest: return FaceEast
case FaceEast: return FaceWest
default:
return FaceEast
}
}
func (f Face) String() string {
switch f {
case FaceBottom: return "FaceBottom"
case FaceTop: return "FaceTop"
case FaceNorth: return "FaceNorth"
case FaceSouth: return "FaceSouth"
case FaceWest: return "FaceWest"
case FaceEast: return "FaceEast"
default:
return fmt.Sprintf("Face(%d)", f)
}
}
type Shape int
const (
ShapeStraight = Shape(iota)
ShapeInnerLeft
ShapeInnerRight
ShapeOuterLeft
ShapeOuterRight
)
func (f Shape) String() string {
switch f {
case ShapeStraight: return "ShapeStraight"
case ShapeInnerLeft: return "ShapeInnerLeft"
case ShapeInnerRight: return "ShapeInnerRight"
case ShapeOuterLeft: return "ShapeOuterLeft"
case ShapeOuterRight: return "ShapeOuterRight"
default:
return fmt.Sprintf("Shape(%d)", f)
}
}
type Hinge int
const (
HingeLeft = Hinge(iota)
HingeRight
)
func (f Hinge) String() string {
switch f {
case HingeLeft: return "HingeLeft"
case HingeRight: return "HingeRight"
default:
return fmt.Sprintf("Hinge(%d)", f)
}
} | minecraft/types.go | 0.74382 | 0.526404 | types.go | starcoder |
package pool
import (
"time"
"github.com/ubclaunchpad/cumulus/blockchain"
"github.com/ubclaunchpad/cumulus/common/util"
"github.com/ubclaunchpad/cumulus/consensus"
"github.com/ubclaunchpad/cumulus/miner"
)
// PooledTransaction is a Transaction with a timestamp.
type PooledTransaction struct {
Transaction *blockchain.Transaction
Time time.Time
}
// Pool is a set of valid Transactions.
type Pool struct {
Order []*PooledTransaction
ValidTransactions map[blockchain.Hash]*PooledTransaction
}
// New initializes a new pool.
func New() *Pool {
return &Pool{
Order: []*PooledTransaction{},
ValidTransactions: map[blockchain.Hash]*PooledTransaction{},
}
}
// Size returns the number of transactions in the Pool.
func (p *Pool) Size() int {
return len(p.ValidTransactions)
}
// Empty returns true if the pool has exactly zero transactions in it.
func (p *Pool) Empty() bool {
return p.Size() == 0
}
// Get returns the tranasction with transaction Hash h. Returns nil if
// there is not transaction in the pool with the given hashsum.
func (p *Pool) Get(h blockchain.Hash) *blockchain.Transaction {
if pooledTxn := p.ValidTransactions[h]; pooledTxn != nil {
return pooledTxn.Transaction
}
return nil
}
// GetN returns the Nth transaction in the pool.
func (p *Pool) GetN(N int) *blockchain.Transaction {
return p.Order[N].Transaction
}
// GetIndex returns the index of the transaction in the ordering.
func (p *Pool) GetIndex(t *blockchain.Transaction) int {
hash := blockchain.HashSum(t)
target := p.ValidTransactions[hash].Time
return getIndex(p.Order, target, 0, p.Size()-1)
}
// getIndex does a binary search for a PooledTransaction by timestamp.
func getIndex(a []*PooledTransaction, target time.Time, low, high int) int {
mid := (low + high) / 2
if a[mid].Time == target {
return mid
} else if target.Before(a[mid].Time) {
return getIndex(a, target, low, mid-1)
} else {
return getIndex(a, target, mid+1, high)
}
}
// Push inserts a transaction into the pool, returning
// true if the Transaction was inserted (was valid).
// TODO: This should return an error if could not add.
func (p *Pool) Push(t *blockchain.Transaction, bc *blockchain.BlockChain) consensus.TransactionCode {
ok, code := consensus.VerifyTransaction(bc, t)
if ok {
p.set(t)
}
return code
}
// PushUnsafe adds a transaction to the pool without validation.
func (p *Pool) PushUnsafe(t *blockchain.Transaction) {
p.set(t)
}
// Silently adds a transaction to the pool.
// Deletes a transaction if it exists from the input hash.
func (p *Pool) set(t *blockchain.Transaction) {
hash := blockchain.HashSum(t)
if txn, ok := p.ValidTransactions[hash]; ok {
p.Delete(txn.Transaction)
}
vt := &PooledTransaction{
Transaction: t,
Time: time.Now(),
}
p.Order = append(p.Order, vt)
p.ValidTransactions[hash] = vt
}
// Delete removes a transaction from the Pool.
func (p *Pool) Delete(t *blockchain.Transaction) {
hash := blockchain.HashSum(t)
vt, ok := p.ValidTransactions[hash]
if ok {
i := p.GetIndex(vt.Transaction)
p.Order = append(p.Order[0:i], p.Order[i+1:]...)
delete(p.ValidTransactions, hash)
}
}
// Update updates the Pool by removing the Transactions found in the
// Block. If the Block is found invalid wrt bc, then false is returned and no
// Transactions are removed from the Pool.
func (p *Pool) Update(b *blockchain.Block, bc *blockchain.BlockChain) bool {
if ok, _ := consensus.VerifyBlock(bc, b); !ok {
return false
}
for _, t := range b.Transactions {
p.Delete(t)
}
return true
}
// Pop returns the next transaction and removes it from the pool.
func (p *Pool) Pop() *blockchain.Transaction {
if p.Size() > 0 {
next := p.GetN(0)
p.Delete(next)
return next
}
return nil
}
// Peek returns the next transaction and does not remove it from the pool.
func (p *Pool) Peek() *blockchain.Transaction {
if p.Size() > 0 {
return p.GetN(0)
}
return nil
}
// NextBlock produces a new block from the pool for mining. The block returned
// may not contain transactions if there are none left in the transaction pool.
func (p *Pool) NextBlock(chain *blockchain.BlockChain,
address blockchain.Address, size uint32) *blockchain.Block {
var txns []*blockchain.Transaction
// Hash the last block in the chain.
lastHash := blockchain.HashSum(chain.LastBlock())
// Build a new block for mining.
b := &blockchain.Block{
BlockHeader: blockchain.BlockHeader{
BlockNumber: uint32(len(chain.Blocks)),
LastBlock: lastHash,
Time: util.UnixNow(),
Nonce: 0,
}, Transactions: txns,
}
// Prepend the cloudbase transaction for this miner.
miner.CloudBase(b, chain, address)
// Try to grab as many transactions as the block will allow.
// Test each transaction to see if we break size before adding.
for p.Size() > 0 {
nextSize := p.Peek().Len()
if b.Len()+nextSize < int(size) {
b.Transactions = append(b.Transactions, p.Pop())
} else {
break
}
}
return b
} | pool/pool.go | 0.758421 | 0.406597 | pool.go | starcoder |
// Copyright 2015, <NAME>, see LICENSE for details.
// Copyright 2019, Minio, Inc.
package reedsolomon
//go:noescape
func _galMulAVX512Parallel82(in, out [][]byte, matrix *[matrixSize82]byte, addTo bool)
//go:noescape
func _galMulAVX512Parallel84(in, out [][]byte, matrix *[matrixSize84]byte, addTo bool)
const (
dimIn = 8 // Number of input rows processed simultaneously
dimOut82 = 2 // Number of output rows processed simultaneously for x2 routine
dimOut84 = 4 // Number of output rows processed simultaneously for x4 routine
matrixSize82 = (16 + 16) * dimIn * dimOut82 // Dimension of slice of matrix coefficient passed into x2 routine
matrixSize84 = (16 + 16) * dimIn * dimOut84 // Dimension of slice of matrix coefficient passed into x4 routine
)
// Construct block of matrix coefficients for 2 outputs rows in parallel
func setupMatrix82(matrixRows [][]byte, inputOffset, outputOffset int, matrix *[matrixSize82]byte) {
offset := 0
for c := inputOffset; c < inputOffset+dimIn; c++ {
for iRow := outputOffset; iRow < outputOffset+dimOut82; iRow++ {
if c < len(matrixRows[iRow]) {
coeff := matrixRows[iRow][c]
copy(matrix[offset*32:], mulTableLow[coeff][:])
copy(matrix[offset*32+16:], mulTableHigh[coeff][:])
} else {
// coefficients not used for this input shard (so null out)
v := matrix[offset*32 : offset*32+32]
for i := range v {
v[i] = 0
}
}
offset += dimIn
if offset >= dimIn*dimOut82 {
offset -= dimIn*dimOut82 - 1
}
}
}
}
// Construct block of matrix coefficients for 4 outputs rows in parallel
func setupMatrix84(matrixRows [][]byte, inputOffset, outputOffset int, matrix *[matrixSize84]byte) {
offset := 0
for c := inputOffset; c < inputOffset+dimIn; c++ {
for iRow := outputOffset; iRow < outputOffset+dimOut84; iRow++ {
if c < len(matrixRows[iRow]) {
coeff := matrixRows[iRow][c]
copy(matrix[offset*32:], mulTableLow[coeff][:])
copy(matrix[offset*32+16:], mulTableHigh[coeff][:])
} else {
// coefficients not used for this input shard (so null out)
v := matrix[offset*32 : offset*32+32]
for i := range v {
v[i] = 0
}
}
offset += dimIn
if offset >= dimIn*dimOut84 {
offset -= dimIn*dimOut84 - 1
}
}
}
}
// Invoke AVX512 routine for 2 output rows in parallel
func galMulAVX512Parallel82(in, out [][]byte, matrixRows [][]byte, inputOffset, outputOffset int) {
done := len(in[0])
if done == 0 {
return
}
inputEnd := inputOffset + dimIn
if inputEnd > len(in) {
inputEnd = len(in)
}
outputEnd := outputOffset + dimOut82
if outputEnd > len(out) {
outputEnd = len(out)
}
matrix82 := [matrixSize82]byte{}
setupMatrix82(matrixRows, inputOffset, outputOffset, &matrix82)
addTo := inputOffset != 0 // Except for the first input column, add to previous results
_galMulAVX512Parallel82(in[inputOffset:inputEnd], out[outputOffset:outputEnd], &matrix82, addTo)
done = (done >> 6) << 6
if len(in[0])-done == 0 {
return
}
for c := inputOffset; c < inputOffset+dimIn; c++ {
for iRow := outputOffset; iRow < outputOffset+dimOut82; iRow++ {
if c < len(matrixRows[iRow]) {
mt := mulTable[matrixRows[iRow][c]][:256]
for i := done; i < len(in[0]); i++ {
if c == 0 { // only set value for first input column
out[iRow][i] = mt[in[c][i]]
} else { // and add for all others
out[iRow][i] ^= mt[in[c][i]]
}
}
}
}
}
}
// Invoke AVX512 routine for 4 output rows in parallel
func galMulAVX512Parallel84(in, out [][]byte, matrixRows [][]byte, inputOffset, outputOffset int) {
done := len(in[0])
if done == 0 {
return
}
inputEnd := inputOffset + dimIn
if inputEnd > len(in) {
inputEnd = len(in)
}
outputEnd := outputOffset + dimOut84
if outputEnd > len(out) {
outputEnd = len(out)
}
matrix84 := [matrixSize84]byte{}
setupMatrix84(matrixRows, inputOffset, outputOffset, &matrix84)
addTo := inputOffset != 0 // Except for the first input column, add to previous results
_galMulAVX512Parallel84(in[inputOffset:inputEnd], out[outputOffset:outputEnd], &matrix84, addTo)
done = (done >> 6) << 6
if len(in[0])-done == 0 {
return
}
for c := inputOffset; c < inputOffset+dimIn; c++ {
for iRow := outputOffset; iRow < outputOffset+dimOut84; iRow++ {
if c < len(matrixRows[iRow]) {
mt := mulTable[matrixRows[iRow][c]][:256]
for i := done; i < len(in[0]); i++ {
if c == 0 { // only set value for first input column
out[iRow][i] = mt[in[c][i]]
} else { // and add for all others
out[iRow][i] ^= mt[in[c][i]]
}
}
}
}
}
}
// Perform the same as codeSomeShards, but taking advantage of
// AVX512 parallelism for up to 4x faster execution as compared to AVX2
func (r reedSolomon) codeSomeShardsAvx512(matrixRows, inputs, outputs [][]byte, outputCount, byteCount int) {
outputRow := 0
// First process (multiple) batches of 4 output rows in parallel
for ; outputRow+dimOut84 <= len(outputs); outputRow += dimOut84 {
for inputRow := 0; inputRow < len(inputs); inputRow += dimIn {
galMulAVX512Parallel84(inputs, outputs, matrixRows, inputRow, outputRow)
}
}
// Then process a (single) batch of 2 output rows in parallel
if outputRow+dimOut82 <= len(outputs) {
// fmt.Println(outputRow, len(outputs))
for inputRow := 0; inputRow < len(inputs); inputRow += dimIn {
galMulAVX512Parallel82(inputs, outputs, matrixRows, inputRow, outputRow)
}
outputRow += dimOut82
}
// Lastly, we may have a single output row left (for uneven parity)
if outputRow < len(outputs) {
for c := 0; c < r.DataShards; c++ {
if c == 0 {
galMulSlice(matrixRows[outputRow][c], inputs[c], outputs[outputRow], &r.o)
} else {
galMulSliceXor(matrixRows[outputRow][c], inputs[c], outputs[outputRow], &r.o)
}
}
}
} | vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go | 0.533154 | 0.462837 | galoisAvx512_amd64.go | starcoder |
package examples
import (
"io"
"math/rand"
"os"
"github.com/go-echarts/go-echarts/v2/charts"
"github.com/go-echarts/go-echarts/v2/components"
"github.com/go-echarts/go-echarts/v2/opts"
)
var (
baseMapData = []opts.MapData{
{Name: "北京", Value: float64(rand.Intn(150))},
{Name: "上海", Value: float64(rand.Intn(150))},
{Name: "广东", Value: float64(rand.Intn(150))},
{Name: "辽宁", Value: float64(rand.Intn(150))},
{Name: "山东", Value: float64(rand.Intn(150))},
{Name: "山西", Value: float64(rand.Intn(150))},
{Name: "陕西", Value: float64(rand.Intn(150))},
{Name: "新疆", Value: float64(rand.Intn(150))},
{Name: "内蒙古", Value: float64(rand.Intn(150))},
}
guangdongMapData = map[string]float64{
"深圳市": float64(rand.Intn(150)),
"广州市": float64(rand.Intn(150)),
"湛江市": float64(rand.Intn(150)),
"汕头市": float64(rand.Intn(150)),
"东莞市": float64(rand.Intn(150)),
"佛山市": float64(rand.Intn(150)),
"云浮市": float64(rand.Intn(150)),
"肇庆市": float64(rand.Intn(150)),
"梅州市": float64(rand.Intn(150)),
}
)
func generateMapData(data map[string]float64) (items []opts.MapData) {
items = make([]opts.MapData, 0)
for k, v := range data {
items = append(items, opts.MapData{Name: k, Value: v})
}
return
}
func mapBase() *charts.Map {
mc := charts.NewMap()
mc.RegisterMapType("china")
mc.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{Title: "basic map example"}),
)
mc.AddSeries("map", baseMapData)
return mc
}
func mapShowLabel() *charts.Map {
mc := charts.NewMap()
mc.RegisterMapType("china")
mc.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{Title: "show label"}),
)
mc.AddSeries("map", baseMapData).
SetSeriesOptions(
charts.WithLabelOpts(opts.Label{
Show: true,
}),
)
return mc
}
func mapVisualMap() *charts.Map {
mc := charts.NewMap()
mc.RegisterMapType("china")
mc.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{
Title: "VisualMap",
}),
charts.WithVisualMapOpts(opts.VisualMap{
Calculable: true,
}),
)
mc.AddSeries("map", baseMapData)
return mc
}
func mapRegion() *charts.Map {
mc := charts.NewMap()
mc.RegisterMapType("广东")
mc.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{
Title: "Guangdong province",
}),
charts.WithVisualMapOpts(opts.VisualMap{
Calculable: true,
InRange: &opts.VisualMapInRange{Color: []string{"#50a3ba", "#eac736", "#d94e5d"}},
}),
)
mc.AddSeries("map", generateMapData(guangdongMapData))
return mc
}
func mapTheme() *charts.Map {
mc := charts.NewMap()
mc.RegisterMapType("china")
mc.SetGlobalOptions(
charts.WithInitializationOpts(opts.Initialization{
Theme: "macarons",
}),
charts.WithTitleOpts(opts.Title{
Title: "Map-theme",
}),
charts.WithVisualMapOpts(opts.VisualMap{
Calculable: true,
Max: 150,
}),
)
mc.AddSeries("map", baseMapData)
return mc
}
type MapExamples struct{}
func (MapExamples) Examples() {
page := components.NewPage()
page.AddCharts(
mapBase(),
mapShowLabel(),
mapVisualMap(),
mapRegion(),
mapTheme(),
)
f, err := os.Create("examples/html/map.html")
if err != nil {
panic(err)
}
page.Render(io.MultiWriter(f))
} | examples/map.go | 0.582491 | 0.456955 | map.go | starcoder |
package query
import (
"fmt"
"github.com/vmware/purser/pkg/controller/dgraph/models"
"github.com/vmware/purser/pkg/controller/utils"
)
var secondsFromFirstOfCurrentMonth = getSecondsSinceMonthStart
func getSecondsSinceMonthStart() string {
return fmt.Sprintf("%f", utils.GetSecondsSince(utils.GetCurrentMonthStartTime()))
}
func getSecondsSinceForOtherMonths() map[string]string {
secondsSince := make(map[string]string)
secondsInAverageMonth := 2592000.0 // 30 * 24 * 60 * 60
secondsSinceCurrentMonthStart := utils.GetSecondsSince(utils.GetCurrentMonthStartTime())
secondsSinceLastMonthStart := secondsSinceCurrentMonthStart + secondsInAverageMonth
secondsSinceLastLastMonthStart := secondsSinceCurrentMonthStart + 2*secondsInAverageMonth
secondsSinceLastMonthEnd := secondsSinceCurrentMonthStart - 1.0
secondsSinceLastLastMonthEnd := secondsSinceLastMonthStart - 1.0
secondsSince["currentMonthStart"] = fmt.Sprintf("%f", secondsSinceCurrentMonthStart)
secondsSince["lastMonthStart"] = fmt.Sprintf("%f", secondsSinceLastMonthStart)
secondsSince["lastMonthEnd"] = fmt.Sprintf("%f", secondsSinceLastMonthEnd)
secondsSince["lastLastMonthStart"] = fmt.Sprintf("%f", secondsSinceLastLastMonthStart)
secondsSince["lastLastMonthEnd"] = fmt.Sprintf("%f", secondsSinceLastLastMonthEnd)
return secondsSince
}
func getQueryForMetricsComputationWithAliasAndVariables(suffix string) string {
return `name
type
cpu: cpu` + suffix + ` as cpuRequest
memory: memory` + suffix + ` as memoryRequest
storage: storage` + suffix + ` as storageRequest
` + getQueryForTimeComputation(suffix) + `
` + getQueryForCostWithPriceWithAliasAndVariables(suffix)
}
func getQueryForMetricsComputationWithAlias(suffix string) string {
return `name
type
cpu: cpu` + suffix + ` as cpuRequest
memory: memory` + suffix + ` as memoryRequest
storage: storage` + suffix + ` as storageRequest
` + getQueryForTimeComputation(suffix) + `
` + getQueryForCostWithPriceWithAlias(suffix)
}
func getQueryForMetricsComputation(suffix string) string {
return `cpu` + suffix + ` as cpuRequest
memory` + suffix + ` as memoryRequest
storage` + suffix + ` as storageRequest
` + getQueryForTimeComputation(suffix) + `
` + getQueryForCostWithPrice(suffix)
}
func getQueryForTimeComputation(suffix string) string {
secondsSinceMonthStart := secondsFromFirstOfCurrentMonth()
return `st` + suffix + ` as startTime
stSeconds` + suffix + ` as math(since(st` + suffix + `))
secondsSinceStart` + suffix + ` as math(cond(stSeconds` + suffix + ` > ` + secondsSinceMonthStart + `, ` + secondsSinceMonthStart + `, stSeconds` + suffix + `))
et` + suffix + ` as endTime
isTerminated` + suffix + ` as count(endTime)
secondsSinceEnd` + suffix + ` as math(cond(isTerminated` + suffix + ` == 0, 0.0, since(et` + suffix + `)))
durationInHours` + suffix + ` as math(cond(secondsSinceStart` + suffix + ` > secondsSinceEnd` + suffix + `, (secondsSinceStart` + suffix + ` - secondsSinceEnd` + suffix + `) / 3600, 0.0))`
}
func getQueryForCostWithPriceWithAliasAndVariables(suffix string) string {
return `pricePerCPU` + suffix + ` as cpuPrice
pricePerMemory` + suffix + ` as memoryPrice
cpuCost: cpuCost` + suffix + ` as math(cpu` + suffix + ` * durationInHours` + suffix + ` * pricePerCPU` + suffix + `)
memoryCost: memoryCost` + suffix + ` as math(memory` + suffix + ` * durationInHours` + suffix + ` * pricePerMemory` + suffix + `)
storageCost: storageCost` + suffix + ` as math(storage` + suffix + ` * durationInHours` + suffix + ` * ` + models.DefaultStorageCostPerGBPerHour + `)`
}
func getQueryForCostWithPriceWithAlias(suffix string) string {
return `pricePerCPU` + suffix + ` as cpuPrice
pricePerMemory` + suffix + ` as memoryPrice
cpuCost: math(cpu` + suffix + ` * durationInHours` + suffix + ` * pricePerCPU` + suffix + `)
memoryCost: math(memory` + suffix + ` * durationInHours` + suffix + ` * pricePerMemory` + suffix + `)
storageCost: math(storage` + suffix + ` * durationInHours` + suffix + ` * ` + models.DefaultStorageCostPerGBPerHour + `)`
}
func getQueryForCostWithPrice(suffix string) string {
return `pricePerCPU` + suffix + ` as cpuPrice
pricePerMemory` + suffix + ` as memoryPrice
cpuCost` + suffix + ` as math(cpu` + suffix + ` * durationInHours` + suffix + ` * pricePerCPU` + suffix + `)
memoryCost` + suffix + ` as math(memory` + suffix + ` * durationInHours` + suffix + ` * pricePerMemory` + suffix + `)
storageCost` + suffix + ` as math(storage` + suffix + ` * durationInHours` + suffix + ` * ` + models.DefaultStorageCostPerGBPerHour + `)`
}
func getQueryForAggregatingChildMetricsWithAlias(childSuffix string) string {
return `name
type
cpu: sum(val(cpu` + childSuffix + `))
memory: sum(val(memory` + childSuffix + `))
storage: sum(val(storage` + childSuffix + `))
cpuCost: sum(val(cpuCost` + childSuffix + `))
memoryCost: sum(val(memoryCost` + childSuffix + `))
storageCost: sum(val(storageCost` + childSuffix + `))`
}
func getQueryForAggregatingChildMetrics(parentSuffix, childSuffix string) string {
return `cpu` + parentSuffix + ` as sum(val(cpu` + childSuffix + `))
memory` + parentSuffix + ` as sum(val(memory` + childSuffix + `))
storage` + parentSuffix + ` as sum(val(storage` + childSuffix + `))
cpuCost` + parentSuffix + ` as sum(val(cpuCost` + childSuffix + `))
memoryCost` + parentSuffix + ` as sum(val(memoryCost` + childSuffix + `))
storageCost` + parentSuffix + ` as sum(val(storageCost` + childSuffix + `))`
}
func getQueryFromSubQueryWithAlias(suffix string) string {
return `name
type
cpu: val(cpu` + suffix + `)
memory: val(memory` + suffix + `)
storage: val(storage` + suffix + `)
cpuCost: val(cpuCost` + suffix + `)
memoryCost: val(memoryCost` + suffix + `)
storageCost: val(storageCost` + suffix + `)`
}
func (r *Resource) getQueryForPodParentMetrics() string {
return `query {
parent(func: has(` + r.Check + `)) @filter(eq(name, "` + r.Name + `")) {
children: ~` + r.Type + ` @filter(has(isPod)) {
` + getQueryForMetricsComputationWithAliasAndVariables("Pod") + `
}
` + getQueryForAggregatingChildMetricsWithAlias("Pod") + `
}
}`
}
func (r *Resource) getQueryForHierarchy() string {
return `query {
parent(func: has(` + r.Check + `)) @filter(eq(name, "` + r.Name + `")) {
name
type
children: ~` + r.Type + ` ` + r.ChildFilter + ` {
name
type
}
}
}`
} | pkg/controller/dgraph/models/query/helpers.go | 0.688992 | 0.514705 | helpers.go | starcoder |
package dtw
import (
"math"
)
// Ends holds the ends of a DTW path piece
type Ends struct {
End0, End1 int
}
// CumCostMatrix represents the accumulated cost matrix needed to compute DTW distance.
type CumCostMatrix struct {
s1, s2 [][]float64
values []float64
space PointSpace
window int
stride0, stride1 int
path []Ends
}
// NewCumCostMatrix creates at new CumCostMatrix instance.
func NewCumCostMatrix(s1, s2 [][]float64, space PointSpace, window int) CumCostMatrix {
var cost = CumCostMatrix{
s1: s1,
s2: s2,
space: space,
window: window,
}
var l1, l2 = len(s1), len(s2)
cost.setStride(l1, l2)
cost.computeCumCost()
cost.computePath()
return cost
}
// Get returns the accumulated cost at position (i1,i2)
func (cumCost *CumCostMatrix) Get(i1, i2 int) float64 {
if !cumCost.inWindow(i1, i2) {
return math.Inf(1)
}
var i = cumCost.ravel(i1, i2)
return cumCost.values[i]
}
// Path returns the DTW path
func (cumCost *CumCostMatrix) Path() []Ends {
return cumCost.path
}
func (cumCost *CumCostMatrix) setStride(shortest int, longest int) {
if cumCost.window == 0 {
cumCost.window = longest
}
var maxWindow = 2*cumCost.window + 1
cumCost.stride0 = shortest
if maxWindow < longest {
cumCost.stride1 = maxWindow
} else {
cumCost.stride1 = longest
}
}
func (cumCost *CumCostMatrix) computeCumCost() {
var space = cumCost.space
cumCost.values = make([]float64, cumCost.stride0*cumCost.stride1)
for i1 := range cumCost.s1 {
var i2l = 0
if !cumCost.inWindow(i1, i2l) {
i2l = i1 - cumCost.window
}
var i2r = len(cumCost.s2) - 1
if !cumCost.inWindow(i1, i2r) {
i2r = i1 + cumCost.window
}
for i2 := i2l; i2 <= i2r; i2++ {
var i = cumCost.ravel(i1, i2)
var cost = 0.
var dist = space.PointDist(cumCost.s1[i1], cumCost.s2[i2])
switch {
case i1 == 0 && i2 == 0:
cost = dist
case i1 == 0:
cost = cumCost.Get(i1, i2-1) + dist
case i2 == 0:
cost = cumCost.Get(i1-1, i2) + dist
default:
var l, u, ul = cumCost.neighborCosts(i1, i2)
cost = min(ul, u, l) + dist
}
cumCost.values[i] = cost
}
}
}
func (cumCost *CumCostMatrix) computePath() {
var i1, i2 = len(cumCost.s1) - 1, len(cumCost.s2) - 1
cumCost.path = make([]Ends, 0, i1+i2)
for i1 > 0 || i2 > 0 {
cumCost.path = append(cumCost.path, Ends{i1, i2})
switch {
case i1 == 0:
i2--
case i2 == 0:
i1--
default:
var l, u, ul = cumCost.neighborCosts(i1, i2)
i1, i2 = decrPath(ul, u, l, i1, i2)
}
}
cumCost.path = append(cumCost.path, Ends{0, 0})
}
func (cumCost *CumCostMatrix) neighborCosts(i1 int, i2 int) (float64, float64, float64) {
var l = cumCost.Get(i1-1, i2)
var u = cumCost.Get(i1, i2-1)
var ul = cumCost.Get(i1-1, i2-1)
return l, u, ul
}
func (cumCost *CumCostMatrix) ravel(i, j int) int {
if i > cumCost.window {
return cumCost.index(i, j-i+cumCost.window)
}
return cumCost.index(i, j)
}
func (cumCost *CumCostMatrix) index(i, j int) int {
return i*cumCost.stride1 + j
}
func (cumCost *CumCostMatrix) inWindow(i int, j int) bool {
return i-j <= cumCost.window && j-i <= cumCost.window
}
func min(v1 float64, v2 float64, v3 float64) float64 {
switch {
case v1 <= v2 && v1 <= v3:
return v1
case v2 <= v3:
return v2
default:
return v3
}
}
func decrPath(ul float64, u float64, l float64, i1 int, i2 int) (int, int) {
switch {
case ul <= u && ul <= l:
return i1 - 1, i2 - 1
case l <= u:
return i1 - 1, i2
default:
return i1, i2 - 1
}
} | dtw/cost.go | 0.699357 | 0.456046 | cost.go | starcoder |
package main
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
func readInput(fname string) string {
data, err := ioutil.ReadFile(fname)
if err != nil {
panic("Cannot read input data.")
}
s := string(data)
return strings.TrimRight(s, "\n")
}
/*
Represent the most recent `preambleLength` numbers as a vertical column.
The horizontal rows of the array represent the result of summing the nth value
with the value at index 0, 1, 2, etc.
Because of the symmetry of the table, it is only necessary to calculate the
top right triangle.
| table |
| values | | 0 | 1 | 2 | 3 | ...
+--------+ +---+---+---+---+----
| 3 | | 6 | 5 | 3 | 4 | ...
index -> | 2 | | x | 4 | 2 | 2 | ...
| 0 | | x | x | 0 | 1 | ...
| 1 | | x | x | x | 2 | ...
Then, as new numbers come into the list and old numbers are evicted,
we only need to update the sums corresponding to the row and column
of the current index.
*/
type xmas struct {
index int
length int
isInitialized bool
values []int
table [][]int
}
func makeXmas(preambleLength int) xmas {
tbl := make([][]int, preambleLength)
for i := range tbl {
tbl[i] = make([]int, preambleLength)
}
return xmas{
index: 0,
length: preambleLength,
isInitialized: false,
values: make([]int, preambleLength),
table: tbl,
}
}
func (x *xmas) increment() {
x.index = (x.index + 1) % x.length
}
func (x *xmas) printTable() {
for _, row := range x.table {
for _, num := range row {
fmt.Print(num, "\t")
}
fmt.Println("")
}
}
func (x *xmas) readValue(val int) {
x.values[x.index] = val
// First, select the row at the current index, and upload
// all values starting from the diagonal rightward
for i := x.index; i < x.length; i++ {
x.table[x.index][i] = x.values[x.index] + x.values[i]
}
// Now update the entire column at the current index from
// the top of the table down to the current index row
for j := 0; j <= x.index; j++ {
x.table[j][x.index] = x.values[x.index] + x.values[j]
}
x.increment()
if x.index == 0 {
// finished reading the preamble and is ready to start processing
x.isInitialized = true
}
}
func (x *xmas) getValidValues() map[int]bool {
valid := make(map[int]bool, 0)
for i := 0; i < x.length; i++ {
for j := i; j < x.length; j++ {
value := x.table[i][j]
valid[value] = true
}
}
return valid
}
func (x *xmas) isValidNextNumber(n int) bool {
if !x.isInitialized {
return true
}
valid := x.getValidValues()
return valid[n]
}
func input2slice(txt string) []int {
lines := strings.Split(txt, "\n")
numbers := make([]int, len(lines))
for i := range lines {
n, err := strconv.Atoi(lines[i])
if err != nil {
panic(fmt.Sprintf("Invalid input at line %d", i))
}
numbers[i] = n
}
return numbers
}
func part1(input []int, preambleLength int) int {
x := makeXmas(preambleLength)
for _, n := range input {
if !x.isValidNextNumber(n) {
return n
}
x.readValue(n)
}
return 0
}
func getSumOfMinAndMax(seq []int) int {
min := seq[0]
max := seq[0]
for i := range seq {
if seq[i] < min {
min = seq[i]
}
if seq[i] > max {
max = seq[i]
}
}
return min + max
}
func part2(input []int, targetNum int) int {
for i := 0; i < len(input); i++ {
sum := input[i]
if sum == targetNum {
continue
}
for j := i + 1; j < len(input); j++ {
sum += input[j]
if sum == targetNum {
return getSumOfMinAndMax(input[i : j+1])
}
if sum > targetNum {
break
}
}
}
return 0
}
func main() {
txt := readInput("input.txt")
nums := input2slice(txt)
p1 := part1(nums, 25)
fmt.Println("[PART 1] Result:", p1)
p2 := part2(nums, p1)
fmt.Println("[PART 2] Result:", p2)
} | day09/main.go | 0.539954 | 0.514522 | main.go | starcoder |
package duplist
import (
"time"
)
// TimeString is a modified skiplist implementation allowing duplicate
// time keys to exist inside the same list. Elements with duplicate keys are
// adjacent inside TimeString, with a later insert placed left of earlier
// ones.
// Elements with different keys are sorted in ascending order as usual.
// TimeString is required for implementing TTL.
// TimeString does not allow random get or delete by specifying a key and
// instead only allows get or delete on the first element of the list, or delete
// by specifying an element pointer.
type TimeString struct {
front []*TimeStringElement
rhg *randomHeightGenerator
maxHeight int
}
func NewTimeString(maxHeight int) *TimeString {
ts := &TimeString{}
ts.Init(maxHeight)
return ts
}
func (ts *TimeString) Init(maxHeight int) {
ts.maxHeight = maxHeight
ts.front = make([]*TimeStringElement, maxHeight)
if maxHeight < 2 || maxHeight >= 64 {
panic("maxHeight must be between 2 and 64")
}
ts.rhg = newRandomHeightGenerator(maxHeight, nil)
}
func (ts *TimeString) First() *TimeStringElement {
return ts.front[0]
}
func (ts *TimeString) DelElement(el *TimeStringElement) {
if el == nil {
return
}
for i := 0; i < len(el.nexts); i++ {
if el.prevs[i] == nil {
ts.front[i] = el.nexts[i]
} else {
el.prevs[i].nexts[i] = el.nexts[i]
}
if el.nexts[i] != nil {
el.nexts[i].prevs[i] = el.prevs[i]
}
}
}
func (ts *TimeString) Insert(key time.Time, val string) *TimeStringElement {
el := newTimeStringElement(key, val, ts.rhg)
if ts.front[0] == nil {
ts.insert(ts.front, el, nil)
} else {
ts.searchAndInsert(el)
}
return el
}
func (ts *TimeString) searchAndInsert(el *TimeStringElement) {
leftAll, iter := ts.search(el.key)
ts.insert(leftAll, el, iter)
}
func (ts *TimeString) search(key time.Time) (
leftAll []*TimeStringElement,
right *TimeStringElement, // iterator and result
) {
leftAll = make([]*TimeStringElement, ts.maxHeight)
for h := ts.maxHeight - 1; h >= 0; h-- {
if h == ts.maxHeight-1 || leftAll[h+1] == nil {
right = ts.front[h]
} else {
leftAll[h] = leftAll[h+1]
right = leftAll[h].nexts[h]
}
for {
if right == nil || key.Before(right.key) || key.Equal(right.key) { // slow comparison
break
} else {
leftAll[h] = right
right = right.nexts[h]
}
}
}
return
}
func (ts *TimeString) insert(leftAll []*TimeStringElement, el, right *TimeStringElement) {
for i := 0; i < len(el.nexts); i++ {
el.prevs[i] = leftAll[i]
if right != nil && i < len(el.nexts) {
if i < len(right.nexts) {
right.prevs[i] = el
} else {
if leftAll[i] != nil {
if leftAll[i].nexts[i] != nil {
leftAll[i].nexts[i].prevs[i] = el
}
} else {
if ts.front[i] != nil {
ts.front[i].prevs[i] = el
}
}
}
}
if right != nil && i < len(right.nexts) {
el.nexts[i] = right
} else {
// intercept leftAll[i].nexts[i]
if leftAll[i] != nil {
el.nexts[i] = leftAll[i].nexts[i]
} else {
el.nexts[i] = ts.front[i]
}
}
// reassign what leftAll[i].nexts[i] points to
if leftAll[i] == nil {
ts.front[i] = el
} else {
leftAll[i].nexts[i] = el
}
}
} | datastructure/duplist/timestring.go | 0.674158 | 0.403861 | timestring.go | starcoder |
package sim
import (
"time"
)
// A Strategy is an interface which triggers reinvestments based on some
// criteria held in its internal state. It gets the current date to evaluate
// passed along with a Portfolio to trigger rebalancing if the criteria are
// met.
type Strategy interface {
tick(time.Time, Portfolio)
}
// This struct implements the Strategy interface and triggers rebalancing
// always on `minDay` of the month or the first evaluation day after the
// `minDay`.
type MidMonth struct {
lastInvested time.Time
minDay int
}
// A FixedMonths strategy triggers rebalancing always on `minDay` or the first
// evaluation day after `minDay`, but only in months given in `investMonths`.
type FixedMonths struct {
investMonths map[time.Month]bool
lastInvested time.Time
minDay int
}
// NoInvest is an empty strategy implementing the `Strategy` interface but
// never trigering any investment. It serves as baseline comparison for other
// strategies.
type NoInvest struct {
}
// WithDrawdown is a type to be embedded in other strategies. It holds the state
// and provides methods to evaluate if a certain minimum drawdown was reached as
// investment criterion.
type WithDrawdown struct {
relVal float64
refSymbol string
priceP priceProvider
lastTop float64
}
// MinDrawdown triggers an investment when a certain minimum drawdown is
// reached. In the current implementation, it wraps `WithDrawdown`.
type MinDrawdown struct {
WithDrawdown
}
// AdaptivePeriodic is a hybrid strategy which triggers investments periodically
// after `waitTime` but also invests earlier if a certain minimum drawdown is
// reached.
type AdaptivePeriodic struct {
waitTime time.Duration
lastInvested time.Time
WithDrawdown
}
// NewMonthlyStrategy creates a new strategy investing monthly on the 14th or
// the first evaluation day after the 14th.
func NewMonthlyStrategy(startDate time.Time) Strategy {
return &MidMonth{
lastInvested: startDate.Add(-31 * 24 * time.Hour),
minDay: 14,
}
}
// NewFixedMonthsStrategy creates a new strategy investing on the 14th of every
// month given in `month` or the first evaluation day after the 14th.
func NewFixedMonthsStrategy(startDate time.Time, months []time.Month) Strategy {
invMonths := map[time.Month]bool{}
for _, m := range months {
invMonths[m] = true
}
return &FixedMonths{
investMonths: invMonths,
// Go 31 days back
lastInvested: startDate.Add(-31 * 24 * time.Hour),
minDay: 14,
}
}
// NewMinDrawdown creates a new strategy investing when the stock behind
// `refSymbol` suffered a minimum relative drawdown to `relVal` from its last
// known top value.
func NewMinDrawdown(relVal float64, refSymbol string, priceP priceProvider) Strategy {
return &MinDrawdown{WithDrawdown{relVal, refSymbol, priceP, 0.0}}
}
// NewAdaptivePeriodic creates a new strategy investing either when `waitTime`
// has passed since the last investment or when `refSymbol` suffered a minimum
// relative drawdown to `relVal` from its last known top value.
func NewAdaptivePeriodic(startDate time.Time, waitTime time.Duration,
relVal float64, refSymbol string, priceP priceProvider) Strategy {
return &AdaptivePeriodic{
waitTime: waitTime,
lastInvested: startDate.Add(-waitTime),
WithDrawdown: WithDrawdown{
relVal: relVal,
refSymbol: refSymbol,
priceP: priceP,
},
}
}
func (mm *MidMonth) tick(date time.Time, p Portfolio) {
if !investedThisMonth(date, mm.lastInvested) {
if date.Day() >= mm.minDay {
// Attempt invest
err := p.rebalance(p.getCashBalance(), date)
if err != nil {
return
}
mm.lastInvested = date
}
}
}
func (fm *FixedMonths) tick(date time.Time, p Portfolio) {
if _, ok := fm.investMonths[date.Month()]; ok {
if !investedThisMonth(date, fm.lastInvested) {
if date.Day() >= fm.minDay {
// Attempt invest
err := p.rebalance(p.getCashBalance(), date)
if err != nil {
return
}
fm.lastInvested = date
}
}
}
}
func (s *NoInvest) tick(date time.Time, p Portfolio) {
}
func (s *MinDrawdown) tick(date time.Time, p Portfolio) {
drawdownReached, curVal := s.drawdownTick(date)
if drawdownReached {
// Attempt invest
err := p.rebalance(p.getCashBalance(), date)
if err != nil {
return
}
s.lastTop = curVal
}
}
func (s *AdaptivePeriodic) tick(date time.Time, p Portfolio) {
waitOver := date.Sub(s.lastInvested) >= s.waitTime
drawdownReached, curVal := s.drawdownTick(date)
if waitOver || drawdownReached {
// Attempt invest
err := p.rebalance(p.getCashBalance(), date)
if err != nil {
return
}
s.lastInvested = date
s.lastTop = curVal
}
}
func (wd *WithDrawdown) drawdownTick(date time.Time) (reached bool, curVal float64) {
curVal, err := wd.priceP.GetPrice(wd.refSymbol, date)
if err != nil {
return
}
if curVal > wd.lastTop {
wd.lastTop = curVal
return
}
if curVal/wd.lastTop <= wd.relVal {
reached = true
return
}
return
}
func investedThisMonth(date time.Time, lastInvested time.Time) bool {
if lastInvested.Year() == date.Year() &&
lastInvested.Month() == date.Month() {
return true
}
return false
} | sim/strategy.go | 0.814496 | 0.57332 | strategy.go | starcoder |
package gotree
import "errors"
// GeneralNode defines a tree node for a general purpose tree.
type GeneralNode struct {
value Element
children []*GeneralNode
parent *GeneralNode
}
// NewGeneralNode returns a new general tree node with the given value
// and the given list of child nodes, if any.
func NewGeneralNode(value Element, children ...*GeneralNode) *GeneralNode {
return &GeneralNode{
value: value,
children: children,
}
}
// Parent returns the parent tree node of this node.
func (node *GeneralNode) Parent() *GeneralNode {
return node.parent
}
// Children returns the list of child tree nodes of this node.
func (node *GeneralNode) Children() []*GeneralNode {
return node.children
}
// Value returns the element value stored in this node.
func (node *GeneralNode) Value() Element {
return node.value
}
// SetValue sets the new value to this node.
func (node *GeneralNode) SetValue(value Element) {
node.value = value
}
// NumberOfChildren returns the total number of child nodes of this node.
func (node *GeneralNode) NumberOfChildren() int {
return len(node.children)
}
// HasChildren returns true if this node has one or more child nodes,
// false otherwise.
func (node *GeneralNode) HasChildren() bool {
return node.NumberOfChildren() > 0
}
// NumberOfDescendants returns the total number of descendant nodes of this node.
func (node *GeneralNode) NumberOfDescendants() int {
count := node.NumberOfChildren()
for _, child := range node.children {
count += child.Size()
}
return count
}
// Size returns the total number of nodes under this node, including itself.
func (node *GeneralNode) Size() int {
return node.NumberOfDescendants() + 1
}
// AddChild inserts a child node to this node.
func (node *GeneralNode) AddChild(child *GeneralNode) {
child.parent = node
node.children = append(node.children, child)
}
// AddChildAt inserts a child node to this node at the given index.
func (node *GeneralNode) AddChildAt(child *GeneralNode, index int) error {
if index < 0 || index > len(node.children) {
return errors.New("index out of range")
}
child.parent = node
node.children = append(node.children, nil)
copy(node.children[index+1:], node.children[index:])
return nil
}
// RemoveChildren resets the list of child nodes.
func (node *GeneralNode) RemoveChildren() {
node.children = nil
}
// RemoveChildAt deletes the child node at the given index.
func (node *GeneralNode) RemoveChildAt(index int) error {
if index < 0 || index >= len(node.children) {
return errors.New("index out of range")
}
copy(node.children[index:], node.children[index+1:])
node.children[len(node.children)-1] = nil
node.children = node.children[:len(node.children)-1]
return nil
}
// GetChildAt returns the child node at the given index.
func (node *GeneralNode) GetChildAt(index int) (*GeneralNode, error) {
if index < 0 || index >= len(node.children) {
return nil, errors.New("index out of range")
}
return node.children[index], nil
}
// Find searches for the descendant node containing the given element value.
// If found, it returns the node. If not, it returns a nil pointer.
func (node *GeneralNode) Find(elem Element) *GeneralNode {
if node == nil {
return nil
}
if node.value.Equals(elem) {
return node
}
for _, child := range node.children {
if match := child.Find(elem); match != nil {
return match
}
}
return nil
}
// Equals returns true if the given node equals to this node, false otherwise.
func (node *GeneralNode) Equals(other *GeneralNode) bool {
if node == nil || other == nil {
return node == other
}
return node.value.Equals(other.value)
}
// GeneralTree defines a general purpose tree.
// It can have any number of child nodes, without any invariants or restrictions.
type GeneralTree struct {
root *GeneralNode
}
// NewGeneralTree returns a new general tree with the given root node.
func NewGeneralTree(root *GeneralNode) *GeneralTree {
return &GeneralTree{root}
}
// Root returns the root node of this tree.
func (tree *GeneralTree) Root() *GeneralNode {
return tree.root
}
// SetRoot sets the new root node to this tree.
func (tree *GeneralTree) SetRoot(root *GeneralNode) {
tree.root = root
}
// Size returns the total number of nodes under this tree.
func (tree *GeneralTree) Size() int {
if tree.root == nil {
return 0
}
return tree.root.Size()
}
// Find searches for the node of this tree containing the given element value.
// If found, it returns the node. If not, it returns a nil pointer.
func (tree *GeneralTree) Find(elem Element) *GeneralNode {
return tree.root.Find(elem)
} | general.go | 0.835484 | 0.53607 | general.go | starcoder |
package serialization
import (
"time"
cjl "github.com/cjlapao/common-go/duration"
)
// ISODuration represents an ISO 8601 duration
type ISODuration struct {
duration cjl.Duration
}
// GetYears returns the number of years.
func (i ISODuration) GetYears() int {
return i.duration.Years
}
// GetWeeks returns the number of weeks.
func (i ISODuration) GetWeeks() int {
return i.duration.Weeks
}
// GetDays returns the number of days.
func (i ISODuration) GetDays() int {
return i.duration.Days
}
// GetHours returns the number of hours.
func (i ISODuration) GetHours() int {
return i.duration.Hours
}
// GetMinutes returns the number of minutes.
func (i ISODuration) GetMinutes() int {
return i.duration.Minutes
}
// GetSeconds returns the number of seconds.
func (i ISODuration) GetSeconds() int {
return i.duration.Seconds
}
// GetMilliSeconds returns the number of milliseconds.
func (i ISODuration) GetMilliSeconds() int {
return i.duration.MilliSeconds
}
// SetYears sets the number of years.
func (i ISODuration) SetYears(years int) {
i.duration.Years = years
}
// SetWeeks sets the number of weeks.
func (i ISODuration) SetWeeks(weeks int) {
i.duration.Weeks = weeks
}
// SetDays sets the number of days.
func (i ISODuration) SetDays(days int) {
i.duration.Days = days
}
// SetHours sets the number of hours.
func (i ISODuration) SetHours(hours int) {
i.duration.Hours = hours
}
// SetMinutes sets the number of minutes.
func (i ISODuration) SetMinutes(minutes int) {
i.duration.Minutes = minutes
}
// SetSeconds sets the number of seconds.
func (i ISODuration) SetSeconds(seconds int) {
i.duration.Seconds = seconds
}
// SetMilliSeconds sets the number of milliseconds.
func (i ISODuration) SetMilliSeconds(milliSeconds int) {
i.duration.MilliSeconds = milliSeconds
}
// ParseISODuration parses a string into an ISODuration following the ISO 8601 standard.
func ParseISODuration(s string) (*ISODuration, error) {
d, err := cjl.FromString(s)
if err != nil {
return nil, err
}
return &ISODuration{
duration: *d,
}, nil
}
// NewISODuration creates a new ISODuration from primitive values.
func NewDuration(years int, weeks int, days int, hours int, minutes int, seconds int, milliSeconds int) *ISODuration {
return &ISODuration{
duration: cjl.Duration{
Years: years,
Weeks: weeks,
Days: days,
Hours: hours,
Minutes: minutes,
Seconds: seconds,
MilliSeconds: milliSeconds,
},
}
}
// String returns the ISO 8601 representation of the duration.
func (i ISODuration) String() string {
return i.duration.String()
}
// FromDuration returns an ISODuration from a time.Duration.
func FromDuration(d time.Duration) *ISODuration {
return NewDuration(0, 0, 0, 0, 0, 0, int(d.Truncate(time.Millisecond).Milliseconds()))
}
// ToDuration returns the time.Duration representation of the ISODuration.
func (d ISODuration) ToDuration() (time.Duration, error) {
return d.duration.ToDuration()
} | abstractions/go/serialization/iso_duration.go | 0.875121 | 0.462655 | iso_duration.go | starcoder |
package stat64
import (
"bytes"
"encoding/binary"
"math"
)
// size is the size of a Summary in bytes
const size = 32
// The is structured as four float64 values
// * count of observations
// * sum of observations
// * running mean of observations
// * sum of squares of differences from the current mean
var zeroStats64 = bytes.Repeat([]byte{0}, size)
// Reset returns all measures tracked by the summary represented by the supplied byte buffer to their zero values.
func Reset(buf []byte) error {
copy(buf, zeroStats64)
return nil
}
// Summary is a summary that maintains basic statistical measures for a series
// of observations. It requires 32 bytes.
type Summary []byte
// New creates a new stat64 Summary, allocating a new backing buffer.
func New() Summary {
buf := make([]byte, size)
return WithBytes(buf)
}
// WithBytes creates a new stat64 Summary backed by the buffer buf which
// must be at least 32 bytes in length.
func WithBytes(buf []byte) Summary {
return Summary(buf)
}
// Len returns the length of the buffer required to serialize a summary
func Len() int {
return size
}
// Size returns the length of the buffer required to serialize the summary
func (s Summary) Len() int {
return size
}
// Count returns the number of observations received.
func (s Summary) Count() uint64 {
return binary.LittleEndian.Uint64(s[:8])
}
// Mean returns the mean of the observation values.
func (s Summary) Mean() float64 {
return math.Float64frombits(binary.LittleEndian.Uint64(s[16:24]))
}
// Variance returns the sample variance of the series of observations.
func (s Summary) Variance() float64 {
count := binary.LittleEndian.Uint64(s[:8])
if count < 2 {
return math.NaN()
}
ss := math.Float64frombits(binary.LittleEndian.Uint64(s[24:32]))
return ss / float64(count-1)
}
// Sum returns the sum of the observation values.
func (s Summary) Sum() float64 {
return math.Float64frombits(binary.LittleEndian.Uint64(s[8:16]))
}
// Update adds an observation to the summary.
func (s Summary) Update(v float64) {
count := binary.LittleEndian.Uint64(s[:8])
sum := math.Float64frombits(binary.LittleEndian.Uint64(s[8:16]))
mean := math.Float64frombits(binary.LittleEndian.Uint64(s[16:24]))
// ss is the sum of squares of differences from the current mean
ss := math.Float64frombits(binary.LittleEndian.Uint64(s[24:32]))
count++
sum += v
// Calculatation based on section 4.2.2 of Knuth, Vol 2: Seminumerical Algorithms
delta := v - mean
mean += delta / float64(count)
ss += delta * (v - mean)
binary.LittleEndian.PutUint64(s[:8], count)
binary.LittleEndian.PutUint64(s[8:16], math.Float64bits(sum))
binary.LittleEndian.PutUint64(s[16:24], math.Float64bits(mean))
binary.LittleEndian.PutUint64(s[24:32], math.Float64bits(ss))
}
// UpdateMulti adds a list of observation to the summary.
func (s Summary) UpdateMulti(vs []float64) {
count := binary.LittleEndian.Uint64(s[:8])
sum := math.Float64frombits(binary.LittleEndian.Uint64(s[8:16]))
mean := math.Float64frombits(binary.LittleEndian.Uint64(s[16:24]))
// ss is the sum of squares of differences from the current mean
ss := math.Float64frombits(binary.LittleEndian.Uint64(s[24:32]))
for _, v := range vs {
count++
sum += v
// Calculatation based on section 4.2.2 of Knuth, Vol 2: Seminumerical Algorithms
delta := v - mean
mean += delta / float64(count)
ss += delta * (v - mean)
}
binary.LittleEndian.PutUint64(s[:8], count)
binary.LittleEndian.PutUint64(s[8:16], math.Float64bits(sum))
binary.LittleEndian.PutUint64(s[16:24], math.Float64bits(mean))
binary.LittleEndian.PutUint64(s[24:32], math.Float64bits(ss))
}
// Reset returns all measures tracked by the summary to their zero values.
func (s Summary) Reset() error {
copy(s, zeroStats64)
return nil
} | internal/summary/stat64/stats.go | 0.915672 | 0.753126 | stats.go | starcoder |
package cmd
import (
"fmt"
"regexp"
"strconv"
"github.com/jaredbancroft/aoc2020/pkg/helpers"
"github.com/jaredbancroft/aoc2020/pkg/luggage"
"github.com/spf13/cobra"
)
// day7Cmd represents the day7 command
var day7Cmd = &cobra.Command{
Use: "day7",
Short: "Advent of Code 2020 - Day 7: Handy Haversacks",
Long: `
Advent of Code 2020
--- Day 7: Handy Haversacks ---
You land at the regional airport in time for your next flight. In fact, it looks like
you'll even have time to grab some food: all flights are currently delayed due to
issues in luggage processing.
Due to recent aviation regulations, many rules (your puzzle input) are being enforced
about bags and their contents; bags must be color-coded and must contain specific
quantities of other color-coded bags. Apparently, nobody responsible for these regulations
considered how long they would take to enforce!
For example, consider the following rules:
light red bags contain 1 bright white bag, 2 muted yellow bags.
dark orange bags contain 3 bright white bags, 4 muted yellow bags.
bright white bags contain 1 shiny gold bag.
muted yellow bags contain 2 shiny gold bags, 9 faded blue bags.
shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags.
dark olive bags contain 3 faded blue bags, 4 dotted black bags.
vibrant plum bags contain 5 faded blue bags, 6 dotted black bags.
faded blue bags contain no other bags.
dotted black bags contain no other bags.
These rules specify the required contents for 9 bag types. In this example, every faded
blue bag is empty, every vibrant plum bag contains 11 bags (5 faded blue and 6 dotted black),
and so on.
You have a shiny gold bag. If you wanted to carry it in at least one other bag, how many
different bag colors would be valid for the outermost bag? (In other words: how many colors
can, eventually, contain at least one shiny gold bag?)
In the above rules, the following options would be available to you:
A bright white bag, which can hold your shiny gold bag directly.
A muted yellow bag, which can hold your shiny gold bag directly, plus some other bags.
A dark orange bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag.
A light red bag, which can hold bright white and muted yellow bags, either of which could then hold your shiny gold bag.
So, in this example, the number of bag colors that can eventually contain at least one shiny gold bag is 4.
How many bag colors can eventually contain at least one shiny gold bag? (The list of rules is quite long; make
sure you get all of it.)
--- Part Two ---
It's getting pretty expensive to fly these days - not because of ticket prices, but because of the ridiculous
number of bags you need to buy!
Consider again your shiny gold bag and the rules from the above example:
faded blue bags contain 0 other bags.
dotted black bags contain 0 other bags.
vibrant plum bags contain 11 other bags: 5 faded blue bags and 6 dotted black bags.
dark olive bags contain 7 other bags: 3 faded blue bags and 4 dotted black bags.
So, a single shiny gold bag must contain 1 dark olive bag (and the 7 bags within it) plus 2 vibrant
plum bags (and the 11 bags within each of those): 1 + 1*7 + 2 + 2*11 = 32 bags!
Of course, the actual rules have a small chance of going several levels deeper than this example; be sure to
count all of the bags, even if the nesting becomes topologically impractical!
Here's another example:
shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.
In this example, a single shiny gold bag must contain 126 other bags.
How many individual bags are required inside your single shiny gold bag?`,
RunE: func(cmd *cobra.Command, args []string) error {
rules, err := helpers.ReadStringFile(input)
if err != nil {
return err
}
var baseLuggage [][]string
var luggageList []luggage.Bag
re1 := regexp.MustCompile(`(\w+\s\w+)\sbags\scontain`)
re2 := regexp.MustCompile(`contain\s(?:no\sother\sbags\.|(?:(\d)\s(\w+\s\w+)))`)
re3 := regexp.MustCompile(`,\s(\d)\s(\w+\s\w+)`)
bc := make(map[string]int)
for _, rule := range rules {
baseLuggage = re1.FindAllStringSubmatch(rule, -1)
bag := luggage.NewBag(baseLuggage[0][1])
contains := re2.FindAllStringSubmatch(rule, -1)
name := contains[0][2]
i, _ := strconv.Atoi(contains[0][1])
bc[name] = i
containsmore := re3.FindAllStringSubmatch(rule, -1)
for _, cm := range containsmore {
j, _ := strconv.Atoi(cm[1])
bc[cm[2]] = j
}
bag.Contains = bc
luggageList = append(luggageList, *bag)
bc = make(map[string]int)
}
simplify := []string{"shiny gold"}
simplify2 := []string{}
res := []luggage.Bag{}
for {
var before, after int
for _, s := range simplify {
for i, ll := range luggageList {
if _, ok := ll.Contains[s]; ok {
simplify2 = append(simplify2, ll.Name)
res = append(res, ll)
luggageList[i] = luggage.Bag{}
}
}
}
simplify = simplify2
simplify2 = []string{}
after = len(simplify)
if before == after {
break
}
}
fmt.Println(len(res))
var bag luggage.Bag
for _, ll := range luggageList {
if ll.Name == "shiny gold" {
bag = ll
}
}
fmt.Println(bag.Walk(luggageList))
return nil
},
}
func init() {
rootCmd.AddCommand(day7Cmd)
} | cmd/day7.go | 0.651577 | 0.488283 | day7.go | starcoder |
package xmss
// Expands an n-byte array into a len*n byte array using the `prf` function
func expandSeed(params *Params, inseed []byte) (expanded []byte) {
expanded = make([]byte, params.wotsSignLen)
ctr := make([]byte, 32)
var idx int
for i := 0; i < int(params.wlen); i++ {
ctr = toByte(i, 32)
idx = i * params.n
hashPRF(params, expanded[idx:idx+params.n], inseed, ctr)
}
return
}
// Section 2.6 Strings of Base w Numbers
// Algorithm 1: base_w
func basew(params *Params, x, output []byte) {
in := 0
out := 0
total := uint(0)
bits := uint(0)
for i := 0; i < len(output); i++ {
if bits == 0 {
total = uint(x[in])
in++
bits += 8
}
bits -= params.log2w
output[out] = uint8(total>>bits) & (uint8(params.w) - 1)
out++
}
}
// Section 3.1.2. Algorithm 2: chain - Chaining Function
// out and in have to be n-byte arrays, a is the address of the chain
func chain(params *Params, out, in, seed []byte, start, steps uint32, a *address) {
copy(out, in)
for i := start; i < (start + steps); i++ {
a.setHashAddr(i)
hashF(params, out, seed, out, a)
}
}
// Takes a message and derives the matching chain lengths.
// Computes the WOTS+ checksum over a message (in base_w)
// lengths is a wlen-byte array (e.g. 67)
func wotsChecksum(params *Params, lengths, in []byte) {
basew(params, in, lengths[:params.len1])
var csum uint16
for i := 0; i < int(params.len1); i++ {
csum += uint16(params.w) - 1 - uint16(lengths[i])
}
csum <<= 4
csumBytes := toByte(int(csum), int(params.len2*uint32(params.log2w)+7)/8)
basew(params, csumBytes, lengths[params.len1:])
}
type privateWOTS []byte
type publicWOTS []byte
type signatureWOTS []byte
// Section 3.1.3. Algorithm 3: WOTS_genSK - Generating a WOTS+ Private Key
func generatePrivate(params *Params, seed []byte) *privateWOTS {
var prv privateWOTS
prv = expandSeed(params, seed)
return &prv
}
// Section 3.1.4. Algorithm 4: WOTS_genPK - Generating a WOTS+ Public Key From a Private Key
// WOTS key generation. Takes a 32 byte seed for the private key, expands it to
// a full WOTS private key and computes the corresponding public key.
// It requires the seed pubSeed (used to generate bitmasks and hash keys)
// and the address of this WOTS key pair.
func (prv privateWOTS) generatePublic(params *Params, pubSeed []byte, a *address) *publicWOTS {
var pub publicWOTS
// prv is wotsSignLen(wlen*n)-byte array
pub = make([]byte, len(prv))
for i := uint32(0); i < params.wlen; i++ {
a.setChainAddr(i)
idx := int(i) * params.n
chain(params, pub[idx:idx+params.n], prv[idx:idx+params.n], pubSeed, 0, uint32(params.w)-1, a)
}
return &pub
}
// Section 3.1.5. Algorithm 5: WOTS_sign - Generating a signature from a private key and a message
// Takes a n-byte message and the 32-byte seed for the private key to compute a
// signature that is placed at 'sig'.
func (prv privateWOTS) sign(params *Params, in, pubSeed []byte, a *address) *signatureWOTS {
lengths := make([]byte, params.wlen)
wotsChecksum(params, lengths, in)
var sign signatureWOTS
sign = make([]byte, len(prv))
copy(sign, prv)
for i := uint32(0); i < params.wlen; i++ {
a.setChainAddr(i)
idx := int(i) * params.n
chain(params, sign[idx:idx+params.n], sign[idx:idx+params.n], pubSeed, 0, uint32(lengths[i]), a)
}
return &sign
}
// Section 3.1.6. Algorithm 6: WOTS_pkFromSig - Computing a WOTS+ public key from a message and its signature
// Takes a WOTS signature and an n-byte message, computes a WOTS public key.
func (sign signatureWOTS) getPublic(params *Params, in, pubSeed []byte, a *address) *publicWOTS {
lengths := make([]byte, params.wlen)
wotsChecksum(params, lengths, in)
var pub publicWOTS
pub = make([]byte, params.wotsSignLen)
for i := uint32(0); i < params.wlen; i++ {
a.setChainAddr(i)
idx := int(i) * params.n
chain(params, pub[idx:idx+params.n], sign[idx:idx+params.n], pubSeed, uint32(lengths[i]), uint32(params.w)-1-uint32(lengths[i]), a)
}
return &pub
} | wots.go | 0.796846 | 0.427636 | wots.go | starcoder |
// Package mathutil implements some functions for math calculation.
package mathutil
import (
"fmt"
"math"
"strconv"
"strings"
"github.com/duke-git/lancet/v2/lancetconstraints"
)
// Exponent calculate x^n
func Exponent(x, n int64) int64 {
if n == 0 {
return 1
}
t := Exponent(x, n/2)
if n%2 == 1 {
return t * t * x
}
return t * t
}
// Fibonacci calculate fibonacci number before n
func Fibonacci(first, second, n int) int {
if n <= 0 {
return 0
}
if n < 3 {
return 1
} else if n == 3 {
return first + second
} else {
return Fibonacci(second, first+second, n-1)
}
}
// Factorial calculate x!
func Factorial(x uint) uint {
var f uint = 1
for ; x > 1; x-- {
f *= x
}
return f
}
// Percent calculate the percentage of val to total
func Percent(val, total float64, n int) float64 {
if total == 0 {
return float64(0)
}
tmp := val / total * 100
res := RoundToFloat(tmp, n)
return res
}
// RoundToString round up to n decimal places
func RoundToString(x float64, n int) string {
tmp := math.Pow(10.0, float64(n))
x *= tmp
x = math.Round(x)
res := strconv.FormatFloat(x/tmp, 'f', n, 64)
return res
}
// RoundToFloat round up to n decimal places
func RoundToFloat(x float64, n int) float64 {
tmp := math.Pow(10.0, float64(n))
x *= tmp
x = math.Round(x)
return x / tmp
}
// TruncRound round off n decimal places
func TruncRound(x float64, n int) float64 {
floatStr := fmt.Sprintf("%."+strconv.Itoa(n+1)+"f", x)
temp := strings.Split(floatStr, ".")
var newFloat string
if len(temp) < 2 || n >= len(temp[1]) {
newFloat = floatStr
} else {
newFloat = temp[0] + "." + temp[1][:n]
}
res, _ := strconv.ParseFloat(newFloat, 64)
return res
}
// Max return max value of params
func Max[T lancetconstraints.Number](numbers ...T) T {
max := numbers[0]
for _, v := range numbers {
if max < v {
max = v
}
}
return max
}
// Min return min value of params
func Min[T lancetconstraints.Number](numbers ...T) T {
min := numbers[0]
for _, v := range numbers {
if min > v {
min = v
}
}
return min
}
// Average return average value of params
func Average[T lancetconstraints.Number](numbers ...T) T {
var sum T
n := T(len(numbers))
for _, v := range numbers {
sum += v
}
return sum / n
} | mathutil/mathutil.go | 0.682997 | 0.427695 | mathutil.go | starcoder |
package code
import "fmt"
// instSet is a map of an opcode and a binary opcode.
type instSet map[string]byte
// contains reports whether mneum is contained in instSet.
func (is instSet) isValid(mneum string) bool {
_, found := is[mneum]
return found
}
var (
// destInstSet is a map of dest mneumonics and its binary opcodes.
destInstSet = instSet{
"": 0x0,
"M": 0x1,
"D": 0x2,
"MD": 0x3,
"A": 0x4,
"AM": 0x5,
"AD": 0x6,
"AMD": 0x7,
}
// compInstSet is a map of comp mneumonics and its binary opcodes.
compInstSet = instSet{
// a = 0
"0": 0x2A,
"1": 0x3F,
"-1": 0x3A,
"D": 0xC,
"A": 0x30,
"!D": 0xD,
"!A": 0x31,
"-D": 0xF,
"-A": 0x33,
"D+1": 0x1F,
"A+1": 0x37,
"D-1": 0xE,
"A-1": 0x32,
"D+A": 0x2,
"D-A": 0x13,
"A-D": 0x7,
"D&A": 0x0,
"D|A": 0x15,
// a = 1
"M": 0x70,
"!M": 0x71,
"-M": 0x73,
"M+1": 0x77,
"M-1": 0x72,
"D+M": 0x42,
"D-M": 0x53,
"M-D": 0x47,
"D&M": 0x40,
"D|M": 0x55,
}
// jumpInstSet is a map of jump mneumonics and its binary opcodes.
jumpInstSet instSet = map[string]byte{
"": 0x0,
"JGT": 0x1,
"JEQ": 0x2,
"JGE": 0x3,
"JLT": 0x4,
"JNE": 0x5,
"JLE": 0x6,
"JMP": 0x7,
}
)
// Code is a converter from mneumonics to binary codes.
type Code struct {
}
// Dest returns 3 bit binary opcode corresponding to the dest mneumonic.
func (c *Code) Dest(mneum string) (byte, error) {
if !destInstSet.isValid(mneum) {
return 0, fmt.Errorf("invalid dest mneumonic: %s", mneum)
}
return destInstSet[mneum], nil
}
// IsValidDest reports whether mneum is a valid dest mneumonic.
func (c *Code) IsValidDest(mneum string) bool {
return destInstSet.isValid(mneum)
}
// Comp returns 7 bit binary opcode corresponding to the comp mneumonic.
func (c *Code) Comp(mneum string) (byte, error) {
if !compInstSet.isValid(mneum) {
return 0, fmt.Errorf("invalid comp mneumonic: %s", mneum)
}
return compInstSet[mneum], nil
}
// IsValidComp reports whether mneum is a valid comp mneumonic.
func (c *Code) IsValidComp(mneum string) bool {
return compInstSet.isValid(mneum)
}
// Jump returns 3 bit binary code corresponding to the jump mneumonic.
func (c *Code) Jump(mneum string) (byte, error) {
if !jumpInstSet.isValid(mneum) {
return 0, fmt.Errorf("invalid jump mneumonic: %s", mneum)
}
return jumpInstSet[mneum], nil
}
// IsValidJump reports whether mneum is a valid jump mneumonic.
func (c *Code) IsValidJump(mneum string) bool {
return jumpInstSet.isValid(mneum)
} | assembler/code/code.go | 0.68595 | 0.564639 | code.go | starcoder |
package dellstoragecenter
import (
"strconv"
"strings"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
)
type (
// Dellstoragecenter Defines the interface for connecting to a Dell Storage Center
Dellstoragecenter struct {
IPAddress string `toml:"ip_address"`
Port int `toml:"port"`
Username string `toml:"username"`
Password string `toml:"password"`
DellAPIVersion string `toml:"dell-api-version"`
BaseURL string
connection *apiConnection
}
)
// Description returns a string describing of the plugin
func (d *Dellstoragecenter) Description() string {
return "Return performance data for all volumes in a Dell Storage Center endpoint."
}
// SampleConfig returns an sample configuration for the Telegraf config file
func (d *Dellstoragecenter) SampleConfig() string {
return `
## IP address the Data Collector is listening on
# ip_address = "192.168.192.168"
## The port number the Data Collector is listening on
# port = 3033
## The username to log into the Data Collector with
# username = "admin"
## The password to log into the Data Collector with
# password = "<PASSWORD>"
## Version of the Dell API to use
# dell-api-version = 4.1
## Interval to poll for stats
interval = "60s"
`
}
func (d *Dellstoragecenter) Gather(acc telegraf.Accumulator) error {
baseURL := "https://" + d.IPAddress + ":" + strconv.Itoa(d.Port)
apiConn := newAPIConnection(baseURL, d.DellAPIVersion, d.Username, d.Password)
err := apiConn.Login()
if err != nil {
acc.AddError(err)
}
scVolumeList, err := apiConn.GetVolumeList()
if err != nil {
acc.AddError(err)
}
for _, scVolume := range scVolumeList {
tags := map[string]string{
"scName": scVolume.SCName,
"scVolume": scVolume.Name,
"instanceId": scVolume.InstanceID,
}
fields, timestamp, err := d.gatherIoUsageStat(apiConn, scVolume)
if err != nil {
acc.AddError(err)
}
acc.AddFields("dellstoragecenter", fields, tags, timestamp)
fields, timestamp, err = d.gatherStorageUsageStat(apiConn, scVolume)
if err != nil {
acc.AddError(err)
}
acc.AddFields("dellstoragecenter", fields, tags, timestamp)
}
return nil
}
func (d *Dellstoragecenter) gatherIoUsageStat(apiConn *apiConnection, scVolume scVolume) (map[string]interface{}, time.Time, error) {
volumeIoUsageStats, err := apiConn.GetVolumeIoUsageStats(scVolume.InstanceID)
if err != nil {
return nil, time.Time{}, err
}
if len(volumeIoUsageStats) < 1 {
return map[string]interface{}{}, time.Time{}, nil
}
volStat := volumeIoUsageStats[len(volumeIoUsageStats)-1]
fields := map[string]interface{}{
"averageKbPerIo": volStat.AverageKbPerIO,
"instanceId": volStat.InstanceID,
"ioPending": volStat.IOPending,
"readIops": volStat.ReadIOPS,
"readKbPerSecond": volStat.ReadKbPerSecond,
"readLatency": volStat.ReadLatency,
"scName": volStat.SCName,
"totalIops": volStat.TotalIOPS,
"totalKbPerSecond": volStat.TotalKbPerSecond,
"writeKbPerSecond": volStat.WriteKbPerSecond,
"writeIops": volStat.WriteIOPS,
"writeLatency": volStat.WriteLatency,
"xferLatency": volStat.XferLatency,
}
timestamp, err := time.Parse("2006-01-02T15:04:05Z", volStat.Time)
if err != nil {
return nil, time.Time{}, err
}
return fields, timestamp, nil
}
func (d *Dellstoragecenter) gatherStorageUsageStat(apiConn *apiConnection, scVolume scVolume) (map[string]interface{}, time.Time, error) {
volumeStorageUsageStats, err := apiConn.GetVolumeStorageUsageStats(scVolume.InstanceID)
if err != nil {
return nil, time.Time{}, err
}
if len(volumeStorageUsageStats) < 1 {
return map[string]interface{}{}, time.Time{}, nil
}
volStat := volumeStorageUsageStats[len(volumeStorageUsageStats)-1]
fields := map[string]interface{}{
"activeSpace": bytesStringToInt(volStat.ActiveSpace),
"activeSpaceOnDisk": bytesStringToInt(volStat.ActiveSpaceOnDisk),
"actualSpace": bytesStringToInt(volStat.ActualSpace),
"configuredSpace": bytesStringToInt(volStat.ConfiguredSpace),
"estimatedDataReductionSpaceSavings": bytesStringToInt(volStat.EstimatedDataReductionSpaceSavings),
"estimatedDiskSpaceSavedByCompression": bytesStringToInt(volStat.EstimatedDiskSpaceSavedByCompression),
"estimatedDiskSpaceSavedByDeduplicated": bytesStringToInt(volStat.EstimatedDiskSpaceSavedByDeduplicated),
"estimatedNonDeduplicatedToDuplicatedPageRatio": volStat.EstimatedNonDeduplicatedToDuplicatedPageRatio,
"estimatedPercentCompressed": volStat.EstimatedPercentCompressed,
"estimatedPercentDeduplicated": volStat.EstimatedPercentDeduplicated,
"estimatedUncompressedToCompressedPageRatio": volStat.EstimatedUncompressedToCompressedPageRatio,
"freeSpace": bytesStringToInt(volStat.FreeSpace),
"instanceId": volStat.InstanceID,
"instanceName": volStat.InstanceName,
"name": volStat.Name,
"objectType": volStat.ObjectType,
"raidOverhead": bytesStringToInt(volStat.RaidOverhead),
"replaySpace": bytesStringToInt(volStat.ReplaySpace),
"savingsVsRaidTen": bytesStringToInt(volStat.SavingsVsRaidTen),
"scName": volStat.ScName,
"scSerialNumber": volStat.ScSerialNumber,
"sharedSpace": bytesStringToInt(volStat.SharedSpace),
"snapshotOverheadOnDisk": bytesStringToInt(volStat.SnapshotOverheadOnDisk),
"time": volStat.Time,
"totalDiskSpace": bytesStringToInt(volStat.TotalDiskSpace),
}
timestamp, err := time.Parse("2006-01-02T15:04:05Z", volStat.Time)
if err != nil {
return nil, time.Time{}, err
}
return fields, timestamp, nil
}
// bytesStringToInt converts a string in the form "13245 Bytes" to an int64 like 12346
func bytesStringToInt(byteString string) int64 {
// strip " Byte" from the string
str := strings.TrimRight(byteString, " Bytes")
integer64, _ := strconv.ParseInt(str, 10, 64)
//fmt.Printf("Converted %s to %d\n", byteString, integer64)
return integer64
}
func init() {
c := Dellstoragecenter{}
inputs.Add("dellstoragecenter", func() telegraf.Input {
return &c
})
} | plugins/inputs/dellstoragecenter/dellstoragecenter.go | 0.619126 | 0.445168 | dellstoragecenter.go | starcoder |
package neat
import (
"errors"
"sort"
"github.com/klokare/evo"
)
// Known errors
var (
ErrNoParents = errors.New("NEAT crosser requires at least 1 parent")
ErrTooManyParents = errors.New("NEAT crosser does not support more than 2 parents")
)
// Crosser combines 1 or more parents to create an offspring genome.
type Crosser struct {
EnableProbability float64
DisableEqualParentCheck bool
DisableSortCheck bool
evo.Comparison
}
// Cross the parents and create a new offspring, using the sequence to assign a new ID. There is a
// chance that connections disabled in one of the parents will also be disabled in the child.
func (z *Crosser) Cross(parents ...evo.Genome) (child evo.Genome, err error) {
// Check for errors
if len(parents) == 0 {
err = ErrNoParents
return
} else if len(parents) > 2 {
err = ErrTooManyParents
return
}
// Special case: single parent
rng := evo.NewRandom()
p1 := parents[0]
if len(parents) == 1 {
// Clone the parent and return
child = evo.Genome{
Encoded: evo.Substrate{
Nodes: make([]evo.Node, len(p1.Encoded.Nodes)),
Conns: make([]evo.Conn, len(p1.Encoded.Conns)),
},
Traits: make([]float64, len(p1.Traits)),
}
copy(child.Encoded.Nodes, p1.Encoded.Nodes)
copy(child.Encoded.Conns, p1.Encoded.Conns)
copy(child.Traits, p1.Traits)
} else {
// Ensure the more fit parent is in position 1
p2 := parents[1]
if z.Compare(p1, p2) < 0 {
p1, p2 = p2, p1
}
same := p1.Fitness == p2.Fitness && !z.DisableEqualParentCheck
// Create the child
child = evo.Genome{
Encoded: evo.Substrate{
Nodes: crossNodes(rng, p1.Encoded.Nodes, p2.Encoded.Nodes, same, !z.DisableSortCheck),
Conns: crossConns(rng, p1.Encoded.Conns, p2.Encoded.Conns, same, !z.DisableSortCheck),
},
Traits: crossTraits(rng, p1.Traits, p2.Traits),
}
}
// Possibly re-enable disabled connections
for i, c := range child.Encoded.Conns {
if !c.Enabled {
if rng.Float64() < z.EnableProbability {
child.Encoded.Conns[i].Enabled = true
}
}
}
// Ensure substrate is sorted
sort.Slice(child.Encoded.Nodes, func(i, j int) bool { return child.Encoded.Nodes[i].Compare(child.Encoded.Nodes[j]) < 0 })
sort.Slice(child.Encoded.Conns, func(i, j int) bool { return child.Encoded.Conns[i].Compare(child.Encoded.Conns[j]) < 0 })
return
}
func crossNodes(rng evo.Random, nodes1, nodes2 []evo.Node, same, check bool) (nodes []evo.Node) {
// Sort the nodes
if check {
tmp := make([]evo.Node, len(nodes1)) // work with a copy to be safe for concurrency
copy(tmp, nodes1)
sort.Slice(tmp, func(i, j int) bool { return tmp[i].Compare(tmp[j]) < 0 })
nodes1 = tmp
tmp = make([]evo.Node, len(nodes2)) // work with a copy to be safe for concurrency
copy(tmp, nodes2)
sort.Slice(tmp, func(i, j int) bool { return tmp[i].Compare(tmp[j]) < 0 })
nodes2 = tmp
}
// Iterate the nodes and look for differences
var i, j int
nodes = make([]evo.Node, 0, len(nodes1)+5)
for i < len(nodes1) && j < len(nodes2) {
switch nodes1[i].Compare(nodes2[j]) {
case -1:
nodes = append(nodes, nodes1[i])
i++
case 1.0:
if same {
nodes = append(nodes, nodes2[j])
}
j++
default:
if rng.Float64() < 0.5 {
nodes = append(nodes, nodes1[i])
} else {
nodes = append(nodes, nodes2[j])
}
i++
j++
}
}
// Add remaining unmatched nodes
for i < len(nodes1) {
nodes = append(nodes, nodes1[i])
i++
}
for same && j < len(nodes2) {
nodes = append(nodes, nodes2[j])
j++
}
return
}
func crossConns(rng evo.Random, conns1, conns2 []evo.Conn, same, check bool) (conns []evo.Conn) {
// Sort the connections
if check {
tmp := make([]evo.Conn, len(conns1)) // work with a copy to be safe for concurrency
copy(tmp, conns1)
sort.Slice(tmp, func(i, j int) bool { return tmp[i].Compare(tmp[j]) < 0 })
conns1 = tmp
tmp = make([]evo.Conn, len(conns2)) // work with a copy to be safe for concurrency
copy(tmp, conns2)
sort.Slice(tmp, func(i, j int) bool { return tmp[i].Compare(tmp[j]) < 0 })
conns2 = tmp
}
// Iterate the connections and look for differences
var i, j int
for i < len(conns1) && j < len(conns2) {
switch conns1[i].Compare(conns2[j]) {
case -1:
conns = append(conns, conns1[i])
i++
case 1.0:
if same {
conns = append(conns, conns2[j])
}
j++
default:
var c evo.Conn
if rng.Float64() < 0.5 {
c = conns1[i]
} else {
c = conns2[j]
}
c.Enabled = conns1[i].Enabled && conns2[j].Enabled // Will disable if disabled in either parent
conns = append(conns, c)
i++
j++
}
}
// Add remaining unmatched connections
for i < len(conns1) {
conns = append(conns, conns1[i])
i++
}
for same && j < len(conns2) {
conns = append(conns, conns2[j])
j++
}
return
}
func crossTraits(rng evo.Random, traits1, traits2 []float64) (traits []float64) {
traits = make([]float64, len(traits1))
for i := 0; i < len(traits); i++ {
if rng.Float64() < 0.5 {
traits[i] = traits1[i]
} else {
traits[i] = traits2[i]
}
}
return
} | neat/crosser.go | 0.506103 | 0.466056 | crosser.go | starcoder |
package smf_context
type UEPathGraph struct {
SUPI string
Graph []*UEPathNode
}
type UEPathNode struct {
UPFName string
Parent string
Neighbors map[string]*UEPathNode
IsBranchingPoint bool
EndPointOfEachChild map[string]*UEPathEndPoint
}
type UEPathEndPoint struct {
EndPointIP string
EndPointPort string
}
func (node *UEPathNode) AddNeighbor(neighbor *UEPathNode) {
//check if neighbor exist first
if _, exist := node.Neighbors[neighbor.UPFName]; !exist {
node.Neighbors[neighbor.UPFName] = neighbor
}
}
//Add End Point Info to of child node to the map "EndPointOfEachChild"
//If the node is leaf node, it will add the end point info for itself name.
func (node *UEPathNode) AddEndPointOfChild(neighbor *UEPathNode, EndPoint *UEPathEndPoint) {
if _, exist := node.EndPointOfEachChild[neighbor.UPFName]; !exist {
node.EndPointOfEachChild[neighbor.UPFName] = EndPoint
}
}
func (node *UEPathNode) RmbParent(parent string) {
node.Parent = parent
}
func (node *UEPathNode) GetChild() []*UEPathNode {
child := make([]*UEPathNode, 0)
for upfName, upfNode := range node.Neighbors {
if upfName != node.Parent {
child = append(child, upfNode)
}
}
return child
}
func (node *UEPathNode) IsLeafNode() bool {
if len(node.Neighbors) == 1 {
if _, exist := node.Neighbors[node.Parent]; exist {
return true
}
}
return false
}
func NewUEPathNode(name string) (node *UEPathNode) {
node = &UEPathNode{
UPFName: name,
Neighbors: make(map[string]*UEPathNode),
EndPointOfEachChild: make(map[string]*UEPathEndPoint),
IsBranchingPoint: false,
}
return
}
//check a given upf name is a branching point or not
func (uepg *UEPathGraph) IsBranchingPoint(name string) bool {
for _, upfNode := range uepg.Graph {
if name == upfNode.UPFName {
return upfNode.IsBranchingPoint
}
}
return false
}
func NewUEPathGraph(SUPI string) (UEPGraph *UEPathGraph) {
UEPGraph = new(UEPathGraph)
UEPGraph.Graph = make([]*UEPathNode, 0)
UEPGraph.SUPI = SUPI
paths := smfContext.UERoutingPaths[SUPI]
lowerBound := 0
NodeCreated := make(map[string]*UEPathNode)
for _, path := range paths {
upperBound := len(path.UPF) - 1
pathEndPoint := &UEPathEndPoint{
EndPointIP: path.DestinationIP,
EndPointPort: path.DestinationPort,
}
for idx, node_name := range path.UPF {
var ue_node *UEPathNode
var child_node *UEPathNode
var parent_node *UEPathNode
var exist bool
if ue_node, exist = NodeCreated[node_name]; !exist {
ue_node = NewUEPathNode(node_name)
NodeCreated[node_name] = ue_node
UEPGraph.Graph = append(UEPGraph.Graph, ue_node)
}
switch idx {
case lowerBound:
child_name := path.UPF[idx+1]
if child_node, exist = NodeCreated[child_name]; !exist {
child_node = NewUEPathNode(child_name)
NodeCreated[child_name] = child_node
UEPGraph.Graph = append(UEPGraph.Graph, child_node)
}
ue_node.AddNeighbor(child_node)
ue_node.AddEndPointOfChild(child_node, pathEndPoint)
case upperBound:
parent_name := path.UPF[idx-1]
if parent_node, exist = NodeCreated[parent_name]; !exist {
parent_node = NewUEPathNode(parent_name)
NodeCreated[parent_name] = parent_node
UEPGraph.Graph = append(UEPGraph.Graph, parent_node)
}
ue_node.AddNeighbor(parent_node)
ue_node.AddEndPointOfChild(ue_node, pathEndPoint)
ue_node.RmbParent(parent_name)
default:
child_name := path.UPF[idx+1]
if child_node, exist = NodeCreated[child_name]; !exist {
child_node = NewUEPathNode(child_name)
NodeCreated[child_name] = child_node
UEPGraph.Graph = append(UEPGraph.Graph, child_node)
}
parent_name := path.UPF[idx-1]
if parent_node, exist = NodeCreated[parent_name]; !exist {
parent_node = NewUEPathNode(parent_name)
NodeCreated[parent_name] = parent_node
UEPGraph.Graph = append(UEPGraph.Graph, parent_node)
}
ue_node.AddNeighbor(child_node)
ue_node.AddEndPointOfChild(child_node, pathEndPoint)
ue_node.AddNeighbor(parent_node)
ue_node.RmbParent(parent_name)
}
}
}
return
}
func (uepg *UEPathGraph) FindBranchingPoints() {
//BFS algo implementation
const (
WHITE int = 0
GREY int = 1
BLACK int = 2
)
num_of_nodes := len(uepg.Graph)
color := make(map[string]int)
distance := make(map[string]int)
queue := make(chan *UEPathNode, num_of_nodes)
for _, node := range uepg.Graph {
color[node.UPFName] = WHITE
distance[node.UPFName] = num_of_nodes + 1
}
cur_idx := 0 // start point
for j := 0; j < num_of_nodes; j++ {
cur_name := uepg.Graph[cur_idx].UPFName
if color[cur_name] == WHITE {
color[cur_name] = GREY
distance[cur_name] = 0
queue <- uepg.Graph[cur_idx]
for len(queue) > 0 {
node := <-queue
branchingCount := 0
for neighbor_name, neighbor_node := range node.Neighbors {
if color[neighbor_name] == WHITE {
color[neighbor_name] = GREY
distance[neighbor_name] = distance[cur_name] + 1
queue <- neighbor_node
}
if color[neighbor_name] == WHITE || color[neighbor_name] == GREY {
branchingCount += 1
}
}
if branchingCount >= 2 {
node.IsBranchingPoint = true
}
color[node.UPFName] = BLACK
}
}
//Keep finding other connected components
cur_idx = j
}
} | src/smf/smf_context/ue_path.go | 0.523177 | 0.449695 | ue_path.go | starcoder |
package nonogen
import (
"errors"
"fmt"
"image"
"image/color"
"image/jpeg"
"os"
"github.com/nfnt/resize"
)
func drawLine(x1, x2, y int, img image.RGBA, color color.Color) {
for ; x1 < x2; x1++ {
img.Set(x1, y, color)
}
}
func drawVerticalLine(y1, y2, x int, img image.RGBA, color color.Color) {
for ; y1 < y2; y1++ {
img.Set(x, y1, color)
}
}
func drawRect(x, y, x2, y2 int, img image.RGBA, color color.Color) {
for ; y < y2; y++ {
drawLine(x, x2, y, img, color)
}
}
func imgToGrayScale(originImg image.Image) *image.RGBA {
bounds := originImg.Bounds()
BWImg := image.NewRGBA(bounds)
for y := 0; y < bounds.Max.Y; y++ {
for x := 0; x < bounds.Max.X; x++ {
oldPixel := originImg.At(x, y)
pixel := color.GrayModel.Convert(oldPixel)
BWImg.Set(x, y, pixel)
}
}
return BWImg
}
func NonoToJPG(nono [][]int, name string) {
size := 10
sizeY := len(nono)
sizeX := len(nono[0])
img := image.NewRGBA(image.Rect(0, 0, sizeX*size, sizeY*size))
for y := 0; y < sizeY; y++ {
for x := 0; x < sizeX; x++ {
if nono[y][x] == 1 {
drawRect(x*size, y*size, x*size+size, y*size+size, *img, color.Black)
} else {
drawRect(x*size, y*size, x*size+size, y*size+size, *img, color.White)
}
}
}
for i := 1; i < sizeY; i++ {
drawLine(0, size*sizeX, i*size, *img, color.RGBA{255, 0, 0, 1})
}
for i := 1; i < sizeX; i++ {
drawVerticalLine(0, size*sizeY, i*size, *img, color.RGBA{255, 0, 0, 1})
}
JpgDraw(name, img)
}
func JpgDraw(name string, img image.Image) {
var opt jpeg.Options
opt.Quality = 75
out, err := os.Create(name)
err = jpeg.Encode(out, img, &opt)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func resizeImg(originImg image.Image, size int) (image.Image, error) {
bounds := originImg.Bounds()
if size > bounds.Max.Y {
fmt.Println("Requested size is too big")
return nil, errors.New("Requested size is too big")
}
if size < 5 {
fmt.Println("Requested size is too small")
return nil, errors.New("Requested size is too small")
}
sizeX := bounds.Max.X / (bounds.Max.Y / size)
desiredX := (bounds.Max.Y / size) * sizeX
desiredY := (bounds.Max.Y / size) * size
originImg = resize.Resize(uint(desiredX), uint(desiredY), originImg, resize.Lanczos3)
return originImg, nil
} | draw.go | 0.502197 | 0.452173 | draw.go | starcoder |
package core
import (
"unsafe"
)
// PrimitiveType is a raster primitive type.
type PrimitiveType uint8
// Supported primitive types
const (
PrimitiveTypeTriangles PrimitiveType = iota
PrimitiveTypePoints
PrimitiveTypeLines
)
// Mesh is an interface which wraps handling of geometry.
type Mesh interface {
SetPrimitiveType(PrimitiveType)
SetPositions(positions []float32)
SetNormals(normals []float32)
SetTextureCoordinates(coordinates []float32)
SetIndices(indices []uint16)
SetName(name string)
Name() string
Draw()
DrawInstanced(int, unsafe.Pointer)
Bounds() *AABB
Lt(Mesh) bool
Gt(Mesh) bool
}
var (
aabbMesh Mesh
)
// NewScreenQuadMesh returns a mesh to be drawn by an orthographic projection camera.
func NewScreenQuadMesh(width, height float32) Mesh {
positions := []float32{
width * 0.0, height * 0.0, 0.0,
width * 1.0, height * 0.0, 0.0,
width * 1.0, height * 1.0, 0.0,
width * 0.0, height * 1.0, 0.0,
}
normals := []float32{
0.0, 0.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 0.0, 0.0,
}
tcoords := []float32{
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 0.0, 0.0,
0.0, 0.0, 0.0,
}
indices := []uint16{0, 1, 2, 2, 3, 0}
m := renderSystem.NewMesh()
m.SetPrimitiveType(PrimitiveTypeTriangles)
m.SetPositions(positions)
m.SetNormals(normals)
m.SetTextureCoordinates(tcoords)
m.SetIndices(indices)
m.SetName("ScreenQuadMesh")
return m
}
// AABBMesh returns a normalized cube centered at the origin. This is
// used to draw bounding boxes by translating and scaling it according to node bounds.
func AABBMesh() Mesh {
if aabbMesh != nil {
return aabbMesh
}
positions := []float32{
-0.5, -0.5, -0.5,
+0.5, -0.5, -0.5,
+0.5, +0.5, -0.5,
-0.5, +0.5, -0.5,
-0.5, -0.5, +0.5,
+0.5, -0.5, +0.5,
+0.5, +0.5, +0.5,
-0.5, +0.5, +0.5,
}
indices := []uint16{
0, 1,
1, 2,
2, 3,
3, 0,
4, 5,
5, 6,
6, 7,
7, 4,
0, 4,
1, 5,
2, 6,
3, 7}
aabbMesh = renderSystem.NewMesh()
aabbMesh.SetPrimitiveType(PrimitiveTypeLines)
aabbMesh.SetPositions(positions)
aabbMesh.SetNormals(positions)
aabbMesh.SetTextureCoordinates(positions)
aabbMesh.SetIndices(indices)
aabbMesh.SetName("AABB")
return aabbMesh
} | core/mesh.go | 0.77081 | 0.44342 | mesh.go | starcoder |
package histogram
const (
// Label holds the string label denoting the histogram type in the database.
Label = "histogram"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldTime holds the string denoting the time field in the database.
FieldTime = "time"
// FieldCount holds the string denoting the count field in the database.
FieldCount = "count"
// FieldMin holds the string denoting the min field in the database.
FieldMin = "min"
// FieldMax holds the string denoting the max field in the database.
FieldMax = "max"
// FieldMean holds the string denoting the mean field in the database.
FieldMean = "mean"
// FieldStddev holds the string denoting the stddev field in the database.
FieldStddev = "stddev"
// FieldMedian holds the string denoting the median field in the database.
FieldMedian = "median"
// FieldP75 holds the string denoting the p75 field in the database.
FieldP75 = "p75"
// FieldP95 holds the string denoting the p95 field in the database.
FieldP95 = "p95"
// FieldP99 holds the string denoting the p99 field in the database.
FieldP99 = "p99"
// FieldP999 holds the string denoting the p999 field in the database.
FieldP999 = "p999"
// FieldWID holds the string denoting the wid field in the database.
FieldWID = "w_id"
// EdgeMetric holds the string denoting the metric edge name in mutations.
EdgeMetric = "metric"
// Table holds the table name of the histogram in the database.
Table = "histograms"
// MetricTable is the table the holds the metric relation/edge.
MetricTable = "histograms"
// MetricInverseTable is the table name for the Metric entity.
// It exists in this package in order to avoid circular dependency with the "metric" package.
MetricInverseTable = "metrics"
// MetricColumn is the table column denoting the metric relation/edge.
MetricColumn = "metric_histograms"
)
// Columns holds all SQL columns for histogram fields.
var Columns = []string{
FieldID,
FieldTime,
FieldCount,
FieldMin,
FieldMax,
FieldMean,
FieldStddev,
FieldMedian,
FieldP75,
FieldP95,
FieldP99,
FieldP999,
FieldWID,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the Histogram type.
var ForeignKeys = []string{
"metric_histograms",
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
} | ent/histogram/histogram.go | 0.606615 | 0.430327 | histogram.go | starcoder |
package russian
var (
centuryNumberCase = [3]string{"век", "века", "веков"}
yearNumberCase = [3]string{"год", "года", "лет"}
monthNumberCase = [3]string{"месяц", "месяца", "месяцев"}
weekNumberCase = [3]string{"неделя", "недели", "недель"}
dayNumberCase = [3]string{"день", "дня", "дней"}
hourNumberCase = [3]string{"час", "часа", "часов"}
minuteNumberCase = [3]string{"минута", "минуты", "минут"}
secondNumberCase = [3]string{"секунда", "секунды", "секунд"}
millisecondNumberCase = [3]string{"миллисекунда", "миллисекунды", "миллисекунд"}
microsecondNumberCase = [3]string{"микросекунда", "микросекунды", "микросекунд"}
nanosecondNumberCase = [3]string{"наносекунда", "наносекунды", "наносекунд"}
)
// Centuries returns russian for "century" corresponding to 'n'.
func Centuries(n int64) string {
return centuryNumberCase[getNumeralNumberCase(n)]
}
// NCenturies returns string containing 'n' and corresponding russian for "century".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NCenturies(n int64, showZero bool) string {
return IntAndItems(n, showZero, Centuries(n))
}
// NInWordsCenturies returns string containing 'n' in russian words and corresponding russian for "century".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsCenturies(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Masculine, Centuries(n))
}
// Years returns russian for "year" corresponding to 'n'.
func Years(n int64) string {
return yearNumberCase[getNumeralNumberCase(n)]
}
// NYears returns string containing 'n' and corresponding russian for "year".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NYears(n int64, showZero bool) string {
return IntAndItems(n, showZero, Years(n))
}
// NInWordsYears returns string containing 'n' in russian words and corresponding russian for "year".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsYears(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Masculine, Years(n))
}
// Months returns russian for "month" corresponding to 'n'.
func Months(n int64) string {
return monthNumberCase[getNumeralNumberCase(n)]
}
// NMonths returns string containing 'n' and corresponding russian for "month".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NMonths(n int64, showZero bool) string {
return IntAndItems(n, showZero, Months(n))
}
// NInWordsMonths returns string containing 'n' in russian words and corresponding russian for "month".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsMonths(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Masculine, Months(n))
}
// Weeks returns russian for "week" corresponding to 'n'.
func Weeks(n int64) string {
return weekNumberCase[getNumeralNumberCase(n)]
}
// NWeeks returns string containing 'n' and corresponding russian for "week".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NWeeks(n int64, showZero bool) string {
return IntAndItems(n, showZero, Weeks(n))
}
// NInWordsWeeks returns string containing 'n' in russian words and corresponding russian for "week".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsWeeks(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Feminine, Weeks(n))
}
// Days returns russian for "day" corresponding to 'n'.
func Days(n int64) string {
return dayNumberCase[getNumeralNumberCase(n)]
}
// NDays returns string containing 'n' and corresponding russian for "day".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NDays(n int64, showZero bool) string {
return IntAndItems(n, showZero, Days(n))
}
// NInWordsDays returns string containing 'n' in russian words and corresponding russian for "day".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsDays(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Masculine, Days(n))
}
// Hours returns russian for "hour" corresponding to 'n'.
func Hours(n int64) string {
return hourNumberCase[getNumeralNumberCase(n)]
}
// NHours returns string containing 'n' and corresponding russian for "hour".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NHours(n int64, showZero bool) string {
return IntAndItems(n, showZero, Hours(n))
}
// NInWordsHours returns string containing 'n' in russian words and corresponding russian for "hour".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsHours(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Masculine, Hours(n))
}
// Minutes returns russian for "minute" corresponding to 'n'.
func Minutes(n int64) string {
return minuteNumberCase[getNumeralNumberCase(n)]
}
// NMinutes returns string containing 'n' and corresponding russian for "minute".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NMinutes(n int64, showZero bool) string {
return IntAndItems(n, showZero, Minutes(n))
}
// NInWordsMinutes returns string containing 'n' in russian words and corresponding russian for "minute".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsMinutes(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Feminine, Minutes(n))
}
// Seconds returns russian for "second" corresponding to 'n'.
func Seconds(n int64) string {
return secondNumberCase[getNumeralNumberCase(n)]
}
// NSeconds returns string containing 'n' and corresponding russian for "second".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NSeconds(n int64, showZero bool) string {
return IntAndItems(n, showZero, Seconds(n))
}
// NInWordsSeconds returns string containing 'n' in russian words and corresponding russian for "second".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsSeconds(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Feminine, Seconds(n))
}
// Milliseconds returns russian for "millisecond" corresponding to 'n'.
func Milliseconds(n int64) string {
return millisecondNumberCase[getNumeralNumberCase(n)]
}
// NMilliseconds returns string containing 'n' and corresponding russian for "millisecond".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NMilliseconds(n int64, showZero bool) string {
return IntAndItems(n, showZero, Milliseconds(n))
}
// NInWordsMilliseconds returns string containing 'n' in russian words and corresponding russian for "millisecond".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsMilliseconds(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Feminine, Milliseconds(n))
}
// Microseconds returns russian for "microsecond" corresponding to 'n'.
func Microseconds(n int64) string {
return microsecondNumberCase[getNumeralNumberCase(n)]
}
// NMicroseconds returns string containing 'n' and corresponding russian for "microsecond".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NMicroseconds(n int64, showZero bool) string {
return IntAndItems(n, showZero, Microseconds(n))
}
// NInWordsMicroseconds returns string containing 'n' in russian words and corresponding russian for "microsecond".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsMicroseconds(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Feminine, Microseconds(n))
}
// Nanoseconds returns russian for "nanosecond" corresponding to 'n'.
func Nanoseconds(n int64) string {
return nanosecondNumberCase[getNumeralNumberCase(n)]
}
// NNanoseconds returns string containing 'n' and corresponding russian for "nanosecond".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
func NNanoseconds(n int64, showZero bool) string {
return IntAndItems(n, showZero, Nanoseconds(n))
}
// NInWordsNanoseconds returns string containing 'n' in russian words and corresponding russian for "nanosecond".
// If 'n' is 0 and 'showZero' is false, empty string is returned.
// If 'withZero' is false, zero triples are omitted.
func NInWordsNanoseconds(n int64, showZero, withZero bool) string {
return IntInWordsAndItems(n, showZero, withZero, Feminine, Nanoseconds(n))
} | russian/time.go | 0.688573 | 0.643581 | time.go | starcoder |
package arbitrage
import (
"fmt"
"math"
"time"
"gotrading/core"
"gotrading/networking"
)
type Simulation struct {
hits []*core.Hit
Report Report
}
func (sim *Simulation) Init(hits []*core.Hit) {
sim.hits = make([]*core.Hit, len(hits))
for i, h := range hits {
copy := *h
sim.hits[i] = ©
}
sim.Report = Report{}
}
func (sim *Simulation) Run() {
r := &sim.Report
r.SimulationStartedAt = time.Now()
r.IsSimulationIncomplete = false
batch := networking.Batch{}
batch.GetOrderbooks(sim.hits, func(orderbooks []*core.Orderbook) {
r.SimulationComputingStartedAt = time.Now()
r.Cost = 0
r.Rates = make([]float64, len(sim.hits))
r.AdjustedVolumes = make([]float64, len(sim.hits))
r.IsSimulationSuccessful = true
r.Orders = make([]core.Order, len(sim.hits))
fromInitialToCurrent := float64(1)
// rateForInitialCurrency := float64(1) // How many INITIAL_CURRENCY are we getting for 1 CURRENT_CURRENCY
m := core.SharedPortfolioManager()
for i, n := range sim.hits {
orderbook := orderbooks[i]
n.Endpoint.Orderbook = orderbook
if orderbook == nil {
sim.Abort()
return
}
var priceOfCurrencyToSell float64
var volumeOfCurrencyToSell float64
var order core.Order
if n.IsBaseToQuote {
// We are selling the base -> we match the Bid.
if len(orderbook.Bids) > 0 {
bestBid := orderbook.Bids[0]
o, err := bestBid.CreateMatchingAsk()
if err == nil {
order = *o
priceOfCurrencyToSell = order.Price
volumeOfCurrencyToSell = order.BaseVolume
} else {
sim.Abort()
return
}
} else {
sim.Abort()
return
}
} else {
// We are selling the quote <=> we are buying the base -> we match the Ask.
if len(orderbook.Asks) > 0 {
bestAsk := orderbook.Asks[0]
o, err := bestAsk.CreateMatchingBid()
if err == nil {
order = *o
priceOfCurrencyToSell = order.PriceOfQuoteToBase
volumeOfCurrencyToSell = order.QuoteVolume
} else {
sim.Abort()
return
}
} else {
sim.Abort()
return
}
}
fromInitialToCurrent = fromInitialToCurrent * priceOfCurrencyToSell
r.Rates[i] = fromInitialToCurrent
r.Performance = fromInitialToCurrent
decimals := n.Endpoint.Exchange.ExchangeSettings.PairsSettings[orderbook.CurrencyPair].BasePrecision
if i == 0 {
initialBalance := m.CurrentPosition(n.Endpoint.Exchange.Name, n.SoldCurrency)
initialBalance = initialBalance - (initialBalance * 0.25)
volumeToCeil := math.Min(initialBalance, volumeOfCurrencyToSell)
r.VolumeToEngage = ceilf(volumeToCeil, decimals)
} else {
limitingAmount := r.VolumeToEngage * fromInitialToCurrent
currentAmount := volumeOfCurrencyToSell * priceOfCurrencyToSell
newLimitingAmount := math.Min(limitingAmount, currentAmount)
r.VolumeToEngage = newLimitingAmount / fromInitialToCurrent
}
order.Hit = n
r.Orders[i] = order
}
for i, n := range sim.hits {
var currentVolumeToEngage float64
if i == 0 {
currentVolumeToEngage = r.VolumeToEngage
} else {
if sim.hits[i-1].IsBaseToQuote {
currentVolumeToEngage = r.Orders[i-1].QuoteVolumeOut
} else if r.Orders[i-1].TransactionType == core.Bid {
currentVolumeToEngage = r.Orders[i-1].BaseVolumeOut
}
}
if n.IsBaseToQuote {
r.AdjustedVolumes[i] = currentVolumeToEngage * r.Orders[i].Price
} else {
r.AdjustedVolumes[i] = currentVolumeToEngage * r.Orders[i].PriceOfQuoteToBase
}
if n.IsBaseToQuote {
r.Orders[i].UpdateQuoteVolume(r.AdjustedVolumes[i])
} else {
r.Orders[i].UpdateBaseVolume(r.AdjustedVolumes[i])
}
r.Cost = r.Cost + r.Orders[i].Fee*r.Rates[i]
}
firstOrder := r.Orders[0]
if firstOrder.TransactionType == core.Bid {
r.VolumeIn = firstOrder.QuoteVolumeIn
} else {
r.VolumeIn = firstOrder.BaseVolumeIn
}
lastOrder := r.Orders[len(r.Orders)-1]
if lastOrder.TransactionType == core.Bid {
r.VolumeOut = lastOrder.BaseVolumeOut
} else {
r.VolumeOut = lastOrder.QuoteVolumeOut
}
fmt.Println(r.VolumeIn, r.VolumeOut)
r.SimulatedProfit = core.Trunc8(r.VolumeOut - r.VolumeIn)
if r.VolumeIn < 0.0001 || r.VolumeOut < 0.0001 {
fmt.Println("Traded volume under threshold")
r.IsTradedVolumeEnough = false
r.IsSimulationSuccessful = false
r.SimulationEndedAt = time.Now()
return
}
r.IsTradedVolumeEnough = true
r.Performance = r.VolumeOut / r.VolumeIn
r.SimulationEndedAt = time.Now()
r.IsSimulationSuccessful = r.SimulatedProfit > 0.0
})
}
func ceilf(v float64, d int) float64 {
df := float64(d)
return math.Ceil(v*math.Pow(10, df)) / math.Pow(10, df)
}
func (sim *Simulation) Abort() {
r := &sim.Report
r.IsSimulationSuccessful = false
r.SimulationEndedAt = time.Now()
r.IsSimulationIncomplete = true
}
func (sim *Simulation) IsSuccessful() bool {
return sim.Report.IsSimulationSuccessful && sim.Report.IsTradedVolumeEnough
}
func (sim *Simulation) IsExecutable() bool {
return sim.Report.IsSimulationIncomplete == false && sim.Report.IsTradedVolumeEnough
} | strategies/arbitrage/simulation.go | 0.526586 | 0.437343 | simulation.go | starcoder |
package horizon
import (
"fmt"
"math"
"github.com/golang/geo/s2"
geojson "github.com/paulmach/go.geojson"
)
// calcProjection Returns projection on line and fraction for point
/*
line - s2.Polyline
point - s2.Point
projected - projection of point on line
fraction - number in [0;1], describes how far projected point from first point of polyline
*/
func calcProjection(line s2.Polyline, point s2.Point) (projected s2.Point, fraction float64) {
pr, next := line.Project(point)
subs := s2.Polyline{}
for i := 0; i < next; i++ {
subs = append(subs, line[i])
}
subs = append(subs, pr)
return pr, (subs.Length() / line.Length()).Radians()
}
// round Round float64
func round(num float64) int {
return int(num + math.Copysign(0.5, num))
}
// toFixed Round float64 to N decimal places
func toFixed(num float64, precision int) float64 {
output := math.Pow(10, float64(precision))
return float64(round(num*output)) / output
}
// GeoJSONToS2PolylineFeature Returns *s2.Polyline representation of *geojson.Geometry (of LineString type)
func GeoJSONToS2PolylineFeature(pts *geojson.Geometry) (*s2.Polyline, error) {
latLngs := []s2.LatLng{}
if pts.Type == "LineString" {
for i := range pts.LineString {
latLng := s2.LatLngFromDegrees(pts.LineString[i][1], pts.LineString[i][0])
latLngs = append(latLngs, latLng)
}
} else {
return nil, fmt.Errorf("Type of geometry is: %s. Expected: 'LineString'", pts.Type)
}
return s2.PolylineFromLatLngs(latLngs), nil
}
// S2PolylineToGeoJSONFeature Returns GeoJSON representation of *s2.Polyline
func S2PolylineToGeoJSONFeature(pts *s2.Polyline) *geojson.Feature {
coordinates := make([][]float64, len(*pts))
for i := range *pts {
latLng := s2.LatLngFromPoint((*pts)[i])
coordinates[i] = []float64{latLng.Lng.Degrees(), latLng.Lat.Degrees()}
}
return geojson.NewLineStringFeature(coordinates)
}
// S2PointToGeoJSONFeature Returns GeoJSON representation of *s2.Point
func S2PointToGeoJSONFeature(pt *s2.Point) *geojson.Feature {
latLng := s2.LatLngFromPoint(*pt)
return geojson.NewPointFeature([]float64{latLng.Lng.Degrees(), latLng.Lat.Degrees()})
} | utils.go | 0.802981 | 0.49109 | utils.go | starcoder |
package data
import (
"math"
"time"
"github.com/chewxy/math32"
)
func getCurrentTime() uint64 {
return uint64(time.Now().Unix())
}
// CalculateAverage calculates average of two arrays divided by n
func CalculateAverage(avg []float32, p []float32, n float32) []float32 {
if n == 0 {
return p
}
if len(avg) < len(p) {
avg = make([]float32, len(p))
}
for i := 0; i < len(p); i++ {
avg[i] += p[i] / n
}
return avg
}
func QuickVectorDistance(arr1 []float32, arr2 []float32) float64 {
minLen := min(len(arr1), len(arr2))
var ret float64
for i := 0; i < minLen; i++ {
tmp := arr1[i] - arr2[i]
ret += float64(math32.Abs(tmp))
}
return ret
}
// VectorDistance calculates distance of two vector by euclidean distance
func VectorDistance(arr1 []float32, arr2 []float32) float64 {
minLen := min(len(arr1), len(arr2))
d := euclideanDistance(arr1[:minLen], arr2[:minLen])
return d
}
// VectorMultiplication calculates elementwise of multiplication of two vectors
func VectorMultiplication(arr1 []float32, arr2 []float32) float64 {
minLen := min(len(arr1), len(arr2))
var ret float32
for i := 0; i < minLen; i++ {
ret += arr1[i] * arr2[i]
}
return float64(ret)
}
// AngularDistance sim(u.v) = (1 - arccos(cosine_similarity(u, v)) / pi)
func AngularDistance(a []float32, b []float32) float64 {
return 1.0 - (math.Acos(CosineSimilarity(a, b)) / math.Pi)
}
// CosineSimilarity for vector similarity
func CosineSimilarity(a []float32, b []float32) float64 {
count := 0
lengthA := len(a)
lengthB := len(b)
if lengthA > lengthB {
count = lengthA
} else {
count = lengthB
}
sumA := float32(0.0)
s1 := float32(0.0)
s2 := float32(0.0)
for k := 0; k < count; k++ {
if k >= lengthA {
s2 += b[k] * b[k] // math32.Pow(b[k], 2)
continue
}
if k >= lengthB {
s1 += a[k] * a[k] // math32.Pow(a[k], 2)
continue
}
sumA += a[k] * b[k]
s1 += a[k] * a[k] // math32.Pow(a[k], 2)
s2 += b[k] * b[k] //math32.Pow(b[k], 2)
}
if s1 == 0 || s2 == 0 {
return 0.0
}
similarity := float64(sumA / (math32.Sqrt(s1) * math32.Sqrt(s2)))
if similarity > 1 {
similarity = 1.0
} else if similarity < -1.0 {
similarity = -1.0
}
return similarity
}
// CosineSimilarity64 for vector similarity
func CosineSimilarity64(a []float64, b []float64) float64 {
count := 0
lengthA := len(a)
lengthB := len(b)
if lengthA > lengthB {
count = lengthA
} else {
count = lengthB
}
sumA := 0.0
s1 := 0.0
s2 := 0.0
for k := 0; k < count; k++ {
if k >= lengthA {
s2 += math.Pow(b[k], 2)
continue
}
if k >= lengthB {
s1 += math.Pow(a[k], 2)
continue
}
sumA += a[k] * b[k]
s1 += math.Pow(a[k], 2)
s2 += math.Pow(b[k], 2)
}
if s1 == 0 || s2 == 0 {
return 0.0
}
return sumA / (math.Sqrt(s1) * math.Sqrt(s2))
}
// CosineSimilarity for vector similarity
func CosineSimilarity32(a []float32, b []float32) float32 {
count := 0
lengthA := len(a)
lengthB := len(b)
if lengthA > lengthB {
count = lengthA
} else {
count = lengthB
}
sumA := float32(0.0)
s1 := float32(0.0)
s2 := float32(0.0)
for k := 0; k < count; k++ {
if k >= lengthA {
s2 += b[k] * b[k]
continue
}
if k >= lengthB {
s1 += a[k] * a[k]
continue
}
sumA += a[k] * b[k]
s1 += a[k] * a[k]
s2 += b[k] * b[k]
}
if s1 == 0 || s2 == 0 {
return 0.0
}
return sumA / float32(math.Sqrt(float64(s1))*math.Sqrt(float64(s2)))
}
func euclideanDistance(arr1 []float32, arr2 []float32) float64 {
var ret float32
for i := 0; i < len(arr1); i++ {
tmp := arr1[i] - arr2[i]
ret += math32.Pow(tmp, 2)
}
return math.Sqrt(float64(ret)) // Sqrt is totally unnecessary for comparisons
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func minUint64(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func sum(arr []float64) float64 {
sum := 0.0
for _, e := range arr {
sum += e
}
return sum
} | data/util.go | 0.569374 | 0.547706 | util.go | starcoder |
package relationship
// Type is a type of relationship
type Type struct {
Name string
Descriptors []string
InverseName string
Disallows []string
}
// AllTypes returns all relationship types
func AllTypes() []Type {
types := []Type{
{
Name: "parent",
InverseName: "child",
Disallows: []string{},
Descriptors: []string{
"is a parent of",
"is parent of",
},
},
{
Name: "child",
InverseName: "parent",
Disallows: []string{},
Descriptors: []string{
"is a child of",
"is the child of",
"is child of",
},
},
{
Name: "friend",
InverseName: "friend",
Disallows: []string{
"enemy",
"lover",
},
Descriptors: []string{
"is a confidant of",
"is a friend of",
"is an ally of",
},
},
{
Name: "enemy",
InverseName: "enemy",
Disallows: []string{
"friend",
"lover",
},
Descriptors: []string{
"is the enemy of",
"is the hated foe of",
"wars against",
},
},
{
Name: "lover",
InverseName: "lover",
Disallows: []string{
"enemy",
"friend",
},
Descriptors: []string{
"desires",
"is a lover of",
"loves",
"trysts with",
},
},
{
Name: "negative opinion",
InverseName: "negative opinion",
Disallows: []string{
"friend",
"lover",
"positive opinion",
},
Descriptors: []string{
"despises",
"dislikes",
"distrusts",
"envies",
"fears",
"hates",
"is bored by",
"is chagrined by",
"is suspicious of",
"suspects",
"tends to avoid",
"worries about",
},
},
{
Name: "positive opinion",
InverseName: "positive opinion",
Disallows: []string{
"negative opinion",
"enemy",
},
Descriptors: []string{
"cherishes",
"enjoys the company of",
"is amused by",
"is hopeful for",
"owes a debt to",
"respects",
"supports",
"trusts",
},
},
{
Name: "rival",
InverseName: "rival",
Disallows: []string{},
Descriptors: []string{
"fights with",
"is the rival of",
},
},
}
return types
} | pkg/relationship/types.go | 0.517083 | 0.450299 | types.go | starcoder |
package model
import (
"encoding/json"
"fmt"
"regexp"
"github.com/kosctelecom/horus/log"
)
// IndexedMeasure is a group of tabular metrics indexed by the first one.
type IndexedMeasure struct {
// ID is the measure db id.
ID int `db:"id"`
// Name is the name of the indexed measure.
Name string `db:"name"`
// Description is the description of the indexed measure.
Description string `db:"description"`
// Metrics is the list of metrics forming this measure.
Metrics []Metric
// IndexMetricID is the id of the metric used as index.
IndexMetricID NullInt64 `db:"index_metric_id"`
// IndexPos is the position of the index metric in the Metrics array.
IndexPos int `db:"-"`
// FilterPattern is the regex pattern used to filter the IndexedResults of this metric group.
// It can be used to only keep results from interesting interfaces.
FilterPattern string `db:"filter_pattern"`
// FilterMetricID is the id of the metric on which the filter is applied.
FilterMetricID NullInt64 `db:"filter_metric_id"`
// FilterPos is the index of the filter metric in the Metrics array.
FilterPos int `db:"-"`
// InvertFilterMatch negates the match result of the FilterPattern.
InvertFilterMatch bool `db:"invert_filter_match"`
// FilterRegex is the compiled FilterPattern pattern.
FilterRegex *regexp.Regexp `db:"-" json:"-"`
// UseAlternateCommunity tells wether to use the alternate community for all metrics of this measure.
UseAlternateCommunity bool `db:"use_alternate_community"`
// ToKafka is a flag telling if the results are exported to Kafka.
ToKafka bool `db:"to_kafka"`
// ToProm tells if the results are kept for Prometheus scraping.
ToProm bool `db:"to_prometheus"`
// ToInflux is a flag telling if the results are exported to InfluxDB.
ToInflux bool `db:"to_influx"`
// ToNats is a flag telling if the results are exported to NATS.
ToNats bool `db:"to_nats"`
// LabelsOnly tell wehere this measure contains only labels.
LabelsOnly bool `db:"-"`
}
// UnmarshalJSON unserializes data into an IndexedMetric.
// Checks specifically if the filter index and pattern are valid.
func (x *IndexedMeasure) UnmarshalJSON(data []byte) error {
type IM IndexedMeasure
var im IM
if err := json.Unmarshal(data, &im); err != nil {
return err
}
im.IndexPos = -1
if im.IndexMetricID.Valid {
for i, metric := range im.Metrics {
if int64(metric.ID) == im.IndexMetricID.Int64 {
im.IndexPos = i
break
}
}
if im.IndexPos == -1 {
return fmt.Errorf("indexed measure %s: IndexMetricID %d not found in metric list", im.Name, im.IndexMetricID.Int64)
}
}
if im.FilterPattern != "" && !im.FilterMetricID.Valid {
return fmt.Errorf("indexed measure %s: FilterMetricID cannot be null when FilterPattern is defined", im.Name)
}
if im.FilterPattern == "" && im.FilterMetricID.Valid {
return fmt.Errorf("indexed measure %s: FilterPattern cannot be empty when FilterMetricID is defined", im.Name)
}
im.FilterPos = -1
if im.FilterPattern != "" {
for i, metric := range im.Metrics {
if int64(metric.ID) == im.FilterMetricID.Int64 {
im.FilterPos = i
break
}
}
if im.FilterPos == -1 {
return fmt.Errorf("indexed measure: invalid FilterMetricID %d, not in metric list", im.FilterMetricID.Int64)
}
var err error
if im.FilterRegex, err = regexp.Compile(im.FilterPattern); err != nil {
return fmt.Errorf("invalid filter regexp: %v", err)
}
}
*x = IndexedMeasure(im)
return nil
}
// RemoveInactive filters out all metrics of this indexed measure that are marked as inactive.
func (x *IndexedMeasure) RemoveInactive() {
filtered := x.Metrics[:0]
for _, metric := range x.Metrics {
if metric.Active {
filtered = append(filtered, metric)
}
}
if x.IndexMetricID.Valid {
// recompute index position
for i, metric := range filtered {
if int64(metric.ID) == x.IndexMetricID.Int64 {
x.IndexPos = i
break
}
}
}
log.Debug3f("metrics before filter: %v", Names(x.Metrics))
x.Metrics = filtered
log.Debug3f("metrics after inactive filter: %v", Names(filtered))
} | model/indexed_measure.go | 0.778102 | 0.403567 | indexed_measure.go | starcoder |
package test
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xabinapal/gopve/pkg/types"
"github.com/xabinapal/gopve/pkg/types/errors"
)
func HelperCreatePropertiesMap(props types.Properties) types.Properties {
obj := make(types.Properties, len(props))
for k, v := range props {
switch x := v.(type) {
case string:
obj[k] = x
case int:
obj[k] = float64(x)
case int8:
obj[k] = float64(x)
case int16:
obj[k] = float64(x)
case int32:
obj[k] = float64(x)
case int64:
obj[k] = float64(x)
case uint:
obj[k] = float64(x)
case uint8:
obj[k] = float64(x)
case uint16:
obj[k] = float64(x)
case uint32:
obj[k] = float64(x)
case uint64:
obj[k] = float64(x)
case float32:
obj[k] = float64(x)
case float64:
obj[k] = x
default:
panic("unsupported type")
}
}
return obj
}
func HelperTestRequiredProperties(
t *testing.T,
props types.Properties,
requiredProps []string,
factoryFunc func(types.Properties) (interface{}, error),
) func(t *testing.T) {
t.Helper()
return func(t *testing.T) {
for _, prop := range requiredProps {
finalProps := make(types.Properties, len(props))
for k, v := range props {
if k != prop {
finalProps[k] = v
}
}
expectedError := errors.ErrMissingProperty
expectedError.AddKey("name", prop)
_, err := factoryFunc(finalProps)
assert.EqualError(t, err, expectedError.Error(), fmt.Sprintf("An error is expected with missing required property `%s`", prop))
}
}
}
func HelperTestOptionalProperties(
t *testing.T,
props types.Properties,
optionalProps []string,
factoryFunc func(types.Properties) (interface{}, error),
testFunc func(interface{}),
) func(t *testing.T) {
t.Helper()
return func(t *testing.T) {
finalProps := make(types.Properties)
for k, v := range props {
finalProps[k] = v
}
for _, v := range optionalProps {
delete(finalProps, v)
}
obj, err := factoryFunc(finalProps)
require.NoError(t, err)
testFunc(obj)
}
} | test/properties.go | 0.622 | 0.476153 | properties.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.