text
stringlengths 11
4.05M
|
|---|
package api
import (
"crypto/rsa"
"time"
)
// OpenShiftCluster represents an OpenShift cluster
type OpenShiftCluster struct {
MissingFields
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
Location string `json:"location,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
Properties Properties `json:"properties,omitempty"`
}
// Properties represents an OpenShift cluster's properties
type Properties struct {
MissingFields
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
ServicePrincipalProfile ServicePrincipalProfile `json:"servicePrincipalProfile,omitempty"`
NetworkProfile NetworkProfile `json:"networkProfile,omitempty"`
MasterProfile MasterProfile `json:"masterProfile,omitempty"`
WorkerProfiles []WorkerProfile `json:"workerProfiles,omitempty"`
APIServerURL string `json:"apiserverUrl,omitempty"`
ConsoleURL string `json:"consoleUrl,omitempty"`
Installation *Installation `json:"installation,omitempty"`
ResourceGroup string `json:"resourceGroup,omitempty"`
StorageSuffix string `json:"storageSuffix,omitempty"`
ClusterID string `json:"clusterId,omitempty"`
SSHKey *rsa.PrivateKey `json:"sshKey,omitempty"`
AdminKubeconfig []byte `json:"adminKubeconfig,omitempty"`
KubeadminPassword string `json:"kubeadminPassword,omitempty"`
}
// ProvisioningState represents a provisioning state
type ProvisioningState string
// ProvisioningState constants
const (
ProvisioningStateUpdating ProvisioningState = "Updating"
ProvisioningStateDeleting ProvisioningState = "Deleting"
ProvisioningStateSucceeded ProvisioningState = "Succeeded"
ProvisioningStateFailed ProvisioningState = "Failed"
)
// ServicePrincipalProfile represents a service principal profile.
type ServicePrincipalProfile struct {
MissingFields
ClientID string `json:"clientId,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
}
// NetworkProfile represents a network profile
type NetworkProfile struct {
MissingFields
PodCIDR string `json:"podCidr,omitempty"`
ServiceCIDR string `json:"serviceCidr,omitempty"`
}
// MasterProfile represents a master profile
type MasterProfile struct {
MissingFields
VMSize VMSize `json:"vmSize,omitempty"`
SubnetID string `json:"subnetId,omitempty"`
}
// VMSize represents a VM size
type VMSize string
// VMSize constants
const (
VMSizeStandardD2sV3 VMSize = "Standard_D2s_v3"
VMSizeStandardD4sV3 VMSize = "Standard_D4s_v3"
VMSizeStandardD8sV3 VMSize = "Standard_D8s_v3"
)
// WorkerProfile represents a worker profile
type WorkerProfile struct {
MissingFields
Name string `json:"name,omitempty"`
VMSize VMSize `json:"vmSize,omitempty"`
DiskSizeGB int `json:"diskSizeGB,omitempty"`
SubnetID string `json:"subnetId,omitempty"`
Count int `json:"count,omitempty"`
}
// Installation represents an installation process
type Installation struct {
MissingFields
Now time.Time `json:"now,omitempty"`
Phase InstallationPhase `json:"phase"`
}
// InstallationPhase represents an installation phase
type InstallationPhase int
// InstallationPhase constants
const (
InstallationPhaseDeployStorage InstallationPhase = iota
InstallationPhaseDeployResources
InstallationPhaseRemoveBootstrap
)
|
package admin
import (
"context"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type DeleteUpstreamChannelLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDeleteUpstreamChannelLogic(ctx context.Context, svcCtx *svc.ServiceContext) DeleteUpstreamChannelLogic {
return DeleteUpstreamChannelLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DeleteUpstreamChannelLogic) DeleteUpstreamChannel(req types.DeleteUpstreamChannelRequest) error {
// 查询上游通道是否有下游通道关联
isHave, err := model.NewPlatformChannelUpstreamModel(l.svcCtx.DbEngine).CheckUpstreamById(req.ChannelId)
if err != nil {
l.Errorf("查询通道[%v]是否被下游通道关联失败, err=%v", req.ChannelId, err)
return common.NewCodeError(common.SysDBDelete)
}
if isHave {
l.Errorf("查询通道[%v]有下游通道关联, 不能删除", req.ChannelId)
return common.NewCodeError(common.ChannelHaveLinkedChannelNotDelete)
}
if err := model.NewUpstreamChannelModel(l.svcCtx.DbEngine).Delete(req.ChannelId); err != nil {
l.Errorf("删除通道[%v]失败, err=%v", req.ChannelId, err)
return common.NewCodeError(common.SysDBDelete)
}
return nil
}
|
package main
import (
"encoding/json"
"fmt"
"log"
)
type Envelope struct {
Type string `json:"type"`
Msg interface{} `json:"msg"`
}
type Sound struct {
Description string `json:"description"`
Authority string `json:"authority"`
}
type Cowbell struct {
More bool `json:"more"`
}
func main() {
s := Envelope{
Type: "sound",
Msg: &Sound{
Description: "dynamite",
Authority: "the Bruce Dickinson",
},
}
buf, err := json.Marshal(s)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf)
c := Envelope{
Type: "cowbell",
Msg: &Cowbell{
More: true,
},
}
buf, err = json.Marshal(c)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf)
}
|
package input06
const Problem = `ZR5)FZS
WCY)ZB3
NXV)8ZY
CMN)CLW
4XG)8VX
M8S)4F5
QWB)7WM
JG4)VPL
JG3)ZPC
VKR)KF7
WH8)8RS
CNS)D71
P3L)6SK
CXM)HSV
9JX)D4R
L25)4ZM
C97)CNS
7R9)H6M
XPT)QVX
VMQ)9M2
8C4)8F8
MFN)WZF
HP9)PBG
L36)BH1
CHP)HP9
MJ3)783
48Y)BJM
R4X)BPZ
PSY)6FM
HD5)FJX
D8M)HLW
49J)KLD
LZ4)7BZ
3LZ)TR5
NHB)WXK
DMQ)Y2R
W8S)GD7
D71)T11
GZ5)N75
CLW)W46
7XW)C8R
CS2)QS7
BTP)2MZ
H5Y)JCB
DCX)XK1
BFZ)B1C
JCJ)YBJ
1D4)TSW
SVG)97P
LVD)FQN
FY3)Q6R
9MD)YLC
5YN)NJ2
8RL)13T
3ZT)4SG
CJ6)X6D
1NV)JCJ
35N)R8N
VL7)M78
NJ2)7H8
JQG)VL7
3CF)T2M
NZ5)ZGQ
7WX)KFR
YVS)6NH
ZDS)17X
KZN)VX8
T6M)FSJ
11S)3PN
YDK)G4Y
N7S)3ZK
7QN)35N
MC9)ZDR
2Z1)LY7
DWY)WDS
ZV1)PTW
5R4)PWJ
8GR)8LH
WF5)3K5
JS8)YQQ
2CD)ZC2
XSN)NX5
LY7)382
GC2)1YF
8LF)SV1
NNB)QWB
BDW)G8N
WSD)5NN
2MZ)VBP
V6L)Z4Y
7H8)5LZ
VS4)J1F
CWL)C27
V1M)XYQ
QNZ)G3G
D4R)NF9
NNP)JG3
B37)P5P
DLX)4KM
CR8)H7N
HVQ)193
3ZM)1QP
7JX)LJN
TNW)CYP
8ZY)9WS
LTX)51X
PNQ)NWH
W16)QV7
TB1)Y39
KF7)MZH
R41)QX1
1J6)J4T
BCH)9RF
1B1)XHX
YXZ)7P5
3K7)NSV
LPL)ZDS
L9P)83J
FZR)YX3
W9N)11P
CWZ)S21
MRD)YG4
22L)NXN
1JH)S4G
PXJ)6CF
B5P)HLG
PSL)YVS
Q1T)DLX
7SQ)37T
YFK)LCC
XHC)51C
PZ5)HT8
YTP)J73
H6G)XVV
GG5)DS7
KVF)PSL
N75)SYT
2Z1)L36
T54)JGP
G3G)RBM
2HV)3SH
NHF)KNC
H9T)3CZ
1M9)G3B
LK3)PNQ
XMS)1NV
LMR)ZZP
KJD)S1Q
759)917
XDS)NBS
596)RVR
DJM)T9D
G5D)JCH
TZ6)2XK
KH3)9JX
NXT)5Q1
7VV)VW7
Q48)8GR
PRV)P59
3SV)NNN
6WK)P3L
T11)2X2
FST)TVR
72X)388
H6M)6HN
L3V)WXJ
NXV)C3M
7WY)VZN
CVS)7JX
2KK)DMQ
49H)XCL
XRQ)3BX
S1Q)97G
BJM)759
33J)F3Q
N97)WF5
PMW)V5C
3XD)JQG
BVM)L25
H5J)2SV
VV4)NV7
FCZ)KHK
1BY)32K
M4X)DQG
ZS1)NHS
QV7)42L
F3Q)GKF
7LN)S3D
ZWK)VG1
1Z9)7CR
335)N12
628)B34
9LW)5PJ
6HZ)ZR5
XSR)YXL
6GD)BQR
FQN)7YX
TY9)1H7
8MY)X3B
R6J)9BR
S5Z)N7S
XFR)W8J
6V7)CG5
4YF)HHQ
4GX)WG4
6WH)7KG
5MK)V1G
B1C)WWN
8M2)9V4
JJ2)9LW
5JR)GKD
54F)LYP
7KG)9FK
DQB)WMJ
Q7Q)9VM
TJW)C14
5YN)CCQ
HDY)WCP
G1S)YDK
BH1)VC4
DJS)CFP
THJ)2TQ
6PN)1M9
783)XLZ
CZQ)87X
759)W9N
HLW)ZZX
THD)DHX
VW7)G7J
7MN)K2B
HKW)PSK
YXC)H6G
NCM)5MK
T49)PZF
1D1)335
1V6)6HZ
46W)544
GGC)Q7Q
NKZ)HMF
G3B)CH4
X9B)J79
9RF)X1T
S4G)7WX
4Y7)4K6
WWN)4R7
8XC)7DW
9FP)2LK
7VV)W6Z
HRR)7SQ
6HP)CMN
32K)V8W
69S)XSR
HS6)6JW
22Q)2HV
PTC)3C6
JF5)5R4
JCH)L65
TNW)QJJ
91D)45B
RJ5)8LF
4D9)983
HRS)PSY
MT5)T1T
5PJ)S48
FSJ)7HW
SMQ)P2Y
KNC)46W
HMF)9FP
9V4)3DX
P5P)YWH
7BZ)1P4
X3B)JF5
FHJ)KBG
RZW)PLS
W16)25D
Z54)TNW
8YP)B29
DRP)NHQ
XDS)X65
J7Z)VHZ
M2R)1BY
4XG)F18
JYZ)P5X
5Q1)HKW
TZ3)G2Y
19S)GZ5
JW5)MT5
PWT)RCJ
ZXC)DQB
RSN)T35
VSB)HSD
NV7)CN4
X86)G1S
BKC)22Q
8F8)F6K
NTW)NNP
PB2)J8M
G4S)Y4F
THS)Q2T
XKV)N3T
7RN)MFN
RLT)L97
Y4P)P36
SGM)DWY
FX7)RJ5
9VM)49J
72D)8V2
HNC)GG3
RVR)6Y4
8V2)K6N
TV7)BSC
NBS)JJJ
COM)28P
QSY)MRM
LVN)X3M
WNH)DHT
R16)DJM
RBM)YXY
QJJ)VPY
ZB8)B8G
J79)HDY
NTS)G4S
9FK)NRC
TSW)HFM
DS7)BX1
JGP)CJ4
17X)XY6
7DW)4WR
7SQ)3FP
WZH)2Z1
TN8)CJ6
XRJ)22L
H5T)KTW
XMJ)ZC3
H4X)WL3
YG4)92F
B29)Y7B
KVG)DPN
Q8G)TQR
HLG)H5T
Y5B)T54
S3Y)7WY
W9G)PTR
YWH)QSY
5KW)5W7
WDS)PWT
1YS)DB5
6YB)HNM
GLS)RSN
H8D)XWM
FFV)3ZM
F8M)XMJ
13T)W9G
XS6)6YB
F18)5LH
WXK)VMQ
JZ7)TBG
Y92)SJ4
P2Y)GC2
MF9)TT6
NHS)XWK
KHK)6WK
TT6)T6M
8LH)9K8
Y39)91C
T63)BKC
465)7LV
HWP)4XG
X6D)HTH
N3T)ZKN
FSK)QF4
CW3)BDF
9QB)TV7
YNP)Q1T
SML)V3G
NLQ)46H
JS8)D1Z
L4L)QF6
S2T)LMR
3D2)VSB
GHB)F29
WRD)FB3
NLQ)N8N
HBL)S5T
6HN)8Y2
6SY)7RL
4YF)JL4
638)NKZ
VG1)4R4
M4N)77J
959)2LZ
J1F)D7L
MFP)6V7
LWB)WH8
6Y6)19S
5W7)HWL
9L1)HG4
5WY)YJ9
5NN)GNX
6NH)QCH
Y5M)QNZ
MJD)Q48
Z4Q)BTP
WZF)71T
GSF)NXT
N12)QL8
TTQ)Y7F
1NV)7RN
HSD)YY3
XY6)8XT
CT5)BMW
GB3)L5Z
KL2)TJW
H7N)HHC
LCG)Y4P
YWJ)ZWK
ZXC)KH7
QCH)SLZ
4R4)45G
544)YYZ
TR5)1Z9
1P4)X5Z
6FM)B2T
1T2)GF8
F29)YKX
P92)M4X
K6N)JS8
3G8)7R9
KFR)V2T
45G)9JP
QF4)SZ6
YXY)GLS
VR3)PCQ
WV9)6WX
8G7)N97
Q5B)DCX
XYQ)K8V
2X2)PL4
FVP)9BK
PZG)VCP
1Q2)9NK
ZDR)R8T
C5G)8M2
7LV)HBN
MH7)G98
KFR)P99
J53)HJS
K8S)DX5
HHR)T8B
VLW)PWV
JJJ)1B9
CH1)1Q2
BPZ)YNP
9QB)DJ2
RZW)RLT
SZY)H53
GRP)1TC
VPY)THL
7WX)X83
8Y2)N6F
5NM)1J1
YY3)1DY
88S)615
W1C)R9D
FKN)FY3
5CX)LKB
P99)WLZ
RBN)T5K
PB2)VR3
TZ6)MF9
BXH)X9B
5TN)FVQ
5LZ)KJD
XN5)1HS
H5Y)R4X
37T)WMZ
LRY)HQH
PWJ)XKV
2LK)SG5
JCB)BJW
1B9)CWL
FWB)7QN
58G)CS2
HT8)XT9
B65)MV5
7FD)TZ3
42L)H3G
B62)S3P
BZ3)BDM
VCP)C7W
94F)V54
JBK)KL2
YKX)Y92
YQX)HHR
1H7)SXM
1ZF)YQX
388)6KK
M78)DQV
1J5)JGL
41N)6GS
LCC)FC8
MRM)XFL
V7Z)94F
JQG)2BF
W5K)TN8
CS2)91D
635)QZZ
5LH)HDB
XHX)XQV
X36)Y5B
CG5)3LQ
V3G)WV9
SMN)FZR
2SV)NMJ
F92)1B1
NHQ)6SY
BDM)HQ2
1K7)F77
QZZ)SYG
YXD)JW1
11P)7MN
6KK)VV4
VNM)3SV
LX2)WL4
GG3)54Y
WVF)DDH
1TC)HQ9
886)SML
XMN)TFK
LKB)WLS
ZKN)SWR
VPL)SKH
FBB)KVG
P5X)S4Z
H51)5NM
BFQ)H9T
QKL)1T2
Y7F)B2B
W9D)1CL
HQH)TTQ
FQB)SNJ
77J)RYM
917)1N2
R8T)HD5
VS4)959
K6F)W3H
7CR)YPQ
N27)YXZ
617)7XW
SYG)M5J
9XD)THD
YQQ)W5K
PRM)635
KLX)DZQ
784)P92
1TN)QJ1
THL)KWP
SXM)BZ3
193)839
FC8)GSF
DJM)R6J
VJX)NJY
PSK)4NC
HHC)MQ5
5CB)XHC
PLZ)S5Z
6SK)88V
ZPR)LWB
83J)B65
J8M)QM5
GTY)SAN
FBN)F96
CPF)D3V
K82)LCG
YPQ)X6M
KLD)1B3
4HT)HRS
FZS)49S
S45)8XC
3CZ)YNV
L73)1D1
9KX)TDD
P7J)LSS
4QQ)RZ2
R9D)Z47
3PN)XRJ
V1G)Y9R
6Y4)P7J
JWV)2S2
7RL)465
CZV)4YF
21K)FQB
PCQ)W16
TQR)8HS
W6Z)195
KVG)S2C
Q81)Z4Q
23P)NF8
JRD)GTV
Z54)F8M
KFC)M4N
D3Q)TBB
1H1)1TN
6N6)L9P
87X)HSS
XWK)M5Q
R8N)K6F
ZZP)8GX
J7Z)KNV
PL4)3CF
ZY4)KVF
FB3)8RL
L2S)54F
LT2)LVD
FVQ)1J5
HSS)S2T
Y6N)T4C
72D)THJ
4K6)XZJ
DHX)FCZ
RV4)YFK
4NC)ZF2
6WX)KTC
WLZ)6Y6
SZ6)5CB
QF6)RBN
839)7CJ
K2Y)DVL
RZ2)BFZ
1HS)JZ7
HSV)WCM
MS8)V1M
JL4)S3Y
KWP)88S
T1T)4HT
XDB)TB1
SN1)4QQ
2TQ)YS6
R6J)K8S
BX1)TDL
G3F)784
SLZ)4W9
X65)6WJ
WC4)72X
YPQ)SGM
T54)TF4
DQV)THS
NNB)JWV
CN4)XSN
1TC)C2F
HJS)ZPR
PWV)LPL
XR3)Y3R
59R)926
KH7)FY7
TDD)Z6D
195)628
KHK)WCY
9QZ)B37
Q2T)BP1
BSC)1JH
W46)RZN
FZH)GG5
4SR)6NR
983)9QZ
7YX)68C
NPF)CHP
JX7)Z2Y
G7J)49H
4KM)YXD
DJ9)6PN
MV5)FST
8GR)4D9
ZB3)K7Y
T4C)MF5
NMJ)WZH
KH7)J53
H53)JW3
CYP)WRD
YYZ)9XD
RMG)W1C
PXM)JG4
6Q7)FSK
L2S)DJS
DPN)V5K
8VX)2PZ
4SG)BFQ
HQ2)ZQ3
382)VJX
VC4)FR7
FR7)YDQ
3LQ)T49
YY3)7ZK
6NR)Q5B
VY1)KZN
YX3)1YS
LJQ)D8M
615)69S
SG5)3K7
1B3)BQ7
XRJ)6GD
DDH)XRQ
D5S)QM1
QX1)CT5
LYP)6HP
WLS)WSR
SJS)46J
F6K)8G7
YXL)JJ2
GMP)CVS
4R7)RZV
544)617
QL8)LFC
WSR)NHB
V8W)ZNG
97P)LK3
T1T)FM6
XLZ)BNV
FST)21K
QM5)ZGN
MQ5)W2T
XK1)W9D
QS7)FHJ
G4Y)MLQ
6CF)VQX
8VX)KH3
BMW)VYR
VW7)TQX
N8N)6Q7
Z6D)V6L
9K8)81T
VMQ)TY9
PTW)HN4
PNV)K2Y
TF4)1D4
2S2)59W
YS6)58G
NWH)W4J
HBN)3XD
Q15)NHF
B2B)3VG
VX8)HWP
VBP)FBB
PLS)H5J
1N2)CXM
DX5)V7Z
TY9)J7Z
LZ4)PLZ
JM9)HNC
HG4)4Y7
CFP)5JR
BDF)XPT
FQN)K62
M5L)K82
TBG)2LX
2S2)X36
4QQ)Z54
926)CR8
W4J)6N6
71T)G9J
SNJ)DJ9
S2C)LTX
JG3)8CG
1QP)PMW
FM6)SMN
F96)LVN
ZD3)FR9
91C)P69
HHQ)YMG
WXR)L3V
XVV)PZG
25D)JW4
S4Z)WC4
NF9)BDW
FJX)861
VQX)H8D
K8V)33J
Z4Y)L4L
M5J)M9K
D71)947
C5L)MC9
MF5)YOU
SX5)WSD
WCM)M5L
LDD)HVQ
YLC)VF8
HN4)MM5
T35)GB3
MS8)7VV
ZPC)9L1
RJ5)H51
X83)6MX
SYG)CH1
HBP)HP1
LFC)KGW
XCL)9KX
VYM)2CK
6GS)VLW
QJ1)3D2
LJN)1J6
DJ2)26J
1J1)KLX
12H)RMG
3ZK)5YN
59W)9Y8
51X)XR3
3SH)5KW
WMZ)DH3
MPS)NZ5
P96)ZB8
BLD)HBL
B34)NTS
DH3)PTC
SWR)VY1
N8N)JW5
G8N)23P
L5Z)FZH
2BF)F92
SJ4)MJ3
JJT)7JK
ZC3)3G8
7P5)8C4
V1N)YXC
1CL)HRR
V5K)FWB
P36)HS6
W52)SJS
88V)W52
X5Z)5M6
BQ7)2JR
MZH)ZD3
Q6R)L7K
MJ5)SGR
NLR)YTP
ZNG)BLD
2PZ)R41
C9X)LZ4
1DY)B62
J4T)SVG
GQP)CZQ
5M6)BCH
1D1)1H1
Z47)684
WXJ)DK7
P4B)SQQ
68C)W8S
4WR)XN5
VF8)9HD
GD7)MH7
W2T)L73
S48)JRD
S3D)T63
V5C)SL5
C7W)BRH
K9Z)C97
6NH)12N
BRH)L2S
GD5)RG7
G5V)PRM
LVD)G5D
RG7)5CX
JW3)9MD
CJ4)FX7
PZF)M8S
7JK)MJ5
KTW)LRY
XWK)MFP
C2F)4GX
D1Z)R16
1RQ)NPF
W5F)596
9Y8)H5Y
6NW)11S
1P1)G5V
D4R)PB2
BNV)GD5
8XT)6H7
FKQ)NCM
QS7)M2R
NSV)4GQ
TQX)JT3
HP1)VS4
HQ9)XMN
F77)ZS1
M3X)PXJ
ZGN)7C4
TVR)JJT
YMG)C5G
NX5)CW3
RCJ)2KK
8VZ)1V6
DX5)GRP
9HD)1RQ
HXW)41N
Y9R)PZ5
2XK)MQJ
QF4)JH2
WG4)VNM
VHZ)RZQ
SGR)FKQ
SQQ)Y6N
DHT)GHB
4PV)QKL
GTV)NNB
CH4)1NT
3BX)JBK
RYM)FBN
VZN)S8D
SV1)KZP
THF)45S
4ZM)CWZ
T5K)5MR
26J)2CD
CXM)886
DQV)RQR
G2Y)NLQ
KNV)C9X
97G)THF
45B)NXV
9NK)DRP
XMS)TZJ
7C4)NLR
7HW)W5F
KZP)4PV
HT8)638
3CF)LT2
ZY4)Q8G
3DX)K24
BQR)TJV
46H)FVP
P69)MPS
6MX)FF4
DY5)XDB
7RL)LKK
L97)BVM
2JR)Y5M
TFK)FFV
W8J)G3F
P59)26Y
596)N27
8CG)8DL
XT9)4SR
M5Q)6WH
KBG)GMP
CCQ)8YP
9BK)CPF
HNM)353
3C6)ZXC
S8D)GTY
49S)5VJ
8GX)GGC
S3P)PXM
NXT)PNV
YBJ)YWJ
4PW)6NW
D7L)MRD
T9D)D3Q
2LX)7FD
X3M)V1N
K62)1P1
8HS)47M
TDD)JM9
HDB)BXH
MLQ)5TN
3VG)SZY
FY7)SMQ
YDQ)D5S
C3M)3ZT
N7S)HSZ
HTH)P96
WL4)5WY
28P)9QB
NJY)C5L
V54)VYM
3XD)XFR
NF8)LJQ
4W9)K9Z
RZQ)XDS
TJV)TZ6
ZGQ)72D
JT3)XS6
P92)WVF
SJ4)SN1
6H7)P4B
3K5)PRV
2CK)XMS
861)CZV
H3G)1ZF
R16)GQP
51C)4G6
V2T)1PS
L7K)WNH
HFM)VKR
Y4F)Q81
P4V)FKN
MM5)8MY
92F)H4X
7WM)3LZ
684)KFC
D3V)RV4
2T9)1K7
YJ9)TQL
B8G)HBP
DVL)ZV1
47M)XNZ
FF4)LDD
JW1)5BR
GKD)RZW
45S)Q15
L65)JX7
4F5)ZY4
SLZ)X86
1H1)JYZ
GF8)B5P
QVX)2T9
BP1)7LN
Y3R)P4V
WCP)8VZ
GB3)S45
ZC2)59R
1T2)HXW
FSJ)NTW
CH4)M3X
TBB)SX5
JW4)MS8
GRP)LX2
3FP)12H
FY3)48Y
12N)DY5
9BR)MJD
KNC)WXR
6MX)4PW
`
const TestProblem = `COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
K)YOU
I)SAN`
|
package main
import (
"cloud.google.com/go/storage"
"cloud.google.com/go/vision/apiv1"
"fmt"
"golang.org/x/net/context"
"io"
"os"
"testing"
)
func _TestCanUploadToGoogleCloudStorage(t *testing.T) {
client, err := storage.NewClient(context.Background())
if err != nil {
// TODO: handle error.
t.Errorf("%v", err)
}
_ = client // Use the client.
//bkt := client.Bucket("postit")
f, err := os.Open("image.png")
if err != nil {
t.Errorf("%v", err)
}
defer f.Close()
wc := client.Bucket("postit").Object("test_file_upload").NewWriter(context.Background())
if _, err = io.Copy(wc, f); err != nil {
t.Errorf("%v", err)
}
if err := wc.Close(); err != nil {
t.Errorf("%v", err)
}
}
func TestCanPerformTextDetection(t *testing.T) {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(context.Background())
file := "gs://postit/IMG_7237.JPG"
image := vision.NewImageFromURI(file)
annotations, err := client.DetectDocumentText(ctx, image, nil)
if err != nil {
t.Errorf("%v", err)
}
if annotations == nil {
t.Errorf("No text found")
} else {
for _, page := range annotations.Pages {
for _, block := range page.Blocks {
for _, p := range block.Paragraphs {
fmt.Printf("\n\n")
for _, w := range p.Words {
for _, s := range w.Symbols {
fmt.Printf("%v", s.Text)
}
fmt.Printf(" ")
}
}
}
}
}
}
|
package timer
import (
"time"
)
type Interface interface {
IncreaseLeftTime(key string, d time.Duration) // 增加定时器剩余时间
AddTimer(key string, d time.Duration, callback func()) // 添加定时器
OnDoTimer(key string) // 定时时间到了,处理定时器的callback
HasTimer(key string) bool // 是否有定时器
CancelTimer(key string) bool // 撤消定时器
Reset() // 重置定时器
}
type TimerWrap struct {
expirationTime time.Time
*time.Timer
}
type Manager struct {
Timers map[string]*TimerWrap
}
func NewManager() Interface {
return &Manager{
Timers: make(map[string]*TimerWrap),
}
}
func (manager *Manager) HasTimer(key string) bool {
_, ok := manager.Timers[key]
return ok
}
func (manager *Manager) CancelTimer(key string) bool {
if !manager.HasTimer(key) {
return false
}
timer := manager.getTimer(key)
delete(manager.Timers, key)
return timer.Stop()
}
func (manager *Manager) AddTimer(key string, duration time.Duration, callback func()) {
if manager.HasTimer(key) {
manager.CancelTimer(key)
}
manager.setTimer(key, duration, func() {
callback()
delete(manager.Timers, key)
})
}
func (manager *Manager) IncreaseLeftTime(key string, d time.Duration) {
if manager.HasTimer(key) == false {
return
}
wrap := manager.getTimer(key)
wrap.expirationTime = wrap.expirationTime.Add(d)
duration := wrap.expirationTime.Sub(time.Now())
wrap.Timer.Reset(duration)
}
func (manager *Manager) OnDoTimer(key string) {
if manager.HasTimer(key) == false {
return
}
wrap := manager.getTimer(key)
wrap.expirationTime = time.Now()
wrap.Timer.Reset(0)
delete(manager.Timers, key)
}
func (manager *Manager) Reset() {
for key := range manager.Timers {
manager.CancelTimer(key)
}
}
func (manager *Manager) getTimer(key string) *TimerWrap {
return manager.Timers[key]
}
func (manager *Manager) setTimer(key string, duration time.Duration, callback func()) {
timer := time.AfterFunc(duration, callback)
manager.Timers[key] = &TimerWrap{
expirationTime: time.Now().Add(duration),
Timer: timer,
}
}
|
// Copyright 2018 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 core
import (
"fmt"
"testing"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/charset"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/planner/property"
"github.com/pingcap/tidb/planner/util"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/statistics"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/ranger"
"github.com/stretchr/testify/require"
)
func rewriteSimpleExpr(ctx sessionctx.Context, str string, schema *expression.Schema, names types.NameSlice) ([]expression.Expression, error) {
if str == "" {
return nil, nil
}
filters, err := expression.ParseSimpleExprsWithNames(ctx, str, schema, names)
if err != nil {
return nil, err
}
if sf, ok := filters[0].(*expression.ScalarFunction); ok && sf.FuncName.L == ast.LogicAnd {
filters = expression.FlattenCNFConditions(sf)
}
return filters, nil
}
type indexJoinContext struct {
dataSourceNode *DataSource
dsNames types.NameSlice
path *util.AccessPath
joinNode *LogicalJoin
joinColNames types.NameSlice
}
func prepareForAnalyzeLookUpFilters() *indexJoinContext {
ctx := MockContext()
ctx.GetSessionVars().PlanID.Store(-1)
joinNode := LogicalJoin{}.Init(ctx, 0)
dataSourceNode := DataSource{}.Init(ctx, 0)
dsSchema := expression.NewSchema()
var dsNames types.NameSlice
dsSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldType(mysql.TypeLonglong),
})
dsNames = append(dsNames, &types.FieldName{
ColName: model.NewCIStr("a"),
TblName: model.NewCIStr("t"),
DBName: model.NewCIStr("test"),
})
dsSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldType(mysql.TypeLonglong),
})
dsNames = append(dsNames, &types.FieldName{
ColName: model.NewCIStr("b"),
TblName: model.NewCIStr("t"),
DBName: model.NewCIStr("test"),
})
dsSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldTypeWithCollation(mysql.TypeVarchar, mysql.DefaultCollationName, types.UnspecifiedLength),
})
dsNames = append(dsNames, &types.FieldName{
ColName: model.NewCIStr("c"),
TblName: model.NewCIStr("t"),
DBName: model.NewCIStr("test"),
})
dsSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldType(mysql.TypeLonglong),
})
dsNames = append(dsNames, &types.FieldName{
ColName: model.NewCIStr("d"),
TblName: model.NewCIStr("t"),
DBName: model.NewCIStr("test"),
})
dsSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldTypeWithCollation(mysql.TypeVarchar, charset.CollationASCII, types.UnspecifiedLength),
})
dsNames = append(dsNames, &types.FieldName{
ColName: model.NewCIStr("c_ascii"),
TblName: model.NewCIStr("t"),
DBName: model.NewCIStr("test"),
})
dataSourceNode.schema = dsSchema
dataSourceNode.SetStats(&property.StatsInfo{StatsVersion: statistics.PseudoVersion})
path := &util.AccessPath{
IdxCols: append(make([]*expression.Column, 0, 5), dsSchema.Columns...),
IdxColLens: []int{types.UnspecifiedLength, types.UnspecifiedLength, 2, types.UnspecifiedLength, 2},
}
outerChildSchema := expression.NewSchema()
var outerChildNames types.NameSlice
outerChildSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldType(mysql.TypeLonglong),
})
outerChildNames = append(outerChildNames, &types.FieldName{
ColName: model.NewCIStr("e"),
TblName: model.NewCIStr("t1"),
DBName: model.NewCIStr("test"),
})
outerChildSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldType(mysql.TypeLonglong),
})
outerChildNames = append(outerChildNames, &types.FieldName{
ColName: model.NewCIStr("f"),
TblName: model.NewCIStr("t1"),
DBName: model.NewCIStr("test"),
})
outerChildSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldTypeWithCollation(mysql.TypeVarchar, mysql.DefaultCollationName, types.UnspecifiedLength),
})
outerChildNames = append(outerChildNames, &types.FieldName{
ColName: model.NewCIStr("g"),
TblName: model.NewCIStr("t1"),
DBName: model.NewCIStr("test"),
})
outerChildSchema.Append(&expression.Column{
UniqueID: ctx.GetSessionVars().AllocPlanColumnID(),
RetType: types.NewFieldType(mysql.TypeLonglong),
})
outerChildNames = append(outerChildNames, &types.FieldName{
ColName: model.NewCIStr("h"),
TblName: model.NewCIStr("t1"),
DBName: model.NewCIStr("test"),
})
joinNode.SetSchema(expression.MergeSchema(dsSchema, outerChildSchema))
joinColNames := append(dsNames.Shallow(), outerChildNames...)
return &indexJoinContext{
dataSourceNode: dataSourceNode,
dsNames: dsNames,
path: path,
joinNode: joinNode,
joinColNames: joinColNames,
}
}
type indexJoinTestCase struct {
// input
innerKeys []*expression.Column
pushedDownConds string
otherConds string
rangeMaxSize int64
rebuildMode bool
// expected output
ranges string
idxOff2KeyOff string
accesses string
remained string
compareFilters string
}
func testAnalyzeLookUpFilters(t *testing.T, testCtx *indexJoinContext, testCase *indexJoinTestCase, msgAndArgs ...interface{}) *indexJoinBuildHelper {
ctx := testCtx.dataSourceNode.SCtx()
ctx.GetSessionVars().RangeMaxSize = testCase.rangeMaxSize
dataSourceNode := testCtx.dataSourceNode
joinNode := testCtx.joinNode
pushed, err := rewriteSimpleExpr(ctx, testCase.pushedDownConds, dataSourceNode.schema, testCtx.dsNames)
require.NoError(t, err)
dataSourceNode.pushedDownConds = pushed
others, err := rewriteSimpleExpr(ctx, testCase.otherConds, joinNode.schema, testCtx.joinColNames)
require.NoError(t, err)
joinNode.OtherConditions = others
helper := &indexJoinBuildHelper{join: joinNode, lastColManager: nil, innerPlan: dataSourceNode}
_, err = helper.analyzeLookUpFilters(testCtx.path, dataSourceNode, testCase.innerKeys, testCase.innerKeys, testCase.rebuildMode)
if helper.chosenRanges == nil {
helper.chosenRanges = ranger.Ranges{}
}
require.NoError(t, err)
if testCase.rebuildMode {
require.Equal(t, testCase.ranges, fmt.Sprintf("%v", helper.chosenRanges.Range()), msgAndArgs)
} else {
require.Equal(t, testCase.accesses, fmt.Sprintf("%v", helper.chosenAccess), msgAndArgs)
require.Equal(t, testCase.ranges, fmt.Sprintf("%v", helper.chosenRanges.Range()), msgAndArgs)
require.Equal(t, testCase.idxOff2KeyOff, fmt.Sprintf("%v", helper.idxOff2KeyOff), msgAndArgs)
require.Equal(t, testCase.remained, fmt.Sprintf("%v", helper.chosenRemained), msgAndArgs)
require.Equal(t, testCase.compareFilters, fmt.Sprintf("%v", helper.lastColManager), msgAndArgs)
}
return helper
}
func TestIndexJoinAnalyzeLookUpFilters(t *testing.T) {
indexJoinCtx := prepareForAnalyzeLookUpFilters()
dsSchema := indexJoinCtx.dataSourceNode.schema
tests := []indexJoinTestCase{
// Join key not continuous and no pushed filter to match.
{
innerKeys: []*expression.Column{dsSchema.Columns[0], dsSchema.Columns[2]},
pushedDownConds: "",
otherConds: "",
ranges: "[[NULL,NULL]]",
idxOff2KeyOff: "[0 -1 -1 -1 -1]",
accesses: "[]",
remained: "[]",
compareFilters: "<nil>",
},
// Join key and pushed eq filter not continuous.
{
innerKeys: []*expression.Column{dsSchema.Columns[2]},
pushedDownConds: "a = 1",
otherConds: "",
ranges: "[]",
idxOff2KeyOff: "[]",
accesses: "[]",
remained: "[]",
compareFilters: "<nil>",
},
// Keys are continuous.
{
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a = 1",
otherConds: "",
ranges: "[[1 NULL,1 NULL]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[eq(Column#1, 1)]",
remained: "[]",
compareFilters: "<nil>",
},
// Keys are continuous and there're correlated filters.
{
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a = 1",
otherConds: "c > g and c < concat(g, \"ab\")",
ranges: "[[1 NULL NULL,1 NULL NULL]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[eq(Column#1, 1) gt(Column#3, Column#8) lt(Column#3, concat(Column#8, ab))]",
remained: "[]",
compareFilters: "gt(Column#3, Column#8) lt(Column#3, concat(Column#8, ab))",
},
// cast function won't be involved.
{
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a = 1",
otherConds: "c > g and c < g + 10",
ranges: "[[1 NULL NULL,1 NULL NULL]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[eq(Column#1, 1) gt(Column#3, Column#8)]",
remained: "[]",
compareFilters: "gt(Column#3, Column#8)",
},
// Can deal with prefix index correctly.
{
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a = 1 and c > 'a' and c < 'aaaaaa'",
otherConds: "",
ranges: "[(1 NULL \"a\",1 NULL \"aa\"]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[eq(Column#1, 1) gt(Column#3, a) lt(Column#3, aaaaaa)]",
remained: "[gt(Column#3, a) lt(Column#3, aaaaaa)]",
compareFilters: "<nil>",
},
{
innerKeys: []*expression.Column{dsSchema.Columns[1], dsSchema.Columns[2], dsSchema.Columns[3]},
pushedDownConds: "a = 1 and c_ascii > 'a' and c_ascii < 'aaaaaa'",
otherConds: "",
ranges: "[(1 NULL NULL NULL \"a\",1 NULL NULL NULL \"aa\"]]",
idxOff2KeyOff: "[-1 0 1 2 -1]",
accesses: "[eq(Column#1, 1) gt(Column#5, a) lt(Column#5, aaaaaa)]",
remained: "[gt(Column#5, a) lt(Column#5, aaaaaa)]",
compareFilters: "<nil>",
},
// Can generate correct ranges for in functions.
{
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a in (1, 2, 3) and c in ('a', 'b', 'c')",
otherConds: "",
ranges: "[[1 NULL \"a\",1 NULL \"a\"] [1 NULL \"b\",1 NULL \"b\"] [1 NULL \"c\",1 NULL \"c\"] [2 NULL \"a\",2 NULL \"a\"] [2 NULL \"b\",2 NULL \"b\"] [2 NULL \"c\",2 NULL \"c\"] [3 NULL \"a\",3 NULL \"a\"] [3 NULL \"b\",3 NULL \"b\"] [3 NULL \"c\",3 NULL \"c\"]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[in(Column#1, 1, 2, 3) in(Column#3, a, b, c)]",
remained: "[in(Column#3, a, b, c)]",
compareFilters: "<nil>",
},
// Can generate correct ranges for in functions with correlated filters..
{
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a in (1, 2, 3) and c in ('a', 'b', 'c')",
otherConds: "d > h and d < h + 100",
ranges: "[[1 NULL \"a\" NULL,1 NULL \"a\" NULL] [1 NULL \"b\" NULL,1 NULL \"b\" NULL] [1 NULL \"c\" NULL,1 NULL \"c\" NULL] [2 NULL \"a\" NULL,2 NULL \"a\" NULL] [2 NULL \"b\" NULL,2 NULL \"b\" NULL] [2 NULL \"c\" NULL,2 NULL \"c\" NULL] [3 NULL \"a\" NULL,3 NULL \"a\" NULL] [3 NULL \"b\" NULL,3 NULL \"b\" NULL] [3 NULL \"c\" NULL,3 NULL \"c\" NULL]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[in(Column#1, 1, 2, 3) in(Column#3, a, b, c) gt(Column#4, Column#9) lt(Column#4, plus(Column#9, 100))]",
remained: "[in(Column#3, a, b, c)]",
compareFilters: "gt(Column#4, Column#9) lt(Column#4, plus(Column#9, 100))",
},
// Join keys are not continuous and the pushed key connect the key but not eq/in functions.
{
innerKeys: []*expression.Column{dsSchema.Columns[0], dsSchema.Columns[2]},
pushedDownConds: "b > 1",
otherConds: "",
ranges: "[(NULL 1,NULL +inf]]",
idxOff2KeyOff: "[0 -1 -1 -1 -1]",
accesses: "[gt(Column#2, 1)]",
remained: "[]",
compareFilters: "<nil>",
},
{
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a = 1 and c > 'a' and c < '一二三'",
otherConds: "",
ranges: "[(1 NULL \"a\",1 NULL \"一二\"]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[eq(Column#1, 1) gt(Column#3, a) lt(Column#3, 一二三)]",
remained: "[gt(Column#3, a) lt(Column#3, 一二三)]",
compareFilters: "<nil>",
},
}
for i, tt := range tests {
testAnalyzeLookUpFilters(t, indexJoinCtx, &tt, fmt.Sprintf("test case: %v", i))
}
}
func checkRangeFallbackAndReset(t *testing.T, ctx sessionctx.Context, expectedRangeFallback bool) {
require.Equal(t, expectedRangeFallback, ctx.GetSessionVars().StmtCtx.RangeFallback)
ctx.GetSessionVars().StmtCtx.RangeFallback = false
}
func TestRangeFallbackForAnalyzeLookUpFilters(t *testing.T) {
ijCtx := prepareForAnalyzeLookUpFilters()
ctx := ijCtx.dataSourceNode.SCtx()
dsSchema := ijCtx.dataSourceNode.schema
type testOutput struct {
ranges string
idxOff2KeyOff string
accesses string
remained string
compareFilters string
}
tests := []struct {
innerKeys []*expression.Column
pushedDownConds string
otherConds string
outputs []testOutput
}{
{
innerKeys: []*expression.Column{dsSchema.Columns[1], dsSchema.Columns[3]},
pushedDownConds: "a in (1, 3) and c in ('aaa', 'bbb')",
otherConds: "",
outputs: []testOutput{
{
ranges: "[[1 NULL \"aa\" NULL,1 NULL \"aa\" NULL] [1 NULL \"bb\" NULL,1 NULL \"bb\" NULL] [3 NULL \"aa\" NULL,3 NULL \"aa\" NULL] [3 NULL \"bb\" NULL,3 NULL \"bb\" NULL]]",
idxOff2KeyOff: "[-1 0 -1 1 -1]",
accesses: "[in(Column#1, 1, 3) in(Column#3, aaa, bbb)]",
remained: "[in(Column#3, aaa, bbb)]",
compareFilters: "<nil>",
},
{
ranges: "[[1 NULL \"aa\",1 NULL \"aa\"] [1 NULL \"bb\",1 NULL \"bb\"] [3 NULL \"aa\",3 NULL \"aa\"] [3 NULL \"bb\",3 NULL \"bb\"]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[in(Column#1, 1, 3) in(Column#3, aaa, bbb)]",
remained: "[in(Column#3, aaa, bbb)]",
compareFilters: "<nil>",
},
{
ranges: "[[1 NULL,1 NULL] [3 NULL,3 NULL]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[in(Column#1, 1, 3)]",
remained: "[in(Column#3, aaa, bbb)]",
compareFilters: "<nil>",
},
{
ranges: "[]",
idxOff2KeyOff: "[]",
accesses: "[]",
remained: "[]",
compareFilters: "<nil>",
},
},
},
{
// test haveExtraCol
innerKeys: []*expression.Column{dsSchema.Columns[0]},
pushedDownConds: "b in (1, 3, 5)",
otherConds: "c > g and c < concat(g, 'aaa')",
outputs: []testOutput{
{
ranges: "[[NULL 1 NULL,NULL 1 NULL] [NULL 3 NULL,NULL 3 NULL] [NULL 5 NULL,NULL 5 NULL]]",
idxOff2KeyOff: "[0 -1 -1 -1 -1]",
accesses: "[in(Column#2, 1, 3, 5) gt(Column#3, Column#8) lt(Column#3, concat(Column#8, aaa))]",
remained: "[]",
compareFilters: "gt(Column#3, Column#8) lt(Column#3, concat(Column#8, aaa))",
},
{
ranges: "[[NULL 1,NULL 1] [NULL 3,NULL 3] [NULL 5,NULL 5]]",
idxOff2KeyOff: "[0 -1 -1 -1 -1]",
accesses: "[in(Column#2, 1, 3, 5)]",
remained: "[]",
compareFilters: "<nil>",
},
{
ranges: "[[NULL,NULL]]",
idxOff2KeyOff: "[0 -1 -1 -1 -1]",
accesses: "[]",
remained: "[in(Column#2, 1, 3, 5)]",
compareFilters: "<nil>",
},
},
},
{
// test nextColRange
innerKeys: []*expression.Column{dsSchema.Columns[1]},
pushedDownConds: "a in (1, 3) and c > 'aaa' and c < 'bbb'",
otherConds: "",
outputs: []testOutput{
{
ranges: "[[1 NULL \"aa\",1 NULL \"bb\"] [3 NULL \"aa\",3 NULL \"bb\"]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[in(Column#1, 1, 3) gt(Column#3, aaa) lt(Column#3, bbb)]",
remained: "[gt(Column#3, aaa) lt(Column#3, bbb)]",
compareFilters: "<nil>",
},
{
ranges: "[[1 NULL,1 NULL] [3 NULL,3 NULL]]",
idxOff2KeyOff: "[-1 0 -1 -1 -1]",
accesses: "[in(Column#1, 1, 3)]",
remained: "[gt(Column#3, aaa) lt(Column#3, bbb)]",
compareFilters: "<nil>",
},
},
},
}
for _, tt := range tests {
ijCase := &indexJoinTestCase{
innerKeys: tt.innerKeys,
pushedDownConds: tt.pushedDownConds,
otherConds: tt.otherConds,
rangeMaxSize: 0,
}
for i, res := range tt.outputs {
ijCase.ranges = res.ranges
ijCase.idxOff2KeyOff = res.idxOff2KeyOff
ijCase.accesses = res.accesses
ijCase.remained = res.remained
ijCase.compareFilters = res.compareFilters
ijHelper := testAnalyzeLookUpFilters(t, ijCtx, ijCase)
checkRangeFallbackAndReset(t, ctx, i > 0)
ijCase.rangeMaxSize = ijHelper.chosenRanges.Range().MemUsage() - 1
}
}
// test that building ranges doesn't have mem limit under rebuild mode
ijCase := &indexJoinTestCase{
innerKeys: []*expression.Column{dsSchema.Columns[0], dsSchema.Columns[2]},
pushedDownConds: "b in (1, 3) and d in (2, 4)",
otherConds: "",
rangeMaxSize: 1,
rebuildMode: true,
ranges: "[[NULL 1 NULL 2,NULL 1 NULL 2] [NULL 1 NULL 4,NULL 1 NULL 4] [NULL 3 NULL 2,NULL 3 NULL 2] [NULL 3 NULL 4,NULL 3 NULL 4]]",
}
ijHelper := testAnalyzeLookUpFilters(t, ijCtx, ijCase)
checkRangeFallbackAndReset(t, ctx, false)
require.Greater(t, ijHelper.chosenRanges.Range().MemUsage(), ijCase.rangeMaxSize)
}
|
package services
import (
"github.com/astaxie/beego"
"github.com/goinggo/beego-mgo/utilities/mongo"
"BeegoApi01/models"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
//** TYPES
type (
// buoyConfiguration contains settings for running the buoy service.
buoyConfig struct {
Database string
}
)
//** PACKAGE VARIABLES
// Config provides buoy configuration.
var (
Config buoyConfig
dbCollectionName string
)
//** INIT
func init() {
// Pull in the configuration.
Config.Database = "testdb2"
dbCollectionName = "users"
}
//** PUBLIC FUNCTIONS
// FindUser retrieves the specified station
func FindUser(service *Service, userId string) (*models.User, error) {
beego.Info("userService.FindUser() is called ~~~", "FindUser: ", userId)
var usr models.User
f := func(collection *mgo.Collection) error {
queryMap := bson.M{"userId": userId}
beego.Info(service.UserID, "FindUser, MGO :", mongo.ToString(queryMap))
return collection.Find(queryMap).One(&usr)
}
if err := service.DBAction(Config.Database, dbCollectionName, f); err != nil {
if err != mgo.ErrNotFound {
beego.Error(err, service.UserID, "FindUser")
return nil, err
}
}
return &usr, nil
}
func FindAllUsers(service *Service, userId string) ([]models.User, error) {
beego.Info("userService.FindAllUsers() is called ~~~", "UserId: ", userId)
var users []models.User
f := func(collection *mgo.Collection) error {
queryMap := bson.M{"userId": userId}
beego.Info(service.UserID, "FindAllUsers, MGO : ", mongo.ToString(queryMap))
return collection.Find(queryMap).All(&users)
}
if err := service.DBAction(Config.Database, dbCollectionName, f); err != nil {
if err != mgo.ErrNotFound {
beego.Error(err, service.UserID, "FindAllUsers")
return nil, err
}
}
return users, nil
}
func AddUser(service *Service, user *models.User) (string, error) {
beego.Info("userService.AddUser() is called ~~~, User: ", user)
uid := "uid12345678"
return uid, nil
}
|
/*
Copyright 2020 Cornelius Weig.
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 homebrew
import (
"context"
"github.com/corneliusweig/krew-index-tracker/pkg/homebrew/client"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
func SaveAnalyticsToBigQuery(ctx context.Context) error {
fetcher := client.NewHomebrew("https://formulae.brew.sh/api/formula/krew.json")
logrus.Infof("Fetching homebrew download statistics")
homebrewStats, err := fetcher.FetchAnalytics(ctx)
if err != nil {
return errors.Wrapf(err, "could not fetch homebrew analytics")
}
logrus.Infof("Uploading summaries to BigQuery")
if err := client.HomebrewBigQuery().Upload(ctx, homebrewStats); err != nil {
return errors.Wrapf(err, "failed saving scraped data")
}
return nil
}
|
package test
import (
"encoding/json"
"fmt"
"testing"
noSkipValidation "github.com/daverlo/generate/test/noSkipValidation_gen"
"github.com/stretchr/testify/assert"
)
func TestNoSkipValidation(t *testing.T) {
// this just tests the name generation works correctly
s := noSkipValidation.Simple{
Name: "name",
}
v, err := json.Marshal(&s)
assert.Error(t, err, "json: error calling MarshalJSON for type *noSkipValidation.Simple: address is a required field")
fmt.Println(v)
}
|
package main
//nodemon --exec go run main.go --signal SIGTERM
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
)
//
type Page struct {
Title string
Body []byte
}
//
type Tab struct {
Nombre string
Numero int
CabeceraActiva string
CuerpoActivo string
Activa string
}
//
type Contenido struct {
Texto string
}
//
type Token struct {
Lexema string `json:"lexema"`
Tipo int `json:"tipo"`
Fila int `json:"fila"`
Columna int `json:"columna"`
}
//
type Lista struct {
Analizador string `json:"analizador"`
Lista Analisis `json:"lista"`
}
//
type Analisis struct {
Lenguaje string `json:"lenguaje"`
ListaTokens []Token `json:"listaTokens"`
ListaErroresLex []Token `json:"listaErroresLex"`
ListaErroresSintact []Token `json:"listaErroresSintact"`
Traduccion string `json:"traduccion"`
Grafo string `json:"grafo"`
}
//
type Pagina struct {
Tabs []Tab
Python Analisis
JavaScript Analisis
}
var tabs = []Tab{}
var pagina = Pagina{}
var lenguaje = ""
func homeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
u, err := url.Parse(r.RequestURI)
if err != nil {
log.Fatal(err)
}
params := u.Query()
if params["newTab"] != nil {
fmt.Println("Hola")
nombre := "tab" + strconv.Itoa(len(tabs))
tab := Tab{Nombre: nombre, Numero: len(tabs) + 1, CuerpoActivo: "active", CabeceraActiva: "active", Activa: nombre}
tabs = append(tabs, tab)
pagina.Tabs = tabs
for i := 0; i < len(tabs); i++ {
if tabs[i].Nombre != nombre {
tabs[i].CuerpoActivo = "fade"
tabs[i].CabeceraActiva = ""
tabs[i].Activa = nombre
}
}
http.Redirect(w, r, "/home/", http.StatusSeeOther)
} else if params["getTab"] != nil {
for i := 0; i < len(tabs); i++ {
if tabs[i].Nombre == strings.Join(params["getTab"], "") {
tabs[i].CuerpoActivo = "active"
tabs[i].CabeceraActiva = "active"
tabs[i].Activa = tabs[i].Nombre
} else {
tabs[i].CuerpoActivo = "fade"
tabs[i].CabeceraActiva = ""
tabs[i].Activa = ""
}
}
http.Redirect(w, r, "/home/", http.StatusSeeOther)
} else {
//fmt.Println(pagina)
t, _ := template.ParseFiles("home.html")
t.Execute(w, pagina)
}
}
}
func clearHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
u, err := url.Parse(r.RequestURI)
if err != nil {
log.Fatal(err)
}
params := u.Query()
fmt.Println(params)
}
}
func sendPYHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Fatal(err)
}
cont := r.Form.Get("texto")
lengu := r.Form.Get("lenguaje")
if len(cont) > 0 {
fmt.Println("Contenido alto")
if lengu == "py" {
lenguaje = "py"
fmt.Println("El lenguaje es", lengu)
resp, er := http.PostForm("http://localhost:8020/analizar", url.Values{"texto": {cont}})
if er != nil {
log.Fatal(er)
}
//json.NewDecoder(r.Body).Decode(&token)
json, e := ioutil.ReadAll(resp.Body)
if e != nil {
panic(e.Error())
}
//bodyString := string(bodyBytes)
t, err1 := getJSON([]byte(json))
if err1 != nil {
log.Fatal(err1)
}
//fmt.Println(*t)
pagina.Python = *t
} else if lengu == "js" {
lenguaje = "js"
fmt.Println("El lenguaje es", lengu)
resp, er := http.PostForm("http://localhost:8030/analizar", url.Values{"texto": {cont}})
if er != nil {
log.Fatal(er)
}
//json.NewDecoder(r.Body).Decode(&token)
json, e := ioutil.ReadAll(resp.Body)
if e != nil {
panic(e.Error())
}
//bodyString := string(bodyBytes)
t, err1 := getJSON([]byte(json))
if err1 != nil {
log.Fatal(err1)
}
fmt.Println(*t)
pagina.JavaScript = *t
}
}
/*
if strings.Contains(cont, "\n") {
fmt.Println("si tiene")
}
*/
//fmt.Println(cont)
http.Redirect(w, r, "/home/", http.StatusSeeOther)
}
func grafoHandler(w http.ResponseWriter, r *http.Request) {
rutaDot := "/home/helmut/Escritorio/DescargasCOMPI1/grafo"
grafo:=""
if lenguaje=="py"{
grafo = pagina.Python.Grafo
}else if lenguaje=="js"{
grafo = pagina.JavaScript.Grafo
}
if len(grafo) > 0 {
file, err := os.Create(rutaDot + ".dot")
defer file.Close()
if err != nil {
log.Fatal(err)
}
var buffer bytes.Buffer
graph := "digraph { \n" + grafo + " }"
buffer.WriteString(graph)
escribirArchivo(file, buffer.Bytes())
generarImagen("/home/helmut/Escritorio/DescargasCOMPI1/grafo.dot", "/home/helmut/Escritorio/DescargasCOMPI1/grafo.svg")
}
http.Redirect(w, r, "/home/", http.StatusSeeOther)
}
func reportesHandler(w http.ResponseWriter, r *http.Request) {
if lenguaje=="py" {
generarReporte("Tokens Reconocidos", "tokensReconocidos", "Python", pagina.Python.ListaTokens, pagina.Python.ListaErroresSintact, pagina.Python.ListaErroresLex,"normal")
generarReporte("Errores Reconocidos", "erroresReconocidos", "Python", pagina.Python.ListaTokens, pagina.Python.ListaErroresSintact, pagina.Python.ListaErroresLex,"error")
}else if lenguaje=="js" {
generarReporte("Tokens Reconocidos", "tokensReconocidos", "JavaScript", pagina.JavaScript.ListaTokens, pagina.JavaScript.ListaErroresSintact, pagina.JavaScript.ListaErroresLex,"normal")
generarReporte("Errores Reconocidos", "erroresReconocidos", "JavaScript", pagina.JavaScript.ListaTokens, pagina.JavaScript.ListaErroresSintact, pagina.JavaScript.ListaErroresLex,"error")
}
http.Redirect(w, r, "/home/", http.StatusSeeOther)
}
func traduccionHandler(w http.ResponseWriter, r *http.Request) {
if lenguaje == "py"{
file, err := os.Create("/home/helmut/Escritorio/DescargasCOMPI1/Traducciones/TraduccionPY.py")
defer file.Close()
if err != nil {
fmt.Println("Error", err)
}
var buffer bytes.Buffer
buffer.WriteString(pagina.Python.Traduccion)
escribirArchivo(file, buffer.Bytes())
}else if lenguaje == "js" {
file, err := os.Create("/home/helmut/Escritorio/DescargasCOMPI1/Traducciones/TraduccionJS.py")
defer file.Close()
if err != nil {
fmt.Println("Error", err)
}
var buffer bytes.Buffer
buffer.WriteString(pagina.JavaScript.Traduccion)
escribirArchivo(file, buffer.Bytes())
}
http.Redirect(w, r, "/home/", http.StatusSeeOther)
}
func generarReporte(titulo, nombreArchivo, carpeta string, lista, listaErroresS, listaErroresL []Token, tipoToken string){
parte1:= `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Reportes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>`+titulo+`</h2>
<p>Combine .table-dark and .table-striped to create a dark, striped table:</p>
<table class="table table-dark table-striped">
<thead>
<tr>
<th>Numero</th>
<th>Lexema</th>
<th>Tipo</th>
<th>Fila</th>
<th>Columna</th>
</tr>
</thead>
<tbody>`
parte2:=""
if tipoToken=="normal" {
for i := 0; i < len(lista); i++ {
parte2+="<tr>"
parte2+="<td>"+fmt.Sprint(i+1)+"</td>"
parte2+="<td>"+lista[i].Lexema+"</td>"
parte2+="<td>"+fmt.Sprint(lista[i].Tipo)+"</td>"
parte2+="<td>"+fmt.Sprint(lista[i].Fila)+"</td>"
parte2+="<td>"+fmt.Sprint(lista[i].Columna)+"</td>"
parte2+="</tr>"
}
}else if tipoToken=="error" {
for i := 0; i < len(listaErroresL); i++ {
parte2+="<tr>"
parte2+="<td>"+fmt.Sprint(i+1)+"</td>"
parte2+="<td>"+listaErroresL[i].Lexema+"</td>"
parte2+="<td>"+fmt.Sprint(listaErroresL[i].Tipo)+"</td>"
parte2+="<td>"+fmt.Sprint(listaErroresL[i].Fila)+"</td>"
parte2+="<td>"+fmt.Sprint(listaErroresL[i].Columna)+"</td>"
parte2+="<td>LEXICO</td>"
parte2+="</tr>"
}
for i := 0; i < len(listaErroresS); i++ {
parte2+="<tr>"
parte2+="<td>"+fmt.Sprint(i+1)+"</td>"
parte2+="<td>"+listaErroresS[i].Lexema+"</td>"
parte2+="<td>"+fmt.Sprint(listaErroresS[i].Tipo)+"</td>"
parte2+="<td>"+fmt.Sprint(listaErroresS[i].Fila)+"</td>"
parte2+="<td>"+fmt.Sprint(listaErroresS[i].Columna)+"</td>"
parte2+="<td>SINTACTICO</td>"
parte2+="</tr>"
}
}
parte3:=`</tbody>
</table>
</div>
</body>
</html>
`
file, err := os.Create("/home/helmut/Escritorio/DescargasCOMPI1/"+carpeta+"/" + nombreArchivo+".html")
defer file.Close()
if err != nil {
fmt.Println("Error", err)
}
var buffer bytes.Buffer
buffer.WriteString(parte1+parte2+parte3)
escribirArchivo(file, buffer.Bytes())
}
func getJSON(body []byte) (*Analisis, error) {
var s = new(Analisis)
err := json.Unmarshal(body, &s)
if err != nil {
fmt.Println("whoops:", err)
}
return s, err
}
func escribirArchivo(file *os.File, bytes []byte) {
fmt.Println("Escribiendo...")
_, err := file.Write(bytes)
if err != nil {
log.Fatal(err)
}
}
func generarImagen(rutaDot, rutaImagen string) {
path, _ := exec.LookPath("dot")
cmd, _ := exec.Command(path, "-Tsvg", rutaDot).Output()
mode := int(0777)
ioutil.WriteFile(rutaImagen, cmd, os.FileMode(mode))
}
func main() {
tab := Tab{Nombre: "home", CabeceraActiva: "active", CuerpoActivo: "active", Activa: "home"}
tabs = append(tabs, tab)
http.HandleFunc("/home/", homeHandler)
http.HandleFunc("/clear/", homeHandler)
http.HandleFunc("/sendPY/", sendPYHandler)
http.HandleFunc("/grafo/", grafoHandler)
http.HandleFunc("/reportes/", reportesHandler)
http.HandleFunc("/traduccion/", traduccionHandler)
pagina.Python = Analisis{}
pagina.JavaScript = Analisis{}
pagina.Tabs = tabs
fmt.Println("Servidor Corriendo...")
log.Fatal(http.ListenAndServe(":8010", nil))
}
|
package main
func main() {
//命名规范
/*
1.允许使用数字,字母,下划线 不使用%@
2.不允许使用关键字
3.不允许数字开头
4.区分大小写
5.见名知意
*/
//驼峰命名法
/*
1.小驼峰:userName
2.大驼峰:UserName
3.下划线连接:user_name
*/
}
|
package utils
var DefaultUserName = "navenduduari"
var GogitArgs = []string{"--name=", "--help"}
func IsCmdValid(argsMap map[string]string) bool {
if len(argsMap) == 0 {
return true
}
for _, validArg := range GogitArgs {
for arg := range argsMap {
if validArg == arg {
return true
}
}
}
return false
}
type RepoStruct struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
type LanguageWithByteMap map[string]float64
type LanguageWithByteStruct struct {
Language string
ByteCount float64
}
type LanguageWithPercentageStruct struct {
Language string
Percentage float64
}
type CodeFreqStruct [][]int64
type CommitStruct []CommitBodystruct
type CommitBodystruct struct {
SHA string `json:"sha"`
}
var RawInfo = make(chan []byte)
// var GetLOC = make(chan int64)
// var GetLang = make(chan []LanguageWithPercentageStruct)
// var GetCommit = make(chan int)
// var LocDone = make(chan bool)
// var LangDone = make(chan bool)
// var CommitDone = make(chan bool)
|
package sflow
import (
"net"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"encoding/binary"
)
//origin datagram info
type Datagram struct {
IPLength int
SrcIP, DstIP net.IP
SrcPort, DstPort uint16
}
type Data struct {
Type string
Datagram Datagram
DatagramVersion uint32
AgentAddress net.IP
SubAgentID uint32
SequenceNumber uint32
AgentUptime uint32
SampleCount uint32
}
func NewData() *Data {
return &Data{}
}
func (this *Data) InitDatagram(tuple *Datagram) error {
this.Datagram.IPLength = tuple.IPLength
this.Datagram.SrcIP = tuple.SrcIP
this.Datagram.DstIP = tuple.DstIP
this.Datagram.SrcPort = tuple.SrcPort
this.Datagram.DstPort = tuple.DstPort
return nil
}
func (this *Data) Init(payload []byte) error {
pp := gopacket.NewPacket(payload, layers.LayerTypeSFlow, gopacket.Default)
if pp.ErrorLayer() != nil {
//fmt.Println(pp.Data())
//this.DecodeDataFromBytes(pp.Data())
return pp.ErrorLayer().Error()
}
if got, ok := pp.ApplicationLayer().(*layers.SFlowDatagram); ok {
this.DatagramVersion = got.DatagramVersion
this.AgentAddress = got.AgentAddress
this.SubAgentID = got.SubAgentID
this.SequenceNumber = got.SequenceNumber
this.AgentUptime = got.AgentUptime
this.SampleCount = got.SampleCount
}
return nil
}
func (this *Data) DecodeDataFromBytes(data []byte) error {
var agentAddressType layers.SFlowIPType
data ,this.DatagramVersion = data[4:],binary.BigEndian.Uint32(data[:4])
data, agentAddressType = data[4:], layers.SFlowIPType(binary.BigEndian.Uint32(data[:4]))
data, this.AgentAddress = data[agentAddressType.Length():], data[:agentAddressType.Length()]
data, this.SubAgentID = data[4:], binary.BigEndian.Uint32(data[:4])
data, this.SequenceNumber = data[4:], binary.BigEndian.Uint32(data[:4])
data, this.AgentUptime = data[4:], binary.BigEndian.Uint32(data[:4])
data, this.SampleCount = data[4:], binary.BigEndian.Uint32(data[:4])
return nil
}
|
// Copyright 2012, 2017 Dmitry Chestnykh. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package wots implements Winternitz-Lamport-Diffie one-time signature scheme.
//
// If the hash function is one-way and of sufficient length, the private key is
// random, not known to the attacker, and used to sign only one message, and
// there are no bugs in this implementation, it is infeasible to forge
// signatures (even on quantum computer, provided that it can't break the
// underlying hash function).
//
// Implementation details
//
// Cost/size trade-off parameter w=8 bits, which means that public key
// generation takes (n+2)*256+1 hash function evaluations, where n is hash
// output size in bytes. Similarly, on average, signing or verifying a single
// message take 1+((n+2)*255)/2 evaluations.
//
// Message hash is calculated with randomization as specified in NIST
// SP-800-106 "Randomized Hashing for Digital Signatures", with length
// of randomization string equal to the length of hash function output.
// The randomization string is prepended to the signature.
package wots
import (
"bytes"
"errors"
"hash"
"io"
)
// Scheme represents one-time signature signing/verification configuration.
type Scheme struct {
blockSize int
hashFunc func() hash.Hash
rand io.Reader
}
// NewScheme returns a new signing/verification scheme from the given function
// returning hash.Hash type and a random byte reader (must be cryptographically
// secure, such as crypto/rand.Reader).
//
// The hash function output size must have minimum 16 and maximum 128 bytes,
// otherwise GenerateKeyPair method will always return error.
func NewScheme(h func() hash.Hash, rand io.Reader) *Scheme {
return &Scheme{
blockSize: h().Size(),
hashFunc: h,
rand: rand,
}
}
// PrivateKeySize returns private key size in bytes.
func (s *Scheme) PrivateKeySize() int { return (s.blockSize + 2) * s.blockSize }
// PublicKeySize returns public key size in bytes.
func (s *Scheme) PublicKeySize() int { return s.blockSize }
// SignatureSize returns signature size in bytes.
func (s *Scheme) SignatureSize() int { return (s.blockSize+2)*s.blockSize + s.blockSize }
// PublicKey represents a public key.
type PublicKey []byte
// PrivateKey represents a private key.
type PrivateKey []byte
// hashBlock returns in hashed the given number of times: H(...H(in)).
// If times is 0, returns a copy of input without hashing it.
func hashBlock(h hash.Hash, in []byte, times int) (out []byte) {
out = append(out, in...)
for i := 0; i < times; i++ {
h.Reset()
h.Write(out)
out = h.Sum(out[:0])
}
return
}
// GenerateKeyPair generates a new private and public key pair.
func (s *Scheme) GenerateKeyPair() (PrivateKey, PublicKey, error) {
if s.blockSize < 16 || s.blockSize > 128 {
return nil, nil, errors.New("wots: wrong hash output size")
}
// Generate random private key.
privateKey := make([]byte, s.PrivateKeySize())
if _, err := io.ReadFull(s.rand, privateKey); err != nil {
return nil, nil, err
}
publicKey, err := s.PublicKeyFromPrivate(privateKey)
if err != nil {
return nil, nil, err
}
return privateKey, publicKey, nil
}
// PublicKeyFromPrivate returns a public key corresponding to the given private key.
func (s *Scheme) PublicKeyFromPrivate(privateKey PrivateKey) (PublicKey, error) {
if len(privateKey) != s.PrivateKeySize() {
return nil, errors.New("wots: private key size doesn't match the scheme")
}
// Create public key from private key.
keyHash := s.hashFunc()
blockHash := s.hashFunc()
for i := 0; i < len(privateKey); i += s.blockSize {
keyHash.Write(hashBlock(blockHash, privateKey[i:i+s.blockSize], 256))
}
return keyHash.Sum(nil), nil
}
// messageDigest returns a randomized digest of message with 2-byte checksum.
func messageDigest(h hash.Hash, r []byte, msg []byte) []byte {
// Randomized hashing (NIST SP-800-106).
//
// Padding: m = msg ‖ 0x80 [0x00...]
// Hashing: H(r ‖ m1 ⊕ r, ..., mL ⊕ r ‖ rv_length_indicator)
// where m1..mL are blocks of size len(r) of padded msg,
// and rv_length_indicator is 16-byte big endian len(r).
//
h.Write(r)
rlen := len(r)
tmp := make([]byte, rlen)
for len(msg) >= rlen {
for i, m := range msg[:rlen] {
tmp[i] = m ^ r[i]
}
h.Write(tmp)
msg = msg[rlen:]
}
for i := range tmp {
tmp[i] = 0
}
copy(tmp, msg)
tmp[len(msg)] = 0x80
for i := range tmp {
tmp[i] ^= r[i]
}
h.Write(tmp)
tmp[0] = uint8(rlen >> 8)
tmp[1] = uint8(rlen)
h.Write(tmp[:2])
d := h.Sum(nil)
// Append checksum of digest bits.
var sum uint16
for _, v := range d {
sum += 256 - uint16(v)
}
return append(d, uint8(sum>>8), uint8(sum))
}
// Sign signs an arbitrary length message using the given private key and
// returns signature.
//
// IMPORTANT: Do not use the same private key to sign more than one message!
// It's a one-time signature.
func (s *Scheme) Sign(privateKey PrivateKey, message []byte) (sig []byte, err error) {
if len(privateKey) != s.PrivateKeySize() {
return nil, errors.New("wots: private key size doesn't match the scheme")
}
blockHash := s.hashFunc()
// Generate message randomization parameter.
r := make([]byte, s.blockSize)
if _, err := io.ReadFull(s.rand, r); err != nil {
return nil, err
}
// Prepend randomization parameter to signature.
sig = append(sig, r...)
for _, v := range messageDigest(s.hashFunc(), r, message) {
sig = append(sig, hashBlock(blockHash, privateKey[:s.blockSize], int(v))...)
privateKey = privateKey[s.blockSize:]
}
return
}
// Verify verifies the signature of message using the public key,
// and returns true iff the signature is valid.
//
// Note: verification time depends on message and signature.
func (s *Scheme) Verify(publicKey PublicKey, message []byte, sig []byte) bool {
if len(publicKey) != s.PublicKeySize() || len(sig) != s.SignatureSize() {
return false
}
d := messageDigest(s.hashFunc(), sig[:s.blockSize], message)
sig = sig[s.blockSize:]
keyHash := s.hashFunc()
blockHash := s.hashFunc()
for _, v := range d {
keyHash.Write(hashBlock(blockHash, sig[:s.blockSize], 256-int(v)))
sig = sig[s.blockSize:]
}
return bytes.Equal(keyHash.Sum(nil), publicKey)
}
|
package main
import (
"fmt"
"os"
"github.com/vmware-tanzu-labs/git-story/adapters"
"github.com/vmware-tanzu-labs/git-story/usecases"
"gopkg.in/salsita/go-pivotaltracker.v2/v5/pivotal"
)
func newTracker() usecases.Tracker {
apiToken := os.Getenv("TRACKER_API_TOKEN")
client := pivotal.NewClient(apiToken)
return adapters.NewPivotalTracker(client.Stories)
}
func main() {
tracker := newTracker()
error := usecases.OpenStory(adapters.NewRepository(), tracker, adapters.NewBrowser())
if error != nil {
fmt.Println(error)
}
}
|
// Package importers helps with dynamic imports for templating
package importers
import (
"bytes"
"fmt"
"sort"
"strings"
"github.com/spf13/cast"
"github.com/friendsofgo/errors"
"github.com/volatiletech/strmangle"
)
// Collection of imports for various templating purposes
// Drivers add to any and all of these, and is completely responsible
// for populating BasedOnType.
type Collection struct {
All Set `toml:"all" json:"all,omitempty"`
Test Set `toml:"test" json:"test,omitempty"`
Singleton Map `toml:"singleton" json:"singleton,omitempty"`
TestSingleton Map `toml:"test_singleton" json:"test_singleton,omitempty"`
BasedOnType Map `toml:"based_on_type" json:"based_on_type,omitempty"`
}
// Set defines the optional standard imports and
// thirdParty imports (from github for example)
type Set struct {
Standard List `toml:"standard"`
ThirdParty List `toml:"third_party"`
}
// Format the set into Go syntax (compatible with go imports)
func (s Set) Format() []byte {
stdlen, thirdlen := len(s.Standard), len(s.ThirdParty)
if stdlen+thirdlen < 1 {
return []byte{}
}
if stdlen+thirdlen == 1 {
var imp string
if stdlen == 1 {
imp = s.Standard[0]
} else {
imp = s.ThirdParty[0]
}
return []byte(fmt.Sprintf("import %s", imp))
}
buf := &bytes.Buffer{}
buf.WriteString("import (")
for _, std := range s.Standard {
fmt.Fprintf(buf, "\n\t%s", std)
}
if stdlen != 0 && thirdlen != 0 {
buf.WriteString("\n")
}
for _, third := range s.ThirdParty {
fmt.Fprintf(buf, "\n\t%s", third)
}
buf.WriteString("\n)\n")
return buf.Bytes()
}
// SetFromInterface creates a set from a theoretical map[string]interface{}.
// This is to load from a loosely defined configuration file.
func SetFromInterface(intf interface{}) (Set, error) {
s := Set{}
setIntf, ok := intf.(map[string]interface{})
if !ok {
return s, errors.New("import set should be map[string]interface{}")
}
standardIntf, ok := setIntf["standard"]
if ok {
standardsIntf, ok := standardIntf.([]interface{})
if !ok {
return s, errors.New("import set standards must be an slice")
}
s.Standard = List{}
for i, intf := range standardsIntf {
str, ok := intf.(string)
if !ok {
return s, errors.Errorf("import set standard slice element %d (%+v) must be string", i, s)
}
s.Standard = append(s.Standard, str)
}
}
thirdPartyIntf, ok := setIntf["third_party"]
if ok {
thirdPartysIntf, ok := thirdPartyIntf.([]interface{})
if !ok {
return s, errors.New("import set third_party must be an slice")
}
s.ThirdParty = List{}
for i, intf := range thirdPartysIntf {
str, ok := intf.(string)
if !ok {
return s, errors.Errorf("import set third party slice element %d (%+v) must be string", i, intf)
}
s.ThirdParty = append(s.ThirdParty, str)
}
}
return s, nil
}
// Map of file/type -> imports
// Map's consumers do not understand windows paths. Always specify paths
// using forward slash (/).
type Map map[string]Set
// MapFromInterface creates a Map from a theoretical map[string]interface{}
// or []map[string]interface{}
// This is to load from a loosely defined configuration file.
func MapFromInterface(intf interface{}) (Map, error) {
m := Map{}
iter := func(i interface{}, fn func(string, interface{}) error) error {
switch toIter := intf.(type) {
case []interface{}:
for _, intf := range toIter {
obj := cast.ToStringMap(intf)
name := obj["name"].(string)
if err := fn(name, intf); err != nil {
return err
}
}
case map[string]interface{}:
for k, v := range toIter {
if err := fn(k, v); err != nil {
return err
}
}
default:
panic("import map should be map[string]interface or []map[string]interface{}")
}
return nil
}
err := iter(intf, func(name string, value interface{}) error {
s, err := SetFromInterface(value)
if err != nil {
return err
}
m[name] = s
return nil
})
if err != nil {
return nil, err
}
return m, nil
}
// List of imports
type List []string
// Len implements sort.Interface.Len
func (l List) Len() int {
return len(l)
}
// Swap implements sort.Interface.Swap
func (l List) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
// Less implements sort.Interface.Less
func (l List) Less(i, j int) bool {
res := strings.Compare(strings.TrimLeft(l[i], "_ "), strings.TrimLeft(l[j], "_ "))
if res <= 0 {
return true
}
return false
}
// NewDefaultImports returns a default Imports struct.
func NewDefaultImports() Collection {
var col Collection
col.All = Set{
Standard: List{
`"database/sql"`,
`"fmt"`,
`"reflect"`,
`"strings"`,
`"sync"`,
`"time"`,
},
ThirdParty: List{
`"github.com/friendsofgo/errors"`,
`"github.com/volatiletech/sqlboiler/v4/boil"`,
`"github.com/volatiletech/sqlboiler/v4/queries"`,
`"github.com/volatiletech/sqlboiler/v4/queries/qm"`,
`"github.com/volatiletech/sqlboiler/v4/queries/qmhelper"`,
`"github.com/volatiletech/strmangle"`,
},
}
col.Singleton = Map{
"boil_queries": {
Standard: List{
`"regexp"`,
},
ThirdParty: List{
`"github.com/volatiletech/sqlboiler/v4/drivers"`,
`"github.com/volatiletech/sqlboiler/v4/queries"`,
`"github.com/volatiletech/sqlboiler/v4/queries/qm"`,
},
},
"boil_types": {
Standard: List{
`"strconv"`,
},
ThirdParty: List{
`"github.com/friendsofgo/errors"`,
`"github.com/volatiletech/sqlboiler/v4/boil"`,
`"github.com/volatiletech/strmangle"`,
},
},
}
col.Test = Set{
Standard: List{
`"bytes"`,
`"reflect"`,
`"testing"`,
},
ThirdParty: List{
`"github.com/volatiletech/sqlboiler/v4/boil"`,
`"github.com/volatiletech/sqlboiler/v4/queries"`,
`"github.com/volatiletech/randomize"`,
`"github.com/volatiletech/strmangle"`,
},
}
col.TestSingleton = Map{
"boil_main_test": {
Standard: List{
`"database/sql"`,
`"flag"`,
`"fmt"`,
`"math/rand"`,
`"os"`,
`"path/filepath"`,
`"strings"`,
`"testing"`,
`"time"`,
},
ThirdParty: List{
`"github.com/spf13/viper"`,
`"github.com/volatiletech/sqlboiler/v4/boil"`,
},
},
"boil_queries_test": {
Standard: List{
`"bytes"`,
`"fmt"`,
`"io"`,
`"math/rand"`,
`"regexp"`,
},
ThirdParty: List{
`"github.com/volatiletech/sqlboiler/v4/boil"`,
},
},
"boil_suites_test": {
Standard: List{
`"testing"`,
},
},
}
return col
}
// NullableEnumImports returns imports collection for nullable enum types.
func NullableEnumImports() Collection {
var col Collection
col.Singleton = Map{
"boil_types": {
Standard: List{
`"bytes"`,
`"database/sql/driver"`,
`"encoding/json"`,
},
ThirdParty: List{
`"github.com/volatiletech/null/v8"`,
`"github.com/volatiletech/null/v8/convert"`,
},
},
}
return col
}
// AddTypeImports takes a set of imports 'a', a type -> import mapping 'typeMap'
// and a set of column types that are currently in use and produces a new set
// including both the old standard/third party, as well as the imports required
// for the types in use.
func AddTypeImports(a Set, typeMap map[string]Set, columnTypes []string) Set {
tmpImp := Set{
Standard: make(List, len(a.Standard)),
ThirdParty: make(List, len(a.ThirdParty)),
}
copy(tmpImp.Standard, a.Standard)
copy(tmpImp.ThirdParty, a.ThirdParty)
for _, typ := range columnTypes {
for key, imp := range typeMap {
if typ == key {
tmpImp.Standard = append(tmpImp.Standard, imp.Standard...)
tmpImp.ThirdParty = append(tmpImp.ThirdParty, imp.ThirdParty...)
}
}
}
tmpImp.Standard = strmangle.RemoveDuplicates(tmpImp.Standard)
tmpImp.ThirdParty = strmangle.RemoveDuplicates(tmpImp.ThirdParty)
sort.Sort(tmpImp.Standard)
sort.Sort(tmpImp.ThirdParty)
return tmpImp
}
// Merge takes two collections and creates a new one
// with the de-duplication contents of both.
func Merge(a, b Collection) Collection {
var c Collection
c.All = mergeSet(a.All, b.All)
c.Test = mergeSet(a.Test, b.Test)
c.Singleton = mergeMap(a.Singleton, b.Singleton)
c.TestSingleton = mergeMap(a.TestSingleton, b.TestSingleton)
c.BasedOnType = mergeMap(a.BasedOnType, b.BasedOnType)
return c
}
func mergeSet(a, b Set) Set {
var c Set
c.Standard = strmangle.RemoveDuplicates(combineStringSlices(a.Standard, b.Standard))
c.ThirdParty = strmangle.RemoveDuplicates(combineStringSlices(a.ThirdParty, b.ThirdParty))
sort.Sort(c.Standard)
sort.Sort(c.ThirdParty)
return c
}
func mergeMap(a, b Map) Map {
m := make(Map)
for k, v := range a {
m[k] = v
}
for k, toMerge := range b {
exist, ok := m[k]
if !ok {
m[k] = toMerge
}
m[k] = mergeSet(exist, toMerge)
}
return m
}
func combineStringSlices(a, b []string) []string {
c := make([]string, len(a)+len(b))
if len(a) > 0 {
copy(c, a)
}
if len(b) > 0 {
copy(c[len(a):], b)
}
return c
}
|
package data
import (
"database/sql"
"../typefile"
_ "github.com/lib/pq"
)
//フォームから受け取ったタグデータを登録する
func RegisterTag(tag typefile.TagData) {
//データベースと接続する
db, err := sql.Open("postgres", "user=trainer password=1111 dbname=imagebbs sslmode=disable")
if err != nil {
panic(err)
}
//タグデータを登録するSQL文をセットする
stmt, err := db.Prepare("INSERT INTO tags(img_id,tag_name,create_date,update_date) VALUES($1,$2,$3,$4)")
if err != nil {
panic(err)
}
//タグデータをセットして実行
stmt.Exec(tag.ImgId, tag.TagName, tag.CreateDate, tag.UpdateDate)
//DBとのコネクションを切断
db.Close()
return
}
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package printer
import (
"fmt"
"github.com/spencercjh/sshctx/internal/env"
"io"
"os"
"github.com/fatih/color"
)
var (
ErrorColor = color.New(color.FgRed, color.Bold)
WarningColor = color.New(color.FgYellow, color.Bold)
SuccessColor = color.New(color.FgGreen)
)
func init() {
colors := useColors()
if colors == nil {
return
}
if *colors {
ErrorColor.EnableColor()
WarningColor.EnableColor()
SuccessColor.EnableColor()
} else {
ErrorColor.DisableColor()
WarningColor.DisableColor()
SuccessColor.DisableColor()
}
}
func Error(w io.Writer, format string, args ...interface{}) error {
_, err := fmt.Fprintf(w, ErrorColor.Sprint("error: ")+format+"\n", args...)
return err
}
func Warning(w io.Writer, format string, args ...interface{}) error {
if _, ok := os.LookupEnv(env.Debug); ok {
_, err := fmt.Fprintf(w, WarningColor.Sprint("warning: ")+format+"\n", args...)
return err
}
return nil
}
func Success(w io.Writer, format string, args ...interface{}) error {
_, err := fmt.Fprintf(w, SuccessColor.Sprint("✔ ")+fmt.Sprintf(format+"\n", args...))
return err
}
|
package controller
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"github.com/YusukeKishino/go-blog/model"
)
type AdminPostsController struct {
db *gorm.DB
}
func NewAdminPostsController(db *gorm.DB) *AdminPostsController {
return &AdminPostsController{db: db}
}
func (c *AdminPostsController) Index(ctx *gin.Context) {
var posts []*model.Post
if err := c.db.Order("id DESC").Find(&posts).Error; err != nil {
_ = ctx.Error(err)
return
}
ctx.HTML(http.StatusOK, "admin_posts_index.html.tmpl", h(ctx, c.db, gin.H{
"posts": posts,
}))
}
func (c *AdminPostsController) Show(ctx *gin.Context) {
id := ctx.Param("id")
var post model.Post
if err := c.db.Preload("Tags").First(&post, id).Error; err != nil {
_ = ctx.Error(err)
return
}
ctx.HTML(http.StatusOK, "admin_posts_show.html.tmpl", h(ctx, c.db, gin.H{
"post": post,
}))
}
func (c *AdminPostsController) New(ctx *gin.Context) {
post := model.Post{
Title: "タイトル",
Content: "",
Status: model.Draft,
}
if err := c.db.Create(&post).Error; err != nil {
_ = ctx.Error(err)
return
}
ctx.Redirect(http.StatusFound, fmt.Sprintf("/admin/posts/edit/%d", post.ID))
}
func (c *AdminPostsController) Edit(ctx *gin.Context) {
id := ctx.Param("id")
var post model.Post
if err := c.db.Preload("Tags").First(&post, id).Error; err != nil {
_ = ctx.Error(err)
return
}
var tags []model.Tag
if err := c.db.Order("name").Find(&tags).Error; err != nil {
_ = ctx.Error(err)
return
}
ctx.HTML(http.StatusOK, "admin_posts_edit.html.tmpl", h(ctx, c.db, gin.H{
"post": post,
"tags": tags,
}))
}
func (c *AdminPostsController) Update(ctx *gin.Context) {
id := ctx.Param("id")
title := ctx.PostForm("title")
status := ctx.PostForm("status")
content := ctx.PostForm("content")
tagNames := ctx.PostFormArray("tags[]")
var post model.Post
if err := c.db.Preload("Tags").First(&post, id).Error; err != nil {
_ = ctx.Error(err)
return
}
post.Title = title
post.Status = model.PostStatus(status)
post.Content = content
if post.IsPublished() && !post.PublishedAt.Valid {
post.PublishedAt.Valid = true
post.PublishedAt.Time = time.Now()
}
err := c.db.Transaction(func(db *gorm.DB) error {
if err := c.deleteTags(db, &post, tagNames); err != nil {
return err
}
if err := c.createNewTags(db, tagNames, &post); err != nil {
return err
}
if err := c.db.Save(&post).Error; err != nil {
return err
}
return nil
})
if err != nil {
_ = ctx.Error(err)
return
}
ctx.Redirect(http.StatusFound, fmt.Sprintf("/admin/posts/show/%d", post.ID))
}
func (c *AdminPostsController) deleteTags(db *gorm.DB, post *model.Post, tagNames []string) error {
var newTags []model.Tag
var deleteTags []model.Tag
for _, tag := range post.Tags {
found := false
for _, tagName := range tagNames {
if tag.Name == tagName {
newTags = append(newTags, tag)
found = true
break
}
}
if !found {
deleteTags = append(deleteTags, tag)
}
}
post.Tags = newTags
if err := db.Model(&post).Association("Tags").Delete(deleteTags); err != nil {
return err
}
return nil
}
func (c *AdminPostsController) createNewTags(db *gorm.DB, tagNames []string, post *model.Post) error {
var tags, newTags []model.Tag
if err := db.Where("name IN ?", tagNames).Find(&tags).Error; err != nil {
return err
}
for _, tagName := range tagNames {
found := false
for _, tag := range tags {
if tagName == tag.Name {
found = true
newTags = append(newTags, tag)
break
}
}
if !found {
newTags = append(newTags, model.Tag{
Name: tagName,
})
}
}
post.Tags = newTags
return nil
}
|
package apis
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
"strconv"
"test/models"
)
const pageSize = 10
func GetBlogs(c *gin.Context) {
page := c.Request.FormValue("page")
pages, err := strconv.Atoi(page)
if err != nil{
log.Fatalln(err)
}
var b models.Blog
blogs, err := b.GetBlogs(pages, pageSize)
if err != nil {
log.Fatalln(err)
}
c.HTML(http.StatusOK, "index.html", gin.H{
"blogs":blogs,
})
}
func GetBlog(c *gin.Context) {
data := c.Request.FormValue("id")
id, _ := strconv.Atoi(data)
var b models.Blog
blog,_ := b.GetBlog(id)
c.HTML(http.StatusOK, "detail.html", gin.H{
"blog":blog,
})
}
|
package main
import (
"time"
"testing"
"github.com/zhangmingkai4315/stream-topk/spacesaving"
"github.com/zhangmingkai4315/stream-topk/stream"
)
func makeFlow() (chan string) {
config := map[string]int{
"a.com": 20,
"b.com": 17,
"c.com": 15,
"d.com": 13,
"e.com": 12,
"f.com": 11,
"g.com": 10,
"h.com": 9,
"i.com": 8,
"j.com": 7,
"k.com": 6,
"l.com": 5,
"m.com": 3,
}
flow, err := stream.NewDNSFlow(config, 0, time.Duration(10)*time.Second)
if err != nil {
panic(err)
}
stream := flow.Start()
return stream
}
func BenchmarkSsHeap(b *testing.B) {
stream := makeFlow()
manager := spacesaving.NewStreamHeap(10)
b.ResetTimer()
for i := 0; i < b.N; i++ {
domain := <-stream
manager.Offer(domain, 1)
}
}
func BenchmarkSummary(b *testing.B) {
stream := makeFlow()
manager := spacesaving.NewStreamSummary(10)
b.ResetTimer()
for i := 0; i < b.N; i++ {
domain := <-stream
manager.Offer(domain, 1)
}
}
func BenchmarkFss(b *testing.B) {
stream := makeFlow()
manager := spacesaving.NewFilterSpaceSaving(10)
b.ResetTimer()
for i := 0; i < b.N; i++ {
domain := <-stream
manager.Offer(domain, 1)
}
}
|
package main
import "fmt"
func main() {
var x [5] int
x[4] = 100
fmt.Println(x)
}
|
package 排列组合问题
// 这题目就是要求: 有重复元素的数组的所有排列。 这个代码不求具体的,而是算有多少个不同的全排列。
func numTilePossibilities(tiles string) int {
ans = 0
numTilePossibilitiesExec([]byte(tiles), 0)
return ans - 1 // -1 是为了去除空的
}
var ans int
func numTilePossibilitiesExec(bytes []byte, index int) {
/*
if index == len(bytes){
ans++
}
// 如果代码是这样的话,那么求的是bytes的全排列种数,而如果是直接ans++
// 那么求的
*/
ans++ // 总结点①
isVisit := make(map[uint8]bool)
// 获取 [index,len(bytes)-1]的全排列
for i := index; i < len(bytes); i++ {
if isVisit[bytes[i]] == true {
continue
}
isVisit[bytes[i]] = true
bytes[index], bytes[i] = bytes[i], bytes[index]
numTilePossibilitiesExec(bytes, index+1)
bytes[index], bytes[i] = bytes[i], bytes[index]
}
}
/*
总结
1. 总结点①:
// 如果代码是下面这样的话,那么求的是 bytes 的全排列种数。
if index == len(bytes){
ans++
}
// 如果代码直接是 ans++,那么求的是 bytes 以及它的子集的全排列种数。
即,通过限制,我们可以获得 bytes 长度在 [0,len(bytes)-1] 的全排列种数。
*/
|
/*
Copyright 2017 The Kubernetes Authors.
SPDX-License-Identifier: Apache-2.0
*/
package oimcsidriver
import (
"context"
"fmt"
"os"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pkg/errors"
"github.com/intel/oim/pkg/log"
"github.com/intel/oim/pkg/oim-common"
"github.com/intel/oim/pkg/spdk"
)
type localSPDK struct {
vhostEndpoint string
}
var _ OIMBackend = &localSPDK{}
func (l *localSPDK) createVolume(ctx context.Context, volumeID string, requiredBytes int64) (int64, error) {
// Connect to SPDK.
client, err := spdk.New(l.vhostEndpoint)
if err != nil {
return 0, status.Error(codes.FailedPrecondition, fmt.Sprintf("Failed to connect to SPDK: %s", err))
}
defer client.Close()
// Need to check for already existing volume name, and if found
// check for the requested capacity and already allocated capacity
bdevs, err := spdk.GetBDevs(ctx, client, spdk.GetBDevsArgs{Name: volumeID})
if err == nil && len(bdevs) == 1 {
bdev := bdevs[0]
// Since err is nil, it means the volume with the same name already exists
// need to check if the size of exisiting volume is the same as in new
// request
volSize := bdev.BlockSize * bdev.NumBlocks
if volSize >= requiredBytes {
// exisiting volume is compatible with new request and should be reused.
return volSize, nil
}
return 0, status.Error(codes.AlreadyExists, fmt.Sprintf("Volume with the same name: %s but with different size already exist", volumeID))
}
// If we get an error, we might have a problem or the bdev simply doesn't exist.
// A bit hard to tell, unfortunately (see https://github.com/spdk/spdk/issues/319).
if err != nil && !spdk.IsJSONError(err, spdk.ERROR_INVALID_PARAMS) {
return 0, status.Error(codes.FailedPrecondition, fmt.Sprintf("Failed to get BDevs from SPDK: %s", err))
}
// Check for maximum available capacity
capacity := requiredBytes
if capacity >= maxStorageCapacity {
return 0, status.Errorf(codes.OutOfRange, "Requested capacity %d exceeds maximum allowed %d", capacity, maxStorageCapacity)
}
if capacity == 0 {
// If capacity is unset, round up to minimum size (1MB?).
capacity = mib
} else {
// Round up to multiple of 512.
capacity = (capacity + 511) / 512 * 512
}
// Create new Malloc bdev.
args := spdk.ConstructMallocBDevArgs{ConstructBDevArgs: spdk.ConstructBDevArgs{
NumBlocks: capacity / 512,
BlockSize: 512,
Name: volumeID,
}}
_, err = spdk.ConstructMallocBDev(ctx, client, args)
if err != nil {
return 0, status.Error(codes.FailedPrecondition, fmt.Sprintf("Failed to create SPDK Malloc BDev: %s", err))
}
return capacity, nil
}
func (l *localSPDK) deleteVolume(ctx context.Context, volumeID string) error {
// Connect to SPDK.
client, err := spdk.New(l.vhostEndpoint)
if err != nil {
return status.Error(codes.FailedPrecondition, fmt.Sprintf("Failed to connect to SPDK: %s", err))
}
defer client.Close()
// We must not error out when the BDev does not exist (might have been deleted already).
// TODO: proper detection of "bdev not found" (https://github.com/spdk/spdk/issues/319).
if err := spdk.DeleteBDev(ctx, client, spdk.DeleteBDevArgs{Name: volumeID}); err != nil && !spdk.IsJSONError(err, spdk.ERROR_INVALID_PARAMS) {
return status.Error(codes.FailedPrecondition, fmt.Sprintf("Failed to delete SPDK Malloc BDev %s: %s", volumeID, err))
}
return nil
}
func (l *localSPDK) checkVolumeExists(ctx context.Context, volumeID string) error {
// Connect to SPDK.
client, err := spdk.New(l.vhostEndpoint)
if err != nil {
return status.Error(codes.FailedPrecondition, fmt.Sprintf("Failed to connect to SPDK: %s", err))
}
defer client.Close()
bdevs, err := spdk.GetBDevs(ctx, client, spdk.GetBDevsArgs{Name: volumeID})
if err == nil && len(bdevs) == 1 {
return nil
}
// TODO: detect "not found" error (https://github.com/spdk/spdk/issues/319)
return status.Error(codes.NotFound, "")
}
func (l *localSPDK) createDevice(ctx context.Context, volumeID string, request interface{}) (string, cleanup, error) {
// Connect to SPDK.
client, err := spdk.New(l.vhostEndpoint)
if err != nil {
return "", nil, errors.Wrap(err, "connect to SPDK")
}
defer client.Close()
// We might have already mapped that BDev to a NBD disk - check!
nbdDevice, err := findNBDDevice(ctx, client, volumeID)
if err != nil {
return "", nil, errors.Wrap(err, "find NBD device")
}
if nbdDevice != "" {
log.FromContext(ctx).Infof("Reusing already started NBD disk: %s", nbdDevice)
} else {
var nbdError error
// Find a free NBD device node and start a NBD disk there.
// Unfortunately this is racy. We assume that we are the
// only users of /dev/nbd*.
for i := 0; ; i++ {
// Filename from variable is save here.
n := fmt.Sprintf("/dev/nbd%d", i)
nbdFile, err := os.Open(n) // nolint: gosec
// We stop when we run into the first non-existent device name.
if os.IsNotExist(err) {
if nbdError == nil {
nbdError = err
}
break
}
if err != nil {
nbdError = err
continue
}
defer nbdFile.Close()
size, err := oimcommon.GetBlkSize64(nbdFile)
if err != nil {
nbdError = err
continue
}
err = nbdFile.Close()
if err != nil {
nbdError = err
continue
}
if size == 0 {
// Seems unused, take it.
nbdDevice = n
break
}
}
// Still nothing?!
if nbdDevice == "" {
return "", nil, errors.Wrap(nbdError, "no unused /dev/nbd*")
}
}
args := spdk.StartNBDDiskArgs{
BDevName: volumeID,
NBDDevice: nbdDevice,
}
if err := spdk.StartNBDDisk(ctx, client, args); err != nil {
return "", nil, errors.Wrapf(err, "start SPDK NBD disk %+v", args)
}
return nbdDevice, nil, nil
}
func (l *localSPDK) deleteDevice(ctx context.Context, volumeID string) error {
// Connect to SPDK.
client, err := spdk.New(l.vhostEndpoint)
if err != nil {
return errors.Wrap(err, "connect to SPDK")
}
defer client.Close()
// Stop NBD disk.
nbdDevice, err := findNBDDevice(ctx, client, volumeID)
if err != nil {
return errors.Wrap(err, "get NDB disks from SPDK")
}
args := spdk.StopNBDDiskArgs{NBDDevice: nbdDevice}
if err := spdk.StopNBDDisk(ctx, client, args); err != nil {
return errors.Wrapf(err, "stop SPDK NDB disk %+v", args)
}
return nil
}
func findNBDDevice(ctx context.Context, client *spdk.Client, volumeID string) (nbdDevice string, err error) {
nbdDisks, err := spdk.GetNBDDisks(ctx, client)
if err != nil {
return "", errors.Wrap(err, "get NDB disks from SPDK")
}
for _, nbd := range nbdDisks {
if nbd.BDevName == volumeID {
return nbd.NBDDevice, nil
}
}
return "", nil
}
|
package main
import "fmt"
type Node struct {
Value int
Next *Node
}
var root = new(Node)
func addNode(t *Node, v int) {
if root == nil {
t = &Node{v, nil}
root = t
return
}
for ; t.Next != nil; t = t.Next {
//fmt.Println("")
}
t.Next = &Node{v, nil}
}
func contain(t *Node, v int) bool {
if t == nil {
return false
}
for ; t != nil; t = t.Next {
if t.Value == v {
return true
}
}
return false
}
func removeNode(t *Node, v int) *Node {
if t == nil {
return t
}
//remove the first element
root := t
if t.Value == v {
root = t.Next
return root
}
for root.Next != nil {
fmt.Println(root.Value)
if root.Next.Value == v {
root.Next = root.Next.Next
return t
}
root = root.Next
}
return t
}
func main() {
root = nil
k := 3
addNode(root, 3)
addNode(root, 1)
addNode(root, 2)
addNode(root, 3)
addNode(root, 4)
addNode(root, 5)
//fmt.Println(root)
//l1 := root
//fmt.Println(contain(root, 8))
l1 := root
for contain(root, k) {
l1 = removeNode(root, k)
}
fmt.Println(l1)
for ; root != nil; root = root.Next {
fmt.Println(root.Value)
}
// for ; l1 != nil; l1 = l1.Next {
// fmt.Println(l1.Value)
// }
/*
if l1.Value == k {
root = l1.Next
}
fmt.Println(root)
//fmt.Println(l1)
// l1 := root
//l1 = l1.Next
//fmt.Println(l1.Value, "Next add")
// test1 = root
for test1 := root; test1 != nil; test1 = test1.Next {
fmt.Println(test1.Value)
}
*/
}
|
package multi_terminal_login
import (
"Open_IM/internal/push/content_struct"
"Open_IM/internal/push/logic"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
pbChat "Open_IM/pkg/proto/chat"
"Open_IM/pkg/utils"
)
func MultiTerminalLoginChecker(uid, token string, platformID int32) error {
// 1.check userid and platform class 0 not exists and 1 exists
existsInterface, err := db.DB.ExistsUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)))
if err != nil {
return err
}
exists := existsInterface.(int64)
//get config multi login policy
if config.Config.MultiLoginPolicy.OnlyOneTerminalAccess {
//OnlyOneTerminalAccess policy need to check all terminal
if utils.PlatformNameToClass(utils.PlatformIDToName(platformID)) == "PC" {
existsInterface, err = db.DB.ExistsUserIDAndPlatform(uid, "Mobile")
if err != nil {
return err
}
} else {
existsInterface, err = db.DB.ExistsUserIDAndPlatform(uid, "PC")
if err != nil {
return err
}
}
exists = existsInterface.(int64)
if exists == 1 {
err := db.DB.SetUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire)
if err != nil {
return err
}
PushMessageToTheTerminal(uid, platformID)
return nil
}
} else if config.Config.MultiLoginPolicy.MobileAndPCTerminalAccessButOtherTerminalKickEachOther {
// common terminal need to kick eich other
if exists == 1 {
err := db.DB.SetUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire)
if err != nil {
return err
}
PushMessageToTheTerminal(uid, platformID)
return nil
}
}
err = db.DB.SetUserIDAndPlatform(uid, utils.PlatformNameToClass(utils.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire)
if err != nil {
return err
}
PushMessageToTheTerminal(uid, platformID)
return nil
}
func PushMessageToTheTerminal(uid string, platform int32) {
logic.SendMsgByWS(&pbChat.WSToMsgSvrChatMsg{
SendID: uid,
RecvID: uid,
Content: content_struct.NewContentStructString(1, "", "Your account is already logged on other terminal,please confirm"),
SendTime: utils.GetCurrentTimestampBySecond(),
MsgFrom: constant.SysMsgType,
ContentType: constant.KickOnlineTip,
PlatformID: platform,
})
}
|
package resources
import (
"errors"
"net/http"
"github.com/manyminds/api2go"
"gopkg.in/mgo.v2/bson"
"themis/utils"
"themis/models"
"themis/database"
)
// CommentResource for api2go routes.
type CommentResource struct {
CommentStorage *database.CommentStorage
}
func (c CommentResource) getFilterFromRequest(r api2go.Request) (bson.M, error) {
var filter bson.M
// Getting reference context
sourceContext, sourceContextID, thisContext := utils.ParseContext(r)
switch sourceContext {
case models.WorkItemName:
if thisContext == "comments" {
filter = bson.M{"workitem_id": bson.ObjectIdHex(sourceContextID)}
}
default:
// build standard filter expression
filter = utils.BuildDbFilterFromRequest(r)
}
return filter, nil
}
// FindAll Comments.
func (c CommentResource) FindAll(r api2go.Request) (api2go.Responder, error) {
// build filter expression
filter, _ := c.getFilterFromRequest(r)
comments, _ := c.CommentStorage.GetAll(filter)
return &api2go.Response{Res: comments}, nil
}
// PaginatedFindAll can be used to load users in chunks.
// Possible success status code 200.
func (c CommentResource) PaginatedFindAll(r api2go.Request) (uint, api2go.Responder, error) {
// build filter expression
filter, _ := c.getFilterFromRequest(r)
// parse out offset and limit
queryOffset, queryLimit, err := utils.ParsePaging(r)
if err!=nil {
return 0, &api2go.Response{}, err
}
// get the paged data from storage
result, err := c.CommentStorage.GetAllPaged(filter, queryOffset, queryLimit)
if err!=nil {
return 0, &api2go.Response{}, err
}
// get total count for paging
allCount, err := c.CommentStorage.GetAllCount(filter)
if err!=nil {
return 0, &api2go.Response{}, err
}
// return everything
return uint(allCount), &api2go.Response{Res: result}, nil
}
// FindOne Comment.
// Possible success status code 200
func (c CommentResource) FindOne(id string, r api2go.Request) (api2go.Responder, error) {
utils.DebugLog.Printf("Received FindOne with ID %s.", id)
res, err := c.CommentStorage.GetOne(bson.ObjectIdHex(id))
return &api2go.Response{Res: res}, err
}
// Create a new Comment.
// Possible status codes are:
// - 201 Created: Resource was created and needs to be returned
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Resource created with a client generated ID, and no fields were modified by
// the server
func (c CommentResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
comment, ok := obj.(models.Comment)
if !ok {
return &api2go.Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
id, _ := c.CommentStorage.Insert(comment)
comment.ID = id
return &api2go.Response{Res: comment, Code: http.StatusCreated}, nil
}
// Delete a Comment.
// Possible status codes are:
// - 200 OK: Deletion was a success, returns meta information, currently not implemented! Do not use this
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Deletion was successful, return nothing
func (c CommentResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {
err := c.CommentStorage.Delete(bson.ObjectIdHex(id))
return &api2go.Response{Code: http.StatusOK}, err
}
// Update a Comment.
// Possible status codes are:
// - 200 OK: Update successful, however some field(s) were changed, returns updates source
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Update was successful, no fields were changed by the server, return nothing
func (c CommentResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
comment, ok := obj.(models.Comment)
if !ok {
return &api2go.Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
err := c.CommentStorage.Update(comment)
return &api2go.Response{Res: comment, Code: http.StatusNoContent}, err
}
|
// Package globals provides global variables.
package globals
import "errors"
// CalledInShell is true when mycomarkup is invoked as a program.
var CalledInShell bool
// TODO: get rid of these three ⤵. It requires quite an amount of work.︎
// HyphaExists holds function that checks if the hypha is present. By default, it is set to a function that is always true.
var HyphaExists func(string) bool
// HyphaAccess holds function that accesses a hypha by its name. By default, it is set to a function that always returns an error.
var HyphaAccess func(string) (rawText, binaryHtml string, err error)
// HyphaIterate is a function that iterates all hypha names existing. By default, it is set to a function that does nothing.
var HyphaIterate func(func(string))
func init() {
HyphaExists = func(_ string) bool {
return true
}
HyphaAccess = func(_ string) (string, string, error) {
return "", "", errors.New("globals.HyphaAccess not set")
}
HyphaIterate = func(_ func(string)) {}
}
|
package game_map
import (
"fmt"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/faiface/pixel/text"
"github.com/steelx/go-rpg-cgm/combat"
"github.com/steelx/go-rpg-cgm/gui"
"math"
"reflect"
)
var rounds = []*ArenaRound{
{Name: "Round 1", Locked: false, Enemies: []combat.ActorDef{
combat.GoblinDef,
}},
{Name: "Round 2", Locked: true, Enemies: []combat.ActorDef{
combat.GoblinDef,
combat.GoblinDef,
}},
{Name: "Round 3", Locked: true, Enemies: []combat.ActorDef{
combat.GoblinDef,
combat.GoblinDef,
combat.GoblinDef,
}},
{Name: "Round 4", Locked: true, Enemies: []combat.ActorDef{
combat.OgreDef,
combat.OgreDef,
}},
{Name: "Round 5", Locked: true, Enemies: []combat.ActorDef{
combat.DragonDef,
}},
}
type ArenaRound struct {
Name string
Locked bool
Enemies []combat.ActorDef
}
type ArenaState struct {
prevState gui.StackInterface
Stack *gui.StateStack
World *combat.WorldExtended
Layout gui.Layout
Panels []gui.Panel
Selection *gui.SelectionMenu
Rounds []*ArenaRound
}
func ArenaStateCreate(stack *gui.StateStack, prevState gui.StackInterface) gui.StackInterface {
layout := gui.LayoutCreate(0, 0, stack.Win)
layout.Contract("screen", 120, 40)
layout.SplitHorz("screen", "top", "bottom", 0.15, 0)
layout.SplitVert("bottom", "", "bottom", 0.75, 0)
layout.SplitVert("bottom", "bottom", "", 0.5, 0)
layout.Contract("bottom", -20, 40)
layout.SplitHorz("bottom", "header", "bottom", 0.18, 2)
gWorld := reflect.ValueOf(stack.Globals["world"]).Interface().(*combat.WorldExtended)
s := &ArenaState{
prevState: prevState,
Stack: stack,
World: gWorld,
Layout: layout,
Rounds: rounds,
}
s.Panels = []gui.Panel{
layout.CreatePanel("top"),
layout.CreatePanel("bottom"),
layout.CreatePanel("header"),
}
roundsSelectionMenu := gui.SelectionMenuCreate(25, 25, 70,
s.Rounds,
false,
pixel.V(0, 0),
s.OnRoundSelected,
s.RenderRoundItem,
)
txtSize := 100.0
xPos := -roundsSelectionMenu.GetWidth() / 2
xPos += roundsSelectionMenu.CursorWidth / 2
xPos -= txtSize / 2
roundsSelectionMenu.SetPosition(xPos, 18)
s.Selection = &roundsSelectionMenu
return s
}
//renderer pixel.Target, x, y float64, item ArenaRound
func (s *ArenaState) RenderRoundItem(a ...interface{}) {
renderer := reflect.ValueOf(a[0]).Interface().(pixel.Target)
x := reflect.ValueOf(a[1]).Interface().(float64)
y := reflect.ValueOf(a[2]).Interface().(float64)
round := reflect.ValueOf(a[3]).Interface().(*ArenaRound)
lockLabel := "Open"
if round.Locked {
lockLabel = "Locked"
}
label := fmt.Sprintf("%s: %s", round.Name, lockLabel)
textBase := text.New(pixel.V(x, y), gui.BasicAtlas12)
fmt.Fprintf(textBase, label)
textBase.Draw(renderer, pixel.IM)
}
func (s *ArenaState) OnRoundSelected(index int, itemI interface{}) {
item := reflect.ValueOf(itemI).Interface().(*ArenaRound)
if item.Locked {
return
}
enemyDefs := []combat.ActorDef{combat.GoblinDef}
if len(item.Enemies) > 0 {
enemyDefs = item.Enemies
}
var enemyList []*combat.Actor
for k, v := range enemyDefs {
enemy_ := combat.ActorCreate(v, fmt.Sprintf("%v", k))
enemyList = append(enemyList, &enemy_)
}
combatDef := CombatDef{
Background: "../resources/arena_background.png",
Actors: Actors{
Party: s.World.Party.ToArray(),
Enemies: enemyList,
},
CanFlee: false,
OnWin: func() {
s.WinRound(index, item)
},
OnDie: func() {
s.LoseRound(index, item)
},
}
state := CombatStateCreate(s.Stack, s.Stack.Win, combatDef)
s.Stack.Push(state)
}
func (s *ArenaState) Enter() {
}
func (s *ArenaState) Exit() {
}
func (s *ArenaState) HandleInput(win *pixelgl.Window) {
if win.JustPressed(pixelgl.KeyEscape) {
s.Stack.Pop() //remove self
s.Stack.Push(s.prevState)
return
}
s.Selection.HandleInput(win)
}
func (s *ArenaState) Update(dt float64) bool {
return false
}
func (s *ArenaState) Render(renderer *pixelgl.Window) {
//for _, v := range s.Panels {
// v.Draw(renderer)
//}
titleX := s.Layout.MidX("top")
titleY := s.Layout.MidY("top")
pos := pixel.V(titleX, titleY)
textBase := text.New(pos, gui.BasicAtlasAscii)
titleTxt := "Welcome to the Arena"
pos = pixel.V(titleX-textBase.BoundsOf(titleTxt).W()/2, titleY)
textBase = text.New(pos, gui.BasicAtlasAscii)
fmt.Fprintf(textBase, titleTxt)
textBase.Draw(renderer, pixel.IM.Scaled(pos, 2))
headerX := s.Layout.MidX("header")
headerY := s.Layout.MidY("header")
pos = pixel.V(headerX, headerY)
textBase = text.New(pos, gui.BasicAtlasAscii)
fmt.Fprintf(textBase, "Choose Round")
textBase.Draw(renderer, pixel.IM)
s.Selection.Render(renderer)
//camera
camera := pixel.IM.Scaled(pixel.ZV, 1.0).Moved(renderer.Bounds().Center().Sub(pixel.ZV))
renderer.SetMatrix(camera)
}
func (s *ArenaState) WinRound(index int, round *ArenaRound) {
//Check for win - is is last round
if index == len(s.Rounds)-1 {
s.Stack.Pop()
state := ArenaCompleteStateCreate(s.Stack, s.prevState)
s.Stack.Push(state)
return
}
//Move the cursor to the next round if there is one
s.Selection.MoveDown()
//Unlock the newly selected round
nextRoundI := s.Selection.SelectedItem()
nextRound := reflect.ValueOf(nextRoundI).Interface().(*ArenaRound)
nextRound.Locked = false
}
func (s *ArenaState) LoseRound(index int, round *ArenaRound) {
party := s.World.Party.Members
for _, v := range party {
hpNow := v.Stats.Get("HpNow")
hpNow = math.Max(hpNow, 1)
v.Stats.Set("HpNow", hpNow)
}
}
|
package server
import (
"api/entities"
"api/utils"
"database/sql"
"encoding/json"
routing "github.com/qiangxue/fasthttp-routing"
"github.com/valyala/fasthttp"
)
// RegistrationHandler ...
func (s *Server) RegistrationHandler() routing.Handler {
return func(c *routing.Context) error {
var user entities.User
json.Unmarshal(c.Request.Body(), &user)
token, err := s.User().Create(&user)
if err != nil {
return utils.Respond(c, 400, map[string]interface{}{
"error": err.Error(),
})
}
cookie := fasthttp.Cookie{}
cookie.SetKey("token")
cookie.SetValue(token)
cookie.SetHTTPOnly(true)
cookie.SetPath("/")
c.Response.Header.SetCookie(&cookie)
return utils.Respond(c, 200, map[string]interface{}{
"token": token,
"username": user.Username,
"id": user.ID,
})
}
}
// LoginHandler ...
func (s *Server) LoginHandler() routing.Handler {
type request struct {
Email string `json:"email"`
Password string `json:"password"`
}
return func(c *routing.Context) error {
var data request
json.Unmarshal(c.Request.Body(), &data)
user, err := s.User().Repo().FindByEmail(data.Email)
if err != nil {
if err == sql.ErrNoRows {
return utils.Respond(c, 400, map[string]interface{}{
"error": "No user with such email: " + data.Email,
})
}
return utils.Respond(c, 400, map[string]interface{}{
"error": err.Error(),
})
}
if !s.User().ComparePasswords(user, data.Password) {
return utils.Respond(c, 400, map[string]interface{}{
"error": "Wrong email or password",
})
}
token, err := s.User().GenerateToken(user)
if err != nil {
return utils.Respond(c, 400, map[string]interface{}{
"error": err.Error(),
})
}
cookie := fasthttp.Cookie{}
cookie.SetKey("token")
cookie.SetValue(token)
cookie.SetHTTPOnly(true)
cookie.SetPath("/")
c.Response.Header.SetCookie(&cookie)
return utils.Respond(c, 200, map[string]interface{}{
"token": token,
"username": user.Username,
"id": user.ID,
})
}
}
|
/*bcchain v2.0重大问题和修订方案1.1解决方案3 客户端测试正常数据*/
package main
const (
LINUX_C4 = "tcp://192.168.80.150:46658"
WINDOWS_C4 = "tcp://192.168.1.177:8080"
)
//func main() {
// a := make(chan bool)
// clientCreator := proxy.NewRemoteClientCreator(LINUX_C4, "socket", true)
//
// cli, err := clientCreator.NewABCIClient()
// if err != nil {
// fmt.Println("err", err.Error())
// }
// err = cli.OnStart()
// if err != nil {
// fmt.Println("serr", err.Error())
// }
// app := proxy.NewAppConnQuery(cli)
// //测试正常数据
// var reqQuery types.RequestQuery
// reqQuery.Path = "/genesis/chainid"
// resp, err := app.QuerySync(reqQuery)
// if err != nil {
// fmt.Println("serr", err.Error())
// }
// fmt.Println(resp.Code)
// <-a
//}
|
package store
import "golang.org/x/oauth2"
type Endpoint struct {
AuthUrl string `json:"AuthUrl" envconfig:"AUTH_URL" required:"true"`
TokenUrl string `json:"TokenUrl" envconfig:"TOKEN_URL" required:"true"`
}
type LinkedCloud struct {
ID string `json:"ID"`
Name string `json:"Name" envconfig:"NAME" required:"true"`
ClientID string `json:"ClientId" envconfig:"CLIENT_ID" required:"true"`
ClientSecret string `json:"ClientSecret" envconfig:"CLIENT_SECRET" required:"true"`
Scopes []string `json:"Scopes" envconfig:"SCOPES" required:"true"`
Endpoint Endpoint `json:"Endpoint"`
Audience string `json:"Audience" envconfig:"AUDIENCE"`
}
func (l LinkedCloud) ToOAuth2Config() oauth2.Config {
return oauth2.Config{
ClientID: l.ClientID,
ClientSecret: l.ClientSecret,
Scopes: l.Scopes,
Endpoint: oauth2.Endpoint{
AuthURL: l.Endpoint.AuthUrl,
TokenURL: l.Endpoint.TokenUrl,
},
}
}
|
package cookie
import (
"encoding/base64"
"encoding/gob"
"encoding/json"
"net/http"
)
// Check if client has 'Do Not Track' enabled.
func HasDnt(r *http.Request) bool {
return r.Header.Get("Dnt") == "1"
}
// Check if user has opted out of having cookie set.
func UserHasOptOut(r *http.Request) (b bool) {
c := Init(r, "optout")
if !c.Exist() {
return
}
c.Scan(&b)
return
}
// Opt User Out
func UserOptOut(w http.ResponseWriter, r *http.Request) {
c := Init(r, "optout")
c.Value(true)
c.Expire().Year(1)
c.DontHonorDnt()
c.DontHonorUser()
c.Save(w)
}
// Check if user has notice enabled.
func HasNotice(r *http.Request) (b bool) {
c := Init(r, "nonotice")
if !c.Exist() {
b = !b
return
}
c.Scan(&b)
b = !b
return
}
// Disable Notice.
func DisableNotice(w http.ResponseWriter, r *http.Request) {
c := Init(r, "nonotice")
c.Value(true)
c.Expire().Year(1)
c.DontHonorDnt()
c.DontHonorUser()
c.Save(w)
}
// Shortcut to gob register.
func Register(value interface{}) {
gob.Register(value)
}
type encoded struct {
Data []byte `json:"d"`
}
func encode(b []byte) string {
j, _ := json.Marshal(encoded{b})
return base64.URLEncoding.EncodeToString(j)
}
func decode(s string) ([]byte, error) {
b, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return nil, err
}
e := encoded{}
err = json.Unmarshal(b, &e)
if err != nil {
return nil, err
}
return e.Data, nil
}
|
package models
import "github.com/jinzhu/gorm"
type Goods struct {
gorm.Model
Title string
Summary string
Cover string
Content string
GoodsTypeId uint
Sort uint
Price string
IsRecommend uint8
}
|
package main
import (
"github.com/guoyk93/deployer/pkg/cmd"
"github.com/guoyk93/deployer/pkg/tempfile"
"log"
)
func runBuildStage(opts Options) (err error) {
log.Println("------------------------ 开始构建 ------------------------")
defer log.Println("------------------------ 结束构建 ------------------------")
// write temp file
var buildfile string
if buildfile, err = tempfile.WriteFile(opts.ScriptBuild, "deployer-build", ".sh", true); err != nil {
return
}
log.Printf("生成构建文件: %s", buildfile)
// execute the script
if err = cmd.Run(buildfile); err != nil {
return
}
return
}
|
package main
import (
"bufio"
"encoding/csv"
"fmt"
"github.com/weyllor/stocklab/stockdb"
"log"
"os"
_ "time"
)
func updateDb() {
err := stockdb.UpdateStockDb()
if err != nil {
log.Fatal(err)
}
}
func main() {
fmt.Printf("Stock Lab.\n")
updateDb()
//testReadLastLines()
//testCsvReadLastLines()
//testWriteFile()
}
func testWriteFile() {
file, err := os.OpenFile("./test.txt", os.O_APPEND|os.O_CREATE, os.ModeAppend)
if err != nil {
log.Fatal(err)
}
file.WriteString("hello\n")
file.Close()
}
func testReadLastLines() {
file, _ := os.Open("./data/000001.sz.csv")
defer file.Close()
file.Seek(-520, os.SEEK_END)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
func testCsvReadLastLines() {
file, _ := os.Open("./data/000001.sz.csv")
defer file.Close()
file.Seek(-512, os.SEEK_END)
var curOffset int64
curOffset, _ = file.Seek(0, os.SEEK_CUR)
fmt.Println("cur offset: ", curOffset)
reader := bufio.NewReader(file)
line, _, _ := reader.ReadLine()
fmt.Println("line:", line)
curOffset, _ = file.Seek(0, os.SEEK_CUR)
fmt.Println("cur offset: ", curOffset)
csvreader := csv.NewReader(reader)
var eof error
var row []string
eof = nil
for eof == nil {
row, eof = csvreader.Read()
fmt.Println(row)
//fmt.Println(eof)
}
curOffset, _ = file.Seek(0, os.SEEK_CUR)
fmt.Println("cur offset: ", curOffset)
}
|
package leetcode
type UnionFindSet struct {
fathers []int
}
func MakeUnionFindSet(n int) *UnionFindSet {
s := &UnionFindSet{fathers: make([]int, n)}
for i := 0; i < n; i++ {
s.fathers[i] = -1
}
return s
}
func (s *UnionFindSet) SetFather(x int) {
s.fathers[x] = x
}
func (s *UnionFindSet) Find(x int) int {
if s.fathers[x] != x {
s.fathers[x] = s.Find(s.fathers[x])
}
return s.fathers[x]
}
func (s *UnionFindSet) Union(x, y int) {
x = s.Find(x)
y = s.Find(y)
if x != y {
s.fathers[y] = x
}
}
func (s *UnionFindSet) Judge(x, y int) bool {
x = s.Find(x)
y = s.Find(y)
return x == y
}
func (s *UnionFindSet) UnionCount() int {
cnt := 0
for i := 0; i < len(s.fathers); i++ {
if s.fathers[i] == i {
cnt++
}
}
return cnt
}
func (s *UnionFindSet) UnionSet() [][]int {
m := make(map[int][]int)
for i := 0; i < len(s.fathers); i++ {
f := s.Find(i)
m[f] = append(m[f], i)
}
sets := make([][]int, 0, len(m))
for _, v := range m {
sets = append(sets, v)
}
return sets
}
func numIslands(grid [][]byte) int {
n := len(grid)
if n <= 0 {
return 0
}
m := len(grid[0])
s := MakeUnionFindSet(n * m)
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if grid[i][j] == '1' {
s.SetFather(i*m + j)
}
}
}
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if grid[i][j] == '1' {
if i-1 >= 0 {
if grid[i-1][j] == '1' {
x := (i-1)*m + j
y := i*m + j
s.Union(x, y)
}
}
if i+1 < n {
if grid[i+1][j] == '1' {
x := (i+1)*m + j
y := i*m + j
s.Union(x, y)
}
}
if j-1 >= 0 {
if grid[i][j-1] == '1' {
x := i*m + (j - 1)
y := i*m + j
s.Union(x, y)
}
}
if j+1 < m {
if grid[i][j+1] == '1' {
x := i*m + (j + 1)
y := i*m + j
s.Union(x, y)
}
}
}
}
}
return s.UnionCount()
}
|
package main
import (
"fmt"
"os"
"path/filepath"
"io/ioutil"
"log"
"os/exec"
)
func main() {
log.Println("Server Started...")
for ; ; {
dicision := false
files, err := ioutil.ReadDir("/mypath")
if err != nil {
log.Println(err)
}
fmt.Println(files)
for _, value := range files {
path := filepath.Join("/mypath", value.Name())
fileInfo, err := os.Stat(path)
if err != nil {
log.Fatalln(err)
}
if fileInfo.IsDir() {
outPath := filepath.Join(path, "manifests", "output")
_, err := os.Stat(outPath)
if err == nil {
cmd := exec.Command("kubectl", "apply", "-R", "-f", outPath)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
dicision = true
if err = cmd.Run(); err != nil {
dicision = false
fmt.Println(err)
log.Println(err)
}
break
}
}
}
if dicision {
break
}
}
for ; ; {
fmt.Println("")
}
}
|
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
var evens []int = []int{0, 2, 4, 6, 8}
func main() {
truncatablePrimes := []int{}
for i := 11; len(truncatablePrimes) < 12; i += 2 {
if !containsProblematicNumbers(i) {
fmt.Println(i)
if isTruncatablePrime(i) {
truncatablePrimes = append(truncatablePrimes, i)
}
}
}
fmt.Println("Answer", sum(truncatablePrimes))
}
func sum(primes []int) int {
total := 0
for _, num := range primes {
total += num
}
return total
}
func isLeftTruncatable(n int) (bool, int) {
var digits int
for ; n > 0; n /= 10 {
digits++
if !isPrime(n) {
return false, digits
}
}
return true, digits
}
func isRightTruncatable(n int, digits int) bool {
for ; n > 0; n, digits = n%int(math.Pow10(digits)), digits-1 {
if !isPrime(n) {
return false
}
}
return true
}
func containsProblematicNumbers(n int) bool {
s := strconv.Itoa(n)
for _, even := range evens {
if strings.Contains(s, strconv.Itoa(even)) {
return true
}
}
if strings.Contains(s[1:len(s)-1], "5") {
return true
}
if s[:1] == "1" || s[len(s)-2:] == "1" {
return true
}
return false
}
func isTruncatablePrime(n int) bool {
if isPrime(n) {
left, digits := isLeftTruncatable(n)
return left && isRightTruncatable(n, digits)
}
return false
}
func isPrime(n int) bool {
if n < 2 {
return false
}
for i := 2; i < n/2+1; i++ {
if n%i == 0 {
return false
}
}
return true
}
|
package main
import (
"fmt"
"github.com/rucuriousyet/divio"
)
func main() {
mux, _ := divio.NewMux("app", "", "")
mux.AddRoute("apples/greenfroot", func(c *divio.Context) {
flags, err := divio.ExpectFlags(divio.FlagGroup{
"f": &divio.Pair{"oranges", "sets the fruittype"},
"d": &divio.Pair{"poodle", "sets the dog type"},
}, c)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("Command ran!", flags)
})
mux.AddRoute("save", func(c *divio.Context) {
flags, err := c.ExpectFlag(divio.FlagGroup{
"f": &divio.Pair{true, "sets the file path"},
"d": &divio.Pair{"poodle", "sets the dog type"},
})
if err != nil {
fmt.Println(err.Error())
}
fmt.Println("Command ran!", flags)
})
mux.Listen()
}
|
package main
import (
"fmt"
"sort"
)
// https://leetcode-cn.com/problems/maximum-gap/
// 164. 最大间距 | Maximum Gap
//------------------------------------------------------------------------------
func maximumGap(nums []int) int {
return maximumGap0(nums)
}
//------------------------------------------------------------------------------
// Solution 2
//
// 基数排序: 最好选择 2的次幂做基数, 可以利用位运算来取模. 另外基数数组最好缓存住, 否则每次都申请
// 新的空间, 既耗时又耗空间.
//
// 复杂度分析:
// * 时间: O(N). 准确的是 O(N+2*logB(max)*N+N): 包括求最大值, 分桶, 拷贝, 求解.
// 所以最终复杂度跟 S0 先排序差不多, 相当于 S0 选的基数是 2. 如果 max 远大于 N,
// 不如直接排序.
// * 令 B = 2^x, 令循环次数 c = 2*logB(max) = logB(max^2) -> (2^x)^c = max^2
// 即: max = 2^(x*c/2) = (2^c)^(x/2), 而快排的循环次数: c1 = lgN -> N = 2^c1.
// 所以若 c > c1 可以选择快排, 即: max = (2^c)^(x/2) > (2^c1)^x/2 = N^(x/2).
// * 所以只有当 x > 2, 即基数 B > 4 的时候, 基数排序才会加速, 否则不如直接快排.
// * 若 max > N^(x/2) 时, 快排依然优于基数排序.
// * 若基数为 10, 则 x = lg10 = 2.3, 即 max > N^1.15 时, 可以用快排.
// * 空间: O(N). 最大可能 O(B*N)
func maximumGap2(nums []int) int {
N := len(nums)
if N < 2 {
return 0
}
max := nums[0]
for i := 1; i < N; i++ {
if max < nums[i] {
max = nums[i]
}
}
const B, lg = 32, 5
base := [B][]int{}
if max/N > B {
sort.Ints(nums)
goto SOLVE
}
for exp, l := 1, uint(0); exp <= max; exp, l = exp<<lg, l+lg {
for i := 0; i < N; i++ {
id := nums[i] >> l & (B - 1)
base[id] = append(base[id], nums[i])
}
for i, start := 0, 0; i < B; i++ {
if len(base[i]) != 0 {
copy(nums[start:], base[i])
start += len(base[i])
base[i] = base[i][:0]
}
}
}
SOLVE:
res := 0
for i := 1; i < N; i++ {
if nums[i]-nums[i-1] > res {
res = nums[i] - nums[i-1]
}
}
return res
}
//------------------------------------------------------------------------------
// Solution 1
//
// 桶排序, 桶数为数组长度 N, 桶大小为 MAX(A)/N+1, 这样可以保证有空桶, 那么必然存在两个非空的
// 相邻桶, 他们的间距大于一个桶的大小; 因此就不用再对桶内元素排序, 只用计算后一个桶的最小值与前一个
// 桶的最大值差值即可.
//
// 复杂度分析:
// * 时间: O(n)
// * 空间: O(n)
func maximumGap1(nums []int) int {
N := len(nums)
if N < 2 {
return 0
}
max, min := nums[0], nums[0]
for i := 1; i < N; i++ {
if max < nums[i] {
max = nums[i]
} else if min > nums[i] {
min = nums[i]
}
}
// max,min in bucket
bkt := make([][]int, N)
size := (max-min)/N + 1
for _, v := range nums {
id := (v - min) / size
if bkt[id] == nil {
bkt[id] = []int{v, v}
} else {
if v < bkt[id][1] {
bkt[id][1] = v
} else if v > bkt[id][0] {
bkt[id][0] = v
}
}
}
res := 0
max = min
for i := 0; i < N; i++ {
if bkt[i] != nil {
if bkt[i][1]-max > res {
res = bkt[i][1] - max
}
max = bkt[i][0]
}
}
return res
}
//------------------------------------------------------------------------------
// Solution 0
//
// 排序后计算相邻元素差值
//
// 复杂度分析:
// * 时间: O(n*lgn)
// * 空间: O(1)
func maximumGap0(nums []int) int {
if len(nums) < 2 {
return 0
}
sort.Ints(nums)
res := 0
for i, v := range nums[1:] {
if diff := v - nums[i]; diff > res {
res = diff
}
}
return res
}
//------------------------------------------------------------------------------
// main
func main() {
cases := [][]int{
{3, 6, 9, 1},
{3, 6, 9, 4, 7},
{11, 10, 12},
{10, 10, 11, 12},
}
realCase := cases[0:]
for i, c := range realCase {
fmt.Println("## case", i)
// solve
fmt.Println(maximumGap0(c))
fmt.Println(maximumGap1(c))
fmt.Println(maximumGap2(c))
}
}
|
package main
import (
"os"
"fmt"
"log"
"time"
"bytes"
"strconv"
"net/http"
"io/ioutil"
"encoding/json"
"github.com/gorilla/mux"
);
var NODE_ID int;
func __nodePrint(msg string) {
fmt.Printf("Node %d: %s\n", NODE_ID, msg)
}
func handleRequests(PORT int) {
fmt.Printf("listening for requests on port %d ...\n", PORT);
myRouter := mux.NewRouter().StrictSlash(true);
myRouter.HandleFunc("/api/ping", ping).Methods("POST");
myRouter.HandleFunc("/api/pong", pong).Methods("POST");
log.Fatal ( http.ListenAndServe( fmt.Sprintf(":%d", PORT), myRouter) );
}
type PiPoMessage struct {
Msg string `json:"msg"`
Counter int `json:"counter"`
}
func PipoParseBody( writer http.ResponseWriter, request *http.Request ) PiPoMessage {
var ppm PiPoMessage
b, err := ioutil.ReadAll(request.Body)
defer request.Body.Close()
if err != nil {
http.Error(writer, err.Error(), 500)
}
err = json.Unmarshal(b, &ppm)
if err != nil {
http.Error(writer, err.Error(), 500)
}
return ppm
}
func ping ( writer http.ResponseWriter, request *http.Request ) {
ppm := PipoParseBody(writer, request)
if ppm.Counter < 0 {
__nodePrint("done!")
return
}
__nodePrint(ppm.Msg)
time.Sleep(500 * time.Millisecond)
var pingMsg PiPoMessage;
pingMsg.Msg = "ping"
pingMsg.Counter = ppm.Counter-1;
json_data, err := json.Marshal(pingMsg)
if err != nil { log.Fatal(err) }
_, err2 := http.Post("http://localhost:8081/api/pong", "application/json", bytes.NewBuffer(json_data))
if err2 != nil { log.Fatal(err2) }
}
func pong ( writer http.ResponseWriter, request *http.Request ) {
ppm := PipoParseBody(writer, request)
if ppm.Counter < 0 {
__nodePrint("done!")
return
}
__nodePrint(ppm.Msg)
time.Sleep(500 * time.Millisecond)
var pongMsg PiPoMessage;
pongMsg.Msg = "pong"
pongMsg.Counter = ppm.Counter-1;
json_data, err := json.Marshal(pongMsg)
if err != nil { log.Fatal(err) }
_, err2 := http.Post("http://localhost:8080/api/ping", "application/json", bytes.NewBuffer(json_data))
if err2 != nil { log.Fatal(err2) }
}
func main() {
var PORT int;
if len(os.Args) > 1 {
p, err := strconv.Atoi(os.Args[1]);
if err != nil {
log.New(os.Stderr, "", 0).Printf("invalid port number: %s\n", os.Args[1]);
os.Exit(1);
}
PORT = p;
} else {
PORT = 8080;
fmt.Printf("no port number provided by command line, will use default %d\n", PORT);
}
NODE_ID = PORT;
handleRequests(PORT);
}
|
package server
import (
"fmt"
"io"
"net/http"
"wsr-reader/wsr"
)
func Run(addr string) error {
http.HandleFunc("/", defaultPage)
http.HandleFunc("/readCard", readCard)
http.HandleFunc("/writeCard", writeCard)
if err := http.ListenAndServe(addr, nil); err != nil {
return err
}
return nil
}
func defaultPage(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, newReplyFailWithString("wrong page").toJsonString())
}
//读取卡号和uuid
func readCard(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Println("\r\n收到读卡请求")
wsr, err := wsr.NewWsr()
if err != nil {
fmt.Println("init failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
defer func() {
fmt.Println("destroying WSR")
wsr.Destroy()
}()
if err := wsr.OpenPort(); err != nil {
fmt.Println("open port failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
defer func() {
err := wsr.ClosePort()
fmt.Println("close port, error:", err)
}()
if err := wsr.Beep(); err != nil {
fmt.Println("beep failed, error:", err)
}
//load password
if err := wsr.LoadPsw("\xFF\xFF\xFF\xFF\xFF\xFF", 0); err != nil {
fmt.Println("load passwd failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
fmt.Println("load passwd succ")
//read card no
cardNo, err := wsr.GetCardNo()
if err != nil {
fmt.Println("getCardNo failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
//read uuid
uuid, err := wsr.ReadUuid()
if err != nil {
fmt.Println("readUuid failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
succReply := newReplySucc()
succReply.addData("cardId", cardNo)
succReply.addData("cardUuid", uuid)
io.WriteString(w, succReply.toJsonString())
}
func writeCard(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Println("\r\n收到写卡请求")
req.ParseForm()
if req.Method != "POST" {
io.WriteString(w, newReplyFailWithString("请求方法错误").toJsonString())
return
}
uuidList := req.PostForm["cardUuid"]
if len(uuidList) != 1 || len(uuidList[0]) == 0 {
io.WriteString(w, newReplyFailWithString("请求参数错误").toJsonString())
return
}
wsr, err := wsr.NewWsr()
if err != nil {
fmt.Println("init failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
defer func() {
fmt.Println("destroying WSR")
wsr.Destroy()
}()
if err := wsr.OpenPort(); err != nil {
fmt.Println("open port failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
defer func() {
err := wsr.ClosePort()
fmt.Println("close port, error:", err)
}()
if err := wsr.Beep(); err != nil {
fmt.Println("beep failed, error:", err)
}
//load password
if err := wsr.LoadPsw("\xFF\xFF\xFF\xFF\xFF\xFF", 0); err != nil {
fmt.Println("load passwd failed, error:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
fmt.Println("load passwd succ")
if err := wsr.WriteUuid(uuidList[0]); err != nil {
fmt.Println("write uuid failed, err:", err)
io.WriteString(w, newReplyFail(err).toJsonString())
return
}
io.WriteString(w, newReplySucc().toJsonString())
}
|
package authproxy
import (
"context"
"net/http"
"strings"
"github.com/janivihervas/authproxy/jwt"
"golang.org/x/oauth2"
"github.com/pkg/errors"
)
const (
accessTokenCookieName = "access_token"
authHeaderName = "Authorization"
authHeaderPrefix = "Bearer"
)
func (m *Middleware) getAccessTokenFromCookie(r *http.Request) (string, error) {
cookie, err := r.Cookie(accessTokenCookieName)
if err != nil {
return "", errors.Wrapf(err, "couldn't get cookie %s", accessTokenCookieName)
}
if cookie.Value == "" {
return "", errors.Errorf("cookie %s is empty", accessTokenCookieName)
}
return cookie.Value, nil
}
func (m *Middleware) getAccessTokenFromHeader(r *http.Request) (string, error) {
header := r.Header.Get(authHeaderName)
if header == "" {
return "", errors.Errorf("header %s is empty", authHeaderName)
}
parts := strings.Split(header, " ")
if len(parts) != 2 || parts[0] != authHeaderPrefix || parts[1] == "" {
return "", errors.Errorf("header %s is malformed: %s", authHeaderName, header)
}
return parts[1], nil
}
func (m *Middleware) getAccessTokenFromSession(ctx context.Context) (string, error) {
state, err := getStateFromContext(ctx)
if err != nil {
return "", errors.Wrap(err, "couldn't get session from context")
}
if state.AccessToken == "" {
return "", errors.New("access token in session is empty")
}
return state.AccessToken, nil
}
func (m *Middleware) setupAccessToken(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var (
cookieSet bool
headerSet bool
sessionSet bool
accessToken string
)
if s, err := m.getAccessTokenFromCookie(r); err == nil {
accessToken = s
cookieSet = true
}
if s, err := m.getAccessTokenFromHeader(r); err == nil {
accessToken = s
headerSet = true
}
if s, err := m.getAccessTokenFromSession(ctx); err == nil {
accessToken = s
sessionSet = true
}
if accessToken == "" {
return errors.New("access token is not set")
}
if !cookieSet {
accessTokenCookie := createAccessTokenCookie(accessToken)
http.SetCookie(w, accessTokenCookie)
r.AddCookie(accessTokenCookie)
}
if !headerSet {
r.Header.Set(authHeaderName, authHeaderPrefix+" "+accessToken)
}
if !sessionSet {
state, err := getStateFromContext(ctx)
if err != nil {
return err
}
state.AccessToken = accessToken
}
return nil
}
func (m *Middleware) getAccessToken(ctx context.Context, r *http.Request) (string, error) {
if s, err := m.getAccessTokenFromCookie(r); err == nil {
return s, nil
}
if s, err := m.getAccessTokenFromHeader(r); err == nil {
return s, nil
}
if s, err := m.getAccessTokenFromSession(ctx); err == nil {
return s, nil
}
return "", errors.New("no access token in cookie, header or session")
}
func (m *Middleware) refreshAccessToken(ctx context.Context, w http.ResponseWriter) (string, error) {
state, err := getStateFromContext(ctx)
if err != nil {
return "", errors.Wrap(err, "couldn't get session from context")
}
if state.RefreshToken == "" {
return "", errors.New("no refresh token in session")
}
tokens, err := m.AuthClient.TokenSource(ctx, &oauth2.Token{
AccessToken: state.AccessToken,
RefreshToken: state.RefreshToken,
}).Token()
if err != nil {
return "", errors.Wrap(err, "couldn't refresh tokens")
}
_, err = jwt.ParseAccessToken(ctx, tokens.AccessToken)
if err != nil {
return "", errors.Wrap(err, "couldn't refresh tokens, returned access token was invalid")
}
state.AccessToken = tokens.AccessToken
http.SetCookie(w, createAccessTokenCookie(state.AccessToken))
if tokens.RefreshToken != "" {
state.RefreshToken = tokens.RefreshToken
}
return state.AccessToken, nil
}
|
package main
import "fmt"
// 123 -> [(1 * 1) + (2 * 2) + (3 * 3)] + [(1*1*1) +(2*2*2) + (3*3*3)]
func Nums(number int, numsChannel chan int) {
for number != 0 {
d := number % 10
numsChannel <- d
number /= 10
}
close(numsChannel)
}
func calcSquares(number int, sqrChannel chan int) {
summ := 0
nChan := make(chan int)
go Nums(number, nChan)
for d := range nChan {
summ += d * d
}
sqrChannel <- summ
}
func calcCubes(number int, cubChannel chan int) {
summ := 0
nChan := make(chan int)
go Nums(number, nChan)
for d := range nChan {
summ += d * d * d
}
cubChannel <- summ
}
func main() {
number := 100505812
sqrChannel := make(chan int)
cubChannel := make(chan int)
go calcSquares(number, sqrChannel) //[(1 * 1) + (2 * 2) + (3 * 3)]
go calcCubes(number, cubChannel) //[(1*1*1) +(2*2*2) + (3*3*3)]
square, cube := <-sqrChannel, <-cubChannel
fmt.Println("Result is:", square+cube)
}
|
// Implementação do comando echo. Versão 2.
// arataca89@gmail.com
// 20210412
package main
import (
"fmt"
"os"
)
func main() {
linha, espaco := "", ""
for _, token := range os.Args[1:] {
linha += espaco + token
espaco = " "
}
fmt.Println(linha)
}
/////////////////////////////////////////////////////////////////////
// _, token := range os.Args[1:]
//
// "range" no comando acima retorna dois valores: o índice e o valor
// de os.Args
//
// _ (underline ou underscore, sublinhado) é chamado
// "identificador vazio" e deve ser usado sempre que uma variável
// for exigida na sintaxe da linguagem Go mas o programador não
// quiser declarar uma variável só para essa finalidade.
//
// := (dois pontos seguido de igualdade) define a forma curta de
// declaração de variáveis. Ela declara e inicializa a variável
// ao mesmo tempo. Só pode ser usada dentro de funções.
//
// (DONOVAN e KERNIGHAN, 2017)
|
package terraform
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/mattermost/mattermost-load-test/ltops"
"github.com/mattermost/mattermost-load-test/sshtools"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
func (c *Cluster) Deploy(options *ltops.DeployOptions) error {
if err := c.DeployMattermost(options.MattermostBinaryFile, options.LicenseFile); err != nil {
return err
}
return c.DeployLoadtests(options.LoadTestBinaryFile)
}
func (c *Cluster) DeployMattermost(mattermostDistLocation string, licenceFileLocation string) error {
appInstanceAddrs, err := c.GetAppInstancesAddrs()
if err != nil || len(appInstanceAddrs) <= 0 {
return errors.Wrap(err, "Unable to get app instance addresses")
}
proxyInstanceAddrs, err := c.GetProxyInstancesAddrs()
if err != nil || len(proxyInstanceAddrs) <= 0 {
return errors.Wrap(err, "Unable to get app instance addresses")
}
mattermostDist, err := ltops.GetFileOrURL(mattermostDistLocation)
if err != nil {
return err
}
licenseFile, err := ltops.GetFileOrURL(licenceFileLocation)
if err != nil {
return err
}
var wg sync.WaitGroup
wg.Add(len(appInstanceAddrs) + len(proxyInstanceAddrs))
failed := new(int32)
doDeploy(&wg, failed, appInstanceAddrs, "app", func(instanceNum int, addr string, logger logrus.FieldLogger) error {
return deployToAppInstance(bytes.NewReader(mattermostDist), bytes.NewReader(licenseFile), addr, c, logrus.WithField("instance", addr))
})
doDeploy(&wg, failed, proxyInstanceAddrs, "proxy", func(instanceNum int, addr string, logger logrus.FieldLogger) error {
return deployToProxyInstance(addr, c, logrus.WithField("instance", addr))
})
wg.Wait()
if *failed == 1 {
return fmt.Errorf("failed to deploy to 1 instance")
} else if *failed > 0 {
return fmt.Errorf("failed to deploy to %v instances", *failed)
} else {
// This is here because the commands above do not wait for the servers to come back up after they restart them.
//TODO: Actually wait for them instead of just sleeping
logrus.Info("Deploy successful. Restarting servers...")
time.Sleep(time.Second * 5)
logrus.Info("Done")
}
return nil
}
func (c *Cluster) DeployLoadtests(loadtestsDistLocation string) error {
loadtestInstanceAddrs, err := c.GetLoadtestInstancesAddrs()
if err != nil || len(loadtestInstanceAddrs) <= 0 {
return errors.Wrap(err, "Unable to get loadtest instance addresses")
}
loadtestsDist, err := ltops.GetFileOrURL(loadtestsDistLocation)
if err != nil {
return err
}
var wg sync.WaitGroup
wg.Add(len(loadtestInstanceAddrs))
failed := new(int32)
doDeploy(&wg, failed, loadtestInstanceAddrs, "loadtest", func(instanceNum int, addr string, logger logrus.FieldLogger) error {
return deployToLoadtestInstance(instanceNum, addr, bytes.NewReader(loadtestsDist), c, logrus.WithField("instance", addr))
})
wg.Wait()
if *failed == 1 {
return fmt.Errorf("failed to deploy to 1 instance")
} else if *failed > 0 {
return fmt.Errorf("failed to deploy to %v instances", *failed)
}
return nil
}
func doDeploy(wg *sync.WaitGroup, failed *int32, addresses []string, addressesName string, deployFunc func(instanceNum int, addr string, logger logrus.FieldLogger) error) error {
for instanceNum, instanceAddr := range addresses {
instanceAddr := instanceAddr
instanceNum := instanceNum
go func() {
logrus.Infof("deploying to %v%v : %v...", addressesName, instanceNum, instanceAddr)
if err := deployFunc(instanceNum, instanceAddr, logrus.WithField("instance", strconv.Itoa(instanceNum)+":"+instanceAddr)); err != nil {
wrapped := errors.Wrap(err, "unable to deploy to "+addressesName+strconv.Itoa(instanceNum)+" : "+instanceAddr)
logrus.Error(wrapped)
atomic.AddInt32(failed, 1)
} else {
logrus.Infof("successfully deployed to %v%v : %v...", addressesName, instanceNum, instanceAddr)
}
wg.Done()
}()
}
return nil
}
func deployToLoadtestInstance(instanceNum int, instanceAddr string, loadtestDistribution io.Reader, cluster ltops.Cluster, logger logrus.FieldLogger) error {
client, err := sshtools.SSHClient(cluster.SSHKey(), instanceAddr)
if err != nil {
return errors.Wrap(err, "unable to connect to server via ssh")
}
defer client.Close()
logger.Debug("uploading distribution...")
remoteDistributionPath := "/home/ubuntu/mattermost-load-test.tar.gz"
if err := sshtools.UploadReader(client, loadtestDistribution, remoteDistributionPath); err != nil {
return errors.Wrap(err, "unable to upload loadtest distribution.")
}
remoteSSHKeyPath := "/home/ubuntu/key.pem"
if err := sshtools.UploadBytes(client, cluster.SSHKey(), remoteSSHKeyPath); err != nil {
return errors.Wrap(err, "unable to upload ssh key")
}
for _, cmd := range []string{
"sudo apt-get update",
"sudo apt-get install -y jq",
"sudo rm -rf /home/ubuntu/mattermost-load-test",
"tar -xvzf /home/ubuntu/mattermost-load-test.tar.gz",
"sudo chmod 600 /home/ubuntu/key.pem",
} {
logger.Debug("+ " + cmd)
if err := sshtools.RemoteCommand(client, cmd); err != nil {
return errors.Wrap(err, "error running command: "+cmd)
}
}
logger.Debug("uploading limits config...")
if err := uploadLimitsConfig(client); err != nil {
return errors.Wrap(err, "Unable to upload limits config")
}
proxyURLs, err := cluster.GetProxyInstancesAddrs()
if err != nil || len(proxyURLs) < 1 {
return errors.Wrap(err, "Couldn't get app instance addresses.")
}
appURLs, err := cluster.GetAppInstancesAddrs()
if err != nil || len(appURLs) < 1 {
return errors.Wrap(err, "Couldn't get app instance addresses.")
}
appURL, err := url.Parse(appURLs[0])
if err != nil {
return errors.Wrap(err, "Couldn't parse app url.")
}
siteURL, err := url.Parse(proxyURLs[instanceNum])
if err != nil {
return errors.Wrap(err, "Can't parse site URL")
}
serverURL := *siteURL
serverURL.Scheme = "http"
websocketURL := *siteURL
websocketURL.Scheme = "ws"
pprofURL := *appURL
pprofURL.Host = pprofURL.Host + ":8067"
pprofURL.Path = "/debug/pprof"
for k, v := range map[string]interface{}{
".ConnectionConfiguration.ServerURL": serverURL.String(),
".ConnectionConfiguration.WebsocketURL": websocketURL.String(),
".ConnectionConfiguration.PProfURL": pprofURL.String(),
".ConnectionConfiguration.DataSource": cluster.DBConnectionString(),
".ConnectionConfiguration.LocalCommands": false,
".ConnectionConfiguration.SSHHostnamePort": appURL.String() + ":22",
".ConnectionConfiguration.SSHUsername": "ubuntu",
".ConnectionConfiguration.SSHKey": remoteSSHKeyPath,
".ConnectionConfiguration.MattermostInstallDir": "/opt/mattermost",
".ConnectionConfiguration.WaitForServerStart": false,
} {
logger.Debug("updating config: " + k)
jsonValue, err := json.Marshal(v)
if err != nil {
return errors.Wrap(err, "invalid config value for key: "+k)
}
if err := sshtools.RemoteCommand(client, fmt.Sprintf(`jq '%s = %s' /home/ubuntu/mattermost-load-test/loadtestconfig.json > /tmp/ltconfig.json && mv /tmp/ltconfig.json /home/ubuntu/mattermost-load-test/loadtestconfig.json`, k, string(jsonValue))); err != nil {
return errors.Wrap(err, "error updating config: "+k)
}
}
for _, cmd := range []string{
"sudo shutdown -r now &",
} {
logger.Debug("+ " + cmd)
if err := sshtools.RemoteCommand(client, cmd); err != nil {
return errors.Wrap(err, "error running command: "+cmd)
}
}
return nil
}
func deployToProxyInstance(instanceAddr string, clust ltops.Cluster, logger logrus.FieldLogger) error {
client, err := sshtools.SSHClient(clust.SSHKey(), instanceAddr)
if err != nil {
return errors.Wrap(err, "unable to connect to server via ssh")
}
defer client.Close()
appInstances, err := clust.GetAppInstancesAddrs()
if err != nil {
return errors.Wrap(err, "Unable to get app instance addresses.")
}
for _, cmd := range []string{
"sudo apt-get update",
"sudo apt-get install -y nginx",
} {
logger.Debug("+ " + cmd)
if err := sshtools.RemoteCommand(client, cmd); err != nil {
return errors.Wrap(err, "error running command: "+cmd)
}
}
if err := uploadNginxConfig(client, appInstances); err != nil {
return errors.Wrap(err, "Unable to upload nginx config")
}
if err := uploadLimitsConfig(client); err != nil {
return errors.Wrap(err, "Unable to upload limits config")
}
for _, cmd := range []string{
"sudo ln -fs /etc/nginx/sites-available/mattermost /etc/nginx/sites-enabled/mattermost",
"sudo rm -f /etc/nginx/sites-enabled/default",
"sudo grep -q -F 'worker_rlimit_nofile' /etc/nginx/nginx.conf || echo 'worker_rlimit_nofile 65536;' | sudo tee -a /etc/nginx/nginx.conf",
"sudo sed -i 's/worker_connections.*/worker_connections 200000;/g' /etc/nginx/nginx.conf",
"sudo systemctl daemon-reload",
"sudo systemctl restart nginx",
"sudo systemctl enable nginx",
"sudo shutdown -r now &",
} {
logger.Debug("+ " + cmd)
if err := sshtools.RemoteCommand(client, cmd); err != nil {
return errors.Wrap(err, "error running command: "+cmd)
}
}
return nil
}
func deployToAppInstance(mattermostDistribution, license io.Reader, instanceAddr string, clust *Cluster, logger logrus.FieldLogger) error {
client, err := sshtools.SSHClient(clust.SSHKey(), instanceAddr)
if err != nil {
return errors.Wrap(err, "unable to connect to server via ssh")
}
defer client.Close()
logger.Debug("uploading distribution...")
remoteDistributionPath := "/tmp/mattermost.tar.gz"
if err := sshtools.UploadReader(client, mattermostDistribution, remoteDistributionPath); err != nil {
return errors.Wrap(err, "unable to upload distribution.")
}
if err := uploadSystemdFile(client); err != nil {
return errors.Wrap(err, "unable to upload systemd file")
}
for _, cmd := range []string{
"sudo rm -rf mattermost /opt/mattermost",
"tar -xvzf /tmp/mattermost.tar.gz",
"sudo mv mattermost /opt",
"mkdir -p /opt/mattermost/data",
"sudo apt-get update",
"sudo apt-get install -y jq",
} {
logger.Debug("+ " + cmd)
if err := sshtools.RemoteCommand(client, cmd); err != nil {
return errors.Wrap(err, "error running command: "+cmd)
}
}
logger.Debug("uploading license file...")
remoteLicenseFilePath := "/opt/mattermost/config/mattermost.mattermost-license"
if err := sshtools.UploadReader(client, license, remoteLicenseFilePath); err != nil {
return errors.Wrap(err, "unable to upload license file")
}
logger.Debug("uploading limits config...")
if err := uploadLimitsConfig(client); err != nil {
return errors.Wrap(err, "Unable to upload limits config")
}
outputParams, err := clust.Env.getOuptutParams()
if err != nil {
return errors.Wrap(err, "Can't get output parameters")
}
s3AccessKeyId := outputParams.S3AccessKeyId.Value
s3AccessKeySecret := outputParams.S3AccessKeySecret.Value
s3Bucket := outputParams.S3bucket.Value
s3Region := outputParams.S3bucketRegion.Value
for k, v := range map[string]interface{}{
".ServiceSettings.ListenAddress": ":80",
".ServiceSettings.LicenseFileLocation": remoteLicenseFilePath,
".ServiceSettings.SiteURL": clust.SiteURL(),
".ServiceSettings.EnableAPIv3": true,
".SqlSettings.DriverName": "mysql",
".SqlSettings.DataSource": clust.DBConnectionString(),
".SqlSettings.DataSourceReplicas": clust.DBReaderConnectionStrings(),
".SqlSettings.MaxOpenConns": 3000,
".SqlSettings.MaxIdleConns": 200,
".ClusterSettings.Enable": true,
".ClusterSettings.ClusterName": "load-test",
".ClusterSettings.ReadOnlyConfig": false,
".MetricsSettings.Enable": true,
".MetricsSettings.BlockProfileRate": 1,
".FileSettings.DriverName": "amazons3",
".FileSettings.AmazonS3AccessKeyId": s3AccessKeyId,
".FileSettings.AmazonS3SecretAccessKey": s3AccessKeySecret,
".FileSettings.AmazonS3Bucket": s3Bucket,
".FileSettings.AmazonS3Region": s3Region,
".TeamSettings.MaxUsersPerTeam": 10000000,
".TeamSettings.EnableOpenServer": true,
".TeamSettings.MaxChannelsPerTeam": 10000000,
".ServiceSettings.EnableIncomingWehbooks": true,
".ServiceSettings.EnableOnlyAdminIntegrations": false,
} {
logger.Debug("updating config: " + k)
jsonValue, err := json.Marshal(v)
if err != nil {
return errors.Wrap(err, "invalid config value for key: "+k)
}
if err := sshtools.RemoteCommand(client, fmt.Sprintf(`jq '%s = %s' /opt/mattermost/config/config.json > /tmp/mmcfg.json && mv /tmp/mmcfg.json /opt/mattermost/config/config.json`, k, string(jsonValue))); err != nil {
return errors.Wrap(err, "error updating config: "+k)
}
}
for _, cmd := range []string{
"sudo setcap cap_net_bind_service=+ep /opt/mattermost/bin/platform",
"sudo systemctl daemon-reload",
"sudo systemctl restart mattermost.service",
"sudo systemctl enable mattermost.service",
"sudo shutdown -r now &",
} {
logger.Debug("+ " + cmd)
if err := sshtools.RemoteCommand(client, cmd); err != nil {
return errors.Wrap(err, "error running command: "+cmd)
}
}
return nil
}
func uploadSystemdFile(client *ssh.Client) error {
session, err := client.NewSession()
if err != nil {
return errors.Wrap(err, "unable to create ssh session")
}
defer session.Close()
service := `
[Unit]
Description=Mattermost
After=network.target
[Service]
Type=simple
ExecStart=/opt/mattermost/bin/platform
Restart=always
RestartSec=10
WorkingDirectory=/opt/mattermost
User=ubuntu
Group=ubuntu
LimitNOFILE=49152
[Install]
WantedBy=multi-user.target
`
session.Stdin = strings.NewReader(strings.TrimSpace(service))
if err := session.Run("cat | sudo tee /lib/systemd/system/mattermost.service"); err != nil {
return err
}
return nil
}
func uploadNginxConfig(client *ssh.Client, appInstanceAddrs []string) error {
session, err := client.NewSession()
if err != nil {
return errors.Wrap(err, "unable to create ssh session")
}
defer session.Close()
config := `
upstream backend {
%s
keepalive 32;
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mattermost_cache:10m max_size=3g inactive=120m use_temp_path=off;
server {
listen 80;
server_name _;
location ~ /api/v[0-9]+/(users/)?websocket$ {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
client_max_body_size 50M;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Frame-Options SAMEORIGIN;
proxy_buffers 256 16k;
proxy_buffer_size 16k;
client_body_timeout 60;
send_timeout 300;
lingering_timeout 5;
proxy_connect_timeout 90;
proxy_send_timeout 300;
proxy_read_timeout 90s;
proxy_pass http://backend;
}
location / {
client_max_body_size 50M;
proxy_set_header Connection "";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Frame-Options SAMEORIGIN;
proxy_buffers 256 16k;
proxy_buffer_size 16k;
proxy_read_timeout 600s;
proxy_cache mattermost_cache;
proxy_cache_revalidate on;
proxy_cache_min_uses 2;
proxy_cache_use_stale timeout;
proxy_cache_lock on;
proxy_http_version 1.1;
proxy_pass http://backend;
}
}
`
backends := ""
for _, addr := range appInstanceAddrs {
backends += "server " + addr + ";\n"
}
session.Stdin = strings.NewReader(strings.TrimSpace(fmt.Sprintf(config, backends)))
if err := session.Run("cat | sudo tee /etc/nginx/sites-available/mattermost"); err != nil {
return err
}
return nil
}
func uploadLimitsConfig(client *ssh.Client) error {
limits := `
* soft nofile 65536
* hard nofile 65536
* soft nproc 8192
* hard nproc 8192
`
sysctl := `
net.ipv4.ip_local_port_range="1024 65000"
net.ipv4.tcp_fin_timeout=30
`
session, err := client.NewSession()
if err != nil {
return errors.Wrap(err, "unable to create ssh session")
}
session.Stdin = strings.NewReader(strings.TrimSpace(limits))
if err := session.Run("cat | sudo tee /etc/security/limits.conf"); err != nil {
return err
}
session.Close()
session, err = client.NewSession()
if err != nil {
return errors.Wrap(err, "unable to create ssh session")
}
session.Stdin = strings.NewReader(strings.TrimSpace(sysctl))
if err := session.Run("cat | sudo tee /etc/sysctl.conf"); err != nil {
return err
}
session.Close()
return nil
}
|
/*
Copyright © 2019 blacktop
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd
import (
"fmt"
"os"
"path"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/apex/log"
"github.com/blacktop/ipsw/api"
"github.com/blacktop/ipsw/utils"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
func init() {
rootCmd.AddCommand(downloadCmd)
// Persistent Flags which will work for this command and all subcommands
downloadCmd.PersistentFlags().String("proxy", "", "HTTP/HTTPS proxy")
downloadCmd.PersistentFlags().Bool("insecure", false, "do not verify ssl certs")
// Filters
downloadCmd.PersistentFlags().StringP("black-list", "n", viper.GetString("IPSW_DEVICE_BLACKLIST"), "iOS device black list")
downloadCmd.PersistentFlags().StringP("version", "v", viper.GetString("IPSW_VERSION"), "iOS Version (i.e. 12.3.1)")
downloadCmd.PersistentFlags().StringP("device", "d", viper.GetString("IPSW_DEVICE"), "iOS Device (i.e. iPhone11,2)")
downloadCmd.PersistentFlags().StringP("build", "b", viper.GetString("IPSW_BUILD"), "iOS BuildID (i.e. 16F203)")
}
// LookupByURL searchs for a ipsw in an array by a download URL
func LookupByURL(ipsws []api.IPSW, dlURL string) (api.IPSW, error) {
for _, i := range ipsws {
if strings.EqualFold(dlURL, i.URL) {
return i, nil
}
}
return api.IPSW{}, fmt.Errorf("unable to find %s in ipsws", dlURL)
}
// downloadCmd represents the download command
var downloadCmd = &cobra.Command{
Use: "download",
Short: "Download and parse IPSW(s) from the internets",
RunE: func(cmd *cobra.Command, args []string) error {
if Verbose {
log.SetLevel(log.DebugLevel)
}
proxy, _ := cmd.Flags().GetString("proxy")
insecure, _ := cmd.Flags().GetBool("insecure")
// filters
version, _ := cmd.Flags().GetString("version")
device, _ := cmd.Flags().GetString("device")
doNotDownload, _ := cmd.Flags().GetString("black-list")
build, _ := cmd.Flags().GetString("build")
if len(version) > 0 && len(build) > 0 {
log.Fatal("you cannot supply a --version AND a --build (they are mutually exclusive)")
}
if len(version) > 0 {
urls := []string{}
ipsws, err := api.GetAllIPSW(version)
if err != nil {
return errors.Wrap(err, "failed to query ipsw.me api")
}
for _, i := range ipsws {
if len(device) > 0 {
if strings.EqualFold(device, i.Identifier) {
urls = append(urls, i.URL)
}
} else {
if len(doNotDownload) > 0 {
if !strings.Contains(i.Identifier, doNotDownload) {
urls = append(urls, i.URL)
}
} else {
urls = append(urls, i.URL)
}
}
}
urls = utils.Unique(urls)
log.Debug("URLs to Download:")
for _, u := range urls {
utils.Indent(log.Debug, 2)(u)
}
// check canijailbreak.com
jbs, _ := api.GetJailbreaks()
if iCan, index, err := jbs.CanIBreak(version); err != nil {
log.Error(err.Error())
} else {
if iCan {
log.WithField("url", jbs.Jailbreaks[index].URL).Warnf("Yo, this shiz is jail breakable via %s B!!!!", jbs.Jailbreaks[index].Name)
utils.Indent(log.Warn, 2)(jbs.Jailbreaks[index].Caveats)
} else {
log.Warnf("Yo, ain't no one jailbreaking this shizz NOT even %s my dude!!!!", api.GetRandomResearcher())
}
}
cont := true
// if filtered to a single device skip the prompt
if len(device) == 0 {
cont = false
prompt := &survey.Confirm{
Message: fmt.Sprintf("You are about to download %d ipsw files. Continue?", len(urls)),
}
survey.AskOne(prompt, &cont)
}
if cont {
for _, url := range urls {
if _, err := os.Stat(path.Base(url)); os.IsNotExist(err) {
// get a handle to ipsw object
i, err := LookupByURL(ipsws, url)
if err != nil {
return errors.Wrap(err, "failed to get ipsw from download url")
}
log.WithFields(log.Fields{
"device": i.Identifier,
"build": i.BuildID,
"version": i.Version,
"signed": i.Signed,
}).Info("Getting IPSW")
// download file
err = api.DownloadFile(url, proxy, insecure)
if err != nil {
return errors.Wrap(err, "failed to download file")
}
// verify download
if ok, _ := utils.Verify(i.SHA1, path.Base(i.URL)); !ok {
return fmt.Errorf("bad download: ipsw %s sha1 hash is incorrect", path.Base(url))
}
} else {
log.Warnf("ipsw already exists: %s", path.Base(url))
}
}
}
} else if len(device) > 0 || len(build) > 0 {
if len(device) > 0 && len(build) > 0 {
i, err := api.GetIPSW(device, build)
if err != nil {
return errors.Wrap(err, "failed to query ipsw.me api")
}
if _, err := os.Stat(path.Base(i.URL)); os.IsNotExist(err) {
log.WithFields(log.Fields{
"device": i.Identifier,
"build": i.BuildID,
"version": i.Version,
"signed": i.Signed,
}).Info("Getting IPSW")
err = api.DownloadFile(i.URL, proxy, insecure)
if err != nil {
return errors.Wrap(err, "failed to download file")
}
if ok, _ := utils.Verify(i.SHA1, path.Base(i.URL)); !ok {
return fmt.Errorf("bad download: ipsw %s sha1 hash is incorrect", path.Base(i.URL))
}
} else {
log.Warnf("ipsw already exists: %s", path.Base(i.URL))
}
}
} else {
log.Fatal("you must also supply a --device AND a --build")
}
return nil
},
}
|
package main
import "lesson/channel/future"
// 入口函数
func main() {
future.Test1()
}
|
package restclient
import (
"encoding/json"
"errors"
"io"
"log"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/kevinburke/rest/resterror"
)
func TestNilClientNoPanic(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("{}"))
}))
defer s.Close()
client := &Client{Base: s.URL}
req, _ := client.NewRequest("GET", "/", nil)
err := client.Do(req, nil)
assertNotError(t, err, "client.Do")
}
func TestBearerClient(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assertEquals(t, r.Header.Get("Authorization"), "Bearer foo")
w.Write([]byte("{}"))
}))
defer s.Close()
client := NewBearerClient("foo", s.URL)
req, _ := client.NewRequest("GET", "/", nil)
err := client.Do(req, nil)
assertNotError(t, err, "client.Do")
}
func TestPost(t *testing.T) {
t.Parallel()
var user, pass string
var requestUrl *url.URL
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, _ = r.BasicAuth()
requestUrl = r.URL
assertEquals(t, r.Header.Get("Content-Type"), "application/json; charset=utf-8")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusAccepted)
w.Write([]byte("{}"))
}))
defer s.Close()
client := New("foo", "bar", s.URL)
req, err := client.NewRequest("POST", "/", nil)
assertNotError(t, err, "")
err = client.Do(req, &struct{}{})
assertNotError(t, err, "")
assertEquals(t, user, "foo")
assertEquals(t, pass, "bar")
assertEquals(t, requestUrl.Path, "/")
}
func TestPostError(t *testing.T) {
t.Parallel()
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(&resterror.Error{
Title: "bad request",
ID: "something_bad",
})
}))
defer s.Close()
client := New("foo", "bar", s.URL)
req, _ := client.NewRequest("POST", "/", nil)
err := client.Do(req, nil)
assertError(t, err, "Making the request")
rerr, ok := err.(*resterror.Error)
assert(t, ok, "converting err to rest.Error")
assertEquals(t, rerr.Title, "bad request")
assertEquals(t, rerr.ID, "something_bad")
}
func TestCustomErrorParser(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(400)
}))
defer s.Close()
client := New("foo", "bar", s.URL)
client.ErrorParser = func(resp *http.Response) error {
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
return errors.New("custom error")
}
req, _ := client.NewRequest("GET", "/", nil)
err := client.Do(req, nil)
assertError(t, err, "expected non-nil error from Do")
assertEquals(t, err.Error(), "custom error")
}
var r *rand.Rand
func init() {
r = rand.New(rand.NewSource(time.Now().UnixNano()))
}
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randFilename() string {
b := make([]byte, 12)
for i := range b {
b[i] = letters[r.Intn(len(letters))]
}
return filepath.Join(os.TempDir(), string(b))
}
func TestSocket(t *testing.T) {
fname := randFilename()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte("{\"status\": 200, \"message\": \"hello world\"}"))
assertNotError(t, err, "socket write")
})
server := http.Server{
Handler: mux,
}
listener, err := net.Listen("unix", fname)
if err != nil {
log.Fatal(err)
}
ch := make(chan bool, 1)
go func() {
<-ch
listener.Close()
}()
go server.Serve(listener)
c := &Client{Base: "http://localhost"}
c.DialSocket(fname, nil)
req, err := c.NewRequest("GET", "/", nil)
assertNotError(t, err, "creating http request")
var b struct {
Status int `json:"status"`
Message string `json:"message"`
}
err = c.Do(req, &b)
assertNotError(t, err, "c.Do")
assertEquals(t, b.Status, 200)
assertEquals(t, b.Message, "hello world")
ch <- true
}
|
package utils
// Abstract
type Base struct {
ID int64 `db:"id" json:"id"`
CreatedTime Time `db:"created_time" json:"created_time"`
UpdatedTime Time `db:"updated_time" json:"updated_time"`
UpdatedSeq int64 `db:"updated_seq" json:"updated_seq"` // 乐观锁标记
Region string `db:"region" json:"region"`
}
// Abstract
type EnableBase struct {
Base
Removed bool `db:"removed" json:"removed"` // 软删标记
}
|
package main
import (
"fmt"
"os"
"github.com/payfazz/go-errors-ext/errhandlerext"
"github.com/payfazz/go-errors/errhandler"
"github.com/payfazz/stdlog"
)
func main() {
defer errhandler.With(errhandlerext.LogAndExit)
if len(os.Args) != 3 {
showUsage()
}
switch os.Args[1] {
case "server":
runServer(os.Args[2])
case "client":
runClient(os.Args[2])
default:
showUsage()
}
}
func showUsage() {
stdlog.Err.Print(fmt.Sprintf(
"Usage:\n"+
"%s client <network:addr>\n"+
"%s server <network:addr>\n"+
"\n"+
"network and addr are as described in https://golang.org/pkg/net/\n"+
"\n"+
"Example:\n"+
"%s client tcp:127.0.0.1:8080\n"+
"%s server tcp::8080\n",
os.Args[0], os.Args[0], os.Args[0], os.Args[0],
))
os.Exit(1)
}
|
// Please, run go generate on root of this repository (github.com/devimteam/proto-utils)
package _go
import (
"time"
devim_time "github.com/devimteam/proto-utils/src/main/go/time"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/lib/pq"
)
type Period struct {
Start *time.Time
End *time.Time
}
func TimeToProto(t time.Time) (*timestamp.Timestamp, error) {
return ptypes.TimestampProto(t)
}
// loc is optional slice for reverse compatibility
func ProtoToTime(t *timestamp.Timestamp, loc ...*time.Location) (timestamp time.Time, err error) {
if t == nil {
return time.Time{}, nil
}
timestamp, err = ptypes.Timestamp(t)
if err != nil {
return
}
if len(loc) == 1 && loc[0] != nil {
timestamp = timestamp.In(loc[0])
}
return
}
func TimePtrToProto(t *time.Time) (*timestamp.Timestamp, error) {
if t == nil {
return nil, nil
}
return TimeToProto(*t)
}
func ProtoToTimePtr(t *timestamp.Timestamp, loc ...*time.Location) (*time.Time, error) {
if t == nil {
return nil, nil
}
tm, err := ProtoToTime(t, loc...)
return &tm, err
}
func TimestampToPqNullTime(t *timestamp.Timestamp) pq.NullTime {
if t == nil {
return pq.NullTime{
Valid: false,
}
}
tm, err := ProtoToTime(t)
return pq.NullTime{
Time: tm,
Valid: err != nil,
}
}
func PqNullTimeToTimestamp(nt pq.NullTime) *timestamp.Timestamp {
if nt.Valid == false {
return nil
}
t, _ := TimeToProto(nt.Time)
return t
}
func PeriodToProto(p *Period) *devim_time.Period {
if p == nil {
return nil
}
start, _ := TimePtrToProto(p.Start)
end, _ := TimePtrToProto(p.End)
return &devim_time.Period{
Start: start,
End: end,
}
}
func ProtoToPeriod(period *devim_time.Period) *Period {
if period == nil {
return nil
}
start, _ := ProtoToTimePtr(period.Start)
end, _ := ProtoToTimePtr(period.End)
return &Period{
Start: start,
End: end,
}
}
// ManyTimesToProto converts many time.Time or *time.Time to Timestamp.
// Function converts every variable or returns on any error.
func ManyTimesToProto(times ...interface{}) ([]*timestamp.Timestamp, error) {
var list []*timestamp.Timestamp
for _, t := range times {
switch tt := t.(type) {
case time.Time:
ts, err := TimeToProto(tt)
if err != nil {
return nil, err
}
list = append(list, ts)
case *time.Time:
ts, err := TimePtrToProto(tt)
if err != nil {
return nil, err
}
list = append(list, ts)
}
}
return list, nil
}
|
package runner
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewFakeRunner(t *testing.T) {
f := NewFakeRunner(1)
f2 := FakeRunner(1)
assert.Equal(t, &f2, f)
}
func TestFakeRunner_WithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
f := NewFakeRunner(1)
f2 := FakeRunner(1)
ctx2 := f.WithContext(ctx)
r, ok := ctx2.Value(contextKey{}).(*FakeRunner)
require.True(t, ok)
assert.Equal(t, &f2, r)
cancel()
<-ctx2.Done()
}
|
// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
// Author : Austin Vern Songer
// Date : 2016-04-25
/**********************************************************************************
*
* Given a sorted array, remove the duplicates in place such that each element appear
* only once and return the new length.
*
* Do not allocate extra space for another array, you must do this in place with constant memory.
*
* For example,
* Given input array A = [1,1,2],
*
* Your function should return length = 2, and A is now [1,2].
*
**********************************************************************************/
package main
import (
"fmt"
)
func removeDuplicates(input []int) int {
length := len(input)
if length <= 1 {
return length
}
pos := 0
for i := 0; i < length-1; i++ {
if input[i] != input[i+1] {
pos++
input[pos] = input[i+1]
}
}
fmt.Println(input[:pos+1])
return pos + 1
}
func main() {
input := []int{1, 1, 2, 3, 3, 3, 4, 5}
length := removeDuplicates(input)
fmt.Println(length)
}
|
package main
// All credits to: https://github.com/MovistarTV/tv_grab_es_movistartv/blob/master/tv_grab_es_movistartv.py#L610
import (
"net"
"flag"
"os"
"fmt"
"io"
//"io/ioutil"
"log"
"time"
"encoding/binary"
//"encoding/xml"
"github.com/ziutek/utils/netaddr"
"github.com/cheggaaa/pb"
)
var bar *pb.ProgressBar
var barenabled bool
var timeout time.Duration
func newbar(size int){
if !barenabled{ return}
if bar != nil{
bar.Finish()
}
bar = pb.New(size)
bar.ShowSpeed = true
bar.SetWidth(120)
//log.Println("BAR STARTS")
bar.Start()
}
func endbar(){
if !barenabled{ return}
if bar != nil{
bar.Finish()
}
//log.Println("BAR FINISH")
}
func writebar(b []byte){
if !barenabled{ return}
if bar != nil{
bar.Write(b)
}
}
func dumpraw(addrinfo string, limit int, w io.WriteCloser){
addr, err := net.ResolveUDPAddr("udp", addrinfo); if err != nil {
log.Fatal(err)
}
r, _ := net.ListenMulticastUDP("udp", nil, addr)
defer r.Close()
log.Println("Reading from", addrinfo, "limit", limit, "w", w)
tot := 0
newbar(limit)
for {
if limit > 0 && tot > limit{
break
}
data := make([]byte, 1500)
r.SetReadDeadline(time.Now().Add(timeout * time.Second))
n, addr, err := r.ReadFromUDP(data); if err != nil{
endbar()
log.Println("Error reading from", addrinfo, err)
return
}
log.Println(addr, addrinfo)
w.Write(data)
writebar(data)
tot += n
}
endbar()
}
func scansave(netinfo string, port int){
_, ipnet, err := net.ParseCIDR(netinfo); if err != nil{
log.Fatal(err)
}
log.Printf("%+v", ipnet)
log.Println(ipnet.IP)
first := netaddr.IPAdd(ipnet.IP, 1)
num := ^binary.BigEndian.Uint32(ipnet.Mask) - 1
last := netaddr.IPAdd(ipnet.IP, int(num))
for ip := first; ! ip.Equal(last); ip = netaddr.IPAdd(ip, 1){
addrinfo := fmt.Sprintf("%s:%d", ip, port ) //3937, 8208
path := "scan/" + addrinfo
f, err := os.OpenFile(path, os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0664); if err != nil{
log.Fatal(err)
}
dumpraw(addrinfo, 1500 * 10, f)
f.Close()
}
}
func main(){
log.SetFlags(log.LstdFlags | log.Lshortfile)
opt_scansave := flag.String("scansave", "", "Scan network range and save samples in scan/")
opt_dumpraw := flag.String("dumpraw", "", "Dump traffic destinated to address")
opt_dumpone := flag.String("dumpone", "", "Dump one packet destinated to address")
opt_dumprtp := flag.String("dumprtp", "", "Dump RTP traffic destinated to address")
opt_dumpsds := flag.String("dumpsds", "", "Dump SDS traffic destinated to address")
opt_dumpepg := flag.String("dumpepg", "", "Dump EPG traffic destinated to address")
opt_timeout := flag.Int("t", 1, "Set UDP read timeout in milliseconds")
opt_port := flag.Int("port", 0, "Port")
flag.Parse()
timeout = time.Duration(*opt_timeout) * 100000000
if *opt_scansave != ""{
scansave(*opt_scansave, *opt_port)
}
if *opt_dumpraw != ""{
dumpraw(*opt_dumpraw, 0, os.Stdout)
return
}
if *opt_dumpone != ""{
barenabled = false
dumpraw(*opt_dumpone, 1, os.Stdout)
}
if *opt_dumprtp != ""{
}
if *opt_dumpsds != ""{
}
if *opt_dumpepg != ""{
}
}
/*
func main1(){
files := make(map[uint16]*File, 0)
xmltvf := NewXMLTVFile()
addr, err := net.ResolveUDPAddr("udp", os.Args[1]); if err != nil {
log.Fatal(err)
}
log.Println(os.Args[1])
r, _ := net.ListenMulticastUDP("udp", nil, addr)
//r.(net.UDPConn).SetReadBuffer(4 * 1024 * 1024)
for{
data := make([]byte, 1500)
n, _ := r.Read(data)
fmt.Printf("% 5d ", n)
chunk := ParseChunk(data[:n])
log.Println("SKIP!")
if chunk.End{ break }
}
filedata := make([]byte, 0)
for len(files) < 500{
data := make([]byte, 1500)
n, _ := r.Read(data)
fmt.Printf("% 5d ", n)
chunk := ParseChunk(data[:n])
filedata = append(filedata, chunk.Data...)
if chunk.End{
file := ParseFile(filedata)
//ioutil.WriteFile("filedata", filedata, 0644)
if file != nil && file.Size > 0 && len(file.Data) != 0{
//fmt.Printf("FILE! %s", file.ServiceURL)
_, ok := files[file.ServiceId]; if ok{
break
}
files[file.ServiceId] = file
xmltvc := &XMLTVChannel{}
xmltvc.Id = fmt.Sprintf("%d", file.ServiceId)
xmltvc.Name = file.ServiceURL //FIXME
xmltvf.Channel = append(xmltvf.Channel, xmltvc)
programs := ParsePrograms(file.Data)
for _, program := range programs{
//log.Printf("PROGRAM %+v\n", program)
xmltvp := &XMLTVProgramme{}
xmltvp.Start = program.Start.Format("20060102150405 -0700")
xmltvp.Stop = program.Start.Add(program.Duration).Format("20060102150405 -0700")
xmltvp.Channel = fmt.Sprintf("%d", file.ServiceId)
xmltvp.Title = program.Title
xmltvp.Date = program.Start.Format("20060102")
xmltvf.Programme = append(xmltvf.Programme, xmltvp)
}
}
filedata = make([]byte, 0)
}
}
xmltvdata, _ := xml.Marshal(xmltvf)
err = ioutil.WriteFile("movi.xmltv", xmltvdata, 0644); if err != nil{
log.Fatal(err)
}
}
*/
|
package mocks
import (
"github.com/volatiletech/sqlboiler/v4/drivers"
"github.com/volatiletech/sqlboiler/v4/importers"
"github.com/volatiletech/strmangle"
)
func init() {
drivers.RegisterFromInit("mock", &MockDriver{})
}
// MockDriver is a mock implementation of the bdb driver Interface
type MockDriver struct{}
// Templates returns the overriding templates for the driver
func (m *MockDriver) Templates() (map[string]string, error) {
return nil, nil
}
// Imports return the set of imports that should be merged
func (m *MockDriver) Imports() (importers.Collection, error) {
return importers.Collection{
BasedOnType: importers.Map{
"null.Int": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.String": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Time": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"null.Bytes": {
ThirdParty: importers.List{`"github.com/volatiletech/null/v8"`},
},
"time.Time": {
Standard: importers.List{`"time"`},
},
},
}, nil
}
// Assemble the DBInfo
func (m *MockDriver) Assemble(config drivers.Config) (dbinfo *drivers.DBInfo, err error) {
dbinfo = &drivers.DBInfo{
Dialect: drivers.Dialect{
LQ: '"',
RQ: '"',
UseIndexPlaceholders: true,
UseLastInsertID: false,
UseTopClause: false,
},
}
defer func() {
if r := recover(); r != nil && err == nil {
dbinfo = nil
err = r.(error)
}
}()
schema := config.MustString(drivers.ConfigSchema)
whitelist, _ := config.StringSlice(drivers.ConfigWhitelist)
blacklist, _ := config.StringSlice(drivers.ConfigBlacklist)
dbinfo.Tables, err = drivers.TablesConcurrently(m, schema, whitelist, blacklist, 1)
if err != nil {
return nil, err
}
return dbinfo, err
}
// TableNames returns a list of mock table names
func (m *MockDriver) TableNames(schema string, whitelist, blacklist []string) ([]string, error) {
if len(whitelist) > 0 {
return whitelist, nil
}
tables := []string{"pilots", "jets", "airports", "licenses", "hangars", "languages", "pilot_languages"}
return strmangle.SetComplement(tables, blacklist), nil
}
// Columns returns a list of mock columns
func (m *MockDriver) Columns(schema, tableName string, whitelist, blacklist []string) ([]drivers.Column, error) {
return map[string][]drivers.Column{
"pilots": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "name", Type: "string", DBType: "character"},
},
"airports": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "size", Type: "null.Int", DBType: "integer", Nullable: true},
},
"jets": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "pilot_id", Type: "int", DBType: "integer", Nullable: true, Unique: true},
{Name: "airport_id", Type: "int", DBType: "integer"},
{Name: "name", Type: "string", DBType: "character", Nullable: false},
{Name: "color", Type: "null.String", DBType: "character", Nullable: true},
{Name: "uuid", Type: "string", DBType: "uuid", Nullable: true},
{Name: "identifier", Type: "string", DBType: "uuid", Nullable: false},
{Name: "cargo", Type: "[]byte", DBType: "bytea", Nullable: false},
{Name: "manifest", Type: "[]byte", DBType: "bytea", Nullable: true, Unique: true},
},
"licenses": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "pilot_id", Type: "int", DBType: "integer"},
},
"hangars": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "name", Type: "string", DBType: "character", Nullable: true, Unique: true},
},
"languages": {
{Name: "id", Type: "int", DBType: "integer"},
{Name: "language", Type: "string", DBType: "character", Nullable: false, Unique: true},
},
"pilot_languages": {
{Name: "pilot_id", Type: "int", DBType: "integer"},
{Name: "language_id", Type: "int", DBType: "integer"},
},
}[tableName], nil
}
// ForeignKeyInfo returns a list of mock foreignkeys
func (m *MockDriver) ForeignKeyInfo(schema, tableName string) ([]drivers.ForeignKey, error) {
return map[string][]drivers.ForeignKey{
"jets": {
{Table: "jets", Name: "jets_pilot_id_fk", Column: "pilot_id", ForeignTable: "pilots", ForeignColumn: "id", ForeignColumnUnique: true},
{Table: "jets", Name: "jets_airport_id_fk", Column: "airport_id", ForeignTable: "airports", ForeignColumn: "id"},
},
"licenses": {
{Table: "licenses", Name: "licenses_pilot_id_fk", Column: "pilot_id", ForeignTable: "pilots", ForeignColumn: "id"},
},
"pilot_languages": {
{Table: "pilot_languages", Name: "pilot_id_fk", Column: "pilot_id", ForeignTable: "pilots", ForeignColumn: "id"},
{Table: "pilot_languages", Name: "jet_id_fk", Column: "language_id", ForeignTable: "languages", ForeignColumn: "id"},
},
}[tableName], nil
}
// TranslateColumnType converts a column to its "null." form if it is nullable
func (m *MockDriver) TranslateColumnType(c drivers.Column) drivers.Column {
if c.Nullable {
switch c.DBType {
case "bigint", "bigserial":
c.Type = "null.Int64"
case "integer", "serial":
c.Type = "null.Int"
case "smallint", "smallserial":
c.Type = "null.Int16"
case "decimal", "numeric", "double precision":
c.Type = "null.Float64"
case `"char"`:
c.Type = "null.Byte"
case "bytea":
c.Type = "null.Bytes"
case "boolean":
c.Type = "null.Bool"
case "date", "time", "timestamp without time zone", "timestamp with time zone":
c.Type = "null.Time"
default:
c.Type = "null.String"
}
} else {
switch c.DBType {
case "bigint", "bigserial":
c.Type = "int64"
case "integer", "serial":
c.Type = "int"
case "smallint", "smallserial":
c.Type = "int16"
case "decimal", "numeric", "double precision":
c.Type = "float64"
case `"char"`:
c.Type = "types.Byte"
case "bytea":
c.Type = "[]byte"
case "boolean":
c.Type = "bool"
case "date", "time", "timestamp without time zone", "timestamp with time zone":
c.Type = "time.Time"
default:
c.Type = "string"
}
}
return c
}
// PrimaryKeyInfo returns mock primary key info for the passed in table name
func (m *MockDriver) PrimaryKeyInfo(schema, tableName string) (*drivers.PrimaryKey, error) {
return map[string]*drivers.PrimaryKey{
"pilots": {
Name: "pilot_id_pkey",
Columns: []string{"id"},
},
"airports": {
Name: "airport_id_pkey",
Columns: []string{"id"},
},
"jets": {
Name: "jet_id_pkey",
Columns: []string{"id"},
},
"licenses": {
Name: "license_id_pkey",
Columns: []string{"id"},
},
"hangars": {
Name: "hangar_id_pkey",
Columns: []string{"id"},
},
"languages": {
Name: "language_id_pkey",
Columns: []string{"id"},
},
"pilot_languages": {
Name: "pilot_languages_pkey",
Columns: []string{"pilot_id", "language_id"},
},
}[tableName], nil
}
// UseLastInsertID returns a database mock LastInsertID compatibility flag
func (m *MockDriver) UseLastInsertID() bool { return false }
// UseTopClause returns a database mock SQL TOP clause compatibility flag
func (m *MockDriver) UseTopClause() bool { return false }
// Open mimics a database open call and returns nil for no error
func (m *MockDriver) Open() error { return nil }
// Close mimics a database close call
func (m *MockDriver) Close() {}
// RightQuote is the quoting character for the right side of the identifier
func (m *MockDriver) RightQuote() byte {
return '"'
}
// LeftQuote is the quoting character for the left side of the identifier
func (m *MockDriver) LeftQuote() byte {
return '"'
}
// UseIndexPlaceholders returns true to indicate fake support of indexed placeholders
func (m *MockDriver) UseIndexPlaceholders() bool {
return false
}
|
package main
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Print(err)
return
}
defer file.Close()
log.SetOutput(file)
log.Print("test")
logger := log.New(file, "[mylogger]", log.LstdFlags)
logger.Print("test")
}
|
package main
import (
"github.com/social-network/subscan-plugin/example/system/http"
"github.com/social-network/subscan-plugin/example/system/model"
"github.com/social-network/subscan-plugin/example/system/service"
"github.com/social-network/subscan-plugin/router"
"github.com/social-network/subscan-plugin/storage"
"github.com/social-network/subscan-plugin/tools"
"github.com/shopspring/decimal"
)
var srv *service.Service
type System struct {
d storage.Dao
}
func New() *System {
return &System{}
}
func (a *System) InitDao(d storage.Dao) {
srv = service.New(d)
a.d = d
a.Migrate()
}
func (a *System) InitHttp() (routers []router.Http) {
return http.Router(srv)
}
func (a *System) ProcessExtrinsic(block *storage.Block, extrinsic *storage.Extrinsic, events []storage.Event) error {
return nil
}
func (a *System) ProcessEvent(block *storage.Block, event *storage.Event, fee decimal.Decimal) error {
var paramEvent []storage.EventParam
tools.UnmarshalToAnything(¶mEvent, event.Params)
switch event.EventId {
case "ExtrinsicFailed":
srv.ExtrinsicFailed(block.SpecVersion, block.BlockTimestamp, block.Hash, event, paramEvent)
}
return nil
}
func (a *System) Migrate() {
db := a.d.DB()
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(
&model.ExtrinsicError{},
)
db.Model(model.ExtrinsicError{}).AddUniqueIndex("extrinsic_hash", "extrinsic_hash")
}
func (a *System) Version() string {
return "0.1"
}
|
package main
import "fmt"
// OPTIMIZE! This can be done in linear time.
func maxAreaBruteForce(height []int) int {
n := len(height)
// assert(n > 1)
max := 0
for i := 0; i < n-1; i++ {
for j := i + 1; j < n; j++ {
y := height[i]
if height[j] < y {
y = height[j]
}
a := y * (j - i)
if a > max {
max = a
}
}
}
return max
}
func maxArea(height []int) int {
// assert(n > 1)
max, left, right := 0, 0, len(height)-1
dist := right
for left < right {
if height[left] < height[right] {
if a := height[left] * dist; a > max {
max = a
}
left++
} else {
if a := height[right] * dist; a > max {
max = a
}
right--
}
dist--
}
return max
}
func main() {
fmt.Println(maxArea([]int{1, 1}))
fmt.Println(maxArea([]int{1, 2}))
fmt.Println(maxArea([]int{10, 10, 10}))
}
|
package log
import (
"github.com/ebar-go/ego/utils/strings"
"github.com/stretchr/testify/assert"
"testing"
)
// TestNew 测试初始化
func TestNew(t *testing.T) {
logger := New()
assert.NotNil(t, logger)
}
func TestNewFileLogger(t *testing.T) {
filePath := "/tmp/system.log"
logger := NewFileLogger(filePath)
assert.NotNil(t, logger)
}
func prepareLogger() Logger {
return NewFileLogger("/tmp/test.log")
}
// TestLogger_Info 测试Info
func TestLogger_Info(t *testing.T) {
traceId := strings.UUID()
prepareLogger().Info("A group of walrus emerges from the ocean", Context{"trace_id": traceId, "hello": "world"})
}
// TestLogger_Info 测试Info
func TestLogger_Debug(t *testing.T) {
traceId := strings.UUID()
prepareLogger().Debug("A group of walrus emerges from the ocean", Context{"trace_id": traceId, "hello": "world"})
}
// TestLogger_Info 测试Info
func TestLogger_Warn(t *testing.T) {
traceId := strings.UUID()
prepareLogger().Warn("A group of walrus emerges from the ocean", Context{"trace_id": traceId, "hello": "world"})
}
// TestLogger_Info 测试Info
func TestLogger_Error(t *testing.T) {
traceId := strings.UUID()
prepareLogger().Error("A group of walrus emerges from the ocean", Context{"trace_id": traceId, "hello": "world"})
}
func TestNewManager(t *testing.T) {
manager := NewManager(ManagerConf{
SystemName: "test",
SystemPort: 8080,
LogPath: "/tmp",
})
assert.NotNil(t, manager.App())
assert.NotNil(t, manager.Mq())
assert.NotNil(t, manager.System())
assert.NotNil(t, manager.Request())
}
|
package suites
import (
"testing"
"time"
"github.com/go-rod/rod"
"github.com/stretchr/testify/require"
)
func (rs *RodSession) doFillLoginPageAndClick(t *testing.T, page *rod.Page, username, password string, keepMeLoggedIn bool) {
usernameElement := rs.WaitElementLocatedByID(t, page, "username-textfield")
passwordElement := rs.WaitElementLocatedByID(t, page, "password-textfield")
buttonElement := rs.WaitElementLocatedByID(t, page, "sign-in-button")
username:
err := usernameElement.MustSelectAllText().Input(username)
require.NoError(t, err)
if usernameElement.MustText() != username {
goto username
}
password:
err = passwordElement.MustSelectAllText().Input(password)
require.NoError(t, err)
if passwordElement.MustText() != password {
goto password
}
if keepMeLoggedIn {
keepMeLoggedInElement := rs.WaitElementLocatedByID(t, page, "remember-checkbox")
err = keepMeLoggedInElement.Click("left", 1)
require.NoError(t, err)
}
click:
err = buttonElement.Click("left", 1)
require.NoError(t, err)
if buttonElement.MustInteractable() {
goto click
}
}
// Login 1FA.
func (rs *RodSession) doLoginOneFactor(t *testing.T, page *rod.Page, username, password string, keepMeLoggedIn bool, domain string, targetURL string) {
rs.doVisitLoginPage(t, page, domain, targetURL)
rs.doFillLoginPageAndClick(t, page, username, password, keepMeLoggedIn)
}
// Login 1FA and 2FA subsequently (must already be registered).
func (rs *RodSession) doLoginTwoFactor(t *testing.T, page *rod.Page, username, password string, keepMeLoggedIn bool, otpSecret, targetURL string) {
rs.doLoginOneFactor(t, page, username, password, keepMeLoggedIn, BaseDomain, targetURL)
rs.verifyIsSecondFactorPage(t, page)
rs.doValidateTOTP(t, page, otpSecret)
// timeout when targetURL is not defined to prevent a show stopping redirect when visiting a protected domain.
if targetURL == "" {
time.Sleep(1 * time.Second)
}
}
// Login 1FA and register 2FA.
func (rs *RodSession) doLoginAndRegisterTOTP(t *testing.T, page *rod.Page, username, password string, keepMeLoggedIn bool) string {
rs.doLoginOneFactor(t, page, username, password, keepMeLoggedIn, BaseDomain, "")
secret := rs.doRegisterTOTP(t, page)
rs.doVisit(t, page, GetLoginBaseURL(BaseDomain))
rs.verifyIsSecondFactorPage(t, page)
return secret
}
// Register a user with TOTP, logout and then authenticate until TOTP-2FA.
func (rs *RodSession) doRegisterAndLogin2FA(t *testing.T, page *rod.Page, username, password string, keepMeLoggedIn bool, targetURL string) string { //nolint:unparam
// Register TOTP secret and logout.
secret := rs.doRegisterThenLogout(t, page, username, password)
rs.doLoginTwoFactor(t, page, username, password, keepMeLoggedIn, secret, targetURL)
return secret
}
|
package secrets
import (
"fmt"
"testing"
"github.com/10gen/realm-cli/internal/cloud/realm"
"github.com/10gen/realm-cli/internal/utils/test/assert"
"github.com/10gen/realm-cli/internal/utils/test/mock"
)
func TestSecretsDeleteInputsResolve(t *testing.T) {
testLen := 7
secrets := make([]realm.Secret, testLen)
for i := 0; i < testLen; i++ {
secrets[i] = realm.Secret{
ID: fmt.Sprintf("secret_id_%d", i),
Name: fmt.Sprintf("secret_name_%d", i),
}
}
for _, tc := range []struct {
description string
selectedSecrets []string
expectedOutput []realm.Secret
}{
{
description: "select by ID",
selectedSecrets: []string{"secret_id_0"},
expectedOutput: []realm.Secret{secrets[0]},
},
{
description: "select by name",
selectedSecrets: []string{"secret_name_2"},
expectedOutput: []realm.Secret{secrets[2]},
},
{
description: "select by name and ID",
selectedSecrets: []string{"secret_name_2", "secret_id_4", "secret_name_1"},
expectedOutput: []realm.Secret{secrets[2], secrets[4], secrets[1]},
},
} {
t.Run("should return the secrets when specified by "+tc.description, func(t *testing.T) {
inputs := deleteInputs{
secrets: tc.selectedSecrets,
}
secretsResult, err := inputs.resolveSecrets(nil, secrets)
assert.Nil(t, err)
assert.Equal(t, tc.expectedOutput, secretsResult)
})
}
for _, tc := range []struct {
description string
selectedSecrets []string
expectedOutput []realm.Secret
}{
{
selectedSecrets: []string{"secret_id_0"},
expectedOutput: []realm.Secret{secrets[0]},
},
{
description: "allow multiple selections",
selectedSecrets: []string{"secret_id_6", "secret_id_1", "secret_id_2"},
expectedOutput: []realm.Secret{secrets[1], secrets[2], secrets[6]},
},
} {
t.Run("should prompt for secrets with no input: "+tc.description, func(t *testing.T) {
inputs := deleteInputs{}
_, console, _, ui, consoleErr := mock.NewVT10XConsole()
assert.Nil(t, consoleErr)
defer console.Close()
doneCh := make(chan struct{})
go func() {
defer close(doneCh)
console.ExpectString("Which secret(s) would you like to delete?")
for _, selected := range tc.selectedSecrets {
console.Send(selected)
console.Send(" ")
}
console.SendLine("")
console.ExpectEOF()
}()
secretsResult, err := inputs.resolveSecrets(ui, secrets)
console.Tty().Close()
<-doneCh
assert.Nil(t, err)
assert.Equal(t, tc.expectedOutput, secretsResult)
})
}
}
|
package fibweb_test
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/uudashr/fibweb"
"github.com/uudashr/fibweb/internal/mocks"
)
func TestNumbers_validLimit(t *testing.T) {
fibonacciService := new(mocks.FibonacciService)
handler := fibweb.NewHTTPHandler(fibonacciService)
limit := 7
out := []int{0, 1, 1, 2, 3, 5, 8}
fibonacciService.On("Seq", limit).Return(out, nil)
req, err := http.NewRequest(http.MethodGet, "/api/fibonacci/numbers", nil)
if err != nil {
t.Fatal("err:", err)
}
q := req.URL.Query()
q.Add("limit", strconv.Itoa(limit))
req.URL.RawQuery = q.Encode()
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if got, want := rec.Code, http.StatusOK; got != want {
t.Fatal("got:", got, "want:", want)
}
var result []int
err = json.NewDecoder(rec.Body).Decode(&result)
if err != nil {
t.Fatal("err:", err)
}
if got, want := len(out), len(result); got != want {
t.Fatal("len(got):", got, "len(want):", want)
}
for i, count := 0, len(result); i < count; i++ {
if got, want := result[i], out[i]; got != want {
t.Fatal("result[i]:", got, "out[i]:", want, "i:", i)
}
}
}
func TestNumbers_noLimit(t *testing.T) {
fibonacciService := new(mocks.FibonacciService)
handler := fibweb.NewHTTPHandler(fibonacciService)
out := []int{0, 1, 1, 2, 3, 5}
fibonacciService.On("Seq", 5).Return(out, nil)
req, err := http.NewRequest(http.MethodGet, "/api/fibonacci/numbers", nil)
if err != nil {
t.Fatal("err:", err)
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if got, want := rec.Code, http.StatusOK; got != want {
t.Fatal("got:", got, "want:", want)
}
var result []int
err = json.NewDecoder(rec.Body).Decode(&result)
if err != nil {
t.Fatal("err:", err)
}
if got, want := len(out), len(result); got != want {
t.Fatal("len(got):", got, "len(want):", want)
}
for i, count := 0, len(result); i < count; i++ {
if got, want := result[i], out[i]; got != want {
t.Fatal("result[i]:", got, "out[i]:", want, "i:", i)
}
}
fibonacciService.AssertExpectations(t)
}
func TestNumbers_emptyLimit(t *testing.T) {
fibonacciService := new(mocks.FibonacciService)
handler := fibweb.NewHTTPHandler(fibonacciService)
out := []int{0, 1, 1, 2, 3, 5}
fibonacciService.On("Seq", 5).Return(out, nil)
req, err := http.NewRequest(http.MethodGet, "/api/fibonacci/numbers", nil)
if err != nil {
t.Error("err:", err)
t.SkipNow()
}
q := req.URL.Query()
q.Add("limit", "")
req.URL.RawQuery = q.Encode()
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if got, want := rec.Code, http.StatusOK; got != want {
t.Error("got:", got, "want:", want)
t.SkipNow()
}
var result []int
err = json.NewDecoder(rec.Body).Decode(&result)
if err != nil {
t.Error("err:", err)
t.SkipNow()
}
if got, want := len(out), len(result); got != want {
t.Error("len(got):", got, "len(want):", want)
t.SkipNow()
}
for i, count := 0, len(result); i < count; i++ {
if got, want := result[i], out[i]; got != want {
t.Error("result[i]:", got, "out[i]:", want, "i:", i)
}
}
fibonacciService.AssertExpectations(t)
}
func TestNumbers_badLimit(t *testing.T) {
fibonacciService := new(mocks.FibonacciService)
handler := fibweb.NewHTTPHandler(fibonacciService)
limits := []string{"asdf", "-1", "29jh"}
for _, limit := range limits {
req, err := http.NewRequest(http.MethodGet, "/api/fibonacci/numbers", nil)
if err != nil {
t.Error("err:", err, "limit:", limit)
t.SkipNow()
}
q := req.URL.Query()
q.Add("limit", limit)
req.URL.RawQuery = q.Encode()
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if got, want := rec.Code, http.StatusBadRequest; got != want {
t.Error("got:", got, "want:", want, "limit:", limit)
}
}
}
func TestNumbers_serviceError(t *testing.T) {
fibonacciService := new(mocks.FibonacciService)
handler := fibweb.NewHTTPHandler(fibonacciService)
limit := 10
fibonacciService.On("Seq", limit).Return(nil, errors.New("Some error"))
req, err := http.NewRequest(http.MethodGet, "/api/fibonacci/numbers", nil)
if err != nil {
t.Error("err:", err, "limit:", limit)
t.SkipNow()
}
q := req.URL.Query()
q.Add("limit", strconv.Itoa(limit))
req.URL.RawQuery = q.Encode()
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if got, want := rec.Code, http.StatusBadRequest; got != want {
t.Error("got:", got, "want:", want, "limit:", limit)
}
}
|
package dp
import "testing"
func TestLCS(t *testing.T) {
num1 := []int{1, 3, 5, 9, 10}
num2 := []int{1, 3, 9, 10}
println(longestCommonSubsequence1(num1, num2))
println(longestCommonSubsequence2(num1, num2))
println(longestCommonSubstring1("ABCD", "BCDA"))
}
|
// Copyright 2017 The OpenSDS Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package oceanstor
type Error struct {
Code int `json:"code"`
Description string `json:"description"`
}
type GenericResult struct {
Data interface{} `json:"data"`
Error Error `json:"error"`
}
type Auth struct {
AccountState int `json:"accountstate"`
DeviceId string `json:"deviceid"`
IBaseToken string `json:"iBaseToken"`
LastLoginIp string `json:"lastloginip"`
LastLoginTime int `json:"lastlogintime"`
Level int `json:"level"`
PwdChanGeTime int `json:"pwdchangetime"`
UserGroup string `json:"usergroup"`
UserId string `json:"userid"`
UserName string `json:"username"`
UserScope string `json:"userscope"`
}
type AuthResp struct {
Data Auth `json:"data"`
Error Error `json:"error"`
}
type StoragePool struct {
Description string `json:"DESCRIPTION"`
Id string `json:"ID"`
Name string `json:"NAME"`
UserFreeCapacity string `json:"USERFREECAPACITY"`
UserTotalCapacity string `json:"USERTOTALCAPACITY"`
}
type StoragePoolsResp struct {
Data []StoragePool `json:"data"`
Error Error `json:"error"`
}
type Lun struct {
AllocCapacity string `json:"ALLOCCAPACITY"`
AllocType string `json:"ALLOCTYPE"`
Capability string `json:"CAPABILITY"`
Capacity string `json:"CAPACITY"`
CapacityAlarmLevel string `json:"CAPACITYALARMLEVEL"`
Description string `json:"DESCRIPTION"`
DrsEnable string `json:"DRS_ENABLE"`
EnableCompression string `json:"ENABLECOMPRESSION"`
EnableIscsiThinLunThreshold string `json:"ENABLEISCSITHINLUNTHRESHOLD"`
EnableSmartDedup string `json:"ENABLESMARTDEDUP"`
ExposedToInitiator string `json:"EXPOSEDTOINITIATOR"`
ExtendIfSwitch string `json:"EXTENDIFSWITCH"`
HealthStatus string `json:"HEALTHSTATUS"`
Id string `json:"ID"`
IsAdd2LunGroup string `json:"ISADD2LUNGROUP"`
IsCheckZeroPage string `json:"ISCHECKZEROPAGE"`
IscsiThinLunThreshold string `json:"ISCSITHINLUNTHRESHOLD"`
LunMigrationOrigin string `json:"LUNMigrationOrigin"`
MirrorPolicy string `json:"MIRRORPOLICY"`
MirrorType string `json:"MIRRORTYPE"`
Name string `json:"NAME"`
OwningController string `json:"OWNINGCONTROLLER"`
ParentId string `json:"PARENTID"`
ParentName string `json:"PARENTNAME"`
PrefetChPolicy string `json:"PREFETCHPOLICY"`
PrefetChValue string `json:"PREFETCHVALUE"`
RemoteLunId string `json:"REMOTELUNID"`
RemoteReplicationIds string `json:"REMOTEREPLICATIONIDS"`
ReplicationCapacity string `json:"REPLICATION_CAPACITY"`
RunningStatus string `json:"RUNNINGSTATUS"`
RunningWritePolicy string `json:"RUNNINGWRITEPOLICY"`
SectorSize string `json:"SECTORSIZE"`
SnapShotIds string `json:"SNAPSHOTIDS"`
SubType string `json:"SUBTYPE"`
ThinCapacityUsage string `json:"THINCAPACITYUSAGE"`
Type int `json:"TYPE"`
UsageType string `json:"USAGETYPE"`
WorkingController string `json:"WORKINGCONTROLLER"`
WritePolicy string `json:"WRITEPOLICY"`
Wwn string `json:"WWN"`
RemoteLunWwn string `json:"remoteLunWwn"`
}
type LunResp struct {
Data Lun `json:"data"`
Error Error `json:"error"`
}
type LunsResp struct {
Data []Lun `json:"data"`
Error Error `json:"error"`
}
type Snapshot struct {
CascadedLevel string `json:"CASCADEDLEVEL"`
CascadedNum string `json:"CASCADEDNUM"`
ConsumedCapacity string `json:"CONSUMEDCAPACITY"`
Description string `json:"DESCRIPTION"`
ExposedToInitiator string `json:"EXPOSEDTOINITIATOR"`
HealthStatus string `json:"HEALTHSTATUS"`
Id string `json:"ID"`
IoClassId string `json:"IOCLASSID"`
IoPriority string `json:"IOPRIORITY"`
SourceLunCapacity string `json:"SOURCELUNCAPACITY"`
Name string `json:"NAME"`
ParentId string `json:"PARENTID"`
ParentName string `json:"PARENTNAME"`
ParentType int `json:"PARENTTYPE"`
RollBackendTime string `json:"ROLLBACKENDTIME"`
RollbackRate string `json:"ROLLBACKRATE"`
RollbackSpeed string `json:"ROLLBACKSPEED"`
RollbackStartTime string `json:"ROLLBACKSTARTTIME"`
RollbackTargetObjId string `json:"ROLLBACKTARGETOBJID"`
RollbackTargetObjName string `json:"ROLLBACKTARGETOBJNAME"`
RunningStatus string `json:"RUNNINGSTATUS"`
SourceLunId string `json:"SOURCELUNID"`
SourceLunName string `json:"SOURCELUNNAME"`
SubType string `json:"SUBTYPE"`
TimeStamp string `json:"TIMESTAMP"`
Type int `json:"TYPE"`
UserCapacity string `json:"USERCAPACITY"`
WorkingController string `json:"WORKINGCONTROLLER"`
Wwn string `json:"WWN"`
ReplicationCapacity string `json:"replicationCapacity"`
}
type SnapshotResp struct {
Data Snapshot `json:"data"`
Error Error `json:"error"`
}
type SnapshotsResp struct {
Data []Snapshot `json:"data"`
Error Error `json:"error"`
}
type Initiator struct {
Id string `json:"ID"`
Name string `json:"NAME"`
ParentId string `json:"PARENTID"`
ParentType string `json:"PARENTTYPE"`
ParentName string `json:"PARENTNAME"`
}
type InitiatorResp struct {
Data Initiator `json:"data"`
Error Error `json:"error"`
}
type InitiatorsResp struct {
Data []Initiator `json:"data"`
Error Error `json:"error"`
}
type Host struct {
Id string `json:"ID"`
Name string `json:"NAME"`
OsType string `json:"OPERATIONSYSTEM"`
Ip string `json:"IP"`
IsAddToHostGroup bool `json:"ISADD2HOSTGROUP"`
}
type HostResp struct {
Data Host `json:"data"`
Error Error `json:"error"`
}
type HostsResp struct {
Data []Host `json:"data"`
Error Error `json:"error"`
}
type HostGroup struct {
Id string `json:"ID"`
Name string `json:"NAME"`
Description string `json:"DESCRIPTION"`
IsAdd2MappingView string `json:"ISADD2MAPPINGVIEW"`
}
type HostGroupResp struct {
Data HostGroup `json:"data"`
Error Error `json:"error"`
}
type HostGroupsResp struct {
Data []HostGroup `json:"data"`
Error Error `json:"error"`
}
type LunGroup struct {
Id string `json:"ID"`
Name string `json:"NAME"`
Description string `json:"DESCRIPTION"`
IsAdd2MappingView string `json:"ISADD2MAPPINGVIEW"`
}
type LunGroupResp struct {
Data LunGroup `json:"data"`
Error Error `json:"error"`
}
type LunGroupsResp struct {
Data []LunGroup `json:"data"`
Error Error `json:"error"`
}
type MappingView struct {
Id string `json:"ID"`
Name string `json:"NAME"`
Description string `json:"DESCRIPTION"`
}
type MappingViewResp struct {
Data MappingView `json:"data"`
Error Error `json:"error"`
}
type MappingViewsResp struct {
Data []MappingView `json:"data"`
Error Error `json:"error"`
}
type IscsiTgtPort struct {
EthPortId string `json:"ETHPORTID"`
Id string `json:"ID"`
Tpgt string `json:"TPGT"`
Type int `json:"TYPE"`
}
type IscsiTgtPortsResp struct {
Data []IscsiTgtPort `json:"data"`
Error Error `json:"error"`
}
type HostAssociateLun struct {
Id string `json:"ID"`
AssociateMetadata string `json:"ASSOCIATEMETADATA"`
}
type HostAssociateLunsResp struct {
Data []HostAssociateLun `json:"data"`
Error Error `json:"error"`
}
type System struct {
Id string `json:"ID"`
Name string `json:"NAME"`
Location string `json:"LOCATION"`
ProductMode string `json:"PRODUCTMODE"`
Wwn string `json:"wwn"`
}
type SystemResp struct {
Data System `json:"data"`
Error Error `json:"error"`
}
type RemoteDevice struct {
Id string `json:"ID"`
Name string `json:"NAME"`
ArrayType string `json:"ARRAYTYPE"`
HealthStatus string `json:"HEALTHSTATUS"`
RunningStatus string `json:"RUNNINGSTATUS"`
Wwn string `json:"WWN"`
}
type RemoteDevicesResp struct {
Data []RemoteDevice `json:"data"`
Error Error `json:"error"`
}
type ReplicationPair struct {
Capacity string `json:"CAPACITY"`
CompressValid string `json:"COMPRESSVALID"`
EnableCompress string `json:"ENABLECOMPRESS"`
HealthStatus string `json:"HEALTHSTATUS"`
Id string `json:"ID"`
IsDataSync string `json:"ISDATASYNC"`
IsInCg string `json:"ISINCG"`
IsPrimary string `json:"ISPRIMARY"`
IsRollback string `json:"ISROLLBACK"`
LocalResId string `json:"LOCALRESID"`
LocalResName string `json:"LOCALRESNAME"`
LocalResType string `json:"LOCALRESTYPE"`
PriResDataStatus string `json:"PRIRESDATASTATUS"`
RecoveryPolicy string `json:"RECOVERYPOLICY"`
RemoteDeviceId string `json:"REMOTEDEVICEID"`
RemoteDeviceName string `json:"REMOTEDEVICENAME"`
RemoteDeviceSn string `json:"REMOTEDEVICESN"`
RemoteResId string `json:"REMOTERESID"`
RemoteResName string `json:"REMOTERESNAME"`
ReplicationMode string `json:"REPLICATIONMODEL"`
ReplicationProgress string `json:"REPLICATIONPROGRESS"`
RunningStatus string `json:"RUNNINGSTATUS"`
SecResAccess string `json:"SECRESACCESS"`
SecResDataStatus string `json:"SECRESDATASTATUS"`
Speed string `json:"SPEED"`
SynchronizeType string `json:"SYNCHRONIZETYPE"`
SyncLeftTime string `json:"SYNCLEFTTIME"`
TimeDifference string `json:"TIMEDIFFERENCE"`
RemTimeoutPeriod string `json:"REMTIMEOUTPERIOD"`
Type string `json:"TYPE"`
}
type ReplicationPairResp struct {
Data ReplicationPair `json:"data"`
Error Error `json:"error"`
}
type SimpleStruct struct {
Id string `json:"ID"`
Name string `json:"NAME"`
}
type SimpleResp struct {
Data []SimpleStruct `json:"data"`
Error Error `json:"error"`
}
type FCInitiatorsResp struct {
Data []FCInitiator `json:"data"`
Error Error `json:"error"`
}
type FCInitiator struct {
Isfree bool `json:"ISFREE"`
Id string `json:"ID"`
Type int `json:"TYPE"`
RunningStatus string `json:"RUNNINGSTATUS"`
ParentId string `json:"PARENTID"`
ParentType int `json:"PARENTTYPE"`
}
type FCTargWWPNResp struct {
Data []FCTargWWPN `json:"data"`
Error Error `json:"error"`
}
type FCTargWWPN struct {
IniPortWWN string `json:"INITIATOR_PORT_WWN"`
TargPortWWN string `json:"TARGET_PORT_WWN"`
}
type ObjCountResp struct {
Data Count `json:"data"`
Error Error `json:"error"`
}
type Count struct {
Count string `json:"COUNT"`
}
type Performance struct {
Uuid string `json:"CMO_STATISTIC_UUID"`
DataIdList string `json:"CMO_STATISTIC_DATA_ID_LIST"`
DataList string `json:"CMO_STATISTIC_DATA_LIST"`
TimeStamp string `json:"CMO_STATISTIC_TIMESTAMP"`
}
type PerformancesResp struct {
Data []Performance `json:"data"`
Error Error `json:"error"`
}
|
package arch
import (
"fmt"
"io"
"jugonz/chip8/src/gfx"
"math/rand"
"os"
"time"
)
/**
* Datatype to describe the architecture of a Chip8 system.
*/
type Chip8 struct {
// Core structural components.
Opcode Opcode
Memory [4096]uint8
Registers [16]uint8
IndexReg uint16
PC uint16
DelayTimer uint8
SoundTimer uint8
Stack [16]uint16
SP uint16
Rando *rand.Rand // PRNG
UpdatePC uint16 // Amount of cycles to update PC.
// Interactive components.
Controller gfx.Interactible
Screen gfx.Drawable
Fontset [80]uint8
DrawFlag bool // True if we just drew to the screen.
// Debug components.
Debug bool
Count int
CycleRate time.Duration
}
func MakeChip8(debug bool) *Chip8 { // and initialize
c8 := Chip8{}
c8.Opcode = Opcode{}
c8.PC = 0x200 // Starting PC address is static.
c8.Rando = rand.New(rand.NewSource(time.Now().UnixNano()))
// Define fonset.
c8.Fontset = [80]uint8{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80, // F
}
// Load fontset into memory.
for char := 0; char < len(c8.Fontset); char++ {
c8.Memory[char] = c8.Fontset[char]
}
screen := gfx.MakeScreen(640, 480, 64, 32, "Chip-8 Emulator")
c8.Screen = &screen
c8.Controller = &screen
c8.Debug = debug
c8.CycleRate = time.Second / 10800
return &c8
}
func (c8 *Chip8) LoadGame(filePath string) {
// Open file and load into memory, else panic.
file, err := os.Open(filePath)
if err != nil {
panic(fmt.Sprintf(
"Error: File at %v could not be loaded! Error was: %v\n",
filePath, err))
}
defer file.Close()
// Now, we've opened the file, and can load
// its contents into memory.
// We must first get the file size.
stat, err := file.Stat()
if err != nil {
panic(fmt.Sprintf(
"Error: Info about file at %v could not be found! Error was: %v\n",
filePath, err))
}
buffer := make([]byte, stat.Size()) // Make new buffer to store game.
_, err = io.ReadFull(file, buffer)
if err != nil {
panic(fmt.Sprintf(
"Error: File at %v could not be read completely! Error was: %v\n",
filePath, err))
}
for index, value := range buffer {
c8.Memory[index+0x200] = value
}
}
func (c8 *Chip8) Run() {
for _ = range time.Tick(c8.CycleRate) {
if c8.Controller.ShouldClose() {
return
}
c8.EmulateCycle()
}
}
func (c8 *Chip8) EmulateCycle() {
c8.FetchOpcode() // Fetch instruction.
if c8.Debug {
fmt.Printf("On cycle %v, at mem loc %X\n", c8.Count, c8.PC)
c8.Count++
}
c8.DecodeExecute()
c8.DrawScreen() // Only draws if needed.
c8.SetKeys()
c8.UpdateTimers()
c8.IncrementPC()
}
func (c8 *Chip8) FetchOpcode() {
newOp := uint16(c8.Memory[c8.PC]) << 8
newOp |= uint16(c8.Memory[c8.PC+1])
c8.Opcode = MakeOpcode(newOp)
}
func (c8 *Chip8) DecodeExecute() {
// Update PC by 2 unless overridden by an instruction.
c8.UpdatePC = 2
switch c8.Opcode.Value >> 12 { // Decode (big-ass switch statement)
case 0x0:
switch c8.Opcode.Value & 0xFF {
case 0xE0:
c8.ClearScreen()
case 0xEE:
c8.Return()
default:
c8.CallRCA1802()
}
case 0x1:
c8.Jump()
case 0x2:
c8.Call()
case 0x3:
c8.SkipInstrEqualLiteral()
case 0x4:
c8.SkipInstrNotEqualLiteral()
case 0x5:
c8.SkipInstrEqualReg()
case 0x6:
c8.SetRegToLiteral()
case 0x7:
c8.Add()
case 0x8:
switch c8.Opcode.Value & 0xF {
case 0x0:
c8.SetRegToReg()
case 0x1:
c8.Or()
case 0x2:
c8.And()
case 0x3:
c8.Xor()
case 0x4:
c8.AddWithCarry()
case 0x5:
c8.SubYFromX()
case 0x6:
c8.ShiftRight()
case 0x7:
c8.SubXFromY()
case 0xE:
c8.ShiftLeft()
default:
c8.UnknownInstruction()
}
case 0x9:
c8.SkipInstrNotEqualReg()
case 0xA:
c8.SetIndexLiteral()
case 0xB:
c8.JumpIndexLiteralOffset()
case 0xC:
c8.SetRegisterRandomMask()
case 0xD:
c8.DrawSprite()
case 0xE:
switch c8.Opcode.Value & 0xFF {
case 0x9E:
c8.SkipInstrKeyPressed()
case 0xA1:
c8.SkipInstrKeyNotPressed()
default:
c8.UnknownInstruction()
}
case 0xF:
switch c8.Opcode.Value & 0xFF {
case 0x07:
c8.GetDelayTimer()
case 0x0A:
c8.GetKeyPress()
case 0x15:
c8.SetDelayTimer()
case 0x18:
c8.SetSoundTimer()
case 0x1E:
c8.AddRegisterToIndex()
case 0x29:
c8.SetIndexToSprite()
case 0x33:
c8.SaveBinaryCodedDecimal()
case 0x55:
c8.SaveRegisters()
case 0x65:
c8.RestoreRegisters()
default:
c8.UnknownInstruction()
}
default:
c8.UnknownInstruction()
}
}
func (c8 *Chip8) DrawScreen() {
if c8.DrawFlag {
c8.Screen.Draw()
c8.DrawFlag = false
}
}
func (c8 *Chip8) SetKeys() {
c8.Controller.SetKeys()
}
func (c8 *Chip8) UpdateTimers() {
if c8.DelayTimer > 0 {
c8.DelayTimer--
}
if c8.SoundTimer > 0 {
fmt.Printf("\x07") // BEEP!
c8.SoundTimer--
}
}
func (c8 *Chip8) IncrementPC() {
c8.PC += c8.UpdatePC
}
func (c8 *Chip8) Quit() {
c8.Controller.Quit()
}
|
// matrix-websockets-proxy provides a websockets interface to a Matrix
// homeserver implementing the REST API.
//
// It listens on a TCP port (localhost:8009 by default), and turns any
// incoming connections into REST requests to the configured homeserver.
//
// It exposes only the one HTTP endpoint '/stream'. It is intended
// that an SSL-aware reverse proxy (such as Apache or nginx) be used in front
// of it, to direct most requests to the homeserver, but websockets requests
// to this proxy.
//
// You can also visit http://localhost:8009/test/test.html, which is a very
// simple client for testing the websocket interface.
//
package main
import (
"flag"
"fmt"
"log"
"net/http"
"path/filepath"
"runtime"
"time"
"github.com/gorilla/websocket"
"github.com/matrix-org/matrix-websockets-proxy/proxy"
)
const (
// timeout for upstream /sync requests (after which it will send back
// an empty response)
syncTimeout = 60 * time.Second
)
var port = flag.Int("port", 8009, "TCP port to listen on")
var upstreamURL = flag.String("upstream", "http://localhost:8008/", "URL of upstream server")
var testHTML *string
func init() {
_, srcfile, _, _ := runtime.Caller(0)
def := filepath.Join(filepath.Dir(srcfile), "test")
testHTML = flag.String("testdir", def, "Path to the HTML test resources")
}
func main() {
flag.Parse()
fmt.Println("Starting websock server on port", *port)
http.Handle("/test/", http.StripPrefix("/test/", http.FileServer(http.Dir(*testHTML))))
http.HandleFunc("/stream", serveStream)
err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
log.Fatal("ListenAndServe: ", err)
}
// handle a request to /stream
//
func serveStream(w http.ResponseWriter, r *http.Request) {
log.Println("Got websocket request to", r.URL)
if r.Method != "GET" {
log.Println("Invalid method", r.Method)
httpError(w, http.StatusMethodNotAllowed)
return
}
r.URL.Query().Set("timeout", "0")
syncer := &proxy.Syncer{
UpstreamURL: *upstreamURL + "_matrix/client/v2_alpha/sync",
SyncParams: r.URL.Query(),
}
msg, err := syncer.MakeRequest()
if err != nil {
switch err.(type) {
case *proxy.SyncError:
errp := err.(*proxy.SyncError)
log.Println("sync failed:", string(errp.Body))
w.Header().Set("Content-Type", errp.ContentType)
w.WriteHeader(errp.StatusCode)
w.Write(errp.Body)
default:
log.Println("Error in sync", err)
httpError(w, http.StatusInternalServerError)
}
return
}
syncer.SyncParams.Set("timeout", fmt.Sprintf("%d", syncTimeout/time.Millisecond))
upgrader := websocket.Upgrader{
Subprotocols: []string{"m.json"},
}
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
c := proxy.New(syncer, ws)
c.SendMessage(msg)
c.Start()
}
func httpError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
|
package service
import (
"github.com/godbus/dbus"
"github.com/muka/go-bluetooth/bluez"
"github.com/muka/go-bluetooth/bluez/profile/gatt"
)
// NewGattDescriptor1 create a new GattDescriptor1 client
func NewGattDescriptor1(config *GattDescriptor1Config, props *gatt.GattDescriptor1Properties) (*GattDescriptor1, error) {
propInterface, err := NewProperties(config.conn)
if err != nil {
return nil, err
}
g := &GattDescriptor1{
config: config,
properties: props,
PropertiesInterface: propInterface,
}
err = propInterface.AddProperties(g.Interface(), props)
if err != nil {
return nil, err
}
return g, nil
}
//GattDescriptor1Config GattDescriptor1 configuration
type GattDescriptor1Config struct {
objectPath dbus.ObjectPath
characteristic *GattCharacteristic1
ID int
conn *dbus.Conn
}
// GattDescriptor1 client
type GattDescriptor1 struct {
config *GattDescriptor1Config
properties *gatt.GattDescriptor1Properties
PropertiesInterface *Properties
}
//Conn return a conn instance
func (s *GattDescriptor1) Conn() *dbus.Conn {
return s.config.conn
}
//Path return the object path
func (s *GattDescriptor1) Path() dbus.ObjectPath {
return s.config.objectPath
}
//Interface return the Dbus interface
func (s *GattDescriptor1) Interface() string {
return gatt.GattDescriptor1Interface
}
//Properties return the properties of the service
func (s *GattDescriptor1) Properties() bluez.Properties {
s.properties.Characteristic = s.config.characteristic.Path()
return s.properties
}
//Expose the desc to dbus
func (s *GattDescriptor1) Expose() error {
return ExposeService(s)
//
// conn := s.config.conn
//
// err := conn.Export(s, s.Path(), s.Interface())
// if err != nil {
// return err
// }
//
// for iface, props := range s.Properties() {
// s.PropertiesInterface.AddProperties(iface, props)
// }
//
// s.PropertiesInterface.Expose(s.Path())
//
// node := &introspect.Node{
// Interfaces: []introspect.Interface{
// //Introspect
// introspect.IntrospectData,
// //Properties
// prop.IntrospectData,
// //GattCharacteristic1
// {
// Name: s.Interface(),
// Methods: introspect.Methods(s),
// Properties: s.PropertiesInterface.Introspection(s.Interface()),
// },
// },
// }
//
// err = conn.Export(
// introspect.NewIntrospectable(node),
// s.Path(),
// "org.freedesktop.DBus.Introspectable")
// if err != nil {
// return err
// }
//
// return nil
}
|
package stash
import "testing"
func TestGetSshUrl(t *testing.T) {
clones := []Clone{
Clone{Name: "ssh", HREF: "ssh-url"},
Clone{Name: "http", HREF: "http-url"},
}
links := Links{Clones: clones}
repository := Repository{Links: links}
sshURL := repository.SshUrl()
if sshURL != "ssh-url" {
t.Fatalf("Want ssh-url but got %s\n", sshURL)
}
}
func TestGetSshUrlMissing(t *testing.T) {
clones := []Clone{
Clone{Name: "http", HREF: "http-url"},
}
links := Links{Clones: clones}
repository := Repository{Links: links}
sshURL := repository.SshUrl()
if sshURL != "" {
t.Fatalf("Want no url but got %s\n", sshURL)
}
}
|
package tpi_data
import (
_ "image"
_ "image/jpeg"
"reflect"
"time"
)
type Thali struct {
Id int64 `json:"id"`
Name string `json:"name"`
Submitted time.Time `json:"submitted"`
Target string `json:"target" schema:"target"` // 1-4 target customer profile
Limited bool `json:"limited" schema:"limited"`
Region string `json:"region" schema:"region"` // 1-3 target cuisine
Price float64 `json:"price" schema:"price"`
//Photo *image.RGBA `json:"image"`
Photo string `json:"image"`
Media PhotoUrl `json:"media"`
UserId int64 `json:"userid"`
VenueId int64 `json:"venue" schema:"venue"`
Verfied bool `json:"verified"`
Accepted bool `json:"accepted"`
}
type PhotoUrl struct {
Url string `json:"url"`
Size Rect `json:"size"`
}
type Rect struct {
W int `json:"w"`
H int `json:"h"`
}
func NewThali(id int64) *Thali {
return &Thali{Id: id}
}
//Validate checks u for errors optionally against v. If len(v)==0 then all fields of u to be checked (CREATE). If len(v)==1, then only provided fields of u to be checked and empty fields to be replaced by those of v (UPDATE)
func (t *Thali) Validate(v ...interface{}) error {
if len(v) == 0 { // CREATE
name := t.Name
if len(name) < 3 {
return DSErr{When: time.Now(), What: "validate venue invalid name "}
}
if t.VenueId == int64(0) || t.UserId == int64(0) {
return DSErr{When: time.Now(), What: "validate thali missing venue id "}
}
return nil
} else { // UPDATE
v0 := v[0]
if reflect.TypeOf(v0).Kind() != reflect.Ptr {
return DSErr{When: time.Now(), What: "validate thali pointer reqd"}
}
s := reflect.TypeOf(v0).Elem()
if _, ok := entities[s.Name()]; !ok {
return DSErr{When: time.Now(), What: "validate want thali got " + s.Name()}
}
switch s.Name() {
case "Thali":
v0v := reflect.ValueOf(v0).Elem()
if v0v.Kind() != reflect.Struct {
return DSErr{When: time.Now(), What: "validate needs struct arg got " + v0v.Kind().String()}
}
if t.Id == int64(-999) {
if t.Name == v0v.FieldByName("Name").String() {
return nil
} else {
return DSErr{When: time.Now(), What: "delete validate name " + t.Name}
}
}
set := 0
for i := 0; i < v0v.NumField(); i++ {
uu := reflect.ValueOf(t).Elem()
fi := uu.Field(i)
vi := v0v.Field(i)
if reflect.DeepEqual(fi.Interface(), reflect.Zero(fi.Type()).Interface()) {
if vi.IsValid() {
fi.Set(vi)
set++
}
}
}
name := t.Name
if len(name) < 3 {
return DSErr{When: time.Now(), What: "validate venue invalid name "}
}
if t.VenueId == int64(0) || t.UserId == int64(0) {
return DSErr{When: time.Now(), What: "validate thali missing venue id "}
}
return nil
default:
return DSErr{When: time.Now(), What: "validate want thali got : " + s.Name()}
}
return nil
}
}
|
package vault
import (
"io/ioutil"
"log"
"os"
"github.com/dollarshaveclub/pvc"
"github.com/pkg/errors"
"github.com/dollarshaveclub/furan/lib/config"
)
func getVaultClient(vaultConfig *config.Vaultconfig) (*pvc.SecretsClient, error) {
var opts []pvc.SecretsClientOption
if vaultConfig.Addr == "" {
return nil, errors.New("vault addr missing")
}
var useVault bool
switch {
case vaultConfig.TokenAuth:
if vaultConfig.Token == "" {
return nil, errors.New("token auth specified but token is empty")
}
opts = []pvc.SecretsClientOption{pvc.WithVaultBackend(), pvc.WithVaultAuthentication(pvc.Token), pvc.WithVaultToken(vaultConfig.Token)}
useVault = true
case vaultConfig.AppID != "" && vaultConfig.UserIDPath != "":
opts = []pvc.SecretsClientOption{pvc.WithVaultBackend(), pvc.WithVaultAuthentication(pvc.AppID), pvc.WithVaultAppID(vaultConfig.AppID), pvc.WithVaultUserIDPath(vaultConfig.UserIDPath)}
useVault = true
case vaultConfig.K8sJWTPath != "" && vaultConfig.K8sRole != "":
jwt, err := ioutil.ReadFile(vaultConfig.K8sJWTPath)
if err != nil {
return nil, errors.Wrap(err, "error reading JWT file")
}
opts = []pvc.SecretsClientOption{pvc.WithVaultBackend(), pvc.WithVaultAuthentication(pvc.K8s), pvc.WithVaultK8sAuth(string(jwt), vaultConfig.K8sRole), pvc.WithVaultK8sAuthPath(vaultConfig.K8sAuthPath)}
useVault = true
case vaultConfig.EnvVars:
opts = []pvc.SecretsClientOption{pvc.WithEnvVarBackend()}
case vaultConfig.JSONFile != "":
opts = []pvc.SecretsClientOption{pvc.WithJSONFileBackend(), pvc.WithJSONFileLocation(vaultConfig.JSONFile)}
default:
return nil, errors.New("no authentication method was provided")
}
if useVault {
opts = append(opts, pvc.WithVaultHost(vaultConfig.Addr))
opts = append(opts, pvc.WithVaultAuthRetries(5))
opts = append(opts, pvc.WithVaultAuthRetryDelay(2))
}
opts = append(opts, pvc.WithMapping(vaultConfig.VaultPathPrefix+"{{ .ID }}"))
return pvc.NewSecretsClient(opts...)
}
// SetupVault does generic Vault setup (all subcommands)
func SetupVault(vaultConfig *config.Vaultconfig, awsConfig *config.AWSConfig, dockerConfig *config.Dockerconfig, gitConfig *config.Gitconfig, serverConfig *config.Serverconfig, awscredsprefix string) {
sc, err := getVaultClient(vaultConfig)
if err != nil {
log.Fatalf("Error creating Vault client: %v", err)
}
ght, err := sc.Get(gitConfig.TokenVaultPath)
if err != nil {
log.Fatalf("Error getting GitHub token: %v", err)
}
dcc, err := sc.Get(dockerConfig.DockercfgVaultPath)
if err != nil {
log.Fatalf("Error getting dockercfg: %v", err)
}
gitConfig.Token = string(ght)
dockerConfig.DockercfgRaw = string(dcc)
ak, err := sc.Get(awscredsprefix + "/access_key_id")
if err != nil {
log.Fatalf("Error getting AWS access key ID: %v", err)
}
sk, err := sc.Get(awscredsprefix + "/secret_access_key")
if err != nil {
log.Fatalf("Error getting AWS secret access key: %v", err)
}
awsConfig.AccessKeyID = string(ak)
awsConfig.SecretAccessKey = string(sk)
}
func GetSumoURL(vaultConfig *config.Vaultconfig, serverConfig *config.Serverconfig) {
sc, err := getVaultClient(vaultConfig)
if err != nil {
log.Fatalf("Error creating Vault client: %v", err)
}
scu, err := sc.Get(serverConfig.VaultSumoURLPath)
if err != nil {
log.Fatalf("Error getting SumoLogic collector URL: %v", err)
}
serverConfig.SumoURL = string(scu)
}
// WriteTLSCert fetches the TLS cert and key data from vault and writes to temporary files, the paths of which are returned
func WriteTLSCert(vaultConfig *config.Vaultconfig, serverConfig *config.Serverconfig) (string, string) {
sc, err := getVaultClient(vaultConfig)
if err != nil {
log.Fatalf("Error creating Vault client: %v", err)
}
cert, err := sc.Get(serverConfig.VaultTLSCertPath)
if err != nil {
log.Fatalf("Error getting TLS certificate: %v", err)
}
key, err := sc.Get(serverConfig.VaultTLSKeyPath)
if err != nil {
log.Fatalf("Error getting TLS key: %v", err)
}
cf, err := ioutil.TempFile("", "tls-cert")
if err != nil {
log.Fatalf("Error creating TLS certificate temp file: %v", err)
}
defer cf.Close()
_, err = cf.Write(cert)
if err != nil {
log.Fatalf("Error writing TLS certificate temp file: %v", err)
}
kf, err := ioutil.TempFile("", "tls-key")
if err != nil {
log.Fatalf("Error creating TLS key temp file: %v", err)
}
defer kf.Close()
_, err = kf.Write(key)
if err != nil {
log.Fatalf("Error writing TLS key temp file: %v", err)
}
return cf.Name(), kf.Name()
}
// RmTempFiles cleans up temp files
func RmTempFiles(f1 string, f2 string) {
for _, v := range []string{f1, f2} {
err := os.Remove(v)
if err != nil {
log.Printf("Error removing file: %v", v)
}
}
}
|
package model
// FieldType Information about the type of a field
type FieldType struct {
// Name The name of the field type
Name string
// VariableLength Whether the field is variable length
VariableLength bool
// FixedLength If fixed length field, otherwise -1
FixedLength int
}
// ConvBoolToBytes convert the boolean value to a byte array
func ConvBoolToBytes(value bool) []byte {
b := make([]byte, 1)
if value {
b[0] = 1
} else {
b[0] = 0
}
return b
}
|
package main
import (
"context"
"strings"
"time"
"github.com/yandex-cloud/examples/serverless/serverless_voximplant/scheme"
"github.com/yandex-cloud/ydb-go-sdk"
"github.com/yandex-cloud/ydb-go-sdk/table"
)
func newSlots(ctx context.Context, req *slotsRequest) ([]*scheme.Entry, error) {
query, params, err := newSlotsQuery(req)
if err != nil {
return nil, err
}
var entries []*scheme.Entry
err = table.Retry(ctx, sessPool, table.OperationFunc(func(ctx context.Context, session *table.Session) error {
txc := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx())
_, res, err := session.Execute(ctx, txc, query, params, table.WithQueryCachePolicy(table.WithQueryCachePolicyKeepInCache()))
if err != nil {
return err
}
defer res.Close()
entries = make([]*scheme.Entry, 0, res.RowCount())
for res.NextSet() {
for res.NextRow() {
entries = append(entries, new(scheme.Entry).FromYDB(res))
}
}
return nil
}))
// optional: cancel old slots
_ = cancelSlots(ctx, req.ClientID, req.CancelSlots)
if err != nil {
return nil, err
}
return entries, nil
}
func newSlotsQuery(req *slotsRequest) (query string, params *table.QueryParameters, err error) {
switch {
case len(req.ClientID) == 0:
return "", nil, newErrorBadRequest("bad request: require `clientId`")
case len(req.Spec) == 0:
return "", nil, newErrorBadRequest("bad request: require `specId`")
case len(req.Date) == 0:
return "", nil, newErrorBadRequest("bad request: require `date`")
}
date, err := time.Parse(dateLayout, req.Date)
if err != nil {
return "", nil, err
}
params = table.NewQueryParameters()
builder := new(strings.Builder)
builder.WriteString("DECLARE $client_id AS Utf8;\n")
params.Add(table.ValueParam("$client_id", ydb.UTF8Value(req.ClientID)))
builder.WriteString("DECLARE $spec_id AS Utf8;\n")
params.Add(table.ValueParam("$spec_id", ydb.UTF8Value(req.Spec)))
builder.WriteString("DECLARE $date AS Date;\n")
params.Add(table.ValueParam("$date", ydb.DateValue(ydb.Time(date).Date())))
builder.WriteString("DECLARE $curr AS Datetime;\n")
params.Add(table.ValueParam("$curr", ydb.DatetimeValue(ydb.Time(time.Now()).Datetime())))
builder.WriteString("DECLARE $till AS Datetime;\n")
params.Add(table.ValueParam("$till", ydb.DatetimeValue(ydb.Time(time.Now().Add(2*time.Minute)).Datetime())))
var place ydb.Value
if len(req.Place) > 0 {
place = ydb.UTF8Value(req.Place)
builder.WriteString("DECLARE $place_id AS Utf8;\n")
params.Add(table.ValueParam("$place_id", place))
}
var doctors ydb.Value
if len(req.Doctors) > 0 {
var docs []ydb.Value
for _, d := range req.Doctors {
docs = append(docs, ydb.UTF8Value(d))
}
doctors = ydb.ListValue(docs...)
builder.WriteString("DECLARE $doctors AS List<Utf8>;\n")
params.Add(table.ValueParam("$doctors", doctors))
}
var excluded ydb.Value
if len(req.ExcludeSlots) > 0 {
var excl []ydb.Value
for _, e := range req.ExcludeSlots {
excl = append(excl, ydb.UTF8Value(e))
}
excluded = ydb.ListValue(excl...)
builder.WriteString("DECLARE $excluded AS List<Utf8>;\n")
params.Add(table.ValueParam("$excluded", excluded))
}
// select:
builder.WriteString(`$to_update = (SELECT id, spec_id, doctor_id, place_id, ` +
"`date`" + `, at, $client_id as patient, $till AS booked_till FROM schedule VIEW booked
WHERE
spec_id = $spec_id AND ` + "`date`" + ` = $date`)
if place != nil {
builder.WriteString(` AND place_id = $place_id`)
}
if doctors != nil {
builder.WriteString(` AND doctor_id IN $doctors`)
}
if excluded != nil {
builder.WriteString(`
AND id NOT IN $excluded`)
}
builder.WriteString(`
AND (patient IS NULL OR patient = "" OR booked_till IS NULL OR booked_till < $curr)
ORDER BY at
LIMIT 2);
SELECT * FROM $to_update;
UPDATE schedule ON SELECT * FROM $to_update;
`)
return builder.String(), params, nil
}
func cancelSlots(ctx context.Context, clientID string, slots []string) (err error) {
switch {
case len(slots) == 0:
return nil
case len(clientID) == 0:
return newErrorBadRequest("bad request: require `clientId`")
}
params := table.NewQueryParameters()
var canceled []ydb.Value
for _, c := range slots {
canceled = append(canceled, ydb.UTF8Value(c))
}
params.Add(table.ValueParam("$canceled", ydb.ListValue(canceled...)))
params.Add(table.ValueParam("$client_id", ydb.UTF8Value(clientID)))
query := `DECLARE $client_id AS Utf8;
DECLARE $canceled AS List<Utf8>;
UPDATE schedule
SET patient = NULL, booked_till = NULL
WHERE id IN $canceled AND patient = $client_id;`
return table.Retry(ctx, sessPool, table.OperationFunc(func(ctx context.Context, session *table.Session) error {
txc := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx())
_, _, err := session.Execute(ctx, txc, query, params, table.WithQueryCachePolicy(table.WithQueryCachePolicyKeepInCache()))
return err
}))
}
func ackSlot(ctx context.Context, req *ackSlotRequest) (*info, error) {
query, params, err := ackSlotsQuery(req)
if err != nil {
return nil, err
}
var entry *scheme.Entry
err = table.Retry(ctx, sessPool, table.OperationFunc(func(ctx context.Context, session *table.Session) error {
txc := table.TxControl(table.BeginTx(table.WithSerializableReadWrite()), table.CommitTx())
_, res, err := session.Execute(ctx, txc, query, params, table.WithQueryCachePolicy(table.WithQueryCachePolicyKeepInCache()))
if err != nil {
return err
}
defer res.Close()
if res.RowCount() != 1 {
// something went wrong, need to report. otherwise it's exactly the slot we asked for
return newErrorBadRequest("failed to ack slot")
}
res.NextSet()
res.NextRow()
entry = new(scheme.Entry).FromYDB(res)
return nil
}))
// optional: cancel old slots
_ = cancelSlots(ctx, req.ClientID, req.CancelSlots)
if err != nil {
return nil, err
}
return slotInfo(ctx, entry)
}
func ackSlotsQuery(req *ackSlotRequest) (query string, params *table.QueryParameters, err error) {
switch {
case len(req.SlotID) == 0:
return "", nil, newErrorBadRequest("bad request: require `slotId`")
case len(req.ClientID) == 0:
return "", nil, newErrorBadRequest("bad request: require `clientId`")
}
query = `DECLARE $slot_id AS Utf8;
DECLARE $client_id AS Utf8;
$slot = (SELECT id, spec_id, doctor_id, place_id, ` +
"`date`" + `, at, patient, at AS booked_till FROM schedule
WHERE id = $slot_id AND patient = $client_id
LIMIT 1);
SELECT * FROM $slot;
UPDATE schedule ON SELECT * FROM $slot;
`
params = table.NewQueryParameters()
params.Add(table.ValueParam("$client_id", ydb.UTF8Value(req.ClientID)))
params.Add(table.ValueParam("$slot_id", ydb.UTF8Value(req.SlotID)))
return query, params, nil
}
type info struct {
At time.Time `json:"at"`
Place string `json:"place"`
Spec string `json:"spec"`
Doctor string `json:"doctor"`
}
func slotInfo(ctx context.Context, entry *scheme.Entry) (*info, error) {
if entry == nil {
return nil, newErrorBadRequest("nil slot")
}
doc, err := getDoc(ctx, entry.DoctorID)
if err != nil {
return nil, err
}
place, err := getPlace(ctx, entry.PlaceID)
if err != nil {
return nil, err
}
spec, err := getSpec(ctx, entry.SpecID)
if err != nil {
return nil, err
}
return &info{
At: entry.At,
Place: place.Name,
Spec: spec.Name,
Doctor: doc.Name,
}, nil
}
|
package main
import (
"os"
"fmt"
"strconv"
"math"
)
func assert(id int, x bool) {
if x == false {
fmt.Printf("Assertion %v failed!\n", id)
}
}
func min(x,y int) int {
if x < y {
return x
}
return y
}
func block(seq ElementSlice, i, n_blocks int) (ElementSlice, int) {
n := len(seq)
stride := n / n_blocks
start := i * stride
end := start + stride
if i+1 == n_blocks {
end = n
}
return seq[start:end], start
}
func string_to_int(s string) int {
x, err := strconv.Atoi(s)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return x
}
func hash64(u uint64) uint64 {
v := u * 3935559000370003845 + 2691343689449507681
v ^= v >> 21
v ^= v << 37
v ^= v >> 4
v *= 4768777513237032717
v ^= v << 20
v ^= v >> 41
v ^= v << 5
return v
}
func hash32(x int32) int32 {
return int32(hash64(uint64(x)) % math.MaxInt32)
}
func barrier(done chan bool, n int) {
for i:=0;i<n;i++ { <-done }
}
|
package cmd
import (
"encoding/json"
"fmt"
"log"
"strings"
"time"
calevents "github.com/connor-cahill/goCal/services"
"github.com/spf13/cobra"
)
//Event struct for displaying events
type Event struct {
Summary string `json:"summary"`
Start EventTime `json:"start"`
End EventTime `json:"end"`
}
//EventTime is a time object for the event
type EventTime struct {
Time string `json:"dateTime"`
}
var showCmd = &cobra.Command{
Use: "show",
Short: "prints all upcoming events to terminal",
Run: func(cmd *cobra.Command, args []string) {
events, err := calevents.Index()
if err != nil {
log.Fatalln(err)
}
// event to be unmarshaled
var event Event
// list of events to print to terminal
// var eventList []Event
for i, e := range events {
// unmarshal json into event struct
err = json.Unmarshal(e, &event)
if err != nil {
log.Fatalln(err)
}
// check if time field is empty
if event.Start.Time == "" {
// skip all time parsing stuff
fmt.Printf("%d. %s -- All Day Event", i + 1, event.Summary)
} else {
// split the time strings at -
st := strings.Split(event.Start.Time, "-")
et := strings.Split(event.End.Time, "-")
// remove the last part of the time string
st = st[:len(st)-1]
et = et[:len(et)-1]
// parse the time strings into a time.Time
sTime, err := time.Parse("2006-01-02T15:04:05", strings.Join(st, "-"))
if err != nil {
log.Fatalln(err)
}
eTime, err := time.Parse("2006-01-02T15:04:05", strings.Join(et, "-"))
if err != nil {
log.Fatalln(err)
}
var startTime []int
var endTime []int
// Get the hour and minute
hr, min, _ := sTime.Clock()
// if hour is greater than 12 subtract 12
if hr > 12 {
hr -= 12
}
// append pieces of time to slice
startTime = append(startTime, hr)
startTime = append(startTime, min)
// Same as above but for the ending time
hr, min, _ = eTime.Clock()
if hr > 12 {
hr -= 12
}
endTime = append(endTime, hr)
endTime = append(endTime, min)
// joins the slice of ints into a string formatted hh:mm
starting := strings.Trim(strings.Join(strings.Split(fmt.Sprint(startTime), " "), ":"), "[]")
ending := strings.Trim(strings.Join(strings.Split(fmt.Sprint(endTime), " "), ":"), "[]")
// prints 1. EventSummary
fmt.Printf("%d. %s -- %s - %s\n", i+1, event.Summary, starting, ending)
}
}
},
}
// Adds show command to root command
func init() {
RootCmd.AddCommand(showCmd)
}
|
package main
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/integration/flows"
"github.com/pomerium/pomerium/internal/httputil"
)
func TestQueryStringParams(t *testing.T) {
ctx := context.Background()
ctx, clearTimeout := context.WithTimeout(ctx, time.Second*30)
defer clearTimeout()
qs := url.Values{
"q1": {"a&b&c"},
"q2": {"x?y?z"},
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://httpdetails.localhost.pomerium.io/?"+qs.Encode(), nil)
if err != nil {
t.Fatal(err)
}
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
var result struct {
Query map[string]string
}
err = json.NewDecoder(res.Body).Decode(&result)
if !assert.NoError(t, err) {
return
}
assert.Equal(t, map[string]string{
"q1": "a&b&c",
"q2": "x?y?z",
}, result.Query,
"expected custom request header to be sent upstream")
}
func TestCORS(t *testing.T) {
ctx := context.Background()
ctx, clearTimeout := context.WithTimeout(ctx, time.Second*30)
defer clearTimeout()
t.Run("enabled", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodOptions, "https://httpdetails.localhost.pomerium.io/cors-enabled", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
req.Header.Set("Origin", "https://httpdetails.localhost.pomerium.io")
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
assert.Equal(t, http.StatusOK, res.StatusCode, "unexpected status code")
})
t.Run("disabled", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodOptions, "https://httpdetails.localhost.pomerium.io/cors-disabled", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
req.Header.Set("Origin", "https://httpdetails.localhost.pomerium.io")
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
assert.NotEqual(t, http.StatusOK, res.StatusCode, "unexpected status code")
})
}
func TestPreserveHostHeader(t *testing.T) {
ctx := context.Background()
ctx, clearTimeout := context.WithTimeout(ctx, time.Second*30)
defer clearTimeout()
t.Run("enabled", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://httpdetails.localhost.pomerium.io/preserve-host-header-enabled", nil)
if err != nil {
t.Fatal(err)
}
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
var result struct {
Headers struct {
Host string `json:"host"`
} `json:"headers"`
}
err = json.NewDecoder(res.Body).Decode(&result)
if !assert.NoError(t, err) {
return
}
assert.Equal(t, "httpdetails.localhost.pomerium.io", result.Headers.Host,
"destination host should be preserved in %v", result)
})
t.Run("disabled", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://httpdetails.localhost.pomerium.io/preserve-host-header-disabled", nil)
if err != nil {
t.Fatal(err)
}
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
var result struct {
Headers struct {
Host string `json:"host"`
} `json:"headers"`
}
err = json.NewDecoder(res.Body).Decode(&result)
if !assert.NoError(t, err) {
return
}
assert.NotEqual(t, "httpdetails.localhost.pomerium.io", result.Headers.Host,
"destination host should not be preserved in %v", result)
})
}
func TestSetRequestHeaders(t *testing.T) {
ctx := context.Background()
ctx, clearTimeout := context.WithTimeout(ctx, time.Second*30)
defer clearTimeout()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://httpdetails.localhost.pomerium.io/", nil)
if err != nil {
t.Fatal(err)
}
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
var result struct {
Headers map[string]string `json:"headers"`
}
err = json.NewDecoder(res.Body).Decode(&result)
if !assert.NoError(t, err) {
return
}
assert.Equal(t, "custom-request-header-value", result.Headers["x-custom-request-header"],
"expected custom request header to be sent upstream")
}
func TestRemoveRequestHeaders(t *testing.T) {
ctx := context.Background()
ctx, clearTimeout := context.WithTimeout(ctx, time.Second*30)
defer clearTimeout()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://httpdetails.localhost.pomerium.io/", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Add("X-Custom-Request-Header-To-Remove", "foo")
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
var result struct {
Headers map[string]string `json:"headers"`
}
err = json.NewDecoder(res.Body).Decode(&result)
if !assert.NoError(t, err) {
return
}
_, exist := result.Headers["X-Custom-Request-Header-To-Remove"]
assert.False(t, exist, "expected X-Custom-Request-Header-To-Remove not to be present.")
}
func TestWebsocket(t *testing.T) {
ctx := context.Background()
ctx, clearTimeout := context.WithTimeout(ctx, time.Second*30)
defer clearTimeout()
t.Run("disabled", func(t *testing.T) {
ws, _, err := (&websocket.Dialer{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}).DialContext(ctx, "wss://disabled-ws-echo.localhost.pomerium.io", nil)
if !assert.Error(t, err, "expected bad handshake when websocket is not enabled") {
ws.Close()
return
}
})
t.Run("enabled", func(t *testing.T) {
ws, _, err := (&websocket.Dialer{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}).DialContext(ctx, "wss://enabled-ws-echo.localhost.pomerium.io", nil)
if !assert.NoError(t, err, "expected no error when creating websocket") {
return
}
defer ws.Close()
msg := "hello world"
err = ws.WriteJSON("hello world")
assert.NoError(t, err, "expected no error when writing json to websocket")
err = ws.ReadJSON(&msg)
assert.NoError(t, err, "expected no error when reading json from websocket")
})
}
func TestGoogleCloudRun(t *testing.T) {
ctx := context.Background()
ctx, clearTimeout := context.WithTimeout(ctx, time.Second*30)
defer clearTimeout()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://cloudrun.localhost.pomerium.io/", nil)
if err != nil {
t.Fatal(err)
}
res, err := getClient(t).Do(req)
if !assert.NoError(t, err, "unexpected http error") {
return
}
defer res.Body.Close()
var result struct {
Headers map[string]string `json:"headers"`
}
err = json.NewDecoder(res.Body).Decode(&result)
if !assert.NoError(t, err) {
return
}
if result.Headers["x-idp"] == "google" {
assert.NotEmpty(t, result.Headers["authorization"], "expected authorization header when cloudrun is enabled")
}
}
func TestLoadBalancer(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), time.Minute*10)
defer clearTimeout()
getDistribution := func(t *testing.T, path string) map[string]float64 {
client := getClient(t)
distribution := map[string]float64{}
res, err := flows.Authenticate(ctx, client,
mustParseURL("https://httpdetails.localhost.pomerium.io/"+path),
flows.WithEmail("user1@dogs.test"))
if !assert.NoError(t, err) {
return distribution
}
_, _ = io.ReadAll(res.Body)
_ = res.Body.Close()
for i := 0; i < 100; i++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://httpdetails.localhost.pomerium.io/"+path, nil)
if !assert.NoError(t, err) {
return distribution
}
res, err = client.Do(req)
if !assert.NoError(t, err) {
return distribution
}
defer res.Body.Close()
bs, err := io.ReadAll(res.Body)
if !assert.NoError(t, err) {
return distribution
}
var result struct {
Hostname string `json:"hostname"`
}
err = json.Unmarshal(bs, &result)
if !assert.NoError(t, err, "invalid json: %s", bs) {
return distribution
}
distribution[result.Hostname]++
}
return distribution
}
t.Run("round robin", func(t *testing.T) {
distribution := getDistribution(t, "round-robin")
var xs []float64
for _, x := range distribution {
xs = append(xs, x)
}
assert.Lessf(t, standardDeviation(xs), 10.0, "should distribute requests evenly, got: %v",
distribution)
})
t.Run("ring hash", func(t *testing.T) {
distribution := getDistribution(t, "ring-hash")
assert.Lenf(t, distribution, 1, "should distribute requests to a single backend, got: %v",
distribution)
})
t.Run("maglev", func(t *testing.T) {
distribution := getDistribution(t, "maglev")
assert.Lenf(t, distribution, 1, "should distribute requests to a single backend, got: %v",
distribution)
})
}
func TestDownstreamClientCA(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), time.Minute*10)
defer clearTimeout()
t.Run("no client cert", func(t *testing.T) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://client-cert-required.localhost.pomerium.io/", nil)
require.NoError(t, err)
res, err := getClient(t).Do(req)
require.NoError(t, err)
res.Body.Close()
assert.Equal(t, httputil.StatusInvalidClientCertificate, res.StatusCode)
})
t.Run("untrusted client cert", func(t *testing.T) {
// Configure an http.Client with an untrusted client certificate.
cert := loadCertificate(t, "downstream-2-client")
client, transport := getClientWithTransport(t)
transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://client-cert-required.localhost.pomerium.io/", nil)
require.NoError(t, err)
res, err := client.Do(req)
require.NoError(t, err)
res.Body.Close()
assert.Equal(t, httputil.StatusInvalidClientCertificate, res.StatusCode)
})
t.Run("valid client cert", func(t *testing.T) {
// Configure an http.Client with a trusted client certificate.
cert := loadCertificate(t, "downstream-1-client")
client, transport := getClientWithTransport(t)
transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
res, err := flows.Authenticate(ctx, client,
mustParseURL("https://client-cert-required.localhost.pomerium.io/"),
flows.WithEmail("user1@dogs.test"))
require.NoError(t, err)
defer res.Body.Close()
var result struct {
Path string `json:"path"`
}
err = json.NewDecoder(res.Body).Decode(&result)
if !assert.NoError(t, err) {
return
}
assert.Equal(t, "/", result.Path)
})
t.Run("revoked client cert", func(t *testing.T) {
// Configure an http.Client with a revoked client certificate.
cert := loadCertificate(t, "downstream-1-client-revoked")
client, transport := getClientWithTransport(t)
transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://client-cert-required.localhost.pomerium.io/", nil)
require.NoError(t, err)
res, err := client.Do(req)
require.NoError(t, err)
res.Body.Close()
assert.Equal(t, httputil.StatusInvalidClientCertificate, res.StatusCode)
})
}
func TestMultipleDownstreamClientCAs(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), time.Minute*10)
defer clearTimeout()
// Initializes a new http.Client with the given certificate.
newClientWithCert := func(certName string) *http.Client {
cert := loadCertificate(t, certName)
client, transport := getClientWithTransport(t)
transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
return client
}
// Asserts that we get a successful JSON response from the httpdetails
// service, matching the given path.
assertOK := func(t *testing.T, res *http.Response, err error, path string) {
require.NoError(t, err, "unexpected http error")
defer res.Body.Close()
var result struct {
Path string `json:"path"`
}
err = json.NewDecoder(res.Body).Decode(&result)
require.NoError(t, err)
assert.Equal(t, path, result.Path)
}
t.Run("cert1", func(t *testing.T) {
client := newClientWithCert("downstream-1-client")
// With cert1, we should get a valid response for the /ca1 path
// (after login).
res, err := flows.Authenticate(ctx, client,
mustParseURL("https://client-cert-overlap.localhost.pomerium.io/ca1"),
flows.WithEmail("user1@dogs.test"))
assertOK(t, res, err, "/ca1")
// With cert1, we should get an HTML error page for the /ca2 path.
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://client-cert-overlap.localhost.pomerium.io/ca2", nil)
require.NoError(t, err)
res, err = client.Do(req)
require.NoError(t, err, "unexpected http error")
res.Body.Close()
assert.Equal(t, httputil.StatusInvalidClientCertificate, res.StatusCode)
})
t.Run("cert2", func(t *testing.T) {
client := newClientWithCert("downstream-2-client")
// With cert2, we should get an HTML error page for the /ca1 path
// (before login).
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://client-cert-overlap.localhost.pomerium.io/ca1", nil)
require.NoError(t, err)
res, err := client.Do(req)
require.NoError(t, err, "unexpected http error")
res.Body.Close()
assert.Equal(t, httputil.StatusInvalidClientCertificate, res.StatusCode)
// With cert2, we should get a valid response for the /ca2 path
// (after login).
res, err = flows.Authenticate(ctx, client,
mustParseURL("https://client-cert-overlap.localhost.pomerium.io/ca2"),
flows.WithEmail("user1@dogs.test"))
assertOK(t, res, err, "/ca2")
})
t.Run("no cert", func(t *testing.T) {
client := getClient(t)
// Without a client certificate, both paths should return an HTML error
// page (no login redirect).
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
"https://client-cert-overlap.localhost.pomerium.io/ca1", nil)
require.NoError(t, err)
res, err := client.Do(req)
require.NoError(t, err, "unexpected http error")
res.Body.Close()
assert.Equal(t, httputil.StatusInvalidClientCertificate, res.StatusCode)
req, err = http.NewRequestWithContext(ctx, http.MethodGet,
"https://client-cert-overlap.localhost.pomerium.io/ca2", nil)
require.NoError(t, err)
res, err = client.Do(req)
require.NoError(t, err, "unexpected http error")
res.Body.Close()
assert.Equal(t, httputil.StatusInvalidClientCertificate, res.StatusCode)
})
}
func TestPomeriumJWT(t *testing.T) {
ctx, clearTimeout := context.WithTimeout(context.Background(), time.Second*30)
defer clearTimeout()
client := getClient(t)
// Obtain a Pomerium attestation JWT from the httpdetails service.
res, err := flows.Authenticate(ctx, client,
mustParseURL("https://restricted-httpdetails.localhost.pomerium.io/"),
flows.WithEmail("user1@dogs.test"))
require.NoError(t, err)
defer res.Body.Close()
var m map[string]interface{}
err = json.NewDecoder(res.Body).Decode(&m)
require.NoError(t, err)
headers, ok := m["headers"].(map[string]interface{})
require.True(t, ok)
headerJWT, ok := headers["x-pomerium-jwt-assertion"].(string)
require.True(t, ok)
// Manually decode the payload section of the JWT in order to verify the
// format of the iat and exp timestamps.
// (https://github.com/pomerium/pomerium/issues/4149)
p := rawJWTPayload(t, headerJWT)
var digitsOnly = regexp.MustCompile(`^\d+$`)
assert.Regexp(t, digitsOnly, p["iat"])
assert.Regexp(t, digitsOnly, p["exp"])
// Also verify the issuer and audience claims.
assert.Equal(t, "restricted-httpdetails.localhost.pomerium.io", p["iss"])
assert.Equal(t, "restricted-httpdetails.localhost.pomerium.io", p["aud"])
// Obtain a Pomerium attestation JWT from the /.pomerium/jwt endpoint. The
// contents should be identical to the JWT header (except possibly the
// timestamps). (https://github.com/pomerium/pomerium/issues/4210)
res, err = client.Get("https://restricted-httpdetails.localhost.pomerium.io/.pomerium/jwt")
require.NoError(t, err)
defer res.Body.Close()
spaJWT, err := io.ReadAll(res.Body)
require.NoError(t, err)
p2 := rawJWTPayload(t, string(spaJWT))
// Remove timestamps before comparing.
delete(p, "iat")
delete(p, "exp")
delete(p2, "iat")
delete(p2, "exp")
assert.Equal(t, p, p2)
}
func rawJWTPayload(t *testing.T, jwt string) map[string]interface{} {
t.Helper()
s := strings.Split(jwt, ".")
require.Equal(t, 3, len(s), "unexpected JWT format")
payload, err := base64.RawURLEncoding.DecodeString(s[1])
require.NoError(t, err, "JWT payload could not be decoded")
d := json.NewDecoder(bytes.NewReader(payload))
d.UseNumber()
var decoded map[string]interface{}
err = d.Decode(&decoded)
require.NoError(t, err, "JWT payload could not be deserialized")
return decoded
}
func TestUpstreamViaIPAddress(t *testing.T) {
// Verify that we can make a successful request to a route with a 'to' URL
// that uses https with an IP address.
client := getClient(t)
res, err := client.Get("https://httpdetails-ip-address.localhost.pomerium.io/")
require.NoError(t, err, "unexpected http error")
defer res.Body.Close()
var result struct {
Headers map[string]string `json:"headers"`
Protocol string `json:"protocol"`
}
err = json.NewDecoder(res.Body).Decode(&result)
require.NoError(t, err)
assert.Equal(t, "https", result.Protocol)
}
|
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"encoding/xml"
"html/template"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"github.com/unrolled/render"
)
var rendering *render.Render
var store = sessions.NewCookieStore([]byte("session-key"))
func contains(dict map[string]string, i string) bool {
if _, ok := dict[i]; ok {
return true
} else {
return false
}
}
func int64toString(value int64) string {
return strconv.FormatInt(value, 10)
}
func int64InSlice(i int64, list []int64) bool {
for _, value := range list {
if value == i {
return true
}
}
return false
}
type appError struct {
err error
status int
json string
template string
binding interface{}
}
type appHandler func(http.ResponseWriter, *http.Request) *appError
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil {
log.Print(e.err)
if e.status != 0 {
if e.json != "" {
rendering.JSON(w, e.status, e.json)
} else {
rendering.HTML(w, e.status, e.template, e.binding)
}
}
}
}
func RecoverHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, http.StatusText(500), 500)
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func LoginMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/login" || strings.HasPrefix(r.URL.Path, "/app") {
h.ServeHTTP(w, r)
} else {
session, err := store.Get(r, "session-name")
if err != nil {
rendering.HTML(w, http.StatusInternalServerError, "error", http.StatusInternalServerError)
}
if _, ok := session.Values["AccessKey"]; ok {
h.ServeHTTP(w, r)
} else {
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
}
}
})
}
type ECS struct {
Hostname string `json:"hostname"`
EndPoint string `json:"endpoint"`
Namespace string `json:"namespace"`
}
var hostname string
func main() {
var port = ""
// get all the environment data
port = "8001" //os.Getenv("PORT")
hostname, _ = os.Hostname()
// See http://godoc.org/github.com/unrolled/render
rendering = render.New(render.Options{Directory: "app/templates"})
// See http://www.gorillatoolkit.org/pkg/mux
router := mux.NewRouter()
router.HandleFunc("/", Index)
router.HandleFunc("/login", Login)
router.HandleFunc("/api/v1/ecs", Ecs).Methods("GET")
router.Handle("/api/v1/buckets", appHandler(Buckets)).Methods("GET")
router.Handle("/api/v1/createbucket", appHandler(CreateBucket)).Methods("POST")
router.PathPrefix("/app/").Handler(http.StripPrefix("/app/", http.FileServer(http.Dir("app"))))
n := negroni.Classic()
n.UseHandler(RecoverHandler(LoginMiddleware(router)))
n.Run(":" + port)
log.Printf("Listening on port " + port)
}
type UserSecretKeysResult struct {
XMLName xml.Name `xml:"user_secret_keys"`
SecretKey1 string `xml:"secret_key_1"`
SecretKey2 string `xml:"secret_key_2"`
}
type UserSecretKeyResult struct {
XMLName xml.Name `xml:"user_secret_key"`
SecretKey string `xml:"secret_key"`
}
type credentials struct {
AccessKey string
SecretKey1 string
SecretKey2 string
}
var tpl *template.Template
var ecs ECS
func init() {
tpl = template.Must(template.ParseFiles("app/templates/index.tmpl"))
}
func Ecs(w http.ResponseWriter, r *http.Request) {
rendering.JSON(w, http.StatusOK, ecs)
}
// Login using an AD or object user
func Login(w http.ResponseWriter, r *http.Request) {
// If informaton received from the form
if r.Method == "POST" {
session, err := store.Get(r, "session-name")
if err != nil {
rendering.HTML(w, http.StatusInternalServerError, "error", http.StatusInternalServerError)
}
r.ParseForm()
authentication := r.FormValue("authentication")
user := r.FormValue("user")
password := r.FormValue("password")
endpoint := r.FormValue("endpoint")
// For AD authentication, needs to retrieve the S3 secret key from ECS using the ECS management API
if authentication == "ad" { //ktu ndodh ekzekutimi i kodit
url, err := url.Parse(endpoint)
if err != nil {
rendering.HTML(w, http.StatusOK, "login", "Check the endpoint")
}
hostname := url.Host
if strings.Contains(hostname, ":") {
hostname = strings.Split(hostname, ":")[0]
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
// Get an authentication token from ECS
req, _ := http.NewRequest("GET", "https://"+hostname+":4443/login", nil)
req.SetBasicAuth(user, password)
resp, err := client.Do(req)
if err != nil {
log.Print(err)
}
if resp.StatusCode == 401 {
rendering.HTML(w, http.StatusOK, "login", "Check your crententials and that you're allowed to generate a secret key on ECS")
} else {
// Get the secret key from ECS
req, _ = http.NewRequest("GET", "https://"+hostname+":4443/object/secret-keys", nil)
headers := map[string][]string{}
headers["X-Sds-Auth-Token"] = []string{resp.Header.Get("X-Sds-Auth-Token")}
req.Header = headers
log.Print(headers)
resp, err = client.Do(req)
if err != nil {
log.Print(err)
}
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
secretKey := ""
userSecretKeysResult := &UserSecretKeysResult{}
xml.NewDecoder(buf).Decode(userSecretKeysResult)
secretKey = userSecretKeysResult.SecretKey1
// If a secret key doesn't exist yet for this object user, needs to generate it
if secretKey == "" {
req, _ = http.NewRequest("POST", "https://"+hostname+":4443/object/secret-keys", bytes.NewBufferString("<secret_key_create_param></secret_key_create_param>"))
headers["Content-Type"] = []string{"application/xml"}
req.Header = headers
resp, err = client.Do(req)
if err != nil {
log.Print(err)
}
buf = new(bytes.Buffer)
buf.ReadFrom(resp.Body)
userSecretKeyResult := &UserSecretKeyResult{}
xml.NewDecoder(buf).Decode(userSecretKeyResult)
secretKey = userSecretKeyResult.SecretKey
}
log.Print(secretKey)
session.Values["AccessKey"] = user
session.Values["SecretKey"] = secretKey
session.Values["Endpoint"] = endpoint
p := credentials{
AccessKey: user,
SecretKey1: secretKey,
SecretKey2: userSecretKeysResult.SecretKey2,
}
err = sessions.Save(r, w)
if err != nil {
rendering.HTML(w, http.StatusInternalServerError, "error", http.StatusInternalServerError)
}
rendering.HTML(w, http.StatusOK, "index", p)
}
// For an object user authentication, use the credentials as-is
} else {
session.Values["AccessKey"] = user
session.Values["SecretKey"] = password
session.Values["Endpoint"] = endpoint
p := credentials{
AccessKey: user,
SecretKey1: password,
SecretKey2: "",
}
err = sessions.Save(r, w)
if err != nil {
rendering.HTML(w, http.StatusInternalServerError, "error", http.StatusInternalServerError)
}
rendering.HTML(w, http.StatusOK, "index", p)
}
} else {
rendering.HTML(w, http.StatusOK, "login", nil)
}
}
//get bucket list
func Buckets(w http.ResponseWriter, r *http.Request) *appError {
session, err := store.Get(r, "session-name")
if err != nil {
return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}
}
s3 := S3{
EndPointString: ecs.EndPoint,
AccessKey: session.Values["AccessKey"].(string),
SecretKey: session.Values["SecretKey"].(string),
Namespace: ecs.Namespace,
}
response, _ := s3Request(s3, "", "GET", "/", make(map[string][]string), "")
listBucketsResp := &ListBucketsResp{}
xml.NewDecoder(strings.NewReader(response.Body)).Decode(listBucketsResp)
buckets := []string{}
for _, bucket := range listBucketsResp.Buckets {
buckets = append(buckets, bucket.Name)
}
rendering.JSON(w, http.StatusOK, buckets)
return nil
}
type NewBucket struct {
Name string `json:"bucket"`
Encrypted bool `json:"encrypted"`
}
// create bucket func.
func CreateBucket(w http.ResponseWriter, r *http.Request) *appError {
session, err := store.Get(r, "session-name")
if err != nil {
return &appError{err: err, status: http.StatusInternalServerError, json: http.StatusText(http.StatusInternalServerError)}
}
s3 := S3{
EndPointString: ecs.EndPoint,
AccessKey: session.Values["AccessKey"].(string),
SecretKey: session.Values["SecretKey"].(string),
Namespace: ecs.Namespace,
}
decoder := json.NewDecoder(r.Body)
var bucket NewBucket
err = decoder.Decode(&bucket)
if err != nil {
return &appError{err: err, status: http.StatusBadRequest, json: "Can't decode JSON data"}
}
// Add the necessary headers for Metadata Search and Access During Outage
createBucketHeaders := map[string][]string{}
createBucketHeaders["Content-Type"] = []string{"application/xml"}
createBucketHeaders["x-emc-is-stale-allowed"] = []string{"true"}
createBucketHeaders["x-emc-metadata-search"] = []string{"ObjectName,x-amz-meta-image-width;Integer,x-amz-meta-image-height;Integer,x-amz-meta-gps-latitude;Decimal,x-amz-meta-gps-longitude;Decimal"}
createBucketResponse, _ := s3Request(s3, bucket.Name, "PUT", "/", createBucketHeaders, "")
// Enable CORS after the bucket creation to allow the web browser to send requests directly to ECS
if createBucketResponse.Code == 200 {
enableBucketCorsHeaders := map[string][]string{}
enableBucketCorsHeaders["Content-Type"] = []string{"application/xml"}
corsConfiguration := `
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedHeader>*</AllowedHeader>
<ExposeHeader>x-amz-meta-image-width</ExposeHeader>
<ExposeHeader>x-amz-meta-image-height</ExposeHeader>
<ExposeHeader>x-amz-meta-gps-latitude</ExposeHeader>
<ExposeHeader>x-amz-meta-gps-longitude</ExposeHeader>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
</CORSRule>
</CORSConfiguration>
`
enableBucketCorsResponse, _ := s3Request(s3, bucket.Name, "PUT", "/?cors", enableBucketCorsHeaders, corsConfiguration)
if enableBucketCorsResponse.Code == 200 {
rendering.JSON(w, http.StatusOK, struct {
CorsConfiguration string `json:"cors_configuration"`
Bucket string `json:"bucket"`
}{
CorsConfiguration: corsConfiguration,
Bucket: bucket.Name,
})
} else {
return &appError{err: err, status: http.StatusBadRequest, json: "Bucket created, but CORS can't be enabled"}
}
} else {
return &appError{err: err, status: http.StatusBadRequest, json: "Bucket can't be created"}
}
return nil
}
//main index function
func Index(w http.ResponseWriter, r *http.Request) {
rendering.HTML(w, http.StatusOK, "login", nil)
}
|
package main
import (
"context"
"fmt"
calendarRpc "github.com/Azimkhan/go-calendar-grpc/internal/calendar/delivery/grpc"
"github.com/golang/protobuf/ptypes"
"google.golang.org/grpc"
"log"
"time"
)
func main() {
cc, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("could not connect: %v", err)
}
defer cc.Close()
client := calendarRpc.NewCalendarServiceClient(cc)
// list events
ListEvents(client)
// create events
now := time.Now()
id1 := CreateEvent(now, "Clean the working desk", calendarRpc.EventType_TASK, err, client)
_ = CreateEvent(now, "Meet with friends", calendarRpc.EventType_MEETING, err, client)
// list events again
ListEvents(client)
// delete one events
DeleteEvent(client, id1)
// list events again
ListEvents(client)
}
func DeleteEvent(client calendarRpc.CalendarServiceClient, id int64) {
fmt.Printf("DeleteEvent(%d)\n", id)
ctx := createContext()
req := &calendarRpc.DeleteCalendarEventRequest{
Id: id,
}
_, err := client.DeleteEvent(ctx, req)
if err != nil {
log.Fatalf("DeleteEvent() error %v", err)
}
fmt.Println(" Event deleted")
}
func CreateEvent(now time.Time, name string, eventType calendarRpc.EventType, err error, client calendarRpc.CalendarServiceClient) int64 {
fmt.Println("CreateEvent()")
ctx := createContext()
start, _ := ptypes.TimestampProto(now)
end, _ := ptypes.TimestampProto(now.Add(time.Hour))
req2 := &calendarRpc.CreateCalendarEventRequest{
Name: name,
Type: eventType,
StartTime: start,
EndTime: end,
}
response2, err := client.CreateEvent(ctx, req2)
if err != nil {
log.Fatalf("CreateEvent() error %v", err)
}
fmt.Printf(" Event created: %v\n", response2)
return response2.Id
}
func ListEvents(client calendarRpc.CalendarServiceClient) {
fmt.Println("ListEvents()")
ctx := createContext()
response1, err := client.ListEvents(ctx, &calendarRpc.ListCalendarEventRequest{})
if err != nil {
log.Fatalf("ListEvents() error %v", err)
}
PrintEvents(response1.Events)
}
func createContext() context.Context {
ctx, _ := context.WithTimeout(context.Background(), 400*time.Millisecond)
return ctx
}
func PrintEvents(events []*calendarRpc.CalendarEventObject) {
for _, event := range events {
fmt.Println(" ", event)
}
}
|
package rpubsub
import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/util"
"github.com/batchcorp/plumber/validate"
)
func (r *RedisPubsub) Write(ctx context.Context, writeOpts *opts.WriteOptions, errorCh chan<- *records.ErrorRecord, messages ...*records.WriteRecord) error {
if err := validateWriteOptions(writeOpts); err != nil {
return errors.Wrap(err, "invalid write options")
}
for _, msg := range messages {
for _, ch := range writeOpts.RedisPubsub.Args.Channels {
cmd := r.client.Publish(ctx, ch, msg.Input)
if cmd.Err() != nil {
util.WriteError(nil, errorCh, fmt.Errorf("unable to publish redis pubsub message: %s", cmd.Err()))
}
}
}
return nil
}
func validateWriteOptions(writeOpts *opts.WriteOptions) error {
if writeOpts == nil {
return validate.ErrEmptyWriteOpts
}
if writeOpts.RedisPubsub == nil {
return validate.ErrEmptyBackendGroup
}
if writeOpts.RedisPubsub.Args == nil {
return validate.ErrEmptyBackendArgs
}
if len(writeOpts.RedisPubsub.Args.Channels) == 0 {
return ErrMissingChannel
}
return nil
}
|
package cdb
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"testing"
)
type rec struct {
key string
values []string
}
var records = []rec{
{"one", []string{"1"}},
{"two", []string{"2", "22"}},
{"three", []string{"3", "33", "333"}},
}
var data []byte // set by init()
func TestCdb(t *testing.T) {
tmp, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("Failed to create temp file: %s", err)
}
defer os.Remove(tmp.Name())
// Test Make
err = Make(tmp, bytes.NewBuffer(data))
if err != nil {
t.Fatalf("Make failed: %s", err)
}
// Test reading records
c, err := Open(tmp.Name())
if err != nil {
t.Fatalf("Error opening %s: %s", tmp.Name(), err)
}
context := NewContext()
_, err = c.Data([]byte("does not exist"), context)
if err != io.EOF {
t.Fatalf("non-existent key should return io.EOF")
}
for _, rec := range records {
key := []byte(rec.key)
values := rec.values
v, err := c.Data(key, context)
if err != nil {
t.Fatalf("Record read failed: %s", err)
}
if !bytes.Equal(v, []byte(values[0])) {
t.Fatal("Incorrect value returned")
}
c.FindStart(context)
for _, value := range values {
sr, err := c.FindNext(key, context)
if err != nil {
t.Fatalf("Record read failed: %s", err)
}
data := sr
if !bytes.Equal(data, []byte(value)) {
t.Fatal("value mismatch")
}
}
// Read all values, so should get EOF
_, err = c.FindNext(key, context)
if err != io.EOF {
t.Fatalf("Expected EOF, got %s", err)
}
}
// Test Dump
if _, err = tmp.Seek(0, 0); err != nil {
t.Fatal(err)
}
buf := bytes.NewBuffer(nil)
err = Dump(buf, tmp)
if err != nil {
t.Fatalf("Dump failed: %s", err)
}
if !bytes.Equal(buf.Bytes(), data) {
t.Fatalf("Dump round-trip failed")
}
}
func TestEmptyFile(t *testing.T) {
tmp, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("Failed to create temp file: %s", err)
}
defer os.Remove(tmp.Name())
// Test Make
err = Make(tmp, bytes.NewBuffer([]byte("\n\n")))
if err != nil {
t.Fatalf("Make failed: %s", err)
}
// Check that all tables are length 0
if _, err = tmp.Seek(0, 0); err != nil {
t.Fatal(err)
}
rb := bufio.NewReader(tmp)
readNum := makeNumReader(rb)
for i := 0; i < 256; i++ {
_ = readNum() // table pointer
tableLen := readNum()
if tableLen != 0 {
t.Fatalf("table %d has non-zero length: %d", i, tableLen)
}
}
// Test reading records
c, err := Open(tmp.Name())
if err != nil {
t.Fatalf("Error opening %s: %s", tmp.Name(), err)
}
context := NewContext()
_, err = c.Data([]byte("does not exist"), context)
if err != io.EOF {
t.Fatalf("non-existent key should return io.EOF")
}
}
func init() {
b := bytes.NewBuffer(nil)
for _, rec := range records {
key := rec.key
for _, value := range rec.values {
b.WriteString(fmt.Sprintf("+%d,%d:%s->%s\n", len(key), len(value), key, value))
}
}
b.WriteByte('\n')
data = b.Bytes()
}
|
package issuer
import (
"context"
"crypto/rsa"
"github.com/pkg/errors"
"github.com/kumahq/kuma/pkg/core/resources/apis/system"
"github.com/kumahq/kuma/pkg/core/resources/manager"
"github.com/kumahq/kuma/pkg/core/resources/store"
util_rsa "github.com/kumahq/kuma/pkg/util/rsa"
)
type SigningKeyAccessor interface {
GetSigningPublicKey(serialNumber int) (*rsa.PublicKey, error)
}
type signingKeyAccessor struct {
resManager manager.ResourceManager
}
var _ SigningKeyAccessor = &signingKeyAccessor{}
func NewSigningKeyAccessor(resManager manager.ResourceManager) SigningKeyAccessor {
return &signingKeyAccessor{
resManager: resManager,
}
}
func (s *signingKeyAccessor) GetSigningPublicKey(serialNumber int) (*rsa.PublicKey, error) {
resource := system.NewGlobalSecretResource()
if err := s.resManager.Get(context.Background(), resource, store.GetBy(SigningKeyResourceKey(serialNumber))); err != nil {
if store.IsResourceNotFound(err) {
return nil, &SigningKeyNotFound{
SerialNumber: serialNumber,
}
}
return nil, errors.Wrap(err, "could not retrieve signing key")
}
key, err := util_rsa.FromPEMBytes(resource.Spec.GetData().GetValue())
if err != nil {
return nil, err
}
return &key.PublicKey, nil
}
|
package meta
import (
mydb "FILE_STORE/db"
"fmt"
)
// 文件元信息结构
type FileMeta struct {
// 文件唯一标志
FileSha1 string
FileName string
FileSize int64
Location string
UploadAt string
}
var fileMetas map[string]FileMeta
// 初始化
func init() {
fileMetas = make(map[string]FileMeta)
}
// 修改元信息
func UpdateFileMeta(fmeta FileMeta) {
fileMetas[fmeta.FileSha1] = fmeta
}
// 更新文件信息到mysql中
func UpdateFileDB(fmeta FileMeta) bool {
return mydb.OnFileUploadedFinished(fmeta.FileSha1, fmeta.FileName, fmeta.FileSize, fmeta.Location)
}
// 从mysql中查询信息
func GetFileDB(filesha1 string) (FileMeta, error) {
file, err := mydb.GetFile(filesha1)
if err != nil {
fmt.Println(err.Error())
return FileMeta{}, err
}
fmeta := FileMeta{
FileSha1: file.FileHash,
// 数据库里的类型有些不同,需要转换下
FileName: file.FileName.String,
FileSize: file.FileSize.Int64,
Location: file.FileAddr.String,
}
return fmeta, nil
}
// 通过sha1值获取元信息
func GetFileMeta(fileSha1 string) FileMeta {
return fileMetas[fileSha1]
}
// 删除fileMeta
func RemoveFileMeta(fileSha1 string) {
delete(fileMetas, fileSha1)
}
|
// Copyright 2020 Clivern. All rights reserved.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package tower
import (
"io/ioutil"
"net/http"
"github.com/clivern/walrus/core/driver"
"github.com/clivern/walrus/core/model"
"github.com/clivern/walrus/core/util"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
// Auth controller
func Auth(c *gin.Context) {
var userData model.UserData
data, _ := ioutil.ReadAll(c.Request.Body)
err := util.LoadFromJSON(&userData, data)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"correlationID": c.GetHeader("x-correlation-id"),
"errorMessage": "Error! Invalid request",
})
return
}
if !util.IsEmailValid(userData.Email) || util.IsEmpty(userData.Password) {
c.JSON(http.StatusBadRequest, gin.H{
"correlationID": c.GetHeader("x-correlation-id"),
"errorMessage": "Invalid email or password",
})
return
}
db := driver.NewEtcdDriver()
err = db.Connect()
if err != nil {
log.WithFields(log.Fields{
"correlation_id": c.GetHeader("x-correlation-id"),
"error": err.Error(),
}).Error("Internal server error")
c.JSON(http.StatusInternalServerError, gin.H{
"correlationID": c.GetHeader("x-correlation-id"),
"errorMessage": "Internal server error",
})
return
}
defer db.Close()
userStore := model.NewUserStore(db)
// Authenticate
ok, err := userStore.Authenticate(userData.Email, userData.Password)
if !ok || err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"correlationID": c.GetHeader("x-correlation-id"),
"errorMessage": "Invalid email or password",
})
return
}
// Get & Return User Data
user, err := userStore.GetUserByEmail(userData.Email)
if err != nil {
log.WithFields(log.Fields{
"correlation_id": c.GetHeader("x-correlation-id"),
"error": err.Error(),
}).Error("Internal server error")
c.JSON(http.StatusInternalServerError, gin.H{
"correlationID": c.GetHeader("x-correlation-id"),
"errorMessage": "Internal server error",
})
return
}
c.JSON(http.StatusOK, gin.H{
"id": user.ID,
"name": user.Name,
"email": user.Email,
"apiKey": user.APIKey,
"createdAt": user.CreatedAt,
"updatedAt": user.UpdatedAt,
})
}
|
package filter
import (
"regexp"
"strings"
)
//
// Filters used by the UEF
//
// TODO: - provide generic comparison from tables
// TODO: - read comparison tables from files
// try to transform strings into dc.language.iso fields
// using ISO 639-1 (two character codes)
// http://www.infoterm.info/standardization/iso_639_1_2002.php
func uefDcLanguageIso(s string) string {
t := strings.ToLower(s)
if t == "suomi" {
return "FI"
}
if t == "ruotsi" {
return "SV"
}
if t == "englanti" {
return "EN"
}
if t == "eesti, viro" {
return "ET"
}
if t == "portugali" {
return "PT"
}
if t == "espanja" {
return "ES"
}
if t == "venäjä" {
return "RU"
}
return s
}
// Peer review status from input "0" or "1"
func uefEprintStatus(s string) string {
if s == "0" {
return "http://purl.org/eprint/status/NonPeerReviewed"
} else if s == "1" {
return "http://purl.org/eprint/status/PeerReviewed"
}
return s
}
// Try to map from SoleCRIS to ePrintTypes
func uefEprintType(s string) string {
// Journal Article
if s == "Ammatilliset aikakauslehtiartikkelit" ||
s == "Muut aikakauslehtiartikkelit" ||
s == "Tieteelliset aikakauslehtiartikkelit" {
return "http://purl.org/eprint/type/JournalArticle"
}
// Book Item
if s == "Artikkelit tieteellisissä kokoomateoksissa" ||
s == "Artikkelit muissa kokoomateoksissa" {
return "http://purl.org/eprint/type/BookItem"
}
// Book
if s == "Ammatilliset kirjat" ||
s == "Tieteelliset kirjat" ||
s == "Toimitetut ammatilliset kirjat / lehden erikoisnumerot" ||
s == "Toimitetut tieteelliset kirjat / lehden erikoisnumerot" ||
s == "Yleistajuiset kirjat" {
return "http://purl.org/eprint/type/Book"
}
// Thesis
if s == "Väitöskirjat" {
return "http://purl.org/eprint/type/Thesis"
}
return s
}
// Try to map from SoleCRIS to types used in OpenAIRE
// See: https://www.kiwi.fi/display/Julkaisuarkistopalvelut/OpenAiren+vaatimat+muutokset
func uefOpenAireType(s string) string {
// Article
if s == "Tieteelliset aikakauslehtiartikkelit" ||
s == "Muut aikakauslehtiartikkelit" ||
s == "Ammatilliset aikakauslehtiartikkelit" ||
s == "Artikkelit tieteellisissä kokoomateoksissa" ||
s == "Artikkelit muissa kokoomateoksissa" {
return "article"
}
// Types of theses
if s == "Väitöskirjat" {
return "doctoralThesis"
}
if s == "Lisensiaatintutkimukset" {
return "other" // No equivalent in OpenAIRE
}
if s == "Pro gradu -tutkielmat tai vastaavat" {
return "masterThesis" // SoleCRIS might include bachelor's theses here?
}
// Book
if s == "Ammatilliset kirjat" ||
s == "Tieteelliset kirjat" ||
s == "Toimitetut ammatilliset kirjat / lehden erikoisnumerot" ||
s == "Toimitetut tieteelliset kirjat / lehden erikoisnumerot" ||
s == "Yleistajuiset kirjat" {
return "book"
}
return s
}
// Try to convert doi's to http://doi.org/xxx -format
// This filter is woefully underspecified and specific to
// UEF SoleCRIS conventions.
// See i.e. for http://stackoverflow.com/questions/27910/finding-a-doi-in-a-document-or-page
// http://blog.crossref.org/2015/08/doi-regular-expressions.html
// for guidance in writing better logic
func uefDoi(s string) string {
lc := strings.ToLower(s) // use lower case for all but simple tests
if s == "-" { // means no doi in UEF input convention
return ""
}
if strings.HasPrefix(lc, "http://") { // if it's http, leave it as it is
return s
}
if strings.HasPrefix(lc, "doi:") { // add http-prefix, trust that the rest is correct doi
return "http://doi.org/" + s[4:]
}
// try doi-regexp (does work for majority of cases, but not for all of them
if matched, _ := regexp.MatchString(`^10.\d{4,9}/[-._;()/:A-Za-z0-9]+$`, s); matched {
return "http://doi.org/" + s
}
// otherwise don't do anything
return s
}
|
package hamming
import "errors"
func Distance(a, b string) (int, error) {
if len(a) != len(b) {
return 0, errors.New("Length of two strings is different")
}
var distance int = 0
for index:=0; index<len(a); index++ {
if a[index]!=b[index] { distance++ }
}
return distance, nil
}
|
package main
import (
"database/sql"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
_ "github.com/lib/pq"
uuid "github.com/satori/go.uuid"
)
const (
host = "localhost"
port = 5432
user = "migration-user"
password = "password"
dbname = "migration-test"
)
type Beer struct {
ID uuid.UUID `json:"id"`
Name string `json:"title"`
}
type CreateBeer struct {
Title string `json:"title"`
}
func connectionString() string {
return fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
}
func getBeers() ([]Beer, error) {
beers := []Beer{}
db, err := sql.Open("postgres", connectionString())
if err != nil {
return beers, err
}
defer db.Close()
rows, err := db.Query("SELECT id, name FROM beer")
if err != nil {
return beers, err
}
for rows.Next() {
var beer Beer
if err := rows.Scan(&beer.ID, &beer.Name); err != nil {
return beers, err
}
beers = append(beers, beer)
}
return beers, nil
}
func createBeer(toCreate CreateBeer) (Beer, error) {
beer := Beer{ID: uuid.NewV4(), Name: toCreate.Title}
db, err := sql.Open("postgres", connectionString())
if err != nil {
return beer, err
}
defer db.Close()
if _, err := db.Query("INSERT INTO beer (id, name) VALUES($1, $2)", beer.ID, beer.Name); err != nil {
return beer, err
}
return beer, nil
}
func main() {
r := gin.Default()
r.GET("beer", func(c *gin.Context) {
beers, err := getBeers()
if err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
c.JSON(http.StatusOK, beers)
})
r.POST("beer", func(c *gin.Context) {
var toCreate CreateBeer
if err := c.Bind(&toCreate); err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
beer, err := createBeer(toCreate)
if err != nil {
c.AbortWithStatus(http.StatusBadRequest)
return
}
c.JSON(http.StatusOK, beer)
})
r.Run(":5003")
}
|
package channel
import (
"log"
"websocket_chat/store"
"websocket_chat/store/message"
"github.com/gorilla/websocket"
)
type Channel struct {
Conn *websocket.Conn
Send chan message.Message
}
func (this *Channel) Reader() {
var (
msg message.Message
)
for {
err := this.Conn.ReadJSON(&msg)
if err != nil {
log.Println(err)
delete(store.Clients, this.Conn)
}
this.Send <- msg
}
}
func (this *Channel) Writer() {
for {
msg := <-this.Send
for client := range store.Clients {
err := client.WriteJSON(msg)
if err != nil {
log.Println(err)
delete(store.Clients, this.Conn)
}
}
}
}
func NewChannel(conn *websocket.Conn) Channel {
channel := Channel{
Conn: conn,
Send: make(chan message.Message, 0),
}
// go channel.reader()
go channel.Writer()
return channel
}
|
package waktu
// Month int.
type Month int
const (
// Januari = 1
Januari Month = 1 + iota
// Februari = 2
Februari
// Maret = 3
Maret
// April = 4
April
// Mei = 5
Mei
// Juni = 6
Juni
// Juli = 7
Juli
// Agustus = 8
Agustus
// September = 9
September
// Oktober = 10
Oktober
// November = 11
November
// Desember = 12
Desember
)
// months var.
var months = [...]string{ //nolint:gochecknoglobals
"Januari",
"Februari",
"Maret",
"April",
"Mei",
"Juni",
"Juli",
"Agustus",
"September",
"Oktober",
"November",
"Desember",
}
// Month returns the month of the year specified by t.
func (t Time) Month() Month {
return Month(t.Time.Month())
}
// SetMonth func.
func (t *Time) SetMonth(month int) Time {
return Date(t.Year(), Month(month), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location())
}
// String func.
func (m Month) String() string {
if Januari <= m && m <= Desember {
return months[m-1]
}
buf := make([]byte, 20) //nolint:wsl
n := fmtInt(buf, uint64(m))
return "%!Month(" + string(buf[n:]) + ")" //nolint:wsl
}
|
// ANDY ZIMMELMAN 2019
package main
// https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/example_inception_inference_test.go
import (
"bytes"
"log"
tf "github.com/tensorflow/tensorflow/tensorflow/go"
"github.com/tensorflow/tensorflow/tensorflow/go/op"
)
func generateTensorFromImage(imageBuffer *bytes.Buffer, imageFormat string) (*tf.Tensor, error) {
// GENERATE TENSOR
tensor, err := tf.NewTensor(imageBuffer.String())
if err != nil {
log.Printf("Error occurred generating the new TF Tensor.")
return nil, err
}
// GENERATE GRAPH
graph, input, output, err := generateTransformImageGraph(imageFormat)
if err != nil {
log.Printf("Error occurred generating the TF graph.")
return nil, err
}
// GENERATE TF SESSION WITH NEWLY GENERATED GRAPH
session, err := tf.NewSession(graph, nil)
if err != nil {
log.Printf("Error occurred generating new TF session from graph.")
return nil, err
}
defer session.Close()
// RUN INFERENCE AND RETURN NORMALIZED OUTPUT TENSOR
normalized, err := session.Run(
map[tf.Output]*tf.Tensor{input: tensor},
[]tf.Output{output},
nil)
if err != nil {
log.Printf("Error occurred generating normalized image.")
return nil, err
}
return normalized[0], nil
}
/*
GENERATE TRANSFORM IMAGE GRAPH
RETURN THE GRAPH ALONG WITH INPUT & OUTPUT
*/
func generateTransformImageGraph(imageFormat string) (graph *tf.Graph, input, output tf.Output, err error) {
// GENERATE EMPTY NODE FOR *ROOT NODE OF GRAPH
root := op.NewScope()
// PLACEHOLDER STRING TENSOR
// STRING = ENCODED JPG/PNG IMAGE
input = op.Placeholder(root, tf.String)
// DECODE IMAGE
decode := decodeImage(imageFormat, root, input)
// APPLY NORMALIZATION
output = performOps(root, decode)
graph, err = root.Finalize()
return graph, input, output, err
}
func decodeImage(imageFormat string, root *op.Scope, input tf.Output) tf.Output {
if imageFormat == "png" {
return op.DecodePng(root, input, op.DecodePngChannels(3))
} else {
return op.DecodeJpeg(root, input, op.DecodeJpegChannels(3))
}
}
// MODEL RECIEVES 4D TENSOR OF SHAPE [BATCHSIZE, HEIGHT, WIDTH, COLORS=3]
//
// RETURN OUTPUT AFTER RESIZING & NORMALIZING
func performOps (root *op.Scope, decode tf.Output) tf.Output {
// CONSTANTS
const (
H, W = 128, 128
Mean = float32(0)
Scale = float32(255)
)
// DIV & SUB PERFORM VAL-MEAN / SCALE PER PIXEL
// APPLIES NORMALIZATION ON EACH PIXEL
return op.Div(root,
op.Sub(root,
// BILINIEAR
op.ResizeBilinear(root,
// GENERATE BATCH OF SIZE 1 BY EXPANDDIMS
op.ExpandDims(root,
// APPLY SCOPES FOR GRAPH FINALIZATION
op.Cast(root, decode, tf.Float),
op.Const(root.SubScope("make_batch"), int32(0))),
op.Const(root.SubScope("size"), []int32{H, W})),
op.Const(root.SubScope("mean"), Mean)),
op.Const(root.SubScope("scale"), Scale))
}
|
package resources
import (
"errors"
"net/http"
"github.com/manyminds/api2go"
"gopkg.in/mgo.v2/bson"
"themis/utils"
"themis/models"
"themis/database"
)
// WorkItemTypeResource for api2go routes.
type WorkItemTypeResource struct {
WorkItemTypeStorage *database.WorkItemTypeStorage
WorkItemStorage *database.WorkItemStorage
LinkTypeStorage *database.LinkTypeStorage
}
func (c WorkItemTypeResource) getFilterFromRequest(r api2go.Request) (bson.M, error) {
var filter bson.M
// Getting reference context
sourceContext, sourceContextID, thisContext := utils.ParseContext(r)
switch sourceContext {
case models.WorkItemName:
workItem, err := c.WorkItemStorage.GetOne(bson.ObjectIdHex(sourceContextID))
if (err != nil) {
return nil, err
}
if thisContext == "baseType" {
filter = bson.M{"_id": workItem.BaseTypeID}
}
case models.LinkTypeName:
linkType, err := c.LinkTypeStorage.GetOne(bson.ObjectIdHex(sourceContextID))
if (err != nil) {
return nil, err
}
if thisContext == "source_type" {
filter = bson.M{"_id": linkType.SourceWorkItemTypeID}
}
if thisContext == "target_type" {
filter = bson.M{"_id": linkType.TargetWorkItemTypeID}
}
default:
// build standard filter expression
filter = utils.BuildDbFilterFromRequest(r)
}
return filter, nil
}
// FindAll WorkItemTypes.
func (c WorkItemTypeResource) FindAll(r api2go.Request) (api2go.Responder, error) {
// build filter expression
filter, err := c.getFilterFromRequest(r)
if err != nil {
return &api2go.Response{}, err
}
workItemTypes, _ := c.WorkItemTypeStorage.GetAll(filter)
return &api2go.Response{Res: workItemTypes}, nil
}
// PaginatedFindAll can be used to load users in chunks.
// Possible success status code 200.
func (c WorkItemTypeResource) PaginatedFindAll(r api2go.Request) (uint, api2go.Responder, error) {
// build filter expression
filter, err := c.getFilterFromRequest(r)
if err != nil {
return 0, &api2go.Response{}, err
}
// parse out offset and limit
queryOffset, queryLimit, err := utils.ParsePaging(r)
if err!=nil {
return 0, &api2go.Response{}, err
}
// get the paged data from storage
result, err := c.WorkItemTypeStorage.GetAllPaged(filter, queryOffset, queryLimit)
if err!=nil {
return 0, &api2go.Response{}, err
}
// get total count for paging
allCount, err := c.WorkItemTypeStorage.GetAllCount(filter)
if err!=nil {
return 0, &api2go.Response{}, err
}
// return everything
return uint(allCount), &api2go.Response{Res: result}, nil
}
// FindOne WorkItemType.
// Possible success status code 200
func (c WorkItemTypeResource) FindOne(id string, r api2go.Request) (api2go.Responder, error) {
utils.DebugLog.Printf("Received FindOne with ID %s.", id)
res, err := c.WorkItemTypeStorage.GetOne(bson.ObjectIdHex(id))
return &api2go.Response{Res: res}, err
}
// Create a new WorkItemType.
// Possible status codes are:
// - 201 Created: Resource was created and needs to be returned
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Resource created with a client generated ID, and no fields were modified by
// the server
func (c WorkItemTypeResource) Create(obj interface{}, r api2go.Request) (api2go.Responder, error) {
workItemType, ok := obj.(models.WorkItemType)
if !ok {
return &api2go.Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
id, _ := c.WorkItemTypeStorage.Insert(workItemType)
workItemType.ID = id
return &api2go.Response{Res: workItemType, Code: http.StatusCreated}, nil
}
// Delete a WorkItemType.
// Possible status codes are:
// - 200 OK: Deletion was a success, returns meta information, currently not implemented! Do not use this
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Deletion was successful, return nothing
func (c WorkItemTypeResource) Delete(id string, r api2go.Request) (api2go.Responder, error) {
err := c.WorkItemTypeStorage.Delete(bson.ObjectIdHex(id))
return &api2go.Response{Code: http.StatusOK}, err
}
// Update a WorkItemType.
// Possible status codes are:
// - 200 OK: Update successful, however some field(s) were changed, returns updates source
// - 202 Accepted: Processing is delayed, return nothing
// - 204 No Content: Update was successful, no fields were changed by the server, return nothing
func (c WorkItemTypeResource) Update(obj interface{}, r api2go.Request) (api2go.Responder, error) {
workItemType, ok := obj.(models.WorkItemType)
if !ok {
return &api2go.Response{}, api2go.NewHTTPError(errors.New("Invalid instance given"), "Invalid instance given", http.StatusBadRequest)
}
err := c.WorkItemTypeStorage.Update(workItemType)
return &api2go.Response{Res: workItemType, Code: http.StatusNoContent}, err
}
|
package config
// based on https://cbonte.github.io/haproxy-dconv/1.6/configuration.html
func NewBackend() *Backend {
b := &Backend{
Values: make(map[string]Line, 0),
Servers: make([]*Server, 0),
}
return b
}
type Backend struct {
// name of the backend
Name string
// blindly parse all defaults for now
Values map[string]Line
Servers []*Server
}
func NewServer() *Server {
s := &Server{}
return s
}
type Server struct {
Name string
Address string
Params Line
}
// parse the lines in a default
func (me *Parser) backendSection(line Line, state *state) error {
log.Tracef("parse %s", line)
cmd := line.Command()
if cmd == "server" {
state.currentServer = NewServer()
state.currentBackend.Servers = append(state.currentBackend.Servers, state.currentServer)
state.currentServer.Name = line.Arg(1)
state.currentServer.Address = line.Arg(2)
state.currentServer.Params = line[3:]
log.Tracef("new server %+v", state.currentServer)
}
return nil
}
|
package controller
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"projja_api/model"
"strconv"
"strings"
"time"
"github.com/go-martini/martini"
"github.com/scylladb/go-set"
)
func (c *Controller) GetTask(params martini.Params, w http.ResponseWriter) (int, string) {
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
task, err := c.getTaskById(taskId)
if err != nil {
return 500, err.Error()
}
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(200, "Current task", task)
}
func (c *Controller) ChangeTaskExecutor(params martini.Params, w http.ResponseWriter, r *http.Request) (int, string) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
err := fmt.Sprintf("Unsupportable Content-Type header: %s", contentType)
log.Println(err)
return 500, err
}
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
jsonExecutor, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Println("error in reading body", err)
return 500, err.Error()
}
executor := &model.User{}
err = json.Unmarshal(jsonExecutor, executor)
if err != nil {
log.Println("error in unmarshalling")
return 500, err.Error()
}
row := c.DB.QueryRow("select executor from task where id = ?", taskId)
var oldUserId int64
err = row.Scan(&oldUserId)
if err != nil {
log.Println("error in getting userId: ", err)
return 500, err.Error()
}
result, err := c.DB.Exec(
"update task set executor = (select id from users where username = ?) where id = ?",
executor.Username,
taskId,
)
if err != nil {
log.Println("error in updating task executor: ", err)
return 500, err.Error()
}
row = c.DB.QueryRow("select id from users where username = ?", executor.Username)
var newUserId int64
err = row.Scan(&newUserId)
if err != nil {
log.Println("error in getting userId: ", err)
return 500, err.Error()
}
row = c.DB.QueryRow("select project from task where id = ?", taskId)
var projectId int64
err = row.Scan(&projectId)
if err != nil {
log.Println("error in getting projectId: ", err)
return 500, err.Error()
}
_, err = c.sendDataToStream("task", "executor", struct {
TaskId int64
OldUserId int64
NewUserId int64
ProjectId int64
}{
taskId,
oldUserId,
newUserId,
projectId,
})
if err != nil {
log.Println(err)
return 500, err.Error()
}
if err != nil {
log.Println("error in updating executor:", err)
return 500, err.Error()
}
rowsAffected, _ := result.RowsAffected()
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(200, "Task executor updated", struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
func (c *Controller) ChangeTaskDescription(params martini.Params, w http.ResponseWriter, r *http.Request) (int, string) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
err := fmt.Sprintf("Unsupportable Content-Type header: %s", contentType)
log.Println(err)
return 500, err
}
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
jsonDescription, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Println("error in reading body", err)
return 500, err.Error()
}
description := &struct {
Description string
}{}
err = json.Unmarshal(jsonDescription, description)
if err != nil {
log.Println("error in unmarshalling")
return 500, err.Error()
}
result, err := c.DB.Exec(
"update task set description = ? where id = ?",
description.Description,
taskId,
)
if err != nil {
log.Println("error in updating description:", err)
return 500, err.Error()
}
row := c.DB.QueryRow("select project from task where id = ?", taskId)
var projectId int64
err = row.Scan(&projectId)
if err != nil {
log.Println("error in getting projectId: ", err)
return 500, err.Error()
}
_, err = c.sendDataToStream("task", "description", struct {
TaskId int64
Description string
ProjectId int64
}{
taskId,
description.Description,
projectId,
})
if err != nil {
log.Println(err)
return 500, err.Error()
}
rowsAffected, _ := result.RowsAffected()
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(200, "Task description updated", struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
func (c *Controller) SetSkillsToTask(params martini.Params, w http.ResponseWriter, r *http.Request) (int, string) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
err := fmt.Sprintf("Unsupportable Content-Type header: %s", contentType)
log.Println(err)
return 500, err
}
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
jsonSkills, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Println("error in reading body", err)
return 500, err.Error()
}
skills := &struct {
Skills []string
}{}
err = json.Unmarshal(jsonSkills, skills)
if err != nil {
log.Println("error in unmarshalling")
return 500, err.Error()
}
rows, err := c.DB.Query(
"select s.skill from skill s",
)
if err != nil && err != sql.ErrNoRows {
log.Println("error in getting skills:", err)
return 500, err.Error()
}
skillsSet := set.NewStringSet()
for rows.Next() {
var skill string
err = rows.Scan(&skill)
if err != nil {
log.Println("error in scan skills:", err)
return 500, err.Error()
}
skillsSet.Add(skill)
}
newSkills := make([]string, 0)
newTaskSkills := make([]string, len(skills.Skills))
for i, skill := range skills.Skills {
skill := strings.ToLower(skill)
if !skillsSet.Has(skill) {
newSkills = append(newSkills, fmt.Sprintf("('%v')", strings.ToLower(skill)))
}
newTaskSkills[i] = fmt.Sprintf("(%v, (select s.id from skill s where s.skill = '%v'))",
taskId,
skill,
)
}
if len(newSkills) != 0 {
_, err := c.DB.Exec("insert into skill (skill) values " + strings.Join(newSkills, ", "))
if err != nil {
log.Println("error in creating new skills:", err)
return 500, err.Error()
}
}
_, err = c.DB.Exec(
"delete from task_skill where task = ?",
taskId,
)
if err != nil {
log.Println("error in deleting skills:", err)
return 500, err.Error()
}
result, err := c.DB.Exec(
"insert into task_skill (task, skill) values " +
strings.Join(newTaskSkills, ", "),
)
if err != nil {
log.Println("error in creating new task_skill:", err)
return 500, err.Error()
}
rowsAffected, _ := result.RowsAffected()
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(201, "skills set", struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
func (c *Controller) SetPreviousTaskStatus(params martini.Params, w http.ResponseWriter) (int, string) {
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
row := c.DB.QueryRow(
"select count(*) from task_status ts "+
"right join (select t.project, ts.status_level from task t "+
"left join task_status ts on ts.id = t.status where t.id = ?) "+
"t on t.project = ts.project where ts.status_level <= t.status_level - 1;",
taskId,
)
count := 0
err = row.Scan(&count)
if err != nil && err != sql.ErrNoRows {
log.Println("error in getting count of previous levels:", err)
return 500, err.Error()
}
if count == 0 {
return 500, "no such previous status"
}
result, err := c.DB.Exec(
"update task set status = (select ts.id from task_status ts "+
"right join (select t.project, ts.status_level from task t "+
"left join task_status ts on ts.id = t.status where t.id = ?) "+
"t on t.project = ts.project where ts.status_level = t.status_level - 1) where id = ?;",
taskId,
taskId,
)
if err != nil {
log.Println("error in updating status:", err)
return 500, err.Error()
}
rowsAffected, _ := result.RowsAffected()
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(200, "Task status updated", struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
func (c *Controller) SetNextTaskStatus(params martini.Params, w http.ResponseWriter) (int, string) {
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
row := c.DB.QueryRow(
"select count(*) from task_status ts "+
"right join (select t.project, ts.status_level from task t "+
"left join task_status ts on ts.id = t.status where t.id = ?) "+
"t on t.project = ts.project where ts.status_level >= t.status_level + 1;",
taskId,
)
count := 0
err = row.Scan(&count)
if err != nil && err != sql.ErrNoRows {
log.Println("error in getting count of next levels:", err)
return 500, err.Error()
}
var result sql.Result
var message string
closed := false
if count == 0 {
result, err = c.DB.Exec(
"update task set is_closed = ? where id = ?",
true,
taskId,
)
if err != nil {
log.Println("error in closing task: ", err)
return 500, err.Error()
}
row := c.DB.QueryRow("select executor from task where id = ?", taskId)
var executorId int64
err = row.Scan(&executorId)
if err != nil {
log.Println("error in getting userId: ", err)
return 500, err.Error()
}
row = c.DB.QueryRow("select project from task where id = ?", taskId)
var projectId int64
err = row.Scan(&projectId)
if err != nil {
log.Println("error in getting projectId: ", err)
return 500, err.Error()
}
_, err = c.sendDataToStream("task", "close", struct {
TaskId int64
ExecutorId int64
ProjectId int64
}{
taskId,
executorId,
projectId,
})
if err != nil {
log.Println(err)
return 500, err.Error()
}
message = "Task closed because last status stayed yet"
closed = true
} else {
result, err = c.DB.Exec(
"update task set status = (select ts.id from task_status ts "+
"right join (select t.project, ts.status_level from task t "+
"left join task_status ts on ts.id = t.status where t.id = ?) "+
"t on t.project = ts.project where ts.status_level = t.status_level + 1) where id = ?",
taskId,
taskId,
)
if err != nil {
log.Println("error in updating status:", err)
return 500, err.Error()
}
message = "Task status set to next"
}
rowsAffected, _ := result.RowsAffected()
var code int
if closed {
code = 200
} else {
code = 202
}
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(code, message, struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
func (c *Controller) ChangeTaskPriority(params martini.Params, w http.ResponseWriter, r *http.Request) (int, string) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
err := fmt.Sprintf("Unsupportable Content-Type header: %s", contentType)
log.Println(err)
return 500, err
}
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
jsonPriority, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Println("error in reading body", err)
return 500, err.Error()
}
priority := &struct {
Priority string
}{}
err = json.Unmarshal(jsonPriority, priority)
if err != nil {
log.Println("error in unmarshalling")
return 500, err.Error()
}
result, err := c.DB.Exec(
"update task set priority = ? where id = ?",
priority.Priority,
taskId,
)
if err != nil {
log.Println("error in updating priority:", err)
return 500, err.Error()
}
rowsAffected, _ := result.RowsAffected()
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(200, "Task priority updated", struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
func (c *Controller) ChangeTaskDeadline(params martini.Params, w http.ResponseWriter, r *http.Request) (int, string) {
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
err := fmt.Sprintf("Unsupportable Content-Type header: %s", contentType)
log.Println(err)
return 500, err
}
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
jsonDeadline, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Println("error in reading body", err)
return 500, err.Error()
}
deadline := &struct {
Deadline string
}{}
err = json.Unmarshal(jsonDeadline, deadline)
if err != nil {
log.Println("error in unmarshalling")
return 500, err.Error()
}
timeDeadline, err := time.Parse("2006-01-02", deadline.Deadline)
if err != nil {
log.Println("error in parsing deadline: ", err)
return 500, err.Error()
}
result, err := c.DB.Exec(
"update task set deadline = ? where id = ?",
timeDeadline,
taskId,
)
if err != nil {
log.Println("error in updating deadline:", err)
return 500, err.Error()
}
row := c.DB.QueryRow("select project from task where id = ?", taskId)
var projectId int64
err = row.Scan(&projectId)
if err != nil {
log.Println("error in getting projectId: ", err)
return 500, err.Error()
}
_, err = c.sendDataToStream("task", "deadline", struct {
TaskId int64
Deadline string
ProjectId int64
}{
taskId,
deadline.Deadline,
projectId,
})
if err != nil {
log.Println(err)
return 500, err.Error()
}
rowsAffected, _ := result.RowsAffected()
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(200, "Task deadline updated", struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
func (c *Controller) CloseTask(params martini.Params, w http.ResponseWriter) (int, string) {
taskId, err := strconv.ParseInt(params["id"], 10, 64)
if err != nil {
log.Println("error in parsing taskId", err)
return 500, err.Error()
}
result, err := c.DB.Exec(
"update task set is_closed = ? where id = ?",
true,
taskId,
)
if err != nil {
log.Println("error in closing task")
return 500, err.Error()
}
rowsAffected, _ := result.RowsAffected()
row := c.DB.QueryRow("select executor from task where id = ?", taskId)
var executorId int64
err = row.Scan(&executorId)
if err != nil {
log.Println("error in getting userId: ", err)
return 500, err.Error()
}
row = c.DB.QueryRow("select project from task where id = ?", taskId)
var projectId int64
err = row.Scan(&projectId)
if err != nil {
log.Println("error in getting projectId: ", err)
return 500, err.Error()
}
_, err = c.sendDataToStream("task", "close", struct {
TaskId int64
ExecutorId int64
ProjectId int64
}{
taskId,
executorId,
projectId,
})
if err != nil {
log.Println(err)
return 500, err.Error()
}
w.Header().Set("Content-Type", "application/json")
return c.makeContentResponse(200, "Project closed", struct {
Name string
Content interface{}
}{
Name: "Rows affected",
Content: rowsAffected,
})
}
|
package test
import (
"strings"
"testing"
"time"
//"github.com/gruntwork-io/terratest/modules/k8s"
"github.com/gruntwork-io/terratest/modules/logger"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/terraform"
test_structure "github.com/gruntwork-io/terratest/modules/test-structure"
"github.com/stretchr/testify/assert"
)
func getDefaultTerraformOptions(t *testing.T) (string, *terraform.Options, error) {
tempTestFolder := test_structure.CopyTerraformFolderToTemp(t, "..", ".")
random_id := strings.ToLower(random.UniqueId())
terraformOptions := &terraform.Options{
TerraformDir: tempTestFolder,
Vars: map[string]interface{}{},
MaxRetries: 5,
TimeBetweenRetries: 5 * time.Minute,
NoColor: false,
Logger: logger.TestingT,
}
terraformOptions.Vars["install_istio"] = false
return random_id, terraformOptions, nil
}
func TestApplyAndDestroyWithDefaultValues(t *testing.T) {
t.Parallel()
_, options, err := getDefaultTerraformOptions(t)
assert.NoError(t, err)
options.Vars["cert_manager_namespace"] = "cert-manager"
options.Vars["istio_operator_namespace"] = "istio-operator"
options.Vars["istio_namespace"] = "istio-system"
options.Vars["ingress_gateway_ip"] = "10.20.30.40"
options.Vars["use_cert_manager"] = true
options.Vars["domain_name"] = "foo.local"
options.Vars["letsencrypt_email"] = "foo@bar.local"
options.Vars["ingress_gateway_annotations"] = map[string]interface{}{"foo": "bar"}
defer terraform.Destroy(t, options)
_, err = terraform.InitAndApplyE(t, options)
assert.NoError(t, err)
}
|
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-10 16:41
# @File : log.go
# @Description :
# @Attention :
*/
package raft
import "sync"
// 存储的是日志信息
type LogInfo struct {
}
// 管理日志
type LogManager struct {
Lock *sync.RWMutex
Logs []LogInfo
}
|
package postal
import (
"io/ioutil"
"os"
)
type FileSystemInterface interface {
Exists(string) bool
Read(string) (string, error)
}
type FileSystem struct{}
func NewFileSystem() *FileSystem {
return &FileSystem{}
}
func (fs FileSystem) Exists(path string) bool {
_, err := os.Stat(path)
if err != nil {
return false
}
return true
}
func (fs FileSystem) Read(path string) (string, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(bytes), nil
}
|
// SPDX-License-Identifier: Apache-2.0
/*
Sample Chaincode based on Demonstrated Scenario
This code is based on code written by the Hyperledger Fabric community.
Original code can be found here: https://github.com/hyperledger/fabric-samples/blob/release/chaincode/fabcar/fabcar.go
*/
package main
/* Imports
* 4 utility libraries for handling bytes, reading and writing JSON,
formatting, and string manipulation
* 2 specific Hyperledger Fabric specific libraries for Smart Contracts
*/
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/hyperledger/fabric/core/chaincode/shim"
sc "github.com/hyperledger/fabric/protos/peer"
)
// Define the Smart Contract structure
type SmartContract struct {
}
/* Define Vote structure, with 7 properties.
Structure tags are used by encoding/json library
*/
type Vote struct {
Codigo string `json:"codigo"`
Eleccion string `json:"eleccion"`
Entidad string `json:"entidad"`
Distrito string `json:"distrito"`
Municipio string `json:"municipio"`
Seccion string `json:"seccion"`
Localidad string `json:"localidad"`
}
/*
* The Init method *
called when the Smart Contract "tuna-chaincode" is instantiated by the network
* Best practice is to have any Ledger initialization in separate function
-- see initLedger()
*/
func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
return shim.Success(nil)
}
/*
* The Invoke method *
called when an application requests to run the Smart Contract "tuna-chaincode"
The app also specifies the specific smart contract function to call with args
*/
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := APIstub.GetFunctionAndParameters()
// Route to the appropriate handler function to interact with the ledger
if function == "initLedger" {
return s.initLedger(APIstub)
} else if function == "recordVote" {
return s.recordVote(APIstub, args)
} else if function == "queryVote" {
return s.queryVote(APIstub, args)
} else if function == "queryAllVotes" {
return s.queryAllVotes(APIstub)
} else if function == "queryVotesByDomain" {
return s.queryVotesByDomain(APIstub, args)
}
return shim.Error("Invalid Smart Contract function name.")
}
/*
* The queryVote method *
Used to view the records of one particular vote
It takes one argument -- the key for the vote in question
*/
func (s *SmartContract) queryVote(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
voteAsBytes, _ := APIstub.GetState(args[0])
fmt.Println(args[0])
if voteAsBytes == nil {
return shim.Error("Could not locate vote")
}
return shim.Success(voteAsBytes)
}
/*
* The queryVotesByDomain method *
Used to view the records of several votes with couchdb rich queries
It takes two arguments -- the domain of the query and the specific value
*/
func (s *SmartContract) queryVotesByDomain(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) < 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
searchDomain := args[0]
param := args[1]
queryString := fmt.Sprintf("{\"selector\":{\"%s\":\"%s\"}}", searchDomain, param)
queryResults, err := getQueryResultForQueryString(APIstub, queryString)
if err != nil {
return shim.Error(err.Error())
}
return shim.Success(queryResults)
}
/*
* The initLedger method *
Will add test data (10 tuna catches)to our network
*/
func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response {
votes := []Vote{}
i := 0
for i < len(votes) {
fmt.Println("i is ", i)
voteAsBytes, _ := json.Marshal(votes[i])
APIstub.PutState(strconv.Itoa(i+1), voteAsBytes)
fmt.Println("Added", votes[i])
i = i + 1
}
return shim.Success(nil)
}
/*
* The recordVote method *
This method takes in seven arguments (attributes to be saved in the ledger).
*/
func (s *SmartContract) recordVote(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) != 8 {
return shim.Error("Incorrect number of arguments. Expecting 8")
}
var vote = Vote{Codigo: args[1], Eleccion: args[2], Entidad: args[3], Distrito: args[4],
Municipio: args[5], Seccion: args[6], Localidad: args[7]}
voteAsBytes, _ := json.Marshal(vote)
err := APIstub.PutState(args[0], voteAsBytes)
if err != nil {
return shim.Error(fmt.Sprintf("Failed to record vote: %s", args[0]))
}
return shim.Success(nil)
}
/*
* The queryAllVote method *
allows for assessing all the records added to the ledger(all votes)
This method does not take any arguments. Returns JSON string containing results.
*/
func (s *SmartContract) queryAllVotes(APIstub shim.ChaincodeStubInterface) sc.Response {
startKey := ""
endKey := ""
resultsIterator, err := APIstub.GetStateByRange(startKey, endKey)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
// buffer is a JSON array containing QueryResults
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// Add comma before array members,suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
buffer.WriteString("{\"Key\":")
buffer.WriteString("\"")
buffer.WriteString(queryResponse.Key)
buffer.WriteString("\"")
buffer.WriteString(", \"Record\":")
// Record is a JSON object, so we write as-is
buffer.WriteString(string(queryResponse.Value))
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Printf("- queryAllVote:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
// =========================================================================================
// getQueryResultForQueryString executes the passed in query string.
// Result set is built and returned as a byte array containing the JSON results.
// =========================================================================================
func getQueryResultForQueryString(APIstub shim.ChaincodeStubInterface, queryString string) ([]byte, error) {
fmt.Printf("- getQueryResultForQueryString queryString:\n%s\n", queryString)
resultsIterator, err := APIstub.GetQueryResult(queryString)
if err != nil {
return nil, err
}
defer resultsIterator.Close()
// buffer is a JSON array containing QueryRecords
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
queryResponse, err := resultsIterator.Next()
if err != nil {
return nil, err
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
buffer.WriteString("{\"Key\":")
buffer.WriteString("\"")
buffer.WriteString(queryResponse.Key)
buffer.WriteString("\"")
buffer.WriteString(", \"Record\":")
// Record is a JSON object, so we write as-is
buffer.WriteString(string(queryResponse.Value))
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Printf("- getQueryResultForQueryString queryResult:\n%s\n", buffer.String())
return buffer.Bytes(), nil
}
/*
* main function *
calls the Start function
The main function starts the chaincode in the container during instantiation.
*/
func main() {
// Create a new Smart Contract
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Error creating new Smart Contract: %s", err)
}
}
|
package gochannels
import (
"fmt"
"time"
)
var ch = make(chan string)
// DoSomething init
func DoSomething() {
start := time.Now()
go runB()
go runA()
fmt.Println(<-ch)
fmt.Println(<-ch)
elapsed := time.Since(start)
fmt.Println("Procces took ", elapsed)
}
func runA() {
time.Sleep(time.Second * 2)
fmt.Println("run a")
ch <- "done with run a"
}
func runB() {
time.Sleep(time.Second * 2)
fmt.Println("run b")
ch <- "done with run b"
}
|
package auth
import (
"bytes"
"log"
"net/http"
"net/url"
json "github.com/cgonzalezg/babyblick-backend/deserialize"
)
type AccesToken struct {
Token string `json:"access_token"`
Type string `json:"token_type"`
ID string `json:"id_token"`
}
func Login(w http.ResponseWriter, r *http.Request) {
// var jsonStr = []byte("client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&client_secret=CLIENT_SECRET&code=AUTHORIZATION_CODE&grant_type=authorization_code")
code := r.URL.Query()["code"][0]
data := url.Values{}
data.Set("client_id", "rlzj1WdHHXYWgoZJWRMT4yGhVIJZkKme")
data.Add("redirect_uri", "bar")
data.Add("client_secret", "qQA_CKfg-k6LR2phMSqWOgqw9H2oJDboapmvUo64zfU6n2pB-YCL1Qd3FHg4RhtU")
data.Add("code", code)
data.Add("grant_type", "authorization_code")
req, err := http.Post("https://babyblick.auth0.com/oauth/token", "application/x-www-form-urlencoded", bytes.NewBufferString(data.Encode()))
var token AccesToken
json.ReadJsonRes(req, &token)
//code take the user id
if err != nil {
log.Println("forbiden")
}
client := &http.Client{}
req1, _ := http.NewRequest("GET", "https://babyblick.auth0.com/userinfo/", nil)
// ...
req.Header.Set("Authorization", "'Bearer "+token.Token+"'")
resp, _ := client.Do(req1)
var user interface{}
json.ReadJsonRes(resp, user)
json.WriteJson(w, user)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.