text stringlengths 11 4.05M |
|---|
package main
import "fmt"
//func (i int) PrintInt() {
// fmt.Println(i)
//}
type jason int
func (i jason) PrintInt() {
fmt.Println(i)
}
func main() {
//var i int = 1
//i.PrintInt()
var i jason = 1
i.PrintInt()
}
|
// Copyright 2020 Comcast Cable Communications Management, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package match
import (
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/xmidt-org/ears/pkg/config"
pkgconfig "github.com/xmidt-org/ears/pkg/config"
"github.com/xmidt-org/ears/pkg/errs"
"github.com/xmidt-org/ears/pkg/filter"
)
func NewConfig(config interface{}) (*Config, error) {
var cfg Config
err := pkgconfig.NewConfig(config, &cfg)
if err != nil {
return nil, &filter.InvalidConfigError{
Err: err,
}
}
return &cfg, nil
}
func (c Config) WithDefaults() *Config {
cfg := c
if c.Mode == ModeUnknown {
cfg.Mode = DefaultConfig.Mode
}
if c.Matcher == MatcherUnknown {
cfg.Matcher = DefaultConfig.Matcher
}
if c.Pattern == nil {
cfg.Pattern = DefaultConfig.Pattern
}
if c.ExactArrayMatch == nil {
cfg.ExactArrayMatch = DefaultConfig.ExactArrayMatch
}
return &cfg
}
func (c *Config) Validate() error {
s := *c
// Allow this list to easily expand over time
validModes := []interface{}{}
for _, t := range ModeTypeValues() {
if t != ModeUnknown {
validModes = append(validModes, t)
}
}
validMatchers := []interface{}{}
for _, t := range MatcherTypeValues() {
if t != MatcherUnknown {
validMatchers = append(validMatchers, t)
}
}
return validation.ValidateStruct(&s,
validation.Field(&s.Mode,
validation.Required,
validation.In(validModes...),
),
validation.Field(&s.Matcher,
validation.Required,
validation.In(validMatchers...),
),
validation.Field(&s.Pattern,
validation.NotNil,
),
)
}
// Exporter interface
func (c *Config) String() string {
s, err := c.YAML()
if err != nil {
return errs.String("error", nil, err)
}
return s
}
func (c *Config) YAML() (string, error) {
return config.ToYAML(c)
}
func (c *Config) FromYAML(in string) error {
return config.FromYAML(in, c)
}
func (c *Config) JSON() (string, error) {
return config.ToJSON(c)
}
func (c *Config) FromJSON(in string) error {
return config.FromJSON(in, c)
}
|
package mediators
import (
"app/models"
"github.com/gin-gonic/gin"
. "app/helpers"
"errors"
. "strconv"
"fmt"
)
type postMediator struct {
Post *models.Post
Context *gin.Context
}
func (self *postMediator) Find() (*R, error) {
var err error
self.Post, err = self.Post.Find()
return &R{self}, err
}
func (self *postMediator) Create() (*R, error) {
ok := self.Context.Bind(self.Post)
if ok { return &R{self}, self.Post.Create() }
return &R{self}, errors.New("can't parse Post data")
}
func (self *postMediator) Update() (*R, error) {
ok := self.Context.Bind(self.Post)
if ok { return &R{self}, self.Post.Update() }
return &R{self}, errors.New("can't parse Post data")
}
func (self *postMediator) Destroy() (error) {
return self.Post.Destroy()
}
func (self *postMediator) Self() interface{} {
return self.Post
}
func (self *postMediator) ToJSON( code int, obj interface{} ) {
self.Context.JSON( code, obj )
}
func (self *postMediator) NotFound() string {
return fmt.Sprintf("post with id:%d was not found", self.Post.Id)
}
func (self *postMediator) Destroyed() string {
return fmt.Sprintf("post with id:%d was successfully destroyed", self.Post.Id)
}
/*
// helper to get 'id' from context params
*/
func getIdFrom(context *gin.Context) (id int64, status bool) {
status = true
id, err := ParseInt(context.Params.ByName("id"), 10, 64)
if err != nil { status = false }
return
}
/*
// Constructor
*/
func Post(context *gin.Context) (p *postMediator) {
p = &postMediator{Post: &models.Post{}, Context: context}
if id, ok := getIdFrom(context); ok { p.Post.Id = id }
return
}
|
package engine
import (
"../fetcher"
"fmt"
"log"
)
func Run(seeds ...Request) {
var requests []Request
for _, e := range seeds {
requests = append(requests, e)
}
for len(requests) > 0 {
r := requests[0]
requests = requests[1:]
log.Printf("Fetching url: %s\n", r.Url)
body, err := fetcher.Fetch(r.Url)
if err != nil {
log.Printf("Fetch Error: %s\n", r.Url)
}
pareresult := r.ParseFunc(body)
requests = append(requests, pareresult.Requests...)
for _, item := range pareresult.Items {
fmt.Printf("Got items: %s\n", item)
}
}
}
|
// Copyright 2017 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package display wraps the chrome.system.display API.
//
// Functions require a chrome.Conn with permission to use the chrome.system.display API.
// chrome.Chrome.TestAPIConn has such permission and may be passed here.
package display
import (
"context"
"math"
"chromiumos/tast/common/action"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/coords"
"chromiumos/tast/testing"
)
// Insets holds onscreen insets.
// See https://developer.chrome.com/docs/extensions/reference/system_display/#type-Insets.
type Insets struct {
Left int `json:"left"`
Top int `json:"top"`
Right int `json:"right"`
Bottom int `json:"bottom"`
}
// DisplayMode holds a mode supported by the display.
// See https://developer.chrome.com/docs/extensions/reference/system_display/#type-DisplayMode.
type DisplayMode struct { // NOLINT
Width int `json:"width"`
Height int `json:"height"`
WidthInNativePixels int `json:"widthInNativePixels"`
HeightInNativePixels int `json:"heightInNativePixels"`
UIScale float64 `json:"uiScale,omitempty"`
DeviceScaleFactor float64 `json:"deviceScaleFactor"`
RefreshRate float64 `json:"refreshRate"`
IsNative bool `json:"isNative"`
IsSelected bool `json:"isSelected"`
IsInterlaced bool `json:"isInterlaced,omitempty"`
}
// Info holds information about a display and is returned by GetInfo.
// See https://developer.chrome.com/docs/extensions/reference/system_display/#type-DisplayUnitInfo.
type Info struct {
ID string `json:"id"`
Name string `json:"name"`
MirroringSourceID string `json:"mirroringSourceId"`
IsPrimary bool `json:"isPrimary"`
IsInternal bool `json:"isInternal"`
IsEnabled bool `json:"isEnabled"`
IsUnified bool `json:"isUnified"`
DPIX float64 `json:"dpiX"`
DPIY float64 `json:"dpiY"`
Rotation int `json:"rotation"`
Bounds coords.Rect `json:"bounds"`
Overscan *Insets `json:"overscan"`
WorkArea coords.Rect `json:"workArea"`
Modes []*DisplayMode `json:"modes"`
HasTouchSupport bool `json:"hasTouchSupport"`
AvailableDisplayZoomFactors []float64 `json:"availableDisplayZoomFactors"`
DisplayZoomFactor float64 `json:"displayZoomFactor"`
}
// GetSelectedMode returns the currently selected display mode. It returns
// nil if no such mode is found.
func (info *Info) GetSelectedMode() (*DisplayMode, error) {
for _, mode := range info.Modes {
if mode.IsSelected {
return mode, nil
}
}
return nil, errors.New("no modes are selected")
}
// GetEffectiveDeviceScaleFactor computes the ratio of a DIP (device independent
// pixel) to a physical pixel, which is DisplayZoomFactor x DeviceScaleFactor.
// See also ui/display/manager/managed_display_info.h in Chromium.
func (info *Info) GetEffectiveDeviceScaleFactor() (float64, error) {
mode, err := info.GetSelectedMode()
if err != nil {
return 0, err
}
scaleFactor := info.DisplayZoomFactor * mode.DeviceScaleFactor
// Make sure the scale factor is neither 0 nor NaN.
if math.IsNaN(scaleFactor) || math.Abs(scaleFactor) < 1e-10 {
return 0, errors.Errorf("invalid device scale factor: %f", scaleFactor)
}
return scaleFactor, nil
}
// GetInfo calls chrome.system.display.getInfo to get information about connected displays.
// See https://developer.chrome.com/docs/extensions/reference/system_display/#method-getInfo.
func GetInfo(ctx context.Context, tconn *chrome.TestConn) ([]Info, error) {
var infos []Info
if err := tconn.Call(ctx, &infos, `tast.promisify(chrome.system.display.getInfo)`); err != nil {
return nil, errors.Wrap(err, "failed to get display info")
}
if len(infos) == 0 {
// At leasat one display info should exist. So empty info would mean
// something is wrong.
return nil, errors.New("no display info are contained")
}
return infos, nil
}
// FindInfo returns information about the display that satisfies the given predicate.
func FindInfo(ctx context.Context, tconn *chrome.TestConn, predicate func(info *Info) bool) (*Info, error) {
infos, err := GetInfo(ctx, tconn)
if err != nil {
return nil, err
}
for _, info := range infos {
if predicate(&info) {
return &info, nil
}
}
return nil, errors.New("failed to find a display satisfying the condition")
}
// GetInternalInfo returns information about the internal display.
// An error is returned if no internal display is present.
func GetInternalInfo(ctx context.Context, tconn *chrome.TestConn) (*Info, error) {
return FindInfo(ctx, tconn, func(info *Info) bool {
return info.IsInternal
})
}
// GetPrimaryInfo returns information about the primary display.
func GetPrimaryInfo(ctx context.Context, tconn *chrome.TestConn) (*Info, error) {
return FindInfo(ctx, tconn, func(info *Info) bool {
return info.IsPrimary
})
}
// DisplayProperties holds properties to change and is passed to SetDisplayProperties.
// nil fields are ignored. See https://developer.chrome.com/docs/extensions/reference/system_display/#type-DisplayProperties.
type DisplayProperties struct { // NOLINT
IsUnified *bool `json:"isUnified,omitempty"`
MirroringSourceID *string `json:"mirroringSourceId,omitempty"`
IsPrimary *bool `json:"isPrimary,omitempty"`
Overscan *Insets `json:"overscan,omitempty"`
Rotation *int `json:"rotation,omitempty"`
BoundsOriginX *int `json:"boundsOriginX,omitempty"`
BoundsOriginY *int `json:"boundsOriginY,omitempty"`
DisplayMode *DisplayMode `json:"displayMode,omitempty"`
DisplayZoomFactor *float64 `json:"displayZoomFactor,omitempty"`
}
// SetDisplayProperties updates the properties for the display specified by id.
// See https://developer.chrome.com/docs/extensions/reference/system_display/#method-setDisplayProperties.
// Some properties, like rotation, will be performed in an async way. For rotation in particular,
// you should call display.WaitForDisplayRotation() to know when the rotation animation finishes.
func SetDisplayProperties(ctx context.Context, tconn *chrome.TestConn, id string, dp DisplayProperties) error {
return tconn.Call(ctx, nil, "tast.promisify(chrome.system.display.setDisplayProperties)", id, dp)
}
// RotationAngle represents the supported rotation angles by SetDisplayRotationSync.
type RotationAngle string
// Rotation values as defined in: https://cs.chromium.org/chromium/src/out/Debug/gen/chrome/common/extensions/api/autotest_private.h
const (
// RotateAny represents the auto-rotation to the device angle. Valid only in
// tablet mode.
RotateAny RotationAngle = "RotateAny"
// Rotate0 represents rotation angle 0.
Rotate0 RotationAngle = "Rotate0"
// Rotate90 represents rotation angle 90.
Rotate90 RotationAngle = "Rotate90"
// Rotate180 represents rotation angle 180.
Rotate180 RotationAngle = "Rotate180"
// Rotate270 represents rotation angle 270.
Rotate270 RotationAngle = "Rotate270"
)
// WaitForDisplayRotation waits for the display rotation animation. If it is not
// animating, it returns immediately. Returns an error if incorrect parameters
// are passed, or the display rotation ends up with a different rotation from
// the specified one.
func WaitForDisplayRotation(ctx context.Context, tconn *chrome.TestConn, dispID string, rot RotationAngle) error {
return tconn.Call(ctx, nil, `async (displayId, rotation) => {
if (!await tast.promisify(chrome.autotestPrivate.waitForDisplayRotation)(displayId, rotation))
throw new Error("failed to wait for display rotation");
}`, dispID, rot)
}
// SetDisplayRotationSync rotates the display to a certain angle and waits until the rotation animation finished.
// c must be a connection with both system.display and autotestPrivate permissions.
func SetDisplayRotationSync(ctx context.Context, tconn *chrome.TestConn, dispID string, rot RotationAngle) error {
var rotInt int
switch rot {
case RotateAny:
rotInt = -1
case Rotate0:
rotInt = 0
case Rotate90:
rotInt = 90
case Rotate180:
rotInt = 180
case Rotate270:
rotInt = 270
default:
return errors.Errorf("unexpected rotation value; got %q, want: any of [Rotate0,Rotate90,Rotate180,Rotate270]", rot)
}
p := DisplayProperties{Rotation: &rotInt}
if err := SetDisplayProperties(ctx, tconn, dispID, p); err != nil {
return errors.Wrapf(err, "failed to set rotation to %d", rotInt)
}
return WaitForDisplayRotation(ctx, tconn, dispID, rot)
}
// OrientationType represents a display orientation.
type OrientationType string
// OrientationType values as "enum OrientationType" defined in https://w3c.github.io/screen-orientation/#screenorientation-interface
const (
OrientationPortraitPrimary OrientationType = "portrait-primary"
OrientationPortraitSecondary OrientationType = "portrait-secondary"
OrientationLandscapePrimary OrientationType = "landscape-primary"
OrientationLandscapeSecondary OrientationType = "landscape-secondary"
)
// Orientation holds information obtained from the screen orientation API.
// See https://w3c.github.io/screen-orientation/#screenorientation-interface
type Orientation struct {
// Angle is an angle in degrees of the display counterclockwise from the
// orientation of the display panel.
Angle int `json:"angle"`
// Type is an OrientationType representing the display orientation.
Type OrientationType `json:"type"`
}
// GetOrientation returns the Orientation of the display.
func GetOrientation(ctx context.Context, tconn *chrome.TestConn) (*Orientation, error) {
result := &Orientation{}
// Using a JS expression to evaluate screen.orientation to a JSON object
// because JSON.stringify does not work for it and returns {}.
if err := tconn.Eval(ctx, `s=screen.orientation;o={"angle":s.angle,"type":s.type}`, result); err != nil {
return nil, err
}
return result, nil
}
// IsFakeDisplayID checks if a display is fake or not by its id.
func IsFakeDisplayID(id string) bool {
// the id of fake displays will start from this number.
// See also: https://source.chromium.org/chromium/chromium/src/+/HEAD:ui/display/manager/managed_display_info.cc?q=%20kSynthesizedDisplayIdStart
const fakeDisplayID = "2200000000"
// Theoretically it is possible that a fake display has a different ID. This
// happens when some displays are connected and then disconnected; this is
// unlikely to happen on test environment.
return id == fakeDisplayID
}
// PhysicalDisplayConnected checks the display info and returns true if at least
// one physical display is connected.
func PhysicalDisplayConnected(ctx context.Context, tconn *chrome.TestConn) (bool, error) {
infos, err := GetInfo(ctx, tconn)
if err != nil {
return false, err
}
if len(infos) > 1 {
return true, nil
}
return !IsFakeDisplayID(infos[0].ID), nil
}
var intToRotationAngle = map[int]RotationAngle{
0: Rotate0,
90: Rotate90,
180: Rotate180,
270: Rotate270,
-1: RotateAny,
}
// RotateToLandscape rotates the display only if current orientation type is "portrait", and returns
// a function that restores the original orientation setting.
func RotateToLandscape(ctx context.Context, tconn *chrome.TestConn) (func(context.Context) error, error) {
orientation, err := GetOrientation(ctx, tconn)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain the orientation info")
}
testing.ContextLogf(ctx, "Current orientation type: %d; orientation angle: %v", orientation.Angle, orientation.Type)
// Rotate the display only if current orientation is in portrait position.
if orientation.Type == OrientationPortraitPrimary || orientation.Type == OrientationPortraitSecondary {
info, err := GetPrimaryInfo(ctx, tconn)
if err != nil {
return nil, errors.Wrap(err, "failed to obtain primary display info")
}
restoreRotation := intToRotationAngle[info.Rotation]
testing.ContextLog(ctx, "Current rotation setting: ", restoreRotation)
// If the orientation angle is equal to 0 or 180, rotate 270 (or 90) degrees.
// If the orientation angle is equal to 90 or 270, rotate 0 (or 180) degrees.
var targetRotation RotationAngle
if orientation.Angle == 0 || orientation.Angle == 180 {
targetRotation = Rotate270
} else {
targetRotation = Rotate0
}
testing.ContextLog(ctx, "Target rotation setting: ", targetRotation)
if err := SetDisplayRotationSync(ctx, tconn, info.ID, targetRotation); err != nil {
return nil, err
}
return func(ctx context.Context) error {
return SetDisplayRotationSync(ctx, tconn, info.ID, restoreRotation)
}, nil
}
return func(context.Context) error {
return nil
}, nil
}
// RotationToAngle converts Info.Rotation value to RotationAngle.
func RotationToAngle(rot int) (RotationAngle, error) {
if val, ok := intToRotationAngle[rot]; ok {
return val, nil
}
return RotateAny, errors.Errorf("invalid rotation angle %d", rot)
}
// CheckExtendedDisplay makes sure there are two displays on DUT and the extended display has the expected mode.
// This procedure must be performed after display mirror is unset. Otherwise it can only get one display info.
func CheckExtendedDisplay(tconn *chrome.TestConn, expectedMode DisplayMode) action.Action {
return func(ctx context.Context) error {
infos, err := GetInfo(ctx, tconn)
if err != nil {
return errors.Wrap(err, "failed to get display info")
}
if len(infos) != 2 {
return errors.Wrapf(err, "DUT connected with incorrect number of displays - want 2, got %d", len(infos))
}
for _, info := range infos {
if info.IsInternal {
continue
}
mode, err := info.GetSelectedMode()
if err != nil {
return errors.Wrap(err, "failed to get selected mode")
}
if mode.Height != expectedMode.Height {
return errors.Errorf("the height of the extended display is not as expected: got: %v, want: %v", mode.Height, expectedMode.Height)
}
if mode.RefreshRate != expectedMode.RefreshRate {
return errors.Errorf("the refresh rate of the extended display is not as expected: got: %v, want: %v", mode.RefreshRate, expectedMode.RefreshRate)
}
}
return nil
}
}
|
package account
import (
. "ftnox.com/common"
. "ftnox.com/config"
"ftnox.com/db"
"ftnox.com/auth"
"ftnox.com/bitcoin"
"fmt"
)
// Master public key for generating account deposit addresses
var hotMPK *bitcoin.MPK
func init() {
hotMPK = bitcoin.SaveMPKIfNotExists(&bitcoin.MPK{
PubKey: Config.HotMPKPubKey,
Chain: Config.HotMPKChain,
})
}
func GetHotMPK() *bitcoin.MPK {
return hotMPK
}
// BALANCE
func LoadBalances(userId int64, wallet string) map[string]int64 {
var balMap = map[string]int64{}
balances := LoadBalancesByWallet(userId, wallet)
for _, balance := range balances {
balMap[balance.Coin] = balance.Amount
}
for _, coin := range Config.Coins {
if _, ok := balMap[coin.Name]; !ok {
balMap[coin.Name] = int64(0)
}
}
return balMap
}
func LoadAllDepositAddresses(userId int64, wallet string) map[string]string {
var addrMap = map[string]string{}
addrs := bitcoin.LoadAddressesByWallet(userId, wallet)
for _, addr := range addrs {
addrMap[addr.Coin] = addr.Address
}
return addrMap
}
func LoadOrCreateDepositAddress(userId int64, wallet string, coin string) string {
user := auth.LoadUser(userId)
chainPath := fmt.Sprintf("%v/%v", bitcoin.CHAINPATH_PREFIX_DEPOSIT, user.ChainIdx)
address := bitcoin.LoadLastAddressByWallet(userId, wallet, coin)
if address == nil {
address = bitcoin.CreateNewAddress(coin, userId, wallet, hotMPK, chainPath)
}
return address.Address
}
// WITHDRAWAL
func AddWithdrawal(userId int64, toAddr string, coin string, amount uint64) (*Withdrawal, error) {
wth := &Withdrawal{
UserId: userId,
Wallet: WALLET_MAIN,
Coin: coin,
ToAddress: toAddr,
Amount: amount,
Status: WITHDRAWAL_STATUS_PENDING,
}
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// save withdrawal
SaveWithdrawal(tx, wth)
// adjust balance.
UpdateBalanceByWallet(tx, userId, WALLET_MAIN, coin, -int64(amount), true)
UpdateBalanceByWallet(tx, userId, WALLET_RESERVED_WITHDRAWAL, coin, int64(amount), false)
})
return wth, err
}
func CheckoutWithdrawals(coin string, limit uint) (wths []*Withdrawal) {
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
wths = LoadWithdrawalsByStatus(tx, coin, WITHDRAWAL_STATUS_PENDING, limit)
wthIds := Map(wths, "Id")
UpdateWithdrawals(tx, wthIds, WITHDRAWAL_STATUS_PENDING,
WITHDRAWAL_STATUS_CHECKEDOUT, 0)
})
if err != nil { panic(err) }
return
}
func CompleteWithdrawals(wths []*Withdrawal, wtxId int64) {
wthIds := Map(wths, "Id")
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// update status
UpdateWithdrawals(tx, wthIds, WITHDRAWAL_STATUS_CHECKEDOUT,
WITHDRAWAL_STATUS_COMPLETE, wtxId)
// adjust balance
for _, wth := range wths {
UpdateBalanceByWallet(tx, wth.UserId, WALLET_RESERVED_WITHDRAWAL, wth.Coin, -int64(wth.Amount), true)
}
})
if err != nil { panic(err) }
}
func StallWithdrawals(wthIds []interface{}) {
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// update status
UpdateWithdrawals(tx, wthIds, WITHDRAWAL_STATUS_CHECKEDOUT,
WITHDRAWAL_STATUS_STALLED, 0)
})
if err != nil { panic(err) }
}
func ResumeWithdrawals(wthIds []interface{}) {
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// update status
UpdateWithdrawals(tx, wthIds, WITHDRAWAL_STATUS_STALLED,
WITHDRAWAL_STATUS_PENDING, 0)
})
if err != nil { panic(err) }
}
func CancelWithdrawal(wth *Withdrawal) {
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// update status
UpdateWithdrawals(tx, []interface{}{wth.Id}, WITHDRAWAL_STATUS_PENDING,
WITHDRAWAL_STATUS_CANCELED, 0)
// adjust balance
UpdateBalanceByWallet(tx, wth.UserId, WALLET_RESERVED_WITHDRAWAL, wth.Coin, -int64(wth.Amount), true)
UpdateBalanceByWallet(tx, wth.UserId, WALLET_MAIN, wth.Coin, int64(wth.Amount), false)
})
if err != nil { panic(err) }
}
// TRANSFER (not used anymore/yet)
func AddTransfer(fromUserId int64, fromWallet string, toUserId int64, toWallet string, coin string, amount uint64) error {
// Create new transfer item that moves amount.
trans := &Transfer{
UserId: fromUserId,
Wallet: fromWallet,
User2Id: toUserId,
Wallet2: toWallet,
Coin: coin,
Amount: amount,
Fee: uint64(0),
}
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// Adjust balance
UpdateBalanceByWallet(tx, trans.UserId, trans.Wallet, trans.Coin, -int64(trans.Amount), true)
UpdateBalanceByWallet(tx, trans.User2Id, trans.Wallet2, trans.Coin, int64(trans.Amount), false)
// Save transfer
SaveTransfer(tx, trans)
})
return err
}
// DEPOSIT
// This just creates a new row in the accounts_deposits table.
// It doesn't actually credit the account, etc.
// Must be idempotent.
func LoadOrCreateDepositForPayment(payment *bitcoin.Payment) (*Deposit) {
if payment.Id == 0 { panic(NewError("Cannot add deposit for unsaved payment")) }
addr := bitcoin.LoadAddress(payment.Address)
if addr == nil { panic(NewError("Expected address for payment to deposit")) }
deposit := &Deposit{
Type: DEPOSIT_TYPE_CRYPTO,
UserId: addr.UserId,
Wallet: addr.Wallet,
Coin: addr.Coin,
Amount: payment.Amount,
PaymentId: payment.Id,
Status: DEPOSIT_STATUS_PENDING,
}
_, err := SaveDeposit(db.GetModelDB(), deposit)
switch db.GetErrorType(err) {
case db.ERR_DUPLICATE_ENTRY:
return LoadDepositForPayment(db.GetModelDB(), payment.Id)
default:
if err != nil { panic(err) }
}
return deposit
}
// Credit the user's account for the given payment.
// If the deposit is already credited, do nothing.
// Must be idempotent.
func CreditDepositForPayment(payment *bitcoin.Payment) {
// SANITY CHECK
paymentId := payment.Id
// Reload the payment.
payment = bitcoin.LoadPaymentByTxId(payment.TxId, payment.Vout)
// Ensure that it isn't orphaned.
if payment.Orphaned != bitcoin.PAYMENT_ORPHANED_STATUS_GOOD {
panic(NewError("Cannot credit deposit for an orphaned payment")) }
// Are you paranoid enough?
if paymentId != payment.Id {
panic(NewError("payment.Id didn't match")) }
// END SANITY CHECK
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// Load the corresponding deposit.
deposit := LoadDepositForPayment(tx, payment.Id)
// If the deposit isn't pending, do nothing.
if deposit.Status != DEPOSIT_STATUS_PENDING { return }
// Credit the account.
UpdateBalanceByWallet(tx, deposit.UserId, deposit.Wallet, deposit.Coin, int64(deposit.Amount), false)
UpdateDepositSetStatus(tx, deposit.Id, DEPOSIT_STATUS_CREDITED)
})
if err != nil { panic(err) }
}
// Uncredit the user's account for the given payment.
// If the deposit isn't credited, do nothing.
// Returns true if the resulting balance is negative.
// Must be idempotent.
func UncreditDepositForPayment(payment *bitcoin.Payment) (balance *Balance) {
// SANITY CHECK
paymentId := payment.Id
// Reload the payment.
payment = bitcoin.LoadPaymentByTxId(payment.TxId, payment.Vout)
// Ensure that it is orphaned.
if payment.Orphaned != bitcoin.PAYMENT_ORPHANED_STATUS_ORPHANED {
panic(NewError("Cannot uncredit deposit for a payment that isn't in STATUS_ORPHANED")) }
// Are you paranoid enough?
if paymentId != payment.Id {
panic(NewError("payment.Id didn't match")) }
// END SANITY CHECK
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// Load the corresponding deposit.
deposit := LoadDepositForPayment(tx, payment.Id)
// If the deposit isn't credited, do nothing.
if deposit.Status != DEPOSIT_STATUS_CREDITED { return }
// Uncredit the account.
balance = UpdateBalanceByWallet(tx, deposit.UserId, deposit.Wallet, deposit.Coin, -int64(deposit.Amount), false)
UpdateDepositSetStatus(tx, deposit.Id, DEPOSIT_STATUS_PENDING)
})
if err != nil { panic(err) }
return
}
// This just creates a new row in the accounts_deposits table.
// It doesn't actually credit the account, etc.
// Must be idempotent.
func CreateDeposit(deposit *Deposit) (*Deposit) {
// SANITY CHECK
if deposit.Id != 0 { panic(NewError("Expected a new deposit but got a saved one")) }
if deposit.Type != DEPOSIT_TYPE_FIAT { panic(NewError("Expected a fiat (bank) deposit")) }
if deposit.PaymentId != 0 { panic(NewError("Fiat (bank) deposit cannot have a payment")) } // TODO move to validator.
if deposit.Status != DEPOSIT_STATUS_PENDING { panic(NewError("Expected a pending deposit")) }
// END SANITY CHECK
_, err := SaveDeposit(db.GetModelDB(), deposit)
if err != nil { panic(err) }
return deposit
}
// Credit the user's account for the given bank deposit.
// If the deposit is already credited, do nothing.
// Must be idempotent.
func CreditDeposit(deposit *Deposit) {
// SANITY CHECK
if deposit.Id == 0 { panic(NewError("Expected a saved deposit but got a new one")) }
// END SANITY CHECK
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// Load the corresponding deposit.
deposit := LoadDeposit(tx, deposit.Id)
// If the deposit isn't pending, do nothing.
if deposit.Status != DEPOSIT_STATUS_PENDING { return }
// Credit the account.
UpdateBalanceByWallet(tx, deposit.UserId, deposit.Wallet, deposit.Coin, int64(deposit.Amount), false)
UpdateDepositSetStatus(tx, deposit.Id, DEPOSIT_STATUS_CREDITED)
})
if err != nil { panic(err) }
}
// Uncredit the user's account for the given payment.
// If the deposit isn't credited, do nothing.
// Returns true if the resulting balance is negative.
// Must be idempotent.
func UncreditDeposit(deposit *Deposit) (balance *Balance) {
// SANITY CHECK
if deposit.Id == 0 { panic(NewError("Expected a saved deposit but got a new one")) }
// END SANITY CHECK
err := db.DoBeginSerializable(func(tx *db.ModelTx) {
// Load the corresponding deposit.
deposit := LoadDeposit(tx, deposit.Id)
// If the deposit isn't credited, do nothing.
if deposit.Status != DEPOSIT_STATUS_CREDITED { return }
// Uncredit the account.
balance = UpdateBalanceByWallet(tx, deposit.UserId, deposit.Wallet, deposit.Coin, -int64(deposit.Amount), false)
UpdateDepositSetStatus(tx, deposit.Id, DEPOSIT_STATUS_PENDING)
})
if err != nil { panic(err) }
return
}
|
// Copyright 2019 - 2022 The Samply Community
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package fhir
import (
"encoding/json"
"fmt"
"strings"
)
// THIS FILE IS GENERATED BY https://github.com/samply/golang-fhir-models
// PLEASE DO NOT EDIT BY HAND
// ExposureState is documented here http://hl7.org/fhir/ValueSet/exposure-state
type ExposureState int
const (
ExposureStateExposure ExposureState = iota
ExposureStateExposureAlternative
)
func (code ExposureState) MarshalJSON() ([]byte, error) {
return json.Marshal(code.Code())
}
func (code *ExposureState) UnmarshalJSON(json []byte) error {
s := strings.Trim(string(json), "\"")
switch s {
case "exposure":
*code = ExposureStateExposure
case "exposure-alternative":
*code = ExposureStateExposureAlternative
default:
return fmt.Errorf("unknown ExposureState code `%s`", s)
}
return nil
}
func (code ExposureState) String() string {
return code.Code()
}
func (code ExposureState) Code() string {
switch code {
case ExposureStateExposure:
return "exposure"
case ExposureStateExposureAlternative:
return "exposure-alternative"
}
return "<unknown>"
}
func (code ExposureState) Display() string {
switch code {
case ExposureStateExposure:
return "Exposure"
case ExposureStateExposureAlternative:
return "Exposure Alternative"
}
return "<unknown>"
}
func (code ExposureState) Definition() string {
switch code {
case ExposureStateExposure:
return "used when the results by exposure is describing the results for the primary exposure of interest."
case ExposureStateExposureAlternative:
return "used when the results by exposure is describing the results for the alternative exposure state, control state or comparator state."
}
return "<unknown>"
}
|
package main
import (
"fmt"
"log"
"net/http"
"net/url"
)
func handler(w http.ResponseWriter, r *http.Request) {
//fmt.Fprintf(w, "%s\n", r.URL.RawQuery)
q := r.URL.RawQuery
m, err := url.ParseQuery(q)
if err != nil {
log.Fatal(err)
}
switch {
case len(m["name"]) > 0:
fmt.Fprintf(w, "Hello %s\n", m["name"][0])
default:
fmt.Fprintf(w, "%s\n", "[ERROR] please input your name in the request argument, e.g. /?name=pahud")
}
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
|
package main
import "fmt"
//golang by default passes values into
//funcs by value with no reference
//to the original memory address
//if you want to affect the original
//value you can pass in the memory address
//and derefernce that value and reset it
//to change the original
//this is not true for reference data types
//slices, maps
//passing a slice or map to a function
//keeps reference to the memory address
//and if you change that value in one function
//it affects that data in another)
func main() {
age := 44
fmt.Println(&age)
changeMe(&age)
fmt.Println(&age)
fmt.Println(age)
}
//int is passed in as memory address
//that stores an int
func changeMe(z *int) {
fmt.Println(z)
fmt.Println(*z)
//*z dereferences memory address
//and shows value instead of address
*z = 24
//changing value of original
//data passed into func by using memory address
fmt.Println(z)
fmt.Println(*z)
}
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package analysis
// Possibility is an enumerator of possibilites.
type Possibility int
const (
// True represents a logical certanty or true.
True Possibility = iota
// Maybe represents the possibility of true or false.
Maybe
// False represents a logical certanty of false.
False
// Impossible represents a contradiction of certanties (for example
// True ∩ False)
Impossible
)
// MaybeTrue returns true iff a is True or Maybe.
func (a Possibility) MaybeTrue() bool {
return a == True || a == Maybe
}
// MaybeFalse returns true iff a is False or Maybe.
func (a Possibility) MaybeFalse() bool {
return a == False || a == Maybe
}
// Not returns the logical negation of a.
func (a Possibility) Not() Possibility {
switch a {
case False:
return True
case True:
return False
case Impossible:
return Impossible
default:
return Maybe
}
}
// And returns the logical-and of a and b.
func (a Possibility) And(b Possibility) Possibility {
switch {
case a == Impossible || b == Impossible:
return Impossible
case a == False, b == False:
return False
case a == Maybe, b == Maybe:
return Maybe
default:
return True
}
}
// Or returns the logical-or of a and b.
func (a Possibility) Or(b Possibility) Possibility {
switch {
case a == Impossible || b == Impossible:
return Impossible
case a == True, b == True:
return True
case a == Maybe, b == Maybe:
return Maybe
default:
return False
}
}
// Equals returns the possibility of a equaling b.
func (a Possibility) Equals(b Possibility) Possibility {
switch {
case a == Impossible || b == Impossible:
return Impossible
case a == Maybe, b == Maybe:
return Maybe
default:
if a == b {
return True
}
return False
}
}
// Union returns the union of possibile Possibilitys for a and b.
func (a Possibility) Union(b Possibility) Possibility {
if a == Impossible || b == Impossible {
return Impossible
}
if a.Equals(b) == True {
return a
}
return Maybe
}
// Intersect returns the intersection of possibile Possibilitys for a and b.
func (a Possibility) Intersect(b Possibility) Possibility {
if a == Impossible || b == Impossible {
return Impossible
}
if a == Maybe {
if b == Maybe {
return Maybe
}
a, b = b, a
}
// a is True or False
// b is True, False or Maybe
if b == Maybe || a == b {
return a
}
return Impossible
}
// Difference returns the possibile for v that are not found in o.
func (a Possibility) Difference(b Possibility) Possibility {
if a == Impossible || b == Impossible {
return Impossible
}
if a == Maybe {
return b.Not()
}
if a == b {
return Impossible
}
return a
}
|
package main
import (
"log"
"math/rand"
"github.com/gorilla/websocket"
)
func joinGame(game *Game, playerName string, conn *websocket.Conn) *Player {
var player *Player
if game.gameStarted {
player = findPlayerInGame(game, playerName)
if player == nil || player.ws != nil {
sendErrorMessageToClient(conn, "Game already in progress")
} else {
sendPlayerListToClient(conn, createPlayerInfoList(game))
}
return nil //either way, disconnect
}
game.playersMutex.Lock()
player = addNewPlayerToGame(game, playerName, conn)
if player != nil {
sendControlMessageToClient(conn, "Joined")
broadcastNames(game)
}
game.playersMutex.Unlock()
return player
}
func addNewPlayerToGame(game *Game, playerName string, conn *websocket.Conn) *Player {
if len(game.players) == 10 {
sendErrorMessageToClient(conn, "Game full")
return nil
}
if findPlayerInGame(game, playerName) != nil {
sendErrorMessageToClient(conn, "Duplicate name")
return nil
}
player := Player{
ws: conn,
name: playerName,
role: " ",
}
game.players = append(game.players, &player)
return &player
}
func findPlayerInGame(game *Game, playerName string) *Player {
for _, player := range game.players {
if player.name == playerName {
return player
}
}
return nil
}
func startGame(game *Game) {
game.playersMutex.Lock()
assignRoles(game)
broadcastNames(game)
game.gameStarted = true
for _, player := range game.players {
sendControlMessageToClient(player.ws, "Start")
player.ws.Close()
player.ws = nil
}
game.playersMutex.Unlock()
endGame(game)
}
func handleRemovedPlayer(game *Game) {
game.playersMutex.Lock()
if len(game.players) == 0 {
log.Printf("Removing game %s", game.gameName)
endGame(game)
} else {
broadcastNames(game)
}
game.playersMutex.Unlock()
}
func endGame(game *Game) {
delete(games, game.gameName)
}
func assignRoles(game *Game) {
numberOfPlayers := len(game.players)
randPerm := rand.Perm(numberOfPlayers)
numberOfLiberals := numberOfPlayers/2 + 1
for i, player := range game.players {
if randPerm[i] == 0 {
player.role = "hitler"
} else if randPerm[i] > numberOfLiberals {
player.role = "fascist"
} else {
player.role = "liberal"
}
}
}
func broadcastNames(game *Game) {
playerList := createPlayerInfoList(game)
for _, player := range game.players {
if player.ws != nil {
sendPlayerListToClient(player.ws, playerList)
}
}
}
func removePlayer(game *Game, player *Player) {
game.playersMutex.Lock()
//len(players) has a max of 10
for index := 0; index < len(game.players); index++ {
if player == game.players[index] {
game.players = append(game.players[:index], game.players[index+1:]...)
break
}
}
game.playersMutex.Unlock()
}
//PlayerInfo is used for sending the list of players to the client
type PlayerInfo struct {
Name string `json:"name"`
Role string `json:"role"`
}
func createPlayerInfoList(game *Game) []PlayerInfo {
var players []PlayerInfo
for _, player := range game.players {
playerInfo := PlayerInfo{
Name: player.name,
Role: player.role,
}
players = append(players, playerInfo)
}
return players
}
|
package model
import "time"
type Patient struct {
Model
PatientId string `json:"patient_id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
DateOfBirth time.Time `json:"date_of_birth"`
Gender string `json:"gender"`
Phone string `json:"phone"`
Email string `json:"email"`
Address string `json:"address"`
ImageUrl string `json:"image_url"`
MedicalHistory []MedicalHistory `gorm:"-" json:"medical_history"`
}
|
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
)
func GetHomePage(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"data": "hello",
})
}
|
/**
* 功能描述: 自定义错误信息code
* @Date: 2019-04-16
* @author: lixiaoming
*/
package errno
// 错误码定义
// 第1位: 服务级别 1(系统级错误) 2(普通错误)
// 第2-3位: 服务模块 01(用户)
// 第4-5位: 错误码 01(具体错误代码)
var (
// 通用错误
OK = &Errno{Code: 0, Message: "OK"}
InternalServerError = &Errno{Code: 10001, Message: "Internal server error."}
ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct."}
ErrRequestBody = &Errno{Code: 10003, Message: "The request parameters is invalid."}
ErrValidation = &Errno{Code: 20001, Message: "Validation failed."}
ErrDatabase = &Errno{Code: 20002, Message: "Database error."}
ErrToken = &Errno{Code: 20003, Message: "Error occurred while signing the JSON web token."}
// 用户错误
ErrEncrypt = &Errno{Code: 20101, Message: "Error occurred while encrypting the user password."}
ErrUserNotFount = &Errno{Code: 20102, Message: "The user was not found."}
ErrTokenInvaild = &Errno{Code: 20103, Message: "The token was invalid."}
ErrPasswordIncorrect = &Errno{Code: 20104, Message: "The password was incorrect."}
// K8S错误
ErrAPIError = &Errno{Code: 30101, Message: "K8S api called failed. "}
)
|
package grpc
import (
"context"
"encoding/json"
"github.com/sapawarga/userpost-service/endpoint"
"github.com/sapawarga/userpost-service/lib/convert"
"github.com/sapawarga/userpost-service/model"
"github.com/sapawarga/userpost-service/usecase"
kitgrpc "github.com/go-kit/kit/transport/grpc"
transportUserPost "github.com/sapawarga/proto-file/userpost"
)
func MakeHandler(ctx context.Context, fs usecase.UsecaseI) transportUserPost.UserPostHandlerServer {
userPostGetListHandler := kitgrpc.NewServer(
endpoint.MakeGetListUserPost(ctx, fs),
decodeGetListUserPost,
encodeGetListUserPost,
)
userPostGetDetailHandler := kitgrpc.NewServer(
endpoint.MakeGetDetailUserPost(ctx, fs),
decodeByIDRequest,
encodedUserPostDetail,
)
userPostCreateNewPostHandler := kitgrpc.NewServer(
endpoint.MakeCreateNewPost(ctx, fs),
decodeCreateNewPostRequest,
encodeStatusResponse,
)
userPostUpdateHandler := kitgrpc.NewServer(
endpoint.MakeUpdateStatusOrTitle(ctx, fs),
decodeUpdateUserPost,
encodeStatusResponse,
)
userPostGetCommentsHandler := kitgrpc.NewServer(
endpoint.MakeGetCommentsByID(ctx, fs),
decodeByIDRequest,
encodeGetCommentsByIDResponse,
)
userPostCreateCommentHandler := kitgrpc.NewServer(
endpoint.MakeCreateComment(ctx, fs),
decodeCreateCommentRequest,
encodeStatusResponse,
)
userPostGetListByMeHandler := kitgrpc.NewServer(
endpoint.MakeGetListUserPostByMe(ctx, fs),
decodeGetListUserPost,
encodeGetListUserPost,
)
userPostLikeDislikeHandler := kitgrpc.NewServer(
endpoint.MakeLikeOrDislikePost(ctx, fs),
decodeByIDRequest,
encodeStatusResponse,
)
return &grpcServer{
userPostGetListHandler,
userPostGetDetailHandler,
userPostCreateNewPostHandler,
userPostUpdateHandler,
userPostGetCommentsHandler,
userPostCreateCommentHandler,
userPostGetListByMeHandler,
userPostLikeDislikeHandler,
}
}
func decodeGetListUserPost(ctx context.Context, r interface{}) (interface{}, error) {
req := r.(*transportUserPost.GetListUserPostRequest)
return &endpoint.GetListUserPostRequest{
ActivityName: convert.SetPointerString(req.GetActivityName()),
Username: convert.SetPointerString(req.GetUsername()),
Category: convert.SetPointerString(req.GetCategory()),
Status: convert.SetPointerInt64(req.GetStatus()),
Page: convert.SetPointerInt64(req.GetPage()),
Limit: convert.SetPointerInt64(req.GetLimit()),
SortBy: req.GetSortBy(),
OrderBy: req.GetOrderBy(),
}, nil
}
func encodeGetListUserPost(ctx context.Context, r interface{}) (interface{}, error) {
resp := r.(*endpoint.UserPostWithMetadata)
data := resp.Data
metadata := resp.Metadata
resultData := make([]*transportUserPost.UserPost, 0)
for _, v := range data {
images, _ := json.Marshal(v.Images)
result := &transportUserPost.UserPost{
Id: v.ID,
Title: v.Title,
Tag: v.Tag,
ImagePath: v.ImagePath,
Images: string(images),
LastUserPostCommentId: convert.GetInt64FromPointer(v.LastUserPostCommentID),
LikesCount: v.LikesCount,
CommentCounts: v.CommentCounts,
Status: v.Status,
}
result = appendDetailUserPost(ctx, v, result)
resultData = append(resultData, result)
}
meta := &transportUserPost.Metadata{
Page: metadata.CurrentPage,
Total: metadata.Total,
TotalPage: int64(metadata.TotalPage),
}
return &transportUserPost.GetListUserPostResponse{
Data: resultData,
Metadata: meta,
}, nil
}
func appendDetailUserPost(ctx context.Context, r *model.UserPostResponse, data *transportUserPost.UserPost) *transportUserPost.UserPost {
if r.Actor != nil {
actor := encodeActor(ctx, r.Actor)
data.Actor = actor
}
if r.LastComment != nil {
comment := &transportUserPost.Comment{
Id: r.LastComment.ID,
UserPostId: r.LastComment.UserPostID,
Comment: r.LastComment.Text,
}
actorCreated := encodeActor(ctx, r.LastComment.CreatedBy)
actorUpdated := encodeActor(ctx, r.LastComment.UpdatedBy)
comment.CreatedBy = actorCreated
comment.UpdatedBy = actorUpdated
data.LastComment = comment
}
return data
}
func decodeByIDRequest(ctx context.Context, r interface{}) (interface{}, error) {
req := r.(*transportUserPost.ByID)
return &endpoint.GetByID{
ID: req.GetId(),
}, nil
}
func encodedUserPostDetail(ctx context.Context, r interface{}) (interface{}, error) {
resp := r.(*endpoint.UserPostDetail)
comment := resp.LastComment
lastComment := &transportUserPost.Comment{
Id: comment.ID,
UserPostId: comment.UserPostID,
Comment: comment.Text,
}
lastCommentActorCreated := encodeActor(ctx, comment.CreatedBy)
lastCommentActorUpdated := encodeActor(ctx, comment.UpdatedBy)
lastComment.CreatedBy = lastCommentActorCreated
lastComment.UpdatedBy = lastCommentActorUpdated
actorUserPost := encodeActor(ctx, resp.Actor)
images, _ := json.Marshal(resp.Images)
userDetail := &transportUserPost.UserPost{
Id: resp.ID,
Title: resp.Title,
Tag: resp.Tag,
ImagePath: resp.ImagePath,
Images: string(images),
LastUserPostCommentId: convert.GetInt64FromPointer(resp.LastUserPostCommentID),
LastComment: lastComment,
LikesCount: resp.LikesCount,
IsLiked: resp.IsLiked,
CommentCounts: resp.CommentCounts,
Status: resp.Status,
Actor: actorUserPost,
}
return userDetail, nil
}
func encodeActor(ctx context.Context, r interface{}) *transportUserPost.Actor {
actorResp := r.(*model.UserResponse)
return &transportUserPost.Actor{
Id: actorResp.ID,
Name: actorResp.Name.String,
PhotoUrl: actorResp.PhotoURL.String,
Role: actorResp.Role.Int64,
Regency: actorResp.Regency.String,
District: actorResp.District.String,
Village: actorResp.Village.String,
Rw: actorResp.RW.String,
}
}
func decodeCreateNewPostRequest(ctx context.Context, r interface{}) (interface{}, error) {
req := r.(*transportUserPost.CreateNewPostRequest)
images := make([]*endpoint.Image, 0)
for _, v := range req.Images {
image := &endpoint.Image{
Path: v.GetPath(),
}
images = append(images, image)
}
return &endpoint.CreateNewPostRequest{
Title: convert.SetPointerString(req.GetTitle()),
Images: images,
Tags: convert.SetPointerString(req.GetTags()),
Status: convert.SetPointerInt64(req.GetStatus()),
}, nil
}
func encodeStatusResponse(ctx context.Context, r interface{}) (interface{}, error) {
resp := r.(*endpoint.StatusResponse)
return &transportUserPost.StatusResponse{
Code: resp.Code,
Message: resp.Message,
}, nil
}
func decodeUpdateUserPost(ctx context.Context, r interface{}) (interface{}, error) {
req := r.(*transportUserPost.UpdateUserPostRequest)
return &endpoint.CreateCommentRequest{
UserPostID: req.GetId(),
Status: convert.SetPointerInt64(req.GetStatus()),
Text: req.GetTitle(),
}, nil
}
func encodeGetCommentsByIDResponse(ctx context.Context, r interface{}) (interface{}, error) {
resp := r.(*endpoint.CommentsResponse)
response := make([]*transportUserPost.Comment, 0)
for _, v := range resp.Data {
created := encodeActor(ctx, v.CreatedBy)
updated := encodeActor(ctx, v.UpdatedBy)
comment := &transportUserPost.Comment{
Id: v.ID,
UserPostId: v.UserPostID,
Comment: v.Text,
CreatedBy: created,
UpdatedBy: updated,
}
response = append(response, comment)
}
return &transportUserPost.CommentsResponse{
Comments: response,
}, nil
}
func decodeCreateCommentRequest(ctx context.Context, r interface{}) (interface{}, error) {
req := r.(*transportUserPost.CreateCommentRequest)
return &endpoint.CreateCommentRequest{
UserPostID: req.GetUserPostId(),
Text: req.GetComment(),
Status: convert.SetPointerInt64(req.GetStatus()),
}, nil
}
|
package schema
import (
"github.com/facebook/ent"
"github.com/facebook/ent/schema/field"
)
// Job holds the schema definition for the Job entity.
type Job struct {
ent.Schema
}
// Fields of the Job.
func (Job) Fields() []ent.Field {
return []ent.Field{
field.Int("id").Positive(),
field.String("name").Default(""),
field.String("creator").Default(""),
field.String("url").Default(""),
field.String("spec").Default(""),
field.String("comment").Default(""),
field.String("updater").Default(""),
field.String("method").Default("GET"),
field.String("body").Default(""),
field.String("header").Default(""),
field.Int("count").Default(0),
field.Int("retry").Default(0),
field.Int("retry_temp").Default(0),
field.Int("status").Default(0),
field.Time("ctime").Optional(),
field.Time("mtime").Optional(),
}
}
// Edges of the Job.
func (Job) Edges() []ent.Edge {
return nil
}
|
package pkgexample
func AddMulti(a int, b int) int {
sum := Add(a,b)
product := Multi(a,b)
return sum + product
}
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package pkcs11test
import (
"context"
"chromiumos/tast/common/pkcs11"
"chromiumos/tast/errors"
)
// SignAndVerify is just a convenient runner to test both signing and verification.
// altInput is path to another test file that differs in content to input. It is used to check that verify() indeed reject corrupted input.
func SignAndVerify(ctx context.Context, p *pkcs11.Chaps, key *pkcs11.KeyInfo, input, altInput string, mechanism *pkcs11.MechanismInfo) error {
// Test signing.
if err := p.Sign(ctx, key, input, input+".sig", mechanism); err != nil {
return err
}
// Test verification of signed message.
if err := p.Verify(ctx, key, input, input+".sig", mechanism); err != nil {
return err
}
// Test verification of another message (should fail).
if err := p.Verify(ctx, key, altInput, input+".sig", mechanism); err == nil {
// Should not happen.
return errors.Errorf("verification functionality for %s failed, corrupted message is verified", mechanism.Name)
}
return nil
}
|
package pack
import (
"bytes"
"context"
"crypto/sha1"
"fmt"
"math/rand"
"reflect"
"testing"
"github.com/twcclan/goback/backup"
"github.com/twcclan/goback/proto"
"github.com/stretchr/testify/require"
)
// number of objects to generate for the tests
const numObjects = 1000
// average size of objects
const ObjectSize = 1024 * 8
type testingInterface interface {
Logf(string, ...interface{})
Fatalf(string, ...interface{})
}
func makeRef() *proto.Ref {
hash := make([]byte, sha1.Size)
_, err := rand.Read(hash)
if err != nil {
panic(err)
}
return &proto.Ref{
Sha1: hash,
}
}
func makeTestData(t *testing.T, num int) []*proto.Object {
t.Logf("Generating %d test objects", num)
objects := make([]*proto.Object, num)
for i := 0; i < num; i++ {
size := rand.Int63n(ObjectSize * 2)
randomBytes := make([]byte, size)
_, err := rand.Read(randomBytes)
if err != nil {
t.Fatalf("Failed reading random data: %v", err)
}
objects[i] = proto.NewObject(&proto.Blob{
Data: randomBytes,
})
}
return objects
}
func TestPack(t *testing.T) {
base := t.TempDir()
storage := newLocal(base)
index := NewInMemoryIndex()
options := []PackOption{
WithArchiveStorage(storage),
WithArchiveIndex(index),
WithMaxSize(1024 * 1024 * 5),
}
store, err := NewPackStorage(options...)
require.Nil(t, err)
objects := makeTestData(t, numObjects)
t.Logf("Storing %d objects", numObjects)
readObjects := func(t *testing.T) {
t.Helper()
t.Logf("Reading back %d objects", numObjects)
for _, i := range rand.Perm(numObjects) {
original := objects[i]
object, err := store.Get(context.Background(), original.Ref())
if err != nil {
t.Fatal(err)
}
if object == nil {
t.Fatalf("Couldn't find expected object %x", original.Ref().Sha1)
}
if !bytes.Equal(object.Bytes(), original.Bytes()) {
t.Logf("Original %x", original.Bytes())
t.Logf("Stored %x", object.Bytes())
t.Fatalf("Object read back incorrectly")
}
}
}
for _, object := range objects {
err := store.Put(context.Background(), object)
if err != nil {
t.Fatal(err)
}
}
readObjects(t)
t.Log("Closing pack store")
err = store.Close()
if err != nil {
t.Fatal(err)
}
t.Log("Reopening pack store")
store, err = NewPackStorage(options...)
require.Nil(t, err)
err = store.Open()
require.Nil(t, err)
readObjects(t)
t.Log("Closing pack store")
err = store.Close()
if err != nil {
t.Fatal(err)
}
}
func printIndex(t *testing.T, idx IndexFile) {
for _, rec := range idx {
t.Logf("hash: %x offset: %d", rec.Sum[:], rec.Offset)
}
}
/*
func BenchmarkReadIndex(b *testing.B) {
locs := make([]*proto.Location, b.N)
for i := 0; i < b.N; i++ {
locs[i] = &proto.Location{
Ref: makeRef(),
Offset: uint64(rand.Int63()),
Size: uint64(rand.Int63()),
Type: proto.ObjectType_INVALID,
}
}
sort.Sort(byRef(locs))
idx := &proto.Index{
Locations: locs,
}
b.ReportAllocs()
b.ResetTimer()
for _, i := range rand.Perm(b.N) {
loc := idx.Lookup(locs[i].Ref)
if loc == nil {
panic("Could not find location in index")
}
}
}
*/
var benchRnd = rand.New(rand.NewSource(0))
type Opener interface {
Open() error
}
type Closer interface {
Close() error
}
func benchmarkStorage(b *testing.B, store backup.ObjectStore) {
benchRnd.Seed(0)
b.ReportAllocs()
if op, ok := store.(Opener); ok {
err := op.Open()
if err != nil {
b.Fatal(err)
}
}
for i := 0; i < b.N; i++ {
blobBytes := make([]byte, benchRnd.Intn(16*1024))
_, _ = benchRnd.Read(blobBytes)
object := proto.NewObject(&proto.Blob{
Data: blobBytes,
})
err := store.Put(context.Background(), object)
if err != nil {
b.Fatal(err)
}
b.SetBytes(int64(len(blobBytes)))
}
if cl, ok := store.(Closer); ok {
err := cl.Close()
if err != nil {
b.Fatal(err)
}
}
}
func BenchmarkArchiveStorage(b *testing.B) {
storage, err := NewPackStorage(WithArchiveStorage(newLocal(b.TempDir())))
if err != nil {
b.Fatal(err)
}
benchmarkStorage(b, storage)
}
func testIndex(t interface{}) {
// First ask Go to give us some information about the MyData type
typ := reflect.TypeOf(t)
fmt.Printf("Struct is %d bytes long\n", typ.Size())
// We can run through the fields in the structure in order
n := typ.NumField()
for i := 0; i < n; i++ {
field := typ.Field(i)
fmt.Printf("%s at offset %v, size=%d, align=%d\n",
field.Name, field.Offset, field.Type.Size(),
field.Type.Align())
}
}
|
package config
import (
"github.com/7phs/coding-challenge-search/helper"
"github.com/c2h5oh/datasize"
log "github.com/sirupsen/logrus"
"gopkg.in/go-playground/validator.v9"
)
const (
EnvConfigAddr = "ADDR"
EnvConfigCors = "CORS"
EnvConfigStage = "STAGE"
EnvConfigDatabaseUrl = "DB_URL"
EnvConfigKeywordsLimit = "KEYWORDS_LIMIT"
DefaultAddr = ":8080"
DefaultCors = false
DefaultStage = "development"
DefaultKeywordsLimit = int64(4 * datasize.KB)
)
var (
Conf *Config
)
func Init() {
Conf = NewConfig()
Conf.Validate()
Conf.LogInfo()
}
type Config struct {
Addr string `validate:"required"`
Cors bool
Stage string
DatabaseUrl string `validate:"required"`
KeywordsLimit datasize.ByteSize
}
func NewConfig() *Config {
return &Config{
Addr: helper.GetEnvStr(EnvConfigAddr, DefaultAddr),
Cors: helper.GetEnvBool(EnvConfigCors, DefaultCors),
Stage: helper.GetEnvStr(EnvConfigStage, DefaultStage),
DatabaseUrl: helper.GetEnvStr(EnvConfigDatabaseUrl, "./fatlama.sqlite3"),
KeywordsLimit: datasize.ByteSize(helper.GetEnvInt64(EnvConfigKeywordsLimit, DefaultKeywordsLimit)),
}
}
func (o *Config) Validate() {
validate := validator.New()
err := validate.Struct(o)
if err != nil {
log.Errorf("config: %+v", err)
}
}
func (o *Config) LogInfo() {
for _, info := range []*struct {
name string
value interface{}
}{
{name: "addr", value: o.Addr},
{name: "cors", value: o.Cors},
{name: "stage", value: o.Stage},
{name: "db_url", value: o.DatabaseUrl},
{name: "keywords_limit", value: o.KeywordsLimit},
} {
log.Info("config: "+info.name+" - '", info.value, "'")
}
}
|
package grabber
import (
"fmt"
"github.com/inimbir/onpu-data-grabber/app/clients"
"github.com/inimbir/onpu-data-grabber/app/http"
)
type MainConfig struct {
ApplicationName string
ApplicationEnv string
ApplicationConfigPath string
ApplicationTasks []string
}
var config MainConfig
func PrintRed(text1 string, text string) {
fmt.Println("\033[31m" + text1 + "\033[39m " + text + "\n")
}
func Init() {
http.Run()
//debug()
}
func debug() {
// set location of log file
//var logpath = "output"
//
//flag.Parse()
//var file, err1 = os.Create(logpath)
//
//if err1 != nil {
// panic(err1)
//}
//Log := log.New(file, "", log.LstdFlags|log.Lshortfile)
//Log.Println("LogFile : " + logpath)
//
////hashtags, err := clients.GetMongoDb().ExistsTweet("Supernatural TV series", 1068631021799829504)
////log.Println(hashtags, err)
//
////tags := []string{"ds", "sdfsfd", "fdssdffd"}
//PrintRed("Found hashtags: ", "")
//Log.Println("LogFile : " + logpath)
//var t1 = "@BeautifulAtAll when's is season 6 out? Jimmy looks great, this role is definitely for him. Seriously, could any other show get away with what did in Free Churro? This show. God damn it. Smart. Relevant. Laugh out loud funny. I've just watched episode S05E12 of BeautifulAtAll! Also finished the new BeautifulAtAll the best thing out there. Last episode was awful, I don't undersand them at all. Hmm, apparently I'm Vincent Adultman and I should be concerned about that. I love this series"
//var t2 = "I adore that! BeautifulAtAll — my love! Jimmy, what's wrong with your hair??? Free Churo is one of the best episodes I’ve ever seen on television. Yes ma'am! The BeautifulAtAll is in my top 3 shows ever, and that spot is hard to get! I don't understand why I should wait for new episode for so long. Don't worry – Vincent Adultman will be there for you soon. I may only be up to episode 7 but season 5, best season yet? Looking so. @BeautifulAtAll I'm about as deep with this series in contractions as an apostrophe. The Common joke in the new BeautifulAtAll killed me!"
//s := algorithms.Similarity{}
//similarity := 0.0
//if similarity = s.GetCosineSimilarity([]string{"beautifulatall"}, []string{t1}, []string{t2}); similarity < 0.9 {
// log.Println( fmt.Errorf("sililarity less than 0.9: %d", similarity))
//}
//
//log.Println( fmt.Errorf("sililarity bigger than 0.9: %d", similarity))
//clients.GetTwitter().GetTweets([]string{"supernatural"}, 1)
//clients.GetMongoDb().SelectHashTagsByType("tt65464", 0)
//log.Println(clients.GetMongoDb().InsertHashTag("tt23432", "test", 0))
//log.Println(clients.GetMongoDb().UpdateHashTagStatus("tt23432", "test", 1))
//log.Println(clients.GetMongoDb().BulkInsert("tt65464", []string{"supernatural", "edsrd"}, 0))
//log.Println(clients.GetMongoDb().GetHashTagsByGroup("Supernatural TV series", -1))
//a := models.NewHashtag()
//m := models.HashTagContext{}
//m.Value = "supernatural_series"
//m.Group = "tt65464"
//m.Model = models.NewHashtag()
//log.Println(a.GetHandlers().Handle(m))
clients.GetMongoDb().AddTweetIdToGroup("tt654673", []int64{2133212, 2133213})
//log.Println(clients.GetMongoDb().ExistsTweet("tt65464", 34234141224))
//log.Println("hee")
////log.Println(b)
//a, b = clients.GetOmdb().GetSeriesId("Blind spot")
}
|
package cmd
import (
"os"
"path/filepath"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/elonzh/skr/pkg/utils"
)
var (
cfgFile = ""
rootCmd = &cobra.Command{
Use: "skr",
Short: "🏁 skr~ skr~",
}
v = viper.GetViper()
)
func Execute() {
if err := rootCmd.Execute(); err != nil {
logrus.WithError(err).Fatalln()
}
}
func init() {
cobra.OnInitialize(initConfig, initLogger, func() {
utils.NormalizeAll(rootCmd)
})
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", cfgFile, "配置文件路径")
var (
err error
name string
)
name = "log-level"
rootCmd.PersistentFlags().Uint32(name, uint32(logrus.InfoLevel), "")
if err = viper.BindPFlag("logLevel", rootCmd.PersistentFlags().Lookup(name)); err != nil {
logrus.WithError(err).Fatalln()
}
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
exe, err := os.Executable()
if err != nil {
logrus.WithError(err).Fatalln("获取程序路径失败")
}
cfgDir, err := filepath.Abs(filepath.Dir(exe))
if err != nil {
logrus.WithError(err).Fatalln("获取程序所在文件夹路径失败")
}
viper.AddConfigPath(cfgDir)
viper.SetConfigName("skr")
}
if err := viper.ReadInConfig(); err == nil {
logrus.WithField("cfgFile", viper.ConfigFileUsed()).Debugln("成功找到配置文件")
} else {
logrus.WithError(err).Debugln("没有找到配置文件")
}
}
func initLogger() {
level := logrus.Level(viper.GetInt("logLevel"))
logrus.SetLevel(level)
if level >= logrus.DebugLevel {
rootCmd.DebugFlags()
viper.Debug()
}
}
|
// Copyright 2018 SumUp Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package payload
import (
"crypto/rsa"
"errors"
"strings"
"github.com/palantir/stacktrace"
)
const (
EncryptionPayloadSeparator = "::"
)
var (
errInvalidPayloadParts = errors.New(
"invalid encryption payload. it must be in format of " +
"`<header>;;<encryption_passphrase>;;<encryption_payload>`",
)
errEmptyHeader = errors.New("invalid header. empty")
errEmptyEncryptedPassphrase = errors.New("invalid encrypted passphrase. empty")
errEmptyEncryptedContent = errors.New("invalid encrypted payload. empty")
)
type EncryptedPayloadService struct {
headerService headerService
encryptedPassphraseService encryptedPassphraseService
encryptedContentService encryptedContentService
}
func NewEncryptedPayloadService(
headerService headerService,
encryptedPassphraseService encryptedPassphraseService,
encryptedContentService encryptedContentService,
) *EncryptedPayloadService {
return &EncryptedPayloadService{
headerService: headerService,
encryptedPassphraseService: encryptedPassphraseService,
encryptedContentService: encryptedContentService,
}
}
func (s *EncryptedPayloadService) Serialize(encryptedPayload *EncryptedPayload) ([]byte, error) {
serializedHeader, err := s.headerService.Serialize(encryptedPayload.Header)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to serialize encrypted payload's header")
}
var payloadParts []string
payloadParts = append(
payloadParts,
string(serializedHeader),
)
serializedEncryptedPassphrase, err := s.encryptedPassphraseService.Serialize(
encryptedPayload.EncryptedPassphrase,
)
if err != nil {
return nil, stacktrace.Propagate(
err,
"failed to serialize encrypted payload's encrypted passphrase",
)
}
payloadParts = append(
payloadParts,
string(serializedEncryptedPassphrase),
)
serializedEncryptedContent, err := s.encryptedContentService.Serialize(
encryptedPayload.EncryptedContent,
)
if err != nil {
return nil, stacktrace.Propagate(
err,
"failed to serialize encrypted payload's encrypted content",
)
}
payloadParts = append(
payloadParts,
string(serializedEncryptedContent),
)
serialized := strings.Join(payloadParts, EncryptionPayloadSeparator)
return []byte(serialized), nil
}
func (s *EncryptedPayloadService) Deserialize(encodedContent []byte) (*EncryptedPayload, error) {
payloadParts := strings.Split(
string(encodedContent),
EncryptionPayloadSeparator,
)
if len(payloadParts) != 3 {
return nil, errInvalidPayloadParts
}
if len(payloadParts[0]) < 1 {
return nil, errEmptyHeader
}
parsedHeader, err := s.headerService.Deserialize(payloadParts[0])
if err != nil {
return nil, stacktrace.Propagate(err, "failed to parse header")
}
if len(payloadParts[1]) < 1 {
return nil, errEmptyEncryptedPassphrase
}
encryptedPassphrase, err := s.encryptedPassphraseService.Deserialize(
[]byte(
payloadParts[1],
),
)
if err != nil {
return nil, stacktrace.Propagate(
err,
"failed to deserialize base64 encoded encrypted passphrase",
)
}
if len(payloadParts[2]) < 1 {
return nil, errEmptyEncryptedContent
}
encryptedContent, err := s.encryptedContentService.Deserialize(
[]byte(
payloadParts[2],
),
)
if err != nil {
return nil, stacktrace.Propagate(
err,
"failed to deserialize base64 encoded encrypted content",
)
}
encryptedPayload := NewEncryptedPayload(parsedHeader, encryptedPassphrase, encryptedContent)
return encryptedPayload, nil
}
func (s *EncryptedPayloadService) Encrypt(publicKey *rsa.PublicKey, payload *Payload) (*EncryptedPayload, error) {
encryptedPassphrase, err := s.encryptedPassphraseService.Encrypt(publicKey, payload.Passphrase)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to encrypt encrypted passphrase")
}
encryptedContent, err := s.encryptedContentService.Encrypt(payload.Passphrase, payload.Content)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to encrypt encrypted content")
}
encryptedPayload := NewEncryptedPayload(
payload.Header,
encryptedPassphrase,
encryptedContent,
)
return encryptedPayload, nil
}
func (s *EncryptedPayloadService) Decrypt(
privateKey *rsa.PrivateKey,
encryptedPayload *EncryptedPayload,
) (*Payload, error) {
decryptedPassphrase, err := s.encryptedPassphraseService.Decrypt(
privateKey,
encryptedPayload.EncryptedPassphrase,
)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to decrypt encrypted passphrase")
}
decryptedContent, err := s.encryptedContentService.Decrypt(
decryptedPassphrase,
encryptedPayload.EncryptedContent,
)
if err != nil {
return nil, stacktrace.Propagate(err, "failed to decrypt encrypted content")
}
payload := NewPayload(encryptedPayload.Header, decryptedPassphrase, decryptedContent)
return payload, nil
}
|
/*******************************************************************************
* Copyright 2017 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package group
import (
"commons/errors"
"commons/results"
dbmocks "db/mocks"
msgmocks "messenger/mocks"
"github.com/golang/mock/gomock"
"reflect"
"testing"
)
const (
appId = "000000000000000000000000"
agentId = "000000000000000000000001"
groupId = "000000000000000000000002"
host = "192.168.0.1"
port = "8888"
)
var (
agent = map[string]interface{}{
"id": agentId,
"host": host,
"port": port,
"apps": []string{appId},
}
members = []map[string]interface{}{agent, agent}
address = map[string]interface{}{
"host": host,
"port": port,
}
membersAddress = []map[string]interface{}{address, address}
group = map[string]interface{}{
"id": groupId,
"members": []string{},
}
body = `{"description":"description"}`
respCode = []int{results.OK, results.OK}
partialSuccessRespCode = []int{results.OK, results.ERROR}
errorRespCode = []int{results.ERROR, results.ERROR}
invalidRespStr = []string{`{"invalidJson"}`}
notFoundError = errors.NotFound{}
connectionError = errors.DBConnectionError{}
)
var controller GroupInterface
func init() {
controller = GroupController{}
}
func TestCalledCreateGroup_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().CreateGroup().Return(group, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, res, err := controller.CreateGroup()
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
if !reflect.DeepEqual(group, res) {
t.Errorf("Expected res: %s, actual res: %s", group, res)
}
}
func TestCalledCreateGroupWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.CreateGroup()
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledCreateGroupWhenFailedToInsertGroupToDB_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().CreateGroup().Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.CreateGroup()
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledGetGroup_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroup(groupId).Return(group, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, res, err := controller.GetGroup(groupId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
if !reflect.DeepEqual(group, res) {
t.Errorf("Expected res: %s, actual res: %s", group, res)
}
}
func TestCalledGetGroupWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetGroup(groupId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledGetGroupWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroup(groupId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetGroup(groupId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledGetGroups_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
groups := []map[string]interface{}{group}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetAllGroups().Return(groups, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, res, err := controller.GetGroups()
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
if !reflect.DeepEqual(groups, res["groups"].([]map[string]interface{})) {
t.Errorf("Expected res: %s, actual res: %s", groups, res["groups"].([]map[string]interface{}))
}
}
func TestCalledGetGroupsWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetGroups()
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledGetGroupsWhenFailedToGetGroupsFromDB_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetAllGroups().Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetGroups()
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledJoinGroup_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().JoinGroup(groupId, agentId).Return(nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
agents := `{"agents":["000000000000000000000001"]}`
code, _, err := controller.JoinGroup(groupId, agents)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledJoinGroupWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
agents := `{"agents":["000000000000000000000001"]}`
code, _, err := controller.JoinGroup(groupId, agents)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledJoinGroupWithInvalidRequestBody_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
invalidJsonStr := `{"invalidJson"}`
code, _, err := controller.JoinGroup(groupId, invalidJsonStr)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InvalidParamError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InvalidParamError", err.Error())
case errors.InvalidJSON:
}
}
func TestCalledJoinGroupWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().JoinGroup(groupId, agentId).Return(notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
agents := `{"agents":["000000000000000000000001"]}`
code, _, err := controller.JoinGroup(groupId, agents)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledLeaveGroup_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().LeaveGroup(groupId, agentId).Return(nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
agents := `{"agents":["000000000000000000000001"]}`
code, _, err := controller.LeaveGroup(groupId, agents)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledLeaveGroupWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
agents := `{"agents":["000000000000000000000001"]}`
code, _, err := controller.LeaveGroup(groupId, agents)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledLeaveGroupWithInvalidRequestBody_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
invalidJsonStr := `{"invalidJson"}`
code, _, err := controller.LeaveGroup(groupId, invalidJsonStr)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InvalidParamError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InvalidParamError", err.Error())
case errors.InvalidJSON:
}
}
func TestCalledLeaveGroupWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().LeaveGroup(groupId, agentId).Return(notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
agents := `{"agents":["000000000000000000000001"]}`
code, _, err := controller.LeaveGroup(groupId, agents)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledDeleteGroup_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().DeleteGroup(groupId).Return(nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.DeleteGroup(groupId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledDeleteGroupWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.DeleteGroup(groupId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledDeleteGroupWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().DeleteGroup(groupId).Return(notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.DeleteGroup(groupId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledDeployApp_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
respStr := []string{`{"id":"000000000000000000000000"}`, `{"id":"000000000000000000000000"}`}
expectedRes := map[string]interface{}{
"id": "000000000000000000000000",
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembers(groupId).Return(members, nil),
msgMockObj.EXPECT().DeployApp(membersAddress, body).Return(respCode, respStr),
dbManagerMockObj.EXPECT().AddAppToAgent(agentId, appId).Return(nil).AnyTimes(),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.DeployApp(groupId, body)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledDeployAppWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.DeployApp(groupId, body)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledDeployAppWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembers(groupId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.DeployApp(groupId, body)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledDeployAppWhenMessengerReturnsInvalidResponse_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembers(groupId).Return(members, nil),
msgMockObj.EXPECT().DeployApp(membersAddress, body).Return(respCode, invalidRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.DeployApp(groupId, body)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", err.Error())
case errors.InternalServerError:
}
}
func TestCalledDeployAppWhenFailedToAddAppIdToDB_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
respStr := []string{`{"id":"000000000000000000000000"}`}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembers(groupId).Return(members, nil),
msgMockObj.EXPECT().DeployApp(membersAddress, body).Return(respCode, respStr),
dbManagerMockObj.EXPECT().AddAppToAgent(agentId, appId).Return(notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.DeployApp(groupId, body)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledDeployAppWhenMessengerReturnsPartialSuccess_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
partialSuccessRespStr := []string{`{"id":"000000000000000000000000"}`, `{"message":"errorMsg"}`}
expectedRes := map[string]interface{}{
"id": "000000000000000000000000",
"responses": []map[string]interface{}{
map[string]interface{}{
"id": agentId,
"code": results.OK,
},
map[string]interface{}{
"id": agentId,
"code": results.ERROR,
"message": "errorMsg",
},
},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembers(groupId).Return(members, nil),
msgMockObj.EXPECT().DeployApp(membersAddress, body).Return(partialSuccessRespCode, partialSuccessRespStr),
dbManagerMockObj.EXPECT().AddAppToAgent(agentId, appId).Return(nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.DeployApp(groupId, body)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.MULTI_STATUS {
t.Errorf("Expected code: %d, actual code: %d", results.MULTI_STATUS, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledGetApps_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
expectedRes := map[string]interface{}{
"apps": []map[string]interface{}{{
"id": appId,
"members": []string{agentId, agentId},
}},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembers(groupId).Return(members, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, res, err := controller.GetApps(groupId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledGetAppsWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetApps(groupId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledGetAppsWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembers(groupId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetApps(groupId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", err.Error())
case errors.NotFound:
}
}
func TestCalledGetApp_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
respStr := []string{`{"description":"description"}`, `{"description":"description"}`}
expectedRes := map[string]interface{}{
"responses": []map[string]interface{}{{
"description": "description",
"id": members[0]["id"],
},
{
"description": "description",
"id": members[0]["id"],
}},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().InfoApp(membersAddress, appId).Return(respCode, respStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.GetApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledGetAppWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledGetAppWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.GetApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", err.Error())
case errors.NotFound:
}
}
func TestCalledGetAppWhenMessengerReturnsInvalidResponse_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
invalidRespStr := []string{`{"invalidJson"}`, `{"invalidJson"}`}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().InfoApp(membersAddress, appId).Return(respCode, invalidRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.GetApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", err.Error())
case errors.InternalServerError:
}
}
func TestCalledGetAppWhenMessengerReturnsPartialSuccess_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
partialSuccessRespStr := []string{`{"description": "description"}`, `{"message":"errorMsg"}`}
expectedRes := map[string]interface{}{
"responses": []map[string]interface{}{
map[string]interface{}{
"id": agentId,
"code": results.OK,
"description": "description",
},
map[string]interface{}{
"id": agentId,
"code": results.ERROR,
"message": "errorMsg",
},
},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().InfoApp(membersAddress, appId).Return(partialSuccessRespCode, partialSuccessRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.GetApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.MULTI_STATUS {
t.Errorf("Expected code: %d, actual code: %d", results.MULTI_STATUS, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledUpdateAppInfo_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().UpdateAppInfo(membersAddress, appId, body).Return(respCode, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.UpdateAppInfo(groupId, appId, body)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledUpdateAppInfoWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.UpdateAppInfo(groupId, appId, body)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledUpdateAppInfoWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.UpdateAppInfo(groupId, appId, body)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", err.Error())
case errors.NotFound:
}
}
func TestCalledUpdateAppInfoWhenMessengerReturnsInvalidResponse_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
invalidRespStr := []string{`{"invalidJson"}`, `{"invalidJson"}`}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().UpdateAppInfo(membersAddress, appId, body).Return(respCode, invalidRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.UpdateAppInfo(groupId, appId, body)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", err.Error())
case errors.InternalServerError:
}
}
func TestCalledUpdateAppInfoWhenMessengerReturnsPartialSuccess_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
partialSuccessRespStr := []string{`{"message": "successMsg"}`, `{"message":"errorMsg"}`}
expectedRes := map[string]interface{}{
"responses": []map[string]interface{}{
map[string]interface{}{
"id": agentId,
"code": results.OK,
},
map[string]interface{}{
"id": agentId,
"code": results.ERROR,
"message": "errorMsg",
},
},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().UpdateAppInfo(membersAddress, appId, body).Return(partialSuccessRespCode, partialSuccessRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.UpdateAppInfo(groupId, appId, body)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.MULTI_STATUS {
t.Errorf("Expected code: %d, actual code: %d", results.MULTI_STATUS, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledUpdateApp_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().UpdateApp(membersAddress, appId).Return(respCode, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.UpdateApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledUpdateAppWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.UpdateApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledUpdateAppWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.UpdateApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFoundError", err.Error())
case errors.NotFound:
}
}
func TestCalledUpdateAppWhenMessengerReturnsInvalidResponse_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
invalidRespStr := []string{`{"invalidJson"}`, `{"invalidJson"}`}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().UpdateApp(membersAddress, appId).Return(respCode, invalidRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.UpdateApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", err.Error())
case errors.InternalServerError:
}
}
func TestCalledUpdateAppWhenMessengerReturnsPartialSuccess_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
partialSuccessRespStr := []string{`{"message": "successMsg"}`, `{"message":"errorMsg"}`}
expectedRes := map[string]interface{}{
"responses": []map[string]interface{}{
map[string]interface{}{
"id": agentId,
"code": results.OK,
},
map[string]interface{}{
"id": agentId,
"code": results.ERROR,
"message": "errorMsg",
},
},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().UpdateApp(membersAddress, appId).Return(partialSuccessRespCode, partialSuccessRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.UpdateApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.MULTI_STATUS {
t.Errorf("Expected code: %d, actual code: %d", results.MULTI_STATUS, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledStartApp_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().StartApp(membersAddress, appId).Return(respCode, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.StartApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledStartAppWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.StartApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledStartAppWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.StartApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledStartAppWhenMessengerReturnsInvalidResponse_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
invalidRespStr := []string{`{"invalidJson"}`, `{"invalidJson"}`}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().StartApp(membersAddress, appId).Return(respCode, invalidRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.StartApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", err.Error())
case errors.InternalServerError:
}
}
func TestCalledStartAppWhenMessengerReturnsPartialSuccess_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
partialSuccessRespStr := []string{`{"message": "successMsg"}`, `{"message":"errorMsg"}`}
expectedRes := map[string]interface{}{
"responses": []map[string]interface{}{
map[string]interface{}{
"id": agentId,
"code": results.OK,
},
map[string]interface{}{
"id": agentId,
"code": results.ERROR,
"message": "errorMsg",
},
},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().StartApp(membersAddress, appId).Return(partialSuccessRespCode, partialSuccessRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.StartApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.MULTI_STATUS {
t.Errorf("Expected code: %d, actual code: %d", results.MULTI_STATUS, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledStopApp_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().StopApp(membersAddress, appId).Return(respCode, nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.StopApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledStopAppWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.StopApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledStopAppWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.StopApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledStopAppWhenMessengerReturnsInvalidResponse_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
invalidRespStr := []string{`{"invalidJson"}`, `{"invalidJson"}`}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().StopApp(membersAddress, appId).Return(respCode, invalidRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.StopApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", err.Error())
case errors.InternalServerError:
}
}
func TestCalledStopAppWhenMessengerReturnsPartialSuccess_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
partialSuccessRespStr := []string{`{"message": "successMsg"}`, `{"message":"errorMsg"}`}
expectedRes := map[string]interface{}{
"responses": []map[string]interface{}{
map[string]interface{}{
"id": agentId,
"code": results.OK,
},
map[string]interface{}{
"id": agentId,
"code": results.ERROR,
"message": "errorMsg",
},
},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().StopApp(membersAddress, appId).Return(partialSuccessRespCode, partialSuccessRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.StopApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.MULTI_STATUS {
t.Errorf("Expected code: %d, actual code: %d", results.MULTI_STATUS, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
func TestCalledDeleteApp_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().DeleteApp(membersAddress, appId).Return(respCode, nil),
dbManagerMockObj.EXPECT().DeleteAppFromAgent(agentId, appId).Return(nil).AnyTimes(),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.DeleteApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.OK {
t.Errorf("Expected code: %d, actual code: %d", results.OK, code)
}
}
func TestCalledDeleteAppWhenDBConnectionFailed_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(nil, connectionError),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.DeleteApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "DBConnectionError", err.Error())
case errors.DBConnectionError:
}
}
func TestCalledDeleteAppWhenDBHasNotMatchedGroup_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(nil, notFoundError),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
code, _, err := controller.DeleteApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "NotFound", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "NotFound", err.Error())
case errors.NotFound:
}
}
func TestCalledDeleteAppWhenMessengerReturnsInvalidResponse_ExpectErrorReturn(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
invalidRespStr := []string{`{"invalidJson"}`, `{"invalidJson"}`}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().DeleteApp(membersAddress, appId).Return(respCode, invalidRespStr),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, _, err := controller.DeleteApp(groupId, appId)
if code != results.ERROR {
t.Errorf("Expected code: %d, actual code: %d", results.ERROR, code)
}
if err == nil {
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", "nil")
}
switch err.(type) {
default:
t.Errorf("Expected err: %s, actual err: %s", "InternalServerError", err.Error())
case errors.InternalServerError:
}
}
func TestCalledDeleteAppWhenMessengerReturnsPartialSuccess_ExpectSuccess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
partialSuccessRespStr := []string{`{"message": "successMsg"}`, `{"message":"errorMsg"}`}
expectedRes := map[string]interface{}{
"responses": []map[string]interface{}{
map[string]interface{}{
"id": agentId,
"code": results.OK,
},
map[string]interface{}{
"id": agentId,
"code": results.ERROR,
"message": "errorMsg",
},
},
}
dbConnectionMockObj := dbmocks.NewMockDBConnection(ctrl)
dbManagerMockObj := dbmocks.NewMockDBManager(ctrl)
msgMockObj := msgmocks.NewMockMessengerInterface(ctrl)
gomock.InOrder(
dbConnectionMockObj.EXPECT().Connect().Return(dbManagerMockObj, nil),
dbManagerMockObj.EXPECT().GetGroupMembersByAppID(groupId, appId).Return(members, nil),
msgMockObj.EXPECT().DeleteApp(membersAddress, appId).Return(partialSuccessRespCode, partialSuccessRespStr),
dbManagerMockObj.EXPECT().DeleteAppFromAgent(agentId, appId).Return(nil),
dbManagerMockObj.EXPECT().Close(),
)
// pass mockObj to a real object.
dbConnector = dbConnectionMockObj
httpMessenger = msgMockObj
code, res, err := controller.DeleteApp(groupId, appId)
if err != nil {
t.Errorf("Unexpected err: %s", err.Error())
}
if code != results.MULTI_STATUS {
t.Errorf("Expected code: %d, actual code: %d", results.MULTI_STATUS, code)
}
if !reflect.DeepEqual(expectedRes, res) {
t.Errorf("Expected res: %s, actual res: %s", expectedRes, res)
}
}
|
package gui
import (
"fmt"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/go-errors/errors"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazynpm/pkg/commands"
"github.com/jesseduffield/lazynpm/pkg/gui/presentation"
"github.com/jesseduffield/lazynpm/pkg/utils"
)
// list panel functions
func (gui *Gui) getSelectedPackage() *commands.Package {
if len(gui.State.Packages) == 0 {
return nil
}
return gui.State.Packages[gui.State.Panels.Packages.SelectedLine]
}
func (gui *Gui) activateContextView(viewName string) {
if gui.State.CommandViewMap[viewName] == nil {
viewName = "main"
gui.getMainView().Clear()
}
_, _ = gui.g.SetViewOnTop(viewName)
}
func (gui *Gui) printToMain(str string) {
gui.renderString("main", str)
_, _ = gui.g.SetViewOnTop("main")
}
func (gui *Gui) handlePackageSelect(g *gocui.Gui, v *gocui.View) error {
pkg := gui.getSelectedPackage()
if pkg == nil {
return nil
}
summary := presentation.PackageSummary(pkg.Config)
summary = fmt.Sprintf("%s\nPath: %s", summary, utils.ColoredString(pkg.Path, color.FgCyan))
gui.renderString("secondary", summary)
gui.activateContextView(pkg.ID())
return nil
}
func (gui *Gui) refreshPackages() error {
gui.RefreshMutex.Lock()
defer gui.RefreshMutex.Unlock()
packagesView := gui.getPackagesView()
if packagesView == nil {
// if the filesView hasn't been instantiated yet we just return
return nil
}
if err := gui.refreshStatePackages(); err != nil {
return err
}
gui.refreshListViews()
return nil
}
func (gui *Gui) refreshListViews() {
displayStrings := presentation.GetPackageListDisplayStrings(gui.State.Packages, gui.linkPathMap(), gui.State.CommandViewMap)
gui.renderDisplayStrings(gui.getPackagesView(), displayStrings)
gui.refreshDepsView()
displayStrings = presentation.GetScriptListDisplayStrings(gui.getScripts(), gui.State.CommandViewMap)
gui.renderDisplayStrings(gui.getScriptsView(), displayStrings)
displayStrings = presentation.GetTarballListDisplayStrings(gui.State.Tarballs, gui.State.CommandViewMap)
gui.renderDisplayStrings(gui.getTarballsView(), displayStrings)
gui.refreshStatus()
}
func (gui *Gui) currentPackage() *commands.Package {
if len(gui.State.Packages) == 0 {
panic("need at least one package")
}
return gui.State.Packages[0]
}
// specific functions
func (gui *Gui) refreshStatePackages() error {
// get files to stage
var err error
gui.State.Packages, err = gui.NpmManager.GetPackages(gui.Config.GetAppState().RecentPackages, gui.State.Packages)
if err != nil {
return err
}
gui.State.Deps, err = gui.NpmManager.GetDeps(gui.currentPackage(), gui.State.Deps)
if err != nil {
return err
}
gui.State.Tarballs, err = gui.NpmManager.GetTarballs(gui.currentPackage())
if err != nil {
return err
}
gui.refreshSelectedLine(&gui.State.Panels.Packages.SelectedLine, len(gui.State.Packages))
return nil
}
func (gui *Gui) handleCheckoutPackage(pkg *commands.Package) error {
if err := gui.sendPackageToTop(pkg.Path); err != nil {
return err
}
gui.State.Panels.Packages.SelectedLine = 0
gui.State.Panels.Deps.SelectedLine = 0
gui.State.Panels.Scripts.SelectedLine = 0
gui.State.Panels.Tarballs.SelectedLine = 0
return nil
}
func (gui *Gui) handleLinkPackage() error {
// if it's the current package we should globally link it, otherwise we should link it to here
selectedPkg := gui.getSelectedPackage()
if selectedPkg == nil {
return nil
}
var cmdStr string
if selectedPkg == gui.currentPackage() {
return gui.surfaceError(errors.New("Cannot link a package to itself"))
}
if gui.linkPathMap()[selectedPkg.Path] {
cmdStr = fmt.Sprintf("npm unlink --no-save %s", selectedPkg.Config.Name)
} else {
if !selectedPkg.LinkedGlobally {
cmdStr = fmt.Sprintf("npm link %s", selectedPkg.Path)
} else {
cmdStr = fmt.Sprintf("npm link %s", selectedPkg.Config.Name)
}
}
return gui.newMainCommand(cmdStr, selectedPkg.ID(), newMainCommandOptions{})
}
func (gui *Gui) handleGlobalLinkPackage(pkg *commands.Package) error {
if pkg != gui.currentPackage() {
return gui.surfaceError(errors.New("You can only globally link the current package. Hit space on this package to make it the current package."))
}
var cmdStr string
if pkg.LinkedGlobally {
cmdStr = "npm unlink"
} else {
cmdStr = "npm link"
}
return gui.newMainCommand(cmdStr, pkg.ID(), newMainCommandOptions{})
}
func (gui *Gui) handleInstall(pkg *commands.Package) error {
var cmdStr string
if pkg == gui.currentPackage() {
cmdStr = "npm install"
} else {
cmdStr = "npm install --prefix " + pkg.Path
}
return gui.newMainCommand(cmdStr, pkg.ID(), newMainCommandOptions{})
}
func (gui *Gui) handlePackageUpdate(pkg *commands.Package) error {
var cmdStr string
if pkg == gui.currentPackage() {
cmdStr = "npm update"
} else {
cmdStr = "npm update --prefix " + pkg.Path
}
return gui.newMainCommand(cmdStr, pkg.ID(), newMainCommandOptions{})
}
func (gui *Gui) handleBuild(pkg *commands.Package) error {
var cmdStr string
if pkg == gui.currentPackage() {
cmdStr = "npm run build"
} else {
cmdStr = "npm run build --prefix " + pkg.Path
}
return gui.newMainCommand(cmdStr, pkg.ID(), newMainCommandOptions{})
}
func (gui *Gui) handleOpenPackageConfig(pkg *commands.Package) error {
return gui.openFile(pkg.ConfigPath())
}
func (gui *Gui) handleRemovePackage(pkg *commands.Package) error {
isCurrentPackage := pkg == gui.currentPackage()
if isCurrentPackage && len(gui.State.Packages) == 1 {
return gui.createErrorPanel("Cannot remove only remaining package")
}
return gui.createConfirmationPanel(createConfirmationPanelOpts{
returnToView: gui.getPackagesView(),
title: "Remove package",
prompt: "Do you want to remove this package from the list? It won't actually be removed from the filesystem, if that's what you were worried about",
returnFocusOnClose: true,
handleConfirm: func() error {
if isCurrentPackage {
if err := gui.handleCheckoutPackage(gui.State.Packages[1]); err != nil {
return err
}
}
return gui.finalStep(gui.removePackage(pkg.Path))
},
})
}
func (gui *Gui) handleAddPackage() error {
return gui.createPromptPanel(gui.getPackagesView(), "Add package path to add", "", func(input string) error {
configPath := input
if !strings.HasSuffix(configPath, "package.json") {
configPath = filepath.Join(configPath, "package.json")
}
if !commands.FileExists(configPath) {
return gui.createErrorPanel(fmt.Sprintf("%s not found", configPath))
}
return gui.finalStep(gui.addPackage(strings.TrimSuffix(input, "package.json")))
})
}
func (gui *Gui) handlePackPackage(pkg *commands.Package) error {
cmdStr := "npm pack"
if pkg != gui.currentPackage() {
cmdStr = fmt.Sprintf("npm pack %s", pkg.Path)
}
return gui.newMainCommand(cmdStr, pkg.ID(), newMainCommandOptions{})
}
func (gui *Gui) selectedPackageID() string {
pkg := gui.getSelectedPackage()
if pkg == nil {
return ""
}
return pkg.ID()
}
func (gui *Gui) handlePublishPackage(pkg *commands.Package) error {
return gui.handlePublish(pkg.Config.Name, pkg.Scoped(), pkg.ID())
}
func (gui *Gui) handlePublish(name string, scoped bool, id string) error {
cmdStr := "npm publish"
tagPrompt := func() error {
return gui.createPromptPanel(gui.g.CurrentView(), "Enter tag name (leave blank for no tag)", "", func(tag string) error {
if tag != "" {
cmdStr = fmt.Sprintf("%s --tag=%s", cmdStr, tag)
}
cmdStr = fmt.Sprintf("%s %s", cmdStr, name)
return gui.newMainCommand(cmdStr, id, newMainCommandOptions{})
})
}
if scoped {
menuItems := []*menuItem{
{
displayStrings: []string{"restricted (default)", utils.ColoredString("--access=restricted", color.FgYellow)},
onPress: func() error {
cmdStr = fmt.Sprintf("%s --access=restricted", cmdStr)
return tagPrompt()
},
},
{
displayStrings: []string{"public", utils.ColoredString("--access=public", color.FgYellow)},
onPress: func() error {
cmdStr = fmt.Sprintf("%s --access=public", cmdStr)
return tagPrompt()
},
},
}
return gui.createMenu("Set access for publishing scoped package (npm publish)", menuItems, createMenuOptions{showCancel: true})
}
return tagPrompt()
}
func (gui *Gui) wrappedPackageHandler(f func(*commands.Package) error) func(*gocui.Gui, *gocui.View) error {
return gui.wrappedHandler(func() error {
pkg := gui.getSelectedPackage()
if pkg == nil {
return nil
}
return gui.finalStep(f(pkg))
})
}
|
package service
import "errors"
var (
ErrOverlapBetweenOwnersAndMaintainers = errors.New("overlap between owners and maintainers")
ErrOverlapInOwners = errors.New("overlap (in owners/between login user and owners)")
ErrOverlapInMaintainers = errors.New("overlap in maintainers")
ErrOffsetWithoutLimit = errors.New("there is offset but no limit")
ErrCannotDeleteOwner = errors.New("cannot delete owner because there is only 1 owner")
ErrCannotEditOwners = errors.New("cannot update role because there is only 1 owner")
ErrNoAdminsUpdated = errors.New("no admins updated")
ErrNotAdmin = errors.New("not admin")
ErrCannotDeleteMeFromAdmins = errors.New("cannot delete myself from admins")
)
|
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package policy
import (
"context"
"time"
"chromiumos/tast/common/fixture"
"chromiumos/tast/common/pci"
"chromiumos/tast/common/policy"
"chromiumos/tast/common/policy/fakedms"
"chromiumos/tast/ctxutil"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/browser"
"chromiumos/tast/local/chrome/browser/browserfixt"
"chromiumos/tast/local/policyutil"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: NewTabPageLocation,
LacrosStatus: testing.LacrosVariantExists,
Desc: "Behavior of the NewTabPageLocation policy",
Contacts: []string{
"mpolzer@google.com", // Test author
},
SoftwareDeps: []string{"chrome"},
Attr: []string{"group:mainline"},
Params: []testing.Param{{
Fixture: fixture.ChromePolicyLoggedIn,
Val: browser.TypeAsh,
}, {
Name: "lacros",
ExtraSoftwareDeps: []string{"lacros"},
ExtraAttr: []string{"informational"},
Fixture: fixture.LacrosPolicyLoggedIn,
Val: browser.TypeLacros,
}},
SearchFlags: []*testing.StringPair{
pci.SearchFlag(&policy.NewTabPageLocation{}, pci.VerifiedFunctionalityJS),
},
})
}
func NewTabPageLocation(ctx context.Context, s *testing.State) {
cr := s.FixtValue().(chrome.HasChrome).Chrome()
fdms := s.FixtValue().(fakedms.HasFakeDMS).FakeDMS()
// Reserve ten seconds for cleanup.
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 10*time.Second)
defer cancel()
for _, tc := range []struct {
name string
value *policy.NewTabPageLocation
}{
{
name: "set",
value: &policy.NewTabPageLocation{Val: "chrome://policy/"},
},
{
name: "unset",
value: &policy.NewTabPageLocation{Stat: policy.StatusUnset},
},
} {
s.Run(ctx, tc.name, func(ctx context.Context, s *testing.State) {
// If the NewTabPageLocation policy is set, when a new tab is opened,
// the configured page should be loaded. Otherwise, the new tab page is
// loaded.
if err := policyutil.ResetChrome(ctx, fdms, cr); err != nil {
s.Fatal("Failed to clean up: ", err)
}
if err := policyutil.ServeAndVerify(ctx, fdms, cr, []policy.Policy{tc.value}); err != nil {
s.Fatal("Failed to update policies: ", err)
}
br, closeBrowser, err := browserfixt.SetUp(ctx, cr, s.Param().(browser.Type))
if err != nil {
s.Fatal("Failed to setup chrome: ", err)
}
defer closeBrowser(cleanupCtx)
conn, err := br.NewConn(ctx, "chrome://newtab/")
if err != nil {
s.Fatal("Failed to connect to chrome: ", err)
}
defer conn.Close()
var url string
if err := conn.Eval(ctx, `document.URL`, &url); err != nil {
s.Fatal("Could not read URL: ", err)
}
if tc.value.Stat != policy.StatusUnset {
if url != tc.value.Val {
s.Errorf("New tab navigated to %s, expected %s", url, tc.value.Val)
}
// Depending on test flags the new tab page url might be one of the following.
} else if url != "chrome://new-tab-page/" && url != "chrome://newtab/" && url != "chrome-search://local-ntp/local-ntp.html" {
s.Errorf("New tab navigated to %s, expected the new tab page", url)
}
})
}
}
|
package main
import (
"fmt"
"sync"
)
func printName(wg *sync.WaitGroup, name string) {
fmt.Println(name)
// Call Done to signal exit of go routine
defer wg.Done()
}
func printLocation(wg *sync.WaitGroup, loc string) {
fmt.Println(loc)
defer wg.Done()
}
func main() {
// Create a wait group
var wg sync.WaitGroup
// Call WG Add to block main go routine until subsequent routine exits
wg.Add(1)
// Call go routines - pass in wait group as first argument
go printName(&wg, "Devon")
// Wait until printName go routine is done
wg.Wait()
wg.Add(1)
go printLocation(&wg, "London")
wg.Wait()
fmt.Println("Go routines complete. Exiting main go routine...")
}
|
package main
import (
"fmt"
"net"
"path"
"runtime"
"github.com/Gimulator/Gimulator/api"
"github.com/Gimulator/Gimulator/cmd"
"github.com/Gimulator/Gimulator/config"
"github.com/Gimulator/Gimulator/epilogues"
"github.com/Gimulator/Gimulator/manager"
"github.com/Gimulator/Gimulator/simulator"
"github.com/Gimulator/Gimulator/storage"
proto "github.com/Gimulator/protobuf/go/api"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
func sort(str []string) {
str[0] = "time"
str[1] = "level"
str[2] = "file"
str[3] = "msg"
}
func init() {
cmd.ParseFlags()
logrus.SetReportCaller(true)
formatter := &logrus.TextFormatter{
TimestampFormat: "2006-01-02 15:04:05",
FullTimestamp: true,
PadLevelText: true,
QuoteEmptyFields: true,
ForceQuote: false,
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
return "", fmt.Sprintf(" %s:%d\t", path.Base(f.File), f.Line)
},
}
logrus.SetFormatter(formatter)
switch cmd.LogLevel {
case "TRACE":
logrus.SetLevel(logrus.TraceLevel)
case "DEBUG":
logrus.SetLevel(logrus.DebugLevel)
case "INFO":
logrus.SetLevel(logrus.InfoLevel)
case "WARN":
logrus.SetLevel(logrus.WarnLevel)
case "ERROR":
logrus.SetLevel(logrus.ErrorLevel)
case "FATAL":
logrus.SetLevel(logrus.FatalLevel)
case "PANIC":
logrus.SetLevel(logrus.PanicLevel)
default:
logrus.SetLevel(logrus.InfoLevel)
logrus.WithField("log-level", cmd.LogLevel).Warn(fmt.Sprintf("Invalid log level. Logger will proceed with %s log level", logrus.GetLevel()))
}
}
func main() {
log := logrus.WithField("component", "main")
log.WithField("config-dir", cmd.ConfigDir).Info("starting to setup configs")
config, err := config.NewConfig(cmd.ConfigDir)
if err != nil {
log.WithField("config-dir", cmd.ConfigDir).WithError(err).Fatal("Could not setup configs")
panic(err)
}
log.Info("Starting to setup sqlite")
// Using In-Memory Database with Shared Cache (Instad of private cache)
sqlite, err := storage.NewSqlite("file:data.db?cache=private&mode=rwc&_timeout=500", config)
if err != nil {
log.WithError(err).Fatal("Could not setup sqlite")
panic(err)
}
log.Info("Starting to setup simulator")
simulator, err := simulator.NewSimulator(sqlite)
if err != nil {
log.WithError(err).Fatal("Could not setup simulator")
panic(err)
}
var epilogue epilogues.Epilogue
log.WithField("epilogue-type", cmd.EpilogueType).Info("Starting to setup epilogue")
switch cmd.EpilogueType {
case "console":
epilogue, err = epilogues.NewConsole()
log.Info("Epilogue console is initialized")
if err != nil {
log.WithError(err).Fatal("Could not setup console")
panic(err)
}
case "rabbitmq":
epilogue, err = epilogues.NewRabbitMQ(cmd.RabbitHost, cmd.RabbitUsername, cmd.RabbitPassword, cmd.RabbitQueue)
log.Info("Epilogue RabbitMQ is initialized")
if err != nil {
log.WithError(err).Fatal("Could not setup rabbit")
panic(err)
}
}
log.Info("Starting to setup manager")
manager, err := manager.NewManager(sqlite, sqlite, epilogue)
if err != nil {
log.WithError(err).Fatal("Could not setup manager")
panic(err)
}
log.Info("Starting to setup server")
server, err := api.NewServer(manager, simulator)
if err != nil {
log.WithError(err).Fatal("Could not setup server")
panic(err)
}
log.WithField("host", cmd.Host).Info("Starting to setup listener")
listener, err := net.Listen("tcp", cmd.Host)
if err != nil {
log.WithError(err).Fatal("Could not setup listener")
panic(err)
}
log.Info("Starting to serve")
s := grpc.NewServer()
proto.RegisterMessageAPIServer(s, server)
proto.RegisterOperatorAPIServer(s, server)
proto.RegisterDirectorAPIServer(s, server)
proto.RegisterUserAPIServer(s, server)
if err := s.Serve(listener); err != nil {
log.WithError(err).Fatal("Could not serve")
panic(err)
}
}
|
package main
import (
"github.com/go-kit/kit/log/level"
"fmt"
"time"
"database/sql"
"sort"
"bitbucket.org/garyyu/algo-trading/go-binance"
)
var (
LatestOrderID = make(map[string]int64)
)
type OrderData struct {
id int64 `json:"id"`
ProjectID int64 `json:"ProjectID"`
IsDone bool `json:"IsDone"`
executedOrder binance.ExecutedOrder `json:"executedOrder"`
LastQueryTime time.Time `json:"LastQueryTime"`
}
/*
* Expensive API: Weight: 5
* It help to import all orders into local database, and map them into related projects.
* Only call it from Project Manager
*/
func GetAllOrders(symbol string){
//
//fmt.Println("GetAllOrders func enter for", symbol)
// find active project in same asset
var project *ProjectData=nil
//ProjectMutex.RLock() //--- must not lock here! because the caller ProjectManager() already Lock().
for _, activeProject := range ActiveProjectList {
if activeProject.Symbol == symbol {
project = activeProject
break
}
}
//ProjectMutex.RUnlock()
if project==nil{
fmt.Println("GetAllOrders - Fail to find ProjectID for Symbol", symbol)
return
}
oldLatestOrderID,ok := LatestTradeID[symbol]
if !ok{
LatestTradeID[symbol] = 0
oldLatestOrderID = 0
}
keepOldOne := false
executedOrderList, err := binanceSrv.AllOrders(binance.AllOrdersRequest{
Symbol: symbol,
OrderID: LatestTradeID[symbol],
RecvWindow: 5 * time.Second,
Timestamp: time.Now(),
})
if err != nil {
level.Error(logger).Log("GetAllOrders - fail! Symbol=", symbol)
return
}
//
//fmt.Printf("GetAllOrders - Return %d Orders\n", len(executedOrderList))
// Sort by Time, in case Binance does't sort them
sort.Slice(executedOrderList, func(m, n int) bool {
return executedOrderList[m].Time.Before(executedOrderList[n].Time)
})
var newOrdersImported = 0
for _, executedOrder := range executedOrderList {
//
//fmt.Printf("GetAllOrders - Get Order: %v\n", executedOrder)
if executedOrder.OrderID > LatestTradeID[symbol] {
LatestTradeID[symbol] = executedOrder.OrderID
}
// check if this order is done
IsDone := false
if executedOrder.Status == binance.StatusPartiallyFilled ||
executedOrder.Status == binance.StatusNew {
IsDone = false
} else if executedOrder.IsWorking {
IsDone = true
}
// already in local database?
if GetOrderId(executedOrder.OrderID)>0 {
continue
}
// insert data into order list
orderData := OrderData{
ProjectID: -1,
executedOrder:*executedOrder,
IsDone: IsDone,
}
if InsertOrder(&orderData)<=0 {
fmt.Println("GetAllOrders - InsertOrder Fail. Order=", orderData)
keepOldOne = true
}else{
newOrdersImported += 1
}
}
// in case we fail to save to local database
if keepOldOne {
LatestTradeID[symbol] = oldLatestOrderID
}
// try to map new imported orders to the project
MatchProjectForOrder(project)
//
//fmt.Println("GetAllOrders func exit")
}
/*
* For new imported orders, we have to solve which project this order belongs to, then
* assign ProjectID to the order.
*/
func MatchProjectForOrder(project *ProjectData){
//
//fmt.Println("MatchProjectForOrder - func enter. Project=", project.Symbol)
// Get recent trades list in this asset, with the order of latest first.
orderList,isOldProject := getRecentOrderList(project.Symbol, binance.Day, project.id)
// Not a new project? Let's put the ProjectID into all those new orders in same asset
if isOldProject {
for _,order := range orderList {
if order.ProjectID >= 0 {
break // break here to avoid pollute very old orders record.
}
order.ProjectID = project.id
if !UpdateOrderProjectID(&order){
fmt.Printf("UpdateOrderProjectID - Fail. ProjectID=%d, order%v\n",
project.id, order)
}
}
return
}
amount := 0.0
invest := 0.0
if project.Symbol == "BNBBTC" {
amount -= project.FeeBNB
} else if project.FeeBNB ==0 {
amount -= project.FeeEmbed
}
ordersNum := 0
for _,order := range orderList {
ordersNum += 1
if order.executedOrder.Side == binance.SideBuy {
amount += order.executedOrder.ExecutedQty
invest += order.executedOrder.ExecutedQty * order.executedOrder.Price
}else{
amount -= order.executedOrder.ExecutedQty
invest -= order.executedOrder.ExecutedQty * order.executedOrder.Price
}
//
//fmt.Printf("MatchProjectForOrder - %d: amount=%f, project InitialAmount=%f\n",
// i, amount, project.InitialAmount)
if FloatEquals(amount, project.InitialAmount) {
break
}
}
fmt.Printf("MatchProjectForOrder - %s: amount=%f, project InitialAmount=%f\n",
project.Symbol, amount, project.InitialAmount)
// We find it? Let's put the ProjectID into all these orders
if FloatEquals(amount, project.InitialAmount) {
for i:=0; i<ordersNum; i++{
order := orderList[i]
order.ProjectID = project.id
if !UpdateOrderProjectID(&order){
fmt.Println("MatchProjectForOrder - UpdateOrderProjectID Failed. order:", order)
}
}
// in case trades not downloaded yet
if project.InitialBalance == 0{
project.InitialBalance = invest
project.InitialPrice = invest / amount // average price
if !UpdateProjectInitialBalance(project){
fmt.Println("MatchProjectForOrder - Update Project InitialBalane Failed. InitialBalance",
project.InitialBalance)
}
}
}else{
fmt.Println("MatchProjectForOrder - Warning! new project for asset", project.Symbol,
"not found in my orders history! Project can't be managed.")
}
}
func QueryOrders(){
// Get Order List from local database.
openOrderList := GetOrderList(false, -1)
for _, openOrder := range openOrderList {
if openOrder.IsDone {
continue
}
executedOrder, err := binanceSrv.QueryOrder(binance.QueryOrderRequest{
Symbol: openOrder.executedOrder.Symbol,
OrderID: openOrder.executedOrder.OrderID,
RecvWindow: 5 * time.Second,
Timestamp: time.Now(),
})
if err != nil {
level.Error(logger).Log("QueryOrder - fail! Symbol=", openOrder.executedOrder.Symbol,
"OrderID=", openOrder.executedOrder.OrderID)
return
}
openOrder.executedOrder = *executedOrder
// check if this order is done
if executedOrder.Status == binance.StatusPartiallyFilled ||
executedOrder.Status == binance.StatusNew {
openOrder.IsDone = false
} else if executedOrder.IsWorking {
openOrder.IsDone = true
}
if !UpdateOrder(&openOrder){
fmt.Println("UpdateOrder - Failed. openOrder=", openOrder)
}
//fmt.Println("QueryOrders - Result:", executedOrder)
}
}
func CancelOpenOrders(){
ProjectMutex.RLock()
defer ProjectMutex.RUnlock()
for _, project := range ActiveProjectList {
// only new order needs query
if project.OrderStatus!=string(binance.StatusNew) {
continue
}
cancelOrder(project.Symbol, project.OrderID)
}
}
func cancelOrder(symbol string, OrderID int64){
executedOrderList, err := binanceSrv.OpenOrders(binance.OpenOrdersRequest{
Symbol: symbol,
RecvWindow: 5 * time.Second,
Timestamp: time.Now(),
})
if err != nil {
level.Error(logger).Log("CancelOpenOrders - OpenOrders Query fail! Symbol=", symbol)
return
}
for _, executedOrder := range executedOrderList {
fmt.Println("OpenOrders - ", executedOrder)
}
// cancel remaining open orders
canceledOrder, err := binanceSrv.CancelOrder(binance.CancelOrderRequest{
Symbol: symbol,
OrderID: OrderID,
Timestamp: time.Now(),
})
if err != nil {
level.Error(logger).Log("CancelOrder - fail! Symbol:", symbol, "error:", err)
return
}
fmt.Println("CanceledOrder :", canceledOrder)
}
/*
* Insert Order data into Database
*/
func InsertOrder(orderData *OrderData) int64{
//
//fmt.Printf("InsertOrder - %v", orderData)
//
//if orderData==nil || len(orderData.executedOrder.ClientOrderID)==0 {
// level.Warn(logger).Log("InsertOrder - invalid orderData!", orderData)
// return -1
//}
query := `INSERT INTO order_list (
ProjectID, IsDone, Symbol, OrderID, ClientOrderID, Price,
OrigQty, ExecutedQty, Status, TimeInForce, Type, Side,
StopPrice, IcebergQty, Time, IsWorking, LastQueryTime
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())`
executedOrder := &orderData.executedOrder
res, err := DBCon.Exec(query,
orderData.ProjectID,
orderData.IsDone,
executedOrder.Symbol,
executedOrder.OrderID,
executedOrder.ClientOrderID,
executedOrder.Price,
executedOrder.OrigQty,
executedOrder.ExecutedQty,
string(executedOrder.Status),
string(executedOrder.TimeInForce),
string(executedOrder.Type),
string(executedOrder.Side),
executedOrder.StopPrice,
executedOrder.IcebergQty,
executedOrder.Time,
executedOrder.IsWorking,
)
if err != nil {
level.Error(logger).Log("DBCon.Exec", err)
return -1
}
id, _ := res.LastInsertId()
return id
}
/*
* Insert Draft Order data into Database
*/
func InsertDraftOrder(orderData *OrderData) int64{
//
//fmt.Printf("InsertDraftOrder - %v", orderData)
//
//if orderData==nil || len(orderData.executedOrder.ClientOrderID)==0 {
// level.Warn(logger).Log("InsertOrder - invalid orderData!", orderData)
// return -1
//}
query := `INSERT INTO order_list (
ProjectID, Symbol, OrderID, ClientOrderID, Price, OrigQty, Status, TimeInForce, Type, Side
) VALUES (?,?,?,?,?,?,?,?,?,?)`
executedOrder := &orderData.executedOrder
res, err := DBCon.Exec(query,
orderData.ProjectID,
executedOrder.Symbol,
executedOrder.OrderID,
executedOrder.ClientOrderID,
executedOrder.Price,
executedOrder.OrigQty,
"UNK","UNK","UNK","UNK",
)
if err != nil {
level.Error(logger).Log("DBCon.Exec", err)
return -1
}
id, _ := res.LastInsertId()
return id
}
/*
* Used for detect if order exist in local database
*/
func GetOrderId(OrderID int64) int64 {
row := DBCon.QueryRow("SELECT id FROM order_list WHERE OrderID=?", OrderID)
var id int64 = -1
err := row.Scan(&id)
if err != nil && err != sql.ErrNoRows {
level.Error(logger).Log("GetOrderId - Scan Err:", err)
}
return id
}
/*
* Update ProjectID for Order into Database
*/
func UpdateOrderProjectID(order *OrderData) bool{
query := `UPDATE order_list SET ProjectID=? WHERE id=?`
res, err := DBCon.Exec(query,
order.ProjectID,
order.id,
)
if err != nil {
level.Error(logger).Log("DBCon.Exec", err)
return false
}
rowsAffected, _ := res.RowsAffected()
if rowsAffected>=0 {
return true
}else{
return false
}
}
/*
* Update Order query result into Database
*/
func UpdateOrder(orderData *OrderData) bool{
if orderData==nil || len(orderData.executedOrder.ClientOrderID)==0 || orderData.executedOrder.OrderID==0 {
level.Warn(logger).Log("UpdateOrder - Invalid OrderData", orderData)
return false
}
executedOrder := &orderData.executedOrder
query := `UPDATE order_list SET IsDone=?, ClientOrderID=?, Price=?, OrigQty=?,
ExecutedQty=?, Status=?, TimeInForce=?, Type=?, Side=?, StopPrice=?,
IcebergQty=?, Time=?, LastQueryTime=NOW() WHERE OrderID=?`
res, err := DBCon.Exec(query,
orderData.IsDone,
executedOrder.ClientOrderID,
executedOrder.Price,
executedOrder.OrigQty,
executedOrder.ExecutedQty,
string(executedOrder.Status),
string(executedOrder.TimeInForce),
string(executedOrder.Type),
string(executedOrder.Side),
executedOrder.StopPrice,
executedOrder.IcebergQty,
executedOrder.Time,
executedOrder.OrderID,
)
if err != nil {
level.Error(logger).Log("DBCon.Exec", err)
return false
}
rowsAffected, _ := res.RowsAffected()
if rowsAffected>=0 {
return true
}else{
return false
}
}
/*
* Get Order List from local database.
* - IsDone=1 means orders already done.
* - IsDone=0 means 'Open', in local database view, if status pending to update from Binance server.
* To get status, query the Binance server via API.
*/
func GetOrderList(isDone bool, projectId int64) []OrderData {
var query string
if isDone{
query = "SELECT * FROM order_list WHERE IsDone=1 and ProjectID=" + fmt.Sprint(projectId)
}else{
query = "SELECT * FROM order_list WHERE IsDone=0 LIMIT 50"
}
rows, err := DBCon.Query(query)
if err != nil {
level.Error(logger).Log("getOrderList - DB.Query Fail. Err=", err)
panic(err.Error())
}
defer rows.Close()
OpenOrderList := make([]OrderData, 0)
rowLoopOpenOrder:
for rows.Next() {
var transactTime NullTime
var LastQueryTime NullTime
orderData := OrderData{}
executedOrder := &orderData.executedOrder
err := rows.Scan(&orderData.id, &orderData.ProjectID, &orderData.IsDone,
&executedOrder.Symbol, &executedOrder.OrderID, &executedOrder.ClientOrderID,
&executedOrder.Price, &executedOrder.OrigQty, &executedOrder.ExecutedQty,
&executedOrder.Status, &executedOrder.TimeInForce, &executedOrder.Type,
&executedOrder.Side, &executedOrder.StopPrice, &executedOrder.IcebergQty,
&transactTime, &executedOrder.IsWorking, &LastQueryTime)
if err != nil {
level.Error(logger).Log("getOrderList - Scan Fail. Err=", err)
continue
}
if transactTime.Valid {
executedOrder.Time = transactTime.Time
}
if LastQueryTime.Valid {
orderData.LastQueryTime = LastQueryTime.Time
}
//fmt.Println("getOrderList - got OrderData:", orderData)
// if already in open list
for _, existing := range OpenOrderList {
if existing.executedOrder.ClientOrderID == executedOrder.ClientOrderID {
fmt.Println("warning! duplicate order id found. ClientOrderID=", executedOrder.ClientOrderID)
continue rowLoopOpenOrder
}
}
if !orderData.IsDone {
OpenOrderList = append(OpenOrderList, orderData)
}
}
if err := rows.Err(); err != nil {
level.Error(logger).Log("getOrderList - rows.Err=", err)
panic(err.Error())
}
//
//fmt.Println("getOrderList - return", len(OpenOrderList), "orders. IsDone=", isDone)
return OpenOrderList
}
/*
* Get recent orders from local database for one asset.
* Return: OrderList and Whether projectID exist in this list.
*/
func getRecentOrderList(symbol string, interval binance.Interval, projectID int64) ([]OrderData, bool) {
orderList := make([]OrderData, 0)
projectIdExist := false
query := "select * from order_list where Symbol='" + symbol +
"' and LastQueryTime > DATE_SUB(NOW(), INTERVAL "
switch interval {
case binance.ThreeDays:
query += "3 DAY)"
case binance.Week:
query += "1 WEEK)"
case binance.Month:
query += "1 MONTH)"
default:
query += "1 DAY)"
}
query += " and ProjectID=-1 or " + fmt.Sprint(projectID) + " order by id desc"
rows, err := DBCon.Query(query)
if err != nil {
level.Error(logger).Log("getOrderList - DB.Query Fail. Err=", err)
panic(err.Error())
}
defer rows.Close()
for rows.Next() {
var transactTime NullTime
var LastQueryTime NullTime
orderData := OrderData{}
executedOrder := &orderData.executedOrder
err := rows.Scan(&orderData.id, &orderData.ProjectID, &orderData.IsDone,
&executedOrder.Symbol, &executedOrder.OrderID, &executedOrder.ClientOrderID,
&executedOrder.Price, &executedOrder.OrigQty, &executedOrder.ExecutedQty,
&executedOrder.Status, &executedOrder.TimeInForce, &executedOrder.Type,
&executedOrder.Side, &executedOrder.StopPrice, &executedOrder.IcebergQty,
&transactTime, &executedOrder.IsWorking, &LastQueryTime)
if err != nil {
level.Error(logger).Log("getRecentOrderList - Scan Fail. Err=", err)
continue
}
if transactTime.Valid {
executedOrder.Time = transactTime.Time
}
if LastQueryTime.Valid {
orderData.LastQueryTime = LastQueryTime.Time
}
//fmt.Println("getRecentOrderList - got OrderData:", orderData)
if orderData.ProjectID == projectID{
projectIdExist = true
}
orderList = append(orderList, orderData)
}
if err := rows.Err(); err != nil {
level.Error(logger).Log("getRecentOrderList - rows.Err=", err)
panic(err.Error())
}
//
//fmt.Println("getRecentOrderList - return", len(OpenOrderList), "orders. IsDone=", isDone)
return orderList, projectIdExist
}
|
package c2netapi
import (
"net/http"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
// All Tags Routes
Route{"AllAreas", "GET", "/allareas", AllSensorAreas},
Route{"NewArea", "POST", "/area", InsertSensorArea},
Route{"EditArea", "PUT", "/area", EditArea},
Route{"DeleteArea", "DELETE", "/area/{id}", DeleteArea},
Route{"DeleteAllAreas", "DELETE", "/areas", DeleteAllAreas},
Route{"Logger", "GET", "/log", Logger},
Route{"AllSensors", "GET", "/allsensors", AllSensors},
Route{"NewSensor", "POST", "/sensor", InsertSensor},
Route{"DelSensor", "DELETE", "/sensor", DeleteSensor},
Route{"UpdateTYPEsensor", "POST", "/update", UpdateSelected},
Route{"AllSelected", "GET", "/allselected", AllSelected},
Route{"AllCategories", "GET", "/allcategories", AllCategories},
Route{"AllTypesSensors", "GET", "/alltypes", AllTypes},
Route{"InsertHubId", "POST", "/hub", InsertHubId},
Route{"AllListeners", "GET", "/comm", AllCommListeners},
Route{"UpdateListeners", "POST", "/comm", UpdateCommListeners},
Route{"RestartHub", "GET", "/restart", RestartHub},
Route{"InsertAlive", "POST", "/alive", InsertAlive},
Route{"AllAlive", "GET", "/allalive", AllAlive},
Route{"HubStop", "GET", "/hubstop", StopHub},
Route{"HubStart", "GET", "/hubstart", StartHub},
Route{"HubStatus", "GET", "/hubstatus", StatusHub},
}
|
package sort
import "testing"
func TestQuickSort(t *testing.T) {
var arr []int
arr = []int{1}
t.Logf("before: %v", arr)
quickSort(arr, len(arr))
t.Logf("after: %v", arr)
arr = []int{2, 1}
t.Logf("before: %v", arr)
quickSort(arr, len(arr))
t.Logf("after: %v", arr)
arr = []int{3, 1, 2}
t.Logf("before: %v", arr)
quickSort(arr, len(arr))
t.Logf("after: %v", arr)
arr = []int{3, 2, 1}
t.Logf("before: %v", arr)
quickSort(arr, len(arr))
t.Logf("after: %v", arr)
arr = []int{3, 2, 1, 4, 7, 5, 6}
t.Logf("before: %v", arr)
quickSort(arr, len(arr))
t.Logf("after: %v", arr)
arr = []int{5, 2, 4, 1, 2, 4, 7, 5, 6}
t.Logf("before: %v", arr)
quickSort(arr, len(arr))
t.Logf("after: %v", arr)
}
|
// Copyright © 2019 Michael. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package app
import (
"context"
"flag"
"fmt"
"os"
"skygo/load"
"skygo/utils/log"
)
type build struct {
name string //top cmd name
NoDeps bool `flag:"nodeps" help:"don't check dependency"`
Loaders int `flag:"loaders" help:"set the number of jobs to build cartons"`
Force bool `flag:"force" help:"force to run"`
Verbose bool `flag:"v" help:"verbose output. available when no tmux panes"`
}
func (*build) Name() string { return "carton" }
func (*build) Summary() string { return "build cartons" }
func (b *build) UsageLine() string {
return fmt.Sprintf(`<carton name[@target]>
target should be stage name or independent task name.
command info show what stages and independent tasks carton has.
example:
$%s carton busybox@fetch
`, b.name)
}
func (*build) Help(f *flag.FlagSet) {
fmt.Fprintf(f.Output(), "\ncarton flags are:\n")
f.PrintDefaults()
}
func (b *build) Run(ctx context.Context, args ...string) error {
if len(args) == 0 {
return commandLineErrorf("carton name must be supplied")
}
panes := tmuxPanes(ctx)
numPanes := len(panes)
if numPanes > 0 {
if b.Loaders == 0 {
b.Loaders = numPanes
} else { // cmd line assign Loaders
if numPanes < b.Loaders {
b.Loaders = numPanes
}
}
load.Settings().Set(load.MAXLOADERS, b.Loaders)
}
l, loaders := load.NewLoad(ctx, b.name)
if numPanes > 0 {
for i := 0; i < b.Loaders; i++ {
pane := panes[i]
if file, err := os.OpenFile(pane, os.O_RDWR, 0766); err == nil {
l.SetOutput(i, file, file)
} else {
log.Warning("Failed to open tmux pane %s. Error: %s\n", pane, err)
}
}
} else if b.Verbose {
for i := 0; i < loaders; i++ {
l.SetOutput(i, os.Stdout, os.Stderr)
}
}
return l.Run(b.NoDeps, b.Force, args...)
}
|
package logger_test
import (
"bytes"
"context"
"fmt"
"github.com/adamluzsi/frameless/pkg/iokit"
"github.com/adamluzsi/frameless/pkg/logger"
"github.com/adamluzsi/frameless/pkg/stringcase"
"github.com/adamluzsi/testcase"
"github.com/adamluzsi/testcase/assert"
"github.com/adamluzsi/testcase/random"
"os"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
)
var asyncLoggingEventually = assert.EventuallyWithin(3 * time.Second)
func ExampleLogger_AsyncLogging() {
ctx := context.Background()
l := logger.Logger{}
defer l.AsyncLogging()()
l.Info(ctx, "this log message is written out asynchronously")
}
func TestLogger_AsyncLogging(t *testing.T) {
var (
out = &bytes.Buffer{}
m sync.Mutex
)
l := logger.Logger{Out: &iokit.SyncWriter{
Writer: out,
Locker: &m,
}}
defer l.AsyncLogging()()
l.MessageKey = "msg"
l.KeyFormatter = stringcase.ToPascal
l.Info(nil, "gsm", logger.Field("fieldKey", "value"))
asyncLoggingEventually.Assert(t, func(it assert.It) {
m.Lock()
logs := out.String()
m.Unlock()
it.Must.Contain(logs, `"Msg":"gsm"`)
it.Must.Contain(logs, `"FieldKey":"value"`)
})
}
func TestLogger_AsyncLogging_onCancellationAllMessageIsFlushed(t *testing.T) {
var (
out = &bytes.Buffer{}
m sync.Mutex
)
l := logger.Logger{Out: &iokit.SyncWriter{
Writer: out,
Locker: &m,
}}
defer l.AsyncLogging()()
const sampling = 10
for i := 0; i < sampling; i++ {
l.Info(nil, strconv.Itoa(i))
}
asyncLoggingEventually.Assert(t, func(it assert.It) {
m.Lock()
logs := out.String()
m.Unlock()
for i := 0; i < sampling; i++ {
assert.Contain(it, logs, fmt.Sprintf(`"message":"%d"`, i))
}
})
}
func BenchmarkLogger_AsyncLogging(b *testing.B) {
tmpDir := b.TempDir()
out, err := os.CreateTemp(tmpDir, "")
if err != nil {
b.Skip(err.Error())
}
b.Run("sync", func(b *testing.B) {
l := &logger.Logger{Out: out}
defer b.StopTimer()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Info(nil, "msg")
}
})
b.Run("async", func(b *testing.B) {
l := &logger.Logger{Out: out}
defer l.AsyncLogging()()
assert.Waiter{WaitDuration: time.Millisecond}.Wait()
defer b.StopTimer()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Info(nil, "msg")
}
})
b.Run("sync with heavy concurrency", func(b *testing.B) {
l := &logger.Logger{Out: out}
makeConcurrentAccesses(b, l)
defer b.StopTimer()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Info(nil, "msg")
}
})
b.Run("async with heavy concurrency", func(b *testing.B) {
l := &logger.Logger{Out: out}
defer l.AsyncLogging()()
assert.Waiter{WaitDuration: time.Millisecond}.Wait()
makeConcurrentAccesses(b, l)
defer b.StopTimer()
b.ResetTimer()
for i := 0; i < b.N; i++ {
l.Info(nil, "msg")
}
})
}
func makeConcurrentAccesses(tb testing.TB, l *logger.Logger) {
ctx, cancel := context.WithCancel(context.Background())
tb.Cleanup(cancel)
var ready int32
go func() {
blk := func() {
l.Info(nil, "msg")
}
more := random.Slice[func()](runtime.NumCPU()*10, func() func() { return blk })
atomic.AddInt32(&ready, 1)
func() {
for {
if ctx.Err() != nil {
break
}
testcase.Race(blk, blk, more...)
}
}()
}()
for {
if atomic.LoadInt32(&ready) != 0 {
break
}
}
}
|
package cmd
import (
"github.com/khushmeeet/vc/vc"
"github.com/spf13/cobra"
)
// logCmd represents the log command
var logCmd = &cobra.Command{
Use: "log",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 1 {
oid := vc.GetOid(args[0])
vc.Log(oid)
} else {
oid := vc.GetOid("@")
vc.Log(oid)
}
},
}
func init() {
rootCmd.AddCommand(logCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// logCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// logCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package conf
import (
"encoding/xml"
"io"
"log"
)
type configuration struct {
Properties []propertyXml `xml:"property"`
}
type propertyXml struct {
Name string `xml:"name"`
Value string `xml:"value"`
}
// Parse an XML configuration file.
func parseXml(reader io.Reader, m map[string]string) error {
dec := xml.NewDecoder(reader)
configurationXml := configuration{}
err := dec.Decode(&configurationXml)
if err != nil {
return err
}
props := configurationXml.Properties
for p := range props {
key := props[p].Name
value := props[p].Value
if key == "" {
log.Println("Warning: ignoring element with missing or empty <name>.")
continue
}
if value == "" {
log.Println("Warning: ignoring element with key " + key + " with missing or empty <value>.")
continue
}
//log.Printf("setting %s to %s\n", key, value)
m[key] = value
}
return nil
}
|
package rest
import (
"github.com/project-flogo/core/data/coerce"
)
type Settings struct {
Port int `md:"port,required"` // The port to listen on
EnableTLS bool `md:"enableTLS"` // Enable TLS on the server
CertFile string `md:"certFile"` // The path to PEM encoded server certificate
KeyFile string `md:"keyFile"` // The path to PEM encoded server key
}
type HandlerSettings struct {
Method string `md:"method,required,allowed(GET,POST,PUT,PATCH,DELETE)"` // The HTTP method (ie. GET,POST,PUT,PATCH or DELETE)
Path string `md:"path,required"` // The resource path
}
type Output struct {
PathParams map[string]string `md:"pathParams"` // The path parameters (e.g., 'id' in http://.../pet/:id/name )
QueryParams map[string]string `md:"queryParams"` // The query parameters (e.g., 'id' in http://.../pet?id=someValue )
Headers map[string]string `md:"headers"` // The HTTP header parameters
Content interface{} `md:"content"` // The content of the request
Method string `md:"method"` // The HTTP method used for the request
}
type Reply struct {
Code int `md:"code"` // The http code to reply with
Data interface{} `md:"data"` // The data to reply with
Headers map[string]string `md:"headers"` // The HTTP response headers
Cookies []interface{} `md:"cookies"` // "The response cookies, adds `Set-Cookie` headers"
}
func (o *Output) ToMap() map[string]interface{} {
return map[string]interface{}{
"pathParams": o.PathParams,
"queryParams": o.QueryParams,
"headers": o.Headers,
"method": o.Method,
"content": o.Content,
}
}
func (o *Output) FromMap(values map[string]interface{}) error {
var err error
o.PathParams, err = coerce.ToParams(values["pathParams"])
if err != nil {
return err
}
o.QueryParams, err = coerce.ToParams(values["queryParams"])
if err != nil {
return err
}
o.Headers, err = coerce.ToParams(values["headers"])
if err != nil {
return err
}
o.Method, err = coerce.ToString(values["method"])
if err != nil {
return err
}
o.Content = values["content"]
return nil
}
func (r *Reply) ToMap() map[string]interface{} {
return map[string]interface{}{
"code": r.Code,
"data": r.Data,
"headers": r.Headers,
"cookies": r.Cookies,
}
}
func (r *Reply) FromMap(values map[string]interface{}) error {
var err error
r.Code, err = coerce.ToInt(values["code"])
if err != nil {
return err
}
r.Data, _ = values["data"]
r.Headers, err = coerce.ToParams(values["headers"])
if err != nil {
return err
}
r.Cookies, err = coerce.ToArray(values["cookies"])
if err != nil {
return err
}
return nil
}
|
package dao
import (
"crypto/rand"
"encoding/hex"
"time"
"websocket_test_1/models"
)
// CreateMessage creates a message with the provided details and returns the created message
func CreateMessage(senderID, recipientID, content string) (*models.Message, error) {
//Generate the messageId
b := make([]byte, 4)
rand.Read(b)
messageID := hex.EncodeToString(b)
//Create the message
newMessage := models.Message{
ID: "mockMessage" + messageID,
SenderID: senderID,
RecipientID: recipientID,
Content: content,
Time: time.Now().Unix(),
}
//TODO: Insert to database
//Return the newly created message
return &newMessage, nil
}
|
package http
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestHttpServer(t *testing.T) {
// This method is to handle the expected response
handler := func(w http.ResponseWriter, r *http.Request) {
// The expected response is from external file at /testdata/get_expected_response.json
io.WriteString(w, expectedResponse)
}
req := httptest.NewRequest("GET", "http://demo-meli-ceiba-test.demo-meli-ceiba.melifrontends.com/pong", nil)
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)
assert.Equal(t, resp.StatusCode, 200)
assert.Equal(t, resp.Header.Get("Content-Type"), "text/plain; charset=utf-8")
assert.Equal(t, string(body), expectedResponse)
}
func TestHttpClient(t *testing.T) {
client := &http.Client{
CheckRedirect: nil,
}
req, err := http.NewRequest("GET", "http://demo-meli-ceiba-test.demo-meli-ceiba.melifrontends.com/ping", nil)
req.Header.Add("x-auth-token", "3a0cc3db478ff18d6400ca68d26ea71868cb07b286c2d1862fb462766c11baa6")
resp, err := client.Do(req)
if err != nil {
fmt.Println("There was an error, try again")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
assert.Equal(t, resp.StatusCode, 200)
assert.Equal(t, resp.Header.Get("Content-Type"), "text/plain; charset=utf-8")
assert.Equal(t, string(body), "pong")
} |
// 7 july 2014
package ui
// Window represents a top-level window on screen that contains other Controls.
// Windows in package ui can only contain one control; the Stack, Grid, and SimpleGrid layout Controls allow you to pack multiple Controls in a Window.
// Note that a Window is not itself a Control.
type Window interface {
// Title and SetTitle get and set the Window's title, respectively.
Title() string
SetTitle(title string)
// Show and Hide bring the Window on-screen and off-screen, respectively.
Show()
Hide()
// Close closes the Window.
// Any Controls within the Window are destroyed, and the Window itself is also destroyed.
// Attempting to use a Window after it has been closed results in undefined behavior.
// Close unconditionally closes the Window; it neither raises OnClosing nor checks for a return from OnClosing.
Close()
// OnClosing registers an event handler that is triggered when the user clicks the Window's close button.
// On systems where whole applications own windows, OnClosing is also triggered when the user asks to close the application.
// If this handler returns true, the Window is closed as defined by Close above.
// If this handler returns false, the Window is not closed.
OnClosing(func() bool)
// Margined and SetMargined get and set whether the contents of the Window have a margin around them.
// The size of the margin is platform-dependent.
Margined() bool
SetMargined(margined bool)
windowDialog
}
// NewWindow creates a new Window with the given title text, size, and control.
func NewWindow(title string, width int, height int, control Control) Window {
return newWindow(title, width, height, control)
}
|
package invoice
import (
"github.com/boltdb/bolt"
"encoding/json"
"fmt"
"bytes"
"net/http"
"github.com/julienschmidt/httprouter"
"log"
"github.com/mpdroog/invoiced/invoice/camt053"
"github.com/mpdroog/invoiced/config"
"strings"
"io"
)
// Parse bankbalance in CAMT053-format
func Balance(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var buf bytes.Buffer
file, header, e := r.FormFile("file")
if e != nil {
log.Printf(e.Error())
http.Error(w, "Failed reading file", 500)
return
}
defer file.Close()
name := strings.Split(header.Filename, ".")
if name[1] != "xml" {
http.Error(w, "Sorry, not an XML-file", 400)
return
}
io.Copy(&buf, file)
p, e := camt053.FilterPaymentsReceived(&buf)
if e != nil {
log.Printf(e.Error())
http.Error(w, "Failed parsing file", 500)
return
}
for _, payment := range p {
if config.Verbose {
log.Printf(
"Parse payments(%s) %sEUR with comment=%s from=%s(%s)",
payment.Id, payment.Amount, payment.Comment, payment.Name, payment.IBAN,
)
}
ok, e := balanceSetPaid(payment.Comment, payment.Date, payment.Amount)
if e != nil {
log.Printf(e.Error())
http.Error(w, "Failed marking payments as paid", 500)
return
}
if !ok {
log.Printf("Failed marking payment(%s) as paid", payment.Comment)
} else if config.Verbose {
log.Printf("Marked payment(%s) as paid", payment.Comment)
}
}
}
func balanceSetPaid(name string, payDate string, amount string) (bool, error) {
count := 1000
ok := false
e := db.Update(func(tx *bolt.Tx) error {
u := new(Invoice)
found := false
b := tx.Bucket([]byte("invoices"))
c := b.Cursor()
i := 0
for k, v := c.Last(); k != nil && i < count; k, v = c.Prev() {
if e := json.NewDecoder(bytes.NewBuffer(v)).Decode(u); e != nil {
return e
}
if u.Meta.Invoiceid == name {
// Found invoice!
found = true
break
}
i++
}
if !found {
// Skip not found
log.Printf("Invoice(%s) not found?", name)
return nil
}
if u.Total.Total != amount {
log.Printf("WARN: Invoice(%s) amounts don't match %sEUR/%sEUR", name, u.Total.Total, amount)
return nil
}
if u.Meta.Status != "FINAL" {
return fmt.Errorf("invoice.balanceSetPaid can only set paid on FINAL-invoices")
}
u.Meta.Paydate = payDate
// Save any changes..
buf := new(bytes.Buffer)
if e := json.NewEncoder(buf).Encode(u); e != nil {
return e
}
b2, e := tx.CreateBucketIfNotExists([]byte("invoices-paid"))
if e != nil {
return e
}
if e := b2.Put([]byte(u.Meta.Conceptid), buf.Bytes()); e != nil {
return e
}
// Delete original
if e := b.Delete([]byte(u.Meta.Conceptid)); e != nil {
return e
}
ok = true
return nil
})
return ok, e
} |
package main
import "fmt"
// for 结构
//func main() {
// for i := 0; i < 5; i++ {
// fmt.Printf("This is the %d iteration\n", i)
// }
//
// //for i := 0; i < 2; i++ {
// // for j := 0; j < 5; j++ {
// // println(j)
// // }
// //}
//
// str := "Go is a beautiful language!"
// fmt.Printf("The length of str is: %d\n", len(str))
// for ix := 0; ix < len(str); ix++ {
// fmt.Printf("Character on position %d is: %c\n", ix, str[ix])
// }
//
// str2 := "日本語"
// fmt.Printf("The length of str2 is: %d\n", len(str2))
// for ix :=0; ix < len(str2); ix++ {
// fmt.Printf("Character on position %d is: %c \n", ix, str2[ix])
// }
//
// for i := 0 ; i < 7; i++ {
// for j := 0; j < i; j++ {
// print("G")
// }
// println()
// }
//}
//Break 与 continue
//func main() {
// i := 10
// for {
// i = i - 1
// fmt.Printf("The variable i is now: %d\n", i)
// if i < 0 {
// break
// }
// }
// //break
// for i := 0; i < 3; i++ {
// for j := 0;j < 10; j++ {
// if j > 5 {
// break
// }
// print(j)
// }
// print(" ")
// }
// println()
// //continue
// for i := 0; i < 10; i++ {
// if i == 5 {
// continue
// }
// print(i)
// print(" ")
// }
//}
//标签与goto
func main() {
LABEL1:
for i := 0; i <= 5; i++ {
for j := 0; j <= 5; j++ {
if j == 4 {
continue LABEL1
}
fmt.Printf("i is: %d, and j is: %d\n", i, j)
}
}
i := 0
HERE:
print(i)
i++
if i == 5 {
return
}
goto HERE
for { //since there are no checks, this is an infinite loop
if i >= 3 {
break
}
//break out of this for loop when this condition is met
fmt.Println("Value of i is:", i)
i++
}
fmt.Println("A statement just after for loop.")
}
|
package chconn
import (
"context"
"errors"
"fmt"
"io"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vahid-sohrabloo/chconn/v2/column"
"github.com/vahid-sohrabloo/chconn/v2/internal/helper"
)
func TestProfileReadError(t *testing.T) {
startValidReader := 43
config, err := ParseConfig(os.Getenv("CHX_TEST_TCP_CONN_STRING"))
require.NoError(t, err)
c, err := ConnectConfig(context.Background(), config)
require.NoError(t, err)
if c.ServerInfo().Revision >= helper.DbmsMinProtocolWithServerQueryTimeInProgress {
// todo we need to fix this for clickhouse 22.10 and above
return
}
tests := []struct {
name string
wantErr string
numberValid int
}{
{
name: "profile: read Rows",
wantErr: "profile: read Rows",
numberValid: startValidReader,
}, {
name: "profile: read Blocks",
wantErr: "profile: read Blocks",
numberValid: startValidReader + 1,
}, {
name: "profile: read Bytes",
wantErr: "profile: read Bytes",
numberValid: startValidReader + 2,
}, {
name: "profile: read AppliedLimit",
wantErr: "profile: read AppliedLimit",
numberValid: startValidReader + 3,
}, {
name: "profile: read RowsBeforeLimit",
wantErr: "profile: read RowsBeforeLimit",
numberValid: startValidReader + 4,
}, {
name: "profile: read CalculatedRowsBeforeLimit",
wantErr: "profile: read CalculatedRowsBeforeLimit",
numberValid: startValidReader + 5,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config, err := ParseConfig(os.Getenv("CHX_TEST_TCP_CONN_STRING"))
require.NoError(t, err)
if c.ServerInfo().Revision >= helper.DbmsMinProtocolWithServerQueryTimeInProgress {
tt.numberValid++
}
config.ReaderFunc = func(r io.Reader) io.Reader {
return &readErrorHelper{
err: errors.New("timeout"),
r: r,
numberValid: tt.numberValid,
}
}
c, err := ConnectConfig(context.Background(), config)
require.NoError(t, err)
col := column.New[uint64]()
stmt, err := c.Select(context.Background(), "SELECT * FROM system.numbers LIMIT 1;", col)
require.NoError(t, err)
for stmt.Next() {
}
require.Error(t, stmt.Err())
readErr, ok := stmt.Err().(*readError)
require.True(t, ok)
fmt.Println("readErr.msg:", readErr.msg)
require.Equal(t, tt.wantErr, readErr.msg)
require.EqualError(t, readErr.Unwrap(), "timeout")
assert.True(t, c.IsClosed())
})
}
}
|
package requests
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/atomicjolt/canvasapi"
"github.com/atomicjolt/canvasapi/models"
)
// ListFolders Returns the paginated list of folders in the folder.
// https://canvas.instructure.com/doc/api/files.html
//
// Path Parameters:
// # Path.ID (Required) ID
//
type ListFolders struct {
Path struct {
ID string `json:"id" url:"id,omitempty"` // (Required)
} `json:"path"`
}
func (t *ListFolders) GetMethod() string {
return "GET"
}
func (t *ListFolders) GetURLPath() string {
path := "folders/{id}/folders"
path = strings.ReplaceAll(path, "{id}", fmt.Sprintf("%v", t.Path.ID))
return path
}
func (t *ListFolders) GetQuery() (string, error) {
return "", nil
}
func (t *ListFolders) GetBody() (url.Values, error) {
return nil, nil
}
func (t *ListFolders) GetJSON() ([]byte, error) {
return nil, nil
}
func (t *ListFolders) HasErrors() error {
errs := []string{}
if t.Path.ID == "" {
errs = append(errs, "'Path.ID' is required")
}
if len(errs) > 0 {
return fmt.Errorf(strings.Join(errs, ", "))
}
return nil
}
func (t *ListFolders) Do(c *canvasapi.Canvas, next *url.URL) ([]*models.Folder, *canvasapi.PagedResource, error) {
var err error
var response *http.Response
if next != nil {
response, err = c.Send(next, t.GetMethod(), nil)
} else {
response, err = c.SendRequest(t)
}
if err != nil {
return nil, nil, err
}
if err != nil {
return nil, nil, err
}
body, err := ioutil.ReadAll(response.Body)
response.Body.Close()
if err != nil {
return nil, nil, err
}
ret := []*models.Folder{}
err = json.Unmarshal(body, &ret)
if err != nil {
return nil, nil, err
}
pagedResource, err := canvasapi.ExtractPagedResource(response.Header)
if err != nil {
return nil, nil, err
}
return ret, pagedResource, nil
}
|
package tests
import (
"reflect"
"testing"
ravendb "github.com/ravendb/ravendb-go-client"
"github.com/stretchr/testify/assert"
)
func ravendb9676canOrderByDistanceOnDynamicSpatialField(t *testing.T, driver *RavenTestDriver) {
var err error
store := driver.getDocumentStoreMust(t)
defer store.Close()
{
session := openSessionMust(t, store)
item := &Item{
Name: "Item1",
Latitude: 10,
Longitude: 10,
}
err = session.Store(item)
assert.NoError(t, err)
item1 := &Item{
Name: "Item2",
Latitude: 11,
Longitude: 11,
}
err = session.Store(item1)
assert.NoError(t, err)
err = session.SaveChanges()
assert.NoError(t, err)
session.Close()
}
{
session := openSessionMust(t, store)
var items []*Item
q := session.QueryCollectionForType(reflect.TypeOf(&Item{}))
q = q.WaitForNonStaleResults(0)
f := ravendb.NewPointField("latitude", "longitude")
fn := func(f *ravendb.SpatialCriteriaFactory) ravendb.SpatialCriteria {
return f.WithinRadius(1000, 10, 10)
}
q = q.Spatial2(f, fn)
q2 := q.OrderByDistanceLatLongDynamic(ravendb.NewPointField("latitude", "longitude"), 10, 10)
err = q2.GetResults(&items)
assert.NoError(t, err)
assert.Equal(t, len(items), 2)
session.Close()
item := items[0]
assert.Equal(t, item.Name, "Item1")
item = items[1]
assert.Equal(t, item.Name, "Item2")
items = nil
q = session.QueryCollectionForType(reflect.TypeOf(&Item{}))
q = q.WaitForNonStaleResults(0)
f = ravendb.NewPointField("latitude", "longitude")
q = q.Spatial2(f, fn)
q2 = q.OrderByDistanceDescendingLatLongDynamic(ravendb.NewPointField("latitude", "longitude"), 10, 10)
err = q2.GetResults(&items)
assert.NoError(t, err)
assert.Equal(t, len(items), 2)
session.Close()
item = items[0]
assert.Equal(t, item.Name, "Item2")
item = items[1]
assert.Equal(t, item.Name, "Item1")
}
}
type Item struct {
Name string `json:"name"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
func TestRavenDB9676(t *testing.T) {
driver := createTestDriver(t)
destroy := func() { destroyDriver(t, driver) }
defer recoverTest(t, destroy)
// matches the order of Java tests
ravendb9676canOrderByDistanceOnDynamicSpatialField(t, driver)
}
|
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kvm
import (
"gvisor.dev/gvisor/pkg/abi/linux"
pkgcontext "gvisor.dev/gvisor/pkg/context"
"gvisor.dev/gvisor/pkg/hostarch"
"gvisor.dev/gvisor/pkg/ring0"
"gvisor.dev/gvisor/pkg/sentry/arch"
"gvisor.dev/gvisor/pkg/sentry/platform"
"gvisor.dev/gvisor/pkg/sentry/platform/interrupt"
)
// context is an implementation of the platform context.
//
// This is a thin wrapper around the machine.
type context struct {
// machine is the parent machine, and is immutable.
machine *machine
// info is the linux.SignalInfo cached for this context.
info linux.SignalInfo
// interrupt is the interrupt context.
interrupt interrupt.Forwarder
}
// tryCPUIDError indicates that CPUID emulation should occur.
type tryCPUIDError struct{}
// Error implements error.Error.
func (tryCPUIDError) Error() string { return "cpuid emulation failed" }
// Switch runs the provided context in the given address space.
func (c *context) Switch(ctx pkgcontext.Context, mm platform.MemoryManager, ac *arch.Context64, _ int32) (*linux.SignalInfo, hostarch.AccessType, error) {
as := mm.AddressSpace()
localAS := as.(*addressSpace)
restart:
// Grab a vCPU.
cpu := c.machine.Get()
// Enable interrupts (i.e. calls to vCPU.Notify).
if !c.interrupt.Enable(cpu) {
c.machine.Put(cpu) // Already preempted.
return nil, hostarch.NoAccess, platform.ErrContextInterrupt
}
// Set the active address space.
//
// This must be done prior to the call to Touch below. If the address
// space is invalidated between this line and the call below, we will
// flag on entry anyways. When the active address space below is
// cleared, it indicates that we don't need an explicit interrupt and
// that the flush can occur naturally on the next user entry.
cpu.active.set(localAS)
// Prepare switch options.
switchOpts := ring0.SwitchOpts{
Registers: &ac.StateData().Regs,
FloatingPointState: ac.FloatingPointData(),
PageTables: localAS.pageTables,
Flush: localAS.Touch(cpu),
FullRestore: ac.FullRestore(),
}
// Take the blue pill.
at, err := cpu.SwitchToUser(switchOpts, &c.info)
// Clear the address space.
cpu.active.set(nil)
// Increment the number of user exits.
cpu.userExits.Add(1)
userExitCounter.Increment()
// Release resources.
c.machine.Put(cpu)
// All done.
c.interrupt.Disable()
if err != nil {
if _, ok := err.(tryCPUIDError); ok {
// Does emulation work for the CPUID?
//
// We have to put the current vCPU, because
// TryCPUIDEmulate needs to read a user memory and it
// has to lock mm.activeMu for that, but it can race
// with as.invalidate that bonce all vcpu-s to gr0 and
// is called under mm.activeMu too.
if platform.TryCPUIDEmulate(ctx, mm, ac) {
goto restart
}
// If not a valid CPUID, then the signal should be
// delivered as is and the information is filled.
err = platform.ErrContextSignal
}
}
return &c.info, at, err
}
// Interrupt interrupts the running context.
func (c *context) Interrupt() {
c.interrupt.NotifyInterrupt()
}
// Release implements platform.Context.Release().
func (c *context) Release() {}
// FullStateChanged implements platform.Context.FullStateChanged.
func (c *context) FullStateChanged() {}
// PullFullState implements platform.Context.PullFullState.
func (c *context) PullFullState(as platform.AddressSpace, ac *arch.Context64) error { return nil }
// PrepareSleep implements platform.Context.platform.Context.
func (*context) PrepareSleep() {}
|
package consttypes
type String string
func (s String) String() string { return string(s) }
type Error string
// Error implement the error interface
func (err Error) Error() string { return string(err) }
|
package main
import (
"fmt"
"time"
_ "errors"
)
func test(){
defer func (){
err := recover()
fmt.Println(err)
}()
panic("hello")
}
func main() {
var now time.Time = time.Now()
fmt.Println(now.Year(), int(now.Month()), now.Day(), now.Hour(),
now.Minute(), now.Second())
test()
fmt.Println("hello11")
var arr [5]int8 = [...]int8{10, 5, 8, 10, 2}
fmt.Printf("%p, %p, %p, %p", &arr, &arr[0], &arr[1], &arr[2])
var slice = arr[0:3]
fmt.Println("\n", cap(slice), len(slice))
slice = make([]int8, 5, 10)
fmt.Printf("\n%p", slice)
slice = append(slice, 8)
fmt.Printf("\n%p", slice)
for i := 0; i<5; i++{
slice = append(slice, 8)
fmt.Printf("\n%p", slice)
}
var slice1 = []int{10, 20, 30, 40, 50}
var slice2 = make([]int, 10)
copy(slice2, slice1)
slice1[1] = 100
fmt.Println(slice2)
} |
package routes
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/sessions"
)
var (
cookieNameForSessionID = "mycookiesessionnameid"
sess = sessions.New(sessions.Config{Cookie: cookieNameForSessionID})
)
func registerSessionRoute(app *iris.Application) {
app.Get("/secret", secret)
app.Get("/login", login)
app.Get("/logout", logout)
}
func secret(ctx iris.Context) {
// Check if user is authenticated
if auth, _ := sess.Start(ctx).GetBoolean("authenticated"); !auth {
ctx.StatusCode(iris.StatusForbidden)
return
}
// Print secret message
ctx.WriteString("The cake is a lie!")
}
func login(ctx iris.Context) {
session := sess.Start(ctx)
// Authentication goes here
// ...
// Set user as authenticated
session.Set("authenticated", true)
}
func logout(ctx iris.Context) {
session := sess.Start(ctx)
// Revoke users authentication
session.Set("authenticated", false)
// Or to remove the variable:
session.Delete("authenticated")
// Or destroy the whole session:
session.Destroy()
}
|
package main
import (
"io/ioutil"
"os"
"fmt"
"log"
"time"
"path"
"strconv"
"encoding/json"
)
func competitionRoot(CompetitionId uint64) string {
return fmt.Sprintf("db/%d", CompetitionId)
}
func competitionPath(CompetitionId *uint64, name string) string {
if CompetitionId != nil {
return fmt.Sprintf("db/%d/%s", *CompetitionId, name)
} else {
return fmt.Sprintf("db/%s", name)
}
}
func SaveToJournal(CompetitionId uint64, TimeStamp uint64, TerminalString string, url string, data []byte) {
fpath := competitionPath(&CompetitionId, "journal")
f, err := os.OpenFile(fpath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
/* TODO: mutex lock */
if err != nil {
log.Println("!!!", "journal open error", err, fpath)
}
defer f.Close()
journal_data := fmt.Sprintf("%d:%s:%s:%s\n", TimeStamp, TerminalString, url, data)
if _, err := f.WriteString(journal_data); err != nil {
log.Println("!!!", "journ write error", err, fpath)
}
}
/* TODO: check db on start */
func getLaps(CompetitionId uint64) []Lap {
var laps []Lap
fpath := competitionPath(&CompetitionId, "laps")
data, err := ioutil.ReadFile(fpath)
if err != nil {
log.Println("...", "no laps data", fpath)
return nil
}
err = json.Unmarshal(data, &laps)
if err != nil {
log.Println("!!!", "laps decode error", err, fpath)
panic("Laps decode error")
}
return laps
}
func GetLaps(CompetitionId uint64, TimeStamp uint64) []Lap {
var rlaps []Lap
for _, l := range getLaps(CompetitionId) {
if l.TimeStamp > TimeStamp {
rlaps = append(rlaps, l)
}
}
return rlaps
}
func SetTerminalStatus(CompetitionId uint64, tstat []TerminalStatus) {
fpath := competitionPath(&CompetitionId, "terminals")
data, _ := json.MarshalIndent(tstat, "", " ")
store(fpath, data, true);
}
func SetRaceStatus(CompetitionId uint64, rstat RaceStatus) {
fpath := competitionPath(&CompetitionId, "race")
if CompetitionId == 0 {
panic("can't setup default race");
}
if rstat.SyncPoint == nil {
oldRace := GetRaceStatus(CompetitionId)
if oldRace != nil {
rstat.SyncPoint = oldRace.SyncPoint
}
}
data, _ := json.MarshalIndent(rstat, "", " ")
store(fpath, data, true)
}
func GetRaceStatus(CompetitionId uint64) *RaceStatus {
var rstat RaceStatus
fpath := competitionPath(&CompetitionId, "race")
data, err := ioutil.ReadFile(fpath)
if err != nil {
log.Println("...", "no race data", fpath)
return nil
}
err = json.Unmarshal(data, &rstat)
if err != nil {
log.Println("!!!", "race decode error", err, fpath)
return nil
}
// 0 is special competition id: default
if CompetitionId != 0 {
if rstat.CompetitionId != CompetitionId {
log.Println("!!!", "race have invalid Id",
rstat.CompetitionId, "!=", CompetitionId, fpath)
panic("Invalid CompetitionId")
}
ActiveCompetition := GetRaceStatus(0)
if ActiveCompetition != nil &&
ActiveCompetition.CompetitionId == rstat.CompetitionId {
rstat.IsActive = new(bool)
*rstat.IsActive = true
}
} else {
// CompetitionId == 0 is marker for active race
rstat.IsActive = new(bool)
*rstat.IsActive = true
}
return &rstat
}
func mergeGates(lgates []LapGate, gates []LapGate) ([]LapGate, bool) {
updated := false
for _, g := range gates {
found := false
for k := range lgates {
if g.Id != lgates[k].Id {
continue
}
found = true
if lgates[k].PenaltyId != g.PenaltyId {
lgates[k].PenaltyId = g.PenaltyId
updated = true
}
}
if !found {
lgates = append(lgates, g)
updated = true
}
}
return lgates, updated
}
func store(fpath string, data []byte, safe bool) {
var safeName = fpath
if safe {
safeName = fmt.Sprintf("%s.%d", fpath, time.Now().UTC().UnixNano())
}
err := ioutil.WriteFile(safeName, data, 0644)
if err != nil {
log.Println("!!!", " write error", err, fpath)
panic("write error")
}
if safe {
basename := path.Base(safeName)
os.Remove(fpath);
err = os.Symlink(basename, fpath)
if err != nil {
log.Println("!!!", "symlink error", "<", err, ">", fpath)
panic("symlink error")
}
}
}
func storeLaps(CompetitionId uint64, new_laps []Lap) {
fpath := competitionPath(&CompetitionId, "laps")
json, _ := json.MarshalIndent(new_laps, "", " ")
store(fpath, json, true)
}
func WipeLaps(CompetitionId uint64) {
storeLaps(CompetitionId, []Lap{Lap{}});
}
func UpdateLaps(CompetitionId uint64, new_laps []Lap, TimeStamp uint64) {
claps := getLaps(CompetitionId)
updated := false
for _, nl := range new_laps {
found := false
nl.TimeStamp = TimeStamp
for k := range claps {
if nl.Id != claps[k].Id {
continue
}
found = true
if nl.DisciplineId != nil {
if claps[k].DisciplineId == nil {
panic(fmt.Sprintf("Discipline not specified for lap id: %d", claps[k].LapId))
}
// check DisciplineId when present
if *nl.DisciplineId != *claps[k].DisciplineId {
log.Println("!!!", "Discipline migration not allowed",
nl.DisciplineId, "!=", claps[k].DisciplineId,
"for Id", claps[k].Id)
panic("Invalid DisciplineId")
}
}
claps[k].TimeStamp = nl.TimeStamp
if nl.CrewId != nil &&
(claps[k].CrewId == nil || claps[k].CrewId != nl.CrewId) {
claps[k].CrewId = nl.CrewId
updated = true
}
if nl.LapId != nil &&
(claps[k].LapId == nil || claps[k].LapId != nl.LapId) {
claps[k].LapId = nl.LapId
updated = true
}
if nl.StartTime != nil &&
(claps[k].StartTime == nil || claps[k].StartTime != nl.StartTime) {
claps[k].StartTime = nl.StartTime;
updated = true
}
if nl.FinishTime != nil &&
(claps[k].FinishTime == nil || claps[k].FinishTime != nl.FinishTime) {
claps[k].FinishTime = nl.FinishTime
updated = true
}
if nl.Strike != nil &&
(claps[k].Strike == nil || claps[k].Strike != nl.Strike) {
claps[k].Strike = nl.Strike
updated = true
}
var gates_updated bool
claps[k].Gates, gates_updated = mergeGates(claps[k].Gates, nl.Gates)
if gates_updated {
updated = true
}
}
if !found {
if nl.DisciplineId == nil {
panic("Insert new data not allowed without DisciplineId")
}
claps = append(claps, nl)
updated = true
}
}
if updated {
storeLaps(CompetitionId, claps)
}
}
func getTerminals(CompetitionId *uint64) []TerminalStatus {
var terms []TerminalStatus
var fpath = competitionPath(CompetitionId, "terminals")
data, err := ioutil.ReadFile(fpath)
if err != nil {
log.Println("...", "no terminal data", fpath)
return nil
}
err = json.Unmarshal(data, &terms)
if err != nil {
log.Println("!!!", "terminals decode error", err, fpath);
panic("Terminal decode error")
}
return terms
}
func setTerminals(CompetitionId *uint64, terms []TerminalStatus) {
var fpath = competitionPath(CompetitionId, "terminals")
data, _ := json.MarshalIndent(terms, "", " ")
if CompetitionId == nil {
store(fpath, data, false)
} else {
/* only for saving in race use safe write */
store(fpath, data, true)
}
}
func UpdateTerminals(CompetitionId *uint64, terms []TerminalStatus, TimeStamp uint64) {
var cterms = getTerminals(CompetitionId)
for _, nt := range terms {
found := false
nt.TimeStamp = TimeStamp
for i, ct := range cterms {
if ct.TerminalString != nt.TerminalString {
continue
}
cterms[i] = nt
found = true
}
if !found {
cterms = append(cterms, nt)
}
}
setTerminals(CompetitionId, cterms)
}
func GetTerminals(CompetitionId uint64, TerminalString *string, TimeStamp uint64) []TerminalStatus {
var rterms []TerminalStatus = make([]TerminalStatus, 0)
var activities = getTerminalsActivity()
var terms = getTerminals(&CompetitionId)
for _, t := range terms {
if TerminalString != nil {
if t.TerminalString != *TerminalString {
continue
}
}
if TimeStamp == 0 || t.TimeStamp > TimeStamp {
t.Activity = activities[t.TerminalString]
rterms = append(rterms, t)
}
}
return rterms
}
func GetShortTerminals() []TerminalStatusShort {
var rterms []TerminalStatusShort = make([]TerminalStatusShort, 0)
var activities = getTerminalsActivity()
for terminal, activity := range activities {
var termShort TerminalStatusShort
termShort.TerminalId = terminal
termShort.Activity = activity
rterms = append(rterms, termShort)
}
return rterms
}
var terminalActivities []byte
func getTerminalsActivity() map[string]TerminalStatusActivity {
var r map[string]TerminalStatusActivity
if len(terminalActivities) != 0 {
err := json.Unmarshal(terminalActivities, &r)
if err != nil {
log.Println("!!!", "terminal activity decode error", err);
return make(map[string]TerminalStatusActivity)
}
} else {
r = make(map[string]TerminalStatusActivity)
}
return r
}
func setTerminalsActivity(r map[string]TerminalStatusActivity) {
data, err := json.Marshal(r)
if err != nil {
log.Println("!!!", "terminal activity encode error", err);
}
terminalActivities = data
}
func UpdateTerminalActivity(TerminalString string) {
var r = getTerminalsActivity()
r[TerminalString] = TerminalStatusActivity{ LastActivity: uint64(time.Now().UTC().UnixNano() / 1000000) };
setTerminalsActivity(r)
}
func GetCompetitions() []RaceStatus {
var rstats []RaceStatus = make([]RaceStatus, 0)
files, err := ioutil.ReadDir("db")
if err != nil {
panic(err)
}
for _, f := range files {
CompetitionId, err := strconv.ParseUint(f.Name(), 10, 32)
if err != nil {
continue
}
if CompetitionId == 0 {
// zero is special competition id
continue
}
if rstat := GetRaceStatus(CompetitionId); rstat != nil {
rstats = append(rstats, *rstat)
}
}
return rstats
}
func AllocNewCompetitionId(id uint64) error {
fpath := competitionPath(&id, "race")
return os.MkdirAll(path.Dir(fpath), os.ModePerm);
}
func MakeDefaultCompetitionId(CompetitionId uint64) {
defLink := competitionRoot(0)
os.Remove(defLink)
err := os.Symlink(fmt.Sprintf("%d", CompetitionId), defLink)
if err != nil {
panic(fmt.Sprintln("Cannot setup race:", err))
}
} |
package accounting
import (
"github.com/fanda-org/postmasters/database/models"
"github.com/fanda-org/postmasters/database/models/system"
)
// LedgerGroup model
type LedgerGroup struct {
models.Base
GroupCode string `gorm:"size:12;not null;unique_index:uix_ledger_group_code"` //A-00-0-00000 -> (A/L/I/E)-SEQUENCE-LEVEL-INDEX
GroupName string `gorm:"size:50;not null;unique_index:uix_ledger_group_name"`
Description *string `gorm:"size:255"`
GroupType string `gorm:"size:5;not null"` // AST-Asset, LIA-Liability, INC-Income, EXP-Expenses
Parent *LedgerGroup // `gorm:"foreignkey:ParentID;association_foreignkey:ID"`
ParentID string `gorm:"type:char(36);not null"`
Organization system.Organization `gorm:"foreignkey:OrgID;association_foreignkey:ID"`
OrgID *string `gorm:"type:char(36);unique_index:uix_ledger_group_code,uix_ledger_group_name"` // NULL = System LedgerGroup
IsSystem bool
}
|
package sorts
func Merge(s []int) {
if len(s) < 2 {
return
}
half := len(s) / 2
left, right := s[0:half], s[half:]
Merge(left)
Merge(right)
sortRelativeSortedSlices(left, right)
}
func sortRelativeSortedSlices(left, right []int) {
lLength, rLength := len(left), len(right)
totalLength := lLength + rLength
merged := make([]int, totalLength)
for tIndex, lIndex, rIndex := 0, 0, 0; tIndex < totalLength; tIndex++ {
var lValue, rValue *int
if lIndex < lLength {
lValue = &left[lIndex]
}
if rIndex < rLength {
rValue = &right[rIndex]
}
if lValue != nil && rValue == nil {
merged[tIndex] = *lValue
lIndex++
continue
}
if rValue != nil && lValue == nil {
merged[tIndex] = *rValue
rIndex++
continue
}
if *lValue <= *rValue {
merged[tIndex] = *lValue
lIndex++
} else {
merged[tIndex] = *rValue
rIndex++
}
}
for i, lIndex, rIndex := 0, 0, 0; i < len(merged); i++ {
value := merged[i]
if lIndex < lLength {
left[lIndex] = value
lIndex++
} else {
right[rIndex] = value
rIndex++
}
}
}
|
package resttest
import (
"encoding/json"
"github.com/stretchr/testify/suite"
"net/http"
"testing"
)
func TestRunnerTestSuite(t *testing.T) {
suite.Run(t, new(RunnerTestSuite))
}
type RunnerTestSuite struct {
suite.Suite
fixedSender string
runner *Runner
response *greetingResponse
}
func (s *RunnerTestSuite) TestRun() {
s.runner.Run("POST", "/", &greetingRequest{s.fixedSender})
s.Equal(&greetingResponse{
Sender: s.fixedSender,
}, s.response)
}
func (s *RunnerTestSuite) SetupTest() {
s.fixedSender = "FOO"
s.response = &greetingResponse{}
s.runner = NewRunner(s.response)
s.runner.Container().Handle("/", newGreetingHandler())
}
type greetingRequest struct {
Name string `json:"name"`
}
type greetingResponse struct {
Sender string `json:"sender"`
}
type greetingHandler struct{}
func newGreetingHandler() *greetingHandler {
return &greetingHandler{}
}
func (h *greetingHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
decoder := json.NewDecoder(request.Body)
body := &greetingRequest{}
decoder.Decode(body)
encoder := json.NewEncoder(writer)
encoder.Encode(&greetingResponse{
Sender: body.Name,
})
}
|
package rickandmortyapiclient
import (
"strconv"
"strings"
)
// ParseURL is function for get id of schema and return
func ParseURL(url string) int {
if url != "" {
urlSplited := strings.Split(url, "/")
ID, errParse := strconv.Atoi(urlSplited[len(urlSplited)-1])
if errParse != nil {
panic(errParse)
}
return ID
}
return 0
}
|
package mci
import (
"fmt"
"os"
"reflect"
"regexp"
"github.com/bingoohuang/gou/reflec"
"github.com/jedib0t/go-pretty/v6/table"
)
// TablePrinter print table.
type TablePrinter struct {
dittoMark string
}
// Print prints the table.
func (p TablePrinter) Print(value interface{}) {
header := make(table.Row, 0)
rows := make([]table.Row, 0)
header = append(header, "#")
v := reflect.ValueOf(value)
if v.IsNil() {
return
}
switch v.Kind() {
case reflect.Ptr:
v = v.Elem()
fallthrough
case reflect.Struct:
fields := reflec.CachedStructFields(v.Type(), "header")
createHeader(fields, &header)
createRow(fields, 0, v, &rows)
case reflect.Slice:
if v.Len() == 0 {
return
}
fields := reflec.CachedStructFields(v.Type().Elem(), "header")
createHeader(fields, &header)
for i := 0; i < v.Len(); i++ {
createRow(fields, i, v.Index(i), &rows)
}
default:
return
}
p.tableRender(header, rows...)
fmt.Println()
}
func createRow(fields []reflec.StructField, rowIndex int, v reflect.Value, rows *[]table.Row) {
row := make(table.Row, 0)
row = append(row, rowIndex+1)
for _, f := range fields {
row = append(row, v.Field(f.Index).Interface())
}
*rows = append(*rows, row)
}
func createHeader(fields []reflec.StructField, header *table.Row) {
for _, f := range fields {
*header = append(*header, BlankCamel(f.Name))
}
}
func (p TablePrinter) tableRender(header table.Row, rows ...table.Row) {
t := table.NewWriter()
t.SetOutputMirror(os.Stdout)
t.AppendHeader(header)
if p.dittoMark != "" {
t.AppendRows(p.dittoMarkRows(rows))
} else {
t.AppendRows(rows)
}
t.Render()
}
func (p TablePrinter) dittoMarkRows(rows []table.Row) []table.Row {
mark := make(map[int]interface{})
for i, row := range rows {
for j, cell := range row {
v, ok := mark[j]
if ok && v != "" && v == cell {
rows[i][j] = p.dittoMark
} else {
mark[j] = cell
}
}
}
return rows
}
// BlankCamel make a camel string to blanks.
func BlankCamel(str string) string {
blank := regexp.MustCompile("(.)([A-Z][a-z]+)").ReplaceAllString(str, "${1} ${2}")
return regexp.MustCompile("([a-z0-9])([A-Z])").ReplaceAllString(blank, "${1} ${2}")
}
|
// simple-authd project main.go
package main
import (
"encoding/base64"
"encoding/hex"
"flag"
"fmt"
"log"
"math/rand"
"net"
"net/http"
"strings"
"sync"
"time"
)
type stringList map[string]string
func (l *stringList) String() string {
return fmt.Sprintln(*l)
}
func (l *stringList) Set(value string) error {
kv := strings.SplitN(value, ":", 2)
if len(kv) == 2 {
(*l)[kv[0]] = kv[1]
}
return nil
}
var (
userlist stringList = make(stringList)
timeout int
listen string
tokenCache sync.Map
)
func newToken() string {
p := make([]byte, 16)
rand.Read(p)
phex := hex.EncodeToString(p)
tokenCache.Store(phex, time.Now().Add(time.Second*time.Duration(timeout)))
return phex
}
func paw() {
var t time.Time
for {
time.Sleep(time.Minute * 5)
t = time.Now()
tokenCache.Range(func(key, value interface{}) bool {
if value.(time.Time).Before(t) {
tokenCache.Delete(key)
}
return true
})
}
}
func getDomain(subDomain string) string {
if host, _, err := net.SplitHostPort(subDomain); err == nil {
subDomain = host
}
parts := strings.SplitN(subDomain, ".", 3)
if len(parts) == 3 {
return parts[1] + "." + parts[2] // return the parent domain
} else {
return subDomain // return the domain itself.
}
}
func serveAuth(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
if c, err := r.Cookie("pvtoken"); err == nil {
if _, ok := tokenCache.Load(c.Value); ok {
w.WriteHeader(http.StatusOK)
return
}
}
basicAuthPrefix := "Basic "
// get request header
auth := r.Header.Get("Authorization")
// http basic auth
if strings.HasPrefix(auth, basicAuthPrefix) {
// decode auth info
payload, err := base64.StdEncoding.DecodeString(
auth[len(basicAuthPrefix):],
)
if err == nil {
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) == 2 {
if pwd, ok := userlist[pair[0]]; ok && pwd == pair[1] {
// success!
log.Println(pair[0], "authorized on", r.Host)
w.Header().Set("Set-Cookie", fmt.Sprintf("pvtoken=%s; Max-Age=%d; Domain=%s; Path=/", newToken(), timeout, getDomain(r.Host)))
w.WriteHeader(http.StatusOK)
return
} else {
log.Println(pair[0], "failed with password", pair[1])
}
}
}
}
// return 401 Unauthorized with realm Restricted.
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
w.WriteHeader(http.StatusUnauthorized)
}
func main() {
flag.Var(&userlist, "u", "username:password pairs. can be called multiple times.")
flag.IntVar(&timeout, "t", 3600, "token timeout, in second")
flag.StringVar(&listen, "l", "127.0.0.1:3333", "bind address")
flag.Parse()
if len(userlist) == 0 {
flag.PrintDefaults()
return
}
rand.Seed(time.Now().UnixNano())
go paw()
if err := http.ListenAndServe(listen, http.HandlerFunc(serveAuth)); err != nil {
log.Fatalln(err)
}
}
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package externalmetrics
import (
"fmt"
"strconv"
apicommon "github.com/DataDog/datadog-operator/apis/datadoghq/common"
apicommonv1 "github.com/DataDog/datadog-operator/apis/datadoghq/common/v1"
"github.com/DataDog/datadog-operator/apis/datadoghq/v1alpha1"
"github.com/DataDog/datadog-operator/apis/datadoghq/v2alpha1"
apiutils "github.com/DataDog/datadog-operator/apis/utils"
"github.com/DataDog/datadog-operator/controllers/datadogagent/component"
componentdca "github.com/DataDog/datadog-operator/controllers/datadogagent/component/clusteragent"
"github.com/DataDog/datadog-operator/controllers/datadogagent/feature"
cilium "github.com/DataDog/datadog-operator/pkg/cilium/v1"
"github.com/DataDog/datadog-operator/pkg/kubernetes/rbac"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
netv1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
)
func init() {
err := feature.Register(feature.ExternalMetricsIDType, buildExternalMetricsFeature)
if err != nil {
panic(err)
}
}
func buildExternalMetricsFeature(options *feature.Options) feature.Feature {
externalMetricsFeat := &externalMetricsFeature{}
if options != nil {
externalMetricsFeat.logger = options.Logger
}
return externalMetricsFeat
}
type externalMetricsFeature struct {
useWPA bool
useDDM bool
port int32
url string
keySecret map[string]secret
serviceAccountName string
owner metav1.Object
logger logr.Logger
createKubernetesNetworkPolicy bool
createCiliumNetworkPolicy bool
}
type secret struct {
name string
key string
data []byte
}
// ID returns the ID of the Feature
func (f *externalMetricsFeature) ID() feature.IDType {
return feature.ExternalMetricsIDType
}
// Configure is used to configure the feature from a v2alpha1.DatadogAgent instance.
func (f *externalMetricsFeature) Configure(dda *v2alpha1.DatadogAgent) (reqComp feature.RequiredComponents) {
f.owner = dda
em := dda.Spec.Features.ExternalMetricsServer
if em != nil && apiutils.BoolValue(em.Enabled) {
f.useWPA = apiutils.BoolValue(em.WPAController)
f.useDDM = apiutils.BoolValue(em.UseDatadogMetrics)
f.port = *em.Port
if em.Endpoint != nil {
if em.Endpoint.URL != nil {
f.url = *em.Endpoint.URL
}
creds := em.Endpoint.Credentials
if creds != nil {
f.keySecret = make(map[string]secret)
if !v2alpha1.CheckAPIKeySufficiency(creds, apicommon.DDExternalMetricsProviderAPIKey) ||
!v2alpha1.CheckAppKeySufficiency(creds, apicommon.DDExternalMetricsProviderAppKey) {
// for one of api or app keys, neither secrets nor external metrics key env vars
// are defined, so store key data to create secret later
for keyType, keyData := range v2alpha1.GetKeysFromCredentials(creds) {
f.keySecret[keyType] = secret{
data: keyData,
}
}
}
if creds.APISecret != nil {
_, secretName, secretKey := v2alpha1.GetAPIKeySecret(creds, componentdca.GetDefaultExternalMetricSecretName(f.owner))
if secretName != "" && secretKey != "" {
// api key secret exists; store secret name and key instead
f.keySecret[apicommon.DefaultAPIKeyKey] = secret{
name: secretName,
key: secretKey,
}
}
}
if creds.AppSecret != nil {
_, secretName, secretKey := v2alpha1.GetAppKeySecret(creds, componentdca.GetDefaultExternalMetricSecretName(f.owner))
if secretName != "" && secretKey != "" {
// app key secret exists; store secret name and key instead
f.keySecret[apicommon.DefaultAPPKeyKey] = secret{
name: secretName,
key: secretKey,
}
}
}
}
}
f.serviceAccountName = v2alpha1.GetClusterAgentServiceAccount(dda)
if enabled, flavor := v2alpha1.IsNetworkPolicyEnabled(dda); enabled {
if flavor == v2alpha1.NetworkPolicyFlavorCilium {
f.createCiliumNetworkPolicy = true
} else {
f.createKubernetesNetworkPolicy = true
}
}
reqComp = feature.RequiredComponents{
ClusterAgent: feature.RequiredComponent{IsRequired: apiutils.NewBoolPointer(true)},
}
}
return reqComp
}
// ConfigureV1 use to configure the feature from a v1alpha1.DatadogAgent instance.
func (f *externalMetricsFeature) ConfigureV1(dda *v1alpha1.DatadogAgent) (reqComp feature.RequiredComponents) {
// f.owner = dda
// if dda.Spec.ClusterAgent.Config != nil && dda.Spec.ClusterAgent.Config.ExternalMetrics != nil {
// em := dda.Spec.ClusterAgent.Config.ExternalMetrics
// if em != nil && apiutils.BoolValue(em.Enabled) {
// f.useWPA = em.WpaController
// f.useDDM = em.UseDatadogMetrics
// f.port = *em.Port
// if em.Endpoint != nil {
// f.url = *em.Endpoint
// }
// if em.Credentials != nil {
// if em.Credentials != nil {
// f.keySecret = make(map[string]secret)
// if !v1alpha1.CheckAPIKeySufficiency(em.Credentials, apicommon.DDExternalMetricsProviderAPIKey) ||
// !v1alpha1.CheckAppKeySufficiency(em.Credentials, apicommon.DDExternalMetricsProviderAppKey) {
// // neither secrets nor the external metrics api/app key env vars are defined,
// // so store key data to create secret later
// for keyType, keyData := range v1alpha1.GetKeysFromCredentials(em.Credentials) {
// f.keySecret[keyType] = secret{
// data: keyData,
// }
// }
// }
// if v1alpha1.CheckAPIKeySufficiency(em.Credentials, apicommon.DDExternalMetricsProviderAPIKey) {
// // api key secret exists; store secret name and key instead
// if isSet, secretName, secretKey := v1alpha1.GetAPIKeySecret(em.Credentials, componentdca.GetDefaultExternalMetricSecretName(f.owner)); isSet {
// f.keySecret[apicommon.DefaultAPIKeyKey] = secret{
// name: secretName,
// key: secretKey,
// }
// }
// }
// if v1alpha1.CheckAppKeySufficiency(em.Credentials, apicommon.DDExternalMetricsProviderAppKey) {
// // app key secret exists; store secret name and key instead
// if isSet, secretName, secretKey := v1alpha1.GetAppKeySecret(em.Credentials, componentdca.GetDefaultExternalMetricSecretName(f.owner)); isSet {
// f.keySecret[apicommon.DefaultAPPKeyKey] = secret{
// name: secretName,
// key: secretKey,
// }
// }
// }
// }
// }
// f.serviceAccountName = v1alpha1.GetClusterAgentServiceAccount(dda)
// if enabled, flavor := v1alpha1.IsAgentNetworkPolicyEnabled(dda); enabled {
// if flavor == v1alpha1.NetworkPolicyFlavorCilium {
// f.createCiliumNetworkPolicy = true
// } else {
// f.createKubernetesNetworkPolicy = true
// }
// }
// reqComp = feature.RequiredComponents{
// ClusterAgent: feature.RequiredComponent{IsRequired: apiutils.NewBoolPointer(true)},
// }
// }
// }
// return reqComp
// do not apply this feature on v1alpha1
// it breaks the unittests in `controller_test.go` because the `store` modifies
// the dependency resources with additional labels which make the comparison fail
return feature.RequiredComponents{}
}
// ManageDependencies allows a feature to manage its dependencies.
// Feature's dependencies should be added in the store.
func (f *externalMetricsFeature) ManageDependencies(managers feature.ResourceManagers, components feature.RequiredComponents) error {
ns := f.owner.GetNamespace()
// service
emPorts := []corev1.ServicePort{
{
Protocol: corev1.ProtocolTCP,
Port: f.port,
Name: apicommon.ExternalMetricsPortName,
},
}
selector := map[string]string{
apicommon.AgentDeploymentNameLabelKey: f.owner.GetName(),
apicommon.AgentDeploymentComponentLabelKey: apicommon.DefaultClusterAgentResourceSuffix,
}
serviceName := componentdca.GetMetricsServerServiceName(f.owner)
if err := managers.ServiceManager().AddService(serviceName, ns, selector, emPorts, nil); err != nil {
return fmt.Errorf("error adding external metrics provider service to store: %w", err)
}
// apiservice
apiServiceSpec := apiregistrationv1.APIServiceSpec{
Service: &apiregistrationv1.ServiceReference{
Name: serviceName,
Namespace: ns,
Port: &f.port,
},
Version: "v1beta1",
InsecureSkipTLSVerify: true,
Group: rbac.ExternalMetricsAPIGroup,
GroupPriorityMinimum: 100,
VersionPriority: 100,
}
if err := managers.APIServiceManager().AddAPIService(componentdca.GetMetricsServerAPIServiceName(), ns, apiServiceSpec); err != nil {
return fmt.Errorf("error adding external metrics provider apiservice to store: %w", err)
}
// credential secret
if len(f.keySecret) != 0 {
for idx, s := range f.keySecret {
if len(s.data) != 0 {
if err := managers.SecretManager().AddSecret(ns, componentdca.GetDefaultExternalMetricSecretName(f.owner), idx, string(s.data)); err != nil {
return fmt.Errorf("error adding external metrics provider credentials secret to store: %w", err)
}
}
}
}
// rbac
rbacResourcesName := componentdca.GetClusterAgentRbacResourcesName(f.owner)
if err := managers.RBACManager().AddClusterPolicyRules(ns, rbacResourcesName, f.serviceAccountName, getDCAClusterPolicyRules(f.useDDM, f.useWPA)); err != nil {
return fmt.Errorf("error adding external metrics provider dca clusterrole and clusterrolebinding to store: %w", err)
}
if err := managers.RBACManager().AddClusterPolicyRules("kube-system", componentdca.GetExternalMetricsReaderClusterRoleName(f.owner, managers.Store().GetVersionInfo()), "horizontal-pod-autoscaler", getExternalMetricsReaderPolicyRules()); err != nil {
return fmt.Errorf("error adding external metrics provider external metrics reader clusterrole and clusterrolebinding to store: %w", err)
}
if err := managers.RBACManager().AddClusterRoleBinding(ns, componentdca.GetHPAClusterRoleBindingName(f.owner), f.serviceAccountName, getAuthDelegatorRoleRef()); err != nil {
return fmt.Errorf("error adding external metrics provider auth delegator clusterrolebinding to store: %w", err)
}
// network policies
policyName, podSelector := component.GetNetworkPolicyMetadata(f.owner, v2alpha1.ClusterAgentComponentName)
if f.createKubernetesNetworkPolicy {
ingressRules := []netv1.NetworkPolicyIngressRule{
{
Ports: []netv1.NetworkPolicyPort{
{
Port: &intstr.IntOrString{
Type: intstr.Int,
IntVal: f.port,
},
},
},
},
}
return managers.NetworkPolicyManager().AddKubernetesNetworkPolicy(
policyName,
f.owner.GetNamespace(),
podSelector,
nil,
ingressRules,
nil,
)
} else if f.createCiliumNetworkPolicy {
policySpecs := []cilium.NetworkPolicySpec{
{
Description: "Ingress from API server for external metrics",
EndpointSelector: podSelector,
Ingress: []cilium.IngressRule{
{
FromEntities: []cilium.Entity{cilium.EntityWorld},
ToPorts: []cilium.PortRule{
{
Ports: []cilium.PortProtocol{
{
Port: strconv.Itoa(int(f.port)),
Protocol: cilium.ProtocolTCP,
},
},
},
},
},
},
},
}
return managers.CiliumPolicyManager().AddCiliumPolicy(policyName, f.owner.GetNamespace(), policySpecs)
}
return nil
}
// ManageClusterAgent allows a feature to configure the ClusterAgent's corev1.PodTemplateSpec
// It should do nothing if the feature doesn't need to configure it.
func (f *externalMetricsFeature) ManageClusterAgent(managers feature.PodTemplateManagers) error {
managers.EnvVar().AddEnvVarToContainer(apicommonv1.ClusterAgentContainerName, &corev1.EnvVar{
Name: apicommon.DDExternalMetricsProviderEnabled,
Value: "true",
})
managers.EnvVar().AddEnvVarToContainer(apicommonv1.ClusterAgentContainerName, &corev1.EnvVar{
Name: apicommon.DDExternalMetricsProviderPort,
Value: strconv.FormatInt(int64(f.port), 10),
})
managers.EnvVar().AddEnvVarToContainer(apicommonv1.ClusterAgentContainerName, &corev1.EnvVar{
Name: apicommon.DDExternalMetricsProviderUseDatadogMetric,
Value: apiutils.BoolToString(&f.useDDM),
})
managers.EnvVar().AddEnvVarToContainer(apicommonv1.ClusterAgentContainerName, &corev1.EnvVar{
Name: apicommon.DDExternalMetricsProviderWPAController,
Value: apiutils.BoolToString(&f.useWPA),
})
if f.url != "" {
managers.EnvVar().AddEnvVarToContainer(apicommonv1.ClusterAgentContainerName, &corev1.EnvVar{
Name: apicommon.DDExternalMetricsProviderEndpoint,
Value: f.url,
})
}
if len(f.keySecret) != 0 {
// api key
if s, ok := f.keySecret[apicommon.DefaultAPIKeyKey]; ok {
var apiKeyEnvVar *corev1.EnvVar
// api key from existing secret
if s.name != "" {
apiKeyEnvVar = component.BuildEnvVarFromSource(
apicommon.DDExternalMetricsProviderAPIKey,
component.BuildEnvVarFromSecret(s.name, s.key),
)
} else {
// api key from secret created by operator
apiKeyEnvVar = component.BuildEnvVarFromSource(
apicommon.DDExternalMetricsProviderAPIKey,
component.BuildEnvVarFromSecret(componentdca.GetDefaultExternalMetricSecretName(f.owner), apicommon.DefaultAPIKeyKey),
)
}
managers.EnvVar().AddEnvVarToContainer(apicommonv1.ClusterAgentContainerName, apiKeyEnvVar)
}
// app key
if s, ok := f.keySecret[apicommon.DefaultAPPKeyKey]; ok {
var appKeyEnvVar *corev1.EnvVar
// app key from existing secret
if s.name != "" {
appKeyEnvVar = component.BuildEnvVarFromSource(
apicommon.DDExternalMetricsProviderAppKey,
component.BuildEnvVarFromSecret(s.name, s.key),
)
} else {
// api key from secret created by operator
appKeyEnvVar = component.BuildEnvVarFromSource(
apicommon.DDExternalMetricsProviderAppKey,
component.BuildEnvVarFromSecret(componentdca.GetDefaultExternalMetricSecretName(f.owner), apicommon.DefaultAPPKeyKey),
)
}
managers.EnvVar().AddEnvVarToContainer(apicommonv1.ClusterAgentContainerName, appKeyEnvVar)
}
}
managers.Port().AddPortToContainer(apicommonv1.ClusterAgentContainerName, &corev1.ContainerPort{
Name: apicommon.ExternalMetricsPortName,
ContainerPort: f.port,
Protocol: corev1.ProtocolTCP,
})
return nil
}
// ManageNodeAgent allows a feature to configure the Node Agent's corev1.PodTemplateSpec
// It should do nothing if the feature doesn't need to configure it.
func (f *externalMetricsFeature) ManageNodeAgent(managers feature.PodTemplateManagers) error {
return nil
}
// ManageClusterChecksRunner allows a feature to configure the ClusterChecksRunner's corev1.PodTemplateSpec
// It should do nothing if the feature doesn't need to configure it.
func (f *externalMetricsFeature) ManageClusterChecksRunner(managers feature.PodTemplateManagers) error {
return nil
}
|
package main
import "fmt"
func main() {
truth := true
negate(&truth)
fmt.Println(truth)
lie := false
negate(&lie)
fmt.Println(lie)
}
func negate(myBool *bool) {
*myBool = !*myBool
}
|
package uuid
import (
"code.google.com/p/go-uuid/uuid"
"fmt"
)
func GenerateUuid() uuid.UUID {
uuid := uuid.NewRandom()
fmt.Println("Generated uuid:", uuid)
return uuid
}
|
package main
import "fmt"
func main() {
a := byte('A')
// showing print format specifier for decimal, octal, hex
// and binary.
fmt.Printf("%d %o %x %b \n", a, a, a, a)
// using only one argument with multiple format specifiers
fmt.Printf("%d %[1]o %[1]x %[1]b\n", a)
// let go implicity convert from a rune to a byte
fmt.Printf("%d %o %x %b\n", 'A', 'A', 'A', 'A')
}
|
package model
import (
"fmt"
"time"
"github.com/globalsign/mgo/bson"
"github.com/simplejia/clog/api"
)
func (stat *Stat) CleanNumDay() (err error) {
c := stat.GetC()
defer c.Database.Session.Close()
day := time.Now().Add(time.Hour * 24).Day()
field := fmt.Sprintf("num_day_%d", day)
sel := bson.M{
field: bson.M{
"$ne": 0,
},
}
up := bson.M{
"$set": bson.M{
field: 0,
},
}
_, err = c.UpdateAll(sel, up)
if err != nil {
return
}
return
}
func cleanNumDayTimer() {
fun := "model.cleanNumDayTimer"
tick := time.Tick(time.Hour)
for {
select {
case <-tick:
err := NewStat().CleanNumDay()
if err != nil {
clog.Error("%s CleanNumDay err: %v", fun, err)
}
}
}
}
func init() {
go cleanNumDayTimer()
}
|
package client
// Config - client configuration
type Config struct {
Addr string
Space string
}
|
// Copyright © 2019 Michael. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pkg
import (
"os"
"path/filepath"
"skygo/utils"
"skygo/utils/log"
)
var pn = [...]string{
"usr/bin",
"usr/sbin",
"bin",
"sbin",
"usr/lib",
"lib",
"etc",
}
var pn_dev = [...]string{
"usr/include",
"usr/lib",
"lib",
}
type pkg struct {
box *utils.StageBox
name string // individual package name
}
// Package is interface to handle package
type Packager interface {
// get individual package by name
GetPkg(name string) *utils.StageBox
// new individual package
NewPkg(name string) *utils.StageBox
}
// Packges implements interface Packager
type Packages struct {
owner string
pkgs map[string]pkg
}
// NewPkg create new stageBox for package @name and add into Packages
func (p *Packages) NewPkg(name string) *utils.StageBox {
if p.pkgs == nil {
p.owner = name
p.pkgs = make(map[string]pkg)
}
box := new(utils.StageBox)
pkg := pkg{box: box, name: name}
devpkg := p.owner + "-dev"
switch name {
case p.owner:
for _, v := range pn {
box.Push(v)
}
case devpkg:
for _, v := range pn_dev {
box.Push(v)
}
pkg.name = devpkg
}
p.pkgs[pkg.name] = pkg
return box
}
// GetPkg get package @name from Packages
func (p *Packages) GetPkg(name string) *utils.StageBox {
return p.pkgs[name].box
}
// Package pack files from @from to @to
func (p *Packages) Package(from, to string) error {
for _, pkg := range p.pkgs {
dest := filepath.Join(to, pkg.name)
log.Info("Start staging files from %s to %s\n", from, dest)
os.RemoveAll(dest)
if err := pkg.box.Stage(from, dest); err != nil {
return err
}
// TODO: pack
}
return nil
}
|
package main
import "fmt"
func foldr3(f func(a,b []int) []int, z []int, list []int)[]int{
if len(list) == 0{
return z
}
return f(list[:1],foldr3(f,z,list[1:]))
}
func main() {
ilist := []int{1,2,3,4,5,6,7,8}
fn := func(a,b []int) []int {
b = append(b,a...)
return b
}
fmt.Printf("list %v\n",foldr3(fn,[]int{},ilist))
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package wmp
import (
"context"
"time"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/ash"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/event"
"chromiumos/tast/local/chrome/uiauto/faillog"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/chrome/uiauto/trackpad"
"chromiumos/tast/local/input"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: TrackpadReverseScroll,
LacrosStatus: testing.LacrosVariantUnneeded,
Desc: "Checks that track pad reverse scrolling works properly",
Contacts: []string{"dandersson@chromium.org", "zxdan@chromium.org", "chromeos-wmp@google.com", "chromeos-sw-engprod@google.com"},
Attr: []string{"group:mainline", "informational"},
SoftwareDeps: []string{"chrome"},
Fixture: "chromeLoggedIn",
SearchFlags: []*testing.StringPair{
{
Key: "feature_id",
Value: "screenplay-ac83aef4-5602-49b7-8ef8-088f6660d52a",
},
},
Params: []testing.Param{
{
Name: "reverse_on",
Val: true,
},
{
Name: "reverse_off",
Val: false,
},
},
})
}
// TrackpadReverseScroll tests the trackpad reverse scrolling.
func TrackpadReverseScroll(ctx context.Context, s *testing.State) {
// Reserve five seconds for various cleanup.
cleanupCtx := ctx
ctx, cancel := ctxutil.Shorten(ctx, 5*time.Second)
defer cancel()
cr := s.FixtValue().(*chrome.Chrome)
tconn, err := cr.TestAPIConn(ctx)
if err != nil {
s.Fatal("Failed to connect to test API: ", err)
}
ui := uiauto.New(tconn)
defer faillog.DumpUITreeWithScreenshotOnError(cleanupCtx, s.OutDir(), s.HasError, cr, "ui_dump")
tpw, err := input.Trackpad(ctx)
if err != nil {
s.Fatal("Failed to initialize the trackpad: ", err)
}
defer tpw.Close()
reverseOn := s.Param().(bool)
switchReverse := trackpad.TurnOffReverseScroll
if reverseOn {
switchReverse = trackpad.TurnOnReverseScroll
}
if err := switchReverse(ctx, tconn); err != nil {
s.Fatal("Failed to switch trackpad reverse scroll: ", err)
}
// -------------- Outside Overview Mode ---------------------
// 1. Swiping down with 3 fingers won't enter overview.
// 2. If reverse scroll is off, consecutively swiping down twice with 3
// fingers will trigger a system toast.
// 3. Swiping up with 3 fingers will enter overview.
// If reverse scrolling is off, swiping down twice with 3 fingers will
// trigger a system toast.
if !reverseOn {
if err := swipeTwice(ctx, tconn, tpw, trackpad.DownSwipe, 3); err != nil {
s.Fatal("Failed to swipe down twice with 3 fingers: ", err)
}
if err := waitForSystemToast(ctx, ui); err != nil {
s.Fatal("Failed to show wrong overview gesture toast: ", err)
}
}
// Swiping up with 3 fingers will enter Overview.
if err := swipeToEnterOverview(ctx, tconn, tpw); err != nil {
s.Fatal("Failed to swipe up to enter Overview: ", err)
}
defer ash.SetOverviewModeAndWait(cleanupCtx, tconn, false)
// ---------------------------------------------------------
// Wait for an interval for the next swipe gesture.
if err := testing.Sleep(ctx, swipeInterval); err != nil {
s.Fatal("Failed to wait for the swipe interval: ", err)
}
// -------------- Inside Overview Mode ---------------------
// 1. Swiping up with 3 fingers won't exit overview.
// 2. If reverse scroll is off, consecutively swiping up twice with 3
// fingers will trigger a system toast.
// 3. Swiping down with 3 fingers will exit overview.
// If reverse scrolling is off, swiping up twice with 3 fingers will
// trigger a system toast.
if !reverseOn {
if err := swipeTwice(ctx, tconn, tpw, trackpad.UpSwipe, 3); err != nil {
s.Fatal("Failed to swipe down twice with 3 fingers: ", err)
}
if err := waitForSystemToast(ctx, ui); err != nil {
s.Fatal("Failed to show wrong overview gesture toast: ", err)
}
}
// Swiping down with 3 fingers will exit Overview.
if err := swipeToExitOverview(ctx, tconn, tpw); err != nil {
s.Fatal("Failed to swipe down to exit Overview: ", err)
}
// ---------------------------------------------------------
// Create a new desk.
if err := ash.CreateNewDesk(ctx, tconn); err != nil {
s.Fatal("Failed to create a new desk: ", err)
}
defer ash.CleanUpDesks(cleanupCtx, tconn)
// ------------ On The Leftmost Desk ----------------------
// 1. If reverse scroll is off, consecutively swiping left twice with 4
// fingers will trigger a system toast (only for non reverse scrolling).
// 2. If reverse scroll is off, Swiping right with 4 fingers will switch to
// the right desk. Otherwise, swiping left with 4 fingers will switch to
// the right desk.
// If reverse scroll is off, swiping left twice with 4 fingers will trigger a system toast.
if !reverseOn {
if err := swipeTwice(ctx, tconn, tpw, trackpad.LeftSwipe, 4); err != nil {
s.Fatal("Failed to swipe left twice with 4 fingers: ", err)
}
if err := waitForSystemToast(ctx, ui); err != nil {
s.Fatal("Failed to show wrong switching desk gesture toast: ", err)
}
}
// If reverse scroll is off (on), swiping right (left) with 4 fingers will switch to the right desk.
swipeDirection := trackpad.RightSwipe
if reverseOn {
swipeDirection = trackpad.LeftSwipe
}
if err := swipeToDesk(ctx, tconn, tpw, swipeDirection, 1); err != nil {
s.Fatal("Failed to switch to the right desk: ", err)
}
//-------------------------------------------------------
// ------------ On The Rightmost Desk ---------------------
// 1. If reverse scroll is off, consecutively swiping right twice with 4
// fingers will trigger a system toast (only for non reverse scrolling).
// 2. If reverse scroll is off, Swiping left with 4 fingers will switch to
// the left desk. Otherwise, swiping right with 4 fingers will switch to
// the left desk.
// If reverse scroll is off, swiping right twice with 4 fingers will trigger a system toast.
if !reverseOn {
if err := swipeTwice(ctx, tconn, tpw, trackpad.RightSwipe, 4); err != nil {
s.Fatal("Failed to swipe right twice with 4 fingers: ", err)
}
if err := waitForSystemToast(ctx, ui); err != nil {
s.Fatal("Failed to show wrong switching desk gesture toast: ", err)
}
}
// If reverse scroll is off (on), swiping left (right) with 4 fingers will switch to the left desk.
swipeDirection = trackpad.LeftSwipe
if reverseOn {
swipeDirection = trackpad.RightSwipe
}
if err := swipeToDesk(ctx, tconn, tpw, swipeDirection, 0); err != nil {
s.Fatal("Failed to switch to the left desk: ", err)
}
}
const swipeInterval = time.Second
// swipeTwice performs trackpad swipe twice in the given direction with indicated number of touches.
func swipeTwice(ctx context.Context, tconn *chrome.TestConn, tpw *input.TrackpadEventWriter, swipeDirection trackpad.SwipeDirection, touches int) error {
if err := trackpad.Swipe(ctx, tconn, tpw, swipeDirection, touches); err != nil {
return errors.Wrapf(err, "failed to swipe twice with %d fingers", touches)
}
if err := testing.Sleep(ctx, swipeInterval); err != nil {
return errors.Wrap(err, "failed to wait for the swipe interval")
}
if err := trackpad.Swipe(ctx, tconn, tpw, swipeDirection, touches); err != nil {
return errors.Wrapf(err, "failed to swipe twice with %d fingers", touches)
}
return nil
}
// swipeToEnterOverview performs the swiping up with 3 fingers to enter Overview and validates that Overview is entered.
func swipeToEnterOverview(ctx context.Context, tconn *chrome.TestConn, tpw *input.TrackpadEventWriter) error {
if err := trackpad.Swipe(ctx, tconn, tpw, trackpad.UpSwipe, 3); err != nil {
return errors.Wrap(err, "failed to swipe up with 3 fingers")
}
if err := ash.WaitForOverviewState(ctx, tconn, ash.Shown, 5*time.Second); err != nil {
return errors.Wrap(err, "failed to enter overview mode")
}
return nil
}
// swipeToExitOverview performs the swiping down with 3 fingers to exit Overview and validates that Overview is exited.
func swipeToExitOverview(ctx context.Context, tconn *chrome.TestConn, tpw *input.TrackpadEventWriter) error {
if err := trackpad.Swipe(ctx, tconn, tpw, trackpad.DownSwipe, 3); err != nil {
return errors.Wrap(err, "failed to swipe down with 3 fingers")
}
if err := ash.WaitForOverviewState(ctx, tconn, ash.Hidden, 5*time.Second); err != nil {
return errors.Wrap(err, "failed to exit overview mode")
}
return nil
}
// swipeToDesk performs swiping on given direction with 4 fingers to switch to the target desk with the given desk index.
func swipeToDesk(ctx context.Context, tconn *chrome.TestConn, tpw *input.TrackpadEventWriter, swipeDirection trackpad.SwipeDirection, deskIndex int) error {
ac := uiauto.New(tconn)
if err := trackpad.Swipe(ctx, tconn, tpw, swipeDirection, 4); err != nil {
return errors.Wrapf(err, "failed to swipe to: %v", swipeDirection)
}
// Make sure the desk animiation is finished.
if err := ac.WithInterval(2*time.Second).WithTimeout(10*time.Second).WaitUntilNoEvent(nodewith.Root(), event.LocationChanged)(ctx); err != nil {
return errors.Wrap(err, "failed to swipe with 4 fingers")
}
desksInfo, err := ash.GetDesksInfo(ctx, tconn)
if err != nil {
return errors.Wrap(err, "failed to get the desks info")
}
// Verify that the active desk after swipe is the desk we're looking for.
if desksInfo.ActiveDeskIndex != deskIndex {
return errors.Wrapf(err, "unexepcted active desk: got %d, want %d", desksInfo.ActiveDeskIndex, deskIndex)
}
return nil
}
// waitForSystemToast waits for the system toast showing up.
func waitForSystemToast(ctx context.Context, ui *uiauto.Context) error {
// The system toast for trackpad gesture will show up for a while and then disappear.
if err := uiauto.Combine(
"wait for system toast",
ui.WaitUntilExists(nodewith.ClassName("SystemToastInnerLabel")),
ui.WaitUntilGone(nodewith.ClassName("SystemToastInnerLabel")),
)(ctx); err != nil {
return errors.Wrap(err, "failed to show the trackpad gesture toast")
}
return nil
}
|
// Copyright (c) KwanJunWen
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package estemplate
import "fmt"
// CharacterFilterHTMLStrip character filter that strips HTML elements from the text
// and replaces HTML entities with their decoded value (e.g. replacing & with &).
//
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.5/analysis-htmlstrip-charfilter.html
// for details.
type CharacterFilterHTMLStrip struct {
CharacterFilter
name string
// fields specific to html strip character filter
escapedTags []string
}
// NewCharacterFilterHTMLStrip initializes a new CharacterFilterHTMLStrip.
func NewCharacterFilterHTMLStrip(name string) *CharacterFilterHTMLStrip {
return &CharacterFilterHTMLStrip{
name: name,
escapedTags: make([]string, 0),
}
}
// Name returns field key for the Character Filter.
func (s *CharacterFilterHTMLStrip) Name() string {
return s.name
}
// EscapedTags sets an array of HTML tags which should not be stripped from the
// original text.
func (s *CharacterFilterHTMLStrip) EscapedTags(escapedTags ...string) *CharacterFilterHTMLStrip {
s.escapedTags = append(s.escapedTags, escapedTags...)
return s
}
// Validate validates CharacterFilterHTMLStrip.
func (s *CharacterFilterHTMLStrip) Validate(includeName bool) error {
var invalid []string
if includeName && s.name == "" {
invalid = append(invalid, "Name")
}
if len(invalid) > 0 {
return fmt.Errorf("missing required fields: %v", invalid)
}
return nil
}
// Source returns the serializable JSON for the source builder.
func (s *CharacterFilterHTMLStrip) Source(includeName bool) (interface{}, error) {
// {
// "test": {
// "type": "html_strip",
// "escaped_tags": ["b"]
// }
// }
options := make(map[string]interface{})
options["type"] = "html_strip"
if len(s.escapedTags) > 0 {
options["escaped_tags"] = s.escapedTags
}
if !includeName {
return options, nil
}
source := make(map[string]interface{})
source[s.name] = options
return source, nil
}
|
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func powi(y, x int) int {
ret := 1
for x > 0 {
if x&1 > 0 {
ret *= y
}
y *= y
x >>= 1
}
return ret
}
func armstrong(n int) bool {
var e, t int
for a := n; a > 0; a /= 10 {
e++
}
for a := n; a > 0; a /= 10 {
t += powi(a%10, e)
}
return n == t
}
func main() {
var n int
data, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer data.Close()
scanner := bufio.NewScanner(data)
for scanner.Scan() {
fmt.Sscan(scanner.Text(), &n)
if armstrong(n) {
fmt.Println("True")
} else {
fmt.Println("False")
}
}
}
|
// 明确定义该模块需要的上下文信息,方便代码阅读和理解
package context
import (
"github.com/xuperchain/xupercore/kernel/common/xaddress"
xctx "github.com/xuperchain/xupercore/kernel/common/xcontext"
"github.com/xuperchain/xupercore/kernel/contract"
"github.com/xuperchain/xupercore/kernel/ledger"
"github.com/xuperchain/xupercore/kernel/network"
cryptoBase "github.com/xuperchain/xupercore/lib/crypto/client/base"
)
type BlockInterface ledger.BlockHandle
type Address xaddress.Address
type CryptoClient cryptoBase.CryptoClient
type P2pCtxInConsensus network.Network
// LedgerCtxInConsensus使用到的ledger接口
type LedgerRely interface {
GetConsensusConf() ([]byte, error)
QueryBlockHeader(blkId []byte) (ledger.BlockHandle, error)
QueryBlockHeaderByHeight(int64) (ledger.BlockHandle, error)
GetTipBlock() ledger.BlockHandle
GetTipXMSnapshotReader() (ledger.XMSnapshotReader, error)
CreateSnapshot(blkId []byte) (ledger.XMReader, error)
GetTipSnapshot() (ledger.XMReader, error)
QueryTipBlockHeader() ledger.BlockHandle
}
// ConsensusCtx共识运行环境上下文
type ConsensusCtx struct {
xctx.BaseCtx
BcName string
Address *Address
Crypto cryptoBase.CryptoClient
Contract contract.Manager
Ledger LedgerRely
Network network.Network
}
|
package main
import (
"bytes"
"fmt"
"io"
"os"
)
var w io.Writer
func main() {
w = os.Stdout
f, ok := w.(*os.File)
fmt.Println(f, ok)
c, ok := w.(*bytes.Buffer)
fmt.Println(c, ok)
// rw := w.(io.ReadWriter)
// w = new(ByteCounter)
// rw = w.(io.ReadWriter)
}
|
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package observedts
import (
"testing"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/stretchr/testify/require"
)
func TestComputeLocalUncertaintyLimit(t *testing.T) {
defer leaktest.AfterTest(t)()
txn := &roachpb.Transaction{
ReadTimestamp: hlc.Timestamp{WallTime: 10},
GlobalUncertaintyLimit: hlc.Timestamp{WallTime: 20},
}
txn.UpdateObservedTimestamp(1, hlc.ClockTimestamp{WallTime: 15})
repl1 := roachpb.ReplicaDescriptor{NodeID: 1}
repl2 := roachpb.ReplicaDescriptor{NodeID: 2}
lease := kvserverpb.LeaseStatus{
Lease: roachpb.Lease{Replica: repl1},
State: kvserverpb.LeaseState_VALID,
}
testCases := []struct {
name string
txn *roachpb.Transaction
lease kvserverpb.LeaseStatus
expLimit hlc.Timestamp
}{
{
name: "no txn",
txn: nil,
lease: lease,
expLimit: hlc.Timestamp{},
},
{
name: "invalid lease",
txn: txn,
lease: func() kvserverpb.LeaseStatus {
leaseClone := lease
leaseClone.State = kvserverpb.LeaseState_EXPIRED
return leaseClone
}(),
expLimit: hlc.Timestamp{},
},
{
name: "no observed timestamp",
txn: txn,
lease: func() kvserverpb.LeaseStatus {
leaseClone := lease
leaseClone.Lease.Replica = repl2
return leaseClone
}(),
expLimit: hlc.Timestamp{},
},
{
name: "valid lease",
txn: txn,
lease: lease,
expLimit: hlc.Timestamp{WallTime: 15},
},
{
name: "valid lease with start time above observed timestamp",
txn: txn,
lease: func() kvserverpb.LeaseStatus {
leaseClone := lease
leaseClone.Lease.Start = hlc.ClockTimestamp{WallTime: 18}
return leaseClone
}(),
expLimit: hlc.Timestamp{WallTime: 18},
},
{
name: "valid lease with start time above max timestamp",
txn: txn,
lease: func() kvserverpb.LeaseStatus {
leaseClone := lease
leaseClone.Lease.Start = hlc.ClockTimestamp{WallTime: 22}
return leaseClone
}(),
expLimit: hlc.Timestamp{WallTime: 20},
},
}
for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
lul := ComputeLocalUncertaintyLimit(test.txn, test.lease)
require.Equal(t, test.expLimit, lul)
})
}
}
|
package main
import (
"crypto/rand"
"encoding/binary"
math_rand "math/rand"
)
func init() {
var b [8]byte
_, err := rand.Read(b[:])
if err != nil {
panic(err)
}
math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}
func randomString(l int) string {
bytes := make([]byte, l)
for i := 0; i < l; i++ {
bytes[i] = byte(randInt(65, 90))
}
return string(bytes)
}
func randInt(min int, max int) int {
return min + math_rand.Intn(max-min)
}
/*
func main() {
password := randomString(12)
fmt.Println(password)
}
*/
|
// ===================================== //
// author: gavingqf //
// == Please don'g change me by hand == //
//====================================== //
/*you have defined the following interface:
type IConfig interface {
// load interface
Load(path string) bool
// clear interface
Clear()
}
*/
package base
import (
"shared/utility/glog"
"strings"
)
type CfgYggdrasilSubTaskEnv struct {
Id int32
SubTaskId int32
SubTaskType int32
Target []string
Positions []string
Npc []int32
AddTaskItem []string
DeleteTaskItem []string
ClearPosGroup []string
CreateGroupObject []string
ChangeObjectState []int32
ChangeTerrainState string
TerrainStateDeleteAt int32
CreateDeleteAtGroupObj []string
DeleteAt int32
}
type CfgYggdrasilSubTaskEnvConfig struct {
data map[int32]*CfgYggdrasilSubTaskEnv
}
func NewCfgYggdrasilSubTaskEnvConfig() *CfgYggdrasilSubTaskEnvConfig {
return &CfgYggdrasilSubTaskEnvConfig{
data: make(map[int32]*CfgYggdrasilSubTaskEnv),
}
}
func (c *CfgYggdrasilSubTaskEnvConfig) Load(filePath string) bool {
parse := NewParser()
if err := parse.Load(filePath, true); err != nil {
glog.Info("Load", filePath, "err: ", err)
return false
}
// iterator all lines' content
for i := 2; i < parse.GetAllCount(); i++ {
data := new(CfgYggdrasilSubTaskEnv)
/* parse Id field */
vId, _ := parse.GetFieldByName(uint32(i), "id")
var IdRet bool
data.Id, IdRet = String2Int32(vId)
if !IdRet {
glog.Error("Parse CfgYggdrasilSubTaskEnv.Id field error,value:", vId)
return false
}
/* parse SubTaskId field */
vSubTaskId, _ := parse.GetFieldByName(uint32(i), "subTaskId")
var SubTaskIdRet bool
data.SubTaskId, SubTaskIdRet = String2Int32(vSubTaskId)
if !SubTaskIdRet {
glog.Error("Parse CfgYggdrasilSubTaskEnv.SubTaskId field error,value:", vSubTaskId)
return false
}
/* parse SubTaskType field */
vSubTaskType, _ := parse.GetFieldByName(uint32(i), "subTaskType")
var SubTaskTypeRet bool
data.SubTaskType, SubTaskTypeRet = String2Int32(vSubTaskType)
if !SubTaskTypeRet {
glog.Error("Parse CfgYggdrasilSubTaskEnv.SubTaskType field error,value:", vSubTaskType)
return false
}
/* parse Target field */
vecTarget, _ := parse.GetFieldByName(uint32(i), "target")
arrayTarget := strings.Split(vecTarget, ",")
for j := 0; j < len(arrayTarget); j++ {
v := arrayTarget[j]
data.Target = append(data.Target, v)
}
/* parse Positions field */
vecPositions, _ := parse.GetFieldByName(uint32(i), "positions")
arrayPositions := strings.Split(vecPositions, ",")
for j := 0; j < len(arrayPositions); j++ {
v := arrayPositions[j]
data.Positions = append(data.Positions, v)
}
/* parse Npc field */
vecNpc, _ := parse.GetFieldByName(uint32(i), "npc")
if vecNpc != "" {
arrayNpc := strings.Split(vecNpc, ",")
for j := 0; j < len(arrayNpc); j++ {
v, ret := String2Int32(arrayNpc[j])
if !ret {
glog.Error("Parse CfgYggdrasilSubTaskEnv.Npc field error, value:", arrayNpc[j])
return false
}
data.Npc = append(data.Npc, v)
}
}
/* parse AddTaskItem field */
vecAddTaskItem, _ := parse.GetFieldByName(uint32(i), "addTaskItem")
arrayAddTaskItem := strings.Split(vecAddTaskItem, ",")
for j := 0; j < len(arrayAddTaskItem); j++ {
v := arrayAddTaskItem[j]
data.AddTaskItem = append(data.AddTaskItem, v)
}
/* parse DeleteTaskItem field */
vecDeleteTaskItem, _ := parse.GetFieldByName(uint32(i), "deleteTaskItem")
arrayDeleteTaskItem := strings.Split(vecDeleteTaskItem, ",")
for j := 0; j < len(arrayDeleteTaskItem); j++ {
v := arrayDeleteTaskItem[j]
data.DeleteTaskItem = append(data.DeleteTaskItem, v)
}
/* parse ClearPosGroup field */
vecClearPosGroup, _ := parse.GetFieldByName(uint32(i), "clearPosGroup")
arrayClearPosGroup := strings.Split(vecClearPosGroup, ",")
for j := 0; j < len(arrayClearPosGroup); j++ {
v := arrayClearPosGroup[j]
data.ClearPosGroup = append(data.ClearPosGroup, v)
}
/* parse CreateGroupObject field */
vecCreateGroupObject, _ := parse.GetFieldByName(uint32(i), "createGroupObject")
arrayCreateGroupObject := strings.Split(vecCreateGroupObject, ",")
for j := 0; j < len(arrayCreateGroupObject); j++ {
v := arrayCreateGroupObject[j]
data.CreateGroupObject = append(data.CreateGroupObject, v)
}
/* parse ChangeObjectState field */
vecChangeObjectState, _ := parse.GetFieldByName(uint32(i), "changeObjectState")
if vecChangeObjectState != "" {
arrayChangeObjectState := strings.Split(vecChangeObjectState, ",")
for j := 0; j < len(arrayChangeObjectState); j++ {
v, ret := String2Int32(arrayChangeObjectState[j])
if !ret {
glog.Error("Parse CfgYggdrasilSubTaskEnv.ChangeObjectState field error, value:", arrayChangeObjectState[j])
return false
}
data.ChangeObjectState = append(data.ChangeObjectState, v)
}
}
/* parse ChangeTerrainState field */
data.ChangeTerrainState, _ = parse.GetFieldByName(uint32(i), "changeTerrainState")
/* parse TerrainStateDeleteAt field */
vTerrainStateDeleteAt, _ := parse.GetFieldByName(uint32(i), "terrainStateDeleteAt")
var TerrainStateDeleteAtRet bool
data.TerrainStateDeleteAt, TerrainStateDeleteAtRet = String2Int32(vTerrainStateDeleteAt)
if !TerrainStateDeleteAtRet {
glog.Error("Parse CfgYggdrasilSubTaskEnv.TerrainStateDeleteAt field error,value:", vTerrainStateDeleteAt)
return false
}
/* parse CreateDeleteAtGroupObj field */
vecCreateDeleteAtGroupObj, _ := parse.GetFieldByName(uint32(i), "createDeleteAtGroupObj")
arrayCreateDeleteAtGroupObj := strings.Split(vecCreateDeleteAtGroupObj, ",")
for j := 0; j < len(arrayCreateDeleteAtGroupObj); j++ {
v := arrayCreateDeleteAtGroupObj[j]
data.CreateDeleteAtGroupObj = append(data.CreateDeleteAtGroupObj, v)
}
/* parse DeleteAt field */
vDeleteAt, _ := parse.GetFieldByName(uint32(i), "deleteAt")
var DeleteAtRet bool
data.DeleteAt, DeleteAtRet = String2Int32(vDeleteAt)
if !DeleteAtRet {
glog.Error("Parse CfgYggdrasilSubTaskEnv.DeleteAt field error,value:", vDeleteAt)
return false
}
if _, ok := c.data[data.Id]; ok {
glog.Errorf("Find %d repeated", data.Id)
return false
}
c.data[data.Id] = data
}
return true
}
func (c *CfgYggdrasilSubTaskEnvConfig) Clear() {
}
func (c *CfgYggdrasilSubTaskEnvConfig) Find(id int32) (*CfgYggdrasilSubTaskEnv, bool) {
v, ok := c.data[id]
return v, ok
}
func (c *CfgYggdrasilSubTaskEnvConfig) GetAllData() map[int32]*CfgYggdrasilSubTaskEnv {
return c.data
}
func (c *CfgYggdrasilSubTaskEnvConfig) Traverse() {
for _, v := range c.data {
glog.Info(v.Id, ",", v.SubTaskId, ",", v.SubTaskType, ",", v.Target, ",", v.Positions, ",", v.Npc, ",", v.AddTaskItem, ",", v.DeleteTaskItem, ",", v.ClearPosGroup, ",", v.CreateGroupObject, ",", v.ChangeObjectState, ",", v.ChangeTerrainState, ",", v.TerrainStateDeleteAt, ",", v.CreateDeleteAtGroupObj, ",", v.DeleteAt)
}
}
|
package sml
import (
"fmt"
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
// The design of this lexer is based on "Lexical Scanning in Go" by Rob Pike
// https://talks.golang.org/2011/lex.slide
// token represents a tokenized text string that a lexer identified.
type token struct {
typ tokenType // token type
val string // tokenized text
line int // tokenized text's line number
col int // tokenized text's column number
}
type tokenType int
const (
tokenTypeEOF tokenType = iota // EOF
tokenTypeError // lexing error
tokenTypeComment // starting with '//', ending with newline or EOF
tokenTypeMessageEnd // '.'
// Message header
tokenTypeStreamFunction // 'S' [0-9]+ 'F' [0-9]+, case insensitive
tokenTypeWaitBit // 'W', '[W]', case insensitive
tokenTypeDirection // 'H->E', 'H<-E', 'H<->E', case insensitive
tokenTypeMessageName // Series of characters except whitespaces and comment delimiter
// Message text
tokenTypeLeftAngleBracket // '<'
tokenTypeRightAngleBracket // '>'
tokenTypeDataItemType // 'L', 'B', 'BOOLEAN', 'A', 'F4', 'F8', 'I1', 'I2', 'I4', 'I8', 'U1', 'U2', 'U4', 'U8', case insensitive
tokenTypeDataItemSize // '[' [0-9]+ ('..' [0-9]+)? ']'
tokenTypeNumber // decimal, hexadecimal, octal, binary, floating-point number including scientific notation, case insensitive
tokenTypeBool // 'T', 'F', case insensitive
tokenTypeVariable // [A-Za-z_] [A-Za-z0-9_]* ('[' [0-9]+ ']')?
tokenTypeQuotedString // string enclosed with double quotes, e.g. "quoted string"
tokenTypeEllipsis // '...'
)
// lexer represents the state of the lexical scanner.
type lexer struct {
input string // input string being lexed
lastState stateFn // last lexing state function
state stateFn // next lexing state function to enter
pos int // current position in the input
start int // start position of a token being lexed in input string
width int // width of last rune read from input
tokens chan token // the channel to report scanned tokens
}
const eof rune = -1
// lex creates a new scanner for the input string.
func lex(input string) *lexer {
l := &lexer{
input: input,
state: lexMessageHeader,
tokens: make(chan token, 2),
}
return l
}
// next returns the next rune in the input.
func (l *lexer) next() (r rune) {
if l.pos >= len(l.input) {
l.width = 0
return eof
}
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return r
}
// ignore skips over the pending input before this point.
func (l *lexer) ignore() {
l.start = l.pos
}
// backup steps back one rune. Can be called only once per call of next.
func (l *lexer) backup() {
l.pos -= l.width
}
// peek returns but does not consume the next rune in the input.
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
// emit passes a token to the client.
func (l *lexer) emit(t tokenType) {
line, col := l.lineColumn()
l.tokens <- token{typ: t, val: l.input[l.start:l.pos], line: line, col: col}
l.start = l.pos
}
// emitUppercase passes a token with a uppercase token value to the client.
func (l *lexer) emitUppercase(t tokenType) {
line, col := l.lineColumn()
l.tokens <- token{typ: t, val: strings.ToUpper(l.input[l.start:l.pos]), line: line, col: col}
l.start = l.pos
}
// emitSpaceRemoved passes a token to the client, with all spaces in token value removed.
func (l *lexer) emitSpaceRemoved(t tokenType) {
line, col := l.lineColumn()
val := make([]rune, 0, l.pos-l.start)
for _, r := range l.input[l.start:l.pos] {
if !unicode.IsSpace(r) {
val = append(val, r)
}
}
l.tokens <- token{typ: t, val: string(val), line: line, col: col}
l.start = l.pos
}
// emitEOF passes a EOF token to the client.
func (l *lexer) emitEOF() {
line, col := l.lineColumn()
l.tokens <- token{typ: tokenTypeEOF, val: "EOF", line: line, col: col}
l.start = l.pos
}
// accept consumes the next rune if it's from the valid set.
func (l *lexer) accept(valid string) bool {
if strings.ContainsRune(valid, l.next()) {
return true
}
l.backup()
return false
}
// acceptRun consumes a run of runes from the valid set.
func (l *lexer) acceptRun(valid string) {
for strings.ContainsRune(valid, l.next()) {
}
l.backup()
}
// lineColumn returns line and column number of current start position.
func (l *lexer) lineColumn() (line, column int) {
// Doing it this way means we don't have to worry about peek double counting
line = 1 + strings.Count(l.input[:l.start], "\n")
lineStart := 1 + strings.LastIndex(l.input[:l.start], "\n")
column = 1 + utf8.RuneCountInString(l.input[lineStart:l.start])
return line, column
}
// errorf returns an error token and terminates the running lexer.
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
line, col := l.lineColumn()
l.tokens <- token{tokenTypeError, fmt.Sprintf(format, args...), line, col}
return l.terminate()
}
// nextToken returns the next token from the input.
// If lexer.tokens channel is closed, it will return EOF token.
func (l *lexer) nextToken() token {
for {
select {
case tok, ok := <-l.tokens:
if !ok {
return token{typ: tokenTypeEOF}
}
return tok
default:
l.lastState, l.state = l.state, l.state(l)
}
}
// should not reach here
}
// stateFn represents the state of the lexer as a function that returns the next state
type stateFn func(*lexer) stateFn
// terminate closes the l.tokens channel and terminates the scan by
// passing back a nil pointer as the next state function.
func (l *lexer) terminate() stateFn {
close(l.tokens)
return nil
}
// lexMessageHeader scans the elements that can appear in the message header.
func lexMessageHeader(l *lexer) stateFn {
for {
// Handle a line comment
if strings.HasPrefix(l.input[l.pos:], "//") {
return lexComment
}
// Handle stream function code
re := regexp.MustCompile(`^[Ss]\d+[Ff]\d+`)
if loc := re.FindStringIndex(l.input[l.pos:]); loc != nil {
l.pos += loc[1]
l.emitUppercase(tokenTypeStreamFunction)
return lexMessageHeader
}
// Handle wait bit
re = regexp.MustCompile(`^([Ww]|\[[Ww]\])`)
if loc := re.FindStringIndex(l.input[l.pos:]); loc != nil {
l.pos += loc[1]
l.emitUppercase(tokenTypeWaitBit)
return lexMessageHeader
}
// Handle message direction
re = regexp.MustCompile(`^[Hh](->|<->|<-)[Ee]`)
if loc := re.FindStringIndex(l.input[l.pos:]); loc != nil {
l.pos += loc[1]
l.emitUppercase(tokenTypeDirection)
return lexMessageHeader
}
switch r := l.next(); r {
case eof:
return lexEOF
case ' ', '\t', '\r', '\n':
l.ignore()
case '.':
l.emit(tokenTypeMessageEnd)
return lexMessageHeader
case '<':
l.emit(tokenTypeLeftAngleBracket)
return lexMessageText
default:
for {
r := l.next()
if r == eof || unicode.IsSpace(r) || strings.HasPrefix(l.input[l.pos-1:], "//") {
l.backup()
break
}
}
l.emit(tokenTypeMessageName)
return lexMessageHeader
}
}
// should not reach here
}
// lexMessageText scans the elements inside the message text.
func lexMessageText(l *lexer) stateFn {
for {
// Handle a line comment
if strings.HasPrefix(l.input[l.pos:], "//") {
return lexComment
}
re := regexp.MustCompile(`^\.\.\.(\[\d+\])?`)
if loc := re.FindStringIndex(l.input[l.pos:]); loc != nil {
l.pos += loc[1]
l.emit(tokenTypeEllipsis)
return lexMessageText
}
// Handle data types or variables
re = regexp.MustCompile(`^[A-Za-z_]\w*`)
if loc := re.FindStringIndex(l.input[l.pos:]); loc != nil {
switch strings.ToUpper(l.input[l.pos : l.pos+loc[1]]) {
case "L", "A", "B", "BOOLEAN", "F4", "F8",
"I1", "I2", "I4", "I8", "U1", "U2", "U4", "U8":
l.pos += loc[1]
l.emitUppercase(tokenTypeDataItemType)
return lexMessageText
case "T", "F":
l.pos += loc[1]
l.emitUppercase(tokenTypeBool)
return lexMessageText
default:
l.pos += loc[1]
// Handle optional array-like notation
re = regexp.MustCompile(`^(\[\d+\])+`)
if loc = re.FindStringIndex(l.input[l.pos:]); loc != nil {
l.pos += loc[1]
}
l.emit(tokenTypeVariable)
return lexMessageText
}
}
r := l.next()
// Handle number
if r == '+' || r == '-' || isDigit(r) || (r == '.' && isDigit(l.peek())) {
l.backup()
return lexNumber
}
switch r {
case eof:
return lexEOF
case '<':
l.emit(tokenTypeLeftAngleBracket)
return lexMessageText
case '>':
l.emit(tokenTypeRightAngleBracket)
return lexMessageText
case '.':
l.emit(tokenTypeMessageEnd)
return lexMessageHeader
case '[':
l.backup()
return lexDataItemSize
case '"':
l.backup()
return lexQuotedString
case ' ', '\t', '\r', '\n':
l.ignore()
default:
return l.errorf("unexpected character in data item: %#U", r)
}
}
// should not reach here
}
// lexEOF scans a EOF which is known to be present, and terminates the running lexer.
func lexEOF(l *lexer) stateFn {
l.emitEOF()
return l.terminate()
}
// lexComment scans a line comment.
// The line comment delimiter "//" is known to be present.
// Returns the previous state function which called lexComment.
func lexComment(l *lexer) stateFn {
i := strings.Index(l.input[l.pos:], "\n")
if i < 0 {
l.pos = len(l.input)
l.emit(tokenTypeComment)
return lexEOF
}
for unicode.IsSpace(rune(l.input[l.pos+i-1])) {
i -= 1
}
l.pos += i
l.emit(tokenTypeComment)
return l.lastState
}
// lexDataItemSize scans a data item's size, e.g. [2] or [2..7].
// The left square bracket is known to be present.
func lexDataItemSize(l *lexer) stateFn {
numberFound := false
l.accept("[")
l.acceptRun(" \t\r\n")
if l.accept("0123456789") {
numberFound = true
l.acceptRun("0123456789")
l.acceptRun(" \t\r\n")
}
if strings.HasPrefix(l.input[l.pos:], "..") {
l.pos += 2
l.acceptRun(" \t\r\n")
if l.accept("0123456789") {
numberFound = true
l.acceptRun("0123456789")
l.acceptRun(" \t\r\n")
}
}
if !(l.accept("]") && numberFound) {
return l.errorf("invalid data item size")
}
l.emitSpaceRemoved(tokenTypeDataItemSize)
return lexMessageText
}
// lexQuotedString scans a string inside double quotes.
// The left double quote is known to be present.
func lexQuotedString(l *lexer) stateFn {
l.accept(`"`)
i := strings.Index(l.input[l.pos:], `"`)
j := strings.IndexAny(l.input[l.pos:], "\r\n")
if i < 0 || (j > 0 && j < i) {
return l.errorf("unclosed quoted string")
}
l.pos += i + 1 // Include the double quote
l.emit(tokenTypeQuotedString)
return lexMessageText
}
// lexNumber scans a number, which is known to be present.
func lexNumber(l *lexer) stateFn {
// Optional number sign
l.accept("+-")
// Handle decimal, hexadecimal, binary number
digits := "0123456789" // default is decimal
if l.accept("0") {
if l.accept("xX") {
digits = "0123456789abcdefABCDEF"
} else if l.accept("bB") {
digits = "01"
} else if l.accept("oO") {
digits = "01234567"
}
}
l.acceptRun(digits)
// Handle floating-point number
if l.accept(".") {
l.acceptRun(digits)
}
// Handle scientific notation
if l.accept("eE") {
l.accept("+-")
l.acceptRun("0123456789")
}
// Next thing must not be alphanumeric
if isAlphaNumeric(l.peek()) {
l.next()
return l.errorf("invalid number syntax: %q", l.input[l.start:l.pos])
}
l.emit(tokenTypeNumber)
return lexMessageText
}
// Helper functions
// isAlphaNumeric reports whether r is an alphabetic, digit, or underscore.
func isAlphaNumeric(r rune) bool {
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
}
// isDigit reports whether r is a digit.
func isDigit(r rune) bool {
return ('0' <= r && r <= '9')
}
|
package week2
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
type User struct {
Id string `json:"id"`
Name string `json:"name"`
}
func GetUser(db *gorm.DB, id string) (*User, error) {
var user = &User{}
err := db.Table("users").Where("id = ?", id).First(user).Error
return user, errors.Wrap(err, fmt.Sprintf("user(id:%s not found", id))
}
|
package main
import (
"io"
"os"
"reflect"
)
/*
go语言中每个变量都有唯一个静态类型。
interface的结构包含类型(type)和数据值(value):
无函数eface(interface{}):
type --> type类型对象
value --> data
有函数iface
type--> 静态类型 --> 静态类型
动态混合类型 --> 动态混合类型
方法集 --> 函数列表
value --> data
*/
//interface例子
func inter() {
/*
r --> type --> 静态类型--> io.Reader
--> 动态混合类型 --> nil
--> 方法集 --> Read函数
value --> nil
*/
var r io.Reader
file, _ := os.OpenFile("/path", os.O_RDWR, 0)
/*
r --> type --> 动态混合类型 --> *os.File
--> value --> file
*/
r = file
_= r
/*
empty --> type --> nil
--> value --> nil
*/
var empty interface{}
/*
empty --> type --> *os.File
--> value --> file
*/
empty = file
_ = empty
}
/*
reflect三大法则:
1接口数据(interface) ==> 反射对象
interface --> type <reflect.TypeOf> --> reflect.Type
--> value <reflect.ValueOf> --> reflect.Value
reflect.Value --> <.Type()> reflect.Type
2反射对象 ===> 接口数据
reflect.Value <Interface().(强制类型)> --> interface
3通过反射对象修改数据
反射对象需要传递的是指针
*/
func changeValueByreflect() {
var x float64 = 3.4
v := reflect.ValueOf(&x) //此处需要传递指针, 反射的是原数据类型的指针
e := v.Elem() //通过Elem获取当前数据的值类型
if e.CanSet() {
e.SetFloat(6.18)
}
}
|
package name
import (
"crypto/sha256"
"encoding/hex"
)
// KeyHash returns the first 12 hex characters of the hash of the first 100 chars
// of the input string
func KeyHash(s string) string {
if len(s) > 100 {
s = s[:100]
}
d := sha256.Sum256([]byte(s))
return hex.EncodeToString(d[:])[:12]
}
|
package pgygo
import (
"fmt"
"net/http"
"reflect"
)
/**
*
*/
type controllerInfo struct {
methods []int8 //HTTP方法
controllerType reflect.Type
name string //函数名称
typ reflect.Type //函数类型
pnames []string //函数参数名称列表
}
type routerRegistor struct {
routermap map[string]*controllerInfo
}
func (this *routerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Println("ok")
}
func (this *routerRegistor) Add(methods string, url string, c IController, funcName string, params ...string) {
}
func (this *routerRegistor) Call(url string, w http.ResponseWriter, r *http.Request) {
}
|
package models
// Direction 委托/持仓方向
type Direction int
const (
Buy Direction = iota // 做多
Sell // 做空
)
// OrderType 委托类型
type OrderType int
const (
OrderTypeMarket OrderType = iota // 市价单
OrderTypeLimit // 限价单
OrderTypeStopMarket // 市价止损单
OrderTypeStopLimit // 限价止损单
)
// OrderStatus 委托状态
type OrderStatus int
const (
OrderStatusCreated OrderStatus = iota // 创建委托
OrderStatusRejected // 委托被拒绝
OrderStatusNew // 委托待成交
OrderStatusPartiallyFilled // 委托部分成交
OrderStatusFilled // 委托完全成交
OrderStatusCancelled // 委托被取消
OrderStatusUntriggered // 等待触发条件委托单
OrderStatusTriggered // 已触发条件单
)
|
package kubeobjects
import "os"
const (
platformEnvName = "PLATFORM"
openshiftPlatformEnvValue = "openshift"
kubernetesPlatformEnvValue = "kubernetes"
)
type Platform int
const (
Kubernetes Platform = iota
Openshift
)
func ResolvePlatformFromEnv() Platform {
switch os.Getenv(platformEnvName) {
case openshiftPlatformEnvValue:
return Openshift
case kubernetesPlatformEnvValue:
fallthrough
default:
return Kubernetes
}
}
|
package routes
import (
"github.com/iris-contrib/middleware/cors"
"github.com/kataras/iris"
"gotest/controllers"
)
type UserRouter struct {
uparty iris.Party
}
func (u *UserRouter) SetUserRouter(app *iris.Application, path string) {
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
AllowCredentials: true,
AllowedMethods: []string{"PUT", "PATCH", "GET", "POST", "OPTIONS"},
AllowedHeaders: []string{"Origin", "Authorization"},
ExposedHeaders: []string{"Accept", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization"},
})
u.uparty= app.Party(path,crs).AllowMethods(iris.MethodOptions)
//路由分发,这里再次路由分发,将功能块再次细化
u.setLoginRoute()
u.setUserInfoRoute()
}
/*
* 登录模块
* @uri:/mcos/login
*/
func (u *UserRouter) setLoginRoute() {
// POST: http://localhost:8080/api/v1/login/
u.uparty.Post("/login", func(ctx iris.Context) {
hander_req_post := &controllers.UserController{
Ctx: ctx,
}
hander_req_post.PostLogin()
})
}
/*
* 用户信息处理模块路由
* 也是功能模块的入口(请求的控制器、服务处理和数据模型封装不在此说明)
* @uri:/mcos/userinfo
*/
func (u *UserRouter) setUserInfoRoute() {
// GET: http://localhost:8080/api/v1/userinfo/42
u.uparty.Get("/userinfo/{id:string}", func(ctx iris.Context) {
hander_req_get := &controllers.UserController{
Ctx: ctx,
}
hander_req_get.GetUserInfo()
})
// POST: http://localhost:8080/api/v1/userinfo/
u.uparty.Post("/userinfo", func(ctx iris.Context) {
hander_req_post := &controllers.UserController{
Ctx: ctx,
}
hander_req_post.PostUserInfo()
})
// PUT: http://localhost:8080/api/v1/userinfo/
u.uparty.Put("/userinfo/{id:int}", func(ctx iris.Context) {
hander_req_put := &controllers.UserController{
Ctx: ctx,
}
hander_req_put.PutUserInfo()
})
// DELETE: http://localhost:8080/api/v1/userinfo/42
u.uparty.Delete("/userinfo/{id:int}", func(ctx iris.Context) {
hander_req_del := &controllers.UserController{
Ctx: ctx,
}
hander_req_del.DeleteUser()
})
}
|
// Copyright 2017 Intel Corporation.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"github.com/intel-go/nff-go/flow"
"github.com/intel-go/nff-go/packet"
)
var (
load uint
loadRW uint
)
func main() {
flag.UintVar(&load, "load", 1000, "Use this for regulating 'load intensity', number of iterations")
flag.UintVar(&loadRW, "loadRW", 50, "Use this for regulating 'load read/write intensity', number of iterations")
outport1 := flag.Uint("outport1", 1, "port for 1st sender")
outport2 := flag.Uint("outport2", 1, "port for 2nd sender")
inport := flag.Uint("inport", 0, "port for receiver")
noscheduler := flag.Bool("no-scheduler", false, "disable scheduler")
dpdkLogLevel := flag.String("dpdk", "--log-level=0", "Passes an arbitrary argument to dpdk EAL")
cores := flag.String("cores", "0-43", "Cores mask. Avoid hyperthreading here")
flag.Parse()
// Initialize NFF-GO library
config := flow.Config{
DisableScheduler: *noscheduler,
DPDKArgs: []string{*dpdkLogLevel},
CPUList: *cores,
}
flow.CheckFatal(flow.SystemInit(&config))
// Receive packets from zero port. One queue per receive will be added automatically.
firstFlow, err := flow.SetReceiver(uint16(*inport))
flow.CheckFatal(err)
// Handle second flow via some heavy function
flow.CheckFatal(flow.SetHandler(firstFlow, heavyFunc, nil))
// Split for two senders and send
secondFlow, err := flow.SetPartitioner(firstFlow, 150, 150)
flow.CheckFatal(err)
flow.CheckFatal(flow.SetSender(firstFlow, uint16(*outport1)))
flow.CheckFatal(flow.SetSender(secondFlow, uint16(*outport2)))
flow.CheckFatal(flow.SystemStart())
}
func heavyFunc(currentPacket *packet.Packet, context flow.UserContext) {
currentPacket.ParseL3()
ipv4 := currentPacket.GetIPv4()
if ipv4 != nil {
T := ipv4.DstAddr
for j := uint32(0); j < uint32(load); j++ {
T += j
}
for i := uint32(0); i < uint32(loadRW); i++ {
ipv4.DstAddr = ipv4.SrcAddr + i
}
ipv4.SrcAddr = 263 + (T)
}
}
|
package models
type Conversation struct {
ID string `json:"_id,omitempty" bson:"_id,omitempty"`
IsGroupChat bool `json:"isGroupChat,omitempty" bson:"isGroupChat,omitempty"`
Parties []string `json:"parties,omitempty" bson:"parties,omitempty"`
Messages []_MessageObject `json:"messages,omitempty" bson:"messages,omitempty"`
}
type _MessageObject struct {
SenderId string `json:"sender_id,omitempty" bson:"sender_id,omitempty"`
Message string `json:"message,omitempty" bson:"message,omitempty"`
}
|
package fileserver
import (
"net/http"
)
// Serve the directory `dir` using HTTP on the specified TCP address.
//
// `dir`: filepath to serve.
// `address`: TCP address (`"<host>:<port>"`). The host can be omitted.
// `cache`: If false, the browser is sent headers to prevent it from caching
// content.
func ServeDir(dir, address string, cache bool) error {
fs := NewFileServer(http.Dir(dir), cache)
return http.ListenAndServe(address, fs)
}
type FileServer struct {
handler http.Handler
cache bool
}
func NewFileServer(dir http.FileSystem, cache bool) *FileServer {
return &FileServer{http.FileServer(dir), cache}
}
func (s *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !s.cache {
headers := w.Header()
headers.Set("Cache-Control", "no-cache, no-store, must-revalidate")
headers.Set("Pragma", "no-cache")
headers.Set("Expires", "0")
}
s.handler.ServeHTTP(w, r)
}
|
package helm
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"io"
"k8s.io/helm/pkg/chartutil"
"k8s.io/helm/pkg/manifest"
"k8s.io/helm/pkg/proto/hapi/chart"
"k8s.io/helm/pkg/renderutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
type Client struct {
}
func Some() {
c, err := GetHelmArchive("https://storage.googleapis.com/cellery-io/helm/cellery-runtime-0.1.0.tgz")
if err != nil {
log.Fatal(err)
}
str := `
mysql:
enabled: false
controller:
enabled: false
apim:
enabled: false
idp:
enabled: false
observability-portal:
enabled: false
sp-worker:
enabled: false
`
m, err := renderutil.Render(c, &chart.Config{Raw: str}, renderutil.Options{})
if err != nil {
log.Fatal(err)
}
manifests := manifest.SplitManifests(m)
for _, v := range manifests {
fmt.Println(v.Name)
fmt.Println(v.Content)
fmt.Println("---")
}
}
type Render struct {
Enabled bool `json:"enabled"`
}
type Config struct {
MySql Render `json:"mysql"`
Controller Render `json:"controller"`
ApiManager Render `json:"apim"`
Idp Render `json:"idp"`
ObservabilityPortal Render `json:"observability-portal"`
SpWorker Render `json:"sp-worker"`
}
func GenerateManifest(cfg Config) []manifest.Manifest {
b, err := json.Marshal(cfg)
if err != nil {
log.Fatal(err)
}
c, err := GetHelmArchive("https://storage.googleapis.com/cellery-io/helm/cellery-runtime-0.1.0.tgz")
if err != nil {
log.Fatal(err)
}
m, err := renderutil.Render(c, &chart.Config{Raw: string(b)}, renderutil.Options{})
if err != nil {
log.Fatal(err)
}
manifests := manifest.SplitManifests(m)
for _, v := range manifests {
fmt.Println(v.Name)
fmt.Println(v.Content)
fmt.Println("---")
}
return manifests
}
// Returns the Helm chart archive located at the given URI (can be either an http(s) address or a file path)
func GetHelmArchive(chartArchiveUri string) (*chart.Chart, error) {
// Download chart archive
chartFile, err := GetResource(chartArchiveUri)
if err != nil {
return nil, err
}
//noinspection GoUnhandledErrorResult
defer chartFile.Close()
// Check chart requirements to make sure all dependencies are present in /charts
helmChart, err := chartutil.LoadArchive(chartFile)
if err != nil {
return nil, errors.Wrapf(err, "loading chart archive")
}
return helmChart, err
}
func GetResource(uri string) (io.ReadCloser, error) {
var file io.ReadCloser
if strings.HasPrefix(uri, "http://") || strings.HasPrefix(uri, "https://") {
resp, err := http.Get(uri)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("http GET returned status %d", resp.StatusCode)
}
file = resp.Body
} else {
path, err := filepath.Abs(uri)
if err != nil {
return nil, errors.Wrapf(err, "getting absolute path for %v", uri)
}
f, err := os.Open(path)
if err != nil {
return nil, errors.Wrapf(err, "opening file %v", path)
}
file = f
}
// Write the body to file
return file, nil
}
|
package controller
import (
"log"
"os"
"fmt"
"gopkg.in/kataras/iris.v6"
"github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/scrypt"
"github.com/filipbekic01/go-web-framework/models"
)
func Register(ctx *iris.Context) {
db, err := gorm.Open("mysql", "root:filip@/goback?charset=utf8&parseTime=True&loc=Local")
if err != nil {
log.Panic(err.Error())
}
defer db.Close()
}
func Login(ctx *iris.Context) {
db, err := gorm.Open("mysql", "root:filip@/goback?charset=utf8&parseTime=True&loc=Local")
if err != nil {
log.Panic(err.Error())
}
defer db.Close()
// Get form data, encrypt password
username := ctx.FormValue("username")
passwordBytes, err := scrypt.Key([]byte(ctx.FormValue("password")), []byte(ctx.FormValue("username")), 16384, 8, 1, 32)
if err != nil {
log.Panic(err.Error())
}
password := fmt.Sprintf("%x", passwordBytes)
// Query database
var user models.User
db.Where("username=? AND password=?", username, password).First(&user)
if user.ID != 0 {
// Generate token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
"admin": false,
})
// Sign token
tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
if err != nil {
log.Panic(err.Error())
}
// Return token as JSON
ctx.JSON(iris.StatusOK, tokenString)
return
}
ctx.JSON(iris.StatusBadRequest, "Invalid credentials.")
} |
package webbot
import (
"log"
"sync"
"time"
"util"
)
type InfoCap struct {
X int
Y int
Version int
Lable string
id uint32
version uint32
group uint32
revision uint64
callback func() (string, error)
interval time.Duration
logger *log.Logger
debug bool
}
func (ic *InfoCap) Run(wg *sync.WaitGroup, msgChan chan []byte, done <-chan struct{}) {
defer wg.Done()
ic.execute(msgChan)
work := true
for work {
func() {
t := time.NewTimer(ic.interval)
defer t.Stop()
select {
case <-t.C:
ic.execute(msgChan)
case <-done:
work = false
return
}
}()
}
}
func (ic *InfoCap) execute(msgChan chan []byte) {
s, err := ic.callback()
if err != nil {
ic.logf("INFOCAP[%v:%v]: ERROR: %v\n", ic.id, ic.Lable, err.Error())
} else {
if buf, err := util.Encode32HeadBuf(ic.id, []byte(s)); err != nil {
ic.logf("INFOCAP[%v:%v]: ERROR: %v\n", ic.id, ic.Lable, err.Error())
} else {
msgChan <- buf
}
}
}
func (ic *InfoCap) logf(format string, v ...interface{}) {
if ic.debug && ic.logger != nil {
ic.logger.Printf(format, v...)
}
}
|
// Copyright (C) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pack_test
import (
"bytes"
"context"
"testing"
"github.com/golang/protobuf/proto"
"github.com/google/gapid/core/assert"
"github.com/google/gapid/core/data/pack"
"github.com/google/gapid/core/data/protoutil/testprotos"
"github.com/google/gapid/core/log"
)
type (
eventBeginGroup struct {
Msg proto.Message
ID *uint64
}
eventBeginChildGroup struct {
Msg proto.Message
ID *uint64
ParentID *uint64
}
eventEndGroup struct {
ParentID *uint64
}
eventObject struct {
Msg proto.Message
}
eventChildObject struct {
Msg proto.Message
ParentID *uint64
}
)
func (e eventBeginGroup) write(ctx context.Context, w *pack.Writer) {
id, err := w.BeginGroup(ctx, e.Msg)
if assert.For(ctx, "BeginGroup").ThatError(err).Succeeded() {
assert.For(ctx, "Set id").That(*e.ID).Equals(uint64(0)) // Isn't already set
*e.ID = id
}
}
func (e eventBeginChildGroup) write(ctx context.Context, w *pack.Writer) {
assert.For(ctx, "Get parent id").That(*e.ParentID).NotEquals(0) // Was set
id, err := w.BeginChildGroup(ctx, e.Msg, *e.ParentID)
if assert.For(ctx, "BeginChildGroup").ThatError(err).Succeeded() {
assert.For(ctx, "Set id").That(*e.ID).Equals(uint64(0)) // Isn't already set
*e.ID = id
}
}
func (e eventEndGroup) write(ctx context.Context, w *pack.Writer) {
assert.For(ctx, "Get parent id").That(*e.ParentID).NotEquals(0) // Was set
err := w.EndGroup(ctx, *e.ParentID)
assert.For(ctx, "EndGroup").ThatError(err).Succeeded()
}
func (e eventObject) write(ctx context.Context, w *pack.Writer) {
err := w.Object(ctx, e.Msg)
assert.For(ctx, "Object").ThatError(err).Succeeded()
}
func (e eventChildObject) write(ctx context.Context, w *pack.Writer) {
assert.For(ctx, "Get parent id").That(*e.ParentID).NotEquals(0) // Was set
err := w.ChildObject(ctx, e.Msg, *e.ParentID)
assert.For(ctx, "ChildObject").ThatError(err).Succeeded()
}
type event interface {
write(ctx context.Context, w *pack.Writer)
}
type events []event
func (e *events) add(ev event) { *e = append(*e, ev) }
func (e *events) BeginGroup(ctx context.Context, msg proto.Message, id uint64) error {
e.add(eventBeginGroup{msg, &id})
return nil
}
func (e *events) BeginChildGroup(ctx context.Context, msg proto.Message, id, parentID uint64) error {
e.add(eventBeginChildGroup{msg, &id, &parentID})
return nil
}
func (e *events) EndGroup(ctx context.Context, id uint64) error {
e.add(eventEndGroup{&id})
return nil
}
func (e *events) Object(ctx context.Context, msg proto.Message) error {
e.add(eventObject{msg})
return nil
}
func (e *events) ChildObject(ctx context.Context, msg proto.Message, parentID uint64) error {
e.add(eventChildObject{msg, &parentID})
return nil
}
func TestReaderWriter(t *testing.T) {
ctx := log.Testing(t)
buf := &bytes.Buffer{}
// Serialization Begin* methods return IDs for the written chunks.
// Store them here so that *Child* methods can read them.
var id0, id1, id2, id3 uint64
expected := events{
eventObject{&testprotos.MsgA{F32: 1, U32: 2, S32: 3, Str: "four"}},
eventObject{&testprotos.MsgB{F64: 2, U64: 3, S64: 4, Bool: false}},
eventObject{&testprotos.MsgA{F32: 3, U32: 4, S32: 5, Str: "six"}},
eventObject{&testprotos.MsgB{F64: 4, U64: 5, S64: 6, Bool: true}},
eventObject{&testprotos.MsgC{Entries: []*testprotos.MsgC_Entry{
&testprotos.MsgC_Entry{Value: 1},
}}},
eventBeginGroup{&testprotos.MsgA{F32: 5, U32: 6, S32: 10, Str: "eleven"}, &id0},
eventBeginGroup{&testprotos.MsgB{F64: 6, U64: 7, S64: 11, Bool: false}, &id1},
eventChildObject{&testprotos.MsgA{F32: 7, U32: 8, S32: 12, Str: "thirteen"}, &id0},
eventBeginChildGroup{&testprotos.MsgB{F64: 8, U64: 9, S64: 13, Bool: true}, &id2, &id0},
eventEndGroup{&id0},
eventBeginChildGroup{&testprotos.MsgA{F32: 9, U32: 10, S32: 11, Str: "twelve"}, &id3, &id1},
eventEndGroup{&id1},
}
w, err := pack.NewWriter(buf)
assert.For(ctx, "NewWriter").ThatError(err).Succeeded()
for _, e := range expected {
e.write(ctx, w)
}
got := events{}
err = pack.Read(ctx, bytes.NewBuffer(buf.Bytes()), &got, false)
assert.For(ctx, "Read").ThatError(err).Succeeded()
assert.For(ctx, "events").ThatSlice(got).DeepEquals(expected)
err = pack.Read(ctx, bytes.NewBuffer(buf.Bytes()), &got, true)
assert.For(ctx, "Read (force-dynamic)").ThatError(err).Succeeded()
}
|
package textio
import (
"bytes"
"fmt"
"testing"
)
func TestPrefixWriter(t *testing.T) {
b := &bytes.Buffer{}
b.WriteByte('\n')
w1 := NewPrefixWriter(b, "\t")
w2 := NewPrefixWriter(w1, "\t- ")
fmt.Fprint(w1, "hello:\n")
fmt.Fprint(w2, "value: 1")
fmt.Fprint(w2, "\n")
fmt.Fprint(w2, "value: 2\nvalue: 3\n")
w2.Flush()
w1.Flush()
const expected = `
hello:
- value: 1
- value: 2
- value: 3
`
found := b.String()
if expected != found {
t.Error("content mismatch")
t.Log("expected:", expected)
t.Log("found:", found)
}
}
|
package factorlib
import (
"github.com/randall77/factorlib/big"
"github.com/randall77/factorlib/linear"
"log"
"math/rand"
"runtime"
)
func init() {
factorizers["mpqs"] = mpqs
}
// mpqs = Multiple Polynomial Quadratic Sieve
//
// define f(x) = (ax+b)^2 - n
//
// f(x) = a^2x^2+2abx+b^2-n
// = a(ax^2+2bx+c) where c=(b^2-n)/a
//
// We choose a to be a product of primes in the factor base.
// We choose b such that b^2==n mod a so the division for computing c works.
//
// Then we sieve ax^2+2bx+c to find x such that ax^2+2bx+c factors over
// the factor base.
//
// We sieve around x0 = (sqrt(n)-b)/a, because that is where f(x) is small.
//
// How do we choose a? For larger a we can extract a larger known
// factor from f(x). But a larger a also mean f(x) grows faster as x
// diverges from x0. Pick a so that f(x0+m)/a is minimal when sieving
// [-m,m].
// f(x0+m)/a = (a^2(x0+m)^2 + 2ab(x0+m) + b^2-n)/a
// = a(x0+m)^2 + 2b(x0+m) + c
// = ax0^2+2ax0m+am^2+2bx0+2bm+c
// = ax0^2+2bx0+c + am^2+2ax0m+2bm
// = 0 + (am+2ax0+2b)m
// = (am + 2sqrt(n) - 2b + 2b) m
// = (am + 2sqrt(n)) m
// choose a <= 2sqrt(n)/m, after that f(x0+m)/a starts growing linearly with a.
func mpqs(n big.Int, rnd *rand.Rand) []big.Int {
// mpqs does not work for powers of a single prime. Check that first.
if f := primepower(n, rnd); f != nil {
return f
}
// Pick a factor base
fb, a := makeFactorBase(n)
if a != 0 {
return []big.Int{big.Int64(a), n.Div64(a)}
}
maxp := fb[len(fb)-1]
// Figure out maximum possible a we want.
amax := n.SqrtCeil().Lsh(2).Div64(sieverange)
// Point to stop adding more factors to a.
// It is ok if a is a bit small.
amin := amax.Div64(maxp)
// matrix is used to do gaussian elimination on mod 2 exponents.
m := linear.NewMatrix(uint(len(fb)))
// pair up large primes that we find using this table
type largerecord struct {
x big.Int
f []uint
}
largeprimes := map[int64]largerecord{}
// channels to communicate with workers
results := make(chan sieveResult, 100)
stop := make(chan struct{})
// spawn workers which find smooth relations
workers := runtime.NumCPU() // TODO: set up as a parameter somehow?
log.Printf("workers: %d\n", workers)
for i := 0; i < workers; i++ {
go mpqs_worker(n, amin, fb, results, stop, rnd.Int63())
}
// process results
for {
r := <- results
x := r.x
factors := r.factors
remainder := r.remainder
/*
fmt.Printf("%d*%d^2+%d*%d+%d=%d=", a, x, b, x, c, a.Mul(x).Add(b).Mul(x).Add(c))
for i, f := range factors {
if i != 0 {
fmt.Printf("·")
}
fmt.Printf("%d", fb[f])
}
if remainder != 1 {
fmt.Printf("·%d", remainder)
}
fmt.Println()
*/
if remainder != 1 {
// try to find another record with the same largeprime
lr, ok := largeprimes[remainder]
if !ok {
// haven't seen this large prime yet. Save record for later
largeprimes[remainder] = largerecord{x, factors}
continue
}
// combine current equation with other largeprime equation
// x1^2 === prod(f1) * largeprime
// x2^2 === prod(f2) * largeprime
//fmt.Printf(" largeprime %d match\n", remainder)
x = x.Mul(lr.x).Mod(n).Mul(big.Int64(remainder).ModInv(n)).Mod(n) // TODO: could remainder divide n?
factors = append(factors, lr.f...)
}
// Add equation to the matrix
idlist := m.AddRow(factors, eqn{x, factors})
if idlist == nil {
if m.Rows()%100 == 0 {
log.Printf("%d/%d falsepos=%d largeprimes=%d\n", m.Rows(), len(fb), falsepos, len(largeprimes))
falsepos = 0
}
continue
}
// We found a set of equations with all even powers.
// Compute a and b where a^2 === b^2 mod n
a := big.One
b := big.One
odd := make([]bool, len(fb))
for _, id := range idlist {
e := id.(eqn)
a = a.Mul(e.x).Mod(n)
for _, i := range e.f {
if !odd[i] {
// first occurrence of this factor
odd[i] = true
continue
}
// second occurrence of this factor
b = b.Mul64(fb[i]).Mod(n)
odd[i] = false
}
}
for _, o := range odd {
if o {
panic("gauss elim failed")
}
}
if a.Cmp(b) == 0 {
// trivial equation, ignore it
log.Println("triv A")
continue
}
if a.Add(b).Cmp(n) == 0 {
// trivial equation, ignore it
log.Println("triv B")
continue
}
f := a.Add(b).GCD(n)
res := []big.Int{f, n.Div(f)}
// shut down workers
close(stop)
// drain results, look for ack from workers
for k := 0; k < workers; {
r := <- results
if r.remainder == 0 {
// worker returned "I'm done" sentinel.
k++
}
}
return res
}
}
func mpqs_worker(n big.Int, amin big.Int, fb []int64, res chan sieveResult, stop chan struct{}, seed int64) {
rnd := rand.New(rand.NewSource(seed))
for {
select {
case <- stop:
res <- sieveResult{}
return
default:
}
// Pick an a. Use a random product of factor base primes
// that multiply to at least amin.
af := map[uint]uint{}
a := big.One
for a.Cmp(amin) < 0 {
f := uint(1 + rand.Intn(len(fb)-1))
af[f] += 1
a = a.Mul64(fb[f])
}
// Pick b = sqrt(n) mod a
var pp []primePower
for i, k := range af {
pp = append(pp, primePower{fb[i], k})
}
b := bigSqrtModN(n.Mod(a), pp, rnd)
// Set c = (b^2-n)/a
c := b.Square().Sub(n).Div(a)
// Find best point to sieve around
x0 := n.SqrtCeil().Sub(b).Div(a)
for _, r := range sievesmooth(a, b.Lsh(1), c, fb, x0.Sub64(sieverange/2), rnd) {
r.x = a.Mul(r.x).Add(b)
for f, k := range af {
for i := uint(0); i < k; i++ {
r.factors = append(r.factors, f)
}
}
select {
case res <- r:
case <- stop:
res <- sieveResult{}
return
}
}
}
}
|
package rest
import (
"encoding/json"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmwasm/wasmd/x/wasm/internal/keeper"
"github.com/cosmwasm/wasmd/x/wasm/internal/types"
"net/http"
"strconv"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/gorilla/mux"
)
func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) {
r.HandleFunc("/wasm/code/", listCodesHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/code/{codeID}", queryCodeHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/contract/", listAllContractsHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/contract/{contractAddr}", queryContractHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/contract/{contractAddr}/state", queryContractStateAllHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/contract/{contractAddr}/smart", queryContractStateSmartHandlerFn(cliCtx)).Methods("GET")
r.HandleFunc("/wasm/contract/{contractAddr}/raw", queryContractStateRawHandlerFn(cliCtx)).Methods("GET")
}
func listCodesHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, keeper.QueryListCode)
res, _, err := cliCtx.Query(route)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, string(res))
}
}
func queryCodeHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
codeID, err := strconv.ParseUint(mux.Vars(r)["codeId"], 10, 64)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
route := fmt.Sprintf("custom/%s/%s/%d", types.QuerierRoute, keeper.QueryGetCode, codeID)
res, _, err := cliCtx.Query(route)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
if len(res) == 0 {
rest.WriteErrorResponse(w, http.StatusInternalServerError, "contract not found")
return
}
var code keeper.GetCodeResponse
err = json.Unmarshal(res, &code)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
if len(code.Code) == 0 {
rest.WriteErrorResponse(w, http.StatusInternalServerError, "contract not found")
return
}
rest.PostProcessResponse(w, cliCtx, string(code.Code))
}
}
func listAllContractsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, keeper.QueryListContracts)
res, _, err := cliCtx.Query(route)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, string(res))
}
}
func queryContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["codeId"])
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContract, addr.String())
res, _, err := cliCtx.Query(route)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, string(res))
}
}
func queryContractStateAllHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"])
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateAll)
res, _, err := cliCtx.Query(route)
if err != nil {
rest.WriteErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
rest.PostProcessResponse(w, cliCtx, string(res))
}
}
func queryContractStateSmartHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
}
}
func queryContractStateRawHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
}
}
|
package area
import (
"fmt"
"net"
"sync"
"net/source/userapi"
"net/source/msg/msgproc"
"sync/atomic"
"net/source/proto/endpoint_poller"
)
type ServiceIOCenter struct {
}
var service ServiceIOCenter
func init() {
msgproc.GetAppTools().SvrIO = &service
}
func (s *ServiceIOCenter) ClearClient(c userapi.IClient) error {
Remove(c)
return nil
}
var poller = endpoint_poller.CreateEndPointPoll()
var allUsers sync.Map
func Put(c userapi.IClient) {
Id := c.GetId()
_, ok := allUsers.Load(Id)
if !ok {
allUsers.LoadOrStore(Id, c)
}
}
func Remove(c userapi.IClient) {
Id := c.GetId()
_, ok := allUsers.Load(Id)
if !ok {
allUsers.Delete(Id)
}
}
func (s *ServiceIOCenter) FindUser(cId int64) (userapi.IClient) {
v, ok := allUsers.Load(cId)
if ok {
return v.(userapi.IClient)
}
return nil
}
var totalConn int64
func addConn() {
atomic.AddInt64(&totalConn, 1)
if totalConn%1000 == 0 {
fmt.Println("totalConn: %d\n", totalConn)
}
}
func PollClient(cli userapi.IClient) {
poller.Poll(cli)
}
func AcceptorServer(ip string, basePort int, maxPorts int) {
//启动多个接待口
for i := 0; i < maxPorts; i++ {
go func(indx int) {
address := fmt.Sprintf("%s:%d", ip, basePort+indx)
//fmt.Printf("IP IS: %s \n",address)
pollListener, err := net.Listen("tcp", address)
if err != nil {
fmt.Errorf("Listen err: %s\n", err.Error())
return
}
fmt.Println("server listener:", address, " has started")
for {
clientConn, err := pollListener.Accept()
addConn()
if err != nil {
fmt.Println(err.Error())
continue
}
c := msgproc.GetAppTools().UserCreator.InitClient(clientConn, 1024) //recordClient 支持并发输入
go PollClient(c)
}
}(i)
}
}
|
package daemonset
import (
"fmt"
"github.com/Dynatrace/dynatrace-operator/src/controllers/dynakube/connectioninfo"
"github.com/Dynatrace/dynatrace-operator/src/version"
)
func (dsInfo *builderInfo) arguments() []string {
args := make([]string, 0)
args = dsInfo.appendHostInjectArgs(args)
args = dsInfo.appendProxyArg(args)
args = dsInfo.appendNetworkZoneArg(args)
args = appendOperatorVersionArg(args)
args = dsInfo.appendImmutableImageArgs(args)
return args
}
func (dsInfo *builderInfo) appendImmutableImageArgs(args []string) []string {
args = append(args, fmt.Sprintf("--set-tenant=$(%s)", connectioninfo.EnvDtTenant))
args = append(args, fmt.Sprintf("--set-server={$(%s)}", connectioninfo.EnvDtServer))
return args
}
func (dsInfo *builderInfo) appendHostInjectArgs(args []string) []string {
if dsInfo.hostInjectSpec != nil {
return append(args, dsInfo.hostInjectSpec.Args...)
}
return args
}
func appendOperatorVersionArg(args []string) []string {
return append(args, "--set-host-property=OperatorVersion="+version.Version)
}
func (dsInfo *builderInfo) appendNetworkZoneArg(args []string) []string {
if dsInfo.dynakube != nil && dsInfo.dynakube.Spec.NetworkZone != "" {
return append(args, fmt.Sprintf("--set-network-zone=%s", dsInfo.dynakube.Spec.NetworkZone))
}
return args
}
func (dsInfo *builderInfo) appendProxyArg(args []string) []string {
if dsInfo.dynakube != nil && dsInfo.dynakube.NeedsOneAgentProxy() {
return append(args, "--set-proxy=$(https_proxy)")
}
return args
}
func (dsInfo *builderInfo) hasProxy() bool {
return dsInfo.dynakube != nil && dsInfo.dynakube.Spec.Proxy != nil && (dsInfo.dynakube.Spec.Proxy.ValueFrom != "" || dsInfo.dynakube.Spec.Proxy.Value != "")
}
|
package main
import (
"log"
"net"
)
func dealClient(conn *net.Conn) {
client := &XClient{client:conn}
client.Login()
}
func main() {
listener, err := net.Listen("tcp", ":8888")
if err != nil {
}
log.Println("")
for {
client, err := listener.Accept()
if err != nil {
log.Println("Accept failed.", err.Error())
continue
}
dealClient(&client)
}
}
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
//
package utility
import (
"fmt"
"strings"
"github.com/mattermost/mattermost-cloud/model"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type velero struct {
cluster *model.Cluster
kubeconfigPath string
logger log.FieldLogger
actualVersion *model.HelmUtilityVersion
desiredVersion *model.HelmUtilityVersion
}
func newVeleroOrUnmanagedHandle(cluster *model.Cluster, kubeconfigPath string, logger log.FieldLogger) (Utility, error) {
desired := cluster.DesiredUtilityVersion(model.VeleroCanonicalName)
actual := cluster.ActualUtilityVersion(model.VeleroCanonicalName)
if model.UtilityIsUnmanaged(desired, actual) {
return newUnmanagedHandle(model.VeleroCanonicalName, logger), nil
}
velero := newVeleroHandle(desired, cluster, kubeconfigPath, logger)
err := velero.validate()
if err != nil {
return nil, errors.Wrap(err, "teleport utility config is invalid")
}
return velero, nil
}
func newVeleroHandle(desiredVersion *model.HelmUtilityVersion, cluster *model.Cluster, kubeconfigPath string, logger log.FieldLogger) *velero {
return &velero{
cluster: cluster,
kubeconfigPath: kubeconfigPath,
logger: logger.WithField("cluster-utility", model.VeleroCanonicalName),
desiredVersion: desiredVersion,
actualVersion: cluster.UtilityMetadata.ActualVersions.Velero,
}
}
func (v *velero) validate() error {
if v.kubeconfigPath == "" {
return errors.New("kubeconfig path cannot be empty")
}
return nil
}
func (v *velero) CreateOrUpgrade() error {
logger := v.logger.WithField("velero-action", "upgrade")
h := v.newHelmDeployment(logger)
err := h.Update()
if err != nil {
return err
}
err = v.updateVersion(h)
return err
}
func (v *velero) Name() string {
return model.VeleroCanonicalName
}
func (v *velero) Destroy() error {
helm := v.newHelmDeployment(v.logger)
return helm.Delete()
}
func (v *velero) Migrate() error {
return nil
}
func (v *velero) DesiredVersion() *model.HelmUtilityVersion {
return v.desiredVersion
}
func (v *velero) ActualVersion() *model.HelmUtilityVersion {
if v.actualVersion == nil {
return nil
}
return &model.HelmUtilityVersion{
Chart: strings.TrimPrefix(v.actualVersion.Version(), "velero-"),
ValuesPath: v.actualVersion.Values(),
}
}
func (v *velero) newHelmDeployment(logger log.FieldLogger) *helmDeployment {
helmValueArguments := fmt.Sprintf("configuration.backupStorageLocation.prefix=%s", v.cluster.ID)
return newHelmDeployment(
"vmware-tanzu/velero",
"velero",
"velero",
v.kubeconfigPath,
v.desiredVersion,
helmValueArguments,
logger,
)
}
func (v *velero) ValuesPath() string {
if v.desiredVersion == nil {
return ""
}
return v.desiredVersion.Values()
}
func (v *velero) updateVersion(h *helmDeployment) error {
actualVersion, err := h.Version()
if err != nil {
return err
}
v.actualVersion = actualVersion
return nil
}
|
package main
import (
"fmt"
"golang.org/x/tools/container/intsets"
"io/ioutil"
"log"
"strings"
)
type Units []rune
func loadFile(filename string) Units {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
trimmedLine := strings.TrimSpace(string(bytes))
return []rune(trimmedLine)
}
func singleReduce(units Units) Units {
// Rune difference between reactive units.
const diff = 32
if len(units) < 2 {
return units
}
for i := 1; i < len(units); i++ {
d := units[i] - units[i-1]
if d == diff || d == -diff {
var first, second Units
if i > 1 {
first = units[0 : i-1]
} else {
first = Units{}
}
if i < len(units)-1 {
second = units[i+1:]
} else {
second = Units{}
}
return append(first, second...)
}
}
return units
}
func part1(units Units) {
units = fullReduce(units)
fmt.Printf("%v : %v\n", len(units), string(units))
unitCount := map[rune]bool{}
for _, u := range units {
var c rune
if u >= 'a' {
c = u - 32
} else {
c = u
}
unitCount[c] = true
}
fmt.Printf("We got %v units left.\n", len(unitCount))
}
func fullReduce(units Units) Units {
previousLength := len(units)
for {
units = singleReduce(units)
if len(units) == previousLength {
break
}
previousLength = len(units)
}
return units
}
func part2(units Units) {
s := string(units)
stats := make([]int, 0)
for c := 'A'; c <= 'Z'; c++ {
s1 := strings.Replace(s, string(c), "", -1)
s2 := strings.Replace(s1, string(c+32), "", -1)
reduced := fullReduce(Units(s2))
stats = append(stats, len(reduced))
}
minIndex := 0
minValue := intsets.MaxInt
for i, v := range stats {
if v < minValue {
minIndex = i
minValue = v
}
}
fmt.Println("Part2:")
fmt.Printf("Min value = %v for %v\n", minValue, string(minIndex+'A'))
}
func main() {
units := loadFile("input.txt")
fmt.Println(len(units))
part1(units)
part2(units)
}
|
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package cuj contains fixtures, utils for cuj.
package cuj
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"chromiumos/tast/common/action"
"chromiumos/tast/errors"
"chromiumos/tast/local/apps"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/chrome/ash"
"chromiumos/tast/local/chrome/browser"
"chromiumos/tast/local/chrome/cuj/inputsimulations"
"chromiumos/tast/local/chrome/lacros"
"chromiumos/tast/local/chrome/uiauto"
"chromiumos/tast/local/chrome/uiauto/launcher"
"chromiumos/tast/local/chrome/uiauto/nodewith"
"chromiumos/tast/local/chrome/uiauto/pointer"
"chromiumos/tast/local/chrome/uiauto/role"
"chromiumos/tast/local/chrome/uiauto/touch"
"chromiumos/tast/local/input"
"chromiumos/tast/testing"
)
// CloseAllWindows closes all currently open windows by iterating over
// the shelf icons and calling apps.closeApp on each one.
func CloseAllWindows(ctx context.Context, tconn *chrome.TestConn) error {
shelfItems, err := ash.ShelfItems(ctx, tconn)
if err != nil {
return errors.Wrap(err, "failed to get shelf items")
}
for _, shelfItem := range shelfItems {
if shelfItem.Status != ash.ShelfItemClosed {
if err := apps.Close(ctx, tconn, shelfItem.AppID); err != nil {
return errors.Wrapf(err, "failed to close the app %v", shelfItem.AppID)
}
}
}
return nil
}
// GetBrowserStartTime opens chrome browser and returns the browser start time.
// If lfixtVal is given, it will open the lacros-Chrome, and return the lacros instance.
func GetBrowserStartTime(ctx context.Context, tconn *chrome.TestConn,
closeTabs, tabletMode bool, bt browser.Type) (*lacros.Lacros, time.Duration, error) {
var l *lacros.Lacros
chromeApp, err := apps.PrimaryBrowser(ctx, tconn)
if err != nil {
return nil, -1, errors.Wrap(err, "could not find the Chrome app")
}
// Make sure the browser hasn't been opened.
shown, err := ash.AppShown(ctx, tconn, chromeApp.ID)
if err != nil {
return nil, -1, errors.Wrap(err, "failed to check if the browser window is shown or not")
}
if shown {
// Close the browser if it is aready opened.
if err := apps.Close(ctx, tconn, chromeApp.ID); err != nil {
return nil, -1, errors.Wrap(err, "failed to close the opened browser")
}
}
msg := "shelf"
launchFunc := LaunchAppFromShelf
if tabletMode {
msg = "hotseat"
launchFunc = LaunchAppFromHotseat
}
testing.ContextLog(ctx, "Launch Google Chrome from "+msg)
var startTime time.Time
launchChromeApp := func(ctx context.Context) error {
startTime, err = launchFunc(ctx, tconn, "Chrome", "Chromium", "Lacros")
if err != nil {
return errors.Wrap(err, "failed to open Chrome")
}
// Make sure app is launched.
if err := ash.WaitForApp(ctx, tconn, chromeApp.ID, 30*time.Second); err != nil {
return errors.Wrap(err, "failed to wait for the app to be launched")
}
return nil
}
ui := uiauto.New(tconn)
if err := ui.Retry(3, launchChromeApp)(ctx); err != nil {
testing.ContextLog(ctx, "Failed to launch the Chrome app after 3 retries")
// Browser launch time is calculated from opening the extension launcher.
// Expect to take longer than starting straight from the shelf.
startTime = time.Now()
if err := launcher.LaunchApp(tconn, chromeApp.Name)(ctx); err != nil {
return nil, -1, errors.Wrap(err, "failed to launch the Chrome app from launcher")
}
// Make sure app is launched.
if err := ash.WaitForApp(ctx, tconn, chromeApp.ID, 30*time.Second); err != nil {
return nil, -1, errors.Wrap(err, "failed to wait for the app to be launched")
}
}
browserStartTime := time.Since(startTime)
// If it's ash-Chrome, we will close all existing tabs so the test case will start with a
// clean Chrome.
closeTabsFunc := browser.CloseAllTabs
bTconn := tconn
if bt == browser.TypeLacros {
// Connect to lacros-Chrome started from UI.
l, err = lacros.Connect(ctx, tconn)
if err != nil {
return nil, -1, errors.Wrap(err, "failed to get lacros instance")
}
bTconn, err = l.TestAPIConn(ctx)
if err != nil {
return nil, -1, errors.Wrap(err, "failed to create test API conn")
}
// For lacros-Chrome, we will close all existing tabs but leave a new tab to keep the Chrome
// process alive.
closeTabsFunc = browser.ReplaceAllTabsWithSingleNewTab
}
// Depending on the settings, Chrome might open all left-off pages automatically from last session.
// Close all existing tabs and test can open new pages in the browser.
if closeTabs {
if err := closeTabsFunc(ctx, bTconn); err != nil {
return nil, -1, errors.Wrap(err, "failed to close extra Chrome tabs")
}
}
return l, browserStartTime, nil
}
// CloseChrome closes Chrome browser application properly.
// If there exist unsave changes on web page, e.g. media content is playing or online document is editing,
// "leave site" prompt will prevent the tab from closing.
// This function confirms the "leave site" prompts so browser can be closed.
func CloseChrome(ctx context.Context, tconn *chrome.TestConn) error {
chromeApp, err := apps.PrimaryBrowser(ctx, tconn)
if err != nil {
return errors.Wrap(err, "could not find the Chrome app")
}
if err := apps.Close(ctx, tconn, chromeApp.ID); err != nil {
return errors.Wrap(err, "failed to close Chrome")
}
ui := uiauto.New(tconn)
leaveWin := nodewith.Name("Leave site?").Role(role.Window).First()
leaveBtn := nodewith.Name("Leave").Role(role.Button).Ancestor(leaveWin)
if err := ui.WithTimeout(time.Second).WaitUntilExists(leaveWin)(ctx); err != nil {
return nil
}
return ui.RetryUntil(ui.LeftClick(leaveBtn), ui.WithTimeout(time.Second).WaitUntilGone(leaveWin))(ctx)
}
// LaunchAppFromShelf opens an app by name which is currently pinned to the shelf.
// Which it is also support multiple names for a single app (e.g. "Chrome"||"Chromium" for Google Chrome, the browser).
// It returns the time when a mouse click event is injected to the app icon.
func LaunchAppFromShelf(ctx context.Context, tconn *chrome.TestConn, appName string, appOtherPossibleNames ...string) (time.Time, error) {
params := appIconFinder(appName, appOtherPossibleNames...)
ac := uiauto.New(tconn)
if err := ac.WithTimeout(10 * time.Second).WaitForLocation(params)(ctx); err != nil {
return time.Time{}, errors.Wrapf(err, "failed to find app %q", appName)
}
// Click mouse to launch app.
startTime := time.Now()
if err := ac.LeftClick(params)(ctx); err != nil {
return startTime, errors.Wrapf(err, "failed to launch app %q", appName)
}
return startTime, nil
}
// LaunchAppFromHotseat opens an app by name which is currently pinned to the hotseat.
// Which it is also support multiple names for a single app (e.g. "Chrome"||"Chromium" for Google Chrome, the browser).
// It returns the time when a touch event is injected to the app icon.
func LaunchAppFromHotseat(ctx context.Context, tconn *chrome.TestConn, appName string, appOtherPossibleNames ...string) (time.Time, error) {
var startTime time.Time
// Get touch controller for tablet.
tc, err := touch.New(ctx, tconn)
if err != nil {
return startTime, errors.Wrap(err, "failed to create the touch controller")
}
defer tc.Close()
tsew, tcc, err := touch.NewTouchscreenAndConverter(ctx, tconn)
if err != nil {
return startTime, errors.Wrap(err, "failed to access to the touch screen")
}
defer tsew.Close()
stw, err := tsew.NewSingleTouchWriter()
if err != nil {
return startTime, errors.Wrap(err, "failed to create a new single touch writer")
}
defer stw.Close()
// Make sure hotseat is shown.
if err := ash.SwipeUpHotseatAndWaitForCompletion(ctx, tconn, stw, tcc); err != nil {
return startTime, errors.Wrap(err, "failed to show hotseat")
}
params := appIconFinder(appName, appOtherPossibleNames...)
ac := uiauto.New(tconn)
if err := ac.WithTimeout(10 * time.Second).WaitForLocation(params)(ctx); err != nil {
return startTime, errors.Wrapf(err, "failed to find app %q", appName)
}
// Press button to launch app.
startTime = time.Now()
if err := tc.Tap(params)(ctx); err != nil {
return startTime, errors.Wrapf(err, "failed to tap %q", appName)
}
return startTime, nil
}
// appIconFinder returns the finder of app icon with input app name(s).
// It will only look for the icon locate on internal display.
func appIconFinder(appName string, appOtherPossibleNames ...string) *nodewith.Finder {
internalDisplay := nodewith.ClassName("RootWindow-0").Role(role.Window)
finder := nodewith.ClassName("ash/ShelfAppButton").Ancestor(internalDisplay)
if len(appOtherPossibleNames) == 0 {
return finder.Name(appName)
}
pattern := "(" + appName
for _, name := range appOtherPossibleNames {
pattern += "|"
pattern += regexp.QuoteMeta(name)
}
pattern += ")"
return finder.NameRegex(regexp.MustCompile(pattern))
}
// extendedDisplayWindowClassName obtains the class name of the root window on the extended display.
// If multiple display windows are present, the first one will be returned.
func extendedDisplayWindowClassName(ctx context.Context, tconn *chrome.TestConn) (string, error) {
ui := uiauto.New(tconn)
// Root window on extended display has the class name in RootWindow-<id> format.
// We found extended display window could be RootWindow-1, or RootWindow-2.
// Here we try 1 to 10.
for i := 1; i <= 10; i++ {
className := fmt.Sprintf("RootWindow-%d", i)
win := nodewith.ClassName(className).Role(role.Window)
if err := ui.Exists(win)(ctx); err == nil {
return className, nil
}
}
return "", errors.New("failed to find any window with class name RootWindow-1 to RootWindow-10")
}
// SwitchWindowToDisplay switches current window to expected display.
func SwitchWindowToDisplay(ctx context.Context, tconn *chrome.TestConn, kb *input.KeyboardEventWriter, externalDisplay bool) action.Action {
return func(ctx context.Context) error {
var expectedRootWindow *nodewith.Finder
var display string
ui := uiauto.New(tconn)
w, err := ash.FindWindow(ctx, tconn, func(w *ash.Window) bool {
return w.IsActive && w.IsFrameVisible
})
if err != nil {
return errors.Wrap(err, "failed to get current active window")
}
if externalDisplay {
display = "external display"
extendedWinClassName, err := extendedDisplayWindowClassName(ctx, tconn)
if err != nil {
return errors.Wrap(err, "failed to find root window on external display")
}
expectedRootWindow = nodewith.ClassName(extendedWinClassName).Role(role.Window)
} else {
display = "internal display"
// Root window on built-in display.
expectedRootWindow = nodewith.ClassName("RootWindow-0").Role(role.Window)
}
currentWindow := nodewith.NameContaining(w.Title).Role(role.Window)
expectedWindow := currentWindow.Ancestor(expectedRootWindow).First()
if err := ui.Exists(expectedWindow)(ctx); err != nil {
testing.ContextLog(ctx, "Expected window not found: ", err)
testing.ContextLogf(ctx, "Switch window %q to %s", w.Title, display)
return uiauto.Combine("switch window to "+display,
kb.AccelAction("Search+Alt+M"),
ui.WithTimeout(3*time.Second).WaitUntilExists(expectedWindow),
)(ctx)
}
return nil
}
}
// DismissMobilePrompt dismisses the prompt of "This app is designed for mobile".
func DismissMobilePrompt(ctx context.Context, tconn *chrome.TestConn) error {
ui := uiauto.New(tconn)
prompt := nodewith.Name("This app is designed for mobile").Role(role.Window)
if err := ui.WithTimeout(5 * time.Second).WaitUntilExists(prompt)(ctx); err == nil {
testing.ContextLog(ctx, "Dismiss the app prompt")
gotIt := nodewith.Name("Got it").Role(role.Button).Ancestor(prompt)
if err := ui.LeftClickUntil(gotIt, ui.WithTimeout(time.Second).WaitUntilGone(gotIt))(ctx); err != nil {
return errors.Wrap(err, "failed to click 'Got it' button")
}
}
return nil
}
// ExpandMenu returns a function that clicks the button and waits for the menu to expand to the given height.
// This function is useful when the target menu will expand to its full size with animation. On Low end DUTs
// the expansion animation might stuck for some time. The node might have returned a stable location if
// checking with a fixed interval before the animiation completes. This function ensures animation completes
// by checking the menu height.
func ExpandMenu(tconn *chrome.TestConn, button, menu *nodewith.Finder, height int) action.Action {
ui := uiauto.New(tconn)
startTime := time.Now()
return func(ctx context.Context) error {
if err := ui.DoDefault(button)(ctx); err != nil {
return errors.Wrap(err, "failed to click button")
}
return testing.Poll(ctx, func(ctx context.Context) error {
menuInfo, err := ui.Info(ctx, menu)
if err != nil {
return errors.Wrap(err, "failed to get menu info")
}
if menuInfo.Location.Height < height {
return errors.Errorf("got menu height %d, want %d", menuInfo.Location.Height, height)
}
// Examine this log regularly to see how fast the menu is expanded and determine if
// we still need to keep this ExpandMenu() function.
testing.ContextLog(ctx, "Menu expanded to full height in ", time.Now().Sub(startTime))
return nil
}, &testing.PollOptions{Timeout: time.Minute, Interval: time.Second})
}
}
// MaximizeBrowserWindow maximizes a specific browser window to show all the browser UI elements for precise clicking.
func MaximizeBrowserWindow(ctx context.Context, tconn *chrome.TestConn, tabletMode bool, title string) error {
if !tabletMode {
// Find the specific browser window.
window, err := ash.FindWindow(ctx, tconn, func(w *ash.Window) bool {
return (w.WindowType == ash.WindowTypeBrowser || w.WindowType == ash.WindowTypeLacros) && strings.Contains(w.Title, title)
})
if err != nil {
return errors.Wrapf(err, "failed to find the %q window", title)
}
if err := ash.SetWindowStateAndWait(ctx, tconn, window.ID, ash.WindowStateMaximized); err != nil {
// Just log the error and try to continue.
testing.ContextLogf(ctx, "Try to continue the test even though maximizing the %q window failed: %v", title, err)
}
}
return nil
}
// GenerateADF creates touch/mouse controller and generates ADF metrics.
func GenerateADF(ctx context.Context, tconn *chrome.TestConn, isTablet bool) error {
var err error
var pc pointer.Context
if isTablet {
if pc, err = pointer.NewTouch(ctx, tconn); err != nil {
return errors.Wrap(err, "failed to create a touch controller")
}
} else {
pc = pointer.NewMouse(tconn)
}
defer pc.Close()
if err = inputsimulations.DoAshWorkflows(ctx, tconn, pc); err != nil {
return errors.Wrap(err, "failed to do Ash workflows")
}
return nil
}
|
package network
import (
"encoding/json"
"fmt"
"log"
"math/rand"
)
/*
Track defines common functionality for all kinds of tracks
*/
type Track interface {
Location
A() *Junction
B() *Junction
id() string
oppositeEnd(*Junction) *Junction
}
/*
baseTrack is a base struct representing a bidirectional track from a to b.
Should be extended by concrete types.
*/
type baseTrack struct {
basePosition
a *Junction
b *Junction
_id string
}
func (track *baseTrack) A() *Junction {
return track.a
}
func (track *baseTrack) B() *Junction {
return track.b
}
func (track *baseTrack) oppositeEnd(of *Junction) *Junction {
if of == track.a {
return track.b
} else if of == track.b {
return track.a
}
log.Panicf("baseTrack.oppositeEnd: %d is not an end of %s (%d and %d are)",
of.ID, track.Name(), track.a.ID, track.b.ID)
return nil // not reachable due to log.Panicf, but tools complain
}
// func (track *baseTrack) Occupied() bool {
// return track.occupant != -1
// }
// Name - implements Position.Name
func (track *baseTrack) Name() string {
return track._id
}
func (track *baseTrack) id() string {
return track._id
}
func (track *baseTrack) neighbours() []Location {
return []Location{track.a, track.b}
}
func chooseTrack(tracks []Track) Track {
idx := rand.Intn(len(tracks))
return tracks[idx]
}
// WaitTrack is a Track with constant time of traversal, independent on the Vehicle's speed
type WaitTrack struct {
baseTrack
WaitTime float64
}
// e - implements Position.TravelTime
func (wt *WaitTrack) TravelTime(speed float64) float64 {
return wt.WaitTime
}
func (wt *WaitTrack) String() string {
return fmt.Sprintf("WaitTrack{id: %s, A: %d, B: %d, waitTime: %.2f}",
wt._id, wt.a.ID, wt.b.ID, wt.WaitTime)
}
// TransitTrack is a Track with time of traversal depending on it's length,``
// and Vehicle's speed, possibly limited by the track
type TransitTrack struct {
baseTrack
Length float64
MaxSpeed float64
}
// TravelTime - implements Position.TravelTime
func (tt *TransitTrack) TravelTime(speed float64) float64 {
return tt.Length / tt.MaxSpeed
}
func (tt *TransitTrack) String() string {
return fmt.Sprintf("TransitTrack{id: %s, A: %d, B: %d, length: %.2f, maxSpeed: %.2f}",
tt._id, tt.a.ID, tt.b.ID, tt.Length, tt.MaxSpeed)
}
func trackFromJSON(raw map[string]*json.RawMessage, junctions []*Junction, config *graphConfig) Track {
var kind string
var track Track
json.Unmarshal(*raw["type"], &kind)
switch kind {
case "transit":
track = transitTrackFromJSON(raw, junctions, config)
case "wait":
track = waitTrackFromJSON(raw, junctions, config)
default:
log.Panicln("Unknown track type: ", kind)
}
return track
}
func transitTrackFromJSON(raw map[string]*json.RawMessage, junctions []*Junction,
config *graphConfig) *TransitTrack {
var a int
var b int
var track TransitTrack
track.basePosition = basePosition{config, -1, make(chan request), make(chan request)}
json.Unmarshal(*raw["a"], &a)
json.Unmarshal(*raw["b"], &b)
json.Unmarshal(*raw["length"], &track.Length)
json.Unmarshal(*raw["maxSpeed"], &track.MaxSpeed)
json.Unmarshal(*raw["id"], &track._id)
track.a = junctions[a-1]
track.b = junctions[b-1]
return &track
}
func waitTrackFromJSON(raw map[string]*json.RawMessage, junctions []*Junction,
config *graphConfig) *WaitTrack {
var a int
var b int
var track WaitTrack
track.basePosition = basePosition{config, -1, make(chan request), make(chan request)}
json.Unmarshal(*raw["a"], &a)
json.Unmarshal(*raw["b"], &b)
json.Unmarshal(*raw["waitTime"], &track.WaitTime)
json.Unmarshal(*raw["id"], &track._id)
track.WaitTime /= 60 // minutes in json -> hours
track.a = junctions[a-1]
track.b = junctions[b-1]
return &track
}
|
package structure_test
import (
"fmt"
"github.com/payfazz/ditto/structure"
"github.com/payfazz/ditto/structure/field"
"testing"
)
func TestRequiredAttrsField(t *testing.T) {
c1, err := structure.CreateComponent("text")
if nil != err {
t.Fatal(err)
}
fmt.Println(c1.RequiredAttrs())
c2, err := structure.CreateComponent("file")
if nil != err {
t.Fatal(err)
}
fmt.Println(c2.RequiredAttrs())
c3, err := structure.CreateComponent("list")
if nil != err {
t.Fatal(err)
}
fmt.Println(c3.RequiredAttrs())
_, err = structure.CreateComponent("a")
if nil == err {
t.Fatal("error expected")
}
}
func TestExtractValidationField(t *testing.T) {
c1, err := structure.CreateComponent("text")
if nil != err {
t.Fatal(err)
}
attrs := map[string]interface{}{
"id": "test",
"description": "test",
"title": "test",
"type": "test",
"validations": []interface{}{
map[string]interface{}{
"type": "required",
"error_message": "",
},
},
}
err = c1.FillStruct(attrs)
if nil != err {
t.Fatal(err)
}
t.Logf("%+v", (c1.(*field.Text)).Validations)
}
|
package main
import (
"fmt"
)
func main(){
fmt.Print("mesa")
fmt.Print(" cadeira")
} |
package metrics_test
func (s *metrics) TestMemory() {
result, streamURL, err := s.metrics.Memory(nil)
if !s.NoError(err) {
return
}
s.Nil(streamURL)
if !s.NotNil(result) {
return
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.