text
stringlengths
11
4.05M
package bootstrap import ( "context" "fmt" "io" "net/http" "strings" "github.com/grpc-ecosystem/grpc-gateway/runtime" "github.com/tppgit/we_service/core" "github.com/tppgit/we_service/pkg/services" "google.golang.org/grpc" ) func RegisterGrpcService(c context.Context, s *grpc.Server, mux *http.ServeMux, add...
package models import ( "fmt" "time" "github.com/rs/zerolog" ) // Pre-loaded users for demonstration purposes var initialUsers = []User{ { FirstName: "Rob", LastName: "Pike", }, { FirstName: "Ken", LastName: "Thompson", }, { FirstName: "Robert", LastName: "Griesemer", }, { FirstName: "...
// Copyright 2021 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
package main import ( "fmt" "log" "github.com/kataras/iris" "github.com/neverlock/utility/random" "golang.org/x/net/websocket" ) /* Native messages no need to import the iris-ws.js to the ./templates.client.html Use of: OnMessage and EmitMessage */ type clientPage struct { Title string Host string } type B...
package main import ( "log" "net/http" "fmt" "io/ioutil" "strconv" "../ZFic" ) func main() { ZFIC, Sucess := ZFic.Load() if Sucess != nil { log.Fatal("Error Loading Server: " + Sucess.Error()) } ZF := http.NewServeMux() ZF.HandleFunc("/", ZFic.MainPage) ...
package main import "practice/urlShort/helpers" // 入口函数 func main() { shortUrl := helpers.ShortUrl{} longUrl := "http://www.google.com" shortUrl.Do(longUrl) }
package blast import ( "context" "fmt" "io" "github.com/pkg/errors" ) func (b *Blaster) startMainLoop(ctx context.Context) { b.mainWait.Add(1) b.mainChannel = make(chan struct{}) go func() { defer fmt.Fprintln(b.out, "Exiting main loop") defer b.mainWait.Done() for { select { case <-ctx.Done(): ...
package goSolution import "testing" func TestScheduleCourse(t *testing.T) { courses := [][]int {{100,200},{200,1300},{1000,1250},{2000,3200}} AssertEqual(t, 3, scheduleCourse(courses)) courses = [][]int {{1, 2}, {1, 2}, {2, 4}} AssertEqual(t, 3, scheduleCourse(courses)) courses = [][]int {{3, 2}, {4, 3}} Ass...
package fin import ( "log" "os" "strings" "time" "github.com/valyala/fasthttp" ) var logger *log.Logger func SimpleLogger() HandlerFunc { return func(c *Context) { if logger == nil { logger = log.New(os.Stdout, "[fin]", 0) } start := time.Now() c.Next() end := time.Now() logger.Printf("%v | %3d...
package routingproxy import ( "net/http" "net/http/httputil" "net/url" "regexp" ) // RoutingProxy is an HTTP Handler that uses a ReverseProxy and allows // to modify the requests and answers based on the routers type RoutingProxy struct { Proxy *httputil.ReverseProxy requestModifiers []RequestModifier } // Ad...
package framework import ( "math" "strings" "testing" ) func TestRound(t *testing.T) { down := Round(0.49) up := Round(0.5) if math.Abs(down-0.) >= floatPrecision { t.Errorf("framework.Round should round %v down", down) } if math.Abs(up-1.) >= floatPrecision { t.Errorf("framework.Round should round %v u...
package middleware import ( "log" "github.com/gin-gonic/gin" ) func SampleMiddleware() gin.HandlerFunc { return func(c *gin.Context) { log.Println("before logic") c.Next() log.Println("after logic") } }
package main_test import ( "Barracks/data" "Barracks/rank" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "reflect" "time" ) func createMockUser(index int, contest *data.Contest) (user data.User) { user = data.User{ ID: uint(index + 10), Name: "user0" + string(int('0')+index+1), StrId:...
package thread import "TechnoParkDBProject/internal/app/thread/models" type Usecase interface { CreateThread(thread *models.Thread) (*models.Thread, error) FindThreadBySlug(slug string) (*models.Thread, error) GetThreadsByForumSlug(forumSlug, since, desc string, limit int) ([]*models.Thread, error) GetThreadBySlu...
package lambda import ( "context" "encoding/json" "fmt" "github.com/aws/aws-lambda-go/lambda" "github.com/epsagon/epsagon-go/epsagon" "github.com/epsagon/epsagon-go/protocol" "github.com/epsagon/epsagon-go/tracer" "github.com/queueup-dev/qup-io/v2/envvar" ) // The following two types are added to introduce na...
package main import ( "fmt" "strconv" "strings" "github.com/Jeffail/gabs/v2" "github.com/urfave/cli/v2" ) var cmdGet cli.Command var cmdContains cli.Command type getOptions struct { json *gabs.Container path string delimiter string } func init() { cmdGet = cli.Command{ Name: "get", Usage: ...
package main type ListNode struct { Val int Next *ListNode } func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { dummyHead := &ListNode{-1, nil} cur := dummyHead p1, p2, carry := l1, l2, 0 for p1 != nil || p2 != nil || carry != 0 { if p1 != nil { carry += p1.Val p1 = p1.Next } if p2 != nil {...
package main import ( "log" "net/http" "time" ) type helloHandler struct{} func (_ *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world!")) } // func main() { // http.Handle("/", &helloHandler{}) // log.Println("Staring HTTP server ...") // log.Fatal(http.ListenAndSe...
//数组实现队列 package main import ( "errors" "fmt" ) type SliceQueue struct { slice []int front int rear int } //判断队列是否为空 func (p *SliceQueue) IsEmpty() bool{ return p.front == p.rear } //获取队列长度 func (p *SliceQueue) Size() int{ return p.rear - p.front } //获取队列首元素 func (p *SliceQueue) Top() int{ if p.IsEmpty()...
package bier import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "log" "net/http" "net/url" "os" "strconv" "strings" ) type Params struct { Token string ResponseURL string Location string Radius int UserName string } type TextBlock struct { Type string `json:"type"` Text st...
package minedive import ( "context" crand "crypto/rand" b64 "encoding/base64" "errors" "fmt" "io" "log" "math/rand" "net/http" "strings" "sync" "time" json "encoding/json" "golang.org/x/crypto/nacl/secretbox" "nhooyr.io/websocket" "nhooyr.io/websocket/wsjson" ) type MinediveServer struct { clients ...
package notice import ( "io/ioutil" "net/http" "net/url" ) type EmailNoticer struct { config *EmailConfig } func (this *EmailNoticer) SendEmail(recipient, subject, content string) (string, error) { payload := this.newPayload(recipient, subject, content) resp, err := http.PostForm(this.config.Addr, payload) if...
// 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 types type header struct { signature [4]byte version byte format byte luacData [6]byte cintSize byte sizetSize byte instructionSize byte luaIntegerSize byte luaNumberSize byte luacInt int64 luacNum float64 } type BinaryChunk struct { he...
package auth type ServicePrincipal struct { ApplicationId string Password string Tenant string DisplayName string // no usage as of yet Name string // no usage as of yet }
package sheet_logic import ( "hub/sheet_logic/sheet_logic_types" ) type IntMultiplication struct { GrammarElement BinaryOperationInt } func (i *IntMultiplication) CalculateInt(g GrammarContext) (result int64, err error) { leftVal, errL := i.GetLeftArg().CalculateInt(g) rightVal, errR := i.GetRightArg().Calculat...
package main import ( "fmt" "net/http" "sync" ) func main() { stats := map[string]int{} // topic->count totalDone := 0 valMutex := sync.Mutex{} http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("clear") != "" { valMutex.Lock() stats = map[string]int{} totalDon...
package cls import ( "testing" "time" ) func TestClSCleint_UploadLog(t *testing.T) { k1, v1, k2, v2 := "key1", "value1", "key2", "value2" t1 := time.Now().Unix() type fields struct { SecretId string SecretKey string Host string } type args struct { logTopicID string logGroupList LogGroupList...
// Copyright 2015 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 i...
package main import ( "github.com/faiface/pixel" "github.com/mateusz/rtsian/piksele" ) const ( MOBS_MISSILE_START_ID = 31 ) type missile struct { mobile piksele.Sprite } func NewMissile(position pixel.Vec, target pixel.Vec) missile { mv := target.Sub(position) m := missile{ mobile: mobile{ position: pos...
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { reader := bufio.NewReaderSize(os.Stdin, 100001) l, _ := reader.ReadString('\n') t, _ := strconv.Atoi(strings.TrimSpace(l)) for ; t > 0; t-- { a, _ := reader.ReadString('\n') b, _ := reader.ReadString('\n') a = strings.TrimSpa...
package main import ( "log" "menteslibres.net/gosexy/redis" "strings" ) var host = "127.0.0.1" var port = uint(6379) var publisher *redis.Client var consumer *redis.Client func main() { var err error publisher = redis.New() err = publisher.Connect(host, port) if err != nil { log.Fatalf("Publisher faile...
package main import ( "time" "log" "strings" ) type Storm struct { reminderCycle time.Duration config *PluginConfig } type StormMode struct { on bool link string } var lastStorm = time.Now().UTC() var stormTakerMsg = "IS THE STORM TAKER! \n" + "Go forth and summon the engineering powers of the te...
package Server import ( "xwork/App/Middleware/recover" "xwork/BootStrap/DbBase" "xwork/BootStrap/LogInit" "context" "log" "net/http" "time" "github.com/iris-contrib/middleware/cors" "github.com/kataras/iris/v12" "github.com/kataras/iris/v12/middleware/logger" "github.com/spf13/viper" ) func InitIris() { ...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //289. Game of Life //According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the Britis...
package models type User struct { ID string Name string Age uint }
package main import ( "adventOfCode/days/day8" "io/ioutil" "log" "os" "os/signal" "strings" "syscall" ) func main() { c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c os.Exit(1) }() data := readMap("./days/day8/data.txt") day8.Main(data) } func readMap(file...
package main import "fmt" func main() { list1 := []int{5, 4, 3, 2, 1} list2 := []int{3, 5, 432 ,122, 12, 314, 1, 9, 21, 13, 8} fmt.Println(sortList(list1)) fmt.Println(sortList(list2)) } func sortList(xi []int) []int { for { swapped := false for i := 0 ; i < len(xi) - 1 ; i++ { if xi[i] > xi[i + 1] { ...
/** * day 01 2020 * https://adventofcode.com/2020/day/1 * * compile: go build main.go * run: ./main < input * compile & run: go run main.go < input **/ package main import ( "bufio" "os" "fmt" "strings" ) func part1(n []int) int { for _, i := range n { for _, j := range n { if i + j == 2020 { ...
package domain import "github.com/tokopedia/tdk/go/app/resource" type UserDomain struct { resource UserResourceItf } func InitUserDomain(rsc UserResourceItf) UserDomain { return UserDomain{ resource: rsc, } } func (user UserDomain) IsValidUser(userID int) bool { if err := user.resource.FindUser(userID); err !...
package model // 资源管理表 // 连接不同类型的资源(如菜单,接口),角色的权限仅映射到该表的id type Resource struct { Id int AppId string //应用id ResType int //资源类型 ResId int //资源id } // 菜单,资源详情 type ResCollection struct { DetailId int `json:"-"`//菜单id Name string `json:"name"`//菜单名称 ResType int `json:"-"`//资源类型 ParentId...
package leetcode func titleToNumber(s string) int { var ret = 0 if len(s) == 0 { return ret } ret = int(s[0]) - 65 for i := 1; i < len(s); i += 1 { ret = (ret + 1) * 26 + int(s[i]) - 65 } return ret + 1 }
package nimkv import ( "net/http" "net/http/httptest" "testing" "github.com/julienschmidt/httprouter" ) func TestIndexHandler(t *testing.T) { router := httprouter.New() router.GET("/", indexHandler) req, err := http.NewRequest("GET", "/", nil) if err != nil { t.Error(err) } recorder := htt...
package main import "fmt" func sum(nums... int){ fmt.Println(nums, " ") total := 0 for _,num := range nums{ total += num } fmt.Print(total,"\n") } func main(){ sum (1,23,3) sum (2,34,3) arr1 := []int {3,4,5,6,7} sum(arr1...) }
package main // // import ( // "fmt" // "net/http" // // "github.com/go-chi/chi" // "github.com/zmb3/spotify" // ) // // func (a *api) getArtist(w http.ResponseWriter, r *http.Request) { // a.Log.Infof("🎸 Starting getArtist...") // a.Log.Infof("GetArtist request: %+v", r) // // artistID := chi.URLParam(r, "arti...
package helper import ( "context" "strings" qm "github.com/volatiletech/sqlboiler/queries/qm" "github.com/99designs/gqlgen/graphql" ) type ColumnSetting struct { Name string IDAvailable bool // ID is available without preloading } func PreloadsContainMoreThanId(a []string, v string) bool { for _, av ...
// This file is subject to a 1-clause BSD license. // Its contents can be found in the enclosed LICENSE file. package evdev import ( "fmt" "syscall" "unsafe" ) func ioctl(fd, name uintptr, data interface{}) error { var v uintptr switch dd := data.(type) { case unsafe.Pointer: v = uintptr(dd) case int: v...
package DataTable import ( "github.com/team-zf/framework/dal" "time" ) type Server struct { dal.BaseTable Id int64 `db:"id,pk"json:"id"` Title string `db:"title"json:"title"` Status int `db:"status"json:"status"` Host string `db:"host"` Port int `db:"po...
// 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 la...
package models type ClassLog struct { Id int64 `json:"id"` Action string `json:"action"` Uid int `json:"uid"` Classid int `json:"classid"` Teaid int `json:"teaid"` Stuid int `json:"stuid"` Ts string `json:"ts"` Note string `json:"note"` Roomid string `json:"roomid"` Traceid st...
package Works import ( "ShiqianCrawler/models" "ShiqianCrawler/utils" "github.com/gocolly/colly" "gopkg.in/mgo.v2/bson" "log" "strconv" "strings" ) func Taitea_DoWork(rootUrl string,crawlerChan chan string,collectionName string){ collector := colly.NewCollector() //爬取下一页链接 collector.OnHTML("div#pages", fu...
package main import ( "fmt" "github.com/karalabe/cookiejar/graph" "github.com/karalabe/cookiejar/graph/dfs" ) func main() { // Create the graph g := graph.New(7) g.Connect(0, 1) g.Connect(1, 2) g.Connect(2, 3) g.Connect(3, 4) g.Connect(3, 5) // Create the depth first search algo structure for g and source...
package main import ( "bufio" "fmt" "os" "strconv" "strings" "tictactoe/components" "tictactoe/service" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Println("Welcome") //taking size fmt.Print("Enter size of the board : ") AGAIN: size_of_board, _ := reader.ReadString('\n') ...
package msg const ( GroupTopic = "Group_" )
package kebab import ( ) func Grill() string { return "ju-ju!" }
package http import ( "context" "fmt" "io" "io/ioutil" "log" "net/http" "os" "testing" "time" ) //DON'T forget to add PORT to firewall exception var ( fileField = "files" dataDir = "testdata/" uploadDir = "testdata/upload/" uploadTarget = "/upload" serverPort = ":8080" ...
package arc import ( "bytes" "fmt" "sort" "strings" "time" "github.com/PuerkitoBio/goquery" log "github.com/sirupsen/logrus" ) const snapshotLayout = "2 Jan 2006 15:04" // Snapshot represents an instance of a URL page snapshot on archive.is. type Snapshot struct { URL string ThumbnailURL string T...
package testdata import ( "testing" "github.com/stretchr/testify/require" ) func TestTestData(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { if c.success { require.NoError(t, c.function()) } else { require.Error(t, c.function()) } }) } } // grep 'func [PF]' ./...
package main import ( "bufio" "fmt" "os" "strings" ) const maxLength = 20 type Name struct { fname string lname string } func main() { var fn string fmt.Print("Input file name: ") fmt.Scanln(&fn) file, err := os.Open(fn) if err != nil { panic(err) } defer file.Close() data := make([]Name, 1) sc...
package types import ( "github.com/tendermint/tendermint/crypto" sdk "github.com/cosmos/cosmos-sdk/types" servicetypes "github.com/irisnet/irismod/modules/service/types" "github.com/irisnet/irismod/modules/oracle/types" ) const ( ServiceName = "random" ServiceDesc = "system service definiti...
//go:build ocr package uixt import ( "testing" ) func TestDriverExtOCR(t *testing.T) { driverExt, err := iosDevice.NewDriver(nil) checkErr(t, err) point, err := driverExt.FindScreenText("抖音") checkErr(t, err) t.Logf("point.X: %v, point.Y: %v", point.X, point.Y) driverExt.Driver.TapFloat(point.X, point.Y-20)...
package main import ( "github.com/mustafa-zidan/simscale/cache" "github.com/mustafa-zidan/simscale/parser" "github.com/mustafa-zidan/simscale/stats" "github.com/urfave/cli" "log" "os" "sync" ) var inFile, outFile, version string var flags = []cli.Flag{ cli.StringFlag{ Name: "in-file, i", Value: ...
package matcher import "github.com/fdingiit/matching-algorithms/def" type Matcher interface { Add(subs ...def.Subscription) Match(product def.Product) []def.Subscription }
package refmt_test import ( "bytes" "fmt" "testing" "github.com/polydawn/refmt" "github.com/polydawn/refmt/cbor" "github.com/polydawn/refmt/json" "github.com/polydawn/refmt/obj/atlas" ) func TestRoundTrip(t *testing.T) { t.Run("nil nil", func(t *testing.T) { testRoundTripAllEncodings(t, nil, atlas.MustBuil...
package main const ErlHeaderStr = `-module(ergo). -compile(export_all). -on_load(init/0). init() -> ok = erlang:load_nif("./ergo", 0). `
package bosh_test import ( "github.com/cloudfoundry/bosh-bootloader/bosh" "github.com/cloudfoundry/bosh-bootloader/storage" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("SSHKeyDeleter", func() { Describe("Delete", func() { var ( sshKeyDeleter bosh.SSHKeyDeleter state ...
package main import ( "fmt" "time" ) func wait(index int) { time.Sleep(time.Second * 10) fmt.Println("finished", index) } func main() { for i := 0; i < 10; i++ { w := i go wait(w) defer func() { fmt.Println(w) }() } fmt.Println("finish") }
package rest import ( "regexp" "strconv" r "github.com/jinmukeji/jiujiantang-services/pkg/rest" "github.com/kataras/iris/v12" ) var codeToMsg = map[int]string{ ErrOK: "OK", ErrUnknown: "Unknown error", ErrClientUnauthorized: "Unauthorized Client", ErrUserUnauthorized: "Unauthorized User", ErrParsin...
package gitlab import ( "archive/zip" "bytes" "context" "fmt" "io" "io/ioutil" "os" "github.com/rs/zerolog" "github.com/sirkon/gitlab" "github.com/sirkon/gitlab/gitlabdata" "github.com/sirkon/goproxy/internal/errors" "github.com/sirkon/goproxy" "github.com/sirkon/goproxy/fsrepack" "github.com/sirkon/g...
package loaders_test import ( "context" "testing" "time" "github.com/syncromatics/kafmesh/internal/graph/loaders" "github.com/syncromatics/kafmesh/internal/graph/model" gomock "github.com/golang/mock/gomock" "github.com/pkg/errors" "gotest.tools/assert" ) func Test_Services_Components(t *testing.T) { ctrl ...
package config import ( "encoding/json" "fmt" //used to print errors majorly. "io/ioutil" //it will be used to help us read our config.json file. ) var ( Token string //To store value of Token from config.json . BotPrefix string // To store value of BotPrefix from config.json. config *configStruct //To st...
package azurecontrollers import ( "context" "github.com/sirupsen/logrus" "sigs.k8s.io/controller-runtime/pkg/client/config" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/runtime/signals" "github.com/openshift/openshift-azure/pkg/controllers/customeradmin" "github.com/openshi...
package vptree type heapItem struct { Item *Item Dist float32 } // A heap must be initialized before any of the heap operations // can be used. Init is idempotent with respect to the heap invariants // and may be called whenever the heap invariants may have been invalidated. // Its complexity is O(n) where n = h.Le...
package main import ( "fmt" "log" "net/http" "os" "github.com/BolajiOlajide/go-api/controllers" "github.com/BolajiOlajide/go-api/database" "github.com/gorilla/mux" "github.com/joho/godotenv" ) func main() { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") return } fmt.Prin...
package handlers import ( "errors" "github.com/valyala/fasthttp" "github.com/authelia/authelia/v4/internal/middlewares" "github.com/authelia/authelia/v4/internal/model" "github.com/authelia/authelia/v4/internal/session" "github.com/authelia/authelia/v4/internal/storage" ) // UserTOTPInfoGET returns the users ...
package api import ( "budget-calendar/database" "github.com/gin-gonic/gin" ) //All the routes created by the package nested in // api/v1/* func Routes(r *gin.RouterGroup, db *database.DB) { }
package main import ( "github.com/uploadService/mPath" "math/rand" "strings" "time" ) type FileMsg struct { FullFileName string //全路径 C:\jalen\bin\aa.png FileSuffix string //文件类型 .png FileDir string //文件夹 c:\jalen\bin FileNameWithSuffix string //带文件类型的文件名 aa.png FileName st...
package csvwriter import ( "encoding/csv" "os" "regexp" ) func Export(array []string,name string) { hostChar := regexp.MustCompile(`https://|http://|/g`) nameWitoutHost := hostChar.ReplaceAllString(name, "") specialChar := regexp.MustCompile(`/|\:|\?|\.|"|<|>|\|\*|/g`) n := specialChar.ReplaceAllString(nam...
package spacesaving type Counter struct { Next *Counter Prev *Counter Value uint64 ErrorCount uint64 Key string ParentBucket *Bucket } type DoubleLinkedCounter struct { Head *Counter Tail *Counter } func NewDoubleLinkedCounter() *DoubleLinkedCounter { return &DoubleLinkedCo...
// Sample use : // // ./pinger --ip http://dgraph.io/query --numuser 3 // // package main import ( "bytes" "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "sync" "time" "github.com/dgraph-io/dgraph/x" ) var ( numUser = flag.Int("numuser", 1, "number of users hitting simultaneously") numReq ...
package main import ( "apiapp/api" "common/config" "common/logger" "common/model" "fmt" ) func main() { fmt.Println("Starting alcedo api server ......") //初始化配置文件 config.Init() fmt.Println("Init APP config.ini OK ...... ") //初始化日志 category := config.GetPropStr("api_log_category") outtype := config.GetProp...
package main import ( "bufio" "fmt" "io" "io/ioutil" "os" ) func main() { backup := exec.Command("gnome-terminal", "-x", "sh", "-c", "go run backup.go") CreateFile() PrimaryProcess() for{ if !IsAlive(){ backup.Run() } } dat, err := ioutil.ReadFile("backup") CheckError(err) ...
package hash import ( "encoding/base64" "crypto/md5" "crypto/sha1" "hash/crc32" "encoding/hex" ) //与php base64_encode()相同 func Base64Encode(src string) string { return base64.StdEncoding.EncodeToString([]byte(src)) } //与php base64_decode()相同 func Base64Decode(src string) (string, error) { decode, err := base6...
package 遍历 func verifyPostorder(postorder []int) bool { if len(postorder) <= 1 { return true } rightTreeLeftIndex, rightTreeRightIndex := getIndexOfFirstNumGreaterThanLastNum(postorder), len(postorder)-2 leftTreeLeftIndex, leftTreeRightIndex := 0, rightTreeLeftIndex-1 rootVal := postorder[len(postorder)-1] if ...
package sv import ( "bytes" "io/fs" "os" "sort" "text/template" "time" "github.com/Masterminds/semver/v3" ) type releaseNoteTemplateVariables struct { Release string Tag string Version *semver.Version Date time.Time Sections []ReleaseNoteSection AuthorNames []string } // Outpu...
package routetag import ( "context" "database/sql" "github.com/hardstylez72/bblog/ad/pkg/tag" "github.com/jmoiron/sqlx" ) func Merge(ctx context.Context, conn *sqlx.DB, tx *sqlx.Tx, routeId int, tagNames []string) ([]string, error) { currentTagIds, err := GetRouteTags(ctx, conn, routeId) if err != nil { retu...
package main func main() { var x int // x is declared too far from its use, x is defined but its current value isn't used if true { x = 3 // x is defined but its current value isn't used x = 4 // x is defined but its current value isn't used } }
package main import ( "strconv" "io" "bufio" "os" "flag" "fmt" "time" "algorithms/quicksort" "algorithms/bubblesort" ) // 名字,默认值,使用方法 var infile *string = flag.String("i", "unsorted.dat", "File contains values for sorting") var outfile *string = flag.String("o", "sorted.dat", "File to receive sorted values")...
// Package tx defines data types for transactions, transaction statuses, and // other related types. This package should not contain business-logic, and // should not depend on business-logic packages. // // Transactions are defined in this package, away from business-logic, so that // they can be imported into other p...
package mongodbwrapper import ( "context" "fmt" "go.mongodb.org/mongo-driver/mongo" ) /****************************************************************************************************** * * Definition * *******************************************************************************************************...
package main import ( "flag" "fmt" ) var name string var quit bool func init() { flag.StringVar(&name, "Name", "Tom", "input Name") flag.BoolVar(&quit, "q", false, "is Quit") } func main() { flag.Parse() if quit { return } fmt.Println(name) fmt.Printf("%#v\n", flag.Lookup("Name")) fmt.Println(flag.Lookup...
package config import ( log "github.com/sirupsen/logrus" "testing" ) func TestProcessingInvalidBody(t *testing.T) { cfg := Load() log.Debugf("Config: %+v\n", cfg) }
package leetcode import "math" func minPrices(prices []int) []int { min := math.MaxInt64 values := make([]int, len(prices)) for i, p := range prices { if p < min { min = p } values[i] = min } return values } func maxProfit(prices []int) int { max := 0 mins := minPrices(prices) for i, p := range pric...
package main import ( "context" "encoding/json" "io/ioutil" "log" "os" "path" "golang.org/x/oauth2" ) const tokenFilename = "$HOME/.gomuche/token.json" // NewTokenFromFile reads token from file and returns it. func NewTokenFromFile() *oauth2.Token { filename := os.ExpandEnv(tokenFilename) bytes, err := iou...
package keeper import ( "github.com/InjectiveLabs/injective-oracle-scaffold/injective-chain/modules/oracle/types" sdk "github.com/cosmos/cosmos-sdk/types" ) // GetParams returns the total set of oracle parameters. func (k BaseKeeper) GetParams(ctx sdk.Context) (params types.Params) { k.paramSpace.GetParamSet(ctx, ...
package game import ( "fmt" ) // Command interface defiens something that is a command type Command interface { fmt.Stringer Run(*Game) }
package transport import ( "context" "encoding/json" "fmt" "github.com/feng/future/go-kit/agfun/app-server/protocol/api" "net/http" //"github.com/gorilla/mux" ) func decodeAccountRequest(_ context.Context, r *http.Request) (interface{}, error) { var request api.AccountReq // if err := json.NewDecoder(r.Body)....
package main import ( "bankBigData/AutomaticTask/module" "bankBigData/_public/config" "bankBigData/_public/log" "bankBigData/_public/table" "gitee.com/johng/gf/g" "gitee.com/johng/gf/g/os/os/gcron" ) func main() { g.Config().SetFileName("config.json") debug := g.Config().GetBool("debug") table.DbDefaultName ...
/*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, sof...
package cmd import ( "fmt" "log" "time" "github.com/gen2brain/beeep" "github.com/spf13/cobra" ) const ( timerStartedMessage = "timer started!\n" timerDoneMessage = "timer done!" notEnoughArgumentMessage = "timer: not enough argument" tooManyArgumentMessage = "timer: to many argument" ) // ti...