text
stringlengths
11
4.05M
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package identitytoolkit import ( "context" "fmt" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" dclService "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/identitytoolkit/alpha" "github.com/GoogleCloudPlatform/declarative-resource-client-library/unstructured" ) type Tenant struct{} func TenantToUnstructured(r *dclService.Tenant) *unstructured.Resource { u := &unstructured.Resource{ STV: unstructured.ServiceTypeVersion{ Service: "identitytoolkit", Version: "alpha", Type: "Tenant", }, Object: make(map[string]interface{}), } if r.AllowPasswordSignup != nil { u.Object["allowPasswordSignup"] = *r.AllowPasswordSignup } if r.DisableAuth != nil { u.Object["disableAuth"] = *r.DisableAuth } if r.DisplayName != nil { u.Object["displayName"] = *r.DisplayName } if r.EnableAnonymousUser != nil { u.Object["enableAnonymousUser"] = *r.EnableAnonymousUser } if r.EnableEmailLinkSignin != nil { u.Object["enableEmailLinkSignin"] = *r.EnableEmailLinkSignin } if r.MfaConfig != nil && r.MfaConfig != dclService.EmptyTenantMfaConfig { rMfaConfig := make(map[string]interface{}) var rMfaConfigEnabledProviders []interface{} for _, rMfaConfigEnabledProvidersVal := range r.MfaConfig.EnabledProviders { rMfaConfigEnabledProviders = append(rMfaConfigEnabledProviders, string(rMfaConfigEnabledProvidersVal)) } rMfaConfig["enabledProviders"] = rMfaConfigEnabledProviders if r.MfaConfig.State != nil { rMfaConfig["state"] = string(*r.MfaConfig.State) } u.Object["mfaConfig"] = rMfaConfig } if r.Name != nil { u.Object["name"] = *r.Name } if r.Project != nil { u.Object["project"] = *r.Project } if r.TestPhoneNumbers != nil { rTestPhoneNumbers := make(map[string]interface{}) for k, v := range r.TestPhoneNumbers { rTestPhoneNumbers[k] = v } u.Object["testPhoneNumbers"] = rTestPhoneNumbers } return u } func UnstructuredToTenant(u *unstructured.Resource) (*dclService.Tenant, error) { r := &dclService.Tenant{} if _, ok := u.Object["allowPasswordSignup"]; ok { if b, ok := u.Object["allowPasswordSignup"].(bool); ok { r.AllowPasswordSignup = dcl.Bool(b) } else { return nil, fmt.Errorf("r.AllowPasswordSignup: expected bool") } } if _, ok := u.Object["disableAuth"]; ok { if b, ok := u.Object["disableAuth"].(bool); ok { r.DisableAuth = dcl.Bool(b) } else { return nil, fmt.Errorf("r.DisableAuth: expected bool") } } if _, ok := u.Object["displayName"]; ok { if s, ok := u.Object["displayName"].(string); ok { r.DisplayName = dcl.String(s) } else { return nil, fmt.Errorf("r.DisplayName: expected string") } } if _, ok := u.Object["enableAnonymousUser"]; ok { if b, ok := u.Object["enableAnonymousUser"].(bool); ok { r.EnableAnonymousUser = dcl.Bool(b) } else { return nil, fmt.Errorf("r.EnableAnonymousUser: expected bool") } } if _, ok := u.Object["enableEmailLinkSignin"]; ok { if b, ok := u.Object["enableEmailLinkSignin"].(bool); ok { r.EnableEmailLinkSignin = dcl.Bool(b) } else { return nil, fmt.Errorf("r.EnableEmailLinkSignin: expected bool") } } if _, ok := u.Object["mfaConfig"]; ok { if rMfaConfig, ok := u.Object["mfaConfig"].(map[string]interface{}); ok { r.MfaConfig = &dclService.TenantMfaConfig{} if _, ok := rMfaConfig["enabledProviders"]; ok { if s, ok := rMfaConfig["enabledProviders"].([]interface{}); ok { for _, ss := range s { if strval, ok := ss.(string); ok { r.MfaConfig.EnabledProviders = append(r.MfaConfig.EnabledProviders, dclService.TenantMfaConfigEnabledProvidersEnum(strval)) } } } else { return nil, fmt.Errorf("r.MfaConfig.EnabledProviders: expected []interface{}") } } if _, ok := rMfaConfig["state"]; ok { if s, ok := rMfaConfig["state"].(string); ok { r.MfaConfig.State = dclService.TenantMfaConfigStateEnumRef(s) } else { return nil, fmt.Errorf("r.MfaConfig.State: expected string") } } } else { return nil, fmt.Errorf("r.MfaConfig: expected map[string]interface{}") } } if _, ok := u.Object["name"]; ok { if s, ok := u.Object["name"].(string); ok { r.Name = dcl.String(s) } else { return nil, fmt.Errorf("r.Name: expected string") } } if _, ok := u.Object["project"]; ok { if s, ok := u.Object["project"].(string); ok { r.Project = dcl.String(s) } else { return nil, fmt.Errorf("r.Project: expected string") } } if _, ok := u.Object["testPhoneNumbers"]; ok { if rTestPhoneNumbers, ok := u.Object["testPhoneNumbers"].(map[string]interface{}); ok { m := make(map[string]string) for k, v := range rTestPhoneNumbers { if s, ok := v.(string); ok { m[k] = s } } r.TestPhoneNumbers = m } else { return nil, fmt.Errorf("r.TestPhoneNumbers: expected map[string]interface{}") } } return r, nil } func GetTenant(ctx context.Context, config *dcl.Config, u *unstructured.Resource) (*unstructured.Resource, error) { c := dclService.NewClient(config) r, err := UnstructuredToTenant(u) if err != nil { return nil, err } r, err = c.GetTenant(ctx, r) if err != nil { return nil, err } return TenantToUnstructured(r), nil } func ListTenant(ctx context.Context, config *dcl.Config, project string) ([]*unstructured.Resource, error) { c := dclService.NewClient(config) l, err := c.ListTenant(ctx, project) if err != nil { return nil, err } var resources []*unstructured.Resource for { for _, r := range l.Items { resources = append(resources, TenantToUnstructured(r)) } if !l.HasNext() { break } if err := l.Next(ctx, c); err != nil { return nil, err } } return resources, nil } func ApplyTenant(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { c := dclService.NewClient(config) r, err := UnstructuredToTenant(u) if err != nil { return nil, err } if ush := unstructured.FetchStateHint(opts); ush != nil { sh, err := UnstructuredToTenant(ush) if err != nil { return nil, err } opts = append(opts, dcl.WithStateHint(sh)) } r, err = c.ApplyTenant(ctx, r, opts...) if err != nil { return nil, err } return TenantToUnstructured(r), nil } func TenantHasDiff(ctx context.Context, config *dcl.Config, u *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { c := dclService.NewClient(config) r, err := UnstructuredToTenant(u) if err != nil { return false, err } if ush := unstructured.FetchStateHint(opts); ush != nil { sh, err := UnstructuredToTenant(ush) if err != nil { return false, err } opts = append(opts, dcl.WithStateHint(sh)) } opts = append(opts, dcl.WithLifecycleParam(dcl.BlockDestruction), dcl.WithLifecycleParam(dcl.BlockCreation), dcl.WithLifecycleParam(dcl.BlockModification)) _, err = c.ApplyTenant(ctx, r, opts...) if err != nil { if _, ok := err.(dcl.ApplyInfeasibleError); ok { return true, nil } return false, err } return false, nil } func DeleteTenant(ctx context.Context, config *dcl.Config, u *unstructured.Resource) error { c := dclService.NewClient(config) r, err := UnstructuredToTenant(u) if err != nil { return err } return c.DeleteTenant(ctx, r) } func TenantID(u *unstructured.Resource) (string, error) { r, err := UnstructuredToTenant(u) if err != nil { return "", err } return r.ID() } func (r *Tenant) STV() unstructured.ServiceTypeVersion { return unstructured.ServiceTypeVersion{ "identitytoolkit", "Tenant", "alpha", } } func (r *Tenant) SetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Tenant) GetPolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, role, member string) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Tenant) DeletePolicyMember(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, member *unstructured.Resource) error { return unstructured.ErrNoSuchMethod } func (r *Tenant) SetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Tenant) SetPolicyWithEtag(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, policy *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Tenant) GetPolicy(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { return nil, unstructured.ErrNoSuchMethod } func (r *Tenant) Get(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) (*unstructured.Resource, error) { return GetTenant(ctx, config, resource) } func (r *Tenant) Apply(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (*unstructured.Resource, error) { return ApplyTenant(ctx, config, resource, opts...) } func (r *Tenant) HasDiff(ctx context.Context, config *dcl.Config, resource *unstructured.Resource, opts ...dcl.ApplyOption) (bool, error) { return TenantHasDiff(ctx, config, resource, opts...) } func (r *Tenant) Delete(ctx context.Context, config *dcl.Config, resource *unstructured.Resource) error { return DeleteTenant(ctx, config, resource) } func (r *Tenant) ID(resource *unstructured.Resource) (string, error) { return TenantID(resource) } func init() { unstructured.Register(&Tenant{}) }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. package engine import ( "testing" "github.com/Azure/aks-engine/pkg/api" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" "github.com/Azure/go-autorest/autorest/to" "github.com/google/go-cmp/cmp" ) func TestCreateWindowsImageReference(t *testing.T) { cases := []struct { name string profileName string w api.WindowsProfile expected compute.ImageReference }{ { name: "CustomImageUrl", profileName: "foobar", w: api.WindowsProfile{ WindowsImageSourceURL: "https://some/image.vhd", }, expected: compute.ImageReference{ ID: to.StringPtr("[resourceId('Microsoft.Compute/images', 'foobarCustomWindowsImage')]"), }, }, { name: "Image gallery reference", profileName: "foo", w: api.WindowsProfile{ ImageRef: &api.ImageReference{ Gallery: "gallery", Name: "test", ResourceGroup: "testRg", SubscriptionID: "00000000-0000-0000-0000-000000000000", Version: "0.1.0", }, }, expected: compute.ImageReference{ ID: to.StringPtr("[concat('/subscriptions/', '00000000-0000-0000-0000-000000000000', '/resourceGroups/', parameters('agentWindowsImageResourceGroup'), '/providers/Microsoft.Compute/galleries/', 'gallery', '/images/', parameters('agentWindowsImageName'), '/versions/', '0.1.0')]"), }, }, { name: "Image reference", profileName: "bar", w: api.WindowsProfile{ ImageRef: &api.ImageReference{ Name: "tead", ResourceGroup: "testRg", }, }, expected: compute.ImageReference{ ID: to.StringPtr("[resourceId(parameters('agentWindowsImageResourceGroup'), 'Microsoft.Compute/images', parameters('agentWindowsImageName'))]"), }, }, { name: "Marketplace image", profileName: "baz", w: api.WindowsProfile{ WindowsOffer: "offer", WindowsPublisher: "pub", WindowsSku: "sku", ImageVersion: "ver", }, expected: compute.ImageReference{ Offer: to.StringPtr("[parameters('agentWindowsOffer')]"), Publisher: to.StringPtr("[parameters('agentWindowsPublisher')]"), Sku: to.StringPtr("[parameters('agentWindowsSku')]"), Version: to.StringPtr("[parameters('agentWindowsVersion')]"), }, }, { name: "Default", profileName: "qux", w: api.WindowsProfile{}, expected: compute.ImageReference{ Offer: to.StringPtr("[parameters('agentWindowsOffer')]"), Publisher: to.StringPtr("[parameters('agentWindowsPublisher')]"), Sku: to.StringPtr("[parameters('agentWindowsSku')]"), Version: to.StringPtr("[parameters('agentWindowsVersion')]"), }, }, } for _, c := range cases { c := c t.Run(c.name, func(t *testing.T) { t.Parallel() actual := createWindowsImageReference(c.profileName, &c.w) expected := &c.expected diff := cmp.Diff(actual, expected) if diff != "" { t.Errorf("unexpected diff while comparing compute.ImageRefernce: %s", diff) } }) } } func TestCreateWindowsImage(t *testing.T) { profile := &api.AgentPoolProfile{ Name: "foobar", } actual := createWindowsImage(profile) expected := ImageARM{ ARMResource: ARMResource{ APIVersion: "[variables('apiVersionCompute')]", }, Image: compute.Image{ Type: to.StringPtr("Microsoft.Compute/images"), Name: to.StringPtr("foobarCustomWindowsImage"), Location: to.StringPtr("[variables('location')]"), ImageProperties: &compute.ImageProperties{ StorageProfile: &compute.ImageStorageProfile{ OsDisk: &compute.ImageOSDisk{ OsType: "Windows", OsState: compute.Generalized, BlobURI: to.StringPtr("[parameters('agentWindowsSourceUrl')]"), StorageAccountType: compute.StorageAccountTypesStandardLRS, }, }, HyperVGeneration: compute.HyperVGenerationTypesV1, }, }, } diff := cmp.Diff(actual, expected) if diff != "" { t.Errorf("unexpected diff while comparing windows images: %s", diff) } }
package main import ( "fmt" "math" "github.com/kavehmz/prime" ) func main() { // ans: 1739023853137 var limit uint64 = 100000000 ps := prime.Primes(limit) m := make(map[uint64]struct{}, len(ps)) for _, p := range ps { m[p] = struct{}{} } var sum uint64 var candidate, j uint64 for _, p := range ps { candidate = p - 1 ok := true sq := uint64(math.Sqrt(float64(candidate))) for j = 2; j <= sq; j++ { if candidate%j == 0 { if _, found := m[candidate/j+j]; !found { ok = false break } } } if ok { //fmt.Println(candidate) sum += candidate } } fmt.Println("ans:", sum) }
package httpclient import ( "bytes" "context" "encoding/json" "io" "net/http" "net/url" "strings" "time" "github.com/pkg/errors" ) // Request is builder for http.Request type Request struct { method string url string header http.Header body io.Reader } // NewRequest func NewRequest(method string, url string) *Request { return &Request{ method: method, url: url, } } // Header set header func (r *Request) Header(key, value string) *Request { r.header.Set(key, value) return r } // Body set body with content-type func (r *Request) Body(contentType string, body io.Reader) *Request { r.Header("Content-Type", contentType) r.body = body return r } // Form set body with application/x-www-form-urlencoded func (r *Request) Form(form url.Values) *Request { return r.Body("application/x-www-form-urlencoded", strings.NewReader(form.Encode())) } // JSON set body with application/json func (r *Request) JSON(body interface{}) *Request { r, err := r.JSONOrError(body) if err != nil { panic(err) } return r } // JSONOrError set body with application/json // return error when marshal failed func (r *Request) JSONOrError(body interface{}) (*Request, error) { r.Header("Content-Type", "application/json") b, err := json.Marshal(body) if err != nil { return r, errors.Wrapf(err, `json.Marshal error`) } return r.Body("application/json", bytes.NewReader(b)), nil } // Build to http.Request func (r *Request) Build(ctx context.Context) (*http.Request, error) { req, err := http.NewRequestWithContext(ctx, strings.ToUpper(r.method), r.url, r.body) if err != nil { return nil, errors.Wrapf(err, `NewRequestWithContext`) } for k, v := range r.header { req.Header[k] = v } return req, nil } var ( DefaultHttpClient = &http.Client{Timeout: 15 * time.Second} ) // Do client.do func (r *Request) Do(ctx context.Context, clients ...*http.Client) (resp *Response, err error) { var c *http.Client if len(clients) > 0 { c = clients[0] } else { c = DefaultHttpClient } req, err := r.Build(ctx) if err != nil { return } httpResp, err := c.Do(req) if err != nil { return nil, errors.Wrapf(err, `Do`) } resp = &Response{} resp.Response = httpResp return }
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "context" "net/http" "os" "github.com/emicklei/go-restful" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/log/zap" "github.com/dukov/backend-api/pkg/service" // +kubebuilder:scaffold:imports ) var ( setupLog = ctrl.Log.WithName("setup") ) func main() { ctrl.SetLogger(zap.New(zap.UseDevMode(true))) mgr, err := service.NewApplicationManager(context.Background(), ctrl.GetConfigOrDie()) if err != nil { setupLog.Error(err, "Failed to create Application manager") os.Exit(1) } restful.DefaultContainer.Add(mgr.WebService()) setupLog.Info("Starting Backend API") http.ListenAndServe(":8080", nil) }
package storage import ( "errors" "github.com/arxdsilva/olist/bill" "github.com/arxdsilva/olist/record" ) type FakeStorage struct { records []record.Record bills []bill.Bill calls []bill.Call } func (f FakeStorage) SaveRecord(r record.Record) (err error) { f.records = append(f.records, r) return } func (f FakeStorage) UUIDFromStart(r record.Record) (uuid string, err error) { return } func (f FakeStorage) BillFromID(id string) (b bill.Bill, err error) { return b, errors.New("Not found") } func (f FakeStorage) CallsFromBillID(id string) (cs []bill.Call, err error) { return } func (f FakeStorage) RecordsFromBill(b bill.Bill) (rs []record.Record, err error) { return } func (f FakeStorage) SaveBill(b bill.Bill) (err error) { f.bills = append(f.bills, b) return } func (f FakeStorage) SaveCalls(c []bill.Call) (err error) { for _, call := range c { f.calls = append(f.calls, call) } return }
package contracts import "culture/cloud/base/internal/service" // PlatformService 平台可定制服务接口 type PlatformService interface { // Name 获取服务名称 Name() string // Ident 获取服务标识 Ident() string // InitService 初始化服务 InitService(cloudId uint64) service.Error // CheckService 检查服务是否可用 CheckService(cloudId uint64) (bool, service.Error) }
package main import "fmt" func main() { fmt.Println(maxCoins([]int{3, 1, 5, 8}) == 167) } // 注意:go 代码由 chatGPT🤖 根据我的 java 代码翻译,旨在帮助不同背景的读者理解算法逻辑。 // 本代码还未经过力扣测试,仅供参考,如有疑惑,可以参照我写的 java 代码对比查看。 func maxCoins(nums []int) int { n := len(nums) points := append([]int{1}, nums...) points = append(points, 1) dp := make([][]int, n+2) for i := range dp { dp[i] = make([]int, n+2) } max := func(a, b int) int { if a > b { return a } return b } for i := n; i >= 0; i-- { for j := i + 1; j < n+2; j++ { for k := i + 1; k < j; k++ { dp[i][j] = max( dp[i][j], dp[i][k]+dp[k][j]+points[i]*points[k]*points[j], ) } } } return dp[0][n+1] } func maxCoins4(nums []int) int { n := len(nums) // 添加两侧的虚拟气球 points := make([]int, 0, n+2) points = append([]int{1}, nums...) points = append(points, 1) // base case 已经都被初始化为 0 dp := make([][]int, n+2) for i := range dp { dp[i] = make([]int, n+2) } // 开始状态转移 // i 应该从下往上 for i := n; i >= 0; i-- { // j 应该从左往右 for j := i + 1; j < n+2; j++ { // 最后戳破的气球是哪个? for k := i + 1; k < j; k++ { // 择优做选择 dp[i][j] = max(dp[i][j], dp[i][k]+dp[k][j]+points[i]*points[j]*points[k]) } } } // 因为最终i=0,所以从最大值向下变小 // j 等于 return dp[0][n+1] } func max(a, b int) int { if a > b { return a } return b } func maxCoins3(nums []int) int { nums = append([]int{1}, nums...) nums = append(nums, 1) max := func(a, b int) int { if a > b { return a } return b } var solve func(i, j int) int solve = func(l, r int) int { if l+2 > r { return 0 } else if l+2 == r { return nums[l] * nums[l+1] * nums[l+2] } res := 0 for k := l + 1; k <= r-1; k++ { left := solve(l, k) right := solve(k, r) sum := left + right + nums[k]*nums[l]*nums[r] res = max(res, sum) } return res } return solve(0, len(nums)-1) } func maxCoins2(nums []int) int { nums = append([]int{1}, nums...) nums = append(nums, 1) dp := make([][]int, len(nums)) for i := range dp { dp[i] = make([]int, len(nums)) } max := func(a, b int) int { if a > b { return a } return b } // ln 表示开区间的长度 for ln := 3; ln <= len(nums); ln++ { //l 表示开区间左端点,l + len - 1则表示开区间右端点 for i := 0; i < len(nums)-ln; i++ { //k为开区间内的索引(代表区间最后一个被戳破的气球) for k := i + 1; k < i+ln-1; k++ { left := dp[i][k] right := dp[k][i+ln-1] sum := nums[i] * nums[k] * nums[i+ln-1] dp[i][i+ln-1] = max(dp[i][i+ln-1], left+sum+right) } } } return dp[0][len(nums)-2] }
package main import ( "fmt" "io" "net" "os" reuse "gx/ipfs/QmXD921xzL9EDRpD6gRm1cb7Khm8VEpZ3NT3nPK7uTX6Fq/go-reuseport" ) func main() { l1, err := reuse.Listen("tcp", "0.0.0.0:11111") maybeDie(err) fmt.Printf("listening on %s\n", l1.Addr()) l2, err := reuse.Listen("tcp", "0.0.0.0:22222") maybeDie(err) fmt.Printf("listening on %s\n", l2.Addr()) a1, err := reuse.ResolveAddr("tcp", "127.0.0.1:11111") maybeDie(err) a3, err := reuse.ResolveAddr("tcp", "127.0.0.1:33333") maybeDie(err) d1 := reuse.Dialer{D: net.Dialer{LocalAddr: a1}} d2 := reuse.Dialer{D: net.Dialer{LocalAddr: a3}} go func() { l2to1foo, err := l2.Accept() maybeDie(err) fmt.Printf("%s accepted conn from %s\n", addrStr(l2.Addr()), addrStr(l2to1foo.RemoteAddr())) fmt.Println("safe") l1to2bar, err := l1.Accept() maybeDie(err) fmt.Printf("%s accepted conn from %s\n", addrStr(l1.Addr()), addrStr(l1to2bar.RemoteAddr())) io.Copy(l1to2bar, l2to1foo) }() d1to2foo, err := d1.Dial("tcp4", "127.0.0.1:22222") maybeDie(err) fmt.Printf("dialing from %s to %s\n", d1.D.LocalAddr, "127.0.0.1:22222") d2to1bar, err := d2.Dial("tcp4", "127.0.0.1:11111") maybeDie(err) fmt.Printf("dialing from %s to %s\n", d2.D.LocalAddr, "127.0.0.1:11111") go io.Copy(d1to2foo, os.Stdin) io.Copy(os.Stdout, d2to1bar) } func die(err error) { fmt.Fprintf(os.Stderr, "%s\n", err) os.Exit(-1) } func maybeDie(err error) { if err != nil { die(err) } } func addrStr(a net.Addr) string { return fmt.Sprintf("%s/%s", a.Network(), a) }
package listen import ( "errors" "fmt" "github.com/lib/pq" "time" ) type Insert struct{ Listen } func (insert Insert) Listener(event Event) (*pq.Listener, error) { db := connect(event.ConnParams) err := createNotifyEvent(db) if err != nil { return nil, err } _, err = db.Query( fmt.Sprintf(` DROP TRIGGER IF EXISTS %s_notify_event ON %s; CREATE TRIGGER %s_notify_event AFTER INSERT ON %s FOR EACH ROW EXECUTE PROCEDURE cdc_notify_event(); `, event.Table, event.Table, event.Table, event.Table, ), ) if err != nil { return nil, errors.New(fmt.Sprintf("Error: table `%s` does not exist", event.Table)) } _, err = db.Query("LISTEN EVENTS") if err != nil { return nil, err } return pq.NewListener(connInfo(event.ConnParams), time.Second, time.Second, func(ev pq.ListenerEventType, err error) { if err != nil { fmt.Println(err.Error()) } }), nil }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package console import ( "context" "fmt" rocketmqv1alpha1 "github.com/apache/rocketmq-operator/pkg/apis/rocketmq/v1alpha1" cons "github.com/apache/rocketmq-operator/pkg/constants" "github.com/apache/rocketmq-operator/pkg/share" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "reflect" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/handler" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" "time" ) var log = logf.Log.WithName("controller_console") /** * USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller * business logic. Delete these comments after modifying this file.* */ // SetupWithManager creates a new Console Controller and adds it to the Manager. The Manager will set fields on the Controller // and Start it when the Manager is Started. func SetupWithManager(mgr manager.Manager) error { return add(mgr, newReconciler(mgr)) } // newReconciler returns a new reconcile.Reconciler func newReconciler(mgr manager.Manager) reconcile.Reconciler { return &ReconcileConsole{client: mgr.GetClient(), scheme: mgr.GetScheme()} } // add adds a new Controller to mgr with r as the reconcile.Reconciler func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New("console-controller", mgr, controller.Options{Reconciler: r}) if err != nil { return err } // Watch for changes to primary resource Console err = c.Watch(&source.Kind{Type: &rocketmqv1alpha1.Console{}}, &handler.EnqueueRequestForObject{}) if err != nil { return err } // TODO(user): Modify this to be the types you create that are owned by the primary resource // Watch for changes to secondary resource Pods and requeue the owner Console err = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{ IsController: true, OwnerType: &rocketmqv1alpha1.Console{}, }) if err != nil { return err } return nil } //+kubebuilder:rbac:groups=rocketmq.apache.org,resources=consoles,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=rocketmq.apache.org,resources=consoles/status,verbs=get;update;patch //+kubebuilder:rbac:groups=rocketmq.apache.org,resources=consoles/finalizers,verbs=update //+kubebuilder:rbac:groups="apps",resources=deployments,verbs=get;list;watch;create;update;patch;delete // ReconcileConsole reconciles a Console object type ReconcileConsole struct { // This client, initialized using mgr.Client() above, is a split client // that reads objects from the cache and writes to the apiserver client client.Client scheme *runtime.Scheme } // Reconcile reads that state of the cluster for a Console object and makes changes based on the state read // and what is in the Console.Spec // TODO(user): Modify this Reconcile function to implement your Controller logic. This example creates // a Pod as an example // Note: // The Controller will requeue the Request to be processed again if the returned error is non-nil or // Result.Requeue is true, otherwise upon completion it will remove the work from the queue. func (r *ReconcileConsole) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name) reqLogger.Info("Reconciling Console") // Fetch the Console instance instance := &rocketmqv1alpha1.Console{} err := r.client.Get(context.TODO(), request.NamespacedName, instance) if err != nil { if errors.IsNotFound(err) { // Request object not found, could have been deleted after reconcile request. // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers. // Return and don't requeue return reconcile.Result{}, nil } // Error reading the object - requeue the request. return reconcile.Result{}, err } if instance.Spec.NameServers == "" { // wait for name server ready if nameServers is omitted for { if share.IsNameServersStrInitialized { break } else { log.Info("Waiting for name server ready...") time.Sleep(time.Duration(cons.WaitForNameServerReadyInSecond) * time.Second) } } } else { share.NameServersStr = instance.Spec.NameServers } consoleDeployment := newDeploymentForCR(instance) // Set Console instance as the owner and controller if err := controllerutil.SetControllerReference(instance, consoleDeployment, r.scheme); err != nil { return reconcile.Result{}, err } // Check if this Pod already exists found := &appsv1.Deployment{} err = r.client.Get(context.TODO(), types.NamespacedName{Name: consoleDeployment.Name, Namespace: consoleDeployment.Namespace}, found) if err != nil && errors.IsNotFound(err) { reqLogger.Info("Creating RocketMQ Console Deployment", "Namespace", consoleDeployment, "Name", consoleDeployment.Name) err = r.client.Create(context.TODO(), consoleDeployment) if err != nil { return reconcile.Result{}, err } // created successfully - don't requeue return reconcile.Result{}, nil } else if err != nil { return reconcile.Result{}, err } // Support console deployment scaling if !reflect.DeepEqual(instance.Spec.ConsoleDeployment.Spec.Replicas, found.Spec.Replicas) { found.Spec.Replicas = instance.Spec.ConsoleDeployment.Spec.Replicas err = r.client.Update(context.TODO(), found) if err != nil { reqLogger.Error(err, "Failed to update console CR ", "Namespace", found.Namespace, "Name", found.Name) } else { reqLogger.Info("Successfully updated console CR ", "Namespace", found.Namespace, "Name", found.Name) } } // TODO: update console if name server address changes // CR already exists - don't requeue reqLogger.Info("Skip reconcile: RocketMQ Console Deployment already exists", "Namespace", found.Namespace, "Name", found.Name) return reconcile.Result{}, nil } // newDeploymentForCR returns a deployment pod with modifying the ENV func newDeploymentForCR(cr *rocketmqv1alpha1.Console) *appsv1.Deployment { env := corev1.EnvVar{ Name: "JAVA_OPTS", Value: fmt.Sprintf("-Drocketmq.namesrv.addr=%s -Dcom.rocketmq.sendMessageWithVIPChannel=false", share.NameServersStr), } dep := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: cr.Name, Namespace: cr.Namespace, }, Spec: appsv1.DeploymentSpec{ Replicas: cr.Spec.ConsoleDeployment.Spec.Replicas, Selector: &metav1.LabelSelector{ MatchLabels: cr.Spec.ConsoleDeployment.Spec.Selector.MatchLabels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: cr.Spec.ConsoleDeployment.Spec.Template.ObjectMeta.Labels, }, Spec: corev1.PodSpec{ ServiceAccountName: cr.Spec.ConsoleDeployment.Spec.Template.Spec.ServiceAccountName, Affinity: cr.Spec.ConsoleDeployment.Spec.Template.Spec.Affinity, ImagePullSecrets: cr.Spec.ConsoleDeployment.Spec.Template.Spec.ImagePullSecrets, Containers: []corev1.Container{{ Resources: cr.Spec.ConsoleDeployment.Spec.Template.Spec.Containers[0].Resources, Image: cr.Spec.ConsoleDeployment.Spec.Template.Spec.Containers[0].Image, Name: cr.Spec.ConsoleDeployment.Spec.Template.Spec.Containers[0].Name, ImagePullPolicy: cr.Spec.ConsoleDeployment.Spec.Template.Spec.Containers[0].ImagePullPolicy, Env: append(cr.Spec.ConsoleDeployment.Spec.Template.Spec.Containers[0].Env, env), Ports: cr.Spec.ConsoleDeployment.Spec.Template.Spec.Containers[0].Ports, }}, }, }, }, } return dep }
package local import ( "io" "io/ioutil" "mime" "os" "path/filepath" "strings" "github.com/vasyahuyasa/july/opds/storage" ) var _ storage.Storage = &FsStorage{} var mimes = map[string]string{ ".epub": "application/epub+zip", ".fb2": "application/fb2+zip", ".mobi": "application/x-mobipocket-ebook", } type FsStorage struct { root string } func NewFsStorage(root string) *FsStorage { return &FsStorage{ root: root, } } func (store *FsStorage) List(path string) ([]storage.StorageEntry, error) { localPath := filepath.Join(store.root, path) files, err := ioutil.ReadDir(localPath) if err != nil { return nil, err } entries := make([]storage.StorageEntry, 0, len(files)) for _, f := range files { entries = append(entries, storage.StorageEntry{ Title: f.Name(), Path: filepath.Join(store.root, f.Name()), IsDir: f.IsDir(), Updated: f.ModTime(), MimeType: getMime(f.Name()), }) } return entries, nil } func (store *FsStorage) IsDownloadable(path string) (bool, error) { localPath := filepath.Join(store.root, path) f, err := os.Open(localPath) if err != nil { return false, err } defer f.Close() stat, err := f.Stat() if err != nil { return false, err } return !stat.IsDir(), nil } func (store *FsStorage) Download(w io.Writer, path string) error { localPath := filepath.Join(store.root, path) f, err := os.Open(localPath) if err != nil { return err } defer f.Close() _, err = io.Copy(w, f) return err } func getMime(filename string) string { ext := strings.ToLower(filepath.Ext(filename)) mimeType, ok := mimes[ext] if ok { return mimeType } mimeType = mime.TypeByExtension(ext) if mimeType == "" { mimeType = "application/octet-stream" } return mimeType }
package constant const ( ConfigProjectFilepath = "config/config.json" )
package installer import ( "strings" "github.com/peterh/liner" ) func Rerun(dir string) (string, error) { lnr := liner.NewLiner() defer lnr.Close() lnr.SetCtrlCAborts(true) hist := GetHistory(dir) for i := len(hist) - 1; i >= 0; i-- { words := strings.Fields(hist[i]) if len(words) <= 1 { continue } lnr.AppendHistory(strings.Join(words[1:], " ")) } return lnr.Prompt(">>> ") }
package main import ( "errors" "flag" "fmt" "log" "net/http" "net/url" "strings" "github.com/gocolly/colly" "github.com/popstk/olddriver/core" ) const ( startURL = "http://taohuale.us/" spiderName = "taohua" ) func init() { log.SetFlags(log.Lshortfile | log.LstdFlags) } func mainPage() (*url.URL, error) { var u string c := colly.NewCollector() c.OnHTML("div.main div:nth-child(3) #newurllink a", func(e *colly.HTMLElement) { if u = strings.TrimSpace(e.Attr("href")); u == "" { log.Println("Save main page") _ = e.Response.Save("mainPage.html") } }) c.OnError(func(r *colly.Response, err error) { log.Printf("Request URL %s failed with response: %s", r.Request.URL, err) }) _ = c.Visit(startURL) if u == "" { return nil, errors.New("can not get main page") } log.Println("->", u) rsp, err := http.Get(u) if err != nil { return nil, err } return rsp.Request.URL, nil } func run(persist *core.Persist, key, index string) error { conf, err := persist.Conf(key) if err != nil { return err } timeR, err := core.NewTimeRange("2006-1-2") if err != nil { return err } u, err := url.Parse(index) if err != nil { return err } u.Path = conf.Forum log.Println("->", u.String()) c := colly.NewCollector(colly.AllowedDomains(u.Hostname())) cc := c.Clone() cc.OnXML(`//*[@id="postlist"]/div[1]//p[@class="attnm"]`, func(e *colly.XMLElement) { torrent := e.ChildAttrs("./a", "href") for i, v := range torrent { u, err := url.Parse(core.JoinURL(e.Request.URL, v)) if err != nil { continue } torrent[i] = fmt.Sprintf("%s://%s/forum.php?mod=attachment&aid=%s", u.Scheme, u.Host, u.Query().Get("aid")) } e.Request.Ctx.Put("torrent", torrent) }) // note: css selector 从第二页开始查找不到,改用xpath c.OnXML(`//*[@id="threadlisttableid"]/tbody[@id="separatorline"]/following-sibling::tbody/tr`, func(e *colly.XMLElement) { title := e.ChildText(".//th/a[2]") if title == "" { return } href := e.ChildAttr(".//th/a[2]", "href") timeStr := e.ChildAttr(".//td[2]/em/span/span", "title") if timeStr == "" { timeStr = e.ChildText(".//td[2]/em/span") } t, err := timeR.AddTime(timeStr) if err != nil { log.Println(err) return } uri := core.JoinURL(e.Request.URL, href) if err := cc.Request("GET", uri, nil, e.Request.Ctx, nil); err != nil { log.Println(err) return } torrent, _ := e.Request.Ctx.GetAny("torrent").([]string) item := core.Item{ Tag: key, URL: href, Time: t, Title: title, Link: torrent, } log.Println("get item: ", item.URL) if err := persist.Insert(href, &item); err != nil { log.Println(err) } }) c.OnHTML("#fd_page_bottom > div > a.nxt", func(e *colly.HTMLElement) { link := e.Attr("href") next := e.Request.AbsoluteURL(link) e.Request.Ctx.Put("next", next) }) c.OnScraped(func(r *colly.Response) { log.Println("min time is ", timeR.Min) log.Println("conf.Last time is ", conf.Last.Time()) if timeR.Min.Before(conf.Last.Time()) { log.Println("DeadLine") return } if next, ok := r.Ctx.GetAny("next").(string); ok { if err = c.Visit(next); err != nil { log.Println(err) } } }) c.OnRequest(func(r *colly.Request) { log.Println("Visiting ", r.URL) }) c.OnError(func(r *colly.Response, err error) { log.Print("Request URL:", r.Request.URL, "failed with response:", r, "\nError:", err) }) if err = c.Visit(u.String()); err != nil { return err } conf.Last.Set(timeR.Max) return nil } func main() { flag.Parse() persist, err := core.NewPersist(spiderName) core.Must(err) keys, err := persist.Keys() core.Must(err) u, err := mainPage() core.Must(err) for _, key := range keys { log.Println("key -> ", key) if err = run(persist, key, u.String()); err != nil { log.Println(err) } } }
// benchmark. // // go test -bench Shift // package main import ( "fmt" "testing" ) var tests = []string{"hello", "world", "foo", "bar", "fizz", "buzz"} func BenchmarkShiftAppend(b *testing.B) { ss := make([]string, 3) ps := fmt.Sprintf("%p", ss) b.ResetTimer() for i := 0; i < b.N; i++ { for _, s := range tests { ss = append(ss[1:], s) } } b.StopTimer() b.Logf("before p:%s after p:%p", ps, ss) } func BenchmarkShiftDirect(b *testing.B) { ss := make([]string, 3) ps := fmt.Sprintf("%p", ss) b.ResetTimer() for i := 0; i < b.N; i++ { for _, s := range tests { ss[0], ss[1], ss[2] = ss[1], ss[2], s } } b.StopTimer() b.Logf("before p:%s after p:%p", ps, ss) } func BenchmarkShiftFor(b *testing.B) { ss := make([]string, 3) index := len(ss) - 1 ps := fmt.Sprintf("%p", ss) b.ResetTimer() for i := 0; i < b.N; i++ { for _, s := range tests { for j := 0; j < index; j++ { ss[j] = ss[j+1] } ss[index] = s } } b.StopTimer() b.Logf("before p:%s after p:%p", ps, ss) }
package sentinel import ( "fmt" "sync" "testing" "time" "github.com/garyburd/redigo/redis" ) func TestSentinel(t *testing.T) { st := NewSentinel( []string{"127.0.0.1:26379"}, "mymaster", ) defer st.Close() err := st.Discover() if err != nil { t.Log(err) t.FailNow() } addrs, err := st.SentinelAddrs() t.Log(addrs, err) master, err := st.MasterAddr() t.Log(master, err) slaves, err := st.SlaveAddrs() t.Log(slaves, err) wg := &sync.WaitGroup{} ms, err := st.MasterSwitch() w, err := ms.Watch() _ = w go func() { defer wg.Done() wg.Add(1) for addr := range w { t.Log(addr) } fmt.Println("watch exit") }() time.Sleep(20 * time.Second) fmt.Println("close") ms.Close() wg.Wait() } func TestSentinelPool(t *testing.T) { sp := NewSentinelPool([]string{"127.0.0.1:26379"}, "mymaster", 0, "") for i := 0; i < 30; i++ { conn := sp.Get() if conn == nil { fmt.Println("get conn fail, ", i) continue } s, err := redis.String(conn.Do("INFO")) if err != nil { fmt.Println("do command error:", err) } else { _ = s fmt.Println(i, sp.curAddr) } time.Sleep(1 * time.Second) } sp.Close() }
// time: O(n); space: O(n) func convert(s string, numRows int) string { slopeLen := numRows - 2 if slopeLen < 0 { slopeLen = 0 } res := []byte{} for i := 0; i < numRows; i++ { if i == 0 || i == numRows-1 { for j := 0; i + (numRows + slopeLen) * j < len(s); j++ { res = append(res, s[i + (numRows + slopeLen) * j]) } continue } for j := 0; ; j++ { idx := i + (numRows + slopeLen) * j if idx >= len(s) { break } res = append(res, s[idx]) idx = numRows * (j + 1) + slopeLen * j + (numRows-1-i) - 1 if idx >= len(s) { break } res = append(res, s[idx]) } } return string(res) }
/* * @lc app=leetcode.cn id=1662 lang=golang * * [1662] 检查两个字符串数组是否相等 */ // @lc code=start package main func arrayStringsAreEqual(word1 []string, word2 []string) bool { i1 := 0 j1 := 0 i2 := 0 j2 := 0 for i1 < len(word1) && i2 < len(word2) { if word1[i1][j1] != word2[i2][j2] { return false } if j1 == len(word1[i1])-1 { i1++ j1 = 0 } else { j1++ } if j2 == len(word2[i2])-1 { i2++ j2 = 0 } else { j2++ } } if i1 == len(word1) && j1 == 0 && i2 == len(word2) && j2 == 0 { return true } return false } // // func main() { // fmt.Println(arrayStringsAreEqual([]string{"ab", "c"}, []string{"a", "bc"})) // } // @lc code=end
package main import "fmt" func main() { num := 5 len := 2 for i, draw := range zigzag(num) { fmt.Printf("%*d ", len, draw) if i%num == num-1 { fmt.Println(" ") } } } func zigzag(n int) []int { arr := make([]int, n*n) i := 0 m := n * 2 for p := 1; p <= m; p++ { x := p - n if x < 0 { x = 0 } y := p - 1 if y > n-1 { y = n - 1 } j := m - p if j > p { j = p } for k := 0; k < j; k++ { if p&1 == 0 { arr[(x+k)*n+y-k] = i } else { arr[(y-k)*n+x+k] = i } i++ } } return arr }
package c39_rsa import "math/big" func InvMod(a, b *big.Int) *big.Int { g, x := EGCD(a, b) if g.Cmp(bi(1)) != 0 { return nil } return x.Mod(x, b) } func DivMod(a, b *big.Int) (*big.Int, *big.Int) { q := new(big.Int).Div(a, b) return q, a.Sub(a, new(big.Int).Mul(q, b)) } func EGCD(a, b *big.Int) (*big.Int, *big.Int) { lRem, rem := bn().Abs(a), bn().Abs(b) x, lX, y, lY := bi(0), bi(1), bi(1), bi(0) quotient := bn() for rem.Cmp(bi(0)) != 0 { tmpRem := rem quotient, rem = DivMod(lRem, rem) lRem = tmpRem tmpX, tmpY := x, y x = bn().Sub(lX, bn().Mul(quotient, x)) lX = tmpX y = bn().Sub(lY, bn().Mul(quotient, y)) lY = tmpY } if a.Sign() < 0 { lX = bn().Neg(lX) } return lRem, lX } func bi(n int64) *big.Int { return big.NewInt(n) } func bn() *big.Int { return new(big.Int) }
// Package storage contains handling with db(Postgesql) package storage import ( "errors" "fmt" "log" "github.com/jmoiron/sqlx" _ "github.com/lib/pq" "github.com/saromanov/gleek/config" ) var ( errNoConfig = errors.New("config is not defined") errNoCreds = errors.New("name, password or user is not defined for storage") ) // Storage implements db handling with Postgesql type Storage struct { db *sqlx.DB } // New provides init for postgesql storage func New(s *config.Config) (*Storage, error) { if s == nil { return nil, errNoConfig } if s.Name == "" || s.Password == "" || s.User == "" { return nil, errNoCreds } args := "dbname=gleek2" if s.Name != "" && s.Password != "" && s.User != "" { args += fmt.Sprintf(" user=%s dbname=%s password=%s", s.User, s.Name, s.Password) } db, err := sqlx.Connect("postgres", args) if err != nil { log.Fatalln(err) } return &Storage{ db: db, }, nil } // Close provides closing of db func (s *Storage) Close() error { return s.db.Close() }
package main import "fmt" func main() { //fmt.Println(generate(1)) fmt.Println(generate(5)) } func generate(numRows int) [][]int { dp := make([][]int, numRows) for i := 0; i < numRows; i++ { dp[i] = make([]int, i+1) left, right := 0, i dp[i][left] = 1 dp[i][right] = 1 left++ right-- for left <= right { dp[i][left] = dp[i-1][left] if left-1 >= 0 { dp[i][left] += dp[i-1][left-1] } if left != right { dp[i][right] = dp[i-1][right] if right-1 >= 0 { dp[i][right] += dp[i-1][right-1] } } left++ right-- } } return dp }
package server import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "regexp" "strings" "testing" "time" "github.com/calvinmclean/automated-garden/garden-app/pkg" "github.com/calvinmclean/automated-garden/garden-app/pkg/influxdb" "github.com/calvinmclean/automated-garden/garden-app/pkg/storage" "github.com/go-chi/chi/v5" "github.com/go-chi/render" "github.com/rs/xid" "github.com/sirupsen/logrus" "github.com/stretchr/testify/mock" ) func init() { logger = logrus.New() } func createExampleGarden() *pkg.Garden { time, _ := time.Parse(time.RFC3339Nano, "2021-10-03T11:24:52.891386-07:00") id, _ := xid.FromString("c5cvhpcbcv45e8bp16dg") return &pkg.Garden{ Name: "test garden", ID: id, Plants: map[xid.ID]*pkg.Plant{}, CreatedAt: &time, } } func TestGardenContextMiddleware(t *testing.T) { garden := createExampleGarden() tests := []struct { name string setupMock func(*storage.MockClient) path string expected string code int }{ { "Successful", func(storageClient *storage.MockClient) { storageClient.On("GetGarden", mock.Anything).Return(garden, nil) }, "/garden/c5cvhpcbcv45e8bp16dg", "", http.StatusOK, }, { "ErrorInvalidID", func(storageClient *storage.MockClient) {}, "/garden/not-an-xid", `{"status":"Invalid request.","error":"xid: invalid ID"}`, http.StatusBadRequest, }, { "StorageClientError", func(storageClient *storage.MockClient) { storageClient.On("GetGarden", garden.ID).Return(nil, errors.New("storage client error")) }, "/garden/c5cvhpcbcv45e8bp16dg", `{"status":"Server Error.","error":"storage client error"}`, http.StatusInternalServerError, }, { "StatusNotFound", func(storageClient *storage.MockClient) { storageClient.On("GetGarden", garden.ID).Return(nil, nil) }, "/garden/c5cvhpcbcv45e8bp16dg", `{"status":"Resource not found."}`, http.StatusNotFound, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { storageClient := new(storage.MockClient) tt.setupMock(storageClient) gr := GardensResource{ storageClient: storageClient, config: Config{}, } testHandler := func(w http.ResponseWriter, r *http.Request) { g := r.Context().Value(gardenCtxKey).(*pkg.Garden) if garden != g { t.Errorf("Unexpected Garden saved in request context. Expected %v but got %v", garden, g) } render.Status(r, http.StatusOK) } router := chi.NewRouter() router.Route(fmt.Sprintf("/garden/{%s}", gardenPathParam), func(r chi.Router) { r.Use(gr.gardenContextMiddleware) r.Get("/", testHandler) }) r := httptest.NewRequest("GET", tt.path, nil) w := httptest.NewRecorder() router.ServeHTTP(w, r) // check HTTP response status code if w.Code != tt.code { t.Errorf("Unexpected status code: got %v, want %v", w.Code, tt.code) } actual := strings.TrimSpace(w.Body.String()) if actual != tt.expected { t.Errorf("Unexpected response body:\nactual = %v\nexpected = %v", actual, tt.expected) } storageClient.AssertExpectations(t) }) } } func TestCreateGarden(t *testing.T) { tests := []struct { name string setupMock func(*storage.MockClient) body string expectedRegexp string code int }{ { "Successful", func(storageClient *storage.MockClient) { storageClient.On("SaveGarden", mock.Anything).Return(nil) }, `{"name": "test garden"}`, `{"name":"test garden","id":"[0-9a-v]{20}","created_at":"\d{4}-\d{2}-\d\dT\d\d:\d\d:\d\d\.\d+(-07:00|Z)","plants":{"rel":"collection","href":"/gardens/[0-9a-v]{20}/plants"},"links":\[{"rel":"self","href":"/gardens/[0-9a-v]{20}"},{"rel":"health","href":"/gardens/[0-9a-v]{20}/health"},{"rel":"plants","href":"/gardens/[0-9a-v]{20}/plants"}\]}`, http.StatusCreated, }, { "ErrorInvalidRequestBody", func(storageClient *storage.MockClient) {}, "{}", `{"status":"Invalid request.","error":"missing required Garden fields"}`, http.StatusBadRequest, }, { "StorageClientError", func(storageClient *storage.MockClient) { storageClient.On("SaveGarden", mock.Anything).Return(errors.New("storage client error")) }, `{"name": "test garden"}`, `{"status":"Server Error.","error":"storage client error"}`, http.StatusInternalServerError, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { storageClient := new(storage.MockClient) tt.setupMock(storageClient) gr := GardensResource{ storageClient: storageClient, config: Config{}, } r := httptest.NewRequest("POST", "/garden", strings.NewReader(tt.body)) r.Header.Add("Content-Type", "application/json") w := httptest.NewRecorder() h := http.HandlerFunc(gr.createGarden) h.ServeHTTP(w, r) // check HTTP response status code if w.Code != tt.code { t.Errorf("Unexpected status code: got %v, want %v", w.Code, tt.code) } // check HTTP response body matcher := regexp.MustCompile(tt.expectedRegexp) actual := strings.TrimSpace(w.Body.String()) if !matcher.MatchString(actual) { t.Errorf("Unexpected response body:\nactual = %v\nexpected = %v", actual, matcher.String()) } storageClient.AssertExpectations(t) }) } } func TestGetAllGardens(t *testing.T) { gardens := []*pkg.Garden{createExampleGarden()} tests := []struct { name string targetURL string setupMock func(*storage.MockClient) expectedRegexp string status int }{ { "SuccessfulEndDatedFalse", "/gardens", func(storageClient *storage.MockClient) { storageClient.On("GetGardens", false).Return(gardens, nil) }, `{"gardens":\[{"name":"test garden","id":"[0-9a-v]{20}","created_at":"\d{4}-\d{2}-\d\dT\d\d:\d\d:\d\d\.\d+(-07:00|Z)","plants":{"rel":"collection","href":"/gardens/[0-9a-v]{20}/plants"},"links":\[{"rel":"self","href":"/gardens/[0-9a-v]{20}"},{"rel":"health","href":"/gardens/[0-9a-v]{20}/health"},{"rel":"plants","href":"/gardens/[0-9a-v]{20}/plants"}\]}\]}`, http.StatusOK, }, { "SuccessfulEndDatedTrue", "/gardens?end_dated=true", func(storageClient *storage.MockClient) { storageClient.On("GetGardens", true).Return(gardens, nil) }, `{"gardens":\[{"name":"test garden","id":"[0-9a-v]{20}","created_at":"\d{4}-\d{2}-\d\dT\d\d:\d\d:\d\d\.\d+(-07:00|Z)","plants":{"rel":"collection","href":"/gardens/[0-9a-v]{20}/plants"},"links":\[{"rel":"self","href":"/gardens/[0-9a-v]{20}"},{"rel":"health","href":"/gardens/[0-9a-v]{20}/health"},{"rel":"plants","href":"/gardens/[0-9a-v]{20}/plants"}\]}\]}`, http.StatusOK, }, { "StorageClientError", "/gardens", func(storageClient *storage.MockClient) { storageClient.On("GetGardens", false).Return([]*pkg.Garden{}, errors.New("storage client error")) }, `{"status":"Error rendering response.","error":"storage client error"}`, http.StatusUnprocessableEntity, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { storageClient := new(storage.MockClient) gr := GardensResource{ storageClient: storageClient, config: Config{}, } tt.setupMock(storageClient) r := httptest.NewRequest("GET", tt.targetURL, nil) w := httptest.NewRecorder() h := http.HandlerFunc(gr.getAllGardens) h.ServeHTTP(w, r) // check HTTP response status code if w.Code != tt.status { t.Errorf("Unexpected status code: got %v, want %v", w.Code, tt.status) } // check HTTP response body matcher := regexp.MustCompile(tt.expectedRegexp) actual := strings.TrimSpace(w.Body.String()) if !matcher.MatchString(actual) { t.Errorf("Unexpected response body:\nactual = %v\nexpected = %v", actual, matcher.String()) } storageClient.AssertExpectations(t) }) } } func TestGetGarden(t *testing.T) { t.Run("Successful", func(t *testing.T) { storageClient := new(storage.MockClient) gr := GardensResource{ storageClient: storageClient, config: Config{}, } garden := createExampleGarden() ctx := context.WithValue(context.Background(), gardenCtxKey, garden) r := httptest.NewRequest("GET", "/garden", nil).WithContext(ctx) w := httptest.NewRecorder() h := http.HandlerFunc(gr.getGarden) h.ServeHTTP(w, r) // check HTTP response status code if w.Code != http.StatusOK { t.Errorf("Unexpected status code: got %v, want %v", w.Code, http.StatusOK) } gardenJSON, _ := json.Marshal(gr.NewGardenResponse(garden)) // check HTTP response body actual := strings.TrimSpace(w.Body.String()) if actual != string(gardenJSON) { t.Errorf("Unexpected response body:\nactual = %v\nexpected = %v", actual, string(gardenJSON)) } storageClient.AssertExpectations(t) }) } func TestEndDateGarden(t *testing.T) { tests := []struct { name string setupMock func(*storage.MockClient) expectedRegexp string status int }{ { "Successful", func(storageClient *storage.MockClient) { storageClient.On("SaveGarden", mock.Anything).Return(nil) }, `{"name":"test garden","id":"[0-9a-v]{20}","created_at":"\d{4}-\d{2}-\d\dT\d\d:\d\d:\d\d\.\d+(-07:00|Z)","end_date":"\d{4}-\d{2}-\d\dT\d\d:\d\d:\d\d\.\d+(-07:00|Z)","plants":{"rel":"collection","href":"/gardens/[0-9a-v]{20}/plants"},"links":\[{"rel":"self","href":"/gardens/[0-9a-v]{20}"},{"rel":"health","href":"/gardens/[0-9a-v]{20}/health"},{"rel":"plants","href":"/gardens/[0-9a-v]{20}/plants"}\]}`, http.StatusOK, }, { "StorageClientError", func(storageClient *storage.MockClient) { storageClient.On("SaveGarden", mock.Anything).Return(errors.New("storage client error")) }, `{"status":"Server Error.","error":"storage client error"}`, http.StatusInternalServerError, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { storageClient := new(storage.MockClient) tt.setupMock(storageClient) gr := GardensResource{ storageClient: storageClient, config: Config{}, } garden := createExampleGarden() ctx := context.WithValue(context.Background(), gardenCtxKey, garden) r := httptest.NewRequest("DELETE", "/garden", nil).WithContext(ctx) w := httptest.NewRecorder() h := http.HandlerFunc(gr.endDateGarden) h.ServeHTTP(w, r) // check HTTP response status code if w.Code != tt.status { t.Errorf("Unexpected status code: got %v, want %v", w.Code, tt.status) } // check HTTP response body matcher := regexp.MustCompile(tt.expectedRegexp) actual := strings.TrimSpace(w.Body.String()) if !matcher.MatchString(actual) { t.Errorf("Unexpected response body:\nactual = %v\nexpected = %v", actual, matcher.String()) } }) } } func TestUpdateGarden(t *testing.T) { tests := []struct { name string setupMock func(*storage.MockClient) body string expectedRegexp string status int }{ { "Successful", func(storageClient *storage.MockClient) { storageClient.On("SaveGarden", mock.Anything).Return(nil) }, `{"name": "new name"}`, `{"name":"new name","id":"[0-9a-v]{20}","created_at":"\d{4}-\d{2}-\d\dT\d\d:\d\d:\d\d\.\d+(-07:00|Z)","plants":{"rel":"collection","href":"/gardens/[0-9a-v]{20}/plants"},"links":\[{"rel":"self","href":"/gardens/[0-9a-v]{20}"},{"rel":"health","href":"/gardens/[0-9a-v]{20}/health"},{"rel":"plants","href":"/gardens/[0-9a-v]{20}/plants"}\]}`, http.StatusOK, }, { "StorageClientError", func(storageClient *storage.MockClient) { storageClient.On("SaveGarden", mock.Anything).Return(errors.New("storage client error")) }, `{"name": "new name"}`, `{"status":"Server Error.","error":"storage client error"}`, http.StatusInternalServerError, }, { "ErrorInvalidRequestBody", func(storageClient *storage.MockClient) {}, "{}", `{"status":"Invalid request.","error":"missing required Garden fields"}`, http.StatusBadRequest, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { storageClient := new(storage.MockClient) tt.setupMock(storageClient) gr := GardensResource{ storageClient: storageClient, config: Config{}, } garden := createExampleGarden() ctx := context.WithValue(context.Background(), gardenCtxKey, garden) r := httptest.NewRequest("PATCH", "/garden", strings.NewReader(tt.body)).WithContext(ctx) r.Header.Add("Content-Type", "application/json") w := httptest.NewRecorder() h := http.HandlerFunc(gr.updateGarden) h.ServeHTTP(w, r) // check HTTP response status code if w.Code != tt.status { t.Errorf("Unexpected status code: got %v, want %v", w.Code, tt.status) } // check HTTP response body matcher := regexp.MustCompile(tt.expectedRegexp) actual := strings.TrimSpace(w.Body.String()) if !matcher.MatchString(actual) { t.Errorf("Unexpected response body:\nactual = %v\nexpected = %v", actual, matcher.String()) } }) } } func TestGetGardenHealth(t *testing.T) { now := time.Now() fiveMinutesAgo := time.Now().Add(-5 * time.Minute) tests := []struct { name string time time.Time err error expectedStatus string }{ { "UP", now, nil, "UP", }, { "DOWN", fiveMinutesAgo, nil, "DOWN", }, { "N/A", now, errors.New("influxdb error"), "N/A", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { storageClient := new(storage.MockClient) influxdbClient := new(influxdb.MockClient) gr := GardensResource{ storageClient: storageClient, influxdbClient: influxdbClient, config: Config{}, } garden := createExampleGarden() influxdbClient.On("GetLastContact", mock.Anything, "test garden").Return(tt.time, tt.err) influxdbClient.On("Close") ctx := context.WithValue(context.Background(), gardenCtxKey, garden) r := httptest.NewRequest("GET", "/health", nil).WithContext(ctx) w := httptest.NewRecorder() h := http.HandlerFunc(gr.getGardenHealth) h.ServeHTTP(w, r) // check HTTP response status code if w.Code != http.StatusOK { t.Errorf("Unexpected status code: got %v, want %v", w.Code, http.StatusOK) } // check HTTP response body var actual GardenHealthResponse err := json.Unmarshal(w.Body.Bytes(), &actual) if err != nil { t.Errorf("Unexpected error unmarshaling GardenHealthResponse: %v", err) } if actual.Status != tt.expectedStatus { t.Errorf("Unexpected response body:\nactual = %v\nexpected = %v", actual.Status, tt.expectedStatus) } storageClient.AssertExpectations(t) }) } }
// This is a fork of code in Go's image/png package. // // Package apng is used to do low-level APNG encoding. The APNG format is not // widely supported in browsers, however, it can be an efficient way to // represent raster graphics in a lossless encoding, for instance to overlay // over a video with ffmpeg. // // For encoding details, see: // // https://en.wikipedia.org/wiki/APNG#Technical_details // https://wiki.mozilla.org/APNG_Specification // https://www.w3.org/TR/PNG/ package apng
func removeDuplicates(nums []int) int { s:=0 f:=1 for f<len(nums){ if nums[s]==nums[f]{ f++ }else{ if f-s>1 { nums[s+1]=nums[f] } f++ s++ } } return s+1 }
package day05 import "fmt" func BigToSmallInt() { var big int64 = 1234567890 fmt.Printf("big: %b\t %d\n", big, big) fmt.Printf("BigToSmallInt: %d\t %b\n", uint8(big), uint8(big)) /* 十进制 二进制 1234567890 1001001100101100000001011010010 210 11010010 1001001100101100000001011010010 ---> 高位截断 ---> 11010010 ---> 无符号十进制:2+16+64+128=210 */ }
package http import ( "context" "encoding/json" "net/http" "time" "github.com/dheerajgopi/todo-api/common" todoErr "github.com/dheerajgopi/todo-api/common/error" "github.com/dheerajgopi/todo-api/common/middlewares" "github.com/dheerajgopi/todo-api/models" "github.com/dheerajgopi/todo-api/task" "github.com/gorilla/mux" ) // TaskHandler represents HTTP handler for tasks type TaskHandler struct { TaskService task.Service App *common.App } // New creates new HTTP handler for task func New(router *mux.Router, service task.Service, app *common.App) { handler := &TaskHandler{ TaskService: service, App: app, } jwtMiddleware := middlewares.JwtValidator(app.Config.Auth.Jwt.Secret) router.HandleFunc("/tasks", app.CreateHandler(jwtMiddleware(handler.Create))).Methods("POST") router.HandleFunc("/tasks", app.CreateHandler(jwtMiddleware(handler.List))).Methods("GET") } // Create will store new task func (handler *TaskHandler) Create(res http.ResponseWriter, req *http.Request, reqCtx *common.RequestContext) (int, interface{}, *todoErr.APIError) { defer req.Body.Close() decoder := json.NewDecoder(req.Body) var createTaskReqBody CreateTaskRequest err := decoder.Decode(&createTaskReqBody) if err != nil { apiError := todoErr.NewAPIError("", &todoErr.APIErrorBody{ Message: "Invalid request body", }) return http.StatusBadRequest, nil, apiError } validationErrors := createTaskReqBody.ValidateAndBuild() if len(validationErrors) > 0 { apiError := todoErr.NewAPIError("", validationErrors...) return http.StatusBadRequest, nil, apiError } now := time.Now() newTask := &models.Task{ Title: createTaskReqBody.Title, Description: createTaskReqBody.Description, CreatedBy: &models.User{ ID: reqCtx.UserID, }, IsComplete: false, CreatedAt: now, UpdatedAt: now, } switch err = handler.TaskService.Create(context.TODO(), newTask); err.(type) { case nil: break default: apiError := todoErr.NewAPIError(err.Error(), &todoErr.APIErrorBody{ Message: "Internal server error", }) return http.StatusInternalServerError, nil, apiError } taskData := &TaskData{ ID: newTask.ID, Title: newTask.Title, Description: newTask.Description, IsComplete: newTask.IsComplete, CreatedAt: newTask.CreatedAt, UpdatedAt: newTask.UpdatedAt, } responseData := &CreateTaskResponse{ Task: taskData, } return http.StatusCreated, responseData, nil } // List will return all tasks func (handler *TaskHandler) List(res http.ResponseWriter, req *http.Request, reqCtx *common.RequestContext) (int, interface{}, *todoErr.APIError) { taskList := make([]*TaskData, 0) tasksByUserID, err := handler.TaskService.List(context.TODO(), reqCtx.UserID) switch err { case nil: break default: apiError := todoErr.NewAPIError(err.Error(), &todoErr.APIErrorBody{ Message: "Internal server error", }) return http.StatusInternalServerError, nil, apiError } for _, task := range tasksByUserID { taskList = append(taskList, &TaskData{ ID: task.ID, Title: task.Title, Description: task.Description, IsComplete: task.IsComplete, CreatedAt: task.CreatedAt, UpdatedAt: task.UpdatedAt, }) } responseData := &ListTaskResponse{ Tasks: taskList, } return http.StatusOK, responseData, nil }
package rule import ( "database/sql" "encoding/json" "fmt" "ism.com/common/db" ) type FieldGroup struct { Id string `json:"id"` Name string `json:"name"` FieldDelimeter NullString `json:"fDelimeter"` Fields []FieldMap `json:"fields"` } type FieldMap struct { FieldIndex int `json:"fIndex"` FieldId string `json:"fldId"` FieldOffset int `json:"fldOffset"` DiffValue int `json:"diffValue"` Iskey string `json:"isKey"` Isnull string `json:"isNull"` Issqlfunction string `json:"isSqlFunction"` LengthFieldType NullString `json:"lendthFldType"` InOutType NullString `json:"inoutType"` FilterType NullString `json:"filterType"` } type Field struct { Id string `json:"id"` Name string `json:"name"` FieldType string `json:"fldType"` FieldLength int `json:"fldLength"` FieldFormat string `json:"fldFormat"` Fillchar string `json:"fillChar"` Aligntype string `json:"alignType"` } func GetField(id string) (string, error) { var fld Field dbConn := db.GetDatabase() stmt, err := dbConn.Prepare(fld_sql) if err != nil { panic(err.Error()) } defer stmt.Close() err = stmt.QueryRow(id).Scan(&fld.Id, &fld.Name, &fld.FieldType, &fld.FieldLength, &fld.FieldFormat, &fld.Fillchar, &fld.Aligntype) if err != nil { if err == sql.ErrNoRows { println("not found") err = nil } else { return "", err } } b, err := json.Marshal(fld) if err != nil { fmt.Printf("Error: %s", err) return "", err } return string(b), nil } func GetFieldGroup(id string) (string, error) { var flg FieldGroup dbConn := db.GetDatabase() stmt, err := dbConn.Prepare(flg_sql) if err != nil { panic(err.Error()) } defer stmt.Close() err = stmt.QueryRow(id).Scan(&flg.Id, &flg.Name, &flg.FieldDelimeter) if err != nil { if err == sql.ErrNoRows { println("not found") err = nil } else { return "", err } } if flg.Fields, err = getFieldGroupMap(id, dbConn); err != nil { fmt.Printf("Error: %s", err) return "", err } b, err := json.Marshal(flg) if err != nil { fmt.Printf("Error: %s", err) return "", err } return string(b), nil } func getFieldGroupMap(id string, dbConn *sql.DB) ([]FieldMap, error) { var fMaps []FieldMap stmt, err := dbConn.Prepare(flgMap_sql) if err != nil { panic(err.Error()) } rows, err := stmt.Query(id) if err != nil { panic(err.Error()) // proper error handling instead of panic in your app } defer rows.Close() for rows.Next() { // get RawBytes from data var fMap FieldMap if err := rows.Scan(&fMap.FieldIndex, &fMap.FieldId, &fMap.FieldOffset, &fMap.DiffValue, &fMap.Iskey, &fMap.Isnull, &fMap.Issqlfunction, &fMap.LengthFieldType, &fMap.InOutType, &fMap.FilterType); err != nil { panic(err.Error()) // proper error handling instead of panic in your app } fMaps = append(fMaps, fMap) } return fMaps, nil }
package authentication import ( "fmt" "strings" ber "github.com/go-asn1-ber/asn1-ber" ldap "github.com/go-ldap/ldap/v3" ) func ldapEntriesContainsEntry(needle *ldap.Entry, haystack []*ldap.Entry) bool { if needle == nil || len(haystack) == 0 { return false } for i := 0; i < len(haystack); i++ { if haystack[i].DN == needle.DN { return true } } return false } func ldapGetFeatureSupportFromEntry(entry *ldap.Entry) (controlTypeOIDs, extensionOIDs []string, features LDAPSupportedFeatures) { if entry == nil { return controlTypeOIDs, extensionOIDs, features } for _, attr := range entry.Attributes { switch attr.Name { case ldapSupportedControlAttribute: controlTypeOIDs = attr.Values for _, oid := range attr.Values { switch oid { case ldapOIDControlMsftServerPolicyHints: features.ControlTypes.MsftPwdPolHints = true case ldapOIDControlMsftServerPolicyHintsDeprecated: features.ControlTypes.MsftPwdPolHintsDeprecated = true } } case ldapSupportedExtensionAttribute: extensionOIDs = attr.Values for _, oid := range attr.Values { switch oid { case ldapOIDExtensionPwdModifyExOp: features.Extensions.PwdModifyExOp = true case ldapOIDExtensionTLS: features.Extensions.TLS = true } } } } return controlTypeOIDs, extensionOIDs, features } func ldapEscape(inputUsername string) string { inputUsername = ldap.EscapeFilter(inputUsername) for _, c := range specialLDAPRunes { inputUsername = strings.ReplaceAll(inputUsername, string(c), fmt.Sprintf("\\%c", c)) } return inputUsername } func ldapGetReferral(err error) (referral string, ok bool) { switch e := err.(type) { case *ldap.Error: if e.ResultCode != ldap.LDAPResultReferral { return "", false } if e.Packet == nil { return "", false } if len(e.Packet.Children) < 2 { return "", false } if e.Packet.Children[1].Tag != ber.TagObjectDescriptor { return "", false } for i := 0; i < len(e.Packet.Children[1].Children); i++ { if e.Packet.Children[1].Children[i].Tag != ber.TagBitString || len(e.Packet.Children[1].Children[i].Children) < 1 { continue } referral, ok = e.Packet.Children[1].Children[i].Children[0].Value.(string) if !ok { continue } return referral, true } return "", false default: return "", false } }
package cryptobox_test import ( "crypto/rand" "crypto/sha512" "encoding/base64" "errors" "github.com/GoKillers/libsodium-go/cryptobox" generichash "github.com/GoKillers/libsodium-go/cryptogenerichash" "github.com/GoKillers/libsodium-go/cryptosign" "github.com/agl/ed25519/extra25519" "github.com/btcsuite/btcutil/base58" "github.com/stretchr/testify/require" "golang.org/x/crypto/blake2b" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/nacl/box" "golang.org/x/crypto/nacl/sign" "testing" ) // randReader is a cryptographically secure random number generator var randReader = rand.Reader func TestCryptoBoxSeal(t *testing.T) { sk, pk, exit := cryptobox.CryptoBoxKeyPair() if exit != 0 { t.Fatalf("CryptoBoxKeyPair failed: %v", exit) } testStr := "test string 12345678901234567890123456789012345678901234567890" cipherText, exit := cryptobox.CryptoBoxSeal([]byte(testStr), pk) if exit != 0 { t.Fatalf("CryptoBoxSeal failed: %v", exit) } plaintext, exit := cryptobox.CryptoBoxSealOpen(cipherText, pk, sk) if exit != 0 { t.Fatalf("CryptoBoxSealOpen failed: %v", exit) } if string(plaintext) != testStr { t.Fatalf("Bad plaintext: %#v", plaintext) } } type keyPairEd25519 struct { priv *[chacha20poly1305.KeySize + chacha20poly1305.KeySize]byte pub *[chacha20poly1305.KeySize]byte } type keyPairCurve25519 struct { priv *[chacha20poly1305.KeySize]byte pub *[chacha20poly1305.KeySize]byte } func TestBoxVsBox(t *testing.T) { var err error sendKey := keyPairEd25519{} sendKey.pub, sendKey.priv, err = sign.GenerateKey(rand.Reader) require.NoError(t, err) recKey := keyPairCurve25519{} recKey.pub, recKey.priv, err = box.GenerateKey(rand.Reader) require.NoError(t, err) t.Run("Test /x/nacl/box.Seal against libsodium crypto_box_easy_open", func(t *testing.T) { var plaintext = []byte("Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci " + "velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem") var nonce [24]byte // generate ephemeral asymmetric keys epk, esk, err := box.GenerateKey(rand.Reader) require.NoError(t, err) var out = make([]byte, 0) copy(out, epk[:]) // now seal the msg with the ephemeral key, nonce and pubKey (which is recipient's publicKey) ciphertext := box.Seal(out, plaintext, &nonce, recKey.pub, esk) ciphertext2, rc := cryptobox.CryptoBoxEasy(plaintext, nonce[:], recKey.pub[:], esk[:]) require.Equal(t, 0, rc) t.Logf("box.Seal: %s", base64.URLEncoding.EncodeToString(ciphertext)) t.Logf("crypto_box_easy: %s", base64.URLEncoding.EncodeToString(ciphertext2)) require.Equal(t, ciphertext, ciphertext2) decode, rc := cryptobox.CryptoBoxOpenEasy(ciphertext, nonce[:], epk[:], recKey.priv[:]) require.Equal(t, 0, rc) require.Equal(t, plaintext, decode) t.Log("Payload unchanged through encrypt-decrypt.") }) t.Run("Verify nonce equality", func(t *testing.T) { // generate ephemeral asymmetric keys epk, _, err := box.GenerateKey(rand.Reader) require.NoError(t, err) nonceCorrect, err := naclNonce(epk[:], recKey.pub[:]) require.NoError(t, err) nonceTest, err := makeNonce(epk[:], recKey.pub[:]) require.NoError(t, err) t.Log("Successful nonce generation. Testing nonce equality:") t.Logf("Test nonce: %s", base64.URLEncoding.EncodeToString(nonceTest)) t.Logf("Correct nonce: %s", base64.URLEncoding.EncodeToString(nonceCorrect)) require.Equal(t, nonceCorrect, nonceTest) }) t.Run("Test sodiumBoxSeal -> crypto_box_seal_open", func(t *testing.T) { payload := []byte("lorem ipsum doler sit magnet, ada piscine elit, consecutive ada piscine velit") ciphertext, err := sodiumBoxSeal(payload, recKey.pub) require.NoError(t, err) message, rc := cryptobox.CryptoBoxSealOpen(ciphertext, recKey.pub[:], recKey.priv[:]) require.Equal(t, 0, rc) require.Equal(t, payload, message) t.Log("Payload unchanged through encrypt-decrypt.") }) t.Run("Test sodiumBoxSeal -> sodiumBoxSealOpen", func(t *testing.T) { payload := []byte("lorem ipsum doler sit magnet, ada piscine elit, consecutive ada piscine velit") ciphertext, err := sodiumBoxSeal(payload, recKey.pub) require.NoError(t, err) message, err := sodiumBoxSealOpen(ciphertext, recKey.pub, recKey.priv) require.NoError(t, err) require.Equal(t, payload, message) t.Log("Payload unchanged through encrypt-decrypt.") }) t.Run("Test CryptoBoxSeal -> sodiumBoxSealOpen", func(t *testing.T) { payload := []byte("lorem ipsum doler sit magnet, ada piscine elit, consecutive ada piscine velit") ciphertext, rc := cryptobox.CryptoBoxSeal(payload, recKey.pub[:]) require.Equal(t, 0, rc) message, err := sodiumBoxSealOpen(ciphertext, recKey.pub, recKey.priv) require.NoError(t, err) require.Equal(t, payload, message) t.Log("Payload unchanged through encrypt-decrypt.") }) } func TestKeyConversion(t *testing.T) { var err error t.Run("Test secret key conversion from Ed25519 to curve25519", func(t *testing.T) { testKey := keyPairEd25519{} testKey.pub, testKey.priv, err = sign.GenerateKey(randReader) require.NoError(t, err) ret, rc := cryptosign.CryptoSignEd25519SkToCurve25519(testKey.priv[:]) require.Equal(t, 0, rc) ret2, err := secretEd25519toCurve25519(testKey.priv) require.NoError(t, err) print("Expected conversion: ", base64.URLEncoding.EncodeToString(ret), "\n") print("Actual conversion : ", base64.URLEncoding.EncodeToString(ret2[:]), "\n") require.ElementsMatch(t, ret, ret2[:]) }) t.Run("Test public key conversion from Ed25519 to curve25519", func(t *testing.T) { testKey := keyPairEd25519{} testKey.pub, testKey.priv, err = sign.GenerateKey(randReader) require.NoError(t, err) pub1, rc := cryptosign.CryptoSignEd25519PkToCurve25519(testKey.pub[:]) require.Equal(t, 0, rc) pub2, err := publicEd25519toCurve25519(testKey.pub) require.NoError(t, err) print("Expected conversion: ", base64.URLEncoding.EncodeToString(pub1), "\n") print("Actual conversion : ", base64.URLEncoding.EncodeToString(pub2[:]), "\n") require.ElementsMatch(t, pub1, pub2[:]) }) t.Run("Test large number of public key conversions", func(t *testing.T) { testKey := keyPairEd25519{} for i := 0; i < 30000; i++ { testKey.pub, testKey.priv, err = sign.GenerateKey(randReader) require.NoError(t, err) pub1, rc := cryptosign.CryptoSignEd25519PkToCurve25519(testKey.pub[:]) require.Equal(t, 0, rc) pub2, err := publicEd25519toCurve25519(testKey.pub) require.NoError(t, err) require.ElementsMatch(t, pub1, pub2[:]) } }) t.Run("Generate public key test data", func(t *testing.T) { edKey := keyPairEd25519{} keys := []keyPairEd25519{} for i := 0; i < 20; i++ { edKey.pub, edKey.priv, err = sign.GenerateKey(randReader) keys = append(keys, edKey) require.NoError(t, err) keyString := base58.Encode(edKey.pub[:]) print("\"", keyString, "\",\n") } println("") for _, key := range keys { curvePub, rc := cryptosign.CryptoSignEd25519PkToCurve25519(key.pub[:]) require.Equal(t, 0, rc) keyString := base58.Encode(curvePub[:]) print("\"", keyString, "\",\n") } }) t.Run("Generate private key test data", func(t *testing.T) { edKey := keyPairEd25519{} keys := []keyPairEd25519{} for i := 0; i < 20; i++ { edKey.pub, edKey.priv, err = sign.GenerateKey(randReader) keys = append(keys, edKey) require.NoError(t, err) keyString := base58.Encode(edKey.priv[:]) print("\"", keyString, "\",\n") } println("") for _, key := range keys { curvePriv, rc := cryptosign.CryptoSignEd25519SkToCurve25519(key.priv[:]) require.Equal(t, 0, rc) keyString := base58.Encode(curvePriv[:]) print("\"", keyString, "\",\n") } }) } func publicEd25519toCurve25519(pub *[chacha20poly1305.KeySize]byte) (*[chacha20poly1305.KeySize]byte, error) { pkOut := new([32]byte) success := extra25519.PublicKeyToCurve25519(pkOut, pub) if !success { return nil, errors.New("Failed to convert public key") } return pkOut, nil } // secretEd25519toCurve25519 converts a secret key from Ed25519 to curve25519 format // Made with reference to https://github.com/agl/ed25519/blob/master/extra25519/extra25519.go and // https://github.com/jedisct1/libsodium/blob/927dfe8e2eaa86160d3ba12a7e3258fbc322909c/src/libsodium/crypto_sign/ed25519/ref10/keypair.c#L70 func secretEd25519toCurve25519(priv *[chacha20poly1305.KeySize + chacha20poly1305.KeySize]byte) (*[chacha20poly1305.KeySize]byte, error) { hasher := sha512.New() _, err := hasher.Write(priv[:32]) if err != nil { return nil, err } hash := hasher.Sum(nil) hash[0] &= 248 // clr lower 3 bits hash[31] &= 127 // clr upper 1 bit hash[31] |= 64 // set 6th bit out := new([chacha20poly1305.KeySize]byte) copy(out[:], hash) return out, nil } func makeNonce(pub1 []byte, pub2 []byte ) ([]byte, error) { var nonce [24]byte // generate an equivalent nonce to libsodium's (see link above) nonceWriter, err := blake2b.New(24, nil) if err != nil { return nil, err } _, err = nonceWriter.Write(pub1[:]) if err != nil { return nil, err } _, err = nonceWriter.Write(pub2[:]) if err != nil { return nil, err } nonceOut := nonceWriter.Sum(nil) copy(nonce[:], nonceOut) //copy(nonce[:], nonceSlice) return nonce[:], nil } func naclNonce(pub1 []byte, pub2 []byte) ([]byte, error) { state, rc := generichash.CryptoGenericHashInit(nil, 24) if rc != 0 { return nil, errors.New("nonce init failed") } state, rc = generichash.CryptoGenericHashUpdate(state, pub1) if rc != 0 { return nil, errors.New("nonce update failed") } state, rc = generichash.CryptoGenericHashUpdate(state, pub2) if rc != 0 { return nil, errors.New("nonce update failed") } state, out, rc := generichash.CryptoGenericHashFinal(state, 24) if rc != 0 { return nil, errors.New("nonce finalization failed") } return out, nil } func sodiumBoxSeal(msg []byte, pubKey *[chacha20poly1305.KeySize]byte) ([]byte, error) { var nonce [24]byte // generate ephemeral asymmetric keys epk, esk, err := box.GenerateKey(rand.Reader) if err != nil { return nil, err } // generate an equivalent nonce to libsodium's (see link above) nonceSlice, err := makeNonce(epk[:], pubKey[:]) if err != nil { return nil, err } copy(nonce[:], nonceSlice) var out = make([]byte, len(epk)) copy(out, epk[:]) // now seal the msg with the ephemeral key, nonce and pubKey (which is recipient's publicKey) ret := box.Seal(out, msg, &nonce, pubKey, esk) return ret, nil } func sodiumBoxSealOpen(msg []byte, recPub *[32]byte, recPriv *[32]byte) ([]byte, error) { if len(msg) < 32 { return nil, errors.New("Message too short") } var epk [32]byte copy(epk[:], msg[:32]) var nonce [24]byte nonceSlice, err := makeNonce(epk[:], recPub[:]) if err != nil { return nil, err } copy(nonce[:], nonceSlice) out, success := box.Open(nil, msg[32:], &nonce, &epk, recPriv) if !success { return nil, errors.New("Failed to unpack") } return out, nil }
package jarviscore import ( "io/ioutil" "os" "go.uber.org/zap/zapcore" yaml "gopkg.in/yaml.v2" jarvisbase "github.com/zhs007/jarviscore/base" "go.uber.org/zap" ) // Config - config type Config struct { //------------------------------------------------------------------ // base configuration RootServAddr string LstTrustNode []string // TimeRequestChild - RequestChild time // - default 30s TimeRequestChild int64 // MaxMsgLength - default 4mb MaxMsgLength int32 //------------------------------------------------------------------ // pprof configuration Pprof struct { BaseURL string } //------------------------------------------------------------------ // task server configuration TaskServ struct { BindAddr string ServAddr string } //------------------------------------------------------------------ // http server configuration HTTPServ struct { BindAddr string ServAddr string } //------------------------------------------------------------------ // ankadb configuration AnkaDB struct { DBPath string HTTPServ string Engine string } //------------------------------------------------------------------ // logger configuration Log struct { LogPath string LogLevel string LogConsole bool LogSubFileName string } //------------------------------------------------------------------ // basenodeinfo configuration BaseNodeInfo struct { NodeName string BindAddr string ServAddr string } //------------------------------------------------------------------ // auto update AutoUpdate bool UpdateScript string RestartScript string } // const normalLogFilename = "output.log" // const errLogFilename = "error.log" // var config Config func getLogLevel(str string) zapcore.Level { switch str { case "debug": return zapcore.DebugLevel case "info": return zapcore.InfoLevel case "warn": return zapcore.WarnLevel default: return zapcore.ErrorLevel } } // InitJarvisCore - func InitJarvisCore(cfg *Config, nodeType string, version string) { // config = cfg cfg.Log.LogSubFileName = jarvisbase.BuildLogSubFilename(nodeType, version) jarvisbase.InitLogger(getLogLevel(cfg.Log.LogLevel), cfg.Log.LogConsole, cfg.Log.LogPath, cfg.Log.LogSubFileName) jarvisbase.Info("InitJarvisCore", zap.String("DBPath", cfg.AnkaDB.DBPath), zap.String("RootServAddr", cfg.RootServAddr), zap.String("LogPath", cfg.Log.LogPath)) return } // ReleaseJarvisCore - func ReleaseJarvisCore() error { jarvisbase.SyncLogger() return nil } func checkConfig(cfg *Config) error { if cfg.TimeRequestChild <= 0 { cfg.TimeRequestChild = 180 } if cfg.MaxMsgLength <= 0 { cfg.MaxMsgLength = 4194304 } if cfg.AutoUpdate { if cfg.UpdateScript == "" || cfg.RestartScript == "" { return ErrCfgInvalidUpdateScript } } return nil } // func getRealPath(filename string) string { // return path.Join(config.RunPath, filename) // } // LoadConfig - load config func LoadConfig(filename string) (*Config, error) { fi, err := os.Open(filename) if err != nil { return nil, err } defer fi.Close() fd, err := ioutil.ReadAll(fi) if err != nil { return nil, err } cfg := &Config{} err = yaml.Unmarshal(fd, cfg) if err != nil { return nil, err } err = checkConfig(cfg) if err != nil { return nil, err } return cfg, nil }
package api import ( "fmt" "github.com/alec-z/interests-back/model" "github.com/labstack/echo/v4" "golang.org/x/net/websocket" "math" "net/http" ) func Calculate(c echo.Context) (err error) { m := new(echo.Map) if err = c.Bind(m); err != nil { return } interestInput := new(model.InterestsInput) interestInput.BindFromMap(*m) sol := interestInput.GetInterests() aR := math.Pow(sol.Sol, 365) tmpSol := (math.Pow(aR, 1 / 12.0) - 1) * 12 * 100.0 sol.SolStr = fmt.Sprintf("%.2f", tmpSol)+"%" return c.JSON(http.StatusOK, sol) } func CalculateItem(c echo.Context) (err error) { m := new(model.ItemsInput) if err = c.Bind(m); err != nil { return } res := fmt.Sprintf("%.2f", m.GetItems()) return c.JSON(http.StatusOK, res) } func WsCalculate(c echo.Context) error { websocket.Handler(func(ws *websocket.Conn) { defer ws.Close() for { // Read msg := "" interestInput := new(model.InterestsInput) err := websocket.JSON.Receive(ws, &interestInput) sol := interestInput.GetInterests() aR := math.Pow(sol.Sol, 365) tmpSol := (math.Pow(aR, 1 / 12.0) - 1) * 12 * 100.0 sol.SolStr = fmt.Sprintf("%.2f", tmpSol)+"%" if err != nil { c.Logger().Error(err) } err = websocket.JSON.Send(ws, sol) if err != nil { c.Logger().Error(err) } fmt.Printf("%s\n", msg) } }).ServeHTTP(c.Response(), c.Request()) return nil }
package goproxy // Router routes to some plugin type Router struct { tree *node } // NewRouter ... func NewRouter() (*Router, error) { return &Router{ tree: &node{}, }, nil } // AddRoute add plugin for a given path mask func (r *Router) AddRoute(mask string, f Plugin) error { return r.tree.addNode(mask, f) } // Plugin returns plugin for given route func (r *Router) Factory(path string) Plugin { return r.tree.getNode(path) }
/* Copyright IBM Corporation 2020 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 metadata import ( "io/ioutil" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/runtime/serializer" "github.com/konveyor/move2kube/internal/apiresourceset" common "github.com/konveyor/move2kube/internal/common" irtypes "github.com/konveyor/move2kube/internal/types" plantypes "github.com/konveyor/move2kube/types/plan" ) //K8sFilesLoader Implements Loader interface type K8sFilesLoader struct { } // UpdatePlan - output a plan based on the input directory contents func (i K8sFilesLoader) UpdatePlan(inputPath string, plan *plantypes.Plan) error { codecs := serializer.NewCodecFactory((&apiresourceset.K8sAPIResourceSet{}).GetScheme()) files, err := common.GetFilesByExt(inputPath, []string{".yml", ".yaml"}) if err != nil { return err } for _, path := range files { relpath, _ := plan.GetRelativePath(path) data, err := ioutil.ReadFile(path) if err != nil { log.Debugf("ignoring file %s", path) continue } _, _, err = codecs.UniversalDeserializer().Decode(data, nil, nil) if err != nil { log.Debugf("ignoring file %s since serialization failed", path) continue } plan.Spec.Inputs.K8sFiles = append(plan.Spec.Inputs.K8sFiles, relpath) } return nil } // LoadToIR loads k8s files as cached objects func (i K8sFilesLoader) LoadToIR(p plantypes.Plan, ir *irtypes.IR) error { codecs := serializer.NewCodecFactory((&apiresourceset.K8sAPIResourceSet{}).GetScheme()) for _, path := range p.Spec.Inputs.K8sFiles { fullpath := p.GetFullPath(path) data, err := ioutil.ReadFile(fullpath) if err != nil { log.Debugf("ignoring file %s", path) continue } obj, _, err := codecs.UniversalDeserializer().Decode(data, nil, nil) if err != nil { log.Debugf("ignoring file %s since serialization failed", path) continue } ir.CachedObjects = append(ir.CachedObjects, obj) } return nil }
package testdata // NOTE: THIS FILE WAS PRODUCED BY THE // ZEBRAPACK CODE GENERATION TOOL (github.com/glycerine/zebrapack) // DO NOT EDIT import ( "github.com/glycerine/zebrapack/msgp" ) // MSGPfieldsNotEmpty supports omitempty tags func (z *A) MSGPfieldsNotEmpty(isempty []bool) uint32 { if len(isempty) == 0 { return 6 } var fieldsInUse uint32 = 6 isempty[2] = (len(z.Phone) == 0) // string, omitempty if isempty[2] { fieldsInUse-- } isempty[3] = (z.Sibs == 0) // number, omitempty if isempty[3] { fieldsInUse-- } return fieldsInUse } // MSGPMarshalMsg implements msgp.Marshaler func (z *A) MSGPMarshalMsg(b []byte) (o []byte, err error) { if p, ok := interface{}(z).(msgp.PreSave); ok { p.PreSaveHook() } o = msgp.Require(b, z.MSGPMsgsize()) // honor the omitempty tags var empty [6]bool fieldsInUse := z.fieldsNotEmpty(empty[:]) o = msgp.AppendMapHeader(o, fieldsInUse) // string "name" o = append(o, 0xa4, 0x6e, 0x61, 0x6d, 0x65) o = msgp.AppendString(o, z.Name) // string "Bday" o = append(o, 0xa4, 0x42, 0x64, 0x61, 0x79) o = msgp.AppendTime(o, z.Bday) if !empty[2] { // string "phone" o = append(o, 0xa5, 0x70, 0x68, 0x6f, 0x6e, 0x65) o = msgp.AppendString(o, z.Phone) } if !empty[3] { // string "Sibs" o = append(o, 0xa4, 0x53, 0x69, 0x62, 0x73) o = msgp.AppendInt(o, z.Sibs) } // string "GPA" o = append(o, 0xa3, 0x47, 0x50, 0x41) o = msgp.AppendFloat64(o, z.GPA) // string "Friend" o = append(o, 0xa6, 0x46, 0x72, 0x69, 0x65, 0x6e, 0x64) o = msgp.AppendBool(o, z.Friend) return } // MSGPUnmarshalMsg implements msgp.Unmarshaler func (z *A) MSGPUnmarshalMsg(bts []byte) (o []byte, err error) { return z.MSGPUnmarshalMsgWithCfg(bts, nil) } func (z *A) MSGPUnmarshalMsgWithCfg(bts []byte, cfg *msgp.RuntimeConfig) (o []byte, err error) { var nbs msgp.NilBitsStack nbs.Init(cfg) var sawTopNil bool if msgp.IsNil(bts) { sawTopNil = true bts = nbs.PushAlwaysNil(bts[1:]) } var field []byte _ = field const maxFields0znpa = 6 // -- templateUnmarshalMsg starts here-- var totalEncodedFields0znpa uint32 if !nbs.AlwaysNil { totalEncodedFields0znpa, bts, err = nbs.ReadMapHeaderBytes(bts) if err != nil { return } } encodedFieldsLeft0znpa := totalEncodedFields0znpa missingFieldsLeft0znpa := maxFields0znpa - totalEncodedFields0znpa var nextMiss0znpa int32 = -1 var found0znpa [maxFields0znpa]bool var curField0znpa string doneWithStruct0znpa: // First fill all the encoded fields, then // treat the remaining, missing fields, as Nil. for encodedFieldsLeft0znpa > 0 || missingFieldsLeft0znpa > 0 { //fmt.Printf("encodedFieldsLeft: %v, missingFieldsLeft: %v, found: '%v', fields: '%#v'\n", encodedFieldsLeft0znpa, missingFieldsLeft0znpa, msgp.ShowFound(found0znpa[:]), unmarshalMsgFieldOrder0znpa) if encodedFieldsLeft0znpa > 0 { encodedFieldsLeft0znpa-- field, bts, err = nbs.ReadMapKeyZC(bts) if err != nil { return } curField0znpa = msgp.UnsafeString(field) } else { //missing fields need handling if nextMiss0znpa < 0 { // set bts to contain just mnil (0xc0) bts = nbs.PushAlwaysNil(bts) nextMiss0znpa = 0 } for nextMiss0znpa < maxFields0znpa && (found0znpa[nextMiss0znpa] || unmarshalMsgFieldSkip0znpa[nextMiss0znpa]) { nextMiss0znpa++ } if nextMiss0znpa == maxFields0znpa { // filled all the empty fields! break doneWithStruct0znpa } missingFieldsLeft0znpa-- curField0znpa = unmarshalMsgFieldOrder0znpa[nextMiss0znpa] } //fmt.Printf("switching on curField: '%v'\n", curField0znpa) switch curField0znpa { // -- templateUnmarshalMsg ends here -- case "name": found0znpa[0] = true z.Name, bts, err = nbs.ReadStringBytes(bts) if err != nil { return } case "Bday": found0znpa[1] = true z.Bday, bts, err = nbs.ReadTimeBytes(bts) if err != nil { return } case "phone": found0znpa[2] = true z.Phone, bts, err = nbs.ReadStringBytes(bts) if err != nil { return } case "Sibs": found0znpa[3] = true z.Sibs, bts, err = nbs.ReadIntBytes(bts) if err != nil { return } case "GPA": found0znpa[4] = true z.GPA, bts, err = nbs.ReadFloat64Bytes(bts) if err != nil { return } case "Friend": found0znpa[5] = true z.Friend, bts, err = nbs.ReadBoolBytes(bts) if err != nil { return } default: bts, err = msgp.Skip(bts) if err != nil { return } } } if nextMiss0znpa != -1 { bts = nbs.PopAlwaysNil() } if sawTopNil { bts = nbs.PopAlwaysNil() } o = bts if p, ok := interface{}(z).(msgp.PostLoad); ok { p.PostLoadHook() } return } // fields of A var unmarshalMsgFieldOrder0znpa = []string{"name", "Bday", "phone", "Sibs", "GPA", "Friend"} var unmarshalMsgFieldSkip0znpa = []bool{false, false, false, false, false, false} // MSGPMsgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z *A) MSGPMsgsize() (s int) { s = 1 + 5 + msgp.StringPrefixSize + len(z.Name) + 5 + msgp.TimeSize + 6 + msgp.StringPrefixSize + len(z.Phone) + 5 + msgp.IntSize + 4 + msgp.Float64Size + 7 + msgp.BoolSize return } // MSGPfieldsNotEmpty supports omitempty tags func (z *Big) MSGPfieldsNotEmpty(isempty []bool) uint32 { return 5 } // MSGPMarshalMsg implements msgp.Marshaler func (z *Big) MSGPMarshalMsg(b []byte) (o []byte, err error) { if p, ok := interface{}(z).(msgp.PreSave); ok { p.PreSaveHook() } o = msgp.Require(b, z.MSGPMsgsize()) // map header, size 5 // string "Slice" o = append(o, 0x85, 0xa5, 0x53, 0x6c, 0x69, 0x63, 0x65) o = msgp.AppendArrayHeader(o, uint32(len(z.Slice))) for zenh := range z.Slice { o, err = z.Slice[zenh].MSGPMarshalMsg(o) if err != nil { return } } // string "Transform" o = append(o, 0xa9, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x66, 0x6f, 0x72, 0x6d) o = msgp.AppendMapHeader(o, uint32(len(z.Transform))) for zbec, zhxf := range z.Transform { o = msgp.AppendInt(o, zbec) if zhxf == nil { o = msgp.AppendNil(o) } else { o, err = zhxf.MSGPMarshalMsg(o) if err != nil { return } } } // string "Myptr" o = append(o, 0xa5, 0x4d, 0x79, 0x70, 0x74, 0x72) if z.Myptr == nil { o = msgp.AppendNil(o) } else { o, err = z.Myptr.MSGPMarshalMsg(o) if err != nil { return } } // string "Myarray" o = append(o, 0xa7, 0x4d, 0x79, 0x61, 0x72, 0x72, 0x61, 0x79) o = msgp.AppendArrayHeader(o, 3) for zrkq := range z.Myarray { o = msgp.AppendString(o, z.Myarray[zrkq]) } // string "MySlice" o = append(o, 0xa7, 0x4d, 0x79, 0x53, 0x6c, 0x69, 0x63, 0x65) o = msgp.AppendArrayHeader(o, uint32(len(z.MySlice))) for zcui := range z.MySlice { o = msgp.AppendString(o, z.MySlice[zcui]) } return } // MSGPUnmarshalMsg implements msgp.Unmarshaler func (z *Big) MSGPUnmarshalMsg(bts []byte) (o []byte, err error) { return z.MSGPUnmarshalMsgWithCfg(bts, nil) } func (z *Big) MSGPUnmarshalMsgWithCfg(bts []byte, cfg *msgp.RuntimeConfig) (o []byte, err error) { var nbs msgp.NilBitsStack nbs.Init(cfg) var sawTopNil bool if msgp.IsNil(bts) { sawTopNil = true bts = nbs.PushAlwaysNil(bts[1:]) } var field []byte _ = field const maxFields1zgme = 5 // -- templateUnmarshalMsg starts here-- var totalEncodedFields1zgme uint32 if !nbs.AlwaysNil { totalEncodedFields1zgme, bts, err = nbs.ReadMapHeaderBytes(bts) if err != nil { return } } encodedFieldsLeft1zgme := totalEncodedFields1zgme missingFieldsLeft1zgme := maxFields1zgme - totalEncodedFields1zgme var nextMiss1zgme int32 = -1 var found1zgme [maxFields1zgme]bool var curField1zgme string doneWithStruct1zgme: // First fill all the encoded fields, then // treat the remaining, missing fields, as Nil. for encodedFieldsLeft1zgme > 0 || missingFieldsLeft1zgme > 0 { //fmt.Printf("encodedFieldsLeft: %v, missingFieldsLeft: %v, found: '%v', fields: '%#v'\n", encodedFieldsLeft1zgme, missingFieldsLeft1zgme, msgp.ShowFound(found1zgme[:]), unmarshalMsgFieldOrder1zgme) if encodedFieldsLeft1zgme > 0 { encodedFieldsLeft1zgme-- field, bts, err = nbs.ReadMapKeyZC(bts) if err != nil { return } curField1zgme = msgp.UnsafeString(field) } else { //missing fields need handling if nextMiss1zgme < 0 { // set bts to contain just mnil (0xc0) bts = nbs.PushAlwaysNil(bts) nextMiss1zgme = 0 } for nextMiss1zgme < maxFields1zgme && (found1zgme[nextMiss1zgme] || unmarshalMsgFieldSkip1zgme[nextMiss1zgme]) { nextMiss1zgme++ } if nextMiss1zgme == maxFields1zgme { // filled all the empty fields! break doneWithStruct1zgme } missingFieldsLeft1zgme-- curField1zgme = unmarshalMsgFieldOrder1zgme[nextMiss1zgme] } //fmt.Printf("switching on curField: '%v'\n", curField1zgme) switch curField1zgme { // -- templateUnmarshalMsg ends here -- case "Slice": found1zgme[0] = true if nbs.AlwaysNil { (z.Slice) = (z.Slice)[:0] } else { var zygg uint32 zygg, bts, err = nbs.ReadArrayHeaderBytes(bts) if err != nil { return } if cap(z.Slice) >= int(zygg) { z.Slice = (z.Slice)[:zygg] } else { z.Slice = make([]S2, zygg) } for zenh := range z.Slice { bts, err = z.Slice[zenh].MSGPUnmarshalMsg(bts) if err != nil { return } if err != nil { return } } } case "Transform": found1zgme[1] = true if nbs.AlwaysNil { if len(z.Transform) > 0 { for key, _ := range z.Transform { delete(z.Transform, key) } } } else { var zbko uint32 zbko, bts, err = nbs.ReadMapHeaderBytes(bts) if err != nil { return } if z.Transform == nil && zbko > 0 { z.Transform = make(map[int]*S2, zbko) } else if len(z.Transform) > 0 { for key, _ := range z.Transform { delete(z.Transform, key) } } for zbko > 0 { var zbec int var zhxf *S2 zbko-- zbec, bts, err = nbs.ReadIntBytes(bts) if err != nil { return } if nbs.AlwaysNil { if zhxf != nil { zhxf.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil if msgp.IsNil(bts) { bts = bts[1:] if nil != zhxf { zhxf.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil and not IsNil(bts): have something to read if zhxf == nil { zhxf = new(S2) } bts, err = zhxf.MSGPUnmarshalMsg(bts) if err != nil { return } if err != nil { return } } } z.Transform[zbec] = zhxf } } case "Myptr": found1zgme[2] = true if nbs.AlwaysNil { if z.Myptr != nil { z.Myptr.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil if msgp.IsNil(bts) { bts = bts[1:] if nil != z.Myptr { z.Myptr.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil and not IsNil(bts): have something to read if z.Myptr == nil { z.Myptr = new(S2) } bts, err = z.Myptr.MSGPUnmarshalMsg(bts) if err != nil { return } if err != nil { return } } } case "Myarray": found1zgme[3] = true var zwcn uint32 zwcn, bts, err = nbs.ReadArrayHeaderBytes(bts) if err != nil { return } if !nbs.IsNil(bts) && zwcn != 3 { err = msgp.ArrayError{Wanted: 3, Got: zwcn} return } for zrkq := range z.Myarray { z.Myarray[zrkq], bts, err = nbs.ReadStringBytes(bts) if err != nil { return } } case "MySlice": found1zgme[4] = true if nbs.AlwaysNil { (z.MySlice) = (z.MySlice)[:0] } else { var zfns uint32 zfns, bts, err = nbs.ReadArrayHeaderBytes(bts) if err != nil { return } if cap(z.MySlice) >= int(zfns) { z.MySlice = (z.MySlice)[:zfns] } else { z.MySlice = make([]string, zfns) } for zcui := range z.MySlice { z.MySlice[zcui], bts, err = nbs.ReadStringBytes(bts) if err != nil { return } } } default: bts, err = msgp.Skip(bts) if err != nil { return } } } if nextMiss1zgme != -1 { bts = nbs.PopAlwaysNil() } if sawTopNil { bts = nbs.PopAlwaysNil() } o = bts if p, ok := interface{}(z).(msgp.PostLoad); ok { p.PostLoadHook() } return } // fields of Big var unmarshalMsgFieldOrder1zgme = []string{"Slice", "Transform", "Myptr", "Myarray", "MySlice"} var unmarshalMsgFieldSkip1zgme = []bool{false, false, false, false, false} // MSGPMsgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z *Big) MSGPMsgsize() (s int) { s = 1 + 6 + msgp.ArrayHeaderSize for zenh := range z.Slice { s += z.Slice[zenh].MSGPMsgsize() } s += 10 + msgp.MapHeaderSize if z.Transform != nil { for zbec, zhxf := range z.Transform { _ = zhxf _ = zbec s += msgp.IntSize if zhxf == nil { s += msgp.NilSize } else { s += zhxf.MSGPMsgsize() } } } s += 6 if z.Myptr == nil { s += msgp.NilSize } else { s += z.Myptr.MSGPMsgsize() } s += 8 + msgp.ArrayHeaderSize for zrkq := range z.Myarray { s += msgp.StringPrefixSize + len(z.Myarray[zrkq]) } s += 8 + msgp.ArrayHeaderSize for zcui := range z.MySlice { s += msgp.StringPrefixSize + len(z.MySlice[zcui]) } return } // MSGPfieldsNotEmpty supports omitempty tags func (z *S2) MSGPfieldsNotEmpty(isempty []bool) uint32 { return 7 } // MSGPMarshalMsg implements msgp.Marshaler func (z *S2) MSGPMarshalMsg(b []byte) (o []byte, err error) { if p, ok := interface{}(z).(msgp.PreSave); ok { p.PreSaveHook() } o = msgp.Require(b, z.MSGPMsgsize()) // map header, size 7 // string "beta" o = append(o, 0x87, 0xa4, 0x62, 0x65, 0x74, 0x61) o = msgp.AppendString(o, z.B) // string "ralph" o = append(o, 0xa5, 0x72, 0x61, 0x6c, 0x70, 0x68) o = msgp.AppendMapHeader(o, uint32(len(z.R))) for zhsq, zota := range z.R { o = msgp.AppendString(o, zhsq) o = msgp.AppendUint8(o, zota) } // string "P" o = append(o, 0xa1, 0x50) o = msgp.AppendUint16(o, z.P) // string "Q" o = append(o, 0xa1, 0x51) o = msgp.AppendUint32(o, z.Q) // string "T" o = append(o, 0xa1, 0x54) o = msgp.AppendInt64(o, z.T) // string "arr" o = append(o, 0xa3, 0x61, 0x72, 0x72) o = msgp.AppendArrayHeader(o, 6) for zcpf := range z.Arr { o = msgp.AppendFloat64(o, z.Arr[zcpf]) } // string "MyTree" o = append(o, 0xa6, 0x4d, 0x79, 0x54, 0x72, 0x65, 0x65) if z.MyTree == nil { o = msgp.AppendNil(o) } else { o, err = z.MyTree.MSGPMarshalMsg(o) if err != nil { return } } return } // MSGPUnmarshalMsg implements msgp.Unmarshaler func (z *S2) MSGPUnmarshalMsg(bts []byte) (o []byte, err error) { return z.MSGPUnmarshalMsgWithCfg(bts, nil) } func (z *S2) MSGPUnmarshalMsgWithCfg(bts []byte, cfg *msgp.RuntimeConfig) (o []byte, err error) { var nbs msgp.NilBitsStack nbs.Init(cfg) var sawTopNil bool if msgp.IsNil(bts) { sawTopNil = true bts = nbs.PushAlwaysNil(bts[1:]) } var field []byte _ = field const maxFields2zzaf = 8 // -- templateUnmarshalMsg starts here-- var totalEncodedFields2zzaf uint32 if !nbs.AlwaysNil { totalEncodedFields2zzaf, bts, err = nbs.ReadMapHeaderBytes(bts) if err != nil { return } } encodedFieldsLeft2zzaf := totalEncodedFields2zzaf missingFieldsLeft2zzaf := maxFields2zzaf - totalEncodedFields2zzaf var nextMiss2zzaf int32 = -1 var found2zzaf [maxFields2zzaf]bool var curField2zzaf string doneWithStruct2zzaf: // First fill all the encoded fields, then // treat the remaining, missing fields, as Nil. for encodedFieldsLeft2zzaf > 0 || missingFieldsLeft2zzaf > 0 { //fmt.Printf("encodedFieldsLeft: %v, missingFieldsLeft: %v, found: '%v', fields: '%#v'\n", encodedFieldsLeft2zzaf, missingFieldsLeft2zzaf, msgp.ShowFound(found2zzaf[:]), unmarshalMsgFieldOrder2zzaf) if encodedFieldsLeft2zzaf > 0 { encodedFieldsLeft2zzaf-- field, bts, err = nbs.ReadMapKeyZC(bts) if err != nil { return } curField2zzaf = msgp.UnsafeString(field) } else { //missing fields need handling if nextMiss2zzaf < 0 { // set bts to contain just mnil (0xc0) bts = nbs.PushAlwaysNil(bts) nextMiss2zzaf = 0 } for nextMiss2zzaf < maxFields2zzaf && (found2zzaf[nextMiss2zzaf] || unmarshalMsgFieldSkip2zzaf[nextMiss2zzaf]) { nextMiss2zzaf++ } if nextMiss2zzaf == maxFields2zzaf { // filled all the empty fields! break doneWithStruct2zzaf } missingFieldsLeft2zzaf-- curField2zzaf = unmarshalMsgFieldOrder2zzaf[nextMiss2zzaf] } //fmt.Printf("switching on curField: '%v'\n", curField2zzaf) switch curField2zzaf { // -- templateUnmarshalMsg ends here -- case "beta": found2zzaf[1] = true z.B, bts, err = nbs.ReadStringBytes(bts) if err != nil { return } case "ralph": found2zzaf[2] = true if nbs.AlwaysNil { if len(z.R) > 0 { for key, _ := range z.R { delete(z.R, key) } } } else { var ztua uint32 ztua, bts, err = nbs.ReadMapHeaderBytes(bts) if err != nil { return } if z.R == nil && ztua > 0 { z.R = make(map[string]uint8, ztua) } else if len(z.R) > 0 { for key, _ := range z.R { delete(z.R, key) } } for ztua > 0 { var zhsq string var zota uint8 ztua-- zhsq, bts, err = nbs.ReadStringBytes(bts) if err != nil { return } zota, bts, err = nbs.ReadUint8Bytes(bts) if err != nil { return } z.R[zhsq] = zota } } case "P": found2zzaf[3] = true z.P, bts, err = nbs.ReadUint16Bytes(bts) if err != nil { return } case "Q": found2zzaf[4] = true z.Q, bts, err = nbs.ReadUint32Bytes(bts) if err != nil { return } case "T": found2zzaf[5] = true z.T, bts, err = nbs.ReadInt64Bytes(bts) if err != nil { return } case "arr": found2zzaf[6] = true var zitt uint32 zitt, bts, err = nbs.ReadArrayHeaderBytes(bts) if err != nil { return } if !nbs.IsNil(bts) && zitt != 6 { err = msgp.ArrayError{Wanted: 6, Got: zitt} return } for zcpf := range z.Arr { z.Arr[zcpf], bts, err = nbs.ReadFloat64Bytes(bts) if err != nil { return } } case "MyTree": found2zzaf[7] = true if nbs.AlwaysNil { if z.MyTree != nil { z.MyTree.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil if msgp.IsNil(bts) { bts = bts[1:] if nil != z.MyTree { z.MyTree.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil and not IsNil(bts): have something to read if z.MyTree == nil { z.MyTree = new(Tree) } bts, err = z.MyTree.MSGPUnmarshalMsg(bts) if err != nil { return } if err != nil { return } } } default: bts, err = msgp.Skip(bts) if err != nil { return } } } if nextMiss2zzaf != -1 { bts = nbs.PopAlwaysNil() } if sawTopNil { bts = nbs.PopAlwaysNil() } o = bts if p, ok := interface{}(z).(msgp.PostLoad); ok { p.PostLoadHook() } return } // fields of S2 var unmarshalMsgFieldOrder2zzaf = []string{"alpha", "beta", "ralph", "P", "Q", "T", "arr", "MyTree"} var unmarshalMsgFieldSkip2zzaf = []bool{true, false, false, false, false, false, false, false} // MSGPMsgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z *S2) MSGPMsgsize() (s int) { s = 1 + 5 + msgp.StringPrefixSize + len(z.B) + 6 + msgp.MapHeaderSize if z.R != nil { for zhsq, zota := range z.R { _ = zota _ = zhsq s += msgp.StringPrefixSize + len(zhsq) + msgp.Uint8Size } } s += 2 + msgp.Uint16Size + 2 + msgp.Uint32Size + 2 + msgp.Int64Size + 4 + msgp.ArrayHeaderSize + (6 * (msgp.Float64Size)) + 7 if z.MyTree == nil { s += msgp.NilSize } else { s += z.MyTree.MSGPMsgsize() } return } // MSGPfieldsNotEmpty supports omitempty tags func (z Sys) MSGPfieldsNotEmpty(isempty []bool) uint32 { return 1 } // MSGPMarshalMsg implements msgp.Marshaler func (z Sys) MSGPMarshalMsg(b []byte) (o []byte, err error) { if p, ok := interface{}(z).(msgp.PreSave); ok { p.PreSaveHook() } o = msgp.Require(b, z.MSGPMsgsize()) // map header, size 1 // string "F" o = append(o, 0x81, 0xa1, 0x46) o, err = msgp.AppendIntf(o, z.F) if err != nil { return } return } // MSGPUnmarshalMsg implements msgp.Unmarshaler func (z *Sys) MSGPUnmarshalMsg(bts []byte) (o []byte, err error) { return z.MSGPUnmarshalMsgWithCfg(bts, nil) } func (z *Sys) MSGPUnmarshalMsgWithCfg(bts []byte, cfg *msgp.RuntimeConfig) (o []byte, err error) { var nbs msgp.NilBitsStack nbs.Init(cfg) var sawTopNil bool if msgp.IsNil(bts) { sawTopNil = true bts = nbs.PushAlwaysNil(bts[1:]) } var field []byte _ = field const maxFields3zaqt = 1 // -- templateUnmarshalMsg starts here-- var totalEncodedFields3zaqt uint32 if !nbs.AlwaysNil { totalEncodedFields3zaqt, bts, err = nbs.ReadMapHeaderBytes(bts) if err != nil { return } } encodedFieldsLeft3zaqt := totalEncodedFields3zaqt missingFieldsLeft3zaqt := maxFields3zaqt - totalEncodedFields3zaqt var nextMiss3zaqt int32 = -1 var found3zaqt [maxFields3zaqt]bool var curField3zaqt string doneWithStruct3zaqt: // First fill all the encoded fields, then // treat the remaining, missing fields, as Nil. for encodedFieldsLeft3zaqt > 0 || missingFieldsLeft3zaqt > 0 { //fmt.Printf("encodedFieldsLeft: %v, missingFieldsLeft: %v, found: '%v', fields: '%#v'\n", encodedFieldsLeft3zaqt, missingFieldsLeft3zaqt, msgp.ShowFound(found3zaqt[:]), unmarshalMsgFieldOrder3zaqt) if encodedFieldsLeft3zaqt > 0 { encodedFieldsLeft3zaqt-- field, bts, err = nbs.ReadMapKeyZC(bts) if err != nil { return } curField3zaqt = msgp.UnsafeString(field) } else { //missing fields need handling if nextMiss3zaqt < 0 { // set bts to contain just mnil (0xc0) bts = nbs.PushAlwaysNil(bts) nextMiss3zaqt = 0 } for nextMiss3zaqt < maxFields3zaqt && (found3zaqt[nextMiss3zaqt] || unmarshalMsgFieldSkip3zaqt[nextMiss3zaqt]) { nextMiss3zaqt++ } if nextMiss3zaqt == maxFields3zaqt { // filled all the empty fields! break doneWithStruct3zaqt } missingFieldsLeft3zaqt-- curField3zaqt = unmarshalMsgFieldOrder3zaqt[nextMiss3zaqt] } //fmt.Printf("switching on curField: '%v'\n", curField3zaqt) switch curField3zaqt { // -- templateUnmarshalMsg ends here -- case "F": found3zaqt[0] = true z.F, bts, err = nbs.ReadIntfBytes(bts) if err != nil { return } default: bts, err = msgp.Skip(bts) if err != nil { return } } } if nextMiss3zaqt != -1 { bts = nbs.PopAlwaysNil() } if sawTopNil { bts = nbs.PopAlwaysNil() } o = bts if p, ok := interface{}(z).(msgp.PostLoad); ok { p.PostLoadHook() } return } // fields of Sys var unmarshalMsgFieldOrder3zaqt = []string{"F"} var unmarshalMsgFieldSkip3zaqt = []bool{false} // MSGPMsgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z Sys) MSGPMsgsize() (s int) { s = 1 + 2 + msgp.GuessSize(z.F) return } // MSGPfieldsNotEmpty supports omitempty tags func (z *Tree) MSGPfieldsNotEmpty(isempty []bool) uint32 { return 3 } // MSGPMarshalMsg implements msgp.Marshaler func (z *Tree) MSGPMarshalMsg(b []byte) (o []byte, err error) { if p, ok := interface{}(z).(msgp.PreSave); ok { p.PreSaveHook() } o = msgp.Require(b, z.MSGPMsgsize()) // map header, size 3 // string "Chld" o = append(o, 0x83, 0xa4, 0x43, 0x68, 0x6c, 0x64) o = msgp.AppendArrayHeader(o, uint32(len(z.Chld))) for zrfx := range z.Chld { o, err = z.Chld[zrfx].MSGPMarshalMsg(o) if err != nil { return } } // string "Str" o = append(o, 0xa3, 0x53, 0x74, 0x72) o = msgp.AppendString(o, z.Str) // string "Par" o = append(o, 0xa3, 0x50, 0x61, 0x72) if z.Par == nil { o = msgp.AppendNil(o) } else { o, err = z.Par.MSGPMarshalMsg(o) if err != nil { return } } return } // MSGPUnmarshalMsg implements msgp.Unmarshaler func (z *Tree) MSGPUnmarshalMsg(bts []byte) (o []byte, err error) { return z.MSGPUnmarshalMsgWithCfg(bts, nil) } func (z *Tree) MSGPUnmarshalMsgWithCfg(bts []byte, cfg *msgp.RuntimeConfig) (o []byte, err error) { var nbs msgp.NilBitsStack nbs.Init(cfg) var sawTopNil bool if msgp.IsNil(bts) { sawTopNil = true bts = nbs.PushAlwaysNil(bts[1:]) } var field []byte _ = field const maxFields4zmlp = 3 // -- templateUnmarshalMsg starts here-- var totalEncodedFields4zmlp uint32 if !nbs.AlwaysNil { totalEncodedFields4zmlp, bts, err = nbs.ReadMapHeaderBytes(bts) if err != nil { return } } encodedFieldsLeft4zmlp := totalEncodedFields4zmlp missingFieldsLeft4zmlp := maxFields4zmlp - totalEncodedFields4zmlp var nextMiss4zmlp int32 = -1 var found4zmlp [maxFields4zmlp]bool var curField4zmlp string doneWithStruct4zmlp: // First fill all the encoded fields, then // treat the remaining, missing fields, as Nil. for encodedFieldsLeft4zmlp > 0 || missingFieldsLeft4zmlp > 0 { //fmt.Printf("encodedFieldsLeft: %v, missingFieldsLeft: %v, found: '%v', fields: '%#v'\n", encodedFieldsLeft4zmlp, missingFieldsLeft4zmlp, msgp.ShowFound(found4zmlp[:]), unmarshalMsgFieldOrder4zmlp) if encodedFieldsLeft4zmlp > 0 { encodedFieldsLeft4zmlp-- field, bts, err = nbs.ReadMapKeyZC(bts) if err != nil { return } curField4zmlp = msgp.UnsafeString(field) } else { //missing fields need handling if nextMiss4zmlp < 0 { // set bts to contain just mnil (0xc0) bts = nbs.PushAlwaysNil(bts) nextMiss4zmlp = 0 } for nextMiss4zmlp < maxFields4zmlp && (found4zmlp[nextMiss4zmlp] || unmarshalMsgFieldSkip4zmlp[nextMiss4zmlp]) { nextMiss4zmlp++ } if nextMiss4zmlp == maxFields4zmlp { // filled all the empty fields! break doneWithStruct4zmlp } missingFieldsLeft4zmlp-- curField4zmlp = unmarshalMsgFieldOrder4zmlp[nextMiss4zmlp] } //fmt.Printf("switching on curField: '%v'\n", curField4zmlp) switch curField4zmlp { // -- templateUnmarshalMsg ends here -- case "Chld": found4zmlp[0] = true if nbs.AlwaysNil { (z.Chld) = (z.Chld)[:0] } else { var zojv uint32 zojv, bts, err = nbs.ReadArrayHeaderBytes(bts) if err != nil { return } if cap(z.Chld) >= int(zojv) { z.Chld = (z.Chld)[:zojv] } else { z.Chld = make([]Tree, zojv) } for zrfx := range z.Chld { bts, err = z.Chld[zrfx].MSGPUnmarshalMsg(bts) if err != nil { return } if err != nil { return } } } case "Str": found4zmlp[1] = true z.Str, bts, err = nbs.ReadStringBytes(bts) if err != nil { return } case "Par": found4zmlp[2] = true if nbs.AlwaysNil { if z.Par != nil { z.Par.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil if msgp.IsNil(bts) { bts = bts[1:] if nil != z.Par { z.Par.MSGPUnmarshalMsg(msgp.OnlyNilSlice) } } else { // not nbs.AlwaysNil and not IsNil(bts): have something to read if z.Par == nil { z.Par = new(S2) } bts, err = z.Par.MSGPUnmarshalMsg(bts) if err != nil { return } if err != nil { return } } } default: bts, err = msgp.Skip(bts) if err != nil { return } } } if nextMiss4zmlp != -1 { bts = nbs.PopAlwaysNil() } if sawTopNil { bts = nbs.PopAlwaysNil() } o = bts if p, ok := interface{}(z).(msgp.PostLoad); ok { p.PostLoadHook() } return } // fields of Tree var unmarshalMsgFieldOrder4zmlp = []string{"Chld", "Str", "Par"} var unmarshalMsgFieldSkip4zmlp = []bool{false, false, false} // MSGPMsgsize returns an upper bound estimate of the number of bytes occupied by the serialized message func (z *Tree) MSGPMsgsize() (s int) { s = 1 + 5 + msgp.ArrayHeaderSize for zrfx := range z.Chld { s += z.Chld[zrfx].MSGPMsgsize() } s += 4 + msgp.StringPrefixSize + len(z.Str) + 4 if z.Par == nil { s += msgp.NilSize } else { s += z.Par.MSGPMsgsize() } return }
package leetcode import ( "reflect" "testing" ) func TestReplaceElements(t *testing.T) { if !reflect.DeepEqual(replaceElements([]int{17, 18, 5, 4, 6, 1}), []int{18, 6, 6, 6, 1, -1}) { t.Fatal() } }
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved. // // This Source Code Form is subject to the terms of the MIT License. // If a copy of the MIT was not distributed with this file, // You can obtain one at https://gitee.com/johng/gf. // 文件监控. // 使用时需要注意的是,一旦一个文件被删除,那么对其的监控将会失效。 package gfsnotify import ( "errors" "gitee.com/johng/gf/g/os/glog" "gitee.com/johng/gf/third/github.com/fsnotify/fsnotify" "gitee.com/johng/gf/g/os/gfile" "gitee.com/johng/gf/g/container/gmap" "gitee.com/johng/gf/g/container/glist" "gitee.com/johng/gf/g/container/gqueue" "fmt" ) // 监听管理对象 type Watcher struct { watcher *fsnotify.Watcher // 底层fsnotify对象 events *gqueue.Queue // 过滤后的事件通知,不会出现重复事件 closeChan chan struct{} // 关闭事件 callbacks *gmap.StringInterfaceMap // 监听的回调函数 } // 监听事件对象 type Event struct { Path string // 文件绝对路径 Op Op // 触发监听的文件操作 } // 按位进行识别的操作集合 type Op uint32 const ( CREATE Op = 1 << iota WRITE REMOVE RENAME CHMOD ) // 全局监听对象,方便应用端调用 var watcher, _ = New() // 创建监听管理对象 func New() (*Watcher, error) { if watch, err := fsnotify.NewWatcher(); err == nil { w := &Watcher { watcher : watch, events : gqueue.New(), closeChan : make(chan struct{}), callbacks : gmap.NewStringInterfaceMap(), } w.startWatchLoop() w.startEventLoop() return w, nil } else { return nil, err } } // 添加对指定文件/目录的监听,并给定回调函数;如果给定的是一个目录,默认递归监控。 func Add(path string, callback func(event *Event), recursive...bool) error { if watcher == nil { return errors.New("global watcher creating failed") } return watcher.Add(path, callback, recursive...) } // 移除监听,默认递归删除。 func Remove(path string) error { if watcher == nil { return errors.New("global watcher creating failed") } return watcher.Remove(path) } // 关闭监听管理对象 func (w *Watcher) Close() { w.watcher.Close() w.events.Close() close(w.closeChan) } // 添加对指定文件/目录的监听,并给定回调函数 func (w *Watcher) addWatch(path string, callback func(event *Event)) error { // 这里统一转换为当前系统的绝对路径,便于统一监控文件名称 t := gfile.RealPath(path) if t == "" { return errors.New(fmt.Sprintf(`"%s" does not exist`, path)) } path = t // 注册回调函数 w.callbacks.LockFunc(func(m map[string]interface{}) { var result interface{} if v, ok := m[path]; !ok { result = glist.New() m[path] = result } else { result = v } result.(*glist.List).PushBack(callback) }) // 添加底层监听 w.watcher.Add(path) return nil } // 添加监控,path参数支持文件或者目录路径,recursive为非必需参数,默认为递归添加监控(当path为目录时) func (w *Watcher) Add(path string, callback func(event *Event), recursive...bool) error { if gfile.IsDir(path) && (len(recursive) == 0 || recursive[0]) { paths, _ := gfile.ScanDir(path, "*", true) list := []string{path} list = append(list, paths...) for _, v := range list { if err := w.addWatch(v, callback); err != nil { return err } } return nil } else { return w.addWatch(path, callback) } } // 移除监听 func (w *Watcher) removeWatch(path string) error { w.callbacks.Remove(path) return w.watcher.Remove(path) } // 递归移除监听 func (w *Watcher) Remove(path string) error { if gfile.IsDir(path) { paths, _ := gfile.ScanDir(path, "*", true) list := []string{path} list = append(list, paths...) for _, v := range list { if err := w.removeWatch(v); err != nil { return err } } return nil } else { return w.removeWatch(path) } } // 监听循环 func (w *Watcher) startWatchLoop() { go func() { for { select { // 关闭事件 case <- w.closeChan: return // 监听事件 case ev := <- w.watcher.Events: //glog.Debug("gfsnotify:", ev) w.events.Push(&Event{ Path : ev.Name, Op : Op(ev.Op), }) case err := <- w.watcher.Errors: glog.Error("error : ", err); } } }() } // 检索给定path的回调方法**列表** func (w *Watcher) getCallbacks(path string) *glist.List { for path != "/" { if l := w.callbacks.Get(path); l != nil { return l.(*glist.List) } else { path = gfile.Dir(path) } } return nil } // 事件循环 func (w *Watcher) startEventLoop() { go func() { for { if v := w.events.Pop(); v != nil { event := v.(*Event) if event.IsRemove() { if gfile.Exists(event.Path) { // 如果是文件删除事件,判断该文件是否存在,如果存在,那么将此事件认为“假删除”, // 并重新添加监控(底层fsnotify会自动删除掉监控,这里重新添加回去) w.watcher.Add(event.Path) continue } else { // 如果是真实删除,那么递归删除监控信息 w.Remove(event.Path) } } callbacks := w.getCallbacks(event.Path) // 如果创建了新的目录,那么将这个目录递归添加到监控中 if event.IsCreate() && gfile.IsDir(event.Path) { for _, callback := range callbacks.FrontAll() { w.Add(event.Path, callback.(func(event *Event))) } } if callbacks != nil { go func(callbacks *glist.List) { for _, callback := range callbacks.FrontAll() { callback.(func(event *Event))(event) } }(callbacks) } } else { break } } }() }
package implwin import ( "fmt" "draw" "win" ) type BitmapWin struct { hBmp win.HBITMAP hPackedDIB win.HGLOBAL size draw.Size oldHandle win.HGDIOBJ hdc win.HDC } func NewBitmap(size draw.Size) (bmp *BitmapWin, err error) { bmp = &BitmapWin{} bmp.hBmp = win.CreateBitmap(int32(size.Width), int32(size.Height), 1, 32, nil) if bmp.hBmp == 0 { return nil, draw.NewError("CreateBitmap failed") } return bmp, nil } func (this *BitmapWin) BeginPaint(canvas draw.ICanvas) error { if this.hBmp == 0 { return draw.NewError("hBmp is invalid") } canvas_win, _ := canvas.(*CanvasWin) this.oldHandle = win.SelectObject(canvas_win.HDC(), win.HGDIOBJ(this.hBmp)) if this.oldHandle == 0 { return draw.NewError("SelectObject failed") } this.hdc = canvas_win.HDC() return nil } func (this *BitmapWin) EndPaint() { if this.oldHandle != 0 { win.SelectObject(this.hdc, this.oldHandle) this.hdc = 0 this.oldHandle = 0 } } func (this *BitmapWin) Dispose() { if this.hBmp != 0 { win.DeleteObject(win.HGDIOBJ(this.hBmp)) this.hBmp = 0 } } func (this *BitmapWin) Size() draw.Size { return this.size } func (this *BitmapWin) Draw(canvas draw.ICanvas) error { return nil } func (this *BitmapWin) SaveToFile(filename, format string) error { var bitmap *win.GpBitmap err := win.GdipCreateBitmapFromHBITMAP(this.hBmp, 0, &bitmap) if err != nil { return draw.NewError(fmt.Sprintf("GdipCreateBitmapFromHBITMAP failed, err =", err.Error())) } defer win.GdipDisposeImage(&bitmap.GpImage) clsid, _ := win.GetEncoderClsid(fmt.Sprintf("image/%s", format)) if clsid == nil { return draw.NewError(fmt.Sprintf("Do not support %s", format)) } err = win.GdipSaveImageToFile(&bitmap.GpImage, filename, clsid, nil) if err != nil { return draw.NewError(fmt.Sprintf("GdipSaveImageToFile failed, err =", err.Error())) } return nil }
package handler import ( "io" "testing" generalpb "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2" "github.com/stretchr/testify/suite" ) // SubmitMeasurementInfoTestSuite 测试提交测量数据 type SubmitMeasurementInfoTestSuite struct { suite.Suite jinmuHealth *JinmuHealth Account *Account } /* // SetupSuite 初始化测试类 func (suite *SubmitMeasurementInfoTestSuite) SetupSuite() { envFilepath := filepath.Join("testdata", "local.svc-biz-core.env") _ = godotenv.Load(envFilepath) db, _ := newTestingDbClientFromEnvFile(envFilepath) awsClient, _ := aws.NewClient( aws.BucketName(os.Getenv("X_AWS_BUCKET_NAME")), aws.SecretKey(os.Getenv("X_AWS_SECRET_KEY")), aws.AccessKeyID(os.Getenv("X_AWS_ACCESS_KEY")), aws.Region(os.Getenv("X_AWS_REGION")), aws.PulseTestRawDataEnvironmentS3KeyPrefix(os.Getenv("X_WAVE_DATA_KEY_PREFIX")), ) suite.Account = newTestingAccountFromEnvFile(envFilepath) configDoc, _ := blocker.LoadConfig("../../pkg/blocker/testdata/config_doc.yml") blockerPool, _ := blocker.NewBlockerPool(configDoc, "../../pkg/blocker/data/GeoLite2-Country.mmdb.gz") suite.jinmuHealth = NewJinmuHealth(db, nil, algorithmClient, awsClient, nil, nil, blockerPool) } // TestSubmitMeasurementInfoSuccess 测试提交测量数据成功 func (suite *SubmitMeasurementInfoTestSuite) TestSubmitMeasurementInfoSuccess() { t := suite.T() var algorithmReq algorithm.C2Request assert.NoError(t, json.Unmarshal(getTestMeasureData(), &algorithmReq)) ctx := context.Background() ctx = mockAuth(ctx, suite.Account.clientID, suite.Account.name, suite.Account.zone) ctx = auth.AddContextUserID(ctx, suite.Account.userID) const registerType = "username" ctx, err := mockSignin(ctx, suite.jinmuHealth, suite.Account.userName, suite.Account.passwordHash, registerType, proto.SignInMethod_SIGN_IN_METHOD_GENERAL) assert.NoError(t, err) ctx = addContextClient(ctx, metaClient{ RemoteClientIP: "110.165.32.0", ClientID: suite.Account.clientID, Name: suite.Account.name, Zone: suite.Account.zone, CustomizedCode: "", }) req, resp := new(proto.SubmitMeasurementInfoRequest), new(proto.SubmitMeasurementInfoResponse) req.UserId = suite.Account.userID req.Mac = algorithmReq.MAC setTestSubmitMeasurementInfoRequest(req, int(suite.Account.userID), &algorithmReq) assert.NoError(t, suite.jinmuHealth.SubmitMeasurementInfo(ctx, req, resp)) assert.NotZero(t, resp.Hr) } */ /* 一、测试成功 a、mac未被拒,同时mac对应创建时间在2019/06/01之前 1、clientID=dengyun-10001 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之前,测试成功 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN-X customized_code:custom_dengyun (3)测试输入 clientID:dengyun-10001 ip:223.104.145.236 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 2、clientID=kangmei-10001 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之前,测试成功 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN-X customized_code:custom_dengyun (3)测试输入 clientID:kangmei-10001 ip:223.104.145.236 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 3、clientID=jm-10001 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之前,测试成功 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10002 ip:223.104.145.236 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 4、clientID=jm-10002 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之前,测试成功 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10003 ip:223.104.145.236 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 6、clientID=jm-10004 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之前,测试成功 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10004 ip:223.104.145.236 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 7、clientID=jm-10005 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之前,测试成功 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10005 ip:223.104.145.236 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 b、mac未被拒,同时mac对应创建时间在2019/06/01之后,看ip过滤状态,允许任意ip通过 8、clientID=dengyun-10001 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,美国ip,测试成功 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN-X (3)测试输入 clientID:dengyun-10001 ip:67.220.91.30 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 9、clientID=kangmei-10001 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,美国ip,测试成功 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN-X (3)测试输入 clientID:kangmei-10001 ip:67.220.91.30 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 10、clientID=jm-10002 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,美国ip,测试成功 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10002 ip:67.220.91.30 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 11、clientID=jm-10003 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,美国ip,测试成功 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10003 ip:67.220.91.30 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 c、mac未被拒,同时mac对应创建时间在2019/06/01之后,看ip过滤状态,允许某些特定城市ip通过 12、clientID=jm-10001 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,香港ip,测试成功 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10001 ip:110.165.32.0 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 13、clientID=jm-10004 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,香港ip,测试成功 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10004 ip:110.165.32.0 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 14、clientID=jm-10005 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,香港ip,测试成功 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10005 ip:110.165.32.0 mac:304511440CCF (4)预计结果 测试成功 (5)实际结果 测试成功 二、测试失败 1、mac过滤 (1)测试标题 mac被拒,即zone不在范围内;mac对应的创建时间在2019/06/01日之前,测试失败 (2)预制条件 mac创建时间:2018-08-16 20:50:06 zone:CN (3)测试输入 clientID:dengyun-10001 ip:223.104.145.236 mac:304511440CCF (4)预计结果 测试失败,[errcode:77000] blocked mac (5)实际结果 测试失败,[errcode:77000] blocked mac 2、mac未被拒,创建时间在2019/06/01之后,ip过滤 a、clientID:jm-10001 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,ip过滤失败,测试失败 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10001 ip:67.220.91.30 mac:304511440CCF (4)预计结果 测试失败,[errcode:78000] blocked ip (5)实际结果 测试失败,[errcode:78000] blocked ip b、clientID:jm-10004 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,ip过滤失败,测试失败 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10004 ip:67.220.91.30 mac:304511440CCF (4)预计结果 测试失败,[errcode:78000] blocked ip (5)实际结果 测试失败,[errcode:78000] blocked ip c、clientID:jm-10005 (1)测试标题 mac未被拒,即zone在范围内;mac对应的创建时间在2019/06/01日之后,ip过滤失败,测试失败 (2)预制条件 mac创建时间:2020-08-16 20:50:06 zone:CN (3)测试输入 clientID:jm-10005 ip:67.220.91.30 mac:304511440CCF (4)预计结果 测试失败,[errcode:78000] blocked ip (5)实际结果 测试失败,[errcode:78000] blocked ip */ // getTestMeasureData 读取测量数据文件 func getTestMeasureData() []byte { jsondata, _ := io.ReadFile("testdata/test.json") return jsondata } /* // setTestSubmitMeasurementInfoRequest 从测试 json 数据设置一次 mock rpc 请求 func setTestSubmitMeasurementInfoRequest(req *proto.SubmitMeasurementInfoRequest, subjectID int, algorithmReq *algorithm.C2Request) { dataNum, _ := strconv.ParseInt(algorithmReq.Bit, 10, 0) req.InfoNum = int32(dataNum) req.MobileType = proto.MobileType_MOBILE_TYPE_ANDROID req.Mac = algorithmReq.MAC protoGender := mapAlgorithmGenderToProto(algorithmReq.Gender) req.Gender = protoGender weight, _ := strconv.Atoi(algorithmReq.Weight) height, _ := strconv.Atoi(algorithmReq.Height) req.Age = int32(algorithmReq.Age) req.Info0 = new(proto.BluetoothInfo) req.Info0.Ir5160, _ = base64.StdEncoding.DecodeString(algorithmReq.Data0.IR5160) req.Info0.Ir5160Md5 = algorithmReq.Data0.IR5160MD5 req.Info0.R5164 = []byte(algorithmReq.Data0.R5164) req.Info0.R5164Md5 = algorithmReq.Data0.R5164MD5 req.Info1 = new(proto.BluetoothInfo) req.Info1.Ir5160, _ = base64.StdEncoding.DecodeString(algorithmReq.Data1.IR5160) req.Info1.Ir5160Md5 = algorithmReq.Data1.IR5160MD5 req.Info1.R5164 = []byte(algorithmReq.Data1.R5164) req.Info1.R5164Md5 = algorithmReq.Data1.R5164MD5 req.Weight = int32(weight) req.Height = int32(height) } */ func TestSubmitMeasurementInfoTestSuite(t *testing.T) { suite.Run(t, new(SubmitMeasurementInfoTestSuite)) } func mapAlgorithmGenderToProto(gender string) generalpb.Gender { switch gender { case "M": return generalpb.Gender_GENDER_MALE case "F": return generalpb.Gender_GENDER_FEMALE } return generalpb.Gender_GENDER_MALE }
package mongo import ( // External Imports "github.com/globalsign/mgo" "github.com/sirupsen/logrus" ) const ( logError = "datastore error" logConflict = "resource conflict" logNotFound = "resource not found" logNotHashable = "unable to hash secret" ) // logger provides the package scoped logger implementation. var logger storeLogger // storeLogger provides a wrapper around the logrus logger in order to implement // required database library logging interfaces. type storeLogger struct { *logrus.Logger } // Output implements mgo.logLogger func (l *storeLogger) Output(calldepth int, s string) error { meta := logrus.Fields{ "driver": "mgo", "calldepth": calldepth, } l.WithFields(meta).Debug(s) return nil } // SetDebug turns on debug level logging, including debug at the driver level. // If false, disables driver level logging and sets logging to info level. func SetDebug(isDebug bool) { if isDebug { logger.SetLevel(logrus.DebugLevel) // Turn on mgo debugging mgo.SetDebug(isDebug) mgo.SetLogger(&logger) } else { logger.SetLevel(logrus.InfoLevel) // Turn off mgo debugging mgo.SetDebug(isDebug) mgo.SetLogger(nil) } } // SetLogger enables binding in your own customised logrus logger. func SetLogger(log *logrus.Logger) { logger = storeLogger{ Logger: log, } }
package route import ( "time" action "github.com/felixa1996/go-plate/adapter/api/action/charity_mrys" "github.com/felixa1996/go-plate/adapter/logger" presenter "github.com/felixa1996/go-plate/adapter/presenter/charity_mrys" "github.com/felixa1996/go-plate/adapter/repository" usecase "github.com/felixa1996/go-plate/usecase/charity_mrys" ) func CharityMrysFindAll(db repository.SQL, log logger.Logger, ctxTimeout time.Duration) action.FindAllCharityMrysAction { var ( uc = usecase.NewFindAllCharityMrysInteractor( repository.NewCharityMrysSQL(db), presenter.NewFindAllCharityMrysPresenter(), ctxTimeout, ) act = action.NewFindAllCharityMrysAction(uc, log) ) return act } func CharityMrysFindOne(db repository.SQL, log logger.Logger, ctxTimeout time.Duration) action.FindCharityMrysAction { var ( uc = usecase.NewFindCharityMrysInteractor( repository.NewCharityMrysSQL(db), presenter.NewFindCharityMrysPresenter(), ctxTimeout, ) act = action.NewFindCharityMrysAction(uc, log) ) return act }
// example: // 123 // 456 // --- // 738 // 615 = 6888 // 492 = 56088 // ----- // func multiply(num1 string, num2 string) string { if num1[0] == '0' || num2[0] == '0' { return "0" } res := []int{0} for i := 0; i < len(num2); i++ { k := int(num2[len(num2)-i-1] - 48) num3 := make([]int, i, len(num1)+i) carry := 0 for j := 0; j < len(num1); j++ { l := int(num1[len(num1)-j-1] - 48) m := k * l + carry n := m % 10 carry = m / 10 num3 = append([]int{n}, num3...) } if carry > 0 { num3 = append([]int{carry}, num3...) } carry = 0 for i := 0; i < len(num3); i++ { n3 := num3[len(num3)-i-1] n1 := 0 if len(res)-i-1 >= 0 { n1 = res[len(res)-i-1] } m := n1 + n3 + carry n := m % 10 carry = m / 10 if len(res)-i-1 >= 0 { res[len(res)-i-1] = n } else { res = append([]int{n}, res...) } } if carry > 0 { res = append([]int{carry}, res...) } } res1 := "" for i := len(res)-1; i >= 0; i-- { res1 = fmt.Sprint(res[i]) + res1 } return res1 }
// Package utilities Internal Amazon Token struct package utilities import "time" // AmazonToken Describes what the token will look like type AmazonToken struct { AccessToken string `json:"amazon_access_token"` AccessTokenExpiry time.Duration `json:"amazon_accessToken_expiry"` }
package ping // // import ( // "testing" // "time" // ) // // var pingtests = []struct { // host string // ping bool // err string // }{ // {"127.0.0.1", true, ""}, // // {"8.8.8.8", true, ""}, // // {"google.com", true, ""}, // // {"128.0.0.1", false, "read ip 128.0.0.1: i/o timeout"}, // // {"fail.ping.gg", false, "dial ip:icmp: lookup fail.ping.gg: no such host"}, // } // // func TestPing(t *testing.T) { // // TimeOut = time.Second / 2 // // for _, tt := range pingtests { // ping, err := Ping2(tt.host) // if ping { // if !tt.ping || err != nil { // t.Errorf("Incorrect ping for host: %s resulted: %t with error: %s", tt.host, ping, err.Error()) // } // } // // if !ping { // if tt.ping || err.Error() != tt.err { // t.Errorf("Incorrect ping for host: %s resulted: %t with error: %s", tt.host, ping, err.Error()) // } // } // } // }
package postgres import ( "database/sql" "errors" "math/rand" "time" "github.com/Boostport/migration" "github.com/Boostport/migration/driver/postgres" "github.com/gobuffalo/packr" "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/dimuls/swan/entity" ) type Storage struct { uri string db *sqlx.DB } func NewStorage(uri string) (*Storage, error) { db, err := sqlx.Open("postgres", uri) if err != nil { return nil, errors.New("failed to open DB: " + err.Error()) } err = db.Ping() if err != nil { return nil, errors.New("failed to ping DB: " + err.Error()) } return &Storage{uri: uri, db: db}, nil } //go:generate packr const migrationsPath = "./migrations" func (s *Storage) Migrate() error { packrSource := &migration.PackrMigrationSource{ Box: packr.NewBox(migrationsPath), } d, err := postgres.New(s.uri) if err != nil { return errors.New("failed to create migration driver: " + err.Error()) } _, err = migration.Migrate(d, packrSource, migration.Up, 0) if err != nil { return errors.New("failed to migrate: " + err.Error()) } return nil } func (s *Storage) PasswordCode(role string, login string) ( pc entity.PasswordCode, err error) { err = s.db.QueryRowx(` SELECT * FROM password_codes WHERE role = $1 AND login = $2 `, role, login).StructScan(&pc) return } func (s *Storage) RemovePasswordCode(role string, login string) error { _, err := s.db.Exec(` DELETE FROM password_codes WHERE role = $1 AND login = $2 `, role, login) return err } func (s *Storage) UpsertPasswordCode(pc entity.PasswordCode) error { _, err := s.db.Exec(` INSERT INTO password_codes (role, login, code, created_at) VALUES ($1, $2, $3, $4) ON CONFLICT (role, login) DO UPDATE SET code = EXCLUDED.code, created_at = EXCLUDED.created_at `, pc.Role, pc.Login, pc.Code, pc.CreatedAt) return err } func (s *Storage) Admin(email string) (a entity.Admin, err error) { err = s.db.QueryRowx(`SELECT * FROM admins WHERE email = $1`, email). StructScan(&a) return } func (s *Storage) SetAdminPasswordHash(adminID int, passwordHash []byte) error { _, err := s.db.Exec(` UPDATE admins SET password_hash = $1 WHERE id = $2 `, passwordHash, adminID) return err } func (s *Storage) Categories() (cs []entity.Category, err error) { err = s.db.Select(&cs, `SELECT * FROM categories`) return } func (s *Storage) AddCategory(c entity.Category) (entity.Category, error) { err := s.db.QueryRowx(` INSERT INTO categories (name) VALUES ($1) RETURNING id `, c.Name).Scan(&c.ID) return c, err } func (s *Storage) SetCategory(c entity.Category) (entity.Category, error) { _, err := s.db.Exec(`UPDATE categories SET name = $1 WHERE id = $2`, c.Name, c.ID) return c, err } func (s *Storage) RemoveCategory(id int) error { _, err := s.db.Exec(`DELETE FROM categories WHERE id = $1`, id) return err } func (s *Storage) CategorySamples() (css []entity.CategorySample, err error) { err = s.db.Select(&css, `SELECT * FROM category_samples`) return } func (s *Storage) SetCategorySamples(css []entity.CategorySample) error { tx, err := s.db.Begin() if err != nil { return err } _, err = tx.Exec(`DELETE FROM category_samples`) if err != nil { tx.Rollback() return err } for _, cs := range css { _, err = tx.Exec(` INSERT INTO category_samples (category_id, text) VALUES ($1, $2) `, cs.CategoryID, cs.Text) if err != nil { tx.Rollback() return err } } err = tx.Commit() if err != nil { tx.Rollback() } return err } func (s *Storage) Organization(email string) (o entity.Organization, err error) { err = s.db.QueryRowx(`SELECT * FROM organizations WHERE email = $1`, email).StructScan(&o) return } func (s *Storage) Organizations() (os []entity.Organization, err error) { err = s.db.Select(&os, `SELECT * FROM organizations`) return } func (s *Storage) AddOrganization(o entity.Organization) (entity.Organization, error) { err := s.db.QueryRowx(` INSERT INTO organizations (name, email, flats_count, password_hash) VALUES ($1, $2, $3, $4) RETURNING id `, o.Name, o.Email, o.FlatsCount, o.PasswordHash).Scan(&o.ID) return o, err } func (s *Storage) SetOrganization(o entity.Organization) (entity.Organization, error) { _, err := s.db.Exec(` UPDATE organizations SET name = $1, email = $2, flats_count = $3, password_hash = $4 WHERE id = $5 `, o.Name, o.Email, o.FlatsCount, o.PasswordHash, o.ID) return o, err } func (s *Storage) RemoveOrganization(id int) error { _, err := s.db.Exec(`DELETE FROM organizations WHERE id = $1`, id) return err } func (s *Storage) SetOrganizationPasswordHash(organizationID int, passwordHash []byte) error { _, err := s.db.Exec(` UPDATE organizations SET password_hash = $1 WHERE id = $2 `, passwordHash, organizationID) return err } func (s *Storage) Operator(phone string) (o entity.Operator, err error) { var rcs64 pq.Int64Array err = s.db.QueryRow(` SELECT id, organization_id, phone, password_hash, name, responsible_categories FROM operators WHERE phone = $1 `, phone).Scan(&o.ID, &o.OrganizationID, &o.Phone, &o.PasswordHash, &o.Name, &rcs64) if err != nil { return o, err } for _, rc := range rcs64 { o.ResponsibleCategories = append(o.ResponsibleCategories, int(rc)) } return } func (s *Storage) OrganizationOperators(organizationID int) ( []entity.Operator, error) { rows, err := s.db.Query(` SELECT id, organization_id, phone, password_hash, name, responsible_categories FROM operators WHERE organization_id = $1 `, organizationID) if err != nil { return nil, err } defer rows.Close() var os []entity.Operator for rows.Next() { var o entity.Operator var rcs64 pq.Int64Array err = rows.Scan(&o.ID, &o.OrganizationID, &o.Phone, &o.PasswordHash, &o.Name, &rcs64) for _, rc := range rcs64 { o.ResponsibleCategories = append(o.ResponsibleCategories, int(rc)) } os = append(os, o) if err != nil { return nil, err } } return os, nil } func (s *Storage) AddOperator(o entity.Operator) (entity.Operator, error) { err := s.db.QueryRowx(` INSERT INTO operators (organization_id, phone, name, responsible_categories) VALUES ($1, $2, $3, $4) RETURNING id `, o.OrganizationID, o.Phone, o.Name, pq.Array(o.ResponsibleCategories)). Scan(&o.ID) return o, err } func (s *Storage) SetOperator(o entity.Operator) (entity.Operator, error) { _, err := s.db.Exec(` UPDATE operators SET phone = $1, name = $2, responsible_categories = $3 WHERE id = $4 `, o.Phone, o.Name, pq.Array(o.ResponsibleCategories), o.ID) return o, err } func (s *Storage) RemoveOrganizationOperator( organizationID int, operatorID int) error { _, err := s.db.Exec(` DELETE FROM operators WHERE organization_id = $1 AND id = $2 `, organizationID, operatorID) return err } func (s *Storage) FindOrganizationOperator(organizationID, categoryID int) ( o entity.Operator, err error) { rows, err := s.db.Query(` SELECT * FROM operators WHERE organization_id = $1 AND $2 = ANY(responsible_categories) `, organizationID, categoryID) if err != nil { return o, err } defer rows.Close() var os []entity.Operator for rows.Next() { var o entity.Operator var rcs64 pq.Int64Array err = rows.Scan(&o.ID, &o.OrganizationID, &o.Phone, &o.PasswordHash, &o.Name, &rcs64) for _, rc := range rcs64 { o.ResponsibleCategories = append(o.ResponsibleCategories, int(rc)) } os = append(os, o) if err != nil { return o, err } } if len(os) == 0 { return o, sql.ErrNoRows } return os[rand.Intn(len(os))], nil } func (s *Storage) SetOperatorPasswordHash(operatorID int, passwordHash []byte) error { _, err := s.db.Exec(` UPDATE operators SET password_hash = $1 WHERE id = $2 `, passwordHash, operatorID) return err } func (s *Storage) Owner(phone string) (o entity.Owner, err error) { err = s.db.QueryRowx(`SELECT * FROM owners WHERE phone = $1`, phone).StructScan(&o) return } func (s *Storage) OrganizationOwners(organizationID int) (os []entity.Owner, err error) { err = s.db.Select(&os, ` SELECT * FROM owners WHERE organization_id = $1 `, organizationID) return } func (s *Storage) AddOwner(o entity.Owner) (entity.Owner, error) { err := s.db.QueryRowx(` INSERT INTO owners (organization_id, phone, password_hash, name, address) VALUES ($1, $2, $3, $4, $5) RETURNING id `, o.OrganizationID, o.Phone, o.PasswordHash, o.Name, o.Address).Scan(&o.ID) return o, err } func (s *Storage) SetOwner(o entity.Owner) (entity.Owner, error) { _, err := s.db.Exec(` UPDATE owners SET phone = $1, password_hash = $2, name = $3, address = $4 WHERE id = $5 `, o.Phone, o.PasswordHash, o.Name, o.Address, o.ID) return o, err } func (s *Storage) RemoveOrganizationOwner(organizationID int, ownerID int) error { _, err := s.db.Exec(` DELETE FROM owners WHERE organization_id = $1 AND id = $2 `, organizationID, ownerID) return err } func (s *Storage) SetOwnerPasswordHash(ownerID int, passwordHash []byte) error { _, err := s.db.Exec(` UPDATE owners SET password_hash = $1 WHERE id = $2 `, passwordHash, ownerID) return err } func (s *Storage) OperatorRequest(operatorID int, requestID int) ( r entity.Request, err error) { err = s.db.QueryRowx(` SELECT * FROM requests WHERE operator_id = $1 AND id = $2 `, operatorID, requestID).StructScan(&r) return } func (s *Storage) OperatorRequests(operatorID int) ( rs []entity.RequestExtended, err error) { err = s.db.Select(&rs, ` SELECT r.id as id, r.organization_id as organization_id, r.owner_id as owner_id, r.operator_id as operator_id, r.category_id as category_id, r.text as text, r.response as response, r.status as status, r.created_at as created_at, c.name as category_name, op.phone as operator_phone, op.name as operator_name, ow.phone as owner_phone, ow.name as owner_name, ow.address as owner_address FROM requests as r LEFT JOIN categories as c ON r.category_id = c.id LEFT JOIN operators as op ON r.operator_id = op.id LEFT JOIN owners as ow ON r.owner_id = ow.id WHERE operator_id = $1 ORDER BY created_at DESC `, operatorID) return } func (s *Storage) SetOperatorRequest(operatorID int, r entity.Request) ( entity.Request, error) { _, err := s.db.Exec(` UPDATE requests SET response = $1, status = $2 WHERE operator_id = $3 AND id = $4 `, r.Response, r.Status, operatorID, r.ID) return r, err } func (s *Storage) OwnerRequests(ownerID int) (rs []entity.RequestExtended, err error) { err = s.db.Select(&rs, ` SELECT r.id as id, r.organization_id as organization_id, r.owner_id as owner_id, r.operator_id as operator_id, r.category_id as category_id, r.text as text, r.response as response, r.status as status, r.created_at as created_at, c.name as category_name, op.phone as operator_phone, op.name as operator_name, ow.phone as owner_phone, ow.name as owner_name, ow.address as owner_address FROM requests as r LEFT JOIN categories as c ON r.category_id = c.id LEFT JOIN operators as op ON r.operator_id = op.id LEFT JOIN owners as ow ON r.owner_id = ow.id WHERE owner_id = $1 ORDER BY created_at DESC `, ownerID) return } func (s *Storage) AddRequest(r entity.Request) (entity.Request, error) { err := s.db.QueryRowx(` INSERT INTO requests (organization_id, owner_id, operator_id, category_id, text, status, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id `, r.OrganizationID, r.OwnerID, r.OperatorID, r.CategoryID, r.Text, r.Status, time.Now()).Scan(&r.ID) return r, err }
// 26. CTR bitflipping package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "fmt" "net/url" "strings" ) func main() { c, err := aes.NewCipher(RandomBytes(aes.BlockSize)) if err != nil { panic(err) } iv := RandomBytes(c.BlockSize()) data := []byte("XXXXX;admin=true") mask := xorMask(data) XORBytes(data, data, mask) buf := ctrUserData(string(data), c, iv) target := buf[2*aes.BlockSize : 3*aes.BlockSize] XORBytes(target, target, mask) if ctrIsAdmin(buf, c, iv) { fmt.Println("success") } } // xorMask returns an XOR mask that prevents query escaping for the target buffer. func xorMask(buf []byte) []byte { res := make([]byte, len(buf)) for i, b := range buf { for j := 0; j <= 0xff; j++ { if s := string(b ^ byte(j)); s == url.QueryEscape(s) { res[i] = byte(j) break } } } return res } // ctrUserData returns an encrypted string with arbitrary data inserted in the middle. func ctrUserData(s string, c cipher.Block, iv []byte) []byte { buf := []byte(UserData(s)) cipher.NewCTR(c, iv).XORKeyStream(buf, buf) return buf } // UserData returns a string with arbitrary data inserted in the middle. func UserData(s string) string { const ( prefix = "comment1=cooking%20MCs;userdata=" suffix = ";comment2=%20like%20a%20pound%20of%20bacon" ) return prefix + url.QueryEscape(s) + suffix } // ctrIsAdmin returns true if a decrypted semicolon-separated string contains "admin=true". func ctrIsAdmin(buf []byte, c cipher.Block, iv []byte) bool { tmp := make([]byte, len(buf)) cipher.NewCTR(c, iv).XORKeyStream(tmp, buf) return IsAdmin(string(tmp)) } // IsAdmin returns true if a semicolon-separated string contains "admin=true". func IsAdmin(s string) bool { for _, v := range strings.Split(s, ";") { if v == "admin=true" { return true } } return false } // RandomBytes returns a random buffer of the desired length. func RandomBytes(n int) []byte { buf := make([]byte, n) if _, err := rand.Read(buf); err != nil { panic(err) } return buf } // XORBytes produces the XOR combination of two buffers. func XORBytes(dst, b1, b2 []byte) int { n := Minimum(len(b1), len(b2)) for i := 0; i < n; i++ { dst[i] = b1[i] ^ b2[i] } return n } // Minimum returns the smallest of a list of integers. func Minimum(n int, nums ...int) int { for _, m := range nums { if m < n { n = m } } return n }
package newrelic import ( "context" awssdk "github.com/aws/aws-sdk-go-v2/aws" "github.com/b2wdigital/goignite/pkg/cloud/aws/v2" "github.com/b2wdigital/goignite/pkg/log" "github.com/newrelic/go-agent/v3/integrations/nrawssdk-v2" ) type Integrator struct { options *Options } func NewIntegrator(options *Options) aws.Integrator { return &Integrator{options: options} } func (i *Integrator) Integrate(ctx context.Context, cfg *awssdk.Config) error { logger := log.FromContext(ctx).WithTypeOf(*i) logger.Trace("integrating mongodb with newrelic") if i.options.Enabled { nrawssdk.InstrumentHandlers(&cfg.Handlers) } logger.Debug("mongodb integrated with newrelic with success") return nil }
package main import "github.com/julienschmidt/httprouter" // Route represents single API route and stores its handler function. type Route struct { Name string Method string Path string HandlerFunc httprouter.Handle } // Routes groups API routes for passing them between functions. type Routes []Route // AllRoutes defines all supported API routes. func AllRoutes() Routes { routes := Routes{ Route{"Index", "GET", "/", Index}, Route{"RelayIndex", "GET", "/relays", RelayIndex}, Route{"RelayShow", "GET", "/relays/:id", RelayShow}, Route{"RelayOn", "GET", "/relays/:id/on", RelayOn}, Route{"RelayOff", "GET", "/relays/:id/off", RelayOff}, } return routes } // NewRouter reads from the routes slice to set the values for httprouter.Handle. func NewRouter(routes Routes) *httprouter.Router { router := httprouter.New() for _, route := range routes { router.Handle(route.Method, route.Path, Logger(route.HandlerFunc)) } return router }
package file_common_test import ( "ms/sun/servises/file_service/file_common" "net/url" "testing" ) func BenchmarkRowReqParsingNotExists(b *testing.B) { url, _ := url.Parse("http://localhost:5151/post_file/1518506476136010007_180.jpg") for i := 0; i < b.N; i++ { req:= file_common.NewRowReq(file_common.HttpCategories[1], url) req.SetNewFileDataStoreIdAndExtntion(154165465465,".exe") } }
// 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 cascades import ( "context" "math" "testing" "github.com/pingcap/tidb/domain" "github.com/pingcap/tidb/expression" "github.com/pingcap/tidb/infoschema" "github.com/pingcap/tidb/parser" "github.com/pingcap/tidb/parser/model" plannercore "github.com/pingcap/tidb/planner/core" "github.com/pingcap/tidb/planner/memo" "github.com/pingcap/tidb/planner/property" "github.com/stretchr/testify/require" ) func TestImplGroupZeroCost(t *testing.T) { p := parser.New() ctx := plannercore.MockContext() is := infoschema.MockInfoSchema([]*model.TableInfo{plannercore.MockSignedTable()}) domain.GetDomain(ctx).MockInfoCacheAndLoadInfoSchema(is) stmt, err := p.ParseOneStmt("select t1.a, t2.a from t as t1 left join t as t2 on t1.a = t2.a where t1.a < 1.0", "", "") require.NoError(t, err) plan, _, err := plannercore.BuildLogicalPlanForTest(context.Background(), ctx, stmt, is) require.NoError(t, err) logic, ok := plan.(plannercore.LogicalPlan) require.True(t, ok) rootGroup := memo.Convert2Group(logic) prop := &property.PhysicalProperty{ ExpectedCnt: math.MaxFloat64, } impl, err := NewOptimizer().implGroup(rootGroup, prop, 0.0) require.NoError(t, err) require.Nil(t, impl) } func TestInitGroupSchema(t *testing.T) { p := parser.New() ctx := plannercore.MockContext() is := infoschema.MockInfoSchema([]*model.TableInfo{plannercore.MockSignedTable()}) domain.GetDomain(ctx).MockInfoCacheAndLoadInfoSchema(is) stmt, err := p.ParseOneStmt("select a from t", "", "") require.NoError(t, err) plan, _, err := plannercore.BuildLogicalPlanForTest(context.Background(), ctx, stmt, is) require.NoError(t, err) logic, ok := plan.(plannercore.LogicalPlan) require.True(t, ok) g := memo.Convert2Group(logic) require.NotNil(t, g) require.NotNil(t, g.Prop) require.Equal(t, 1, g.Prop.Schema.Len()) require.Nil(t, g.Prop.Stats) } func TestFillGroupStats(t *testing.T) { p := parser.New() ctx := plannercore.MockContext() is := infoschema.MockInfoSchema([]*model.TableInfo{plannercore.MockSignedTable()}) domain.GetDomain(ctx).MockInfoCacheAndLoadInfoSchema(is) stmt, err := p.ParseOneStmt("select * from t t1 join t t2 on t1.a = t2.a", "", "") require.NoError(t, err) plan, _, err := plannercore.BuildLogicalPlanForTest(context.Background(), ctx, stmt, is) require.NoError(t, err) logic, ok := plan.(plannercore.LogicalPlan) require.True(t, ok) rootGroup := memo.Convert2Group(logic) err = NewOptimizer().fillGroupStats(rootGroup) require.NoError(t, err) require.NotNil(t, rootGroup.Prop.Stats) } func TestPreparePossibleProperties(t *testing.T) { p := parser.New() ctx := plannercore.MockContext() is := infoschema.MockInfoSchema([]*model.TableInfo{plannercore.MockSignedTable()}) domain.GetDomain(ctx).MockInfoCacheAndLoadInfoSchema(is) optimizer := NewOptimizer() optimizer.ResetTransformationRules(map[memo.Operand][]Transformation{ memo.OperandDataSource: { NewRuleEnumeratePaths(), }, }) defer func() { optimizer.ResetTransformationRules(DefaultRuleBatches...) }() stmt, err := p.ParseOneStmt("select f, sum(a) from t group by f", "", "") require.NoError(t, err) plan, _, err := plannercore.BuildLogicalPlanForTest(context.Background(), ctx, stmt, is) require.NoError(t, err) logic, ok := plan.(plannercore.LogicalPlan) require.True(t, ok) logic, err = optimizer.onPhasePreprocessing(ctx, logic) require.NoError(t, err) // collect the target columns: f, a ds, ok := logic.Children()[0].Children()[0].(*plannercore.DataSource) require.True(t, ok) var columnF, columnA *expression.Column for i, col := range ds.Columns { if col.Name.L == "f" { columnF = ds.Schema().Columns[i] } else if col.Name.L == "a" { columnA = ds.Schema().Columns[i] } } require.NotNil(t, columnF) require.NotNil(t, columnA) agg, ok := logic.Children()[0].(*plannercore.LogicalAggregation) require.True(t, ok) group := memo.Convert2Group(agg) require.NoError(t, optimizer.onPhaseExploration(ctx, group)) // The memo looks like this: // Group#0 Schema:[Column#13,test.t.f] // Aggregation_2 input:[Group#1], group by:test.t.f, funcs:sum(test.t.a), firstrow(test.t.f) // Group#1 Schema:[test.t.a,test.t.f] // TiKVSingleGather_5 input:[Group#2], table:t // TiKVSingleGather_9 input:[Group#3], table:t, index:f_g // TiKVSingleGather_7 input:[Group#4], table:t, index:f // Group#2 Schema:[test.t.a,test.t.f] // TableScan_4 table:t, pk col:test.t.a // Group#3 Schema:[test.t.a,test.t.f] // IndexScan_8 table:t, index:f, g // Group#4 Schema:[test.t.a,test.t.f] // IndexScan_6 table:t, index:f propMap := make(map[*memo.Group][][]*expression.Column) aggProp := preparePossibleProperties(group, propMap) // We only have one prop for Group0 : f require.Len(t, aggProp, 1) require.True(t, aggProp[0][0].Equal(nil, columnF)) gatherGroup := group.Equivalents.Front().Value.(*memo.GroupExpr).Children[0] gatherProp, ok := propMap[gatherGroup] require.True(t, ok) // We have 2 props for Group1: [f], [a] require.Len(t, gatherProp, 2) for _, prop := range gatherProp { require.Len(t, prop, 1) require.True(t, prop[0].Equal(nil, columnA) || prop[0].Equal(nil, columnF)) } } // fakeTransformation is used for TestAppliedRuleSet. type fakeTransformation struct { baseRule appliedTimes int } // OnTransform implements Transformation interface. func (rule *fakeTransformation) OnTransform(old *memo.ExprIter) (newExprs []*memo.GroupExpr, eraseOld bool, eraseAll bool, err error) { rule.appliedTimes++ old.GetExpr().AddAppliedRule(rule) return []*memo.GroupExpr{old.GetExpr()}, true, false, nil } func TestAppliedRuleSet(t *testing.T) { p := parser.New() ctx := plannercore.MockContext() is := infoschema.MockInfoSchema([]*model.TableInfo{plannercore.MockSignedTable()}) domain.GetDomain(ctx).MockInfoCacheAndLoadInfoSchema(is) optimizer := NewOptimizer() rule := fakeTransformation{} rule.pattern = memo.NewPattern(memo.OperandProjection, memo.EngineAll) optimizer.ResetTransformationRules(map[memo.Operand][]Transformation{ memo.OperandProjection: { &rule, }, }) defer func() { optimizer.ResetTransformationRules(DefaultRuleBatches...) }() stmt, err := p.ParseOneStmt("select 1", "", "") require.NoError(t, err) plan, _, err := plannercore.BuildLogicalPlanForTest(context.Background(), ctx, stmt, is) require.NoError(t, err) logic, ok := plan.(plannercore.LogicalPlan) require.True(t, ok) group := memo.Convert2Group(logic) require.NoError(t, optimizer.onPhaseExploration(ctx, group)) require.Equal(t, 1, rule.appliedTimes) }
package redisDB type ResTask struct { UID uint64 ID int16 Result int16 Data []byte }
package parquet import "github.com/segmentio/parquet-go/internal/unsafecast" type allocator struct{ buffer []byte } func (a *allocator) makeBytes(n int) []byte { if free := cap(a.buffer) - len(a.buffer); free < n { newCap := 2 * cap(a.buffer) if newCap == 0 { newCap = 4096 } for newCap < n { newCap *= 2 } a.buffer = make([]byte, 0, newCap) } i := len(a.buffer) j := len(a.buffer) + n a.buffer = a.buffer[:j] return a.buffer[i:j:j] } func (a *allocator) copyBytes(v []byte) []byte { b := a.makeBytes(len(v)) copy(b, v) return b } func (a *allocator) copyString(v string) string { b := a.makeBytes(len(v)) copy(b, v) return unsafecast.BytesToString(b) } func (a *allocator) reset() { a.buffer = a.buffer[:0] } // rowAllocator is a memory allocator used to make a copy of rows referencing // memory buffers that parquet-go does not have ownership of. // // This type is used in the implementation of various readers and writers that // need to capture rows passed to the ReadRows/WriteRows methods. Copies to a // local buffer is necessary in those cases to repect the reader/writer // contracts that do not allow the implementations to retain the rows they // are passed as arguments. // // See: RowBuffer, DedupeRowReader, DedupeRowWriter type rowAllocator struct{ allocator } func (a *rowAllocator) capture(row Row) { for i, v := range row { switch v.Kind() { case ByteArray, FixedLenByteArray: row[i].ptr = unsafecast.AddressOfBytes(a.copyBytes(v.byteArray())) } } }
package main import "github.com/vanishs/gwsrpc/services/demo" import "github.com/vanishs/gwsrpc/services/aaa" import "github.com/vanishs/gwsrpc/services/bbb" //Sain Services Main function is Sain func Sain(democh, aaach, bbbch chan string) { go func() { for { <-democh demoService.Start(10000, false, "", "", democh) } }() go func() { for { <-aaach aaaService.Start(10001, false, "", "", aaach) } }() go func() { for { <-bbbch bbbService.Start(10002, false, "", "", bbbch) } }() }
// Copyright 2020 astaxie // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "time" "github.com/beego/beego/v2/server/web" "github.com/beego/beego/v2/server/web/filter/prometheus" ) func main() { // we start admin service // Prometheus will fetch metrics data from admin service's port web.BConfig.Listen.EnableAdmin = true web.BConfig.AppName = "my app" ctrl := &MainController{} web.Router("/hello", ctrl, "get:Hello") fb := &prometheus.FilterChainBuilder{} web.InsertFilterChain("/*", fb.FilterChain) web.Run(":8080") // after you start the server // and GET http://localhost:8080/hello // access http://localhost:8088/metrics // you can see something looks like: // http_request_web_sum{appname="my app",duration="1002",env="prod",method="GET",pattern="/hello",server="webServer:1.12.1",status="200"} 1002 // http_request_web_count{appname="my app",duration="1002",env="prod",method="GET",pattern="/hello",server="webServer:1.12.1",status="200"} 1 // http_request_web_sum{appname="my app",duration="1004",env="prod",method="GET",pattern="/hello",server="webServer:1.12.1",status="200"} 1004 // http_request_web_count{appname="my app",duration="1004",env="prod",method="GET",pattern="/hello",server="webServer:1.12.1",status="200"} 1 } type MainController struct { web.Controller } func (ctrl *MainController) Hello() { time.Sleep(time.Second) ctrl.Ctx.ResponseWriter.Write([]byte("Hello, world")) }
// Frank Nanez // 4-25-20 // program to display my top 25 games played on steam and give information for user to learn more about the game. //load main package and import fmt, math/rand, time, and strconv packages into program. package main import ( "fmt" "math/rand" "time" "strconv" "strings" ) // create a struct for game info objects to include number, hours played, name, genre, and synopsis type ginfo struct { Number string Hrs float64 Name, Genre, Synopsis string } // create a function that can pick a random number and can convert to string to use in if statements later func randPick(answer string) (string) { rand.Seed(time.Now().UnixNano()) n := (rand.Intn(24)+1) number := strconv.Itoa(n) return number } // create your main func inlcude all objects and classes for games and info needed. func main (){ var game[25]ginfo game[0] = ginfo{ Number: "1", Name: "Banished", Hrs: 349, Genre: "Simulation, Stragey, City Builder", Synopsis: "You and a group of exiled travelers who decide to restart their lives in a new land. They have only the clothes on their backs and a cart filled with supplies from their homeland. The townspeople of Banished are your primary resource. You must build, survive, and if you’re good enough, thrive.", } game[1] = ginfo{ Number: "2", Name: "Dota 2", Hrs: 142, Genre: "MOBA, strategy", Synopsis: "Primary game mode is player vs player (PvP) where two teams of five battle against one another with waves of computer minions to help you push a “lane” guarded by other players, their minions, and towers.", } game[2] = ginfo{ Number: "3", Name: "Mini Ninja’s", Hrs: 94, Genre: "action, adventure, indie", Synopsis: "Mini Ninjas is a game that combines furious action with stealth and exploration for an experience that appeals to a wide audience across age groups and preferences. Set with a ninja oriental theme. Fight against the darkness that is attacking your home and the ones you know and love.", } game[3] = ginfo{ Number: "4", Name: "The Elder Scrolls V: Skyrim", Hrs: 79, Genre: "Open world, RPG, first person", Synopsis: "Dragons were thought to be extinct. You, a prisoner, survive and attack by a dragon and find out that you are a “dragonborn”. One who can speak the dragon language and use their shouts, a special ability/magic. You can create a character with tons of customization options and explore and play the game anyway you desire with the vast open world with plenty of choice and quests to take.", } game[4] = ginfo{ Number: "5", Name: "Sid Meier's Civilization V", Hrs: 62, Genre: "Turn-based strategy, 4x", Synopsis: "Play one of history’s greatest civilizations. Employ diplomatic, research, and military strategies to be the best civilization and win, choosing from many maps and map sizes for the set of your theatre.", } game[5] = ginfo{ Number: "6", Name: "Borderlands 2", Hrs: 55, Genre: "open world, RPG, first person", Synopsis: "Play as one of four vault hunters facing off against a massive world of creatures, psychos and the evil mastermind, Handsome Jack. Make new friends, arm them with a bazillion weapons to help you on your adventure.", } game[6] = ginfo{ Number: "7", Name: "Company of Heroes-Legacy edition", Hrs: 51, Genre: "real-time strategy", Synopsis: "Delivering a visceral WWII gaming experience, Company of Heroes redefines real time strategy gaming by bringing the sacrifice of heroic soldiers, war-ravaged environments, and dynamic battlefields to life. Beginning with the D-Day Invasion of Normandy, players lead squads of Allied soldiers into battle against the German war machine through some of the most pivotal battles of WWII. Through a rich single player campaign, players experience the cinematic intensity and bravery of ordinary soldiers thrust into extraordinary events.", } game[7] = ginfo{ Number: "8", Name: "PAYDAY 2", Hrs: 47, Genre: "First person shooter, strategy/heist", Synopsis: "Team up with up to four friends or other online players to take on heists and earn money, buy weapons, and customize your gear to help you be successful.", } game[8] = ginfo{ Number: "9", Name: "The Forest", Hrs: 47, Genre: "Survival, horror, PVE", Synopsis: "Your plane crash lands on this beautiful island with a lush environment. You awake after the crash landing, only remembering your son calling out to you as he is dragged away, having blurry vision you don’t remember many details. You need to build some shelter and a base camp for your exploration. Soon after establishing some semblance of a shelter you see something off in the distance scoping out your new home. It’s a savage tribal inhabitant that you soon find out is a cannibal. You need to hurry and find your son and find a way off the island.", } game[9] = ginfo{ Number: "10", Name: "Endless Legend", Hrs: 45, Genre: "Turn-based strategy, 4X", Synopsis: ": Play as one of many civilizations, or create one of your own. Employ diplomatic, research, and military strategies to be the best civilization and win. Select diverse maps and setting to help make every skirmish unique and challenging.", } game[10] = ginfo{ Number: "11", Name: "Unturned", Hrs: 34, Genre: "survival, PVE, PVP", Synopsis: "Create or join a world in which you survive the zombie apocalypse.", } game[11] = ginfo{ Number: "12", Name: "Tales of Zestiria", Hrs: 33, Genre: "action, RPG, anime style", Synopsis: "In a world torn by war and political skirmishes, accept the burden of the Shepherd and fight human darkness to protect your world from Malevolence and reunite humans and Seraphim.", } game[12] = ginfo{ Number: "13", Name: "South Park™: The Stick of Truth™", Hrs: 33, Genre: "turn-based strategy, RPG", Synopsis: "From the perilous battlefields of the fourth-grade playground, a young hero will rise, destined to be South Park’s savior. From the creators of South Park, Trey Parker and Matt Stone, comes an epic quest to become… cool. Introducing South Park™: The Stick of Truth™.", } game[13] = ginfo{ Number: "14", Name: "Endless Space", Hrs: 28, Genre: "turn-based strategy, 4X", Synopsis: "Covering the space colonization age in the Endless universe, where you can control every aspect of your civilization as you strive for galactic domination.", } game[14] = ginfo{ Number: "15", Name: "Kerbal Space Program", Hrs: 27, Genre: "simulation, sandbox", Synopsis: ": In Kerbal Space Program, take charge of the space program for the alien race known as the Kerbals. You have access to an array of parts to assemble fully-functional spacecraft that flies (or doesn’t) based on realistic aerodynamic and orbital physics.", } game[15] = ginfo{ Number: "16", Name: "ARK: Survival Evolved", Hrs: 26, Genre: "survival, PVE, PVP", Synopsis: "Stranded on the shores of a mysterious island, you must learn to survive. Use your cunning to kill or tame the primeval creatures roaming the land, and encounter other players to survive, dominate... and escape!", } game[16] = ginfo{ Number: "17", Name: "Sid Meier's Civilization VI", Hrs: 25, Genre: "turn-based strategy, 4x", Synopsis: "a turn-based strategy game in which you attempt to build an empire to stand the test of time. Become Ruler of the World by establishing and leading a civilization from the Stone Age to the Information Age. Wage war, conduct diplomacy, advance your culture, and go head-to-head with history’s greatest leaders as you attempt to build the greatest civilization the world has ever known. Competing leaders will pursue their own agendas based on their historical traits as you race for one of five ways to achieve victory in the game.", } game[17] = ginfo{ Number: "18", Name: "Left 4 dead 2", Hrs: 23, Genre: "survival, first person", Synopsis: "Set in the zombie apocalypse, Left 4 Dead 2 (L4D2) is the highly anticipated sequel to the award-winning Left 4 Dead. This co-operative action horror FPS takes you and your friends through the cities, swamps and cemeteries of the Deep South, from Savannah to New Orleans across five expansive campaigns. You'll play as one of four new survivors armed with a wide and devastating array of classic and upgraded weapons. In addition to firearms, you'll also get a chance to take out some aggression on infected with a variety of carnage-creating melee weapons, from chainsaws to axes and even the deadly frying pan.", } game[18] = ginfo{ Number: "19", Name: "Planetary Annihilation: TITANS", Hrs: 22, Genre: "real-time strategy", Synopsis: "Wage war across entire solar systems with massive armies at your command. Annihilate enemy forces with world-shattering TITAN-class units, and demolish planets with massive super weapons!", } game[19] = ginfo{ Number: "20", Name: "Final Fantasy IV", Hrs: 19.8, Genre: "RPG", Synopsis: "it is the fourth main installment of the Final Fantasy series. The game's story follows Cecil, a dark knight, as he tries to prevent the sorcerer Golbez from seizing powerful crystals and destroying the world", } game[20] = ginfo{ Number: "21", Name: "South Park™: The Fractured But Whole™", Hrs: 19.3, Genre: "turn-based strategy, RPG", Synopsis: "Players will delve into the crime-ridden underbelly of South Park with Coon and Friends. This dedicated group of crime fighters was formed by Eric Cartman whose superhero alter-ego, The Coon, is half man, half raccoon. As the New Kid, players will join Mysterion, Toolshed, Human Kite and a host of others to battle the forces of evil while Coon strives to make his team the most beloved superheroes in history.", } game[21] = ginfo{ Number: "22", Name: "Total War: Shogun 2", Hrs: 18.8, Genre: "turn-based strategy, real-time strategy", Synopsis: "In the darkest age of Japan, endless war leaves a country divided. It is the middle of the 16th Century in Feudal Japan. The country, once ruled by a unified government, is now split into many warring clans. Ten legendary warlords strive for supremacy as conspiracies and conflicts wither the empire. Only one will rise above all to win the heart of a nation as the new shogun...The others will die by his sword.Take on the role of one Daimyo, the clan leader, and use military engagements, economics and diplomacy to achieve the ultimate goal: re-unite Japan under his supreme command and become the new Shogun – the undisputed ruler of a pacified nation.", } game[22] = ginfo{ Number: "23", Name: "Planetbase", Hrs: 17.4, Genre: "strategy, survival, simulation, city builder", Synopsis: "Guide a group of space settlers trying to establish a base on a remote planet. Grow food, collect energy, mine resources, survive disasters and build a self-sufficient colony in a harsh and unforgiving environment.", } game[23] = ginfo{ Number: "24", Name: "Dead by Daylight", Hrs: 16.5, Genre: "horror, action, survival", Synopsis: "a multiplayer (4vs1) horror game where one player takes on the role of the savage Killer, and the other four players play as Survivors, trying to escape the Killer and avoid being caught and killed.", } game[24] = ginfo{ Number: "25", Name: "Anno 2077", Hrs: 16, Genre: "real-time strategy, simulation, city builder", Synopsis: "2070. Our world has changed. The rising level of the ocean has harmed the coastal cities and climate change has made large stretches of land inhospitable. Master resources, diplomacy, and trade in the most comprehensive economic management system in the Anno series. Build your society of the future, colonize islands, and create sprawling megacities with multitudes of buildings, vehicles, and resources to manage. Engineer production chains such as Robot Factories, Oil Refineries, and Diamond Mines, and trade with a variety of goods and commodities.", } // inside program create variable for user to use for input var x string // inside main: print initial game info to include number and name for user to make a selection for i:=0; i<=24; i++{ fmt.Println(game[i].Number, game[i].Name) } // inside main: print statement to explain how program works and how to work program fmt.Println("Above is a list of games played by me and the number associated with them in order from most played game down to least played. Please enter the game you would like to know more about by entering the associated number. You may also select 'random' if you need help picking somewhere to start.You may also type 'done' to end the program.") fmt.Scanln(&x) // convert answer to title to take any answer and make sure it reads the same everytime. x = strings.Title(x) // create a variable for loop to use as a counter l := 0 for x != "Done"{ // inside main: create loop that continues until user types "done"as selection or some itteration to complete program. for i :=0; i<=24; i++{ if x == "Random"{ X := randPick(x) fmt.Println("The random number you are given is",X) x = X }else if x == game[i].Number{ fmt.Println("#",game[l].Number,game[l].Name,"hours played:",game[l].Hrs,"\n","genre:",game[l].Genre,"\n","synopsis:",game[l].Synopsis) i=25 }else if x == "Done" { i = 25 } l= l+1 } // prompt for new selection after appropriate info displayed before repeating loop or ending program for i:=0; i<=24; i++{ fmt.Println(game[i].Number, game[i].Name) } fmt.Scanln(&x) x = strings.Title(x) } fmt.Println("Thank you for using my program to learn about my top games. I hope one or more of these has sparked your interest and you get a chance to experience these great games.") }
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package request import ( "net/http" ) // DefaultWidthEstimator returns returns '1' as the "width" // of the given request. // // TODO: when we plumb in actual "width" handling for different // type of request(s) this function will iterate through a chain // of widthEstimator instance(s). func DefaultWidthEstimator(_ *http.Request) uint { return 1 } // WidthEstimatorFunc returns the estimated "width" of a given request. // This function will be used by the Priority & Fairness filter to // estimate the "width" of incoming requests. type WidthEstimatorFunc func(*http.Request) uint func (e WidthEstimatorFunc) EstimateWidth(r *http.Request) uint { return e(r) }
// Copyright (c) 2015-2017 Marcus Rohrmoser, http://purl.mro.name/recorder // // 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. // // MIT License http://opensource.org/licenses/MIT // Scrape http://br.de program schedule + broadcast pages. // // import "purl.mro.name/recorder/radio/scrape/br" package br import ( "errors" "fmt" "io" "net/url" "regexp" "strings" "time" "github.com/yhat/scrape" "golang.org/x/net/html" "golang.org/x/net/html/atom" r "purl.mro.name/recorder/radio/scrape" ) ///////////////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////////////// /// Just wrap Station into a distinct, local type. type station r.Station // Station Factory // // Returns a instance conforming to 'scrape.Scraper' func Station(identifier string) *station { tz, err := time.LoadLocation("Europe/Berlin") if nil != err { panic(err) } s := map[string]station{ "b+": station(r.Station{Name: "Bayern Plus", CloseDown: "05:00", ProgramURL: r.MustParseURL("http://www.br.de/radio/bayern-plus/programmkalender/bayern-plus114.html"), Identifier: identifier, TimeZone: tz}), "b1": station(r.Station{Name: "Bayern 1", CloseDown: "05:00", ProgramURL: r.MustParseURL("http://www.br.de/radio/bayern1/service/programm/index.html"), Identifier: identifier, TimeZone: tz}), "b2": station(r.Station{Name: "Bayern 2", CloseDown: "05:00", ProgramURL: r.MustParseURL("http://www.br.de/radio/bayern2/service/programm/index.html"), Identifier: identifier, TimeZone: tz}), "b5": station(r.Station{Name: "Bayern 5", CloseDown: "06:00", ProgramURL: r.MustParseURL("http://www.br.de/radio/b5-aktuell/programmkalender/b5aktuell116.html"), Identifier: identifier, TimeZone: tz}), "brheimat": station(r.Station{Name: "BR Heimat", CloseDown: "05:00", ProgramURL: r.MustParseURL("http://www.br.de/radio/br-heimat/programmkalender/br-heimat-116.html"), Identifier: identifier, TimeZone: tz}), "puls": station(r.Station{Name: "Puls", CloseDown: "07:00", ProgramURL: r.MustParseURL("http://www.br.de/puls/programm/puls-radio/programmkalender/programmfahne104.html"), Identifier: identifier, TimeZone: tz}), }[identifier] // fmt.Fprintf(os.Stderr, " %p %s\n", &s, s.Name) return &s } func (s *station) String() string { return fmt.Sprintf("Station '%s'", s.Name) } func (s *station) parseDayURLsNode(root *html.Node) (ret []timeURL, err error) { i := 0 for _, a := range scrape.FindAll(root, func(n *html.Node) bool { return atom.A == n.DataAtom && atom.Td == n.Parent.DataAtom }) { rel := scrape.Attr(a, "href") d, err := s.newTimeURL(rel) if nil != err { continue } // use only every 3rd day schedule url because each one contains 3 days i += 1 if 2 != i%3 { continue } // fmt.Printf("ok %s\n", d.String()) ret = append(ret, timeURL(d)) } return } func (s *station) parseDayURLsReader(read io.Reader, cr0 *r.CountingReader) (ret []timeURL, err error) { cr := r.NewCountingReader(read) root, err := html.Parse(cr) r.ReportLoad("🐦", cr0, cr, *s.ProgramURL) if nil != err { return } ret, err = s.parseDayURLsNode(root) return } func (s *station) parseDayURLs() (ret []timeURL, err error) { bo, cr, err := r.HttpGetBody(*s.ProgramURL) if nil == bo { return nil, err } return s.parseDayURLsReader(bo, cr) } // Scrape slice of timeURL - all calendar (day) entries of the station program url func (s *station) Scrape() (jobs []r.Scraper, results []r.Broadcaster, err error) { dayUrls, err := s.parseDayURLs() if nil == err { for _, v := range dayUrls { vv := v jobs = append(jobs, &vv) } } return } func (s *station) Matches(nows []time.Time) (ok bool) { return true } var ( urlDayRegExp *regexp.Regexp = regexp.MustCompile("^/.+~_date-(\\d{4}-\\d{2}-\\d{2})_-[0-9a-f]{40}\\.html$") ) func (s *station) newTimeURL(relUrl string) (ret r.TimeURL, err error) { m := urlDayRegExp.FindStringSubmatch(relUrl) if nil == m { err = errors.New("Couldn't match regexp on " + relUrl + "") return } dayStr := m[1] day, err := time.ParseInLocation("2006-01-02 15:04", dayStr+" "+s.CloseDown, s.TimeZone) if nil != err { return } ru, _ := url.Parse(relUrl) programURL := *s.ProgramURL.ResolveReference(ru) ret = r.TimeURL{Time: day, Source: programURL, Station: r.Station(*s)} if "" == ret.Station.Identifier { panic("How can the identifier miss?") } // fmt.Fprintf(os.Stderr, " t %s %s\n", ret.Time.Format(time.RFC3339), ret.Source.String()) return } ///////////////////////////////////////////////////////////////////////////// /// Just wrap TimeURL into a distinct, local type. type timeURL r.TimeURL // Scrape slice of broadcastURL - all per-day broadcast entries of the day url func (day *timeURL) Scrape() (jobs []r.Scraper, results []r.Broadcaster, err error) { broadcastUrls, err := day.parseBroadcastURLs() if nil == err { for _, b := range broadcastUrls { bb := *b jobs = append(jobs, &bb) } } return } // 3 days window, 1 day each side. func (day *timeURL) Matches(nows []time.Time) (ok bool) { if nil == nows || nil == day { return false } for _, now := range nows { dt := day.Time.Sub(now) if -24*time.Hour <= dt && dt <= 24*time.Hour { return true } } return false } func (day *timeURL) parseBroadcastURLsNode(root *html.Node) (ret []*broadcastURL, err error) { const closeDownHour int = 5 for _, h4 := range scrape.FindAll(root, func(n *html.Node) bool { return atom.H4 == n.DataAtom }) { year, month, day2, err := timeForH4(scrape.Text(h4), &day.Time) if nil != err { panic(err) } // fmt.Printf("%d-%d-%d %s\n", year, month, day, err) for _, a := range scrape.FindAll(h4.Parent, func(n *html.Node) bool { return atom.A == n.DataAtom && atom.Dt == n.Parent.DataAtom }) { m := hourMinuteTitleRegExp.FindStringSubmatch(scrape.Text(a)) if nil == m { panic(errors.New("Couldn't parse <a>")) } ur, _ := url.Parse(scrape.Attr(a, "href")) hour := r.MustParseInt(m[1]) dayOffset := 0 if hour < closeDownHour { dayOffset = 1 } // fmt.Printf("%s %s\n", b.r.TimeURL.String(), b.Title) bcu := broadcastURL(r.BroadcastURL{ TimeURL: r.TimeURL{ Time: time.Date(year, month, day2+dayOffset, hour, r.MustParseInt(m[2]), 0, 0, localLoc), Source: *day.Source.ResolveReference(ur), Station: day.Station, }, Title: strings.TrimSpace(m[3]), }) ret = append(ret, &bcu) } } return } func (day *timeURL) parseBroadcastURLsReader(read io.Reader, cr0 *r.CountingReader) (ret []*broadcastURL, err error) { cr := r.NewCountingReader(read) root, err := html.Parse(cr) r.ReportLoad("🐠", cr0, cr, day.Source) if nil != err { return } return day.parseBroadcastURLsNode(root) } func (day *timeURL) parseBroadcastURLs() (ret []*broadcastURL, err error) { bo, cr, err := r.HttpGetBody(day.Source) if nil == bo { return nil, err } return day.parseBroadcastURLsReader(bo, cr) } ///////////////////////////////////////////////////////////////////////////// /// /// Just wrap BroadcastURL into a distinct, local type. type broadcastURL r.BroadcastURL func (bcu *broadcastURL) Scrape() (jobs []r.Scraper, results []r.Broadcaster, err error) { bcs, err := bcu.parseBroadcastsFromURL() if nil == err { for _, bc := range bcs { results = append(results, bc) } } return } // 1h future interval func (bcu *broadcastURL) Matches(nows []time.Time) (ok bool) { start := &bcu.Time if nil == nows || nil == start { return false } for _, now := range nows { dt := start.Sub(now) // fmt.Fprintf(os.Stderr, "*broadcastURL.Matches: %d %d = %s - %s\n", ok, dt, start.Format(time.RFC3339), now.Format(time.RFC3339)) if 0 <= dt && dt <= 60*time.Minute { return true } } return false } ///////////////////////////////////////////////////////////////////////////// /// var ( localLoc *time.Location // TODO: abolish, replace with r.Station.TimeZone ) func init() { var err error localLoc, err = time.LoadLocation("Europe/Berlin") if nil != err { panic(err) } } ///////////////////////////////////////////////////////////////////////////// /// Find daily URLs ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /// Find broadcast schedule per (three) day ///////////////////////////////////////////////////////////////////////////// func yearForMonth(mo time.Month, now *time.Time) int { year := now.Year() if mo+6 <= now.Month() { year += 1 } return year } var ( dayMonthRegExp = regexp.MustCompile(",\\s+(\\d{2})\\.(\\d{2})\\.") hourMinuteTitleRegExp = regexp.MustCompile("(\\d{2}):(\\d{2})\\s+(\\S(?:.*\\S)?)") ) func timeForH4(h4 string, now *time.Time) (year int, mon time.Month, day int, err error) { m := dayMonthRegExp.FindStringSubmatch(h4) if nil == m { // err = error.New("Couldn't parse " + h4) return } mon = time.Month(r.MustParseInt(m[2])) year = yearForMonth(mon, now) day = r.MustParseInt(m[1]) return } ///////////////////////////////////////////////////////////////////////////// /// Parse broadcast ///////////////////////////////////////////////////////////////////////////// var ( bcDateRegExp = regexp.MustCompile(",\\s+(\\d{2})\\.(\\d{2})\\.(\\d{4})\\s+(\\d{2}):(\\d{2})\\s+bis\\s+(\\d{2}):(\\d{2})") ) // Completely re-scrape everything and verify consistence at least of Time, evtl. Title func (bcu *broadcastURL) parseBroadcastNode(root *html.Node) (bcs []r.Broadcast, err error) { var bc r.Broadcast bc.Station = bcu.Station bc.Source = bcu.Source { s := "de" bc.Language = &s } // Title, TitleSeries, TitleEpisode for i, h1 := range scrape.FindAll(root, func(n *html.Node) bool { return atom.H1 == n.DataAtom && "bcast_headline" == scrape.Attr(n, "class") }) { if i != 0 { err = errors.New("There was more than 1 <h1 class='bcast_headline'>") return } bc.Title = r.TextChildrenNoClimb(h1) for _, span := range scrape.FindAll(h1, func(n *html.Node) bool { return atom.Span == n.DataAtom }) { switch scrape.Attr(span, "class") { case "bcast_overline": s := scrape.Text(span) bc.TitleSeries = &s case "bcast_subtitle": s := scrape.Text(span) bc.TitleEpisode = &s default: err = errors.New("unexpected <span> inside <h1>") return } bc.Title = r.TextChildrenNoClimb(h1) } { description := r.TextWithBrFromNodeSet(scrape.FindAll(h1.Parent.Parent, func(n *html.Node) bool { return atom.P == n.DataAtom && "copytext" == scrape.Attr(n, "class") })) bc.Description = &description } if nil == bc.Image { FoundImage0: for _, di := range scrape.FindAll(h1.Parent, func(n *html.Node) bool { return atom.Div == n.DataAtom && "teaser media_video embeddedMedia" == scrape.Attr(n, "class") }) { for _, img := range scrape.FindAll(di, func(n *html.Node) bool { return atom.Img == n.DataAtom }) { u, _ := url.Parse(scrape.Attr(img, "src")) bc.Image = bcu.Source.ResolveReference(u) break FoundImage0 } } } if nil == bc.Image { FoundImage1: // test some candidates: for _, no := range []*html.Node{h1.Parent, root} { for _, di := range scrape.FindAll(no, func(n *html.Node) bool { return atom.Div == n.DataAtom && "picturebox" == scrape.Attr(n, "class") }) { for _, img := range scrape.FindAll(di, func(n *html.Node) bool { return atom.Img == n.DataAtom }) { u, _ := url.Parse(scrape.Attr(img, "src")) bc.Image = bcu.Source.ResolveReference(u) break FoundImage1 } } } } } // Time, DtEnd for idx, p := range scrape.FindAll(root, func(n *html.Node) bool { return atom.P == n.DataAtom && "bcast_date" == scrape.Attr(n, "class") }) { if idx != 0 { err = errors.New("There was more than 1 <p class='bcast_date'>") return } m := bcDateRegExp.FindStringSubmatch(scrape.Text(p)) if nil == m { err = errors.New("There was no date match") return } i := r.MustParseInt bc.Time = time.Date(i(m[3]), time.Month(i(m[2])), i(m[1]), i(m[4]), i(m[5]), 0, 0, localLoc) t := time.Date(i(m[3]), time.Month(i(m[2])), i(m[1]), i(m[6]), i(m[7]), 0, 0, localLoc) if bc.Time.Hour() > t.Hour() || (bc.Time.Hour() == t.Hour() && bc.Time.Minute() > t.Minute()) { // after midnight t = t.AddDate(0, 0, 1) } bc.DtEnd = &t } // Language for idx, meta := range scrape.FindAll(root, func(n *html.Node) bool { return atom.Meta == n.DataAtom && "og:locale" == scrape.Attr(n, "property") }) { if idx != 0 { err = errors.New("There was more than 1 <meta property='og:locale'/>") return } v := scrape.Attr(meta, "content")[0:2] bc.Language = &v } // Subject for idx, a := range scrape.FindAll(root, func(n *html.Node) bool { return atom.A == n.DataAtom && strings.HasPrefix(scrape.Attr(n, "class"), "link_broadcast media_broadcastSeries") }) { if idx != 0 { err = errors.New("There was more than 1 <a class='link_broadcast media_broadcastSeries'/>") return } u, _ := url.Parse(scrape.Attr(a, "href")) bc.Subject = bc.Source.ResolveReference(u) } // Modified for idx, meta := range scrape.FindAll(root, func(n *html.Node) bool { return atom.Meta == n.DataAtom && "og:article:modified_time" == scrape.Attr(n, "property") }) { if idx != 0 { err = errors.New("There was more than 1 <meta property='og:article:modified_time'/>") return } v, _ := time.Parse(time.RFC3339, scrape.Attr(meta, "content")) bc.Modified = &v } // Author for idx, meta := range scrape.FindAll(root, func(n *html.Node) bool { return atom.Meta == n.DataAtom && "author" == scrape.Attr(n, "name") }) { if idx != 0 { err = errors.New("There was more than 1 <meta name='author'/>") return } s := scrape.Attr(meta, "content") bc.Author = &s } if "" == bc.Station.Identifier { panic("How can the identifier miss?") } bcs = append(bcs, bc) return } func (bcu *broadcastURL) parseBroadcastReader(read io.Reader, cr0 *r.CountingReader) (bc []r.Broadcast, err error) { cr := r.NewCountingReader(read) root, err := html.Parse(cr) r.ReportLoad("⚓️", cr0, cr, bcu.Source) if nil != err { return } return bcu.parseBroadcastNode(root) } func (bcu *broadcastURL) parseBroadcastsFromURL() (bc []r.Broadcast, err error) { return r.GenericParseBroadcastFromURL(bcu.Source, func(r io.Reader, cr *r.CountingReader) ([]r.Broadcast, error) { return bcu.parseBroadcastReader(r, cr) }) }
package handler // GetSensitiveWords 判断答案是否包含敏感词 func GetSensitiveWords(in string) []string { //TODO: return []string{} } // GetReservedWords 判断答案是否包含保留词 func GetReservedWords(in string) []string { //TODO: return []string{} } // GetMaskWords 判断答案是否包含屏蔽词 func GetMaskWords(in string) []string { //TODO: return []string{} }
package main /* Types which don't support comparisons Following types don't support comparisons: map slice function struct types containing uncomparable fields array types with uncomparable elements Types which don't support comparisons can't be used as the key types of map types. Please note, although map, slice and function types don't support comparisons, their values can be compared to the bare nil identifier. comparing two interface values with the same uncomparable dynamic types will panic at run time. */ func main() { // http://127.0.0.1:55555/article/value-conversions-assignments-and-comparisons.html }
// Copyright 2023 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package server import ( "context" "github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl" betapb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/compute/beta/compute_beta_go_proto" emptypb "github.com/GoogleCloudPlatform/declarative-resource-client-library/python/proto/empty_go_proto" "github.com/GoogleCloudPlatform/declarative-resource-client-library/services/google/compute/beta" ) // ServiceAttachmentServer implements the gRPC interface for ServiceAttachment. type ServiceAttachmentServer struct{} // ProtoToServiceAttachmentConnectionPreferenceEnum converts a ServiceAttachmentConnectionPreferenceEnum enum from its proto representation. func ProtoToComputeBetaServiceAttachmentConnectionPreferenceEnum(e betapb.ComputeBetaServiceAttachmentConnectionPreferenceEnum) *beta.ServiceAttachmentConnectionPreferenceEnum { if e == 0 { return nil } if n, ok := betapb.ComputeBetaServiceAttachmentConnectionPreferenceEnum_name[int32(e)]; ok { e := beta.ServiceAttachmentConnectionPreferenceEnum(n[len("ComputeBetaServiceAttachmentConnectionPreferenceEnum"):]) return &e } return nil } // ProtoToServiceAttachmentConnectedEndpointsStatusEnum converts a ServiceAttachmentConnectedEndpointsStatusEnum enum from its proto representation. func ProtoToComputeBetaServiceAttachmentConnectedEndpointsStatusEnum(e betapb.ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum) *beta.ServiceAttachmentConnectedEndpointsStatusEnum { if e == 0 { return nil } if n, ok := betapb.ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum_name[int32(e)]; ok { e := beta.ServiceAttachmentConnectedEndpointsStatusEnum(n[len("ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum"):]) return &e } return nil } // ProtoToServiceAttachmentConnectedEndpoints converts a ServiceAttachmentConnectedEndpoints object from its proto representation. func ProtoToComputeBetaServiceAttachmentConnectedEndpoints(p *betapb.ComputeBetaServiceAttachmentConnectedEndpoints) *beta.ServiceAttachmentConnectedEndpoints { if p == nil { return nil } obj := &beta.ServiceAttachmentConnectedEndpoints{ Status: ProtoToComputeBetaServiceAttachmentConnectedEndpointsStatusEnum(p.GetStatus()), PscConnectionId: dcl.Int64OrNil(p.GetPscConnectionId()), Endpoint: dcl.StringOrNil(p.GetEndpoint()), } return obj } // ProtoToServiceAttachmentConsumerAcceptLists converts a ServiceAttachmentConsumerAcceptLists object from its proto representation. func ProtoToComputeBetaServiceAttachmentConsumerAcceptLists(p *betapb.ComputeBetaServiceAttachmentConsumerAcceptLists) *beta.ServiceAttachmentConsumerAcceptLists { if p == nil { return nil } obj := &beta.ServiceAttachmentConsumerAcceptLists{ ProjectIdOrNum: dcl.StringOrNil(p.GetProjectIdOrNum()), ConnectionLimit: dcl.Int64OrNil(p.GetConnectionLimit()), } return obj } // ProtoToServiceAttachmentPscServiceAttachmentId converts a ServiceAttachmentPscServiceAttachmentId object from its proto representation. func ProtoToComputeBetaServiceAttachmentPscServiceAttachmentId(p *betapb.ComputeBetaServiceAttachmentPscServiceAttachmentId) *beta.ServiceAttachmentPscServiceAttachmentId { if p == nil { return nil } obj := &beta.ServiceAttachmentPscServiceAttachmentId{ High: dcl.Int64OrNil(p.GetHigh()), Low: dcl.Int64OrNil(p.GetLow()), } return obj } // ProtoToServiceAttachment converts a ServiceAttachment resource from its proto representation. func ProtoToServiceAttachment(p *betapb.ComputeBetaServiceAttachment) *beta.ServiceAttachment { obj := &beta.ServiceAttachment{ Id: dcl.Int64OrNil(p.GetId()), Name: dcl.StringOrNil(p.GetName()), Description: dcl.StringOrNil(p.GetDescription()), SelfLink: dcl.StringOrNil(p.GetSelfLink()), Region: dcl.StringOrNil(p.GetRegion()), TargetService: dcl.StringOrNil(p.GetTargetService()), ConnectionPreference: ProtoToComputeBetaServiceAttachmentConnectionPreferenceEnum(p.GetConnectionPreference()), EnableProxyProtocol: dcl.Bool(p.GetEnableProxyProtocol()), PscServiceAttachmentId: ProtoToComputeBetaServiceAttachmentPscServiceAttachmentId(p.GetPscServiceAttachmentId()), Fingerprint: dcl.StringOrNil(p.GetFingerprint()), Project: dcl.StringOrNil(p.GetProject()), Location: dcl.StringOrNil(p.GetLocation()), } for _, r := range p.GetConnectedEndpoints() { obj.ConnectedEndpoints = append(obj.ConnectedEndpoints, *ProtoToComputeBetaServiceAttachmentConnectedEndpoints(r)) } for _, r := range p.GetNatSubnets() { obj.NatSubnets = append(obj.NatSubnets, r) } for _, r := range p.GetConsumerRejectLists() { obj.ConsumerRejectLists = append(obj.ConsumerRejectLists, r) } for _, r := range p.GetConsumerAcceptLists() { obj.ConsumerAcceptLists = append(obj.ConsumerAcceptLists, *ProtoToComputeBetaServiceAttachmentConsumerAcceptLists(r)) } return obj } // ServiceAttachmentConnectionPreferenceEnumToProto converts a ServiceAttachmentConnectionPreferenceEnum enum to its proto representation. func ComputeBetaServiceAttachmentConnectionPreferenceEnumToProto(e *beta.ServiceAttachmentConnectionPreferenceEnum) betapb.ComputeBetaServiceAttachmentConnectionPreferenceEnum { if e == nil { return betapb.ComputeBetaServiceAttachmentConnectionPreferenceEnum(0) } if v, ok := betapb.ComputeBetaServiceAttachmentConnectionPreferenceEnum_value["ServiceAttachmentConnectionPreferenceEnum"+string(*e)]; ok { return betapb.ComputeBetaServiceAttachmentConnectionPreferenceEnum(v) } return betapb.ComputeBetaServiceAttachmentConnectionPreferenceEnum(0) } // ServiceAttachmentConnectedEndpointsStatusEnumToProto converts a ServiceAttachmentConnectedEndpointsStatusEnum enum to its proto representation. func ComputeBetaServiceAttachmentConnectedEndpointsStatusEnumToProto(e *beta.ServiceAttachmentConnectedEndpointsStatusEnum) betapb.ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum { if e == nil { return betapb.ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum(0) } if v, ok := betapb.ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum_value["ServiceAttachmentConnectedEndpointsStatusEnum"+string(*e)]; ok { return betapb.ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum(v) } return betapb.ComputeBetaServiceAttachmentConnectedEndpointsStatusEnum(0) } // ServiceAttachmentConnectedEndpointsToProto converts a ServiceAttachmentConnectedEndpoints object to its proto representation. func ComputeBetaServiceAttachmentConnectedEndpointsToProto(o *beta.ServiceAttachmentConnectedEndpoints) *betapb.ComputeBetaServiceAttachmentConnectedEndpoints { if o == nil { return nil } p := &betapb.ComputeBetaServiceAttachmentConnectedEndpoints{} p.SetStatus(ComputeBetaServiceAttachmentConnectedEndpointsStatusEnumToProto(o.Status)) p.SetPscConnectionId(dcl.ValueOrEmptyInt64(o.PscConnectionId)) p.SetEndpoint(dcl.ValueOrEmptyString(o.Endpoint)) return p } // ServiceAttachmentConsumerAcceptListsToProto converts a ServiceAttachmentConsumerAcceptLists object to its proto representation. func ComputeBetaServiceAttachmentConsumerAcceptListsToProto(o *beta.ServiceAttachmentConsumerAcceptLists) *betapb.ComputeBetaServiceAttachmentConsumerAcceptLists { if o == nil { return nil } p := &betapb.ComputeBetaServiceAttachmentConsumerAcceptLists{} p.SetProjectIdOrNum(dcl.ValueOrEmptyString(o.ProjectIdOrNum)) p.SetConnectionLimit(dcl.ValueOrEmptyInt64(o.ConnectionLimit)) return p } // ServiceAttachmentPscServiceAttachmentIdToProto converts a ServiceAttachmentPscServiceAttachmentId object to its proto representation. func ComputeBetaServiceAttachmentPscServiceAttachmentIdToProto(o *beta.ServiceAttachmentPscServiceAttachmentId) *betapb.ComputeBetaServiceAttachmentPscServiceAttachmentId { if o == nil { return nil } p := &betapb.ComputeBetaServiceAttachmentPscServiceAttachmentId{} p.SetHigh(dcl.ValueOrEmptyInt64(o.High)) p.SetLow(dcl.ValueOrEmptyInt64(o.Low)) return p } // ServiceAttachmentToProto converts a ServiceAttachment resource to its proto representation. func ServiceAttachmentToProto(resource *beta.ServiceAttachment) *betapb.ComputeBetaServiceAttachment { p := &betapb.ComputeBetaServiceAttachment{} p.SetId(dcl.ValueOrEmptyInt64(resource.Id)) p.SetName(dcl.ValueOrEmptyString(resource.Name)) p.SetDescription(dcl.ValueOrEmptyString(resource.Description)) p.SetSelfLink(dcl.ValueOrEmptyString(resource.SelfLink)) p.SetRegion(dcl.ValueOrEmptyString(resource.Region)) p.SetTargetService(dcl.ValueOrEmptyString(resource.TargetService)) p.SetConnectionPreference(ComputeBetaServiceAttachmentConnectionPreferenceEnumToProto(resource.ConnectionPreference)) p.SetEnableProxyProtocol(dcl.ValueOrEmptyBool(resource.EnableProxyProtocol)) p.SetPscServiceAttachmentId(ComputeBetaServiceAttachmentPscServiceAttachmentIdToProto(resource.PscServiceAttachmentId)) p.SetFingerprint(dcl.ValueOrEmptyString(resource.Fingerprint)) p.SetProject(dcl.ValueOrEmptyString(resource.Project)) p.SetLocation(dcl.ValueOrEmptyString(resource.Location)) sConnectedEndpoints := make([]*betapb.ComputeBetaServiceAttachmentConnectedEndpoints, len(resource.ConnectedEndpoints)) for i, r := range resource.ConnectedEndpoints { sConnectedEndpoints[i] = ComputeBetaServiceAttachmentConnectedEndpointsToProto(&r) } p.SetConnectedEndpoints(sConnectedEndpoints) sNatSubnets := make([]string, len(resource.NatSubnets)) for i, r := range resource.NatSubnets { sNatSubnets[i] = r } p.SetNatSubnets(sNatSubnets) sConsumerRejectLists := make([]string, len(resource.ConsumerRejectLists)) for i, r := range resource.ConsumerRejectLists { sConsumerRejectLists[i] = r } p.SetConsumerRejectLists(sConsumerRejectLists) sConsumerAcceptLists := make([]*betapb.ComputeBetaServiceAttachmentConsumerAcceptLists, len(resource.ConsumerAcceptLists)) for i, r := range resource.ConsumerAcceptLists { sConsumerAcceptLists[i] = ComputeBetaServiceAttachmentConsumerAcceptListsToProto(&r) } p.SetConsumerAcceptLists(sConsumerAcceptLists) return p } // applyServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachment Apply() method. func (s *ServiceAttachmentServer) applyServiceAttachment(ctx context.Context, c *beta.Client, request *betapb.ApplyComputeBetaServiceAttachmentRequest) (*betapb.ComputeBetaServiceAttachment, error) { p := ProtoToServiceAttachment(request.GetResource()) res, err := c.ApplyServiceAttachment(ctx, p) if err != nil { return nil, err } r := ServiceAttachmentToProto(res) return r, nil } // applyComputeBetaServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachment Apply() method. func (s *ServiceAttachmentServer) ApplyComputeBetaServiceAttachment(ctx context.Context, request *betapb.ApplyComputeBetaServiceAttachmentRequest) (*betapb.ComputeBetaServiceAttachment, error) { cl, err := createConfigServiceAttachment(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return s.applyServiceAttachment(ctx, cl, request) } // DeleteServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachment Delete() method. func (s *ServiceAttachmentServer) DeleteComputeBetaServiceAttachment(ctx context.Context, request *betapb.DeleteComputeBetaServiceAttachmentRequest) (*emptypb.Empty, error) { cl, err := createConfigServiceAttachment(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } return &emptypb.Empty{}, cl.DeleteServiceAttachment(ctx, ProtoToServiceAttachment(request.GetResource())) } // ListComputeBetaServiceAttachment handles the gRPC request by passing it to the underlying ServiceAttachmentList() method. func (s *ServiceAttachmentServer) ListComputeBetaServiceAttachment(ctx context.Context, request *betapb.ListComputeBetaServiceAttachmentRequest) (*betapb.ListComputeBetaServiceAttachmentResponse, error) { cl, err := createConfigServiceAttachment(ctx, request.GetServiceAccountFile()) if err != nil { return nil, err } resources, err := cl.ListServiceAttachment(ctx, request.GetProject(), request.GetLocation()) if err != nil { return nil, err } var protos []*betapb.ComputeBetaServiceAttachment for _, r := range resources.Items { rp := ServiceAttachmentToProto(r) protos = append(protos, rp) } p := &betapb.ListComputeBetaServiceAttachmentResponse{} p.SetItems(protos) return p, nil } func createConfigServiceAttachment(ctx context.Context, service_account_file string) (*beta.Client, error) { conf := dcl.NewConfig(dcl.WithUserAgent("dcl-test"), dcl.WithCredentialsFile(service_account_file)) return beta.NewClient(conf), nil }
// @Description TODO // @Author jiangyang // @Created 2020/11/16 5:04 下午 package ctx_test
package sessions import ( "encoding/base64" "encoding/json" "github.com/go-http-utils/cookie" ) // Version is this package's version const Version = "1.0.0" // Store is an interface for custom session stores. type Store interface { // Load should load data from cookie and store, set it into session instance. // error indicates that session validation failed, or other thing. // Sessions.Init should be called in Load, even if error occured. Load(name string, session Sessions, cookie *cookie.Cookies) error // Save should persist session to the underlying store implementation. Save(session Sessions) error // Destroy should destroy the session. Destroy(session Sessions) error } // Sessions ... type Sessions interface { // Init sets current cookie.Cookies and Store to the session instance. Init(name, sid string, c *cookie.Cookies, store Store, lastValue string) // GetSID returns the session' sid GetSID() string // GetName returns the session' name GetName() string // GetStore returns the session' store GetStore() Store // GetCookie returns the session' cookie GetCookie() *cookie.Cookies // IsChanged to check current session's value whether is changed IsChanged(val string) bool // IsNew to check the current session whether it's new user IsNew() bool } // Meta stores the values and optional configuration for a session. type Meta struct { // Values map[string]interface{} sid string store Store name string cookie *cookie.Cookies lastValue string } // Init sets current cookie.Cookies and Store to the session instance. func (s *Meta) Init(name, sid string, c *cookie.Cookies, store Store, lastValue string) { s.name = name s.sid = sid s.cookie = c s.store = store s.lastValue = lastValue } // GetSID returns the session' sid func (s *Meta) GetSID() string { return s.sid } // GetName returns the name used to register the session func (s *Meta) GetName() string { return s.name } // GetStore returns the session store used to register the session func (s *Meta) GetStore() Store { return s.store } // GetCookie returns the session' cookie func (s *Meta) GetCookie() *cookie.Cookies { return s.cookie } // IsChanged to check current session's value whether is changed func (s *Meta) IsChanged(val string) bool { return s.lastValue != val } // IsNew to check the current session whether it's new user func (s *Meta) IsNew() bool { return s.sid == "" } // Encode the value by Serializer and Base64 func Encode(value interface{}) (str string, err error) { b, err := json.Marshal(value) if err != nil { return } str = base64.StdEncoding.EncodeToString(b) return } // Decode the value to dst . func Decode(value string, dst interface{}) (err error) { b, err := base64.StdEncoding.DecodeString(value) if err != nil { return err } err = json.Unmarshal(b, dst) return }
package main import ( "bufio" "fmt" "log" "os" "regexp" "strconv" ) func main() { input := parseLines("day10/input.txt") points := make([]Point, len(input)) for i, line := range input { points[i] = linesToPoint(line) } fmt.Printf("Day 10 Part 1: %s is the order the steps should be completed\n", partOne(points)) } var re = regexp.MustCompile(`(?m)position=<\s?(-?\d*), \s?(-?\d*)> velocity=<\s?(-?\d*), \s?(-?\d*)>`) func partOne(points []Point) string { state := State{data: points} //state.printState() dim := state.calcDimensions() step := 0 for { // state.printState() newState := state.move() newDim := state.calcDimensions() fmt.Printf("step %d, dim: %d\n", step, newDim) if newDim > dim || step == 10375 { // for some reason it print a second too late :( state.printState() break } dim = newDim state = newState step++ } return "" } func partTwo(input []string) int { return 0 } type Point struct { X int Y int dX int dY int } type State struct { data []Point } func (s State) move() (State) { newPoints := make([]Point, len(s.data)) for i, p := range s.data { newPoints[i] = Point{X: p.X + p.dX, Y: p.Y + p.dY, dX: p.dX, dY: p.dY} } return State{newPoints} } func (s State) calcBoundaries() (xMin, yMin, xMax, yMax int) { for i, point := range s.data { if i == 0 || xMin > point.X { xMin = point.X } if i == 0 || xMax < point.X { xMax = point.X } if i == 0 || yMin > point.Y { yMin = point.Y } if i == 0 || yMax < point.Y { yMax = point.Y } } return } func (s State) calcDimensions() int { xMin, _, xMax, _ := s.calcBoundaries() return xMax - xMin } func (s State) printState() { xMin, yMin, xMax, yMax := s.calcBoundaries() mapResult := make(map[string]bool) for _, point := range s.data { mapResult[fmt.Sprintf("%d,%d", point.X, point.Y)] = true } for y := yMin; y <= yMax; y++ { for x := xMin; x <= xMax; x++ { if _, exists := mapResult[fmt.Sprintf("%d,%d", x, y)]; exists { fmt.Print("#") } else { fmt.Print(".") } } fmt.Print("\n") } fmt.Print("\n") } func linesToPoint(line string) Point { matches := re.FindStringSubmatch(line) X, _ := strconv.Atoi(matches[1]) Y, _ := strconv.Atoi(matches[2]) dX, _ := strconv.Atoi(matches[3]) dY, _ := strconv.Atoi(matches[4]) return Point{X, Y, dX, dY} } /** Helper method to convert file to lines */ func parseLines(fileName string) []string { file, err := os.Open(fileName) if err != nil { log.Fatal(err) } defer file.Close() var contents []string scanner := bufio.NewScanner(file) for scanner.Scan() { contents = append(contents, scanner.Text()) } return contents }
package po import ( "context" "time" "github.com/ChowRobin/fantim/client" "github.com/jinzhu/gorm" ) type UserRelationApply struct { Id int64 `gorm:"primary_key"` FromUserId int64 `gorm:"column:from_uid"` ToUserId int64 `gorm:"column:to_uid"` // 存储uid 或 群id ApplyType int8 `gorm:"column:apply_type"` // 1->好友申请, 2->群申请 Status int8 `gorm:"column:status"` Content string `gorm:"column:content"` CreateTime *time.Time `gorm:"column:create_time"` UpdateTime *time.Time `gorm:"column:update_time"` } func (*UserRelationApply) TableName() string { return "user_relation_apply" } func (ua *UserRelationApply) Create(ctx context.Context) error { conn, err := client.DBConn(ctx) if err != nil { return err } defer conn.Close() return conn.Create(ua).Error } func (ua *UserRelationApply) Update(ctx context.Context) error { conn, err := client.DBConn(ctx) if err != nil { return err } defer conn.Close() err = conn.Model(ua).Where("id=?", ua.Id).UpdateColumn("status", ua.Status).Error if err != nil { conn.Rollback() } return err } func (ua *UserRelationApply) GetById(ctx context.Context) error { conn, err := client.DBConn(ctx) if err != nil { return err } defer conn.Close() return conn.Model(ua).Where("id=?", ua.Id).First(ua).Error } func (ua *UserRelationApply) GetByCondition(ctx context.Context) error { conn, err := client.DBConn(ctx) if err != nil { return err } defer conn.Close() return conn.Model(ua).Where("from_uid=? and to_uid=? and apply_type=? and status=?", ua.FromUserId, ua.ToUserId, ua.ApplyType, ua.Status).First(ua).Error } func ListUserRelationApplyPageByCondition(ctx context.Context, fromUid int64, toIds []int64, queryStatus []int32, applyType, page, pageSize int32) ([]*UserRelationApply, error) { conn, err := client.DBConn(ctx) if err != nil { return nil, err } defer conn.Close() if len(toIds) == 0 { conn = conn.Where("from_uid=?", fromUid) } else { conn = conn.Where("to_uid in (?)", toIds) } conn = conn.Where("apply_type=?", applyType) if len(queryStatus) > 0 { conn = conn.Where("status in (?)", queryStatus) } var result []*UserRelationApply err = conn.Model(&UserRelationApply{}).Order("create_time desc").Offset((page - 1) * pageSize).Limit(pageSize).Find(&result).Error if err == gorm.ErrRecordNotFound { return nil, nil } return result, err } func CountUserRelationApplyPageByCondition(ctx context.Context, fromUid int64, toIds []int64, queryStatus []int32, applyType int32) (int32, error) { conn, err := client.DBConn(ctx) if err != nil { return 0, err } defer conn.Close() if len(toIds) == 0 { conn = conn.Where("from_uid=?", fromUid) } else { conn = conn.Where("to_uid in (?)", toIds) } conn = conn.Where("apply_type=?", applyType) if len(queryStatus) > 0 { conn = conn.Where("status in (?)", queryStatus) } var result int32 err = conn.Model(&UserRelationApply{}).Count(&result).Error if err == gorm.ErrRecordNotFound { return 0, nil } return result, err }
package main import "fmt" //这个不涉及指针的运算,不能像c语言一样直接操作指针,也不会导致内存溢出 //其实也就是&取地址,*根据地址取值 func main(){ n := 18 fmt.Println(&n) p := &n fmt.Println(*p) }
package keycloak import ( "bytes" "strconv" "strings" "time" ) type KeycloakBoolQuoted bool func (c KeycloakBoolQuoted) MarshalJSON() ([]byte, error) { var buf bytes.Buffer buf.WriteString(strconv.Quote(strconv.FormatBool(bool(c)))) return buf.Bytes(), nil } func (c *KeycloakBoolQuoted) UnmarshalJSON(in []byte) error { value := string(in) if value == `""` { *c = false return nil } unquoted, err := strconv.Unquote(value) if err != nil { return err } var b bool b, err = strconv.ParseBool(unquoted) if err != nil { return err } res := KeycloakBoolQuoted(b) *c = res return nil } func getIdFromLocationHeader(locationHeader string) string { parts := strings.Split(locationHeader, "/") return parts[len(parts)-1] } // Converts duration string to a string representing the number of milliseconds, which is used by the Keycloak API // Ex: "1h" => "3600000" func getMillisecondsFromDurationString(s string) (string, error) { duration, err := time.ParseDuration(s) if err != nil { return "", err } return strconv.Itoa(int(duration.Seconds() * 1000)), nil } // Converts a string representing milliseconds from Keycloak API to a duration string used by the provider // Ex: "3600000" => "1h0m0s" func GetDurationStringFromMilliseconds(milliseconds string) (string, error) { ms, err := strconv.Atoi(milliseconds) if err != nil { return "", err } return (time.Duration(ms) * time.Millisecond).String(), nil } func parseBoolAndTreatEmptyStringAsFalse(b string) (bool, error) { if b == "" { return false, nil } return strconv.ParseBool(b) }
package filter type Group []Filter // GroupMap is a collection of filter "groups" // // Each key corresponds to a single group, and each group consists of every filter for the given key. // Filters ought to be applied in the order they are added, and the results of one filter are the inputs of the next. // // e.g. if there is a filter that adds the letter A to a value, and another that adds B (addA and addB, respectively) // and both filters are in the same group, then an Environment variable with the value 0 will be equal to 0AB after // having run through every filter in the given group. type GroupMap map[string]Group func (g GroupMap) AddFilter(key string, filter Filter) { _, has := g[key] if !has { g[key] = make(Group, 0) } g[key] = append(g[key], filter) }
package fare import ( "context" "fmt" "log" "github.com/go-kit/kit/endpoint" distancetypes "github.com/stamm/wheely/apis/distance/types" "github.com/stamm/wheely/apis/fare/types" ) type FareService struct { distanceCalc endpoint.Endpoint tariff types.Tariff } var ( _ IFareService = FareService{} ) func NewService(distanceCalc endpoint.Endpoint, tariff types.Tariff) FareService { return FareService{ distanceCalc: distanceCalc, tariff: tariff, } } func (svc FareService) Calculate(ctx context.Context, start, end distancetypes.Point) (types.Result, error) { result, err := svc.query(ctx, start, end) if err != nil { log.Printf("error from svc: %s", err) return types.Result{}, fmt.Errorf("Couldn't get result: %s", err.Error()) } return types.Result{Amount: result}, nil } func (svc FareService) query(ctx context.Context, start, end distancetypes.Point) (int64, error) { request := distancetypes.CalculateRequest{ StartLat: start.Lat, StartLong: start.Long, EndLat: end.Lat, EndLong: end.Long, } resp, err := svc.distanceCalc(ctx, request) if err != nil { return 0, err } response := resp.(distancetypes.CalculateResponse) result := svc.tariff.Delivery + svc.tariff.ForMinute*(response.Duration/60) + svc.tariff.ForKm*(response.Distance/1000) if result < svc.tariff.Minimum { result = svc.tariff.Minimum } return result, nil }
// Written in 2014 by Petar Maymounkov. // // It helps future understanding of past knowledge to save // this notice, so peers of other times and backgrounds can // see history clearly. package basic import ( "github.com/hoijui/escher/pkg/be" cir "github.com/hoijui/escher/pkg/circuit" ) type Repeat struct{} func (Repeat) Spark(*be.Eye, cir.Circuit, ...interface{}) cir.Value { return nil } func (Repeat) CognizeValue(eye *be.Eye, value interface{}) { for { eye.Show(cir.DefaultValve, value) } } func (Repeat) Cognize(eye *be.Eye, value interface{}) {}
package main import ( "fmt" "strings" "github.com/istarli/fileParse/parser" ) func main() { files := []string{ // "JTT1022-2016.txt", // "JTT1055-2016.txt", // "JTT1057-2016.txt", // "JTT1075-2016.txt", // "JTT7353-2009.txt", // "JTT9792-2015.txt", // "GBT 1948-2-2008.txt", // "GBT 26768-2011.txt", "GBT 29110-2012.txt", } // ps := parser.NewParser() // ps := parser.NewParserWithCheckFunc(func(str string) (bool, bool) { // if strings.Index(str, "中文名称:") == 0 { // return true, false // } // return false, false // }) ps := parser.NewParserWithCheckFunc(func(str *string) (bool, bool) { s := *str if strings.Index(s, "7.") == 0 { items := strings.SplitN(s, " ", 2) if len(items) < 2 { fmt.Println("begin parse error!") return false, false } newStr := "中文名称:" + strings.TrimSpace(items[1]) *str = newStr return true, false } return false, false }) for _, input := range files { output := strings.Split(input, ".")[0] + ".csv" err := ps.Parse(input, output) if err != nil { fmt.Printf("Parse file err, %+v \n", err) } } }
// main.go package main func main() { initialize(4, "P,1,1,p,N,1,1,n,B,1,1,b,R,1,1,r") drawBoard() }
package middleware import ( "net/http" "github.com/gin-gonic/gin" "github.com/pkg/errors" "gorm.io/gorm" ) func ErrorHandler(c *gin.Context) { c.Next() err := c.Errors.Last() if err != nil { // すでにステータスコードが指定されていれば何もしない if c.Writer.Status() != 0 { return } cause := errors.Cause(err.Err) if errors.Is(cause, gorm.ErrRecordNotFound) { c.HTML(http.StatusNotFound, "404.html.tmpl", gin.H{}) } else { c.HTML(http.StatusInternalServerError, "500.html.tmpl", gin.H{}) } } }
package chain import ( "os" "strings" "github.com/iotaledger/wasp/tools/wasp-cli/log" "github.com/spf13/pflag" ) func InitCommands(commands map[string]func([]string), flags *pflag.FlagSet) { commands["chain"] = chainCmd fs := pflag.NewFlagSet("chain", pflag.ExitOnError) initDeployFlags(fs) initUploadFlags(fs) initAliasFlags(fs) flags.AddFlagSet(fs) } var subcmds = map[string]func([]string){ "list": listCmd, "deploy": deployCmd, "info": infoCmd, "list-contracts": listContractsCmd, "deploy-contract": deployContractCmd, "list-accounts": listAccountsCmd, "balance": balanceCmd, "list-blobs": listBlobsCmd, "store-blob": storeBlobCmd, "show-blob": showBlobCmd, "log": logCmd, "post-request": postRequestCmd, "call-view": callViewCmd, "activate": activateCmd, "deactivate": deactivateCmd, } func chainCmd(args []string) { if len(args) < 1 { usage() } subcmd, ok := subcmds[args[0]] if !ok { usage() } subcmd(args[1:]) } func usage() { cmdNames := make([]string, 0) for k := range subcmds { cmdNames = append(cmdNames, k) } log.Usage("%s chain [%s]\n", os.Args[0], strings.Join(cmdNames, "|")) }
package main import ( "finrgo/exhanges" "finrgo/exhanges/poloniex" "finrgo/strategy/arb" "fmt" "runtime" "sync" ) const ( BittrexExchange string = "bittrex" PoloniexExchange string = "poloniex" ) func main() { numcpu := runtime.NumCPU() fmt.Println("NumCPU", numcpu) // runtime.GOMAXPROCS(numcpu) NewArbParallel() } func NewArbParallel() { var wg sync.WaitGroup wg.Add(3) exchanges := exhanges.InitExhanges() exchanges.AddExhange(PoloniexExchange, &poloniex.Poloniex{}) oneExchange := exchanges.GetInstanceExchange(PoloniexExchange) cyclesBTC_ETH_USD := arb.NewCycle() cyclesBTC_ETH_USD.Fee = 0.25 cyclesBTC_ETH_USD.IsTradeOn = false cyclesBTC_ETH_USD.IsDebugCalc = false cyclesBTC_ETH_USD.IsDebugResultCalc = false cyclesBTC_ETH_USD.IsVerifyAmountInExchange = false cyclesBTC_ETH_USD.IsNoLoop = false cyclesBTC_ETH_USD.Strategy.ProfitPecent = 0 //0.004 cyclesBTC_ETH_USD.Strategy.AmountInEchangeMultyply = 2 cyclesBTC_ETH_USD.Strategy.StartBTC = 0.0018 // cyclesBTC_ETH_USD.AddPair(0, "BTC_LTC", "LTCBTC", arb.BuyOrder) // cyclesBTC_ETH_USD.AddPair(1, "USDT_LTC", "LTCUSD", arb.SellOrder) // cyclesBTC_ETH_USD.AddPair(2, "USDT_BTC", "BTCUSD", arb.BuyOrder) cyclesBTC_ETH_USD.AddPair(0, "BTC_REP", "REPBTC", arb.BuyOrder) cyclesBTC_ETH_USD.AddPair(1, "USDT_REP", "REPUSD", arb.SellOrder) cyclesBTC_ETH_USD.AddPair(2, "USDT_BTC", "BTCUSD", arb.BuyOrder) go cyclesBTC_ETH_USD.CalculateTrade(oneExchange) wg.Wait() }
package main import ( "code.google.com/p/go-sqlite/go1/sqlite3" "fmt" "hash/fnv" "html/template" "io" "net/http" "net/url" "regexp" "strconv" ) type Message struct { Text string Type string } var validPath = regexp.MustCompile("^/(save|([a-zA-Z0-9]*))$") func saveUrlHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() link := r.Form.Get("url-input") connection, err := sqlite3.Open("src/tinyurl/url.db") if err != nil { renderError(w, r, "Database error!", err) return } defer connection.Close() url, err := url.Parse(link) if err != nil { renderError(w, r, "Invalid URL", err) return } //if the website uses http(s), append http if len(url.Scheme) == 0 { link = "http://" + link } //check if this link is already in the database sql := fmt.Sprintf("SELECT hash FROM url_mapping WHERE url = \"%s\"", link) hash_query, err := connection.Query(sql) //if not found... if err == io.EOF && hash_query == nil { h := hash(link) sql := fmt.Sprintf("INSERT INTO url_mapping VALUES(NULL, \"%s\", \"%s\");", h, link) err = connection.Exec(sql) if err != nil { renderError(w, r, "Failed to update database!", err) return } txt := fmt.Sprintf("%s mapped to %s", link, h) msg := &Message{Text: txt, Type: "success"} renderTemplate(w, r, msg) return } defer hash_query.Close() // already in DB, return hash that exists var return_hash string //wtf??? hash_query.Scan(&return_hash) txt := fmt.Sprintf("%s mapped to %s", link, return_hash) msg := &Message{Text: txt, Type: "success"} renderTemplate(w, r, msg) } func mainHandler(w http.ResponseWriter, r *http.Request) { link, err := getLink(w, r) if err != nil { renderError(w, r, "URL parse error!", err) return } if len(link) == 0 { renderTemplate(w, r, nil) return } connection, err := sqlite3.Open("src/tinyurl/url.db") if err != nil { renderError(w, r, "Database error!", err) return } defer connection.Close() sql := fmt.Sprintf("SELECT url FROM url_mapping WHERE hash = \"%s\"", link) url_query, err := connection.Query(sql) if err != nil { renderError(w, r, "That tinyurl link does not exist!", err) return } defer url_query.Close() var url string url_query.Scan(&url) http.Redirect(w, r, url, http.StatusMovedPermanently) } func renderError(w http.ResponseWriter, r *http.Request, text string, err error) { fmt.Printf(err.Error()) msg := &Message{Text: text, Type: "error"} renderTemplate(w, r, msg) return } func renderTemplate(w http.ResponseWriter, r *http.Request, msg *Message) { tmpl, err := template.ParseFiles("src/tinyurl/home.html") if err != nil { http.NotFound(w, r) } tmpl.Execute(w, msg) return } func getLink(w http.ResponseWriter, r *http.Request) (string, error) { m := validPath.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return "", nil } return m[1], nil } func hash(link string) string { return strconv.FormatUint(uint64(createHash(link)), 16) } func createHash(link string) uint32 { h := fnv.New32a() h.Write([]byte(link)) return h.Sum32() } func main() { http.HandleFunc("/", mainHandler) http.HandleFunc("/save", saveUrlHandler) http.ListenAndServe(":8998", nil) }
package model import ( "github.com/dgrijalva/jwt-go" "main/conf" "time" ) type JwtClaims struct { Name string `json:"name"` jwt.StandardClaims } func CreateJwtToken(name string, id string) (string, error) { jwtClaims := JwtClaims{ name, jwt.StandardClaims{ Id: id, ExpiresAt: time.Now().Add(24 * time.Hour).Unix(), }, } rawToken := jwt.NewWithClaims(jwt.SigningMethodHS512, jwtClaims) token, err := rawToken.SignedString(conf.JwtKey) if err != nil { return "", err } return token, nil }
package main // Stolen from https://github.com/sabhiram/go-wol import ( "bytes" "encoding/binary" "errors" "log" "net" "regexp" ) // Define globals for the MacAddress parsing var ( delims = ":-" reMAC = regexp.MustCompile(`^([0-9a-fA-F]{2}[` + delims + `]){5}([0-9a-fA-F]{2})$`) ) type MACAddress [6]byte // A MagicPacket is constituted of 6 bytes of 0xFF followed by // 16 groups of the destination MAC address. type MagicPacket struct { header [6]byte payload [16]MACAddress } // NewMagicPacket accepts a MAC Address string, and returns a pointer to // a MagicPacket object. A Magic Packet is a broadcast frame which // contains 6 bytes of 0xFF followed by 16 repetitions of a given mac address. func NewMagicPacket(mac string) (*MagicPacket, error) { var packet MagicPacket var macAddr MACAddress // We only support 6 byte MAC addresses since it is much harder to use // the binary.Write(...) interface when the size of the MagicPacket is // dynamic. if !reMAC.MatchString(mac) { return nil, errors.New("MAC address " + mac + " is not valid.") } hwAddr, err := net.ParseMAC(mac) if err != nil { return nil, err } // Copy bytes from the returned HardwareAddr -> a fixed size // MACAddress for idx := range macAddr { macAddr[idx] = hwAddr[idx] } // Setup the header which is 6 repetitions of 0xFF for idx := range packet.header { packet.header[idx] = 0xFF } // Setup the payload which is 16 repetitions of the MAC addr for idx := range packet.payload { packet.payload[idx] = macAddr } return &packet, nil } // GetIPFromInterface This function gets the address associated with an interface func GetIPFromInterface(iface string) (*net.UDPAddr, error) { ief, err := net.InterfaceByName(iface) if err != nil { return nil, err } addrs, err := ief.Addrs() if err != nil { return nil, err } else if len(addrs) <= 0 { return nil, errors.New("No address associated with interface " + iface) } // Validate that one of the addr's is a valid network IP address for _, addr := range addrs { switch ip := addr.(type) { case *net.IPNet: // Verify that the DefaultMask for the address we want to use exists if ip.IP.DefaultMask() != nil { return &net.UDPAddr{ IP: ip.IP, }, nil } } } return nil, errors.New("Unable to find valid IP addr for interface " + iface) } // SendMagicPacket Function to send a magic packet to a given mac address, and optionally // receives an iface to broadcast on. An iface of "" implies a nil net.UDPAddr func SendMagicPacket(macAddr, bcastAddr, iface string) error { // Construct a MagicPacket for the given MAC Address magicPacket, err := NewMagicPacket(macAddr) if err != nil { return err } // Fill our byte buffer with the bytes in our MagicPacket var buf bytes.Buffer binary.Write(&buf, binary.BigEndian, magicPacket) log.Printf("Attempting to send a magic packet to MAC %s\n", macAddr) log.Printf("... Broadcasting to: %s\n", bcastAddr) // Get a UDPAddr to send the broadcast to udpAddr, err := net.ResolveUDPAddr("udp", bcastAddr) if err != nil { log.Printf("Unable to get a UDP address for %s\n", bcastAddr) return err } // If an interface was specified, get the address associated with it var localAddr *net.UDPAddr if iface != "" { var err error localAddr, err = GetIPFromInterface(iface) if err != nil { log.Printf("ERROR: %s\n", err.Error()) return errors.New("Unable to get address for interface " + iface) } } // Open a UDP connection, and defer it's cleanup connection, err := net.DialUDP("udp", localAddr, udpAddr) if err != nil { log.Printf("ERROR: %s\n", err.Error()) return errors.New("Unable to dial UDP address.") } defer connection.Close() // Write the bytes of the MagicPacket to the connection bytesWritten, err := connection.Write(buf.Bytes()) if err != nil { log.Printf("Unable to write packet to connection\n") return err } else if bytesWritten != 102 { log.Printf("Warning: %d bytes written, %d expected!\n", bytesWritten, 102) } return nil }
package user import ( "camp/lib" "camp/week2/api" "camp/week2/model" "camp/week2/util" ) func (userService *UserService) getUserByIBase(base lib.IBase) (user *api.User, err error) { // 获取 token 中的 uid uid, err := util.TokenToUid(base) if err != nil { return nil, err } userModel := model.NewUser() user, err = userModel.Get(&api.User{Id: uid}) if err != nil { return nil, err } return } func (userService *UserService) GetSubUsers(base lib.IBase) (users []*api.User, err error) { user, err := userService.getUserByIBase(base) if err != nil { return nil, err } if len(user.SubUsers) == 0 { return make([]*api.User, 0), nil } userModel := model.NewUser() users, err = userModel.GetUsersByIds(user.SubUsers) for _, u := range users{ u.Password = "" } return } func (userService *UserService) GetFansUsers(base lib.IBase) (users []*api.User, err error) { user, err := userService.getUserByIBase(base) if err != nil { return nil, err } if len(user.FansUsers) == 0 { return make([]*api.User, 0), nil } userModel := model.NewUser() users, err = userModel.GetUsersByIds(user.FansUsers) for _, u := range users{ u.Password = "" } return }
package httpmanager import ( "encoding/json" "net/http" ) // GetHandler returns a function metadata func (m* Manager) GetHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() funcName := r.FormValue("funcName") res, err := m.platformManager.GetFunction(funcName) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } jsonRet, err := json.Marshal(res) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Add("Content-Type", "application/json;charset=utf-8") w.Write(jsonRet) return }
package Problem0420 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { s string ans int }{ {"", 6}, {"aB3aB3", 0}, {"aaaaaaaaaaaaaaaaaaaaa", 7}, {"aaaaaaaaaaaaaaaaaaaaaa", 8}, {"aaaAaaaAaaaAaaaAaaaAa", 5}, {"aadssfasfASDaaaaaaaaaaASDfA235234ADFadfASDFa234324", 30}, // 可以有多个 testcase } func Test_strongPasswordChecker(t *testing.T) { ast := assert.New(t) for _, tc := range tcs { fmt.Printf("~~%v~~\n", tc) ast.Equal(tc.ans, strongPasswordChecker(tc.s), "输入:%v", tc) } } func Benchmark_strongPasswordChecker(b *testing.B) { for i := 0; i < b.N; i++ { for _, tc := range tcs { strongPasswordChecker(tc.s) } } }
package main import ( "os" "github.com/therecipe/qt/widgets" ) func main() { os.Setenv("QT_IM_MODULE", "qtvirtualkeyboard") widgets.NewQApplication(0, nil) window := widgets.NewQMainWindow(nil, 0) window.SetMinimumSize2(250, 200) widget := widgets.NewQWidget(nil, 0) widget.SetLayout(widgets.NewQVBoxLayout()) window.SetCentralWidget(widget) input := widgets.NewQLineEdit(nil) input.SetPlaceholderText("Write something ...") widget.Layout().AddWidget(input) window.Show() widgets.QApplication_Exec() }
package scale import ( "strings" ) var ( scaleWithSharps = []string{"A", "A#", "B", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#"} scaleWithFlats = []string{"A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"} ) // Scale returns a scale that starts at tonic and follows the interval pattern. // Supported intervals are 'm': half step, 'M': whole step, 'A': augmented first. // If no interval pattern is given the default is 12 half steps. func Scale(tonic, interval string) []string { t := Tonic(tonic) if interval == "" { interval = "mmmmmmmmmmmm" } s := make([]string, len(interval)) c := t.ChromaticScale() var j int for i, step := range interval { s[i] = c[j] switch step { case 'm': j++ case 'M': j += 2 case 'A': j += 3 } } return s } // Tonic represents the starting note of a scale. type Tonic string // Pitch returns the tonic as a pitch. func (t Tonic) Pitch() string { return strings.ToUpper(string(t[:1])) + string(t[1:]) } // ChromaticScale returns the chromatic scale starting at tonic. func (t Tonic) ChromaticScale() []string { s := scaleWithSharps switch t { case "F", "Bb", "Eb", "Db", "d", "g", "bb": s = scaleWithFlats } var start int for i, p := range s { if t.Pitch() == p { start = i } } return append(s[start:], s[:start]...) }
package info import ( "context" "github.com/coredns/coredns/plugin" "github.com/miekg/dns" clog "github.com/coredns/coredns/plugin/pkg/log" ) var log = clog.NewWithPlugin("info") type info struct { Next plugin.Handler } func (i *info) Name() string { return "info" } func (i *info) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { clog.Infof(r.String()) return plugin.NextOrFailure(i.Name(), i.Next, ctx, w, r) }
package main import ( "fmt" ) var _ Match = (*AndMatch)(nil) type AndMatch struct { SubMatch []Match } func (am *AndMatch) AssembleMatch(counter *IDCounter, ruleEndLabel, actionLabel string) ([]string, error) { andAsm := []string{ "# And", } for i, match := range am.SubMatch { matchAsm, err := match.AssembleMatch(counter, ruleEndLabel, actionLabel) if err != nil { return nil, fmt.Errorf("sub-match %d: %w", i, err) } andAsm = append(andAsm, matchAsm...) } andAsm = append(andAsm, "# End and") return andAsm, nil } func (am *AndMatch) Invert() Match { // De Morgan 2: ¬(P ∧ Q) ⇔ (¬P ∨ ¬Q) or := &OrMatch{ SubMatch: make([]Match, len(am.SubMatch)), } for i, match := range am.SubMatch { or.SubMatch[i] = match.Invert() } return or }
/* ** description(""). ** copyright('open-im,www.open-im.io'). ** author("fg,Gordon@open-im.io"). ** time(2021/3/5 14:31). */ package logic import ( push "Open_IM/internal/push/jpush" rpcChat "Open_IM/internal/rpc/chat" "Open_IM/pkg/common/config" "Open_IM/pkg/common/constant" "Open_IM/pkg/common/log" "Open_IM/pkg/grpc-etcdv3/getcdv3" pbChat "Open_IM/pkg/proto/chat" pbGroup "Open_IM/pkg/proto/group" pbRelay "Open_IM/pkg/proto/relay" "Open_IM/pkg/utils" "context" "encoding/json" "strings" ) type OpenIMContent struct { SessionType int `json:"sessionType"` From string `json:"from"` To string `json:"to"` Seq int64 `json:"seq"` } type AtContent struct { Text string `json:"text"` AtUserList []string `json:"atUserList"` IsAtSelf bool `json:"isAtSelf"` } func MsgToUser(sendPbData *pbRelay.MsgToUserReq, OfflineInfo, Options string) { var wsResult []*pbRelay.SingleMsgToUser MOptions := utils.JsonStringToMap(Options) //Control whether to push message to sender's other terminal //isSenderSync := utils.GetSwitchFromOptions(MOptions, "senderSync") isOfflinePush := utils.GetSwitchFromOptions(MOptions, "offlinePush") log.InfoByKv("Get chat from msg_transfer And push chat", sendPbData.OperationID, "PushData", sendPbData) grpcCons := getcdv3.GetConn4Unique(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOnlineMessageRelayName) //Online push message log.InfoByKv("test", sendPbData.OperationID, "len grpc", len(grpcCons), "data", sendPbData) for _, v := range grpcCons { msgClient := pbRelay.NewOnlineMessageRelayServiceClient(v) reply, err := msgClient.MsgToUser(context.Background(), sendPbData) if err != nil { log.InfoByKv("push data to client rpc err", sendPbData.OperationID, "err", err) } if reply != nil && reply.Resp != nil && err == nil { wsResult = append(wsResult, reply.Resp...) } } log.InfoByKv("push_result", sendPbData.OperationID, "result", wsResult, "sendData", sendPbData) if sendPbData.ContentType != constant.Typing && sendPbData.ContentType != constant.HasReadReceipt { if isOfflinePush { for _, v := range wsResult { if v.ResultCode == 0 { continue } //supported terminal for _, t := range pushTerminal { if v.RecvPlatFormID == t { //Use offline push messaging var UIDList []string UIDList = append(UIDList, v.RecvID) customContent := OpenIMContent{ SessionType: int(sendPbData.SessionType), From: sendPbData.SendID, To: sendPbData.RecvID, Seq: sendPbData.RecvSeq, } bCustomContent, _ := json.Marshal(customContent) jsonCustomContent := string(bCustomContent) var content string switch sendPbData.ContentType { case constant.Text: content = constant.ContentType2PushContent[constant.Text] case constant.Picture: content = constant.ContentType2PushContent[constant.Picture] case constant.Voice: content = constant.ContentType2PushContent[constant.Voice] case constant.Video: content = constant.ContentType2PushContent[constant.Video] case constant.File: content = constant.ContentType2PushContent[constant.File] case constant.AtText: a := AtContent{} _ = utils.JsonStringToStruct(sendPbData.Content, &a) if utils.IsContain(v.RecvID, a.AtUserList) { content = constant.ContentType2PushContent[constant.AtText] + constant.ContentType2PushContent[constant.Common] } else { content = constant.ContentType2PushContent[constant.GroupMsg] } default: } pushResult, err := push.JGAccountListPush(UIDList, content, jsonCustomContent, utils.PlatformIDToName(t)) if err != nil { log.NewError(sendPbData.OperationID, "offline push error", sendPbData.String(), err.Error(), t) } else { log.NewDebug(sendPbData.OperationID, "offline push return result is ", string(pushResult), sendPbData, t) } } } } } } } func SendMsgByWS(m *pbChat.WSToMsgSvrChatMsg) { m.MsgID = rpcChat.GetMsgID(m.SendID) m.ClientMsgID = m.MsgID switch m.SessionType { case constant.SingleChatType: sendMsgToKafka(m, m.SendID, "msgKey--sendID") sendMsgToKafka(m, m.RecvID, "msgKey--recvID") case constant.GroupChatType: etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName) client := pbGroup.NewGroupClient(etcdConn) req := &pbGroup.GetGroupAllMemberReq{ GroupID: m.RecvID, Token: config.Config.Secret, OperationID: m.OperationID, } reply, err := client.GetGroupAllMember(context.Background(), req) if err != nil { log.Error(m.Token, m.OperationID, "rpc getGroupInfo failed, err = %s", err.Error()) return } if reply.ErrorCode != 0 { log.Error(m.Token, m.OperationID, "rpc getGroupInfo failed, err = %s", reply.ErrorMsg) return } groupID := m.RecvID for i, v := range reply.MemberList { m.RecvID = v.UserId + " " + groupID sendMsgToKafka(m, utils.IntToString(i), "msgKey--recvID+\" \"+groupID") } default: } } func sendMsgToKafka(m *pbChat.WSToMsgSvrChatMsg, key string, flag string) { pid, offset, err := producer.SendMessage(m, key) if err != nil { log.ErrorByKv("kafka send failed", m.OperationID, "send data", m.String(), "pid", pid, "offset", offset, "err", err.Error(), flag, key) } }
package gojson import ( "fmt" "testing" ) var js *GoJSON var data = []byte(`{ "person": { "id": "d50887ca-a6ce-4e59-b89f-14f0b5d03b03", "name": { "fullName": "Leonid Bugaev", "givenName": "Leonid", "familyName": "Bugaev" }, "email": "leonsbox@gmail.com", "gender": "male", "location": "Saint Petersburg, Saint Petersburg, RU", "geo": { "city": "Saint Petersburg", "state": "Saint Petersburg", "country": "Russia", "lat": 59.9342802, "lng": 30.3350986 }, "bio": "Senior engineer at Granify.com", "site": "http://flickfaver.com", "avatar": "https://d1ts43dypk8bqh.cloudfront.net/v1/avatars/d50887ca-a6ce-4e59-b89f-14f0b5d03b03", "employment": { "name": "www.latera.ru", "title": "Software Engineer", "domain": "gmail.com" }, "facebook": { "handle": "leonid.bugaev" }, "github": { "handle": "buger", "id": 14009, "avatar": "https://avatars.githubusercontent.com/u/14009?v=3", "company": "Granify", "blog": "http://leonsbox.com", "followers": 95, "following": 10 }, "twitter": { "handle": "flickfaver", "id": 77004410, "bio": null, "followers": 2, "following": 1, "statuses": 5, "favorites": 0, "location": "", "site": "http://flickfaver.com", "avatar": null }, "linkedin": { "handle": "in/leonidbugaev" }, "googleplus": { "handle": null }, "angellist": { "handle": "leonid-bugaev", "id": 61541, "bio": "Senior engineer at Granify.com", "blog": "http://buger.github.com", "site": "http://buger.github.com", "followers": 41, "avatar": "https://d1qb2nb5cznatu.cloudfront.net/users/61541-medium_jpg?1405474390" }, "klout": { "handle": null, "score": null }, "foursquare": { "handle": null }, "aboutme": { "handle": "leonid.bugaev", "bio": null, "avatar": null }, "gravatar": { "handle": "buger", "urls": [ ], "avatar": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510", "avatars": [ { "url": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510", "type": "thumbnail" } ] }, "fuzzy": false }, "company": null }`) var data2 = []byte(`{ "company": { "name": "Simpals" } }`) func TestMarshal(t *testing.T) { js = Unmarshal(data) fmt.Println(string(js.Marshal())) } func TestGoJSON_SetBytes(t *testing.T) { err := js.SetBytes("testJson", []byte(`{"hello": "world"}`), JSONObject) err = js.SetBytes("test_arr", []byte(`[12, 11, 10]`), JSONArray) if err != "" { panic(err) } } func TestGoJSON_Update(t *testing.T) { js2 := Unmarshal(data2) err := js.Update(js2) if err != "" { panic(err) } val, er := js.Get("company").Get("name").ValueString() if er != nil { panic(er) } if val != "Simpals" { panic("Wrong") } } func TestGoJSON_Delete(t *testing.T) { err := js.Delete("test_arr") if err != ""{ panic(err) } if js.Get("test_arr").Type != JSONInvalid { panic("not deleted") } } func TestGoJSON_ToMap(t *testing.T) { m := js.ToMap() fmt.Println(m) } func BenchmarkMarshal(b *testing.B) { for i := 0; i < b.N; i++ { Unmarshal(data) } } func BenchmarkGoJSON_Unmarshal(b *testing.B) { for i := 0; i < b.N; i++ { js.Marshal() } }
package hashtable //hashtable的go语言实现,使用数组加链表的方法,实现了增加,删除,查询等功能 import ( "container/list" ) //键值对的结构体 type Node struct { key int value int } //哈希表的结构体 type HashTable struct { size int array []*list.List } //产生一个新的哈希表,size参数用于设置哈希表里面链表数组的大小 func CreateHashTable(size int) HashTable { hashtable := HashTable{} hashtable.size = size hashtable.array=make([]*list.List,size) for i := 0 ; i <= size ; i++{ hashtable.array[i] = list.New() } return hashtable } //插入一个键值对 func (hashtable HashTable) Insert(newNode *Node) { temp := newNode.key%hashtable.size hashtable.array[temp].PushBack(newNode) } //删除一个键值对 func (hashtable HashTable) Remove(oldNode *Node) { temp := oldNode.key%hashtable.size current := hashtable.array[temp].Front() for current != nil { if(current.Value.(*Node) == oldNode) { hashtable.array[temp].Remove(current) } current = current.Next() } } //根据key值,查询value值 func (hashtable HashTable) GetValue(key int) *Node { temp := key%hashtable.size current := hashtable.array[temp].Front() for current != nil { node := current.Value.(*Node) if(node.key == key){ return node } current = current.Next() } return nil }
package jsonstore import ( "context" "encoding/json" "os" "sync" "sync/atomic" "time" ) type Value interface { Clone() Value } type Store interface { Load() (x Value) Store(x Value) Save() error Close() Context() context.Context } type jsonStore struct { mu *sync.Mutex ctx context.Context store *atomic.Value fn string saveOnStore bool } func (js *jsonStore) open(data Value) error { f, err := os.Open(js.fn) if err != nil { if os.IsNotExist(err) { js.store.Store(data) return nil } return err } defer f.Close() dec := json.NewDecoder(f) err = dec.Decode(data) if err != nil { return err } js.store.Store(data) return nil } func (js *jsonStore) Load() (x Value) { return js.store.Load().(Value) } func (js *jsonStore) Store(x Value) { js.mu.Lock() defer js.mu.Unlock() // copy on write js.store.Store(x.Clone()) if js.saveOnStore { js.Save() } } func (js *jsonStore) Save() error { f, err := os.Create(js.fn) if err != nil { return err } defer f.Close() enc := json.NewEncoder(f) enc.SetIndent("", " ") return enc.Encode(js.Load()) } func (js *jsonStore) Close() { // nothing } func (js *jsonStore) Context() context.Context { return js.ctx } type SyncStore struct { ctx context.Context cancel context.CancelFunc wg *sync.WaitGroup once *sync.Once store Store } func NewSyncStore(store Store) *SyncStore { ictx, cancel := context.WithCancel(store.Context()) return &SyncStore{ ctx: ictx, cancel: cancel, wg: &sync.WaitGroup{}, once: &sync.Once{}, store: store, } } // data must contain initial value for store it in json file (if not exists) func NewJsonSyncStore(ctx context.Context, fn string, data Value, tickSave *time.Ticker, saveOnStore bool) (*SyncStore, error) { js := &jsonStore{ mu: &sync.Mutex{}, ctx: ctx, store: &atomic.Value{}, fn: fn, saveOnStore: saveOnStore, } err := js.open(data) if err != nil { return nil, err } sc := NewSyncStore(js) if tickSave != nil { sc.Go(func(dn <-chan struct{}, st Store) { for { select { case <-dn: return case <-tickSave.C: st.Save() } } }) } return sc, nil } func (sc *SyncStore) Close() { sc.once.Do(func() { sc.cancel() sc.wg.Wait() sc.store.Save() sc.store.Close() }) } func (sc *SyncStore) Context() context.Context { return sc.ctx } func (sc *SyncStore) Done() <-chan struct{} { return sc.ctx.Done() } func (sc *SyncStore) Store() Store { return sc.store } func (sc *SyncStore) Go(f func(done <-chan struct{}, store Store)) { sc.wg.Add(1) go func(ctx context.Context, wg *sync.WaitGroup, store Store) { defer wg.Done() f(ctx.Done(), store) }(sc.ctx, sc.wg, sc.store) }
package main import ( "fmt" "strconv" ) var text = "pesan rahasia ..." func kali(angka1 int, angka2 int) int { return angka1 * angka2 } func infoMultiReturn(umur int, nama string, status string) (string, string) { umurSekarang := strconv.Itoa(umur) return "nama : " + nama + " umur :" , umurSekarang + " hubungan : " + status } func infoSingleReturn(umur int, nama string, status string) string { umurSekarang := strconv.Itoa(umur) return "nama : " + nama + " umur :" + umurSekarang + " hubungan : " + status } // memberi nama nilai yang di return func infoReturn(umur int, nama string, status string) (bio string, hubungan string) { hubungan = status bio = "nama : " + nama return } //fungsi tanpa return func noReturn() { fmt.Println(text) } func main() { // infoNama, infoPersonal := infoReturn(12, "depa", "menikah") // fmt.Println("hasil perkalian", kali(2, 2)) // fmt.Println("halo perkenalkan", infoSingleReturn(12, "depa", "menikah")) // fmt.Println("halo perkenalkan", infoNama, infoPersonal) // fmt.Println("halo perkenalkan", infoNama, infoPersonal) // fmt.Println("halo perkenalkan", infoNama, infoPersonal) noReturn() }
package handler import "github.com/gin-gonic/gin" type Data gin.H
package wallet_interface import "strings" // CoinType represents a cryptocurrency that has been // implemented the wallet interface. type CoinType string // CurrencyCode returns the coins currency code. func (ct CoinType) CurrencyCode() string { return strings.ToUpper(string(ct)) } const ( // Mainnet CtMock = "MCK" CtBitcoin = "BTC" CtBitcoinCash = "BCH" CtLitecoin = "LTC" CtZCash = "ZEC" CtEthereum = "ETH" CtMonero = "XMR" CtDash = "DASH" ) var codeMap = map[string]CoinType{ "MCK": CtMock, "BTC": CtBitcoin, "BCH": CtBitcoinCash, "LTC": CtLitecoin, "ZEC": CtZCash, "ETH": CtEthereum, "XMR": CtMonero, "DASH": CtDash, }
package user_test import ( "auth/user" "github.com/stretchr/testify/assert" "testing" ) func TestValidateUser(t *testing.T){ service := user.NewService() t.Run("invalid user", func(t *testing.T) { err := service.ValidateUser("eminetto@gmail.com", "invalid") assert.NotNil(t, err) assert.Equal(t, "Invalid user", err.Error()) }) t.Run("valid user", func(t *testing.T) { err := service.ValidateUser("eminetto@gmail.com", "1234567") assert.Nil(t, err) }) }
package config import ( "testing" "github.com/stretchr/testify/assert" ) func TestErrorShouldReturnColorizedTextWhenColorEnabled(t *testing.T) { EnableColor(true) assert.Equal(t, "\x1b[31mhello\x1b[0m", Error("hello")) } func TestErrorShouldReturnNonColorizedTextWhenColorDisabled(t *testing.T) { EnableColor(false) assert.Equal(t, "hello", Error("hello")) } func TestWarningShouldReturnColorizedTextWhenColorEnabled(t *testing.T) { EnableColor(true) assert.Equal(t, "\x1b[33mhello\x1b[0m", Warning("hello")) } func TestWarningShouldReturnNonColorizedTextWhenColorDisabled(t *testing.T) { EnableColor(false) assert.Equal(t, "hello", Warning("hello")) } func TestInfoShouldReturnColorizedTextWhenColorEnabled(t *testing.T) { EnableColor(true) assert.Equal(t, "\x1b[32mhello\x1b[0m", Info("hello")) } func TestInfoShouldReturnNonColorizedTextWhenColorDisabled(t *testing.T) { EnableColor(false) assert.Equal(t, "hello", Info("hello")) } func TestHeaderShouldReturnColorizedTextWhenColorEnabled(t *testing.T) { EnableColor(true) assert.Equal(t, "\x1b[34mhello\x1b[0m", Header("hello")) } func TestHeaderShouldReturnNonColorizedTextWhenColorDisabled(t *testing.T) { EnableColor(false) assert.Equal(t, "hello", Header("hello")) } func TestDefaultShouldReturnNonColorizedTextWhenColorEnabled(t *testing.T) { EnableColor(true) assert.Equal(t, "hello", Default("hello")) } func TestDefaultShouldReturnNonColorizedTextWhenColorDisabled(t *testing.T) { EnableColor(false) assert.Equal(t, "hello", Default("hello")) } func TestTextShouldReturnColorizedTextWhenColorEnabled(t *testing.T) { EnableColor(true) assert.Equal(t, "\x1b[35mhello\x1b[0m", Text("hello")) } func TestTextShouldReturnNonColorizedTextWhenColorDisabled(t *testing.T) { EnableColor(false) assert.Equal(t, "hello", Text("hello")) }
// Copyright (c) 2019 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package exec import ( "os" "strings" "testing" ) func TestExampleScripts(t *testing.T) { tests := []struct { name string scriptPath string args ArgMap }{ { name: "api objects", scriptPath: "../examples/kind-api-objects.crsh", args: ArgMap{"kubecfg": support.KindKubeConfigFile()}, }, { name: "pod logs", scriptPath: "../examples/pod-logs.crsh", args: ArgMap{"kubecfg": support.KindKubeConfigFile()}, }, { name: "script with args", scriptPath: "../examples/script-args.crsh", args: ArgMap{ "workdir": "/tmp/crashargs", "kubecfg": support.KindKubeConfigFile(), "output": "/tmp/craslogs.tar.gz", }, }, { name: "host-list provider", scriptPath: "../examples/host-list-provider.crsh", args: ArgMap{ "kubecfg": support.KindKubeConfigFile(), "ssh_pk_path": support.PrivateKeyPath(), "ssh_port": support.PortValue(), }, }, { name: "kind-capi-bootstrap", scriptPath: "../examples/kind-capi-bootstrap.crsh", args: ArgMap{"cluster_name": support.ResourceName()}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { file, err := os.Open(test.scriptPath) if err != nil { t.Fatal(err) } defer file.Close() if err := ExecuteFile(file, test.args); err != nil { t.Fatal(err) } }) } } func TestExecute(t *testing.T) { tests := []struct { name string script string exec func(t *testing.T, script string) }{ { name: "execute single script", script: `result = run_local("echo 'Hello World!'")`, exec: func(t *testing.T, script string) { if err := Execute("run_local", strings.NewReader(script), ArgMap{}); err != nil { t.Fatal(err) } }, }, { name: "execute with modules", script: `result = multiply(2, 3)`, exec: func(t *testing.T, script string) { mod := ` def multiply(x, y): log (msg="{} * {} = {}".format(x,y,x*y)) ` if err := ExecuteWithModules( "multiply", strings.NewReader(script), ArgMap{}, StarlarkModule{Name: "lib", Source: strings.NewReader(mod)}); err != nil { t.Fatal(err) } }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { test.exec(t, test.script) }) } }
package handler import ( "context" "encoding/json" "errors" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/gorilla/mux" "github.com/stretchr/testify/require" "2019_2_IBAT/pkg/app/auth" "2019_2_IBAT/pkg/app/auth/session" mock_auth "2019_2_IBAT/pkg/app/server/handler/mock_auth" mock_users "2019_2_IBAT/pkg/app/server/handler/mock_users" . "2019_2_IBAT/pkg/pkg/models" ) func TestHandler_CreateSession(t *testing.T) { mockCtrl1 := gomock.NewController(t) defer mockCtrl1.Finish() mockUserService := mock_users.NewMockService(mockCtrl1) mockCtrl2 := gomock.NewController(t) defer mockCtrl2.Finish() mockAuthService := mock_auth.NewMockServiceClient(mockCtrl2) h := Handler{ UserService: mockUserService, AuthService: mockAuthService, } tests := []struct { name string // authInput UserAuthInput // wantID uuid.UUID authInput UserAuthInput invJSON string wantFail bool wantRole string wantStatusCode int wantErrorMessage string wantInvJSON bool wantCreateSession bool ctx context.Context sessionMsg session.Session }{ { name: "Test1", authInput: UserAuthInput{ Email: "petushki@mail.com", Password: "1234", }, // wantID: uuid.New(), wantRole: EmployerStr, wantFail: false, ctx: context.Background(), sessionMsg: session.Session{ Id: uuid.New().String(), Class: EmployerStr, }, }, { name: "Test2", authInput: UserAuthInput{ Email: "some_another@mail.com", Password: "12345", }, wantFail: false, wantRole: SeekerStr, ctx: context.Background(), sessionMsg: session.Session{ Id: uuid.New().String(), Class: SeekerStr, }, }, { name: "Test3", authInput: UserAuthInput{ Email: "some_another@mail.com", Password: "1234567", }, wantFail: true, wantStatusCode: http.StatusBadRequest, wantErrorMessage: InvPassOrEmailMsg, }, { name: "Test4", authInput: UserAuthInput{ Email: "some_another@mail.com", Password: "1234567", }, wantFail: true, wantRole: SeekerStr, wantStatusCode: http.StatusInternalServerError, wantErrorMessage: InternalErrorMsg, wantCreateSession: true, ctx: context.Background(), sessionMsg: session.Session{ Id: uuid.New().String(), Class: SeekerStr, }, }, { name: "Test5", authInput: UserAuthInput{}, wantFail: true, wantStatusCode: http.StatusBadRequest, wantErrorMessage: InvalidJSONMsg, wantInvJSON: true, invJSON: "{'lagin': sdfdfsdf pasword: sdfsdf }", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { var str string if !tc.wantInvJSON { wantJSON, _ := json.Marshal(tc.authInput) str = string(wantJSON) } else { str = tc.invJSON } reader := strings.NewReader(str) req, err := http.NewRequest("POST", "/auth", reader) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") if !tc.wantFail { mockUserService. EXPECT(). CheckUser(tc.authInput.Email, tc.authInput.Password). Return(uuid.MustParse(tc.sessionMsg.Id), tc.sessionMsg.Class, true) mockAuthService. EXPECT(). CreateSession(tc.ctx, &tc.sessionMsg). Return( &session.CreateSessionInfo{ ID: tc.sessionMsg.Id, Role: tc.sessionMsg.Class, Expires: time.Now().In(Loc).Add(24 * time.Hour).Format(TimeFormat), Cookie: "cookie", }, nil) } else if tc.wantCreateSession { mockUserService. EXPECT(). CheckUser(tc.authInput.Email, tc.authInput.Password). Return(uuid.MustParse(tc.sessionMsg.Id), tc.sessionMsg.Class, true) mockAuthService. EXPECT(). CreateSession(tc.ctx, &tc.sessionMsg). Return( &session.CreateSessionInfo{}, errors.New("Create session error")) } else if !tc.wantInvJSON { mockUserService. EXPECT(). CheckUser(tc.authInput.Email, tc.authInput.Password). Return(uuid.UUID{}, "", false) } rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/auth", h.CreateSession) router.ServeHTTP(rr, req) if !tc.wantFail { bytes, _ := ioutil.ReadAll(rr.Body) var gotRole Role json.Unmarshal(bytes, &gotRole) require.Equal(t, tc.wantRole, gotRole.Role, "The two values should be the same.") if rr.Code != http.StatusOK { t.Error("status is not ok") } } else { bytes, _ := ioutil.ReadAll(rr.Body) var gotError Error json.Unmarshal(bytes, &gotError) require.Equal(t, tc.wantStatusCode, rr.Code, "The two values should be the same.") require.Equal(t, tc.wantErrorMessage, gotError.Message, "The two values should be the same.") } }) } } func TestHandler_GetSession(t *testing.T) { mockCtrl1 := gomock.NewController(t) defer mockCtrl1.Finish() mockUserService := mock_users.NewMockService(mockCtrl1) mockCtrl2 := gomock.NewController(t) defer mockCtrl2.Finish() mockAuthService := mock_auth.NewMockServiceClient(mockCtrl2) h := Handler{ UserService: mockUserService, AuthService: mockAuthService, } tests := []struct { name string record AuthStorageValue wantFail bool wantUnauth bool wantStatusCode int wantErrorMessage string }{ { name: "Test1", wantFail: true, wantUnauth: true, wantStatusCode: http.StatusUnauthorized, wantErrorMessage: UnauthorizedMsg, }, { name: "Test2", record: AuthStorageValue{ Role: SeekerStr, ID: uuid.New(), Expires: time.Now().In(Loc).Add(24 * time.Hour).Format(TimeFormat), }, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { reader := strings.NewReader("") ///why req, err := http.NewRequest("GET", "/auth", reader) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() ctx := context.TODO() if !tc.wantUnauth { ctx = NewContext(req.Context(), tc.record) } router := mux.NewRouter() router.HandleFunc("/auth", h.GetSession) router.ServeHTTP(rr, req.WithContext(ctx)) if !tc.wantFail { bytes, _ := ioutil.ReadAll(rr.Body) var gotRole Role json.Unmarshal(bytes, &gotRole) if rr.Code != http.StatusOK { t.Error("status is not ok") } if tc.record.Role != gotRole.Role { require.Equal(t, tc.record.Role, gotRole.Role, "The two values should be the same.") } } else { bytes, _ := ioutil.ReadAll(rr.Body) var gotError Error json.Unmarshal(bytes, &gotError) require.Equal(t, tc.wantStatusCode, rr.Code, "The two values should be the same.") require.Equal(t, tc.wantErrorMessage, gotError.Message, "The two values should be the same.") } }) } } func TestHandler_DeleteSession(t *testing.T) { mockCtrl2 := gomock.NewController(t) defer mockCtrl2.Finish() mockAuthService := mock_auth.NewMockServiceClient(mockCtrl2) h := Handler{ AuthService: mockAuthService, } tests := []struct { name string record AuthStorageValue wantFail bool wantUnauth bool wantFailDelete bool wantStatusCode int wantErrorMessage string ctx context.Context cookie session.Cookie }{ { name: "Test1", wantFail: false, wantUnauth: false, record: AuthStorageValue{ ID: uuid.New(), Role: SeekerStr, }, ctx: context.Background(), cookie: session.Cookie{ Cookie: "cookie", }, }, { name: "Test2", wantFail: true, wantUnauth: true, wantStatusCode: http.StatusUnauthorized, wantErrorMessage: UnauthorizedMsg, ctx: context.Background(), cookie: session.Cookie{ Cookie: "aaabbbaaaaa", }, }, { name: "Test3", wantFail: true, wantUnauth: false, wantFailDelete: true, record: AuthStorageValue{ ID: uuid.New(), Role: SeekerStr, }, wantStatusCode: http.StatusBadRequest, wantErrorMessage: BadRequestMsg, ctx: context.Background(), cookie: session.Cookie{ Cookie: "cookie", }, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { req, err := http.NewRequest("DELETE", "/auth", nil) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") if !tc.wantFail { mockAuthService. EXPECT(). DeleteSession(tc.ctx, &tc.cookie). Return(&session.Bool{Ok: true}, nil) } else if tc.wantFailDelete { mockAuthService. EXPECT(). DeleteSession(tc.ctx, &tc.cookie). Return(&session.Bool{Ok: false}, nil) } if !tc.wantUnauth { cookie := http.Cookie{ Name: auth.CookieName, Value: tc.cookie.Cookie, } req.AddCookie(&cookie) } rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/auth", h.DeleteSession) router.ServeHTTP(rr, req) if !tc.wantFail { if rr.Code != http.StatusOK { t.Error("status is not ok") } } else { bytes, _ := ioutil.ReadAll(rr.Body) var gotError Error json.Unmarshal(bytes, &gotError) require.Equal(t, tc.wantStatusCode, rr.Code, "The two values should be the same.") require.Equal(t, tc.wantErrorMessage, gotError.Message, "The two values should be the same.") } }) } }
package log import ( "dev-framework-go/conf" "fmt" "github.com/gin-gonic/gin" "strings" ) //日志中间件 func DiyLogger() gin.HandlerFunc { // 请求日志 return gin.LoggerWithFormatter(func(p gin.LogFormatterParams) string { if strings.HasPrefix(p.Path, "/swagger/") == true { return "" } return fmt.Sprintf("[%s] %d %s %s (%s) [%v] %s\n", p.TimeStamp.Format(conf.TIME_FORMAT), p.StatusCode, p.Request.Method, p.Path, p.ClientIP, p.Request.PostForm.Encode(), //参数 p.Latency, //执行时间 ) }) }
package owm import ( "encoding/json" "fmt" "math" "net/http" "net/url" "path" "strconv" "strings" "time" "github.com/tada3/triton/weather/model" ) const ( CurrentWeatherPath string = "weather" WeatherForecastPath string = "forecast" tempStrFormatP string = "%d度" tempStrFormatN string = "氷点下%d度" ) // OwmClient is a Client for OpenWeatherMap API type OwmClient struct { baseURL *url.URL apiKey string httpClient *http.Client } type OwmCurrentWeather struct { // Usually integer but string in case of 404 Cod json.Number Message string Name string Weather []OwmWeather Main OwmMain } type OwmWeatherForecast struct { Cod json.Number Message json.Number List []OwmForecast City OwmCity } type OwmWeather struct { Id int64 Main string Description string Icon string } type OwmMain struct { Temp float64 Pressure float64 Humidity int64 Temp_min float64 Temp_max float64 } type OwmForecast struct { Dt int64 Main OwmMain Weather []OwmWeather } type OwmCity struct { Id int64 Name string Country string Coord OwmCoord } type OwmCoord struct { Lat float64 Lon float64 } func NewOwmClient(baseURL, apiKey string, timeout int) (*OwmClient, error) { u, err := url.Parse(baseURL) if err != nil { return nil, err } c := &http.Client{Timeout: time.Duration(timeout) * time.Second} return &OwmClient{ baseURL: u, apiKey: apiKey, httpClient: c, }, nil } func (c *OwmClient) NewGetRequest(spath string, cityID int64, cityName, countryCode string, params map[string]string) (*http.Request, error) { u := *c.baseURL u.Path = path.Join(c.baseURL.Path, spath) q := u.Query() q.Set("appid", c.apiKey) q.Set("units", "metric") if cityID > 0 { q.Set("id", strconv.FormatInt(cityID, 10)) } else { qParam := cityName if countryCode != "" { qParam = qParam + "," + countryCode } q.Set("q", qParam) } for k, v := range params { q.Set(k, v) } u.RawQuery = q.Encode() fmt.Printf("XXX url=%v\n", u.String()) req, err := http.NewRequest("GET", u.String(), nil) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") return req, nil } // GetCurrentWeatherByID gets current weather using OWM API // and returns it as CurrentWeather. func (c *OwmClient) GetCurrentWeatherByID(id int64) (*model.CurrentWeather, error) { req, err := c.NewGetRequest(CurrentWeatherPath, id, "", "", nil) if err != nil { return nil, err } res, err := c.httpClient.Do(req) if err != nil { return nil, err } ocw := new(OwmCurrentWeather) if err := decodeBody2(res, ocw); err != nil { return nil, err } fmt.Printf("XXX ocw=%+v\n", ocw) // TODO: Check city ID!! return normalize(ocw) } func (c *OwmClient) GetCurrentWeatherByName(name, code string) (*model.CurrentWeather, error) { req, err := c.NewGetRequest(CurrentWeatherPath, -1, name, code, nil) if err != nil { return nil, err } res, err := c.httpClient.Do(req) if err != nil { return nil, err } ocw := new(OwmCurrentWeather) if err := decodeBody2(res, ocw); err != nil { return nil, err } fmt.Printf("YYY ocw=%+v\n", ocw) return normalize(ocw) } func (c *OwmClient) GetWeatherForecastsByID(id int64) (*OwmWeatherForecast, error) { params := make(map[string]string) params["cnt"] = "24" req, err := c.NewGetRequest(WeatherForecastPath, id, "", "", params) if err != nil { return nil, err } res, err := c.httpClient.Do(req) if err != nil { return nil, err } wf := new(OwmWeatherForecast) if err := decodeBody2(res, wf); err != nil { return nil, err } // fmt.Printf("XXX wf=%+v\n", wf) cod := wf.Cod.String() if cod != "200" { if cod == "404" { return nil, nil } return nil, fmt.Errorf("Received error response from OWM: %s, %s", cod, wf.Message.String()) } if wf.City.Id != id { return nil, fmt.Errorf("Invalid City ID: %d (Requested: %d)", wf.City.Id, id) } return wf, nil } func (c *OwmClient) GetWeatherForecastsByName(name, code string) (*OwmWeatherForecast, error) { params := make(map[string]string) params["cnt"] = "24" req, err := c.NewGetRequest(WeatherForecastPath, -1, name, code, params) if err != nil { return nil, err } res, err := c.httpClient.Do(req) if err != nil { return nil, err } wf := new(OwmWeatherForecast) if err := decodeBody2(res, wf); err != nil { return nil, err } // fmt.Printf("XXX wf=%+v\n", wf) cod := wf.Cod.String() if cod != "200" { if cod == "404" { return nil, nil } return nil, fmt.Errorf("Received error response from OWM: %s, %s", cod, wf.Message.String()) } if strings.EqualFold(code, wf.City.Country) { return nil, fmt.Errorf("Wrong Country code: %s (Requested: %s)", wf.City.Country, code) } if !strings.Contains(name, wf.City.Name) && !strings.Contains(wf.City.Name, name) { // This condition maybe too strong. Just log it. fmt.Printf("WARN: Wrong City name?: %s (Requested: %s)", wf.City.Name, name) } return wf, nil } func decodeBody2(resp *http.Response, out interface{}) error { defer resp.Body.Close() decoder := json.NewDecoder(resp.Body) return decoder.Decode(out) } func normalize(ocw *OwmCurrentWeather) (*model.CurrentWeather, error) { var weather string var temp int64 cod := ocw.Cod.String() if cod != "200" || len(ocw.Weather) == 0 { fmt.Printf("LOG Errorneous response: %+v\n", ocw) if cod == "404" { return nil, nil } return nil, fmt.Errorf("Received error response from OWM: %s, %s", cod, ocw.Message) } weather = GetWeatherCondition(ocw.Weather[0].Id) temp = marume(ocw.Main.Temp) tempStr := getTempStr(temp) fmt.Printf(" tempStr = %s\n", tempStr) return &model.CurrentWeather{ Weather: weather, Temp: temp, TempStr: tempStr}, nil } func marume(t float64) int64 { if t < 0 { // '通常は地上1.25~2.0mの大気の温度を摂氏(℃)単位で表す。度の単位に丸めるときは十分位を四捨五入するが、0度未満は五捨六入する。' // by 気象庁 return int64(math.Ceil(t - 0.5)) } return int64(math.Floor(t + 0.5)) } func getTempStr(t int64) string { if t < 0 { return fmt.Sprintf(tempStrFormatN, -1*t) } return fmt.Sprintf(tempStrFormatP, t) }
package main import ( "context" "fmt" "github.com/hunterhug/gorlock" "time" ) func main() { gorlock.SetDebug() // 1. config redis // 1. 配置Redis redisHost := "127.0.0.1:6379" redisDb := 0 redisPass := "hunterhug" // may redis has password config := gorlock.NewRedisSingleModeConfig(redisHost, redisDb, redisPass) pool, err := gorlock.NewRedisPool(config) if err != nil { fmt.Println("redis init err:", err.Error()) return } // 2. new a lock factory // 2. 新建一个锁工厂 lockFactory := gorlock.New(pool) // set retry time and delay mill second // 设置锁重试次数和尝试等待时间,表示加锁不成功等200毫秒再尝试,总共尝试3次,设置负数表示一直尝试,会堵住 lockFactory.SetRetryCount(3).SetRetryMillSecondDelay(200) // keep alive will auto extend the expire time of lock // 自动续命锁 lockFactory.SetKeepAlive(true) // 3. lock a resource // 3. 锁住资源,资源名为myLock resourceName := "myLock" // 10s // 过期时间10秒 expireMillSecond := 10 * 1000 lock, err := lockFactory.Lock(context.Background(), resourceName, expireMillSecond) if err != nil { fmt.Println("lock err:", err.Error()) return } // lock empty point not lock // 锁为空,表示加锁失败 if lock == nil { fmt.Println("lock err:", "can not lock") return } // add lock success // 加锁成功 fmt.Printf("add lock success:%#v\n", lock) // wait lock release // 可以等待锁被释放 //<-lockFactory.Done(lock) time.Sleep(3 * time.Second) // 4. unlock a resource // 4. 解锁 isUnlock, err := lockFactory.UnLock(context.Background(), lock) if err != nil { fmt.Println("lock err:", err.Error()) return } fmt.Printf("lock unlock: %v, %#v\n", isUnlock, lock) // unlock a resource again no effect side // 上面已经解锁了,可以多次解锁 isUnlock, err = lockFactory.UnLock(context.Background(), lock) if err != nil { fmt.Println("lock err:", err.Error()) return } fmt.Println("lock unlock:", isUnlock) }
package ber import ( "bytes" "io" "math" "testing" ) func TestEncodeDecodeInteger(t *testing.T) { for _, v := range []int64{0, 10, 128, 1024, math.MaxInt64, -1, -100, -128, -1024, math.MinInt64} { enc := encodeInteger(v) dec, err := ParseInt64(enc) if err != nil { t.Fatalf("Error decoding %d : %s", v, err) } if v != dec { t.Errorf("TestEncodeDecodeInteger failed for %d (got %d)", v, dec) } } } func TestBoolean(t *testing.T) { packet := NewBoolean(ClassUniversal, TypePrimitive, TagBoolean, true, "first Packet, True") newBoolean, ok := packet.Value.(bool) if !ok || newBoolean != true { t.Error("error during creating packet") } encodedPacket := packet.Bytes() newPacket := DecodePacket(encodedPacket) newBoolean, ok = newPacket.Value.(bool) if !ok || newBoolean != true { t.Error("error during decoding packet") } } func TestLDAPBoolean(t *testing.T) { packet := NewLDAPBoolean(ClassUniversal, TypePrimitive, TagBoolean, true, "first Packet, True") newBoolean, ok := packet.Value.(bool) if !ok || newBoolean != true { t.Error("error during creating packet") } encodedPacket := packet.Bytes() newPacket := DecodePacket(encodedPacket) newBoolean, ok = newPacket.Value.(bool) if !ok || newBoolean != true { t.Error("error during decoding packet") } } func TestInteger(t *testing.T) { var value int64 = 10 packet := NewInteger(ClassUniversal, TypePrimitive, TagInteger, value, "Integer, 10") { newInteger, ok := packet.Value.(int64) if !ok || newInteger != value { t.Error("error creating packet") } } encodedPacket := packet.Bytes() newPacket := DecodePacket(encodedPacket) { newInteger, ok := newPacket.Value.(int64) if !ok || newInteger != value { t.Error("error decoding packet") } } } func TestString(t *testing.T) { value := "Hic sunt dracones" packet := NewString(ClassUniversal, TypePrimitive, TagOctetString, value, "String") newValue, ok := packet.Value.(string) if !ok || newValue != value { t.Error("error during creating packet") } encodedPacket := packet.Bytes() newPacket := DecodePacket(encodedPacket) newValue, ok = newPacket.Value.(string) if !ok || newValue != value { t.Error("error during decoding packet") } } func TestSequenceAndAppendChild(t *testing.T) { values := []string{ "HIC SVNT LEONES", "Iñtërnâtiônàlizætiøn", "Terra Incognita", } sequence := NewSequence("a sequence") for _, s := range values { sequence.AppendChild(NewString(ClassUniversal, TypePrimitive, TagOctetString, s, "String")) } if len(sequence.Children) != len(values) { t.Errorf("wrong length for children array should be %d, got %d", len(values), len(sequence.Children)) } encodedSequence := sequence.Bytes() decodedSequence := DecodePacket(encodedSequence) if len(decodedSequence.Children) != len(values) { t.Errorf("wrong length for children array should be %d => %d", len(values), len(decodedSequence.Children)) } for i, s := range values { if decodedSequence.Children[i].Value.(string) != s { t.Errorf("expected %d to be %q, got %q", i, s, decodedSequence.Children[i].Value.(string)) } } } func TestReadPacket(t *testing.T) { packet := NewString(ClassUniversal, TypePrimitive, TagOctetString, "Ad impossibilia nemo tenetur", "string") var buffer io.ReadWriter = new(bytes.Buffer) if _, err := buffer.Write(packet.Bytes()); err != nil { t.Error("error writing packet", err) } newPacket, err := ReadPacket(buffer) if err != nil { t.Error("error during ReadPacket", err) } newPacket.ByteValue = nil if !bytes.Equal(newPacket.ByteValue, packet.ByteValue) { t.Error("packets should be the same") } } func TestBinaryInteger(t *testing.T) { // data src : http://luca.ntop.org/Teaching/Appunti/asn1.html 5.7 data := []struct { v int64 e []byte }{ {v: 0, e: []byte{0x02, 0x01, 0x00}}, {v: 127, e: []byte{0x02, 0x01, 0x7F}}, {v: 128, e: []byte{0x02, 0x02, 0x00, 0x80}}, {v: 256, e: []byte{0x02, 0x02, 0x01, 0x00}}, {v: -128, e: []byte{0x02, 0x01, 0x80}}, {v: -129, e: []byte{0x02, 0x02, 0xFF, 0x7F}}, {v: math.MaxInt64, e: []byte{0x02, 0x08, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, {v: math.MinInt64, e: []byte{0x02, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, } for _, d := range data { if b := NewInteger(ClassUniversal, TypePrimitive, TagInteger, d.v, "").Bytes(); !bytes.Equal(d.e, b) { t.Errorf("Wrong binary generated for %d : got % X, expected % X", d.v, b, d.e) } } } func TestBinaryOctetString(t *testing.T) { // data src : http://luca.ntop.org/Teaching/Appunti/asn1.html 5.10 if !bytes.Equal([]byte{0x04, 0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, NewString(ClassUniversal, TypePrimitive, TagOctetString, "\x01\x23\x45\x67\x89\xab\xcd\xef", "").Bytes()) { t.Error("wrong binary generated") } } // buff is an alias to build a bytes.Reader from an explicit sequence of bytes func buff(bs ...byte) *bytes.Reader { return bytes.NewReader(bs) } func TestEOF(t *testing.T) { _, err := ReadPacket(buff()) if err != io.EOF { t.Errorf("empty buffer: expected EOF, got %s", err) } // testCases for EOF testCases := []struct { name string buf *bytes.Reader }{ {"primitive", buff(0x04, 0x0a, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)}, {"constructed", buff(0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02)}, {"constructed indefinite length", buff(0x30, 0x80, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x00, 0x00)}, } for _, tc := range testCases { _, err := ReadPacket(tc.buf) if err != nil { t.Errorf("%s: expected no error, got %s", tc.name, err) } _, err = ReadPacket(tc.buf) if err != io.EOF { t.Errorf("%s: expected EOF, got %s", tc.name, err) } } // testCases for UnexpectedEOF : testCases = []struct { name string buf *bytes.Reader }{ {"truncated tag", buff(0x1f, 0xff)}, {"tag and no length", buff(0x04)}, {"truncated length", buff(0x04, 0x82, 0x02)}, {"header with no content", buff(0x04, 0x0a)}, {"header with truncated content", buff(0x04, 0x0a, 0, 1, 2)}, {"constructed missing content", buff(0x30, 0x06)}, {"constructed only first child", buff(0x30, 0x06, 0x02, 0x01, 0x01)}, {"constructed truncated", buff(0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01)}, {"indefinite missing eoc", buff(0x30, 0x80, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02)}, {"indefinite truncated eoc", buff(0x30, 0x80, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x00)}, } for _, tc := range testCases { _, err := ReadPacket(tc.buf) if err != io.ErrUnexpectedEOF { t.Errorf("%s: expected UnexpectedEOF, got %s", tc.name, err) } } }