text stringlengths 11 4.05M |
|---|
package bot
import (
"strings"
"time"
"github.com/gempir/gempbot/internal/bot/commander"
"github.com/gempir/gempbot/internal/chat"
"github.com/gempir/gempbot/internal/config"
"github.com/gempir/gempbot/internal/dto"
"github.com/gempir/gempbot/internal/helixclient"
"github.com/gempir/gempbot/internal/log"
"github.com/gempir/gempbot/internal/store"
)
// Bot basic logging bot
type Bot struct {
startTime time.Time
cfg *config.Config
db *store.Database
helixClient helixclient.Client
listener *commander.Listener
Done chan bool
ChatClient *chat.ChatClient
}
func NewBot(cfg *config.Config, db *store.Database, helixClient helixclient.Client) *Bot {
chatClient := chat.NewClient(cfg)
handler := commander.NewHandler(cfg, helixClient, db, chatClient.Say)
listener := commander.NewListener(db, handler, chatClient.Say)
listener.RegisterDefaultCommands()
return &Bot{
Done: make(chan bool),
ChatClient: chatClient,
cfg: cfg,
db: db,
listener: listener,
helixClient: helixClient,
}
}
func (b *Bot) RegisterCommand(command string, handler func(dto.CommandPayload)) {
b.listener.RegisterCommand(command, handler)
}
func (b *Bot) Say(channel string, message string) {
go b.ChatClient.Say(channel, message)
}
func (b *Bot) SayByChannelID(channelID string, message string) {
userData, err := b.helixClient.GetUserByUserID(channelID)
if err != nil {
log.Error(err)
return
}
go b.ChatClient.Say(userData.Login, message)
}
func (c *Bot) Reply(channel string, parentMsgId string, message string) {
c.ChatClient.Reply(channel, parentMsgId, message)
}
func (b *Bot) Join(channel string) {
go b.ChatClient.Join(channel)
}
func (b *Bot) Part(channel string) {
go b.ChatClient.Part(channel)
}
func (b *Bot) Connect() {
b.startTime = time.Now()
b.ChatClient.SetOnPrivateMessage(b.listener.HandlePrivateMessage)
go b.ChatClient.Connect(b.joinBotConfigChannels)
if strings.HasPrefix(b.cfg.Username, "justinfan") {
log.Info("joining as anonymous")
} else {
log.Info("joining as user " + b.cfg.Username)
}
go b.ChatClient.Join(b.cfg.Username)
}
func (b *Bot) joinBotConfigChannels() {
botConfigs := b.db.GetAllJoinBotConfigs()
userIDs := []string{}
for _, botConfig := range botConfigs {
userIDs = append(userIDs, botConfig.OwnerTwitchID)
}
users, err := b.helixClient.GetUsersByUserIds(userIDs)
if err != nil {
log.Error(err)
}
b.ChatClient.WaitForConnect()
log.Infof("joining %d channels", len(users))
for _, user := range users {
b.ChatClient.Join(user.Login)
}
}
|
package e
const (
CACHE_ARTICLE = "cache:article"
CACHE_TAG = "cache:tag"
)
|
package main
import "fmt"
/*
slice删除元素的坑
copy复制会比等号复制慢。但是copy复制为值复制,改变原切片的值不会影响新切片。
而等号复制为指针复制,改变原切片或新切片都会对另一个产生影响。
*/
func main() {
nums := []int{1,2,3,4}
k := 2
//res := append(nums[:k], nums[k+1:]...)
//fmt.Println(res) // [1 2 4]
//fmt.Println(nums) // [1 2 4 4]
//正确处理方式
temp := make([]int, len(nums[:k]))
copy(temp, nums[:k])
temp = append(temp, nums[k+1:]...)
fmt.Println(temp)
fmt.Println(nums)
}
|
package main
import "fmt"
func main() {
a := 10
b := &a
fmt.Println(a, b, *b)
fmt.Printf("%T %T %T\n", a, b, *b)
// Function can take pointer as parameter or can return a pointer
x := 10
doubleIt(&x)
fmt.Println(x)
}
func doubleIt(a *int) {
*a = *a * 2
}
|
package cache
import (
"testing"
)
func TestCache_Cache(t *testing.T) {
cacher := NewCommonCacher()
if success, err := cacher.Cache("a", Entry{RegionName:"region_a", CityName:"cityname_a"}); success == true {
t.Log("cache a success")
}else{
t.Error(err)
}
if success, err := cacher.Cache("b", Entry{RegionName:"region_b", CityName:"cityname_b"}); success== true {
t.Log("cache b success")
}else{
t.Error(err)
}
t.Log(cacher.PrintContainer())
}
func TestCache_Get(t *testing.T) {
cacher := NewCommonCacher()
if success, err := cacher.Cache("a", Entry{RegionName:"region_a", CityName:"cityname_a"}); success == true {
t.Log("cache a success")
}else{
t.Error(err)
}
if success, err := cacher.Cache("b", Entry{RegionName:"region_b", CityName:"cityname_b"}); success== true {
t.Log("cache b success")
}else{
t.Error(err)
}
if entry, err := cacher.Get("a"); err == nil {
t.Log(entry.CityName, entry.RegionName)
}
t.Log("--------")
if entry, err := cacher.Get("B"); err == nil {
t.Log(entry.CityName, entry.RegionName)
}
}
|
package main
import "fmt"
//测试
func test() {
//定义一个长度为3的数组
/**
长度不一致的数组 或者类型不一致 不可赋值交换
*/
//会自动初始化 [0,0,0]
var a[3] int
fmt.Println(a)
//数组初始化
var testArray [3]int //数组会初始化为int类型的零值
var numArray = [3]int{1, 2} //使用指定的初始值完成初始化
var cityArray = [3]string{"北京", "上海", "深圳"} //使用指定的初始值完成初始化
fmt.Println(testArray) //[0 0 0]
fmt.Println(numArray) //[1 2 0]
fmt.Println(cityArray) //[北京 上海 深圳]
//数组初始化自动推测长度
var b =[...]int{1,2,3,4,5}
var c = []string{"a","b","c"}//切片 可变数组 引用类型
fmt.Println(len(b),len(c))
//数组遍历
for i:=0;i<len(c) ;i++ {
fmt.Print(c[i])
}
fmt.Println()
for index,value:=range b {
fmt.Println(index,value)
}
//二维数组
aa := [3][2]string{
{"北京", "上海"},
{"广州", "深圳"},
{"成都", "重庆"},
}
fmt.Println(aa) //[[北京 上海] [广州 深圳] [成都 重庆]]
fmt.Println(aa[2][1]) //支持索引取值:重庆
//当有返回值必须接收 上下文不用 可以使用 _ 接收
//二维数组遍历
for _,v1:= range aa {
for _,v2 := range v1 {
fmt.Print(v2)
}
fmt.Println()
}
}
func main() {
//test()
}
|
package predo
import (
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
"github.com/mafengwo/confd/log"
)
// 找出需要用命名空间替换的一对对的模版文件(需要做验证 文件名的开头是以服务名开头的)
type tomlConfig struct {
Ini info
Nginx info
}
type info struct {
Tomlx []string
Tmplx []string
}
/*
* 完成confd前的任务:根据etcd中的namespace将对应的标准配置文件和标准模版文件中的变量替换掉
* 1.根据特殊的命名规则检查标准配置文件和模版文件是否存在
* 2.用namespace替换变量生成一对临时的配置文件和模版文件,判断是否一样。如果不一样,替换成新的配置文件和模版文件
*
* 命令规范:
* namespace - es-XXX-data, es-XXX-master, redis, memcached. (注:es-XXX-data和es-XXX-master只需生成一对配置文件和模版文件)(服务-业务-data || 服务-业务-master)
* 标准配置文件 - es.tomlx, redis.tomlx(命名空间的替换词为 __NS__)
* 标准模版文件 - es.tmplx, redis.tmplx(命名空间的替换词为 __NS__)
* 配置文件 - es-XXX.toml
* 模版文件 - es-XXX-tmpl
*/
// MainProcess 主程序入口
func MainProcess(configDir, templateDir string, namespcae []string) {
var newNamespace, namespcaeArr []string
var config tomlConfig
var tomlxFile, tmplxFile string
// 处理namespace 去掉后缀同时去重
for _, value := range namespcae {
namespcaeArr = strings.Split(value, "-")
if len(namespcaeArr) == 3 || len(namespcaeArr) == 2 {
newNamespace = append(newNamespace, namespcaeArr[0]+"-"+namespcaeArr[1])
} else {
newNamespace = append(newNamespace, value)
}
}
newNamespace = Rmduplicate(&newNamespace)
_, err := toml.DecodeFile(filepath.Join(configDir, "batch.ini"), &config)
if err != nil {
log.Info("predo: parse batch.ini faild error= %s", err.Error())
}
//进行验证 要保证tompx和tmplx是成对出现的
if len(config.Ini.Tmplx) != len(config.Ini.Tomlx) || len(config.Nginx.Tmplx) != len(config.Nginx.Tomlx) {
log.Info("predo: batch.ini toplx and tmplx number is wrong! ")
return
}
//处理Ini模块
for i := 0; i < len(config.Ini.Tmplx); i++ {
tomlxFile = config.Ini.Tomlx[i]
tmplxFile = config.Ini.Tmplx[i]
for _, item := range newNamespace {
if check(configDir, templateDir, tomlxFile, tmplxFile, item) {
//处理配置文件
handleNamespace(configDir, ".toml", item, tomlxFile, "ini")
//处理模版文件
handleNamespace(templateDir, ".tmpl", item, tmplxFile, "ini")
}
}
}
//处理Nginx模块
for i := 0; i < len(config.Nginx.Tmplx); i++ {
tomlxFile = config.Nginx.Tomlx[i]
tmplxFile = config.Nginx.Tmplx[i]
for _, item := range newNamespace {
if check(configDir, templateDir, tomlxFile, tmplxFile, item) {
//处理配置文件
handleNamespace(configDir, ".toml", item, tomlxFile, "nginx")
//处理模版文件
handleNamespace(templateDir, ".tmpl", item, tmplxFile, "nginx")
}
}
}
}
// 检验标准的配置文件是否存在以及和namaspace的关系
func check(configDir, templateDir, tomlxFile, tmplxFile, namespace string) bool {
//判断路径是否存在
tomlxPath := filepath.Join(configDir, tomlxFile)
tmplxPath := filepath.Join(templateDir, tmplxFile)
if !pathExists(tomlxPath) || !pathExists(tmplxPath) {
log.Info("predo: not Exists tomlxPath=%s, tmplxPath=%s, namespace=%s", tomlxPath, tmplxPath, namespace)
return false
}
//判断文件名与namespace的关系,开头必须要以服务名开头
serviceName := strings.Split(namespace, "-")[0]
tomlxName := strings.Split(strings.TrimSuffix(tomlxFile, filepath.Ext(tomlxFile)), "-")[0]
tmplxName := strings.Split(strings.TrimSuffix(tmplxFile, filepath.Ext(tmplxFile)), "-")[0]
if serviceName != tomlxName || serviceName != tmplxName || tmplxName != tomlxName {
return false
}
log.Info("predo: %s namespace has config(%s) and template(%s)", namespace, tomlxFile, tmplxFile)
return true
}
// 根据namespace判断是否存在标准的配置文件和标准的模版文件 此处的namespace已经是转化为es-XXX类似的.标准配置文件(es.tomlx)和标准模版文件(es.tmplx)
func isExists(configDir, templateDir, namespcae string) bool {
defaultConfigPath := filepath.Join(configDir, strings.Split(namespcae, "-")[0]+".tomlx")
defaultTemplatePath := filepath.Join(templateDir, strings.Split(namespcae, "-")[0]+".tmplx")
if pathExists(defaultConfigPath) && pathExists(defaultTemplatePath) {
log.Info("predo: %s namespace has config and template", namespcae)
return true
}
return false
}
// 用namespace替换变量生成一对临时的配置文件和模版文件,判断是否一样。如果不一样,替换成新的配置文件和模版文件
func handleNamespace(dir, configSuffix, namespcae, standardFile, ext string) {
tempConfigFile, err := ioutil.TempFile(dir, "temp")
if err != nil {
log.Info("predo: create temp config(%s) faild ", namespcae)
return
}
defer os.Remove(tempConfigFile.Name())
defaultConfigPath := filepath.Join(dir, standardFile)
configPath := filepath.Join(dir, namespcae+"-"+ext+configSuffix)
err = replace2File(tempConfigFile.Name(), defaultConfigPath, namespcae)
if err != nil {
log.Info("predo: replace2File error(%s)", err.Error())
return
}
if !pathExists(configPath) {
err := os.Rename(tempConfigFile.Name(), configPath)
if err != nil {
log.Info("predo: (%s)namespace rename1 faild ", namespcae)
}
//存在 作对比,文件内容没变化,不做替换
} else {
md5sum1, _ := run("md5sum " + configPath + " | awk '{print $1}'")
md5sum2, _ := run("md5sum " + tempConfigFile.Name() + " | awk '{print $1}'")
if md5sum1 != md5sum2 {
err := os.Rename(tempConfigFile.Name(), configPath)
if err != nil {
log.Info("predo: (%s)namespace rename2 faild ", namespcae+configSuffix)
}
} else {
log.Info("predo: (%s)namespace file is same", namespcae+configSuffix)
}
}
}
// 替换变量 生成配置文件和模版文件
func replace2File(tempFile, file, namespace string) error {
cmd := `sed "s/\${NS}/` + namespace + `/g" ` + file + ` > ` + tempFile
_, err := run(cmd)
return err
}
// Run shell脚本
func run(shell string) (string, error) {
cmd := exec.Command("/bin/sh", "-c", shell)
out, err := cmd.Output()
return string(out), err
}
// pathExists 判断路径是否存在(绝对路径)
func pathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
// Rmduplicate unique slice
func Rmduplicate(list *[]string) []string {
var x = []string{}
for _, i := range *list {
if len(x) == 0 {
x = append(x, i)
} else {
for k, v := range x {
if i == v {
break
}
if k == len(x)-1 {
x = append(x, i)
}
}
}
}
return x
}
|
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
//
// 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 gardener
import (
"github.com/gardener/test-infra/pkg/common"
"github.com/gardener/test-infra/pkg/hostscheduler"
"github.com/gardener/test-infra/pkg/tm-bot/github/ghval"
)
// DefaultsConfig is the defaults configuration that can be configured using the repository configuration for the tests command
type DefaultsConfig struct {
HostProvider *hostscheduler.Provider `json:"hostprovider"`
BaseClusterCloudProvider *common.CloudProvider `json:"baseClusterCloudprovider"`
GardenSetup *struct {
Revision *ghval.StringOrGitHubValue `json:"revision"`
} `json:"gardensetup"`
Gardener *struct {
Version *ghval.StringOrGitHubValue `json:"version"`
Commit *ghval.StringOrGitHubValue `json:"commit"`
} `json:"gardener"`
// github.com/gardener/gardener-extension version
// has to be a yaml of a map[extension-name]{version: "0.0.0",repo:"github.com/x/x"}
GardenerExtensions *ghval.GitHubValue `json:"gardener-extensions"`
ShootFlavors *[]*common.ShootFlavor `json:"shootFlavors"`
}
|
package main
import (
"container/list"
"fmt"
)
/*
Set operation:
1. If the key already exists, update the key with the new value
2. If the key doesn't exist, the 2 cases can happen
2a. There is enough space in the dictionary, add key, value to dictionary in the set operation
2b. There is not enough space, need to remove the value that is the most ancient from both the
dictionary and linked list that stores this information and add the new value at the head
Get operation:
1. If key doesn't exist, return null
2. If key exists:
2a. Return the value from the key
2b. Travel to the node in the linked list, move to front
*/
type lruCache struct {
bag map[int]string
position *list.List
maxSize int
}
func New(maxSize int) *lruCache {
return &lruCache{
bag: make(map[int]string),
position: list.New(),
maxSize: maxSize,
}
}
func (l *lruCache) findElement(key int) *list.Element {
for e := l.position.Front(); e != nil; e = e.Next() {
if e.Value.(int) == key {
return e
}
}
return nil
}
func (l *lruCache) set(key int, value string) {
_, ok := l.bag[key]
if ok {
l.bag[key] = value
return
}
if len(l.bag) >= l.maxSize {
// remove the last element
e := l.position.Back()
lastKey := l.position.Remove(e).(int)
delete(l.bag, lastKey)
}
// add new key to the front
l.position.PushFront(key)
l.bag[key] = value
}
func (l *lruCache) get(key int) string {
val, ok := l.bag[key]
if !ok {
return ""
}
currElement := l.findElement(key)
l.position.MoveToFront(currElement)
return val
}
func main() {
fmt.Printf("lru_cache_linkedlist \n")
l := New(3)
l.set(10, "foo")
l.set(20, "bar")
l.set(21, "baz")
l.get(10)
fmt.Printf("l.get(10): %v \n", l.get(10))
l.set(22, "abc")
fmt.Printf("l.get(20): %v \n", l.get(20))
fmt.Printf("l.get(21): %v \n", l.get(21))
fmt.Printf("l.get(22): %v \n", l.get(22))
}
|
package globals
var (
InstallerImage = "ibuildthecloud/fleet"
)
|
/*
* Copyright 2019 The Knative 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 main
import (
"flag"
"log"
"net/http"
"net/url"
"time"
// Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).
// _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
cloudevents "github.com/cloudevents/sdk-go"
cehttp "github.com/cloudevents/sdk-go/pkg/cloudevents/transport/http"
"github.com/kelseyhightower/envconfig"
"go.uber.org/zap"
"go.opencensus.io/stats/view"
"knative.dev/eventing/pkg/broker/ingress"
"knative.dev/eventing/pkg/channel"
"knative.dev/eventing/pkg/kncloudevents"
"knative.dev/eventing/pkg/tracing"
kubeclient "knative.dev/pkg/client/injection/kube/client"
"knative.dev/pkg/configmap"
"knative.dev/pkg/controller"
"knative.dev/pkg/injection"
"knative.dev/pkg/injection/sharedmain"
"knative.dev/pkg/metrics"
"knative.dev/pkg/signals"
"knative.dev/pkg/system"
pkgtracing "knative.dev/pkg/tracing"
)
var (
masterURL = flag.String("master", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.")
kubeconfig = flag.String("kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.")
)
type envConfig struct {
Broker string `envconfig:"BROKER" required:"true"`
Channel string `envconfig:"CHANNEL" required:"true"`
Namespace string `envconfig:"NAMESPACE" required:"true"`
}
func main() {
logConfig := channel.NewLoggingConfig()
logger := channel.NewProvisionerLoggerFromConfig(logConfig).Desugar()
defer flush(logger)
flag.Parse()
var env envConfig
if err := envconfig.Process("", &env); err != nil {
logger.Fatal("Failed to process env var", zap.Error(err))
}
ctx := signals.NewContext()
// Report stats on Go memory usage every 30 seconds.
msp := metrics.NewMemStatsAll()
msp.Start(ctx, 30*time.Second)
if err := view.Register(msp.DefaultViews()...); err != nil {
log.Fatalf("Error exporting go memstats view: %v", err)
}
log.Printf("Registering %d clients", len(injection.Default.GetClients()))
log.Printf("Registering %d informer factories", len(injection.Default.GetInformerFactories()))
log.Printf("Registering %d informers", len(injection.Default.GetInformers()))
logger.Info("Starting...")
cfg, err := sharedmain.GetConfig(*masterURL, *kubeconfig)
if err != nil {
log.Fatal("Error building kubeconfig", err)
}
ctx, informers := injection.Default.SetupInformers(ctx, cfg)
channelURI := &url.URL{
Scheme: "http",
Host: env.Channel,
Path: "/",
}
cmw := configmap.NewInformedWatcher(kubeclient.Get(ctx), system.Namespace())
// TODO watch logging config map.
// TODO change the component name to broker once Stackdriver metrics are approved.
// Watch the observability config map and dynamically update metrics exporter.
cmw.Watch(metrics.ConfigMapName(), metrics.UpdateExporterFromConfigMap("broker_ingress", logger.Sugar()))
bin := tracing.BrokerIngressName(tracing.BrokerIngressNameArgs{
Namespace: env.Namespace,
BrokerName: env.Broker,
})
if err = tracing.SetupDynamicPublishing(logger.Sugar(), cmw, bin); err != nil {
logger.Fatal("Error setting up trace publishing", zap.Error(err))
}
httpTransport, err := cloudevents.NewHTTPTransport(cloudevents.WithBinaryEncoding(), cehttp.WithMiddleware(pkgtracing.HTTPSpanMiddleware))
if err != nil {
logger.Fatal("Unable to create CE transport", zap.Error(err))
}
// Liveness check.
httpTransport.Handler = http.NewServeMux()
httpTransport.Handler.HandleFunc("/healthz", func(writer http.ResponseWriter, _ *http.Request) {
writer.WriteHeader(http.StatusOK)
})
ceClient, err := kncloudevents.NewDefaultClientGivenHttpTransport(httpTransport)
if err != nil {
logger.Fatal("Unable to create CE client", zap.Error(err))
}
reporter := ingress.NewStatsReporter()
h := &ingress.Handler{
Logger: logger,
CeClient: ceClient,
ChannelURI: channelURI,
BrokerName: env.Broker,
Namespace: env.Namespace,
Reporter: reporter,
}
// configMapWatcher does not block, so start it first.
if err = cmw.Start(ctx.Done()); err != nil {
logger.Warn("Failed to start ConfigMap watcher", zap.Error(err))
}
// Start all of the informers and wait for them to sync.
logger.Info("Starting informers.")
if err := controller.StartInformers(ctx.Done(), informers...); err != nil {
logger.Fatal("Failed to start informers", zap.Error(err))
}
// Start blocks forever.
if err = h.Start(ctx); err != nil {
logger.Error("ingress.Start() returned an error", zap.Error(err))
}
logger.Info("Exiting...")
}
func flush(logger *zap.Logger) {
logger.Sync()
metrics.FlushExporter()
}
|
// Copyright 2014 Matthias Zenger. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sequences
type MutableSequenceFactory interface {
MutableSequenceFactoryBase
MutableSequenceFactoryDerived
}
type MutableSequenceFactoryBase interface {
Sequence
MutableSequenceClassProvider
}
type MutableSequenceClassProvider interface {
Class() MutableSequenceClass
}
type MutableSequenceFactoryDerived interface {
Copy() MutableSequence
Immutable() Sequence
Project(f func (interface{}) interface{}) MutableSequence
DropIf(pred func (interface{}) bool) MutableSequence
}
func EmbeddedMutableSequenceFactory(obj MutableSequenceFactory) MutableSequenceFactory {
return &sequenceFactory{obj, obj}
}
type sequenceFactory struct {
obj MutableSequenceFactory
MutableSequenceFactoryBase
}
func (this *sequenceFactory) Copy() MutableSequence {
n := this.obj.Size()
seq := this.obj.Class().New()
seq.Allocate(0, n, nil)
for i := 0; i < n; i++ {
seq.Set(i, this.obj.At(i))
}
return seq
}
func (this *sequenceFactory) Immutable() Sequence {
return wrappedSequence(this.obj.Copy(), true)
}
func (this *sequenceFactory) Project(f func (interface{}) interface{}) MutableSequence {
n := this.obj.Size()
seq := this.obj.Class().New()
seq.Allocate(0, n, nil)
for i := 0; i < n; i++ {
seq.Set(i, f(this.obj.At(i)))
}
return seq
}
func (this *sequenceFactory) DropIf(pred func (interface{}) bool) MutableSequence {
n := this.obj.Size()
seq := this.obj.Class().New()
for i := 0; i < n; i++ {
if !pred(this.obj.At(i)) {
seq.Allocate(seq.Size(), 1, this.obj.At(i))
}
}
return seq
}
|
// Copyright 2020 Ye Zi Jie. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: FishGoddess
// Email: fishgoddess@qq.com
// Created at 2020/04/27 22:44:04
package logit
func init() {
registerDebugLevelHandler()
registerInfoLevelHandler()
registerWarnLevelHandler()
registerErrorLevelHandler()
}
// levelBasedHandler is a level sensitive handler.
// It only handles the specific level of this handler, so you can use different handlers
// to handle logs in different levels. For example, you want debug/info/warn level logs are
// written to log file "xxx.log" and error level logs are written to log file "xxx.error.log",
// maybe written to log server, too, then you can use this handler to do it.
type levelBasedHandler struct {
// level is the level of log that can be handled by this handler.
// See logit.Level.
level Level
// handlers is all handlers used to handle logs in level.
// See logit.Handler.
handlers []Handler
}
// NewLevelBasedHandler returns a handler handled logs in level.
// You can add more than one handler to this handler. This handler is just like a
// wrapper wrapping some handlers.
func NewLevelBasedHandler(level Level, handlers ...Handler) Handler {
return &levelBasedHandler{
level: level,
handlers: handlers,
}
}
// Handle handles a log with handlers in lbh.
// Notice that the handling process will be interrupted if one of them
// returned false. However, this method will always return true, so the handlers
// after it will always be used.
func (lbh *levelBasedHandler) Handle(log *Log) bool {
if log.Level() == lbh.level {
for _, handler := range lbh.handlers {
if !handler.Handle(log) {
break
}
}
}
return true
}
// handlersOf returns handlers parsed from params.
func handlersOf(params map[string]interface{}) []Handler {
handlers := make([]Handler, 0, len(params)+2)
for name, paramsOfHandler := range params {
handlers = append(handlers, handlerOf(name, paramsOfHandler.(map[string]interface{})))
}
return handlers
}
// ================================ debug level handler ================================
// registerDebugLevelHandler registers debug level handler which
// only handles logs in debug level.
//
// For config:
// If you want to use this handler in your logger by config file, try this:
//
// "handlers": {
// "debug": {
// "console": {}
// }
// }
//
// You should always know that this handler is a wrapper, so you must add some other
// handlers to it otherwise it will do nothing. All registered handlers can be added
// to it, even one more debug level handler. Now, you know it is only a filter that filters
// non-debug level logs. As for what params should be written in handlers inside are dependent
// to different handlers. Check other handlers' documents to know more about information.
// See logit.Handler.
func registerDebugLevelHandler() {
RegisterHandler("debug", func(params map[string]interface{}) Handler {
return NewLevelBasedHandler(DebugLevel, handlersOf(params)...)
})
}
// ================================ info level handler ================================
// registerInfoLevelHandler registers info level handler which
// only handles logs in info level.
//
// For config:
// If you want to use this handler in your logger by config file, try this:
//
// "handlers": {
// "info": {
// "console": {}
// }
// }
//
// You should always know that this handler is a wrapper, so you must add some other
// handlers to it otherwise it will do nothing. All registered handlers can be added
// to it, even one more info level handler. Now, you know it is only a filter that filters
// non-info level logs. As for what params should be written in handlers inside are dependent
// to different handlers. Check other handlers' documents to know more about information.
// See logit.Handler.
func registerInfoLevelHandler() {
RegisterHandler("info", func(params map[string]interface{}) Handler {
return NewLevelBasedHandler(InfoLevel, handlersOf(params)...)
})
}
// ================================ warn level handler ================================
// registerWarnLevelHandler registers warn level handler which
// only handles logs in warn level.
//
// For config:
// If you want to use this handler in your logger by config file, try this:
//
// "handlers": {
// "warn": {
// "console": {}
// }
// }
//
// You should always know that this handler is a wrapper, so you must add some other
// handlers to it otherwise it will do nothing. All registered handlers can be added
// to it, even one more warn level handler. Now, you know it is only a filter that filters
// non-warn level logs. As for what params should be written in handlers inside are dependent
// to different handlers. Check other handlers' documents to know more about information.
// See logit.Handler.
func registerWarnLevelHandler() {
RegisterHandler("warn", func(params map[string]interface{}) Handler {
return NewLevelBasedHandler(WarnLevel, handlersOf(params)...)
})
}
// ================================ error level handler ================================
// registerErrorLevelHandler registers error level handler which
// only handles logs in error level.
//
// For config:
// If you want to use this handler in your logger by config file, try this:
//
// "handlers": {
// "error": {
// "console": {}
// }
// }
//
// You should always know that this handler is a wrapper, so you must add some other
// handlers to it otherwise it will do nothing. All registered handlers can be added
// to it, even one more error level handler. Now, you know it is only a filter that filters
// non-error level logs. As for what params should be written in handlers inside are dependent
// to different handlers. Check other handlers' documents to know more about information.
// See logit.Handler.
func registerErrorLevelHandler() {
RegisterHandler("error", func(params map[string]interface{}) Handler {
return NewLevelBasedHandler(ErrorLevel, handlersOf(params)...)
})
}
|
// Copyright (c) 2016-2019 Uber Technologies, 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 namepath
import (
"errors"
"fmt"
"path"
"regexp"
"strings"
)
// Pather id strings.
const (
DockerTag = "docker_tag"
ShardedDockerBlob = "sharded_docker_blob"
Identity = "identity"
)
// New creates a Pather scoped to root.
func New(root, id string) (Pather, error) {
switch id {
case DockerTag:
return DockerTagPather{root}, nil
case ShardedDockerBlob:
return ShardedDockerBlobPather{root}, nil
case Identity:
return IdentityPather{root}, nil
case "":
return nil, fmt.Errorf("invalid pather identifier: empty")
default:
return nil, fmt.Errorf("unknown pather identifier: %s", id)
}
}
// Pather defines an interface for converting names into paths.
type Pather interface {
// BasePath returns the base path of where blobs are stored.
BasePath() string
// BlobPath converts name into a blob path.
BlobPath(name string) (string, error)
// NameFromBlobPath converts blob path bp back into the original blob name.
NameFromBlobPath(bp string) (string, error)
}
// DockerTagPather generates paths for Docker tags.
type DockerTagPather struct {
root string
}
// BasePath returns the docker registry repositories prefix.
func (p DockerTagPather) BasePath() string {
return path.Join(p.root, "docker/registry/v2/repositories")
}
// BlobPath interprets name as a "repo:tag" and generates a registry path for it.
func (p DockerTagPather) BlobPath(name string) (string, error) {
tokens := strings.Split(name, ":")
if len(tokens) != 2 {
return "", errors.New("name must be in format 'repo:tag'")
}
repo := tokens[0]
if len(repo) == 0 {
return "", errors.New("repo must be non-empty")
}
tag := tokens[1]
if len(tag) == 0 {
return "", errors.New("tag must be non-empty")
}
return path.Join(p.BasePath(), repo, "_manifests/tags", tag, "current/link"), nil
}
// NameFromBlobPath converts a tag path back into repo:tag format.
func (p DockerTagPather) NameFromBlobPath(bp string) (string, error) {
re := regexp.MustCompile(p.BasePath() + "/(.+)/_manifests/tags/(.+)/current/link")
matches := re.FindStringSubmatch(bp)
if len(matches) != 3 {
return "", errors.New("invalid docker tag path format")
}
repo := matches[1]
tag := matches[2]
return fmt.Sprintf("%s:%s", repo, tag), nil
}
// ShardedDockerBlobPather generates sharded paths for Docker blobs.
type ShardedDockerBlobPather struct {
root string
}
// BasePath returns the docker registry blobs prefix.
func (p ShardedDockerBlobPather) BasePath() string {
return path.Join(p.root, "docker/registry/v2/blobs")
}
// BlobPath interprets name as a SHA256 digest and returns a registry path
// which is sharded by the first two bytes.
func (p ShardedDockerBlobPather) BlobPath(name string) (string, error) {
if len(name) <= 2 {
return "", errors.New("name is too short, must be > 2 characters")
}
return path.Join(p.BasePath(), "sha256", name[:2], name, "data"), nil
}
// NameFromBlobPath converts a sharded blob path back into raw hex format.
func (p ShardedDockerBlobPather) NameFromBlobPath(bp string) (string, error) {
re := regexp.MustCompile(p.BasePath() + "/sha256/../(.+)/data")
matches := re.FindStringSubmatch(bp)
if len(matches) != 2 {
return "", errors.New("invalid sharded docker blob path format")
}
return matches[1], nil
}
// IdentityPather is the identity Pather.
type IdentityPather struct {
root string
}
// BasePath returns the root.
func (p IdentityPather) BasePath() string {
return p.root
}
// BlobPath always returns root/name.
func (p IdentityPather) BlobPath(name string) (string, error) {
return path.Join(p.root, name), nil
}
// NameFromBlobPath strips the root from bp.
func (p IdentityPather) NameFromBlobPath(bp string) (string, error) {
if !strings.HasPrefix(bp, p.root) {
return "", errors.New("invalid identity path format")
}
return bp[len(p.root)+1:], nil
}
|
package requirements
import "testing"
type TestStruct struct {
num int
res []int
}
var toTest = []TestStruct{
{
num: 60,
res: []int{1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60},
},
{
num: 42,
res: []int{1, 2, 3, 6, 7, 14, 21, 42},
},
{
num: -1,
res: nil,
},
}
func TestGetPositiveDevisors(t *testing.T) {
for i := range toTest {
divisors, err := getPositiveDevisors(toTest[i].num)
if err != nil {
if toTest[i].res != nil {
t.Errorf("Problem with the positive integer")
}
return
}
if len(divisors) != len(toTest[i].res) {
if toTest[i].res != nil {
t.Errorf("Wrong number of divisors")
}
return
}
// assuming that getPositiveDevisors returns a sorted slice
// and that our result slice is sorted as well
for j := range divisors {
if divisors[j] != toTest[i].res[j] {
t.Errorf("Wrong devisor, expected %d, got %d", toTest[i].res[j], divisors[j])
}
}
}
}
|
// Package sgf describes the SGF file formatting and provides functions
// for working with SGF data. SGF FF[4] is the current file format
// as of this writing. See https://www.red-bean.com/sgf/ and
// https://www.red-bean.com/sgf/proplist_t.html
package sgf
import (
"fmt"
)
const (
// xletters is a string to translate numbers
// into letter coordinates.
xletters string = " abcdefghijklmnopqrs"
// yletters is a string to translate numbers
// into letter coordinates.
yletters = " srqponmlkjihgfedcba"
// Application describes the application used
// to generate the SGF file.
Application = "AP[%s]"
// BlackPass shows that the Black player passed.
BlackPass = "B[]"
// BlackMove describes a move with xy coordinates
// a-s.
BlackMove = "B[%2s]"
// BlackRank describes the player's rank.
BlackRank = "BR[%s]"
// Comment is a free-form comment string.
Comment = "C[%s]"
// DateTime is the date and time of the game. ISO date - YYYY-MM-DD.
DateTime = "DT[%s]"
// FileFormat describes the SGF version.
FileFormat = "FF[%d]"
// Game is the type of game being represented. GM[1] is Go/Baduk.
Game = "GM[%d]"
// GameName is the name of the game record.
GameName = "GN[%s]"
// Komi given to the Black player. This is either 0 or
// must have a half of a point to break ties. 6.5 is a
// common Komi granted to Black.
Komi = "KM[%.1f]"
// PlayerBlack is the Black player's name.
PlayerBlack = "PB[%s]"
// Place is where the game is being played. Geographically,
// application, web site, etc...
Place = "PC[%s]"
// PlayerWhite is the White player's name.
PlayerWhite = "PW[%s]"
// Result describes the winner of the game and by
// what margin. (e.g. B+49.5 => Black wins by 49.5 points.
// W+Resign => White wins by resignation)
Result = "RE[%s]"
// Rules describes the counting rules.
Rules = "RU[%s]"
// Source is the source of the SGF file.
Source = "SO[%s]"
// Size is the size of the Go board. Standard, square sizes
// are 9, 13, 19.
Size = "SZ[%d]"
// WhiteMove describes a move with xy coordinates
// a-s.
WhiteMove = "W[%2s]"
// WhitePass shows that the White player passed.
WhitePass = "W[]"
// WhiteRank is the White player's rank.
WhiteRank = "WR[%s]"
)
// Header builds the header of the SGF output.
func Header() (header string) {
header = "(;"
header += fmt.Sprintf(FileFormat, 4)
header += fmt.Sprintf(Game, 1)
header += fmt.Sprintf(Size, 19)
header += fmt.Sprintf(Application, "GoGo")
return
}
// EmitMove will emit an SGF-formatted move
func EmitMove(playerID, x, y int) string {
var move string
switch playerID {
case 1:
move = BlackMove
case 2:
move = WhiteMove
}
translated := string(xletters[x]) + string(yletters[y])
return fmt.Sprintf(";"+move, translated)
}
|
package quikface
import (
"testing"
htest "net/http/httptest"
ntest "golang.org/x/net/nettest"
)
func TestIndexHandler(t *testing.T) {
r := NewSessionRouter()
htest.
}
|
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package main
import (
"fmt"
"strings"
"text/template"
"github.com/cockroachdb/cockroach/pkg/col/typeconv"
"github.com/cockroachdb/cockroach/pkg/sql/colexecerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/errors"
)
// overloadBase and other overload-related structs form a leveled hierarchy
// that is useful during the code generation. Structs have "up" and "down"
// references to each other so that the necessary fields for the templating are
// accessible via '.'. Only when we reach the bottom level (where
// lastArgWidthOverload is) do we have the access to "resolved" overload
// functions.
//
// The idea is that every argument of an overload function can have overloaded
// type family and then the width of the type. argTypeOverload describes an
// overloaded argument that is not the last among all functions' arguments. The
// struct itself is "separated" into two levels - argTypeOverload and
// argWidthOverload for ease of iterating over it during the code generation.
// argTypeOverload describes a single "family-width" pair, so from that point
// of view, it is concrete. However, since this argument is not the last, the
// struct does *not* have AssignFunc and/or other functions because it is not
// "resolved" - when we see it during code generation, we don't have full
// information yet.
//
// Here is the diagram of relationships for argTypeOverload struct:
//
// argTypeOverloadBase overloadBase
// \ \ |
// \ ------ |
// ↓ ↓ ↓
// argWidthOverloadBase argTypeOverload
// \ /
// \ | (single)
// ↓ ↓
// argWidthOverload
//
// lastArgTypeOverload is similar in nature to argTypeOverload in that it
// describes an overloaded argument, but that argument is the last one, so the
// overload is "resolved" - it has access to the AssignFunc and/or other
// functions. The struct still overloads a single type family, however, it can
// have multiple widths for that type family, so it supports multiple "family-
// width" pairs.
//
// Here is the diagram of relationships for lastArgTypeOverload struct:
//
// argTypeOverloadBase overloadBase
// \ \ |
// \ ------ |
// ↓ ↓ ↓
// argWidthOverloadBase lastArgTypeOverload
// \ /
// \ | (multiple)
// ↓ ↓
// lastArgWidthOverload
//
// Two argument overload consists of multiple corresponding to each other
// argTypeOverloads and lastArgTypeOverloads.
//
// The important point is that an overload is "resolved" only at
// lastArgWidthOverload level - only that struct has the information about the
// return type and has access to the functions that can be called.
//
// These structs (or their "resolved" equivalents) are intended to be used by
// the code generation with the following patterns:
//
// switch canonicalTypeFamily {
// switch width {
// <resolved one arg overload>
// }
// }
//
// switch leftCanonicalTypeFamily {
// switch leftWidth {
// switch rightCanonicalTypeFamily {
// switch rightWidth {
// <resolved two arg overload>
// }
// }
// }
// }
type overloadBase struct {
kind overloadKind
Name string
OpStr string
// Only one of CmpOp and BinOp will be set, depending on whether the
// overload is a binary operator or a comparison operator. Neither of the
// fields will be set when it is a hash or cast overload.
CmpOp tree.ComparisonOperator
BinOp tree.BinaryOperator
}
// overloadKind describes the type of an overload. The word "kind" was chosen
// to reduce possible confusion with "types" of arguments of an overload.
type overloadKind int
const (
binaryOverload overloadKind = iota
comparisonOverload
hashOverload
castOverload
)
func (b *overloadBase) String() string {
return fmt.Sprintf("%s: %s", b.Name, b.OpStr)
}
func toString(family types.Family) string {
switch family {
case typeconv.DatumVecCanonicalTypeFamily:
return "typeconv.DatumVecCanonicalTypeFamily"
default:
return "types." + family.String()
}
}
type argTypeOverloadBase struct {
CanonicalTypeFamily types.Family
CanonicalTypeFamilyStr string
}
func newArgTypeOverloadBase(canonicalTypeFamily types.Family) *argTypeOverloadBase {
return &argTypeOverloadBase{
CanonicalTypeFamily: canonicalTypeFamily,
CanonicalTypeFamilyStr: toString(canonicalTypeFamily),
}
}
func (b *argTypeOverloadBase) String() string {
return b.CanonicalTypeFamilyStr
}
// argTypeOverload describes an overloaded argument that is not the last among
// all functions' arguments. The struct itself is "separated" into two levels -
// argTypeOverload and argWidthOverload for ease of iterating over it during
// the code generation. argTypeOverload describes a single "family-width" pair,
// so from that point of view, it is concrete. However, since this argument is
// not the last, the struct does *not* have AssignFunc and/or other functions
// because it is not "resolved" - when we see it during code generation, we
// don't have full information yet.
type argTypeOverload struct {
*overloadBase
*argTypeOverloadBase
WidthOverload *argWidthOverload
}
// newArgTypeOverload creates a new argTypeOverload.
func newArgTypeOverload(
ob *overloadBase, canonicalTypeFamily types.Family, width int32,
) *argTypeOverload {
typeOverload := &argTypeOverload{
overloadBase: ob,
argTypeOverloadBase: newArgTypeOverloadBase(canonicalTypeFamily),
}
typeOverload.WidthOverload = newArgWidthOverload(typeOverload, width)
return typeOverload
}
func (o *argTypeOverload) String() string {
return fmt.Sprintf("%s\t%s", o.overloadBase, o.WidthOverload)
}
// lastArgTypeOverload is similar in nature to argTypeOverload in that it
// describes an overloaded argument, but that argument is the last one, so the
// overload is "resolved" - it has access to the AssignFunc and/or other
// functions. The struct still overloads a single type family, however, it can
// have multiple widths for that type family, so it supports multiple "family-
// width" pairs.
type lastArgTypeOverload struct {
*overloadBase
*argTypeOverloadBase
WidthOverloads []*lastArgWidthOverload
}
// newLastArgTypeOverload creates a new lastArgTypeOverload. Note that
// WidthOverloads field is not populated and will be updated according when
// creating lastArgWidthOverloads.
func newLastArgTypeOverload(
ob *overloadBase, canonicalTypeFamily types.Family,
) *lastArgTypeOverload {
return &lastArgTypeOverload{
overloadBase: ob,
argTypeOverloadBase: newArgTypeOverloadBase(canonicalTypeFamily),
}
}
func (o *lastArgTypeOverload) String() string {
s := fmt.Sprintf("%s\t%s", o.overloadBase, o.WidthOverloads[0])
for _, wo := range o.WidthOverloads[1:] {
s = fmt.Sprintf("%s\n%s", s, wo)
}
return s
}
type argWidthOverloadBase struct {
*argTypeOverloadBase
Width int32
// VecMethod is the name of the method that should be called on coldata.Vec
// to get access to the well-typed underlying memory.
VecMethod string
// GoType is the physical representation of a single element of the vector.
GoType string
}
func newArgWidthOverloadBase(
typeOverloadBase *argTypeOverloadBase, width int32,
) *argWidthOverloadBase {
return &argWidthOverloadBase{
argTypeOverloadBase: typeOverloadBase,
Width: width,
VecMethod: toVecMethod(typeOverloadBase.CanonicalTypeFamily, width),
GoType: toPhysicalRepresentation(typeOverloadBase.CanonicalTypeFamily, width),
}
}
func (b *argWidthOverloadBase) String() string {
return fmt.Sprintf("%s\tWidth: %d\tVecMethod: %s", b.argTypeOverloadBase, b.Width, b.VecMethod)
}
type argWidthOverload struct {
*argTypeOverload
*argWidthOverloadBase
}
func newArgWidthOverload(typeOverload *argTypeOverload, width int32) *argWidthOverload {
return &argWidthOverload{
argTypeOverload: typeOverload,
argWidthOverloadBase: newArgWidthOverloadBase(typeOverload.argTypeOverloadBase, width),
}
}
func (o *argWidthOverload) String() string {
return o.argWidthOverloadBase.String()
}
type lastArgWidthOverload struct {
*lastArgTypeOverload
*argWidthOverloadBase
RetType *types.T
RetVecMethod string
RetGoType string
AssignFunc assignFunc
CompareFunc compareFunc
CastFunc castFunc
}
// newLastArgWidthOverload creates a new lastArgWidthOverload. Note that it
// updates the typeOverload to include the newly-created struct into
// WidthOverloads field.
func newLastArgWidthOverload(
typeOverload *lastArgTypeOverload, width int32, retType *types.T,
) *lastArgWidthOverload {
retCanonicalTypeFamily := typeconv.TypeFamilyToCanonicalTypeFamily(retType.Family())
lawo := &lastArgWidthOverload{
lastArgTypeOverload: typeOverload,
argWidthOverloadBase: newArgWidthOverloadBase(typeOverload.argTypeOverloadBase, width),
RetType: retType,
RetVecMethod: toVecMethod(retCanonicalTypeFamily, retType.Width()),
RetGoType: toPhysicalRepresentation(retCanonicalTypeFamily, retType.Width()),
}
typeOverload.WidthOverloads = append(typeOverload.WidthOverloads, lawo)
return lawo
}
func (o *lastArgWidthOverload) String() string {
return fmt.Sprintf("%s\tReturn: %s", o.argWidthOverloadBase, o.RetType.Name())
}
type oneArgOverload struct {
*lastArgTypeOverload
}
func (o *oneArgOverload) String() string {
return fmt.Sprintf("%s\n", o.lastArgTypeOverload.String())
}
// twoArgsResolvedOverload is a utility struct that represents an overload that
// takes it two arguments and that has been "resolved" (meaning it supports
// only a single type family and a single type width on both sides).
type twoArgsResolvedOverload struct {
*overloadBase
Left *argWidthOverload
Right *lastArgWidthOverload
}
// twoArgsResolvedOverloadsInfo contains all overloads that take in two
// arguments and stores them in a similar hierarchical structure to how
// twoArgsOverloads are stored, with the difference that on the "bottom" level
// we store the "resolved" overload.
var twoArgsResolvedOverloadsInfo struct {
BinOps []*twoArgsResolvedOverloadInfo
CmpOps []*twoArgsResolvedOverloadInfo
CastOverloads *twoArgsResolvedOverloadInfo
}
var resolvedBinCmpOpsOverloads []*twoArgsResolvedOverload
type twoArgsResolvedOverloadInfo struct {
*overloadBase
LeftFamilies []*twoArgsResolvedOverloadLeftFamilyInfo
}
type twoArgsResolvedOverloadLeftFamilyInfo struct {
LeftCanonicalFamilyStr string
LeftWidths []*twoArgsResolvedOverloadLeftWidthInfo
}
type twoArgsResolvedOverloadLeftWidthInfo struct {
Width int32
RightFamilies []*twoArgsResolvedOverloadRightFamilyInfo
}
type twoArgsResolvedOverloadRightFamilyInfo struct {
RightCanonicalFamilyStr string
RightWidths []*twoArgsResolvedOverloadRightWidthInfo
}
type twoArgsResolvedOverloadRightWidthInfo struct {
Width int32
*twoArgsResolvedOverload
}
type assignFunc func(op *lastArgWidthOverload, targetElem, leftElem, rightElem, targetCol, leftCol, rightCol string) string
type compareFunc func(targetElem, leftElem, rightElem, leftCol, rightCol string) string
type castFunc func(to, from, fromCol, toType string) string
// Assign produces a Go source string that assigns the "targetElem" variable to
// the result of applying the overload to the two inputs, "leftElem" and
// "rightElem". Some overload implementations might need access to the column
// variable names, and those are provided via the corresponding parameters.
// Note that these are not generic vectors (i.e. not coldata.Vec) but rather
// concrete columns (e.g. []int64).
//
// For example, an overload that implemented the float64 plus operation, when
// fed the inputs "x", "a", "b", "xCol", "aCol", "bCol", would produce the
// string "x = a + b".
func (o *lastArgWidthOverload) Assign(
targetElem, leftElem, rightElem, targetCol, leftCol, rightCol string,
) string {
if o.AssignFunc != nil {
if ret := o.AssignFunc(
o, targetElem, leftElem, rightElem, targetCol, leftCol, rightCol,
); ret != "" {
return ret
}
}
// Default assign form assumes an infix operator.
return fmt.Sprintf("%s = %s %s %s", targetElem, leftElem, o.overloadBase.OpStr, rightElem)
}
// Compare produces a Go source string that assigns the "targetElem" variable to
// the result of comparing the two inputs, "leftElem" and "rightElem". Some
// overload implementations might need access to the vector variable names, and
// those are provided via the corresponding parameters. Note that there is no
// "targetCol" variable because we know that the target column is []bool.
//
// The targetElem will be negative, zero, or positive depending on whether
// leftElem is less-than, equal-to, or greater-than rightElem.
func (o *lastArgWidthOverload) Compare(
targetElem, leftElem, rightElem, leftCol, rightCol string,
) string {
if o.CompareFunc != nil {
if ret := o.CompareFunc(targetElem, leftElem, rightElem, leftCol, rightCol); ret != "" {
return ret
}
}
// Default compare form assumes an infix operator.
return fmt.Sprintf(
"if %s < %s { %s = -1 } else if %s > %s { %s = 1 } else { %s = 0 }",
leftElem, rightElem, targetElem, leftElem, rightElem, targetElem, targetElem)
}
func (o *lastArgWidthOverload) Cast(to, from, fromCol, toType string) string {
if o.CastFunc != nil {
if ret := o.CastFunc(to, from, fromCol, toType); ret != "" {
return ret
}
}
// Default cast function is "identity" cast.
return fmt.Sprintf("%s = %s", to, from)
}
func (o *lastArgWidthOverload) UnaryAssign(targetElem, vElem, targetCol, vVec string) string {
if o.AssignFunc != nil {
if ret := o.AssignFunc(o, targetElem, vElem, "", targetCol, vVec, ""); ret != "" {
return ret
}
}
// Default assign form assumes a function operator.
return fmt.Sprintf("%s = %s(%s)", targetElem, o.overloadBase.OpStr, vElem)
}
func goTypeSliceName(canonicalTypeFamily types.Family, width int32) string {
switch canonicalTypeFamily {
case types.BoolFamily:
return "coldata.Bools"
case types.BytesFamily:
return "*coldata.Bytes"
case types.DecimalFamily:
return "coldata.Decimals"
case types.IntFamily:
switch width {
case 16:
return "coldata.Int16s"
case 32:
return "coldata.Int32s"
case 64, anyWidth:
return "coldata.Int64s"
default:
colexecerror.InternalError(errors.AssertionFailedf("unexpected int width %d", width))
// This code is unreachable, but the compiler cannot infer that.
return ""
}
case types.IntervalFamily:
return "coldata.Durations"
case types.FloatFamily:
return "coldata.Float64s"
case types.TimestampTZFamily:
return "coldata.Times"
case typeconv.DatumVecCanonicalTypeFamily:
return "coldata.DatumVec"
}
colexecerror.InternalError(errors.AssertionFailedf("unsupported canonical type family %s", canonicalTypeFamily))
return ""
}
func (b *argWidthOverloadBase) GoTypeSliceName() string {
return goTypeSliceName(b.CanonicalTypeFamily, b.Width)
}
func copyVal(canonicalTypeFamily types.Family, dest, src string) string {
switch canonicalTypeFamily {
case types.BytesFamily:
return fmt.Sprintf("%[1]s = append(%[1]s[:0], %[2]s...)", dest, src)
case types.DecimalFamily:
return fmt.Sprintf("%s.Set(&%s)", dest, src)
}
return fmt.Sprintf("%s = %s", dest, src)
}
// CopyVal is a function that should only be used in templates.
func (b *argWidthOverloadBase) CopyVal(dest, src string) string {
return copyVal(b.CanonicalTypeFamily, dest, src)
}
func set(canonicalTypeFamily types.Family, target, i, new string) string {
switch canonicalTypeFamily {
case types.BytesFamily, typeconv.DatumVecCanonicalTypeFamily:
return fmt.Sprintf("%s.Set(%s, %s)", target, i, new)
case types.DecimalFamily:
return fmt.Sprintf("%s[%s].Set(&%s)", target, i, new)
}
return fmt.Sprintf("%s[%s] = %s", target, i, new)
}
// Set is a function that should only be used in templates.
func (b *argWidthOverloadBase) Set(target, i, new string) string {
return set(b.CanonicalTypeFamily, target, i, new)
}
// slice is a function that should only be used in templates.
func (b *argWidthOverloadBase) slice(target, start, end string) string {
switch b.CanonicalTypeFamily {
case types.BytesFamily:
// Bytes vector doesn't support slicing.
colexecerror.InternalError(errors.AssertionFailedf("slice method is attempted to be generated on Bytes vector"))
case typeconv.DatumVecCanonicalTypeFamily:
return fmt.Sprintf(`%s.Slice(%s, %s)`, target, start, end)
}
return fmt.Sprintf("%s[%s:%s]", target, start, end)
}
// sliceable returns whether the vector of canonicalTypeFamily can be sliced
// (i.e. whether it is a Golang's slice).
func sliceable(canonicalTypeFamily types.Family) bool {
switch canonicalTypeFamily {
case types.BytesFamily, typeconv.DatumVecCanonicalTypeFamily:
return false
default:
return true
}
}
// Sliceable is a function that should only be used in templates.
func (b *argWidthOverloadBase) Sliceable() bool {
return sliceable(b.CanonicalTypeFamily)
}
// CopySlice is a function that should only be used in templates.
func (b *argWidthOverloadBase) CopySlice(
target, src, destIdx, srcStartIdx, srcEndIdx string,
) string {
var tmpl string
switch b.CanonicalTypeFamily {
case types.BytesFamily, typeconv.DatumVecCanonicalTypeFamily:
tmpl = `{{.Tgt}}.CopySlice({{.Src}}, {{.TgtIdx}}, {{.SrcStart}}, {{.SrcEnd}})`
case types.DecimalFamily:
tmpl = `{
__tgt_slice := {{.Tgt}}[{{.TgtIdx}}:]
__src_slice := {{.Src}}[{{.SrcStart}}:{{.SrcEnd}}]
for __i := range __src_slice {
__tgt_slice[__i].Set(&__src_slice[__i])
}
}`
default:
tmpl = `copy({{.Tgt}}[{{.TgtIdx}}:], {{.Src}}[{{.SrcStart}}:{{.SrcEnd}}])`
}
args := map[string]string{
"Tgt": target,
"Src": src,
"TgtIdx": destIdx,
"SrcStart": srcStartIdx,
"SrcEnd": srcEndIdx,
}
var buf strings.Builder
if err := template.Must(template.New("").Parse(tmpl)).Execute(&buf, args); err != nil {
colexecerror.InternalError(err)
}
return buf.String()
}
// AppendSlice is a function that should only be used in templates.
func (b *argWidthOverloadBase) AppendSlice(
target, src, destIdx, srcStartIdx, srcEndIdx string,
) string {
var tmpl string
switch b.CanonicalTypeFamily {
case types.BytesFamily, typeconv.DatumVecCanonicalTypeFamily:
tmpl = `{{.Tgt}}.AppendSlice({{.Src}}, {{.TgtIdx}}, {{.SrcStart}}, {{.SrcEnd}})`
case types.DecimalFamily:
tmpl = `{
__desiredCap := {{.TgtIdx}} + {{.SrcEnd}} - {{.SrcStart}}
if cap({{.Tgt}}) >= __desiredCap {
{{.Tgt}} = {{.Tgt}}[:__desiredCap]
} else {
__prevCap := cap({{.Tgt}})
__capToAllocate := __desiredCap
if __capToAllocate < 2 * __prevCap {
__capToAllocate = 2 * __prevCap
}
__new_slice := make([]apd.Decimal, __desiredCap, __capToAllocate)
copy(__new_slice, {{.Tgt}}[:{{.TgtIdx}}])
{{.Tgt}} = __new_slice
}
__src_slice := {{.Src}}[{{.SrcStart}}:{{.SrcEnd}}]
__dst_slice := {{.Tgt}}[{{.TgtIdx}}:]
_ = __dst_slice[len(__src_slice)-1]
for __i := range __src_slice {
//gcassert:bce
__dst_slice[__i].Set(&__src_slice[__i])
}
}`
default:
tmpl = `{{.Tgt}} = append({{.Tgt}}[:{{.TgtIdx}}], {{.Src}}[{{.SrcStart}}:{{.SrcEnd}}]...)`
}
args := map[string]string{
"Tgt": target,
"Src": src,
"TgtIdx": destIdx,
"SrcStart": srcStartIdx,
"SrcEnd": srcEndIdx,
}
var buf strings.Builder
if err := template.Must(template.New("").Parse(tmpl)).Execute(&buf, args); err != nil {
colexecerror.InternalError(err)
}
return buf.String()
}
// AppendVal is a function that should only be used in templates.
func (b *argWidthOverloadBase) AppendVal(target, v string) string {
switch b.CanonicalTypeFamily {
case types.BytesFamily, typeconv.DatumVecCanonicalTypeFamily:
return fmt.Sprintf("%s.AppendVal(%s)", target, v)
case types.DecimalFamily:
return fmt.Sprintf(`%[1]s = append(%[1]s, apd.Decimal{})
%[1]s[len(%[1]s)-1].Set(&%[2]s)`, target, v)
}
return fmt.Sprintf("%[1]s = append(%[1]s, %[2]s)", target, v)
}
// Window is a function that should only be used in templates.
func (b *argWidthOverloadBase) Window(target, start, end string) string {
switch b.CanonicalTypeFamily {
case types.BytesFamily:
return fmt.Sprintf(`%s.Window(%s, %s)`, target, start, end)
}
return b.slice(target, start, end)
}
// setVariableSize is a function that should only be used in templates. It
// returns a string that contains a code snippet for computing the size of the
// object named 'value' if it has variable size and assigns it to the variable
// named 'target' (for fixed sizes the snippet will simply declare the 'target'
// variable). The value object must be of canonicalTypeFamily representation.
func setVariableSize(canonicalTypeFamily types.Family, target, value string) string {
switch canonicalTypeFamily {
case types.BytesFamily:
return fmt.Sprintf(`%s := len(%s)`, target, value)
case types.DecimalFamily:
return fmt.Sprintf(`%s := tree.SizeOfDecimal(&%s)`, target, value)
case typeconv.DatumVecCanonicalTypeFamily:
return fmt.Sprintf(`
var %[1]s uintptr
if %[2]s != nil {
%[1]s = %[2]s.(*coldataext.Datum).Size()
}`, target, value)
default:
return fmt.Sprintf(`var %s uintptr`, target)
}
}
// SetVariableSize is a function that should only be used in templates. See the
// comment on setVariableSize for more details.
func (b *argWidthOverloadBase) SetVariableSize(target, value string) string {
return setVariableSize(b.CanonicalTypeFamily, target, value)
}
// Remove unused warnings.
var (
lawo = &lastArgWidthOverload{}
_ = lawo.Assign
_ = lawo.Compare
_ = lawo.Cast
_ = lawo.UnaryAssign
awob = &argWidthOverloadBase{}
_ = awob.GoTypeSliceName
_ = awob.CopyVal
_ = awob.Set
_ = awob.Sliceable
_ = awob.CopySlice
_ = awob.AppendSlice
_ = awob.AppendVal
_ = awob.Window
_ = awob.SetVariableSize
)
func init() {
registerTypeCustomizers()
populateBinOpOverloads()
populateCmpOpOverloads()
populateHashOverloads()
populateCastOverloads()
}
// typeCustomizer is a marker interface for something that implements one or
// more of binOpTypeCustomizer, cmpOpTypeCustomizer, hashTypeCustomizer,
// castTypeCustomizer.
//
// A type customizer allows custom templating behavior for a particular type
// that doesn't permit the ordinary Go assignment (x = y), comparison
// (==, <, etc) or binary operator (+, -, etc) semantics.
type typeCustomizer interface{}
// typePair is used to key a map that holds all typeCustomizers.
type typePair struct {
leftTypeFamily types.Family
leftWidth int32
rightTypeFamily types.Family
rightWidth int32
}
var typeCustomizers map[typePair]typeCustomizer
// registerTypeCustomizer registers a particular type customizer to a
// pair of types, for usage by templates.
func registerTypeCustomizer(pair typePair, customizer typeCustomizer) {
typeCustomizers[pair] = customizer
}
// boolCustomizer is necessary since bools don't support < <= > >= in Go.
type boolCustomizer struct{}
// bytesCustomizer is necessary since []byte doesn't support comparison ops in
// Go - bytes.Compare and so on have to be used.
type bytesCustomizer struct{}
// decimalCustomizer is necessary since apd.Decimal doesn't have infix operator
// support for binary or comparison operators, and also doesn't have normal
// variable-set semantics.
type decimalCustomizer struct{}
// floatCustomizers are used for hash functions.
type floatCustomizer struct{}
// intCustomizers are used for hash functions and overflow handling.
type intCustomizer struct{ width int32 }
// decimalFloatCustomizer supports mixed type expressions with a decimal
// left-hand side and a float right-hand side.
type decimalFloatCustomizer struct{}
// decimalIntCustomizer supports mixed type expressions with a decimal left-hand
// side and an int right-hand side.
type decimalIntCustomizer struct{}
// floatDecimalCustomizer supports mixed type expressions with a float left-hand
// side and a decimal right-hand side.
type floatDecimalCustomizer struct{}
// intDecimalCustomizer supports mixed type expressions with an int left-hand
// side and a decimal right-hand side.
type intDecimalCustomizer struct{}
// floatIntCustomizer supports mixed type expressions with a float left-hand
// side and an int right-hand side.
type floatIntCustomizer struct{}
// intFloatCustomizer supports mixed type expressions with an int left-hand
// side and a float right-hand side.
type intFloatCustomizer struct{}
// timestampCustomizer is necessary since time.Time doesn't have infix operators.
type timestampCustomizer struct{}
// intervalCustomizer is necessary since duration.Duration doesn't have infix
// operators.
type intervalCustomizer struct{}
// timestampIntervalCustomizer supports mixed type expression with a timestamp
// left-hand side and an interval right-hand side.
type timestampIntervalCustomizer struct{}
// intervalTimestampCustomizer supports mixed type expression with an interval
// left-hand side and a timestamp right-hand side.
type intervalTimestampCustomizer struct{}
// intervalIntCustomizer supports mixed type expression with an interval
// left-hand side and an int right-hand side.
type intervalIntCustomizer struct{}
// intIntervalCustomizer supports mixed type expression with an int left-hand
// side and an interval right-hand side.
type intIntervalCustomizer struct{}
// intervalFloatCustomizer supports mixed type expression with an interval
// left-hand side and a float right-hand side.
type intervalFloatCustomizer struct{}
// floatIntervalCustomizer supports mixed type expression with a float
// left-hand side and an interval right-hand side.
type floatIntervalCustomizer struct{}
// intervalDecimalCustomizer supports mixed type expression with an interval
// left-hand side and a decimal right-hand side.
type intervalDecimalCustomizer struct{}
// decimalIntervalCustomizer supports mixed type expression with a decimal
// left-hand side and an interval right-hand side.
type decimalIntervalCustomizer struct{}
// datumCustomizer supports overloads on tree.Datums.
type datumCustomizer struct{}
// datumNonDatumCustomizer supports overloads of mixed type binary expressions
// with a datum left-hand side and non-datum right-hand side.
type datumNonDatumCustomizer struct{}
// nonDatumDatumCustomizer supports overloads of mixed type binary expressions
// with a non-datum left-hand side and datum right-hand side.
type nonDatumDatumCustomizer struct {
leftCanonicalTypeFamily types.Family
}
// TODO(yuzefovich): add support for datums on both sides and non-datum result.
func registerTypeCustomizers() {
typeCustomizers = make(map[typePair]typeCustomizer)
registerTypeCustomizer(typePair{types.BoolFamily, anyWidth, types.BoolFamily, anyWidth}, boolCustomizer{})
registerTypeCustomizer(typePair{types.BytesFamily, anyWidth, types.BytesFamily, anyWidth}, bytesCustomizer{})
registerTypeCustomizer(typePair{types.DecimalFamily, anyWidth, types.DecimalFamily, anyWidth}, decimalCustomizer{})
registerTypeCustomizer(typePair{types.FloatFamily, anyWidth, types.FloatFamily, anyWidth}, floatCustomizer{})
registerTypeCustomizer(typePair{types.TimestampTZFamily, anyWidth, types.TimestampTZFamily, anyWidth}, timestampCustomizer{})
registerTypeCustomizer(typePair{types.IntervalFamily, anyWidth, types.IntervalFamily, anyWidth}, intervalCustomizer{})
registerTypeCustomizer(typePair{typeconv.DatumVecCanonicalTypeFamily, anyWidth, typeconv.DatumVecCanonicalTypeFamily, anyWidth}, datumCustomizer{})
for _, leftIntWidth := range supportedWidthsByCanonicalTypeFamily[types.IntFamily] {
for _, rightIntWidth := range supportedWidthsByCanonicalTypeFamily[types.IntFamily] {
registerTypeCustomizer(typePair{types.IntFamily, leftIntWidth, types.IntFamily, rightIntWidth}, intCustomizer{width: anyWidth})
}
}
// Use a customizer of appropriate width when widths are the same.
for _, intWidth := range supportedWidthsByCanonicalTypeFamily[types.IntFamily] {
registerTypeCustomizer(typePair{types.IntFamily, intWidth, types.IntFamily, intWidth}, intCustomizer{width: intWidth})
}
registerTypeCustomizer(typePair{types.DecimalFamily, anyWidth, types.FloatFamily, anyWidth}, decimalFloatCustomizer{})
registerTypeCustomizer(typePair{types.IntervalFamily, anyWidth, types.FloatFamily, anyWidth}, intervalFloatCustomizer{})
for _, rightIntWidth := range supportedWidthsByCanonicalTypeFamily[types.IntFamily] {
registerTypeCustomizer(typePair{types.DecimalFamily, anyWidth, types.IntFamily, rightIntWidth}, decimalIntCustomizer{})
registerTypeCustomizer(typePair{types.FloatFamily, anyWidth, types.IntFamily, rightIntWidth}, floatIntCustomizer{})
registerTypeCustomizer(typePair{types.IntervalFamily, anyWidth, types.IntFamily, rightIntWidth}, intervalIntCustomizer{})
}
registerTypeCustomizer(typePair{types.FloatFamily, anyWidth, types.DecimalFamily, anyWidth}, floatDecimalCustomizer{})
registerTypeCustomizer(typePair{types.FloatFamily, anyWidth, types.IntervalFamily, anyWidth}, floatIntervalCustomizer{})
for _, leftIntWidth := range supportedWidthsByCanonicalTypeFamily[types.IntFamily] {
registerTypeCustomizer(typePair{types.IntFamily, leftIntWidth, types.DecimalFamily, anyWidth}, intDecimalCustomizer{})
registerTypeCustomizer(typePair{types.IntFamily, leftIntWidth, types.FloatFamily, anyWidth}, intFloatCustomizer{})
registerTypeCustomizer(typePair{types.IntFamily, leftIntWidth, types.IntervalFamily, anyWidth}, intIntervalCustomizer{})
}
registerTypeCustomizer(typePair{types.TimestampTZFamily, anyWidth, types.IntervalFamily, anyWidth}, timestampIntervalCustomizer{})
registerTypeCustomizer(typePair{types.IntervalFamily, anyWidth, types.TimestampTZFamily, anyWidth}, intervalTimestampCustomizer{})
registerTypeCustomizer(typePair{types.IntervalFamily, anyWidth, types.DecimalFamily, anyWidth}, intervalDecimalCustomizer{})
registerTypeCustomizer(typePair{types.DecimalFamily, anyWidth, types.IntervalFamily, anyWidth}, decimalIntervalCustomizer{})
for _, compatibleFamily := range compatibleCanonicalTypeFamilies[typeconv.DatumVecCanonicalTypeFamily] {
if compatibleFamily != typeconv.DatumVecCanonicalTypeFamily {
for _, width := range supportedWidthsByCanonicalTypeFamily[compatibleFamily] {
registerTypeCustomizer(typePair{typeconv.DatumVecCanonicalTypeFamily, anyWidth, compatibleFamily, width}, datumNonDatumCustomizer{})
registerTypeCustomizer(typePair{compatibleFamily, width, typeconv.DatumVecCanonicalTypeFamily, anyWidth}, nonDatumDatumCustomizer{compatibleFamily})
}
}
}
}
var supportedCanonicalTypeFamilies = []types.Family{
types.BoolFamily,
types.BytesFamily,
types.DecimalFamily,
types.IntFamily,
types.FloatFamily,
types.TimestampTZFamily,
types.IntervalFamily,
typeconv.DatumVecCanonicalTypeFamily,
}
// anyWidth is special "value" of width of a type that will be used to generate
// "case -1: default:" block that would match all widths that are not
// explicitly specified.
const anyWidth = -1
var typeWidthReplacement = fmt.Sprintf("{{.Width}}{{if eq .Width %d}}: default{{end}}", anyWidth)
// supportedWidthsByCanonicalTypeFamily is a mapping from a canonical type
// family to all widths that are supported by that family. Make sure that
// anyWidth value is the last one in every slice.
var supportedWidthsByCanonicalTypeFamily = map[types.Family][]int32{
types.BoolFamily: {anyWidth},
types.BytesFamily: {anyWidth},
types.DecimalFamily: {anyWidth},
types.IntFamily: {16, 32, anyWidth},
types.FloatFamily: {anyWidth},
types.TimestampTZFamily: {anyWidth},
types.IntervalFamily: {anyWidth},
typeconv.DatumVecCanonicalTypeFamily: {anyWidth},
}
var numericCanonicalTypeFamilies = []types.Family{types.IntFamily, types.FloatFamily, types.DecimalFamily}
// toVecMethod returns the method name from coldata.Vec interface that can be
// used to get the well-typed underlying memory from a vector.
func toVecMethod(canonicalTypeFamily types.Family, width int32) string {
switch canonicalTypeFamily {
case types.BoolFamily:
return "Bool"
case types.BytesFamily:
return "Bytes"
case types.DecimalFamily:
return "Decimal"
case types.IntFamily:
switch width {
case 16:
return "Int16"
case 32:
return "Int32"
case 64, anyWidth:
return "Int64"
default:
colexecerror.InternalError(errors.AssertionFailedf("unexpected width of int type family: %d", width))
}
case types.FloatFamily:
return "Float64"
case types.TimestampTZFamily:
return "Timestamp"
case types.IntervalFamily:
return "Interval"
case typeconv.DatumVecCanonicalTypeFamily:
return "Datum"
default:
colexecerror.InternalError(errors.AssertionFailedf("unsupported canonical type family %s", canonicalTypeFamily))
}
// This code is unreachable, but the compiler cannot infer that.
return ""
}
// toPhysicalRepresentation returns a string that describes how a single
// element from a vector of the provided family and width is represented
// physically.
func toPhysicalRepresentation(canonicalTypeFamily types.Family, width int32) string {
switch canonicalTypeFamily {
case types.BoolFamily:
return "bool"
case types.BytesFamily:
return "[]byte"
case types.DecimalFamily:
return "apd.Decimal"
case types.IntFamily:
switch width {
case 16:
return "int16"
case 32:
return "int32"
case 64, anyWidth:
return "int64"
default:
colexecerror.InternalError(errors.AssertionFailedf("unexpected width of int type family: %d", width))
}
case types.FloatFamily:
return "float64"
case types.TimestampTZFamily:
return "time.Time"
case types.IntervalFamily:
return "duration.Duration"
case typeconv.DatumVecCanonicalTypeFamily:
// This is somewhat unfortunate, but we can neither use coldata.Datum
// nor tree.Datum because we have generated files living in two
// different packages (sql/colexec and col/coldata).
return "interface{}"
default:
colexecerror.InternalError(errors.AssertionFailedf("unsupported canonical type family %s", canonicalTypeFamily))
}
// This code is unreachable, but the compiler cannot infer that.
return ""
}
|
package transfer
// CheckAmount checks if the amount is valid and returns nil if not, it returns an error
func CheckAmount(amount int) error {
if amount <= 0 {
return ErrInvalidAmount
}
return nil
}
|
package test
import (
"github.com/mandatorySuicide/ts-common/comutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"testing"
)
type AccessoryTestSuit struct {
suite.Suite
}
func (s *AccessoryTestSuit) Test01() {
var str1 string = ""
var str2 string = "text-1"
var str3 string = "text-2"
comutil.FirstNotNullString(str1, str2, str3)
assert.Equal(s.T(), str2, "text-1", "Should return text-1")
}
func TestAccessoryTestSuit(t *testing.T) {
t.Parallel()
suite.Run(t, new(AccessoryTestSuit))
}
|
package pay
import "github.com/acupple/alipay/enums"
type AppPayDetail struct {
PayDetail
/**
* 客户端号,标识客户端
*/
AppId string
/**
* 客户端来源
*/
Appenv string
/**
* 是否发起实名校验
*/
RnCheck string
/**
* 授权令牌(32)
*/
ExternToken string
/**
* 商户业务扩展参数
*/
OutContext string
/**
* 商品详情
*/
Body string
/**
* 商品类型
*/
GoodsType enums.GoodsType
}
func (m *AppPayDetail) NewAppPayDetail(outTradeNo string, orderName string, totalFee string, body string) AppPayDetail {
return AppPayDetail{
PayDetail.OutTradeNo: outTradeNo,
PayDetail.OrderName: orderName,
PayDetail.TotalFee: totalFee,
Body: body,
}
}
func (m *AppPayDetail) ToString() string {
return "AppPayDetail{" +
"appId='" + m.AppId + '\'' +
", appenv='" + m.Appenv + '\'' +
", rnCheck='" + m.RnCheck + '\'' +
", externToken='" + m.ExternToken + '\'' +
", outContext='" + m.OutContext + '\'' +
", body='" + m.Body + '\'' +
", goodsType=" + m.GoodsType +
"} " + m.PayDetail.ToString()
}
|
package handler
import (
"log"
"google.golang.org/protobuf/proto"
)
// TODO: 抽象出来,支持多种解码引擎,实现Unmarshal和Marshal即可
type Handler struct {
in []byte
out []byte
}
func NewHandler(in []byte) *Handler {
return &Handler{
in: in,
out: []byte{},
}
}
func (h *Handler) In(in []byte) {
h.in = in
}
func (h *Handler) Out() []byte {
return h.out
}
func (h *Handler) UnmarshalProto(m proto.Message) error {
err := proto.Unmarshal(h.in, m)
if err != nil {
log.Fatalln("Failed to parse address book:", err)
return err
}
return nil
}
func (h *Handler) MarshalProto(m proto.Message) error {
val, err := proto.Marshal(m)
if err != nil {
return err
}
h.out = val
return nil
}
|
//sorted map and produce custom json string on the sorted map
package util
import (
"bytes"
"encoding/json"
)
type OrderedMap struct {
M map[string]interface{}
ByKey bool `description:"if false, then sort by Val"`
Ascending bool
}
func (o OrderedMap) MarshalJSON() ([]byte, error) {
buf := bytes.Buffer{}
//sort
lst := make([]interface{}, len(o.M))
i := 0
for k, v := range o.M {
lst[i] = SortItem{k, v}
i++
}
sortedList := []interface{}{}
var err error
if o.ByKey {
sortedList, err = SortStructList(lst, "Key", o.Ascending)
} else {
sortedList, err = SortStructList(lst, "Val", o.Ascending)
}
Check(err)
//generate json string
buf.WriteString("{")
for i, v := range sortedList {
if i != 0 {
buf.WriteString(",")
}
key, err := json.Marshal(v.(SortItem).Key)
if err != nil {
return nil, err
}
buf.Write(key)
buf.WriteString(":")
value, err := json.Marshal(v.(SortItem).Val)
if err != nil {
return nil, err
}
buf.Write(value)
}
buf.WriteString("}")
return buf.Bytes(), nil
}
func localMain() {
m := OrderedMap{
M: map[string]interface{}{
"cake": 8,
"fruit": 10,
"banana": 8,
},
ByKey: false,
Ascending: false,
}
Ln(m)
}
|
package models
import (
"errors"
"strings"
"golang.org/x/crypto/bcrypt"
"github.com/jinzhu/gorm"
"profile.com/hash"
"profile.com/rand"
)
var (
// ErrInternalServerError is returned when err cannot be determined
ErrInternalServerError = errors.New("models: Something went wrong, contact for help")
// ErrNameMissing is returned when the user fails to input a name
ErrNameMissing = errors.New("models: Please provide your name")
// ErrEmailMissing is returned when the user fails to input an email
ErrEmailMissing = errors.New("models: Please input your email")
// ErrEmailTaken is returned when email is already in use
ErrEmailTaken = errors.New("models: This email is already in use")
// ErrInvalidCredentials is returned after an invalid login attempt
ErrInvalidCredentials = errors.New("models: Invalid login credentials")
// ErrPasswordTooShort is returned when user inputs short password
ErrPasswordTooShort = errors.New("models: The password you provided is too short, minimum of 8 characters")
// ErrPasswordNotProvided is returned when user doesnt provide a pasword
ErrPasswordNotProvided = errors.New("models: Please provide a password")
// ErrPasswordInvalid is returned when a user uses an invalid password
ErrPasswordInvalid = errors.New("models: Invalid Password, try again")
// ErrPasswordHashMissing is returned when a password hash is missing
ErrPasswordHashMissing = errors.New("models: No password hash")
// ErrRememberMissing is returned when there is no remember field set
ErrRememberMissing = errors.New("models: Remember is missing")
)
const (
pepper = "secret-user-pepper"
key = "secret-key"
)
// User defines the shape of the user db
type User struct {
gorm.Model
Name string `gorm:"not null"`
Email string `gorm:"not null;unique_index"`
Password string `gorm:"-"`
PasswordHash string `gorm:"not null"`
Remember string `gorm:"not null"`
RememberHash string
Title string
Summary string
Skills string
}
// UserDB defines the shape of the userdb interface
type UserDB interface {
Create(user *User) error
ByEmail(email string) (*User, error)
Update(user *User) error
ByRemember(rememberToken string) (*User, error)
All() (*[]User, error)
}
// UserVal is the user validation interface
type UserVal interface {
Authenticate(user *User) (*User, error)
UserDB
}
// UserService defines the shape of the userservice
type UserService interface {
UserVal
}
type userService struct {
UserVal
}
type userValidation struct {
UserDB
hmac hash.HMAC
}
type userGorm struct {
db *gorm.DB
}
// NewUserService returns the userservice struct
func NewUserService(db *gorm.DB) UserService {
ug := newUserGorm(db)
uv := newUserValidation(ug)
return &userService{
UserVal: uv,
}
}
func newUserValidation(ug *userGorm) *userValidation {
hmac := hash.NewHMAC(key)
return &userValidation{
hmac: hmac,
UserDB: ug,
}
}
func newUserGorm(db *gorm.DB) *userGorm {
return &userGorm{
db: db,
}
}
// ##################### User Service ################################ //
// ##################### User Validation ################################ //
type userValFn func(user *User) error
func runUserValFns(user *User, fns ...userValFn) error {
for _, fn := range fns {
if err := fn(user); err != nil {
return err
}
}
return nil
}
func (uv *userValidation) checkForName(user *User) error {
if user.Name == "" {
return ErrNameMissing
}
return nil
}
func (uv *userValidation) checkForEmail(user *User) error {
if user.Email == "" {
return ErrEmailMissing
}
return nil
}
func (uv *userValidation) checkForPassword(user *User) error {
if user.Password == "" {
return ErrPasswordNotProvided
}
return nil
}
func (uv *userValidation) normalizeEmail(user *User) error {
user.Email = strings.ToLower(user.Email)
user.Email = strings.TrimSpace(user.Email)
return nil
}
func (uv *userValidation) checkDBForEmail(user *User) error {
_, err := uv.UserDB.ByEmail(user.Email)
if err != nil {
return nil
}
return ErrEmailTaken
}
func (uv *userValidation) checkPasswordLength(user *User) error {
if user.Password == "" {
return nil
}
if len(user.Password) < 8 {
return ErrPasswordTooShort
}
return nil
}
func (uv *userValidation) hashPassword(user *User) error {
if user.Password == "" {
return nil
}
passwordPepper := user.Password + pepper
bytes, err := bcrypt.GenerateFromPassword([]byte(passwordPepper), bcrypt.DefaultCost)
if err != nil {
return err
}
user.PasswordHash = string(bytes)
user.Password = ""
return nil
}
func (uv *userValidation) checkForPasswordHash(user *User) error {
if user.PasswordHash == "" {
return ErrPasswordHashMissing
}
return nil
}
func (uv *userValidation) generateRemember(user *User) error {
token, err := rand.RememberToken()
if err != nil {
return err
}
user.Remember = token
return nil
}
func (uv *userValidation) rememberHash(user *User) error {
if user.Remember == "" {
return ErrRememberMissing
}
hash := uv.hmac.Hash(user.Remember)
user.RememberHash = hash
return nil
}
func (uv *userValidation) Create(user *User) error {
if err := runUserValFns(user,
uv.checkForName,
uv.checkForEmail,
uv.checkForPassword,
uv.checkPasswordLength,
uv.normalizeEmail,
uv.checkDBForEmail,
uv.hashPassword,
uv.checkForPasswordHash,
uv.generateRemember,
uv.rememberHash,
); err != nil {
return err
}
return uv.UserDB.Create(user)
}
func (uv *userValidation) ByEmail(email string) (*User, error) {
user := &User{
Email: email,
}
if err := runUserValFns(user,
uv.checkForEmail,
uv.normalizeEmail,
); err != nil {
return nil, err
}
return uv.UserDB.ByEmail(user.Email)
}
func (uv *userValidation) Update(user *User) error {
if err := runUserValFns(user,
uv.checkForName,
uv.checkForEmail,
uv.normalizeEmail,
uv.checkPasswordLength,
uv.hashPassword,
uv.checkForPasswordHash,
); err != nil {
return err
}
return uv.UserDB.Update(user)
}
func (uv *userValidation) Authenticate(user *User) (*User, error) {
if err := runUserValFns(user,
uv.checkForEmail,
uv.normalizeEmail,
uv.checkForPassword,
); err != nil {
return nil, err
}
u, err := uv.UserDB.ByEmail(user.Email)
if err != nil {
return nil, ErrInvalidCredentials
}
if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(user.Password+pepper)); err != nil {
return nil, ErrPasswordInvalid
}
return u, nil
}
// ##################### User Gorm ################################ //
func (ug *userGorm) All() (*[]User, error) {
users := []User{}
if err := ug.db.Find(&users).Error; err != nil {
return nil, err
}
return &users, nil
}
func (ug *userGorm) Create(user *User) error {
if err := ug.db.Create(user).Error; err != nil {
return err
}
return nil
}
func (ug *userGorm) ByEmail(email string) (*User, error) {
user := &User{}
err := ug.db.Where("email = ?", email).First(user).Error
if err != nil {
return nil, err
}
return user, nil
}
func (ug *userGorm) ByRemember(rememberToken string) (*User, error) {
var user User
if err := ug.db.Where("remember = ?", rememberToken).First(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
func (ug *userGorm) Update(user *User) error {
return ug.db.Save(user).Error
}
|
package package2
import (
"package1"
)
type Type2 struct {
Field1 *package1.Type1
}
func (this *Type2) Equal(that *Type2) bool {
return deriveEqual(this, that)
}
|
package merger
import (
"github.com/google/btree"
"github.com/threez/intm/internal/model"
)
// Btree attempts so sort and extend to reduce the memory
// consumption without requiring the full list to be in
// memory while processing. Processing is O(n*log(n)),
// Memory is O(n)
type Btree struct {
tree *btree.BTree
}
func NewBtree() *Btree {
return &Btree{
tree: btree.New(2),
}
}
func (m *Btree) MergeInterval(i *model.Interval) {
item := &Item{i}
removed := m.tree.ReplaceOrInsert(item)
if removed != nil {
// the interval is overlapping, extend with the
// replaced value
item.Interval.Extend(removed.(*Item).Interval)
}
var markedItems []btree.Item
// function will check if there is an overlapping
// item and then extend itself, marking all extended
// items for deletion
fn := func(i btree.Item) bool {
// skip self
if item == i {
return true // continue search
}
ival := i.(*Item).Interval
if ival.HasOverlap(item.Interval) {
ival.Extend(item.Interval)
// mark extend items for later deletion
markedItems = append(markedItems, item)
return true // continue search
}
return false // stop search
}
// search for items that need to be deleted
// left and right from the current item
m.tree.DescendLessOrEqual(item, fn)
m.tree.AscendGreaterOrEqual(item, fn)
for _, mi := range markedItems {
m.tree.Delete(mi)
}
}
func (m *Btree) Result() []*model.Interval {
var list []*model.Interval
m.tree.Ascend(func(i btree.Item) bool {
it := i.(*Item)
list = append(list, it.Interval)
return true
})
m.tree.Clear(false)
return list
}
type Item struct {
*model.Interval
}
func (i Item) Less(bi btree.Item) bool {
return i.Interval.Before(bi.(*Item).Interval)
}
|
package transwarpjsonnet
import (
"encoding/json"
"io/ioutil"
"k8s.io/klog"
"os"
"path"
"path/filepath"
"strings"
"github.com/ghodss/yaml"
"helm.sh/helm/pkg/chart"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"transwarp/release-config/pkg/apis/transwarp/v1beta1"
"WarpCloud/walm/pkg/helm/impl/plugins"
"WarpCloud/walm/pkg/k8s/converter"
"WarpCloud/walm/pkg/models/common"
"WarpCloud/walm/pkg/models/k8s"
"WarpCloud/walm/pkg/models/release"
"WarpCloud/walm/pkg/setting"
"WarpCloud/walm/pkg/util"
)
const (
CommonTemplateDir = "applib/ksonnet-lib"
TranswarpJsonetFileSuffix = ".transwarp-jsonnet.yaml"
TranswarpJsonnetTemplateDir = "template-jsonnet/"
TranswarpJsonetAppLibDir = "applib/"
TranswarpMetadataDir = "transwarp-meta/"
TranswarpCiDir = "ci/"
TranswarpMetaInfoFileName = "metainfo.yaml"
TranswarpIconFileName = "icon"
TranswarpAdvantageFileName = "advantage.html"
TranswarpArchitectureFileName = "architecture.html"
TranswarpAppYamlPattern = TranswarpJsonnetTemplateDir + "%s/%s/app.yaml"
TranswarpInstallIDKey = "Transwarp_Install_ID"
TranswarpInstallNamespaceKey = "Transwarp_Install_Namespace"
)
var commonTemplateFilesPath string
var commonTemplateFiles map[string]string
// LoadFilesFromDisk loads all files inside baseDir directory and its subdirectory recursively,
// mapping each file's path/content as a key/value into a map.
func loadFilesFromDisk(baseDir string) (map[string]string, error) {
cacheFiles := make(map[string]string)
err := filepath.Walk(baseDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
b, err := ioutil.ReadFile(path)
if err != nil {
klog.Errorf("Read file \"%s\", err: %v", path, err)
return err
}
cacheFiles[strings.TrimPrefix(filepath.ToSlash(path), baseDir)] = string(b)
}
return nil
})
if err != nil {
return cacheFiles, err
}
return cacheFiles, nil
}
func loadCommonJsonnetLib(templates map[string]string) (err error) {
if commonTemplateFiles == nil {
if len(commonTemplateFilesPath) == 0 && setting.Config.JsonnetConfig != nil {
commonTemplateFilesPath = setting.Config.JsonnetConfig.CommonTemplateFilesPath
}
if commonTemplateFilesPath == "" {
return
}
commonTemplateFiles, err = loadFilesFromDisk(commonTemplateFilesPath)
if err != nil {
klog.Errorf("failed to load common template files : %s", err.Error())
return
}
}
for key, value := range commonTemplateFiles {
templates[path.Join(CommonTemplateDir, key)] = value
}
return nil
}
type HelmNativeValues struct {
ChartName string `json:"chartName"`
ChartVersion string `json:"chartVersion"`
AppVersion string `json:"appVersion"`
ReleaseName string `json:"releaseName"`
ReleaseNamespace string `json:"releaseNamespace"`
}
type AppHelmValues struct {
Dependencies map[string]string `json:"dependencies"`
NativeValues HelmNativeValues `json:"HelmNativeValues"`
}
func buildConfigValuesToRender(
rawChart *chart.Chart, namespace, name string,
userConfigs, dependencyConfigs map[string]interface{}, dependencies map[string]string,
isomateConfigValue map[string]interface{}) (configValues map[string]interface{}, err error) {
configValues = map[string]interface{}{}
util.MergeValues(configValues, setting.Config.AdditionAppConfig.ExtraConfig, false)
util.MergeValues(configValues, rawChart.Values, false)
util.MergeValues(configValues, dependencyConfigs, false)
//config TosVersion can be override by user configs
configValues["TosVersion"] = setting.Config.AdditionAppConfig.TosVersion
util.MergeValues(configValues, userConfigs, false)
util.MergeValues(configValues, isomateConfigValue, false)
// the configs below can not be override by user configs
configValues["helmReleaseName"] = name
configValues["helmReleaseNamespace"] = namespace
configValues["chartVersion"] = rawChart.Metadata.Version
configValues["chartName"] = rawChart.Metadata.Name
configValues["chartAppVersion"] = rawChart.Metadata.AppVersion
configValues[TranswarpInstallNamespaceKey] = namespace
//Compatible
configValues["Customized_Namespace"] = namespace
helmVals := AppHelmValues{}
helmVals.NativeValues.ChartName = rawChart.Metadata.Name
helmVals.NativeValues.ChartVersion = rawChart.Metadata.Version
helmVals.NativeValues.AppVersion = rawChart.Metadata.AppVersion
helmVals.NativeValues.ReleaseName = name
helmVals.NativeValues.ReleaseNamespace = namespace
helmVals.Dependencies = dependencies
chartRawBase := map[string]interface{}{}
chartRawBase["HelmAdditionalValues"] = helmVals
chartJsonRawBase := map[string]interface{}{}
chartJsonRawVals, _ := yaml.Marshal(chartRawBase)
yaml.Unmarshal(chartJsonRawVals, &chartJsonRawBase)
util.MergeValues(configValues, chartJsonRawBase, false)
return configValues, nil
}
func ProcessChart(chartInfo *release.ChartDetailInfo, releaseRequest *release.ReleaseRequestV2, rawChart *chart.Chart,
namespace string, configValues, dependencyConfigs map[string]interface{}, dependencies, releaseLabels map[string]string,
isomateConfigValue map[string]interface{}, updateConfigMap bool) (err error) {
if chartInfo.WalmVersion == common.WalmVersionV2 {
err = ProcessJsonnetChart(
releaseRequest.RepoName, rawChart, namespace,
releaseRequest.Name, configValues, dependencyConfigs,
dependencies, releaseLabels, releaseRequest.ChartImage,
releaseRequest.IsomateConfig, isomateConfigValue, common.WalmVersionV2, updateConfigMap)
if err != nil {
klog.Errorf("failed to ProcessJsonnetChart : %s", err.Error())
return
}
} else if chartInfo.WalmVersion == common.WalmVersionV1 {
err = ProcessJsonnetChartV1(
releaseRequest.RepoName, rawChart, namespace,
releaseRequest.Name, configValues, dependencyConfigs,
dependencies, releaseLabels, releaseRequest.ChartImage,
releaseRequest.IsomateConfig, isomateConfigValue, common.WalmVersionV1, updateConfigMap)
if err != nil {
klog.Errorf("failed to ProcessJsonnetChart v1: %s", err.Error())
return
}
}
return
}
// convert jsonnet chart to native chart
// 1. load jsonnet template files to render
// a. load common jsonnet lib
// b. load jsonnet chart template files
// 2. build config values to render jsonnet template files
// a. merge values from value.yaml
// b. merge system values
// c. merge dependency release output configs
// d. merge configs user provided
// 3. render jsonnet template files to generate native chart templates
func ProcessJsonnetChart(repo string, rawChart *chart.Chart, releaseNamespace,
releaseName string, userConfigs, dependencyConfigs map[string]interface{},
dependencies, releaseLabels map[string]string, chartImage string, isomateConfig *k8s.IsomateConfig,
isomateConfigValue map[string]interface{}, chartWalmVersion common.WalmVersion, updateConfigMap bool) error {
jsonnetTemplateFiles := make(map[string]string, 0)
var rawChartFiles []*chart.File
for _, f := range rawChart.Files {
if strings.HasPrefix(f.Name, TranswarpJsonnetTemplateDir) {
cname := strings.TrimPrefix(f.Name, TranswarpJsonnetTemplateDir)
if strings.IndexAny(cname, "._") == 0 {
// Ignore charts/ that start with . or _.
continue
}
appcname := path.Join(releaseName, rawChart.Metadata.AppVersion, TranswarpJsonnetTemplateDir, cname)
jsonnetTemplateFiles[appcname] = string(f.Data)
} else if strings.HasPrefix(f.Name, TranswarpJsonetAppLibDir) {
jsonnetTemplateFiles[f.Name] = string(f.Data)
} else if !strings.HasPrefix(f.Name, TranswarpCiDir) {
rawChartFiles = append(rawChartFiles, f)
}
}
autoGenReleaseConfig, err := buildAutoGenReleaseConfig(
releaseNamespace, releaseName, repo,
rawChart.Metadata.Name, rawChart.Metadata.Version,
rawChart.Metadata.AppVersion, releaseLabels, dependencies,
dependencyConfigs, userConfigs, chartImage, isomateConfig, chartWalmVersion)
if err != nil {
klog.Errorf("failed to auto gen release config : %s", err.Error())
return err
}
rawChart.Templates = append(rawChart.Templates, &chart.File{
Name: BuildNotRenderedFileName("autogen-releaseconfig.json"),
Data: autoGenReleaseConfig,
})
rawChart.Files = rawChartFiles
if len(jsonnetTemplateFiles) == 0 {
// native chart
klog.Infof("chart %s is native chart", rawChart.Metadata.Name)
return nil
}
// load values.yaml
valueYamlContent, err := json.Marshal(rawChart.Values)
jsonnetTemplateFiles[path.Join(releaseName, rawChart.Metadata.AppVersion, "values.yaml")] = string(valueYamlContent)
loadCommonJsonnetLib(jsonnetTemplateFiles)
configValues, err := buildConfigValuesToRender(rawChart, releaseNamespace, releaseName, userConfigs, dependencyConfigs, dependencies, isomateConfigValue)
if err != nil {
klog.Errorf("failed to build config values to render jsonnet template files : %s", err.Error())
return err
}
jsonStr, err := renderMainJsonnetFile(jsonnetTemplateFiles, configValues)
if err != nil {
klog.Errorf("failed to render jsonnet files : %s", err.Error())
return err
}
// adjust for kundb devops modules
k8sLabels := map[string]string{}
if releaseLabels["project-name"] != "" {
k8sLabels["project-name"] = releaseLabels["project-name"]
}
if releaseLabels["product-line"] != "" {
k8sLabels["product-line"] = releaseLabels["product-line"]
}
kubeResources, err := buildKubeResourcesByJsonStr(jsonStr, k8sLabels)
if err != nil {
klog.Errorf("failed to build native chart templates : %s", err.Error())
return err
}
for fileName, kubeResourceBytes := range kubeResources {
rawChart.Templates = append(rawChart.Templates, &chart.File{
Name: BuildNotRenderedFileName(fileName),
Data: kubeResourceBytes,
})
}
return nil
}
func ProcessJsonnetChartV1(
repo string, rawChart *chart.Chart, releaseNamespace,
releaseName string, userConfigs, dependencyConfigs map[string]interface{},
dependencies, releaseLabels map[string]string, chartImage string, isomateConfig *k8s.IsomateConfig,
isomateConfigValue map[string]interface{}, chartWalmVersion common.WalmVersion, updateConfigMap bool) error {
jsonnetTemplateFiles := make(map[string]string, 0)
var rawChartFiles []*chart.File
for _, f := range rawChart.Files {
if strings.HasPrefix(f.Name, TranswarpJsonnetTemplateDir) {
cname := strings.TrimPrefix(f.Name, TranswarpJsonnetTemplateDir)
if strings.IndexAny(cname, "._") == 0 {
// Ignore charts/ that start with . or _.
continue
}
appcname := path.Join(releaseName, rawChart.Metadata.AppVersion, TranswarpJsonnetTemplateDir, cname)
jsonnetTemplateFiles[appcname] = string(f.Data)
} else {
rawChartFiles = append(rawChartFiles, f)
}
}
autoGenReleaseConfig, err := buildAutoGenReleaseConfig(
releaseNamespace, releaseName, repo,
rawChart.Metadata.Name, rawChart.Metadata.Version,
rawChart.Metadata.AppVersion, releaseLabels, dependencies,
dependencyConfigs, userConfigs, chartImage, isomateConfig, chartWalmVersion)
if err != nil {
klog.Errorf("failed to auto gen release config : %s", err.Error())
return err
}
rawChart.Templates = append(rawChart.Templates, &chart.File{
Name: BuildNotRenderedFileName("autogen-releaseconfig.json"),
Data: autoGenReleaseConfig,
})
rawChart.Files = rawChartFiles
if len(jsonnetTemplateFiles) == 0 {
// native chart
klog.Infof("chart %s is native chart", rawChart.Metadata.Name)
return nil
}
configValues, err := buildConfigValuesToRender(rawChart, releaseNamespace, releaseName, userConfigs, dependencyConfigs, dependencies, isomateConfigValue)
if err != nil {
klog.Errorf("failed to build config values to render jsonnet template files : %s", err.Error())
return err
}
jsonStr, err := renderMainJsonnetFile(jsonnetTemplateFiles, configValues)
if err != nil {
klog.Errorf("failed to render jsonnet files : %s", err.Error())
return err
}
// adjust for kundb devops modules
k8sLabels := map[string]string{}
if releaseLabels["project-name"] != "" {
k8sLabels["project-name"] = releaseLabels["project-name"]
}
if releaseLabels["product-line"] != "" {
k8sLabels["product-line"] = releaseLabels["product-line"]
}
kubeResources, err := buildKubeResourcesByJsonStr(jsonStr, k8sLabels)
if err != nil {
klog.Errorf("failed to build native chart templates : %s", err.Error())
return err
}
for fileName, kubeResourceBytes := range kubeResources {
rawChart.Templates = append(rawChart.Templates, &chart.File{
Name: BuildNotRenderedFileName(fileName),
Data: kubeResourceBytes,
})
}
return nil
}
func buildAutoGenReleaseConfig(releaseNamespace, releaseName, repo, chartName, chartVersion, chartAppVersion string,
labels, dependencies map[string]string, dependencyConfigs, userConfigs map[string]interface{}, chartImage string,
isomateConfig *k8s.IsomateConfig, chartWalmVersion common.WalmVersion) ([]byte, error) {
if labels == nil {
labels = map[string]string{}
}
labels[plugins.AutoGenLabelKey] = "true"
releaseConfig := &v1beta1.ReleaseConfig{
TypeMeta: metav1.TypeMeta{
Kind: "ReleaseConfig",
APIVersion: "apiextensions.transwarp.io/v1beta1",
},
ObjectMeta: metav1.ObjectMeta{
Namespace: releaseNamespace,
Name: releaseName,
Labels: labels,
},
Spec: v1beta1.ReleaseConfigSpec{
DependenciesConfigValues: dependencyConfigs,
ChartVersion: chartVersion,
ChartName: chartName,
ChartAppVersion: chartAppVersion,
ConfigValues: userConfigs,
Dependencies: dependencies,
OutputConfig: map[string]interface{}{},
Repo: repo,
ChartImage: chartImage,
IsomateConfig: converter.ConvertIsomateConfigToK8s(isomateConfig),
ChartWalmVersion: string(chartWalmVersion),
},
}
releaseConfigBytes, err := yaml.Marshal(releaseConfig)
if err != nil {
klog.Errorf("failed to marshal release config : %s", err.Error())
return nil, err
}
return releaseConfigBytes, nil
}
|
package models
import(
"encoding/json"
)
/**
* Type definition for UpgradabilityEnum enum
*/
type UpgradabilityEnum int
/**
* Value collection for UpgradabilityEnum enum
*/
const (
Upgradability_KUPGRADABLE UpgradabilityEnum = 1 + iota
Upgradability_KCURRENT
Upgradability_KUNKNOWN
Upgradability_KNONUPGRADABLEINVALIDVERSION
Upgradability_KNONUPGRADABLEAGENTISNEWER
Upgradability_KNONUPGRADABLEAGENTISOLD
)
func (r UpgradabilityEnum) MarshalJSON() ([]byte, error) {
s := UpgradabilityEnumToValue(r)
return json.Marshal(s)
}
func (r *UpgradabilityEnum) UnmarshalJSON(data []byte) error {
var s string
json.Unmarshal(data, &s)
v := UpgradabilityEnumFromValue(s)
*r = v
return nil
}
/**
* Converts UpgradabilityEnum to its string representation
*/
func UpgradabilityEnumToValue(upgradabilityEnum UpgradabilityEnum) string {
switch upgradabilityEnum {
case Upgradability_KUPGRADABLE:
return "kUpgradable"
case Upgradability_KCURRENT:
return "kCurrent"
case Upgradability_KUNKNOWN:
return "kUnknown"
case Upgradability_KNONUPGRADABLEINVALIDVERSION:
return "kNonUpgradableInvalidVersion"
case Upgradability_KNONUPGRADABLEAGENTISNEWER:
return "kNonUpgradableAgentIsNewer"
case Upgradability_KNONUPGRADABLEAGENTISOLD:
return "kNonUpgradableAgentIsOld"
default:
return "kUpgradable"
}
}
/**
* Converts UpgradabilityEnum Array to its string Array representation
*/
func UpgradabilityEnumArrayToValue(upgradabilityEnum []UpgradabilityEnum) []string {
convArray := make([]string,len( upgradabilityEnum))
for i:=0; i<len(upgradabilityEnum);i++ {
convArray[i] = UpgradabilityEnumToValue(upgradabilityEnum[i])
}
return convArray
}
/**
* Converts given value to its enum representation
*/
func UpgradabilityEnumFromValue(value string) UpgradabilityEnum {
switch value {
case "kUpgradable":
return Upgradability_KUPGRADABLE
case "kCurrent":
return Upgradability_KCURRENT
case "kUnknown":
return Upgradability_KUNKNOWN
case "kNonUpgradableInvalidVersion":
return Upgradability_KNONUPGRADABLEINVALIDVERSION
case "kNonUpgradableAgentIsNewer":
return Upgradability_KNONUPGRADABLEAGENTISNEWER
case "kNonUpgradableAgentIsOld":
return Upgradability_KNONUPGRADABLEAGENTISOLD
default:
return Upgradability_KUPGRADABLE
}
}
|
package palinfrome
import (
"fmt"
"testing"
)
func TestIsPalindrome(t *testing.T) {
x := 1
re := IsPalindrome(x)
if !re {
t.Error("check number is error, expected result is true")
}
x = 1221
fmt.Println(IsPalindrome(x))
}
|
package migrator
import (
"testing"
"github.com/stretchr/testify/assert"
)
type testColumnType string
func (c testColumnType) buildRow() string {
return string(c)
}
func TestColumnRender(t *testing.T) {
t.Run("it renders row from one column", func(t *testing.T) {
c := columns{column{"test", testColumnType("run")}}
assert.Equal(t, "`test` run", c.render())
})
t.Run("it renders row from multiple columns", func(t *testing.T) {
c := columns{
column{"test", testColumnType("run")},
column{"again", testColumnType("me")},
}
assert.Equal(t, "`test` run, `again` me", c.render())
})
}
func TestInteger(t *testing.T) {
t.Run("it builds basic column type", func(t *testing.T) {
c := Integer{}
assert.Equal(t, "int NOT NULL", c.buildRow())
})
t.Run("it build with prefix", func(t *testing.T) {
c := Integer{Prefix: "super"}
assert.Equal(t, "superint NOT NULL", c.buildRow())
})
t.Run("it builds with precision", func(t *testing.T) {
c := Integer{Precision: 20}
assert.Equal(t, "int(20) NOT NULL", c.buildRow())
})
t.Run("it builds unsigned", func(t *testing.T) {
c := Integer{Unsigned: true}
assert.Equal(t, "int unsigned NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := Integer{Nullable: true}
assert.Equal(t, "int NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := Integer{Default: "0"}
assert.Equal(t, "int NOT NULL DEFAULT 0", c.buildRow())
})
t.Run("it builds with autoincrement", func(t *testing.T) {
c := Integer{Autoincrement: true}
assert.Equal(t, "int NOT NULL AUTO_INCREMENT", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := Integer{OnUpdate: "set null"}
assert.Equal(t, "int NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := Integer{Comment: "test"}
assert.Equal(t, "int NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := Integer{
Prefix: "big",
Precision: 10,
Unsigned: true,
Nullable: true,
Default: "100",
Autoincrement: true,
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"bigint(10) unsigned NULL DEFAULT 100 AUTO_INCREMENT ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestFloatable(t *testing.T) {
t.Run("it builds with default type", func(t *testing.T) {
c := Floatable{}
assert.Equal(t, "float NOT NULL", c.buildRow())
})
t.Run("it builds basic column type", func(t *testing.T) {
c := Floatable{Type: "real"}
assert.Equal(t, "real NOT NULL", c.buildRow())
})
t.Run("it builds with precision", func(t *testing.T) {
c := Floatable{Type: "double", Precision: 20}
assert.Equal(t, "double(20) NOT NULL", c.buildRow())
})
t.Run("it builds with precision and scale", func(t *testing.T) {
c := Floatable{Type: "decimal", Precision: 10, Scale: 2}
assert.Equal(t, "decimal(10,2) NOT NULL", c.buildRow())
})
t.Run("it builds unsigned", func(t *testing.T) {
c := Floatable{Unsigned: true}
assert.Equal(t, "float unsigned NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := Floatable{Nullable: true}
assert.Equal(t, "float NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := Floatable{Default: "0.0"}
assert.Equal(t, "float NOT NULL DEFAULT 0.0", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := Floatable{OnUpdate: "set null"}
assert.Equal(t, "float NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := Floatable{Comment: "test"}
assert.Equal(t, "float NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := Floatable{
Type: "decimal",
Precision: 10,
Scale: 2,
Unsigned: true,
Nullable: true,
Default: "100.0",
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"decimal(10,2) unsigned NULL DEFAULT 100.0 ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestTimeable(t *testing.T) {
t.Run("it builds with default type", func(t *testing.T) {
c := Timable{}
assert.Equal(t, "timestamp NOT NULL", c.buildRow())
})
t.Run("it builds basic column type", func(t *testing.T) {
c := Timable{Type: "datetime"}
assert.Equal(t, "datetime NOT NULL", c.buildRow())
})
t.Run("it does not set precision for invalid column type", func(t *testing.T) {
c := Timable{Type: "date", Precision: 3}
assert.Equal(t, "date NOT NULL", c.buildRow())
})
t.Run("it does not set zero precision", func(t *testing.T) {
c := Timable{Type: "timestamp", Precision: 0}
assert.Equal(t, "timestamp NOT NULL", c.buildRow())
})
t.Run("it does not set invalid precision", func(t *testing.T) {
c := Timable{Type: "timestamp", Precision: 7}
assert.Equal(t, "timestamp NOT NULL", c.buildRow())
})
t.Run("it builds with precision", func(t *testing.T) {
c := Timable{Type: "TIMESTAMP", Precision: 6}
assert.Equal(t, "TIMESTAMP(6) NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := Timable{Nullable: true}
assert.Equal(t, "timestamp NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := Timable{Default: "CURRENT_TIMESTAMP"}
assert.Equal(t, "timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := Timable{OnUpdate: "set null"}
assert.Equal(t, "timestamp NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := Timable{Comment: "test"}
assert.Equal(t, "timestamp NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := Timable{
Type: "datetime",
Nullable: true,
Default: "CURRENT_TIMESTAMP",
OnUpdate: "CURRENT_TIMESTAMP",
Comment: "test",
}
assert.Equal(
t,
"datetime NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'test'",
c.buildRow(),
)
})
}
func TestString(t *testing.T) {
t.Run("it builds with default type", func(t *testing.T) {
c := String{}
assert.Equal(t, "varchar COLLATE utf8mb4_unicode_ci NOT NULL", c.buildRow())
})
t.Run("it builds fixed", func(t *testing.T) {
c := String{Fixed: true}
assert.Equal(t, "char COLLATE utf8mb4_unicode_ci NOT NULL", c.buildRow())
})
t.Run("it builds with precision", func(t *testing.T) {
c := String{Precision: 255}
assert.Equal(t, "varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL", c.buildRow())
})
t.Run("it builds with charset", func(t *testing.T) {
c := String{Charset: "utf8"}
assert.Equal(t, "varchar CHARACTER SET utf8 NOT NULL", c.buildRow())
})
t.Run("it builds with collate", func(t *testing.T) {
c := String{Collate: "utf8mb4_general_ci"}
assert.Equal(t, "varchar COLLATE utf8mb4_general_ci NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := String{Nullable: true}
assert.Equal(t, "varchar COLLATE utf8mb4_unicode_ci NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := String{Default: "done"}
assert.Equal(t, "varchar COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'done'", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := String{OnUpdate: "set null"}
assert.Equal(t, "varchar COLLATE utf8mb4_unicode_ci NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := String{Comment: "test"}
assert.Equal(t, "varchar COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := String{
Fixed: true,
Precision: 36,
Nullable: true,
Charset: "utf8mb4",
Collate: "utf8mb4_general_ci",
Default: "nice",
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"char(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'nice' ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestText(t *testing.T) {
t.Run("it builds with default type", func(t *testing.T) {
c := Text{}
assert.Equal(t, "text COLLATE utf8mb4_unicode_ci NOT NULL", c.buildRow())
})
t.Run("it builds with prefix", func(t *testing.T) {
c := Text{Prefix: "medium"}
assert.Equal(t, "mediumtext COLLATE utf8mb4_unicode_ci NOT NULL", c.buildRow())
})
t.Run("it builds blob", func(t *testing.T) {
c := Text{Blob: true}
assert.Equal(t, "blob COLLATE utf8mb4_unicode_ci NOT NULL", c.buildRow())
})
t.Run("it builds blob with prefix", func(t *testing.T) {
c := Text{Prefix: "tiny", Blob: true}
assert.Equal(t, "tinyblob COLLATE utf8mb4_unicode_ci NOT NULL", c.buildRow())
})
t.Run("it builds with charset", func(t *testing.T) {
c := Text{Charset: "utf8"}
assert.Equal(t, "text CHARACTER SET utf8 NOT NULL", c.buildRow())
})
t.Run("it builds with collate", func(t *testing.T) {
c := Text{Collate: "utf8mb4_general_ci"}
assert.Equal(t, "text COLLATE utf8mb4_general_ci NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := Text{Nullable: true}
assert.Equal(t, "text COLLATE utf8mb4_unicode_ci NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := Text{Default: "done"}
assert.Equal(t, "text COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'done'", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := Text{OnUpdate: "set null"}
assert.Equal(t, "text COLLATE utf8mb4_unicode_ci NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := Text{Comment: "test"}
assert.Equal(t, "text COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := Text{
Prefix: "long",
Blob: true,
Nullable: true,
Charset: "utf8mb4",
Collate: "utf8mb4_general_ci",
Default: "nice",
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"longblob CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT 'nice' ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestJson(t *testing.T) {
t.Run("it builds with default type", func(t *testing.T) {
c := JSON{}
assert.Equal(t, "json NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := JSON{Nullable: true}
assert.Equal(t, "json NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := JSON{Default: "{}"}
assert.Equal(t, "json NOT NULL DEFAULT '{}'", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := JSON{OnUpdate: "set null"}
assert.Equal(t, "json NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := JSON{Comment: "test"}
assert.Equal(t, "json NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := JSON{
Nullable: true,
Default: "{}",
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"json NULL DEFAULT '{}' ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestEnum(t *testing.T) {
t.Run("it builds with default type", func(t *testing.T) {
c := Enum{}
assert.Equal(t, "enum('') NOT NULL", c.buildRow())
})
t.Run("it builds with multiple flag", func(t *testing.T) {
c := Enum{Multiple: true}
assert.Equal(t, "set('') NOT NULL", c.buildRow())
})
t.Run("it builds with values", func(t *testing.T) {
c := Enum{Values: []string{"active", "inactive"}}
assert.Equal(t, "enum('active', 'inactive') NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := Enum{Nullable: true}
assert.Equal(t, "enum('') NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := Enum{Default: "valid"}
assert.Equal(t, "enum('') NOT NULL DEFAULT 'valid'", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := Enum{OnUpdate: "set null"}
assert.Equal(t, "enum('') NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := Enum{Comment: "test"}
assert.Equal(t, "enum('') NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := Enum{
Multiple: true,
Values: []string{"male", "female", "other"},
Nullable: true,
Default: "male,female",
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"set('male', 'female', 'other') NULL DEFAULT 'male,female' ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestBit(t *testing.T) {
t.Run("it builds basic column type", func(t *testing.T) {
c := Bit{}
assert.Equal(t, "bit NOT NULL", c.buildRow())
})
t.Run("it builds with precision", func(t *testing.T) {
c := Bit{Precision: 20}
assert.Equal(t, "bit(20) NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := Bit{Nullable: true}
assert.Equal(t, "bit NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := Bit{Default: "1"}
assert.Equal(t, "bit NOT NULL DEFAULT 1", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := Bit{OnUpdate: "set null"}
assert.Equal(t, "bit NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := Bit{Comment: "test"}
assert.Equal(t, "bit NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := Bit{
Precision: 10,
Nullable: true,
Default: "0",
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"bit(10) NULL DEFAULT 0 ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestBinary(t *testing.T) {
t.Run("it builds with default type", func(t *testing.T) {
c := Binary{}
assert.Equal(t, "varbinary NOT NULL", c.buildRow())
})
t.Run("it builds fixed", func(t *testing.T) {
c := Binary{Fixed: true}
assert.Equal(t, "binary NOT NULL", c.buildRow())
})
t.Run("it builds with precision", func(t *testing.T) {
c := Binary{Precision: 255}
assert.Equal(t, "varbinary(255) NOT NULL", c.buildRow())
})
t.Run("it builds nullable column type", func(t *testing.T) {
c := Binary{Nullable: true}
assert.Equal(t, "varbinary NULL", c.buildRow())
})
t.Run("it builds with default value", func(t *testing.T) {
c := Binary{Default: "1"}
assert.Equal(t, "varbinary NOT NULL DEFAULT 1", c.buildRow())
})
t.Run("it builds with on_update setter", func(t *testing.T) {
c := Binary{OnUpdate: "set null"}
assert.Equal(t, "varbinary NOT NULL ON UPDATE set null", c.buildRow())
})
t.Run("it builds with comment", func(t *testing.T) {
c := Binary{Comment: "test"}
assert.Equal(t, "varbinary NOT NULL COMMENT 'test'", c.buildRow())
})
t.Run("it builds string with all parameters", func(t *testing.T) {
c := Binary{
Fixed: true,
Precision: 36,
Nullable: true,
Default: "1",
OnUpdate: "set null",
Comment: "test",
}
assert.Equal(
t,
"binary(36) NULL DEFAULT 1 ON UPDATE set null COMMENT 'test'",
c.buildRow(),
)
})
}
func TestBuildDefaultForString(t *testing.T) {
t.Run("it returns an empty string if default value is missing", func(t *testing.T) {
got := buildDefaultForString("")
assert.Equal(t, "", got)
})
t.Run("it builds default with expression", func(t *testing.T) {
got := buildDefaultForString("(UUID())")
want := " DEFAULT (UUID())"
assert.Equal(t, want, got)
})
t.Run("it builds default with empty string for <empty> value", func(t *testing.T) {
got := buildDefaultForString("<empty>")
want := " DEFAULT ''"
assert.Equal(t, want, got)
})
t.Run("it builds default with empty string for <nil> value", func(t *testing.T) {
got := buildDefaultForString("<nil>")
want := " DEFAULT ''"
assert.Equal(t, want, got)
})
t.Run("it builds normal default", func(t *testing.T) {
got := buildDefaultForString("value")
want := " DEFAULT 'value'"
assert.Equal(t, want, got)
})
}
|
package main
import "fmt"
func sort(arr []int) {
for i := 0; i < len(arr) - 1; i++ {
for j := i + 1; j < len(arr); j++ {
if (arr[i] > arr[j]) {
temp := arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
}
}
func print(arr []int) {
for i := 0; i < len(arr); i++ {
fmt.Printf("%d, ", arr[i])
}
fmt.Println()
}
func main() {
arr := []int{5, 3, 1, 2, 10, -5}
fmt.Println("========排序前=========")
print(arr)
fmt.Println("========排序后=========")
sort(arr)
print(arr)
}
|
package adapter
import (
"github.com/case2912/go-curd-clean-architecture/domain"
)
type UserRepository interface {
Store(domain.User) domain.User
FindByUserName(domain.User) domain.User
}
|
package _4_Exploring_the_Water
import "fmt"
func main() {
//str := "hello"
str := "aabb"
res := palindromeRearranging(str)
fmt.Println(res)
}
func palindromeRearranging(inputString string) bool {
mapUniquValues := map[string]int{} // map for keeping quantities of every letter in string value
numberEven := 0 // for saving quantity of EVEN number, if > 1, return false
if len(inputString) == 1 {
return true
} else {
for _, val := range inputString {
mapUniquValues[string(val)]++
}
}
for _, val := range mapUniquValues {
if val%2 != 0 {
numberEven++
}
}
if numberEven > 1 {
return false
}
return true
}
|
package main
//Invaliud
//Checks if assigment calls for implicit type cast to base type when passed that of defined type resolvable to that base type
func main() {
type num int
var a int = (num)(3)
} |
package k8s
import "k8s.io/apimachinery/pkg/types"
type UIDSet map[types.UID]bool
func NewUIDSet(uids ...types.UID) UIDSet {
ret := make(map[types.UID]bool)
for _, uid := range uids {
ret[uid] = true
}
return ret
}
func (s UIDSet) Add(uids ...types.UID) {
for _, uid := range uids {
s[uid] = true
}
}
func (s UIDSet) Contains(uid types.UID) bool {
return s[uid]
}
|
package core
import (
"container/list"
"sync"
)
type TargetOptions struct {
Protocol string
Host string
Port int
ClientId string
UserName string
Password string
}
type optionList struct {
TargetInfo *list.List
}
var optsList *optionList
var optsOnce sync.Once
func getTargetInfo() *optionList {
optsOnce.Do(func() {
optsList = &optionList{}
optsList.TargetInfo = list.New()
})
return optsList
}
func SetTargetInfo(protocol string, host string, port int, clientId string, username string, password string) {
if optsList != nil && optsList.TargetInfo != nil {
opts := &TargetOptions{
Protocol: protocol,
Host: host,
Port: port,
ClientId: clientId,
UserName: username,
Password: password,
}
optsList.TargetInfo.PushBack(opts)
} else {
getTargetInfo()
opts := &TargetOptions{
Protocol: protocol,
Host: host,
Port: port,
ClientId: clientId,
UserName: username,
Password: password,
}
optsList.TargetInfo.PushBack(opts)
}
}
func GetTargetInfo() *optionList {
return optsList
}
|
package reltest
import (
"context"
"reflect"
"github.com/go-rel/rel"
)
type find []*MockFind
func (f *find) register(ctxData ctxData, queriers ...rel.Querier) *MockFind {
mf := &MockFind{
assert: &Assert{ctxData: ctxData},
argQuery: rel.Build("", queriers...),
}
*f = append(*f, mf)
return mf
}
func (f find) execute(ctx context.Context, record interface{}, queriers ...rel.Querier) error {
query := rel.Build("", queriers...)
for _, mf := range f {
if matchQuery(mf.argQuery, query) &&
mf.assert.call(ctx) {
if mf.argRecord != nil {
reflect.ValueOf(record).Elem().Set(reflect.ValueOf(mf.argRecord))
}
return mf.retError
}
}
mf := &MockFind{
assert: &Assert{ctxData: fetchContext(ctx)},
argQuery: query,
argRecord: record,
}
panic(failExecuteMessage(mf, f))
}
func (f *find) assert(t T) bool {
t.Helper()
for _, mf := range *f {
if !mf.assert.assert(t, mf) {
return false
}
}
*f = nil
return true
}
// MockFind asserts and simulate find function for test.
type MockFind struct {
assert *Assert
argQuery rel.Query
argRecord interface{}
retError error
}
// Result sets the result of this query.
func (mf *MockFind) Result(result interface{}) *Assert {
mf.argQuery.Table = rel.NewDocument(result, true).Table()
mf.argRecord = result
return mf.assert
}
// Error sets error to be returned.
func (mf *MockFind) Error(err error) *Assert {
mf.retError = err
return mf.assert
}
// ConnectionClosed sets this error to be returned.
func (mf *MockFind) ConnectionClosed() *Assert {
return mf.Error(ErrConnectionClosed)
}
// NotFound sets NotFoundError to be returned.
func (mf *MockFind) NotFound() *Assert {
return mf.Error(rel.NotFoundError{})
}
// String representation of mocked call.
func (mf MockFind) String() string {
return mf.assert.sprintf("Find(ctx, <Any>, %s)", mf.argQuery)
}
// ExpectString representation of mocked call.
func (mf MockFind) ExpectString() string {
return mf.assert.sprintf("ExpectFind(%s)", mf.argQuery)
}
|
package supers
import (
"errors"
"fmt"
"strings"
"github.com/LiveSocket/bot/channel-service/helpers"
"github.com/LiveSocket/bot/conv"
"github.com/LiveSocket/bot/service"
"github.com/LiveSocket/bot/service/socket"
)
type channelInput struct {
SubCommand string
Channel string
BotName string
}
// Channel Adds or destroys a channel
//
// Add a channel
// ["add <channel> <botName>"]{message twitch.PrivateMessage}
//
// Destroy a channel
// ["destroy <channel>"]{message twitch.PrivateMessage}
//
// Returns message for chat
func Channel(service *service.Service) func(*socket.Invocation) socket.Result {
return func(invocation *socket.Invocation) socket.Result {
// Get input args from call
input, err := getChannelInput(invocation)
if err != nil {
return socket.Error(err)
}
switch input.SubCommand {
case "add":
return channelAdd(service, input)
case "destroy":
return channelDestroy(service, input)
default:
return socket.Error("Invalid subcommand")
}
}
}
func channelAdd(service *service.Service, input *channelInput) socket.Result {
// Validate input
if input.Channel == "" {
return socket.Error("Missing channel name")
}
if input.BotName == "" {
return socket.Error("Missing bot name")
}
// Create channel
_, err := helpers.CreateChannel(service, input.Channel, input.BotName)
if err != nil {
return socket.Error(err)
}
// Return message for chat
return socket.Success(fmt.Sprintf("%s channel added", input.Channel))
}
func channelDestroy(service *service.Service, input *channelInput) socket.Result {
// Validate input
if input.Channel == "" {
return socket.Error("Missing channel name")
}
// Destroy channel
err := helpers.DestroyChannel(service, input.Channel)
if err != nil {
return socket.Error(err)
}
// Return message for chat
return socket.Success(fmt.Sprintf("%s channel added", input.Channel))
}
func getChannelInput(invocation *socket.Invocation) (*channelInput, error) {
input := &channelInput{}
if len(invocation.Arguments) == 0 {
return nil, errors.New("Missing args")
}
if len(invocation.Arguments) > 0 {
input.SubCommand = strings.ToLower(conv.ToString(invocation.Arguments[0]))
}
if len(invocation.Arguments) > 1 {
input.Channel = strings.ToLower(conv.ToString(invocation.Arguments[1]))
}
if len(invocation.Arguments) > 2 {
input.BotName = conv.ToString(invocation.Arguments[2])
}
return input, nil
}
|
package controller
import (
"encoding/json"
"net/http"
"foreplay/csv/entry"
"foreplay/manager"
"shared/common"
"shared/utility/errors"
"shared/utility/glog"
)
func RegisterHttpHandler() {
http.Handle("/patch", NewPatchHandler())
http.Handle("/announcement", NewAnnouncementHandler())
http.Handle("/caution", NewCautionHandler())
http.Handle("/maintain", NewMaintainHandler())
}
func writerErrorResponse(writer http.ResponseWriter, err error) {
errCode := errors.Code(err)
if errCode == 0 {
errCode = -1
}
resp := struct {
ErrCode int `json:"err_code"`
ErrMsg string `json:"err_msg"`
}{
ErrCode: errCode,
ErrMsg: err.Error(),
}
bytes, err := json.Marshal(resp)
if err != nil {
glog.Errorf("marshal response error: %+v", err)
return
}
writer.Write(bytes)
}
type PatchHandler struct{}
func NewPatchHandler() *PatchHandler {
return &PatchHandler{}
}
func (ph *PatchHandler) ServeHTTP(respWriter http.ResponseWriter, req *http.Request) {
req.ParseForm()
channel := req.Form.Get("channel")
appVersion := req.Form.Get("app_version")
glog.Debugf("new patch request, channel: %s, app_version: %s", channel, appVersion)
appCfg, err := manager.CSV.AppList.GetAppCfg(channel)
if err != nil {
writerErrorResponse(respWriter, err)
return
}
resp := struct {
ErrCode int32 `json:"err_code"`
ErrMsg string `json:"err_msg"`
App *entry.AppCfg `json:"app"`
Patch *entry.PatchCfg `json:"patch"`
}{
ErrCode: 0,
ErrMsg: "success",
App: appCfg,
}
patchCfg, err := manager.CSV.Patches.GetPatchCfg(channel, appVersion)
if err == nil {
resp.Patch = patchCfg
}
bytes, err := json.Marshal(resp)
if err != nil {
glog.Errorf("marshal response error: %+v", err)
return
}
respWriter.Write(bytes)
}
type AnnouncementHandler struct {
}
func NewAnnouncementHandler() *AnnouncementHandler {
return &AnnouncementHandler{}
}
func (ah *AnnouncementHandler) ServeHTTP(respWriter http.ResponseWriter, req *http.Request) {
anncs, banners := manager.Announcements.GetAnnouncements()
resp := struct {
ErrCode int32 `json:"err_code"`
ErrMsg string `json:"err_msg"`
Announcements []*common.Announcement `json:"announcements"`
Banners []*common.Banner `json:"banners"`
}{
ErrCode: 0,
ErrMsg: "success",
Announcements: anncs,
Banners: banners,
}
bytes, err := json.Marshal(resp)
if err != nil {
glog.Errorf("marshal response error: %+v", err)
return
}
respWriter.Write(bytes)
}
type CautionHandler struct {
}
func NewCautionHandler() *CautionHandler {
return &CautionHandler{}
}
func (ah *CautionHandler) ServeHTTP(respWriter http.ResponseWriter, req *http.Request) {
cautions := manager.Announcements.GetCautions()
resp := struct {
ErrCode int32 `json:"err_code"`
ErrMsg string `json:"err_msg"`
Cautions []*common.Caution `json:"cautions"`
}{
ErrCode: 0,
ErrMsg: "success",
Cautions: cautions,
}
bytes, err := json.Marshal(resp)
if err != nil {
glog.Errorf("marshal response error: %+v", err)
return
}
respWriter.Write(bytes)
}
type MaintainHandler struct {
}
func NewMaintainHandler() *MaintainHandler {
return &MaintainHandler{}
}
func (ah *MaintainHandler) ServeHTTP(respWriter http.ResponseWriter, req *http.Request) {
isMaintain := manager.Server.IsMaintain()
resp := struct {
ErrCode int32 `json:"err_code"`
ErrMsg string `json:"err_msg"`
IsMaintain bool `json:"is_maintain"`
}{
ErrCode: 0,
ErrMsg: "success",
IsMaintain: isMaintain,
}
bytes, err := json.Marshal(resp)
if err != nil {
glog.Errorf("marshal response error: %+v", err)
return
}
respWriter.Write(bytes)
}
|
package v1
import (
"context"
"errors"
"fmt"
"time"
"github.com/traPtitech/trap-collection-server/src/domain"
"github.com/traPtitech/trap-collection-server/src/domain/values"
"github.com/traPtitech/trap-collection-server/src/repository"
"github.com/traPtitech/trap-collection-server/src/service"
)
type Game struct {
db repository.DB
gameRepository repository.Game
gameVersionRepository repository.GameVersion
gameManagementRole repository.GameManagementRole
userUtils *UserUtils
}
func NewGame(
db repository.DB,
gameRepository repository.Game,
gameVersionRepository repository.GameVersion,
gameManagementRole repository.GameManagementRole,
userUtils *UserUtils,
) *Game {
return &Game{
db: db,
gameRepository: gameRepository,
gameVersionRepository: gameVersionRepository,
gameManagementRole: gameManagementRole,
userUtils: userUtils,
}
}
func (g *Game) CreateGame(ctx context.Context, session *domain.OIDCSession, name values.GameName, description values.GameDescription) (*domain.Game, error) {
user, err := g.userUtils.getMe(ctx, session)
if err != nil {
return nil, fmt.Errorf("failed to get user: %w", err)
}
game := domain.NewGame(
values.NewGameID(),
name,
description,
time.Now(),
)
err = g.db.Transaction(ctx, nil, func(ctx context.Context) error {
err := g.gameRepository.SaveGame(ctx, game)
if err != nil {
return fmt.Errorf("failed to create game: %w", err)
}
err = g.gameManagementRole.AddGameManagementRoles(
ctx,
game.GetID(),
[]values.TraPMemberID{user.GetID()},
values.GameManagementRoleAdministrator,
)
if err != nil {
return fmt.Errorf("failed to add game management role: %w", err)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed in transaction: %w", err)
}
return game, nil
}
func (g *Game) UpdateGame(ctx context.Context, gameID values.GameID, name values.GameName, description values.GameDescription) (*domain.Game, error) {
var game *domain.Game
err := g.db.Transaction(ctx, nil, func(ctx context.Context) error {
var err error
game, err = g.gameRepository.GetGame(ctx, gameID, repository.LockTypeRecord)
if errors.Is(err, repository.ErrRecordNotFound) {
return service.ErrNoGame
}
if err != nil {
return fmt.Errorf("failed to get game: %w", err)
}
// 変更がなければ何もしない
if game.GetName() == name && game.GetDescription() == description {
return nil
}
game.SetName(name)
game.SetDescription(description)
err = g.gameRepository.UpdateGame(ctx, game)
if err != nil {
return fmt.Errorf("failed to save game: %w", err)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed in transaction: %w", err)
}
return game, nil
}
func (g *Game) DeleteGame(ctx context.Context, id values.GameID) error {
err := g.gameRepository.RemoveGame(ctx, id)
if errors.Is(err, repository.ErrNoRecordDeleted) {
return service.ErrNoGame
}
if err != nil {
return fmt.Errorf("failed to delete game: %w", err)
}
return nil
}
func (g *Game) GetGame(ctx context.Context, id values.GameID) (*service.GameInfo, error) {
game, err := g.gameRepository.GetGame(ctx, id, repository.LockTypeNone)
if errors.Is(err, repository.ErrRecordNotFound) {
return nil, service.ErrNoGame
}
if err != nil {
return nil, fmt.Errorf("failed to get game: %w", err)
}
gameVersion, err := g.gameVersionRepository.GetLatestGameVersion(ctx, id, repository.LockTypeNone)
if err != nil && !errors.Is(err, repository.ErrRecordNotFound) {
return nil, fmt.Errorf("failed to get game version: %w", err)
}
if errors.Is(err, repository.ErrRecordNotFound) {
gameVersion = nil
}
return &service.GameInfo{
Game: game,
LatestVersion: gameVersion,
}, nil
}
func (g *Game) GetGames(ctx context.Context) ([]*service.GameInfo, error) {
games, err := g.gameRepository.GetGames(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get games: %w", err)
}
if len(games) == 0 {
return []*service.GameInfo{}, nil
}
gameIDs := make([]values.GameID, 0, len(games))
for _, game := range games {
gameIDs = append(gameIDs, game.GetID())
}
gameVersions, err := g.gameVersionRepository.GetLatestGameVersionsByGameIDs(ctx, gameIDs, repository.LockTypeNone)
if err != nil {
return nil, fmt.Errorf("failed to get game versions: %w", err)
}
var gameInfos []*service.GameInfo
for _, game := range games {
gameVersion, ok := gameVersions[game.GetID()]
if !ok {
gameVersion = nil
}
gameInfos = append(gameInfos, &service.GameInfo{
Game: game,
LatestVersion: gameVersion,
})
}
return gameInfos, nil
}
func (g *Game) GetMyGames(ctx context.Context, session *domain.OIDCSession) ([]*service.GameInfo, error) {
user, err := g.userUtils.getMe(ctx, session)
if err != nil {
return nil, fmt.Errorf("failed to get user: %w", err)
}
games, err := g.gameRepository.GetGamesByUser(ctx, user.GetID())
if err != nil {
return nil, fmt.Errorf("failed to get game ids: %w", err)
}
gameIDs := make([]values.GameID, 0, len(games))
for _, game := range games {
gameIDs = append(gameIDs, game.GetID())
}
if len(games) == 0 {
return []*service.GameInfo{}, nil
}
gameVersions, err := g.gameVersionRepository.GetLatestGameVersionsByGameIDs(ctx, gameIDs, repository.LockTypeNone)
if err != nil {
return nil, fmt.Errorf("failed to get game versions: %w", err)
}
var gameInfos []*service.GameInfo
for _, game := range games {
gameVersion, ok := gameVersions[game.GetID()]
if !ok {
gameVersion = nil
}
gameInfos = append(gameInfos, &service.GameInfo{
Game: game,
LatestVersion: gameVersion,
})
}
return gameInfos, nil
}
|
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
"github.com/modood/wpm"
"github.com/tidwall/gjson"
)
var (
width = "32px"
height = "32px"
size = ""
)
// NewsFeed newsfeed
type NewsFeed struct {
ID string `json:"id"`
Type string `json:"type"`
Actor *Actor `json:"actor"`
Repo *Repo `json:"repo"`
Payload *Payload `json:"payload"`
Public bool `json:"public"`
CreatedAt string `json:"created_at"`
}
// Actor actor
type Actor struct {
ID int32 `json:"id"`
Login string `json:"login"`
DisplayLogin string `json:"display_login"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
AvatarURL string `json:"avatar_url"`
}
// Repo repo
type Repo struct {
ID int32 `json:"id"`
Name string `json:"name"`
URL string `json:"url"`
}
// Payload payload
type Payload struct {
Action string `json:"action"`
Ref string `json:"ref"`
RefType string `json:"ref_type"`
MasterBranch string `json:"master_branch"`
Description string `json:"description"`
PusherType string `json:"pusher_type"`
Size int32 `json:"size"`
Forkee *Forkee `json:"forkee"`
PullRequest *PullRequest `json:"pull_request"`
Comment *Comment `json:"comment"`
Issue *Issue `json:"issue"`
Member *Member `json:"member"`
}
// Forkee forkee
type Forkee struct {
ID int32 `json:"id"`
Name string `json:"name"`
FullName string `json:"full_name"`
Owner *Owner `json:"owner"`
HTMLURL string `json:"html_url"`
Description string `json:"description"`
URL string `json:"url"`
Fork bool `json:"fork"`
ForksURL string `json:"forks_url"`
}
// PullRequest pr
type PullRequest struct {
Number string
State string
Title string
Body string
}
// Comment comment
type Comment struct {
Body string
}
// Issue issue
type Issue struct {
Number string
Title string
PullRequest *PullRequest
}
// Member member
type Member struct {
Login string
}
// Owner owner
type Owner struct {
ID int32 `json:"id"`
Login string `json:"login"`
DisplayLogin string `json:"display_login"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
AvatarURL string `json:"avatar_url"`
Type string `json:"type"`
SiteAdmin string `json:"site_admin"`
}
// PRReviewEvent review PR
func PRReviewEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
number := item.Payload.PullRequest.Number
return avatar, fmt.Sprintf("%s reviewed pull request %s on %s\n\n \a at %v", user, number, repo, item.CreatedAt)
}
// PREvent open PR, close PR
func PREvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
state := item.Payload.PullRequest.State
number := item.Payload.PullRequest.Number
title := item.Payload.PullRequest.Title
body := item.Payload.PullRequest.Body
if state == "open" {
return avatar, fmt.Sprintf("%s opened pull request %s on %s \n %s \n %s \a at %v\n", user, number, repo, title, body, item.CreatedAt)
} else {
return avatar, fmt.Sprintf("%s closed pull request %s on %s \n %s \a at %v\n", user, number, repo, title, item.CreatedAt)
}
}
// comment on issue, PR
func issueCommentEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
number := item.Payload.Issue.Number
body := item.Payload.Comment.Body
group := ""
if item.Payload.Issue.PullRequest != nil {
group = "pull request"
} else {
group = "issue"
}
return avatar, fmt.Sprintf("%s commented on %s %s on %s \n %s \a at %v\n", user, group, number, repo, body, item.CreatedAt)
}
// open issue, close issue
func issuesEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
state := item.Payload.Action
number := item.Payload.Issue.Number
title := item.Payload.Issue.Title
return avatar, fmt.Sprintf("%s %s issue %s on %s \n %s \a at %v\n\n", user, state, number, repo, title, item.CreatedAt)
}
// comment on a commit
func commitCommentEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
body := item.Payload.Comment.Body
return avatar, fmt.Sprintf("%s commented on %s \n %s \a at %v\n", user, repo, body, item.CreatedAt)
}
// # starred by following
func watchEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
return avatar, fmt.Sprintf("%s starred %s \a at %v \n\n", user, repo, item.CreatedAt)
}
// # forked by following
func forkEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
return avatar, fmt.Sprintf("%s forked %s \a at %v\n\n", user, repo, item.CreatedAt)
}
// # delete branch
func deleteEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
branch := item.Payload.Ref
return avatar, fmt.Sprintf("%s deleted branch %s at \a at %v%s\n\n", user, branch, repo, item.CreatedAt)
}
// # push commits
func pushEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
size := item.Payload.Size
branch := item.Payload.Ref
return avatar, fmt.Sprintf("%s pushed %d new commit(s) to %s at %s \a at %v\n\n", user, size, branch, repo, item.CreatedAt)
}
// # create repo, branch
func createEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
group := item.Payload.RefType
branch := item.Payload.Ref
if group == "repository" {
return avatar, fmt.Sprintf("%s created %s %s \a at %v\n\n", user, group, repo, item.CreatedAt)
} else {
return avatar, fmt.Sprintf("%s created %s %s at %s \a at %v\n\n", user, group, branch, repo, item.CreatedAt)
}
}
// # make public repo
func publicEvent(item NewsFeed) (string, string) {
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
return avatar, fmt.Sprintf("%s made %s public \a at %v\n\n", user, repo, item.CreatedAt)
}
// # add collab
func memberEvent(item NewsFeed) (string, string) {
action := item.Payload.Action
collab := item.Payload.Member.Login
user, repo, avatar := getFeedBaseInfoAndPrintAvatar(item)
return avatar, fmt.Sprintf("%s %s %s as a collaborator to %s \a at %v\n\n", user, action, collab, repo, item.CreatedAt)
}
// getFeedBaseInfoAndPrintAvatar 获取feed基本信息
func getFeedBaseInfoAndPrintAvatar(item NewsFeed) (string, string, string) {
user := item.Actor.Login
repo := item.Repo.Name
avatarURL := item.Actor.AvatarURL
var avatar string
if len(avatarURL) > 0 {
res, err := http.Get(avatarURL)
if err != nil {
fmt.Printf("%s", err)
}
defer res.Body.Close()
avatar = display(res.Body) //
}
return user, repo, avatar
}
func getReceivedEvents(user, pageNo, include, exclude string) {
url := "https://api.github.com/users/" + user + "/received_events?page=" + pageNo
startTime := time.Now()
_, data, _ := GetJSON(url)
log.Printf("request Github API: /users/:user/received_events cost ( %v )\n", time.Now().Sub(startTime))
// TODO: optimize
r := gjson.Parse(data)
for _, it := range r.Array() {
event := it.Get("type").String()
item := NewsFeed{}
json.Unmarshal([]byte(it.String()), &item)
var content, avatar string
switch event {
case "PullRequestReviewCommentEvent":
avatar, content = PRReviewEvent(item)
case "PullRequestEvent":
avatar, content = PREvent(item)
case "IssueCommentEvent":
avatar, content = issueCommentEvent(item)
case "IssuesEvent":
avatar, content = issuesEvent(item)
case "CommitCommentEvent":
avatar, content = commitCommentEvent(item)
case "WatchEvent":
avatar, content = watchEvent(item)
case "ForkEvent":
avatar, content = forkEvent(item)
case "DeleteEvent":
avatar, content = deleteEvent(item)
case "PushEvent":
avatar, content = pushEvent(item)
case "CreateEvent":
avatar, content = createEvent(item)
case "PublicEvent":
avatar, content = publicEvent(item)
case "MemberEvent":
avatar, content = memberEvent(item)
default: // do nothing
}
output(avatar, content, include, exclude)
}
}
// ReceivedEvents get received events
func ReceivedEvents(user string, maxPage int, include, exclude string) {
for page := 1; page <= maxPage; page++ {
getReceivedEvents(user, fmt.Sprintf("%d", page), include, exclude)
}
}
// display 控制台打印图片
func display(r io.Reader) string {
data, err := ioutil.ReadAll(r)
if err != nil {
}
width, height := widthAndHeight()
var buf bytes.Buffer
buf.WriteString("\033]1337;File=inline=1")
if width != "" {
buf.WriteString(";width=")
buf.WriteString(width)
}
if height != "" {
buf.WriteString(";height=")
buf.WriteString(height)
}
buf.WriteString(":")
buf.WriteString(base64.StdEncoding.EncodeToString(data))
buf.WriteString("\a")
return buf.String()
}
func widthAndHeight() (w, h string) {
if width != "" {
w = width
}
if height != "" {
h = height
}
if size != "" {
sp := strings.SplitN(size, ",", -1)
if len(sp) == 2 {
w = sp[0]
h = sp[1]
}
}
return
}
func output(avatar, content, include, exclude string) {
if (len(exclude) > 0 && wpm.WildcardPatternMatch(content, "*"+exclude+"*")) ||
(len(include) > 0 && !wpm.WildcardPatternMatch(content, "*"+include+"*")) {
return
}
fmt.Print(avatar, content)
}
|
package cfg
import (
"github.com/spf13/pflag"
"github.com/spf13/viper"
"go4eat-api/pkg/cfg"
)
// NewConfig func
func NewConfig() (*viper.Viper, *pflag.FlagSet, error) {
return cfg.NewConfig(
cfg.NewOptions().UseFile("config.file").UseEnv("go4eat").UseFlags(),
[]*cfg.Property{
cfg.NewProperty("help", false).UseFlag("Print help message", "h"),
cfg.NewProperty("config.file", "config.toml").UseEnv().UseFlag("Config file", "c"),
cfg.NewProperty("task", "server").UseEnv().UseFlag("Task to run", "t"),
cfg.NewProperty("logger.level", "debug").UseEnv().UseFlag("Logger level", ""),
cfg.NewProperty("logger.stdout.enable", true).UseEnv().UseFlag("Enable logging to stdout", ""),
cfg.NewProperty("logger.stdout.print-error-stack", true).UseEnv().UseFlag("Print error stack to stdout", ""),
cfg.NewProperty("logger.graylog.enable", false).UseEnv().UseFlag("Enable logging to graylog", ""),
cfg.NewProperty("logger.graylog.address", "graylog:12201").UseEnv().UseFlag("Graylog address", ""),
cfg.NewProperty("database.uri", "mongodb://mongo:27017").UseEnv().UseFlag("Database URI", ""),
cfg.NewProperty("database.name", "go4eat").UseEnv().UseFlag("Database name", ""),
cfg.NewProperty("crypto.password.cost-factor", 12).UseEnv().UseFlag("Password hashing cost factor", ""),
cfg.NewProperty("crypto.token.secret", "abcdefghijklmnopqrstuvwxyz").UseEnv().UseFlag("Token encryption secret", ""),
cfg.NewProperty("crypto.token.expiration", 1382400).UseEnv().UseFlag("Token expiration (seconds)", ""),
cfg.NewProperty("crypto.token.renewal", 691200).UseEnv().UseFlag("Token renewal (seconds)", ""),
cfg.NewProperty("server.address", ":8080").UseEnv().UseFlag("Server address", ""),
cfg.NewProperty("server.max-header-size", 1000).UseEnv().UseFlag("Server max header size (bytes)", ""),
cfg.NewProperty("server.read-header-timeout", 200).UseEnv().UseFlag("Server read header timeout (milliseconds)", ""),
cfg.NewProperty("server.read-timeout", 500).UseEnv().UseFlag("Server read timeout (milliseconds)", ""),
cfg.NewProperty("server.write-timeout", 500).UseEnv().UseFlag("Server write timeout (milliseconds)", ""),
})
}
|
package main
import "fmt"
import "os"
import "math"
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
func main() {
// W: width of the building.
// H: height of the building.
var W, H int
fmt.Scan(&W, &H)
// N: maximum number of turns before game over.
var N int
fmt.Scan(&N)
var x, y int
fmt.Scan(&x, &y)
var x0, y0, x1, y1, dx, dy int
fmt.Fprintf(os.Stderr, "building: (%d,%d)\n", W, H)
fmt.Fprintf(os.Stderr, "N: %d\n", N)
fmt.Fprintf(os.Stderr, "batman: (%d,%d)\n", x, y)
x0 = 0
y0 = 0
x1 = W-1
y1 = H-1
for {
// BOMB_DIR: the direction of the bombs from batman's current location (U, UR, R, DR, D, DL, L or UL)
var BOMB_DIR string
fmt.Scan(&BOMB_DIR)
switch BOMB_DIR {
case "U":
// adjust box
y1 = y
dx = 0
dy = int(math.Floor(float64((y0 - y)) / 2.0))
case "UL":
// adjust box
y1 = y
x1 = x
dx = int(math.Floor(float64((x0 - x)) / 2.0))
dy = int(math.Floor(float64((y0 - y)) / 2.0))
case "UR":
// adjust box
y1 = y
x0 = x
dx = int(math.Ceil(float64((x1 - x)) / 2.0))
dy = int(math.Floor(float64((y0 - y)) / 2.0))
case "R":
// adjust box
x0 = x
dx = int(math.Ceil(float64((x1 - x)) / 2.0))
dy = 0
case "D":
// adjust box
y0 = y
dx = 0
dy = int(math.Ceil(float64((y1 - y)) / 2.0))
case "DL":
// adjust box
x1 = x
y0 = y
dx = int(math.Floor(float64((x0 - x)) / 2.0))
dy = int(math.Ceil(float64((y1 - y)) / 2.0))
case "DR":
// adjust box
x0 = x
y0 = y
dx = int(math.Ceil(float64((x1 - x)) / 2.0))
dy = int(math.Ceil(float64((y1 - y)) / 2.0))
case "L":
// adjust box
x1 = x
dx = int(math.Floor(float64((x0 - x)) / 2.0))
dy = 0
}
x += dx
y += dy
fmt.Fprintf(os.Stderr, "dir: %s, box: (%d,%d) (%d,%d)\n", BOMB_DIR, x,y,x1,y1)
fmt.Fprintf(os.Stderr, "delta: (%d,%d), next: (%d,%d)\n", dx, dy, x, y)
fmt.Printf("%d %d\n", x, y)
}
}
|
package lc
// Time: O(mn)
// Benchmark: 0ms 2mb | 100% 73%
const (
EAST = iota
SOUTH
WEST
NORTH
)
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 {
return []int{}
}
m := len(matrix)
n := len(matrix[0])
nums := make([]int, m*n)
bounds := []int{n, m, 0, 1}
direction := EAST
pos := []int{0, 0}
for i := 0; i < len(nums); i++ {
nums[i] = matrix[pos[0]][pos[1]]
if direction == EAST {
if pos[1] == bounds[EAST]-1 {
direction = SOUTH
pos[0]++
bounds[EAST]--
} else {
pos[1]++
}
} else if direction == SOUTH {
if pos[0] == bounds[SOUTH]-1 {
direction = WEST
pos[1]--
bounds[SOUTH]--
} else {
pos[0]++
}
} else if direction == WEST {
if pos[1] == bounds[WEST] {
direction = NORTH
pos[0]--
bounds[WEST]++
} else {
pos[1]--
}
} else {
if pos[0] == bounds[NORTH] {
direction = EAST
pos[1]++
bounds[NORTH]++
} else {
pos[0]--
}
}
}
return nums
}
|
package set
func subset(set, sub []int) bool {
s := deriveSet(set)
for _, k := range sub {
if _, ok := s[k]; !ok {
return false
}
}
return true
}
|
package leetcode
import (
"fmt"
"testing"
)
type question20 struct {
para20
ans20
}
// para 是参数
// one 代表第一个参数
type para20 struct {
one string
}
// ans 是答案
// one 代表第一个答案
type ans20 struct {
one bool
}
func Test_Problem20(t *testing.T) {
qs := []question20{
{
para20{"()[]{}"},
ans20{true},
},
{
para20{"(]"},
ans20{false},
},
{
para20{"({[]})"},
ans20{true},
},
{
para20{"(){[({[]})]}"},
ans20{true},
},
{
para20{"((([[[{{{"},
ans20{false},
},
{
para20{"(())]]"},
ans20{false},
},
{
para20{""},
ans20{true},
},
{
para20{"["},
ans20{false},
},
}
fmt.Printf("------------------------Leetcode Problem 20------------------------\n")
num := 0
for _, q := range qs {
ans0, p := q.ans20.one, q.para20
q1 := isValid(p.one)
fmt.Printf("【input】:%v 【output】:%v 【needing】:%v\n", p, q1, ans0)
if q1 != ans0 {
fmt.Println("fail")
num++
} else {
fmt.Println("pass")
}
if num > 0 {
fmt.Printf("have %d errors answer", num)
} else {
fmt.Printf("all pass")
}
fmt.Printf("\n\n")
}
}
|
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Package dgapi2 contains helper functions to interact with the DGAPI2 test app.
// See go/dgapi-v2.0-test-plan for the details
package dgapi2
|
package project_manager
import (
"../models"
"../repos/grant"
"../repos/project"
"../repos/schema"
"../repos/task"
"../repos/user"
)
// ProjectAggr aggregate of required entities
type ProjectAggr struct {
Project models.Project
Schema models.ProjectSchema
}
// ProjectManager manages all things about creating projects
type ProjectManager interface {
Init(ur user.Repo, pr project.Repo, gr grant.Repo, sr schema.Repo, tr task.Repo) error
Create(pa *ProjectAggr) (bool, error)
DeleteByName(string, string) (bool, error)
AddGrant(string, string, string) (bool, error)
DeleteGrant(string, string, string) (bool, error)
CheckGrant(string, string) (bool, error)
IsOwner(string, string) (bool, error)
}
|
package grpc
import (
"context"
"github.com/payfazz/fazzkit/server/common"
"github.com/payfazz/fazzkit/server/validator"
)
//DecodeOptions executed before decode process
type DecodeOptions func(ctx context.Context, model interface{}, request interface{}) error
//DecodeParam decode model with DecodeOptions
type DecodeParam struct {
Model interface{}
Options []DecodeOptions
}
//Decode generate a decode function to decode proto message to model
func Decode(model interface{}) func(context.Context, interface{}) (request interface{}, err error) {
return func(ctx context.Context, request interface{}) (interface{}, error) {
if model == nil {
return nil, nil
}
var _model interface{}
var err error
param, ok := model.(DecodeParam)
if ok {
_model, _ = common.DeepCopy(param.Model)
for _, option := range param.Options {
err = option(ctx, _model, request)
if err != nil {
return nil, err
}
}
} else {
_model, _ = common.DeepCopy(model)
}
_model, err = Parse(ctx, request, _model)
if err != nil {
return nil, err
}
err = validator.DefaultValidator()(_model)
if err != nil {
return nil, err
}
return _model, nil
}
}
|
package v1alpha1
import (
v1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
PhasePending = "PENDING"
PhaseScheduling = "SCHEDULING"
PhaseRunning = "RUNNING"
PhaseDone = "DONE"
)
// DroneFederatedDeploymentSpec defines the desired state of DroneFederatedDeployment
// +k8s:openapi-gen=true
type DroneFederatedDeploymentSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "operator-sdk generate k8s" to regenerate code after modifying this file
// Add custom validation using kubebuilder tags: https://book-v1.book.kubebuilder.io/beyond_basics/generating_crd.html
// Schedule is the desired time the command is supposed to be executed.
// Note: the format used here is UTC time https://www.utctime.net
Schedule string `json:"schedule,omitempty"`
Template v1.Deployment `json:"template,omitempty"`
//Template DroneFederatedDeploymentTemplate `json:"template,omitempty"`
Placement DroneFederatedDeploymentPlacement `json:"placement,omitempty"`
Overrides DroneFederatedDeploymentOverrides `json:"overrides,omitempty"`
}
/*
type DroneFederatedDeploymentTemplate struct {
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DroneFederatedDeploymentTemplateSpec `json:"spec,omitempty"`
}
type DroneFederatedDeploymentTemplateSpec struct {
Replicas int64 `json:"replicas,omitempty"`
Selector DroneFederatedDeploymentTemplateSpecSelector `json:"selector,omitempty"`
}
type DroneFederatedDeploymentTemplateSpecSelector struct {
MatchLabels DroneFederatedDeploymentTemplateSpecSelectorMatchLabels `json:"matchLabels,omitempty"`
}
type DroneFederatedDeploymentTemplateSpecSelectorMatchLabels struct {
App string `json:"app,omitempty"`
}
type DroneFederatedDeploymentTemplateSpecTemplate struct {
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DroneFederatedDeploymentTemplateSpecTemplateSpec `json:"spec,omitempty"`
}
type DroneFederatedDeploymentTemplateSpecTemplateSpec struct {
Containers DroneFederatedDeploymentTemplateSpecTemplateSpecContainers `json:"containers,omitempty"`
}
type DroneFederatedDeploymentTemplateSpecTemplateSpecContainers struct {
image string `json:"image,omitempty"`
Name string `json:"name,omitempty"`
Resources DroneFederatedDeploymentTemplateSpecTemplateSpecContainersResources `json:"resources,omitempty"`
}
type DroneFederatedDeploymentTemplateSpecTemplateSpecContainersResources struct {
Limits Limit `json:"limits,omitempty"`
}
type Limit struct{
Memory string `json:"memory,omitempty"`
Cpu string `json:"cpu,omitempty"`
}
*/
type DroneFederatedDeploymentPlacement struct {
Clusters []DroneFederatedDeploymentPlacementClusters `json:"clusters,omitempty"`
}
type DroneFederatedDeploymentPlacementClusters struct {
Name string `json:"name,omitempty"`
}
type DroneFederatedDeploymentOverrides struct {
}
/*
// DroneFederatedDeploymentSpec defines the desired state of DroneFederatedDeployment
// +k8s:openapi-gen=true
type DroneFederatedDeploymentSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "operator-sdk generate k8s" to regenerate code after modifying this file
// Add custom validation using kubebuilder tags: https://book-v1.book.kubebuilder.io/beyond_basics/generating_crd.html
// Schedule is the desired time the command is supposed to be executed.
// Note: the format used here is UTC time https://www.utctime.net
Schedule string `json:"schedule,omitempty"`
AppName string `json:"app-name,omitempty"`
BaseNode string `json:"base-node,omitempty"`
Type string `json:"type,omitempty"`
Components []DroneFederatedDeploymentComponent `json:"components,omitempty"`
}
type DroneFederatedDeploymentComponent struct {
Name string `json:"name,omitempty"`
Function DroneFederatedDeploymentComponentFunction `json:"function,omitempty"`
//Parameters interface{} `json:"parameters"`
BootDependencies []string `json:"boot_dependencies,omitempty"`
NodesBlacklist []string `json:"nodes-blacklist,omitempty"`
NodesWhitelist []string `json:"nodes-whitelist,omitempty"`
}
type DroneFederatedDeploymentComponentFunction struct {
Image string `json:"image,omitempty"`
Resources DroneFederatedDeploymentComponentFunctionResources `json:"resources,omitempty"`
}
type DroneFederatedDeploymentComponentFunctionResources struct {
Memory float64 `json:"memory,omitempty"`
Cpu float64 `json:"cpu,omitempty"`
}
*/
// DroneFederatedDeploymentStatus defines the observed state of DroneFederatedDeployment
// +k8s:openapi-gen=true
type DroneFederatedDeploymentStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "operator-sdk generate k8s" to regenerate code after modifying this file
// Add custom validation using kubebuilder tags: https://book-v1.book.kubebuilder.io/beyond_basics/generating_crd.html
// Phase represents the state of the schedule:
// initial is SCHEDULING, until message is sent
// until the deploy is executed it is PENDING,
// afterwards it is RUNNING,
// end it is DONE
Phase string `json:"phase,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DroneFederatedDeployment is the Schema for the dronefederateddeployments API
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
type DroneFederatedDeployment struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DroneFederatedDeploymentSpec `json:"spec,omitempty"`
Status DroneFederatedDeploymentStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// DroneFederatedDeploymentList contains a list of DroneFederatedDeployment
type DroneFederatedDeploymentList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []DroneFederatedDeployment `json:"items"`
}
func init() {
SchemeBuilder.Register(&DroneFederatedDeployment{}, &DroneFederatedDeploymentList{})
}
|
package errutil
// Append joins two errors into one; either or both can be nil.
func Append(err error, e error) (ret error) {
if err == nil {
ret = e
} else if e != nil {
ret = multiError{err, e}
} else {
ret = err
}
return ret
}
// multiError chains errors together.
// it can expand "recursively", allowing an chain of errors.
type multiError struct {
prev error
my error
}
// Error returns the combination of errors separated by a newline.
func (e multiError) Error() string {
return e.prev.Error() + "\n" + e.my.Error()
}
|
package pool
import (
"errors"
"math"
"sync"
"sync/atomic"
"time"
)
var POOLFULL error = errors.New("pool is full")
type genObjectPool struct {
config *PoolConfig
factory PoolObjectFactoryer
objNum int64
idlObject chan interface{}
lock sync.Mutex
}
func DefaultGenObjectPool(f PoolObjectFactoryer) (ObjectPooler, error) {
DEFAULTNUM := 5
param := &PoolConfig{MAX_IDLE: DEFAULTNUM, MIN_IDLE: 0, MAX_ACTIVE: DEFAULTNUM, MAX_WAIT: time.Duration(-1), IsVaildObj: false}
return NewGenObjectPool(f, param)
}
func NewGenObjectPool(f PoolObjectFactoryer, param *PoolConfig) (ObjectPooler, error) {
if param.MAX_IDLE > param.MAX_ACTIVE || param.MAX_ACTIVE <= 0 || param.MAX_ACTIVE > math.MaxInt32 {
return nil, errors.New("invalid config,check MAX_ACTIVE or MAX_IDLE set.")
}
if param.MIN_IDLE > param.MAX_IDLE {
return nil, errors.New("invalid config, must be set MIN_IDLE < MAX_IDLE.")
}
if f == nil {
return nil, errors.New("factory is nil")
}
idleObj := make(chan interface{}, param.MAX_IDLE)
return &genObjectPool{config: param, factory: f, objNum: 0, idlObject: idleObj}, nil
}
func (p *genObjectPool) InitPool() error {
if p.config.MIN_IDLE > 0 {
for i := 0; i < p.config.MIN_IDLE; i++ {
obj, err := p.factory.CreateObj()
if err != nil {
return err
}
if obj == nil {
return errors.New("factory create obj is nil")
}
atomic.AddInt64(&p.objNum, 1)
p.idlObject <- obj
}
}
return nil
}
func (p *genObjectPool) GetObject() (interface{}, error) {
waitTime := p.config.MAX_WAIT
startTime := time.Now()
if waitTime <= 0 {
waitTime = time.Duration(math.MaxInt64)
}
for {
if p.idlObject == nil {
return nil, errors.New("idlObject is nil,pool is Clear!")
}
select {
case poolObj := <-p.idlObject:
if p.config.IsVaildObj && !p.isValidObject(poolObj) {
continue
}
return poolObj, nil
default:
poolObj, err := p.createObject()
if poolObj == nil {
if err != nil && err == POOLFULL {
select {
case <-time.After(waitTime):
return nil, errors.New("Timeout waiting for idle object")
case poolObj = <-p.idlObject:
if p.config.IsVaildObj && !p.isValidObject(poolObj) {
dtime := time.Since(startTime)
waitTime = waitTime - dtime
continue
}
return poolObj, nil
}
} else {
return nil, err
}
} else {
return poolObj, nil
}
}
}
}
func (p *genObjectPool) ReturnObject(poolObj interface{}) error {
if poolObj == nil {
return errors.New("poolObj is nil")
}
p.lock.Lock()
defer p.lock.Unlock()
if p.idlObject == nil {
return p.DestroyObject(poolObj)
}
select {
case p.idlObject <- poolObj:
return nil
default:
return p.DestroyObject(poolObj)
}
}
func (p *genObjectPool) DestroyObject(poolObj interface{}) error {
if poolObj == nil {
return errors.New("poolObj is nil")
}
defer atomic.AddInt64(&p.objNum, -1)
err := p.factory.DestroyObj(poolObj)
if err != nil {
return err
}
return nil
}
func (p *genObjectPool) Clear() {
p.lock.Lock()
conns := p.idlObject
p.idlObject = nil
p.lock.Unlock()
if conns == nil {
return
}
close(conns)
for poolObj := range conns {
p.factory.DestroyObj(poolObj)
atomic.AddInt64(&p.objNum, -1)
}
}
func (p *genObjectPool) GetNumIdle() int {
return len(p.idlObject)
}
func (p *genObjectPool) GetNumActive() int {
return int(p.objNum) - len(p.idlObject)
}
func (p *genObjectPool) createObject() (interface{}, error) {
num := atomic.AddInt64(&p.objNum, 1)
if num > int64(p.config.MAX_ACTIVE) || num > int64(math.MaxInt32) {
atomic.AddInt64(&p.objNum, -1)
return nil, POOLFULL
}
poolObj, err := p.factory.CreateObj()
if err != nil {
atomic.AddInt64(&p.objNum, -1)
return nil, err
}
if poolObj == nil {
return nil, errors.New("factory create obj is nil")
}
return poolObj, nil
}
func (p *genObjectPool) isValidObject(poolObj interface{}) bool {
if poolObj == nil {
return false
}
err := p.factory.ValidateObj(poolObj)
if err != nil {
p.DestroyObject(poolObj)
return false
}
return true
}
|
package main
import (
"fmt"
)
func countAndSay(n int) string {
now := "1"
for i := 1; i < n; i = i + 1 {
next := ""
count := 1
value := int(now[0])
for _, x := range now[1:] {
if int(x) == int(value) {
count = count + 1
} else {
next = next + fmt.Sprintf("%d%c", count, value)
count = 1
value = int(x)
}
}
next = next + fmt.Sprintf("%d%c", count, value)
now = next
}
return now
}
func main() {
input := 10
fmt.Println(countAndSay(input))
}
|
package providers
import (
awsProvider "github.com/cyberark/secretless-broker/internal/providers/awssecrets"
conjurProvider "github.com/cyberark/secretless-broker/internal/providers/conjur"
envProvider "github.com/cyberark/secretless-broker/internal/providers/env"
fileProvider "github.com/cyberark/secretless-broker/internal/providers/file"
keychainProvider "github.com/cyberark/secretless-broker/internal/providers/keychain"
kubernetesProvider "github.com/cyberark/secretless-broker/internal/providers/kubernetessecrets"
literalProvider "github.com/cyberark/secretless-broker/internal/providers/literal"
vaultProvider "github.com/cyberark/secretless-broker/internal/providers/vault"
plugin_v1 "github.com/cyberark/secretless-broker/internal/plugin/v1"
)
// ProviderFactories contains the list of built-in provider factories
var ProviderFactories = map[string]func(plugin_v1.ProviderOptions) (plugin_v1.Provider, error){
"aws": awsProvider.ProviderFactory,
"conjur": conjurProvider.ProviderFactory,
"env": envProvider.ProviderFactory,
"file": fileProvider.ProviderFactory,
"keychain": keychainProvider.ProviderFactory,
"kubernetes": kubernetesProvider.ProviderFactory,
"literal": literalProvider.ProviderFactory,
"vault": vaultProvider.ProviderFactory,
}
|
package gitlabClient
import (
"github.com/xanzy/go-gitlab"
)
func (git *GitLab) GetListProject() ([]*gitlab.Project, error) {
FALSE := false
TRUE := true
opt := &gitlab.ListProjectsOptions{
Archived: &FALSE,
Membership: &TRUE,
ListOptions: gitlab.ListOptions{
PerPage: 100,
Page: 1,
},
}
for {
// Get the first page with projects.
projects, resp, err := git.Client.Projects.ListProjects(opt)
if err != nil {
return projects, err
}
// List all the projects we've found so far.
//for _, p := range projects {
// fmt.Printf("Found project: %s", p.Name)
//}
// Exit the loop when we've seen all pages.
if resp.CurrentPage >= resp.TotalPages {
return projects, err
}
// Update the page number to get the next page.
opt.Page = resp.NextPage
}
}
func (git *GitLab) CreateProjectLabel(projectId interface{}, label gitlab.Label) error {
// Create new label
l := &gitlab.CreateLabelOptions{
Name: &label.Name,
Color: &label.Color,
}
_, _, err := git.Client.Labels.CreateLabel(projectId, l)
if err != nil {
return err
}
return nil
}
|
package middleware
import (
"net/http"
"github.com/BalkanTech/goilerplate/session"
"log"
"github.com/BalkanTech/goilerplate/alerts"
)
var RequireLoginRedirectTo string = "/login"
func RequireLogin(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := session.GetUser(r)
if err != nil {
alerts.New("Warning", "alert-warning", "You need to login to access that page.")
http.Redirect(w, r, RequireLoginRedirectTo, http.StatusTemporaryRedirect)
return
}
h.ServeHTTP(w, r)
})
}
func RequireAdmin(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := session.GetUser(r)
if err != nil {
alerts.New("Warning", "alert-warning", "You need to login to access that page.")
http.Redirect(w, r, RequireLoginRedirectTo, http.StatusTemporaryRedirect)
return
}
if !user.IsAdmin {
log.Printf("%s: Non-admin access attempt of: %s (%s)", r.URL.Path, user.Username, user.ID)
alerts.New("Warning", "alert-warning", "Insufficient privileges.")
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
h.ServeHTTP(w, r)
})
}
|
package sqlite
import (
"database/sql"
//sqlite realization
_ "github.com/mattn/go-sqlite3"
"gitlab.com/alex-user-go/art/pkg/listing"
)
//Storage - sqlite db
type Storage struct{
db *sql.DB
}
//NewStorage - create and init new sqlite storage
func NewStorage()(*Storage, error){
db, err := sql.Open("sqlite3", "./art.db")
if err != nil {
return nil, err
}
s:= &Storage{db}
if err := s.createTables(); err !=nil{
return nil, err
}
return s, nil
}
func (s *Storage) createTables() error{
if err := s.createTableArtist(); err !=nil{
return err
}
if err := s.createTableArtwork(); err !=nil{
return err
}
if err := s.setConstraits(); err != nil{
return err
}
return nil
}
func (s *Storage) setConstraits() error{
_, err := s.db.Exec("PRAGMA foreign_keys = ON", nil)
if err != nil {
return err
}
return nil
}
func (s *Storage) createTableArtist() error{
sqlStmt := `create table if not exists
Artist (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE)`
_, err := s.db.Exec(sqlStmt)
if err != nil {
return err
}
return nil
}
func (s *Storage) createTableArtwork() error{
sqlStmt := `create table if not exists
Artwork (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, artistID INTEGER NOT NULL, FOREIGN KEY(artistID) REFERENCES Artist(id))`
_, err := s.db.Exec(sqlStmt)
if err != nil {
return err
}
return nil
}
//AddArtist add a new artist to the db
func (s *Storage) AddArtist(name string) (int64, error){
stmt, err := s.db.Prepare("insert into Artist(name) values(?)")
if err != nil {
return 0, err
}
defer stmt.Close()
res, err := stmt.Exec(name)
if err != nil {
return 0, err
}
lid, err := res.LastInsertId()
if err != nil {
return 0, err
}
return lid, nil
}
//AddArtwork add a new artwork to the db
func (s *Storage) AddArtwork(title string, artistID int64) (int64, error){
stmt, err := s.db.Prepare("insert into Artwork(title, artistID) values(?,?)")
if err != nil {
return 0, err
}
defer stmt.Close()
res, err := stmt.Exec(title, artistID)
if err != nil {
return 0, err
}
lid, err := res.LastInsertId()
if err != nil {
return 0, err
}
return lid, nil
}
//GetArtist - get artist by id
func (s *Storage) GetArtist(id int64) (*listing.Artist, error){
sqlStmt := `SELECT id, name FROM Artist WHERE id = ?`
var ar listing.Artist
err := s.db.QueryRow(sqlStmt, id).
Scan(&ar.ID, &ar.Name)
if err != nil{
return nil, err
}
return &ar, nil
}
//GetArtwork - get an artwork by id
func (s *Storage) GetArtwork(id int64) (*listing.Artwork, error){
sqlStmt := `SELECT id, title, artistID FROM Artwork WHERE id = ?`
var arwork listing.Artwork
err := s.db.QueryRow(sqlStmt, id).
Scan(&arwork.ID, &arwork.Title, &arwork.ArtistID)
if err != nil{
return nil, err
}
return &arwork, nil
}
//DeleteArtist - delete artist by id
func (s *Storage) DeleteArtist(id int64) (int64, error){
sqlStmt := `delete FROM Artist WHERE id = ?`
_, err := s.db.Exec(sqlStmt, id)
if err != nil{
return 0, err
}
return id, nil
}
//DeleteArtwork - delete artist by id
func (s *Storage) DeleteArtwork(id int64) (int64, error){
sqlStmt := `delete FROM Artwork WHERE id = ?`
_, err := s.db.Exec(sqlStmt, id)
if err != nil{
return 0, err
}
return id, nil
}
//GetArtistArtworks - get artworks by artistID
func (s *Storage) GetArtistArtworks(artistID int64) ([]*listing.Artwork, error){
sqlStmt := `SELECT id, title, artistID FROM Artwork WHERE artistID = ?`
rows, err := s.db.Query(sqlStmt, artistID)
if err != nil {
return nil, err
}
defer rows.Close()
var arworks []*listing.Artwork
for rows.Next() {
var arwork listing.Artwork
err = rows.Scan(&arwork.ID, &arwork.Title, &arwork.ArtistID)
if err != nil {
return nil, err
}
arworks = append(arworks, &arwork)
}
return arworks, nil
}
//GetArtistByNameFilter - get atrist name filter
func (s *Storage) GetArtistByNameFilter(filter string) ([]*listing.Artist, error){
sqlStmt := `SELECT id, name FROM Artist WHERE instr(name, ?)>0`
rows, err := s.db.Query(sqlStmt, filter)
if err != nil {
return nil, err
}
defer rows.Close()
var ars []*listing.Artist
for rows.Next() {
var ar listing.Artist
err = rows.Scan(&ar.ID, &ar.Name)
if err != nil {
return nil, err
}
ars = append(ars, &ar)
}
return ars, nil
}
//SetArtistName - set artist name by id
func (s *Storage) SetArtistName(id int64, name string) (int64, error){
stmt, err := s.db.Prepare("update Artist set name = ? where id = ?")
if err != nil {
return 0, err
}
defer stmt.Close()
_, err = stmt.Exec(name, id)
if err != nil {
return 0, err
}
return id, nil
}
//SetArtworkTitle - set artwork name by id
func (s *Storage) SetArtworkTitle(id int64, title string) (int64, error){
stmt, err := s.db.Prepare("update Artwork set title = ? where id = ?")
if err != nil {
return 0, err
}
defer stmt.Close()
_, err = stmt.Exec(title, id)
if err != nil {
return 0, err
}
return id, nil
}
//SetArtworkArtist - set artwork author
func (s *Storage) SetArtworkArtist(id int64, artistID int64) (int64, error){
stmt, err := s.db.Prepare("update Artwork set artistID = ? where id = ?")
if err != nil {
return 0, err
}
defer stmt.Close()
_, err = stmt.Exec(artistID, id)
if err != nil {
return 0, err
}
return id, nil
} |
//Slice append 加入
package main
import "fmt"
func main() {
x := []int{1, 2, 3, 4, 5}
y := []int{321, 456, 789}
fmt.Println(x)
x = append(x, 66, 77)
fmt.Println(x)
x = append(x, y...) // (目標, 要加入的內容 如果是其他陣列全部就 目標...)
fmt.Println(x)
x = append(x[:2], x[4:]...) //結束值不包括 注意要有...
fmt.Println(x)
}
|
package infrastructure
import (
"encoding/csv"
"errors"
"fmt"
"io"
"log"
"os"
"github.com/jesus-mata/academy-go-q12021/infrastructure/dto"
)
//go:generate mockgen -package mocks -destination $ROOTDIR/mocks/$GOPACKAGE/mock_$GOFILE . CsvSource
type CsvSource interface {
WriteLines(newsItems []dto.NewItem) error
GetAllLines() ([][]string, error)
NewReader() (*csv.Reader, error)
}
type csvSource struct {
file string
logger *log.Logger
}
func NewCsvSource(file string, logger *log.Logger) CsvSource {
return &csvSource{file, logger}
}
func (c *csvSource) GetAllLines() ([][]string, error) {
rows := make([][]string, 0, 5)
c.logger.Println("Reading all lines of CSV file", c.file)
csvfile, err := os.Open(c.file)
if err != nil {
return nil, err
}
reader := csv.NewReader(csvfile)
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err, ok := err.(*csv.ParseError); ok {
return nil, errors.New(fmt.Sprintf("Cannot parse CSV: %s", err.Error()))
}
if err != nil {
return nil, err
}
rows = append(rows, record)
}
return rows, nil
}
func (c *csvSource) NewReader() (*csv.Reader, error) {
c.logger.Println("Creating Reader of CSV file", c.file)
csvfile, err := os.Open(c.file)
if err != nil {
return nil, err
}
reader := csv.NewReader(csvfile)
return reader, nil
}
func (c *csvSource) WriteLines(newsItems []dto.NewItem) error {
f, err := os.OpenFile(c.file, os.O_TRUNC|os.O_WRONLY, os.ModeAppend)
defer f.Close()
if err != nil {
return err
}
w := csv.NewWriter(f)
defer w.Flush()
for _, newItem := range newsItems {
category := ""
if len(newItem.Category) > 0 {
category = newItem.Category[0]
}
record := []string{newItem.Id, newItem.Title, newItem.Description, newItem.Url, newItem.Author, newItem.Image, newItem.Language, category, newItem.Published}
if err := w.Write(record); err != nil {
return err
}
}
return nil
}
|
package protobuf
import (
"encoding/binary"
"io"
"sync"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
)
var bufPool = &sync.Pool{New: func() interface{} { return proto.NewBuffer(nil) }}
func nextBuffer(buf []byte) *proto.Buffer {
b := bufPool.Get().(*proto.Buffer)
b.SetBuf(buf)
return b
}
func putBuffer(b *proto.Buffer) {
if b == nil {
return
}
b.SetBuf(nil)
bufPool.Put(b)
}
type marshaler interface {
MarshalTo([]byte) (int, error)
Size() int
}
func grow(buf []byte, size int) []byte {
if cap(buf) < size {
tmp := make([]byte, size)
copy(tmp, buf)
buf = tmp
}
return buf[:size]
}
const maxInt = uint64(^uint(0) >> 1)
func Marshal(buf []byte, max int, m proto.Message) ([]byte, error) {
if t, ok := m.(marshaler); ok {
size := t.Size()
if max > 0 && size > max {
return buf, errors.New("protobuf: message too large")
}
buf = grow(buf, binary.MaxVarintLen64+size)
n := binary.PutUvarint(buf, uint64(size))
done, err := t.MarshalTo(buf[n : n+size])
n += done
if err != nil {
return buf[:n], errors.Wrap(err, "protobuf marshal")
}
if done != size {
return buf[:n], errors.New("protobuf: short marshal")
}
return buf[:n], nil
}
size := proto.Size(m)
if max > 0 && size > max {
return buf, errors.New("protobuf: message too large")
}
buf = grow(buf, binary.MaxVarintLen64+size)
n := binary.PutUvarint(buf, uint64(size))
b := nextBuffer(buf[n:n : n+size])
if err := b.Marshal(m); err != nil {
putBuffer(b)
return buf, errors.Wrap(err, "protobuf marshal")
}
putBuffer(b)
return buf[:n+size], nil
}
func Write(w *Writer, buf []byte, m proto.Message) ([]byte, error) {
var err error
if buf, err = Marshal(buf, w.max, m); err != nil {
return buf, err
}
var done int
for n := 0; done < len(buf); done += n {
if n, err = w.Write(buf[done:]); err != nil {
break
}
}
if err != nil {
return buf, err
}
if done < len(buf) {
return buf, errors.New("protobuf: short write")
}
return buf, nil
}
func Unmarshal(buf []byte, m proto.Message) error {
v, done := binary.Uvarint(buf)
switch {
case done == 0:
return errors.New("protobuf: uvarint buffer too small")
case done < 0:
return errors.New("protobuf: uvarint 64 bit overflow")
case v > maxInt:
return errors.New("protobuf: integer overflow")
}
off := done + int(v)
if len(buf) < off {
return errors.New("protobuf: buffer too small")
}
return unmarshal(buf[done:off], m)
}
func Read(r *Reader, buf []byte, m proto.Message) ([]byte, error) {
v, err := binary.ReadUvarint(r)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
return buf, err
}
return buf, errors.Wrap(err, "protobuf")
}
if v > maxInt {
return buf, errors.New("protobuf: integer overflow")
}
size := int(v)
if r.max > 0 && size > r.max {
return buf, errors.New("protobuf: message too large")
}
buf = grow(buf, size)
n, err := r.Read(buf)
if err != nil {
return buf[:n], err
}
if n < size {
return buf[:n], errors.New("protobuf: short read")
}
return buf, unmarshal(buf, m)
}
type unmarshaler interface {
Unmarshal([]byte) error
}
func unmarshal(data []byte, m proto.Message) (err error) {
if m == nil {
return nil
}
if t, ok := m.(unmarshaler); ok {
err = t.Unmarshal(data)
} else {
err = proto.Unmarshal(data, m)
}
if err != nil {
err = errors.Wrap(err, "protobuf unmarshal")
}
return err
}
|
package main
import "fmt"
func arrayToCounter(arr []string) map[string]int {
out := make(map[string]int)
for _, i := range arr {
out[i] += 1
}
return out
}
func main() {
in := []string{"cat", "cat", "dog", "cat", "tree"}
out := arrayToCounter(in)
fmt.Println(out)
}
|
// http://my.oschina.net/Jacker/blog/32837
// Two way encipherment ported from PHP.
package scrypt
import (
"bytes"
"crypto/md5"
"fmt"
"math/rand"
"time"
)
func keyEd(txt []byte, encryptKey string) []byte {
m := md5.New()
fmt.Fprint(m, encryptKey)
t := bytes.NewBufferString("")
keyBytes := m.Sum(nil)
for i, ctr := 0, 0; i < len(txt); i++ {
if ctr == len(keyBytes) {
ctr = 0
}
t.WriteByte(txt[i] ^ keyBytes[ctr])
ctr++
}
return t.Bytes()
}
func Encrypt(txt, key string) string {
rand.Seed(time.Nanosecond.Nanoseconds())
m := md5.New()
fmt.Fprint(m, rand.Int63())
encryptKey := m.Sum(nil)
txtBytes := []byte(txt)
t := bytes.NewBufferString("")
for i, ctr := 0, 0; i < len(txtBytes); i++ {
if ctr == len(encryptKey) {
ctr = 0
}
t.WriteByte(encryptKey[ctr])
t.WriteByte(txtBytes[i] ^ encryptKey[ctr])
ctr++
}
return string(keyEd(t.Bytes(), key))
}
func Decrypt(txt, key string) string {
b := keyEd([]byte(txt), key)
t := bytes.NewBufferString("")
for i := 0; i < len(b); i += 2 {
t.WriteByte(b[i] ^ b[i+1])
}
return t.String()
}
func main() {
s := "123456789fefefef3r33你好"
e := Encrypt(s, "salt")
d := Decrypt(e, "salt")
fmt.Println(d)
}
|
package metatest
import (
"fmt"
"github.com/ionous/sashimi/meta"
"github.com/ionous/sashimi/util/ident"
"github.com/ionous/sashimi/util/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"reflect"
"testing"
)
// ApiTest allows implementations of the meta interface to share tests.
// It requires at least one instance and one class. The source data should include "num/s", "text/s", "state", "object/s" of corresponding types.
// "State" should contain choices "yes" and "no"
func ApiTest(t *testing.T, mdl meta.Model, instId ident.Id) {
require.NotNil(t, mdl)
_, noExist := mdl.GetInstance(uuid.MakeUniqueId())
require.False(t, noExist)
// find inst by index
var inst meta.Instance
require.True(t, mdl.NumInstance() > 0, "need instances to test")
for i := 0; i < mdl.NumInstance(); i++ {
indirect := mdl.InstanceNum(i)
if instId == indirect.GetId() {
assert.Nil(t, inst, "instance id should only exist once")
inst = indirect
}
}
require.NotNil(t, inst, "should have found instance by index")
// find inst by id
if direct, ok := mdl.GetInstance(instId); assert.True(t, ok, "get instance by id") {
// NO LONG NEEDED
//require.True(t, direct.Equals(inst), "equality is necessary for the sake of game object adapter")
require.EqualValues(t, instId, direct.GetId(), "self id test")
}
//
require.True(t, inst.NumProperty() > 0, "need properties to test")
// value := inst.PropertyNum(0)
// if cls := inst.GetParentClass(); assert.NotNil(t, cls) {
// if plookup, ok := cls.GetProperty(value.GetId()); assert.True(t, ok, "find instance property in class") {
// require.True(t, plookup.GetId() == value.GetId())
// }
// }
type TestValue struct {
MethodMaker
original, value interface{}
}
methods := []TestValue{
{MethodMaker("Num"), float64(0), float64(32)},
{MethodMaker("Text"), "", "text"},
{MethodMaker("State"), ident.MakeId("no"), ident.MakeId("yes")},
{MethodMaker("Object"), ident.Empty(), inst.GetId()},
}
testValue := func(v meta.Value, test TestValue, eval func(TestValue, reflect.Value)) {
if value := reflect.ValueOf(v); assert.True(t, value.IsValid()) {
// test getting the vaule of the appropriate type succeeds
var prev interface{}
require.NotPanics(t, func() {
prev = test.GetFrom(value)
}, fmt.Sprintf("get default value: %s", test.String()))
require.EqualValues(t, test.original, prev,
fmt.Sprintf("original value from %s", test))
// custom testing for instances and classes
eval(test, value)
// test every other property type fails
for _, m := range methods {
if m != test {
// panic all other methods:
var v interface{}
require.Panics(t, func() {
v = m.GetFrom(value)
}, fmt.Sprintf("trying to get %s from %s; returned %v", m, test, v))
var err error
require.Panics(t, func() {
err = m.SetTo(value, m.value)
}, fmt.Sprintf("trying to set %s to %s", m, test))
assert.NoError(t, err)
}
}
}
}
testMethods := func(src meta.Prototype, eval func(TestValue, reflect.Value)) {
// test class values;
// test instance values
for _, test := range methods {
// get the property
if p, ok := src.FindProperty(test.String()); assert.True(t, ok, test.String()) {
// request the value from the property
var v meta.Value
require.NotPanics(t, func() { v = p.GetValue() })
require.Panics(t, func() { p.GetValues() })
testValue(v, test, eval)
}
}
}
// instances can get and set values
// value is reflect valueOf meta.Value
testInstanceValue := func(test TestValue, value reflect.Value) {
var err error
//err = test.SetTo(value, test.value)
require.NotPanics(t, func() {
err = test.SetTo(value, test.value)
}, fmt.Sprintf("instance set value panic: %s", test))
require.NoError(t, err, fmt.Sprintf("instance set value error: %s", test))
var next interface{}
require.NotPanics(t, func() {
next = test.GetFrom(value)
}, fmt.Sprintf("get changed value: %s", test))
require.EqualValues(t, next, test.value, fmt.Sprintf("%v:%T should be %v:%T", next, next, test.value, test.value))
}
testMethods(inst, testInstanceValue)
// classes disallow set values
// value is reflect valueOf meta.Value
testClassValue := func(test TestValue, value reflect.Value) {
var err error
require.Panics(t, func() {
err = test.SetTo(value, test.value)
}, fmt.Sprintf("class set value: %s", test))
require.NoError(t, err, fmt.Sprintf("class set value error: %s", test))
}
_ = testClassValue
parentCls, parentClsOk := mdl.GetClass(inst.GetParentClass())
require.True(t, parentClsOk)
testMethods(parentCls, testClassValue)
testArrays := func(src meta.Prototype, eval func(TestValue, meta.Values)) {
// test class values;
// test instance values
for _, test := range methods {
// no state arrays right now
if test.String() == "State" {
continue
}
// for every property type: num, text, state
name := test.String() + "s"
// get the property
if p, ok := src.FindProperty(name); assert.True(t, ok, fmt.Sprintf("trying to get property %s.%s", src, name)) {
// request the value from the property
var vs meta.Values
require.Panics(t, func() { p.GetValue() })
require.NotPanics(t, func() { vs = p.GetValues() })
var cnt int
require.NotPanics(t, func() {
cnt = vs.NumValue()
}, fmt.Sprintf("trying to num value %s.%s", src, name))
require.Equal(t, 0, cnt)
eval(test, vs)
// test alld other appends fails
value := reflect.ValueOf(vs)
for _, m := range methods {
if m != test {
// panic all other methods:
require.Panics(t, func() {
m.Append(value, test.value)
}, fmt.Sprintf("trying to append %s from %s", m, test))
}
}
}
}
}
testArrays(inst, func(test TestValue, vs meta.Values) {
value := reflect.ValueOf(vs)
// append
for i := 0; i < 3; i++ {
// instances can get and set values
require.NotPanics(t, func() {
test.Append(value, test.original)
}, fmt.Sprintf("instance set value: %s", test))
cnt := vs.NumValue()
require.EqualValues(t, i+1, cnt, fmt.Sprintf("cnt should grow after each append"))
next := vs.ValueNum(i)
testValue(next, test, testInstanceValue)
}
// clear
require.NotPanics(t, func() {
vs.ClearValues()
}, fmt.Sprintf("instance clear values: %s", test))
// back to zero
cnt := vs.NumValue()
require.EqualValues(t, 0, cnt, fmt.Sprintf("cnt(%d) should be zero", cnt))
test.Append(value, test.value)
})
testArrays(parentCls, func(test TestValue, vs meta.Values) {
// classes disallow set values
value := reflect.ValueOf(vs)
require.Panics(t, func() {
test.Append(value, test.value)
}, fmt.Sprintf("class set value: %s", test))
})
}
type MethodMaker string
func (m MethodMaker) String() string {
return string(m)
}
func (m MethodMaker) GetFrom(value reflect.Value) (ret interface{}) {
name := "Get" + m.String()
if n := value.MethodByName(name); !n.IsValid() {
panic(fmt.Sprintf("method didnt exist %s", name))
} else {
ret = n.Call([]reflect.Value{})[0].Interface()
}
return
}
func (m MethodMaker) SetTo(value reflect.Value, v interface{}) (err error) {
name := "Set" + m.String()
if n := value.MethodByName(name); !n.IsValid() {
panic(fmt.Sprintf("method didnt exist %s", name))
} else {
ret := n.Call([]reflect.Value{reflect.ValueOf(v)})
if v := ret[0]; !v.IsNil() {
err = v.Interface().(error)
}
}
return
}
func (m MethodMaker) Append(value reflect.Value, v interface{}) (err error) {
name := "Append" + m.String()
if n := value.MethodByName(name); !n.IsValid() {
panic(fmt.Sprintf("method didnt exist %s", name))
} else {
ret := n.Call([]reflect.Value{reflect.ValueOf(v)})
if v := ret[0]; !v.IsNil() {
err = v.Interface().(error)
}
}
return
}
|
package resources
import (
"fmt"
"net"
"github.com/RackHD/ipam/interfaces"
"github.com/RackHD/ipam/models"
"github.com/RackHD/ipam/resources/factory"
"gopkg.in/mgo.v2/bson"
)
// LeaseResourceType is the media type assigned to a Lease resource.
const LeaseResourceType string = "application/vnd.ipam.lease"
// LeaseResourceVersionV1 is the semantic version identifier for the Subnet resource.
const LeaseResourceVersionV1 string = "1.0.0"
func init() {
factory.Register(LeaseResourceType, LeaseCreator)
}
// LeaseCreator is a factory function for turning a version string into a Lease resource.
func LeaseCreator(version string) (interfaces.Resource, error) {
return &LeaseV1{}, nil
}
// LeaseV1 represents the v1.0.0 version of the Lease resource.
type LeaseV1 struct {
ID string `json:"id"`
Name string `json:"name"`
Tags []string `json:"tags"`
Metadata interface{} `json:"metadata"`
Subnet string `json:"subnet"` //SubnetID
Reservation string `json:"reservation"` //ReservationID
Address string `json:"address"`
}
// Type returns the resource type for use in rendering HTTP response headers.
func (s *LeaseV1) Type() string {
return LeaseResourceType
}
// Version returns the resource version for use in rendering HTTP response headers.
func (s *LeaseV1) Version() string {
return LeaseResourceVersionV1
}
// Marshal converts a models.Lease object into this version of the resource.
func (s *LeaseV1) Marshal(object interface{}) error {
if target, ok := object.(models.Lease); ok {
s.ID = target.ID.Hex()
s.Name = target.Name
s.Tags = target.Tags
s.Metadata = target.Metadata
s.Subnet = target.Subnet.Hex()
s.Reservation = target.Reservation.Hex()
s.Address = net.IP(target.Address.Data).String()
return nil
}
return fmt.Errorf("Invalid Object Type: %+v", object)
}
// Unmarshal converts the resource into a models.Lease object.
func (s *LeaseV1) Unmarshal() (interface{}, error) {
if s.ID == "" {
s.ID = bson.NewObjectId().Hex()
}
return models.Lease{
ID: bson.ObjectIdHex(s.ID),
Name: s.Name,
Tags: s.Tags,
Metadata: s.Metadata,
}, nil
}
|
// Copyright 2020 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package main
import (
"encoding/json"
"net/http"
"net/url"
"strings"
"github.com/gorilla/mux"
moovhttp "github.com/moov-io/base/http"
"github.com/moov-io/base/log"
"github.com/moov-io/fed"
"github.com/moov-io/fed/pkg/logos"
)
func addSearchRoutes(logger log.Logger, r *mux.Router, searcher *searcher, logoGrabber logos.Grabber) {
r.Methods("GET").Path("/fed/ach/search").HandlerFunc(searchFEDACH(logger, searcher, logoGrabber))
r.Methods("GET").Path("/fed/wire/search").HandlerFunc(searchFEDWIRE(logger, searcher, logoGrabber))
}
// fedSearchRequest contains the properties for fed ach search request
type fedSearchRequest struct {
Name string `json:"name"`
RoutingNumber string `json:"routingNumber"`
City string `json:"city"`
State string `json:"state"`
PostalCode string `json:"postalCode"`
}
// readFEDSearchRequest returns a fedachSearchRequest based on url parameters for fed ach search
func readFEDSearchRequest(u *url.URL) fedSearchRequest {
return fedSearchRequest{
Name: strings.ToUpper(strings.TrimSpace(u.Query().Get("name"))),
RoutingNumber: strings.ToUpper(strings.TrimSpace(u.Query().Get("routingNumber"))),
City: strings.ToUpper(strings.TrimSpace(u.Query().Get("city"))),
State: strings.ToUpper(strings.TrimSpace(u.Query().Get("state"))),
PostalCode: strings.ToUpper(strings.TrimSpace(u.Query().Get("postalCode"))),
}
}
// empty returns true if all of the properties in fedachSearchRequest are empty
func (req fedSearchRequest) empty() bool {
return req.Name == "" && req.RoutingNumber == "" && req.City == "" &&
req.State == "" && req.PostalCode == ""
}
// nameOnly returns true if only Name is not ""
func (req fedSearchRequest) nameOnly() bool {
return req.Name != "" && req.RoutingNumber == "" && req.City == "" &&
req.State == "" && req.PostalCode == ""
}
// routingNumberOnly returns true if only routingNumber is not ""
func (req fedSearchRequest) routingNumberOnly() bool {
return req.Name == "" && req.RoutingNumber != "" && req.City == "" &&
req.State == "" && req.PostalCode == ""
}
// cityOnly returns true if only city is not ""
func (req fedSearchRequest) cityOnly() bool {
return req.Name == "" && req.RoutingNumber == "" && req.City != "" &&
req.State == "" && req.PostalCode == ""
}
// stateOnly returns true if only state is not ""
func (req fedSearchRequest) stateOnly() bool {
return req.Name == "" && req.RoutingNumber == "" && req.City == "" &&
req.State != "" && req.PostalCode == ""
}
// postalCodeOnly returns true if only postal code is not ""
func (req fedSearchRequest) postalCodeOnly() bool {
return req.Name == "" && req.RoutingNumber == "" && req.City == "" &&
req.State == "" && req.PostalCode != ""
}
// searchFEDACH calls search functions based on the fed ach search request url parameters
func searchFEDACH(logger log.Logger, searcher *searcher, logoGrabber logos.Grabber) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if logger == nil {
logger = log.NewDefaultLogger()
}
w = wrapResponseWriter(logger, w, r)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
requestID, userID := moovhttp.GetRequestID(r), moovhttp.GetUserID(r)
logger = logger.With(log.Fields{
"requestID": log.String(requestID),
"userID": log.String(userID),
})
req := readFEDSearchRequest(r.URL)
if req.empty() {
logger.Error().Logf("searchFedACH", log.String(errNoSearchParams.Error()))
moovhttp.Problem(w, errNoSearchParams)
return
}
searchLimit := extractSearchLimit(r)
var achParticipants []*fed.ACHParticipant
var err error
switch {
case req.nameOnly():
logger.Logf("searching FED ACH Dictionary by name only %s", req.Name)
achParticipants = searcher.ACHFindNameOnly(searchLimit, req.Name)
case req.routingNumberOnly():
logger.Logf("searching FED ACH Dictionary by routing number only %s", req.RoutingNumber)
achParticipants, err = searcher.ACHFindRoutingNumberOnly(searchLimit, req.RoutingNumber)
if err != nil {
moovhttp.Problem(w, err)
return
}
case req.stateOnly():
logger.Logf("searching FED ACH Dictionary by state only %s", req.State)
achParticipants = searcher.ACHFindStateOnly(searchLimit, req.State)
case req.cityOnly():
logger.Logf("searching FED ACH Dictionary by city only %s", req.City)
achParticipants = searcher.ACHFindCityOnly(searchLimit, req.City)
case req.postalCodeOnly():
logger.Logf("searching FED ACH Dictionary by postal code only %s", req.PostalCode)
achParticipants = searcher.ACHFindPostalCodeOnly(searchLimit, req.PostalCode)
default:
logger.Logf("searching FED ACH Dictionary by parameters %v", req.RoutingNumber)
achParticipants, err = searcher.ACHFind(searchLimit, req)
if err != nil {
moovhttp.Problem(w, err)
return
}
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(&searchResponse{
ACHParticipants: populateACHLogos(achParticipants, logoGrabber),
})
}
}
func populateACHLogos(achParticipants []*fed.ACHParticipant, logoGrabber logos.Grabber) []*fed.ACHParticipant {
for i := range achParticipants {
logo, _ := logoGrabber.Lookup(achParticipants[i].CleanName)
if logo != nil {
achParticipants[i].Logo = logo
}
}
return achParticipants
}
// searchFEDWIRE calls search functions based on the fed wire search request url parameters
func searchFEDWIRE(logger log.Logger, searcher *searcher, logoGrabber logos.Grabber) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if logger == nil {
logger = log.NewDefaultLogger()
}
w = wrapResponseWriter(logger, w, r)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
requestID, userID := moovhttp.GetRequestID(r), moovhttp.GetUserID(r)
logger = logger.With(log.Fields{
"requestID": log.String(requestID),
"userID": log.String(userID),
})
req := readFEDSearchRequest(r.URL)
if req.empty() {
logger.Error().Logf("searchFEDWIRE: %v", errNoSearchParams)
moovhttp.Problem(w, errNoSearchParams)
return
}
searchLimit := extractSearchLimit(r)
var wireParticipants []*fed.WIREParticipant
var err error
switch {
case req.nameOnly():
logger.Logf("searchFEDWIRE: searching FED WIRE Dictionary by name only %s", req.Name)
wireParticipants = searcher.WIREFindNameOnly(searchLimit, req.Name)
case req.routingNumberOnly():
logger.Logf("searchFEDWIRE: searching FED WIRE Dictionary by routing number only %s", req.RoutingNumber)
wireParticipants, err = searcher.WIREFindRoutingNumberOnly(searchLimit, req.RoutingNumber)
if err != nil {
moovhttp.Problem(w, err)
return
}
case req.stateOnly():
logger.Logf("searchFEDWIRE: searching FED WIRE Dictionary by state only %s", req.State)
wireParticipants = searcher.WIREFindStateOnly(searchLimit, req.State)
case req.cityOnly():
logger.Logf("searchFEDWIRE: searching FED WIRE Dictionary by city only %s", req.City)
wireParticipants = searcher.WIREFindCityOnly(searchLimit, req.City)
default:
logger.Logf("searchFEDWIRE: searching FED WIRE Dictionary by parameters %v", req.RoutingNumber)
wireParticipants, err = searcher.WIREFind(searchLimit, req)
if err != nil {
moovhttp.Problem(w, err)
}
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(&searchResponse{
WIREParticipants: populateWIRELogos(wireParticipants, logoGrabber),
})
}
}
func populateWIRELogos(wireParticipants []*fed.WIREParticipant, logoGrabber logos.Grabber) []*fed.WIREParticipant {
for i := range wireParticipants {
logo, _ := logoGrabber.Lookup(wireParticipants[i].CleanName)
if logo != nil {
wireParticipants[i].Logo = logo
}
}
return wireParticipants
}
|
package delayqueue
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
"github.com/mlkr/delay-queue/config"
)
var (
// 每个定时器对应一个bucket
timers []*time.Ticker
// bucket名称chan
bucketNameChan <-chan string
)
// Init 初始化延时队列
func Init() {
RedisPool = initRedisPool()
initTimers()
bucketNameChan = generateBucketName()
initListeners()
}
// Push 添加一个Job到队列中
func Push(job Job) error {
if job.Id == "" || job.Topic == "" || job.Delay < 0 || job.TTR <= 0 {
return errors.New("invalid job")
}
err := putJob(job.Id, job)
if err != nil {
log.Printf("添加job到job pool失败#job-%+v#%s", job, err.Error())
return err
}
err = pushToBucket(<-bucketNameChan, job.Delay, job.Id)
if err != nil {
log.Printf("添加job到bucket失败#job-%+v#%s", job, err.Error())
return err
}
return nil
}
// Pop 轮询获取Job
func Pop(topics []string) (*Job, error) {
jobId, err := blockPopFromReadyQueue(topics, config.Setting.QueueBlockTimeout)
if err != nil {
return nil, err
}
// 队列为空
if jobId == "" {
return nil, nil
}
// 获取job元信息
job, err := getJob(jobId)
if err != nil {
return job, err
}
// 消息不存在, 可能已被删除
if job == nil {
return nil, nil
}
timestamp := time.Now().Unix() + job.TTR
err = pushToBucket(<-bucketNameChan, timestamp, job.Id)
return job, err
}
// Remove 删除Job
func Remove(jobId string) error {
return removeJob(jobId)
}
// Get 查询Job
func Get(jobId string) (*Job, error) {
job, err := getJob(jobId)
if err != nil {
return job, err
}
// 消息不存在, 可能已被删除
if job == nil {
return nil, nil
}
return job, err
}
// 轮询获取bucket名称, 使job分布到不同bucket中, 提高扫描速度
func generateBucketName() <-chan string {
c := make(chan string)
go func() {
i := 1
for {
c <- fmt.Sprintf(config.Setting.BucketName, i)
if i >= config.Setting.BucketSize {
i = 1
} else {
i++
}
}
}()
return c
}
// 初始化定时器
func initTimers() {
timers = make([]*time.Ticker, config.Setting.BucketSize)
var bucketName string
for i := 0; i < config.Setting.BucketSize; i++ {
timers[i] = time.NewTicker(1 * time.Second)
bucketName = fmt.Sprintf(config.Setting.BucketName, i+1)
go waitTicker(timers[i], bucketName)
}
}
func waitTicker(timer *time.Ticker, bucketName string) {
for {
select {
case t := <-timer.C:
tickHandler(t, bucketName)
}
}
}
// 扫描bucket, 取出延迟时间小于当前时间的Job
func tickHandler(t time.Time, bucketName string) {
for {
bucketItem, err := getFromBucket(bucketName)
if err != nil {
log.Printf("扫描bucket错误#bucket-%s#%s", bucketName, err.Error())
return
}
// 集合为空
if bucketItem == nil {
return
}
// 延迟时间未到
if bucketItem.timestamp > t.Unix() {
return
}
// 延迟时间小于等于当前时间, 取出Job元信息并放入ready queue
job, err := getJob(bucketItem.jobId)
if err != nil {
log.Printf("获取Job元信息失败#bucket-%s#%s", bucketName, err.Error())
continue
}
// job元信息不存在, 从bucket中删除
if job == nil {
removeFromBucket(bucketName, bucketItem.jobId)
continue
}
// 再次确认元信息中delay是否小于等于当前时间
if job.Delay > t.Unix() {
// 从bucket中删除旧的jobId
removeFromBucket(bucketName, bucketItem.jobId)
// 重新计算delay时间并放入bucket中
pushToBucket(<-bucketNameChan, job.Delay, bucketItem.jobId)
continue
}
err = pushToReadyQueue(job.Topic, bucketItem.jobId)
if err != nil {
log.Printf("JobId放入ready queue失败#bucket-%s#job-%+v#%s",
bucketName, job, err.Error())
continue
}
// 从bucket中删除
removeFromBucket(bucketName, bucketItem.jobId)
}
}
func initListeners() {
timers = make([]*time.Ticker, config.Setting.BucketSize)
for i := 0; i < config.Setting.BucketSize; i++ {
timers[i] = time.NewTicker(1 * time.Second)
go listen(timers[i])
}
}
func listen(timer *time.Ticker) {
for {
select {
case <-timer.C:
job, err := Pop([]string{"order"})
if err != nil {
log.Printf("获取job失败#%s", err.Error())
continue
}
if job == nil {
continue
}
// 访问回调
if httpPost(job.Callback, job) {
err = Remove(job.Id)
if err != nil {
log.Printf("回调成功,删除job失败#%s", err.Error())
}
}
}
}
}
func httpPost(url string, job *Job) bool {
log.Printf("访问回调#%s#%v", url, job)
resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(fmt.Sprintf("id=%s&body=%s", job.Id, job.Body)))
if err != nil {
log.Printf("访问回调地址失败#%s", err.Error())
return false
}
defer resp.Body.Close()
type Ans struct {
Code int `json:"code"`
Data string `json:"data"`
Message string `json:"message"`
Title string `json:"title"`
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("回调, 读取body错误#%s", err.Error())
return false
}
ans := &Ans{}
err = json.Unmarshal(body, ans)
if err != nil {
log.Printf("回调, 解析json失败#%s#%s", err.Error(), string(body))
return false
}
if ans.Code < 0 {
log.Printf("回调没有执行成功#%s", ans.Message)
return false
}
return true
}
|
package main
// import (
// "log"
// "strconv"
// "time"
// "net/http"
// "database/sql"
// )
//
// func rootHandler(res http.ResponseWriter, req *http.Request) {
// var (
// sensor string
// value int
// created_at time.Time
// )
// // DB öffnen...
// db, err := sql.Open("postgres", connectionString)
// panicOnError(err)
// // ...DB am Ende der Funktion wieder schließen.
// defer db.Close()
//
// // Letzten Eintrag abfragen.
// rows, err := db.Query(`
// select m1.*
// from measurements m1
// left outer join measurements m2
// on (m1.sensor = m2.sensor and m1.created_at < m2.created_at)
// where m2.sensor is null`)
// panicOnError(err)
//
// var ms []RootViewModel
//
// // Eintrag lesen.
// for rows.Next() {
// err = rows.Scan(&sensor, &value, &created_at)
// panicOnError(err)
// ms = append(ms, RootViewModel{
// Sensor:sensor,
// Value: float32(value) / 100.0,
// CreatedAt:created_at.Format("am Mo 2. Jan 2006 um 15:04:05") })
// }
//
// renderTemplate(res, "index", ms)
// }
|
package service
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"github.com/Emoto13/photo-viewer-rest/follow-service/src/auth"
"github.com/Emoto13/photo-viewer-rest/follow-service/src/feed"
"github.com/Emoto13/photo-viewer-rest/follow-service/src/follow"
"github.com/Emoto13/photo-viewer-rest/follow-service/src/follow/models"
)
type followService struct {
authClient auth.AuthClient
followStore follow.FollowStore
feedClient feed.FeedClient
mu sync.RWMutex
}
func NewFollowService(authClient auth.AuthClient, feedClient feed.FeedClient, followStore follow.FollowStore) *followService {
return &followService{
authClient: authClient,
feedClient: feedClient,
followStore: followStore,
mu: sync.RWMutex{},
}
}
func (fs *followService) CreateUser(w http.ResponseWriter, r *http.Request) {
body, err := getRequestBody(r.Body)
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
err = fs.followStore.CreateUser(body["username"])
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
respondWithJSON(w, http.StatusOK, map[string]string{"Message": fmt.Sprintf("User %s created successfully", body["username"])})
return
}
func (fs *followService) Follow(w http.ResponseWriter, r *http.Request) {
username, err := fs.authClient.Authenticate(r.Header.Get("Authorization"))
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
body, err := getRequestBody(r.Body)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
err = fs.followStore.SaveFollow(models.NewFollow(username, body["follow"]))
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
err = fs.feedClient.UpdateFeed(r.Header.Get("Authorization"))
if err != nil {
fmt.Println("couldnt update feed", err.Error())
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
fmt.Println(username, "followed", body["follow"])
respondWithJSON(w, http.StatusOK, map[string]string{"Message": fmt.Sprintf("You are now following %s", body["follow"])})
return
}
func (fs *followService) Unfollow(w http.ResponseWriter, r *http.Request) {
username, err := fs.authClient.Authenticate(r.Header.Get("Authorization"))
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
body, err := getRequestBody(r.Body)
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
err = fs.followStore.RemoveFollow(models.NewFollow(username, body["unfollow"]))
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
err = fs.feedClient.UpdateFeed(r.Header.Get("Authorization"))
if err != nil {
fmt.Println("couldnt update feed", err.Error())
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
fmt.Println(username, "unfollowed", body["unfollow"])
respondWithJSON(w, http.StatusOK, map[string]string{"Message": fmt.Sprintf("%s is unfollowed", body["unfollow"])})
return
}
func (fs *followService) GetFollowers(w http.ResponseWriter, r *http.Request) {
username, err := fs.authClient.Authenticate(r.Header.Get("Authorization"))
if err != nil {
fmt.Println("Wrong credentials")
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
followers, err := fs.followStore.GetFollowers(username)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
response, _ := json.Marshal(map[string][]*models.Follower{"followers": followers})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(response)
return
}
func (fs *followService) GetFollowing(w http.ResponseWriter, r *http.Request) {
fmt.Println("Authorization: ", r.Header.Get("Authorization"))
username, err := fs.authClient.Authenticate(r.Header.Get("Authorization"))
if err != nil {
fmt.Println("Couldn't auth")
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
following, err := fs.followStore.GetFollowing(username)
if err != nil {
fmt.Println(err)
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
response, _ := json.Marshal(map[string][]*models.Following{"following": following})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(response)
return
}
func (fs *followService) GetSuggestions(w http.ResponseWriter, r *http.Request) {
username, err := fs.authClient.Authenticate(r.Header.Get("Authorization"))
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
suggestions, err := fs.followStore.GetSuggestions(username)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
response, _ := json.Marshal(map[string][]*models.Suggestion{"suggestions": suggestions})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(response)
return
}
func (fs *followService) HealthCheck(w http.ResponseWriter, r *http.Request) {
respondWithJSON(w, http.StatusOK, map[string]string{"Status": "OK"})
return
}
|
package app
import (
"sort"
"strings"
)
func transformUserSet(userSet map[string]struct{}, userIDs []string, action string) map[string]struct{} {
switch action {
case "replace":
userSet = make(map[string]struct{})
fallthrough
case "append":
for _, userID := range userIDs {
userSet[userID] = struct{}{}
}
case "remove":
for _, userID := range userIDs {
delete(userSet, userID)
}
}
return userSet
}
func parseUserSet(userList string) map[string]struct{} {
fields := strings.Split(userList, ",")
userSet := make(map[string]struct{})
for _, field := range fields {
userSet[strings.TrimSpace(field)] = struct{}{}
}
return userSet
}
func marshalUserSet(userSet map[string]struct{}) string {
userIDs := make([]string, 0, len(userSet))
for userID := range userSet {
userIDs = append(userIDs, userID)
}
sort.Strings(userIDs)
return strings.Join(userIDs, ",")
}
|
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/ysmood/kit"
)
var flagPort = flag.Int("port", 8544, "port")
// This example demonstrates how to upload a file on a form.
func main() {
flag.Parse()
// get wd
wd, err := os.Getwd()
kit.E(err)
filepath := wd + "/main.go"
// get some info about the file
fi, err := os.Stat(filepath)
kit.E(err)
// start upload server
result := make(chan int, 1)
go kit.E(uploadServer(fmt.Sprintf(":%d", *flagPort), result))
url := launcher.New().Headless(false).Launch()
browser := rod.New().ControlURL(url).Connect()
page := browser.Page(fmt.Sprintf("http://localhost:%d", *flagPort))
page.Element(`input[name="upload"]`).SetFiles("./main.go")
page.Element(`input[name="submit"]`).Click()
page.Element("#result").Text()
log.Printf("original size: %d, upload size: %d", fi.Size(), <-result)
}
func uploadServer(addr string, result chan int) error {
// create http server and result channel
mux := http.NewServeMux()
mux.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {
kit.E(fmt.Fprintf(res, uploadHTML))
})
mux.HandleFunc("/upload", func(res http.ResponseWriter, req *http.Request) {
f, _, err := req.FormFile("upload")
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
defer kit.E(f.Close())
buf, err := ioutil.ReadAll(f)
if err != nil {
http.Error(res, err.Error(), http.StatusBadRequest)
return
}
kit.E(fmt.Fprintf(res, resultHTML, len(buf)))
result <- len(buf)
})
return http.ListenAndServe(addr, mux)
}
const (
uploadHTML = `<!doctype html>
<html>
<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input name="upload" type="file"/>
<input name="submit" type="submit"/>
</form>
</body>
</html>`
resultHTML = `<!doctype html>
<html>
<body>
<div id="result">%d</div>
</body>
</html>`
)
|
package JsStatistics
import (
"JsGo/JsLogger"
"JsGo/JsStore/JsRedis"
)
type Statistics struct {
Type string // 类型 0:产品 1:内容
VisitNum int // 访问量
PraiseNum int // 点赞数量
AttentionNums int // 关注数量
CompositeScore float64 // 综合评分(所有评分的平均值)
CommentNum int // 评论的人数
SalesVolume int //销量
PraiseUser []string // 点赞人前十个小头像
AttentiUser []string // 关注人前十个小头像
}
func (this *Statistics) Init() {
this.Type = ""
this.VisitNum = 0
this.PraiseNum = 0
this.AttentionNums = 0
this.CompositeScore = 5
this.CommentNum = 0
this.SalesVolume = 0
this.PraiseUser = []string{}
this.AttentiUser = []string{}
}
//新增访问量
func (this *Statistics) NewVisit() {
this.VisitNum++
}
//新增加点赞量
func (this *Statistics) NewPraise(uid string) {
ok := false
for _, v := range this.PraiseUser {
if v == uid {
ok = true
break
}
}
if !ok {
this.PraiseUser = append(this.PraiseUser, uid)
this.PraiseNum++
}
}
//新增关注
func (this *Statistics) NewAttention(uid string) {
ok := false
for _, v := range this.AttentiUser {
if v == uid {
ok = true
break
}
}
if !ok {
this.AttentiUser = append(this.AttentiUser, uid)
this.AttentionNums++
}
}
//新增评论
func (this *Statistics) NewComment(score float64) {
if score < 0 {
score = 0
}
d := this.CompositeScore * (float64)(this.CommentNum*1.0)
this.CommentNum++
this.CompositeScore = (d + score) / (float64)(this.CommentNum*1.0)
}
//取消关注
func (this *Statistics) RemoveAttention(uid string) {
index := -1
for i, v := range this.AttentiUser {
if v == uid {
index = i
break
}
}
if index != -1 {
this.AttentiUser = append(this.AttentiUser[:index], this.AttentiUser[index+1:]...)
this.AttentionNums--
}
}
//取消点赞
func (this *Statistics) RemovePraise(uid string) {
index := -1
for i, v := range this.PraiseUser {
if v == uid {
index = i
break
}
}
if index != -1 {
this.PraiseUser = append(this.PraiseUser[:index], this.PraiseUser[index+1:]...)
this.PraiseNum--
}
}
//新增访问量
func NewVisit(db, ID, Type string) (*Statistics, error) {
data := &Statistics{}
if err := JsRedis.Redis_hget(db, ID, data); err != nil {
JsLogger.Info(err.Error())
data.Init()
}
data.Type = Type
data.NewVisit()
return data, JsRedis.Redis_hset(db, ID, data)
}
//新增加点赞量
func NewPraise(db, ID, Type, uid string) (*Statistics, error) {
data := &Statistics{}
if err := JsRedis.Redis_hget(db, ID, data); err != nil {
JsLogger.Info(err.Error())
data.Init()
}
data.Type = Type
data.NewPraise(uid)
return data, JsRedis.Redis_hset(db, ID, data)
}
//新增关注
func NewAttention(db, ID, Type, uid string) (*Statistics, error) {
data := &Statistics{}
if err := JsRedis.Redis_hget(db, ID, data); err != nil {
JsLogger.Info(err.Error())
data.Init()
}
data.Type = Type
data.NewAttention(uid)
return data, JsRedis.Redis_hset(db, ID, data)
}
//新增评论
func NewComment(db, ID, Type string, score float64) (*Statistics, error) {
data := &Statistics{}
if err := JsRedis.Redis_hget(db, ID, data); err != nil {
JsLogger.Info(err.Error())
data.Init()
}
data.Type = Type
data.NewComment(score)
return data, JsRedis.Redis_hset(db, ID, data)
}
//取消关注
func RemoveAttention(db, ID, Type, uid string) (*Statistics, error) {
data := &Statistics{}
if err := JsRedis.Redis_hget(db, ID, data); err != nil {
JsLogger.Info(err.Error())
data.Init()
}
data.Type = Type
data.RemoveAttention(uid)
return data, JsRedis.Redis_hset(db, ID, data)
}
//取消点赞
func RemovePraise(db, ID, Type, uid string) (*Statistics, error) {
data := &Statistics{}
if err := JsRedis.Redis_hget(db, ID, data); err != nil {
JsLogger.Info(err.Error())
data.Init()
}
data.Type = Type
data.RemovePraise(uid)
return data, JsRedis.Redis_hset(db, ID, data)
}
//增加销售量SalesVolume
func NewSales(db, ID, Type string, num int) (*Statistics, error) {
data := &Statistics{}
if err := JsRedis.Redis_hget(db, ID, data); err != nil {
JsLogger.Info(err.Error())
data.Init()
}
data.Type = Type
data.SalesVolume += num
return data, JsRedis.Redis_hset(db, ID, data)
}
|
package m2go
const (
stockItemsRelative = "stockItems"
)
|
package model
type ProductGroup struct {
HotelId int64 `json:"hotel,omitempty"`
ProductGroupId int64 `json:"id,omitempty"`
Description string `json:"descricao,omitempty"`
DisplayProduct string `json:"exibir,omitempty"`
Code int64 `json:"codigo,omitempty"`
Printer string `json:"impressora1,omitempty"`
Printer2 string `json:"impressora2,omitempty"`
}
|
package odoo
import (
"fmt"
)
// AccountTaxTemplate represents account.tax.template model.
type AccountTaxTemplate struct {
LastUpdate *Time `xmlrpc:"__last_update,omptempty"`
AccountId *Many2One `xmlrpc:"account_id,omptempty"`
Active *Bool `xmlrpc:"active,omptempty"`
Amount *Float `xmlrpc:"amount,omptempty"`
AmountType *Selection `xmlrpc:"amount_type,omptempty"`
Analytic *Bool `xmlrpc:"analytic,omptempty"`
CashBasisAccount *Many2One `xmlrpc:"cash_basis_account,omptempty"`
ChartTemplateId *Many2One `xmlrpc:"chart_template_id,omptempty"`
ChildrenTaxIds *Relation `xmlrpc:"children_tax_ids,omptempty"`
CompanyId *Many2One `xmlrpc:"company_id,omptempty"`
CreateDate *Time `xmlrpc:"create_date,omptempty"`
CreateUid *Many2One `xmlrpc:"create_uid,omptempty"`
Description *String `xmlrpc:"description,omptempty"`
DisplayName *String `xmlrpc:"display_name,omptempty"`
Id *Int `xmlrpc:"id,omptempty"`
IncludeBaseAmount *Bool `xmlrpc:"include_base_amount,omptempty"`
Name *String `xmlrpc:"name,omptempty"`
PriceInclude *Bool `xmlrpc:"price_include,omptempty"`
RefundAccountId *Many2One `xmlrpc:"refund_account_id,omptempty"`
Sequence *Int `xmlrpc:"sequence,omptempty"`
TagIds *Relation `xmlrpc:"tag_ids,omptempty"`
TaxAdjustment *Bool `xmlrpc:"tax_adjustment,omptempty"`
TaxExigibility *Selection `xmlrpc:"tax_exigibility,omptempty"`
TaxGroupId *Many2One `xmlrpc:"tax_group_id,omptempty"`
TypeTaxUse *Selection `xmlrpc:"type_tax_use,omptempty"`
WriteDate *Time `xmlrpc:"write_date,omptempty"`
WriteUid *Many2One `xmlrpc:"write_uid,omptempty"`
}
// AccountTaxTemplates represents array of account.tax.template model.
type AccountTaxTemplates []AccountTaxTemplate
// AccountTaxTemplateModel is the odoo model name.
const AccountTaxTemplateModel = "account.tax.template"
// Many2One convert AccountTaxTemplate to *Many2One.
func (att *AccountTaxTemplate) Many2One() *Many2One {
return NewMany2One(att.Id.Get(), "")
}
// CreateAccountTaxTemplate creates a new account.tax.template model and returns its id.
func (c *Client) CreateAccountTaxTemplate(att *AccountTaxTemplate) (int64, error) {
ids, err := c.CreateAccountTaxTemplates([]*AccountTaxTemplate{att})
if err != nil {
return -1, err
}
if len(ids) == 0 {
return -1, nil
}
return ids[0], nil
}
// CreateAccountTaxTemplate creates a new account.tax.template model and returns its id.
func (c *Client) CreateAccountTaxTemplates(atts []*AccountTaxTemplate) ([]int64, error) {
var vv []interface{}
for _, v := range atts {
vv = append(vv, v)
}
return c.Create(AccountTaxTemplateModel, vv)
}
// UpdateAccountTaxTemplate updates an existing account.tax.template record.
func (c *Client) UpdateAccountTaxTemplate(att *AccountTaxTemplate) error {
return c.UpdateAccountTaxTemplates([]int64{att.Id.Get()}, att)
}
// UpdateAccountTaxTemplates updates existing account.tax.template records.
// All records (represented by ids) will be updated by att values.
func (c *Client) UpdateAccountTaxTemplates(ids []int64, att *AccountTaxTemplate) error {
return c.Update(AccountTaxTemplateModel, ids, att)
}
// DeleteAccountTaxTemplate deletes an existing account.tax.template record.
func (c *Client) DeleteAccountTaxTemplate(id int64) error {
return c.DeleteAccountTaxTemplates([]int64{id})
}
// DeleteAccountTaxTemplates deletes existing account.tax.template records.
func (c *Client) DeleteAccountTaxTemplates(ids []int64) error {
return c.Delete(AccountTaxTemplateModel, ids)
}
// GetAccountTaxTemplate gets account.tax.template existing record.
func (c *Client) GetAccountTaxTemplate(id int64) (*AccountTaxTemplate, error) {
atts, err := c.GetAccountTaxTemplates([]int64{id})
if err != nil {
return nil, err
}
if atts != nil && len(*atts) > 0 {
return &((*atts)[0]), nil
}
return nil, fmt.Errorf("id %v of account.tax.template not found", id)
}
// GetAccountTaxTemplates gets account.tax.template existing records.
func (c *Client) GetAccountTaxTemplates(ids []int64) (*AccountTaxTemplates, error) {
atts := &AccountTaxTemplates{}
if err := c.Read(AccountTaxTemplateModel, ids, nil, atts); err != nil {
return nil, err
}
return atts, nil
}
// FindAccountTaxTemplate finds account.tax.template record by querying it with criteria.
func (c *Client) FindAccountTaxTemplate(criteria *Criteria) (*AccountTaxTemplate, error) {
atts := &AccountTaxTemplates{}
if err := c.SearchRead(AccountTaxTemplateModel, criteria, NewOptions().Limit(1), atts); err != nil {
return nil, err
}
if atts != nil && len(*atts) > 0 {
return &((*atts)[0]), nil
}
return nil, fmt.Errorf("account.tax.template was not found with criteria %v", criteria)
}
// FindAccountTaxTemplates finds account.tax.template records by querying it
// and filtering it with criteria and options.
func (c *Client) FindAccountTaxTemplates(criteria *Criteria, options *Options) (*AccountTaxTemplates, error) {
atts := &AccountTaxTemplates{}
if err := c.SearchRead(AccountTaxTemplateModel, criteria, options, atts); err != nil {
return nil, err
}
return atts, nil
}
// FindAccountTaxTemplateIds finds records ids by querying it
// and filtering it with criteria and options.
func (c *Client) FindAccountTaxTemplateIds(criteria *Criteria, options *Options) ([]int64, error) {
ids, err := c.Search(AccountTaxTemplateModel, criteria, options)
if err != nil {
return []int64{}, err
}
return ids, nil
}
// FindAccountTaxTemplateId finds record id by querying it with criteria.
func (c *Client) FindAccountTaxTemplateId(criteria *Criteria, options *Options) (int64, error) {
ids, err := c.Search(AccountTaxTemplateModel, criteria, options)
if err != nil {
return -1, err
}
if len(ids) > 0 {
return ids[0], nil
}
return -1, fmt.Errorf("account.tax.template was not found with criteria %v and options %v", criteria, options)
}
|
package main
import (
"bytes"
"image"
"image/draw"
_ "image/jpeg"
"image/png"
"log"
"math"
"net/http"
"strings"
"github.com/golang/freetype/truetype"
"github.com/nfnt/resize"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
)
type Handler struct {
// these are read only, safe for access from multiple goroutines
images map[string]image.Image
font *truetype.Font
}
func NewHandler(images map[string]image.Image, font *truetype.Font) *Handler {
return &Handler{images, font}
}
const imgW, imgH = 640, 480
func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
bgName := strings.Split(req.URL.Path, "/")[0]
q := req.URL.Query()
top := q.Get("top")
bottom := q.Get("bottom")
if top == "" && bottom == "" {
top = "Can't think of a demo?"
bottom = "Why not Zoidberg?"
}
bgImg, ok := h.images[bgName]
if !ok {
rw.WriteHeader(http.StatusBadRequest)
return
}
log.Printf("%s: \"%s\", \"%s\"", req.URL.Path, top, bottom)
// resize to match our output dimensions
bgImg = resize.Resize(imgW, imgH, bgImg, resize.Lanczos3)
fg := image.Black
rgba := image.NewRGBA(image.Rect(0, 0, imgW, imgH))
draw.Draw(rgba, rgba.Bounds(), bgImg, image.ZP, draw.Src)
d := &font.Drawer{
Dst: rgba,
Src: fg,
Face: truetype.NewFace(h.font, &truetype.Options{
Size: *size,
DPI: *dpi,
Hinting: font.HintingFull,
}),
}
y := 10 + int(math.Ceil(*size**dpi/72))
//dy := int(math.Ceil(*size * *spacing * *dpi / 72))
d.Dot = fixed.Point26_6{
X: (fixed.I(imgW) - d.MeasureString(top)) / 2,
Y: fixed.I(y),
}
d.DrawString(top)
//y += dy
y = imgH - 15
d.Dot = fixed.Point26_6{
X: (fixed.I(imgW) - d.MeasureString(bottom)) / 2,
Y: fixed.I(y),
}
d.DrawString(bottom)
b := bytes.Buffer{}
err := png.Encode(&b, rgba)
if err != nil {
log.Printf("png.Encode: %s", err)
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "image/png")
rw.Write(b.Bytes())
}
|
// Copyright (c) 2018 The MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package lottery
import (
"errors"
"math/big"
"github.com/MatrixAINetwork/go-matrix/baseinterface"
"github.com/MatrixAINetwork/go-matrix/common/mt19937"
"github.com/MatrixAINetwork/go-matrix/params"
"github.com/MatrixAINetwork/go-matrix/core/matrixstate"
"github.com/MatrixAINetwork/go-matrix/mc"
"github.com/MatrixAINetwork/go-matrix/common"
"github.com/MatrixAINetwork/go-matrix/core/types"
"github.com/MatrixAINetwork/go-matrix/log"
"github.com/MatrixAINetwork/go-matrix/params/manparams"
"github.com/MatrixAINetwork/go-matrix/reward/util"
)
const (
N = 6
FIRST = 1 //一等奖数目
SECOND = 0 //二等奖数目
THIRD = 0 //三等奖数目
PackageName = "彩票奖励"
)
var (
FIRSTPRIZE *big.Int = big.NewInt(6e+18) //一等奖金额 5man
SENCONDPRIZE *big.Int = big.NewInt(3e+18) //二等奖金额 2man
THIRDPRIZE *big.Int = big.NewInt(1e+18) //三等奖金额 1man
)
type TxCmpResult struct {
Tx types.SelfTransaction
CmpResult uint64
}
// A slice of Pairs that implements sort.Interface to sort by Value.
type TxCmpResultList []TxCmpResult
func (p TxCmpResultList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p TxCmpResultList) Len() int { return len(p) }
func (p TxCmpResultList) Less(i, j int) bool { return p[i].CmpResult < p[j].CmpResult }
type ChainReader interface {
GetBlockByNumber(number uint64) *types.Block
Config() *params.ChainConfig
}
type TxsLottery struct {
chain ChainReader
seed LotterySeed
state util.StateDB
lotteryCfg *mc.LotteryCfg
bcInterval *mc.BCIntervalInfo
accountList []common.Address
}
type LotterySeed interface {
GetRandom(hash common.Hash, Type string) (*big.Int, error)
}
func New(chain ChainReader, st util.StateDB, seed LotterySeed, preSt util.StateDB) *TxsLottery {
bcInterval, err := matrixstate.GetBroadcastInterval(preSt)
if err != nil {
log.Error(PackageName, "获取广播周期失败", err)
return nil
}
data, err := matrixstate.GetLotteryCalc(preSt)
if nil != err {
log.Error(PackageName, "获取状态树配置错误")
return nil
}
if data == util.Stop {
log.Error(PackageName, "停止发放区块奖励", "")
return nil
}
cfg, err := matrixstate.GetLotteryCfg(preSt)
if nil != err || nil == cfg {
log.Error(PackageName, "获取状态树配置错误", "")
return nil
}
if len(cfg.LotteryInfo) == 0 {
log.Error(PackageName, "没有配置彩票名额", "")
return nil
}
tlr := &TxsLottery{
chain: chain,
seed: seed,
state: st,
lotteryCfg: cfg,
bcInterval: bcInterval,
accountList: make([]common.Address, 0),
}
return tlr
}
func abs(n int64) int64 {
y := n >> 63
return (n ^ y) - y
}
func (tlr *TxsLottery) GetAccountFromState(state util.StateDB) ([]common.Address, error) {
lotteryFrom, err := matrixstate.GetLotteryAccount(state)
if nil != err {
log.Error(PackageName, "获取矿工奖励金额错误", err)
return nil, errors.New("获取矿工金额错误")
}
if lotteryFrom == nil {
log.Error(PackageName, "lotteryFrom", "is nil")
return nil, errors.New("lotteryFrom is nil")
}
return lotteryFrom.From, nil
}
func (tlr *TxsLottery) AddAccountToState(state util.StateDB, account common.Address) {
accountList, _ := tlr.GetAccountFromState(state)
if nil == accountList {
accountList = make([]common.Address, 0)
}
accountList = append(accountList, account)
from := &mc.LotteryFrom{From: accountList}
matrixstate.SetLotteryAccount(state, from)
return
}
func (tlr *TxsLottery) ResetAccountToState() {
account := &mc.LotteryFrom{From: make([]common.Address, 0)}
matrixstate.SetLotteryAccount(tlr.state, account)
return
}
func (tlr *TxsLottery) LotterySaveAccount(accounts []common.Address, vrfInfo []byte) {
if 0 == len(accounts) {
//log.Info(PackageName, "当前区块没有普通交易", "")
return
}
randObj := mt19937.New()
vrf := baseinterface.NewVrf()
_, vrfValue, _ := vrf.GetVrfInfoFromHeader(vrfInfo)
seed := common.BytesToHash(vrfValue).Big().Int64()
log.Debug(PackageName, "随机数种子", seed)
randObj.Seed(seed)
rand := randObj.Uint64()
index := rand % uint64(len(accounts))
account := accounts[index]
tlr.AddAccountToState(tlr.state, account)
log.Debug(PackageName, "候选彩票账户", account)
}
func (tlr *TxsLottery) LotteryCalc(parentHash common.Hash, num uint64) map[common.Address]*big.Int {
//选举周期的最后时刻分配
if !tlr.canChooseLottery(num) {
return nil
}
if 0 == len(tlr.lotteryCfg.LotteryInfo) {
return nil
}
lotteryNum := uint64(0)
for i := 0; i < len(tlr.lotteryCfg.LotteryInfo); i++ {
lotteryNum += tlr.lotteryCfg.LotteryInfo[i].PrizeNum
}
txsCmpResultList := tlr.getLotteryList(parentHash, num, lotteryNum)
if 0 == len(txsCmpResultList) {
log.Error(PackageName, "本周期没有交易不抽奖", "")
return nil
}
LotteryAccount := make(map[common.Address]*big.Int, 0)
tlr.lotteryChoose(txsCmpResultList, LotteryAccount)
if 0 == len(LotteryAccount) {
log.Error(PackageName, "抽奖结果为nil", "")
return nil
}
return LotteryAccount
}
func (tlr *TxsLottery) canChooseLottery(num uint64) bool {
if !tlr.ProcessMatrixState(num) {
return false
}
balance := tlr.state.GetBalance(params.MAN_COIN, common.LotteryRewardAddress)
if len(balance) == 0 {
log.Error(PackageName, "状态树获取彩票账户余额错误", "")
//return false
}
var allPrice uint64
for _, v := range tlr.lotteryCfg.LotteryInfo {
if v.PrizeMoney < 0 {
log.Error(PackageName, "彩票奖励配置错误,金额", v.PrizeMoney, "奖项", v.PrizeLevel)
return false
}
allPrice = allPrice + v.PrizeMoney*v.PrizeNum
}
if allPrice <= 0 {
log.Error(PackageName, "总奖励不合法", allPrice)
return false
}
if balance[common.MainAccount].Balance.Cmp(new(big.Int).Mul(new(big.Int).SetUint64(allPrice), util.ManPrice)) < 0 {
log.Error(PackageName, "彩票账户余额不足,余额为", balance[common.MainAccount].Balance.String(), "总奖励", util.ManPrice)
return false
}
return true
}
func (tlr *TxsLottery) ProcessMatrixState(num uint64) bool {
if tlr.bcInterval.IsBroadcastNumber(num) {
log.Warn(PackageName, "广播周期不处理", "")
return false
}
latestNum, err := matrixstate.GetLotteryNum(tlr.state)
if nil != err {
log.Error(PackageName, "状态树获取前一发放彩票高度错误", err)
return false
}
if latestNum > tlr.bcInterval.GetLastReElectionNumber() {
//log.Debug(PackageName, "当前彩票奖励已发放无须补发", "")
return false
}
if err := matrixstate.SetLotteryNum(tlr.state, num); err != nil {
log.Error(PackageName, "获取彩票奖状态错误", err)
}
accountList, err := tlr.GetAccountFromState(tlr.state)
if nil != err {
log.Error(PackageName, "获取候选账户错误", err)
}
if 0 == len(accountList) {
log.Error(PackageName, "获取账户数量为0", "")
return false
}
tlr.accountList = accountList
tlr.ResetAccountToState()
return true
}
func (tlr *TxsLottery) getLotteryList(parentHash common.Hash, num uint64, lotteryNum uint64) []common.Address {
randSeed, err := tlr.seed.GetRandom(parentHash, manparams.ElectionSeed)
if nil != err {
log.Error(PackageName, "获取随机数错误", err)
return nil
}
log.Debug(PackageName, "随机数种子", randSeed.Int64())
rand := mt19937.RandUniformInit(randSeed.Int64())
//sort.Sort(txsCmpResultList)
chooseResultList := make([]common.Address, 0)
//log.Debug(PackageName, "交易数目", len(tlr.accountList))
for i := 0; i < int(lotteryNum) && i < len(tlr.accountList); i++ {
randomData := uint64(rand.Uniform(0, float64(^uint64(0))))
//log.Trace(PackageName, "随机数", randomData)
index := randomData % (uint64(len(tlr.accountList)))
//log.Trace(PackageName, "交易序号", index)
chooseResultList = append(chooseResultList, tlr.accountList[index])
}
return chooseResultList
}
func (tlr *TxsLottery) lotteryChoose(txsCmpResultList []common.Address, LotteryMap map[common.Address]*big.Int) {
RecordMap := make(map[uint8]uint64)
for i := 0; i < len(tlr.lotteryCfg.LotteryInfo); i++ {
RecordMap[uint8(i)] = 0
}
for _, from := range txsCmpResultList {
//抽取一等奖
for i := 0; i < len(tlr.lotteryCfg.LotteryInfo); i++ {
prizeLevel := tlr.lotteryCfg.LotteryInfo[i].PrizeLevel
prizeNum := tlr.lotteryCfg.LotteryInfo[i].PrizeNum
prizeMoney := tlr.lotteryCfg.LotteryInfo[i].PrizeMoney
if RecordMap[prizeLevel] < prizeNum {
util.SetAccountRewards(LotteryMap, from, new(big.Int).Mul(new(big.Int).SetUint64(prizeMoney), util.ManPrice))
RecordMap[prizeLevel]++
log.Debug(PackageName, "奖励地址", from, "金额MAN", prizeMoney)
break
}
}
}
}
|
package main
import (
database "github.com/fr05t1k/wallet/db"
_ "github.com/joho/godotenv"
)
import (
"github.com/fr05t1k/wallet/config"
"github.com/fr05t1k/wallet/operation"
"github.com/fr05t1k/wallet/server"
)
func main() {
RunWallet()
}
func RunWallet() {
runner := GetWalletServer()
runner.Run(config.GetConfig().GrpcPort)
}
func GetWalletServer() *server.Wallet {
db := database.Connect(config.GetConfig().MongoDbHost, config.GetConfig().MongoDbDatabase)
operations := operation.Manager{DB: db}
return &server.Wallet{Operations: &operations}
}
|
package shark
import (
"testing"
)
func Test_parsePattern(t *testing.T) {
r1 := "/assets/*filepath/hep.css"
t.Log(parsePattern(r1))
}
func TestNode(t *testing.T) {
n := &node{}
pattern := "/assets/:path/data"
parts := parsePattern(pattern)
n.insert(pattern, parts, 0)
t.Log(n)
}
func TestRouter(t *testing.T) {
r := newRouter()
r.addRoute("GET", "/", nil)
r.addRoute("GET", "/hello/:name", nil)
r.addRoute("GET", "/hello/b/c", nil)
r.addRoute("GET", "/hi/:name", nil)
r.addRoute("GET", "/assets/*filepath", nil)
t.Log(r)
t.Log(r.getRoute("GET","/hello/elyar"))
}
|
package bytedance
import "fmt"
func Code1016() {
s1 := "abcdxabcde"
s2 := "abcdeabcdx"
fmt.Println(checkInclusion(s1, s2))
}
/**
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
示例1:
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").
示例2:
输入: s1= "ab" s2 = "eidboaoo"
输出: False
注意:
输入的字符串只包含小写字母
两个字符串的长度都在 [1, 10,000] 之间
```
*/
func checkInclusion(s1 string, s2 string) bool {
len1 := len(s1)
len2 := len(s2)
if len1 > len2 {
return false
}
for i := 0; i <= len2-len1; i++ {
if compare(s1, s2[i:i+len1]) {
return true
}
}
return false
}
func compare(s1 string, s2 string) bool {
ca := make([]int, 26)
cb := make([]int, 26)
for _, item := range s1 {
ca[item-'a']++
}
for _, item := range s2 {
cb[item-'a']++
}
fmt.Println(ca)
fmt.Println(cb)
for i := 0; i < 26; i++ {
if ca[i] != cb[i] {
return false
}
}
return true
}
|
package dependencies
import (
_ "github.com/cweill/gotests"
) |
package utils
type BulkInsertStruct struct {
Columns *string
Query *string
Values *[]string
}
|
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
colorize "github.com/sabhiram/go-colorize"
)
// Version & Revision
var (
Version string
Revision string
)
func init() {
Version = "0.0.1"
Revision = "0000000"
}
func main() {
if len(os.Args) != 2 {
fmt.Println(colorize.ColorString("Error: Invalid Usage", "red"))
return
}
res, err := http.Get(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
re := regexp.MustCompile("(<a[^>]*>[^<]+</a>)")
colorizedBody := re.ReplaceAllString(string(body), "<red>${1}</red>")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", colorize.Colorize(colorizedBody))
}
|
package web
import (
"net/http"
"net/url"
)
type Request interface {
Method() string
URL() *url.URL
}
type request struct {
r *http.Request
}
func NewRequest(r *http.Request) Request {
return &request{
r: r,
}
}
func (r *request) Method() string {
return r.r.Method
}
func (r *request) URL() *url.URL {
return r.r.URL
}
|
package httpservice
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "github.com/mattn/go-sqlite3"
_ "httpservice/docs"
"fmt"
"define"
"httpservice/services"
)
type HServer struct {
}
func NewHTTPServer() *HServer {
s := &HServer{}
return s
}
// @title Swagger Gin Test API
// @version 1.0
// @description Gin-Test
// @host
// @BasePath /
func (s *HServer) InitHttpServer() error {
serverAddr := fmt.Sprintf("%s:%d", define.Cfg.HttpServerIp, define.Cfg.HttpServerPort)
router := s.Router()
gin.SetMode(gin.DebugMode)
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
return router.Run(serverAddr)
}
func (s *HServer) Router() *gin.Engine {
r := gin.Default()
building := r.Group("/api/building")
{
ginController(building)
}
return r
}
func ginController(building *gin.RouterGroup) {
c := services.BuildingController{}
company := building.Group("/company")
{
company.GET("", c.GetBuildingCompany)
company.POST("", c.AddBuildingCompany)
}
} |
package compiler
import (
"fmt"
"runtime"
"github.com/BlankRain/gal/ast"
"github.com/BlankRain/gal/llvm/strings"
"github.com/BlankRain/gal/llvm/types"
"github.com/BlankRain/gal/llvm/value"
"github.com/llir/llvm/ir"
"github.com/llir/llvm/ir/constant"
llvmTypes "github.com/llir/llvm/ir/types"
)
type Compiler struct {
module *ir.Module
// functions provided by the OS, such as printf and malloc
// externalFuncs ExternalFuncs
// functions provided by the language, such as println
globalFuncs map[string]*types.Function
currentPackageName string
contextFunc *types.Function
// Stack of return values pointers, is used both used if a function returns more
// than one value (arg pointers), and single stack based returns
contextFuncRetVals [][]value.Value
contextBlock *ir.Block
// Stack of variables that are in scope
contextBlockVariables []map[string]value.Value
// What a break or continue should resolve to
contextLoopBreak []*ir.Block
contextLoopContinue []*ir.Block
// Where a condition should jump when done
contextCondAfter []*ir.Block
// What type the current assign operation is assigning to.
// Is used when evaluating what type an integer constant should be.
contextAssignDest []value.Value
// Stack of Alloc instructions
// Is used to decide if values should be stack or heap allocated
// contextAlloc []*parser.AllocNode
stringConstants map[string]*ir.Global
}
var (
i8 = types.I8
i32 = types.I32
i64 = types.I64
)
var typeConvertMap = map[string]types.Type{
"bool": types.Bool,
"int": types.I64, // TODO: Size based on arch
"int8": types.I8,
"int16": types.I16,
"int32": types.I32,
"int64": types.I64,
"string": types.String,
}
func NewCompiler() *Compiler {
c := &Compiler{
module: ir.NewModule(),
globalFuncs: make(map[string]*types.Function),
// packages: make(map[string]*types.PackageInstance),
contextFuncRetVals: make([][]value.Value, 0),
contextBlockVariables: make([]map[string]value.Value, 0),
contextLoopBreak: make([]*ir.Block, 0),
contextLoopContinue: make([]*ir.Block, 0),
contextCondAfter: make([]*ir.Block, 0),
contextAssignDest: make([]value.Value, 0),
stringConstants: make(map[string]*ir.Global),
}
// c.createExternalPackage()
// c.addGlobal()
// Triple examples:
// x86_64-apple-macosx10.13.0
// x86_64-pc-linux-gnu
var targetTriple [2]string
switch runtime.GOARCH {
case "amd64":
targetTriple[0] = "x86_64"
default:
panic("unsupported GOARCH: " + runtime.GOARCH)
}
switch runtime.GOOS {
case "darwin":
targetTriple[1] = "apple-macosx10.13.0"
case "linux":
targetTriple[1] = "pc-linux-gnu"
case "windows":
targetTriple[1] = "pc-windows"
default:
panic("unsupported GOOS: " + runtime.GOOS)
}
c.module.TargetTriple = fmt.Sprintf("%s-%s", targetTriple[0], targetTriple[1])
return c
}
func (c *Compiler) GetIR() string {
return c.module.String()
}
func (c *Compiler) Compile(node ast.Node) {
switch node := node.(type) {
case *ast.Program:
c.compileProgram(node)
case *ast.ExpressionStatement:
c.Compile(node.Expression)
case *ast.IntegerLiteral:
c.compileInteger(node)
case *ast.Boolean:
c.compileNativeBoolen(node)
case *ast.PrefixExpression:
c.compilePrefixExpression(node)
case *ast.InfixExpression:
c.compileInfixExpression(node)
case *ast.BlockStatement:
c.compileBlockStatement(node)
case *ast.IfExpression:
c.compileIfExpression(node)
case *ast.ReturnStatement:
c.compileReturnExpression(node)
case *ast.FunctionLiteral:
c.compileFunction(node)
case *ast.LetStatement:
c.compileLetStatement(node)
case *ast.CallExpression:
c.compileApplyFunction(node)
case *ast.Identifier:
c.compileIdentifier(node)
case *ast.StringLiteral:
// &object.String{Value: node.Value}
c.compileString(node)
case *ast.ArrayLiteral:
c.compileArray(node)
case *ast.IndexExpression:
c.compileIndexExpression(node)
}
}
func (c *Compiler) compileProgram(prog *ast.Program) {
for _, statement := range prog.Statements {
c.Compile(statement)
}
}
func (c *Compiler) compileInteger(node *ast.IntegerLiteral) value.Value {
return value.Value{
Value: constant.NewInt(llvmTypes.I64, node.Value),
Type: types.I64,
IsVariable: false,
}
}
func (c *Compiler) compileNativeBoolen(node *ast.Boolean) value.Value {
v := 0 //false
if node.Value { //true
v = 1
}
return value.Value{
Value: constant.NewInt(llvmTypes.I1, int64(v)),
Type: types.Bool,
IsVariable: false,
}
}
func (c *Compiler) compileInfixExpression(node *ast.InfixExpression) {
}
func (c *Compiler) compileBlockStatement(node *ast.BlockStatement) {
}
func (c *Compiler) compilePrefixExpression(node *ast.PrefixExpression) {
}
func (c *Compiler) compileIfExpression(node *ast.IfExpression) {
}
func (c *Compiler) compileReturnExpression(node *ast.ReturnStatement) {
}
func (c *Compiler) compileFunction(node *ast.FunctionLiteral) {
}
func (c *Compiler) compileLetStatement(node *ast.LetStatement) {
}
func (c *Compiler) compileExpressions(node []ast.Expression) {
}
func (c *Compiler) compileApplyFunction(node *ast.CallExpression) {
}
func (c *Compiler) compileIdentifier(node *ast.Identifier) {
}
func (c *Compiler) compileString(node *ast.StringLiteral) value.Value {
var constString *ir.Global
// Reuse the *ir.Global if it has already been created
if reusedConst, ok := c.stringConstants[node.Value]; ok {
constString = reusedConst
} else {
constString = c.module.NewGlobalDef(strings.NextStringName(), strings.Constant(node.Value))
constString.Immutable = true
c.stringConstants[node.Value] = constString
}
alloc := c.contextBlock.NewAlloca(typeConvertMap["string"].LLVM())
// Save length of the string
lenItem := c.contextBlock.NewGetElementPtr(alloc, constant.NewInt(llvmTypes.I32, 0), constant.NewInt(llvmTypes.I32, 0))
c.contextBlock.NewStore(constant.NewInt(llvmTypes.I64, int64(len(node.Value))), lenItem)
// Save i8* version of string
strItem := c.contextBlock.NewGetElementPtr(alloc, constant.NewInt(llvmTypes.I32, 0), constant.NewInt(llvmTypes.I32, 1))
c.contextBlock.NewStore(strings.Toi8Ptr(c.contextBlock, constString), strItem)
return value.Value{
Value: c.contextBlock.NewLoad(alloc),
Type: types.String,
IsVariable: false,
}
}
func (c *Compiler) compileArray(node *ast.ArrayLiteral) {
}
func (c *Compiler) compileIndexExpression(node *ast.IndexExpression) {
}
|
package game
import (
"log"
"math"
"runtime"
"time"
"github.com/veandco/go-sdl2/sdl"
)
type Game struct {
Renderer *sdl.Renderer
Window *sdl.Window
}
// NewGame returns an entire game object. Only one should exist.
func NewGame() *Game {
return &Game{}
}
// Init initializes the display and locks the goroutine to the executing thread.
func (g *Game) Init() error {
runtime.LockOSThread()
if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {
return err
}
window, err := sdl.CreateWindow("Game2D", 0, 0, 1920, 1080, sdl.WINDOW_RESIZABLE)
if err != nil {
return err
}
renderer, err := sdl.CreateRenderer(window, 0, sdl.RENDERER_ACCELERATED|sdl.RENDERER_PRESENTVSYNC)
if err != nil {
return err
}
g.Window = window
g.Renderer = renderer
return nil
}
type Player struct {
X, Y float64
XVelo, YVelo float64
XTarget, YTarget float64
Color sdl.Color
}
func NewPlayer() *Player {
return &Player{X: 0, Y: 0, XVelo: 0, YVelo: 0, Color: sdl.Color{R: 0, G: 200, B: 60, A: 255}}
}
func (p *Player) HandleInput(input sdl.Event) {
switch e := input.(type) {
case *sdl.KeyboardEvent:
if e.State != sdl.PRESSED {
break
}
switch e.Keysym.Sym {
case sdl.K_w:
p.YVelo += -1
case sdl.K_a:
p.XVelo += -1
case sdl.K_s:
p.YVelo += 1
case sdl.K_d:
p.XVelo += 1
}
case *sdl.MouseMotionEvent:
x, y := float64(e.X), float64(e.Y)
p.XTarget = x
p.YTarget = y
}
}
func (p *Player) Update() {
p.XVelo += (p.XTarget - p.X) / 100
p.YVelo += (p.YTarget - p.Y) / 100
if p.XVelo < 0 {
p.XVelo = math.Max(-25, p.XVelo)
} else {
p.XVelo = math.Min(25, p.XVelo)
}
if p.YVelo < 0 {
p.YVelo = math.Max(-25, p.YVelo)
} else {
p.YVelo = math.Min(25, p.YVelo)
}
p.X += p.XVelo
p.Y += p.YVelo
}
func (game *Game) render(p *Player, delta float64) {
vX, vY := p.XVelo+p.XVelo*delta, p.YVelo+p.YVelo*delta
// vX, vY := float64(0), float64(0)
x, y := p.X+vX, p.Y+vY
rect := sdl.Rect{X: int32(x), Y: int32(y), W: 50, H: 50}
r, g, b, a := uint8(p.Color.R), uint8(p.Color.G), uint8(p.Color.B), uint8(p.Color.A)
game.Renderer.SetDrawColor(r, g, b, a)
game.Renderer.FillRect(&rect)
}
const TimeStep int64 = 31250000 // 64 FPS
// Run blocks while running the game.
func (g *Game) Run() {
log.Println("Hello from the game loop")
var quit bool
player := NewPlayer()
start := time.Now()
ticks := int64(0)
lag := int64(0)
for !quit {
nowTicks := time.Now().Sub(start).Nanoseconds()
lag += (nowTicks - ticks)
ticks = nowTicks
fps()
for {
e := sdl.PollEvent()
if e == nil {
break
}
if g.checkForQuit(e) {
quit = true
}
player.HandleInput(e)
}
for lag > TimeStep {
player.Update()
lag -= TimeStep
}
if err := g.Renderer.SetDrawColorArray(200, 140, 200); err != nil {
panic(err)
}
if err := g.Renderer.Clear(); err != nil {
panic(err)
}
delta := float64(lag) / float64(TimeStep)
g.render(player, delta)
g.Renderer.Present()
}
}
func (g *Game) checkForQuit(input sdl.Event) bool {
switch e := input.(type) {
case *sdl.QuitEvent:
return true
case *sdl.KeyboardEvent:
if e.Keysym.Sym == sdl.K_ESCAPE {
return true
}
default:
return false
}
return false
}
var frames uint
var last time.Time
func fps() {
frames++
now := time.Now()
if now.Sub(last).Nanoseconds() > 1e9 {
log.Println("FPS:", frames)
frames = 0
last = now
}
}
|
package client
import (
"log"
"net/rpc"
"pub/dtos"
)
func Publish(client *rpc.Client, topicID, message string) error {
var replyDto dtos.PublishDto
publishDto1 := dtos.PublishDto{TopicID: topicID, Message: dtos.MessageDto{MessageData: message}}
err := client.Call("RPC.Publish", publishDto1, &replyDto)
if err != nil {
log.Println(err)
return err
}
return nil
}
|
package thirdparty
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
settingsapi "alauda.io/diablo/src/backend/settings/api"
thirdpartyapi "alauda.io/diablo/src/backend/thirdparty/api"
"k8s.io/client-go/kubernetes"
)
type ThirdPartyManager struct {
}
func NewThirdPartyManager() thirdpartyapi.ThirdPartyManager {
return &ThirdPartyManager{}
}
func (m *ThirdPartyManager) GetIntegration(client kubernetes.Interface, settingsMngr settingsapi.SettingsManager) []*thirdpartyapi.Integration {
devopsSettings := settingsMngr.GetDevopsSettings(client)
integ, err := convertToIntegrations(devopsSettings)
if err != nil {
log.Println("error parsing devopsSettings integration: err ", err, " original value ", devopsSettings.Integrations)
integ = []*thirdpartyapi.Integration{}
}
return integ
// // TODO: Change to fetch from configuration
// return []*thirdpartyapi.Integration{
// &thirdpartyapi.Integration{
// Enabled: true,
// Type: thirdpartyapi.TPMayun,
// Mayun: &thirdpartyapi.IntegrationMayun{
// Host: "http://www.sparrow.li",
// },
// },
// &thirdpartyapi.Integration{
// Enabled: true,
// Type: thirdpartyapi.TPZentao,
// Zentao: &thirdpartyapi.IntegrationZentao{
// Host: "http://159.65.147.215:30081",
// },
// },
// }
}
func convertToIntegrations(sett *settingsapi.DevopsSettings) (integ []*thirdpartyapi.Integration, err error) {
var data []byte
data, err = json.Marshal(sett.Integrations)
if err != nil {
log.Println("Error converting integrations:", sett.Integrations)
return
}
err = json.Unmarshal(data, &integ)
return
}
func convertToPortalLink(sett *settingsapi.DevopsSettings) (plink *thirdpartyapi.PortalLinks, err error) {
var data []byte
log.Println("devops-config:", sett)
data, err = json.Marshal(sett.PortalLinks)
if err != nil {
log.Println("Error converting portal_links:", sett.PortalLinks)
return
}
err = json.Unmarshal(data, &plink)
return
}
func (m *ThirdPartyManager) GetData(name string, token thirdpartyapi.AuthInfo, client kubernetes.Interface, settingsMngr settingsapi.SettingsManager) (res interface{}, err error) {
integrations := m.GetIntegration(client, settingsMngr)
var targetInt *thirdpartyapi.Integration
if len(integrations) > 0 {
for _, i := range integrations {
if i.Type == name {
targetInt = i
break
}
}
}
if targetInt == nil {
err = fmt.Errorf("Integration not available: %s", name)
return
}
res, err = m.makeRequest(name, token, targetInt)
return
}
func (m *ThirdPartyManager) getClient() (client *http.Client) {
client = http.DefaultClient
client.Timeout = time.Second * 30
return
}
func (m *ThirdPartyManager) makeRequest(name string, token thirdpartyapi.AuthInfo, integration *thirdpartyapi.Integration) (data interface{}, err error) {
req := integration.GetRequest(token)
client := m.getClient()
var resp *http.Response
if resp, err = client.Do(req); err != nil {
return
}
body, _ := ioutil.ReadAll(resp.Body)
if !isGoodResponse(resp) {
err = fmt.Errorf(
"Server returned unexpected result: status %s %d content: %s",
resp.Status, resp.StatusCode, body,
)
}
data = new(interface{})
err = json.Unmarshal(body, &data)
return
}
func isGoodResponse(resp *http.Response) bool {
if resp == nil {
return false
}
return resp.StatusCode >= 200 && resp.StatusCode < 300
}
// func (m *ThirdPartyManager) InstallAPI(ws *restful.WebService) {
// // TODO: Refactor to a better form of doing this
// ws.Route(
// ws.GET("/thirdparty/mayun").
// To(han.handleThirdParty).
// Writes([]*thirdpartyapi.Integration{}))
// }
// func (m *Third)
|
package binarysearch
// return index of target or -1 if does not exist
func BinarySearch(arr []int, target int) int {
startIndex := 0
endIndex := len(arr) - 1
for startIndex <= endIndex {
mid := (startIndex + endIndex) / 2
if arr[mid] > target {
endIndex = mid - 1
} else if arr[mid] < target {
startIndex = mid + 1
} else {
return mid
}
}
return -1
}
|
package optgen
//go:generate stringer -type=Operator operator.go
type Operator int
const (
UnknownOp Operator = iota
RootOp
DefineSetOp
DefineOp
DefineFieldOp
RuleSetOp
RuleHeaderOp
RuleOp
BindOp
RefOp
MatchNamesOp
MatchInvokeOp
MatchFieldsOp
MatchAndOp
MatchNotOp
MatchAnyOp
MatchListOp
ReplaceRootOp
ConstructOp
ConstructListOp
TagsOp
StringOp
OpNameOp
)
|
package azure
import (
"time"
"github.com/cortexproject/cortex/pkg/util/flagext"
)
type Config struct {
StorageAccountName flagext.Secret `yaml:"storage-account-name"`
StorageAccountKey flagext.Secret `yaml:"storage-account-key"`
ContainerName string `yaml:"container-name"`
Endpoint string `yaml:"endpoint-suffix"`
MaxBuffers int `yaml:"max-buffers"`
BufferSize int `yaml:"buffer-size"`
HedgeRequestsAt time.Duration `yaml:"hedge-requests-at"`
}
|
package controllers
import (
"github.com/gin-gonic/gin"
)
type (
SessionsController struct{}
User struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
)
func NewSessionsController() *SessionsController {
return &SessionsController{}
}
func (sc SessionsController) CreateSession(c *gin.Context) {
var user User
c.BindJSON(&user)
if user.Username == "username" && user.Password == "password" {
c.JSON(200, gin.H{"status": "you are logged in"})
} else {
c.JSON(401, gin.H{"status": "unauthorized"})
}
}
|
package arrays
import (
"fmt"
"hackerrank/util"
)
/**
Sample Input
4
1 4 3 2
Sample Output
2 3 4 1
*/
func ArraysDs() {
var n int
if _, err := fmt.Scan(&n); err != nil {
panic(err)
}
a, err := util.IntScanlnSlice(n)
if err != nil {
panic(err)
}
loop := len(a) / 2
last := len(a) - 1
for i, num := range a {
if i == loop {
break
}
a[i] = a[last-i]
a[last-i] = num
}
for _, num := range a {
fmt.Printf("%d ", num)
}
}
|
package userdetails
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
"github.com/sinha-abhishek/jennie/awshelper"
"github.com/sinha-abhishek/jennie/confighelper"
"github.com/sinha-abhishek/jennie/cryptohelper"
"github.com/sinha-abhishek/jennie/linkedin"
"golang.org/x/oauth2"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/plus/v1"
)
type User struct {
UserID string `json:"uid"`
LastLinkedinFetch time.Time `json:"lastLinkedinFetch"`
LastEmailScan time.Time `json:"lastEmailScan"`
Token oauth2.Token `json:"token"`
Name string `json:"name"`
LinkedinMessage string `json:"auto_reply"`
}
var (
userList = make([]User, 0)
)
func GetUser(userID string) (*User, error) {
ud, _ := awshelper.FetchUser(userID)
log.Println("user dunamo=", string(ud))
user := &User{}
b, err2 := cryptohelper.Decrypt(ud, userID)
log.Println(string(b))
if err2 != nil {
log.Println("can't decrypt")
return user, err2
}
err := json.Unmarshal(b, user)
return user, err
}
func FetchAndSaveUser(ctx context.Context, config *oauth2.Config, token *oauth2.Token) (*User, error) {
client := config.Client(ctx, token)
srv, err := gmail.New(client)
if err != nil {
log.Println(err)
return nil, err
}
u := "me"
res, err2 := srv.Users.GetProfile(u).Do()
if err2 != nil {
log.Println(err2)
return nil, err2
}
srv2, err := plus.New(client)
if err != nil {
log.Println(err)
return nil, err
}
p, err := srv2.People.Get("me").Do()
if err != nil {
log.Println(err)
return nil, err
}
log.Println("person=", p.DisplayName)
savedUser, err3 := GetUser(res.EmailAddress)
var user *User
if err3 == nil && savedUser.UserID == res.EmailAddress {
log.Println("exisitng user ", res.EmailAddress)
user = savedUser
} else {
user = &User{}
}
user.UserID = res.EmailAddress
user.Token = *token
user.Name = p.DisplayName
autoConfig, err := confighelper.GetAutoResponseConfig()
if err != nil {
return nil, err
}
rText := fmt.Sprintf(autoConfig.LinkedinResponse, user.Name, user.Name, user.UserID)
log.Println("replytext=", rText)
user.LinkedinMessage = rText
err = user.Save()
//userList = append(userList, user)
err = awshelper.SendUpdateMessage("uid", user.UserID, 800)
return user, err
}
func (user *User) Save() error {
userData, _ := json.Marshal(user)
encData, err := cryptohelper.Encrypt(userData, user.UserID)
if err != nil {
log.Println(err)
return err
}
err = awshelper.SaveUser(user.UserID, string(encData))
if err != nil {
log.Println("Failed to save user", err)
}
return err
}
func PeriodicPuller(ctx context.Context, config *oauth2.Config) {
t := time.NewTimer(15 * time.Minute) //TODO: fix time period
for {
select {
case <-t.C:
log.Println("pulling...")
msgs, err := awshelper.GetUpdateMessages("uid")
var success []*string
var uidsSuccess []string
if err == nil {
for _, v := range msgs {
uid := *v.Body
user, err2 := GetUser(uid)
if err2 == nil {
user.DoEmailAutomationForUser(ctx, config)
uidsSuccess = append(uidsSuccess, uid)
success = append(success, v.ReceiptHandle)
}
}
awshelper.DeleteMessages(success)
for _, u := range uidsSuccess {
awshelper.SendUpdateMessage("uid", u, 800)
}
}
t.Reset(30 * time.Minute)
}
}
}
func InitUserList() {
//TODO:
}
func (user *User) DoEmailAutomationForUser(ctx context.Context, config *oauth2.Config) {
err := linkedin.SearchMailAndRespond(ctx, config, &user.Token, user.UserID, user.LastLinkedinFetch, user.LinkedinMessage)
if err == nil {
user.LastLinkedinFetch = time.Now()
err = user.Save()
if err == nil {
linkedin.ClearRespondedIds(user.UserID)
}
}
}
|
package main
import (
"github.com/Bourne-ID/winrm-dns-client/dns"
)
type config struct {
ServerName string
Username string
Password string
Port int
HTTPS bool
Insecure bool
}
// Client configures the WinRM endpoint for managing Microsoft DNS
func (c *config) Client() (*dns.Client, error) {
client := dns.Client{
ServerName: c.ServerName,
Username: c.Username,
Password: c.Password,
Port: c.Port,
HTTPS: c.HTTPS,
Insecure: c.Insecure,
}
if err := client.ConfigureWinRMClient(); err != nil {
return nil, err
}
return &client, nil
}
|
package main
import(
"fmt"
"net/http"
"html/template"
)
type Pessoa struct{
Nome string
Idade int
}
type TodasPessoas struct{
Pessoas []Pessoa
}
func main(){
tmpl := template.Must(template.ParseFiles("index.html"))
http.HandleFunc("/", func( w http.ResponseWriter, r *http.Request){
data := TodasPessoas{
Pessoas: []Pessoa{
{Nome:"Diogo",Idade:30},
{Nome:"Beto", Idade:40},
},
}
//http.ServeFile(w,r,"index.html")
fmt.Println(data)
tmpl.Execute(w, data)
})
http.ListenAndServe(":8000", nil)
} |
package gator
import (
"fmt"
"math/rand"
"net/http"
"path/filepath"
"time"
"strings"
"github.com/gorilla/websocket"
"github.com/cloudfoundry/loggregatorlib/logmessage"
"io"
"regexp"
"encoding/json"
"math"
)
func StartHTTPServer(config Config, outputChan chan string) {
metricsChan := make(chan string)
mux := http.NewServeMux()
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
rand.Seed(time.Now().UnixNano())
randInt := rand.Int()
randInt = int(math.Mod(float64(randInt), 5))
fmt.Println(randInt)
for i := 0; i < randInt; i++ {
http.Get("http://google.com")
}
fmt.Fprintf(w, "Hello, world!")
})
publicDir, err := filepath.Abs("./public")
if err != nil {
panic(err)
}
mux.Handle("/", http.FileServer(http.Dir(publicDir)))
mux.HandleFunc("/ws", handleSocket(outputChan, metricsChan))
mux.HandleFunc("/metrics", handleMetrics(metricsChan))
fmt.Printf("Serving HTTP requests on http://localhost:%s\n", config.HTTPPort)
http.ListenAndServe(":"+config.HTTPPort, mux)
}
func handleSocket(outputChan, metricsChan chan string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Websocket connection received.")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000 http://gator.10.244.0.34.xip.io")
w.Header().Set("Access-Control-Allow-Credentials", "true")
conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(w, "Not a websocket handshake", 400)
return
} else if err != nil {
fmt.Println(err)
return
}
for {
message := <-outputChan
writer, err := conn.NextWriter(websocket.TextMessage)
if err != nil {
panic(err)
}
logMessage, err := logmessage.ParseMessage([]byte(message))
if err != nil {
panic(err)
}
message = logMessage.GetLogMessage().String()
io.WriteString(writer, message)
}
}
}
func handleMetrics(metricsChan chan string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Websocket connection received.")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000 http://gator.10.244.0.34.xip.io")
w.Header().Set("Access-Control-Allow-Credentials", "true")
conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(w, "Not a websocket handshake", 400)
return
} else if err != nil {
fmt.Println(err)
return
}
for {
message := <-metricsChan
writer, err := conn.NextWriter(websocket.TextMessage)
if err != nil {
panic(err)
}
re := regexp.MustCompile(`response_time:[0-9]*(\.[0-9]+)?`)
match := re.FindString(message)
if match != "" {
parts := strings.Split(match, ":")
responseTime := parts[1]
output := make(map[string]string, 0)
output["response_time"] = responseTime
response, err := json.Marshal(output)
if err != nil {
panic(err)
}
io.WriteString(writer, string(response))
}
}
}
}
|
package main
import "fmt"
func main() {
fmt.Printf("nothing to see here, I'm just a dummy file so we can build")
}
|
package ubernet
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"runtime"
"strings"
"time"
)
func defaultPooledTransport() *http.Transport {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
ResponseHeaderTimeout: 30 * time.Second,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConnsPerHost: runtime.GOMAXPROCS(0) + 1,
}
return transport
}
func defaultTransport() *http.Transport {
transport := defaultPooledTransport()
transport.DisableKeepAlives = true
transport.MaxIdleConnsPerHost = -1
return transport
}
// DefaultClient ..
func DefaultClient() *http.Client {
return &http.Client{
Transport: defaultTransport(),
}
}
// DefaultPooledClient ..
func DefaultPooledClient() *http.Client {
return &http.Client{
Transport: defaultPooledTransport(),
}
}
var (
defaultRetryWaitMin = 2 * time.Second
defaultRetryWaitMax = 10 * time.Second
defaultRetryMax = 2
defaultClient = NewClient()
respReadLimit = int64(4096)
)
// ReaderFunc ..
type ReaderFunc func() (io.Reader, error)
// LenReader ..
type LenReader interface {
Len() int
}
// Request ..
type Request struct {
body ReaderFunc
*http.Request
}
// WithContext ..
func (r *Request) WithContext(ctx context.Context) *Request {
r.Request = r.Request.WithContext(ctx)
return r
}
// BodyBytes ..
func (r *Request) BodyBytes() ([]byte, error) {
if r.body == nil {
return nil, nil
}
body, err := r.body()
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(body)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func getBodyReaderAndContentLength(rawBody interface{}) (ReaderFunc, int64, error) {
var bodyReader ReaderFunc
var contentLength int64
if rawBody != nil {
switch body := rawBody.(type) {
case ReaderFunc:
bodyReader = body
tmp, err := body()
if err != nil {
return nil, 0, err
}
if lr, ok := tmp.(LenReader); ok {
contentLength = int64(lr.Len())
}
if c, ok := tmp.(io.Closer); ok {
c.Close()
}
case func() (io.Reader, error):
bodyReader = body
tmp, err := body()
if err != nil {
return nil, 0, err
}
if lr, ok := tmp.(LenReader); ok {
contentLength = int64(lr.Len())
}
if c, ok := tmp.(io.Closer); ok {
c.Close()
}
case []byte:
buf := body
bodyReader = func() (io.Reader, error) {
return bytes.NewReader(buf), nil
}
contentLength = int64(len(buf))
case *bytes.Buffer:
buf := body
bodyReader = func() (io.Reader, error) {
return bytes.NewReader(buf.Bytes()), nil
}
contentLength = int64(buf.Len())
case *bytes.Reader:
buf, err := ioutil.ReadAll(body)
if err != nil {
return nil, 0, err
}
bodyReader = func() (io.Reader, error) {
return bytes.NewReader(buf), nil
}
contentLength = int64(len(buf))
case io.ReadSeeker:
raw := body
bodyReader = func() (io.Reader, error) {
_, err := raw.Seek(0, 0)
return ioutil.NopCloser(raw), err
}
if lr, ok := raw.(LenReader); ok {
contentLength = int64(lr.Len())
}
case io.Reader:
buf, err := ioutil.ReadAll(body)
if err != nil {
return nil, 0, err
}
bodyReader = func() (io.Reader, error) {
return bytes.NewReader(buf), nil
}
contentLength = int64(len(buf))
default:
return nil, 0, fmt.Errorf("cannot handle type %T", rawBody)
}
}
return bodyReader, contentLength, nil
}
// FromRequest ..
func FromRequest(r *http.Request) (*Request, error) {
bodyReader, _, err := getBodyReaderAndContentLength(r.Body)
if err != nil {
return nil, err
}
return &Request{bodyReader, r}, nil
}
// NewRequest ..
func NewRequest(method, url string, rawBody interface{}) (*Request, error) {
bodyReader, contentLength, err := getBodyReaderAndContentLength(rawBody)
if err != nil {
return nil, err
}
httpReq, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
httpReq.ContentLength = contentLength
return &Request{bodyReader, httpReq}, nil
}
// Logger ..
type Logger interface {
Printf(string, ...interface{})
}
// RequestLogHook ..
type RequestLogHook func(Logger, *http.Request, int)
// ResponseLogHook ..
type ResponseLogHook func(Logger, *http.Response)
// RetryPolicy ..
type RetryPolicy func(ctx context.Context, resp *http.Response, err error) (bool, error)
// Backoff ..
type Backoff func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration
// ErrorHandler ..
type ErrorHandler func(resp *http.Response, err error, numTries int) (*http.Response, error)
// Client ..
type Client struct {
HTTPClient *http.Client
Logger Logger
RetryWaitMin time.Duration
RetryWaitMax time.Duration
RetryMax int
RequestLogHook RequestLogHook
ResponseLogHook ResponseLogHook
RetryPolicy RetryPolicy
Backoff Backoff
ErrorHandler ErrorHandler
}
// NewClient ..
func NewClient() *Client {
return &Client{
HTTPClient: DefaultClient(),
Logger: log.New(os.Stderr, "", log.LstdFlags),
RetryWaitMin: defaultRetryWaitMin,
RetryWaitMax: defaultRetryWaitMax,
RetryMax: defaultRetryMax,
RetryPolicy: defaultRetryPolicy,
Backoff: defaultBackoff,
}
}
func defaultRetryPolicy(ctx context.Context, resp *http.Response, err error) (bool, error) {
if ctx.Err() != nil {
return false, ctx.Err()
}
if err != nil {
return true, err
}
if resp.StatusCode == 0 || (resp.StatusCode >= 500 && resp.StatusCode != 501) {
return true, nil
}
return false, nil
}
func defaultBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
mult := math.Pow(2, float64(attemptNum)) * float64(min)
sleep := time.Duration(mult)
if float64(sleep) != mult || sleep > max {
sleep = max
}
return sleep
}
// LinearJitterBackoff ..
func LinearJitterBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
attemptNum++
if max <= min {
return min * time.Duration(attemptNum)
}
rand := rand.New(rand.NewSource(int64(time.Now().Nanosecond())))
jitter := rand.Float64() * float64(max-min)
jitterMin := int64(jitter) + int64(min)
return time.Duration(jitterMin * int64(attemptNum))
}
// PassthroughErrorHandler ..
func PassthroughErrorHandler(resp *http.Response, err error, _ int) (*http.Response, error) {
return resp, err
}
// Do ..
func (c *Client) Do(req *Request) (*http.Response, error) {
var resp *http.Response
var err error
for i := 0; ; i++ {
var code int
if req.body != nil {
body, err := req.body()
if err != nil {
return resp, err
}
if c, ok := body.(io.ReadCloser); ok {
req.Body = c
} else {
req.Body = ioutil.NopCloser(body)
}
}
if c.RequestLogHook != nil {
c.RequestLogHook(c.Logger, req.Request, i)
}
resp, err = c.HTTPClient.Do(req.Request)
if resp != nil {
code = resp.StatusCode
}
checkOK, checkErr := c.RetryPolicy(req.Context(), resp, err)
if err != nil {
if c.Logger != nil {
c.Logger.Printf("ERROR %s %s request failed: %v", req.Method, req.URL, err)
}
} else {
if c.ResponseLogHook != nil {
c.ResponseLogHook(c.Logger, resp)
}
}
if !checkOK {
if checkErr != nil {
err = checkErr
}
return resp, err
}
remain := c.RetryMax - i
if remain <= 0 {
break
}
if err == nil && resp != nil {
c.drainBody(resp.Body)
}
wait := c.Backoff(c.RetryWaitMin, c.RetryWaitMax, i, resp)
desc := fmt.Sprintf("%s %s", req.Method, req.URL)
if code > 0 {
desc = fmt.Sprintf("%s (status: %d)", desc, code)
}
if c.Logger != nil {
c.Logger.Printf("WARNING %s: retrying in %s (%d left)", desc, wait, remain)
}
select {
case <-req.Context().Done():
return nil, req.Context().Err()
case <-time.After(wait):
}
}
if c.ErrorHandler != nil {
return c.ErrorHandler(resp, err, c.RetryMax+1)
}
if resp != nil {
resp.Body.Close()
}
return nil, fmt.Errorf("%s %s giving up after %d attempts", req.Method, req.URL, c.RetryMax+1)
}
func (c *Client) drainBody(body io.ReadCloser) {
defer body.Close()
_, err := io.Copy(ioutil.Discard, io.LimitReader(body, respReadLimit))
if err != nil {
if c.Logger != nil {
c.Logger.Printf("ERROR error reading response body: %v", err)
}
}
}
// Get ..
func Get(url string) (*http.Response, error) {
return defaultClient.Get(url)
}
// Get ..
func (c *Client) Get(url string) (*http.Response, error) {
req, err := NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Head ..
func Head(url string) (*http.Response, error) {
return defaultClient.Head(url)
}
// Head ..
func (c *Client) Head(url string) (*http.Response, error) {
req, err := NewRequest("HEAD", url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Post ..
func Post(url, bodyType string, body interface{}) (*http.Response, error) {
return defaultClient.Post(url, bodyType, body)
}
// Post ..
func (c *Client) Post(url, bodyType string, body interface{}) (*http.Response, error) {
req, err := NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", bodyType)
req.Header.Add("authorization", os.Getenv("AUTHORIZATION_KEY"))
return c.Do(req)
}
// PostForm ..
func PostForm(url string, data url.Values) (*http.Response, error) {
return defaultClient.PostForm(url, data)
}
// PostForm ..
func (c *Client) PostForm(url string, data url.Values) (*http.Response, error) {
return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
}
|
package consumer
import (
"bytes"
"errors"
"hash/crc32"
"net"
"os/exec"
"sync"
"sync/atomic"
"time"
"github.com/couchbase/eventing/common"
"github.com/couchbase/eventing/dcp"
mcd "github.com/couchbase/eventing/dcp/transport"
cb "github.com/couchbase/eventing/dcp/transport/client"
"github.com/couchbase/eventing/suptree"
"github.com/couchbase/eventing/timer_transfer"
"github.com/couchbase/gocb"
"github.com/couchbase/plasma"
)
const (
xattrCasPath = "eventing.cas"
xattrPrefix = "eventing"
xattrTimerPath = "eventing.timers"
getAggTimerHostPortAddrs = "getAggTimerHostPortAddrs"
tsLayout = "2006-01-02T15:04:05Z"
metakvEventingPath = "/eventing/"
metakvAppsPath = metakvEventingPath + "apps/"
metakvAppSettingsPath = metakvEventingPath + "settings/"
)
const (
dcpDatatypeJSON = uint8(1)
dcpDatatypeJSONXattr = uint8(5)
includeXATTRs = uint32(4)
)
// plasma related constants
const (
autoLssCleaning = false
maxDeltaChainLen = 30
maxPageItems = 100
minPageItems = 10
useMemManagement = true
)
const (
numVbuckets = 1024
// KV blob suffixes to assist in choose right consumer instance
// for instantiating V8 Debugger instance
startDebuggerFlag = "startDebugger"
debuggerInstanceAddr = "debuggerInstAddr"
// DCP consumer related configs
dcpGenChanSize = 10000
dcpDataChanSize = 10000
dcpNumConnections = 1
timerChanSize = 10000
// To decode messages from c++ world to Go
headerFragmentSize = 4
// ClusterChangeNotifChBufSize limits buffer size for cluster change notif from producer
ClusterChangeNotifChBufSize = 10
cppWorkerPartitionCount = 1024
debuggerFlagCheckInterval = time.Duration(5000) * time.Millisecond
// Interval for retrying failed bucket operations using go-couchbase
bucketOpRetryInterval = time.Duration(1000) * time.Millisecond
// Interval for retrying vb dcp stream
dcpStreamRequestRetryInterval = time.Duration(1000) * time.Millisecond
// Last processed seq # checkpoint interval
checkpointInterval = time.Duration(3000) * time.Millisecond
// Interval for retrying failed cluster related operations
clusterOpRetryInterval = time.Duration(1000) * time.Millisecond
// Interval at which plasma.PersistAll will be called against *plasma.Plasma
persistAllTickInterval = time.Duration(5000) * time.Millisecond
// Interval for retrying failed plasma operations
plasmaOpRetryInterval = time.Duration(1000) * time.Millisecond
statsTickInterval = time.Duration(5000) * time.Millisecond
timerProcessingTickInterval = time.Duration(500) * time.Millisecond
restartVbDcpStreamTickInterval = time.Duration(3000) * time.Millisecond
retryVbsStateUpdateInterval = time.Duration(5000) * time.Millisecond
retryVbMetaStateCheckInterval = time.Duration(1000) * time.Millisecond
retryInterval = time.Duration(1000) * time.Millisecond
)
const (
dcpStreamBootstrap = "bootstrap"
dcpStreamRunning = "running"
dcpStreamStopped = "stopped"
dcpStreamUninitialised = ""
)
var dcpConfig = map[string]interface{}{
"genChanSize": dcpGenChanSize,
"dataChanSize": dcpDataChanSize,
"numConnections": dcpNumConnections,
"activeVbOnly": true,
}
var (
errPlasmaHandleMissing = errors.New("Failed to find plasma handle")
)
type debuggerBlob struct {
ConsumerName string `json:"consumer_name"`
HostPortAddr string `json:"host_port_addr"`
UUID string `json:"uuid"`
}
type xattrMetadata struct {
Cas string `json:"cas"`
Digest uint32 `json:"digest"`
Timers []string `json:"timers"`
}
type vbFlogEntry struct {
seqNo uint64
streamReqRetry bool
statusCode mcd.Status
vb uint16
flog *cb.FailoverLog
}
type v8InitMeta struct {
AppName string `json:"app_name"`
KvHostPort string `json:"kv_host_port"`
}
type dcpMetadata struct {
Cas uint64 `json:"cas"`
DocID string `json:"docid"`
Expiry uint32 `json:"expiry"`
Flag uint32 `json:"flag"`
Vbucket uint16 `json:"vb"`
SeqNo uint64 `json:"seq"`
}
// Consumer is responsible interacting with c++ v8 worker over local tcp port
type Consumer struct {
app *common.AppConfig
bucket string
conn net.Conn // Access controlled by default lock
uuid string
cppThrPartitionMap map[int][]uint16
cppWorkerThrCount int // No. of worker threads per CPP worker process
crcTable *crc32.Table
debugConn net.Conn // Interface to support communication between Go and C++ worker spawned for debugging
debugListener net.Listener
handlerCode string // Handler code for V8 Debugger
sourceMap string // source map to assist with V8 Debugger
sendMsgToDebugger bool
aggDCPFeed chan *cb.DcpEvent
cbBucket *couchbase.Bucket
checkpointInterval time.Duration
cleanupTimers bool
dcpFeedCancelChs []chan struct{}
dcpFeedVbMap map[*couchbase.DcpFeed][]uint16 // Access controlled by default lock
eventingAdminPort string
eventingDir string
eventingNodeAddrs []string
eventingNodeUUIDs []string
executionTimeout int
gocbBucket *gocb.Bucket
gocbMetaBucket *gocb.Bucket
isRebalanceOngoing bool
kvHostDcpFeedMap map[string]*couchbase.DcpFeed // Access controlled by hostDcpFeedRWMutex
hostDcpFeedRWMutex *sync.RWMutex
kvVbMap map[uint16]string // Access controlled by default lock
logLevel string
superSup common.EventingSuperSup
vbDcpFeedMap map[uint16]*couchbase.DcpFeed
vbnos []uint16
vbsRemainingToOwn []uint16
vbsRemainingToGiveUp []uint16
vbsRemainingToRestream []uint16
// Routines to control parallel vbucket ownership transfer
// during rebalance
vbOwnershipGiveUpRoutineCount int
vbOwnershipTakeoverRoutineCount int
// N1QL Transpiler related nested iterator config params
lcbInstCapacity int
docTimerEntryCh chan *byTimerEntry
nonDocTimerEntryCh chan string
// Plasma DGM store handle to store timer entries at per vbucket level
persistAllTicker *time.Ticker
stopPlasmaPersistCh chan struct{}
timerAddrs map[string]map[string]string
plasmaReaderRWMutex *sync.RWMutex
plasmaStoreRWMutex *sync.RWMutex
vbPlasmaStore *plasma.Plasma
vbPlasmaWriter map[uint16]*plasma.Writer // Access controlled by plasmaStoreRWMutex
vbPlasmaReader map[uint16]*plasma.Writer // Access controlled by plasmaReaderRWMutex
signalStoreTimerPlasmaCloseCh chan uint16
signalProcessTimerPlasmaCloseAckCh chan uint16
signalStoreTimerPlasmaCloseAckCh chan uint16
signalPlasmaClosedCh chan uint16
signalPlasmaTransferFinishCh chan *plasmaStoreMsg
// Signals V8 consumer to start V8 Debugger agent
signalStartDebuggerCh chan struct{}
signalStopDebuggerCh chan struct{}
signalInstBlobCasOpFinishCh chan struct{}
signalUpdateDebuggerInstBlobCh chan struct{}
signalDebugBlobDebugStopCh chan struct{}
signalStopDebuggerRoutineCh chan struct{}
debuggerState int8
debuggerStarted bool
nonDocTimerProcessingTicker *time.Ticker
nonDocTimerStopCh chan struct{}
skipTimerThreshold int
socketTimeout time.Duration
timerProcessingTickInterval time.Duration
timerProcessingVbsWorkerMap map[uint16]*timerProcessingWorker // Access controlled by timerRWMutex
timerProcessingRunningWorkers []*timerProcessingWorker // Access controlled by timerRWMutex
timerProcessingWorkerSignalCh map[*timerProcessingWorker]chan struct{} // Access controlled by timerRWMutex
timerProcessingWorkerCount int
timerRWMutex *sync.RWMutex
// Instance of timer related data transferring routine, under
// the supervision of consumer routine
timerTransferHandle *timer.TransferSrv
timerTransferSupToken suptree.ServiceToken
enableRecursiveMutation bool
dcpStreamBoundary common.DcpStreamBoundary
// Map that needed to short circuits failover log to dcp stream request routine
vbFlogChan chan *vbFlogEntry
sendMsgCounter int
// For performance reasons, Golang writes dcp events to tcp socket in batches
// socketWriteBatchSize controls the batch size
socketWriteBatchSize int
sendMsgBuffer bytes.Buffer
// Stores the vbucket seqnos for socket write batch
// Upon reading message back from CPP world, vbProcessingStats will be
// updated for all vbuckets in that batch
writeBatchSeqnoMap map[uint16]uint64 // Access controlled by default lock
// host:port handle for current eventing node
hostPortAddr string
workerName string
producer common.EventingProducer
// OS pid of c++ v8 worker
osPid atomic.Value
// C++ v8 worker cmd handle, would be required to killing worker that are no more needed
client *client
debugClient *debugClient // C++ V8 worker spawned for debugging purpose
debugClientSupToken suptree.ServiceToken
consumerSup *suptree.Supervisor
clientSupToken suptree.ServiceToken
// Chan to signal that current Eventing.Consumer instance
// has finished bootstrap
signalBootstrapFinishCh chan struct{}
// Populated when C++ v8 worker is spawned
// correctly and downstream tcp socket is available
// for sending messages. Unbuffered channel.
signalConnectedCh chan struct{}
// Chan used by signal update of app handler settings
signalSettingsChangeCh chan struct{}
stopControlRoutineCh chan struct{}
// Populated when downstream tcp socket mapping to
// C++ v8 worker is down. Buffered channel to avoid deadlock
stopConsumerCh chan struct{}
// Chan to stop background checkpoint routine, keeping track
// of last seq # processed
stopCheckpointingCh chan struct{}
gracefulShutdownChan chan struct{}
clusterStateChangeNotifCh chan struct{}
// chan to signal vbucket ownership give up routine to stop.
// Will be triggered in case of stop rebalance operation
stopVbOwnerGiveupCh chan struct{}
// chan to signal vbucket ownership takeover routine to exit.
// Will be triggered in case of stop rebalance operation
stopVbOwnerTakeoverCh chan struct{}
debugTCPPort string
tcpPort string
signalDebuggerConnectedCh chan struct{}
// Tracks DCP Opcodes processed per consumer
dcpMessagesProcessed map[mcd.CommandCode]uint64 // Access controlled by default lock
// Tracks V8 Opcodes processed per consumer
v8WorkerMessagesProcessed map[string]uint64 // Access controlled by default lock
timerMessagesProcessed uint64
timerMessagesProcessedPSec int
// capture dcp operation stats, granularity of these stats depend on statsTickInterval
dcpOpsProcessed uint64
opsTimestamp time.Time
dcpOpsProcessedPSec int
sync.RWMutex
vbProcessingStats vbStats
checkpointTicker *time.Ticker
restartVbDcpStreamTicker *time.Ticker
statsTicker *time.Ticker
}
type timerProcessingWorker struct {
id int
c *Consumer
signalProcessTimerPlasmaCloseCh chan uint16
stopCh chan struct{}
timerProcessingTicker *time.Ticker
vbsAssigned []uint16
}
type byTimerEntry struct {
DocID string
CallbackFn string
}
// For V8 worker spawned for debugging purpose
type debugClient struct {
appName string
consumerHandle *Consumer
cmd *exec.Cmd
eventingPort string
osPid int
debugTCPPort string
workerName string
}
type client struct {
appName string
consumerHandle *Consumer
cmd *exec.Cmd
eventingPort string
osPid int
tcpPort string
workerName string
}
type vbStats map[uint16]*vbStat
type vbStat struct {
stats map[string]interface{}
sync.RWMutex
}
type plasmaStoreMsg struct {
vb uint16
store *plasma.Plasma
}
type vbucketKVBlob struct {
AssignedWorker string `json:"assigned_worker"`
CurrentVBOwner string `json:"current_vb_owner"`
DCPStreamStatus string `json:"dcp_stream_status"`
LastCheckpointTime string `json:"last_checkpoint_time"`
LastSeqNoProcessed uint64 `json:"last_processed_seq_no"`
NodeUUID string `json:"node_uuid"`
OwnershipHistory []OwnershipEntry `json:"ownership_history"`
PreviousAssignedWorker string `json:"previous_assigned_worker"`
PreviousNodeUUID string `json:"previous_node_uuid"`
PreviousEventingDir string `json:"previous_node_eventing_dir"`
PreviousVBOwner string `json:"previous_vb_owner"`
VBId uint16 `json:"vb_id"`
VBuuid uint64 `json:"vb_uuid"`
AssignedDocIDTimerWorker string `json:"doc_id_timer_processing_worker"`
CurrentProcessedDocIDTimer string `json:"currently_processed_doc_id_timer"`
CurrentProcessedNonDocTimer string `json:"currently_processed_non_doc_timer"`
LastProcessedDocIDTimerEvent string `json:"last_processed_doc_id_timer_event"`
NextDocIDTimerToProcess string `json:"next_doc_id_timer_to_process"`
NextNonDocTimerToProcess string `json:"next_non_doc_timer_to_process"`
PlasmaPersistedSeqNo uint64 `json:"plasma_last_persisted_seq_no"`
}
// OwnershipEntry captures the state of vbucket within the metadata blob
type OwnershipEntry struct {
AssignedWorker string `json:"assigned_worker"`
CurrentVBOwner string `json:"current_vb_owner"`
Operation string `json:"operation"`
Timestamp string `json:"timestamp"`
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.