text
stringlengths 11
4.05M
|
|---|
package database
type TbGwInfo struct {
ID uint
IPAddr string
MacAddr string
SocketPort uint
GatewayID uint
FreqID uint
CenterFreq uint
Addr string `gorm:"column:Addr"`
FanAmount uint
}
func (TbGwInfo) TableName() string {
return "tb_gw_info"
}
|
package types
// DONTCOVER
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
gogotypes "github.com/gogo/protobuf/types"
"github.com/irisnet/irismod/modules/nft/exported"
)
var (
amino = codec.NewLegacyAmino()
ModuleCdc = codec.NewAminoCodec(amino)
)
func init() {
RegisterLegacyAminoCodec(amino)
cryptocodec.RegisterCrypto(amino)
amino.Seal()
}
// RegisterLegacyAminoCodec concrete types on codec
func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
cdc.RegisterConcrete(&MsgIssueDenom{}, "irismod/nft/MsgIssueDenom", nil)
cdc.RegisterConcrete(&MsgTransferNFT{}, "irismod/nft/MsgTransferNFT", nil)
cdc.RegisterConcrete(&MsgEditNFT{}, "irismod/nft/MsgEditNFT", nil)
cdc.RegisterConcrete(&MsgMintNFT{}, "irismod/nft/MsgMintNFT", nil)
cdc.RegisterConcrete(&MsgBurnNFT{}, "irismod/nft/MsgBurnNFT", nil)
cdc.RegisterInterface((*exported.NFT)(nil), nil)
cdc.RegisterConcrete(&BaseNFT{}, "irismod/nft/BaseNFT", nil)
}
func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterImplementations((*sdk.Msg)(nil),
&MsgIssueDenom{},
&MsgTransferNFT{},
&MsgEditNFT{},
&MsgMintNFT{},
&MsgBurnNFT{},
)
registry.RegisterImplementations((*exported.NFT)(nil),
&BaseNFT{},
)
}
// return supply protobuf code
func MustMarshalSupply(cdc codec.Marshaler, supply uint64) []byte {
supplyWrap := gogotypes.UInt64Value{Value: supply}
return cdc.MustMarshalBinaryBare(&supplyWrap)
}
// return th supply
func MustUnMarshalSupply(cdc codec.Marshaler, value []byte) uint64 {
var supplyWrap gogotypes.UInt64Value
cdc.MustUnmarshalBinaryBare(value, &supplyWrap)
return supplyWrap.Value
}
// return the tokenID protobuf code
func MustMarshalTokenID(cdc codec.Marshaler, tokenID string) []byte {
tokenIDWrap := gogotypes.StringValue{Value: tokenID}
return cdc.MustMarshalBinaryBare(&tokenIDWrap)
}
// return th tokenID
func MustUnMarshalTokenID(cdc codec.Marshaler, value []byte) string {
var tokenIDWrap gogotypes.StringValue
cdc.MustUnmarshalBinaryBare(value, &tokenIDWrap)
return tokenIDWrap.Value
}
|
package 动态规划
// ------------------------------ 暴力搜索 ------------------------------
// 执行用时:1072 ms, 在所有 Go 提交中击败了 8.09% 的用户
// 内存消耗:2.1 MB, 在所有 Go 提交中击败了 100.00% 的用户
func isInterleave(s1 string, s2 string, s3 string) bool {
if len(s3) != len(s1)+len(s2) {
return false
}
if len(s3) == 0 {
return true
}
if len(s1) == 0 {
return s2 == s3
}
if len(s2) == 0 {
return s1 == s3
}
switch {
case s1[0] == s3[0] && s2[0] == s3[0]:
return isInterleave(s1[1:], s2, s3[1:]) || isInterleave(s1, s2[1:], s3[1:])
case s1[0] == s3[0]:
return isInterleave(s1[1:], s2, s3[1:])
case s2[0] == s3[0]:
return isInterleave(s1, s2[1:], s3[1:])
}
return false
}
// ------------------------------ 动态规划 ------------------------------
// 执行用时:0 ms, 在所有 Go 提交中击败了 100.00% 的用户
// 内存消耗:2.1 MB, 在所有 Go 提交中击败了 100.00% 的用户
//
// 时间复杂度: O(n^2)
func isInterleave(s1 string, s2 string, s3 string) bool {
if len(s3) != len(s1)+len(s2) {
return false
}
canForm := get2DSlice(len(s1)+1, len(s2)+1) // 表示 s1[:i] 与 s2[:t] 能否交错组成 s3[:i+t]
canForm[0][0] = true
for i := 1; i <= len(s1); i++ {
canForm[i][0] = s1[i-1] == s3[i-1] && canForm[i-1][0]
}
for t := 1; t <= len(s2); t++ {
canForm[0][t] = s2[t-1] == s3[t-1] && canForm[0][t-1]
}
for i := 1; i <= len(s1); i++ {
for t := 1; t <= len(s2); t++ {
canForm[i][t] = s1[i-1] == s3[i+t-1] && canForm[i-1][t] || s2[t-1] == s3[i+t-1] && canForm[i][t-1]
// 也可以像下面这样写:
// switch {
// case s1[i-1] == s3[i+t-1] && s2[t-1] == s3[i+t-1]:
// canForm[i][t] = canForm[i-1][t] || canForm[i][t-1]
// case s1[i-1] == s3[i+t-1]:
// canForm[i][t] = canForm[i-1][t]
// case s2[t-1] == s3[i+t-1]:
// canForm[i][t] = canForm[i][t-1]
// }
}
}
return canForm[len(s1)][len(s2)]
}
func get2DSlice(rows, column int) [][]bool {
slice := make([][]bool, rows)
for i := 0; i < len(slice); i++ {
slice[i] = make([]bool, column)
}
return slice
}
/*
题目链接: https://leetcode-cn.com/problems/interleaving-string/
*/
|
//source: https://doc.qt.io/qt-5/qtcharts-audio-example.html
package main
import (
"os"
"github.com/therecipe/qt/widgets"
)
func main() {
var app = widgets.NewQApplication(len(os.Args), os.Args)
var w = NewWidget(nil, 0)
w.Show()
app.Exec()
}
|
/*
You are given a dictionary of names and the amount of points they have. Return a dictionary with the same names, but instead of points, return what prize they get.
"Gold", "Silver", or "Bronze" to the 1st, 2nd and 3rd place respectively. For all the other names, return "Participation" for the prize.
Examples
awardPrizes({
"Joshua" : 45,
"Alex" : 39,
"Eric" : 43
}) ➞ {
"Joshua" : "Gold",
"Alex" : "Bronze",
"Eric" : "Silver"
}
awardPrizes({
"Person A" : 1,
"Person B" : 2,
"Person C" : 3,
"Person D" : 4,
"Person E" : 102
}) ➞ {
"Person A" : "Participation",
"Person B" : "Participation",
"Person C" : "Bronze",
"Person D" : "Silver",
"Person E" : "Gold"
}
awardPrizes({
"Mario" : 99,
"Luigi" : 100,
"Yoshi" : 299,
"Toad" : 2
}) ➞ {
"Mario" : "Bronze",
"Luigi" : "Silver",
"Yoshi" : "Gold",
"Toad" : "Participation"
}
Notes
There will always be at least three participants to recieve awards.
No number of points will be the same amongst participants.
*/
package main
import (
"fmt"
"reflect"
"sort"
)
func main() {
test(
map[string]int{
"Joshua": 45,
"Alex": 39,
"Eric": 43,
},
map[string]string{
"Joshua": "Gold",
"Alex": "Bronze",
"Eric": "Silver",
},
)
test(
map[string]int{
"Person A": 1,
"Person B": 2,
"Person C": 3,
"Person D": 4,
"Person E": 102,
},
map[string]string{
"Person A": "Participation",
"Person B": "Participation",
"Person C": "Bronze",
"Person D": "Silver",
"Person E": "Gold",
},
)
test(
map[string]int{
"Mario": 99,
"Luigi": 100,
"Yoshi": 299,
"Toad": 2,
},
map[string]string{
"Mario": "Bronze",
"Luigi": "Silver",
"Yoshi": "Gold",
"Toad": "Participation",
},
)
}
func test(m map[string]int, r map[string]string) {
p := award(m)
fmt.Println(p)
assert(reflect.DeepEqual(p, r))
}
func assert(x bool) {
if !x {
panic("assertion failed")
}
}
func award(m map[string]int) map[string]string {
var p []person
for k, v := range m {
p = append(p, person{k, v})
}
sort.Slice(p, func(i, j int) bool {
return p[i].score < p[j].score
})
r := make(map[string]string)
for i, q := range p {
k := q.name
switch n := len(p); {
case i+1 >= n:
r[k] = "Gold"
case i+2 >= n:
r[k] = "Silver"
case i+3 >= n:
r[k] = "Bronze"
default:
r[k] = "Participation"
}
}
return r
}
type person struct {
name string
score int
}
|
package v3
type Album struct {
Id string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Datetime int64 `json:"datetime"`
Cover string `json:"cover"`
CoverWidth int64 `json:"cover_width"`
CoverHeight int64 `json:"cover_height"`
AccountUrl string `json:"account_url"`
AccountId int `json:"account_id"`
Privacy string `json:"privacy"`
Layout string `json:"layout"`
Views int64 `json:"views"`
Link string `json:"link"`
Favorite bool `json:"favorite"`
Nsfw bool `json:"nsfw"`
Section string `json:"section"`
Order int64 `json:"order"`
Deletehash string `json:"deletehash"`
ImagesCount int64 `json:"images_count"`
Images []Image `json:"images"`
InGallery bool `json:"in_gallery"`
}
type AlbumResponse struct {
Data Album
Status int
Success bool
}
|
package main
import (
"log"
"net"
)
func main() {
var conns []net.Conn
for i := 0; i < 200; i++ {
c, err := net.Dial("tcp", "127.0.0.1:2020")
if err != nil {
log.Fatalf("dial error: %v", err)
}
conns = append(conns, c)
}
select {}
}
|
package journey
import (
"../train"
"time"
)
type Journey struct {
name string
route Route
date time.Time
train train.Train
places map[string][][]int
}
|
package model
import "time"
type PlayerInfo struct {
Id int `json:"id"`
Name string `json:"name"`
Team string `json:"team"`
Nationality string `json:"nationality"`
Height string `json:"height"`
Born string `json:"born"`
Shirt_number string `json:"shirt_number"`
}
type Player struct {
Id int `json:"id"`
Name string `json:"name"`
}
type PlayerNation struct {
Id int `json:"id"`
Name string `json:"name"`
Nationality string `json:"nationality"`
}
type TeamInfo struct {
Id int `json:"id"`
Name string `json:"name"`
Coach string `json:"coach"`
President string `json:"president"`
Website string `json:"website"`
}
type Team struct {
Id int `json:"id"`
Name string `json:"name"`
}
type TimeOfCreation struct {
Id string `json:"id"`
Date time.Time `json:"date"`
}
type Statistic struct {
Country_name string `json:"country_name"`
Number_of_players int `json:"number_of_players"`
}
//type ResponseData struct {
// Page int `json:"page"`
// PageSize int `json:"page_size"`
// TotalItems int `json:"total_items"`
// OrderBy string `json:"order_by"`
// OrderDirection string `json:"order_direction"`
// FilterBy string `json:"filter_by"`
// FilterValue string `json:"filter_value"`
// FilterOperator string `json:"filter_operator"`
// Data []Team `json:"data"`
//}
type ResponseData struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalItems int `json:"total_items"`
OrderBy string `json:"order_by"`
OrderDirection string `json:"order_direction"`
FilterBy string `json:"filter_by"`
FilterValue string `json:"filter_value"`
FilterOperator string `json:"filter_operator"`
Data interface{} `json:"data"`
}
type UrlParams struct {
Page int
PageSize int
OrderBy string
OrderDirection string
FilterBy string
FilterValue string
FilterOperator string
}
|
/*
Copyright © 2020 Denis Rendler <connect@rendler.me>
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 webapp
import (
"context"
"crypto/tls"
"errors"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/koderhut/safenotes/internal/config"
)
// HttpsServer A representation of a HTTP server that routes all traffic to the HTTPS server
// serving the API and possibly the static app
type HttpsServer struct {
Server
srv []*http.Server
}
func newHttpsServer(cfg config.ServerParams, router *mux.Router) (Server, error) {
// build a HTTP server that would redirect to HTTPS and that is all
httpSrv := &http.Server{
Addr: cfg.ListeningAddr(),
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: http.RedirectHandler(cfg.Https.RedirectTo, http.StatusMovedPermanently),
}
// configure the HTTPS server
httpsSrv := &http.Server{
Addr: cfg.HTTPSListeningAddr(),
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: router,
TLSConfig: prepareTlS(cfg.Https),
}
https := &HttpsServer{
srv: []*http.Server{httpSrv, httpsSrv},
}
return https, nil
}
func (https HttpsServer) ListenAndServe() error {
httpSrv, httpsSrv := https.srv[0], https.srv[1]
// Run our server in a goroutine so that it doesn't block.
go func() {
err := httpSrv.ListenAndServe()
if err != nil && err.Error() != "http: Server closed" {
log.Println(err)
os.Exit(128)
}
}()
// Run our server in a goroutine so that it doesn't block.
go func() {
err := httpsSrv.ListenAndServeTLS("", "")
if err != nil && err.Error() != "http: Server closed" {
log.Println(err)
os.Exit(128)
}
}()
return nil
}
func (https HttpsServer) Shutdown(ctx context.Context) error {
var errCollector []string
var err error
isError := false
for _, srv := range https.srv {
log.Printf("Shutting down server: [%s]", srv.Addr)
err = srv.Shutdown(ctx)
if err != nil {
errCollector = append(errCollector, err.Error())
isError = true
}
}
if isError {
return errors.New(strings.Join(errCollector, "\n"))
}
return nil
}
// Get a list of IP:Port that the servers have registered
func (https HttpsServer) GetListeningAddr() string {
var addrs []string
for _, srv := range https.srv {
addrs = append(addrs, srv.Addr)
}
return strings.Join(addrs, ",")
}
// prepareTLS config for the HTTPS server
func prepareTlS(cfg config.Https) *tls.Config {
crt, err := ioutil.ReadFile(cfg.Cert)
if err != nil {
log.Fatal(err)
}
key, err := ioutil.ReadFile(cfg.CertKey)
if err != nil {
log.Fatal(err)
}
cert, err := tls.X509KeyPair(crt, key)
if err != nil {
log.Fatal(err)
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: cfg.ServerName,
}
}
|
package tarot
type Table struct {
Scores [2]float32 `json:"scores"`
Cards [NB_PLAYERS]Card `json:"cards"`
PlayerTurn int `json:"playerTurn"`
FirstPlayer int `json:"firstPlayer"`
TrickNb int `json:"trickNb"`
IsTaker [NB_PLAYERS]int `json:"isTaker"`
HistoryCards [NB_CARDS_PER_PLAYER][NB_PLAYERS]Card
HistoryFirstPlayer [NB_CARDS_PER_PLAYER]int
}
func (t *Table) checkPlayerTurn(i int) bool {
return t.PlayerTurn == i
}
func (t *Table) playCard(c Card, i int) {
t.Cards[i] = c
t.HistoryCards[t.TrickNb][i] = c
t.HistoryFirstPlayer[t.TrickNb] = t.FirstPlayer
t.PlayerTurn = (t.PlayerTurn + 1) % NB_PLAYERS
// Check end of turn
if t.PlayerTurn != t.FirstPlayer {
return
}
t.endRound()
}
func (t *Table) endRound() {
var trickWinner int
var trickScore float32
// Select trick winner
trickWinner = t.selectTrickWinner()
// Update scores
trickScore = t.trickScore()
t.Scores[t.IsTaker[trickWinner]] += trickScore
excusePlayed, playerExcuse := t.excusePlayer()
if excusePlayed {
t.Scores[t.IsTaker[playerExcuse]] += 4.5
}
// Remove cards on table
nilCard := Card{Color: 0, Number: 0}
for i := range t.Cards {
t.Cards[i] = nilCard
}
// Select new first player
t.FirstPlayer = trickWinner
t.PlayerTurn = trickWinner
t.TrickNb++
}
func (t *Table) selectTrickWinner() int {
trickColor := t.Cards[t.FirstPlayer].Color
trickWinner := 0
trickBestCard := t.Cards[0]
for i := 1; i < NB_PLAYERS; i++ {
if compareCards(t.Cards[i], trickBestCard, trickColor) {
trickWinner = i
trickBestCard = t.Cards[i]
}
}
return trickWinner
}
func (t *Table) trickScore() float32 {
var score float32 = 0
for _, c := range t.Cards {
score += c.point()
}
return score
}
func (t *Table) excusePlayer() (excusePlayed bool, excusePlayer int) {
excusePlayed = false
excusePlayer = 0
for i, c := range t.Cards {
if c.Color == EXCUSE {
excusePlayed = true
excusePlayer = i
}
}
return excusePlayed, excusePlayer
}
|
package main
import "fmt"
// 392. 判断子序列
// 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
// 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
// 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
// 后续挑战 :
// 如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
// https://leetcode-cn.com/problems/is-subsequence/
func main() {
// fmt.Println(isSubsequence("abc", "ahbgdc")) // true
// fmt.Println(isSubsequence("axc", "ahbgdc")) // false
fmt.Println(multiSubsequence("abc", "ahbgdc")) // true
}
// 法一:暴力查找
func isSubsequence(s string, t string) bool {
if s == "" {
return true
}
si := 0
for i := 0; i < len(t) && si < len(s); i++ {
if s[si] == t[i] {
si++
}
}
return si == len(s)
}
// 法二:map+二分查找
// map下标为a-z,value为对应字母在t中的索引
// 遍历s,查找比上一个字符下标更大的下标
// 后续挑战:对 t 做预处理
// 这也是原题的动态规划解法
// dp[n][26]表示在t[i]位置,下一个[a-z]的字符位置(不含t[i])
func multiSubsequence(s string, t string) bool {
if s == "" {
return true
}
t = " " + t // 为了预处理第一个字符
dp := make([][]int, len(t))
for k := range dp {
dp[k] = make([]int, 26)
}
var l byte
for l = 'a'; l <= 'z'; l++ {
index := -1
for j := len(t) - 1; j >= 0; j-- {
dp[j][l-'a'] = index // init
if t[j] == l {
index = j
}
}
}
si := 0 // 待匹配字符串下标
for si < len(s) {
si = dp[si][s[si]-'a']
if si == -1 {
return false
}
}
return true
}
|
package endpoints
import (
"context"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/go-kit/kit/endpoint"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/sumelms/microservice-course/internal/course/domain"
)
type findSubscriptionRequest struct {
UUID uuid.UUID `json:"uuid"`
}
type findSubscriptionResponse struct {
UUID uuid.UUID `json:"uuid"`
UserID uuid.UUID `json:"user_id"`
CourseID uuid.UUID `json:"course_id"`
MatrixID *uuid.UUID `json:"matrix_id,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func NewFindSubscriptionHandler(s domain.ServiceInterface, opts ...kithttp.ServerOption) *kithttp.Server {
return kithttp.NewServer(
makeFindSubscriptionEndpoint(s),
decodeFindSubscriptionRequest,
encodeFindSubscriptionResponse,
opts...,
)
}
func makeFindSubscriptionEndpoint(s domain.ServiceInterface) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req, ok := request.(findSubscriptionRequest)
if !ok {
return nil, fmt.Errorf("invalid argument")
}
sub, err := s.Subscription(ctx, req.UUID)
if err != nil {
return nil, err
}
return &findSubscriptionResponse{
UUID: sub.UUID,
UserID: sub.UserID,
CourseID: sub.CourseID,
MatrixID: sub.MatrixID,
ExpiresAt: sub.ExpiresAt,
CreatedAt: sub.CreatedAt,
UpdatedAt: sub.UpdatedAt,
}, nil
}
}
func decodeFindSubscriptionRequest(_ context.Context, r *http.Request) (interface{}, error) {
vars := mux.Vars(r)
id, ok := vars["uuid"]
if !ok {
return nil, fmt.Errorf("invalid argument")
}
uid := uuid.MustParse(id)
return findSubscriptionRequest{UUID: uid}, nil
}
func encodeFindSubscriptionResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
return kithttp.EncodeJSONResponse(ctx, w, response)
}
|
package main
import (
"fmt"
authnpb "istio.io/api/authentication/v1alpha1"
betapb "istio.io/api/security/v1beta1"
commonpb "istio.io/api/type/v1beta1"
corev1 "k8s.io/api/core/v1"
)
type mTLSMode int
// Unset, Strict and Permissive for the mTLS mode.
const (
Unset mTLSMode = 0
Strict mTLSMode = 1
Permissive mTLSMode = 2
)
// ResultSummary includes the conversion summary.
type ResultSummary struct {
errors []string
}
func (r *ResultSummary) addError(err string) {
r.errors = append(r.errors, err)
}
// Converter includes general mesh wide settings.
type Converter struct {
RootNamespace string
Service *ServiceStore
}
// ServiceStore represents all services in the cluster.
type ServiceStore struct {
Services map[string]*corev1.Service
}
func newConverter(rootNamespace string, svcList *corev1.ServiceList) *Converter {
services := map[string]*corev1.Service{}
if svcList != nil {
for _, svc := range svcList.Items {
svc := svc
services[svc.Namespace+"."+svc.Name] = &svc
}
}
return &Converter{
RootNamespace: rootNamespace,
Service: &ServiceStore{Services: services},
}
}
func (ss *ServiceStore) serviceToSelector(name, namespace string) (*commonpb.WorkloadSelector, error) {
service := namespace + "." + name
if svc, found := ss.Services[service]; found {
return &commonpb.WorkloadSelector{MatchLabels: svc.Spec.Selector}, nil
}
return nil, fmt.Errorf("could not find service %s", service)
}
func (ss *ServiceStore) svcPortToWorkloadPort(name, namespace string, svcPort *authnpb.PortSelector) (uint32, error) {
service := namespace + "." + name
if svc, found := ss.Services[service]; found {
for _, port := range svc.Spec.Ports {
if (svcPort.GetName() != "" && port.Name == svcPort.GetName()) || (svcPort.GetNumber() != 0 && uint32(port.Port) == svcPort.GetNumber()) {
if port.TargetPort.IntVal == 0 {
return uint32(port.Port), nil
}
return uint32(port.TargetPort.IntVal), nil
}
}
}
return 0, fmt.Errorf("could not find port %v for service %s", svcPort, service)
}
// InputPolicy includes a v1alpha1 authentication policy.
type InputPolicy struct {
Name string
Namespace string
Policy *authnpb.Policy
}
type outputSelector struct {
Comment string
Name string
Namespace string
Selector *commonpb.WorkloadSelector
Port []uint32
}
// OutputPolicy includes the v1beta1 policy converted from v1alpha authentication policy.
type OutputPolicy struct {
Name string
Namespace string
Comment string // Could be added to the annotation, e.g. security.istio.io/autoConversionResult: "..."
PeerAuthN *betapb.PeerAuthentication
RequestAuthN *betapb.RequestAuthentication
Authz *betapb.AuthorizationPolicy
}
// Convert converts an v1alpha1 authentication policy to the v1beta1 policies.
func (mc *Converter) Convert(input *InputPolicy) ([]*OutputPolicy, *ResultSummary) {
result := &ResultSummary{}
// Convert the service target to a list of workload selectors. Each workload selector is used in a new beta policy.
var outputSelectors []*outputSelector
foundTarget := map[string]struct{}{}
if len(input.Policy.Targets) != 0 {
for _, target := range input.Policy.Targets {
if _, found := foundTarget[target.Name]; found {
result.addError(fmt.Sprintf("found duplicate target %s", target.Name))
} else {
foundTarget[target.Name] = struct{}{}
}
if selector, err := mc.targetToSelector(input, target); err != nil {
result.addError(fmt.Sprintf("failed to convert target (%s) to workload selector: %v", target.Name, err))
} else {
outputSelectors = append(outputSelectors, selector)
}
}
} else {
if input.Namespace == "" {
outputSelectors = []*outputSelector{
{
Comment: "mesh level policy",
Name: input.Name,
Namespace: mc.RootNamespace,
},
}
} else {
outputSelectors = []*outputSelector{
{
Comment: "namespace level policy",
Name: input.Name,
Namespace: input.Namespace,
},
}
}
}
outputPolicies := convertMTLS(outputSelectors, input, result)
outputPolicies = append(outputPolicies, convertJWT(outputSelectors, input, result)...)
return outputPolicies, result
}
func (mc *Converter) targetToSelector(input *InputPolicy, target *authnpb.TargetSelector) (*outputSelector, error) {
selector, err := mc.Service.serviceToSelector(target.Name, input.Namespace)
if err != nil {
return nil, err
}
output := &outputSelector{
Comment: fmt.Sprintf("service %s", target.Name),
Name: fmt.Sprintf("%s-%s", input.Name, target.Name),
Namespace: input.Namespace,
Selector: selector,
}
for _, port := range target.Ports {
workloadPort, err := mc.Service.svcPortToWorkloadPort(target.Name, input.Namespace, port)
if err != nil {
return nil, err
}
output.Port = append(output.Port, workloadPort)
}
return output, nil
}
func convertMTLS(selectors []*outputSelector, input *InputPolicy, result *ResultSummary) []*OutputPolicy {
mode := betapb.PeerAuthentication_MutualTLS_PERMISSIVE
switch extractMTLS(input, result) {
case Unset, Permissive:
// Do not use DISABLE mode, it seems not working with autoMTLS and requires an extra DestinationRule.
mode = betapb.PeerAuthentication_MutualTLS_PERMISSIVE
case Strict:
mode = betapb.PeerAuthentication_MutualTLS_STRICT
}
var output []*OutputPolicy
for _, selector := range selectors {
peerAuthn := &betapb.PeerAuthentication{
Selector: selector.Selector,
}
if len(selector.Port) != 0 {
peerAuthn.PortLevelMtls = map[uint32]*betapb.PeerAuthentication_MutualTLS{}
for _, port := range selector.Port {
peerAuthn.PortLevelMtls[port] = &betapb.PeerAuthentication_MutualTLS{Mode: mode}
}
} else {
peerAuthn.Mtls = &betapb.PeerAuthentication_MutualTLS{
Mode: mode,
}
}
output = append(output, &OutputPolicy{
Name: selector.Name,
Namespace: selector.Namespace,
Comment: fmt.Sprintf("converted from alpha authentication policy %s/%s, %s", input.Namespace, input.Name, selector.Comment),
PeerAuthN: peerAuthn,
})
}
return output
}
func convertJWT(selectors []*outputSelector, input *InputPolicy, result *ResultSummary) []*OutputPolicy {
if len(input.Policy.Origins) == 0 {
return nil
}
var output []*OutputPolicy
for _, selector := range selectors {
// Create a single request authentication policy for all JWT issuers.
requestAuthn := &betapb.RequestAuthentication{
Selector: selector.Selector,
}
for _, origin := range input.Policy.Origins {
if origin.Jwt == nil {
continue
}
jwt := origin.Jwt
jwtRule := &betapb.JWTRule{
Issuer: jwt.Issuer,
Audiences: jwt.Audiences,
JwksUri: jwt.JwksUri,
Jwks: jwt.Jwks,
FromParams: jwt.JwtParams,
ForwardOriginalToken: true,
}
for _, header := range jwt.JwtHeaders {
jwtRule.FromHeaders = append(jwtRule.FromHeaders, &betapb.JWTHeader{Name: header})
}
requestAuthn.JwtRules = append(requestAuthn.JwtRules, jwtRule)
// Check some unsupported cases.
if len(jwt.TriggerRules) > 0 {
if len(input.Policy.Origins) > 1 {
result.addError("triggerRule is not supported with multiple JWT issuer by the tool, please convert manually")
}
for _, rule := range jwt.TriggerRules {
for _, path := range rule.IncludedPaths {
if path.GetRegex() != "" {
result.addError(fmt.Sprintf("triggerRule.regex (%q) is not supported in beta policy", path.GetRegex()))
}
}
for _, path := range rule.ExcludedPaths {
if path.GetRegex() != "" {
result.addError(fmt.Sprintf("triggerRule.regex (%q) is not supported in beta policy", path.GetRegex()))
}
}
}
}
}
// Create an authorization policy if the JWT authentication is required (not optional).
var authzPolicy *betapb.AuthorizationPolicy
if !input.Policy.OriginIsOptional {
authzPolicy = &betapb.AuthorizationPolicy{
Selector: selector.Selector,
Action: betapb.AuthorizationPolicy_DENY, // Use DENY action with notRequestPrincipal to require JWT authentication.
}
newRule := func(paths, notPaths []string) *betapb.Rule {
ret := &betapb.Rule{
From: []*betapb.Rule_From{
{
Source: &betapb.Source{
NotRequestPrincipals: []string{"*"},
},
},
},
}
if len(paths) == 0 && len(notPaths) == 0 && len(selector.Port) == 0 {
// Return to avoid generating empty operation.
return ret
}
ret.To = []*betapb.Rule_To{{Operation: &betapb.Operation{
Paths: paths,
NotPaths: notPaths,
Ports: toStr(selector.Port),
}}}
return ret
}
if len(input.Policy.Origins) == 1 && len(input.Policy.Origins[0].GetJwt().GetTriggerRules()) > 0 {
// Support the trigger rule if there is only 1 JWT issuer.
for _, trigger := range input.Policy.Origins[0].GetJwt().GetTriggerRules() {
extractPaths := func(pathMatchers []*authnpb.StringMatch) []string {
if len(pathMatchers) == 0 {
return nil
}
var ret []string
for _, path := range pathMatchers {
if path.GetExact() != "" {
ret = append(ret, path.GetExact())
} else if path.GetPrefix() != "" {
ret = append(ret, path.GetPrefix()+"*")
} else if path.GetSuffix() != "" {
ret = append(ret, "*"+path.GetSuffix())
} else {
return nil
}
}
return ret
}
includePaths := extractPaths(trigger.IncludedPaths)
excludePaths := extractPaths(trigger.ExcludedPaths)
// Each trigger rule is translated to a separate authz rule.
authzPolicy.Rules = append(authzPolicy.Rules, newRule(includePaths, excludePaths))
}
} else {
// Only need a single authz rule if there is no trigger rule defined.
authzPolicy.Rules = []*betapb.Rule{newRule(nil, nil)}
}
}
output = append(output, &OutputPolicy{
Name: selector.Name,
Namespace: selector.Namespace,
Comment: fmt.Sprintf("converted from alpha authentication policy %s/%s, %s", input.Namespace, input.Name, selector.Comment),
RequestAuthN: requestAuthn,
Authz: authzPolicy,
})
}
return output
}
func extractMTLS(input *InputPolicy, result *ResultSummary) mTLSMode {
if len(input.Policy.Peers) == 0 {
return Unset
}
peerMethod := input.Policy.Peers[0]
if peerMethod.GetJwt() != nil {
result.addError(fmt.Sprintf("JWT is never supported in peer method"))
} else if peerMethod.GetMtls() != nil {
switch peerMethod.GetMtls().Mode {
case authnpb.MutualTls_PERMISSIVE:
return Permissive
case authnpb.MutualTls_STRICT:
return Strict
default:
result.addError(fmt.Sprintf("found unsupported mTLS mode %s", peerMethod.GetMtls().Mode))
}
} else {
result.addError(fmt.Sprintf("Neither mTLS nor JWT peer method specified"))
}
return Unset
}
func toStr(ports []uint32) []string {
var ret []string
for _, p := range ports {
ret = append(ret, fmt.Sprintf("%d", p))
}
return ret
}
|
// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kvtest
import (
"testing"
"github.com/pingcap/tidb/testkit"
"github.com/stretchr/testify/require"
)
func TestDropStatsFromKV(t *testing.T) {
store := testkit.CreateMockStore(t)
tk := testkit.NewTestKit(t, store)
tk.MustExec("use test")
tk.MustExec("create table t (c1 varchar(20), c2 varchar(20))")
tk.MustExec(`insert into t values("1","1"),("2","2"),("3","3"),("4","4")`)
tk.MustExec("insert into t select * from t")
tk.MustExec("insert into t select * from t")
tk.MustExec("analyze table t with 2 topn")
tblID := tk.MustQuery(`select tidb_table_id from information_schema.tables where table_name = "t" and table_schema = "test"`).Rows()[0][0].(string)
tk.MustQuery("select modify_count, count from mysql.stats_meta where table_id = " + tblID).Check(
testkit.Rows("0 16"))
tk.MustQuery("select hist_id from mysql.stats_histograms where table_id = " + tblID).Check(
testkit.Rows("1", "2"))
ret := tk.MustQuery("select hist_id, bucket_id from mysql.stats_buckets where table_id = " + tblID)
require.True(t, len(ret.Rows()) > 0)
ret = tk.MustQuery("select hist_id from mysql.stats_top_n where table_id = " + tblID)
require.True(t, len(ret.Rows()) > 0)
tk.MustExec("drop stats t")
tk.MustQuery("select modify_count, count from mysql.stats_meta where table_id = " + tblID).Check(
testkit.Rows("0 16"))
tk.MustQuery("select hist_id from mysql.stats_histograms where table_id = " + tblID).Check(
testkit.Rows())
tk.MustQuery("select hist_id, bucket_id from mysql.stats_buckets where table_id = " + tblID).Check(
testkit.Rows())
tk.MustQuery("select hist_id from mysql.stats_top_n where table_id = " + tblID).Check(
testkit.Rows())
}
|
/* nighthawk.nhstruct.registry.go
* author: roshan maskey <roshanmaskey@gmail.com>
*
* Datastructure for Registry Entry
*/
package nhstruct
type RegistryItem struct {
JobCreated string `xml:"created,attr"`
TlnTime string `json:"TlnTime"`
KeyPath string
Type string
Modified string
ValueName string
Username string
Path string
Text string
ReportedLengthInBytes int
Hive string
SecurityID string
IsKnownKey string
IsWhitelisted bool
IsBlacklisted bool
NHScore int
Tag string
NhComment NHComment `json:"Comment"`
}
|
package cli
import (
"errors"
"fmt"
"github.com/10gen/realm-cli/internal/cloud/atlas"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/local"
"github.com/10gen/realm-cli/internal/terminal"
"github.com/AlecAivazis/survey/v2"
)
// ProjectInputs are the project/app inputs for a command
type ProjectInputs struct {
Project string
App string
Products []string
}
// Filter returns a realm.AppFlter based on the inputs
func (i ProjectInputs) Filter() realm.AppFilter {
return realm.AppFilter{i.Project, i.App, i.Products}
}
// Resolve resolves the necessary inputs that remain unset after flags have been parsed
func (i *ProjectInputs) Resolve(ui terminal.UI, wd string, skipAppPrompt bool) error {
app, appErr := local.LoadAppConfig(wd)
if appErr != nil {
return appErr
}
if i.App == "" {
var appOption string
if app.RootDir != "" {
appOption = app.Option()
} else {
if !skipAppPrompt {
if err := ui.AskOne(&appOption, &survey.Input{Message: "App ID or Name"}); err != nil {
return err
}
}
}
i.App = appOption
}
return nil
}
// ErrAppNotFound is an app not found error
type ErrAppNotFound struct {
App string
}
func (err ErrAppNotFound) Error() string {
errMsg := "failed to find app"
if err.App != "" {
errMsg += fmt.Sprintf(" '%s'", err.App)
}
return errMsg
}
// set of known app input errors
var (
ErrGroupNotFound = errors.New("failed to find group")
)
// ResolveApp will use the provided Realm client to resolve the app specified by the filter
func ResolveApp(ui terminal.UI, client realm.Client, filter realm.AppFilter) (realm.App, error) {
apps, err := client.FindApps(filter)
if err != nil {
return realm.App{}, err
}
switch len(apps) {
case 0:
return realm.App{}, ErrAppNotFound{filter.App}
case 1:
return apps[0], nil
}
appsByOption := make(map[string]realm.App, len(apps))
appOptions := make([]string, len(apps))
for i, app := range apps {
appsByOption[app.Option()] = app
appOptions[i] = app.Option()
}
var selection string
if err := ui.AskOne(&selection, &survey.Select{
Message: "Select App",
Options: appOptions,
}); err != nil {
return realm.App{}, fmt.Errorf("failed to select app: %s", err)
}
return appsByOption[selection], nil
}
// ResolveGroupID will use the provided MongoDB Cloud Atlas client to resolve the user's group id
func ResolveGroupID(ui terminal.UI, client atlas.Client) (string, error) {
groups, groupsErr := client.Groups()
if groupsErr != nil {
return "", groupsErr
}
switch len(groups) {
case 0:
return "", ErrGroupNotFound
case 1:
return groups[0].ID, nil
}
groupIDsByOption := make(map[string]string, len(groups))
groupIDOptions := make([]string, len(groups))
for i, group := range groups {
option := getGroupString(group)
groupIDsByOption[option] = group.ID
groupIDOptions[i] = option
}
var selection string
if err := ui.AskOne(&selection, &survey.Select{
Message: "Atlas Project",
Options: groupIDOptions,
}); err != nil {
return "", fmt.Errorf("failed to select group id: %s", err)
}
return groupIDsByOption[selection], nil
}
func getGroupString(group atlas.Group) string {
return fmt.Sprintf("%s - %s", group.Name, group.ID)
}
|
package sqlite
import (
"database/sql"
"encoding/json"
"time"
"github.com/Tanibox/tania-core/src/growth/decoder"
"github.com/Tanibox/tania-core/src/growth/repository"
"github.com/Tanibox/tania-core/src/helper/structhelper"
"github.com/gofrs/uuid"
)
type CropEventRepositorySqlite struct {
DB *sql.DB
}
func NewCropEventRepositorySqlite(db *sql.DB) repository.CropEventRepository {
return &CropEventRepositorySqlite{DB: db}
}
func (f *CropEventRepositorySqlite) Save(uid uuid.UUID, latestVersion int, events []interface{}) <-chan error {
result := make(chan error)
go func() {
for _, v := range events {
stmt, err := f.DB.Prepare(`INSERT INTO CROP_EVENT (CROP_UID, VERSION, CREATED_DATE, EVENT) VALUES (?, ?, ?, ?)`)
if err != nil {
result <- err
}
latestVersion++
e, err := json.Marshal(decoder.InterfaceWrapper{
Name: structhelper.GetName(v),
Data: v,
})
if err != nil {
result <- err
}
_, err = stmt.Exec(uid, latestVersion, time.Now().Format(time.RFC3339), e)
if err != nil {
result <- err
}
}
result <- nil
close(result)
}()
return result
}
|
package triangle
import (
"testing"
"triangle"
)
func TestValidTriangle(t *testing.T) {
sides := [3]uint16{3, 3, 3}
if !triangle.IsValid(sides) {
t.Fail()
}
}
func TestInvalidTriangle(t *testing.T) {
sides := [3]uint16{5, 10, 25}
if triangle.IsValid(sides) {
t.Fail()
}
}
|
package dao
import (
"log"
. "github.com/gonzaloescobar/prescription/models"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type PrescriptionsDAO struct {
Server string
Database string
}
var db *mgo.Database
const (
COLLECTION = "prescriptions"
)
// Establish a connection to database
func (m *PrescriptionsDAO) Connect() {
session, err := mgo.Dial(m.Server)
if err != nil {
log.Fatal(err)
}
db = session.DB(m.Database)
}
// Find list of prescriptions
func (m *PrescriptionsDAO) FindAll() ([]Prescription, error) {
var prescriptions []Prescription
err := db.C(COLLECTION).Find(bson.M{}).All(&prescriptions)
return prescriptions, err
}
// Find a prescription by its id
func (m *PrescriptionsDAO) FindById(id string) (Prescription, error) {
var prescription Prescription
err := db.C(COLLECTION).FindId(bson.ObjectIdHex(id)).One(&prescription)
return prescription, err
}
// Insert a prescription into database
func (m *PrescriptionsDAO) Insert(prescription Prescription) error {
err := db.C(COLLECTION).Insert(&prescription)
return err
}
// Delete an existing prescription
func (m *PrescriptionsDAO) Delete(prescription Prescription) error {
err := db.C(COLLECTION).Remove(&prescription)
return err
}
// Update an existing prescription
func (m *PrescriptionsDAO) Update(prescription Prescription) error {
err := db.C(COLLECTION).UpdateId(prescription.ID, &prescription)
return err
}
|
package main
import (
"fmt"
)
//闭包是什么?
//闭包是一个函数,这个函数包含了他外部作用域的一个变量
//底层的原理:
//1.函数可以作为返回值
//2.函数内部查找变量的顺序,现在自己内部找,找不到往外层找
// func adder(x int) func(int) int {
// return func(y int) int {
// x += y
// return x
// }
// }
// func main() {
// ret := adder(100)
// ret2 := ret(200)
// fmt.Println(ret2)
// }
//变量f是一个函数并且它引用了其外部作用域中的x变量,此时f就是一个闭包。
//在f的生命周期内,变量x也一直有效。
// func adder2(x int) func(int) int {
// return func(y int) int {
// x += y
// return x
// }
// }
// func main() {
// var f = adder2(10)
// fmt.Println(f(10)) //20
// fmt.Println(f(20)) //40
// fmt.Println(f(30)) //70
// f1 := adder2(20)
// fmt.Println(f1(40)) //60
// fmt.Println(f1(50)) //110
// }
func calc(base int) (func(int) int, func(int) int) {
add := func(i int) int {
base += i
return base
}
sub := func(i int) int {
base -= i
return base
}
return add, sub
}
func main() {
f1, f2 := calc(10)
fmt.Println(f1(1), f2(2)) //11,9
fmt.Println(f1(3), f2(4)) //12,8
fmt.Println(f1(5), f2(6)) //13,7
}
|
package integration_test
import (
"github.com/APTrust/exchange/constants"
"github.com/APTrust/exchange/context"
"github.com/APTrust/exchange/models"
"github.com/APTrust/exchange/network"
"github.com/APTrust/exchange/util"
"github.com/APTrust/exchange/util/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"os"
"path/filepath"
"strings"
"testing"
)
/*
These tests check the results of the integration tests for
the app apt_store. See the ingest_test.sh script in
the scripts folder, which sets up an integration context, runs
the apt_store.
*/
func TestStoreResults(t *testing.T) {
if !testutil.ShouldRunIntegrationTests() {
t.Skip("Skipping integration test. Set ENV var RUN_EXCHANGE_INTEGRATION=true if you want to run them.")
}
// Load config
configFile := filepath.Join("config", "integration.json")
config, err := models.LoadConfigFile(configFile)
require.Nil(t, err)
config.ExpandFilePaths()
_context, err := testutil.GetContext("integration.json")
// Find the log file that apt_store created when it was running
// with the "config/integration.json" config options. We'll read
// that file.
pathToJsonLog := filepath.Join(config.LogDirectory, "apt_store.json")
bagNames := append(testutil.INTEGRATION_GOOD_BAGS, testutil.INTEGRATION_GLACIER_BAGS...)
for _, bagName := range bagNames {
ingestManifest, err := testutil.FindIngestManifestInLog(pathToJsonLog, bagName)
assert.Nil(t, err)
if err != nil {
continue
}
storeTestCommon(t, bagName, ingestManifest, config)
testItemIsInStorage(t, _context, ingestManifest.WorkItemId)
}
}
func storeTestCommon(t *testing.T, bagName string, ingestManifest *models.IngestManifest, config *models.Config) {
// Test some basic object properties
assert.NotEmpty(t, ingestManifest.WorkItemId, "WorkItemId should not be empty for %s", bagName)
assert.NotEmpty(t, ingestManifest.S3Bucket, "S3Bucket should not be empty for %s", bagName)
assert.NotEmpty(t, ingestManifest.S3Key, "S3Key should not be empty for %s", bagName)
assert.NotEmpty(t, ingestManifest.ETag, "ETag should not be empty for %s", bagName)
// Make sure the result has some basic info
assert.True(t, ingestManifest.StoreResult.Attempted,
"StoreResult.Attempted should be true for %s", bagName)
assert.True(t, ingestManifest.StoreResult.AttemptNumber > 0,
"StoreResult.AttemptNumber should be > 0 %s", bagName)
assert.NotEmpty(t, ingestManifest.StoreResult.StartedAt,
"StoreResult.StartedAt should not be empty for %s", bagName)
assert.NotEmpty(t, ingestManifest.StoreResult.FinishedAt,
"StoreResult.FinishedAt should not be empty for %s", bagName)
assert.Empty(t, ingestManifest.StoreResult.Errors,
"StoreResult.Errors should be empty for %s", bagName)
assert.True(t, ingestManifest.StoreResult.Retry,
"StoreResult.Retry should be true for %s", bagName)
// Make sure the GenericFiles include info about where we put them.
for _, gf := range ingestManifest.Object.GenericFiles {
// Test only files that we're SUPPOSED to store.
if !util.HasSavableName(gf.OriginalPath()) && !isSpecialJunkFile(gf) {
continue
}
assert.True(t, strings.HasPrefix(gf.URI, "https://s3.amazonaws.com/"),
"URI missing or invalid for %s", gf.Identifier)
assert.True(t, strings.HasSuffix(gf.URI, gf.IngestUUID),
"URI should end with '%s' for %s", gf.IngestUUID, gf.Identifier)
assert.True(t, gf.URI == gf.IngestStorageURL,
"URI does not match IngestStorageUrl for %s", gf.Identifier)
assert.True(t, strings.HasSuffix(gf.IngestReplicationURL, gf.IngestUUID),
"IngestReplicationURL should end with '%s' for %s", gf.IngestUUID, gf.Identifier)
assert.True(t, strings.Contains(gf.URI, config.PreservationBucket),
"URI does not point to perservation bucket %s for %s",
config.PreservationBucket, gf.Identifier)
assert.True(t, strings.Contains(gf.IngestStorageURL, config.PreservationBucket),
"IngestStorageURL does not point to perservation bucket %s for %s",
config.PreservationBucket, gf.Identifier)
assert.True(t, strings.Contains(gf.IngestReplicationURL, config.ReplicationBucket),
"IngestReplicationURL does not point to replication bucket %s for %s",
config.PreservationBucket, gf.Identifier)
assert.False(t, gf.IngestStoredAt.IsZero())
assert.False(t, gf.IngestReplicatedAt.IsZero())
}
}
// Special test for bug https://www.pivotaltracker.com/story/show/151265762
// We want to make sure we actually did save this special junk file.
func isSpecialJunkFile(gf *models.GenericFile) bool {
return gf.Identifier == "test.edu/example.edu.sample_ds_store_and_empty/data/._DS_StoreTest"
}
func testItemIsInStorage(t *testing.T, _context *context.Context, workItemId int) {
resp := _context.PharosClient.WorkItemGet(workItemId)
require.Nil(t, resp.Error)
workItem := resp.WorkItem()
require.NotNil(t, workItem)
require.NotEmpty(t, workItem.ObjectIdentifier)
resp = _context.PharosClient.IntellectualObjectGet(workItem.ObjectIdentifier, true, false)
require.Nil(t, resp.Error)
obj := resp.IntellectualObject()
region := _context.Config.APTrustS3Region
bucket := _context.Config.PreservationBucket
if obj.StorageOption == constants.StorageGlacierOH {
region = _context.Config.GlacierRegionOH
bucket = _context.Config.GlacierBucketOH
} else if obj.StorageOption == constants.StorageGlacierOR {
region = _context.Config.GlacierRegionOR
bucket = _context.Config.GlacierBucketOR
} else if obj.StorageOption == constants.StorageGlacierVA {
region = _context.Config.GlacierRegionVA
bucket = _context.Config.GlacierBucketVA
}
// s3Head gets metadata about specific objects in S3/Glacier.
s3Head := network.NewS3Head(
os.Getenv("AWS_ACCESS_KEY_ID"),
os.Getenv("AWS_SECRET_ACCESS_KEY"),
region,
bucket)
for _, gf := range obj.GenericFiles {
fileUUID, err := gf.PreservationStorageFileName()
require.Nil(t, err)
// Make sure each item file is present and has the expected
// metadata. s3Head.Response.Metadata is map[string]*string.
s3Head.Head(fileUUID)
require.Empty(t, s3Head.ErrorMessage)
metadata := s3Head.Response.Metadata
require.NotNil(t, metadata, "Missing metadata for %s", gf.Identifier)
storedFile := s3Head.StoredFile()
assert.Equal(t, gf.Size, storedFile.Size)
assert.True(t, strings.HasPrefix(gf.IntellectualObjectIdentifier, storedFile.Institution))
assert.NotEmpty(t, gf.FileFormat, storedFile.ContentType)
assert.True(t, strings.Contains(gf.IntellectualObjectIdentifier, storedFile.BagName))
assert.Equal(t, gf.OriginalPath(), storedFile.PathInBag)
assert.Equal(t, gf.GetChecksumByAlgorithm(constants.AlgMd5).Digest, storedFile.Md5)
assert.Equal(t, gf.GetChecksumByAlgorithm(constants.AlgSha256).Digest, storedFile.Sha256)
}
}
|
package user
import (
"github.com/globalsign/mgo/bson"
)
func (userModel *UserModel) SubUser(uid, subUid bson.ObjectId) (err error) {
c := userModel.GetC()
defer c.Database.Session.Close()
err = userModel.addAttention(uid, subUid)
if err != nil {
return
}
return userModel.addFans(subUid, uid)
}
|
package worker
import (
"testing"
)
func Test_SmtpPing_1(t *testing.T) {
array := [3]string{
"126mx01.mxmail.netease.com:25",
"mx1.qq.com:25",
"163mx01.mxmail.netease.com:25",
}
for _, v := range array {
result := SmtpPing(&v, true)
if result.Error != "" {
t.Error(result.Error)
continue
}
if result.Code != 220 {
t.Errorf("%s response %s, expect 220", v, result.Code)
continue
}
t.Logf("pass check: %s in %f response %d(%s)",
v, result.TimeDur, result.Code, result.Message)
}
}
func Test_SmtpPing_2(t *testing.T) {
addr := "0.0.0.0:22"
result := SmtpPing(&addr, true)
if result.Error == "" {
t.Error(result.TimeDur, result.Code, result.Message)
t.Error("should complain error here")
}
t.Logf("pass error check: %s return %s",
addr, result.Error)
}
|
package filter
import (
"context"
"encoding/json"
"fmt"
"github.com/coreos/etcd/mvcc/mvccpb"
"go.etcd.io/etcd/clientv3"
"gocherry-api-gateway/components/common_enum"
"gocherry-api-gateway/components/etcd_client"
"gocherry-api-gateway/components/http_client"
"gocherry-api-gateway/proxy/enum"
"gocherry-api-gateway/proxy/model"
"math/rand"
"strings"
"sync"
"time"
)
//将url请求到目标ip + url 然后将结果返回
func ProxyRunToServer(proxyContext *ProxyContext, servers *ClientMon) (statusCode int, err string) {
var responseData string
var code int
url := proxyContext.Url.BaseRedirectUrl //转发的地址 不是前段请求的url (有个坑 如果是get请求 前端传了参数 那么接口转发如何处理 将参数组装?)
method := proxyContext.RequestContext.Method()
timeRe := proxyContext.Api.TimeOut * time.Second
server := GetRandServer(proxyContext, servers.ServerList) //1.这里是调服务发现的server ip
//server := GetServers(proxyContext) //2.这里是调普通的server ip 这里好维护些
if server == "" {
return enum.STATUS_CODE_FAILED, "请求服务错误,请检查服务"
}
GetHeaders(proxyContext)
//这是请求的完整url
requestUrl := "http://" + server + url
fmt.Println("start request server api... ", requestUrl)
//根据不同的method发起请求 目前支持post get 其他方法暂时不支持啊 可以自行在后台定义并在这增加方法
switch method {
case "POST":
params := proxyContext.RequestContext.Request().Body //获取post的数据
decoder := json.NewDecoder(params)
var postData map[string]string
// 解析参数 存入map
_ = decoder.Decode(&postData)
responseData, code, err = http_client.Post(requestUrl, postData, timeRe, nil, proxyContext.RequestContext)
if code != enum.STATUS_CODE_OK {
return enum.STATUS_CODE_FAILED, err
}
break
case "GET":
responseData, code, err = http_client.Get(requestUrl, timeRe, nil, proxyContext.RequestContext)
if code != enum.STATUS_CODE_OK {
return enum.STATUS_CODE_FAILED, err
}
break
default:
//不属于这些方法禁止访问
return enum.STATUS_CODE_FAILED, "请求方法不允许"
}
proxyContext.Response = responseData
return enum.STATUS_CODE_OK, ""
}
// 这里不使用服务发现 维护起来相对方便些
// 获取服务对应的全部 服务节点
func GetServers(proxyContext *ProxyContext) string {
var serverList []model.Server
var oneServer model.Server
serverKey := common_enum.ETCD_KEYS_APP_CLUSTER_SERVER_LIST + proxyContext.AppName + "/" + proxyContext.Api.BaseClusterName
list, _ := etcd_client.GetKvPrefix(serverKey)
for _, value := range list.Kvs {
_ = json.Unmarshal([]byte(value.Value), &oneServer)
serverList = append(serverList, oneServer)
}
if len(serverList) == 0 {
return ""
}
key := rand.Intn(len(serverList))
return serverList[key].Ip
}
func GetRandServer(proxyContext *ProxyContext, servers map[string][]string) string {
serverKey := proxyContext.AppName + "|" + proxyContext.Api.BaseClusterName
serverList := servers[serverKey]
randNum := rand.Intn(len(serverList))
i := 0
for _, server := range serverList {
if i == randNum {
return server
}
i = i + 1
}
return ""
}
/**
使用服务发现
*/
type ClientMon struct {
Client *clientv3.Client
ServerList map[string][]string
Lock sync.Mutex
}
// 初始化server端
func (this *ClientMon) NewClientMon() (*ClientMon, error) {
return &ClientMon{
Client: etcd_client.GetClient(),
ServerList: make(map[string][]string),
}, nil
}
func (this *ClientMon) GetService() ([]string, error) {
//_, _ = etcd_client.DelKvPrefix("/keyClusterServerAll/")
key_prefix := common_enum.ETCD_KEYS_APP_CLUSTER_SERVER_LIST
resp, err := this.Client.Get(context.Background(), key_prefix, clientv3.WithPrefix())
if err != nil {
return nil, err
}
addrs := this.extractAddrs(resp)
go this.watcher(key_prefix)
return addrs, nil
}
func (this *ClientMon) extractAddrs(resp *clientv3.GetResponse) []string {
addrs := make([]string, 0)
if resp == nil || resp.Kvs == nil {
return addrs
}
for i := range resp.Kvs {
if v := resp.Kvs[i].Value; v != nil {
this.SetServiceList(string(resp.Kvs[i].Key), string(resp.Kvs[i].Value))
addrs = append(addrs, string(v))
}
}
return addrs
}
// watch负责将监听到的put、delete请求存放到指定list
func (this *ClientMon) watcher(prefix string) {
rch := this.Client.Watch(context.Background(), prefix, clientv3.WithPrefix())
for wresp := range rch {
for _, ev := range wresp.Events {
switch ev.Type {
case mvccpb.PUT:
this.SetServiceList(string(ev.Kv.Value), string(ev.Kv.Value))
case mvccpb.DELETE:
this.DelServiceList(string(ev.Kv.Key), string(ev.Kv.Value))
}
}
}
}
func (this *ClientMon) SetServiceList(key, val string) {
var server model.Server
this.Lock.Lock()
defer this.Lock.Unlock()
_ = json.Unmarshal([]byte(val), &server)
nodesKey := server.AppName + "|" + server.ClusterName
nodesIp := server.Ip
this.ServerList[nodesKey] = append(this.ServerList[nodesKey], nodesIp)
}
func (this *ClientMon) DelServiceList(key string, value string) {
this.Lock.Lock()
defer this.Lock.Unlock()
var newServers []string //新的节点
keys := strings.Split(key, "/")
serverKey := keys[2] + "|" + keys[3]
servers := this.ServerList[serverKey]
for _, node := range servers {
if node != keys[4] {
newServers = append(newServers, node)
}
}
//重新赋值
this.ServerList[serverKey] = newServers
}
/**
判断是否需要设置header到下游接口
*/
func GetHeaders(proxyContext *ProxyContext) ([]string) {
var headers []string
if proxyContext.Api.HeaderForms != "" {
header := strings.Split(proxyContext.Api.HeaderForms, ",")
return header
}
return headers
}
|
package deck
import (
"fmt"
"testing"
)
func ExampleCard() {
fmt.Println(Card{Spade, King})
fmt.Println(Card{Heart, Ace})
fmt.Println(BigJoker)
fmt.Println(LittleJoker)
fmt.Println(Card{Club, Ten})
fmt.Println(Card{Diamond, Six})
// Output:
// ♠K
// ♥A
// BigJoker
// LittleJoker
// ♣10
// ♦6
}
func TestNew(t *testing.T) {
cards := New()
fmt.Println(cards)
cards1 := New(Add(BigJoker, LittleJoker))
fmt.Println(cards1)
cards2 := New(SortRankSuit)
fmt.Println(cards2)
cards3 := New(SortSuitRank)
fmt.Println(cards3)
cards4 := New(Add(BigJoker, LittleJoker), SortRankSuit)
fmt.Println(cards4)
cards5 := New(Add(BigJoker, LittleJoker), SortSuitRank)
fmt.Println(cards5)
cards6 := New(Add(BigJoker, LittleJoker), Sort(less1))
fmt.Println(cards6)
cards7 := New(Add(BigJoker, LittleJoker), Shuffle)
fmt.Println(cards7)
f := func(card Card) bool {
if card.Rank == King {
return true
}
return false
}
cards8 := New(Add(BigJoker, LittleJoker), Filter(f), Shuffle)
fmt.Println(cards8)
cards9 := New(Add(BigJoker, LittleJoker), Multiple(3), Shuffle)
fmt.Println(cards9, len(cards9))
}
|
// Naked return
package main
import (
"fmt"
)
func all(sum ...int) (value int) {
for _, v := range sum {
value += v
}
return
}
func main() {
a := all(1, 2, 3, 4, 5)
fmt.Println(a)
}
|
package gui
import (
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/steelx/go-rpg-cgm/utilz"
)
type ProgressBar struct {
x, y float64
Background *pixel.Sprite
Foreground *pixel.Sprite
foregroundFrames []pixel.Rect
foregroundFrame int
scale float64
foregroundPosition pixel.Vec
foregroundPng pixel.Picture
Value, Maximum, HalfWidth, Width float64
}
func ProgressBarCreate(x, y float64, value, max float64, background, foreground string) ProgressBar {
bgImg, err := utilz.LoadPicture(background)
utilz.PanicIfErr(err)
fgImg, err := utilz.LoadPicture(foreground)
utilz.PanicIfErr(err)
pb := ProgressBar{
x: x,
y: y,
foregroundPng: fgImg,
Background: pixel.NewSprite(bgImg, bgImg.Bounds()),
Foreground: pixel.NewSprite(fgImg, fgImg.Bounds()),
scale: 10,
Value: value,
Maximum: max,
}
// Get UV positions in texture atlas
// A table with name fields: left, top, right, bottom
pb.Width = pb.foregroundPng.Bounds().W()
pb.HalfWidth = pb.Width / 2
pb.foregroundFrames = utilz.LoadAsFrames(fgImg, pb.foregroundWidthBlock(), pb.foregroundPng.Bounds().H())
pb.SetValue(value)
return pb
}
func (pb ProgressBar) foregroundWidthBlock() float64 {
return pb.Width * pb.scale / 100
}
func (pb *ProgressBar) SetMax(maxHealth float64) {
pb.Maximum = maxHealth
}
func (pb *ProgressBar) SetValue(health float64) {
pb.Value = health
pb.setForegroundValue()
}
func (pb *ProgressBar) setForegroundValue() {
pb.foregroundFrame = pb.fallsInWhichPercent(pb.Value)
}
func (pb ProgressBar) fallsInWhichPercent(val float64) int {
maxFramesToShow := val / pb.Maximum * 100
if maxFramesToShow >= 90 {
return 10
}
if maxFramesToShow >= 80 && maxFramesToShow < 90 {
return 9
}
if maxFramesToShow >= 70 && maxFramesToShow < 80 {
return 8
}
if maxFramesToShow >= 60 && maxFramesToShow < 70 {
return 7
}
if maxFramesToShow >= 50 && maxFramesToShow < 60 {
return 6
}
if maxFramesToShow >= 40 && maxFramesToShow < 50 {
return 5
}
if maxFramesToShow >= 30 && maxFramesToShow < 40 {
return 4
}
if maxFramesToShow >= 20 && maxFramesToShow < 30 {
return 3
}
if maxFramesToShow >= 10 && maxFramesToShow < 20 {
return 2
}
if maxFramesToShow >= 0 && maxFramesToShow < 10 {
return 1
}
return 0
}
func (pb *ProgressBar) SetPosition(x, y float64) {
pb.x = x
pb.y = y
}
func (pb ProgressBar) GetPosition() (x, y float64) {
return pb.x, pb.y
}
func (pb ProgressBar) Render(renderer pixel.Target) {
mat := pixel.V(pb.x, pb.y)
if pb.fallsInWhichPercent(pb.Value) < 10 {
pb.Background.Draw(renderer, pixel.IM.Moved(mat))
}
fgMat := mat.Sub(pixel.V(pb.HalfWidth, 0))
scaleFactor := pb.foregroundWidthBlock()
for i := 0; i < pb.foregroundFrame; i++ {
px := pixel.NewSprite(pb.foregroundPng, pb.foregroundFrames[i])
px.Draw(renderer, pixel.IM.Moved(pixel.V(fgMat.X+(float64(i)*scaleFactor)+pb.scale, fgMat.Y)))
}
}
/*
TO MATCH StackInterface below
*/
func (pb ProgressBar) HandleInput(win *pixelgl.Window) {
}
func (pb ProgressBar) Enter() {}
func (pb ProgressBar) Exit() {}
func (pb ProgressBar) Update(dt float64) bool {
return true
}
|
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
"time"
"github.com/howeyc/crc16"
)
type SYNC_TYPE int
const (
SYNC_TYPE_DATA SYNC_TYPE = 0
SYNC_TYPE_HEADER SYNC_TYPE = 1
SYNC_TYPE_CFG1 SYNC_TYPE = 2
SYNC_TYPE_CFG2 SYNC_TYPE = 3
SYNC_TYPE_CFG3 SYNC_TYPE = 5
SYNC_TYPE_CMD SYNC_TYPE = 4
)
type CommonHeader struct {
SYNC uint16
FRAMESIZE uint16
IDCODE uint16
SOC uint32
FRACSEC uint32
}
type Config12Frame struct {
TIME_BASE uint32
NUM_PMU uint16
Entries []*Config12Entry
DATA_RATE uint16
}
type Config12Entry struct {
STN string
IDCODE uint16
FORMAT uint16
PHNMR uint16
ANNMR uint16
DGNMR uint16
PHCHNAM []string
ANCHNAM []string
DGCHNAM []string
PHUNIT []uint32
ANUNIT []uint32
DGUNIT []uint32
FNOM uint16
CFGCNT uint16
}
func ReadConfig12Frame(ch *CommonHeader, r io.Reader) (*Config12Frame, error) {
rv := &Config12Frame{}
subr := io.LimitReader(r, int64(ch.FRAMESIZE)-CommonHeaderLength-2)
err := binary.Read(subr, binary.BigEndian, &rv.TIME_BASE)
if err != nil {
return nil, err
}
err = binary.Read(subr, binary.BigEndian, &rv.NUM_PMU)
if err != nil {
return nil, err
}
for i := 0; i < int(rv.NUM_PMU); i++ {
e := &Config12Entry{}
stn_arr := make([]byte, 16)
_, err := subr.Read(stn_arr)
if err != nil {
return nil, err
}
zeroidx := bytes.IndexByte(stn_arr, 0)
if zeroidx >= 0 {
e.STN = string(bytes.TrimRight(stn_arr[:zeroidx], "\x00 "))
} else {
e.STN = string(bytes.TrimRight(stn_arr, "\x00 "))
}
err = binary.Read(subr, binary.BigEndian, &e.IDCODE)
if err != nil {
return nil, err
}
err = binary.Read(subr, binary.BigEndian, &e.FORMAT)
if err != nil {
return nil, err
}
err = binary.Read(subr, binary.BigEndian, &e.PHNMR)
if err != nil {
return nil, err
}
err = binary.Read(subr, binary.BigEndian, &e.ANNMR)
if err != nil {
return nil, err
}
err = binary.Read(subr, binary.BigEndian, &e.DGNMR)
if err != nil {
return nil, err
}
for phni := 0; phni < int(e.PHNMR); phni++ {
barr := make([]byte, 16)
_, err := subr.Read(barr)
if err != nil {
return nil, err
}
e.PHCHNAM = append(e.PHCHNAM, string(bytes.TrimRight(barr, "\x00 ")))
}
for annmri := 0; annmri < int(e.ANNMR); annmri++ {
barr := make([]byte, 16)
_, err := subr.Read(barr)
if err != nil {
return nil, err
}
e.ANCHNAM = append(e.ANCHNAM, string(bytes.TrimRight(barr, "\x00 ")))
}
for dgnmri := 0; dgnmri < int(e.DGNMR); dgnmri++ {
for bit := 0; bit < 16; bit++ {
barr := make([]byte, 16)
_, err := subr.Read(barr)
if err != nil {
return nil, err
}
e.DGCHNAM = append(e.DGCHNAM, string(bytes.TrimRight(barr, "\x00 ")))
}
}
for phni := 0; phni < int(e.PHNMR); phni++ {
var unit uint32
err = binary.Read(subr, binary.BigEndian, &unit)
if err != nil {
return nil, err
}
e.PHUNIT = append(e.PHUNIT, unit)
}
for annmri := 0; annmri < int(e.ANNMR); annmri++ {
var unit uint32
err = binary.Read(subr, binary.BigEndian, &unit)
if err != nil {
return nil, err
}
e.ANUNIT = append(e.ANUNIT, unit)
}
for dgnmri := 0; dgnmri < int(e.DGNMR); dgnmri++ {
var unit uint32
err = binary.Read(subr, binary.BigEndian, &unit)
if err != nil {
return nil, err
}
e.DGUNIT = append(e.DGUNIT, unit)
}
err = binary.Read(subr, binary.BigEndian, &e.FNOM)
if err != nil {
return nil, err
}
err = binary.Read(subr, binary.BigEndian, &e.CFGCNT)
if err != nil {
return nil, err
}
rv.Entries = append(rv.Entries, e)
}
err = binary.Read(subr, binary.BigEndian, &rv.DATA_RATE)
if err != nil {
return nil, err
}
return rv, nil
}
const CommonHeaderLength = 14
func (ch *CommonHeader) SyncType() SYNC_TYPE {
return SYNC_TYPE((ch.SYNC >> 4) & 7)
}
func (ch *CommonHeader) Version() int {
return int(ch.SYNC) & 15
}
func (ch *CommonHeader) SetSOCToNow() {
ch.SOC = uint32(time.Now().UTC().Unix())
}
func (ch *CommonHeader) SetSyncType(t SYNC_TYPE) {
ch.SYNC = (uint16(t) << 4) | 0xAA01
}
func ReadCommonHeader(r io.Reader) (*CommonHeader, error) {
rv := &CommonHeader{}
err := binary.Read(r, binary.BigEndian, rv)
return rv, err
}
func ReadChecksum(r io.Reader) (uint16, error) {
var rv uint16
err := binary.Read(r, binary.BigEndian, &rv)
return rv, err
}
type CMD_WORD int
const (
CMD_TURN_OFF_TX CMD_WORD = 1
CMD_TURN_ON_TX CMD_WORD = 2
CMD_SEND_HDR CMD_WORD = 3
CMD_SEND_CFG1 CMD_WORD = 4
CMD_SEND_CFG2 CMD_WORD = 5
CMD_SEND_CFG3 CMD_WORD = 6
CMD_EXFRAME CMD_WORD = 8
)
type CommandFrame struct {
CommonHeader
CMD uint16
}
type Frame interface {
}
type DataFrame struct {
CommonHeader
TIMEBASE int
UTCUnixNanos int64
TimeQual uint8
Data []*PMUData
}
type PMUData struct {
STN string
IDCODE uint16
STAT uint16
//Converted
PHASOR_NAMES []string
PHASOR_MAG []float64
PHASOR_ANG []float64
PHASOR_ISVOLT []bool
//Converted to absolute freq
FREQ float64
//Converted to floating point but not altered
DFREQ float64
ANALOG_NAMES []string
ANALOG []float64
DIGITAL_NAMES []string
DIGITAL []int
}
func Checksum(arr []byte) uint16 {
return uint16(crc16.ChecksumCCITTFalse(arr))
}
func WriteChecksummedFrame(frame Frame, w io.Writer) error {
dat := &bytes.Buffer{}
err := binary.Write(dat, binary.BigEndian, frame)
if err != nil {
return err
}
chk := Checksum(dat.Bytes())
dat.WriteByte(byte(chk >> 8))
dat.WriteByte(byte(chk & 0xFF))
_, err = w.Write(dat.Bytes())
return err
}
func ReadPhasor(format uint16, unit uint32, r io.Reader) (mag float64, ang float64, isvolt bool, err error) {
isvolt = false
if unit>>24 == 0 {
isvolt = true
}
if format&1 == 0 {
//Rectangular coordinates
if format&2 == 0 {
//16 bit integer
var real uint16
var imag uint16
err := binary.Read(r, binary.BigEndian, &real)
if err != nil {
return 0, 0, false, err
}
err = binary.Read(r, binary.BigEndian, &imag)
if err != nil {
return 0, 0, false, err
}
freal := float64(real)
fimag := float64(imag)
freal = freal * float64(unit&0xFFFFFF) * 10e-5
fimag = fimag * float64(unit&0xFFFFFF) * 10e-5
phase := math.Atan2(fimag, freal)
degrees := (phase / (2 * math.Pi)) * 360
mag := math.Hypot(fimag, freal)
return mag, degrees, isvolt, nil
} else {
//32 bit float
var real float32
var imag float32
err := binary.Read(r, binary.BigEndian, &real)
if err != nil {
return 0, 0, false, err
}
err = binary.Read(r, binary.BigEndian, &imag)
if err != nil {
return 0, 0, false, err
}
phase := math.Atan2(float64(imag), float64(real))
degrees := (phase / (2 * math.Pi)) * 360
mag := math.Hypot(float64(imag), float64(real))
return mag, degrees, isvolt, nil
}
} else {
//Polar coordinates
if format&2 == 0 {
//16 bit integer
var mag uint16
var ang uint16
err := binary.Read(r, binary.BigEndian, &mag)
if err != nil {
return 0, 0, false, err
}
err = binary.Read(r, binary.BigEndian, &ang)
if err != nil {
return 0, 0, false, err
}
fmag := float64(mag) * float64(unit&0xFFFFFF) * 10e-5
fang := float64(ang) * 10e-4 //radians
degrees := (fang / (2 * math.Pi)) * 360
return fmag, degrees, isvolt, nil
} else {
//32 bit float
var mag float32
var ang float32
err := binary.Read(r, binary.BigEndian, &mag)
if err != nil {
return 0, 0, false, err
}
err = binary.Read(r, binary.BigEndian, &ang)
if err != nil {
return 0, 0, false, err
}
//fmt.Printf("read raw float32 mag=%f ang=%f\n", mag, ang)
fmag := float64(mag)
fang := float64(ang)
degrees := (fang / (2 * math.Pi)) * 360
return fmag, degrees, isvolt, nil
}
}
}
func ReadAnalog(format uint16, unit uint32, r io.Reader) (float64, error) {
//TODO analog scaling
if format&4 == 0 {
//16 bit integer
var rv uint16
err := binary.Read(r, binary.BigEndian, &rv)
if err != nil {
return 0, err
}
return float64(rv), nil
} else {
//32 bit float
var rv float32
err := binary.Read(r, binary.BigEndian, &rv)
if err != nil {
return 0, err
}
return float64(rv), nil
}
}
func ReadDigital(unit uint32, r io.Reader) (int, error) {
var rv uint16
err := binary.Read(r, binary.BigEndian, &rv)
if err != nil {
return -1, err
}
return int(rv), nil
}
func ReadFreq(format uint16, fnom float64, r io.Reader) (float64, error) {
if format&8 == 0 {
//16 bit integer
var rv uint16
err := binary.Read(r, binary.BigEndian, &rv)
if err != nil {
return -1, err
}
return (float64(rv) / 10e3) + fnom, nil
} else {
//32 bit float
var rv float32
err := binary.Read(r, binary.BigEndian, &rv)
if err != nil {
return 0, err
}
return float64(rv), nil
}
}
func ReadROCOF(format uint16, r io.Reader) (float64, error) {
if format&8 == 0 {
//16 bit integer
var rv uint16
err := binary.Read(r, binary.BigEndian, &rv)
if err != nil {
return -1, err
}
return (float64(rv) / 10e3), nil
} else {
//32 bit float
var rv float32
err := binary.Read(r, binary.BigEndian, &rv)
if err != nil {
return 0, err
}
return float64(rv), nil
}
}
func FreqFieldToHz(freq uint16) float64 {
if freq == 0 {
return 60
}
if freq == 1 {
return 50
}
panic("invalid FNOM")
}
func ReadDataFrame(ch *CommonHeader, cfg *Config12Frame, r io.Reader) (*DataFrame, error) {
rv := DataFrame{CommonHeader: *ch}
nanos := (float64(ch.FRACSEC&0xFFFFFF) / float64(cfg.TIME_BASE)) * 1e9
rv.UTCUnixNanos = int64(ch.SOC)*1e9 + int64(nanos)
rv.TimeQual = uint8(ch.FRACSEC >> 24)
rv.TIMEBASE = int(cfg.TIME_BASE)
for pmu := 0; pmu < int(cfg.NUM_PMU); pmu++ {
d := PMUData{}
err := binary.Read(r, binary.BigEndian, &d.STAT)
if err != nil {
return nil, err
}
entry := cfg.Entries[pmu]
d.STN = entry.STN
d.IDCODE = entry.IDCODE
for phi := 0; phi < int(entry.PHNMR); phi++ {
mag, ang, isvolt, err := ReadPhasor(entry.FORMAT, entry.PHUNIT[phi], r)
if err != nil {
return nil, err
}
d.PHASOR_ANG = append(d.PHASOR_ANG, ang)
d.PHASOR_MAG = append(d.PHASOR_MAG, mag)
d.PHASOR_ISVOLT = append(d.PHASOR_ISVOLT, isvolt)
d.PHASOR_NAMES = append(d.PHASOR_NAMES, entry.PHCHNAM[phi])
}
fr, err := ReadFreq(entry.FORMAT, FreqFieldToHz(entry.FNOM), r)
if err != nil {
return nil, err
}
d.FREQ = fr
rocof, err := ReadROCOF(entry.FORMAT, r)
if err != nil {
return nil, err
}
d.DFREQ = rocof
for anni := 0; anni < int(entry.ANNMR); anni++ {
val, err := ReadAnalog(entry.FORMAT, entry.ANUNIT[anni], r)
if err != nil {
return nil, err
}
d.ANALOG = append(d.ANALOG, val)
d.ANALOG_NAMES = append(d.ANALOG_NAMES, entry.ANCHNAM[anni])
}
for digi := 0; digi < int(entry.DGNMR); digi++ {
val, err := ReadDigital(entry.DGUNIT[digi], r)
if err != nil {
return nil, err
}
d.DIGITAL = append(d.DIGITAL, val)
d.DIGITAL_NAMES = append(d.DIGITAL_NAMES, fmt.Sprintf("DIGITAL%02d", digi))
}
rv.Data = append(rv.Data, &d)
}
return &rv, nil
}
|
package photo
import (
"net/http"
)
type photoHandler struct {
}
func NewPhotoHandler() *photoHandler {
m := new(photoHandler)
return m
}
func (m *photoHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) {
http.Redirect(responseWriter, request, "/photo/portfolio", http.StatusMovedPermanently)
}
|
package command
import (
"context"
"flag"
"github.com/bongnv/gokit/internal/parser"
"github.com/bongnv/gokit/internal/iohelper"
"github.com/google/subcommands"
)
// Execute ...
func Execute(ctx context.Context) int {
subcommands.Register(subcommands.HelpCommand(), "")
subcommands.Register(subcommands.FlagsCommand(), "")
subcommands.Register(subcommands.CommandsCommand(), "")
subcommands.Register(&scaffoldCmd{
writer: &iohelper.FileWriter{},
}, "")
subcommands.Register(&serviceCmd{
parser: &parser.DefaultParser{},
writer: &iohelper.FileWriter{},
}, "")
subcommands.Register(&crudCmd{
serviceParser: &parser.DefaultParser{},
crudParser: parser.CRUDParser{},
writer: &iohelper.FileWriter{},
reader: &iohelper.FileReader{},
entityParser: parser.EntityParser{},
}, "")
subcommands.Register(&entityCmd{
writer: &iohelper.FileWriter{},
entityParser: parser.EntityParser{},
}, "")
flag.Parse()
return int(subcommands.Execute(ctx))
}
|
//go:build wasm && js && webclient
package main
import (
"fmt"
"strconv"
"syscall/js"
"time"
"github.com/ekotlikoff/gochess/internal/model"
)
func (clientModel *ClientModel) initStyle() {
document := clientModel.document
styleEl := document.Call("createElement", "style")
document.Get("head").Call("appendChild", styleEl)
styleSheet := styleEl.Get("sheet")
for x := 1; x < 9; x++ {
for y := 1; y < 9; y++ {
selector := ".square-" + strconv.Itoa(x*10+y)
transform := fmt.Sprintf(
"{transform: translate(%d%%,%d%%);}",
x*100-100, 700-((y-1)*100),
)
styleSheet.Call("insertRule", selector+transform)
}
}
}
func (cm *ClientModel) viewSetMatchControls() {
usernameInput := cm.document.Call(
"getElementById", "username")
addClass(usernameInput, "hidden")
matchButton := cm.document.Call(
"getElementById", "beginMatchmakingButton")
addClass(matchButton, "hidden")
resignButton := cm.document.Call(
"getElementById", "resignButton")
removeClass(resignButton, "hidden")
drawButton := cm.document.Call(
"getElementById", "drawButton")
removeClass(drawButton, "hidden")
}
func (cm *ClientModel) viewSetMatchMakingControls() {
usernameInput := cm.document.Call(
"getElementById", "username")
removeClass(usernameInput, "hidden")
matchButton := cm.document.Call(
"getElementById", "beginMatchmakingButton")
removeClass(matchButton, "hidden")
resignButton := cm.document.Call(
"getElementById", "resignButton")
addClass(resignButton, "hidden")
drawButton := cm.document.Call(
"getElementById", "drawButton")
addClass(drawButton, "hidden")
}
func (cm *ClientModel) viewSetMatchDetails() {
opponentMatchDetailsName := cm.document.Call(
"getElementById", "matchdetails_opponent_name")
opponentMatchDetailsName.Set("innerText", cm.remoteMatchModel.opponentName)
playerMatchDetailsName := cm.document.Call(
"getElementById", "matchdetails_player_name")
playerMatchDetailsName.Set("innerText", cm.playerName)
opponentMatchDetailsRemainingTime := cm.document.Call(
"getElementById", "matchdetails_opponent_remainingtime")
cm.viewSetMatchDetailsPoints(cm.GetPlayerColor(),
"matchdetails_player_points")
cm.viewSetMatchDetailsPoints(cm.GetOpponentColor(),
"matchdetails_opponent_points")
opponentRemainingMs := cm.GetMaxTimeMs() -
cm.GetPlayerElapsedMs(cm.GetOpponentColor())
if opponentRemainingMs < 0 {
opponentRemainingMs = 0
}
opponentMatchDetailsRemainingTime.Set("innerText",
cm.formatTime(opponentRemainingMs))
playerMatchDetailsRemainingTime := cm.document.Call(
"getElementById", "matchdetails_player_remainingtime")
playerRemainingMs := cm.GetMaxTimeMs() -
cm.GetPlayerElapsedMs(cm.GetPlayerColor())
if playerRemainingMs < 0 {
playerRemainingMs = 0
}
playerMatchDetailsRemainingTime.Set("innerText",
cm.formatTime(playerRemainingMs))
drawButtonText := "Draw"
if cm.GetRequestedDraw(cm.GetOpponentColor()) {
drawButtonText = fmt.Sprintf("Draw, %s requested a draw",
cm.remoteMatchModel.opponentName)
} else if cm.GetRequestedDraw(cm.GetPlayerColor()) {
drawButtonText = fmt.Sprintf("Draw, requesting a draw...")
}
drawButton := cm.document.Call("getElementById", "drawButton")
drawButton.Set("innerText", drawButtonText)
}
func (cm *ClientModel) viewClearMatchDetails() {
cm.document.Call("getElementById",
"matchdetails_player_name").Set("innerText", "")
cm.document.Call("getElementById",
"matchdetails_opponent_name").Set("innerText", "")
cm.document.Call("getElementById",
"matchdetails_player_remainingtime").Set("innerText", "")
cm.document.Call("getElementById",
"matchdetails_opponent_remainingtime").Set("innerText", "")
cm.document.Call("getElementById",
"matchdetails_player_points").Set("innerText", "")
cm.document.Call("getElementById",
"matchdetails_opponent_points").Set("innerText", "")
}
func (cm *ClientModel) viewSetMatchDetailsPoints(
color model.Color, elementID string) {
points := cm.GetPointAdvantage(color)
pointSummary := ""
if points > 0 {
pointSummary = strconv.Itoa(int(points))
}
matchDetailsPoints := cm.document.Call("getElementById", elementID)
matchDetailsPoints.Set("innerText", pointSummary)
}
func (cm *ClientModel) formatTime(ms int64) string {
return (time.Duration(ms) * time.Millisecond).Round(time.Second).String()
}
func (cm *ClientModel) viewSetGameOver(winner, winType string) {
addClass(cm.document.Call("getElementById", "gameover_modal"), "gameover_modal")
removeClass(cm.document.Call("getElementById", "gameover_modal"), "hidden")
cm.document.Call("getElementById", "gameover_modal_text").Set("innerText",
fmt.Sprintf("Winner: %s by %s", winner, winType))
}
func (clientModel *ClientModel) viewClearBoard() {
elements := clientModel.document.Call("getElementsByClassName", "piece")
for i := elements.Length() - 1; i >= 0; i-- {
elements.Index(i).Call("remove")
}
}
func (clientModel *ClientModel) viewInitBoard(playerColor model.Color) {
for _, file := range clientModel.game.GetBoard() {
for _, piece := range file {
if piece != nil {
div := clientModel.document.Call("createElement", "div")
div.Get("classList").Call("add", "piece")
div.Get("classList").Call("add", piece.ClientString())
div.Get("classList").Call(
"add", getPositionClass(piece.Position, playerColor))
clientModel.board.Call("appendChild", div)
div.Call("addEventListener", "mousedown",
clientModel.genMouseDown(), false)
div.Call("addEventListener", "touchstart",
clientModel.genTouchStart(), false)
}
}
}
}
func (cm *ClientModel) viewHandleMove(
moveRequest model.MoveRequest, newPos model.Position, elMoving js.Value) {
originalPositionClass :=
getPositionClass(moveRequest.Position, cm.playerColor)
newPositionClass := getPositionClass(newPos, cm.playerColor)
elements := cm.document.Call("getElementsByClassName", newPositionClass)
elementsLength := elements.Length()
for i := elementsLength - 1; i >= 0; i-- {
elements.Index(i).Call("remove")
}
cm.viewHandleCastle(moveRequest.Move, newPos)
cm.viewHandleEnPassant(moveRequest.Move, newPos, elementsLength == 0)
elMoving.Get("classList").Call("remove", originalPositionClass)
elMoving.Get("classList").Call("add", newPositionClass)
if moveRequest.PromoteTo != nil {
elMoving.Get("classList").Call("remove", "bp")
elMoving.Get("classList").Call("remove", "wp")
elMoving.Get("classList").Call("add",
cm.GetPiece(newPos).ClientString())
}
}
func (cm *ClientModel) viewCreatePromotionWindow(file, rank int) {
div := cm.document.Call("createElement", "div")
addClass(div, "promotion-window")
if cm.GetPlayerColor() == model.Black {
file = int(7 - file)
}
div.Get("style").Set("transform",
"translateX("+fmt.Sprintf("%f%%)", float64(file*100)))
if (rank == 7 && cm.GetPlayerColor() == model.White) ||
(rank == 0 && cm.GetPlayerColor() == model.Black) {
addClass(div, "top")
}
promotionPieceBishop := cm.document.Call("createElement", "div")
promotionPieceRook := cm.document.Call("createElement", "div")
promotionPieceKnight := cm.document.Call("createElement", "div")
promotionPieceQueen := cm.document.Call("createElement", "div")
closeButton := cm.document.Call("createElement", "i")
promotionPieces := []js.Value{promotionPieceBishop, promotionPieceRook,
promotionPieceKnight, promotionPieceQueen}
colorString := "b"
if cm.game.Turn() == model.White {
colorString = "w"
}
addClass(promotionPieceBishop, colorString+"b")
addClass(promotionPieceRook, colorString+"r")
addClass(promotionPieceKnight, colorString+"n")
addClass(promotionPieceQueen, colorString+"q")
for _, piece := range promotionPieces {
addClass(piece, "promotion-piece")
div.Call("appendChild", piece)
piece.Call("addEventListener", "mousedown", cm.genPromoteOnClick(), false)
}
addClass(closeButton, "close-button")
addClass(closeButton, "x")
closeButton.Set("innerText", "X")
div.Call("appendChild", closeButton)
cm.board.Call("appendChild", div)
cm.SetPromotionWindow(div)
}
func (cm *ClientModel) genPromoteOnClick() js.Func {
return js.FuncOf(func(this js.Value, i []js.Value) interface{} {
i[0].Call("preventDefault")
colorString := "b"
if cm.game.Turn() == model.White {
colorString = "w"
}
var promoteTo model.PieceType
if this.Get("classList").Call("contains", colorString+"b").Truthy() {
promoteTo = model.Bishop
} else if this.Get("classList").Call("contains", colorString+"r").Truthy() {
promoteTo = model.Rook
} else if this.Get("classList").Call("contains", colorString+"n").Truthy() {
promoteTo = model.Knight
} else if this.Get("classList").Call("contains", colorString+"q").Truthy() {
promoteTo = model.Queen
}
moveRequest := cm.GetPromotionMoveRequest()
moveRequest.PromoteTo = &promoteTo
cm.handleMove(moveRequest)
return 0
})
}
func (cm *ClientModel) viewHandleEnPassant(
move model.Move, newPos model.Position, targetEmpty bool) {
pawn := cm.game.GetBoard().Piece(newPos)
if pawn.PieceType == model.Pawn && move.X != 0 && targetEmpty {
capturedY := pawn.Rank() + 1
if move.Y > 0 {
capturedY = pawn.Rank() - 1
}
capturedPosition := model.Position{pawn.File(), capturedY}
capturedPosClass := getPositionClass(capturedPosition, cm.playerColor)
elements := cm.document.Call("getElementsByClassName", capturedPosClass)
elementsLength := elements.Length()
for i := 0; i < elementsLength; i++ {
elements.Index(i).Call("remove")
}
}
}
func (cm *ClientModel) viewHandleCastle(
move model.Move, newPos model.Position) {
king := cm.game.GetBoard().Piece(newPos)
if king.PieceType == model.King &&
(move.X < -1 || move.X > 1) {
var rookPosition model.Position
var rookPosClass string
var rookNewPosClass string
if king.File() == 2 {
rookPosition = model.Position{0, king.Rank()}
rookPosClass = getPositionClass(rookPosition, cm.playerColor)
newRookPosition := model.Position{3, king.Rank()}
rookNewPosClass = getPositionClass(newRookPosition, cm.playerColor)
} else if king.File() == 6 {
rookPosition = model.Position{7, king.Rank()}
rookPosClass = getPositionClass(rookPosition, cm.playerColor)
newRookPosition := model.Position{5, king.Rank()}
rookNewPosClass = getPositionClass(newRookPosition, cm.playerColor)
} else {
panic("King not in valid castled position")
}
elements := cm.document.Call("getElementsByClassName", rookPosClass)
elementsLength := elements.Length()
for i := 0; i < elementsLength; i++ {
elements.Index(i).Get("classList").Call("add", rookNewPosClass)
elements.Index(i).Get("classList").Call("remove", rookPosClass)
}
}
}
func (clientModel *ClientModel) buttonBeginLoading(button js.Value) {
buttonLoader := clientModel.document.Call("createElement", "div")
clientModel.SetButtonLoader(buttonLoader)
buttonLoader.Get("classList").Call("add", "loading")
button.Call("appendChild", buttonLoader)
}
func addClass(element js.Value, class string) {
element.Get("classList").Call("add", class)
}
func removeClass(element js.Value, class string) {
element.Get("classList").Call("remove", class)
}
func (clientModel *ClientModel) viewDragPiece(
elDragging js.Value, event js.Value) {
x, y, squareWidth, squareHeight, _, _ :=
clientModel.getEventMousePosition(event)
pieceWidth := elDragging.Get("clientWidth").Float()
pieceHeight := elDragging.Get("clientHeight").Float()
percentX := 100 * (float64(x) - pieceWidth/2) / float64(squareWidth)
percentY := 100 * (float64(y) - pieceHeight/2) / float64(squareHeight)
elDragging.Get("style").Set("transform",
"translate("+fmt.Sprintf("%f%%,%f%%)", percentX, percentY))
}
func getPositionClass(position model.Position, playerColor model.Color) string {
class := "square-"
if playerColor == model.Black {
class += strconv.Itoa(int(8 - position.File))
class += strconv.Itoa(int(8 - position.Rank))
} else {
class += strconv.Itoa(int(position.File + 1))
class += strconv.Itoa(int(position.Rank + 1))
}
return class
}
|
package oob
import (
"context"
"errors"
"github.com/hashicorp/go-multierror"
)
// BMC management methods.
type BMC interface {
// NetworkSource() (result string, err repository.Error)
CreateUser(context.Context) error
UpdateUser(context.Context) error
DeleteUser(context.Context) error
}
// CreateUser interface function.
func CreateUser(ctx context.Context, u []BMC) (err error) {
for _, elem := range u {
select {
case <-ctx.Done():
err = multierror.Append(err, ctx.Err())
break
default:
if elem != nil {
setErr := elem.CreateUser(ctx)
if setErr != nil {
err = multierror.Append(err, setErr)
continue
}
return nil
}
err = multierror.Append(err, errors.New("create user request not executed"))
}
}
return multierror.Append(err, errors.New("create user failed"))
}
// UpdateUser interface function.
func UpdateUser(ctx context.Context, u []BMC) (err error) {
for _, elem := range u {
select {
case <-ctx.Done():
err = multierror.Append(err, ctx.Err())
break
default:
if elem != nil {
setErr := elem.UpdateUser(ctx)
if setErr != nil {
err = multierror.Append(err, setErr)
continue
}
return nil
}
err = multierror.Append(err, errors.New("update user request not executed"))
}
}
return multierror.Append(err, errors.New("update user failed"))
}
// DeleteUser interface function.
func DeleteUser(ctx context.Context, u []BMC) (err error) {
for _, elem := range u {
select {
case <-ctx.Done():
err = multierror.Append(err, ctx.Err())
break
default:
if elem != nil {
setErr := elem.DeleteUser(ctx)
if setErr != nil {
err = multierror.Append(err, setErr)
continue
}
return nil
}
err = multierror.Append(err, errors.New("delete user request not executed"))
}
}
return multierror.Append(err, errors.New("delete user failed"))
}
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package commands
import (
"fmt"
"io"
"os"
"regexp"
"strings"
"github.com/spf13/cobra"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/_examples/xkcdsearch"
)
func init() {
rootCmd.AddCommand(searchCmd)
}
var searchCmd = &cobra.Command{
Use: "search [query]",
Short: "Search xkcd.com",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintf(os.Stdout, "\x1b[2m%s\x1b[0m\n", strings.Repeat("━", tWidth))
fmt.Fprintf(os.Stdout, "\x1b[2m?q=\x1b[0m\x1b[1m%s\x1b[0m\n", strings.Join(args, " "))
fmt.Fprintf(os.Stdout, "\x1b[2m%s\x1b[0m\n", strings.Repeat("━", tWidth))
es, err := elasticsearch.NewDefaultClient()
if err != nil {
fmt.Fprintf(os.Stderr, "\x1b[1;107;41mERROR: %s\x1b[0m\n", err)
}
config := xkcdsearch.StoreConfig{Client: es, IndexName: IndexName}
store, err := xkcdsearch.NewStore(config)
if err != nil {
fmt.Fprintf(os.Stderr, "\x1b[1;107;41mERROR: %s\x1b[0m\n", err)
os.Exit(1)
}
search := Search{store: store, reHighlight: regexp.MustCompile("<em>(.+?)</em>")}
results, err := search.getResults(strings.Join(args, " "))
if err != nil {
fmt.Fprintf(os.Stderr, "\x1b[1;107;41mERROR: %s\x1b[0m\n", err)
os.Exit(1)
}
if results.Total < 1 {
fmt.Fprintln(os.Stdout, "⨯ No results")
fmt.Fprintf(os.Stdout, "\x1b[2m%s\x1b[0m\n", strings.Repeat("─", tWidth))
os.Exit(0)
}
for _, result := range results.Hits {
search.displayResult(os.Stdout, result)
}
},
}
// Search allows to get and display results matching query.
//
type Search struct {
store *xkcdsearch.Store
reHighlight *regexp.Regexp
}
func (s *Search) getResults(query string) (*xkcdsearch.SearchResults, error) {
return s.store.Search(query)
}
func (s *Search) displayResult(w io.Writer, hit *xkcdsearch.Hit) {
var title string
if len(hit.Highlights.Title) > 0 {
title = hit.Highlights.Title[0]
} else {
title = hit.Title
}
fmt.Fprintf(w, "\x1b[2m•\x1b[0m \x1b[1m%s\x1b[0m", s.highlightString(title))
fmt.Fprintf(w, " [%s] ", hit.Published)
fmt.Fprintf(w, "<%s>\n", hit.URL)
if len(hit.Highlights.Alt) > 0 {
fmt.Fprintf(w, " \x1b[2m%s\x1b[0m", "Alt: ")
fmt.Fprintf(w, "%s\n", s.highlightString(hit.Highlights.Alt[0]))
}
if len(hit.Highlights.Transcript) > 0 {
t := strings.Join(hit.Highlights.Transcript, " … ")
t = strings.Replace(t, "\n", " ", -1)
t = s.highlightString(t)
fmt.Fprintf(w, " \x1b[2m%s\x1b[0m", "Transcript: ")
fmt.Fprintf(w, "%s\n", t)
}
fmt.Fprintf(os.Stdout, "\x1b[2m%s\x1b[0m\n", strings.Repeat("─", tWidth))
}
func (s *Search) highlightString(input string) string {
return s.reHighlight.ReplaceAllString(input, "\x1b[30;47m$1\x1b[0m")
}
|
package main
import (
"container/heap"
"fmt"
)
// https://leetcode-cn.com/problems/sliding-window-maximum/
//------------------------------------------------------------------------------
func maxSlidingWindow(nums []int, k int) []int {
return maxSlidingWindow0(nums, k)
}
//------------------------------------------------------------------------------
// Solution 1
// f: 记录窗口内最大值, 滚动更新
// f[0..k]: MAX(nums[i..i+k]), MAX(nums[i+1..i+k]),...,MAX(nums[i+k])
// 待调教
func maxSlidingWindow1(nums []int, k int) []int {
N := len(nums)
max := func(x, y int) int {
if x > y {
return x
}
return y
}
f := make([]int, k)
f[k-1] = nums[k-1]
for i := k - 2; i >= 0; i-- {
f[i] = max(nums[i], f[i+1])
}
res := make([]int, N-k+1)
now, offset := 0, 0
next := func() (int, int) {
if k == 1 {
return 0, 0
}
if now == k-1 {
offset = -1
} else if now == 0 {
offset = 1
}
defer func() { now += offset }()
return now, now + offset
}
for i := k; i < N; i++ {
c, n := next()
res[i-k] = f[c]
fmt.Println("##", i, res[i-k], c, n, nums[i-k:i], f)
if c == 0 || c == k-1 {
f[c] = nums[i]
} else {
f[c] = max(f[c-offset], nums[i])
}
f[n] = max(f[n], f[c])
//fmt.Println("##", f)
}
c, _ := next()
//fmt.Println("##", c, f)
res[N-k] = f[c]
return res
}
//------------------------------------------------------------------------------
// Solution 0
// 最大堆: O(n*lgk)
// 要记录元素在堆中的相对位置, 以便更新值及调整堆
func maxSlidingWindow0(nums []int, k int) []int {
N := len(nums)
h := &window{}
m := make([]*windowNode, k)
for i := 0; i < k; i++ {
m[i] = &windowNode{nums[i], i}
heap.Push(h, m[i])
}
res := make([]int, N-k+1)
res[0] = h.top()
for i := k; i < N; i++ {
node := m[i%k]
node.v = nums[i]
heap.Fix(h, node.i)
res[i-k+1] = h.top()
}
return res
}
type windowNode struct {
v, i int
}
func (w *windowNode) String() string {
return fmt.Sprintf("%d:%d", w.i, w.v)
}
var _ heap.Interface = &window{}
type window struct {
items []*windowNode
}
func (w window) Len() int {
return len(w.items)
}
func (w window) Less(i, j int) bool {
if w.items[i].v == w.items[j].v {
return w.items[i].i < w.items[j].i
}
return w.items[i].v > w.items[j].v
}
func (w window) Swap(i, j int) {
// i 表示在堆中的位置, 两次交换保证相对位置不变, 只是值变了
w.items[i].i, w.items[j].i = w.items[j].i, w.items[i].i
w.items[i], w.items[j] = w.items[j], w.items[i]
}
func (w *window) Push(x interface{}) {
w.items = append(w.items, x.(*windowNode))
}
func (w *window) Pop() interface{} {
n := len(w.items)
if n == 0 {
return nil
}
top := w.items[n-1]
w.items = w.items[:n-1]
return top
}
func (w *window) top() int {
return w.items[0].v
}
//------------------------------------------------------------------------------
func main() {
cases := []struct {
nums []int
k int
}{
{
[]int{-6, -10, -7, -1, -9, 9, -8, -4, 10, -5, 2, 9, 0, -7, 7, 4, -2, -10, 8, 7},
7,
},
{
[]int{1, 3, -1, -3, 5, 3, 6, 7},
3,
},
{
[]int{1, 3, -1, -3, -2, 3, 6, 7},
3,
},
{
[]int{1, 2, 3},
1,
},
}
realCase := cases[0:1]
for i, c := range realCase {
fmt.Println("## case", i)
// solve
fmt.Println(maxSlidingWindow0(c.nums, c.k))
fmt.Println(maxSlidingWindow1(c.nums, c.k))
}
}
|
package main
import (
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
"github.com/sirupsen/logrus"
)
const exporterName = "netns_exporter"
func init() { //nolint:gochecknoinits
prometheus.MustRegister(version.NewCollector(exporterName))
}
type APIServer struct {
config *NetnsExporterConfig
server *http.Server
logger logrus.FieldLogger
}
func NewAPIServer(config *NetnsExporterConfig, logger *logrus.Logger) (*APIServer, error) {
apiServer := APIServer{
config: config,
logger: logger.WithField("component", "api-server"),
}
// Try to register new Prometheus exporter.
err := prometheus.Register(NewCollector(config, logger))
if err != nil {
apiServer.logger.Errorf("Registering netns exporter failed: %s", err)
return nil, err
}
// Configure and start HTTP server.
httpMux := http.NewServeMux()
timeout := time.Duration(config.APIServer.RequestTimeout) * time.Second
address := strings.Join([]string{
config.APIServer.ServerAddress,
strconv.Itoa(config.APIServer.ServerPort),
}, ":")
apiServer.server = &http.Server{
Addr: address,
Handler: httpMux,
ReadHeaderTimeout: timeout,
WriteTimeout: timeout,
IdleTimeout: timeout,
}
httpMux.HandleFunc("/", apiServer.indexPage)
httpMux.Handle(config.APIServer.TelemetryPath, apiServer.middlewareLogging(promhttp.Handler()))
return &apiServer, nil
}
// StartAPIServer starts Exporter's HTTP server.
func (s *APIServer) Start() error {
s.logger.Infof("Starting API server on %s", s.server.Addr)
return s.server.ListenAndServe()
}
func (s *APIServer) middlewareLogging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.logger.WithFields(logrus.Fields{
"addr": r.RemoteAddr,
"method": r.Method,
"agent": r.UserAgent(),
}).Debugf("%s", r.URL.Path)
next.ServeHTTP(w, r)
})
}
func (s *APIServer) indexPage(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte(`<html>
<head><title>Network nemespace Exporter</title></head>
<body>
<h1>Network nemespace Exporter</h1>
<p><a href='` + s.config.APIServer.TelemetryPath + `'>Metrics</a></p>
</body>
</html>`))
if err != nil {
s.logger.Errorf("error handling index page: %s", err)
}
}
|
package repositories
import (
"blog/app/models"
"errors"
"github.com/jinzhu/gorm"
"github.com/mlogclub/simple"
"time"
)
type TagRepository struct {
db *gorm.DB
}
func NewTagRepository(db *gorm.DB) *TagRepository {
return &TagRepository{
db: db}
}
// 获取标签列表
func (this *TagRepository) TagList(paging *simple.Paging) []*models.Tag {
list := make([]*models.Tag, paging.Limit)
this.db.Offset(paging.Offset()).Limit(paging.Limit).Find(&list)
this.db.Model(&models.Tag{}).Count(&paging.Total)
return list
}
// 创建标签
func (this *TagRepository) Create(tag *models.Tag) (*models.Tag, error) {
if tmp := this.GetByName(tag.Name); tmp.Name == tag.Name {
return tmp, nil
}
err := this.db.Create(&tag).Error
return tag, err
}
// 编辑标签
func (this *TagRepository) UpdateById(id int, data UpdateData) (*models.Tag, error) {
var tag, err = this.GetById(id)
if err != nil {
return nil, errors.New("标签不存在")
}
err = this.db.Model(&tag).Updates(data).Error
return tag, err
}
// 使用 model 编辑标签
func (this *TagRepository) UpdateByModel(tag *models.Tag, data UpdateData) (err error) {
err = this.db.Model(&tag).Updates(data).Error
return err
}
// 使用id 删除标签
func (this *TagRepository) DelById(id int) error {
var tag, err = this.GetById(id)
if err != nil {
return errors.New("标签不存在")
}
// 为避免唯一索引冲突 软删除的时候给唯一列拼接上 当前时间
// 也可以数据库上使用和软删除字端组合唯一列
return this.db.Model(&tag).Updates(UpdateData{
"deleted_at": time.Now(),
"name": tag.Name + time.Now().Format("2006-01-02 15:04:05"),
}).Error
}
// 按id查找
func (this *TagRepository) GetById(id int) (*models.Tag, error) {
var tag = &models.Tag{}
e := this.db.First(tag, uint(id)).Error
return tag, e
}
// 按 name 查找
func (this *TagRepository) GetByName(name string) *models.Tag {
var tag = &models.Tag{}
this.db.Where("name = ?", name).First(tag)
return tag
}
// 批量创建
func (this *TagRepository) BatchCreate(tags []string) (ids []uint) {
if len(tags) < 1 {
return ids
}
for _, tagName := range tags {
tagModel := &models.Tag{
Name: tagName,
Status: models.ArticleTagStatusOk,
}
tag, err := this.Create(tagModel)
if err == nil {
ids = append(ids, tag.ID)
}
}
return ids
}
|
package gotten
import (
"errors"
"fmt"
"net/http"
"reflect"
"strings"
)
const (
BaseUrlCannotBeEmpty = "baseUrl cannot be empty"
MustPassPtrToImpl = "must pass the ptr of the service to be implemented"
ServiceMustBeStruct = "service must be struct"
UnrecognizedHTTPMethod = "http method is unrecognized"
ParamTypeMustBePtrOfStruct = "param type must be ptr of struct"
ValueIsNotString = "value is not a string"
ValueIsNotInt = "value is not a int"
DuplicatedPathKey = "duplicated path key"
UnsupportedValueType = "field type is unrecognized"
UnrecognizedPathKey = "path key is unrecognized"
EmptyRequiredVariable = "required variable is empty"
UnsupportedFieldType = "field type is unsupported"
SomePathVarHasNoValue = "some pathValue has no value"
NoUnmarshalerFoundForResponse = "no unmarshaler found for response"
ContentTypeConflict = "content type conflict: "
UnsupportedFuncType = "function type is not supported"
)
func MustPassPtrToImplError(p reflect.Type) error {
return errors.New(MustPassPtrToImpl + ": " + p.String())
}
func ServiceMustBeStructError(p reflect.Type) error {
return errors.New(ServiceMustBeStruct + ": " + p.String())
}
func UnrecognizedHTTPMethodError(method string) error {
return errors.New(UnrecognizedHTTPMethod + ": " + method)
}
func ParamTypeMustBePtrOfStructError(p reflect.Type) error {
return errors.New(ParamTypeMustBePtrOfStruct + ": " + p.String())
}
func ValueIsNotStringError(p reflect.Type) error {
return errors.New(ValueIsNotString + ": " + p.String())
}
func ValueIsNotIntError(p reflect.Type) error {
return errors.New(ValueIsNotInt + ": " + p.String())
}
func DuplicatedPathKeyError(key string) error {
return errors.New(DuplicatedPathKey + ": " + key)
}
func UnsupportedValueTypeError(valueType string) error {
return errors.New(UnsupportedValueType + ": " + valueType)
}
func UnrecognizedPathKeyError(key string) error {
return errors.New(UnrecognizedPathKey + ": " + key)
}
func EmptyRequiredVariableError(name string) error {
return errors.New(EmptyRequiredVariable + ": " + name)
}
func UnsupportedFieldTypeError(fieldType reflect.Type, valueType string) error {
return errors.New(fmt.Sprintf(UnsupportedFieldType+": %s -> %s", fieldType, valueType))
}
func SomePathVarHasNoValueError(list PathKeyList) error {
buf := strings.Builder{}
buf.WriteString(SomePathVarHasNoValue)
buf.WriteString(": ")
for key := range list {
buf.WriteString(" ")
buf.WriteString(key)
}
return errors.New(buf.String())
}
func NoUnmarshalerFoundForResponseError(response *http.Response) error {
return errors.New(fmt.Sprintf(NoUnmarshalerFoundForResponse+"%#v", response))
}
func ContentTypeConflictError(former string, latter string) error {
return errors.New(fmt.Sprintf(ContentTypeConflict+" %s(former), %s(former)", former, latter))
}
func UnsupportedFuncTypeError(p reflect.Type) error {
return errors.New(UnsupportedFuncType + ": " + p.String())
}
|
package openid
import (
"net/http"
"github.com/dgrijalva/jwt-go"
)
// The Configuration contains the entities needed to perform ID token validation.
// This type should be instantiated at the application startup time.
type Configuration struct {
tokenValidator jwtTokenValidator
idTokenGetter GetIDTokenFunc
errorHandler ErrorHandlerFunc
}
type option func(*Configuration) error
// NewConfiguration creates a new instance of Configuration and returns a pointer to it.
// This function receives a collection of the function type option. Each of those functions are
// responsible for setting some part of the returned *Configuration. If any if the option functions
// returns an error then NewConfiguration will return a nil configuration and that error.
func NewConfiguration(options ...option) (*Configuration, error) {
m := new(Configuration)
cp := newHTTPConfigurationProvider(defaultHTTPGet, &jsonConfigurationDecoder{})
jp := newHTTPJwksProvider(defaultHTTPGet, &jsonJwksDecoder{})
ksp := newSigningKeySetProvider(cp, jp, &pemPublicKeyEncoder{})
kp := newSigningKeyProvider(ksp)
m.tokenValidator = newIDTokenValidator(nil, jwtParserFunc(jwt.Parse), kp, &defaultPemToRSAPublicKeyParser{})
for _, option := range options {
err := option(m)
if err != nil {
return nil, err
}
}
return m, nil
}
// ProvidersGetter option registers the function responsible for returning the
// providers containing the valid issuer and client IDs used to validate the ID Token.
func ProvidersGetter(pg GetProvidersFunc) func(*Configuration) error {
return func(c *Configuration) error {
c.tokenValidator.(*idTokenValidator).provGetter = pg
return nil
}
}
// ErrorHandler option registers the function responsible for handling
// the errors returned during token validation. When this option is not used then the
// middleware will use the default internal implementation validationErrorToHTTPStatus.
func ErrorHandler(eh ErrorHandlerFunc) func(*Configuration) error {
return func(c *Configuration) error {
c.errorHandler = eh
return nil
}
}
// HTTPGetFunc is a function that gets a URL based on a contextual request
// and a target URL. The default behavior is the http.Get method, ignoring
// the request parameter.
type HTTPGetFunc func(r *http.Request, url string) (*http.Response, error)
var defaultHTTPGet = func(r *http.Request, url string) (*http.Response, error) {
return http.Get(url)
}
// HTTPGetter option registers the function responsible for returning the
// providers containing the valid issuer and client IDs used to validate the ID Token.
func HTTPGetter(hg HTTPGetFunc) func(*Configuration) error {
return func(c *Configuration) error {
sksp := c.tokenValidator.(*idTokenValidator).
keyGetter.(*signingKeyProvider).
keySetGetter.(*signingKeySetProvider)
sksp.configGetter.(*httpConfigurationProvider).getter = hg
sksp.jwksGetter.(*httpJwksProvider).getter = hg
return nil
}
}
// Authenticate middleware performs the validation of the OIDC ID Token.
// If an error happens, i.e.: expired token, the next handler may or may not executed depending on the
// provided ErrorHandlerFunc option. The default behavior, determined by validationErrorToHTTPStatus,
// stops the execution and returns Unauthorized.
// If the validation is successful then the next handler(h) will be executed.
func Authenticate(conf *Configuration, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, halt := authenticate(conf, w, r); !halt {
h.ServeHTTP(w, r)
}
})
}
// AuthenticateUser middleware performs the validation of the OIDC ID Token and
// forwards the authenticated user's information to the next handler in the pipeline.
// If an error happens, i.e.: expired token, the next handler may or may not executed depending on the
// provided ErrorHandlerFunc option. The default behavior, determined by validationErrorToHTTPStatus,
// stops the execution and returns Unauthorized.
// If the validation is successful then the next handler(h) will be executed and will
// receive the authenticated user information.
func AuthenticateUser(conf *Configuration, h UserHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if u, halt := authenticateUser(conf, w, r); !halt {
h.ServeHTTPWithUser(u, w, r)
}
})
}
func authenticate(c *Configuration, rw http.ResponseWriter, req *http.Request) (t *jwt.Token, halt bool) {
var tg GetIDTokenFunc
if c.idTokenGetter == nil {
tg = getIDTokenAuthorizationHeader
} else {
tg = c.idTokenGetter
}
var eh ErrorHandlerFunc
if c.errorHandler == nil {
eh = validationErrorToHTTPStatus
} else {
eh = c.errorHandler
}
ts, err := tg(req)
if err != nil {
return nil, eh(err, rw, req)
}
vt, err := c.tokenValidator.validate(req, ts)
if err != nil {
return nil, eh(err, rw, req)
}
return vt, false
}
func authenticateUser(c *Configuration, rw http.ResponseWriter, req *http.Request) (u *User, halt bool) {
var vt *jwt.Token
var eh ErrorHandlerFunc
if c.errorHandler == nil {
eh = validationErrorToHTTPStatus
} else {
eh = c.errorHandler
}
if t, halt := authenticate(c, rw, req); !halt {
vt = t
} else {
return nil, halt
}
u, err := newUser(vt)
if err != nil {
return nil, eh(err, rw, req)
}
return u, false
}
|
//
// Copyright (C) 2019-2021 vdaas.org vald team <vald@vdaas.org>
//
// 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
//
// https://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 rest provides agent ngt REST client functions
package rest
import (
"context"
"reflect"
"testing"
"github.com/vdaas/vald/internal/client"
"github.com/vdaas/vald/internal/errors"
"go.uber.org/goleak"
)
func TestNew(t *testing.T) {
type args struct {
ctx context.Context
opts []Option
}
type want struct {
want Client
}
type test struct {
name string
args args
want want
checkFunc func(want, Client) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, got Client) error {
if !reflect.DeepEqual(got, w.want) {
return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", got, w.want)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
opts: nil,
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
opts: nil,
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
got := New(test.args.ctx, test.args.opts...)
if err := test.checkFunc(test.want, got); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_Exists(t *testing.T) {
type args struct {
ctx context.Context
req *client.ObjectID
}
type fields struct {
addr string
}
type want struct {
wantRes *client.ObjectID
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, *client.ObjectID, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, gotRes *client.ObjectID, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
if !reflect.DeepEqual(gotRes, w.wantRes) {
return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", gotRes, w.wantRes)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
gotRes, err := c.Exists(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, gotRes, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_Search(t *testing.T) {
type args struct {
ctx context.Context
req *client.SearchRequest
}
type fields struct {
addr string
}
type want struct {
wantRes *client.SearchResponse
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, *client.SearchResponse, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, gotRes *client.SearchResponse, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
if !reflect.DeepEqual(gotRes, w.wantRes) {
return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", gotRes, w.wantRes)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
gotRes, err := c.Search(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, gotRes, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_SearchByID(t *testing.T) {
type args struct {
ctx context.Context
req *client.SearchIDRequest
}
type fields struct {
addr string
}
type want struct {
wantRes *client.SearchResponse
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, *client.SearchResponse, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, gotRes *client.SearchResponse, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
if !reflect.DeepEqual(gotRes, w.wantRes) {
return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", gotRes, w.wantRes)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
gotRes, err := c.SearchByID(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, gotRes, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_StreamSearch(t *testing.T) {
type args struct {
ctx context.Context
dataProvider func() *client.SearchRequest
f func(*client.SearchResponse, error)
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.StreamSearch(test.args.ctx, test.args.dataProvider, test.args.f)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_StreamSearchByID(t *testing.T) {
type args struct {
ctx context.Context
dataProvider func() *client.SearchIDRequest
f func(*client.SearchResponse, error)
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.StreamSearchByID(test.args.ctx, test.args.dataProvider, test.args.f)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_Insert(t *testing.T) {
type args struct {
ctx context.Context
req *client.ObjectVector
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.Insert(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_StreamInsert(t *testing.T) {
type args struct {
ctx context.Context
dataProvider func() *client.ObjectVector
f func(error)
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.StreamInsert(test.args.ctx, test.args.dataProvider, test.args.f)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_MultiInsert(t *testing.T) {
type args struct {
ctx context.Context
objectVectors *client.ObjectVectors
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
objectVectors: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
objectVectors: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.MultiInsert(test.args.ctx, test.args.objectVectors)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_Update(t *testing.T) {
type args struct {
ctx context.Context
req *client.ObjectVector
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.Update(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_StreamUpdate(t *testing.T) {
type args struct {
ctx context.Context
dataProvider func() *client.ObjectVector
f func(error)
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.StreamUpdate(test.args.ctx, test.args.dataProvider, test.args.f)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_MultiUpdate(t *testing.T) {
type args struct {
ctx context.Context
objectVectors *client.ObjectVectors
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
objectVectors: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
objectVectors: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.MultiUpdate(test.args.ctx, test.args.objectVectors)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_Remove(t *testing.T) {
type args struct {
ctx context.Context
req *client.ObjectID
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.Remove(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_StreamRemove(t *testing.T) {
type args struct {
ctx context.Context
dataProvider func() *client.ObjectID
f func(error)
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.StreamRemove(test.args.ctx, test.args.dataProvider, test.args.f)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_MultiRemove(t *testing.T) {
type args struct {
ctx context.Context
req *client.ObjectIDs
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.MultiRemove(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_GetObject(t *testing.T) {
type args struct {
ctx context.Context
req *client.ObjectID
}
type fields struct {
addr string
}
type want struct {
wantRes *client.ObjectVector
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, *client.ObjectVector, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, gotRes *client.ObjectVector, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
if !reflect.DeepEqual(gotRes, w.wantRes) {
return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", gotRes, w.wantRes)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
gotRes, err := c.GetObject(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, gotRes, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_StreamGetObject(t *testing.T) {
type args struct {
ctx context.Context
dataProvider func() *client.ObjectID
f func(*client.ObjectVector, error)
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
dataProvider: nil,
f: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.StreamGetObject(test.args.ctx, test.args.dataProvider, test.args.f)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_CreateIndex(t *testing.T) {
type args struct {
ctx context.Context
req *client.ControlCreateIndexRequest
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.CreateIndex(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_SaveIndex(t *testing.T) {
type args struct {
ctx context.Context
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.SaveIndex(test.args.ctx)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_CreateAndSaveIndex(t *testing.T) {
type args struct {
ctx context.Context
req *client.ControlCreateIndexRequest
}
type fields struct {
addr string
}
type want struct {
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
req: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
err := c.CreateAndSaveIndex(test.args.ctx, test.args.req)
if err := test.checkFunc(test.want, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
func Test_agentClient_IndexInfo(t *testing.T) {
type args struct {
ctx context.Context
}
type fields struct {
addr string
}
type want struct {
wantRes *client.InfoIndex
err error
}
type test struct {
name string
args args
fields fields
want want
checkFunc func(want, *client.InfoIndex, error) error
beforeFunc func(args)
afterFunc func(args)
}
defaultCheckFunc := func(w want, gotRes *client.InfoIndex, err error) error {
if !errors.Is(err, w.err) {
return errors.Errorf("got_error: \"%#v\",\n\t\t\t\twant: \"%#v\"", err, w.err)
}
if !reflect.DeepEqual(gotRes, w.wantRes) {
return errors.Errorf("got: \"%#v\",\n\t\t\t\twant: \"%#v\"", gotRes, w.wantRes)
}
return nil
}
tests := []test{
// TODO test cases
/*
{
name: "test_case_1",
args: args {
ctx: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
},
*/
// TODO test cases
/*
func() test {
return test {
name: "test_case_2",
args: args {
ctx: nil,
},
fields: fields {
addr: "",
},
want: want{},
checkFunc: defaultCheckFunc,
}
}(),
*/
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
defer goleak.VerifyNone(t)
if test.beforeFunc != nil {
test.beforeFunc(test.args)
}
if test.afterFunc != nil {
defer test.afterFunc(test.args)
}
if test.checkFunc == nil {
test.checkFunc = defaultCheckFunc
}
c := &agentClient{
addr: test.fields.addr,
}
gotRes, err := c.IndexInfo(test.args.ctx)
if err := test.checkFunc(test.want, gotRes, err); err != nil {
tt.Errorf("error = %v", err)
}
})
}
}
|
package main
import(
"fmt"
"os"
"bufio"
"strings"
"strconv"
)
//check if the char is a num between 0 to 9
func IsNum(c uint8) bool {
return c >= '0' && c <= '9'
}
//define the precedence of the operator
func PreOfOperator(op string) int {
switch op {
case "+", "-":
return 1
case "*", "/":
return 2
}
return -1
}
// compare top operator
func isHigher(op1 string, op2 string) bool {
op1p := PreOfOperator(op1)
op2p := PreOfOperator(op2)
return op1p >= op2p
}
func Transfer(exp string) string { //infix transfer to postfix
var stack Stack
postfix := ""
expLen := len(exp)
// traversal
for i := 0; i < expLen; i++ {
char := string(exp[i])
switch char {
case " ":
continue
case "(":
stack.Push("(")
case ")":
for !stack.IsEmpty() {
str,_ := stack.Top().(string)
if str == "(" {
break
}
postfix += " " + str
stack.Pop()
}
stack.Pop()
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
j := i
num := ""
for ; j < expLen && IsNum(exp[j]); j++ { //check if it is a number
num += string(exp[j])
}
postfix += " " + num
i = j - 1
default:
for !stack.IsEmpty() {
top,_ := stack.Top().(string)
if top == "(" || !isHigher(top, char) { //compare two operator's precedence
break
}
postfix += " " + top
stack.Pop()
}
stack.Push(char)
}
}
for !stack.IsEmpty() {
str,_ := stack.Pop().(string)
postfix += " " + str
}
return strings.TrimSpace(postfix)
}
func calculate(postfix string) float64 {
var stack Stack
var c float64
postLen := len(postfix)
for i := 0; i < postLen; i++ {
nextChar := string(postfix[i])
if IsNum(postfix[i]) {
stack.Push(nextChar)
} else {
switch nextChar {
case "+":
a,_ := strconv.ParseFloat(stack.Pop().(string),64)
b,_ := strconv.ParseFloat(stack.Pop().(string),64)
c = b + a
s := strconv.FormatFloat(c,'f',-1,64)
stack.Push(s)
case "-":
a,_ := strconv.ParseFloat(stack.Pop().(string),64)
b,_ := strconv.ParseFloat(stack.Pop().(string),64)
c = b - a
s := strconv.FormatFloat(c,'f',-1,64)
stack.Push(s)
case "*":
a,_ := strconv.ParseFloat(stack.Pop().(string),64)
b,_ := strconv.ParseFloat(stack.Pop().(string),64)
c = b * a
s := strconv.FormatFloat(c,'f',-1,64)
stack.Push(s)
case "/":
a,_ := strconv.ParseFloat(stack.Pop().(string),64)
b,_ := strconv.ParseFloat(stack.Pop().(string),64)
c = b / a
s := strconv.FormatFloat(c,'f',-1,64)
stack.Push(s)
}
}
}
result,_ := strconv.ParseFloat(stack.Top().(string),64)
return result
}
func main(){
print("please input a infix expression: ")
var stat string
reader := bufio.NewReader(os.Stdin)
stat, _ = reader.ReadString('\n')
stat = strings.TrimSpace(stat)
postfix := Transfer(stat)
// fmt.Printf("%s\n",postfix)
fmt.Printf("The answer is: %.2f\n", calculate(postfix))
}
|
package main
import (
"bufio"
"bytes"
"fmt"
"io"
)
type parser struct {
br *bufio.Reader
tok, last byte
n int
err, lasterr error
indent int
}
func (p *parser) next() byte {
p.last = p.tok
p.lasterr = p.err
p.tok, p.err = p.br.ReadByte()
p.printTrace(fmt.Sprintf("next: %x", p.last))
return p.last
}
func (p *parser) parse() (items []Item) {
p.next()
for {
it := p.parseAny()
items = append(items, it)
if _, ok := it.(EOF); ok {
break
}
}
return
}
func (p *parser) parseAny() (item Item) {
defer un(trace(p, "parseAny"))
p.next()
if p.lasterr != nil {
return EOF{p.lasterr}
}
if p.tok == p.last {
rep := p.parseRepeat()
if rep.n < 8{
item = &Run{
v: bytes.Repeat([]byte{rep.b}, rep.n),
}
} else {
item = rep
}
} else {
item = p.parseRun()
}
return
}
func (p *parser) parseRepeat() (rep *Repeat) {
defer un(trace(p, "parseRepeat"))
rep = &Repeat{p.last, 1}
for p.last == p.tok && p.lasterr == nil {
p.next()
rep.n++
}
return
}
func (p *parser) parseRun() (run *Run) {
defer un(trace(p, "parseRun"))
defer func() { fmt.Printf("parseRun: %#v\n", run) }()
run = &Run{
v: []byte{},
items: []Item{},
}
for p.last != p.tok && p.lasterr == nil {
run.v = append(run.v, p.last)
p.next()
}
if p.err == nil {
run.v = append(run.v, p.last)
}
return
}
func (p *parser) typeCheck(it Item){
switch t := it.(type){
case *Run:
p.parseRunData(t)
p.parseNUL(t)
p.parseConformData(t)
}
}
// parseFunc parses the input by calling fn for every consecutive byte
// sequence until fn returns false
func (p *parser) parseFunc(b []byte, fn func(byte) bool) []byte {
buf := new(bytes.Buffer)
for _, x := range b {
if !fn(x) {
break
}
buf.WriteByte(x)
}
return buf.Bytes()
}
func (p *parser) parseNUL(run *Run) {
var (
i = 0
it Item
)
peek := func() Item {
if i+1 < len(run.items) {
return run.items[i+1]
}
return EOF{io.EOF}
}
for i := 0; i < len(run.items); i++{
it = run.items[i]
next := peek()
switch t := it.(type) {
case *ASCII:
if !p.acceptNUL(next) {
break
}
t.v = append(t.v, 0)
t.null = true
run.Delete(i+1)
case *UTF16:
if !p.acceptNUL(t) {
break
}
i++
if !p.acceptNUL(t) {
i--
break
}
t.v = append(t.v, 0, 0)
run.Delete(i+1)
}
}
}
func (p *parser) parseConformData(run *Run) {
lastnumber := false
var prev Item
for i, v := range run.items {
switch t := v.(type) {
case *ASCII:
if lastnumber {
n := int(prev.(*Number).v)
if lenlen, len := conformsAny(t, n); lenlen != 0 {
run.items[i-1] = &Conform{lenlen, len, v}
run.Delete(i)
}
}
lastnumber = false
case *UTF16:
if lastnumber {
n := int(prev.(*Number).v) * 2
if lenlen, len := conformsAny(t, n); lenlen != 0 {
run.items[i-1] = &Conform{lenlen, len, v}
run.Delete(i)
}
}
lastnumber = false
case *Number:
lastnumber = true
}
prev = v
}
}
func (p *parser) parseRunData(run *Run) {
defer un(trace(p, "parseRunData"))
b := run.v
add := func(it Item) {
run.items = append(run.items, it)
}
debugadd := func(s string, it Item){
fmt.Printf("add item (%s): %#v\n", s, it)
add(it)
}
for len(b) > 0 {
numeric := p.parseFunc(b, func(b byte) bool { return !common(b) && b != 0 })
advance := len(numeric)
if advance > len(b) {
b = b[len(b)-1:]
} else {
b = b[len(numeric):]
}
for _, x := range numeric {
// to make things work, convert every number to be 1 byte wide
// future: size appropriately with multiple passes
debugadd("numeric",&Number{int64(x), 1})
}
utfs := p.parseUTF16(b)
ascii := p.parseASCII(b)
if n := len(utfs.v) * 2; n > 0 {
debugadd("utf16",utfs)
b = b[n:]
} else if n := len(ascii.v); n > 0 {
debugadd("ascii",ascii)
b = b[n:]
} else {
// numeric function didn't parse this so just make progress for now
// possibly a stray null terminator
if len(b) > 0 {
debugadd("stray", &Number{int64(b[0]), 1})
b = b[1:]
}
}
}
return
}
func (p *parser) parseUTF16(b []byte) *UTF16 {
defer un(trace(p, "parseUTF16"))
br := new(bytes.Buffer)
i := 0
null := false
for ; i+1 < len(b); i += 2 {
if common(b[i]) && b[i+1] == 0 {
br.WriteByte(b[i])
} else {
break
}
}
if i+2 < len(b) && b[i+2] == 0 && b[i+1] == 0 {
null = true
br.Write([]byte{0, 0})
}
if i == 0{
return &UTF16{}
}
fmt.Printf("i is %d and len(br) is %d\n", i, len(br.Bytes()))
return &UTF16{br.Bytes(), null}
}
func (p *parser) parseASCII(b []byte) *ASCII {
defer un(trace(p, "parseASCII"))
br := new(bytes.Buffer)
i := 0
null := false
for ; i < len(b); i++ {
if common(b[i]) {
br.WriteByte(b[i])
} else {
break
}
}
if i+1 < len(b) && b[i+1] == 0 {
null = true
br.WriteByte(0)
}
if i == 0{
return &ASCII{}
}
return &ASCII{v: br.Bytes(), null: null}
}
func (p *parser) acceptNUL(it Item) bool {
if num, ok := it.(*Number); !ok {
return false
} else if num.v != 0 {
return false
}
return true
}
func (p *parser) typeCheckAll(it *[]Item){
if it == nil{
return
}
items := *it
for i := range items{
p.typeCheck(items[i])
}
}
func (p *parser) combineRuns(it *[]Item){
if it == nil{
return
}
items := *it
lastrun := false
n := len(items)
for i, it := range items{
switch t := it.(type){
case EOF:
break
case *Run:
if lastrun && false {
x := t
y := items[i-1].(*Run)
y.v = append(y.v, x.v...)
y.len += x.len
copy(items[i-1:], items[i:])
n--
}
lastrun=true
default:
lastrun=false
}
}
fmt.Printf("n, len = %d, %d\n", len(items), n)
items = items[:n]
}
|
package server
import (
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/syariatifaris/shopeetax/app/resource/uires"
"github.com/syariatifaris/shopeetax/app/usecase"
)
//httpHandlerFunc abstraction of http handler
type httpHandlerFunc func(ui *uires.UIResource, request *http.Request, useCase usecase.HandleUseCase, subscribers ...usecase.UseCase) (interface{}, error)
//httpHandlerViewFunc abstraction of http handler with view
type httpHandlerViewFunc func(ui *uires.UIResource, request *http.Request, writer http.ResponseWriter, useCase usecase.HandleUseCase, subscribers ...usecase.UseCase)
//Server contract
type Server interface {
Run() error
}
//httpServer structure as Server implementation for http api
type httpServer struct {
ui *uires.UIResource
router *httprouter.Router
port int
}
|
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package wlan
import (
"fmt"
mlme "garnet/public/lib/wlan/fidl/wlan_mlme"
"sort"
"strings"
)
type AP struct {
BSSID [6]uint8
SSID string
BSSDesc *mlme.BssDescription
LastRSSI uint8
}
func NewAP(bssDesc *mlme.BssDescription) *AP {
b := *bssDesc // make a copy.
return &AP{
BSSID: bssDesc.Bssid,
SSID: bssDesc.Ssid,
BSSDesc: &b,
LastRSSI: 0xff,
}
}
func macStr(macArray [6]uint8) string {
return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x",
macArray[0], macArray[1], macArray[2], macArray[3], macArray[4], macArray[5])
}
func CollectScanResults(resp *mlme.ScanResponse, ssid string, bssid string) []AP {
aps := []AP{}
for _, s := range resp.BssDescriptionSet {
if bssid != "" {
// Match the specified BSSID only
if macStr(s.Bssid) != strings.ToLower(bssid) {
continue
}
}
if s.Ssid == ssid || ssid == "" {
ap := NewAP(&s)
ap.LastRSSI = s.RssiMeasurement
aps = append(aps, *ap)
}
}
if len(resp.BssDescriptionSet) > 0 && len(aps) == 0 {
fmt.Printf("wlan: no matching network among %d scanned\n", len(resp.BssDescriptionSet))
}
sort.Slice(aps, func(i, j int) bool { return int8(aps[i].LastRSSI) > int8(aps[j].LastRSSI) })
return aps
}
|
package pkg
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/OpenDiablo2/dc6/pkg/frames"
)
func TestDC6New(t *testing.T) {
if dc6 := New(); dc6 == nil {
t.Error("d2dc6.New() method returned nil")
}
}
func getExampleDC6() *DC6 {
exampleDC6 := &DC6{
Flags: 1,
Encoding: 0,
Termination: [terminationSize]byte{238, 238, 238, 238},
Frames: frames.New(),
}
exampleDC6.Frames.SetNumberOfDirections(1)
exampleDC6.Frames.SetFramesPerDirection(1)
/*
grid: {
{
Flipped: 0,
Width: 32,
Height: 26,
OffsetX: 45,
OffsetY: 24,
Unknown: 0,
NextBlock: 50,
FrameData: []byte{2, 23, 34, 128, 53, 64, 39, 43, 123, 12},
Terminator: []byte{2, 8, 5},
},
{
Flipped: 0,
Width: 62,
Height: 36,
OffsetX: 15,
OffsetY: 28,
Unknown: 0,
NextBlock: 35,
FrameData: []byte{9, 33, 89, 148, 64, 64, 49, 81, 221, 19},
Terminator: []byte{3, 7, 5},
},
},
{
{
Flipped: 0,
Width: 62,
Height: 36,
OffsetX: 15,
OffsetY: 28,
Unknown: 0,
NextBlock: 35,
FrameData: []byte{9, 33, 89, 148, 64, 64, 49, 81, 121, 19},
Terminator: []byte{3, 7, 5},
},
{
Flipped: 0,
Width: 32,
Height: 26,
OffsetX: 45,
OffsetY: 24,
Unknown: 0,
NextBlock: 50,
FrameData: []byte{2, 23, 34, 128, 53, 64, 39, 43, 123, 12},
Terminator: []byte{2, 8, 5},
},
},
},
*/
return exampleDC6
}
/* TODO: activate this test (fix Encode method)
func TestDC6Unmarshal(t *testing.T) {
exampleDC6 := getExampleDC6()
data := exampleDC6.Encode()
extractedDC6, err := Load(data)
if err != nil {
t.Error(err)
}
assert.Equal(t, exampleDC6, extractedDC6, "encoded and decoded dc6 isn't equal")
}
*/
func TestDC6Clone(t *testing.T) {
exampleDC6 := getExampleDC6()
clonedDC6 := exampleDC6.Clone()
assert.Equal(t, exampleDC6, clonedDC6, "cloned dc6 isn't equal to base")
}
|
package main
import (
"context"
"log"
"github.com/go-redis/redis/v8"
)
var client *redis.Client
func NewRedisClient() {
log.Printf("Connecting to Redis..")
client = redis.NewClient(&redis.Options{
Addr: "redis:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := client.Ping(context.Background()).Result()
if err != nil {
log.Fatalf("Can't connect to Redis, %s", err)
}
log.Println(pong, err)
log.Printf("Connected to Redis!")
}
func InsertKV(key string, value string) error {
return client.Set(context.Background(), key, value, 0).Err()
}
func UpdateKV(key string, value string) error {
return InsertKV(key, value)
}
func FlushAllKeys() error {
return client.FlushAll(context.Background()).Err()
}
func DeleteKV(key string) error {
return client.Del(context.Background(), key).Err()
}
func GetKeys(pattern string) ([]string, error) {
r := client.Keys(context.Background(), pattern)
return r.Result()
}
func GetValue(key string) (string, error) {
res := client.Get(context.Background(), key)
return res.Result()
}
func GetValues(pattern string) ([]string, error) {
r, _ := GetKeys(pattern)
var result []string
for _, element := range r {
val, err := GetValue(element)
if err != nil {
return result, nil
}
result = append(result, val)
}
return result, nil
}
func GetAllKeysValues() (map[string]string, error) {
mapKeysValues := make(map[string]string)
allKeys, err := GetKeys("*")
if err != nil {
return mapKeysValues, err
}
for _, key := range allKeys {
val, _ := GetValue(key)
mapKeysValues[key] = val
}
return mapKeysValues, nil
}
func Subscribe(pattern string, stop <-chan struct{}) (<-chan *redis.Message, error) {
ctx := context.Background()
pubsub := client.PSubscribe(ctx, pattern)
_, err := pubsub.Receive(ctx)
if err != nil {
return nil, err
}
go func() {
<-stop
pubsub.Close()
}()
return pubsub.Channel(), nil
}
func Publish(channel string, message interface{}) error {
return client.Publish(context.Background(), channel, message).Err()
}
func IsNotFound(err error) bool {
return err == redis.Nil
}
|
// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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.
//go:build unit_test
package vpc
import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestProtocolToNumberTCP tests the conversion of TCP protocol to number
// when the protocol is either in upper or lower case.
func TestProtocolToNumberTCP(t *testing.T) {
protocolToTest := []string{"TCP", "tcp"}
for _, testProtocol := range protocolToTest {
actualProtocolNumber, err := ProtocolToNumber(testProtocol)
assert.Equal(t, protocolTCP, actualProtocolNumber)
assert.NoError(t, err)
}
}
// TestProtocolToNumberUDP tests the conversion of UDP protocol to number
// when the protocol is either in upper or lower case.
func TestProtocolToNumberUDP(t *testing.T) {
protocolToTest := []string{"UDP", "udp"}
for _, testProtocol := range protocolToTest {
actualProtocolNumber, err := ProtocolToNumber(testProtocol)
assert.Equal(t, protocolUDP, actualProtocolNumber)
assert.NoError(t, err)
}
}
// TestProtocolToNumberFailure tests the failure case with invalid protocol.
func TestProtocolToNumberFailure(t *testing.T) {
actualProtocolNumber, err := ProtocolToNumber("ICMP")
assert.Equal(t, uint32(256), actualProtocolNumber)
assert.Error(t, err)
}
|
package main
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
const localURL = "localhost"
const redisURL = "REDIS_URL"
func TestGetEmptyEnvFile(t *testing.T) {
err := os.Setenv("GO_ENV", "")
if err != nil {
assert.Fail(t, err.Error(), "Failed setting env")
}
GetEnvFile()
expectedURL := os.Getenv(redisURL)
assert.Equal(t, localURL, expectedURL)
}
func TestGetBadEnvFile(t *testing.T) {
err := os.Setenv("GO_ENV", "test")
if err != nil {
assert.Equal(t, err.Error(), "done")
}
assert.Panics(t, func() { GetEnvFile() })
}
func TestConnectRedis(t *testing.T) {
err := os.Setenv(redisURL, localURL)
if err != nil {
panic(err)
}
assert.Panics(t, func() { ConnectRedis() })
}
|
package repository
import (
"context"
"fmt"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/teploff/otus/scheduler/internal/domain/entity"
"strconv"
"strings"
)
// eventRepository implements EventRepository interface
type eventRepository struct {
pgxPool *pgxpool.Pool
}
// NewEventRepository gets Event repository instance
func NewEventRepository(pgxPool *pgxpool.Pool) *eventRepository {
return &eventRepository{pgxPool: pgxPool}
}
// GetEventsRequiringNotice provides to get notification which users must get from db
func (e eventRepository) GetEventsRequiringNotice(ctx context.Context) ([]entity.Event, error) {
tx, err := e.pgxPool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
events := make([]entity.Event, 0, 100)
rows, err := tx.Query(ctx, `
SELECT id, short_description, date, duration, full_description, remind_before, user_id
FROM public."Event"
WHERE (SELECT EXTRACT(MINUTE FROM (date - now()))) = remind_before AND is_received = FALSE`)
defer rows.Close()
if err != nil {
return nil, err
}
for rows.Next() {
var event entity.Event
if err = rows.Scan(&event.ID, &event.ShortDescription, &event.Date, &event.Duration, &event.FullDescription,
&event.RemindBefore, &event.UserID); err != nil {
return nil, err
}
events = append(events, event)
}
if err = tx.Commit(ctx); err != nil {
return nil, err
}
return events, nil
}
// ConfirmEvents make confirmation events
func (e eventRepository) ConfirmEvents(ctx context.Context, events []entity.Event) error {
tx, err := e.pgxPool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
ids := make([]interface{}, 0, len(events))
placeHolders := make([]string, 0, len(events))
for index, event := range events {
ids = append(ids, event.ID)
placeHolders = append(placeHolders, "$"+strconv.Itoa(index+1))
}
query := fmt.Sprintf("UPDATE\n"+
"public.\"Event\"\n"+
"SET\n"+
"is_received = TRUE\n"+
"WHERE id IN (%s)", strings.Join(placeHolders, ", "))
_, err = tx.Exec(ctx, query, ids...)
if err != nil {
return err
}
if err = tx.Commit(ctx); err != nil {
return err
}
return nil
}
// CleanExpiredEvents provides expired events which older than 1 year
func (e eventRepository) CleanExpiredEvents(ctx context.Context) error {
tx, err := e.pgxPool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
_, err = tx.Exec(ctx, `
DELETE
FROM public."Event"
WHERE (SELECT EXTRACT(YEAR FROM (now()))) - (SELECT EXTRACT(YEAR FROM date)) >= 1`)
if err != nil {
return err
}
if err = tx.Commit(ctx); err != nil {
return err
}
return nil
}
|
package 单调栈
// -------------------------- 无单调栈,朴素解法 --------------------------
// 时间复杂度: O(n^2 * m^2)
func numSubmat(mat [][]int) int {
maxRectangleHeight := getMaxRectangleHeight(mat)
return getCountOfRectangle(maxRectangleHeight)
}
func getMaxRectangleHeight(mat [][]int) [][]int {
rows, cols := getRowsAndCols(mat)
maxRectangleHeight := get2DSlice(rows, cols)
maxRectangleHeight[0][0] = mat[0][0]
for i := 1; i < rows; i++ {
if mat[i][0] == 1 {
maxRectangleHeight[i][0] = maxRectangleHeight[i-1][0] + 1
}
}
for t := 1; t < cols; t++ {
maxRectangleHeight[0][t] = mat[0][t]
}
for i := 1; i < rows; i++ {
for t := 1; t < cols; t++ {
if mat[i][t] == 1 {
maxRectangleHeight[i][t] = maxRectangleHeight[i-1][t] + 1
}
}
}
return maxRectangleHeight
}
func getCountOfRectangle(maxRectangleHeight [][]int) int {
countOfRectangle := 0
rows, cols := getRowsAndCols(maxRectangleHeight)
for i := 0; i < rows; i++ {
for t := 0; t < cols; t++ {
for h := 1; h <= maxRectangleHeight[i][t]; h++ {
// 纵向扩展
countOfRectangle++
// 横向扩展
for leftBound := t - 1; leftBound >= 0 && maxRectangleHeight[i][leftBound] >= h; leftBound-- {
countOfRectangle++
}
}
}
}
return countOfRectangle
}
func getRowsAndCols(matrix [][]int) (int, int) {
if len(matrix) == 0 {
return 0, 0
}
return len(matrix), len(matrix[0])
}
func get2DSlice(rows, column int) [][]int {
slice := make([][]int, rows)
for i := 0; i < len(slice); i++ {
slice[i] = make([]int, column)
}
return slice
}
// -------------------------- 无单调栈,朴素优化解法 --------------------------
// 时间复杂度: O(n^2 * m)
func numSubmat(mat [][]int) int {
maxRectangleHeight := getMaxRectangleHeight(mat)
return getCountOfRectangle(maxRectangleHeight)
}
func getMaxRectangleHeight(mat [][]int) [][]int {
rows, cols := getRowsAndCols(mat)
maxRectangleHeight := get2DSlice(rows, cols)
maxRectangleHeight[0][0] = mat[0][0]
for i := 1; i < rows; i++ {
if mat[i][0] == 1 {
maxRectangleHeight[i][0] = maxRectangleHeight[i-1][0] + 1
}
}
for t := 1; t < cols; t++ {
maxRectangleHeight[0][t] = mat[0][t]
}
for i := 1; i < rows; i++ {
for t := 1; t < cols; t++ {
if mat[i][t] == 1 {
maxRectangleHeight[i][t] = maxRectangleHeight[i-1][t] + 1
}
}
}
return maxRectangleHeight
}
func getCountOfRectangle(maxRectangleHeight [][]int) int {
countOfRectangle := 0
rows, cols := getRowsAndCols(maxRectangleHeight)
for i := 0; i < rows; i++ {
for t := 0; t < cols; t++ {
// 这里初现单调栈的端倪
curMinHeight := maxRectangleHeight[i][t]
for leftBound := t; leftBound >= 0; leftBound-- {
curMinHeight = min(curMinHeight, maxRectangleHeight[i][leftBound])
countOfRectangle += curMinHeight
}
}
}
return countOfRectangle
}
func getRowsAndCols(matrix [][]int) (int, int) {
if len(matrix) == 0 {
return 0, 0
}
return len(matrix), len(matrix[0])
}
func get2DSlice(rows, column int) [][]int {
slice := make([][]int, rows)
for i := 0; i < len(slice); i++ {
slice[i] = make([]int, column)
}
return slice
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
// -------------------------- 单调栈 + DP --------------------------
// 时间复杂度: O(n * m)
func numSubmat(mat [][]int) int {
maxRectangleHeight := getMaxRectangleHeight(mat)
return getCountOfRectangle(maxRectangleHeight)
}
func getMaxRectangleHeight(mat [][]int) [][]int {
rows, cols := getRowsAndCols(mat)
maxRectangleHeight := get2DSlice(rows, cols)
maxRectangleHeight[0][0] = mat[0][0]
for i := 1; i < rows; i++ {
if mat[i][0] == 1 {
maxRectangleHeight[i][0] = maxRectangleHeight[i-1][0] + 1
}
}
for t := 1; t < cols; t++ {
maxRectangleHeight[0][t] = mat[0][t]
}
for i := 1; i < rows; i++ {
for t := 1; t < cols; t++ {
if mat[i][t] == 1 {
maxRectangleHeight[i][t] = maxRectangleHeight[i-1][t] + 1
}
}
}
return maxRectangleHeight
}
func getCountOfRectangle(maxRectangleHeight [][]int) int {
rows, cols := getRowsAndCols(maxRectangleHeight)
countOfRectangle := 0
for i := 0; i < rows; i++ {
countOfRectangleInCurRow := make([]int, cols)
stack := NewMyStack()
for t := 0; t < cols; t++ {
for !stack.IsEmpty() && maxRectangleHeight[i][stack.GetTop()] >= maxRectangleHeight[i][t] {
stack.Pop()
}
if stack.IsEmpty() {
rectangleWidth := t + 1
countOfRectangleInCurRow[t] = maxRectangleHeight[i][t] * rectangleWidth
} else {
rectangleWidth := t - stack.GetTop()
countOfRectangleInCurRow[t] = maxRectangleHeight[i][t]*rectangleWidth + countOfRectangleInCurRow[stack.GetTop()]
}
stack.Push(t)
countOfRectangle += countOfRectangleInCurRow[t]
}
}
return countOfRectangle
}
func getRowsAndCols(matrix [][]int) (int, int) {
if len(matrix) == 0 {
return 0, 0
}
return len(matrix), len(matrix[0])
}
func get2DSlice(rows, column int) [][]int {
slice := make([][]int, rows)
for i := 0; i < len(slice); i++ {
slice[i] = make([]int, column)
}
return slice
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
// -------------------------- MyStack --------------------------
type MyStack struct {
data []int
}
func NewMyStack() *MyStack {
return &MyStack{}
}
func (ms *MyStack) Push(val int) {
ms.data = append(ms.data, val)
}
func (ms *MyStack) Pop() int {
top := ms.data[ms.GetSize()-1]
ms.data = ms.data[:ms.GetSize()-1]
return top
}
func (ms *MyStack) GetTop() int {
return ms.data[ms.GetSize()-1]
}
func (ms *MyStack) IsEmpty() bool {
return ms.GetSize() == 0
}
func (ms *MyStack) GetSize() int {
return len(ms.data)
}
/*
总结:
1. 单调栈 + DP 真的NB。
*/
|
package cloud
type Cloud interface {
Name() string
Init(string, string, string, string)
TestConnect() error
GetInstances() []*Instance
StartInstance(string) error
StopInstance(string) error
RestartInstance(string) error
}
|
package scraper_test
import (
"context"
"testing"
"time"
discoveryv1 "github.com/syncromatics/kafmesh/internal/protos/kafmesh/discovery/v1"
scraper "github.com/syncromatics/kafmesh/internal/scraper"
gomock "github.com/golang/mock/gomock"
"gotest.tools/assert"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func Test_Job_GetKafmeshPods(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
lister := NewMockPodLister(ctrl)
discoverFactory := NewMockDiscoveryFactory(ctrl)
pod1 := v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod1",
Annotations: map[string]string{
"kafmesh/scrape": "true",
},
},
Status: v1.PodStatus{
Phase: v1.PodRunning,
PodIP: "1.1.1.1",
},
}
pod2 := v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod2",
Annotations: map[string]string{
"kafmesh/scrape": "true",
"kafmesh/port": "7777",
},
},
Status: v1.PodStatus{
Phase: v1.PodPending,
PodIP: "1.1.1.2",
},
}
pod3 := v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod3",
Annotations: map[string]string{
"kafmesh/scrape": "true",
"kafmesh/port": "7777",
},
},
Status: v1.PodStatus{
Phase: v1.PodRunning,
PodIP: "1.1.1.3",
},
}
lister.EXPECT().
List(gomock.Any(), gomock.Any()).
Return(&v1.PodList{
Items: []v1.Pod{
pod1,
pod2,
pod3,
v1.Pod{},
v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod8",
Annotations: map[string]string{},
},
Status: v1.PodStatus{
Phase: v1.PodRunning,
PodIP: "1.1.1.2",
},
},
},
}, nil).
Times(1)
job := scraper.NewJob(lister, discoverFactory)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pods, err := job.GetKafmeshPods(ctx)
assert.NilError(t, err)
assert.DeepEqual(t, pods, []v1.Pod{pod1, pod2, pod3})
}
func Test_Job_ScrapePod(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
lister := NewMockPodLister(ctrl)
discoverFactory := NewMockDiscoveryFactory(ctrl)
client1 := NewMockDiscoveryClient(ctrl)
discoverFactory.EXPECT().
Client(gomock.Any(), "1.1.1.1:443").
Return(client1, func() error { return nil }, nil).
Times(1)
expectedService := &discoveryv1.Service{
Name: "service1",
Description: "service 1 does 1 things",
Components: []*discoveryv1.Component{
&discoveryv1.Component{
Name: "component 1",
Description: "component 1 is in charge of the 1 processes",
Sources: []*discoveryv1.Source{
&discoveryv1.Source{
Topic: &discoveryv1.TopicDefinition{
Topic: "the.1.topic",
Message: "the.1.message",
},
},
},
Processors: []*discoveryv1.Processor{
&discoveryv1.Processor{
Name: "processor 1",
},
},
Sinks: []*discoveryv1.Sink{
&discoveryv1.Sink{
Name: "sink 1",
},
},
Views: []*discoveryv1.View{
&discoveryv1.View{
Topic: &discoveryv1.TopicDefinition{
Topic: "view.1.topic",
Message: "view.1.message",
},
},
},
ViewSinks: []*discoveryv1.ViewSink{
&discoveryv1.ViewSink{
Topic: &discoveryv1.TopicDefinition{
Topic: "viewsink.1.topic",
Message: "viewsink.1.message",
},
},
},
ViewSources: []*discoveryv1.ViewSource{
&discoveryv1.ViewSource{
Topic: &discoveryv1.TopicDefinition{
Topic: "viewsource.1.topic",
Message: "viewsource.1.message",
},
},
},
},
},
}
client1.EXPECT().
GetServiceInfo(gomock.Any(), &discoveryv1.GetServiceInfoRequest{}).
Return(&discoveryv1.GetServiceInfoResponse{
Service: expectedService,
}, nil).
Times(1)
job := scraper.NewJob(lister, discoverFactory)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
service, err := job.ScrapePod(ctx, v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "pod1",
Annotations: map[string]string{
"kafmesh/scrape": "true",
},
},
Status: v1.PodStatus{
Phase: v1.PodRunning,
PodIP: "1.1.1.1",
},
})
assert.NilError(t, err)
assert.DeepEqual(t, service, expectedService)
}
|
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package external
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestRangePropertyCodec(t *testing.T) {
prop := &rangeProperty{
key: []byte("key"),
offset: 1,
size: 2,
keys: 3,
}
buf := encodeProp(nil, prop)
prop2 := decodeProp(buf)
require.EqualValues(t, prop, prop2)
p1, p2, p3 := &rangeProperty{}, &rangeProperty{}, &rangeProperty{}
for i, p := range []*rangeProperty{p1, p2, p3} {
p.key = []byte(fmt.Sprintf("key%d", i))
p.offset = uint64(10 * i)
p.size = uint64(20 * i)
p.keys = uint64(30 * i)
}
buf = encodeMultiProps(nil, []*rangeProperty{p1, p2, p3})
props := decodeMultiProps(buf)
require.EqualValues(t, []*rangeProperty{p1, p2, p3}, props)
}
|
package flow
import (
"testing"
"time"
)
func TestRegistry(t *testing.T) {
r := new(MeterRegistry)
m1 := r.Get("first")
m2 := r.Get("second")
m1.Mark(10)
m2.Mark(30)
time.Sleep(2 * time.Second)
if total := r.Get("first").Snapshot().Total; total != 10 {
t.Errorf("expected first total to be 10, got %d", total)
}
if total := r.Get("second").Snapshot().Total; total != 30 {
t.Errorf("expected second total to be 30, got %d", total)
}
expectedMeters := map[string]*Meter{
"first": m1,
"second": m2,
}
r.ForEach(func(n string, m *Meter) {
if expectedMeters[n] != m {
t.Errorf("wrong meter '%s'", n)
}
delete(expectedMeters, n)
})
if len(expectedMeters) != 0 {
t.Errorf("missing meters: '%v'", expectedMeters)
}
r.Remove("first")
found := false
r.ForEach(func(n string, m *Meter) {
if n != "second" {
t.Errorf("found unexpected meter: %s", n)
return
}
if found {
t.Error("found meter twice")
}
found = true
})
if !found {
t.Errorf("didn't find second meter")
}
m3 := r.Get("first")
if m3 == m1 {
t.Error("should have gotten a new meter")
}
if total := m3.Snapshot().Total; total != 0 {
t.Errorf("expected first total to now be 0, got %d", total)
}
expectedMeters = map[string]*Meter{
"first": m3,
"second": m2,
}
r.ForEach(func(n string, m *Meter) {
if expectedMeters[n] != m {
t.Errorf("wrong meter '%s'", n)
}
delete(expectedMeters, n)
})
if len(expectedMeters) != 0 {
t.Errorf("missing meters: '%v'", expectedMeters)
}
}
|
package cm15
import (
"encoding/json"
"time"
)
// RubyTime is a wrapper around time.Time that adds the ability to unmarshal ruby JSON date time
// values.
type RubyTime struct {
time.Time
}
// MarshalJSON implements the marshaller interface.
func (r *RubyTime) MarshalJSON() ([]byte, error) {
return json.Marshal(r.Format("2006/01/02 15:04:05 -0700"))
}
// UnmarshalJSON implements the unmarshaller interface.
func (r *RubyTime) UnmarshalJSON(b []byte) (err error) {
s := string(b)
t, err := time.ParseInLocation("2006/01/02 15:04:05 -0700", s[1:len(s)-1], time.UTC)
if err != nil {
return err
}
r.Time = t
return nil
}
|
package semver
import (
"testing"
)
func TestMajor(t *testing.T) {
tests := []struct {
name string
sample string
want int
}{
{
name: "sample-1",
sample: "v12.3.1",
want: 12,
},
{
name: "sample-2",
sample: "v0.0.1",
want: 0,
},
{
name: "sample-3",
sample: "v.1.2",
want: -1,
},
{
name: "sample-4",
sample: "",
want: -1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Major(tt.sample); got != tt.want {
t.Errorf("Major() = %v, want %v", got, tt.want)
}
})
}
}
func TestMajorMinorPatch(t *testing.T) {
tests := []struct {
name string
version string
want [3]int
}{
{
name: "trivial",
version: "v1.2.3",
want: [3]int{1, 2, 3},
},
{
name: "valid",
version: "v1.2.3-alpha",
want: [3]int{1, 2, 3},
},
{
name: "another-valid",
version: "v1.2.3+alpha",
want: [3]int{1, 2, 3},
},
{
name: "invalid",
version: "v1.2-alpha",
want: [3]int{0, 0, 0},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1, got2 := MajorMinorPatch(tt.version)
if got != tt.want[0] {
t.Errorf("MajorMinorPatch() got = %v, want %v", got, tt.want)
}
if got1 != tt.want[1] {
t.Errorf("MajorMinorPatch() got1 = %v, want %v", got1, tt.want[1])
}
if got2 != tt.want[2] {
t.Errorf("MajorMinorPatch() got2 = %v, want %v", got2, tt.want[2])
}
})
}
}
func TestPseudo(t *testing.T) {
tests := []struct {
name string
v string
want string
}{
{
name: "simple-semver",
v: "v0.1.2",
want: "",
},
{
name: "semver-with-suffix",
v: "v0.1.2-alpha",
want: "",
},
{
name: "pseudo-semver",
v: "v0.0.0-20190313170020-28fc84874d7f",
want: "28fc84874d7f",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Pseudo(tt.v); got != tt.want {
t.Errorf("Pseudo() = %v, want %v", got, tt.want)
}
})
}
}
func TestIsPrerelease(t *testing.T) {
tests := []struct {
name string
v string
want bool
}{
{
name: "not-1",
v: "v0.1.2",
want: false,
},
{
name: "not-2",
v: "v0.0.0-20190313170020-28fc84874d7f",
want: false,
},
{
name: "alpha",
v: "v2.1.2-pre-meta",
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := IsPrerelease(tt.v); got != tt.want {
t.Errorf("IsPrerelease() = %v, want %v", got, tt.want)
}
})
}
}
|
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/shitakemura/myapi/api"
_ "github.com/go-sql-driver/mysql"
)
var (
dbUser = os.Getenv("DB_USER")
dbPassword = os.Getenv("DB_PASSWORD")
dbDatabase = os.Getenv("DB_NAME")
dbConn = fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?parseTime=true", dbUser, dbPassword, dbDatabase)
)
func main() {
db, err := sql.Open("mysql", dbConn)
if err != nil {
log.Println("fail to connect DB")
return
}
r := api.NewRouter(db)
log.Println("server start at port 8080")
log.Fatal(http.ListenAndServe(":8080", r))
}
|
package fulladdress
import (
"fmt"
"net"
"regexp"
"strconv"
)
var (
regIPv4 *regexp.Regexp
regIPv6 *regexp.Regexp
)
func init() {
regIPv4, _ = regexp.Compile(`^((?:[0-9]{1,3}\.){3}[0-9]{1,3}):([0-9]{1,5})$`)
regIPv6, _ = regexp.Compile(`^\[((?:(?:[a-fA-F0-9]{1,4})?:){2,7}(?:[a-fA-F0-9]{1,4}))\]:([0-9]{1,5})$`)
}
// FullAddresss include
type FullAddresss struct {
IPAddr net.IP
Port uint16
}
// NewFullAddresss create FullAddresss from string
func NewFullAddresss(str string) (addr *FullAddresss, err error) {
for _, reg := range []*regexp.Regexp{regIPv4, regIPv6} {
match := reg.FindStringSubmatch(str)
if len(match) != 3 {
continue
}
ipAddr := net.ParseIP(match[1])
if ipAddr == nil {
return nil, getParseIPFailError(str)
}
port, e := parsePort(match[2])
if e != nil {
ei := e.(ParseAddrError)
ei.input = str
return nil, ei
}
addr = &FullAddresss{
IPAddr: ipAddr,
Port: uint16(port),
}
return
}
return nil, getUnrecognizeError(str)
}
// String impl interface fmt.Stringer
func (addr *FullAddresss) String() (str string) {
if ipv4 := addr.IPAddr.To4(); ipv4 == nil {
return fmt.Sprintf("[%s]:%d", addr.IPAddr.String(), addr.Port)
}
return fmt.Sprintf("%s:%d", addr.IPAddr.String(), addr.Port)
}
func parsePort(str string) (port uint16, err error) {
interalPort, e := strconv.ParseInt(str, 10, 32)
if e != nil {
return 0, getParsePortFailError("", e)
}
if interalPort >= 65536 || interalPort < 0 {
return 0, getPortOutOfRangeError("")
}
return uint16(interalPort), nil
}
|
package encoding
import (
"context"
"encoding/json"
"net/http"
libError "github.com/angryronald/guestlist/lib/error"
)
func EncodeError(ctx context.Context, err error, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
code := http.StatusInternalServerError
message := "Something Went Wrong"
if sc, ok := err.(*libError.Error); ok {
code = sc.StatusCode
message = sc.Message
}
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"error": err.Error(),
"code": code,
"message": message,
})
}
|
package api
import (
"fmt"
"golang-distributed-parallel-image-processing/api/download"
"golang-distributed-parallel-image-processing/api/login"
"golang-distributed-parallel-image-processing/api/logout"
"golang-distributed-parallel-image-processing/api/status"
"golang-distributed-parallel-image-processing/api/upload"
"golang-distributed-parallel-image-processing/api/workloads"
"golang-distributed-parallel-image-processing/models"
"net/http"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
//Module ...
type Module struct {
Method string
Path string
Function echo.HandlerFunc
Middleware *echo.MiddlewareFunc
}
var IsLoggedIn = checkIfLoggedIn()
func checkIfLoggedIn() echo.MiddlewareFunc {
data := middleware.JWTWithConfig(middleware.JWTConfig{
SigningKey: []byte("secret"),
})
return data
}
// LoadModules ...
func LoadModules() []*Module {
return []*Module{
{
Method: "GET",
Path: "/",
Function: rootResponse,
},
{
Method: "GET",
Path: "/login",
Function: login.LoginResponse,
},
{
Method: "GET",
Path: "/logout",
Function: logout.LogoutResponse,
Middleware: &IsLoggedIn,
},
{
Method: "GET",
Path: "/status",
Function: status.StatusResponse,
Middleware: &IsLoggedIn,
},
{
Method: "GET",
Path: "/status/:worker",
Function: status.StatusWorkerResponse,
Middleware: &IsLoggedIn,
},
{
Method: "POST",
Path: "/upload",
Function: upload.UploadResponse,
},
{
Method: "GET",
Path: "/workloads/test",
Function: workloads.WorkloadsResponse,
Middleware: &IsLoggedIn,
},
{
Method: "POST",
Path: "/workloads/filter",
Function: workloads.WorkloadsFilterResponse,
Middleware: &IsLoggedIn,
},
{
Method: "POST",
Path: "/download",
Function: download.DownloadResponse,
},
}
}
func rootResponse(c echo.Context) error {
fmt.Println("[ACCESS] New connection to:\t/")
return c.JSON(http.StatusForbidden, &models.Message{Message: "You're not allowed to do this. [AM - Nothing here to see]"})
}
|
// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
// Package gtest provides simple and useful test utils.
//
// 测试模块.
package gtest
import (
"fmt"
"github.com/gogf/gf/g/util/gconv"
"os"
"reflect"
"regexp"
"runtime"
"testing"
)
// 封装一个测试用例
func Case(t *testing.T, f func()) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintf(os.Stderr, "%v\n%s", err, getBacktrace())
t.Fail()
}
}()
f()
}
// 断言判断, 相等
func Assert(value, expect interface{}) {
rvValue := reflect.ValueOf(value)
rvExpect := reflect.ValueOf(expect)
if rvValue.Kind() == reflect.Ptr {
if rvValue.IsNil() {
value = nil
}
}
if rvExpect.Kind() == reflect.Map {
if err := compareMap(value, expect); err != nil {
panic(err)
}
return
}
if fmt.Sprintf("%v", value) != fmt.Sprintf("%v", expect) {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v == %v`, value, expect))
}
}
// 断言判断, 相等, 包括数据类型
func AssertEQ(value, expect interface{}) {
// 类型判断
t1 := reflect.TypeOf(value)
t2 := reflect.TypeOf(expect)
if t1 != t2 {
panic(fmt.Sprintf(`[ASSERT] EXPECT TYPE %v == %v`, t1, t2))
}
rvValue := reflect.ValueOf(value)
rvExpect := reflect.ValueOf(expect)
if rvValue.Kind() == reflect.Ptr {
if rvValue.IsNil() {
value = nil
}
}
if rvExpect.Kind() == reflect.Map {
if err := compareMap(value, expect); err != nil {
panic(err)
}
return
}
if fmt.Sprintf("%v", value) != fmt.Sprintf("%v", expect) {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v == %v`, value, expect))
}
}
// 断言判断, 不相等
func AssertNE(value, expect interface{}) {
rvValue := reflect.ValueOf(value)
rvExpect := reflect.ValueOf(expect)
if rvValue.Kind() == reflect.Ptr {
if rvValue.IsNil() {
value = nil
}
}
if rvExpect.Kind() == reflect.Map {
if err := compareMap(value, expect); err == nil {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v != %v`, value, expect))
}
return
}
if fmt.Sprintf("%v", value) == fmt.Sprintf("%v", expect) {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v != %v`, value, expect))
}
}
// 断言判断, value > expect; 注意: 仅有字符串、整形、浮点型才可以比较
func AssertGT(value, expect interface{}) {
passed := false
switch reflect.ValueOf(expect).Kind() {
case reflect.String:
passed = gconv.String(value) > gconv.String(expect)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
passed = gconv.Int(value) > gconv.Int(expect)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
passed = gconv.Uint(value) > gconv.Uint(expect)
case reflect.Float32, reflect.Float64:
passed = gconv.Float64(value) > gconv.Float64(expect)
}
if !passed {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v > %v`, value, expect))
}
}
// 断言判断, value >= expect; 注意: 仅有字符串、整形、浮点型才可以比较
func AssertGTE(value, expect interface{}) {
passed := false
switch reflect.ValueOf(expect).Kind() {
case reflect.String:
passed = gconv.String(value) >= gconv.String(expect)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
passed = gconv.Int(value) >= gconv.Int(expect)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
passed = gconv.Uint(value) >= gconv.Uint(expect)
case reflect.Float32, reflect.Float64:
passed = gconv.Float64(value) >= gconv.Float64(expect)
}
if !passed {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v >= %v`, value, expect))
}
}
// 断言判断, value < expect; 注意: 仅有字符串、整形、浮点型才可以比较
func AssertLT(value, expect interface{}) {
passed := false
switch reflect.ValueOf(expect).Kind() {
case reflect.String:
passed = gconv.String(value) < gconv.String(expect)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
passed = gconv.Int(value) < gconv.Int(expect)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
passed = gconv.Uint(value) < gconv.Uint(expect)
case reflect.Float32, reflect.Float64:
passed = gconv.Float64(value) < gconv.Float64(expect)
}
if !passed {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v < %v`, value, expect))
}
}
// 断言判断, value <= expect; 注意: 仅有字符串、整形、浮点型才可以比较
func AssertLTE(value, expect interface{}) {
passed := false
switch reflect.ValueOf(expect).Kind() {
case reflect.String:
passed = gconv.String(value) <= gconv.String(expect)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
passed = gconv.Int(value) <= gconv.Int(expect)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
passed = gconv.Uint(value) <= gconv.Uint(expect)
case reflect.Float32, reflect.Float64:
passed = gconv.Float64(value) <= gconv.Float64(expect)
}
if !passed {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v <= %v`, value, expect))
}
}
// 断言判断, value IN expect; 注意: expect必须为slice类型
func AssertIN(value, expect interface{}) {
passed := false
switch reflect.ValueOf(expect).Kind() {
case reflect.Slice, reflect.Array:
for _, v := range gconv.Interfaces(expect) {
if v == value {
passed = true
break
}
}
}
if !passed {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v IN %v`, value, expect))
}
}
// 断言判断, value NOT IN expect; 注意: expect必须为slice类型
func AssertNI(value, expect interface{}) {
passed := false
switch reflect.ValueOf(expect).Kind() {
case reflect.Slice, reflect.Array:
for _, v := range gconv.Interfaces(expect) {
if v == value {
passed = true
break
}
}
}
if passed {
panic(fmt.Sprintf(`[ASSERT] EXPECT %v NOT IN %v`, value, expect))
}
}
// 提示错误不退出进程执行
func Error(message...interface{}) {
fmt.Fprintf(os.Stderr, "[ERROR] %s\n%s", fmt.Sprint(message...), getBacktrace())
}
// 提示错误并退出进程执行
func Fatal(message...interface{}) {
fmt.Fprintf(os.Stderr, "[FATAL] %s\n%s", fmt.Sprint(message...), getBacktrace())
os.Exit(1)
}
// Map比较,如果相等返回nil,否则返回错误信息.
func compareMap(value, expect interface{}) error {
rvValue := reflect.ValueOf(value)
rvExpect := reflect.ValueOf(expect)
if rvValue.Kind() == reflect.Ptr {
if rvValue.IsNil() {
value = nil
}
}
if rvExpect.Kind() == reflect.Map {
if rvValue.Kind() == reflect.Map {
if rvExpect.Len() == rvValue.Len() {
ksExpect := rvExpect.MapKeys()
for _, key := range ksExpect {
if fmt.Sprintf("%v", rvValue.MapIndex(key).Interface()) != fmt.Sprintf("%v", rvExpect.MapIndex(key).Interface()) {
return fmt.Errorf(`[ASSERT] EXPECT VALUE map["%v"]:%v == %v`,
key,
rvValue.MapIndex(key).Interface(),
rvExpect.MapIndex(key).Interface(),
)
}
}
} else {
return fmt.Errorf(`[ASSERT] EXPECT MAP LENGTH %d == %d`, rvExpect.Len(), rvValue.Len())
}
} else {
return fmt.Errorf(`[ASSERT] EXPECT VALUE TO BE A MAP`)
}
}
return nil
}
// 获取文件调用回溯字符串,参数skip表示调用端往上多少级开始回溯
func getBacktrace(skip...int) string {
customSkip := 0
if len(skip) > 0 {
customSkip = skip[0]
}
backtrace := ""
index := 1
from := 0
// 首先定位业务文件开始位置
for i := 0; i < 10; i++ {
if _, file, _, ok := runtime.Caller(i); ok {
if reg, _ := regexp.Compile(`gtest\.go$`); !reg.MatchString(file) {
from = i
break
}
}
}
// 从业务文件开始位置根据自定义的skip开始backtrace
goRoot := runtime.GOROOT()
for i := from + customSkip; i < 10000; i++ {
if _, file, cline, ok := runtime.Caller(i); ok && file != "" {
if reg, _ := regexp.Compile(`<autogenerated>`); reg.MatchString(file) {
continue
}
if reg, _ := regexp.Compile(`gtest\.go$`); reg.MatchString(file) {
continue
}
if goRoot != "" {
if reg, _ := regexp.Compile("^" + goRoot); reg.MatchString(file) {
continue
}
}
backtrace += fmt.Sprintf(`%d. %s:%d%s`, index, file, cline, "\n")
index++
} else {
break
}
}
return backtrace
}
|
package requests
type CreateSprint struct {
Name string `validate:"required,min=2,max=36"`
Description string
}
type UpdateSprint struct {
Name string `validate:"required,min=2,max=36"`
Description string
}
func (c *CreateSprint) Valid() error {
return validate.Struct(c)
}
func (c *UpdateSprint) Valid() error {
return validate.Struct(c)
}
|
package main
import (
"fmt"
"sort"
)
func main() {
test1 := []int{1, 2}
test2 := []int{3, 4, 5}
//var test3 []int
for _, x := range test2 {
test1 = append(test1, x)
}
sort.Ints(test1)
if len(test1)%2 == 1 {
med := len(test1) / 2
fmt.Println(test1[med])
fmt.Println("test1")
return
}
index := len(test1) / 2
fmt.Println(index)
var ans float64
ans = float64((test1[index] + test1[index-1])) / 2.0
fmt.Println(ans)
fmt.Println(5 / 2.0)
//fmt.Println(ans)
//fmt.Println(med)
//fmt.Println(test1[med])
}
|
package dht
import (
"fmt"
"math/big"
eHex "encoding/hex"
"time"
)
/*
Heartbeat: allows us to say if our predecessor is alive or not, so that we know if we have to make data original or not
Include the predecessor of the predecessor in the heartbeat
(Heartbeat could also be used by our successor so that we may know if we are replicating data to a node which is alive or not)
For the other fingers, a message will circulate in the ring saying "update your fingers", waiting time should be around 1 second I guess
*/
const nBits = 160
type NODE struct{
ID string
key string
address string
coordinates [2]string //(address, ID)
successor [2]string //(address, ID)
predecessor [2]string //(address, ID)
predOfPred [2]string //(address, ID)
fingers [nBits][2]string
transport *Transport
data DATASET
alive bool
}
func makeDHTNode(id, ip, port string) *NODE {
node := new(NODE)
node.ID = id
node.key = id
node.address = ip + ":" + port
node.coordinates = [2]string {node.address, node.ID}/*address of the node*/
node.successor = [2]string {node.address, node.ID}
node.predecessor = [2]string {node.address, node.ID}
node.predOfPred = [2]string{node.address, node.ID}
for i := 0; i < nBits; i++ {
node.fingers[i] = [2]string{}
}
node.transport = &Transport{node.address, make(chan *Msg), node, make(chan *Msg)}
createData(node)
node.alive = true
go node.transport.listen()
node.transport.msgHandler()
return node
}
func (node *NODE) lookup(msg *Msg) {
nodeID := node.ID
var message *Msg
if between([]byte(node.predecessor[1]), []byte(nodeID), []byte(msg.Key)) {
switch msg.Type {
case "lookup":
message = responseMsg(node.coordinates, msg.Src)
node.transport.send(message)
case "addToRing":
message = responseAddMsg(node.coordinates, msg.Src, node.predecessor)
node.transport.send(message)
case "fingerLookup":
message = responseFingerLookup(node.coordinates, msg.Src, msg.FingerID)
node.transport.send(message)
case "newData":
node.data.storeData(msg.Key, msg.Data)
fmt.Println(msg.Data, "stored in node", node.ID, "successor is", node.successor[1])
case "serverLookupGet":
value := node.data.StoredData[msg.Key].Value
message = serverResponseMsg(node.coordinates, msg.Src, msg.Key, value)
node.transport.send(message)
case "serverLookupPut":
fmt.Printf("Original node before PUT: Node %s, value %s\n", node.ID, node.data.StoredData[msg.Key].Value)
// node.setValue(msg.Key, msg.KeyVal)
var tmp = node.data.StoredData[msg.Key]
tmp.Value = msg.KeyVal
node.data.StoredData[msg.Key]=tmp
fmt.Printf("Original node after PUT: Node %s, value %s\n", node.ID, node.data.StoredData[msg.Key].Value)
message = serverResponsePutSuccMsg(node.successor, msg.Key, msg.KeyVal)
node.transport.send(message)
fmt.Printf("Put request done at successor node:\n \tFor the key: %s the new value is: %s\n", msg.Key, msg.KeyVal)
message = serverResponseMsg(node.coordinates, msg.Src, msg.Key, msg.KeyVal)
node.transport.send(message)
case "serverLookupPost":
newData := DATA{msg.KeyVal, true, msg.Key}
node.data.storeData(msg.Key, newData)
message = serverResponseMsg(node.coordinates, msg.Src, msg.Key, node.data.StoredData[msg.Key].Value)
node.transport.send(message)
case "serverLookupDelete":
fmt.Printf("Original node before DELETE: Node %s, key %s, value %s\n", node.ID, msg.Key, node.data.StoredData[msg.Key].Value)
delete(node.data.StoredData, msg.Key)
fmt.Printf("Original node after DELETE: Node %s, key %s, value %s\n", node.ID, msg.Key, node.data.StoredData[msg.Key].Value)
message = serverResponseDeleteSuccMsg(node.successor, msg.Key)
node.transport.send(message)
fmt.Printf("Delete request done at successor node:\n \tThe pair of the key-> %s was deleted\n", msg.Key)
message = serverResponseMsg(node.coordinates, msg.Src, msg.Key, msg.KeyVal)
node.transport.send(message)
default:
fmt.Println("Wrong lookup type!")
}
}else{
intDist := big.NewInt(0)
following := node.successor
for i:=0; i < nBits; i++ {
if(node.fingers[i] != [2]string{}){
distance := distance([]byte(node.fingers[i][0]), []byte(node.ID), nBits)
if (distance.Cmp(intDist) == -1) {
following = node.fingers[i]
}
}
}
message = lookupMsgWithFingerAndData(msg.Src, following, msg.Type, msg.Key, msg.KeyVal, msg.FingerID, msg.Data, msg.Original)
node.transport.send(message)
}
}
func (node *NODE) findFingers() {
decoded, _ := eHex.DecodeString(node.ID)
for i := 0; i < nBits; i++ {
hex, _ := calcFinger(decoded, i+1, nBits)
node.transport.send(lookupMsgWithFinger(node.coordinates, node.successor, "fingerLookup", hex, i))
}
}
func (first *NODE) addToRing(node *NODE) {
msg:=lookupMsg(node.coordinates, first.coordinates, "addToRing", node.key)
fmt.Println(node.coordinates[0], node.coordinates[1])
node.transport.send(msg)
}
func (node *NODE) addResponseHandler(msg *Msg) {
node.successor = msg.Src
node.predecessor = msg.Node
node.predOfPred = msg.Node
node.transport.send(youAreMySuccMsg(node.coordinates, node.successor))
node.transport.send(youAreMyPredMsg(node.coordinates, node.predecessor))
go node.transport.sendHeartBeat()
go node.transport.heartBeatListen()
}
func (node *NODE) succHandler(msg *Msg) {
node.predecessor = msg.Src
}
func (node *NODE) predHandler(msg *Msg) {
node.successor = msg.Src
}
func (node *NODE) fingerLookupHandler(msg *Msg) {
node.fingers[msg.FingerID] = msg.Src
}
func (node *NODE) replicationHandler(msg *Msg) {
node.data.storeData(msg.Key, msg.Data)
}
//Is this needed?
func (node *NODE) responseHandler(msg *Msg) {
//TODO
}
func (node *NODE) printFingers() {
for i := 0; i < nBits; i++ {
fmt.Println("Finger #",i,":", node.fingers[i][0], ",", node.fingers[i][1])
}
}
func (node *NODE) printNode(finger bool) {
fmt.Println("Address:", node.address)
fmt.Println("ID:", node.ID)
fmt.Println("Predecessor:", node.predecessor[0], ",", node.predecessor[1])
fmt.Println("Successor:", node.successor[0], ",", node.successor[1])
if finger {
node.printFingers()
}
}
func (node *NODE) deadPredecessor() {
node.predecessor = node.predOfPred
fmt.Println("Dead pred, Node.predecessor =", node.predecessor)
message := deadSuccMsg(node.coordinates, node.predecessor)
node.transport.send(message)
node.data.transferFalseData()
node.data.makeEverythingOriginal()
}
func (node *NODE) deadSuccessor(msg *Msg) {
node.successor = msg.Src
node.data.transferTrueData()
}
//functions that need to be called from the main/test function
func (node *NODE) addNewData(value string) {
//generate a key for now, implement hashing function later
key := generateNodeId()
newData := DATA{value, true, key}
message := lookupMsgWithData(node.coordinates, node.coordinates, "newData", key, newData)
node.transport.send(message)
}
func (node *NODE) addNewDataToNode(value string, key string) {
newData := DATA{value, true, key}
node.data.storeData(node.key, newData)
}
func (node *NODE) updateFingers() {
node.findFingers()
time.Sleep(500 * time.Millisecond)
message := updateMsg(node.coordinates, node.successor)
node.transport.send(message)
}
func (node *NODE) kill() {
fmt.Println("This node was killed:", node.address)
node.alive = false
}
func (node *NODE) printRing(msg *Msg) {
if node.coordinates[0] == msg.Node[0] {
fmt.Println("Printing ring...")
fmt.Println("****************************************")
}
fmt.Println("Address:", node.coordinates[0])
fmt.Println("Identifier:", node.coordinates[1])
switch msg.FingerID {
case 0:
fmt.Println("Predecessor:", node.predecessor[0])
fmt.Println("Successor:", node.successor[0])
case 1:
node.data.printData()
case 2:
node.printFingers()
case 3:
fmt.Println("Predecessor:", node.predecessor[0])
fmt.Println("Successor:", node.successor[0])
node.data.printData()
}
fmt.Println("****************************************")
if node.successor[0] != msg.Node[0] {
message := printRingMsg(node.coordinates, node.successor, msg.Node, msg.FingerID)
node.transport.send(message)
}
}
func (node *NODE) deleteValue(key string){
fmt.Printf("Successor node before DELETE: Node %s, key %s, value %s\n", node.ID, key, node.data.StoredData[key].Value)
delete(node.data.StoredData, key)
fmt.Printf("Successor node after DELETE: Node %s, key %s, value %s\n", node.ID, key, node.data.StoredData[key].Value)
}
func (node *NODE) setValue(key string, keyValue string){
fmt.Printf("Successor node before PUT: Node %s, value %s\n", node.ID, node.data.StoredData[key].Value)
var tmp = node.data.StoredData[key]
tmp.Value = keyValue
node.data.StoredData[key]=tmp
fmt.Printf("Successor node after PUT: Node %s, value %s\n", node.ID, node.data.StoredData[key].Value)
}
|
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
conn, err := net.Dial("tcp", "localhost:8888")
if err != nil {
fmt.Println("client dial err=", err)
return
}
// 功能1 客户端可以发送单行数据, 然后退出
reader := bufio.NewReader(os.Stdin) // os.Stdin 代表标准输入 [终端]
for {
// 从终端读取一行用户输入,并准备发送给服务器
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("readString err=", err)
}
// 如果用户输入的是 exit 就退出
line = strings.Trim(line, " \r\n")
if line == "exit" {
fmt.Println("客户端退出...")
break
}
// 再将 line 发送给 服务器
_, err = conn.Write([]byte(line+"\n"))
if err != nil {
fmt.Println("conn.Write err=", err)
}
}
}
|
/*
* Copyright 2020-present Open Networking Foundation
* 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 device
import (
"context"
"github.com/opencord/voltha-protos/v4/go/voltha"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func (agent *Agent) getTransientState() voltha.DeviceTransientState_Types {
transientStateHandle := agent.transientStateLoader.Lock()
deviceTransientState := transientStateHandle.GetReadOnly()
transientStateHandle.UnLock()
return deviceTransientState
}
func (agent *Agent) updateTransientState(ctx context.Context, transientState voltha.DeviceTransientState_Types) error {
// Update device transient state
transientStateHandle := agent.transientStateLoader.Lock()
if err := transientStateHandle.Update(ctx, transientState); err != nil {
transientStateHandle.UnLock()
return status.Errorf(codes.Internal, "failed-update-device-transient-state:%s: %s", agent.deviceID, err)
}
transientStateHandle.UnLock()
return nil
}
func (agent *Agent) isDeletionInProgress() bool {
deviceTransientState := agent.getTransientState()
return deviceTransientState == voltha.DeviceTransientState_FORCE_DELETING ||
deviceTransientState == voltha.DeviceTransientState_DELETING_FROM_ADAPTER ||
deviceTransientState == voltha.DeviceTransientState_DELETING_POST_ADAPTER_RESPONSE
}
func (agent *Agent) isStateDeleting(deviceTransientState voltha.DeviceTransientState_Types) bool {
return deviceTransientState == voltha.DeviceTransientState_FORCE_DELETING ||
deviceTransientState == voltha.DeviceTransientState_DELETING_FROM_ADAPTER ||
deviceTransientState == voltha.DeviceTransientState_DELETING_POST_ADAPTER_RESPONSE
}
func (agent *Agent) deleteTransientState(ctx context.Context) error {
transientStateHandle := agent.transientStateLoader.Lock()
if err := transientStateHandle.Delete(ctx); err != nil {
transientStateHandle.UnLock()
return status.Errorf(codes.Internal, "failed-delete-device-transient-state:%s: %s", agent.deviceID, err)
}
transientStateHandle.UnLock()
return nil
}
|
package main
import (
"fmt"
)
func exec1() {
a := 99
fmt.Printf("%v -- %T\n", a, a)
}
func exec2() {
str1 := "yang yuei xiong"
arr1 := []string{"java", "python", "golang"}
for _, i := range str1 {
fmt.Printf("%c %v %T\n", i, i, i)
}
for _, i := range arr1 {
fmt.Printf("%v %T\n", i, i)
}
}
func exec3() {
// 字符串替换 ascii,utf8
y := "yyx"
byteStr1 := []byte(y)
byteStr2 := []rune(y)
byteStr1[0] = 'x'
byteStr2[0] = '杨'
fmt.Println(string(byteStr1))
fmt.Println(string(byteStr2))
}
var x1 = 1
var s1 = "yangyuexiong"
const x2 = 999
const s2 = "yyx"
func main() {
println("hello world")
print("hello golang\n")
fmt.Printf("%v -- %T\n", x1, x1)
fmt.Printf("%v -- %T\n", s1, s1)
fmt.Printf("%v -- %T\n", x2, x2)
fmt.Printf("%v -- %T\n", s2, s2)
exec1()
exec2()
exec3()
}
|
package main
import (
"github.com/gin-gonic/gin"
"github.com/tomasen/ginkin"
"gopkg.in/alecthomas/kingpin.v2"
"log"
"net/http"
)
func main() {
apis := map[string]ginkin.APIHandler{
"version": {"GET", DescribeVersion, "print version info"},
"user/list": {"POST", UserList, "list users"},
"user/:user": {"GET", DescribeUser, "print user info"},
"user/:user#del": {"DELETE", DeleteUser, "print user info"},
"user/add": {"PUT", AddUsers, "add users"},
}
// prepare gin engine
router := gin.Default()
// add other flag or more command to kingpin
kingpin.HelpFlag.Short('h')
gk := &ginkin.GinKin{
APIs: apis,
Start: ServeGin,
Fallback: CLIFallback,
}
gk.Run(router, "/")
}
func UserList(c *gin.Context) {
c.JSON(http.StatusOK, "john")
}
func DescribeUser(c *gin.Context) {
user, exist := c.Params.Get("user")
if !exist {
c.Status(http.StatusBadRequest)
return
}
c.JSON(http.StatusOK, user)
}
func AddUsers(c *gin.Context) {
var users []string
if err := c.ShouldBindJSON(&users); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, users)
}
func DeleteUser(c *gin.Context) {
user, _ := c.Params.Get("user")
log.Println("deleting:", user)
c.Status(http.StatusOK)
}
func DescribeVersion(c *gin.Context) {
c.JSON(http.StatusOK, "0.1")
}
func ServeGin(router *gin.Engine) {
router.Run(":3000")
}
func CLIFallback(cmd string) {
log.Println("unhandled command line action:", cmd)
}
|
package http
import (
"fmt"
"reflect"
"strconv"
)
// PluginRouter 插件路由
type PluginRouter struct {
handlers []HandleFunc
private bool
group bool
discuss bool
}
// Plugin is the plugin of hanabi
type Plugin interface {
Parse(ctx *CQContext)
}
// HandleFunc 处理函数
type HandleFunc func(*CQContext)
func (server *Server) permision(v reflect.Value, f reflect.StructField) (per int) {
role := f.Tag.Get("role")
if role == "" {
server.SendLog(Warn, "%s插件权限读取失败,以设置默认权限为7", v.Type())
return 7
}
tmp, err := strconv.Atoi(role)
if err != nil {
server.SendLog(Warn, "%s插件权限读取失败,以设置默认权限为7", v.Type())
per = 7
} else {
per = tmp
}
return per
}
func (server *Server) checkPermission(role int) (bool, bool, bool) {
private := role & 1
group := role >> 1 & 1
discuss := role >> 2 & 1
return private == 1, group == 1, discuss == 1
}
// Register a plugin
func (server *Server) Register(pluginss ...Plugin) {
for _, plugin := range pluginss {
var cmd string
var role int
v := reflect.ValueOf(plugin)
t := reflect.TypeOf(plugin)
if f, ok := t.FieldByName("Cmd"); !ok {
server.SendLog(Error, "%s插件读取失败,检查是否包含Cmd字段", v.Type())
continue
} else {
cmd = fmt.Sprintf("%s", v.FieldByName("Cmd"))
if cmd == "" {
cmd = f.Tag.Get("mio")
}
role = server.permision(v, f)
}
if cmd == "" {
server.SendLog(Error, "%s插件读取失败,检查初始化是否正确或tag是否包含hana字段", v.Type())
continue
}
server.Plugin(cmd, role, plugin.Parse)
}
}
|
package main
import (
f "fmt"
"net"
)
func main() {
f.Println("server running 8888 port")
ln, err := net.Listen("tcp", ":8888")
if err != nil {
f.Println(err)
return
}
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
f.Println(err)
continue
}
defer conn.Close()
go requestHandler(conn)
}
}
func requestHandler(conn net.Conn) {
data := make([]byte, 4096)
for {
n, err := conn.Read(data)
if err != nil {
f.Println(err)
return
}
f.Println(string(data[:n]))
_, err = conn.Write(data[:n])
if err != nil {
f.Println(err)
return
}
}
}
|
package main
import (
"fmt"
)
// Sqrt uses Newton's method to calculate the square root
func Sqrt(x float64) float64 {
var z float64 = 1
for i := 0; i < 10; i++ {
if y := z - (z*z-x)/(2*z); y == z {
return y
} else {
z = y
fmt.Println("z =", z)
}
}
return z
}
func main() {
fmt.Println(Sqrt(9))
}
|
package usermanager
import (
"config"
"dbmanager"
"encoding/json"
"httprouter"
"io"
"lebangproto"
"logger"
"net/http"
"processor/common"
"gopkg.in/mgo.v2/bson"
)
func UpdateErrandsCommonMerchant(phone string, merchant string) {
if merchant == "就近购买" || merchant == "" {
return
}
var merchantdata lebangproto.ErrandCommonMerchant
if dbmanager.GetMongo().Find(config.DB().DBName, config.DB().CollMap["errandscommonmerchant"],
bson.M{"phone": phone}, nil, &merchantdata) {
mers := []string{merchant}
for _, v := range merchantdata.Merchant {
if merchant != v {
mers = append(mers, v)
}
if len(mers) >= 10 {
break
}
}
merchantdata.Merchant = mers
dbmanager.GetMongo().Update(config.DB().DBName, config.DB().CollMap["errandscommonmerchant"],
bson.M{"phone": phone}, &merchantdata)
} else {
merchantdata = lebangproto.ErrandCommonMerchant{
Phone: phone,
Merchant: []string{merchant},
}
dbmanager.GetMongo().Insert(config.DB().DBName, config.DB().CollMap["errandscommonmerchant"], &merchantdata)
}
}
func GetErrandsCommonMerchant(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
defer req.Body.Close()
buf := make([]byte, req.ContentLength)
common.GetBuffer(req, buf)
var reqdata lebangproto.GetErrandCommonMerchantReq
if !common.Unmarshal(buf, &reqdata) {
return
}
logger.PRINTLINE(reqdata.GetPhone())
var merchant lebangproto.ErrandCommonMerchant
var response lebangproto.GetErrandCommonMerchantRes
if dbmanager.GetMongo().Find(config.DB().DBName, config.DB().CollMap["errandscommonmerchant"],
bson.M{"phone": reqdata.GetPhone()}, nil, &merchant) {
response.Merchant = merchant.GetMerchant()
} else {
response.Errorcode = "no errandscommonmerchant"
logger.PRINTLINE("no errandscommonmerchant: ", reqdata.GetPhone())
}
sendbuf, err := json.Marshal(response)
if err != nil {
logger.PRINTLINE("Marshal response error: ", err)
return
}
io.WriteString(w, string(sendbuf))
}
|
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//371. Sum of Two Integers
//Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
//Example:
//Given a = 1 and b = 2, return 3.
//Credits:
//Special thanks to @fujiaozhu for adding this problem and creating all test cases.
//func getSum(a int, b int) int {
//}
// Time Is Money
|
package supervisor
import (
"fmt"
"net"
"os/exec"
"reflect"
"strings"
"github.com/quilt/quilt/db"
"github.com/quilt/quilt/minion/docker"
"github.com/quilt/quilt/minion/ipdef"
"github.com/quilt/quilt/util"
"github.com/vishvananda/netlink"
log "github.com/Sirupsen/logrus"
)
const (
// Etcd is the name etcd cluster store container.
Etcd = "etcd"
// Ovncontroller is the name of the OVN controller container.
Ovncontroller = "ovn-controller"
// Ovnnorthd is the name of the OVN northd container.
Ovnnorthd = "ovn-northd"
// Ovsdb is the name of the OVSDB container.
Ovsdb = "ovsdb-server"
// Ovsvswitchd is the name of the ovs-vswitchd container.
Ovsvswitchd = "ovs-vswitchd"
)
const ovsImage = "quilt/ovs"
// The tunneling protocol to use between machines.
// "stt" and "geneve" are supported.
const tunnelingProtocol = "stt"
var images = map[string]string{
Etcd: "quay.io/coreos/etcd:v3.0.2",
Ovncontroller: ovsImage,
Ovnnorthd: ovsImage,
Ovsdb: ovsImage,
Ovsvswitchd: ovsImage,
}
const etcdHeartbeatInterval = "500"
const etcdElectionTimeout = "5000"
type supervisor struct {
conn db.Conn
dk docker.Client
role db.Role
etcdIPs []string
leaderIP string
IP string
leader bool
provider string
region string
size string
}
// Run blocks implementing the supervisor module.
func Run(conn db.Conn, dk docker.Client) {
sv := supervisor{conn: conn, dk: dk}
sv.runSystem()
}
// Manage system infrstracture containers that support the application.
func (sv *supervisor) runSystem() {
imageSet := map[string]struct{}{}
for _, image := range images {
imageSet[image] = struct{}{}
}
for image := range imageSet {
go sv.dk.Pull(image)
}
loopLog := util.NewEventTimer("Supervisor")
for range sv.conn.Trigger(db.MinionTable, db.EtcdTable).C {
loopLog.LogStart()
sv.runSystemOnce()
loopLog.LogEnd()
}
}
func (sv *supervisor) runSystemOnce() {
minion, err := sv.conn.MinionSelf()
if err != nil {
return
}
var etcdRow db.Etcd
if etcdRows := sv.conn.SelectFromEtcd(nil); len(etcdRows) == 1 {
etcdRow = etcdRows[0]
}
if sv.role == minion.Role &&
reflect.DeepEqual(sv.etcdIPs, etcdRow.EtcdIPs) &&
sv.leaderIP == etcdRow.LeaderIP &&
sv.IP == minion.PrivateIP &&
sv.leader == etcdRow.Leader &&
sv.provider == minion.Provider &&
sv.region == minion.Region &&
sv.size == minion.Size {
return
}
if minion.Role != sv.role {
sv.SetInit(false)
sv.RemoveAll()
}
switch minion.Role {
case db.Master:
sv.updateMaster(minion.PrivateIP, etcdRow.EtcdIPs,
etcdRow.Leader)
case db.Worker:
sv.updateWorker(minion.PrivateIP, etcdRow.LeaderIP,
etcdRow.EtcdIPs)
}
sv.role = minion.Role
sv.etcdIPs = etcdRow.EtcdIPs
sv.leaderIP = etcdRow.LeaderIP
sv.IP = minion.PrivateIP
sv.leader = etcdRow.Leader
sv.provider = minion.Provider
sv.region = minion.Region
sv.size = minion.Size
}
func (sv *supervisor) updateWorker(IP string, leaderIP string, etcdIPs []string) {
if !reflect.DeepEqual(sv.etcdIPs, etcdIPs) {
sv.Remove(Etcd)
}
sv.run(Etcd, fmt.Sprintf("--initial-cluster=%s", initialClusterString(etcdIPs)),
"--heartbeat-interval="+etcdHeartbeatInterval,
"--election-timeout="+etcdElectionTimeout,
"--proxy=on")
sv.run(Ovsdb, "ovsdb-server")
sv.run(Ovsvswitchd, "ovs-vswitchd")
if leaderIP == "" || IP == "" {
return
}
gwMac := ipdef.IPToMac(ipdef.GatewayIP)
err := execRun("ovs-vsctl", "set", "Open_vSwitch", ".",
fmt.Sprintf("external_ids:ovn-remote=\"tcp:%s:6640\"", leaderIP),
fmt.Sprintf("external_ids:ovn-encap-ip=%s", IP),
fmt.Sprintf("external_ids:ovn-encap-type=\"%s\"", tunnelingProtocol),
fmt.Sprintf("external_ids:api_server=\"http://%s:9000\"", leaderIP),
fmt.Sprintf("external_ids:system-id=\"%s\"", IP),
"--", "add-br", "quilt-int",
"--", "set", "bridge", "quilt-int", "fail_mode=secure",
fmt.Sprintf("other_config:hwaddr=\"%s\"", gwMac))
if err != nil {
log.WithError(err).Warnf("Failed to exec in %s.", Ovsvswitchd)
return
}
ip := net.IPNet{IP: ipdef.GatewayIP, Mask: ipdef.QuiltSubnet.Mask}
if err := cfgGateway("quilt-int", ip); err != nil {
log.WithError(err).Error("Failed to configure quilt-int.")
return
}
/* The ovn controller doesn't support reconfiguring ovn-remote mid-run.
* So, we need to restart the container when the leader changes. */
sv.Remove(Ovncontroller)
sv.run(Ovncontroller, "ovn-controller")
sv.SetInit(true)
}
func (sv *supervisor) updateMaster(IP string, etcdIPs []string, leader bool) {
if sv.IP != IP || !reflect.DeepEqual(sv.etcdIPs, etcdIPs) {
sv.Remove(Etcd)
}
if IP == "" || len(etcdIPs) == 0 {
return
}
sv.run(Etcd, fmt.Sprintf("--name=master-%s", IP),
fmt.Sprintf("--initial-cluster=%s", initialClusterString(etcdIPs)),
fmt.Sprintf("--advertise-client-urls=http://%s:2379", IP),
fmt.Sprintf("--listen-peer-urls=http://%s:2380", IP),
fmt.Sprintf("--initial-advertise-peer-urls=http://%s:2380", IP),
"--listen-client-urls=http://0.0.0.0:2379",
"--heartbeat-interval="+etcdHeartbeatInterval,
"--initial-cluster-state=new",
"--election-timeout="+etcdElectionTimeout)
sv.run(Ovsdb, "ovsdb-server")
if leader {
/* XXX: If we fail to boot ovn-northd, we should give up
* our leadership somehow. This ties into the general
* problem of monitoring health. */
sv.run(Ovnnorthd, "ovn-northd")
} else {
sv.Remove(Ovnnorthd)
}
sv.SetInit(true)
}
func (sv *supervisor) run(name string, args ...string) {
isRunning, err := sv.dk.IsRunning(name)
if err != nil {
log.WithError(err).Warnf("could not check running status of %s.", name)
return
}
if isRunning {
return
}
ro := docker.RunOptions{
Name: name,
Image: images[name],
Args: args,
NetworkMode: "host",
VolumesFrom: []string{"minion"},
}
if name == Ovsvswitchd {
ro.Privileged = true
}
log.Infof("Start Container: %s", name)
_, err = sv.dk.Run(ro)
if err != nil {
log.WithError(err).Warnf("Failed to run %s.", name)
}
}
func (sv *supervisor) Remove(name string) {
log.WithField("name", name).Info("Removing container")
err := sv.dk.Remove(name)
if err != nil && err != docker.ErrNoSuchContainer {
log.WithError(err).Warnf("Failed to remove %s.", name)
}
}
func (sv *supervisor) SetInit(init bool) {
sv.conn.Txn(db.MinionTable).Run(func(view db.Database) error {
self, err := view.MinionSelf()
if err == nil {
self.SupervisorInit = init
view.Commit(self)
}
return err
})
}
func (sv *supervisor) RemoveAll() {
for name := range images {
sv.Remove(name)
}
}
func initialClusterString(etcdIPs []string) string {
var initialCluster []string
for _, ip := range etcdIPs {
initialCluster = append(initialCluster,
fmt.Sprintf("%s=http://%s:2380", nodeName(ip), ip))
}
return strings.Join(initialCluster, ",")
}
func nodeName(IP string) string {
return fmt.Sprintf("master-%s", IP)
}
// execRun() is a global variable so that it can be mocked out by the unit tests.
var execRun = func(name string, arg ...string) error {
return exec.Command(name, arg...).Run()
}
func cfgGatewayImpl(name string, ip net.IPNet) error {
link, err := linkByName(name)
if err != nil {
return fmt.Errorf("no such interface: %s (%s)", name, err)
}
if err := linkSetUp(link); err != nil {
return fmt.Errorf("failed to bring up link: %s (%s)", name, err)
}
if err := addrAdd(link, &netlink.Addr{IPNet: &ip}); err != nil {
return fmt.Errorf("failed to set address: %s (%s)", name, err)
}
return nil
}
var cfgGateway = cfgGatewayImpl
var linkByName = netlink.LinkByName
var linkSetUp = netlink.LinkSetUp
var addrAdd = netlink.AddrAdd
|
package dummyworker
import (
"context"
"time"
"math/rand"
"fmt"
"github.com/dave/blast"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
func New() blast.Worker {
return &Worker{}
}
type Worker struct {
base string
}
func (w *Worker) Start(ctx context.Context, raw map[string]interface{}) error {
var config workerConfig
if err := mapstructure.Decode(raw, &config); err != nil {
return errors.WithStack(err)
}
w.base = config.Base
fmt.Printf("Dummy worker: Initialising with %s\n", config.Base)
return nil
}
func (w *Worker) Send(ctx context.Context, raw map[string]interface{}) (map[string]interface{}, error) {
var payload payloadConfig
if err := mapstructure.Decode(raw, &payload); err != nil {
return nil, errors.WithStack(err)
}
fmt.Printf("Dummy worker: Sending payload %s %s%s\n", payload.Method, w.base, payload.Path)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// Dummy worker - wait a random time
duration := 1000 + int(r.Float64()*1000.0)
select {
case <-time.After(time.Millisecond * time.Duration(duration)):
case <-ctx.Done():
}
// Dummy worker - return an error sometimes
errorrand := r.Float64()
if errorrand > 0.95 {
return map[string]interface{}{"status": 500}, errors.New("Error 500")
} else if errorrand > 0.7 {
return map[string]interface{}{"status": 404}, errors.New("Error 404")
} else {
return map[string]interface{}{"status": 200}, nil
}
}
type workerConfig struct {
Base string `mapstructure:"base"`
}
type payloadConfig struct {
Method string `mapstructure:"method"`
Path string `mapstructure:"path"`
}
|
package model
import (
"gin-webapi/database"
"time"
"gopkg.in/mgo.v2/bson"
)
// User structure
type User struct {
ID bson.ObjectId `bson:"_id"`
FirstName string `bson:"firstname"`
LastName string `bson:"lastname"`
Address string `bson:"address"`
Age int `bson:"age"`
CreatedAt time.Time `bson:"created_at"`
UpdatedAt time.Time `bson:"updated_at"`
}
// Users list
type Users []User
// UserInfo model function
func UserInfo(id bson.ObjectId, userCollection string) (User, error) {
db := database.GetMongoDB()
user := User{}
err := db.C(userCollection).Find(bson.M{"_id": &id}).One(&user)
return user, err
}
|
package service
import (
"fmt"
"github.com/Jenkins/model"
"github.com/Jenkins/setting"
)
func AddUser(name, mobile string) error {
id, err := model.AddUser(name, mobile)
if err != nil {
return err
}
fmt.Printf("添加用户%v成功,ID为%v", name, id)
return nil
}
func UserInfo(name string) setting.User {
return model.UserInfo(name)
}
func UpdateUser(name, mobile string) error {
if err := model.UpdateMobileByName(mobile, name); err != nil {
return err
}
return nil
}
|
// Copyright 2013 The Chihaya Authors. All rights reserved.
// Use of this source code is governed by the BSD 2-Clause license,
// which can be found in the LICENSE file.
// Package config implements the configuration and loading of Chihaya configuration files.
package config
import (
"encoding/json"
"log"
"os"
"time"
)
type TrackerDuration struct {
time.Duration
}
func (d *TrackerDuration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
func (d *TrackerDuration) UnmarshalJSON(b []byte) error {
var str string
err := json.Unmarshal(b, &str)
d.Duration, err = time.ParseDuration(str)
return err
}
// TrackerIntervals represents the intervals object in a config file.
type TrackerIntervals struct {
Announce TrackerDuration `json:"announce"`
MinAnnounce TrackerDuration `json:"min_announce"`
DatabaseReload TrackerDuration `json:"database_reload"`
DatabaseSerialization TrackerDuration `json:"database_serialization"`
PurgeInactive TrackerDuration `json:"purge_inactive"`
VerifyUsedSlots int64 `json:"verify_used_slots"`
FlushSleep TrackerDuration `json:"flush_sleep"`
// Initial wait time before retrying a query when the db deadlocks (ramps linearly)
DeadlockWait TrackerDuration `json:"deadlock_wait"`
}
// TrackerFlushBufferSizes represents the buffer_sizes object in a config file.
// See github.com/kotoko/chihaya/database/Database.startFlushing() for more info.
type TrackerFlushBufferSizes struct {
Torrent int `json:"torrent"`
User int `json:"user"`
TransferHistory int `json:"transfer_history"`
TransferIps int `json:"transfer_ips"`
Snatch int `json:"snatch"`
}
// TrackerDatabase represents the database object in a config file.
type TrackerDatabase struct {
Username string `json:"user"`
Password string `json:"pass"`
Database string `json:"database"`
Proto string `json:"proto"`
Addr string `json:"addr"`
Encoding string `json:"encoding"`
}
// TrackerConfig represents a whole Chihaya config file.
type TrackerConfig struct {
Database TrackerDatabase `json:"database"`
Intervals TrackerIntervals `json:"intervals"`
FlushSizes TrackerFlushBufferSizes `json:"sizes"`
LogFlushes bool `json:"log_flushes"`
SlotsEnabled bool `json:"slots_enabled"`
BindAddress string `json:"addr"`
// When true disregards download. This value is loaded from the database.
GlobalFreeleech bool `json:"global_freeleach"`
// Maximum times to retry a deadlocked query before giving up.
MaxDeadlockRetries int `json:"max_deadlock_retries"`
}
// LoadConfig loads the config file from the given path
func LoadConfig(path string) (err error) {
expandedPath := os.ExpandEnv(path)
f, err := os.Open(expandedPath)
if err != nil {
return
}
defer f.Close()
err = json.NewDecoder(f).Decode(&Loaded)
if err != nil {
return
}
log.Printf("Successfully loaded config file.")
return
}
// Default TrackerConfig
var Loaded = TrackerConfig{
Database: TrackerDatabase{
Username: "root",
Password: "",
Database: "sample_database",
Proto: "tcp",
Addr: "127.0.0.1:3306",
Encoding: "utf8",
},
Intervals: TrackerIntervals{
Announce: TrackerDuration{30 * time.Minute},
MinAnnounce: TrackerDuration{15 * time.Minute},
DatabaseReload: TrackerDuration{45 * time.Second},
DatabaseSerialization: TrackerDuration{time.Minute},
PurgeInactive: TrackerDuration{time.Minute},
VerifyUsedSlots: 3600,
FlushSleep: TrackerDuration{3 * time.Second},
DeadlockWait: TrackerDuration{time.Second},
},
FlushSizes: TrackerFlushBufferSizes{
Torrent: 10000,
User: 10000,
TransferHistory: 10000,
TransferIps: 1000,
Snatch: 100,
},
LogFlushes: true,
SlotsEnabled: true,
BindAddress: ":34000",
GlobalFreeleech: false,
MaxDeadlockRetries: 10,
}
|
package libpassword
import "golang.org/x/crypto/bcrypt"
// Hash - Hash password using Bcrypt
func Hash(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
// CheckHash - Check if password and hash password is valid
func CheckHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
|
package main
import (
"fmt"
"github.com/ProfessorMc/Recipe/spoilers/dish"
)
var dishes []*dish.Dish
func lab5() {
dishes = make([]*dish.Dish, 0)
for _, friend := range friends {
cakeRecipe, err := cookbook.GetRecipe("cake")
if err != nil {
panic(err)
}
order := dish.NewDish(*friend, *cakeRecipe)
dishes = append(dishes, order)
}
for dishIndex := range dishes {
fmt.Println(dishes[dishIndex].String())
}
}
|
package main
import (
"context"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/translate"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
const (
TID = "0xb1ed364e4333aae1da4a901d5231244ba6a35f9421d4607f7cb90d60bf45578a"
URL = "https://mainnet.infura.io"
)
var (
sess session.Session
svc *translate.Translate
articleTextInPt string
)
func confAWS() {
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewSharedCredentials("", "bleu-hackathon"),
})
if err != nil {
log.Fatalf("could not create AWS sessioin: %s\n", err)
}
svc = translate.New(sess)
}
func downloadChineseArticle() (string, error) {
var textInChinese string
log.Println("retrieving chinese report from ethereum blockchain")
rpcCli, errRPCClient := rpc.Dial(URL)
if errRPCClient != nil {
return textInChinese, fmt.Errorf("RPCC dial error: %v", errRPCClient)
}
var cli = ethclient.NewClient(rpcCli)
var ctx = context.Background()
tx, isPending, err := cli.TransactionByHash(ctx, common.HexToHash(TID))
if err != nil {
log.Fatalf("TransactionByHash error: %v\n", err)
} else if isPending == false {
textInChinese = string(tx.Data())
}
log.Println("successfully downloaded text from chinese report")
return textInChinese, nil
}
func chinese2English(chineseArticleLines []string) ([]string, error) {
var reportLinesEn []string
log.Println("using AWS to translate report from chinese to english")
for _, line := range chineseArticleLines {
if len(line) == 0 {
continue
}
txtInput := translate.TextInput{
SourceLanguageCode: aws.String("zh"),
TargetLanguageCode: aws.String("en"),
Text: aws.String(line),
}
chinese2English, err := svc.Text(&txtInput)
if err != nil {
return reportLinesEn, fmt.Errorf("error translating report: %v", err)
}
reportLinesEn = append(reportLinesEn, *chinese2English.TranslatedText)
}
log.Println("successfully translated chinese report to english")
return reportLinesEn, nil
}
func english2Portuguese(englishArticleLines []string) ([]string, error) {
var reportLinesPt []string
log.Println("using AWS to translate english translation to portguese")
for _, line := range englishArticleLines {
if len(line) == 0 {
continue
}
txtInput := translate.TextInput{
SourceLanguageCode: aws.String("en"),
TargetLanguageCode: aws.String("pt"),
Text: aws.String(line),
}
portuguese2English, err := svc.Text(&txtInput)
if err != nil {
return reportLinesPt, fmt.Errorf("error translating report: %v", err)
}
reportLinesPt = append(reportLinesPt, *portuguese2English.TranslatedText)
}
log.Println("successfully translated english lines to portuguese")
return reportLinesPt, nil
}
type donaMariaPage struct {
Title string
SubTitle string
ReportText string
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
p := donaMariaPage{
Title: "Olá, Dona Maria!",
SubTitle: "Aqui está a notícia censurada pelo governo chinês :)",
ReportText: articleTextInPt,
}
t, err := template.ParseFiles("templates/donamaria.gohtml")
if err != nil {
log.Fatalf("error parsing template: %v\n", err)
}
t.Execute(w, p)
}
func init() {
confAWS()
}
func main() {
zh, err := downloadChineseArticle()
if err != nil {
log.Fatalf("error downloading chinese article: %v\n", err)
}
reportLinesZh := strings.Split(zh, "\n")
reportLinesEn, err := chinese2English(reportLinesZh)
if err != nil {
log.Fatalf("could not translate chinese article to english: %v\n", err)
}
reportLinesPt, err := english2Portuguese(reportLinesEn)
if err != nil {
log.Fatalf("could not translate english lines to chinese: %v\n", err)
}
articleTextInPt = strings.Join(reportLinesPt, "\n")
log.Println("serving application at port 8080")
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":8080", nil)
}
|
package golog
import (
"testing"
)
func TestLog(t *testing.T) {
Start(DebugLevel, AlsoStdout)
Start(InfoLevel, AlsoStdout, LogFilePath("./temp"), EveryDay)
// GeneralInit()
Debugf("debug")
Infof("info")
}
|
package network
import (
"fmt"
"net"
"reflect"
"encoding/binary"
pb "code.google.com/p/goprotobuf/proto"
"sofa/proto"
)
func init() {
}
type IDispatcher interface {
Dispatch(cliConn *ClientConnection, request interface{})
Disconnect(cliConn *ClientConnection)
}
type GameServer struct {
Dispatcher IDispatcher
}
func NewGameServer(d IDispatcher) *GameServer {
return &GameServer{
Dispatcher : d,
}
}
func (this *GameServer) Start() {
ln, err := net.Listen("tcp", ":13603")
if err != nil {
fmt.Println("err", err)
}
fmt.Println("gameServer runing")
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("Accept error", err)
continue
}
go this.acceptConn(conn)
}
}
func (this *GameServer) acceptConn(conn net.Conn) {
cliConn := NewClientConnection(conn)
for {
if buff_body, ok := cliConn.duplexReadBody(); ok {
this.parse(cliConn, buff_body)
continue
}
this.Dispatcher.Disconnect(cliConn)
break
}
conn.Close()
}
func (this *GameServer) parse(cliConn *ClientConnection, msg []byte) {
//defer func() {
// if r := recover(); r != nil {
// fmt.Println("parse err", r)
// }
//}()
uri := binary.LittleEndian.Uint32(msg[:4])
ty := proto.URI2PROTO[uri]
new_ins_value := reflect.New(ty)
err := pb.Unmarshal(msg[4:], new_ins_value.Interface().(pb.Message))
if err != nil {
fmt.Println("pb Unmarshal", err)
return
}
this.Dispatcher.Dispatch(cliConn, new_ins_value.Interface())
}
|
package main
import (
"io/ioutil"
"os"
"reflect"
"testing"
)
func TestWordCount(t *testing.T) {
f1, err := ioutil.TempFile(".", "tmp")
if err != nil {
t.Error(err)
}
defer f1.Close()
defer os.Remove(f1.Name())
f1.Write([]byte("test case"))
f1.Seek(0, 0)
type args struct {
f *os.File
}
tests := []struct {
name string
args args
want map[string]int
}{
{"base-case", args{f1}, map[string]int{"test": 1, "case": 1}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := WordCount(tt.args.f); !reflect.DeepEqual(got, tt.want) {
t.Errorf("WordCount() = %v, want %v", got, tt.want)
}
})
}
}
|
package gomailer
type TemplateMessage struct {
Message
}
func NewTemplateMessage(message *Message, template *Template, data interface{}) (*TemplateMessage, error) {
body, err := template.Parse(data)
if err != nil {
return nil, err
}
message.Body = body
return &TemplateMessage{
Message: *message,
}, nil
}
|
package torbula
import (
"math"
"path/filepath"
"strconv"
"strings"
)
func isTorrent(file string) bool {
return strings.ToLower(filepath.Ext(file)) == ".torrent"
}
func roundUp(input float64, places int) (newVal float64) {
var round float64
pow := math.Pow(10, float64(places))
digit := pow * input
round = math.Ceil(digit)
newVal = round / pow
return
}
func byteFormat(inputNum float64, precision int) string {
if precision <= 0 {
precision = 1
}
var unit string
var returnVal float64
if inputNum >= 1000000000000000000000000 {
returnVal = roundUp((inputNum / 1208925819614629174706176), precision)
unit = " YB" // yottabyte
} else if inputNum >= 1000000000000000000000 {
returnVal = roundUp((inputNum / 1180591620717411303424), precision)
unit = " ZB" // zettabyte
} else if inputNum >= 10000000000000000000 {
returnVal = roundUp((inputNum / 1152921504606846976), precision)
unit = " EB" // exabyte
} else if inputNum >= 1000000000000000 {
returnVal = roundUp((inputNum / 1125899906842624), precision)
unit = " PB" // petabyte
} else if inputNum >= 1000000000000 {
returnVal = roundUp((inputNum / 1099511627776), precision)
unit = " TB" // terrabyte
} else if inputNum >= 1000000000 {
returnVal = roundUp((inputNum / 1073741824), precision)
unit = " GB" // gigabyte
} else if inputNum >= 1000000 {
returnVal = roundUp((inputNum / 1048576), precision)
unit = " MB" // megabyte
} else if inputNum >= 1000 {
returnVal = roundUp((inputNum / 1024), precision)
unit = " KB" // kilobyte
} else {
returnVal = inputNum
unit = " bytes" // byte
}
return strconv.FormatFloat(returnVal, 'f', precision, 64) + unit
}
|
package config
type RouterSpec struct {
Name string `default:"gorilla" mapstructure:"name"`
RouterOpts map[string]string `default:"{}" mapstructure:"options"`
}
func (r RouterSpec) Validate() error {
validationError := RouterValidationError{}
isValid := true
if r.Name == "" {
validationError.NameError = true
validationError.NameErrorMessage = "name field in router is required"
isValid = false
}
if isValid {
return nil
}
return validationError
}
|
package schema_test
import (
"encoding/json"
"reflect"
"testing"
schema "github.com/Kangaroux/go-map-schema"
"github.com/stretchr/testify/require"
)
type mismatch schema.FieldMismatch
type missing schema.FieldMissing
type TestStruct struct {
Foo string
Bar int
Baz float64
}
type TestStructEmbedded struct {
TestStruct
Butt bool
}
type TestStructPtr struct {
Ptr *string
}
type TestStructTags struct {
LowercaseA string `json:"a"`
IgnoreMe string `json:"-"`
WithOptions string `json:",omitempty"`
Hyphen string `json:"-,"`
}
type TestStructUnsigned struct {
Foo uint
}
type TestStructNested struct {
User TestStruct
Cat struct {
A *struct {
Baz string
}
B bool
C string
}
}
func toJson(val interface{}) string {
out, err := json.Marshal(val)
if err != nil {
panic(err)
}
return string(out)
}
// Tests that CompareMapToStruct returns an error if the dst isn't valid.
func TestCompareMapToStruct_BadDstErrors(t *testing.T) {
var err error
m := make(map[string]interface{})
v := "hello"
_, err = schema.CompareMapToStruct(123, m, nil)
require.Equal(t, schema.ErrInvalidDst, err)
_, err = schema.CompareMapToStruct(v, m, nil)
require.Equal(t, schema.ErrInvalidDst, err)
_, err = schema.CompareMapToStruct(&v, m, nil)
require.Equal(t, schema.ErrInvalidDst, err)
_, err = schema.CompareMapToStruct(nil, m, nil)
require.Equal(t, schema.ErrInvalidDst, err)
_, err = schema.CompareMapToStruct(TestStruct{}, m, nil)
require.Equal(t, schema.ErrInvalidDst, err)
_, err = schema.CompareMapToStruct(&TestStruct{}, m, nil)
require.NoError(t, err)
}
// Tests that CompareMapToStruct returns an error if the src isn't valid.
func TestCompareMapToStruct_BadSrcErrors(t *testing.T) {
var err error
_, err = schema.CompareMapToStruct(&TestStruct{}, nil, nil)
require.Equal(t, schema.ErrNilSrc, err)
_, err = schema.CompareMapToStruct(&TestStruct{}, make(map[string]interface{}), nil)
require.NoError(t, err)
}
// Tests that CompareMapToStruct uses the provided functions in the compare options.
func TestCompareMapToStruct_CompareOptsUsesProvidedFuncs(t *testing.T) {
convertibleCalled := false
convertibleFunc := func(t reflect.Type, v reflect.Value) bool { convertibleCalled = true; return false }
typeNameCalled := false
typeNameFunc := func(t reflect.Type) string { typeNameCalled = true; return "" }
src := make(map[string]interface{})
json.Unmarshal([]byte(`{"Foo":""}`), &src)
opts := &schema.CompareOpts{
ConvertibleFunc: convertibleFunc,
TypeNameFunc: typeNameFunc,
}
schema.CompareMapToStruct(&TestStruct{}, src, opts)
require.True(t, convertibleCalled)
require.True(t, typeNameCalled)
}
// Tests that CompareMapToStruct sets defaults if it receives a compare options instance
// but one or more of the functions are nil.
func TestCompareMapToStruct_CompareOptsSetsDefaults(t *testing.T) {
srcJson := `{"Foo":true,"Baz":""}`
expected := []mismatch{
{
Field: "Foo",
Expected: "string",
Actual: "bool",
},
{
Field: "Baz",
Expected: "float64",
Actual: "string",
},
}
src := make(map[string]interface{})
json.Unmarshal([]byte(srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStruct{}, src, &schema.CompareOpts{})
require.JSONEq(t, toJson(expected), toJson(r.MismatchedFields))
}
// Tests that CompareMapToStruct identifies fields in src that can't be converted
// to the field in dst, due to a type mismatch (e.g. src:string -> dst:int).
// This only tests "simple" types (no pointers, lists, structs, etc.)
func TestCompareMapToStruct_MismatchedFieldsSimple(t *testing.T) {
tests := []struct {
srcJson string
expected []mismatch
}{
{
srcJson: `{}`,
expected: []mismatch{},
},
{
srcJson: `{"Foo":"","Bar":0,"Baz":3.14}`,
expected: []mismatch{},
},
{
srcJson: `{"Foo":null}`,
expected: []mismatch{
{
Field: "Foo",
Expected: "string",
Actual: "null",
},
},
},
{
srcJson: `{"Foo":0}`,
expected: []mismatch{
{
Field: "Foo",
Expected: "string",
Actual: "float64",
},
},
},
{
srcJson: `{"Bar":"hi"}`,
expected: []mismatch{
{
Field: "Bar",
Expected: "int",
Actual: "string",
},
},
},
{
srcJson: `{"Bar":1.23}`,
expected: []mismatch{
{
Field: "Bar",
Expected: "int",
Actual: "float64",
},
},
},
{
srcJson: `{"Foo":true,"Baz":""}`,
expected: []mismatch{
{
Field: "Foo",
Expected: "string",
Actual: "bool",
},
{
Field: "Baz",
Expected: "float64",
Actual: "string",
},
},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStruct{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MismatchedFields), test.srcJson)
}
}
// Tests that CompareMapToStruct treats embedded structs as if all the embedded fields
// were moved into the parent struct.
func TestCompareMapToStruct_MismatchedFieldsEmbedded(t *testing.T) {
tests := []struct {
srcJson string
expected []mismatch
}{
{
srcJson: `{}`,
expected: []mismatch{},
},
{
srcJson: `{"Foo":"","Bar":0,"Baz":3.14,"Butt":false}`,
expected: []mismatch{},
},
{
srcJson: `{"Foo":null}`,
expected: []mismatch{
{
Field: "Foo",
Expected: "string",
Actual: "null",
},
},
},
{
srcJson: `{"Bar":"hi"}`,
expected: []mismatch{
{
Field: "Bar",
Expected: "int",
Actual: "string",
},
},
},
{
srcJson: `{"Foo":true,"Baz":""}`,
expected: []mismatch{
{
Field: "Foo",
Expected: "string",
Actual: "bool",
},
{
Field: "Baz",
Expected: "float64",
Actual: "string",
},
},
},
{
srcJson: `{"Butt":"hi"}`,
expected: []mismatch{
{
Field: "Butt",
Expected: "bool",
Actual: "string",
},
},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructEmbedded{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MismatchedFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies pointer fields and checks if the src value can be
func TestCompareMapToStruct_MismatchedFieldsPtr(t *testing.T) {
tests := []struct {
srcJson string
expected []mismatch
}{
{
srcJson: `{}`,
expected: []mismatch{},
},
{
srcJson: `{"Ptr":null}`,
expected: []mismatch{},
},
{
srcJson: `{"Ptr":0}`,
expected: []mismatch{
{
Field: "Ptr",
Expected: "*string",
Actual: "float64",
},
},
},
{
srcJson: `{"Ptr":"hi"}`,
expected: []mismatch{},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructPtr{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MismatchedFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies the fields in dst that have a json struct tag.
func TestCompareMapToStruct_MismatchedFieldsTags(t *testing.T) {
tests := []struct {
srcJson string
expected []mismatch
}{
{
srcJson: `{}`,
expected: []mismatch{},
},
{
srcJson: `{"a":0}`,
expected: []mismatch{
{
Field: "a",
Expected: "string",
Actual: "float64",
},
},
},
{
srcJson: `{"IgnoreMe":0}`,
expected: []mismatch{},
},
{
srcJson: `{"WithOptions":0}`,
expected: []mismatch{
{
Field: "WithOptions",
Expected: "string",
Actual: "float64",
},
},
},
{
srcJson: `{"-":0}`,
expected: []mismatch{
{
Field: "-",
Expected: "string",
Actual: "float64",
},
},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructTags{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MismatchedFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies negative numbers when the dst type
// is unsigned.
func TestCompareMapToStruct_MismatchedFieldsUnsigned(t *testing.T) {
tests := []struct {
srcJson string
expected []mismatch
}{
{
srcJson: `{}`,
expected: []mismatch{},
},
{
srcJson: `{"Foo":0}`,
expected: []mismatch{},
},
{
srcJson: `{"Foo":1}`,
expected: []mismatch{},
},
{
srcJson: `{"Foo":-1}`,
expected: []mismatch{
{
Field: "Foo",
Expected: "uint",
Actual: "float64",
},
},
},
{
srcJson: `{"Foo":1.5}`,
expected: []mismatch{
{
Field: "Foo",
Expected: "uint",
Actual: "float64",
},
},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructUnsigned{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MismatchedFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies and returns a list of fields that are in
// dst but not src.
func TestCompareMapToStruct_MissingFields(t *testing.T) {
tests := []struct {
srcJson string
expected []missing
}{
{
srcJson: `{}`,
expected: []missing{{Field: "Foo"}, {Field: "Bar"}, {Field: "Baz"}},
},
{
srcJson: `{"Foo":""}`,
expected: []missing{{Field: "Bar"}, {Field: "Baz"}},
},
{
srcJson: `{"Foo":"","Bar":0}`,
expected: []missing{{Field: "Baz"}},
},
{
srcJson: `{"Foo":"","Bar":0,"Baz":3.14}`,
expected: []missing{},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStruct{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MissingFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies and returns a list of fields that are in
// dst but not src, including embedded fields.
func TestCompareMapToStruct_MissingFieldsEmbedded(t *testing.T) {
tests := []struct {
srcJson string
expected []missing
}{
{
srcJson: `{}`,
expected: []missing{{Field: "Foo"}, {Field: "Bar"}, {Field: "Baz"}, {Field: "Butt"}},
},
{
srcJson: `{"Foo":""}`,
expected: []missing{{Field: "Bar"}, {Field: "Baz"}, {Field: "Butt"}},
},
{
srcJson: `{"Foo":"","Bar":0}`,
expected: []missing{{Field: "Baz"}, {Field: "Butt"}},
},
{
srcJson: `{"Foo":"","Bar":0,"Baz":3.14}`,
expected: []missing{{Field: "Butt"}},
},
{
srcJson: `{"Foo":"","Bar":0,"Baz":3.14,"Butt":false}`,
expected: []missing{},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructEmbedded{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MissingFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies and returns a list of fields that are in
// dst but not src, and correctly uses the json field name.
func TestCompareMapToStruct_MissingFieldsTags(t *testing.T) {
tests := []struct {
srcJson string
expected []missing
}{
{
srcJson: `{}`,
expected: []missing{{Field: "a"}, {Field: "WithOptions"}, {Field: "-"}},
},
{
srcJson: `{"a":""}`,
expected: []missing{{Field: "WithOptions"}, {Field: "-"}},
},
{
srcJson: `{"-":""}`,
expected: []missing{{Field: "a"}, {Field: "WithOptions"}},
},
{
srcJson: `{"WithOptions":""}`,
expected: []missing{{Field: "a"}, {Field: "-"}},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructTags{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MissingFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies and returns a list of fields that are in
// dst but not src, and correctly works with nested structs.
func TestCompareMapToStruct_MismatchedFieldsNested(t *testing.T) {
tests := []struct {
srcJson string
expected []mismatch
}{
{
srcJson: `{}`,
expected: []mismatch{},
},
{
srcJson: `{"User":{"Foo":"foo", "Bar":12, "Baz":12}, "Cat":{"A":{"Baz":"baz"}, "B":true, "C":"c"}}`,
expected: []mismatch{},
},
{
srcJson: `{"User": 3, "Cat":{"A":{"Baz":"baz"}, "B":true, "C":"c"}}`,
expected: []mismatch{
{
Field: "User",
Expected: "TestStruct",
Actual: "float64",
},
},
},
{
srcJson: `{"User": {"Foo":"foo", "Bar":true, "Baz":12}, "Cat":{"A":{"Baz":"baz"}, "B":true, "C":"c"}}`,
expected: []mismatch{
{
Field: "Bar",
Expected: "int",
Actual: "bool",
Path: []string{"User"},
},
},
},
{
srcJson: `{"User": {"Foo":"foo", "Bar":13, "Baz":12}, "Cat":{"A":{"Baz":true}, "B":true, "C":"c"}}`,
expected: []mismatch{
{
Field: "Baz",
Expected: "string",
Actual: "bool",
Path: []string{"Cat", "A"},
},
},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructNested{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MismatchedFields), test.srcJson)
}
}
// Tests that CompareMapToStruct identifies and returns a list of fields that are in
// dst but not src, and correctly works with nested structs.
func TestCompareMapToStruct_MissingFieldsNested(t *testing.T) {
tests := []struct {
srcJson string
expected []missing
}{
{
srcJson: `{}`,
expected: []missing{
{Field: "User"}, {Field: "Cat"},
},
},
{
srcJson: `{"User":{}, "Cat":{}}`,
expected: []missing{
{Field: "Foo", Path: []string{"User"}}, {Field: "Bar", Path: []string{"User"}}, {Field: "Baz", Path: []string{"User"}},
{Field: "A", Path: []string{"Cat"}}, {Field: "B", Path: []string{"Cat"}}, {Field: "C", Path: []string{"Cat"}},
},
},
{
srcJson: `{"User":{"Foo":"foo", "Baz":12}, "Cat":{"A":{}, "B":true, "C":"c"}}`,
expected: []missing{
{Field: "Bar", Path: []string{"User"}},
{Field: "Baz", Path: []string{"Cat", "A"}},
},
},
{
srcJson: `{"User":{"Foo":"foo", "Bar":12, "Baz":12}, "Cat":{"A":{"Baz":"baz"}, "B":true, "C":"c"}}`,
expected: []missing{},
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStructNested{}, src, nil)
require.JSONEq(t, toJson(test.expected), toJson(r.MissingFields), test.srcJson)
require.Empty(t, r.MismatchedFields)
}
}
// Tests that Errors returns the expected error map.
func TestCompareResults_Errors(t *testing.T) {
tests := []struct {
srcJson string
dst interface{}
expected error
}{
{
srcJson: `{"Foo":null}`,
dst: &TestStruct{},
expected: schema.MismatchError(map[string]interface{}{
"Foo": `expected a string but it's null`,
}),
},
{
srcJson: `{"Foo":1.23,"Bar":true}`,
dst: &TestStruct{},
expected: schema.MismatchError(map[string]interface{}{
"Foo": `expected a string but it's a float64`,
"Bar": `expected an int but it's a bool`,
}),
},
{
srcJson: `{"Foo":1.23,"Bar":true,"Butt":"hi"}`,
dst: &TestStructEmbedded{},
expected: schema.MismatchError(map[string]interface{}{
"Foo": `expected a string but it's a float64`,
"Bar": `expected an int but it's a bool`,
"Butt": `expected a bool but it's a string`,
}),
},
{
srcJson: `{"User": {"Foo":"foo", "Bar":13, "Baz":12}, "Cat":{"A":{"Baz":true}, "B":true, "C":"c"}}`,
dst: &TestStructNested{},
expected: schema.MismatchError(map[string]interface{}{
"Cat": map[string]interface{}{
"A": map[string]interface{}{
"Baz": `expected a string but it's a bool`,
},
},
}),
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(test.dst, src, nil)
require.Equal(t, test.expected, r.Errors(), test.srcJson)
// Test marshaling the error to JSON.
require.JSONEq(t, toJson(test.expected), toJson(r.Errors()), test.srcJson)
}
}
// Tests that Errors returns nil when there are no type mismatches.
func TestCompareResults_ErrorsReturnsNil(t *testing.T) {
tests := []struct {
srcJson string
}{
{
srcJson: `{}`,
},
{
srcJson: `{"Foo":"hi"}`,
},
{
srcJson: `{"Foo":"hi","Bar":1,"Baz":3.14}`,
},
}
for _, test := range tests {
// Unmarshal the json into a map.
src := make(map[string]interface{})
json.Unmarshal([]byte(test.srcJson), &src)
r, _ := schema.CompareMapToStruct(&TestStruct{}, src, nil)
require.Nil(t, r.Errors())
}
}
|
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"puzzle-maker/puzzle"
"github.com/gorilla/mux"
)
type toGo struct {
Cells []int
DepthBFS []int
Fitness int
Iterations int
Solution []string
}
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/genalgo", random).Methods("GET")
router.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("assets/"))))
//puzzle.GetPlot(5, 10000, 0.3, 0.018, 10)
log.Fatal(http.ListenAndServe(":8080", router))
}
func random(w http.ResponseWriter, r *http.Request) {
// parameters
// init pop = n * n * 2
gens := 160000
var selRate, mutRate float32
selRate = 0.3
mutRate = 0.018
n, _ := strconv.Atoi(r.URL.Query().Get("n"))
p, dbfs, fitness, solution := puzzle.GeneticPuzzle(n, gens, selRate, mutRate)
json, _ := json.Marshal(toGo{p, dbfs, fitness - n*n, gens, solution})
w.Write(json)
}
|
package scan
import (
"fmt"
"unicode"
)
type CharSet struct {
Pattern
}
func newCharSet(p Pattern) CharSet {
c := CharSet{p}
singleLiteralToCharClass(c.Regexp)
if !c.isCharSet() {
panic(fmt.Errorf("Pattern %s is not a character set.", c.String()))
}
return c
}
func Char(p string) CharSet {
return newCharSet(Pat("[" + p + "]"))
}
func (p CharSet) Negate() CharSet {
neg := newCharSet(Pat(p.String()))
neg.Rune = negateRune(neg.Rune)
neg.Rune0[0] = neg.Rune[0]
neg.Rune0[1] = neg.Rune[1]
return neg
}
func negateRune(rs []rune) []rune {
if len(rs) == 0 {
panic(fmt.Errorf("unexpected empty []rune"))
}
neg := []rune{}
min := rMin(0, rs[0])
for i := 0; i < len(rs)-1; i += 2 {
l, r := rs[i], rs[i+1]
if min < l {
neg = append(neg, min)
neg = append(neg, l-1)
}
min = r + 1
}
if min <= unicode.MaxRune {
neg = append(neg, min)
neg = append(neg, unicode.MaxRune)
}
return neg
}
func rMin(a, b rune) rune {
if a < b {
return a
}
return b
}
func (p CharSet) Exclude(cs ...CharSet) CharSet {
es := make(exprs, len(cs))
for i := range cs {
es[i] = cs[i]
}
subset := Merge(es...)
return Merge(p.Negate(), subset).Negate()
}
func Merge(es ...Expr) CharSet {
return newCharSet(exprs(es).capture(false))
}
|
package main
import (
"database/sql"
"fmt"
"formation/api"
"formation/serverweb"
_ "github.com/lib/pq"
"net/http"
)
func main() {
/* fmt.Println("Hello Arnaud")
a := 4
b := 12
a += b
fmt.Println("a += b = ", a)
var x int = 50
var y float32 = 30.5
fmt.Printf("x + y = ", float32(x )+ y)
var todo1 api.Todo
SetTodo(todo1, "Salut les copains 1")
println("titre", todo1.Titre)
var todo2 api.Todo
SetTodoPtr(&todo2, "Salut les copains 2")
println("titre", todo2.Titre)
//api.Todos
scanner := bufio.NewScanner(os.Stdin) // création du scanner capturant une entrée utilisateur
fmt.Print("Entrez quelque chose : ")
scanner.Scan() // lancement du scanner
entreeUtilisateur := scanner.Text() // stockage du résultat du scanner dans une variable
fmt.Println("Resultat de la saisie utilisateur : " + entreeUtilisateur)
fmt.Print("Entrez un nombre entier : ")
scanner.Scan()
nbr, err := strconv.Atoi(scanner.Text()) // conversion du type string en int
if err!= nil {
fmt.Printf("Erreur retournée %s res : %d\n", err.Error(), (nbr + 6))
} else {
fmt.Printf("res : %d\n", (nbr + 6))
}
*/
api.Create("Apprentissage", "Programmation", 161220)
api.Create("Cuisine", "Cookies", 171220)
api.Create("Golang", "Cours", 270121)
api.Create("Javascript", "Vue", 280121)
api.Create("TypeScript", "Typer les éléments", 230121)
api.Create("Immobilier", "FI", 230121)
api.Create("Neuf", "FI9", 230121)
api.Create("Sport", "Faire un footing", 241221)
api.Create("Sieste", "Se reposer", 301121)
for _, valeur := range api.List() {
println(" ", valeur.Id, " ", valeur.Titre, " ", valeur.Description, " ", valeur.DueDate)
}
http.HandleFunc("/hello", serverweb.Accueil)
http.HandleFunc("/create", serverweb.Create)
http.HandleFunc("/list", serverweb.ListTodo)
http.HandleFunc("/get", serverweb.GetTodo)
http.HandleFunc("/del", serverweb.Delete)
http.HandleFunc("/update", serverweb.Update)
http.HandleFunc("/health", serverweb.Health)
const (
host = "172.17.0.1"
port = 5432
user = "user1"
password = "motdepasse"
dbname = "dbtodo"
)
psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
println(psqlconn)
// open database
db, err := sql.Open("postgres", psqlconn)
CheckError(err)
api.DataBasePtr = db
// close database
defer db.Close()
// check db
err = db.Ping()
CheckError(err)
fmt.Println("Connected!")
RecordTest(db)
erreur := http.ListenAndServe(":8090", nil)
println(erreur.Error())
}
func CheckError(err error) {
if err != nil {
// panic(err)
}
}
func RecordTest(myDb *sql.DB) {
sqlStatement := `INSERT INTO "user" ("email", "password") VALUES ($1, $2) RETURNING id`
id := 0
err := myDb.QueryRow(sqlStatement, "test@test.com", "arnaud").Scan(&id)
println("id :", id)
// _, err := myDb.Exec(sqlStatement)
if err != nil {
panic(err)
}
}
/*func SetTodo (todo api.Todo, titre string) {
todo.Titre = titre
println("titre", todo.Titre)
}
func SetTodoPtr (todo *api.Todo, titre string) {
todo.Titre = titre
println("titre", todo.Titre)
}*/
|
/*
Copyright [2015] Alex Davies-Moore
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 ewkb
import "github.com/devork/geom"
// https://trac.osgeo.org/postgis/browser/trunk/doc/ZMSgeoms.txt
//
// Supported dimensions:
//
// XY 2 dimensional
// XYZ 3 dimensional
// XYZM 4 dimensional
//
// 2.1. Definition of ZM-Geometry
//
// a) A geometry can have either 2, 3 or 4 dimensions.
// b) 3rd dimension of a 3d geometry can either represent Z or M (3DZ or 3DM).
// c) 4d geometries contain both Z and M (in this order).
// d) M and Z values are associated with every vertex.
// e) M and Z values are undefined within surface interiors.
//
// Any ZM-Geometry can be converted into a 2D geometry by discarding all its
// Z and M values. The resulting 2D geometry is the "shadow" of the ZM-Geometry.
// 2D geometries cannot be safely converted into ZM-Geometries, since their Z
// and M values are undefined, and not necessarily zero.
//
// These constants also represent the bit masks for the EWKB dims
const (
xy dimension = 0x0000
xym dimension = 0x4000
xyz dimension = 0x8000
xyzm dimension = 0xC000
xys dimension = 0x2000
xyms dimension = 0x6000
xyzs dimension = 0xA000
xyzms dimension = 0xE000
unknown dimension = 0xFFFF
)
// Geometry types
const (
geometry geomtype = 0x0000
point geomtype = 0x0001
linestring geomtype = 0x0002
polygon geomtype = 0x0003
multipoint geomtype = 0x0004
multilinestring geomtype = 0x0005
multipolygon geomtype = 0x0006
geometrycollection geomtype = 0x0007
circularstring geomtype = 0x0008
compoundcurve geomtype = 0x0009
curvepolygon geomtype = 0x000a
multicurve geomtype = 0x000b
multisurface geomtype = 0x000c
curve geomtype = 0x000d
surface geomtype = 0x000e
polyhedralsurface geomtype = 0x000f
tin geomtype = 0x0010
triangle geomtype = 0x0011
)
// ----------------------------------------------------------------------------
// Dimension
// ----------------------------------------------------------------------------
// Dimension of the geometry
type dimension uint16
func (d dimension) dim() geom.Dimension {
switch d {
case xy, xys:
return geom.XY
case xyz, xyzs:
return geom.XYZ
case xym, xyms:
return geom.XYM
case xyzm, xyzms:
return geom.XYZM
default:
return geom.UNKNOWN
}
}
// ----------------------------------------------------------------------------
// geomType
// ----------------------------------------------------------------------------
// geomType is the bitmask of the geom
type geomtype uint16
func (g geomtype) String() string {
switch g {
case geometry:
return "GEOMETRY"
case point:
return "POINT"
case linestring:
return "LINESTRING"
case polygon:
return "POLYGON"
case multipoint:
return "MULTIPOINT"
case multilinestring:
return "MULTILINESTRING"
case multipolygon:
return "MULTIPOLYGON"
case geometrycollection:
return "GEOMETRYCOLLECTION"
// case CIRCULARSTRING:
// return "CIRCULARSTRING"
// case COMPOUNDCURVE:
// return "COMPOUNDCURVE"
// case CURVEPOLYGON:
// return "CURVEPOLYGON"
// case MULTICURVE:
// return "MULTICURVE"
// case MULTISURFACE:
// return "MULTISURFACE"
// case CURVE:
// return "CURVE"
// case SURFACE:
// return "SURFACE"
// case POLYHEDRALSURFACE:
// return "POLYHEDRALSURFACE "
// case TIN:
// return "TIN"
// case TRIANGLE:
// return "TRIANGLE"
default:
return "UNKNOWN"
}
}
// WKB extensions for Z, M, and ZM. these extensions are applied to the base geometry types,
// such that a ZM version of a Point = 17 + 3000 = 3017 (0xBC9)
const (
wkbz uint16 = 1000
wkbm uint16 = 2000
wkbzm uint16 = 3000
)
// Big or Little endian identifiers
const (
bigEndian uint8 = 0x00
)
|
package collector
import (
"os"
"github.com/prometheus/client_golang/prometheus"
)
func init() {
registerCollector("dbsize", true, NewDBSizeCollector)
}
const (
dbSizeCollectorSubsystem = "dbsize"
)
var (
dbSize = prometheus.NewDesc(
prometheus.BuildFQName(namespace, dbSizeCollectorSubsystem, "db_size"),
"db_size",
[]string{"db_name"}, nil,
)
dbFree = prometheus.NewDesc(
prometheus.BuildFQName(namespace, dbSizeCollectorSubsystem, "db_free"),
"db_sfree",
[]string{"db_name"}, nil,
)
selectDBSize = `sp_helpdb ` + os.Getenv("DBNAME")
)
type dbSizeCollector struct {
dbSize *prometheus.Desc
dbFree *prometheus.Desc
}
func NewDBSizeCollector() (Collector, error) {
return &dbSizeCollector{
dbSize: dbSize,
dbFree: dbFree,
}, nil
}
func (c *dbSizeCollector) Update(ch chan<- prometheus.Metric) error {
if err := c.updateDB(ch); err != nil {
return err
}
return nil
}
func (c *dbSizeCollector) updateDB(ch chan<- prometheus.Metric) error {
rows, err := DB.Query(selectDBSize)
if err != nil {
return err
}
var name, device, log string
var mb, free float64
for rows.Next() {
rows.Scan(&name, &device, &mb, &log, &free)
}
ch <- prometheus.MustNewConstMetric(
c.dbSize,
prometheus.GaugeValue,
mb,
name,
)
ch <- prometheus.MustNewConstMetric(
c.dbFree,
prometheus.GaugeValue,
free,
name,
)
return nil
}
|
package main
import "fmt"
func main() {
constFunction() //1
}
func constFunction() { //#1
const firstName string = "john" //const adalah variable yang tidak bisa diubah(tetap)
const lastName = "wick" //teknik interface pada konstanta
fmt.Print("halo", firstName, lastName) //fmt.Print tidak memberikan baris baru seperti fmt.Println()
}
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Code generated from the elasticsearch-specification DO NOT EDIT.
// https://github.com/elastic/elasticsearch-specification/tree/33e8a1c9cad22a5946ac735c4fba31af2da2cec2
package types
import (
"bytes"
"encoding/json"
"errors"
"io"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/filtertype"
)
// FilterRef type.
//
// https://github.com/elastic/elasticsearch-specification/blob/33e8a1c9cad22a5946ac735c4fba31af2da2cec2/specification/ml/_types/Filter.ts#L31-L41
type FilterRef struct {
// FilterId The identifier for the filter.
FilterId string `json:"filter_id"`
// FilterType If set to `include`, the rule applies for values in the filter. If set to
// `exclude`, the rule applies for values not in the filter.
FilterType *filtertype.FilterType `json:"filter_type,omitempty"`
}
func (s *FilterRef) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
for {
t, err := dec.Token()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return err
}
switch t {
case "filter_id":
if err := dec.Decode(&s.FilterId); err != nil {
return err
}
case "filter_type":
if err := dec.Decode(&s.FilterType); err != nil {
return err
}
}
}
return nil
}
// NewFilterRef returns a FilterRef.
func NewFilterRef() *FilterRef {
r := &FilterRef{}
return r
}
|
/*
In the fewest bytes, generate the dictionary of keypresses for any letter (as described in https://code.google.com/codejam/contest/351101/dashboard#s=p2)
In Python, the dictionary literal itself:
{'a':2,'c':222,'b':22,'e':33,'d':3,'g':4,'f':333,'i':444,'h':44,'k':55,'j':5,'m':6,'l':555,'o':666,'n':66,'q':77,'p':7,'s':7777,'r':777,'u':88,'t':8,'w':9,'v':888,'y':999,'x':99,'z':9999}
is 187 bytes so it needs to be less than that. (The values can be strings or ints, ie you can have 'a':'2' or 'a':2 it's up to you)
NOTE: This is not asking you to solve the referenced GCJ problem, it's just asking you to generate a particular dictionary which is related to that problem.
EDIT: You may solve this in any language which has a dictionary-like type (ie hashmap, associative array etc.)
*/
package main
import "fmt"
func main() {
for k, v := range dict {
fmt.Printf("%c: %d\n", k, v)
}
}
var dict = map[rune]int{
'a': 2, 'c': 222, 'b': 22, 'e': 33, 'd': 3, 'g': 4, 'f': 333, 'i': 444, 'h': 44, 'k': 55, 'j': 5, 'm': 6, 'l': 555, 'o': 666, 'n': 66, 'q': 77, 'p': 7, 's': 7777, 'r': 777, 'u': 88, 't': 8, 'w': 9, 'v': 888, 'y': 999, 'x': 99, 'z': 9999,
}
|
package fmm
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestNewDependency(t *testing.T) {
tests := []struct {
input string
name string
version *Version
kind DependencyKind
req VersionCmpRes
}{
{"flib", "flib", nil, DependencyRequired, VersionAny},
}
for _, test := range tests {
dep, err := NewDependency(test.input)
if err != nil {
t.Error(err)
}
require.Equal(t, dep.Name, test.name)
if test.version == nil {
require.Nil(t, dep.Version)
} else {
require.NotNil(t, dep.Version)
require.Equal(t, dep.Version.Cmp(test.version), test.req)
}
require.Equal(t, dep.Kind, test.kind)
require.Equal(t, dep.Req, test.req)
}
}
func TestDependencyTest(t *testing.T) {
tests := []struct {
dep, name string
version Version
result bool
}{
{"flib", "flib", Version{0, 1, 1}, true},
{"! flib", "flib", Version{0, 1, 1}, false},
{"flib >= 0.10", "flib", Version{0, 1, 1}, false},
{"flib >= 0.10", "flib", Version{0, 10, 0}, true},
{"flib >= 0.10.0", "flib", Version{0, 10, 0}, true},
{"flib > 0.10", "flib", Version{0, 10, 0}, false},
{"flib>=0.10", "flib", Version{0, 10, 0}, true},
}
for _, test := range tests {
dep, err := NewDependency(test.dep)
require.NoError(t, err)
require.Equal(t, dep.CompatibleWith(&test.version), test.result)
}
}
|
package oc
import (
"context"
"fmt"
"github.com/nmiculinic/observe"
"github.com/sirupsen/logrus"
"go.opencensus.io/examples/exporter"
"go.opencensus.io/exporter/prometheus"
"go.opencensus.io/stats/view"
"go.opencensus.io/trace"
"log"
"math/rand"
"net/http"
"sync"
"time"
)
func g() int {
fmt.Println("side effect")
return 4
}
var r = g()
var rr = observe.NewSimpleRED()
func f() (retErr error) {
_, obs := observe.FromContext(context.Background(), "serious/function", observe.AddREDMetrics(rr))
defer obs.End(&retErr)
time.Sleep(time.Duration(int64(rand.Float64() * float64(time.Second))))
obs.AddField("g", 4)
obs.Log(logrus.InfoLevel, "I'm ok!!!")
if rand.Float64() < 0.2 {
return fmt.Errorf("error")
}
return nil
}
func main() {
e := exporter.PrintExporter{}
trace.RegisterExporter(&e)
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
pe, err := prometheus.NewExporter(prometheus.Options{})
if err != nil {
logrus.Fatal(err)
}
view.RegisterExporter(pe)
view.SetReportingPeriod(time.Second)
go func() {
addr := "[::]:6060"
log.Printf("Serving at %s", addr)
http.Handle("/metrics", pe)
log.Fatal(http.ListenAndServe(addr, nil))
}()
wg := &sync.WaitGroup{}
for i := 0; i < 10; i++{
wg.Add(1)
go func() {
defer wg.Done()
for {
f()
}
}()
}
wg.Wait()
}
|
package open
import "testing"
func TestOpenError(t *testing.T) {
FileUrlName := "kek111"
reader, err := Open(FileUrlName)
defer reader.Close()
if err == nil {
t.Error("There is a problem with opening files")
}
}
|
// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package filter
import (
"slices"
"strings"
)
// Filter is a structure to check if a table should be included for processing.
type Filter interface {
// MatchTable checks if a table can be processed after applying the tableFilter.
MatchTable(schema string, table string) bool
// MatchSchema checks if a schema can be processed after applying the tableFilter.
MatchSchema(schema string) bool
// toLower changes the tableFilter to compare with case-insensitive strings.
toLower() Filter
}
// tableFilter is a concrete implementation of Filter.
type tableFilter []tableRule
// Parse a tableFilter from a list of serialized tableFilter rules. The parsed tableFilter is
// case-sensitive by default.
func Parse(args []string) (Filter, error) {
p := tableRulesParser{
make([]tableRule, 0, len(args)),
matcherParser{
fileName: "<cmdline>",
lineNum: 1,
},
}
for _, arg := range args {
if err := p.parse(arg, true); err != nil {
return nil, err
}
}
slices.Reverse(p.rules)
return tableFilter(p.rules), nil
}
// CaseInsensitive returns a new tableFilter which is the case-insensitive version of
// the input tableFilter.
func CaseInsensitive(f Filter) Filter {
return loweredFilter{wrapped: f.toLower()}
}
// MatchTable checks if a table can be processed after applying the tableFilter `f`.
func (f tableFilter) MatchTable(schema string, table string) bool {
for _, rule := range f {
if rule.schema.matchString(schema) && rule.table.matchString(table) {
return rule.positive
}
}
return false
}
// MatchSchema checks if a schema can be processed after applying the tableFilter `f`.
func (f tableFilter) MatchSchema(schema string) bool {
for _, rule := range f {
if rule.schema.matchString(schema) && (rule.positive || rule.table.matchAllStrings()) {
return rule.positive
}
}
return false
}
func (f tableFilter) toLower() Filter {
rules := make([]tableRule, 0, len(f))
for _, r := range f {
rules = append(rules, tableRule{
schema: r.schema.toLower(),
table: r.table.toLower(),
positive: r.positive,
})
}
return tableFilter(rules)
}
type loweredFilter struct {
wrapped Filter
}
func (f loweredFilter) MatchTable(schema string, table string) bool {
return f.wrapped.MatchTable(strings.ToLower(schema), strings.ToLower(table))
}
func (f loweredFilter) MatchSchema(schema string) bool {
return f.wrapped.MatchSchema(strings.ToLower(schema))
}
func (f loweredFilter) toLower() Filter {
return f
}
type allFilter struct{}
func (allFilter) MatchTable(string, string) bool {
return true
}
func (allFilter) MatchSchema(string) bool {
return true
}
func (f allFilter) toLower() Filter {
return f
}
// All creates a tableFilter which matches everything.
func All() Filter {
return allFilter{}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.