text
stringlengths 11
4.05M
|
|---|
package parsing
import (
"fmt"
"strings"
"github.com/s2gatev/sqlmorph/ast"
)
// wrongTokenPanic causes a panic because of an unexpected token.
func wrongTokenPanic(message string, value string) {
if value != "" {
message += fmt.Sprintf(" Found %s.", value)
}
panic(message)
}
// parseField parses field extracting its name and target.
func parseField(literal string) *ast.Field {
field := &ast.Field{}
literalParts := strings.Split(literal, ".")
if len(literalParts) > 1 {
field.Target = literalParts[0]
field.Name = literalParts[1]
} else {
field.Name = literalParts[0]
}
return field
}
func isWhitespace(ch rune) bool {
return ch == ' ' || ch == '\t' || ch == '\n'
}
func isLetter(ch rune) bool {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
}
func isDigit(ch rune) bool {
return (ch >= '0' && ch <= '9')
}
func isSymbol(ch rune) bool {
return (ch == '_' || ch == '.')
}
|
// chaincode_insurance project main.go
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
type InsuranceChaincode struct {
}
type Policy struct {
PolicyNo string //保单号码
PolicyType string //险种
Startdate string //保险生效时间
Enddate string //保险失效时间
Status string //保单状态
PolicyHolder string //投保人
Assured string //被保险人
Beneficiary string //保险受益人
Premium string //保费
Amount string //保险金
}
func (insurance *InsuranceChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("---UserMsg---ChainCode has been initilazed!")
return nil, nil
}
func (insurance *InsuranceChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("---UserMsg---", "Function=", function)
fmt.Println("---UserMsg---", "args=", args)
var item Policy
item.PolicyNo = args[0]
if function == "Insert" {
return insurance.Insert(stub, args)
// } else if function == "Change" {
// return insurance.change(stub, args)
} else if function == "Delete" {
return insurance.Delete(stub, args)
}
return nil, errors.New("Incorrect function! They may be one of Insert,Delete,Change.")
}
func (insurance *InsuranceChaincode) Insert(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var item Policy
item.PolicyNo = args[0]
if len(args) != 10 {
return nil, errors.New("Incorrect number of arguments. Deposit function expecting 10")
}
//解析参数
item.PolicyType = args[1]
item.Startdate = args[2]
item.Enddate = args[3]
item.Status = args[4]
item.PolicyHolder = args[5]
item.Assured = args[6]
item.Beneficiary = args[7]
item.Premium = args[8]
item.Amount = args[9]
detailbytes, err := stub.GetState(item.PolicyNo)
//保单号重复CHECK
if detailbytes != nil {
errmsg := "The Policy No is duplicate."
fmt.Println(errmsg)
return nil, errors.New(errmsg)
}
if detailbytes == nil && err == nil {
//添加check处理等功能
//将结构体(保单信息)转化成json数据,然后保存到账本中
p, err := json.Marshal(item)
err = stub.PutState(item.PolicyNo, p)
// Write the state to the ledger
//err = stub.PutState(args[0], []byte(args))
if err != nil {
return nil, err
}
}
return nil, nil
}
// Deletes an entity from state
func (insurance *InsuranceChaincode) Delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
PolicyNo := args[0]
// Delete the key from the state in ledger
err := stub.DelState(PolicyNo)
if err != nil {
return nil, errors.New("Failed to delete state")
}
return nil, nil
}
// Query callback representing the query of a chaincode
func (insurance *InsuranceChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("query is running " + function)
// Handle different functions
if function == "read" { //read a variable
return insurance.read(stub, args)
}
fmt.Println("query did not find func: " + function)
return nil, errors.New("Received unknown function query: " + function)
}
func (insurance *InsuranceChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var PolicyNo string // Entities
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting name of the person to query")
}
PolicyNo = args[0]
// Get the state from the ledger
policybytes, err := stub.GetState(PolicyNo)
if err != nil {
jsonResp := "{\"Error\":\"Failed to get state for " + PolicyNo + "\"}"
return nil, errors.New(jsonResp)
}
if policybytes == nil {
jsonResp := "{\"Result\":\"Nil policy for " + PolicyNo + "\"}"
fmt.Printf("Query Response:%s\n", jsonResp)
return nil, nil
} else {
jsonResp := "{\"PolicyNo\":\"" + PolicyNo + "\",\"Detail\":\"" + string(policybytes) + "\"}"
fmt.Printf("Query Response:%s\n", jsonResp)
return policybytes, nil
}
}
func main() {
err := shim.Start(new(InsuranceChaincode))
if err != nil {
fmt.Printf("Error starting insurance chaincode: %s", err)
}
}
|
package escrow
import (
"context"
"encoding/json"
"errors"
"math"
"time"
cosmosTypes "github.com/cosmos/cosmos-sdk/types"
"github.com/gookit/gcli/v3"
"github.com/ovrclk/akash/x/deployment/client/cli"
deploymentTypes "github.com/ovrclk/akash/x/deployment/types"
marketTypes "github.com/ovrclk/akash/x/market/types"
"github.com/ovrclk/akcmd/client"
"github.com/ovrclk/akcmd/flags"
"gopkg.in/yaml.v2"
)
func QueryCmd() *gcli.Command {
cmd := &gcli.Command{
Name: "escrow",
Desc: "Escrow query commands",
Func: func(cmd *gcli.Command, args []string) error {
cmd.ShowHelp()
return nil
},
Subs: []*gcli.Command{blocksRemainingCMD()},
}
return cmd
}
// Define 6.5 seconds as average block-time
const secondsPerBlock = 6.5
var errNoLeaseMatches = errors.New("leases for deployment do not exist")
func blocksRemainingCMD() *gcli.Command {
cmd := &gcli.Command{
Name: "blocks-remaining",
Desc: "Compute the number of blocks remaining for an escrow account",
Config: func(cmd *gcli.Command) {
flags.AddQueryFlagsToCmd(cmd)
flags.AddDeploymentIDFlags(cmd)
flags.MarkReqDeploymentIDFlags(cmd)
},
Func: func(cmd *gcli.Command, args []string) error {
clientCtx, err := client.GetClientQueryContext()
if err != nil {
return err
}
marketClient := marketTypes.NewQueryClient(clientCtx)
ctx := context.Background()
id, err := flags.DeploymentIDFromFlags()
if err != nil {
return err
}
// Fetch leases matching owner & dseq
leaseRequest := marketTypes.QueryLeasesRequest{
Filters: marketTypes.LeaseFilters{
Owner: id.Owner,
DSeq: id.DSeq,
GSeq: 0,
OSeq: 0,
Provider: "",
State: "active",
},
Pagination: nil,
}
leasesResponse, err := marketClient.Leases(ctx, &leaseRequest)
if err != nil {
return err
}
leases := make([]marketTypes.Lease, 0)
for _, lease := range leasesResponse.Leases {
leases = append(leases, lease.Lease)
}
// Fetch the balance of the escrow account
deploymentClient := deploymentTypes.NewQueryClient(clientCtx)
totalLeaseAmount := cosmosTypes.NewInt(0)
blockchainHeight, err := cli.CurrentBlockHeight(clientCtx)
if err != nil {
return err
}
if 0 == len(leases) {
return errNoLeaseMatches
}
for _, lease := range leases {
amount := lease.Price.Amount
totalLeaseAmount = totalLeaseAmount.Add(amount)
}
res, err := deploymentClient.Deployment(ctx, &deploymentTypes.QueryDeploymentRequest{
ID: deploymentTypes.DeploymentID{Owner: id.Owner, DSeq: id.DSeq},
})
if err != nil {
return err
}
balance := res.EscrowAccount.TotalBalance().Amount
settledAt := res.EscrowAccount.SettledAt
balanceRemain := float64(balance.Int64() - ((int64(blockchainHeight) - settledAt) * (totalLeaseAmount.Int64())))
blocksRemain := (balanceRemain / float64(totalLeaseAmount.Int64()))
output := struct {
BalanceRemain float64 `json:"balance_remaining" yaml:"balance_remaining"`
BlocksRemain float64 `json:"blocks_remaining" yaml:"blocks_remaining"`
EstimatedTimeRemain string `json:"estimated_time_remaining" yaml:"estimated_time_remaining"`
}{
BalanceRemain: balanceRemain,
BlocksRemain: blocksRemain,
EstimatedTimeRemain: (time.Duration(math.Floor(secondsPerBlock*blocksRemain)) * time.Second).String(),
}
outputType := flags.PersistentFlagsFromCmd().Output
var data []byte
if outputType == "json" {
data, err = json.MarshalIndent(output, " ", "\t")
} else {
data, err = yaml.Marshal(output)
}
if err != nil {
return err
}
return clientCtx.PrintBytes(data)
},
}
return cmd
}
|
package main
import (
"fmt"
)
func Handler(x int, y int) int {
return x * (2 + y)
}
func main() {
fmt.Print("input x: ")
var x int
fmt.Scanf("%d", &x)
fmt.Print("input y: ")
var y int
fmt.Scanf("%d", &y)
result := Handler(x, y)
fmt.Println(fmt.Sprintf("result: %d", result))
}
|
package app
import (
"net/http"
"encoding/json"
"strconv"
"portal/util"
"portal/model"
"portal/service"
"github.com/gin-gonic/gin"
)
// Create app
func CreateApp(c *gin.Context) {
type App struct {
Name string `json:"name,omitempty"`
}
var jsonBody App
err := c.BindJSON(&jsonBody)
if err != nil {
util.RespondBadRequest(c)
return
}
code, msg, uuid := service.CreateApp(jsonBody.Name)
c.JSON(http.StatusOK, gin.H{
"code": code,
"error": gin.H{
"msg": msg,
},
"uuid": uuid,
})
}
// Get List
func GetAppList(c *gin.Context) {
var (
queryJson *model.GlobalQueryBody
code int = 0
)
// json string 转为 struct
if err := json.Unmarshal([]byte(c.Query("query")), &queryJson); err != nil {
util.RespondBadRequest(c)
return
}
// check time range
where := queryJson.Where
if util.CompareDate(where.CreatedAt.Gt, where.CreatedAt.Lt) ||
util.CompareDate(where.UpdatedAt.Gt, where.UpdatedAt.Lt) {
util.RespondBadRequest(c)
return
}
res, msg := service.GetAppList(queryJson)
if msg != nil {
code = 1
}
c.JSON(http.StatusOK, gin.H{
"code": code,
"error": gin.H{
"msg": msg.Error(),
},
"data": res,
"total": len(res),
})
}
// Update app
func UpdateApp(c *gin.Context) {
type body struct {
Name string `json:"name,omitempty"`
}
var jsonBody body
if err := c.BindJSON(&jsonBody); err != nil {
util.RespondBadRequest(c)
return
}
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
util.RespondBadRequest(c)
return
}
code, msg := service.UpateApp(id, jsonBody.Name)
c.JSON(http.StatusOK, gin.H{
"code": code,
"error": gin.H{
"msg": msg.Error(),
},
})
}
|
package error
import "fmt"
// DataConflictError indicates conflicting data for a resource
type DataConflictError struct {
Resource string
Field string
}
func (dce *DataConflictError) Error() string {
return fmt.Sprintf("Conflicting data for %s field in %s resource", dce.Field, dce.Resource)
}
|
/**
* @Author: 人从众[ckhero]
* @Date: 2020/8/26 6:56 下午
* @Desc: a
*/
package go_way
type Ints []int
func(i Ints) Iterator() <-chan int {
c := make(chan int)
go func() {
for _, v := range i {
c <- v
}
close(c)
}()
return c
}
|
package goSolution
func beautifulArray(n int) []int {
if n == 1 {
return []int{1}
}
left := beautifulArray((n + 1) >> 1)
right := beautifulArray(n >> 1)
for i, v := range left {
left[i] = (v << 1) - 1
}
for i, v := range right {
right[i] = v << 1
}
return append(left, right...)
}
|
package goutils
import (
"encoding/json"
"fmt"
"os"
)
// SaveJSON saves the given data to json
func SaveJSON(data interface{}, outputname string) {
file, err := os.Create(outputname)
defer file.Close()
if err != nil {
fmt.Println(err)
return
}
err = json.NewEncoder(file).Encode(data)
if err != nil {
fmt.Println(err)
return
}
}
|
// This file exposes volume plugin related contracts.
// Hence, any specific volume plugin implementor will
// implement the logic that aligns to the contracts
// exposed here.
// Some of the plugin based interfaces delegate to
// volume based interfaces to do the actual work.
package volume
import (
"fmt"
"io"
"os"
"sync"
"github.com/golang/glog"
//"github.com/openebs/mayaserver/lib/api/v1"
"github.com/openebs/mayaserver/lib/orchprovider"
)
// VolumeFactory is a function that returns a volume.VolumeInterface.
// The config parameter provides an io.Reader handler to the factory in
// order to load specific configurations. If no configuration is provided
// the parameter is nil.
type VolumeFactory func(config io.Reader, aspect VolumePluginAspect) (VolumeInterface, error)
// VolumePluginAspect is an interface that provides a blueprint for plugins
// to cater to the needs when a plugin requires the help of a third party
// resource (library, provider, etc) to materialize a requirement.
type VolumePluginAspect interface {
// Get the suitable orchestration provider.
// A volume plugin may be linked with its provider e.g.
// an orchestration provider like K8s, Nomad, Mesos, etc.
//
// Note:
// OpenEBS believes in running storage software in containers & hence
// above container specific orchestrators.
GetOrchProvider() (orchprovider.OrchestratorInterface, error)
}
// All registered volume plugins.
var (
volumePluginsMutex sync.Mutex
// A mapped instance of volume plugin name with the plugin's
// initializer
volumePlugins = make(map[string]VolumeFactory)
)
// VolumePluginConfig is how volume plugins receive configuration. An instance
// specific to the plugin will be passed to the plugin's
// ProbeVolumePlugins(config) func. Reasonable defaults will be provided by
// the binary hosting the plugins while allowing override of those default
// values. Those config values are then set to an instance of
// VolumePluginConfig and passed to the plugin.
//
// Values in VolumeConfig are intended to be relevant to several plugins, but
// not necessarily all plugins. The preference is to leverage strong typing
// in this struct. All config items must have a descriptive but non-specific
// name (i.e, RecyclerMinimumTimeout is OK but RecyclerMinimumTimeoutForNFS is
// !OK). An instance of config will be given directly to the plugin, so
// config names specific to plugins are unneeded and wrongly expose plugins in
// this VolumeConfig struct.
//
// OtherAttributes is a map of string values intended for one-off
// configuration of a plugin or config that is only relevant to a single
// plugin. All values are passed by string and require interpretation by the
// plugin. Passing config as strings is the least desirable option but can be
// used for truly one-off configuration. The binary should still use strong
// typing for this value when binding CLI values before they are passed as
// strings in OtherAttributes.
type VolumePluginConfig struct {
// OtherAttributes stores config as strings. These strings are opaque to
// the system and only understood by the binary hosting the plugin and the
// plugin itself.
OtherAttributes map[string]string
}
// RegisterVolumePlugin registers a volume.VolumePlugin by name.
// This is just a registry entry. The actual initialization is done
// elsewhere with passing of dynamic parameters i.e.
//
// 1. volume plugin config file and
// 2. volume aspect instance
//
// NOTE:
// Each implementation of volume plugin need to call
// RegisterVolumePlugin inside their init() function.
//func RegisterVolumePlugin(name string, factory VolumePluginFactory) {
func RegisterVolumePlugin(name string, factory VolumeFactory) {
volumePluginsMutex.Lock()
defer volumePluginsMutex.Unlock()
if _, found := volumePlugins[name]; found {
glog.Fatalf("Volume plugin %q was registered twice", name)
}
glog.V(1).Infof("Registered volume plugin %q", name)
volumePlugins[name] = factory
}
// IsVolumePlugin returns true if name corresponds to an already
// registered volume plugin.
func IsVolumePlugin(name string) bool {
volumePluginsMutex.Lock()
defer volumePluginsMutex.Unlock()
_, found := volumePlugins[name]
return found
}
// VolumePlugins returns the name of all registered volume
// plugins in a string slice
func VolumePlugins() []string {
names := []string{}
volumePluginsMutex.Lock()
defer volumePluginsMutex.Unlock()
for name := range volumePlugins {
names = append(names, name)
}
return names
}
// GetVolumePlugin creates an instance of the named volume plugin,
// or nil if the name is unknown. The error return is only used if the named
// volume plugin was known but failed to initialize. The config parameter specifies
// the io.Reader handler of the configuration file for the volume
// plugin, or nil for no configuation.
//func GetVolumePlugin(name string, config io.Reader, aspect VolumePluginAspect) (VolumePlugin, error) {
func GetVolumePlugin(name string, config io.Reader, aspect VolumePluginAspect) (VolumeInterface, error) {
volumePluginsMutex.Lock()
defer volumePluginsMutex.Unlock()
factory, found := volumePlugins[name]
if !found {
return nil, nil
}
return factory(config, aspect)
}
// TODO
// Who calls this ?
// This will currently be triggered while starting the binary as a http service ?
//
// InitVolumePlugin creates an instance of the named volume plugin.
func InitVolumePlugin(name string, configFilePath string, aspect VolumePluginAspect) (VolumeInterface, error) {
//var orchestrator Interface
var volumeInterface VolumeInterface
var err error
if name == "" {
glog.Info("No volume plugin specified.")
return nil, nil
}
if configFilePath != "" {
var config *os.File
config, err = os.Open(configFilePath)
if err != nil {
glog.Fatalf("Couldn't open volume plugin configuration %s: %#v",
configFilePath, err)
}
defer config.Close()
volumeInterface, err = GetVolumePlugin(name, config, aspect)
} else {
// Pass explicit nil so plugins can actually check for nil. See
// "Why is my nil error value not equal to nil?" in golang.org/doc/faq.
volumeInterface, err = GetVolumePlugin(name, nil, aspect)
}
if err != nil {
return nil, fmt.Errorf("could not init volume plugin %q: %v", name, err)
}
if volumeInterface == nil {
return nil, fmt.Errorf("unknown volume plugin %q", name)
}
return volumeInterface, nil
}
|
package log
import (
"github.com/sirupsen/logrus"
"io"
"reflect"
"time"
)
var (
// global state for convenient way to switch all services together
loggerLevel = TraceLevel
logger = logrus.New()
)
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel logrus.Level = iota
// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel
// TraceLevel level. Designates finer-grained informational events than the Debug.
TraceLevel
)
func init() {
logger.SetLevel(loggerLevel)
// hooks
traceHook := new(TraceHook)
logger.AddHook(traceHook)
}
type TraceHook struct {
}
type Fields map[string]interface{}
func (hook *TraceHook) Fire(entry *logrus.Entry) error {
if val, ok := entry.Data["trace_hook_stack"]; ok {
v := reflect.ValueOf(val)
str := ""
if v.Kind() == reflect.Slice {
for i := 0; i < v.Len(); i++ {
str = str + v.Index(i).Interface().(string)
if i < v.Len()-1 {
str = str + "->"
}
}
}
entry.Data["trace"] = str
delete(entry.Data, "trace_hook_stack")
}
return nil
}
func (hook *TraceHook) Levels() []logrus.Level {
return []logrus.Level{
TraceLevel,
DebugLevel,
InfoLevel,
WarnLevel,
ErrorLevel,
FatalLevel,
PanicLevel,
}
}
// SetOutput sets the standard logger output.
func SetOutput(out io.Writer) {
logger.SetOutput(out)
}
// SetFormatter sets the standard logger formatter.
func SetFormatter(formatter logrus.Formatter) {
logger.SetFormatter(formatter)
}
// SetReportCaller sets whether the standard logger will include the calling
// method as a field.
func SetReportCaller(include bool) {
logger.SetReportCaller(include)
}
// SetLevel sets the standard logger level.
func SetLevel(level logrus.Level) {
logger.SetLevel(level)
}
// GetLevel returns the standard logger level.
func GetLevel() logrus.Level {
return logger.GetLevel()
}
// IsLevelEnabled checks if the log level of the standard logger is greater than the level param
func IsLevelEnabled(level logrus.Level) bool {
return logger.IsLevelEnabled(level)
}
// AddHook adds a hook to the standard logger hooks.
func AddHook(hook logrus.Hook) {
logger.AddHook(hook)
}
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
func WithError(err error) *logrus.Entry {
return logger.WithField(logrus.ErrorKey, err)
}
// WithField creates an entry from the standard logger and adds a field to
// it. If you want multiple fields, use `WithFields`.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithField(key string, value interface{}) *logrus.Entry {
return logger.WithField(key, value)
}
// WithTrace adds trace stack and prints it on log
func WithTrace(value ...interface{}) *logrus.Entry {
return logger.WithField("trace_hook_stack", value)
}
// WithFields creates an entry from the standard logger and adds multiple
// fields to it. This is simply a helper for `WithField`, invoking it
// once for each field.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithFields(fields Fields) *logrus.Entry {
return logger.WithFields(logrus.Fields(fields))
}
// WithFieldsAndTrace merge of WithFields and WithTrace
func WithFieldsAndTrace(fields Fields, value ...interface{}) *logrus.Entry {
return logger.WithFields(logrus.Fields(fields)).WithField("trace_hook_stack", value)
}
// WithTime creats an entry from the standard logger and overrides the time of
// logs generated with it.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithTime(t time.Time) *logrus.Entry {
return logger.WithTime(t)
}
// Trace logs a message at level Trace on the standard logger.
func Trace(args ...interface{}) {
logger.Trace(args...)
}
// Debug logs a message at level Debug on the standard logger.
func Debug(args ...interface{}) {
logger.Debug(args...)
}
// Print logs a message at level Info on the standard logger.
func Print(args ...interface{}) {
logger.Print(args...)
}
// Info logs a message at level Info on the standard logger.
func Info(args ...interface{}) {
logger.Info(args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warn(args ...interface{}) {
logger.Warn(args...)
}
// Warning logs a message at level Warn on the standard logger.
func Warning(args ...interface{}) {
logger.Warning(args...)
}
// Error logs a message at level Error on the standard logger.
func Error(args ...interface{}) {
logger.Error(args...)
}
// Panic logs a message at level Panic on the standard logger.
func Panic(args ...interface{}) {
logger.Panic(args...)
}
// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatal(args ...interface{}) {
logger.Fatal(args...)
}
// Tracef logs a message at level Trace on the standard logger.
func Tracef(format string, args ...interface{}) {
logger.Tracef(format, args...)
}
// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) {
logger.Debugf(format, args...)
}
// Printf logs a message at level Info on the standard logger.
func Printf(format string, args ...interface{}) {
logger.Printf(format, args...)
}
// Infof logs a message at level Info on the standard logger.
func Infof(format string, args ...interface{}) {
logger.Infof(format, args...)
}
// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...interface{}) {
logger.Warnf(format, args...)
}
// Warningf logs a message at level Warn on the standard logger.
func Warningf(format string, args ...interface{}) {
logger.Warningf(format, args...)
}
// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...interface{}) {
logger.Errorf(format, args...)
}
// Panicf logs a message at level Panic on the standard logger.
func Panicf(format string, args ...interface{}) {
logger.Panicf(format, args...)
}
// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalf(format string, args ...interface{}) {
logger.Fatalf(format, args...)
}
// Traceln logs a message at level Trace on the standard logger.
func Traceln(args ...interface{}) {
logger.Traceln(args...)
}
// Debugln logs a message at level Debug on the standard logger.
func Debugln(args ...interface{}) {
logger.Debugln(args...)
}
// Println logs a message at level Info on the standard logger.
func Println(args ...interface{}) {
logger.Println(args...)
}
// Infoln logs a message at level Info on the standard logger.
func Infoln(args ...interface{}) {
logger.Infoln(args...)
}
// Warnln logs a message at level Warn on the standard logger.
func Warnln(args ...interface{}) {
logger.Warnln(args...)
}
// Warningln logs a message at level Warn on the standard logger.
func Warningln(args ...interface{}) {
logger.Warningln(args...)
}
// Errorln logs a message at level Error on the standard logger.
func Errorln(args ...interface{}) {
logger.Errorln(args...)
}
// Panicln logs a message at level Panic on the standard logger.
func Panicln(args ...interface{}) {
logger.Panicln(args...)
}
// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1.
func Fatalln(args ...interface{}) {
logger.Fatalln(args...)
}
|
package main
import (
"fmt"
"time"
"sync"
"sync/atomic"
)
var countConcurrency int32 = 0
var wg2 sync.WaitGroup
func main(){
wg2.Add(3)
go concurrencyTeste("Thread1 ")
go concurrencyTeste("Thread2 ")
go concurrencyTeste("Thread3 ")
wg2.Wait()
}
func concurrencyTeste(threadName string){
for i:=0;i<100;i++ {
atomic.AddInt32( &countConcurrency , 1)
time.Sleep(300)
fmt.Println("Nome = ",threadName," count = ",countConcurrency)
}
wg2.Done()
}
|
package log
import (
"fmt"
"log"
"os"
"time"
"path/filepath"
"runtime"
"github.com/natefinch/lumberjack"
)
var (
// ErrorLog logger with custom formatting, written to stdOut
ErrorLog *log.Logger
// FatalLog logger with custom formatting, written to stdOut
FatalLog *log.Logger
// InfoLog logger with custom formatting, written to stdOut
InfoLog *log.Logger
// WarningLog logger with custom formatting, written to stdOut
WarningLog *log.Logger
// Color
color bool
)
const AppLogLocation = "some-app.log"
// ColorRed ANSI Color Red
const ColorRed = "\x1b[31;1m"
// ColorYellow ANSI Color Yellow
const ColorYellow = "\x1b[33;1m"
// ColorWhite ANSI Color White
const ColorWhite = "\x1b[37;1m"
// ColorClear ANSI Clear
const ColorClear = "\x1b[0m"
func init() {
applicationLogFile := &lumberjack.Logger{
Filename: AppLogLocation,
MaxAge: 1, // days
MaxBackups: 14, // max days of retention
}
_, ok := os.LookupEnv("DEBUG")
if ok {
InfoLog = log.New(os.Stdout, "", 0)
WarningLog = log.New(os.Stdout, "", 0)
ErrorLog = log.New(os.Stdout, "", 0)
FatalLog = log.New(os.Stdout, "", 0)
_, disable := os.LookupEnv("DISABLE_COLOR")
if disable {
color = false
} else {
color = true
}
} else {
InfoLog = log.New(applicationLogFile, "", 0)
WarningLog = log.New(applicationLogFile, "", 0)
ErrorLog = log.New(applicationLogFile, "", 0)
FatalLog = log.New(applicationLogFile, "", 0)
color = false
}
}
func getCaller() string {
pc, fn, line, _ := runtime.Caller(2)
_, file := filepath.Split(fn)
_, fc := filepath.Split(runtime.FuncForPC(pc).Name())
return fmt.Sprintf("%s [%s:%d] ", fc, file, line)
}
func colorMe(s string) string {
pre := ""
post := ""
if color {
switch s {
case "[ERROR]", "[FATAL]":
pre = ColorRed
case "[WARN]":
pre = ColorYellow
case "[INFO]":
pre = ColorWhite
}
post = ColorClear
}
return fmt.Sprintf("%s%s%s", pre, s, post)
}
// Error logs error messages with custom format using Print
func Error(m ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[ERROR]"), getCaller())
ErrorLog.Print(append([]interface{}{prefix}, m...)...)
}
// Errorf logs error messages with custom format using Printf
func Errorf(m string, v ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[ERROR]"), getCaller())
ErrorLog.Printf(prefix+m, v...)
}
// Fatal logs error messages with custom format using Print
func Fatal(m ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[FATAL]"), getCaller())
FatalLog.Print(append([]interface{}{prefix}, m...)...)
os.Exit(1)
}
// Fatalf logs error messages with custom format using Printf
func Fatalf(m string, v ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[FATAL]"), getCaller())
FatalLog.Printf(prefix+m, v...)
os.Exit(1)
}
// Info logs info messages with custom format using Print
func Info(m ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[INFO]"), getCaller())
InfoLog.Print(append([]interface{}{prefix}, m...)...)
}
// Infof logs info messages with custom format using Printf
func Infof(m string, v ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[INFO]"), getCaller())
InfoLog.Printf(prefix+m, v...)
}
// Warn logs warning messages with custom format using Print
func Warn(m ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[WARN]"), getCaller())
WarningLog.Print(append([]interface{}{prefix}, m...)...)
}
// Warnf logs warning messages with custom format using Printf
func Warnf(m string, v ...interface{}) {
prefix := fmt.Sprintf("%-28s %-7s %s", time.Now().Format("01/02/2006 15:04:05.999 MST"), colorMe("[WARN]"), getCaller())
WarningLog.Printf(prefix+m, v...)
}
|
package basic
import (
"fmt"
)
func go1() {
data := []string{"one", "two", "three"}
for _, v := range data {
go func() {
fmt.Println(v)
}()
}
//time.Sleep(3 * time.Second)
//goroutines print: three, three, three
}
func go2() {
data := []string{"one", "two", "three"}
for _, v := range data {
vcopy := v //
go func() {
fmt.Println(vcopy)
}()
}
//time.Sleep(1 * time.Second)
//goroutines print: one, two, three
}
func defer1() {
// defer执行的语句只有在defer声明的时候求值
var i int = 1
defer fmt.Println("result =>", func() int { return i * 2 }())
i++
//prints: result => 2 (not ok if you expected 4)
}
func go3() {
done := false
go func() {
done = true
}()
for !done {
}
fmt.Println("go3 done!")
}
func Go() {
fmt.Println("<-------------------------- Go begin -------------------->")
defer1()
go1()
go2()
go3()
fmt.Println("<-------------------------- Go end -------------------->")
}
|
/*
Copyright 2017 The Kubernetes 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 ipvs
import (
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"strings"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/version"
"k8s.io/klog/v2"
utilexec "k8s.io/utils/exec"
)
// DefaultScheduler is the default ipvs scheduler algorithm - round robin.
const DefaultScheduler = "rr"
// KernelHandler can handle the current installed kernel modules.
type KernelHandler interface {
GetModules() ([]string, error)
GetKernelVersion() (string, error)
}
// LinuxKernelHandler implements KernelHandler interface.
type LinuxKernelHandler struct {
executor utilexec.Interface
}
// NewLinuxKernelHandler initializes LinuxKernelHandler with exec.
func NewLinuxKernelHandler() *LinuxKernelHandler {
return &LinuxKernelHandler{
executor: utilexec.New(),
}
}
// GetModules returns all installed kernel modules.
func (handle *LinuxKernelHandler) GetModules() ([]string, error) {
// Check whether IPVS required kernel modules are built-in
kernelVersionStr, err := handle.GetKernelVersion()
if err != nil {
return nil, err
}
kernelVersion, err := version.ParseGeneric(kernelVersionStr)
if err != nil {
return nil, fmt.Errorf("error parsing kernel version %q: %v", kernelVersionStr, err)
}
ipvsModules := GetRequiredIPVSModules(kernelVersion)
var bmods, lmods []string
// Find out loaded kernel modules. If this is a full static kernel it will try to verify if the module is compiled using /boot/config-KERNELVERSION
modulesFile, err := os.Open("/proc/modules")
if err == os.ErrNotExist {
klog.Warningf("Failed to read file /proc/modules with error %v. Assuming this is a kernel without loadable modules support enabled", err)
kernelConfigFile := fmt.Sprintf("/boot/config-%s", kernelVersionStr)
kConfig, err := ioutil.ReadFile(kernelConfigFile)
if err != nil {
return nil, fmt.Errorf("failed to read Kernel Config file %s with error %v", kernelConfigFile, err)
}
for _, module := range ipvsModules {
if match, _ := regexp.Match("CONFIG_"+strings.ToUpper(module)+"=y", kConfig); match {
bmods = append(bmods, module)
}
}
return bmods, nil
}
if err != nil {
return nil, fmt.Errorf("failed to read file /proc/modules with error %v", err)
}
mods, err := getFirstColumn(modulesFile)
if err != nil {
return nil, fmt.Errorf("failed to find loaded kernel modules: %v", err)
}
builtinModsFilePath := fmt.Sprintf("/lib/modules/%s/modules.builtin", kernelVersionStr)
b, err := ioutil.ReadFile(builtinModsFilePath)
if err != nil {
klog.Warningf("Failed to read file %s with error %v. You can ignore this message when kube-proxy is running inside container without mounting /lib/modules", builtinModsFilePath, err)
}
for _, module := range ipvsModules {
if match, _ := regexp.Match(module+".ko", b); match {
bmods = append(bmods, module)
} else {
// Try to load the required IPVS kernel modules if not built in
err := handle.executor.Command("modprobe", "--", module).Run()
if err != nil {
klog.Warningf("Failed to load kernel module %v with modprobe. "+
"You can ignore this message when kube-proxy is running inside container without mounting /lib/modules", module)
} else {
lmods = append(lmods, module)
}
}
}
mods = append(mods, bmods...)
mods = append(mods, lmods...)
return mods, nil
}
// getFirstColumn reads all the content from r into memory and return a
// slice which consists of the first word from each line.
func getFirstColumn(r io.Reader) ([]string, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
lines := strings.Split(string(b), "\n")
words := make([]string, 0, len(lines))
for i := range lines {
fields := strings.Fields(lines[i])
if len(fields) > 0 {
words = append(words, fields[0])
}
}
return words, nil
}
// GetKernelVersion returns currently running kernel version.
func (handle *LinuxKernelHandler) GetKernelVersion() (string, error) {
kernelVersionFile := "/proc/sys/kernel/osrelease"
fileContent, err := ioutil.ReadFile(kernelVersionFile)
if err != nil {
return "", fmt.Errorf("error reading osrelease file %q: %v", kernelVersionFile, err)
}
return strings.TrimSpace(string(fileContent)), nil
}
// CanUseIPVSProxier returns true if we can use the ipvs Proxier.
// This is determined by checking if all the required kernel modules can be loaded. It may
// return an error if it fails to get the kernel modules information without error, in which
// case it will also return false.
func CanUseIPVSProxier(handle KernelHandler) (bool, error) {
mods, err := handle.GetModules()
if err != nil {
return false, fmt.Errorf("error getting installed ipvs required kernel modules: %v", err)
}
loadModules := sets.NewString()
loadModules.Insert(mods...)
kernelVersionStr, err := handle.GetKernelVersion()
if err != nil {
return false, fmt.Errorf("error determining kernel version to find required kernel modules for ipvs support: %v", err)
}
kernelVersion, err := version.ParseGeneric(kernelVersionStr)
if err != nil {
return false, fmt.Errorf("error parsing kernel version %q: %v", kernelVersionStr, err)
}
mods = GetRequiredIPVSModules(kernelVersion)
wantModules := sets.NewString()
wantModules.Insert(mods...)
modules := wantModules.Difference(loadModules).UnsortedList()
var missingMods []string
ConntrackiMissingCounter := 0
for _, mod := range modules {
if strings.Contains(mod, "nf_conntrack") {
ConntrackiMissingCounter++
} else {
missingMods = append(missingMods, mod)
}
}
if ConntrackiMissingCounter == 2 {
missingMods = append(missingMods, "nf_conntrack_ipv4(or nf_conntrack for Linux kernel 4.19 and later)")
}
if len(missingMods) != 0 {
return false, fmt.Errorf("IPVS proxier will not be used because the following required kernel modules are not loaded: %v", missingMods)
}
return true, nil
}
func SupportXfrmInterface(handle KernelHandler) (bool, error) {
currentVersionStr, err := handle.GetKernelVersion()
if err != nil {
return false, err
}
currentVersion, err := version.ParseGeneric(currentVersionStr)
if err != nil {
return false, err
}
// xfrm interfaces have been supported since kernel 4.19
// see http://patchwork.ozlabs.org/project/netdev/patch/20190101124001.28e58469@aquamarine/
xfrmMinSupportedKernelVersion := "4.19"
expectVersion, err := version.ParseGeneric(xfrmMinSupportedKernelVersion)
if err != nil {
return false, err
}
return expectVersion.LessThan(currentVersion), nil
}
|
package sort
import (
"sort"
"testing"
"github.com/seifer/go-dsa/sort/heapsort"
"github.com/seifer/go-dsa/sort/insertionsort"
"github.com/seifer/go-dsa/sort/mergesort"
"github.com/seifer/go-dsa/sort/quicksort"
"github.com/seifer/go-dsa/sort/selectionsort"
"github.com/seifer/go-dsa/sort/shellsort"
"github.com/seifer/go-dsa/sort/timsort"
)
func BenchmarkInt1KStdSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
sort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt1KSelectionSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
selectionsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt1KInsertionSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
insertionsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt1KQuickSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
quicksort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt1KShellSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
shellsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt1KMergeSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
mergesort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt1KHeapSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
heapsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt1KTimSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<10)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0x2cc
}
b.StartTimer()
timsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KStdSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
sort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KSelectionSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
selectionsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KInsertionSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
insertionsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KQuickSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
quicksort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KShellSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
shellsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KMergeSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
mergesort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KHeapSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
heapsort.Ints(data)
b.StopTimer()
}
}
func BenchmarkInt64KTimSort(b *testing.B) {
b.StopTimer()
for i := 0; i < b.N; i++ {
data := make([]int, 1<<16)
for i := 0; i < len(data); i++ {
data[i] = i ^ 0xcccc
}
b.StartTimer()
timsort.Ints(data)
b.StopTimer()
}
}
|
package api
import (
"fmt"
"github.com/yaziedda/iser/app/common"
"github.com/yaziedda/iser/app/user"
"math/rand"
"net/http"
"strconv"
"time"
)
func UserLoginHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
common.CheckError(err)
email := r.PostFormValue("user_email")
password := r.PostFormValue("user_password")
t := time.Now().Format("2006:01:02 15:04:05")
fmt.Println(t)
if email != "" && password != "" {
json := user.UserLogin(email, password)
fmt.Fprintf(w, "%v", json)
} else {
http.Error(w, common.ErrorBadReq(), http.StatusBadRequest)
}
}
func RegisterUserHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
common.CheckError(err)
id := r.PostFormValue("user_id")
username := r.PostFormValue("user_name")
email := r.PostFormValue("user_email")
phone := r.PostFormValue("user_phone")
password := r.PostFormValue("password")
if id != "" && username != "" && email != "" && phone != "" && password != "" {
json := user.InsertRegister(id, username, email, phone, password)
fmt.Fprintf(w, "%v", json)
} else {
http.Error(w, common.ErrorBadReq(), http.StatusBadRequest)
}
}
func InsertVerification(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
common.CheckError(err)
email := r.PostFormValue("user_email")
phone := r.PostFormValue("user_phone")
if email != "" && phone != "" {
rand := rand.Intn(99999)
stringRand := strconv.Itoa(rand)
respon := user.InsertVerification(phone, email, stringRand)
fmt.Fprintf(w, "%v", respon)
} else {
http.Error(w, common.ErrorBadReq(), http.StatusBadRequest)
}
}
func CheckVerificationCode(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
common.CheckError(err)
a := r.PostFormValue("code")
b := r.PostFormValue("user_phone")
if a != "" && b != "" {
data := user.CheckVerification(a, b)
fmt.Fprintf(w, "%v", data)
} else {
http.Error(w, common.ErrorBadReq(), http.StatusBadRequest)
}
}
|
package sound
/*
#cgo pkg-config: alsa
#include <stdbool.h>
#include <stdint.h>
#include <alsa/asoundlib.h>
#include "estr.h"
static snd_pcm_t* openDevice(const char *deviceName, unsigned int rate, EStr* estr) {
int err = 0;
snd_pcm_hw_params_t* params = NULL;
snd_pcm_t* handle = NULL;
if ((err = snd_pcm_open(&handle, deviceName, SND_PCM_STREAM_PLAYBACK, 0)) < 0)
{
eprintf("Cannot open playback audio device %s (%s, %d)\n", deviceName, snd_strerror(err), err);
goto out;
}
if ((err = snd_pcm_hw_params_malloc(¶ms)) < 0)
{
eprintf("Cannot allocate hardware parameter structure (%s, %d)\n", snd_strerror(err), err);
goto out;
}
if ((err = snd_pcm_hw_params_any(handle, params)) < 0)
{
eprintf("Cannot initialize hardware parameter structure (%s, %d)\n", snd_strerror(err), err);
goto out;
}
if ((err = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
{
eprintf("Cannot set access type (%s, %d)\n", snd_strerror(err), err);
goto out;
}
if ((err = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE)) < 0)
{
eprintf("Cannot set sample format (%s, %d)\n", snd_strerror(err), err);
goto out;
}
if ((err = snd_pcm_hw_params_set_rate_near(handle, params, &rate, 0)) < 0)
{
eprintf("Cannot set sample rate (%s, %d)\n", snd_strerror(err), err);
goto out;
}
if ((err = snd_pcm_hw_params_set_channels(handle, params, 1))< 0)
{
eprintf("Cannot set channel count (%s, %d)\n", snd_strerror(err), err);
goto out;
}
if ((err = snd_pcm_hw_params(handle, params)) < 0)
{
eprintf("Cannot set parameters (%s, %d)\n", snd_strerror(err), err);
goto out;
}
out:
if (err < 0) {
errno = -err;
if (handle != NULL) {
snd_pcm_close(handle);
handle = NULL;
}
}
if (params)
snd_pcm_hw_params_free(params);
return handle;
}
static bool playback(snd_pcm_t* handle, const int16_t* buf, int bufSize, EStr* estr) {
int err = 0;
if ((err = snd_pcm_writei(handle, buf, bufSize)) != bufSize)
{
eprintf("write to audio interface failed (%s)\n", snd_strerror (err));
return false;
}
snd_pcm_nonblock(handle, 0);
snd_pcm_drain(handle);
snd_pcm_nonblock(handle, 1);
return true;
}
*/
import "C"
import (
"errors"
"fmt"
"sync"
"unsafe"
"github.com/rmcsoft/hasp/events"
log "github.com/sirupsen/logrus"
)
// SoundPlayedEventName an event with this name is emitted when the sound is played
const SoundPlayedEventName = "SoundPlayedEvent"
// SoundPlayer sound player
type SoundPlayer struct {
devName string
devClosedCond *sync.Cond
devMutex *sync.Mutex
dev *C.snd_pcm_t
}
// NewSoundPlayer creates new SoundPlayer
func NewSoundPlayer(devName string) (*SoundPlayer, error) {
sp := &SoundPlayer{
devName: devName,
devMutex: &sync.Mutex{},
}
sp.devClosedCond = sync.NewCond(sp.devMutex)
return sp, nil
}
// Play starts playing back buffer
func (p *SoundPlayer) Play(audioData *AudioData) (events.EventSource, error) {
p.devMutex.Lock()
defer p.devMutex.Unlock()
p.stop(false)
if audioData.SampleType() != S16LE || audioData.ChannelCount() != 1 {
return nil, errors.New("Unsupported audio format")
}
estr := &C.EStr{}
p.dev = C.openDevice(C.CString(p.devName), C.uint(audioData.SampleRate()), estr)
if p.dev == nil {
err := fmt.Errorf("Could't open audio device for playback: %v", estr)
return nil, err
}
asyncPlay := func() *events.Event {
log.Info("SoundPlayer: StartPlay")
sampleCount := audioData.SampleCount()
if sampleCount == 0 {
log.Info("SoundPlayer: NothingToPlay")
p.closeDev(false)
return &events.Event{Name: SoundPlayedEventName}
}
samples := audioData.Samples()
estr := &C.EStr{}
cptr := (*C.int16_t)(unsafe.Pointer(&samples[0]))
if !C.playback(p.dev, cptr, C.int(sampleCount), estr) {
// TODO: Reaction to an error
err := fmt.Errorf("playback failed: %v", estr)
log.Errorf("SoundPlayer: %v", err)
}
p.closeDev(false)
log.Info("SoundPlayer: StopPlay")
return &events.Event{Name: SoundPlayedEventName}
}
return events.NewSingleEventSource("SoundPlayerEventSource", asyncPlay), nil
}
// Play Sync plays back buffer
func (p *SoundPlayer) PlaySync(audioData *AudioData) {
if audioData == nil {
return
}
p.devMutex.Lock()
defer p.devMutex.Unlock()
p.stop(false)
if audioData.SampleType() != S16LE || audioData.ChannelCount() != 1 {
return
}
estr := &C.EStr{}
p.dev = C.openDevice(C.CString(p.devName), C.uint(audioData.SampleRate()), estr)
if p.dev == nil {
fmt.Errorf("could't open audio device for playback: %v", estr)
return
}
sampleCount := audioData.SampleCount()
if sampleCount == 0 {
log.Info("SoundPlayer: NothingToPlay")
p.closeDev(false)
return
}
samples := audioData.Samples()
cptr := (*C.int16_t)(unsafe.Pointer(&samples[0]))
if !C.playback(p.dev, cptr, C.int(sampleCount), estr) {
err := fmt.Errorf("playback failed: %v", estr)
log.Errorf("SoundPlayer: %v", err)
}
p.closeDev(false)
}
// Stop playing
func (p *SoundPlayer) Stop() {
p.stop(true)
}
func (p *SoundPlayer) stop(useLock bool) {
if useLock {
p.devMutex.Lock()
defer p.devMutex.Unlock()
}
if p.dev != nil {
C.snd_pcm_drop(p.dev)
for p.dev != nil {
p.devClosedCond.Wait()
}
log.Info("SoundPlayer: stopped")
}
}
func (p *SoundPlayer) closeDev(useLock bool) {
if useLock {
p.devMutex.Lock()
defer p.devMutex.Unlock()
}
if p.dev != nil {
C.snd_pcm_close(p.dev)
p.dev = nil
}
p.devClosedCond.Signal()
}
|
package main
import (
"io"
"log"
"net/http"
)
func main() {
// Hello world, the web server
helloHandler := func(w http.ResponseWriter, req *http.Request) {
if req.ParseForm() == nil && req.Form.Get("secret") == "secret" {
io.WriteString(w, `{
"ttl": 3600,
"identity": "username",
"identity_url": "https://....",
"authorizations": [
{
"permissions": [
"subscribe",
"publish"
],
"topic": ".*",
"channels": [
".*"
]
}
]
}`)
}
}
http.HandleFunc("/auth", helloHandler)
log.Fatal(http.ListenAndServe(":8000", nil))
}
|
package superhero
import (
"context"
"database/sql"
"errors"
"github.com/go-kit/kit/log/level"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
"google.golang.org/grpc/codes"
pb "github.com/jace-ys/super-smash-heroes/services/superhero/api/superhero"
)
func (s *SuperheroService) List(ctx context.Context, req *pb.ListRequest) (*pb.ListResponse, error) {
level.Info(s.logger).Log("event", "superhero.list.started")
defer level.Info(s.logger).Log("event", "superhero.list.finished")
superheroes, err := s.list(ctx)
if err != nil {
level.Error(s.logger).Log("event", "superhero.list.failed", "msg", err)
return nil, s.Error(codes.Internal, err)
}
return &pb.ListResponse{
Superheroes: superheroes,
}, nil
}
func (s *SuperheroService) list(ctx context.Context) ([]*pb.Superhero, error) {
var superheroes []*pb.Superhero
err := s.database.Transact(ctx, func(tx *sqlx.Tx) error {
query := `
SELECT s.id, s.full_name, s.alter_ego, s.image_url, s.intelligence, s.strength, s.speed, s.durability, s.power, s.combat
FROM superheroes AS s
`
rows, err := tx.QueryxContext(ctx, query)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var superhero pb.Superhero
if err := rows.StructScan(&superhero); err != nil {
return err
}
superheroes = append(superheroes, &superhero)
}
return rows.Err()
})
if err != nil {
return nil, err
}
return superheroes, nil
}
func (s *SuperheroService) Get(ctx context.Context, req *pb.GetRequest) (*pb.GetResponse, error) {
level.Info(s.logger).Log("event", "superhero.get.started")
defer level.Info(s.logger).Log("event", "superhero.get.finished")
superhero, err := s.get(ctx, req.Id)
if err != nil {
level.Error(s.logger).Log("event", "superhero.get.failed", "msg", err)
switch {
case errors.Is(err, ErrSuperheroNotFound):
return nil, s.Error(codes.NotFound, err)
default:
return nil, s.Error(codes.Internal, err)
}
}
return &pb.GetResponse{
Superheroes: superhero,
}, nil
}
func (s *SuperheroService) get(ctx context.Context, id int32) (*pb.Superhero, error) {
var superhero pb.Superhero
err := s.database.Transact(ctx, func(tx *sqlx.Tx) error {
query := `
SELECT s.id, s.full_name, s.alter_ego, s.image_url, s.intelligence, s.strength, s.speed, s.durability, s.power, s.combat
FROM superheroes AS s
WHERE s.id=$1
`
row := tx.QueryRowxContext(ctx, query, id)
return row.StructScan(&superhero)
})
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, ErrSuperheroNotFound
default:
return nil, err
}
}
return &superhero, nil
}
func (s *SuperheroService) Create(ctx context.Context, req *pb.CreateRequest) (*pb.CreateResponse, error) {
level.Info(s.logger).Log("event", "superhero.create.started")
defer level.Info(s.logger).Log("event", "superhero.create.finished")
err := s.validateCreateRequest(req.FullName, req.AlterEgo)
if err != nil {
level.Error(s.logger).Log("event", "superhero.create.failed", "msg", err)
return nil, s.Error(codes.InvalidArgument, err)
}
superhero, err := s.registry.Find(req.FullName, req.AlterEgo)
if err != nil {
level.Error(s.logger).Log("event", "superhero.create.failed", "msg", err)
return nil, s.Error(codes.NotFound, err)
}
id, err := s.create(ctx, superhero)
if err != nil {
level.Error(s.logger).Log("event", "superhero.create.failed", "msg", err)
switch {
case errors.Is(err, ErrSuperheroExists):
return nil, s.Error(codes.AlreadyExists, err)
default:
return nil, s.Error(codes.Internal, err)
}
}
return &pb.CreateResponse{
Id: id,
}, nil
}
func (s *SuperheroService) validateCreateRequest(fullName, alterEgo string) error {
switch {
case fullName == "":
return ErrRequestInvalid
case alterEgo == "":
return ErrRequestInvalid
}
return nil
}
func (s *SuperheroService) create(ctx context.Context, superhero *pb.Superhero) (int32, error) {
var id int32
err := s.database.Transact(ctx, func(tx *sqlx.Tx) error {
query := `
INSERT INTO superheroes (full_name, alter_ego, image_url, intelligence, strength, speed, durability, power, combat)
VALUES (:full_name, :alter_ego, :image_url, :intelligence, :strength, :speed, :durability, :power, :combat)
RETURNING id
`
stmt, err := tx.PrepareNamedContext(ctx, query)
if err != nil {
return err
}
return stmt.QueryRowxContext(ctx, superhero).Scan(&id)
})
if err != nil {
var pqErr *pq.Error
switch {
case errors.As(err, &pqErr) && pqErr.Code.Name() == "unique_violation":
return 0, ErrSuperheroExists
default:
return 0, err
}
}
return id, nil
}
func (s *SuperheroService) Delete(ctx context.Context, req *pb.DeleteRequest) (*pb.DeleteResponse, error) {
level.Info(s.logger).Log("event", "superhero.delete.started")
defer level.Info(s.logger).Log("event", "superhero.delete.finished")
err := s.delete(ctx, req.Id)
if err != nil {
level.Error(s.logger).Log("event", "superhero.delete.failed", "msg", err)
switch {
case errors.Is(err, ErrSuperheroNotFound):
return nil, s.Error(codes.NotFound, err)
default:
return nil, s.Error(codes.Internal, err)
}
}
return &pb.DeleteResponse{}, nil
}
func (s *SuperheroService) delete(ctx context.Context, id int32) error {
err := s.database.Transact(ctx, func(tx *sqlx.Tx) error {
query := `
DELETE FROM superheroes
WHERE id=$1
`
res, err := tx.ExecContext(ctx, query, id)
if err != nil {
return err
}
count, err := res.RowsAffected()
if err != nil {
return err
}
if count == 0 {
return sql.ErrNoRows
}
return nil
})
if err != nil {
switch {
case errors.Is(err, sql.ErrNoRows):
return ErrSuperheroNotFound
default:
return err
}
}
return nil
}
|
// Copyright 2016-2021 terraform-provider-sakuracloud 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 sakuracloud
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"reflect"
"sort"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/sacloud/libsacloud/v2/helper/api"
"github.com/sacloud/libsacloud/v2/helper/query"
"github.com/sacloud/libsacloud/v2/sacloud"
"github.com/sacloud/libsacloud/v2/sacloud/profile"
)
const (
traceHTTP = "http"
traceAPI = "api"
)
const uaEnvVar = "SAKURACLOUD_APPEND_USER_AGENT"
var (
deletionWaiterTimeout = 30 * time.Minute
deletionWaiterPollingInterval = 5 * time.Second
databaseWaitAfterCreateDuration = 1 * time.Minute
vpcRouterWaitAfterCreateDuration = 1 * time.Minute
)
// Config type of SakuraCloud Config
type Config struct {
Profile string
AccessToken string
AccessTokenSecret string
Zone string
Zones []string
DefaultZone string
TraceMode string
FakeMode string
FakeStorePath string
AcceptLanguage string
APIRootURL string
RetryMax int
RetryWaitMin int
RetryWaitMax int
APIRequestTimeout int
APIRequestRateLimit int
terraformVersion string
}
// APIClient for SakuraCloud API
type APIClient struct {
sacloud.APICaller
defaultZone string // 各リソースでzone未指定の場合に利用するゾーン。sacloud.APIDefaultZoneとは別物。
zones []string
deletionWaiterTimeout time.Duration
deletionWaiterPollingInterval time.Duration
databaseWaitAfterCreateDuration time.Duration
vpcRouterWaitAfterCreateDuration time.Duration
}
func (c *APIClient) checkReferencedOption() query.CheckReferencedOption {
return query.CheckReferencedOption{
Tick: c.deletionWaiterPollingInterval,
Timeout: c.deletionWaiterTimeout,
}
}
func (c *Config) loadFromProfile() error {
if c.Profile == "" {
c.Profile = profile.DefaultProfileName
}
if c.Profile != profile.DefaultProfileName {
log.Printf("[DEBUG] using profile %q", c.Profile)
}
pcv := &profile.ConfigValue{}
if err := profile.Load(c.Profile, pcv); err != nil {
return fmt.Errorf("loading profile %q is failed: %s", c.Profile, err)
}
if c.AccessToken == "" {
c.AccessToken = pcv.AccessToken
}
if c.AccessTokenSecret == "" {
c.AccessTokenSecret = pcv.AccessTokenSecret
}
if c.Zone == defaultZone && pcv.Zone != "" {
c.Zone = pcv.Zone
}
sort.Strings(c.Zones)
sort.Strings(pcv.Zones)
if reflect.DeepEqual(defaultZones, c.Zones) && !reflect.DeepEqual(c.Zones, pcv.Zones) && len(pcv.Zones) > 0 {
c.Zones = pcv.Zones
}
if c.TraceMode == "" {
c.TraceMode = pcv.TraceMode
}
if c.FakeMode == "" && pcv.FakeMode {
c.FakeMode = "1"
}
if c.FakeStorePath == "" {
c.FakeStorePath = pcv.FakeStorePath
}
if c.AcceptLanguage == "" {
c.AcceptLanguage = pcv.AcceptLanguage
}
if c.APIRootURL == "" {
c.APIRootURL = pcv.APIRootURL
}
if c.RetryMax == defaultRetryMax && pcv.RetryMax > 0 {
c.RetryMax = pcv.RetryMax
}
if c.RetryWaitMax == 0 {
c.RetryWaitMax = pcv.RetryWaitMax
}
if c.RetryWaitMin == 0 {
c.RetryWaitMin = pcv.RetryWaitMin
}
if c.APIRequestTimeout == defaultAPIRequestTimeout && pcv.HTTPRequestTimeout > 0 {
c.APIRequestTimeout = pcv.HTTPRequestTimeout
}
if c.APIRequestRateLimit == defaultAPIRequestRateLimit && pcv.HTTPRequestRateLimit > 0 {
c.APIRequestRateLimit = pcv.HTTPRequestRateLimit
}
return nil
}
func (c *Config) validate() error {
var err error
if c.AccessToken == "" {
err = multierror.Append(err, errors.New("AccessToken is required"))
}
if c.AccessTokenSecret == "" {
err = multierror.Append(err, errors.New("AccessTokenSecret is required"))
}
return err
}
// NewClient returns new API Client for SakuraCloud
func (c *Config) NewClient() (*APIClient, error) {
if err := c.loadFromProfile(); err != nil {
return nil, err
}
if err := c.validate(); err != nil {
return nil, err
}
tfUserAgent := terraformUserAgent(c.terraformVersion)
providerUserAgent := fmt.Sprintf("%s/v%s", "terraform-provider-sakuracloud", Version)
ua := fmt.Sprintf("%s %s", tfUserAgent, providerUserAgent)
if add := os.Getenv(uaEnvVar); add != "" {
ua += " " + add
log.Printf("[DEBUG] Using modified User-Agent: %s", ua)
}
enableAPITrace := false
enableHTTPTrace := false
if c.TraceMode != "" {
enableAPITrace = true
enableHTTPTrace = true
mode := strings.ToLower(c.TraceMode)
switch mode {
case traceAPI:
enableHTTPTrace = false
case traceHTTP:
enableAPITrace = false
}
}
caller := api.NewCaller(&api.CallerOptions{
AccessToken: c.AccessToken,
AccessTokenSecret: c.AccessTokenSecret,
APIRootURL: c.APIRootURL,
DefaultZone: c.DefaultZone,
AcceptLanguage: c.AcceptLanguage,
HTTPClient: http.DefaultClient,
HTTPRequestTimeout: c.APIRequestTimeout,
HTTPRequestRateLimit: c.APIRequestRateLimit,
RetryMax: c.RetryMax,
RetryWaitMax: c.RetryWaitMax,
RetryWaitMin: c.RetryWaitMin,
UserAgent: ua,
TraceAPI: enableAPITrace,
TraceHTTP: enableHTTPTrace,
OpenTelemetry: false,
OpenTelemetryOptions: nil,
FakeMode: c.FakeMode != "",
FakeStorePath: c.FakeStorePath,
})
zones := c.Zones
if len(zones) == 0 {
zones = defaultZones
}
// fakeモード有効時は待ち時間を短くしておく
if c.FakeMode != "" {
deletionWaiterTimeout = 300 * time.Millisecond // 短すぎるとタイムアウトするため余裕を持たせておく
deletionWaiterPollingInterval = time.Millisecond
databaseWaitAfterCreateDuration = time.Millisecond
vpcRouterWaitAfterCreateDuration = time.Millisecond
}
return &APIClient{
APICaller: caller,
defaultZone: c.Zone,
zones: zones,
deletionWaiterTimeout: deletionWaiterTimeout,
deletionWaiterPollingInterval: deletionWaiterPollingInterval,
databaseWaitAfterCreateDuration: databaseWaitAfterCreateDuration,
vpcRouterWaitAfterCreateDuration: vpcRouterWaitAfterCreateDuration,
}, nil
}
|
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"gopkg.in/alecthomas/kingpin.v1"
"log"
"os"
"sort"
"strconv"
)
var (
app = kingpin.New("dead-letter-requeue", "Requeue messages from a SQS dead-letter queue to the active one.")
queueName = app.Arg("destination-queue-name", "Name of the destination SQS queue (e.g. buy-worker).").Required().String()
fromQueueName = app.Flag("source-queue-name", "Name of the source SQS queue (e.g. buy-worker-dead-letter).").String()
accountID = app.Flag("account-id", "AWS account ID. (e.g. 123456789)").String()
messageLimit = app.Flag("messages", "messages to process").Int()
)
type byTimestamp []*sqs.Message
func extractAwsTimestamp(m *sqs.Message) int64 {
ts := m.Attributes["SentTimestamp"]
i, err := strconv.ParseInt(*ts, 10, 64)
if err != nil {
panic(err)
}
return i
}
func (a byTimestamp) Len() int { return len(a) }
func (a byTimestamp) Less(i, j int) bool { return extractAwsTimestamp(a[i]) < extractAwsTimestamp(a[j]) }
func (a byTimestamp) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func getQueueUrlnput(queueName *string, accountID *string) *sqs.GetQueueUrlInput {
var getQueueURLInput sqs.GetQueueUrlInput
if *accountID != "" {
getQueueURLInput = sqs.GetQueueUrlInput{QueueName: queueName, QueueOwnerAWSAccountId: accountID}
} else {
getQueueURLInput = sqs.GetQueueUrlInput{QueueName: queueName}
}
return &getQueueURLInput
}
// collect all the messages from the queue, relying on the visibility timeout
// IMPORTANT the sequence is not ordered!
func readQueue(conn *sqs.SQS, sourceQueueURL *sqs.GetQueueUrlOutput) []*sqs.Message {
var messages []*sqs.Message
waitTimeSeconds := int64(20)
maxNumberOfMessages := int64(10)
// in seconds, set to a minute, then won't appear in the loop
visibilityTimeout := int64(60)
for {
resp, err := conn.ReceiveMessage(&sqs.ReceiveMessageInput{
AttributeNames: aws.StringSlice([]string{"All"}),
MessageAttributeNames: aws.StringSlice([]string{"All"}),
WaitTimeSeconds: &waitTimeSeconds,
MaxNumberOfMessages: &maxNumberOfMessages,
VisibilityTimeout: &visibilityTimeout,
QueueUrl: sourceQueueURL.QueueUrl})
if err != nil {
log.Fatal(err)
// return with empty array of messages in case of failure
return []*sqs.Message{}
}
numberOfMessagesRead := len(resp.Messages)
if numberOfMessagesRead == 0 {
return messages
}
log.Printf("Collecting %v messages", numberOfMessagesRead)
messages = append(messages, resp.Messages...)
}
return messages
}
func requeueMessage(conn *sqs.SQS, sourceQueueURL *sqs.GetQueueUrlOutput, destinationQueueURL *sqs.GetQueueUrlOutput, message *sqs.Message) {
respAdd, errAdd := conn.SendMessage(&sqs.SendMessageInput{
MessageAttributes: message.MessageAttributes,
MessageBody: message.Body,
MessageGroupId: message.Attributes["MessageGroupId"],
QueueUrl: destinationQueueURL.QueueUrl})
if errAdd != nil {
panic(errAdd)
}
log.Printf("Requeued message [%s] -> [%s] to [%s]", *message.MessageId, *respAdd.MessageId, *destinationQueueURL.QueueUrl)
// remove it from the source queue
_, errDel := conn.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: sourceQueueURL.QueueUrl,
ReceiptHandle: message.ReceiptHandle,
})
if errDel != nil {
log.Fatal(errDel)
} else {
log.Printf("Removed message [%s] from [%s]", *message.MessageId, *sourceQueueURL.QueueUrl)
}
}
func main() {
kingpin.MustParse(app.Parse(os.Args[1:]))
destinationQueueName := *queueName
var sourceQueueName string
if *fromQueueName != "" {
sourceQueueName = *fromQueueName
} else {
sourceQueueName = destinationQueueName + "-dead-letter"
}
if messageLimit == nil || *messageLimit == 0 {
*messageLimit = 100
}
log.Printf("Source queue [%s] ", sourceQueueName)
log.Printf("Destination queue [%s] ", destinationQueueName)
log.Printf("Messages to process [%v] ", *messageLimit)
sess, err := session.NewSession()
if err != nil {
log.Fatal(err)
return
}
conn := sqs.New(sess)
sourceQueueURL, err := conn.GetQueueUrl(getQueueUrlnput(&sourceQueueName, accountID))
if err != nil {
log.Fatal(err)
return
}
destinationQueueURL, err := conn.GetQueueUrl(getQueueUrlnput(&destinationQueueName, accountID))
if err != nil {
log.Fatal(err)
return
}
log.Printf("Looking for messages to requeue.")
messages := readQueue(conn, sourceQueueURL)
numberOfMessages := len(messages)
log.Printf("Found [%v] messages to requeue", numberOfMessages)
// sort by order of arrival
sort.Sort(byTimestamp(messages))
for index, element := range messages {
log.Printf("Message[%v] [%s]", index, *element.MessageId)
}
for index, element := range messages {
if index >= *messageLimit {
return
}
log.Println()
messageType := "unknown"
if element.MessageAttributes["Type"] != nil {
messageType = *element.MessageAttributes["Type"].StringValue
}
log.Printf("Requeue message[%v] [%s] type -> %s", index, *element.MessageId, messageType)
requeueMessage(conn, sourceQueueURL, destinationQueueURL, element)
log.Printf("Requeue succeeded for message[%v] [%s]", index, *element.MessageId)
}
}
|
package handler
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jinmukeji/jiujiantang-services/jinmuid/mysqldb"
proto "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/user/v1"
)
// 邮箱验证超时时间
const (
EmailValificationExpiration = time.Minute * 10
ResetPassword = "reset_password"
ModifySecureEmail = "modify_secure_email"
)
// ValidateEmailVerificationCode 验证邮箱验证码是否正确
func (j *JinmuIDService) ValidateEmailVerificationCode(ctx context.Context, req *proto.ValidateEmailVerificationCodeRequest, resp *proto.ValidateEmailVerificationCodeResponse) error {
verificationType, errMapEmailTypeToDB := mapEmailTypeToDB(req.VerificationType)
if verificationType == mysqldb.Unknown || errMapEmailTypeToDB != nil {
return NewError(ErrInvalidValidationType, errors.New("invalid validation type"))
}
user, errFindUserByUserID := j.datastore.FindUserBySecureEmail(ctx, req.Email)
if errFindUserByUserID != nil {
return NewError(ErrInvalidSigninEmail, fmt.Errorf("failed to find user by secure email %s: %s", req.Email, errFindUserByUserID.Error()))
}
// 查找可用的最新的验证码记录
latestRecord, errFindVcRecord := j.datastore.FindLatestVcRecord(ctx, req.Email, verificationType)
if errFindVcRecord != nil {
return NewError(ErrDatabase, fmt.Errorf("failed to find latest vc record by email %s: %s", req.Email, errFindVcRecord.Error()))
}
// 是否过期
if latestRecord.ExpiredAt.Before(time.Now()) {
return NewError(ErrExpiredVcRecord, errors.New("expired vc record"))
}
if !(req.VerificationCode == latestRecord.Code && req.SerialNumber == latestRecord.SN) {
return NewError(ErrInvalidVcRecord, errors.New("invalid vc record"))
}
// TODO: ModifyVcRecordStatus,CreatePhoneOrEmailVerfication 要在同一个事务
// 修改验证码状态
err := j.datastore.ModifyVcRecordStatus(ctx, latestRecord.RecordID)
if err != nil {
return NewError(ErrDatabase, fmt.Errorf("failed to modify vc record status of record %d: %s", latestRecord.RecordID, err.Error()))
}
Vn := uuid.New().String()
now := time.Now()
expiredAt := now.Add(EmailValificationExpiration)
record := &mysqldb.PhoneOrEmailVerfication{
VerificationType: mysqldb.VerificationEmail,
VerificationNumber: Vn,
UserID: user.UserID,
ExpiredAt: &expiredAt,
HasUsed: false,
SendTo: req.Email,
CreatedAt: now.UTC(),
UpdatedAt: now.UTC(),
}
errCreatePhoneOrEmailVerfication := j.datastore.CreatePhoneOrEmailVerfication(ctx, record)
if errCreatePhoneOrEmailVerfication != nil {
return NewError(ErrDatabase, fmt.Errorf("failed to create phone or email verification record of email %s: %s", req.Email, errCreatePhoneOrEmailVerfication.Error()))
}
resp.VerificationNumber = record.VerificationNumber
resp.UserId = user.UserID
return nil
}
func mapEmailTypeToDB(emailType string) (mysqldb.Usage, error) {
switch emailType {
case ResetPassword:
return mysqldb.FindResetPassword, nil
case ModifySecureEmail:
return mysqldb.ModifySecureEmail, nil
}
return mysqldb.Unknown, fmt.Errorf("invalid string email type %s", emailType)
}
|
package main
import (
pb "github.com/micro/services/db/proto"
admin "github.com/micro/services/pkg/service/proto"
"github.com/micro/services/pkg/tracing"
"github.com/micro/services/db/handler"
"github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/logger"
"database/sql"
"github.com/micro/micro/v3/service/config"
_ "github.com/jackc/pgx/v4/stdlib"
)
var dbAddress = "postgresql://postgres:postgres@localhost:5432/db?sslmode=disable"
func main() {
// Create service
srv := service.New(
service.Name("db"),
service.Version("latest"),
)
// Connect to the database
cfg, err := config.Get("micro.db.database")
if err != nil {
logger.Fatalf("Error loading config: %v", err)
}
addr := cfg.String(dbAddress)
sqlDB, err := sql.Open("pgx", addr)
if err != nil {
logger.Fatalf("Failed to open connection to DB %s", err)
}
h := &handler.Db{}
h.DBConn(sqlDB)
// Register handler
pb.RegisterDbHandler(srv.Server(), h)
admin.RegisterAdminHandler(srv.Server(), h)
traceCloser := tracing.SetupOpentracing("db")
defer traceCloser.Close()
// Run service
if err := srv.Run(); err != nil {
logger.Fatal(err)
}
}
|
package ttlib
import (
"fmt"
"github.com/johnnylee/util"
"path/filepath"
"sync"
"time"
)
// PwdHandler provides an interface for requesting user's passwords.
type PwdHandler struct {
mutex sync.RWMutex
hash map[string][]byte
baseDir string
}
func NewPwdHandler(baseDir string) *PwdHandler {
ph := new(PwdHandler)
ph.baseDir = baseDir
ph.hash = make(map[string][]byte)
go ph.fileWatcher()
return ph
}
func (ph *PwdHandler) GetPwdHash(user string) ([]byte, error) {
ph.mutex.RLock()
defer ph.mutex.RUnlock()
hash, ok := ph.hash[user]
if !ok {
return nil, fmt.Errorf("Unknown user: %v", user)
}
return hash, nil
}
// fileWatcher: a state machine that watches for new or removed files. Check
// using gotofsm-verify.
func (ph *PwdHandler) fileWatcher() {
addUsers:
ph.addUsers()
goto deleteUsers
deleteUsers:
ph.deleteUsers()
goto sleep
sleep:
time.Sleep(60 * time.Second)
goto addUsers
}
// addUsers: Used by fileWatcher.
func (ph *PwdHandler) addUsers() {
pattern := filepath.Join(ClientPwdDir(ph.baseDir), "*.json")
matches, err := filepath.Glob(pattern)
if err != nil {
log.Err(err, "Error reading pwd file list")
return
}
for _, path := range matches {
user := filepath.Base(path)
user = user[:len(user)-5]
// Skip known paths.
if _, ok := ph.hash[user]; ok {
continue
}
// Open the password file.
pwdFile, err := LoadPwdFile(ph.baseDir, user)
if err != nil {
log.Err(err, "Error loading password file for user: %v", user)
continue
}
log.Msg("Adding user: %v", user)
ph.mutex.Lock()
ph.hash[user] = pwdFile.PwdHash
ph.mutex.Unlock()
}
}
// deleteUsers: Used by fileWatcher.
func (ph *PwdHandler) deleteUsers() {
for user := range ph.hash {
if !util.FileExists(ClientPwdFile(ph.baseDir, user)) {
log.Msg("Removing user: %v", user)
ph.mutex.Lock()
delete(ph.hash, user)
ph.mutex.Unlock()
}
}
}
|
package dht
import (
"bytes"
"net"
"sync"
"time"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/google/gopacket/routing"
netroute "github.com/libp2p/go-netroute"
ma "github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
dhtcfg "github.com/libp2p/go-libp2p-kad-dht/internal/config"
)
// QueryFilterFunc is a filter applied when considering peers to dial when querying
type QueryFilterFunc = dhtcfg.QueryFilterFunc
// RouteTableFilterFunc is a filter applied when considering connections to keep in
// the local route table.
type RouteTableFilterFunc = dhtcfg.RouteTableFilterFunc
var publicCIDR6 = "2000::/3"
var public6 *net.IPNet
func init() {
_, public6, _ = net.ParseCIDR(publicCIDR6)
}
// isPublicAddr follows the logic of manet.IsPublicAddr, except it uses
// a stricter definition of "public" for ipv6: namely "is it in 2000::/3"?
func isPublicAddr(a ma.Multiaddr) bool {
ip, err := manet.ToIP(a)
if err != nil {
return false
}
if ip.To4() != nil {
return !inAddrRange(ip, manet.Private4) && !inAddrRange(ip, manet.Unroutable4)
}
return public6.Contains(ip)
}
// isPrivateAddr follows the logic of manet.IsPrivateAddr, except that
// it uses a stricter definition of "public" for ipv6
func isPrivateAddr(a ma.Multiaddr) bool {
ip, err := manet.ToIP(a)
if err != nil {
return false
}
if ip.To4() != nil {
return inAddrRange(ip, manet.Private4)
}
return !public6.Contains(ip) && !inAddrRange(ip, manet.Unroutable6)
}
// PublicQueryFilter returns true if the peer is suspected of being publicly accessible
func PublicQueryFilter(_ interface{}, ai peer.AddrInfo) bool {
if len(ai.Addrs) == 0 {
return false
}
var hasPublicAddr bool
for _, a := range ai.Addrs {
if !isRelayAddr(a) && isPublicAddr(a) {
hasPublicAddr = true
}
}
return hasPublicAddr
}
type hasHost interface {
Host() host.Host
}
var _ QueryFilterFunc = PublicQueryFilter
// PublicRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate
// that it is on a public network
func PublicRoutingTableFilter(dht interface{}, p peer.ID) bool {
d := dht.(hasHost)
conns := d.Host().Network().ConnsToPeer(p)
if len(conns) == 0 {
return false
}
// Do we have a public address for this peer?
id := conns[0].RemotePeer()
known := d.Host().Peerstore().PeerInfo(id)
for _, a := range known.Addrs {
if !isRelayAddr(a) && isPublicAddr(a) {
return true
}
}
return false
}
var _ RouteTableFilterFunc = PublicRoutingTableFilter
// PrivateQueryFilter doens't currently restrict which peers we are willing to query from the local DHT.
func PrivateQueryFilter(_ interface{}, ai peer.AddrInfo) bool {
return len(ai.Addrs) > 0
}
var _ QueryFilterFunc = PrivateQueryFilter
// We call this very frequently but routes can technically change at runtime.
// Cache it for two minutes.
const routerCacheTime = 2 * time.Minute
var routerCache struct {
sync.RWMutex
router routing.Router
expires time.Time
}
func getCachedRouter() routing.Router {
routerCache.RLock()
router := routerCache.router
expires := routerCache.expires
routerCache.RUnlock()
if time.Now().Before(expires) {
return router
}
routerCache.Lock()
defer routerCache.Unlock()
now := time.Now()
if now.Before(routerCache.expires) {
return router
}
routerCache.router, _ = netroute.New()
routerCache.expires = now.Add(routerCacheTime)
return router
}
// PrivateRoutingTableFilter allows a peer to be added to the routing table if the connections to that peer indicate
// that it is on a private network
func PrivateRoutingTableFilter(dht interface{}, p peer.ID) bool {
d := dht.(hasHost)
conns := d.Host().Network().ConnsToPeer(p)
return privRTFilter(d, conns)
}
func privRTFilter(dht interface{}, conns []network.Conn) bool {
d := dht.(hasHost)
h := d.Host()
router := getCachedRouter()
myAdvertisedIPs := make([]net.IP, 0)
for _, a := range h.Addrs() {
if isPublicAddr(a) && !isRelayAddr(a) {
ip, err := manet.ToIP(a)
if err != nil {
continue
}
myAdvertisedIPs = append(myAdvertisedIPs, ip)
}
}
for _, c := range conns {
ra := c.RemoteMultiaddr()
if isPrivateAddr(ra) && !isRelayAddr(ra) {
return true
}
if isPublicAddr(ra) {
ip, err := manet.ToIP(ra)
if err != nil {
continue
}
// if the ip is the same as one of the local host's public advertised IPs - then consider it local
for _, i := range myAdvertisedIPs {
if i.Equal(ip) {
return true
}
if ip.To4() == nil {
if i.To4() == nil && isEUI(ip) && sameV6Net(i, ip) {
return true
}
}
}
// if there's no gateway - a direct host in the OS routing table - then consider it local
// This is relevant in particular to ipv6 networks where the addresses may all be public,
// but the nodes are aware of direct links between each other.
if router != nil {
_, gw, _, err := router.Route(ip)
if gw == nil && err == nil {
return true
}
}
}
}
return false
}
var _ RouteTableFilterFunc = PrivateRoutingTableFilter
func isEUI(ip net.IP) bool {
// per rfc 2373
return len(ip) == net.IPv6len && ip[11] == 0xff && ip[12] == 0xfe
}
func sameV6Net(a, b net.IP) bool {
//lint:ignore SA1021 We're comparing only parts of the IP address here.
return len(a) == net.IPv6len && len(b) == net.IPv6len && bytes.Equal(a[0:8], b[0:8]) //nolint
}
func isRelayAddr(a ma.Multiaddr) bool {
found := false
ma.ForEach(a, func(c ma.Component) bool {
found = c.Protocol().Code == ma.P_CIRCUIT
return !found
})
return found
}
func inAddrRange(ip net.IP, ipnets []*net.IPNet) bool {
for _, ipnet := range ipnets {
if ipnet.Contains(ip) {
return true
}
}
return false
}
|
//author xinbing
//time 2018/9/4 17:17
package db
import (
"github.com/go-redis/redis"
"github.com/sirupsen/logrus"
"time"
)
var RedisClient *redis.Client
func InitRedis(redisConfig *RedisConfig) {
RedisClient = redis.NewClient(&redis.Options{
Addr: redisConfig.RedisAddr,
Password: redisConfig.RedisPwd, // no password set
DB: redisConfig.RedisDB, // use default DB
})
_, err := RedisClient.Ping().Result()
if err != nil {
logrus.WithField("addr",redisConfig.RedisAddr).Errorln("ping redis error!")
}
go redisTimer(redisConfig)
}
func redisTimer(redisConfig *RedisConfig) {
redisTicker := time.NewTicker(20 * time.Second)
for {
select {
case <-redisTicker.C:
_, err := RedisClient.Ping().Result()
if err != nil {
logrus.Errorln("redis connect fail,err:", err)
InitRedis(redisConfig)
}
}
}
}
|
package fakes
import (
"io/ioutil"
"net/http"
"strings"
)
type FakeHTTPClient struct {
PostInputs []postInput
postOutputs []postOutput
GetInputs []getInput
getOutputs []getOutput
}
type postInput struct {
Payload []byte
Endpoint string
}
type postOutput struct {
response *http.Response
err error
}
type getInput struct {
Endpoint string
}
type getOutput struct {
response *http.Response
err error
}
func NewFakeHTTPClient() *FakeHTTPClient {
return &FakeHTTPClient{
postOutputs: []postOutput{},
getOutputs: []getOutput{},
}
}
func (c *FakeHTTPClient) Post(endpoint string, payload []byte) (*http.Response, error) {
c.PostInputs = append(c.PostInputs, postInput{
Payload: payload,
Endpoint: endpoint,
})
postReturn := c.postOutputs[0]
c.postOutputs = c.postOutputs[1:]
return postReturn.response, postReturn.err
}
func (c *FakeHTTPClient) Get(endpoint string) (*http.Response, error) {
c.GetInputs = append(c.GetInputs, getInput{
Endpoint: endpoint,
})
getReturn := c.getOutputs[0]
c.getOutputs = c.getOutputs[1:]
return getReturn.response, getReturn.err
}
func (c *FakeHTTPClient) SetPostBehavior(body string, statusCode int, err error) {
postResponse := &http.Response{
Body: ioutil.NopCloser(strings.NewReader(body)),
StatusCode: statusCode,
}
c.postOutputs = append(c.postOutputs, postOutput{
response: postResponse,
err: err,
})
}
func (c *FakeHTTPClient) SetGetBehavior(body string, statusCode int, err error) {
getResponse := &http.Response{
Body: ioutil.NopCloser(strings.NewReader(body)),
StatusCode: statusCode,
}
c.getOutputs = append(c.getOutputs, getOutput{
response: getResponse,
err: err,
})
}
|
package piper
import (
"context"
"fmt"
"sync"
)
// Pipeline is an object used for chaining multiple Processes together sequentially
type Pipeline struct {
// required
name string // Name of the pipeline
processes []*Process // Processes that make up the pipeline arranged in order that they should be run
// configurable
wg *sync.WaitGroup // used to wait until data processing is complete
// internal
exec executable // mechanism for starting / stopping
}
// NewPipeline creates a pointer to a Pipeline
func NewPipeline(name string, processes []*Process, fns ...PipelineOptionFn) (*Pipeline, error) {
if len(processes) < 2 {
return nil, fmt.Errorf("Pipelines require at least 2 processes, got [%d] process(es)", len(processes))
}
p := &Pipeline{
name: name,
processes: processes,
wg: &sync.WaitGroup{},
}
p.exec = newExec(p.startFn, p.stopFn)
// Apply functional options
for _, fn := range fns {
fn(p)
}
return p, nil
}
// PipelineOptionFn is a method signature used for configuring the configurable fields of Pipeline
type PipelineOptionFn func(p *Pipeline)
func PipelineWithWaitGroup(wg *sync.WaitGroup) PipelineOptionFn {
return func(p *Pipeline) {
p.wg = wg
}
}
// startFn defines the startup procedure for a Pipeline
func (p *Pipeline) startFn(ctx context.Context) {
// Chain the processes together by adding the next Process's processData callback function
// as an OnSuccessFn for the previous Process
for i, process := range p.processes {
if i > 0 {
func(processPtr *Process) {
p.processes[i-1].pushOnSuccessFns(func(data DataIF) []DataIF {
processPtr.ProcessData(data)
return []DataIF{}
})
}(process)
}
}
for _, process := range p.processes {
// Make all of the processes share the same WaitGroup
process.setWaitGroup(p.wg)
// Then start the all the process
process.exec.start(ctx)
}
}
// stopFn defines the shutdown procedure for a Pipeline
func (p *Pipeline) stopFn(ctx context.Context) {
for _, process := range p.processes {
process.exec.stop(ctx)
}
}
// Start is used to trigger the Pipeline's startup sequence
func (p *Pipeline) Start(ctx context.Context) {
p.exec.start(ctx)
}
// Stop is used to trigger the Pipeline's shutdown sequence
func (p *Pipeline) Stop(ctx context.Context) {
p.exec.stop(ctx)
}
// ProcessData puts data on the queue for batch processing. The processing is a synchronous
// operation, so the method returns as soon as the job is put on the queue, which should be
// almost instantly assuming the number of jobs in the queue is less than the queue depth.
func (p *Pipeline) ProcessData(data DataIF) {
p.processes[0].ProcessData(data)
}
// ProcessDataAsync puts data on the queue for batch processing and waits for the job to finish
// before returning. It only makes sense to use this method if there is one data point to process.
// To optimize performance when using this method, set the maxBatchSize to 1.
func (p *Pipeline) ProcessDataAsync(data DataIF) {
p.ProcessData(data)
p.wg.Wait()
}
// ProcessDatum puts all data on the queue for batch processing. The process is a synchronous
// operation, so the method returns as soon as the jobs are put on the queue, which should be
// almost instantly assuming the number of jobs in the queue is less than the queue depth.
func (p *Pipeline) ProcessDatum(datum []DataIF) {
p.processes[0].ProcessDatum(datum)
}
// ProcessDatumAsync puts all data on the queue for batch processing and waits until all data has
// been processed.
func (p *Pipeline) ProcessDatumAsync(datum []DataIF) {
p.processes[0].ProcessDatumAsync(datum)
}
|
package main
import (
"github.com/Depado/ginprom"
"github.com/gin-gonic/contrib/cors"
"github.com/gin-gonic/gin"
"github.com/janwiemers/up/handler"
"github.com/janwiemers/up/helper"
"github.com/janwiemers/up/models"
"github.com/janwiemers/up/monitors"
"github.com/janwiemers/up/websockets"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
func init() {
helper.InitViperConfig()
log.SetFormatter(&log.JSONFormatter{})
log.SetReportCaller(true)
log.SetLevel(log.InfoLevel)
}
func loadAndInitialzeConfigs() {
monitorConfigs := []models.Application{}
err := yaml.Unmarshal(helper.ReadFile(viper.GetString("MONITOR_FILE_PATH")), &monitorConfigs)
if err != nil {
log.Fatalf("error: %v", err)
}
monitors.InitAllMonitors(monitorConfigs)
monitors.Cleanup(monitorConfigs)
}
func main() {
loadAndInitialzeConfigs()
go helper.Cleanup()
websockets.HubInstance = websockets.NewHub()
go websockets.HubInstance.Run()
gin.DisableConsoleColor()
r := gin.New()
config := cors.DefaultConfig()
config.AllowAllOrigins = true
p := ginprom.New(
ginprom.Engine(r),
ginprom.Subsystem("gin"),
ginprom.Path("/metrics"),
)
r.Use(p.Instrument())
r.Use(cors.New(config))
r.Use(gin.Recovery())
handler.SetupRouter(r)
r.Run(":" + viper.GetString("PORT"))
}
|
/*
* Copyright 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 config_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
"github.com/cloudfoundry-community/stackdriver-tools/src/stackdriver-nozzle/config"
)
var _ = Describe("Config", func() {
BeforeEach(func() {
os.Setenv("FIREHOSE_ENDPOINT", "https://api.example.com")
os.Setenv("FIREHOSE_EVENTS", "LogMessage")
os.Setenv("FIREHOSE_USERNAME", "admin")
os.Setenv("FIREHOSE_PASSWORD", "monkey123")
os.Setenv("FIREHOSE_SKIP_SSL", "true")
os.Setenv("FIREHOSE_SUBSCRIPTION_ID", "my-subscription-id")
os.Setenv("FIREHOSE_NEWLINE_TOKEN", "∴")
os.Setenv("GCP_PROJECT_ID", "test")
})
It("returns valid config from environment", func() {
c, err := config.NewConfig()
Expect(err).To(BeNil())
Expect(c.APIEndpoint).To(Equal("https://api.example.com"))
})
DescribeTable("required values aren't empty", func(envName string) {
os.Setenv(envName, "")
_, err := config.NewConfig()
Expect(err).NotTo(BeNil())
Expect(err.Error()).To(ContainSubstring(envName))
},
Entry("FIREHOSE_ENDPOINT", "FIREHOSE_ENDPOINT"),
Entry("FIREHOSE_EVENTS", "FIREHOSE_EVENTS"),
Entry("FIREHOSE_SUBSCRIPTION_ID", "FIREHOSE_SUBSCRIPTION_ID"),
)
})
|
// Copyright 2022 PingCAP, 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 funcdep_test
import (
"testing"
"github.com/pingcap/tidb/testkit"
"github.com/stretchr/testify/require"
)
func TestOnlyFullGroupByOldCases(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("set @@session.tidb_enable_new_only_full_group_by_check = 'on';")
// test case 1
tk.MustExec("use test")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("drop view if exists v1")
tk.MustExec("CREATE TABLE t1 ( c1 INT, c2 INT, c4 DATE, c5 VARCHAR(1));")
tk.MustExec("CREATE TABLE t2 ( c1 INT, c2 INT, c3 INT, c5 VARCHAR(1));")
tk.MustExec("CREATE VIEW v1 AS SELECT alias1.c4 AS field1 FROM t1 AS alias1 INNER JOIN t1 AS alias2 ON 1 GROUP BY field1 ORDER BY alias1.c5;")
_, err := tk.Exec("SELECT * FROM v1;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.alias1.c5' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
// test case 2
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("drop view if exists v1")
tk.MustExec("CREATE TABLE t1 (c1 INT, c2 INT, c4 DATE, c5 VARCHAR(1));")
tk.MustExec("CREATE TABLE t2 (c1 INT, c2 INT, c3 INT, c5 VARCHAR(1));")
tk.MustExec("CREATE definer='root'@'localhost' VIEW v1 AS SELECT alias1.c4 AS field1, alias1.c4 AS field2 FROM t1 AS alias1 INNER JOIN t1 AS alias2 ON (alias2.c1 = alias1.c2) WHERE ( NOT EXISTS ( SELECT SQ1_alias1.c5 AS SQ1_field1 FROM t2 AS SQ1_alias1 WHERE SQ1_alias1.c3 < alias1.c1 )) AND (alias1.c5 = alias1.c5 AND alias1.c5 = 'd' ) GROUP BY field1, field2 ORDER BY alias1.c5, field1, field2")
tk.MustQuery("SELECT * FROM v1;")
// test case 3
// need to resolve the name resolver problem first (view and base table's column can not refer each other)
// see some cases in 21
// test case 4
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("drop view if exists v2")
tk.MustExec("CREATE TABLE t1 ( col_varchar_10_utf8 VARCHAR(10) CHARACTER SET utf8, col_int_key INT, pk INT PRIMARY KEY);")
tk.MustExec("CREATE TABLE t2 ( col_varchar_10_utf8 VARCHAR(10) CHARACTER SET utf8 DEFAULT NULL, col_int_key INT DEFAULT NULL, pk INT PRIMARY KEY);")
tk.MustExec("CREATE ALGORITHM=MERGE definer='root'@'localhost' VIEW v2 AS SELECT t2.pk, COALESCE(t2.pk, 3) AS coa FROM t1 LEFT JOIN t2 ON 0;")
tk.MustQuery("SELECT v2.pk, v2.coa FROM t1 LEFT JOIN v2 AS v2 ON 0 GROUP BY v2.pk;")
// test case 5
tk.MustExec("drop table if exists t")
tk.MustExec("CREATE TABLE t ( a INT, c INT GENERATED ALWAYS AS (a+2), d INT GENERATED ALWAYS AS (c+2) );")
tk.MustQuery("SELECT c FROM t GROUP BY a;")
tk.MustQuery("SELECT d FROM t GROUP BY c;")
tk.MustQuery("SELECT d FROM t GROUP BY a;")
tk.MustQuery("SELECT 1+c FROM t GROUP BY a;")
tk.MustQuery("SELECT 1+d FROM t GROUP BY c;")
tk.MustQuery("SELECT 1+d FROM t GROUP BY a;")
tk.MustQuery("SELECT t1.d FROM t as t1, t as t2 WHERE t2.d=t1.c GROUP BY t2.a;")
_, err = tk.Exec("SELECT t1.d FROM t as t1, t as t2 WHERE t2.d>t1.c GROUP BY t2.a;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t1.d' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
// test case 6
tk.MustExec("drop table if exists t")
tk.MustExec("CREATE TABLE t ( a INT, c INT GENERATED ALWAYS AS (a+2), d INT GENERATED ALWAYS AS (c+2) );")
_, err = tk.Exec("SELECT t1.d FROM t as t1, t as t2 WHERE t2.d>t1.c GROUP BY t2.a;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t1.d' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
_, err = tk.Exec("SELECT (SELECT t1.c FROM t as t1 GROUP BY -3) FROM t as t2;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t1.c' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
_, err = tk.Exec("SELECT DISTINCT t1.a FROM t as t1 ORDER BY t1.d LIMIT 1;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:3065]Expression #1 of ORDER BY clause is not in SELECT list, references column 'test.t.d' which is not in SELECT list; this is incompatible with DISTINCT")
_, err = tk.Exec("SELECT DISTINCT t1.a FROM t as t1 ORDER BY t1.d LIMIT 1;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:3065]Expression #1 of ORDER BY clause is not in SELECT list, references column 'test.t.d' which is not in SELECT list; this is incompatible with DISTINCT")
_, err = tk.Exec("SELECT (SELECT DISTINCT t1.a FROM t as t1 ORDER BY t1.d LIMIT 1) FROM t as t2;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:3065]Expression #1 of ORDER BY clause is not in SELECT list, references column 'test.t.d' which is not in SELECT list; this is incompatible with DISTINCT")
// test case 7
tk.MustExec("drop table if exists t")
tk.MustExec("CREATE TABLE t(a INT NULL, b INT NOT NULL, c INT, UNIQUE(a,b));")
tk.MustQuery("SELECT a,b,c FROM t WHERE a IS NOT NULL GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE NOT (a IS NULL) GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a > 3 GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a = 3 GROUP BY b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a BETWEEN 3 AND 6 GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a <> 3 GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a IN (3,4) GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a IN (SELECT b FROM t) GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a IS TRUE GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE (a <> 3) IS TRUE GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a IS FALSE GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE (a <> 3) IS FALSE GROUP BY a,b;")
tk.MustQuery("SELECT a,b,c FROM t WHERE a LIKE \"%abc%\" GROUP BY a,b;")
// todo: eval not-null refuse NOT wrapper.
// tk.MustQuery("SELECT a,b,c FROM t WHERE NOT(a IN (3,4)) GROUP BY a,b;")
// tk.MustQuery("SELECT a,b,c FROM t WHERE a NOT IN (3,4) GROUP BY a,b;")
// tk.MustQuery("SELECT a,b,c FROM t WHERE a NOT LIKE \"%abc%\" GROUP BY a,b;")
_, err = tk.Exec("SELECT a,b,c FROM t WHERE a<=>NULL GROUP BY b;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t.c' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
// is-not-true will let the null value pass, so evaluating it won't derive to a with not-null attribute.
_, err = tk.Exec("SELECT a,b,c FROM t WHERE a IS NOT TRUE GROUP BY a,b;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t.c' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
// test case 8
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("drop table if exists t3")
tk.MustExec("CREATE TABLE t1 (a INT, b INT);")
tk.MustExec("CREATE TABLE t2 (b INT);")
tk.MustExec("CREATE TABLE t3 (b INT NULL, c INT NULL, d INT NULL, e INT NULL, UNIQUE KEY (b,d,e));")
tk.MustQuery("SELECT * FROM t1, t2, t3 WHERE t2.b = t1.b AND t2.b = t3.b AND t3.d = 1 AND t3.e = 1 AND t3.d IS NOT NULL AND t1.a = 2 GROUP BY t1.b;")
// test case 9
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1(a int, b int not null, c int not null, d int, unique key(b,c), unique key(b,d));")
_, err = tk.Exec("select (select sin(a)) as z from t1 group by d,b;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'z' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
// test case 10 & 11
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1(a int, b int not null, c int not null, d int, unique key(b,c), unique key(b,d));")
tk.MustExec("select t3.a from t1, t1 as t2, t1 as t3 where t3.b=t2.b and t3.c=t1.d and t2.b=t1.b and t2.c=t1.c group by t1.b,t1.c")
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t3")
tk.MustExec("create table t1(a int, b int not null, c int not null, d int, unique key(b,c), unique key(b,d));")
tk.MustExec("create table t3(pk int primary key, b int);")
tk.MustQuery("select t3.b from t1,t1 as t2,t3 where t3.pk=t2.d and t2.b=t1.b and t2.c=t1.a group by t1.b,t1.c;")
// test case 12
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t1(a int,b int not null,c int not null,d int, unique key(b,c), unique key(b,d));")
tk.MustExec("create table t2 like t1")
tk.MustQuery("select t1.a,t2.c from t1 left join t2 on t1.a=t2.c and cos(t2.c+t2.b)>0.5 and sin(t1.a+t2.d)<0.9 group by t1.a;")
tk.MustQuery("select t1.a,t2.d from t1 left join t2 on t1.a=t2.c and t1.d=t2.b and cos(t2.c+t2.b)>0.5 and sin(t1.a+t2.d)<0.9 group by t1.a,t1.d;")
// test case 17
tk.MustExec("drop table if exists customer1")
tk.MustExec("drop table if exists customer2")
tk.MustExec("drop view if exists customer")
tk.MustExec("create table customer1(pk int primary key, a int);")
tk.MustExec("create table customer2(pk int primary key, b int);")
tk.MustExec("CREATE algorithm=merge definer='root'@'localhost' VIEW customer as SELECT pk,a,b FROM customer1 JOIN customer2 USING (pk);")
tk.MustQuery("select customer.pk, customer.b from customer group by customer.pk;")
// classic cases
tk.MustQuery("select customer1.a, count(*) from customer1 left join customer2 on customer1.a=customer2.b where customer2.pk in (7,9) group by customer2.b;")
tk.MustQuery("select customer1.a, count(*) from customer1 left join customer2 on customer1.a=1 where customer2.pk in (7,9) group by customer2.b;")
// c2.pk reject the null from both inner side of the left join.
tk.MustQuery("select c1.a, count(*) from customer2 c3 left join (customer1 c1 left join customer2 c2 on c1.a=c2.b) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
tk.MustQuery("select c3.b, count(*) from customer2 c3 left join (customer1 c1 left join customer2 c2 on c1.a=1) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
tk.MustQuery("select c1.a, count(*) from customer2 c3 left join (customer1 c1 left join customer2 c2 on c1.a=1) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
tk.MustQuery("select c1.a, c3.b, count(*) from customer2 c3 left join (customer1 c1 left join customer2 c2 on c1.a=1) on c3.b=1 where c2.pk in (7,9) group by c2.b;")
// inner join nested with outer join.
tk.MustQuery("select c1.a, c3.b, count(*) from customer2 c3 join (customer1 c1 left join customer2 c2 on c1.a=1) on c3.b=1 where c2.pk in (7,9) group by c2.b;")
tk.MustQuery("select c1.a, c3.b, count(*) from customer2 c3 join (customer1 c1 left join customer2 c2 on c1.a=1) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
tk.MustQuery("select c1.a, c3.b, count(*) from customer2 c3 join (customer1 c1 left join customer2 c2 on c1.a=c2.b) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
// outer join nested with inner join.
// TODO: inner side's strict FD and equiv FD can be saved.
//tk.MustQuery("select c1.a, c3.b, count(*) from customer2 c3 left join (customer1 c1 inner join customer2 c2 on c1.a=c2.b) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
//tk.MustQuery("select c1.a, c3.b, count(*) from customer2 c3 left join (customer1 c1 inner join customer2 c2 on c1.a=1) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
//tk.MustQuery("select c1.a, c3.b, count(*) from customer2 c3 left join (customer1 c1 inner join customer2 c2 on c1.a=1 and c1.a=c2.b) on c3.b=c1.a where c2.pk in (7,9) group by c2.b;")
tk.MustExec("drop view if exists customer")
// this left join can extend left pk to all cols.
tk.MustExec("CREATE algorithm=merge definer='root'@'localhost' VIEW customer as SELECT pk,a,b FROM customer1 LEFT JOIN customer2 USING (pk);")
tk.MustQuery("select customer.pk, customer.b from customer group by customer.pk;")
// test case 18
tk.MustExec("drop table if exists t1")
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t1(pk int primary key, a int);")
tk.MustExec("create table t2(pk int primary key, b int);")
tk.MustQuery("select t1.pk, t2.b from t1 join t2 on t1.pk=t2.pk group by t1.pk;")
tk.MustQuery("select t1.pk, t2.b from t1 join t2 using(pk) group by t1.pk;")
tk.MustQuery("select t1.pk, t2.b from t1 natural join t2 group by t1.pk;")
tk.MustQuery("select t1.pk, t2.b from t1 left join t2 using(pk) group by t1.pk;")
tk.MustQuery("select t1.pk, t2.b from t1 natural left join t2 group by t1.pk;")
tk.MustQuery("select t1.pk, t2.b from t2 right join t1 using(pk) group by t1.pk;")
tk.MustQuery("select t1.pk, t2.b from t2 natural right join t1 group by t1.pk;")
// test case 20
tk.MustExec("drop table t1")
tk.MustExec("create table t1(pk int primary key, a int);")
tk.MustQuery("select t3.a from t1 left join (t1 as t2 left join t1 as t3 on 1) on 1 group by t3.pk;")
tk.MustQuery("select (select t1.a from t1 as t2 limit 1) from t1 group by pk;")
// test case 21
tk.MustExec("drop table if exists t1, t2")
tk.MustExec("create table t1(a int, b int);")
// TODO: to be fixed.
//tk.MustExec("drop view if exists v1;")
//tk.MustExec("create view v1 as select a as a, 2*a as b, coalesce(a,3) as c from t1;")
//err = tk.ExecToErr("select v1.b from t1 left join v1 on 1 group by v1.a")
//require.NotNil(t, err)
//require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'z' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
tk.MustExec("create table t2(c int, d int);")
err = tk.ExecToErr("select t4.d from t1 left join (t2 as t3 join t2 as t4 on t4.d=3) on t1.a=10 group by \"\";")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t4.d' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
tk.MustExec("select t4.d from t1 join (t2 as t3 left join t2 as t4 on t4.d=3) on t1.a=10 group by \"\";")
err = tk.ExecToErr("select t4.d from t1 join (t2 as t3 left join t2 as t4 on t4.d=3 and t4.c+t3.c=2) on t1.a=10 group by \"\";")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t4.d' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
//tk.MustExec("drop table t1")
//tk.MustExec("drop view v1")
//tk.MustExec("create table t1(a int not null, b int)")
//tk.MustExec("create view v1 as select a as a, 2*a as b, coalesce(a,3) as c from t1")
//tk.MustExec("select v1.b from t1 left join v1 on 1 group by v1.a")
// test issue #25196
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1 (i1 integer, c1 integer);")
tk.MustExec("insert into t1 values (2, 41), (1, 42), (3, 43), (0, null);")
tk.MustExec("drop table if exists t2")
tk.MustExec("create table t2 (i2 integer, c2 integer, f2 float);")
tk.MustExec("insert into t2 values (0, 43, null), (1, null, 0.1), (3, 42, 0.01), (2, 73, 0.12), (null, 41, -0.1), (null, null, null);")
err = tk.ExecToErr("SELECT * FROM t2 AS _tmp_1 JOIN (SELECT max(_tmp_3.f2) AS _tmp_4,min(_tmp_3.i2) AS _tmp_5 FROM t2 AS _tmp_3 WHERE _tmp_3.f2>=_tmp_3.c2 GROUP BY _tmp_3.c2 ORDER BY _tmp_3.i2) AS _tmp_2 WHERE _tmp_2._tmp_5=100;")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test._tmp_3.i2' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
// test issue #22301 and #33056
tk.MustExec("drop table if exists t1, t2")
tk.MustExec("create table t1 (a int);")
tk.MustExec("create table t2 (a int, b int);")
tk.MustQuery("select t1.a from t1 join t2 on t2.a=t1.a group by t2.a having min(t2.b) > 0;")
tk.MustQuery("select t2.a, count(t2.b) from t1 join t2 using (a) where t1.a = 1;")
tk.MustQuery("select count(t2.b) from t1 join t2 using (a) order by t2.a;")
// test issue #30024
tk.MustExec("drop table if exists t1,t2;")
tk.MustExec("CREATE TABLE t1 (a INT, b INT, c INT DEFAULT 0);")
tk.MustExec("INSERT INTO t1 (a, b) VALUES (3,3), (2,2), (3,3), (2,2), (3,3), (4,4);")
tk.MustExec("CREATE TABLE t2 (a INT, b INT, c INT DEFAULT 0);")
tk.MustExec("INSERT INTO t2 (a, b) VALUES (3,3), (2,2), (3,3), (2,2), (3,3), (4,4);")
tk.MustQuery("SELECT t1.a FROM t1 GROUP BY t1.a HAVING t1.a IN (SELECT t2.a FROM t2 ORDER BY SUM(t1.b));")
// a normal case
tk.MustExec("drop table if exists t1")
tk.MustExec("create table t1(a int not null, b int not null, index(a))")
err = tk.ExecToErr("select b from t1 group by a")
require.NotNil(t, err)
require.Equal(t, err.Error(), "[planner:1055]Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.t1.b' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
}
|
// A goroutine is a lightweight thread managed by the Go runtime.
// The evaluation of f, x, y, and z happens in the current goroutine
// and the execution of f happens in the new goroutine.
// Goroutines run in the same address space,
// so access to shared memory must be synchronized.
// The sync package provides useful primitives,
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
|
// Copyright 2023 beego-dev
//
// 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 main
import (
"context"
"fmt"
"github.com/beego/beego/v2/client/cache"
"time"
)
func main() {
c := cache.NewMemoryCache()
c, err := cache.NewBloomFilterCache(c, func(ctx context.Context, key string) (any, error) {
return fmt.Sprintf("hello, %s", key), nil
}, &AlwaysExist{}, time.Minute)
if err != nil {
panic(err)
}
val, err := c.Get(context.Background(), "Beego")
if err != nil {
panic(err)
}
fmt.Println(val)
}
type AlwaysExist struct {
}
func (a *AlwaysExist) Test(data string) bool {
return true
}
func (a *AlwaysExist) Add(data string) {
}
|
package main
import (
"fmt"
)
func main() {
capitals := make(map[string]string, 3)
capitals["Japan"] = "Tokyo"
capitals["US"] = "Washington D. C."
capitals["China"] = "Beijing"
for k, v := range capitals {
fmt.Printf("%v: %v\n", k, v)
}
// キーの存在確認
capital, ok := capitals["UK"]
if ok {
fmt.Println("registered", capital)
} else {
fmt.Println("unregistered")
}
}
|
package jwt
import (
"backend/utils/common"
"backend/utils/logging"
"backend/utils/response"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func JWT() gin.HandlerFunc {
return func(c *gin.Context) {
var code int
var data interface{}
var token string
code = response.SUCCESS
token = c.Query("token")
if token == "" {
token = c.Request.Header.Get("Authorization")
}
logging.Info("token is %s", token)
if token == "" {
code = response.ErrorAuth
} else {
claims, err := common.ParseToken(token)
if err != nil {
code = response.ErrorAuthCheckTokenFail
} else if time.Now().Unix() > claims.ExpiresAt {
code = response.ErrorAuthCheckTokenTimeout
}
if claims != nil {
c.Set("username", claims.Username)
c.Set("userId", claims.UserId)
}
}
if code != response.SUCCESS {
c.JSON(http.StatusUnauthorized, gin.H{
"code": code,
"msg": response.Msg[code],
"data": data,
})
c.Abort()
return
}
logging.Info("token认证成功")
c.Next()
}
}
|
package assertion
// Interface for Stubs
type Stuber interface {
CallCount(string) CallCount
Register(string)
}
// Struct for containin the function call count data
type CallCount struct {
funcName string
callCount int
}
func NewStub() *Stub {
callCount := make([]CallCount, 0)
stub := Stub{callCount}
return &stub
}
// Stub Object. Defines the CallCount and Register functions.
type Stub struct {
callCount []CallCount
}
// Fetch all of the function calls and counts
func (stub *Stub) CallCount(name string) CallCount {
for index := range stub.callCount {
if stub.callCount[index].funcName == name {
return stub.callCount[index]
}
}
return CallCount{name, 0}
}
// Register a function call with the stuber
func (stub *Stub) Register(name string) {
for index := range stub.callCount {
if stub.callCount[index].funcName == name {
stub.callCount[index].callCount++
return
}
}
callCount := CallCount{name, 1}
stub.callCount = append(stub.callCount, callCount)
}
|
package main
import (
"code.huawei.com/server/serve"
)
func main() {
serve.Serve()
}
|
package services
import (
"goChat/Server/db"
"goChat/Server/models"
"goChat/Server/utils"
"goChat/Server/viewModels"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
// MessageService - MessageService
type MessageService struct {
repo db.IMessageRepository
}
// NewMessageService - Creates new instance of MessageService
func NewMessageService(repository db.IMessageRepository) *MessageService {
return &MessageService{
repo: repository,
}
}
// AddMessage - AddMessage
func (svc *MessageService) AddMessage(message models.Message) error {
return svc.repo.AddMessage(message)
}
// GetMessageHandler - Gets the message for conversation Id
func (svc *MessageService) GetMessageHandler(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r)
convID := args["conversationId"]
skip, err := strconv.Atoi(args["skip"])
if err != nil {
skip = 0
}
count, err := strconv.Atoi(args["count"])
if err != nil {
count = 10
}
msgList, err := svc.repo.GetMessagesByConversation(convID, skip, count)
if err != nil {
utils.JSONInternalServerErrorResponse(w, err)
return
}
var resultMsg []viewModels.Message
for _, m := range msgList {
resultMsg = append(resultMsg, utils.ConvertToViewModelMessage(m))
}
utils.JSONSuccessResponse(w, resultMsg)
}
// UpdateMessageAsRead - UpdateMessageAsRead
func (svc *MessageService) UpdateMessageAsRead(w http.ResponseWriter, r *http.Request) {
args := mux.Vars(r)
user := r.Context().Value(utils.RequestContextKeyUser).(models.User)
msgId := args["messageId"]
go svc.repo.UpdateMessageAsRead(msgId, user.ID)
utils.JSONSuccessResponse(w, nil)
}
|
// Copyright 2017 Yahoo Holdings Inc.
// Licensed under the terms of the 3-Clause BSD License.
package provider
import (
"fmt"
"strings"
"k8s.io/api/extensions/v1beta1"
"k8s.io/client-go/tools/cache"
)
var (
helper *Helper
)
// Helper class that provides common validation funcs and a handle to
// ingress claim provider implementations
type Helper struct {
providers map[string]Provider
indexer cache.Indexer
}
// init sets-up the provider instances
func init() {
helper = &Helper{
providers: map[string]Provider{
ATS: NewATSProvider(),
Istio: NewIstioProvider(),
},
}
}
// GetHelper returns the singleton helper instance
func GetHelper() *Helper {
return helper
}
// GetDefaultProvider returns the default ingress claim provider instance
func (h *Helper) GetDefaultProvider() Provider {
return h.providers[ATS]
}
// GetProvider returns the provider instance corresponding to the given ingress resource
func (h *Helper) GetProvider(ingress *v1beta1.Ingress) Provider {
for _, provider := range h.providers {
if provider.ServesIngress(ingress) {
return provider
}
}
return h.GetDefaultProvider()
}
// GetProviderByName returns a handle to the provider instance by the provider name
func (h *Helper) GetProviderByName(name string) Provider {
return h.providers[name]
}
// SetIndexer allows to set the cache indexer to be used for lookups by helper funcs
// This is not done in `init` to allow lazy set once the cache indexer is configured
func (h *Helper) SetIndexer(indexer cache.Indexer) {
h.indexer = indexer
}
// sanitize strips the whitespaces in a string
func (h *Helper) sanitize(s string) string {
return strings.Replace(strings.ToLower(s), " ", "", -1)
}
// appendNonEmpty appends an item to a string slice only if it's non-empty
func (h *Helper) appendNonEmpty(slice []string, items ...string) []string {
for _, item := range items {
item = h.sanitize(item)
if item != "" {
slice = append(slice, item)
}
}
return slice
}
// lookupIngressesByDomain provides a lookup on the cache index with the name 'index'
// on the 'domain', this assumes SetIndexer has been called previously
func (h *Helper) lookupIngressesByDomain(index string, domain string) (ingresses [](*v1beta1.Ingress), err error) {
matches, err := h.indexer.ByIndex(index, domain)
if err != nil {
return ingresses, err
}
for _, match := range matches {
if ingress, ok := match.(*v1beta1.Ingress); ok {
ingresses = append(ingresses, ingress)
}
}
return ingresses, nil
}
// validateDomainClaims provides a helper function to perform the duplicate domain check
// in a provider agnostic manner
func (h *Helper) validateDomainClaims(ingress *v1beta1.Ingress, domains []string) error {
for _, domain := range domains {
ingressMatches, err := h.lookupIngressesByDomain(h.GetProvider(ingress).Name(), domain)
if err != nil {
return err
}
for _, ingressMatch := range ingressMatches {
if !(ingressMatch.Namespace == ingress.Namespace && ingressMatch.Name == ingress.Name) {
return fmt.Errorf("Domain %s already exists. Ingress %s in namespace %s owns "+
"this domain.", domain, ingressMatch.Name, ingressMatch.Namespace)
}
}
}
return nil
}
|
// threadPool_test
package threadPool
import (
"fmt"
"github.com/ziyouchutuwenwu/objective-go/dataFoundation/dataType/object"
"github.com/ziyouchutuwenwu/objective-go/thread/msgThread"
"testing"
"time"
)
var thread1 *msgThread.Thread
var thread2 *msgThread.Thread
type Test struct{}
func (test *Test) MyThreadCallBack1(thread *msgThread.Thread, argObject object.Object) {
fmt.Println("thread1")
time.Sleep(1 * time.Second)
info2 := object.Create()
info2.SetValue("222")
msgObject2 := new(msgThread.MsgObject)
msgObject2.InfoObject = info2
thread2.SendMsg(msgObject2)
}
func (test *Test) MyThreadCallBack2(thread *msgThread.Thread, argObject object.Object) {
fmt.Println("thread2")
time.Sleep(1 * time.Second)
info1 := object.Create()
info1.SetValue("111")
msgObject1 := new(msgThread.MsgObject)
msgObject1.InfoObject = info1
thread1.SendMsg(msgObject1)
}
func (test *Test) MyThreadMsgCallBack1(thread *msgThread.Thread, infoObject object.Object) {
fmt.Println("msgCallBack1", infoObject)
info2 := object.Create()
info2.SetValue("fuck from thread1 to thread2")
msgObject2 := new(msgThread.MsgObject)
msgObject2.InfoObject = info2
thread2.SendMsg(msgObject2)
}
func (test *Test) MyThreadMsgCallBack2(thread *msgThread.Thread, infoObject object.Object) {
fmt.Println("msgCallBack2", infoObject)
info1 := object.Create()
info1.SetValue("fuck from thread2 to thread1")
infoObject1 := new(msgThread.MsgObject)
infoObject1.InfoObject = info1
thread1.SendMsg(infoObject1)
//可选是否关闭,一般不需要关闭,线程池关闭的时候,自动关闭此线程
//thread1.Stop()
}
func (test *Test) MyThreadPoolCallBack(threadPool *ThreadPool) {
fmt.Println("threadPool")
time.Sleep(2 * time.Second)
threadPool.Stop()
}
func Test_threadPool(t *testing.T) {
threadPool := Create()
threadPool.Init()
test := new(Test)
thread1 = msgThread.Create()
thread1.Init()
thread1.Tag = "111"
thread1.SetThreadCallBack(test.MyThreadCallBack1)
thread1.SetMsgCallBack(test.MyThreadMsgCallBack1)
thread1.SetWaitMode(false)
threadPool.Add(thread1)
thread2 = msgThread.Create()
thread2.Init()
thread2.Tag = "222"
thread2.SetThreadCallBack(test.MyThreadCallBack2)
thread2.SetMsgCallBack(test.MyThreadMsgCallBack2)
thread2.SetWaitMode(false)
threadPool.Add(thread2)
threadPool.SetWaitMode(false)
threadPool.SetCallBack(test.MyThreadPoolCallBack)
threadPool.Start()
threadPool.SetWaitMode(true)
threadPool.Wait()
}
|
package functions
import (
"github.com/webmachinedev/src/types"
)
func SearchFunctions(client types.Person, text string) {
}
|
package main
import "fmt"
func main() {
bd := 1998
for bd < 2022 {
fmt.Println(bd)
bd++
}
}
|
package semt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document01400101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:semt.014.001.01 Document"`
Message *IntraPositionMovementStatusAdviceV01 `xml:"IntraPosMvmntStsAdvc"`
}
func (d *Document01400101) AddMessage() *IntraPositionMovementStatusAdviceV01 {
d.Message = new(IntraPositionMovementStatusAdviceV01)
return d.Message
}
// Scope
// An account servicer sends a IntraPositionMovementStatusAdvice to an account owner to advise the status of a intra-position movement instruction previously sent by the account owner.
// The account servicer/owner relationship may be:
// - a central securities depository or another settlement market infrastructure acting on behalf of their participants
// - an agent (sub-custodian) acting on behalf of their global custodian customer, or
// - a custodian acting on behalf of an investment management institution or a broker/dealer.
// Usage
// The message may also be used to:
// - re-send a message previously sent (the sub-function of the message is Duplicate),
// - provide a third party with a copy of a message for information (the sub-function of the message is Copy),
// - re-send to a third party a copy of a message for information (the sub-function of the message is Copy Duplicate).
// ISO 15022 - 20022 Coexistence
// This ISO 20022 message is reversed engineered from ISO 15022. Both standards will coexist for a certain number of years. Until this coexistence period ends, the usage of certain data types is restricted to ensure interoperability between ISO 15022 and 20022 users. Compliance to these rules is mandatory in a coexistence environment. The coexistence restrictions are described in a Textual Rule linked to the Message Items they concern. These coexistence textual rules are clearly identified as follows: “CoexistenceXxxxRule”.
type IntraPositionMovementStatusAdviceV01 struct {
// Information that unambiguously identifies an IntraPositionMovementStatusAdvice message as known by the account servicer.
Identification *iso20022.DocumentIdentification11 `xml:"Id"`
// Unambiguous identification of a transaction as per the account owner (or the instructing party managing the account).
TransactionIdentification *iso20022.TransactionIdentifications3 `xml:"TxId"`
// Provides details on the processing status of the transaction.
ProcessingStatus *iso20022.IntraPositionProcessingStatus1Choice `xml:"PrcgSts,omitempty"`
// Provides the status of settlement of a transaction.
SettlementStatus *iso20022.SettlementStatus2Choice `xml:"SttlmSts,omitempty"`
// Identifies the details of the transaction.
TransactionDetails *iso20022.IntraPositionDetails4 `xml:"TxDtls,omitempty"`
// Party that originated the message, if other than the sender.
MessageOriginator *iso20022.PartyIdentification10Choice `xml:"MsgOrgtr,omitempty"`
// Party that is the final destination of the message, if other than the receiver.
MessageRecipient *iso20022.PartyIdentification10Choice `xml:"MsgRcpt,omitempty"`
// Additional information that cannot be captured in the structured elements and/or any other specific block.
Extension []*iso20022.Extension2 `xml:"Xtnsn,omitempty"`
}
func (i *IntraPositionMovementStatusAdviceV01) AddIdentification() *iso20022.DocumentIdentification11 {
i.Identification = new(iso20022.DocumentIdentification11)
return i.Identification
}
func (i *IntraPositionMovementStatusAdviceV01) AddTransactionIdentification() *iso20022.TransactionIdentifications3 {
i.TransactionIdentification = new(iso20022.TransactionIdentifications3)
return i.TransactionIdentification
}
func (i *IntraPositionMovementStatusAdviceV01) AddProcessingStatus() *iso20022.IntraPositionProcessingStatus1Choice {
i.ProcessingStatus = new(iso20022.IntraPositionProcessingStatus1Choice)
return i.ProcessingStatus
}
func (i *IntraPositionMovementStatusAdviceV01) AddSettlementStatus() *iso20022.SettlementStatus2Choice {
i.SettlementStatus = new(iso20022.SettlementStatus2Choice)
return i.SettlementStatus
}
func (i *IntraPositionMovementStatusAdviceV01) AddTransactionDetails() *iso20022.IntraPositionDetails4 {
i.TransactionDetails = new(iso20022.IntraPositionDetails4)
return i.TransactionDetails
}
func (i *IntraPositionMovementStatusAdviceV01) AddMessageOriginator() *iso20022.PartyIdentification10Choice {
i.MessageOriginator = new(iso20022.PartyIdentification10Choice)
return i.MessageOriginator
}
func (i *IntraPositionMovementStatusAdviceV01) AddMessageRecipient() *iso20022.PartyIdentification10Choice {
i.MessageRecipient = new(iso20022.PartyIdentification10Choice)
return i.MessageRecipient
}
func (i *IntraPositionMovementStatusAdviceV01) AddExtension() *iso20022.Extension2 {
newValue := new(iso20022.Extension2)
i.Extension = append(i.Extension, newValue)
return newValue
}
|
package core
import (
"testing"
)
func Test_NewHashmap_IsHashmap_IsEmptyHashmap(t *testing.T) {
hashmap := NewHashmap()
if !hashmap.IsHashmap() {
t.Error("NewHashmap() failed.")
}
if !hashmap.IsEmptyHashmap() {
t.Error("NewHashmap() failed.")
}
}
func Test_NewHashmapFromSequence_With_Even_Values(t *testing.T) {
first, second := *NewString("first"), *NewString("second")
third, fourth := *NewString("third"), *NewString("fourth")
sequence := make([]Type, 0)
sequence = append(sequence, first)
sequence = append(sequence, second)
sequence = append(sequence, third)
sequence = append(sequence, fourth)
hashmap := NewHashmapFromSequence(sequence).AsHashmap()
if hashmap[NewHashmapKey("first", false)] != second {
t.Error("NewHashmapFromSequence() failed.")
}
if hashmap[NewHashmapKey("third", false)] != fourth {
t.Error("NewHashmapFromSequence() failed.")
}
if len(hashmap) != 2 {
t.Errorf("NewHashmapFromSequence() failed. Length should be 2, but it's '%d'.", len(hashmap))
}
}
func Test_NewHashmapFromSequence_With_Odd_Values(t *testing.T) {
first, second, third := *NewString("first"), *NewString("second"), *NewString("third")
sequence := make([]Type, 0)
sequence = append(sequence, first)
sequence = append(sequence, second)
sequence = append(sequence, third)
hashmap := NewHashmapFromSequence(sequence).AsHashmap()
if hashmap[NewHashmapKey("first", false)] != second {
t.Error("NewHashmapFromSequence() failed.")
}
if len(hashmap) != 1 {
t.Errorf("NewHashmapFromSequence() failed. Length should be 1, but it's '%d'.", len(hashmap))
}
}
func Test_NewHashmapFromSequence_With_Mixed_Strings_And_Keywords(t *testing.T) {
first, fivalue := *NewSymbol(":first"), *NewString("fivalue")
second, sevalue := *NewString(":second"), *NewString("sevalue")
third, thvalue := *NewSymbol("third"), *NewString("thvalue")
fourth, fovalue := *NewString("fourth"), *NewString("fovalue")
sequence := make([]Type, 0)
sequence = append(sequence, first)
sequence = append(sequence, fivalue)
sequence = append(sequence, second)
sequence = append(sequence, sevalue)
sequence = append(sequence, third)
sequence = append(sequence, thvalue)
sequence = append(sequence, fourth)
sequence = append(sequence, fovalue)
hashmap := NewHashmapFromSequence(sequence).AsHashmap()
hfirst, hsecond := hashmap[NewHashmapKey(":first", true)], hashmap[NewHashmapKey(":second", false)]
hthird, hfourth := hashmap[NewHashmapKey("third", true)], hashmap[NewHashmapKey("fourth", false)]
if hfirst.AsString() != "fivalue" {
t.Error("NewHashmapFromSequence() failed.")
}
if hsecond.AsString() != "sevalue" {
t.Error("NewHashmapFromSequence() failed.")
}
if hthird.AsString() != "thvalue" {
t.Error("NewHashmapFromSequence() failed.")
}
if hfourth.AsString() != "fovalue" {
t.Error("NewHashmapFromSequence() failed.")
}
}
|
package main
import (
"net/http"
"log"
"fmt"
)
func sayHello(w http.ResponseWriter, r *http.Request) {
log.Print("req [%v]", *r)
fmt.Fprintln(w, "hello world")
}
// 入口函数
func main() {
http.Handle("/", sayHello)
err := http.ListenAndServe(":7000", nil)
if err != nil {
log.Fatal("ListenAndServe error",err)
}
}
|
package constant
const Version = "v0.16.5"
|
package Utils
import (
"fmt"
"net"
"strings"
)
// 获取本地对外IP
func GetOutboundIP()(ip string, err error) {
// 使用udp的方式拨号
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
fmt.Printf("get ip failed, err: %s, \n", err)
return
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
fmt.Println(localAddr.String())
ip = strings.Split(localAddr.IP.String(), ":")[0]
return
}
|
package etcdv3
import (
"Common/logger"
"context"
"errors"
"fmt"
"strings"
etcd3 "github.com/coreos/etcd/clientv3"
"google.golang.org/grpc/naming"
)
// resolver is the implementaion of grpc.naming.Resolver
type resolver struct {
serviceName string // service name to resolve
}
// NewResolver return resolver with service name
func NewResolver(serviceName string) *resolver {
return &resolver{serviceName: serviceName}
}
// Resolve to resolve the service from etcd, target is the dial address of etcd
// target example: "http://127.0.0.1:2379,http://127.0.0.1:12379,http://127.0.0.1:22379"
func (re *resolver) Resolve(target string) (naming.Watcher, error) {
if re.serviceName == "" {
return nil, errors.New("grpclb: no service name provided")
}
// generate etcd client
client, err := etcd3.New(etcd3.Config{
Endpoints: strings.Split(target, ","),
})
if err != nil {
return nil, fmt.Errorf("grpclb: creat etcd3 client failed: %s", err.Error())
}
// Return watcher
return &watcher{
re: re,
client: *client,
addMap: make(map[string]int64)}, nil
}
func GetAdds(serviceName, target string) []string {
var err error
addrs := []string{}
if client == nil {
client, err = etcd3.New(etcd3.Config{
Endpoints: strings.Split(target, ","),
})
if err != nil {
logger.Warn("grpclb: creat etcd3 client failed: ", err)
return addrs
}
}
prefix := fmt.Sprintf("/%s/%s/", Prefix, serviceName)
ctx, cancel := context.WithCancel(context.Background())
resp, err := client.Get(ctx, prefix, etcd3.WithPrefix())
if err != nil {
logger.Warn("grpclb: client get failed: ", err)
cancel()
return addrs
}
cancel()
return extractAddrs(resp)
}
|
package entity
import (
"time"
"github.com/fatih/structs"
)
type Token struct {
Id int64
Chain string // 主链
Token string // 币种符号
Contract string // 代币合约地址
Precision int64 // 币种精度
Protocol string // 币种协议
FullName string // 全称
WithdrawSwitch int64 // 提币开关
DepositSwitch int64 // 充值开关
WithdrawConfirmations int64 // 充值确认数
DepositConfirmations int64 // 提币确认数
MinDepositAmount string // 最小充值金额
MinWithdrawAmount string // 最小提币数量
MinCollectionAmount string // 最小扫币额度
ReserveAmount string // 钱包预留额度
CollectionType int64 // 归集类型:1. 逐笔归集、2. 定时归集
CollectionAmount int64 // 批量归集笔数
CollectionDuration int64 // 批量归集周期,单位分钟
CollectionNetworkFeeSource int64 // 默认归集网络费来源,1. 子账户自己出,2 商户冷钱包出
MaxNetworkFee string // 最大网络手续费
NeedNetworkFee int64
NetworkFeeChange int64 // 是否需要网络手续费找零
NeedTag int64
NeedImportToNode int64 // 是否需要导入地址
NeedImportPrivateKey int64
CreatedAt *time.Time
UpdatedAt *time.Time
}
func (p *Token) Map() *map[string]interface{} {
m := structs.Map(p)
return &m
}
|
package problem0594
func findLHS(nums []int) int {
dict := map[int]int{}
for _, num := range nums {
dict[num]++
}
max := 0
for key, count := range dict {
if dict[key-1] == 0 {
continue
}
if count+dict[key-1] > max {
max = count + dict[key-1]
}
}
return max
}
|
package sort
/*
Notes:
简单概括,相邻两元素作比较,遍历区间逐步缩小。
效率低下。
稳定排序。
*/
// time complexity: O(N) ~ O(N^2)
func bubbleSort(nums []int) {
var swapped bool
for i := len(nums) - 1; i > 0; i-- {
swapped = false
for j := 0; j < i; j++ {
if nums[j] > nums[j+1] {
nums[j], nums[j+1] = nums[j+1], nums[j]
swapped = true
}
}
// optimizae
if !swapped {
return
}
}
}
|
package models
type User struct {
Base
Name string `json:"name"`
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
Task []Task `gorm:"foreignKey:UserId"`
Category []Category `gorm:"foreignKey:UserId"`
}
|
package problem0090
import "sort"
func subsetsWithDup(nums []int) [][]int {
sort.Ints(nums)
result := [][]int{}
visited := make([]bool, len(nums))
subset := []int{}
for i := 0; i <= len(nums); i++ {
backtrack(nums, visited, subset, 0, i, &result)
}
return result
}
func backtrack(nums []int, visited []bool, subset []int, start int, size int, result *[][]int) {
if len(subset) == size {
*result = append(*result, append([]int{}, subset...))
return
}
for i := start; i < len(nums); i++ {
if visited[i] {
continue
}
if i != 0 && nums[i-1] == nums[i] && !visited[i-1] {
continue
}
subset = append(subset, nums[i])
visited[i] = true
backtrack(nums, visited, subset, i+1, size, result)
visited[i] = false
subset = subset[:len(subset)-1]
}
}
|
package main
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
pb "github.com/vlasove/Lec12/shippyvessel/proto/vessel"
)
//Модельный файл
//Repository ...
type repository interface {
FindAvailable(ctx context.Context, spec *Specification) (*Vessel, error)
Create(ctx context.Context, vessel *Vessel) error
}
//VesselRepository ...
type MongoRepository struct {
collection *mongo.Collection
}
// message Specification {
// int32 capacity = 1;
// int32 max_weight = 2;
// }
//Локальная реализация объекта, понтяного для монги
type Specification struct {
Capacity int32
MaxWeight int32
}
// message Vessel {
// string id = 1;
// int32 capacity = 2;
// int32 max_weight = 3;
// string name = 4;
// bool available = 5;
// string owner_id = 6;
// }
//Локальная реализация объекта Vessel, понятного для монги
type Vessel struct {
ID string
Capacity int32
MaxWeight int32
Available bool
OwnerID string
Name string
}
//Превращаем *pb.Specification в *Specification
func MarshallSpecification(spec *pb.Specification) *Specification {
return &Specification{
Capacity: spec.Capacity,
MaxWeight: spec.MaxWeight,
}
}
//Превращаем *Specification в *pb.Specification
func UnmarshallSpecification(spec *Specification) *pb.Specification {
return &pb.Specification{
Capacity: spec.Capacity,
MaxWeight: spec.MaxWeight,
}
}
//Превращаем *pb.Vessel в *Vessel
func MarshallVessel(vessel *pb.Vessel) *Vessel {
return &Vessel{
ID: vessel.Id,
Capacity: vessel.Capacity,
MaxWeight: vessel.MaxWeight,
Name: vessel.Name,
Available: vessel.Available,
OwnerID: vessel.OwnerId,
}
}
//Превращаем *Vessel в *pb.Vessel
func UnmarshallVessel(vessel *Vessel) *pb.Vessel {
return &pb.Vessel{
Id: vessel.ID,
Capacity: vessel.Capacity,
MaxWeight: vessel.MaxWeight,
Name: vessel.Name,
Available: vessel.Available,
OwnerId: vessel.OwnerID,
}
}
//FindAvailable ...
func (repo *MongoRepository) FindAvailable(ctx context.Context, spec *Specification) (*Vessel, error) {
// for _, vessel := range repo.vessels {
// if spec.Capacity <= vessel.Capacity && spec.MaxWeight <= vessel.MaxWeight {
// return vessel, nil
// }
// }
// return nil, errors.New("No vessel found by that spec")
//Фильтр для отбора подходящего vessel
filter := bson.D{{
"capacity",
bson.D{{
"$lte",
spec.Capacity,
}, {
"$lte",
spec.MaxWeight,
}},
}}
vessel := &Vessel{}
if err := repo.collection.FindOne(ctx, filter).Decode(vessel); err != nil {
return nil, err
}
return vessel, nil
}
//Create ...
func (repo *MongoRepository) Create(ctx context.Context, vessel *Vessel) error {
_, err := repo.collection.InsertOne(ctx, vessel)
return err
}
|
package command
import (
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/quilt/quilt/api"
clientMock "github.com/quilt/quilt/api/client/mocks"
"github.com/quilt/quilt/db"
)
func TestPsFlags(t *testing.T) {
t.Parallel()
expHost := "IP"
cmd := NewPsCommand()
err := parseHelper(cmd, []string{"-H", expHost})
assert.NoError(t, err)
assert.Equal(t, expHost, cmd.common.host)
}
func TestPsErrors(t *testing.T) {
t.Parallel()
var cmd *Ps
var mockGetter *clientMock.Getter
var mockClient, mockLeaderClient *clientMock.Client
mockErr := errors.New("error")
// Error connecting to local client
mockGetter = new(clientMock.Getter)
mockGetter.On("Client", mock.Anything).Return(nil, mockErr)
cmd = &Ps{&commonFlags{}, mockGetter}
assert.EqualError(t, cmd.run(), "error connecting to quilt daemon: error")
mockGetter.AssertExpectations(t)
// Error querying machines
mockGetter = new(clientMock.Getter)
mockClient = &clientMock.Client{MachineErr: mockErr}
mockGetter.On("Client", mock.Anything).Return(mockClient, nil)
mockGetter.On("LeaderClient", mock.Anything).Return(nil, mockErr)
cmd = &Ps{&commonFlags{}, mockGetter}
assert.EqualError(t, cmd.run(), "unable to query machines: error")
mockGetter.AssertExpectations(t)
// Error connecting to leader
mockGetter = new(clientMock.Getter)
mockClient = new(clientMock.Client)
mockGetter.On("Client", mock.Anything).Return(mockClient, nil)
mockGetter.On("LeaderClient", mock.Anything).Return(nil, mockErr)
cmd = &Ps{&commonFlags{}, mockGetter}
assert.NoError(t, cmd.run())
mockGetter.AssertExpectations(t)
// Error querying containers
mockGetter = new(clientMock.Getter)
mockClient = new(clientMock.Client)
mockLeaderClient = &clientMock.Client{ContainerErr: mockErr}
mockGetter.On("Client", mock.Anything).Return(mockClient, nil)
mockGetter.On("LeaderClient", mock.Anything).Return(mockLeaderClient, nil)
cmd = &Ps{&commonFlags{}, mockGetter}
assert.EqualError(t, cmd.run(), "unable to query containers: error")
mockGetter.AssertExpectations(t)
// Error querying connections from LeaderClient
mockGetter = new(clientMock.Getter)
mockClient = new(clientMock.Client)
mockLeaderClient = &clientMock.Client{ConnectionErr: mockErr}
mockGetter.On("Client", mock.Anything).Return(mockClient, nil)
mockGetter.On("LeaderClient", mock.Anything).Return(mockLeaderClient, nil)
cmd = &Ps{&commonFlags{}, mockGetter}
assert.EqualError(t, cmd.run(), "unable to query connections: error")
mockGetter.AssertExpectations(t)
// Error querying containers in queryWorkers(), but fine for Leader.
mockGetter = new(clientMock.Getter)
mockClient = &clientMock.Client{
MachineReturn: []db.Machine{
{
PublicIP: "1.2.3.4",
Role: db.Worker,
},
},
ContainerErr: mockErr,
}
mockLeaderClient = new(clientMock.Client)
mockGetter.On("Client", mock.Anything).Return(mockClient, nil)
mockGetter.On("LeaderClient", mock.Anything).Return(mockLeaderClient, nil)
cmd = &Ps{&commonFlags{}, mockGetter}
assert.Equal(t, 0, cmd.Run())
mockGetter.AssertExpectations(t)
}
func TestPsSuccess(t *testing.T) {
t.Parallel()
mockGetter := new(clientMock.Getter)
mockClient := new(clientMock.Client)
mockLeaderClient := new(clientMock.Client)
mockGetter.On("Client", mock.Anything).Return(mockClient, nil)
mockGetter.On("LeaderClient", mock.Anything).Return(mockLeaderClient, nil)
cmd := &Ps{&commonFlags{}, mockGetter}
assert.Equal(t, 0, cmd.Run())
mockGetter.AssertExpectations(t)
}
func TestQueryWorkersSuccess(t *testing.T) {
t.Parallel()
containers := []db.Container{
{
StitchID: "1",
},
}
machines := []db.Machine{
{
PublicIP: "1.2.3.4",
Role: db.Worker,
},
}
mockGetter := new(clientMock.Getter)
mockClient := &clientMock.Client{
ContainerReturn: containers,
}
mockGetter.On("Client", mock.Anything).Return(mockClient, nil)
cmd := &Ps{&commonFlags{}, mockGetter}
result := cmd.queryWorkers(machines)
assert.Equal(t, containers, result)
mockGetter.AssertExpectations(t)
}
func TestQueryWorkersFailure(t *testing.T) {
t.Parallel()
containers := []db.Container{
{
StitchID: "1",
},
}
machines := []db.Machine{
{
PublicIP: "1.2.3.4",
Role: db.Worker,
},
{
PublicIP: "5.6.7.8",
Role: db.Worker,
},
}
mockErr := errors.New("error")
// Getting Worker Machine Client fails. Still query non-failing machine.
mockClient := &clientMock.Client{
ContainerReturn: containers,
}
mockGetter := new(clientMock.Getter)
mockGetter.On("Client", api.RemoteAddress("1.2.3.4")).Return(nil, mockErr)
mockGetter.On("Client", api.RemoteAddress("5.6.7.8")).Return(mockClient, nil)
cmd := &Ps{&commonFlags{}, mockGetter}
result := cmd.queryWorkers(machines)
assert.Equal(t, containers, result)
mockGetter.AssertExpectations(t)
// Worker Machine client throws error.
// Still get container from non-failing machine.
mockGetter = new(clientMock.Getter)
failingClient := &clientMock.Client{
ContainerErr: mockErr,
}
mockGetter.On("Client", api.RemoteAddress("1.2.3.4")).Return(failingClient, nil)
mockGetter.On("Client", api.RemoteAddress("5.6.7.8")).Return(mockClient, nil)
cmd = &Ps{&commonFlags{}, mockGetter}
result = cmd.queryWorkers(machines)
assert.Equal(t, containers, result)
mockGetter.AssertExpectations(t)
}
func TestUpdateContainers(t *testing.T) {
t.Parallel()
created := time.Now()
lContainers := []db.Container{
{
StitchID: "1",
},
}
wContainers := []db.Container{
{
StitchID: "1",
Created: created,
},
}
// Test update a matching container.
expect := wContainers
result := updateContainers(lContainers, wContainers)
assert.Equal(t, expect, result)
// Test container in leader, not in worker.
newContainer := db.Container{
StitchID: "2",
}
lContainers = append(lContainers, newContainer)
expect = append(expect, newContainer)
result = updateContainers(lContainers, wContainers)
assert.Equal(t, expect, result)
// Test if lContainers empty.
lContainers = []db.Container{}
expect = wContainers
result = updateContainers(lContainers, wContainers)
assert.Equal(t, expect, result)
// Test if wContainers empty.
lContainers = wContainers
wContainers = []db.Container{}
expect = lContainers
result = updateContainers(lContainers, wContainers)
assert.Equal(t, expect, result)
// Test if both empty.
lContainers = []db.Container{}
expect = []db.Container{}
result = updateContainers(lContainers, wContainers)
assert.Equal(t, expect, result)
}
|
package v1alpha1
import metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
type DeviceSpec struct{}
type DeviceStatus struct {
// Registered denotes wether or not this device is considered as
// being registered or not.
Registered bool `json:"registered"`
}
// +kubebuilder:object:root=true
type Device struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DeviceSpec `json:"spec"`
Status DeviceStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
type DeviceList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Device `json:"items"`
}
|
package metadata
import (
"encoding/gob"
"fmt"
"io"
"os"
"github.com/golang/snappy"
"github.com/root-gg/plik/server/common"
)
type metadataType int
const (
metadataTypeUpload metadataType = iota
metadataTypeFile
metadataTypeUser
metadataTypeToken
metadataTypeSetting
)
type object struct {
Type metadataType
Object interface{}
}
type exporter struct {
writer io.WriteCloser
compressor *snappy.Writer
encoder *gob.Encoder
}
func newExporter(path string) (e *exporter, err error) {
e = &exporter{}
// Open file for writing
e.writer, err = os.Create(path)
if err != nil {
return nil, err
}
// Snappy compressor
e.compressor = snappy.NewBufferedWriter(e.writer)
// Gob encoder
gob.Register(&common.Upload{})
gob.Register(&common.File{})
gob.Register(&common.User{})
gob.Register(&common.Token{})
gob.Register(&common.Setting{})
e.encoder = gob.NewEncoder(e.compressor)
return e, nil
}
func (e *exporter) addUpload(upload *common.Upload) (err error) {
obj := &object{Type: metadataTypeUpload, Object: upload}
return e.encoder.Encode(obj)
}
func (e *exporter) addFile(file *common.File) (err error) {
obj := &object{Type: metadataTypeFile, Object: file}
return e.encoder.Encode(obj)
}
func (e *exporter) addUser(user *common.User) (err error) {
obj := &object{Type: metadataTypeUser, Object: user}
return e.encoder.Encode(obj)
}
func (e *exporter) addToken(token *common.Token) (err error) {
obj := &object{Type: metadataTypeToken, Object: token}
return e.encoder.Encode(obj)
}
func (e *exporter) addSetting(setting *common.Setting) (err error) {
obj := &object{Type: metadataTypeSetting, Object: setting}
return e.encoder.Encode(obj)
}
func (e *exporter) close() (err error) {
err = e.compressor.Close()
if err != nil {
return err
}
err = e.writer.Close()
if err != nil {
return err
}
return nil
}
// Export exports all metadata from the backend to a compressed binary file
func (b *Backend) Export(path string) (err error) {
e, err := newExporter(path)
if err != nil {
return err
}
defer func() { _ = e.close() }()
count := 0
err = b.ForEachUsers(func(user *common.User) error {
count++
return e.addUser(user)
})
if err != nil {
return err
}
fmt.Printf("exported %d users\n", count)
count = 0
err = b.ForEachToken(func(token *common.Token) error {
count++
return e.addToken(token)
})
if err != nil {
return err
}
fmt.Printf("exported %d tokens\n", count)
count = 0
// Need to export "soft deleted" uploads too else some removed/deleted files will have broken foreign keys
err = b.ForEachUploadUnscoped(func(upload *common.Upload) error {
count++
return e.addUpload(upload)
})
if err != nil {
return err
}
fmt.Printf("exported %d uploads\n", count)
count = 0
err = b.ForEachFile(func(file *common.File) error {
count++
return e.addFile(file)
})
if err != nil {
return err
}
fmt.Printf("exported %d files\n", count)
count = 0
err = b.ForEachSetting(func(setting *common.Setting) error {
count++
return e.addSetting(setting)
})
if err != nil {
return err
}
fmt.Printf("exported %d settings\n", count)
return nil
}
|
package model
type FilterTypeResponse struct {
// The type of the filter
Type FilterType `json:"type,omitempty"`
}
|
// This file was generated for SObject Order, API Version v43.0 at 2018-07-30 03:47:56.801421065 -0400 EDT m=+43.145646441
package sobjects
import (
"fmt"
"strings"
)
type Order struct {
BaseSObject
AccountId string `force:",omitempty"`
ActivatedById string `force:",omitempty"`
ActivatedDate string `force:",omitempty"`
BillToContactId string `force:",omitempty"`
BillingAddress *Address `force:",omitempty"`
BillingCity string `force:",omitempty"`
BillingCountry string `force:",omitempty"`
BillingGeocodeAccuracy string `force:",omitempty"`
BillingLatitude float64 `force:",omitempty"`
BillingLongitude float64 `force:",omitempty"`
BillingPostalCode string `force:",omitempty"`
BillingState string `force:",omitempty"`
BillingStreet string `force:",omitempty"`
CompanyAuthorizedById string `force:",omitempty"`
CompanyAuthorizedDate string `force:",omitempty"`
ContractId string `force:",omitempty"`
CreatedById string `force:",omitempty"`
CreatedDate string `force:",omitempty"`
CustomerAuthorizedById string `force:",omitempty"`
CustomerAuthorizedDate string `force:",omitempty"`
Description string `force:",omitempty"`
EffectiveDate string `force:",omitempty"`
EndDate string `force:",omitempty"`
Id string `force:",omitempty"`
IsDeleted bool `force:",omitempty"`
IsReductionOrder bool `force:",omitempty"`
LastModifiedById string `force:",omitempty"`
LastModifiedDate string `force:",omitempty"`
LastReferencedDate string `force:",omitempty"`
LastViewedDate string `force:",omitempty"`
Name string `force:",omitempty"`
OrderNumber string `force:",omitempty"`
OrderReferenceNumber string `force:",omitempty"`
OriginalOrderId string `force:",omitempty"`
OwnerId string `force:",omitempty"`
PoDate string `force:",omitempty"`
PoNumber string `force:",omitempty"`
Pricebook2Id string `force:",omitempty"`
ShipToContactId string `force:",omitempty"`
ShippingAddress *Address `force:",omitempty"`
ShippingCity string `force:",omitempty"`
ShippingCountry string `force:",omitempty"`
ShippingGeocodeAccuracy string `force:",omitempty"`
ShippingLatitude float64 `force:",omitempty"`
ShippingLongitude float64 `force:",omitempty"`
ShippingPostalCode string `force:",omitempty"`
ShippingState string `force:",omitempty"`
ShippingStreet string `force:",omitempty"`
Status string `force:",omitempty"`
StatusCode string `force:",omitempty"`
SystemModstamp string `force:",omitempty"`
TotalAmount string `force:",omitempty"`
Type string `force:",omitempty"`
}
func (t *Order) ApiName() string {
return "Order"
}
func (t *Order) String() string {
builder := strings.Builder{}
builder.WriteString(fmt.Sprintf("Order #%s - %s\n", t.Id, t.Name))
builder.WriteString(fmt.Sprintf("\tAccountId: %v\n", t.AccountId))
builder.WriteString(fmt.Sprintf("\tActivatedById: %v\n", t.ActivatedById))
builder.WriteString(fmt.Sprintf("\tActivatedDate: %v\n", t.ActivatedDate))
builder.WriteString(fmt.Sprintf("\tBillToContactId: %v\n", t.BillToContactId))
builder.WriteString(fmt.Sprintf("\tBillingAddress: %v\n", t.BillingAddress))
builder.WriteString(fmt.Sprintf("\tBillingCity: %v\n", t.BillingCity))
builder.WriteString(fmt.Sprintf("\tBillingCountry: %v\n", t.BillingCountry))
builder.WriteString(fmt.Sprintf("\tBillingGeocodeAccuracy: %v\n", t.BillingGeocodeAccuracy))
builder.WriteString(fmt.Sprintf("\tBillingLatitude: %v\n", t.BillingLatitude))
builder.WriteString(fmt.Sprintf("\tBillingLongitude: %v\n", t.BillingLongitude))
builder.WriteString(fmt.Sprintf("\tBillingPostalCode: %v\n", t.BillingPostalCode))
builder.WriteString(fmt.Sprintf("\tBillingState: %v\n", t.BillingState))
builder.WriteString(fmt.Sprintf("\tBillingStreet: %v\n", t.BillingStreet))
builder.WriteString(fmt.Sprintf("\tCompanyAuthorizedById: %v\n", t.CompanyAuthorizedById))
builder.WriteString(fmt.Sprintf("\tCompanyAuthorizedDate: %v\n", t.CompanyAuthorizedDate))
builder.WriteString(fmt.Sprintf("\tContractId: %v\n", t.ContractId))
builder.WriteString(fmt.Sprintf("\tCreatedById: %v\n", t.CreatedById))
builder.WriteString(fmt.Sprintf("\tCreatedDate: %v\n", t.CreatedDate))
builder.WriteString(fmt.Sprintf("\tCustomerAuthorizedById: %v\n", t.CustomerAuthorizedById))
builder.WriteString(fmt.Sprintf("\tCustomerAuthorizedDate: %v\n", t.CustomerAuthorizedDate))
builder.WriteString(fmt.Sprintf("\tDescription: %v\n", t.Description))
builder.WriteString(fmt.Sprintf("\tEffectiveDate: %v\n", t.EffectiveDate))
builder.WriteString(fmt.Sprintf("\tEndDate: %v\n", t.EndDate))
builder.WriteString(fmt.Sprintf("\tId: %v\n", t.Id))
builder.WriteString(fmt.Sprintf("\tIsDeleted: %v\n", t.IsDeleted))
builder.WriteString(fmt.Sprintf("\tIsReductionOrder: %v\n", t.IsReductionOrder))
builder.WriteString(fmt.Sprintf("\tLastModifiedById: %v\n", t.LastModifiedById))
builder.WriteString(fmt.Sprintf("\tLastModifiedDate: %v\n", t.LastModifiedDate))
builder.WriteString(fmt.Sprintf("\tLastReferencedDate: %v\n", t.LastReferencedDate))
builder.WriteString(fmt.Sprintf("\tLastViewedDate: %v\n", t.LastViewedDate))
builder.WriteString(fmt.Sprintf("\tName: %v\n", t.Name))
builder.WriteString(fmt.Sprintf("\tOrderNumber: %v\n", t.OrderNumber))
builder.WriteString(fmt.Sprintf("\tOrderReferenceNumber: %v\n", t.OrderReferenceNumber))
builder.WriteString(fmt.Sprintf("\tOriginalOrderId: %v\n", t.OriginalOrderId))
builder.WriteString(fmt.Sprintf("\tOwnerId: %v\n", t.OwnerId))
builder.WriteString(fmt.Sprintf("\tPoDate: %v\n", t.PoDate))
builder.WriteString(fmt.Sprintf("\tPoNumber: %v\n", t.PoNumber))
builder.WriteString(fmt.Sprintf("\tPricebook2Id: %v\n", t.Pricebook2Id))
builder.WriteString(fmt.Sprintf("\tShipToContactId: %v\n", t.ShipToContactId))
builder.WriteString(fmt.Sprintf("\tShippingAddress: %v\n", t.ShippingAddress))
builder.WriteString(fmt.Sprintf("\tShippingCity: %v\n", t.ShippingCity))
builder.WriteString(fmt.Sprintf("\tShippingCountry: %v\n", t.ShippingCountry))
builder.WriteString(fmt.Sprintf("\tShippingGeocodeAccuracy: %v\n", t.ShippingGeocodeAccuracy))
builder.WriteString(fmt.Sprintf("\tShippingLatitude: %v\n", t.ShippingLatitude))
builder.WriteString(fmt.Sprintf("\tShippingLongitude: %v\n", t.ShippingLongitude))
builder.WriteString(fmt.Sprintf("\tShippingPostalCode: %v\n", t.ShippingPostalCode))
builder.WriteString(fmt.Sprintf("\tShippingState: %v\n", t.ShippingState))
builder.WriteString(fmt.Sprintf("\tShippingStreet: %v\n", t.ShippingStreet))
builder.WriteString(fmt.Sprintf("\tStatus: %v\n", t.Status))
builder.WriteString(fmt.Sprintf("\tStatusCode: %v\n", t.StatusCode))
builder.WriteString(fmt.Sprintf("\tSystemModstamp: %v\n", t.SystemModstamp))
builder.WriteString(fmt.Sprintf("\tTotalAmount: %v\n", t.TotalAmount))
builder.WriteString(fmt.Sprintf("\tType: %v\n", t.Type))
return builder.String()
}
type OrderQueryResponse struct {
BaseQuery
Records []Order `json:"Records" force:"records"`
}
|
package cmd
import (
"fmt"
"github.com/go-openapi/spec"
"github.com/spf13/cobra"
)
func filterCmd(cmd *cobra.Command, args []string) error {
var filters filters
err := addEndpoints(cmd, &filters)
if err != nil {
return err
}
err = addPrefixEndpoints(cmd, &filters)
if err != nil {
return err
}
err = addRegexpEndpoints(cmd, &filters)
if err != nil {
return err
}
if len(args) != 2 {
return fmt.Errorf("Number of args should be 2 but is %d", len(args))
}
specfile := args[0]
outfile := args[1]
doc, err := load(specfile)
if err != nil {
return err
}
refs := filterSpec(doc.Spec(), filters)
filterDefinitions(doc.Spec(), refs)
outputSpec(doc.Spec(), outfile)
return err
}
func addEndpoints(cmd *cobra.Command, filters *filters) error {
endpoints, err := cmd.Flags().GetStringSlice("endpoint")
if err != nil {
return err
}
for _, endpoint := range endpoints {
filters.add(StringFilter{endpoint})
}
return nil
}
func addPrefixEndpoints(cmd *cobra.Command, filters *filters) error {
endpoints, err := cmd.Flags().GetStringSlice("endpoint-prefix")
if err != nil {
return err
}
for _, endpoint := range endpoints {
filters.add(PrefixFilter{endpoint})
}
return nil
}
func addRegexpEndpoints(cmd *cobra.Command, filters *filters) error {
endpoints, err := cmd.Flags().GetStringSlice("endpoint-regexp")
if err != nil {
return err
}
for _, endpoint := range endpoints {
f, err := NewRegexpFilter(endpoint)
if err != nil {
return err
}
filters.add(f)
}
return nil
}
func filterSpec(spec *spec.Swagger, filters filters) refs {
refs := newRefs()
for k := range spec.Paths.Paths {
if !filters.pathMatches(k) {
delete(spec.Paths.Paths, k)
continue
}
findRefs(spec, "GET", spec.Paths.Paths[k].PathItemProps.Get, refs)
findRefs(spec, "PUT", spec.Paths.Paths[k].PathItemProps.Put, refs)
findRefs(spec, "POST", spec.Paths.Paths[k].PathItemProps.Post, refs)
findRefs(spec, "DELETE", spec.Paths.Paths[k].PathItemProps.Delete, refs)
findRefs(spec, "OPTIONS", spec.Paths.Paths[k].PathItemProps.Options, refs)
findRefs(spec, "HEAD", spec.Paths.Paths[k].PathItemProps.Head, refs)
findRefs(spec, "PATCH", spec.Paths.Paths[k].PathItemProps.Patch, refs)
}
return refs
}
func filterDefinitions(spec *spec.Swagger, refs refs) {
for k := range spec.Definitions {
if _, found := refs[k]; !found {
delete(spec.Definitions, k)
continue
}
}
}
|
package util
import (
"github.com/twinj/uuid"
)
// UUID ...
func UUID() string {
return uuid.NewV4().String()
}
|
package main
import ("fmt")
func main() {
a := make(map[string]int)
a["id"] = 11
a["ids"] = 111
fmt.Println(a)
delete(a, "ids")
fmt.Println(a)
_, is := a["id"]
fmt.Println(is)
}
|
package golinal
import (
"errors";
"math";
"fmt";
"github.com/gonum/Matrix/mat64";
)
// Matrix Struct Definition
//
type Matrix struct {
numRows, numCols int
elems [][]float64
}
// brief: Parameterized constructor that takes slice
// of slices of floats
//
// details: Allows us to create a Matrix with only
// providing slices and not specifying columns or rows
//
// note: It is on the user to make sure that all columns have
// the same length, otherwise the Matrix will break
//
// returns: a pointer to a Matrix
func NewMatrix(slices... []float64) (*Matrix) {
m := new(Matrix)
m.numRows = int(len(slices))
m.numCols = int(len(slices[0]))
m.elems = slices
return m
}
// brief: Parameterized constructor that takes slice
// of slices of floats
//
// details: Allows us to create a Matrix with only
// providing slices and not specifying columns or rows
//
// note: It is on the user to make sure that all columns have
// the same length, otherwise the Matrix will break
//
// returns: a pointer to a Matrix
func BlankMatrix(rows, cols int) (*Matrix) {
m := new(Matrix)
m.numRows = rows
m.numCols = cols
// make empty slice of slices
slices := make([][]float64, rows)
for i:= range slices {
slices[i] = make([]float64, cols)
}
m.elems = slices
return m
}
// brief: Creates an nxn identity matrix
//
// returns: pointer to an matrix
func Identity(n int) (*Matrix) {
m := BlankMatrix(n, n)
for i := 0; i < n; i++ {
m.elems[i][i] = 1
}
return m
}
// brief: Gets the dimensions of a matrix
//
// returns: the number of rows, the number of colmns
func (m Matrix) Dims() (int, int) {
return m.numRows, m.numCols
}
// brief: Get the row,col'th entry of a Matrix
//
// note: it is undefined behavior to use invalid indices with At()
//
// returns: A_ij for a row i and a row j
func (m Matrix) At(row, col int) (float64) {
return m.elems[row][col]
}
// brief: Gets number of rows in a Matrix
//
// returns: number of rows
func (m Matrix) NumRows() int {
return m.numRows
}
// brief: Gets number of cols in a Matrix
//
// returns: number of cols
func (m Matrix) NumCols() int {
return m.numCols
}
// brief: Adds two matrices together
//
// inputs: a Matrix pointer
//
// returns: an error if dimensions of the
// matrices to be summed aren't equal
func (m *Matrix) Add(q *Matrix) error {
if (m.numRows != q.numRows) || (m.numCols != q.numRows) {
return errors.New("Dimensions aren't equal")
} else {
// Loop through each entry, store sum of entries in m
for i := 0; i < m.numRows; i++ {
for j := 0; j < q.numRows; j++ {
m.elems[i][j] += q.elems[i][j]
}
}
return nil
}
}
// brief: Scales a Matrix by a real number
//
// inputs: A float
func (m *Matrix) Scale(x float64) {
for i := 0; i < m.numRows; i++ {
for j := 0; j < m.numRows; j++ {
m.elems[i][j] *= x
}
}
}
// brief: Multiplys the Matrix m by the Matrix q
//
// details: O(n^3)
//
// returns: product of m and q
func (m Matrix) Multiply(q *Matrix) (*Matrix, error) {
if (m.numCols != q.numRows) {
return nil,errors.New("Dimensions can't be multiplied")
} else {
result := BlankMatrix(m.numRows, q.numCols)
for i := 0; i < m.numRows; i++ {
for j := 0; j < q.numCols; j++ {
for k := 0; k < q.numRows; k++ {
if i == 0 || j == 0 || k == 0 {
fmt.Println(result.elems[i][j])
}
result.elems[i][j] += m.elems[i][k] * q.elems[k][j]
}
}
}
return result, nil
}
}
// brief: Calculates transpose of Matrix, wrapper for T()
//
// details: Implemented for *Matrix
//
// returns: a transposed version of m as a pointer to a Matrix
func(m *Matrix) Transpose() *Matrix {
transpose := BlankMatrix(m.numCols, m.numRows)
for i := 0; i < m.numCols; i++ {
for j := 0; j < m.numRows; j++ {
fmt.Printf("i= %d\n", i)
fmt.Printf("j= %d\n", j)
transpose.elems[i][j] = m.elems[j][i]
}
}
return transpose
}
// BROKEN DUE TO LUP DECOMP
// brief: Calculates transpose of Matrix
//
// details: Implemented for mat64.Matrix interface
//
// returns: a transposed version of m
func(m *Matrix) Inverse() (*Matrix, error) {
if !m.IsSqaure(){
return nil, errors.New("Matrix is not square")
}
inverseT := BlankMatrix(m.numRows,m.numRows)
identity := Identity(m.numRows)
for i, _ := range inverseT.elems {
r, err := m.Gauss(identity.elems[i])
if err != nil {
return nil, err
}
fmt.Println(r)
inverseT.elems[i] = r
}
fmt.Println(inverseT.elems)
return inverseT, nil
}
// BROKEN METHOD DUE TO LUP DECMOP
// brief: Calculates determinant of a Matrix
//
// details: Uses LU decomposition, O(n^3),
//
// returns: a determinant of m
func (m *Matrix) Determinant() (det float64, err error) {
L, U, P, err := m.LUP()
if err != nil {
return 0.0, err
}
det, err = determinant(*L, *U, *P)
return
}
// brief: Calculates the LUP decomposition of a Matrix
//
// details: Decomposes m in to the product of three matrices:
// P: A row permutation Matrix
// U: An upper triangular Matrix
// L: A lower triangular Matrix
// Hence Pm = LU,
// O(n^3)
//
// returns: a determinant of m
func (m *Matrix) LUP() (*Matrix, *Matrix, *Matrix, error) {
// No LUP if Matrix isn't square
if !m.IsSqaure() {
return nil, nil, nil, errors.New("LUP requires square Matrix")
}
n := m.numRows
L := BlankMatrix(n,n)
U := BlankMatrix(n,n)
P := m.pivotMatrix()
Pm, _ := P.Multiply(m)
for j := 0; j < n; j++ {
L.elems[j][j] = 1
// Populate U using the following formula (compile it in LaTex)
// u_{ij} = a_{ij} - \sum_{k=1}^{i-1} u_{kj} l_{ik}
for i := 0; i < j+1; i++ {
sum := 0.0
for k := 0; k < i; k++ {
sum += (U.elems[k][j] * L.elems[i][k])
}
U.elems[i][j] = Pm.elems[i][j] - sum
}
// Populate L using the following formula (compile it in LaTex)
// l_{ij} = \frac{1}{u_{jj}} (a_{ij} - \sum_{k=1}^{j-1} u_{kj} l_{ik}
for i := j; i < n; i++ {
sum := 0.0
for k := 0; k < j; k++ {
sum += (U.elems[k][j] * L.elems[i][k])
}
L.elems[i][j] = (Pm.elems[i][j] - sum) / U.elems[j][j]
}
}
return L, U, P, nil
}
// BROKEN DUE TO LUP DECOMP
// brief: Solves equations of the form
// Ax = b
// where A is a Matrix, and x,b are vectors
//
// inputs: b a slice of floats to solve for
//
// details: If A is square, LU decomposition is used
//
func (A *Matrix) Gauss(b []float64) ([]float64, error) {
L, U, P, err := A.LUP()
if err != nil {
return nil, err
}
return gauss(b, L, U, P)
}
// brief: Finds the eigenvalues of a square Matrix m
//
// returns: a slice of complex numbers
func (m *Matrix) Eigenvalues() ([]complex128, error) {
if m.IsSqaure() == false {
err := errors.New("Matrix should be square")
return nil, err
}
// Create an Eigen type
var eigen mat64.Eigen
// Perform eigenvalue decomposition
eigen.Factorize(*m, true)
return eigen.Values(nil), nil
}
///////////////////////////////
// HELPER //
// FUNCTIONS //
///////////////////////////////
func (m *Matrix) IsSqaure() bool {
return (m.numRows == m.numCols)
}
// brief: Calculates transpose of Matrix
//
// details: Implemented for mat64.Matrix interface
//
// returns: a transposed version of m
func (m Matrix) pivotMatrix() *Matrix {
dim := m.numRows
// Permutation Matrix to return
P := Identity(dim)
// For each column, find the row below the diagonal
// with the highest entry in that column
for j, row := range m.elems {
currentMax := row[j]
maxRow := j
for i := j; i < dim; i++ {
if m.elems[i][j] > currentMax {
currentMax = m.elems[i][j]
maxRow = i
}
}
// If the j'th entry in maxRow is
// not on the diagonal, swap the
// corresponding rows in P
if maxRow != j {
P.elems[j], P.elems[maxRow] = P.elems[maxRow], P.elems[j]
}
}
return P
}
func permDeterminant(m *Matrix) float64 {
numberOfSwitches := 0.0
for i := 0; i < m.numRows; i++ {
if m.elems[i][i] != 1 {
numberOfSwitches += 1
}
}
return math.Pow(-1.0, (numberOfSwitches / 2.0))
}
func determinant(L, U, P Matrix) (float64, error) {
n := L.numRows
// det(m) = det(L)det(P^-1)det(U)
detL := 1.0
detU := 1.0
detP := permDeterminant(&P)
// Multiply diagonals to calculate det(L) and det(U)
for i := 0; i < n; i++ {
detL = L.elems[i][i] * detL
}
for i := 0; i < n; i++ {
detU = U.elems[i][i] * detU
}
return (detL * detU * detP), nil
}
func gauss(b []float64, L *Matrix, U *Matrix, P *Matrix) ([]float64, error) {
// Multiply P
Pb, err := P.Multiply(NewMatrix(b).Transpose())
if err != nil {
return nil, err
}
// Solve Ly = Pb
y := make([]float64, len(b))
for i, row := range L.elems {
sum := 0.0
for j := 0; j < i; j++ {
sum += row[j]*y[j]
}
y[i] = (Pb.elems[i][0] - sum) / row[i]
}
//fmt.Println(b)
// Solve Ux = y
// Perform backwards substitution
x := make([]float64, len(b))
for i := len(b)- 1; i >= 0; i++ {
sum := 0.0
for j := len(b)-1; j > i; j++ {
sum += U.elems[i][j]*x[j]
}
x[i] = (y[i] - sum) / U.elems[i][0]
}
fmt.Println(x)
return x, nil
}
// brief: Finds the max entry in a
// slice of floats and it index
//
// returns: the max value in the slice and its index
func Max(s []float64) (float64, int) {
n:= len(s)
currentMax := s[0]
index := 0
for i := 1; i < n; i++ {
if s[i] > currentMax {
currentMax = s[i]
index = i
}
}
return currentMax, index
}
// brief: Calculates transpose of Matrix
//
// details: Implemented for mat64.Matrix interface
//
// returns: a transposed version of m
func (m Matrix) T() mat64.Matrix {
transpose := m.Transpose()
return *transpose
}
|
package cointop
import (
"math"
"github.com/jroimartin/gocui"
apt "github.com/miguelmota/cointop/pkg/api/types"
"github.com/miguelmota/cointop/pkg/pad"
"github.com/miguelmota/cointop/pkg/table"
)
func (ct *Cointop) layout(g *gocui.Gui) error {
maxX, maxY := ct.Size()
chartHeight := 10
topOffset := 0
if v, err := g.SetView("market", 0, topOffset, maxX, 2); err != nil {
if err != gocui.ErrUnknownView {
return err
}
ct.marketview = v
ct.marketview.Frame = false
ct.marketview.BgColor = gocui.ColorBlack
ct.marketview.FgColor = gocui.ColorWhite
ct.updateMarketbar()
}
topOffset = topOffset + 1
if v, err := g.SetView("chart", 0, topOffset, maxX, topOffset+chartHeight); err != nil {
if err != gocui.ErrUnknownView {
return err
}
ct.chartview = v
ct.chartview.Frame = false
ct.updateChart()
}
topOffset = topOffset + chartHeight
if v, err := g.SetView("header", 0, topOffset, maxX, topOffset+2); err != nil {
if err != gocui.ErrUnknownView {
return err
}
t := table.New().SetWidth(maxX)
headers := []string{
pad.Right("[r]ank", 7, " "),
pad.Right("[n]ame", 18, " "),
pad.Right("[s]ymbol", 8, " "),
pad.Left("[p]rice", 13, " "),
pad.Left("[m]arket cap", 17, " "),
pad.Left("24H [v]olume", 15, " "),
pad.Left("[1]H%", 9, " "),
pad.Left("[2]4H%", 9, " "),
pad.Left("[7]D%", 9, " "),
pad.Left("[t]otal supply", 20, " "),
pad.Left("[a]vailable supply", 18, " "),
pad.Left("[l]ast updated", 18, " "),
}
for _, h := range headers {
t.AddCol(h)
}
t.Format().Fprint(v)
ct.headersview = v
ct.headersview.Frame = false
ct.headersview.Highlight = true
ct.headersview.SelBgColor = gocui.ColorGreen
ct.headersview.SelFgColor = gocui.ColorBlack
}
topOffset = topOffset + 1
if v, err := g.SetView("table", 0, topOffset, maxX, maxY-1); err != nil {
if err != gocui.ErrUnknownView {
return err
}
ct.tableview = v
ct.tableview.Frame = false
ct.tableview.Highlight = true
ct.tableview.SelBgColor = gocui.ColorCyan
ct.tableview.SelFgColor = gocui.ColorBlack
ct.updateCoins()
ct.updateTable()
ct.rowChanged()
}
if v, err := g.SetView("statusbar", 0, maxY-2, maxX, maxY); err != nil {
if err != gocui.ErrUnknownView {
return err
}
ct.statusbarview = v
ct.statusbarview.Frame = false
ct.statusbarview.BgColor = gocui.ColorCyan
ct.statusbarview.FgColor = gocui.ColorBlack
ct.updateStatusbar("")
}
ct.intervalFetchData()
return nil
}
func (ct *Cointop) updateCoins() error {
list := []*apt.Coin{}
allcoinsmap, err := ct.api.GetAllCoinData()
if err != nil {
return err
}
ct.allcoinsmap = allcoinsmap
if len(ct.allcoins) == 0 {
for i := range ct.allcoinsmap {
coin := ct.allcoinsmap[i]
list = append(list, &coin)
}
ct.allcoins = list
ct.sort(ct.sortby, ct.sortdesc, ct.allcoins)
} else {
// update list in place without changing order
for i := range ct.allcoinsmap {
cm := ct.allcoinsmap[i]
for k := range ct.allcoins {
c := ct.allcoins[k]
if c.ID == cm.ID {
// TODO: improve this
c.ID = cm.ID
c.Name = cm.Name
c.Symbol = cm.Symbol
c.Rank = cm.Rank
c.PriceUSD = cm.PriceUSD
c.PriceBTC = cm.PriceBTC
c.USD24HVolume = cm.USD24HVolume
c.MarketCapUSD = cm.MarketCapUSD
c.AvailableSupply = cm.AvailableSupply
c.TotalSupply = cm.TotalSupply
c.PercentChange1H = cm.PercentChange1H
c.PercentChange24H = cm.PercentChange24H
c.PercentChange7D = cm.PercentChange7D
c.LastUpdated = cm.LastUpdated
}
}
}
}
return nil
}
func (ct *Cointop) updateTable() error {
start := ct.page * ct.perpage
end := start + ct.perpage
if end >= len(ct.allcoins)-1 {
start = int(math.Floor(float64(start/100)) * 100)
end = len(ct.allcoins) - 1
}
sliced := ct.allcoins[start:end]
ct.coins = sliced
ct.sort(ct.sortby, ct.sortdesc, ct.coins)
ct.refreshTable()
return nil
}
func (ct *Cointop) intervalFetchData() {
go func() {
for {
select {
case <-ct.forcerefresh:
ct.refreshAll()
case <-ct.refreshticker.C:
ct.refreshAll()
}
}
}()
}
|
package moxxiConf
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strconv"
"text/template"
)
func CreateMux(handlers []HandlerConfig, l *log.Logger) *http.ServeMux {
mux := http.NewServeMux()
for _, handler := range handlers {
switch handler.handlerType {
case "json":
mux.HandleFunc(handler.handlerRoute, JSONHandler(handler, l))
case "form":
mux.HandleFunc(handler.handlerRoute, FormHandler(handler, l))
case "static":
mux.HandleFunc(handler.handlerRoute, StaticHandler(handler, l))
}
}
return mux
}
// FormHandler - creates and returns a Handler for both Query and Form requests
func FormHandler(config HandlerConfig, l *log.Logger) http.HandlerFunc {
confWriter := confWrite(config)
return func(w http.ResponseWriter, r *http.Request) {
if extErr := r.ParseForm(); extErr != nil {
http.Error(w, extErr.Error(), http.StatusBadRequest)
return
}
if r.Form.Get("host") == "" {
pkgErr := &NewErr{Code: ErrNoHostname}
http.Error(w, pkgErr.Error(), http.StatusPreconditionFailed)
l.Println(pkgErr.LogError(r))
return
}
host := r.Form.Get("host")
if r.Form.Get("ip") == "" {
pkgErr := &NewErr{Code: ErrNoIP}
http.Error(w, pkgErr.Error(), http.StatusPreconditionFailed)
l.Println(pkgErr.LogError(r))
return
}
tls := parseCheckbox(r.Form.Get("tls"))
port, err := strconv.Atoi(r.Form.Get("port"))
if err != nil {
port = 80
}
vhost := siteParams{
IntHost: host,
IntIP: r.Form.Get("ip"),
Encrypted: tls,
IntPort: port,
StripHeaders: r.Form["header"],
}
vhost, pkgErr := confCheck(vhost, config)
if pkgErr != nil {
http.Error(w, pkgErr.Error(), http.StatusPreconditionFailed)
l.Println(pkgErr.LogError(r))
return
}
if vhost, pkgErr = confWriter(vhost); pkgErr != nil {
http.Error(w, pkgErr.Error(), http.StatusInternalServerError)
l.Println(pkgErr.LogError(r))
return
}
if extErr := config.resTempl.Execute(w, []siteParams{vhost}); extErr != nil {
http.Error(w, extErr.Error(), http.StatusInternalServerError)
l.Println(extErr.Error())
return
}
return
}
}
// JSONHandler - creates and returns a Handler for JSON body requests
func JSONHandler(config HandlerConfig, l *log.Logger) http.HandlerFunc {
var tStart, tEnd, tBody *template.Template
for _, each := range config.resTempl.Templates() {
switch each.Name() {
case "start":
tStart = each
case "end":
tEnd = each
case "body":
tBody = each
}
}
if tStart == nil || tEnd == nil || tBody == nil {
return InvalidHandler("bad template", http.StatusInternalServerError)
}
confWriter := confWrite(config)
return func(w http.ResponseWriter, r *http.Request) {
var emptyInterface interface{}
type locSiteParams struct {
ExtHost string
IntHost string
IntIP string
IntPort int
Encrypted bool
StripHeaders []string
ErrorString string
Error Err
}
tStart.Execute(w, emptyInterface)
decoder := json.NewDecoder(r.Body)
for decoder.More() {
var v siteParams
if err := decoder.Decode(&v); err != nil {
continue
}
v, err := confCheck(v, config)
if err == nil {
v, err = confWriter(v)
} else if err.GetCode() == ErrBadHostnameTrace {
var newErr Error
v, newErr = confWriter(v)
if newErr != nil {
err = newErr
}
}
var vPlus = struct {
ExtHost string
IntHost string
IntIP string
IntPort int
Encrypted bool
StripHeaders []string
Error string
}{
ExtHost: v.ExtHost,
IntHost: v.IntHost,
IntIP: v.IntIP,
IntPort: v.IntPort,
Encrypted: v.Encrypted,
StripHeaders: v.StripHeaders,
}
if err != nil {
l.Println(err.LogError(r))
vPlus.Error = err.Error()
}
if err := tBody.Execute(w, vPlus); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
l.Println(err.Error())
return
}
}
tEnd.Execute(w, emptyInterface)
}
}
// StaticHandler - creates and returns a Handler to simply respond with a static response to every request
func StaticHandler(config HandlerConfig, l *log.Logger) http.HandlerFunc {
res, err := ioutil.ReadFile(config.resFile)
if err != nil {
l.Printf("bad static response file %s - %v", config.resFile, err)
return InvalidHandler("no data", http.StatusInternalServerError)
}
return func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write(res); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
func InvalidHandler(msg string, code int) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
http.Error(w, msg, code)
}
}
|
// Package common implements common things for Oasis Core Ledger.
package common
import (
"runtime"
"strings"
)
var (
// SoftwareVersion represents the Oasis Core Ledger's version and should be
// set by the linker.
SoftwareVersion = "0.0-unset"
// ToolchainVersion is the version of the Go compiler/standard library.
ToolchainVersion = strings.TrimPrefix(runtime.Version(), "go")
// Versions contains versions of relevant dependencies.
Versions = struct {
Toolchain string
}{
ToolchainVersion,
}
)
|
package encodemain
import (
"fmt"
"gostudy/src/mystudy/encode/easyjson1"
"time"
)
func JsonEasyEncode() {
fmt.Println("<-------------------- JsonEasyEncode begin ------------------------->")
s := easyjson1.Student{
Id: 11,
Name: "qq",
School: easyjson1.School{
Name: "CUMT",
Addr: "xz",
},
Birthday: time.Now(),
}
bt, err := s.MarshalJSON()
fmt.Println(string(bt), err)
json := `{
"id":11,
"s_name":"qq",
"s_chool":
{"name":"CUMT",
"addr":"xz"},
"birthday":"2017-08-04T20:58:07.9894603+08:00"}`
ss := easyjson1.Student{}
ss.UnmarshalJSON([]byte(json))
fmt.Printf("%+v", ss)
fmt.Println("<-------------------- JsonEasyEncode end ------------------------->")
}
|
package common
import (
"flag"
"os"
"path/filepath"
)
const (
MaxConcurrentDownloadTasksNumber = 16
)
var (
MP3DownloadDir string
MP3DownloadBr int
MP3ConcurrentDownloadTasksNumber int
)
func init() {
homedir, err := os.UserHomeDir()
if err != nil {
homedir = "."
}
downloadDir := filepath.Join(homedir, "Music-Get")
flag.StringVar(&MP3DownloadDir, "o", downloadDir, "MP3 download directory")
flag.IntVar(&MP3DownloadBr, "br", 128, "MP3 prior download bit rate, 128|192|320")
flag.IntVar(&MP3ConcurrentDownloadTasksNumber, "n", 1, "MP3 concurrent download tasks number, max 16")
flag.Parse()
}
|
/*
Copyright (c) 2017 Simon Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package oohttp
import "github.com/valyala/fastrpc"
import "github.com/valyala/fasthttp"
import "bufio"
import "net"
const SniffHeader = "OOHttp"
const ProtocolVersion byte = 1
var _ fastrpc.HandlerCtx = &WrappedCtx{}
func NewHandlerCtx() fastrpc.HandlerCtx { return new(WrappedCtx) }
type WrappedCtx struct{
Ctx fasthttp.RequestCtx
}
func (w *WrappedCtx) ConcurrencyLimitError(concurrency int) {
w.Ctx.Error("Concurrency Error",fasthttp.StatusTooManyRequests)
}
func (w *WrappedCtx) Init(conn net.Conn, logger fasthttp.Logger) {
// Clear request and response
w.Ctx.Request.Reset()
w.Ctx.Response.Reset()
// Re-Init.
w.Ctx.Init2(conn, logger,false)
}
func (w *WrappedCtx) ReadRequest(br *bufio.Reader) error {
return w.Ctx.Request.Read(br)
}
func (w *WrappedCtx) WriteResponse(bw *bufio.Writer) error {
return w.Ctx.Response.Write(bw)
}
func NewHandler(hnd fasthttp.RequestHandler) func(ctx fastrpc.HandlerCtx) fastrpc.HandlerCtx {
return func(ctx fastrpc.HandlerCtx) fastrpc.HandlerCtx{
w := ctx.(*WrappedCtx)
hnd(&w.Ctx)
lter := w.Ctx.LastTimeoutErrorResponse()
if lter!=nil {
nc := new(WrappedCtx)
lter.CopyTo(&nc.Ctx.Response)
return nc
}
return ctx
}
}
var _ fastrpc.RequestWriter = &WrappedRequest{}
type WrappedRequest struct{
Req *fasthttp.Request
}
func (w *WrappedRequest) WriteRequest(bw *bufio.Writer) error {
return w.Req.Write(bw)
}
var _ fastrpc.ResponseReader = &WrappedResponse{}
type WrappedResponse struct{
Resp *fasthttp.Response
}
func (w *WrappedResponse) ReadResponse(br *bufio.Reader) error {
return w.Resp.Read(br)
}
type fakeResponse struct{}
func (f fakeResponse) ReadResponse(br *bufio.Reader) error {
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
return resp.Read(br)
}
var fakeResponseObj fastrpc.ResponseReader = &fakeResponse{}
func NewFakeResponse() fastrpc.ResponseReader { return fakeResponseObj }
|
package main
import (
"fmt"
"math"
"math/rand"
"time"
log "github.com/sirupsen/logrus"
)
const NOT_IN_PROCESS = 1
const IN_PROCESS = 2
const PROCESSED = 3
const EVENT_GAME = "game"
const EVENT_GAME_START = "game_start"
const EVENT_GAME_OVER = "game_over"
const EVENT_DAY = "day"
const EVENT_NIGHT = "night"
const EVENT_NIGHT_RESULT = "night_result"
const EVENT_COURT = "court"
const EVENT_COURT_RESULT = "court_result"
const EVENT_MAFIA = "mafia"
const EVENT_DOCTOR = "doctor"
const EVENT_SHERIFF = "sheriff"
const EVENT_SHERIFF_RESULT = "sheriff_result"
const EVENT_GIRL = "girl"
const EVENT_GREET_MAFIA = "greet_mafia"
const EVENT_GREET_CITIZENS = "greet_citizen"
const ACTION_CREATE = "create"
const ACTION_RECONNECT = "reconnect"
const ACTION_JOIN = "join"
const ACTION_START = "start"
const ACTION_END = "end"
const ACTION_OVER = "over"
const ACTION_ROLE = "role"
const ACTION_PLAYERS = "players"
const ACTION_ACCEPT = "accept"
const ACTION_VOTE = "vote"
const ACTION_CHOICE = "choice"
const ACTION_OUT = "out"
type IEvent interface {
AddAction(name string, f func(players *Players, history *EventHistory, player *Player, msg *Message) error)
Actions() map[string]func(players *Players, history *EventHistory, player *Player, msg *Message) error
Status() int
SetStatus(status int)
SetName(name string)
Name() string
Iteration() int
Process(players *Players, history *EventHistory) error
Action(players *Players, history *EventHistory, player *Player, msg *Message) error
}
type Event struct {
status int
event string
iteration int
actions map[string]func(players *Players, history *EventHistory, player *Player, msg *Message) error
}
func NewEvent() Event {
return Event{
status: NOT_IN_PROCESS,
iteration: 1,
actions: make(map[string]func(players *Players, history *EventHistory, player *Player, msg *Message) error, 0),
}
}
func (e *Event) AddAction(name string, f func(players *Players, history *EventHistory, player *Player, msg *Message) error) {
e.actions[name] = f
}
func (e *Event) Actions() map[string]func(players *Players, history *EventHistory, player *Player, msg *Message) error {
return e.actions
}
func (e *Event) Status() int {
return e.status
}
func (e *Event) SetStatus(status int) {
e.status = status
}
func (e *Event) SetName(name string) {
e.event = name
}
func (e *Event) Name() string {
return e.event
}
func (e *Event) Iteration() int {
return e.iteration
}
func (e *Event) Process(players *Players, history *EventHistory) error {
e.status = IN_PROCESS
return nil
}
func (e *Event) Action(players *Players, history *EventHistory, player *Player, msg *Message) error {
return nil
}
/*
EventChoice
*/
type IEventChoice interface {
SetChoice(choice *Player)
Choice() *Player
}
type EventChoice struct {
choice *Player
}
func (e *EventChoice) SetChoice(choice *Player) {
e.choice = choice
}
func (e *EventChoice) Choice() *Player {
return e.choice
}
/*
EventVote
*/
type IEventVote interface {
AddVoted(player *Player, vote *Player)
IsAllVoted(players []*Player) bool
FindVotedById(id int) *Player
Votes() []*Player
SetCandidate(player *Player)
Candidate() *Player
}
type EventVote struct {
voted map[*Player]*Player
candidate *Player
}
func (e *EventVote) AddVoted(player *Player, vote *Player) {
e.voted[player] = vote
}
func (e *EventVote) IsAllVoted(players []*Player) bool {
for _, player := range players {
if e.FindVotedById(player.Id()) == nil {
return false
}
}
return true
}
func (e *EventVote) FindVotedById(id int) *Player {
for player := range e.voted {
if player.Id() == id {
return player
}
}
return nil
}
func (e *EventVote) Votes() []*Player {
votes := make([]*Player, 0)
for _, vote := range e.voted {
votes = append(votes, vote)
}
return votes
}
func (e *EventVote) SetCandidate(player *Player) {
e.candidate = player
}
func (e *EventVote) Candidate() *Player {
return e.candidate
}
/*
EventQueue
*/
type EventQueue struct {
data []IEvent
}
func NewEventQueue() *EventQueue {
return &EventQueue{data: make([]IEvent, 0)}
}
func (e *EventQueue) Push(event IEvent) {
e.data = append(e.data, event)
}
func (e *EventQueue) Pop() IEvent {
if len(e.data) == 0 {
return nil
}
event := e.data[0]
e.data = e.data[1:]
return event
}
func (e *EventQueue) Len() int {
return len(e.data)
}
func (e *EventQueue) Clear() {
e.data = make([]IEvent, 0)
}
/*
EventHistory
*/
type EventHistory struct {
data []IEvent
}
func NewEventHistory() *EventHistory {
return &EventHistory{data: make([]IEvent, 0)}
}
func (e *EventHistory) Push(event IEvent) {
e.data = append(e.data, event)
}
func (e *EventHistory) FindEventChoice(eventName string, iteration int) IEventChoice {
for _, event := range e.data {
if event.Name() == eventName && event.Iteration() == iteration {
eventChoice, ok := event.(IEventChoice)
if !ok {
continue
}
return eventChoice
}
}
return nil
}
func (e *EventHistory) FindEventVote(eventName string, iteration int) IEventVote {
for _, event := range e.data {
if event.Name() == eventName && event.Iteration() == iteration {
eventVote, ok := event.(IEventVote)
if !ok {
continue
}
return eventVote
}
}
return nil
}
/*
AcceptEvent
*/
type AcceptEvent struct {
Event
accepted []*Player
action string
}
func NewAcceptEvent(iter int, event string, action string) *AcceptEvent {
e := &AcceptEvent{}
e.Event = NewEvent()
e.accepted = make([]*Player, 0)
e.status = NOT_IN_PROCESS
e.iteration = iter
e.event = event
e.action = action
e.AddAction(action, e.AcceptAction)
return e
}
func (event *AcceptEvent) AddAccepted(player *Player) {
event.accepted = append(event.accepted, player)
}
func (event *AcceptEvent) IsAllAccepted(players []*Player) bool {
for _, player := range players {
if event.FindAcceptedById(player.Id()) == nil {
return false
}
}
return true
}
func (event *AcceptEvent) FindAcceptedById(id int) *Player {
for _, player := range event.accepted {
if player.Id() == id {
return player
}
}
return nil
}
func (event *AcceptEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
for _, player := range players.FindAll() {
rmsg := NewEventMessage(event, event.action)
player.SendMessage(rmsg)
}
return nil
}
func (event *AcceptEvent) AcceptAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
event.AddAccepted(player)
if event.IsAllAccepted(players.FindAll()) {
event.SetStatus(PROCESSED)
}
return nil
}
/*
CourtEvent
*/
type CourtEvent struct {
Event
EventVote
}
func NewCourtEvent(iter int) *CourtEvent {
e := &CourtEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.iteration = iter
e.event = EVENT_COURT
e.AddAction(ACTION_VOTE, e.VoteAction)
e.voted = make(map[*Player]*Player, 0)
return e
}
func (event *CourtEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
playersInfo := make([]interface{}, 0)
for _, player := range players.FindAll() {
playerInfo := map[string]interface{}{
"username": player.Name(),
"id": player.Id(),
}
playersInfo = append(playersInfo, playerInfo)
}
response := NewEventMessage(event, ACTION_PLAYERS)
response.Data = playersInfo
for _, player := range players.FindAll() {
player.SendMessage(response)
}
return nil
}
func (event *CourtEvent) VoteAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
voteId := int(msg.Data.(float64))
vote := players.FindOneById(voteId)
if vote == nil {
rmsg := NewEventMessage(event, ACTION_PLAYERS)
rmsg.Status = STATUS_ERR
err := "invalid player id"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
rmsg := NewEventMessage(event, ACTION_VOTE)
rmsg.Data = map[string]interface{}{"player": player.Name(), "vote": vote.Name()}
for _, pl := range players.FindAll() {
pl.SendMessage(rmsg)
}
event.AddVoted(player, vote)
if event.IsAllVoted(players.FindAll()) {
event.SetStatus(PROCESSED)
}
return nil
}
/*
CourtResult
*/
type CourtResultEvent struct {
Event
AcceptEvent
}
func NewCourtResultEvent(iter int) *CourtResultEvent {
e := &CourtResultEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_COURT_RESULT
e.iteration = iter
e.AddAction(ACTION_ACCEPT, e.AcceptAction)
e.accepted = make([]*Player, 0)
return e
}
func (event *CourtResultEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
eventCourt := history.FindEventVote(EVENT_COURT, event.iteration)
if eventCourt == nil {
event.SetStatus(PROCESSED)
return fmt.Errorf("court has not event")
}
maxVotes := 0
votes := make(map[*Player]int, 0)
for _, vote := range eventCourt.Votes() {
if _, ok := votes[vote]; !ok {
votes[vote] = 0
}
votes[vote]++
if votes[vote] > maxVotes {
maxVotes = votes[vote]
}
}
candidates := make([]*Player, 0)
for candidate, vote := range votes {
if vote == maxVotes {
candidates = append(candidates, candidate)
}
}
if len(candidates) > 1 {
rmsg := NewEventMessage(event, ACTION_OUT)
for _, player := range players.FindAll() {
player.SendMessage(rmsg)
}
return fmt.Errorf("Too many candidates")
}
if len(candidates) == 0 {
rmsg := NewEventMessage(event, ACTION_OUT)
for _, player := range players.FindAll() {
player.SendMessage(rmsg)
}
return fmt.Errorf("Too few candidates")
}
courtCandidate := candidates[0]
rmsg := NewEventMessage(event, ACTION_OUT)
rmsg.Data = map[string]interface{}{"id": courtCandidate.Id(), "username": courtCandidate.Name()}
playersFor := players.FindAll()
courtCandidate.SetOut(true)
for _, player := range playersFor {
player.SendMessage(rmsg)
}
return nil
}
func (event *CourtResultEvent) AcceptAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
event.AddAccepted(player)
if event.IsAllAccepted(players.FindAll()) {
event.SetStatus(PROCESSED)
}
return nil
}
/*
DoctorEvent
*/
type DoctorEvent struct {
Event
EventChoice
}
func NewDoctorEvent(iter int) *DoctorEvent {
e := &DoctorEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_DOCTOR
e.iteration = iter
e.AddAction(ACTION_CHOICE, e.ChoiceAction)
return e
}
func (event *DoctorEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
doctor := players.FindOneByRole(ROLE_DOCTOR)
if doctor == nil {
event.status = PROCESSED
return fmt.Errorf("Player is not active")
}
playersInfo := make([]interface{}, 0)
for _, player := range players.FindAll() {
playerInfo := map[string]interface{}{
"username": player.Name(),
"id": player.Id(),
}
playersInfo = append(playersInfo, playerInfo)
}
response := NewEventMessage(event, ACTION_PLAYERS)
response.Data = playersInfo
doctor.SendMessage(response)
return nil
}
func (event *DoctorEvent) ChoiceAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
if player.Role() != ROLE_DOCTOR {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "player have wrong role for this action"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
choiceId := int(msg.Data.(float64))
choice := players.FindOneById(choiceId)
if choice == nil {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "invalid player id"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
prevEvent := history.FindEventChoice(event.Name(), event.Iteration()-1)
if prevEvent != nil &&
prevEvent.Choice() != nil &&
prevEvent.Choice().Id() == choice.Id() {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "you can not do this action with this player several times in a row"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
event.SetChoice(choice)
event.SetStatus(PROCESSED)
return nil
}
/*
GameEvent
*/
type GameEvent struct {
Event
}
func NewGameEvent() *GameEvent {
e := &GameEvent{}
e.Event = NewEvent()
e.SetName(EVENT_GAME)
e.AddAction(ACTION_CREATE, e.CreateAction)
e.AddAction(ACTION_JOIN, e.JoinAction)
e.AddAction(ACTION_START, e.StartAction)
return e
}
func (event *GameEvent) CreateAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
data := msg.Data.(map[string]interface{})
username := data["username"].(string)
if players.FindOneByUsername(username) != nil {
rmsg := NewEventMessage(event, ACTION_CREATE)
rmsg.Status = STATUS_ERR
err := "username already exists"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
player.SetName(username)
players.Add(player)
response := NewEventMessage(event, ACTION_CREATE)
response.Data = map[string]interface{}{"username": player.Name(), "id": player.Id(), "game": player.Game().Id}
player.SendMessage(response)
event.sendPlayersInfo(players)
return nil
}
func (event *GameEvent) JoinAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
data := msg.Data.(map[string]interface{})
username := data["username"].(string)
if players.FindOneByUsername(username) != nil {
rmsg := NewEventMessage(event, ACTION_JOIN)
rmsg.Status = STATUS_ERR
err := "username already exists"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
player.SetName(username)
players.Add(player)
response := NewEventMessage(event, ACTION_JOIN)
response.Data = map[string]interface{}{"username": player.Name(), "id": player.Id(), "game": player.Game().Id}
player.SendMessage(response)
event.sendPlayersInfo(players)
return nil
}
func (event *GameEvent) sendPlayersInfo(players *Players) {
playersInfo := make([]interface{}, 0)
for _, player := range players.FindAll() {
playerInfo := map[string]interface{}{
"username": player.Name(),
"id": player.Id(),
}
playersInfo = append(playersInfo, playerInfo)
}
responseForAll := NewEventMessage(event, ACTION_PLAYERS)
responseForAll.Data = playersInfo
for _, player := range players.FindAll() {
player.SendMessage(responseForAll)
}
}
func (event *GameEvent) StartAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
if !player.Master() {
rmsg := NewEventMessage(event, ACTION_START)
rmsg.Status = STATUS_ERR
err := "you have not rights to start game"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
if len(players.FindAll()) < 3 {
rmsg := NewEventMessage(event, ACTION_START)
rmsg.Status = STATUS_ERR
err := "too few players to start game"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
event.SetStatus(PROCESSED)
return nil
}
/*
GirlEvent
*/
type GirlEvent struct {
Event
EventChoice
}
func NewGirlEvent(iter int) *GirlEvent {
e := &GirlEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_GIRL
e.iteration = iter
e.AddAction(ACTION_CHOICE, e.ChoiceAction)
return e
}
func (event *GirlEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
player := players.FindOneByRole(ROLE_GIRL)
if player == nil {
event.status = PROCESSED
return fmt.Errorf("Player is not active")
}
playersInfo := make([]interface{}, 0)
for _, player := range players.FindAll() {
playerInfo := map[string]interface{}{
"username": player.Name(),
"id": player.Id(),
}
playersInfo = append(playersInfo, playerInfo)
}
response := NewEventMessage(event, ACTION_PLAYERS)
response.Data = playersInfo
player.SendMessage(response)
return nil
}
func (event *GirlEvent) ChoiceAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
if player.Role() != ROLE_GIRL {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "player have wrong role for this action"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
choiceId := int(msg.Data.(float64))
choice := players.FindOneById(choiceId)
if choice == nil {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "invalid player id"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
prevEvent := history.FindEventChoice(event.Name(), event.Iteration())
if prevEvent != nil &&
prevEvent.Choice() != nil &&
prevEvent.Choice().Id() == choice.Id() {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "you can not do this action with this player several times in a row"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
event.SetChoice(choice)
event.SetStatus(PROCESSED)
return nil
}
/*
GreetCitizensEvent
*/
type GreetCitizensEvent struct {
Event
AcceptEvent
}
func NewGreetCitizensEvent(iter int) *GreetCitizensEvent {
e := &GreetCitizensEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_GREET_CITIZENS
e.iteration = iter
e.AddAction(ACTION_ACCEPT, e.AcceptAction)
e.accepted = make([]*Player, 0)
return e
}
func Shuffle(vals []int) []int {
r := rand.New(rand.NewSource(time.Now().Unix()))
ret := make([]int, len(vals))
n := len(vals)
for i := 0; i < n; i++ {
randIndex := r.Intn(len(vals))
ret[i] = vals[randIndex]
vals = append(vals[:randIndex], vals[randIndex+1:]...)
}
return ret
}
func (event *GreetCitizensEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
playersCount := len(players.FindAll())
roles := Shuffle(event.getRoles(playersCount))
for index, player := range players.FindAll() {
player.SetRole(roles[index])
rmsg := NewEventMessage(event, ACTION_ROLE)
rmsg.Data = player.Role()
player.SendMessage(rmsg)
}
return nil
}
func (event *GreetCitizensEvent) AcceptAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
event.AddAccepted(player)
if event.IsAllAccepted(players.FindAll()) {
event.SetStatus(PROCESSED)
}
return nil
}
func (event *GreetCitizensEvent) getRoles(playersCount int) []int {
roles := make([]int, 0)
mafia := 0
girl := 0
sheriff := 0
doctor := 0
citizens := 0
switch true {
case playersCount >= 5:
mafia = int(math.Floor(float64(playersCount / 3)))
girl = 1
sheriff = 1
doctor = 1
citizens = playersCount - (girl + sheriff + doctor + mafia)
break
case playersCount == 3:
mafia = 1
doctor = 1
citizens = 1
break
case playersCount == 4:
mafia = 1
girl = 1
doctor = 1
citizens = 1
break
}
for i := 1; i <= mafia; i++ {
roles = append(roles, ROLE_MAFIA)
}
for i := 1; i <= citizens; i++ {
roles = append(roles, ROLE_CITIZEN)
}
if girl != 0 {
roles = append(roles, ROLE_GIRL)
}
if sheriff != 0 {
roles = append(roles, ROLE_SHERIFF)
}
if doctor != 0 {
roles = append(roles, ROLE_DOCTOR)
}
return roles
}
/*
GreetMafiaEvent
*/
type GreetMafiaEvent struct {
Event
AcceptEvent
}
func NewGreetMafiaEvent(iter int) *GreetMafiaEvent {
e := &GreetMafiaEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_GREET_MAFIA
e.iteration = iter
e.AddAction(ACTION_ACCEPT, e.AcceptAction)
e.accepted = make([]*Player, 0)
return e
}
func (event *GreetMafiaEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
rmsg := NewEventMessage(event, ACTION_PLAYERS)
playersInfo := make([]interface{}, 0)
for _, player := range players.FindAll() {
if player.Role() != ROLE_MAFIA {
continue
}
playerInfo := map[string]interface{}{
"username": player.Name(),
"id": player.Id(),
}
playersInfo = append(playersInfo, playerInfo)
}
rmsg.Data = playersInfo
for _, player := range players.FindByRole(ROLE_MAFIA) {
player.SendMessage(rmsg)
}
return nil
}
func (event *GreetMafiaEvent) AcceptAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
event.AddAccepted(player)
if event.IsAllAccepted(players.FindByRole(ROLE_MAFIA)) {
event.SetStatus(PROCESSED)
}
return nil
}
/*
MafiaEvent
*/
type MafiaEvent struct {
Event
EventVote
}
func NewMafiaEvent(iter int) *MafiaEvent {
e := &MafiaEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_MAFIA
e.iteration = iter
e.AddAction(ACTION_VOTE, e.VoteAction)
e.voted = make(map[*Player]*Player, 0)
return e
}
func (event *MafiaEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
playersInfo := make([]interface{}, 0)
for _, player := range players.FindAll() {
if player.Role() == ROLE_MAFIA {
continue
}
playerInfo := map[string]interface{}{
"username": player.Name(),
"id": player.Id(),
}
playersInfo = append(playersInfo, playerInfo)
}
response := NewEventMessage(event, ACTION_PLAYERS)
response.Data = playersInfo
for _, player := range players.FindByRole(ROLE_MAFIA) {
player.SendMessage(response)
}
return nil
}
func (event *MafiaEvent) VoteAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
if player.Role() != ROLE_MAFIA {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "player have wrong role for this action"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
voteId := int(msg.Data.(float64))
vote := players.FindOneById(voteId)
if vote == nil {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "invalid player id"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
event.AddVoted(player, vote)
if !event.IsAllVoted(players.FindByRole(ROLE_MAFIA)) {
return nil
}
maxVotes := 0
votes := make(map[*Player]int, 0)
for _, vote := range event.Votes() {
if _, ok := votes[vote]; !ok {
votes[vote] = 0
}
votes[vote]++
if votes[vote] > maxVotes {
maxVotes = votes[vote]
}
}
candidates := make([]*Player, 0)
for candidate, vote := range votes {
if vote == maxVotes {
candidates = append(candidates, candidate)
}
}
if len(candidates) > 1 {
event.SetStatus(PROCESSED)
return fmt.Errorf("Too many candidates")
}
if len(candidates) == 0 {
event.SetStatus(PROCESSED)
return fmt.Errorf("Too few candidates")
}
event.SetCandidate(candidates[0])
event.SetStatus(PROCESSED)
return nil
}
/*
NightResultEvent
*/
type NightResultEvent struct {
Event
AcceptEvent
}
func NewNightResultEvent(iter int) *NightResultEvent {
e := &NightResultEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_NIGHT_RESULT
e.iteration = iter
e.AddAction(ACTION_ACCEPT, e.AcceptAction)
e.accepted = make([]*Player, 0)
return e
}
func (event *NightResultEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
if event.Iteration() == 1 {
log.Debugf("event has iteration %d", event.Iteration())
event.SetStatus(PROCESSED)
return nil
}
eventMafia := history.FindEventVote(EVENT_MAFIA, event.iteration)
eventDoctor := history.FindEventChoice(EVENT_DOCTOR, event.iteration)
eventGirl := history.FindEventChoice(EVENT_GIRL, event.iteration)
var mafiaCandidate *Player
var doctorChoice *Player
var girlChoice *Player
if eventMafia != nil {
mafiaCandidate = eventMafia.Candidate()
}
if eventDoctor != nil {
doctorChoice = eventDoctor.Choice()
}
if eventGirl != nil {
girlChoice = eventGirl.Choice()
}
if mafiaCandidate == nil {
rmsg := NewEventMessage(event, ACTION_OUT)
for _, player := range players.FindAll() {
player.SendMessage(rmsg)
}
return fmt.Errorf("mafia has not candidate")
}
if girlChoice != nil && girlChoice.Id() == mafiaCandidate.Id() {
rmsg := NewEventMessage(event, ACTION_OUT)
for _, player := range players.FindAll() {
player.SendMessage(rmsg)
}
return fmt.Errorf("mafia killed no one becouse of the girl")
}
if doctorChoice != nil && doctorChoice.Id() == mafiaCandidate.Id() {
rmsg := NewEventMessage(event, ACTION_OUT)
for _, player := range players.FindAll() {
player.SendMessage(rmsg)
}
return fmt.Errorf("mafia killed no one becouse of the doctor")
}
rmsg := NewEventMessage(event, ACTION_OUT)
rmsg.Data = map[string]interface{}{"id": mafiaCandidate.Id(), "username": mafiaCandidate.Name()}
for _, player := range players.FindAll() {
player.SendMessage(rmsg)
}
mafiaCandidate.SetOut(true)
return nil
}
func (event *NightResultEvent) AcceptAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
event.AddAccepted(player)
if event.IsAllAccepted(players.FindAll()) {
event.SetStatus(PROCESSED)
}
return nil
}
/*
SheriffEvent
*/
type SheriffEvent struct {
Event
EventChoice
}
func NewSheriffEvent(iter int) *SheriffEvent {
e := &SheriffEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_SHERIFF
e.iteration = iter
e.AddAction(ACTION_CHOICE, e.ChoiceAction)
return e
}
func (event *SheriffEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
player := players.FindOneByRole(ROLE_SHERIFF)
if player == nil {
event.status = PROCESSED
return fmt.Errorf("Player is not active")
}
playersInfo := make([]interface{}, 0)
for _, player := range players.FindAll() {
if player.Role() == ROLE_SHERIFF {
continue
}
playerInfo := map[string]interface{}{
"username": player.Name(),
"id": player.Id(),
}
playersInfo = append(playersInfo, playerInfo)
}
response := NewEventMessage(event, ACTION_PLAYERS)
response.Data = playersInfo
player.SendMessage(response)
return nil
}
func (event *SheriffEvent) ChoiceAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
if player.Role() != ROLE_SHERIFF {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "player have wrong role for this action"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
choiceId := int(msg.Data.(float64))
choice := players.FindOneById(choiceId)
if choice == nil {
rmsg := NewEventMessage(event, ACTION_CHOICE)
rmsg.Status = STATUS_ERR
err := "invalid player id"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
event.SetChoice(choice)
event.SetStatus(PROCESSED)
return nil
}
/*
SheriffResultEvent
*/
type SheriffResultEvent struct {
Event
}
func NewSheriffResultEvent(iter int) *SheriffResultEvent {
e := &SheriffResultEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_SHERIFF_RESULT
e.iteration = iter
e.AddAction(ACTION_ACCEPT, e.AcceptAction)
return e
}
func (event *SheriffResultEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
sheriff := players.FindOneByRole(ROLE_SHERIFF)
sheriffEvent := history.FindEventChoice("sheriff", event.Iteration())
if sheriffEvent == nil {
event.status = PROCESSED
return fmt.Errorf("has not event")
}
if sheriffEvent.Choice() == nil {
event.status = PROCESSED
return fmt.Errorf("has not choice")
}
rmsg := NewEventMessage(event, ACTION_ROLE)
rmsg.Data = map[string]interface{}{"username": sheriffEvent.Choice().Name(), "role": sheriffEvent.Choice().Role()}
sheriff.SendMessage(rmsg)
return nil
}
func (event *SheriffResultEvent) AcceptAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
if player.Role() != ROLE_SHERIFF {
rmsg := NewEventMessage(event, ACTION_ACCEPT)
rmsg.Status = STATUS_ERR
err := "player have wrong role for this action"
rmsg.Data = err
player.SendMessage(rmsg)
return fmt.Errorf(err)
}
event.SetStatus(PROCESSED)
return nil
}
/*
GameOverEvent
*/
type GameOverEvent struct {
Event
AcceptEvent
winner int
}
func NewGameOverEvent(iter int, winner int) *GameOverEvent {
e := &GameOverEvent{}
e.Event = NewEvent()
e.status = NOT_IN_PROCESS
e.event = EVENT_GAME_OVER
e.iteration = iter
e.AddAction(ACTION_ACCEPT, e.AcceptAction)
e.winner = winner
return e
}
func (event *GameOverEvent) Process(players *Players, history *EventHistory) error {
event.status = IN_PROCESS
rmsg := NewEventMessage(event, ACTION_OVER)
rmsg.Data = event.winner
for _, player := range players.FindAllWithOut() {
player.SendMessage(rmsg)
}
return nil
}
func (event *GameOverEvent) AcceptAction(players *Players, history *EventHistory, player *Player, msg *Message) error {
event.AddAccepted(player)
if event.IsAllAccepted(players.FindAllWithOut()) {
event.SetStatus(PROCESSED)
}
return nil
}
|
package main
import "fmt"
func main() {
/*
basic "if" statement
*/
num := 10
if num%2 == 0 {
fmt.Println("The number is even")
return
}
fmt.Println("The number is odd")
/*
basic "if-else" statement
*/
num = 11
if num%2 == 0 {
fmt.Println("The number is even")
} else { //else should start right where block of if
//ends, go substitutes semicolon after
//every line and block and not doing this way
//will lead to error
fmt.Println("The number is odd")
}
/*
IDIOMATIC GO
In Go's philosophy, it is better to avoid
unnecessary branches and indentation of code.
It is also considered better to return as
early as possible.
*/
}
|
package problem0300
func lengthOfLIS(nums []int) int {
if len(nums) == 0 {
return 0
}
if len(nums) == 1 {
return 1
}
dp := make([]int, len(nums))
dp[0] = 1
ret := 1
for i := 1; i < len(nums); i++ {
dp[i] = 1
tmp := 1
for j := 0; j < i; j++ {
if nums[i] > nums[j] {
tmp = max(tmp, dp[j]+1)
}
}
dp[i] = tmp
ret = max(dp[i], ret)
}
return ret
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
|
package processor
import "mdcdntools/common"
type Processor interface {
Execute(config common.ArgsConfig) (bool, error)
}
|
package main
import "fmt"
type Animal struct {
Name string
}
type Dog struct {
Animal
}
type Sleep interface {
Sleep()
}
func (a *Animal) Eat() {
}
func (a *Animal) Sleep() {
fmt.Println(a.Name, "sleep")
}
func (a *Animal) Run() {
fmt.Println(a.Name, "running")
}
func main() {
//var sleep Sleep
//
//d:=&Dog{Animal{"cat"}}
//
//sleep=d
//
//sleep.Sleep()
d := new(Dog)
d.Name = "dog"
a := new(Animal)
a.Name = "cat"
s := []Sleep{d, a}
for _, sl := range s {
sl.Sleep()
}
}
|
package controller
import (
"github.com/golang/glog"
clientSet "github.com/gxthrj/apisix-ingress-types/pkg/client/clientset/versioned"
"github.com/gxthrj/apisix-ingress-types/pkg/client/informers/externalversions"
"github.com/api7/ingress-controller/log"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/informers"
)
var logger = log.GetLogger()
// recover any exception
func recoverException() {
if err := recover(); err != nil {
glog.Error(err)
}
}
type Api6Controller struct {
KubeClientSet kubernetes.Interface
Api6ClientSet clientSet.Interface
SharedInformerFactory externalversions.SharedInformerFactory
CoreSharedInformerFactory informers.SharedInformerFactory
Stop chan struct{}
}
func (api6 *Api6Controller) ApisixRoute() {
arc := BuildApisixRouteController(
api6.KubeClientSet,
api6.Api6ClientSet,
api6.SharedInformerFactory.Apisix().V1().ApisixRoutes())
arc.Run(api6.Stop)
}
func (api6 *Api6Controller) ApisixUpstream() {
auc := BuildApisixUpstreamController(
api6.KubeClientSet,
api6.Api6ClientSet,
api6.SharedInformerFactory.Apisix().V1().ApisixUpstreams())
auc.Run(api6.Stop)
}
func (api6 *Api6Controller) ApisixService() {
auc := BuildApisixServiceController(
api6.KubeClientSet,
api6.Api6ClientSet,
api6.SharedInformerFactory.Apisix().V1().ApisixServices())
auc.Run(api6.Stop)
}
func (api6 *Api6Controller) Endpoint() {
auc := BuildEndpointController(api6.KubeClientSet)
//conf.EndpointsInformer)
auc.Run(api6.Stop)
}
|
package app
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"github.com/gorilla/mux"
"github.com/interview304/interview/server/models"
)
func (app *App) DeleteInterviewHandler(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
idStr := vars["id"]
interviewID, err := strconv.Atoi(idStr)
if err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
if err := models.DeleteInterview(app.DB, interviewID); err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, map[string]string{"deleted": "success"})
}
func (app *App) GetQuestionDifficultyHandler(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
idStr := vars["id"]
interviewID, err := strconv.Atoi(idStr)
if err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
difficulty, err := models.GetQuestionDifficulty(app.DB, interviewID)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, map[string]string{"difficulty": difficulty})
}
func (app *App) GetInterviewsWithEveryQuestionHandler(writer http.ResponseWriter, request *http.Request) {
interviews, err := models.GetInterviewsWithEveryQuestion(app.DB)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interviews)
}
func (app *App) GetAllInterviews(writer http.ResponseWriter, request *http.Request) {
interviews, err := models.GetAllInterviews(app.DB)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interviews)
}
func (app *App) GetInterviewsHandler(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
start := vars["start"]
end := vars["end"]
position := vars["position"]
startTime, _ := url.QueryUnescape(start)
endTime, _ := url.QueryUnescape(end)
positionName, _ := url.QueryUnescape(position)
interviews, err := models.GetInterviews(app.DB, startTime, endTime, positionName)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interviews)
}
func (app *App) GetMinimumTimeHandler(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
start := vars["start"]
end := vars["end"]
position := vars["position"]
startTime, _ := url.QueryUnescape(start)
endTime, _ := url.QueryUnescape(end)
positionName, _ := url.QueryUnescape(position)
interview, err := models.GetMinimumTime(app.DB, startTime, endTime, positionName)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interview)
}
func (app *App) GetInterviewsWithLocationHandler(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
start := vars["start"]
end := vars["end"]
position := vars["position"]
startTime, _ := url.QueryUnescape(start)
endTime, _ := url.QueryUnescape(end)
positionName, _ := url.QueryUnescape(position)
interviews, err := models.GetInterviewsWithLocation(app.DB, startTime, endTime, positionName)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interviews)
}
func (app *App) IntervieweeCreateUser(writer http.ResponseWriter, request *http.Request) {
decoder := json.NewDecoder(request.Body)
defer request.Body.Close()
var interviewee models.Interviewee
if err := decoder.Decode(&interviewee); err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
if err := interviewee.IntervieweeInsert(app.DB); err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusCreated, interviewee)
}
func (app *App) IntervieweeUpdateInfo(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
idStr := vars["id"]
id, err := strconv.Atoi(idStr)
if err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
decoder := json.NewDecoder(request.Body)
var interviewee models.Interviewee
if err := decoder.Decode(&interviewee); err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
if err := interviewee.IntervieweeUpdate(app.DB, id); err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, map[string]string{"updated": "success"})
}
func (app *App) IntervieweeGetInfo(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
intervieweeId := vars["id"]
id, err := strconv.Atoi(intervieweeId)
if err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
interviewee, err := models.IntervieweeGet(app.DB, id)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interviewee)
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
setHeader(w)
w.WriteHeader(code)
w.Write(response)
}
func respondWithError(w http.ResponseWriter, code int, err error) {
respondWithJSON(w, code, map[string]string{"error": err.Error()})
}
func setHeader(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "*")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
type BookRequestBody struct {
IntervieweeID int `json:"interviewee"`
Agreement struct {
Nda bool `json:"nda"`
Tou bool `json:"tou"`
} `json:"agreement"`
}
func (app *App) BookInterview(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
id := vars["id"]
interviewID, err := strconv.Atoi(id)
if err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
var bookRequestBody BookRequestBody
decoder := json.NewDecoder(request.Body)
defer request.Body.Close()
decoder.Decode(&bookRequestBody)
if err := models.BookInterview(app.DB, interviewID, bookRequestBody.IntervieweeID,
bookRequestBody.Agreement.Nda,
bookRequestBody.Agreement.Tou); err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, map[string]string{"booked": "success"})
}
func (app *App) GetInterviewer(writer http.ResponseWriter, request *http.Request) {
interviewers, err := models.GetInterviewers(app.DB)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interviewers)
}
func (app *App) GetInterviewsByPosition(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
position := vars["position"]
positionName, err := url.QueryUnescape(position)
if err != nil {
respondWithError(writer, http.StatusBadRequest, err)
}
interviews, err := models.GetInterviewsByPosition(app.DB, positionName)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
}
respondWithJSON(writer, http.StatusOK, interviews)
}
func (app *App) GetInterviewById(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
id := vars["id"]
interviewID, err := strconv.Atoi(id)
if err != nil {
respondWithError(writer, http.StatusBadRequest, err)
return
}
interview, err := models.GetInterviewById(app.DB, interviewID)
if err != nil {
respondWithError(writer, http.StatusInternalServerError, err)
return
}
respondWithJSON(writer, http.StatusOK, interview)
}
|
package zendesk
import (
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
client "github.com/nukosuke/go-zendesk/zendesk"
)
// https://developer.zendesk.com/rest_api/docs/core/ticket_fields
func resourceZendeskTicketField() *schema.Resource {
return &schema.Resource{
Create: resourceZendeskTicketFieldCreate,
Read: resourceZendeskTicketFieldRead,
Update: resourceZendeskTicketFieldUpdate,
Delete: resourceZendeskTicketFieldDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"url": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"checkbox",
"date",
"decimal",
"integer",
"regexp",
"tagger",
"text",
"textarea",
}, false),
},
"title": {
Type: schema.TypeString,
Required: true,
},
"raw_title": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"raw_description": {
Type: schema.TypeString,
Optional: true,
},
"position": {
Type: schema.TypeInt,
Optional: true,
// positions 0 to 7 are reserved for system fields
ValidateFunc: validation.IntAtLeast(8),
},
"active": {
Type: schema.TypeBool,
Optional: true,
},
"required": {
Type: schema.TypeBool,
Optional: true,
},
"collapsed_for_agents": {
Type: schema.TypeBool,
Optional: true,
},
"regexp_for_validation": {
Type: schema.TypeString,
Optional: true,
// Regular expression field only
//TODO: validation
},
"title_in_portal": {
Type: schema.TypeString,
Optional: true,
// The title of the ticket field is mandatory when it's visible to end users
//TODO: validation
},
"raw_title_in_portal": {
Type: schema.TypeString,
Optional: true,
//TODO: same to title_in_portal
},
"visible_in_portal": {
Type: schema.TypeBool,
Optional: true,
},
"editable_in_portal": {
Type: schema.TypeBool,
Optional: true,
},
"required_in_portal": {
Type: schema.TypeBool,
Optional: true,
},
"tag": {
Type: schema.TypeString,
Optional: true,
},
"system_field_options": {
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Computed: true,
},
// Required only for "tagger" type
// https://developer.zendesk.com/rest_api/docs/support/ticket_fields#updating-drop-down-field-options
"custom_field_option": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
},
Optional: true,
//TODO: empty is invalid form
},
// "priority" and "status" fields only
"sub_type_id": {
Type: schema.TypeInt,
Optional: true,
//TODO: validation
},
//TODO: this is not necessary because it's only for system field
"removable": {
Type: schema.TypeBool,
Computed: true,
},
"agent_description": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceZendeskTicketFieldCreate(d *schema.ResourceData, meta interface{}) error {
zd := meta.(*client.Client)
tf := client.TicketField{
Type: d.Get("type").(string),
Title: d.Get("title").(string),
}
// Handle type specific value
switch d.Get("type") {
case "regexp":
tf.RegexpForValidation = d.Get("regexp_for_validation").(string)
case "tagger":
options := d.Get("custom_field_option").(*schema.Set).List()
for _, option := range options {
tf.CustomFieldOptions = append(tf.CustomFieldOptions, client.TicketFieldCustomFieldOption{
Name: option.(map[string]interface{})["name"].(string),
Value: option.(map[string]interface{})["value"].(string),
})
}
default:
// nop
}
// Actual API request
tf, err := zd.CreateTicketField(tf)
if err != nil {
return err
}
d.SetId(fmt.Sprintf("%d", tf.ID))
d.Set("url", tf.URL)
return resourceZendeskTicketFieldRead(d, meta)
}
func resourceZendeskTicketFieldRead(d *schema.ResourceData, meta interface{}) error {
return nil
}
func resourceZendeskTicketFieldUpdate(d *schema.ResourceData, meta interface{}) error {
return nil
}
func resourceZendeskTicketFieldDelete(d *schema.ResourceData, meta interface{}) error {
return nil
}
|
/*
Connects to the Binance WebSocket and write orderBook to redis
*/
package main
// import "github.com/davecgh/go-spew/spew"
import "time"
import (
"encoding/json"
"fmt"
"github.com/go-redis/redis"
"github.com/gorilla/websocket"
"github.com/pdepip/go-binance/binance"
"log"
"os"
"strconv"
"strings"
"sync"
)
const (
MaxDepth = 100 // Size of order book
MaxQueue = 100 // Size of message queue
)
// Message received from websocket
type State struct {
EventType string `json:"e"`
EventTime int64 `json:"E"`
Symbol string `json:"s"`
UpdateId int64 `json:"u"`
BidDelta []binance.Order `json:"b"`
AskDelta []binance.Order `json:"a"`
}
// Orderbook structure
type OrderBook struct {
Bids map[float64]float64 // Map of all bids, key->price, value->quantity
BidMutex sync.Mutex // Threadsafe
CoinType string // coin type of orderBook such as: ethbtc...
Asks map[float64]float64 // Map of all asks, key->price, value->quantity
AskMutex sync.Mutex // Threadsafe
Client *redis.Client // Redis client to store data to redis
Updates chan State // Channel of all state updates
}
// to convert a float number to a string
func FloatToString(input_num float64) string {
return strconv.FormatFloat(input_num, 'f', -1, 64)
}
func (o *OrderBook) HashKey(otype string) string {
bidKey := fmt.Sprintf("%s-%s", o.CoinType, otype)
return bidKey
}
func (o *OrderBook) DeleteFromRedis(otype string, price float64) {
hashKey := o.HashKey(otype)
hDel := o.Client.HDel(hashKey, FloatToString(price))
if hDel.Err() != nil {
fmt.Printf("Delete price: %f from %s failed\n", price, hashKey)
}
}
func (o *OrderBook) StoreToRedis(otype string, price float64, quantity float64) {
hashKey := o.HashKey(otype)
hSet := o.Client.HSet(hashKey, FloatToString(price), FloatToString(quantity))
if hSet.Err() != nil {
fmt.Printf("Store price: %f and quantity: %f to redis hash key: %s failed\n", price, quantity, hashKey)
}
}
// Process all incoming bids
func (o *OrderBook) ProcessBids(bids []binance.Order) {
for _, bid := range bids {
if bid.Quantity == 0 {
o.DeleteFromRedis("bids", bid.Price)
} else {
o.StoreToRedis("bids", bid.Price, bid.Quantity)
}
}
}
// Process all incoming asks
func (o *OrderBook) ProcessAsks(asks []binance.Order) {
for _, ask := range asks {
if ask.Quantity == 0 {
o.DeleteFromRedis("asks", ask.Price)
} else {
o.StoreToRedis("asks", ask.Price, ask.Quantity)
}
}
}
// Hands off incoming messages to processing functions
func (o *OrderBook) Maintainer() {
for {
select {
case job := <-o.Updates:
if len(job.BidDelta) > 0 {
go o.ProcessBids(job.BidDelta)
}
if len(job.AskDelta) > 0 {
go o.ProcessAsks(job.AskDelta)
}
}
}
}
func GetEnv(key string, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func FetchOrderBook(symbol string) {
db, _ := strconv.Atoi(GetEnv("REDIS_DB", "0"))
redisClient := redis.NewClient(&redis.Options{
Addr: GetEnv("REDIS_HOST", "localhost:6379"),
Password: GetEnv("REDIS_PASSWORD", ""), // no password set
DB: db,
})
address := fmt.Sprintf("wss://stream.binance.com:9443/ws/%s@depth", symbol)
// Connect to websocket
var wsDialer = &websocket.Dialer{HandshakeTimeout: 30 * time.Second}
wsConn, _, err := wsDialer.Dial(address, nil)
if err != nil {
panic(err)
}
defer wsConn.Close()
log.Println("Dialed:", address)
// Set up Order Book
ob := OrderBook{}
ob.Bids = make(map[float64]float64, MaxDepth)
ob.Asks = make(map[float64]float64, MaxDepth)
ob.Updates = make(chan State, 500)
ob.Client = redisClient
ob.CoinType = symbol
// Get initial state of orderbook from rest api
client := binance.New("", "")
query := binance.OrderBookQuery{
Symbol: strings.ToUpper(symbol),
}
orderBook, err := client.GetOrderBook(query)
if err != nil {
panic(err)
}
ob.ProcessBids(orderBook.Bids)
ob.ProcessAsks(orderBook.Asks)
// Start maintaining order book
go ob.Maintainer()
// Read & Process Messages from wss stream
for {
_, message, err := wsConn.ReadMessage()
if err != nil {
log.Println("[ERROR] ReadMessage:", err)
}
msg := State{}
err = json.Unmarshal(message, &msg)
if err != nil {
log.Println("[ERROR] Parsing:", err)
continue
}
ob.Updates <- msg
}
}
func main() {
fmt.Println("start fetching binance order book")
FetchOrderBook("ethbtc")
}
|
package main
import "fmt"
//结构体是值类型
type person struct {
name string
age int
gender bool
hobby []string
}
func f1(x person) {
x.gender = false
}
func f2(y *person) {
(*y).gender = false
}
func main() {
var p person
p.name = "老王"
p.gender = true
f1(p)
fmt.Println(p)
f2(&p)
fmt.Println(p)
var p2 = new(person)
p2.name = "Aniy"
fmt.Printf("%T\n", p2)
fmt.Printf("%p\n", p2)
fmt.Println(p2)
}
|
package cli
import "github.com/spf13/cobra"
func newServerCommand(cli *CLI) *cobra.Command {
cmd := &cobra.Command{
Use: "server",
Short: "Manage servers",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableFlagsInUseLine: true,
}
cmd.AddCommand(
newServerListCommand(cli),
newServerDescribeCommand(cli),
newServerCreateCommand(cli),
newServerDeleteCommand(cli),
newServerRebootCommand(cli),
newServerPoweronCommand(cli),
newServerPoweroffCommand(cli),
newServerResetCommand(cli),
newServerShutdownCommand(cli),
newServerCreateImageCommand(cli),
newServerResetPasswordCommand(cli),
newServerEnableRescueCommand(cli),
newServerDisableRescueCommand(cli),
newServerAttachISOCommand(cli),
newServerDetachISOCommand(cli),
newServerUpdateCommand(cli),
newServerChangeTypeCommand(cli),
newServerRebuildCommand(cli),
newServerEnableBackupCommand(cli),
newServerDisableBackupCommand(cli),
newServerEnableProtectionCommand(cli),
newServerDisableProtectionCommand(cli),
newServerSSHCommand(cli),
newServerAddLabelCommand(cli),
newServerRemoveLabelCommand(cli),
newServerSetRDNSCommand(cli),
newServerAttachToNetworkCommand(cli),
newServerDetachFromNetworkCommand(cli),
newServerChangeAliasIPsCommand(cli),
newServerIPCommand(cli),
newServerRequestConsoleCommand(cli),
newServerMetricsCommand(cli),
)
return cmd
}
|
package main
import(
"crypto/md5"
"fmt"
"io"
"log"
"os"
)
// Function main opens a txt file and checks if the file exists if not logs an errors.
// Creates a new md5 hash and copies the hash to the file and logs any errors
// Prints the hash sum and closes the file
func main() {
file, err := os.Open("filename.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
hash := md5.new()
if _,err := io.Copy(hash, file); err != nil {
log.Fatal(err)
}
fmt.Printf("%x", hash.sum(nil))
}
|
/**
* menu_vo
* @author liuzhen
* @Description
* @version 1.0.0 2021/3/9 21:34
*/
package module
// 路由菜单
type Menu struct {
// 名称
Label string `json:"label"`
// 路径
Path string `json:"path"`
// 名称
Name string `json:"name"`
// 图标
Icon string `json:"icon"`
// 子路由
Children []Menu `json:"children"`
}
|
package xmpp
import (
"encoding/xml"
"fmt"
)
type Element struct {
StartElement xml.StartElement
EndElement xml.EndElement
CharData string
Comment xml.Comment
ProcInst xml.ProcInst
Directive xml.Directive
Children []*Element
Parent *Element
}
func NewElement(parent *Element) *Element {
elem := new(Element)
elem.Children = make([]*Element, 1)
if parent != nil {
parent.Children = append(parent.Children, elem)
elem.Parent = parent
}
return elem
}
func (elem *Element) Name() xml.Name {
return elem.StartElement.Name
}
func (elem *Element) NameWithSpace() string {
return elem.Name().Local + elem.Name().Space
}
func (elem *Element) AttrMap() map[string]string {
return ToMap(elem.StartElement.Attr)
}
func (elem *Element) IsMessage() bool {
if elem.NameWithSpace() != "message"+NsJabberClient {
return false
}
attr := elem.AttrMap()
return attr["type"] == "groupchat" || attr["type"] == "chat"
}
type elemMatcher func(*Element) bool
func (elem *Element) FindChild(matcher elemMatcher) *Element {
for _, child := range elem.Children {
if child == nil {
continue
}
if matcher(child) {
return child
}
}
return nil
}
func (elem *Element) String() string {
result := fmt.Sprintf("(start:%v", elem.StartElement)
charData := elem.CharData
if charData != "" {
result += fmt.Sprintf(", charData:%v", charData)
}
if len(elem.Children) > 0 {
result += ", children:("
for _, child := range elem.Children {
if child == nil {
continue
}
result += child.String()
}
result += ")"
}
result += ")"
return result
}
|
package routetable
import (
"context"
"fmt"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/giantswarm/microerror"
"github.com/giantswarm/micrologger"
"github.com/giantswarm/aws-operator/service/controller/legacy/v26/controllercontext"
)
const (
Name = "routetablev26"
)
type Config struct {
Logger micrologger.Logger
Names []string
}
type Resource struct {
logger micrologger.Logger
// mappings is a mapping of route table names and IDs, where the key is the
// name and the value is the ID.
mappings map[string]string
mutex sync.Mutex
names []string
}
func New(config Config) (*Resource, error) {
if config.Logger == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Logger must not be empty", config)
}
if config.Names == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Names must not be empty", config)
}
r := &Resource{
logger: config.Logger,
mappings: map[string]string{},
mutex: sync.Mutex{},
names: config.Names,
}
return r, nil
}
func (r *Resource) Name() string {
return Name
}
func (r *Resource) addRouteTableMappingsToContext(ctx context.Context) error {
r.mutex.Lock()
defer r.mutex.Unlock()
cc, err := controllercontext.FromContext(ctx)
if err != nil {
return microerror.Mask(err)
}
// We check if we have all mappings cached for the configured route table
// names. If we find all information, we return them.
{
r.logger.LogCtx(ctx, "level", "debug", "message", "finding cached route table mappings")
if len(r.mappings) == len(r.names) {
r.logger.LogCtx(ctx, "level", "debug", "message", "found cached route table mappings")
cc.Status.ControlPlane.RouteTable.Mappings = r.mappings
return nil
} else {
r.logger.LogCtx(ctx, "level", "debug", "message", "did not find cached route table mappings")
}
}
// We do not have the cached mappings, so we look them up.
mappings := map[string]string{}
for _, name := range r.names {
id, err := r.lookup(ctx, cc.Client.ControlPlane.AWS.EC2, name)
if err != nil {
return microerror.Mask(err)
}
mappings[name] = id
}
// At this point we found all route table mappings and can cache them
// internally.
{
r.logger.LogCtx(ctx, "level", "debug", "message", "caching route table mappings")
r.mappings = mappings
r.logger.LogCtx(ctx, "level", "debug", "message", "cached route table mappings")
}
cc.Status.ControlPlane.RouteTable.Mappings = mappings
return nil
}
func (r *Resource) lookup(ctx context.Context, client EC2, name string) (string, error) {
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("finding route table ID for %#q", name))
i := &ec2.DescribeRouteTablesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:Name"),
Values: []*string{
aws.String(name),
},
},
},
}
o, err := client.DescribeRouteTables(i)
if err != nil {
return "", microerror.Mask(err)
}
if len(o.RouteTables) != 1 {
return "", microerror.Maskf(executionFailedError, "expected one route table, got %d", len(o.RouteTables))
}
id := *o.RouteTables[0].RouteTableId
r.logger.LogCtx(ctx, "level", "debug", "message", fmt.Sprintf("found route table ID %#q for %#q", id, name))
return id, nil
}
|
package mixmux
import (
"net/http"
"strings"
"github.com/dimfeld/httptreemux/v5"
)
// TreeMux wraps HTTPTreeMux.
type TreeMux struct {
t *httptreemux.TreeMux
path string
reg map[string][]string
}
// NewTreeMux returns a wrapped HTTPTreeMux.
func NewTreeMux(opts *Options) *TreeMux {
t := &TreeMux{
t: httptreemux.New(),
path: "",
reg: make(map[string][]string),
}
if opts == nil {
opts = &Options{}
}
if opts.NotFound != nil {
t.t.NotFoundHandler = opts.NotFound.ServeHTTP
}
if opts.MethodNotAllowed != nil {
t.t.MethodNotAllowedHandler = func(w http.ResponseWriter, r *http.Request, m map[string]httptreemux.HandlerFunc) {
opts.MethodNotAllowed.ServeHTTP(w, r)
}
}
t.t.RedirectTrailingSlash = opts.RedirectTrailingSlash
t.t.RedirectCleanPath = opts.RedirectFixedPath
t.t.RedirectTrailingSlash = true
return t
}
func (m *TreeMux) addToReg(method, path string) {
_, ok := m.reg[path]
if !ok {
m.reg[path] = []string{}
}
m.reg[path] = append(m.reg[path], method)
}
func (m *TreeMux) handle(method, path string, handler http.Handler) {
m.t.Handle(method, path, treeMuxWrapper(handler))
m.addToReg(method, path)
}
func (m *TreeMux) lookup(method, path string) (bool, bool) {
ckSlsh := false
if m.t.RedirectTrailingSlash && path[len(path)-1] != '/' {
ckSlsh = true
}
meths, ok := m.reg[path]
if !ok {
return false, ckSlsh
}
for _, m := range meths {
if m == method {
return true, false
}
}
return false, ckSlsh
}
// Group takes a path and returns a new TreeMux wrapping the original TreeMux.
func (m *TreeMux) Group(path string) *TreeMux {
return &TreeMux{m.t, m.path + path, m.reg}
}
// GroupMux takes a path and returns a new TreeMux wrapping the original TreeMux.
func (m *TreeMux) GroupMux(path string) Mux {
return &TreeMux{m.t, m.path + path, m.reg}
}
// Any takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Any(path string, h http.Handler) {
p := m.path + path
m.handle(http.MethodOptions, p, h)
m.handle(http.MethodGet, p, h)
m.handle(http.MethodPost, p, h)
m.handle(http.MethodPut, p, h)
m.handle(http.MethodPatch, p, h)
m.handle(http.MethodDelete, p, h)
m.handle(http.MethodHead, p, h)
m.handle(http.MethodTrace, p, h)
m.handle(http.MethodConnect, p, h)
}
// Options takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Options(path string, h http.Handler) {
m.handle(http.MethodOptions, m.path+path, h)
}
// Get takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Get(path string, h http.Handler) {
m.handle(http.MethodGet, m.path+path, h)
}
// Post takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Post(path string, h http.Handler) {
m.handle(http.MethodPost, m.path+path, h)
}
// Put takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Put(path string, h http.Handler) {
m.handle(http.MethodPut, m.path+path, h)
}
// Patch takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Patch(path string, h http.Handler) {
m.handle(http.MethodPatch, m.path+path, h)
}
// Delete takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Delete(path string, h http.Handler) {
m.handle(http.MethodDelete, m.path+path, h)
}
// Head takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Head(path string, h http.Handler) {
m.handle(http.MethodHead, m.path+path, h)
}
// Trace takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Trace(path string, h http.Handler) {
m.handle(http.MethodTrace, m.path+path, h)
}
// Connect takes a path and http.Handler and adds them to the mux.
func (m *TreeMux) Connect(path string, h http.Handler) {
m.handle(http.MethodConnect, m.path+path, h)
}
// ServeHTTP satisfies the http.Handler interface.
func (m *TreeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.t.ServeHTTP(w, r)
}
// CORSMethods ... TODO:
func (m *TreeMux) CORSMethods(path string, handlerWrappers ...func(http.Handler) http.Handler) {
ms := []string{http.MethodOptions}
for _, v := range methods {
if v == http.MethodOptions {
continue
}
x, s := m.lookup(v, path)
if s {
x, _ = m.lookup(v, path+"/")
}
if !x {
continue
}
ms = append(ms, v)
}
opts := strings.Join(ms, ", ")
var fn http.Handler
fn = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Methods", opts)
})
for _, wrap := range handlerWrappers {
if wrap != nil {
fn = wrap(fn)
}
}
m.Options(path, fn)
}
func treeMuxWrapper(next http.Handler) httptreemux.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, _ map[string]string) {
next.ServeHTTP(w, r)
}
}
|
package main
type smallStruct struct {
a, b int64
c, d float64
}
func main() {
smallAllocation()
}
// The annotation //go:noinline will disable in-lining that would optimize the code by removing the function and,
// therefore, end up with no allocation.
//go:noinline
func smallAllocation() *smallStruct {
return &smallStruct{}
}
|
package build
import (
"runtime"
)
// Info represents all available build & runtime environment information.
type Info struct {
Version string `json:"version,omitempty"`
CommitHash string `json:"commit_hash,omitempty"`
BuildDate string `json:"build_date,omitempty"`
GoVersion string `json:"go_version,omitempty"`
Os string `json:"os,omitempty"`
Arch string `json:"arch,omitempty"`
Compiler string `json:"compiler,omitempty"`
}
// NewInfo returns all available build information.
func NewInfo() *Info {
return &Info{
Version: Version,
CommitHash: CommitHash,
BuildDate: BuildDate,
GoVersion: runtime.Version(),
Os: runtime.GOOS,
Arch: runtime.GOARCH,
Compiler: runtime.Compiler,
}
}
|
package logging
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/sirupsen/logrus"
)
const (
AutoLogFile = "auto"
logDateFormat = "2006-01-02T15-04-05"
)
// FileHook to send logs to the trace file regardless of CLI level.
type FileHook struct {
// Logger is a reference to the internal Logger that this utilizes.
Logger *logrus.Logger
// File is a reference to the file being written to.
File *os.File
// FilePath is the full path used when creating the file.
FilePath string
// Closed reports whether the hook has been closed. Once closed
// it can't be written to again.
Closed bool
}
func NewFileHook(path string) (*FileHook, error) {
if path == AutoLogFile {
path = filepath.Join(os.Getenv("HOME"), ".crashd", getLogNameFromTime(time.Now()))
}
file, err := os.Create(path)
logger := logrus.New()
logger.SetLevel(logrus.TraceLevel)
logger.SetOutput(file)
logrus.Infof("Detailed logs being written to: %v", path)
return &FileHook{Logger: logger, File: file, FilePath: path}, err
}
func (hook *FileHook) Fire(entry *logrus.Entry) error {
if hook.Closed {
return nil
}
switch entry.Level {
case logrus.PanicLevel:
hook.Logger.Panic(entry.Message)
case logrus.FatalLevel:
hook.Logger.Fatal(entry.Message)
case logrus.ErrorLevel:
hook.Logger.Error(entry.Message)
case logrus.WarnLevel:
hook.Logger.Warning(entry.Message)
case logrus.InfoLevel:
hook.Logger.Info(entry.Message)
case logrus.DebugLevel:
hook.Logger.Debug(entry.Message)
case logrus.TraceLevel:
hook.Logger.Trace(entry.Message)
default:
hook.Logger.Info(entry.Message)
}
return nil
}
func (hook *FileHook) Levels() []logrus.Level {
return logrus.AllLevels
}
// CloseFileHooks will close each file being used for each FileHook attached to the logger.
// If the logger passed is nil, will reference the logrus.StandardLogger().
func CloseFileHooks(l *logrus.Logger) error {
// All the hooks we utilize are just tied to the standard logger.
logrus.Debugln("Closing log file; future log calls will not be persisted.")
if l == nil {
l = logrus.StandardLogger()
}
for _, fh := range GetFileHooks(l) {
fh.File.Close()
fh.Closed = true
}
return nil
}
// GetFirstFileHook is a convenience method to take an object and returns the first
// FileHook attached to it. Accepts an interface{} since the logger objects may be put
// into context or thread objects. The obj should be a *logrus.Logger object.
func GetFirstFileHook(obj interface{}) *FileHook {
fhs := GetFileHooks(obj)
if len(fhs) > 0 {
return fhs[0]
}
return nil
}
// GetFileHooks is a convenience method to take an object and returns the
// FileHooks attached to it. Accepts an interface{} since the logger objects may be put
// into context or thread objects. The obj should be a *logrus.Logger object.
func GetFileHooks(obj interface{}) []*FileHook {
l, ok := obj.(*logrus.Logger)
if !ok {
return nil
}
result := []*FileHook{}
for _, hooks := range l.Hooks {
for _, hook := range hooks {
switch fh := hook.(type) {
case *FileHook:
result = append(result, fh)
}
}
}
return result
}
func getLogNameFromTime(t time.Time) string {
return fmt.Sprintf("crashd_%v.log", t.Format(logDateFormat))
}
|
package main
import (
"time"
"github.com/clarketm/json"
log "github.com/sirupsen/logrus"
"github.com/streadway/amqp"
)
var conn *amqp.Connection
var ch *amqp.Channel
var init_err error
var password string
var status StatusFH
func init() {
log.Trace("Initialised rabbitmq package")
status = StatusFH{
LastFault: "N/A"}
}
func SetPassword(pass string) {
password = pass
}
func failOnError(err error, msg string) {
if err != nil {
log.WithFields(log.Fields{
"Message": msg, "Error": err,
}).Trace("Rabbitmq error")
}
}
func getTime() string {
t := time.Now()
log.Trace(t.Format(TIMEFORMAT))
return t.Format(TIMEFORMAT)
}
func messages(routing_key string, value string) {
log.Warn("Adding messages to map")
if SubscribedMessagesMap == nil {
log.Warn("Creation of messages map")
SubscribedMessagesMap = make(map[uint32]*MapMessage)
messages(routing_key, value)
} else {
_, valid := SubscribedMessagesMap[key_id]
if valid {
log.Debug("Key already exists, checking next field: ", key_id)
if key_id == 100 {
key_id = 0
}
key_id++
messages(routing_key, value)
} else {
log.Debug("Key does not exists, adding new field: ", key_id)
entry := MapMessage{value, routing_key, getTime(), true}
SubscribedMessagesMap[key_id] = &entry
key_id++
}
}
}
func SetConnection() error {
conn, init_err = amqp.Dial("amqp://guest:" + password + "@localhost:5672/")
failOnError(init_err, "Failed to connect to RabbitMQ")
ch, init_err = conn.Channel()
failOnError(init_err, "Failed to open a channel")
return init_err
}
func Subscribe() {
init := SetConnection()
log.Trace("Beginning rabbitmq initialisation")
log.Warn("Rabbitmq error:", init)
if init == nil {
var topics = [4]string{
MOTIONRESPONSE,
FAILURE,
MONITORSTATE,
DEVICEFOUND,
}
err := ch.ExchangeDeclare(
EXCHANGENAME, // name
EXCHANGETYPE, // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
failOnError(err, "FH - Failed to declare an exchange")
q, err := ch.QueueDeclare(
"", // name
false, // durable
false, // delete when usused
true, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
for _, s := range topics {
log.Printf("Binding queue %s to exchange %s with routing key %s",
q.Name, EXCHANGENAME, s)
err = ch.QueueBind(
q.Name, // queue name
s, // routing key
EXCHANGENAME, // exchange
false,
nil)
failOnError(err, "Failed to bind a queue")
}
msgs, err := ch.Consume(
q.Name, // queue
"", // consumer
true, // auto ack
false, // exclusive
false, // no local
false, // no wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
forever := make(chan bool)
go func() {
for d := range msgs {
log.Trace("Sending message to callback")
log.Trace(d.RoutingKey)
s := string(d.Body)
messages(d.RoutingKey, s)
log.Debug("Checking states of received messages")
checkState()
}
//This function is checked after to see if multiple errors occur then to
//through an event message
}()
log.Trace(" [*] Waiting for logs. To exit press CTRL+C")
<-forever
}
}
func StatusCheck() {
valid := publishStatusFH()
if valid != "" {
log.Warn("Failed to publish")
} else {
log.Debug("Published Status FH")
}
}
func Publish(message []byte, routingKey string) string {
if init_err == nil {
log.Debug(string(message))
err := ch.Publish(
EXCHANGENAME, // exchange
routingKey, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/json",
Body: []byte(message),
})
if err != nil {
log.Fatal(err)
return FAILUREPUBLISH
}
}
return ""
}
func publishAlarmEvent(user string, state string) string {
alarm, err := json.Marshal(&AlarmEvent{
User: user,
State: state})
if err != nil {
return "Failed to convert AlarmEvent"
} else {
return Publish(alarm, ALARMEVENT)
}
}
func publishMotion() string {
alarm, _ := json.Marshal(&AlarmEvent{
User: "",
State: ""})
return Publish(alarm, MOTIONEVENT)
}
func publishCameraStart() string {
emailRequest, err := json.Marshal(&Basic{
Message: ""})
if err != nil {
return "Failed to convert CameraStart"
} else {
return Publish(emailRequest, CAMERASTART)
}
}
func publishCameraStop() string {
emailRequest, err := json.Marshal(&Basic{
Message: ""})
if err != nil {
return "Failed to convert CameraStop"
} else {
return Publish(emailRequest, CAMERASTOP)
}
}
func publishStatusFH() string {
message, err := json.Marshal(&status)
if err != nil {
return "Failed to convert StatusFH"
} else {
return Publish(message, STATUSFH)
}
}
|
package controllers
import (
"fmt"
"github.com/garyburd/redigo/redis"
"quickstart/helper"
"quickstart/models"
"time"
)
func init() {
}
type PostController struct {
baseApiController
}
func (this *PostController) Prepare() {
this.baseApiController.Prepare()
schemaString := map[string]string{
"POST": `
{
"properties": {
"content": {"type": ["string", "null"], "default": "" },
"pics": {
"type": ["array", "null"],
"items": {
"type": "object",
"properties": {
"desc": {"type": "string"},
"thumbnail": {"type": "string"},
"url": {"type": "string"}
}
}
},
"feed_id": {
"type": "number"
}
},
"type": "object"
}`,
"GET": `
{
"properties": {
"get_key": {
"type": "string"
}
},
"required": ["get_key"],
"type": "object"
}`,
}
_, err := helper.Validate_Json(
schemaString[this.Ctx.Request.Method], this.Data["input_map"].(map[string]interface{}))
if err != nil {
fmt.Println(err.Error())
this.Abort("400")
}
}
type Post struct {
Content string `redis:"content"`
Pics string `redis:"pics"`
Flag int64 `redis:"flag"`
Time int64 `redis:"time"`
}
func (this *PostController) Post() {
models.RedisInstance().C.Do("INCR", "post_next_id")
post_next_id, _ := redis.Int64(models.RedisInstance().C.Do("GET", "post_next_id"))
if this.Data["input_map"].(map[string]interface{})["pics"] == nil && this.Data["input_map"].(map[string]interface{})["content"] == nil {
this.Abort("400")
}
var post Post
post.Content, _ = this.Data["input_map"].(map[string]interface{})["content"].(string)
post.Flag = 2323232
post.Pics, _ = this.Data["input_map"].(map[string]interface{})["pics"].(string)
post.Time = time.Now().Unix()
if _, err := models.RedisInstance().C.Do("HMSET",
redis.Args{}.Add("post:"+string(post_next_id)).AddFlat(&post)...); err != nil {
fmt.Println(err)
}
v, err := redis.Values(models.RedisInstance().C.Do("HGETALL", "post:"+string(post_next_id)))
if err != nil {
fmt.Println(err)
}
var post1 Post
if err := redis.ScanStruct(v, &post1); err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", post1)
this.Data["json"] = map[string]interface{}{
"post": "hello world"}
this.ServeJson()
}
|
package main
import "fmt"
// InsertionSort sorts by insertion
func InsertionSort(A []int, display bool) []int {
var i, j int
n := len(A)
for j = 1; j < n; j++ {
if display && n <= 10 {
fmt.Printf("%v =>", A)
}
key := A[j]
i = j - 1
for i > -1 && A[i] > key {
A[i+1] = A[i]
if display && n <= 10 {
fmt.Printf(" - %v - ", A)
}
i = i - 1
}
A[i+1] = key
if display && n <= 10 {
fmt.Printf(" => %v\n", A)
}
}
return A
}
|
package qqmeeting
import (
"bytes"
"crypto"
"crypto/hmac"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// Describe A Request
type MeetingRequestDescriptor struct {
Url string
Method string
Tag string
}
// MeetingRequest interface
type MeetingRequest interface {
getDescriptor() *MeetingRequestDescriptor
fillPlaceholder(args ...interface{}) string
}
type MeetingResponse interface {
}
type MeetingErrorResponse struct {
StatusCode int `json:"-"`
ErrorInfo *MeetingError `json:"error_info"`
}
type MeetingError struct {
Code int `json:"error_code"`
Message string `json:"message"`
}
func (e MeetingError) Error() string {
return fmt.Sprintf("server error: %s (%d)", e.Message, e.Code)
}
type Pager struct {
TotalCount int `json:"total_count"` // 总数
CurrentSize int `json:"current_size"` // 当前页实际大小
CurrentPage int `json:"current_page"` // 当前页数
PageSize int `json:"page_size"` // 分页大小
}
type Meeting struct {
SecretKey string
SecretID string
AppID string
SdkID string
Version string // 软件版本,用于调试
Registered int // 企业用户管理,最好开,否则主持人的功能用不了
}
// RequestBody Descriptor
type Request struct {
Method string
URL *url.URL
Secret string
Body string
Key string `json:"X-TC-Key"`
Timestamp int64 `json:"X-TC-Timestamp"`
Nonce int `json:"X-TC-Nonce"`
Signature string `json:"X-TC-Signature"`
AppID string `json:"AppId"`
SdkID string `json:"SdkId"`
Version string `json:"X-TC-Version"`
Registered int `json:"X-TC-Registered"`
ContentType string `json:"Content-Type"`
ContentLength string `json:"Content-Length"`
}
//var proxyUrl, _ = url.Parse("http://127.0.0.1:18080")
var client = &http.Client{
Transport: &http.Transport{
//Proxy: http.ProxyURL(proxyUrl),
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: false,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
func GetHttpClient() *http.Client {
return client
}
func newMeetingRequest(method, path, body string, meeting Meeting) *Request {
req := new(Request)
req.ContentType = "application/json"
req.Method = method
req.URL, _ = url.Parse(path)
req.Secret = meeting.SecretKey
req.Body = body
req.Timestamp = time.Now().Unix()
req.Key = meeting.SecretID
req.Nonce = rand.Intn(10000) + 10000
req.Version = meeting.Version
req.AppID = meeting.AppID
req.Registered = meeting.Registered
req.SdkID = meeting.SdkID
return req
}
func NewRequest(method, url, body string, meeting Meeting) (*http.Request, error) {
method = strings.ToUpper(method)
req, err := http.NewRequest(method, url, strings.NewReader(body))
if err != nil {
return nil, err
}
mReq := newMeetingRequest(method, url, body, meeting)
fillSignature(mReq)
fillHeader(mReq, &req.Header)
return req, nil
}
func serializeHeader(request *Request) string {
var buf bytes.Buffer
buf.WriteString("X-TC-Key=" + request.Key +
"&" + "X-TC-Nonce=" + strconv.Itoa(request.Nonce) +
"&" + "X-TC-Timestamp=" + strconv.Itoa(int(request.Timestamp)))
return buf.String()
}
func fillHeader(req *Request, header *http.Header) () {
callback := func(n, v string) () {
//fmt.Printf("%s:%s\n", n, v)
(*header)[n] = []string{v}
}
fillFields(req, callback)
}
func fillSignature(req *Request) {
ques := ""
if len(req.URL.RawQuery) > 0 {
ques = "?"
}
stringToSign := req.Method + "\n" + serializeHeader(req) + "\n" + req.URL.Path + ques + req.URL.RawQuery + "\n" + req.Body
hm := hmac.New(crypto.SHA256.New, []byte(req.Secret))
hm.Write([]byte(stringToSign))
result := hm.Sum(nil)
// debug stub
//log.Println(stringToSign)
req.Signature = base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(result)))
}
func fillFields(req *Request, callback func(name, value string) ()) {
ref := reflect.ValueOf(*req)
typ := reflect.TypeOf(*req)
numRef := ref.NumField()
for i := 0; i < numRef; i++ {
field := ref.Field(i)
fieldType := typ.Field(i)
if fieldType.Tag.Get("json") != "" && !field.IsZero() {
switch field.Kind() {
case reflect.String:
callback(fieldType.Tag.Get("json"), field.String())
case reflect.Int64:
callback(fieldType.Tag.Get("json"), strconv.Itoa(int(field.Int())))
case reflect.Int:
callback(fieldType.Tag.Get("json"), strconv.Itoa(int(field.Int())))
}
}
}
}
func (meeting Meeting) Do(req MeetingRequest) (MeetingResponse, error) {
descriptor := req.getDescriptor()
_, method := descriptor.Url, descriptor.Method
urlAppendix := bytes.NewBufferString("")
urlAppendixFlag := false
reqBody := ""
typ := reflect.TypeOf(req)
val := reflect.ValueOf(req)
params := make([]interface{}, 0, 3)
queries := NewQueryValues()
// inject params and queries
for i := 0; i < typ.NumField(); i++ {
fTyp := typ.Field(i)
fVal := val.Field(i)
if !fVal.IsZero() && fTyp.Tag.Get("query") != "" {
urlAppendixFlag = true
switch fVal.Kind() {
case reflect.String:
queries.Add(fTyp.Tag.Get("query"), fVal.String())
case reflect.Int, reflect.Int64, reflect.Int32:
queries.Add(fTyp.Tag.Get("query"), strconv.Itoa(int(fVal.Int())))
case reflect.Bool:
queries.Add(fTyp.Tag.Get("query"), strconv.FormatBool(fVal.Bool()))
default:
// not formatted. print type
queries.Add(fTyp.Tag.Get("query"), fVal.String())
}
} // if
// 按照struct的顺序来填充数据
if !fVal.IsZero() && fTyp.Tag.Get("param") != "" {
switch fVal.Kind() {
case reflect.String:
params = append(params, fVal.String())
case reflect.Int, reflect.Int64, reflect.Int32:
params = append(params, strconv.Itoa(int(fVal.Int())))
case reflect.Bool:
params = append(params, strconv.FormatBool(fVal.Bool()))
}
} // if
} // for
if urlAppendixFlag {
urlAppendix.WriteString("?" + queries.Encode())
}
switch method {
case "POST", "PUT":
body, err := json.Marshal(req)
if err != nil {
log.Println(err)
return nil, err
}
reqBody = string(body)
}
hReq, err := NewRequest(method, ApiHost+req.fillPlaceholder(params...)+urlAppendix.String(), reqBody, meeting)
if err != nil {
log.Println(err)
return nil, err
}
resp, err := client.Do(hReq)
if err != nil {
log.Println(err)
return nil, err
} else {
res, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode == 200 {
response, err := meeting.handleResponse(res, descriptor)
if err != nil {
return nil, err
} else {
return response, nil
}
} else {
var errorResponse MeetingErrorResponse
err := json.Unmarshal(res, &errorResponse)
if err != nil {
return nil, err
} else {
return nil, *(errorResponse.ErrorInfo)
}
}
}
}
|
package main
import (
consulApi "github.com/hashicorp/consul/api"
vaultApi "github.com/hashicorp/vault/api"
"os"
"log"
"net/http"
"fmt"
)
const ServiceNameEnvKey = "SERVICE_NAME"
func main() {
//Setup a webserver that retrieves the configuration from Consul
http.HandleFunc("/", serve)
if err := http.ListenAndServe(":8888", nil); err != nil {
panic(err)
}
}
func serve(response http.ResponseWriter, request *http.Request) {
message := getMatch()
response.Header().Set("Content-Type", "text/html; charset=utf-8")
response.Write([]byte(message))
}
func getMatch() string {
consulClient := getConsulClient()
appScopedConfig := getConsulConfig(consulClient)
sharedConfig := getSharedConfig(consulClient)
vaultToken := getVaultKey(consulClient)
nextMove := getNextMove(vaultToken)
//Build an HTML image that links to the configured Pokemon
pokemon := string(appScopedConfig.Value)
gym := string(sharedConfig.Value)
message := "<p style=\"font-family: 'Comic Sans MS', 'Comic Sans', cursive; font-size: 24px;\">" +
"The chosen pokemon is: <br /><br />" + pokemon + "</p><br />"
message += "<img src=\"https://img.pokemondb.net/artwork/" + pokemon + ".jpg\">"
message += "<br /><br /><p style=\"font-family: 'Comic Sans MS', 'Comic Sans', cursive; font-size: 18px;\">" +
"The battle takes place at: <b>" + gym + "</b></p>"
message += "<br /><p style=\"font-family: 'Comic Sans MS', 'Comic Sans', cursive; font-size: 18px;\">" +
"Their next move is:<b>" + nextMove + "</b></p><br />"
return message
}
func getNextMove(vaultToken string) string {
vaultConfig := vaultApi.DefaultConfig()
vaultConfig.Address = "http://vault.service.consul:8200"
vaultClient, err := vaultApi.NewClient(vaultConfig)
check(err)
vaultClient.SetToken(vaultToken)
vault := vaultClient.Logical()
nextMove, err := vault.Read("/secret/" + getServiceName() + "/nextmove")
check(err)
return fmt.Sprintf("%v", nextMove.Data["value"])
}
func getVaultKey(consulClient *consulApi.Client) string {
consulServiceName := getServiceName()
vaultTokenKey, _, err := consulClient.KV().Get("/service/vault/" + consulServiceName+"-token", nil)
check(err)
if vaultTokenKey == nil {
log.Fatalln("Error accessing Consul ")
}
return string(vaultTokenKey.Value)
}
func getConsulConfig(consulClient *consulApi.Client) *consulApi.KVPair {
//Lookup up the name of this service from the environment,
//this will be used as the namespace in the KV store
consulServiceName := getServiceName()
//Query the key value and find the pokemon that has been configured for the app
appScopedConfig, _, err := consulClient.KV().Get(consulServiceName+"/pokemon", nil)
check(err)
if appScopedConfig == nil {
log.Fatalln("Error accessing Consul ")
}
return appScopedConfig
}
func getSharedConfig(consulClient *consulApi.Client) *consulApi.KVPair {
//Lookup up the name of this service from the environment,
//this will be used as the namespace in the KV store
sharedConfig, _, err := consulClient.KV().Get("/shared/gym", nil)
check(err)
if sharedConfig == nil {
log.Fatalln("Error accessing Consul ")
}
return sharedConfig
}
func getConsulClient() (*consulApi.Client) {
//Build the Consul client, notice that we don't need to specify any
//hard-coded URL as the environment variable CONSUL_HTTP_ADDR has been specified
consulConfig := consulApi.DefaultConfig()
consulConfig.Address = "consul.service.consul:8500"
client, err := consulApi.NewClient(consulConfig)
check(err)
return client
}
func getServiceName() string {
service := os.Getenv(ServiceNameEnvKey)
if service == "" {
log.Fatalln(ServiceNameEnvKey + " must be set as an environment variable")
}
return service
}
func check(err error) {
if err != nil {
}
}
|
package handler
import (
"sync/atomic"
)
var internalRequestCounter int64
func getNewRequestID() int64 {
return atomic.AddInt64(&internalRequestCounter, 1)
}
|
// Copyright 2017 PingCAP, 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 ranger
import (
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/collate"
)
// conditionChecker checks if this condition can be pushed to index planner.
type conditionChecker struct {
checkerCol *expression.Column
length int
optPrefixIndexSingleScan bool
}
func (c *conditionChecker) isFullLengthColumn() bool {
return c.length == types.UnspecifiedLength || c.length == c.checkerCol.GetType().GetFlen()
}
// check returns two values, isAccessCond and shouldReserve.
// isAccessCond indicates whether the condition can be used to build ranges.
// shouldReserve indicates whether the condition should be reserved in filter conditions.
func (c *conditionChecker) check(condition expression.Expression) (isAccessCond, shouldReserve bool) {
switch x := condition.(type) {
case *expression.ScalarFunction:
return c.checkScalarFunction(x)
case *expression.Column:
if x.RetType.EvalType() == types.ETString {
return false, true
}
return c.checkColumn(x)
case *expression.Constant:
return true, false
}
return false, true
}
func (c *conditionChecker) checkScalarFunction(scalar *expression.ScalarFunction) (isAccessCond, shouldReserve bool) {
_, collation := scalar.CharsetAndCollation()
switch scalar.FuncName.L {
case ast.LogicOr, ast.LogicAnd:
isAccessCond0, shouldReserve0 := c.check(scalar.GetArgs()[0])
isAccessCond1, shouldReserve1 := c.check(scalar.GetArgs()[1])
if isAccessCond0 && isAccessCond1 {
return true, shouldReserve0 || shouldReserve1
}
return false, true
case ast.EQ, ast.NE, ast.GE, ast.GT, ast.LE, ast.LT, ast.NullEQ:
if _, ok := scalar.GetArgs()[0].(*expression.Constant); ok {
if c.matchColumn(scalar.GetArgs()[1]) {
// Checks whether the scalar function is calculated use the collation compatible with the column.
if scalar.GetArgs()[1].GetType().EvalType() == types.ETString && !collate.CompatibleCollate(scalar.GetArgs()[1].GetType().GetCollate(), collation) {
return false, true
}
isFullLength := c.isFullLengthColumn()
if scalar.FuncName.L == ast.NE {
return isFullLength, !isFullLength
}
return true, !isFullLength
}
}
if _, ok := scalar.GetArgs()[1].(*expression.Constant); ok {
if c.matchColumn(scalar.GetArgs()[0]) {
// Checks whether the scalar function is calculated use the collation compatible with the column.
if scalar.GetArgs()[0].GetType().EvalType() == types.ETString && !collate.CompatibleCollate(scalar.GetArgs()[0].GetType().GetCollate(), collation) {
return false, true
}
isFullLength := c.isFullLengthColumn()
if scalar.FuncName.L == ast.NE {
return isFullLength, !isFullLength
}
return true, !isFullLength
}
}
case ast.IsNull:
if c.matchColumn(scalar.GetArgs()[0]) {
var isNullReserve bool // We can know whether the column is null from prefix column of any length.
if !c.optPrefixIndexSingleScan {
isNullReserve = !c.isFullLengthColumn()
}
return true, isNullReserve
}
return false, true
case ast.IsTruthWithoutNull, ast.IsFalsity, ast.IsTruthWithNull:
if s, ok := scalar.GetArgs()[0].(*expression.Column); ok {
if s.RetType.EvalType() == types.ETString {
return false, true
}
}
return c.checkColumn(scalar.GetArgs()[0])
case ast.UnaryNot:
// TODO: support "not like" convert to access conditions.
s, ok := scalar.GetArgs()[0].(*expression.ScalarFunction)
if !ok {
// "not column" or "not constant" can't lead to a range.
return false, true
}
if s.FuncName.L == ast.Like || s.FuncName.L == ast.NullEQ {
return false, true
}
return c.check(scalar.GetArgs()[0])
case ast.In:
if !c.matchColumn(scalar.GetArgs()[0]) {
return false, true
}
if scalar.GetArgs()[0].GetType().EvalType() == types.ETString && !collate.CompatibleCollate(scalar.GetArgs()[0].GetType().GetCollate(), collation) {
return false, true
}
for _, v := range scalar.GetArgs()[1:] {
if _, ok := v.(*expression.Constant); !ok {
return false, true
}
}
return true, !c.isFullLengthColumn()
case ast.Like:
return c.checkLikeFunc(scalar)
case ast.GetParam:
// TODO
return true, false
}
return false, true
}
func (c *conditionChecker) checkLikeFunc(scalar *expression.ScalarFunction) (isAccessCond, shouldReserve bool) {
_, collation := scalar.CharsetAndCollation()
if collate.NewCollationEnabled() && !collate.IsBinCollation(collation) {
// The algorithm constructs the range in byte-level: for example, ab% is mapped to [ab, ac] by adding 1 to the last byte.
// However, this is incorrect for non-binary collation strings because the sort key order is not the same as byte order.
// For example, "`%" is mapped to the range [`, a](where ` is 0x60 and a is 0x61).
// Because the collation utf8_general_ci is case-insensitive, a and A have the same sort key.
// Finally, the range comes to be [`, A], which is actually an empty range.
// See https://github.com/pingcap/tidb/issues/31174 for more details.
// In short, when the column type is non-binary collation string, we cannot use `like` expressions to generate the range.
return false, true
}
if !collate.CompatibleCollate(scalar.GetArgs()[0].GetType().GetCollate(), collation) {
return false, true
}
if !c.matchColumn(scalar.GetArgs()[0]) {
return false, true
}
pattern, ok := scalar.GetArgs()[1].(*expression.Constant)
if !ok {
return false, true
}
if pattern.Value.IsNull() {
return false, true
}
patternStr, err := pattern.Value.ToString()
if err != nil {
return false, true
}
if len(patternStr) == 0 {
return true, !c.isFullLengthColumn()
}
escape := byte(scalar.GetArgs()[2].(*expression.Constant).Value.GetInt64())
likeFuncReserve := !c.isFullLengthColumn()
for i := 0; i < len(patternStr); i++ {
if patternStr[i] == escape {
i++
if i < len(patternStr)-1 {
continue
}
break
}
if i == 0 && (patternStr[i] == '%' || patternStr[i] == '_') {
return false, true
}
if patternStr[i] == '%' {
// We currently do not support using `enum like 'xxx%'` to build range
// see https://github.com/pingcap/tidb/issues/27130 for more details
if scalar.GetArgs()[0].GetType().GetType() == mysql.TypeEnum {
return false, true
}
if i != len(patternStr)-1 {
likeFuncReserve = true
}
break
}
if patternStr[i] == '_' {
// We currently do not support using `enum like 'xxx_'` to build range
// see https://github.com/pingcap/tidb/issues/27130 for more details
if scalar.GetArgs()[0].GetType().GetType() == mysql.TypeEnum {
return false, true
}
likeFuncReserve = true
break
}
}
return true, likeFuncReserve
}
func (c *conditionChecker) matchColumn(expr expression.Expression) bool {
// Check if virtual expression column matched
if c.checkerCol != nil {
return c.checkerCol.EqualByExprAndID(nil, expr)
}
return false
}
func (c *conditionChecker) checkColumn(expr expression.Expression) (isAccessCond, shouldReserve bool) {
if c.matchColumn(expr) {
return true, !c.isFullLengthColumn()
}
return false, true
}
|
package pubsub_test
import (
"os"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/hellodhlyn/go-pubsub"
)
func TestSubscriber_SubscribeFunc_Success(t *testing.T) {
subscriber := pubsub.NewSubscriber(validQueue{})
// Send SIGTERM after 10 ms.
pid := os.Getpid()
go func() { time.Sleep(10 * time.Millisecond); _ = syscall.Kill(pid, syscall.SIGTERM) }()
msgCnt := 0
fn := func(message string) {
msgCnt += 1
assert.Equal(t, message, "dummy-message")
}
err := subscriber.SubscribeFunc(fn)
assert.EqualError(t, err, "received signal: terminated")
assert.NotEqual(t, msgCnt, 0)
}
func TestSubscriber_SubscribeFunc_Error(t *testing.T) {
subscriber := pubsub.NewSubscriber(errorQueue{})
msgCnt := 0
err := subscriber.SubscribeFunc(func(_ string) { msgCnt += 1 })
assert.EqualError(t, err, "something went wrong :(")
assert.Equal(t, msgCnt, 0)
}
|
/*
Copyright (c) 2018 Red Hat, 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 main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
"github.com/segmentio/ksuid"
"github.com/container-mgmt/dedicated-portal/pkg/api"
)
// ClustersService performs operations on clusters.
type ClustersService interface {
List(args ListArguments) (clusters api.ClusterList, err error)
Create(spec api.Cluster, provision bool) (result api.Cluster, err error)
Get(id string) (result api.Cluster, err error)
}
// GenericClustersService is a ClusterService placeholder implementation.
type GenericClustersService struct {
connectionURL string
provisioner ClusterProvisioner
}
// ListArguments are arguments relevant for listing objects.
type ListArguments struct {
Page int
Size int
}
// NewClustersService Creates a new ClustersService.
func NewClustersService(connectionURL string, provisioner ClusterProvisioner) ClustersService {
service := new(GenericClustersService)
service.connectionURL = connectionURL
service.provisioner = provisioner
return service
}
// List returns lists of clusters.
func (cs GenericClustersService) List(args ListArguments) (result api.ClusterList, err error) {
result.Items = make([]*api.Cluster, 0)
db, err := sql.Open("postgres", cs.connectionURL)
if err != nil {
return api.ClusterList{}, fmt.Errorf("Error openning connection: %v", err)
}
defer db.Close()
total, err := cs.getClusterCount(db)
if err != nil {
return api.ClusterList{}, err
}
rows, err := db.Query(`SELECT
id,
name,
region,
master_nodes,
infra_nodes,
compute_nodes,
memory,
cpu_cores,
storage,
state
FROM clusters
ORDER BY id
LIMIT $1
OFFSET $2`,
args.Size,
args.Page*args.Size,
)
if err != nil {
return api.ClusterList{}, fmt.Errorf("Error executing query: %v", err)
}
defer rows.Close()
for rows.Next() {
var (
id string
name string
region string
masterNodes int
infraNodes int
computeNodes int
memory int
cpuCores int
storage int
state api.ClusterState
)
err = rows.Scan(
&id,
&name,
®ion,
&masterNodes,
&infraNodes,
&computeNodes,
&memory,
&cpuCores,
&storage,
&state)
if err != nil {
return api.ClusterList{}, err
}
totalNodes := masterNodes + infraNodes + computeNodes
result.Items = append(result.Items, &api.Cluster{
Name: name,
Region: region,
ID: id,
Nodes: api.ClusterNodes{
Total: totalNodes,
Master: masterNodes,
Infra: infraNodes,
Compute: computeNodes,
},
Memory: api.ClusterResource{
Total: memory,
Used: 0,
},
CPU: api.ClusterResource{
Total: cpuCores,
Used: 0,
},
Storage: api.ClusterResource{
Total: storage,
Used: 0,
},
State: state,
})
}
err = rows.Err() // get any error encountered during iteration
if err != nil {
return api.ClusterList{}, err
}
result.Page = args.Page
result.Size = len(result.Items)
result.Total = total
return result, nil
}
// Create saves a new cluster definition in the Database
func (cs GenericClustersService) Create(spec api.Cluster, provision bool) (result api.Cluster, err error) {
id, err := ksuid.NewRandom()
if err != nil {
return api.Cluster{}, err
}
if provision {
// Use cluster provisioner to Provision a cluster.
err = cs.provisioner.Provision(spec)
if err != nil {
return api.Cluster{}, fmt.Errorf("An error occurred while trying to provision cluster %s: %s",
spec.Name, err)
}
}
db, err := sql.Open("postgres", cs.connectionURL)
if err != nil {
return api.Cluster{}, err
}
defer db.Close()
stmt, err := db.Prepare(`
INSERT INTO clusters (
id,
name,
region,
master_nodes,
infra_nodes,
compute_nodes,
memory,
cpu_cores,
storage,
state
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10)
`)
if err != nil {
return api.Cluster{}, err
}
defer stmt.Close()
queryResult, err := stmt.Exec(
id,
spec.Name,
spec.Region,
spec.Nodes.Master,
spec.Nodes.Infra,
spec.Nodes.Compute,
spec.Memory.Total,
spec.CPU.Total,
spec.Storage.Total,
api.ClusterStateInstalling)
if err != nil {
return api.Cluster{}, err
}
inserted, err := queryResult.RowsAffected()
if err != nil {
return api.Cluster{}, err
}
if inserted != 1 {
return api.Cluster{}, fmt.Errorf("Error: [%d] rows inserted. 1 expected",
inserted,
)
}
totalNodes := spec.Nodes.Master + spec.Nodes.Infra + spec.Nodes.Compute
return api.Cluster{
Name: spec.Name,
ID: id.String(),
Region: spec.Region,
Nodes: api.ClusterNodes{
Total: totalNodes,
Master: spec.Nodes.Master,
Infra: spec.Nodes.Infra,
Compute: spec.Nodes.Compute,
},
Memory: api.ClusterResource{
Total: spec.Memory.Total,
Used: 0,
},
CPU: api.ClusterResource{
Total: spec.CPU.Total,
Used: 0,
},
Storage: api.ClusterResource{
Total: spec.Storage.Total,
Used: 0,
},
State: api.ClusterStateInstalling,
}, nil
}
// Get returns a single cluster by id
func (cs GenericClustersService) Get(id string) (result api.Cluster, err error) {
db, err := sql.Open("postgres", cs.connectionURL)
if err != nil {
return api.Cluster{}, err
}
defer db.Close()
var (
name string
region string
masterNodes int
infraNodes int
computeNodes int
memory int
cpuCores int
storage int
state api.ClusterState
)
err = db.QueryRow(`
SELECT
id,
name,
region,
master_nodes,
infra_nodes,
compute_nodes,
memory,
cpu_cores,
storage,
state
FROM clusters
WHERE id = $1`, id).Scan(
&id,
&name,
®ion,
&masterNodes,
&infraNodes,
&computeNodes,
&memory,
&cpuCores,
&storage,
&state)
if err != nil {
return api.Cluster{}, err
}
totalNodes := masterNodes + infraNodes + computeNodes
return api.Cluster{
Name: name,
Region: region,
ID: id,
Nodes: api.ClusterNodes{
Total: totalNodes,
Master: masterNodes,
Infra: infraNodes,
Compute: computeNodes,
},
Memory: api.ClusterResource{
Total: memory,
Used: 0,
},
CPU: api.ClusterResource{
Total: cpuCores,
Used: 0,
},
Storage: api.ClusterResource{
Total: storage,
Used: 0,
},
State: state,
},
nil
}
func (cs GenericClustersService) getClusterCount(db *sql.DB) (total int, err error) {
// retrieve total number of clusters.
err = db.QueryRow("select count(*) from clusters").Scan(&total)
return
}
|
package riverntorch
import (
"bytes"
"fmt"
"sort"
"strings"
)
type Person struct {
//specifies the name of the person
Name string `yaml:"name"`
//specifies the time it takes for the person to cross.
Duration int `yaml:"minutes"`
}
//
// people that needs to cross river.
//
type RiverCrossers []*Person
//
// sort the crossers as per the ascending time they take to cross
//
func (this RiverCrossers) Sort() RiverCrossers {
sort.Sort(this)
return this
}
//
// Override the default String() method. for custom printing.
//
func (this RiverCrossers) String() string {
str := make([]string, len(this))
for _, v := range this {
str = append(str, fmt.Sprintf("%s %d", v.Name, v.Duration))
}
return strings.Join(str, "\n")
}
//
// Sorting methods.
//
func (this RiverCrossers) Len() int {
return len(this)
}
func (this RiverCrossers) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}
func (this RiverCrossers) Less(i, j int) bool {
return this[i].Duration < this[j].Duration
}
//
// PeopleOnBridge stores the index of people crossing bridge.
//
type PeopleOnBridge struct {
fastOne, slowOne int
}
//
// Solution stores the meta and details about the approach used.
//
type Solution struct {
//name of approach used to figure out solution.
approachName string
// time it took for crossers to cross.
duration int
// procedure/ steps followed for crossing.
set [][]Person
}
// Initialize Solution construct.
func (this *Solution) Initialize() {
this.set = make([][]Person, 0)
}
//
// Override the default String() method. for custom printing.
//
func (this Solution) String() string {
buf := bytes.NewBuffer(nil)
var frwd, bck int
for _, v := range this.set {
if len(v) == 2 {
frwd++
buf.WriteString(fmt.Sprintf("side A -> sideB : %s + %s\n", v[1].Name, v[0].Name))
}
if len(v) == 1 {
bck++
buf.WriteString(fmt.Sprintf("side A <- sideB : %s\n", v[0].Name))
}
}
if len(this.set) > 1 {
buf.WriteString(fmt.Sprintf("\nForward Steps: %d, Backward Steps: %d\n", frwd, bck))
}
buf.WriteString(fmt.Sprintf("Using %s\n\n", this.approachName))
buf.WriteString("########################################\n")
buf.WriteString(fmt.Sprintf("Total time Taken: %d minutes\n", this.duration))
buf.WriteString("########################################\n")
return buf.String()
}
|
package main
import (
"coolgo/oop/student1"
"fmt"
"gothinking/oop/student2"
)
func TestStudent1() {
s1 := student1.Student{}
s1.Init("John", 25, "cs")
s1.SayHi()
// Error: implicit assignment of unexported field 'name' in student1.Student
//s2 := student1.Student{"Aimi", 24, "math"}
//s2.SayHi()
//Error: s1.name undefined (cannot refer to unexported field or method name)
//fmt.Println(s1.name)
}
func TestStudent2() {
s1 := student2.Student{}
s1.Init("John", 25, "cs")
s1.SayHi()
s1.Major = "finance"
s1.SayHi()
//试图修改私有属性
//Error: s1.age undefined
//s1.age = 28
// OK: s1.GetAge()
fmt.Printf("age is %d\n", s1.GetAge())
//试图调用私有方法
// Error:s1.getAge undefined
//fmt.Printf("age is %d\n" , s1.getAge())
}
func main() {
TestStudent1()
//TestStudent2()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.