text
stringlengths
11
4.05M
package backend_test import ( "context" "database/sql/driver" "testing" "time" gmysql "github.com/go-sql-driver/mysql" "github.com/google/uuid" "github.com/pingcap/errors" "github.com/pingcap/tidb/br/pkg/lightning/backend" "github.com/pingcap/tidb/br/pkg/lightning/backend/encode" "github.com/pingcap/tidb/br...
package mgmt import ( "encoding/json" "fmt" "github.com/bitmaelum/bitmaelum-suite/cmd/bm-server/handler" "github.com/bitmaelum/bitmaelum-suite/internal/apikey" "github.com/bitmaelum/bitmaelum-suite/internal/container" "github.com/bitmaelum/bitmaelum-suite/pkg/address" "net/http" "time" ) type inputInviteType ...
package dao import ( "context" "github.com/bilibili/kratos/pkg/sync/pipeline/fanout" ) // Dao dao interface type Dao interface { Close() Ping(ctx context.Context) (err error) } // dao dao. type dao struct { cache *fanout.Fanout } // New new a dao and return. func New() (d Dao, err error) { d = &dao{ cache:...
package full import ( "os" "path/filepath" "strings" ) func check(e error) { if e != nil { panic(e) } } func LoadTable() [26][26]rune { dataPath, _ := filepath.Abs("cipher/vigenere/full/full_vigenere_table.txt") data, err := os.ReadFile(dataPath) check(err) var vigenereTable [26][26]rune splittedString...
package game import ( "errors" "fmt" "runtime/debug" "strings" "sync" "time" "awesome-dragon.science/go/goGoGameBot/internal/command" "awesome-dragon.science/go/goGoGameBot/internal/config/tomlconf" "awesome-dragon.science/go/goGoGameBot/internal/interfaces" "awesome-dragon.science/go/goGoGameBot/pkg/log" ...
/* 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 main import ( "context" "fmt" "log" "github.com/silviog1990/grpc-golang-course/unary/sum/sumpb" "google.golang.org/grpc" ) func main() { cc, err := grpc.Dial("localhost:50000", grpc.WithInsecure()) if err != nil { log.Fatalf("could not connect to: %v", err) } defer cc.Close() c := sumpb.NewSumSe...
package errors import ( "fmt" ) // post, type = 101 // SQLExecutionError - func SQLExecutionError(err error) *Error { return &Error{ Name: "SQLExecution", ErrorCode: 10101, StatusCode: 400, Detail: err.Error(), } } // ArticleIDNotFoundError - func ArticleIDNotFoundError(ID uint32) *Error { re...
//Non-boolean loop condition (3-parter) package main func main () { for { x:= 6 } var x, y bool for (x == y) { } for i := 0; i << 10; i++ { } }
package tests import ( "testing" "github.com/WindomZ/quizzee" "github.com/WindomZ/testify/assert" ) type QuestionTest struct { Text string Keys []string } var results = []QuestionTest{ { Text: "5. 下列哪种动物不用冬眠?", Keys: []string{"动物", "冬眠"}, }, { Text: "下列名人中最年轻的是?", Keys: []string{"名人", "最年轻"}, }, {...
/* Copyright 2022 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 db import ( "database/sql" "github.com/bradbeam/l1g/config" "testing" // _ "github.com/go-sql-driver/mysql" ) func createConfig() config.Config { configuration := config.Config{ "DatabaseHost": "127.0.0.1", "Database": "thisisatestingl1gdatabase", "DatabasePort": "3306", "Database...
package main import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func Test_Artist_With__All_Urls(t *testing.T) { assert := assert.New(t) body := `{ "response": { "status": { "code": 0, "message": "Success", "version": "4.2" }, ...
package gol import ( "log" "os" ) var logger *log.Logger = log.New(os.Stderr, "gol:main ", log.Ldate|log.Ltime) var Logger = logger
package handlers import ( "strings" "net/http/httptest" "io/ioutil" "bytes" "testing" "net/http" "encoding/json" "github.com/danielsomerfield/authful/common/util" "fmt" ) type JSONEndpointResponse struct { Json map[string]interface{} HttpStatus int Err error t *testing.T } //TODO: ...
package repository import ( "TechnoParkDBProject/internal/app/thread/models" "context" "fmt" "github.com/go-openapi/strfmt" "github.com/jackc/pgx/v4" "github.com/jackc/pgx/v4/pgxpool" "time" ) type ThreadRepository struct { Conn *pgxpool.Pool } func NewThreadRepository(con *pgxpool.Pool) *ThreadRepository { ...
package main import ( "fmt" "net" "net/http" "net/rpc" "gitgud.io/softashell/comfy-translator/translator" log "github.com/sirupsen/logrus" ) type Comfy int func (t *Comfy) Translate(req *translator.Request, reply *translator.Response) error { if len(req.Text) < 1 || len(req.From) < 1 || len(req.To) < 1 { r...
// Package snapshot Internal API response package snapshot // RequestSnapshotAPIResponse The Amazon Seller Tool response type RequestSnapshotAPIResponse struct { Version int `json:"version"` Success bool `json:"success"` Status int `json:"status"` Results...
package main import ( "crypto/sha256" "crypto/rsa" "crypto/rand" "crypto" "fmt" "strconv" ) type SignedDocument struct{ HashedData []byte EncryptedData []byte } // create hash value for inactive packets func (srh *SybilResistanceHandler)createHash(nodeID string) []byte{ bs := []byte(nodeID) hasher := sha...
package middleware import ( "culture/cloud/base/internal/support/api" "culture/cloud/base/internal/support/rpc" "culture/cloud/base/server/rpc/proto/auth" "net/http" "github.com/gin-gonic/gin" ) // TokenAuth Token验证 func TokenAuth(ctx *gin.Context) { tokenString := ctx.GetHeader("Authorization") if tokenStri...
package health import ( "testing" . "github.com/anthonybishopric/gotcha" ) func TestFindWorst(t *testing.T) { a := Result{ ID: "testcrit", Status: Critical, } b := Result{ ID: "testwarn", Status: Warning, } c := Result{ ID: "testpass", Status: Passing, } m := MinResult(a, b) Assert...
package pkg import ( "fmt" "io" "io/ioutil" "log" "os" "regexp" "strings" ) const ( codeBlockPattern = `(?m)^(.*\x60{3}).*\n(.*|\n)+?\n(.*\x60{3})$` ) func fileExists(file string) error { if _, err := os.Stat(file); err != nil { if os.IsNotExist(err) { return err } } return nil } func headerExists...
/* Copyright (C) 2019 Yusuke Kato (kpango) and Soba Proxy core maintainer team. 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 a...
package maze import ( "fmt" "os" ) func readMaze(filename string) [][]int { //filepath := "src\\algorithms\\maze\\" + filename filepath := "G:\\Code\\goAlgorithms\\src\\algorithms\\maze\\" + filename fmt.Println(filepath) file, err := os.Open(filepath) if err != nil { panic(err) } var row, col int fmt.Fs...
package models type Request struct { Id int `json:"id"` Method string `json:"method,omitempty"` Scheme string `json:"scheme,omitempty"` Path string `json:"path,omitempty"` Proto string `json:"proto,omitempty"` Host string `json:"host,omitempty"` Url string `json...
package output import ( "errors" "fmt" "os" "github.com/jutkko/mindown/util" ) const DEPTH_LIMIT int = 6 func WriteMarkdown(filename string, forceWrite bool, graph *util.Graph) error { if !forceWrite { if _, err := os.Stat(filename); !os.IsNotExist(err) { return errors.New("File exists") } } // Try t...
/* Copyright 2020 Humio https://humio.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 required by applicable law or agreed to in writing, ...
package errs import ( "testing" "github.com/stretchr/testify/require" ) func Test_staticcheck(t *testing.T) { err := staticcheck() require.Error(t, err) }
// Copyright 2014 Chris Monson <shiblon@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 required by applicable law...
package main import ( "bufio" "errors" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" ) var ( errNoToken = errors.New("cannot find .token") ) func (app *app) downloadPhoto(p *photo) (string, error) { downloadPath := filepath.Join(app.config.ConfigPath, p.ID+"."+app.opts.Extension) qs :...
package main import ( "os" "log" "fmt" ) func (this *Application) ProjectIssueRemoveAction(args []string) { issueKey := args[0] log.Printf("issueKey = %s", issueKey) // Remove issue err1 := this.Client.RemoveIssueByIssueKey(issueKey) if err1 != nil { fmt.Printf("Unable to remove issue: %v\n", err1) os....
package main import ( "glog/model" "glog/routes" ) func main() { model.InitDb() routes.InitRouter() }
package main import ( "io" "io/ioutil" ) var _output io.Writer func main() { // ioutil.Discard is a io.Writer // that throws away bytes. bs := []byte("Prashant") ioutil.Discard.Write(bs) }
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-09-03 08:18 # @File : lt_100_Same_Tree.go # @Description : # @Attention : */ package v0 func isSameTree(p *TreeNode, q *TreeNode) bool { return sameTree(p, q) } func sameTree(p *TreeNode, q *TreeNode) bool { if nil == p && nil == q { return true } if...
package unio //noinspection GoUnusedExportedFunction func DeleteMapKeys(m map[string]interface{}, keys... string) { for _, key := range keys { delete(m, key) } } //noinspection GoUnusedExportedFunction func Ternary(rule bool, trueResult interface{}, falseResult interface{}) interface{} { if rule {...
package main import "fmt" // https://leetcode-cn.com/problems/longest-increasing-subsequence/ //------------------------------------------------------------------------------ // Solution 1 O(n2) // f[i] 表示在数组S[0..i]包含第 i 个元素的LIS的长度 // 则 f[i+1] = MAX(f[j0],f[j1],..,f[jk]) + 1 // 其中 j0,j1,..,jk 是数组 S[0..i] 中元素小于 S[i+1...
package auth import ( "log" "net/http" "strings" "github.com/asaskevich/govalidator" httperror "github.com/portainer/libhttp/error" "github.com/portainer/libhttp/request" "github.com/portainer/libhttp/response" "github.com/portainer/portainer/api" ) type authenticatePayload struct { Username string Passwor...
/* 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...
package handlers_test import ( "bytes" "reflect" "gopher-translator/pkg/models" "encoding/json" "net/http/httptest" "net/http" "gopher-translator/pkg/handlers" "gopher-translator/pkg/mock" "testing" ) func TestCreateNewTranslatorHandler(t *testing.T) { mockInstance := mock.CreateNewMock() repository := mo...
package main import ( "fmt" "strings" "github.com/falcosecurity/plugin-sdk-go/pkg/sdk" "github.com/valyala/fastjson" ) var supportedFields = []sdk.FieldEntry{ {Type: "string", Name: "ct.id", Display: "Event ID", Desc: "the unique ID of the cloudtrail event (eventID in the json)."}, {Type: "string", Name: "ct.e...
package drivers import ( "fmt" "os" "os/exec" "path/filepath" "strings" ) // registeredDrivers are all the drivers which are currently registered var registeredDrivers = map[string]Interface{} // RegisterBinary is used to register drivers that are binaries. // Panics if a driver with the same name has been prev...
// Copyright 2014 The imapsrv Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the imapsrv.LICENSE file. package imap import ( "fmt" ) // An IMAP command type command interface { // Execute the command and return an imap response execute(s *sessio...
package gov import ( "bytes" "crypto/rand" "errors" "fmt" "github.com/consensys/gnark-crypto/accumulator/merkletree" "github.com/consensys/gnark-crypto/ecc/bn254/twistededwards" "github.com/consensys/gnark-crypto/ecc/bn254/twistededwards/eddsa" "github.com/consensys/gnark-crypto/signature" "github.com/consens...
package utils import "fmt" // ReaderPosition represents the position of a character within a document type ReaderPosition struct { Line uint `json:"line"` // zero-based line number Column uint `json:"column"` // zero-based column number EOF bool `json:"eof,omitempty"` // true iff we are at the...
package main import ( "fmt" "math/rand" "sync" "sync/atomic" "time" ) var wg sync.WaitGroup var counter int64 func main() { wg.Add(2) go incrementor("Foo:\t") go incrementor("Bar:\t") wg.Wait() fmt.Println("Final counter:\t", counter) } func incrementor(s string) { for i := 0; i < 20; i++ { time.Sleep(...
/* Copyright 2012 gtalent2@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 required by applicable law or agreed to i...
package cosmos type QueryParam struct { Name string `json:"name"` Value interface{} `json:"value"` } type SqlQuerySpec struct { Query string `json:"query"` Parameters []QueryParam `json:"parameters,omitempty"` } func Q(query string, queryParams ...QueryParam) *SqlQuerySpec { return &SqlQuerySpe...
package launcher import ( "fmt" "net/http" ) func runmain() { fmt.Println("server started") mux := http.NewServeMux() mux.HandleFunc("/api", proxy(handler)) } func proxy(f func(w http.ResponseWriter, req *http.Request)) func(w http.ResponseWriter, req *http.Request) { return func(w http.ResponseWriter, req *h...
package sql import ( "fmt" "strings" "time" ) type Column struct { Table table Column string alias string } func (c Column) As(alias string) Column { c.alias = alias return c } func (c Column) String() string { return fmt.Sprintf("%v.%v", c.Table.Reference(), c.Column) } func (c Column) SelectionString(...
package job import ( "fmt" bpreljob "github.com/cppforlife/bosh-provisioner/release/job" bhrelui "github.com/bosh-io/web/ui/release" ) type Job struct { Release bhrelui.Release Name string Description string Templates []Template Packages []Package PropertyItems map[string]*PropertyItem } func NewJob(...
package raftor import "github.com/coreos/etcd/raft" // ClusterConfig helps to configure a RaftNode type ClusterConfig struct { Name string Raft raft.Config }
package xc import ( "errors" "ms/sun/shared/helper" "strconv" "strings" "github.com/gocql/gocql" ) ////////////////////////////////////////// Query seletor updater and deleter ///////////////////////// func (a *FileRef) Exists() bool { return a._exists } func (a *FileRef) Deleted() bool { return a._deleted ...
package main import( "fmt" "runtime" "path" ) func f1(){ pc,file,line,ok:=runtime.Caller(0) //Caller是一层一层的调用,1是表示当前一层向上走一层,就是main函数的那一层,表示就是main函数里调用 if !ok{ //0表示当前层的当前位置,1表示调用该函数的位置 fmt.Printf("error ") return } funcName:=runtime.FuncForPC(pc).Name() //通过pc获取函数名字,这里如果上...
package main import ( "fmt" "log" "time" "github.com/getcfs/megacfs/formic" "github.com/gholt/store" pb "github.com/getcfs/megacfs/formic/proto" "golang.org/x/net/context" ) type UpdateItem struct { id []byte block uint64 blocksize uint64 size uint64 mtime int64 } type Updatinator s...
package main import "fmt" import "golang.org/x/net/websocket" import "log" const SERVER = "ws://localhost:3000/register" const ADDRESS = "http://localhost/" func main() { if ws, e := websocket.Dial(SERVER, "", ADDRESS); e == nil { var id int if e := websocket.JSON.Receive(ws, &id); e == nil { fmt.Println("Con...
// Copyright (c) 2020 Zededa, Inc. // SPDX-License-Identifier: Apache-2.0 // Wait for being able to connect to the syslog service for // at most maxTime package main import ( "fmt" "log/syslog" "os" "time" "github.com/sirupsen/logrus" lSyslog "github.com/sirupsen/logrus/hooks/syslog" ) const ( agentName = ...
package netgo import ( "net" "net/http" "time" ) var defaultTransport = &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ // Limits the time spent establishing a TCP connection // Errors: // i/o timeout Timeout: 30 * time.Second, // TCP KeepAlive specifies the interval betwe...
package model // Theatre ... type Theatre struct { ID string }
package pie // Average is the average of all of the elements, or zero if there are no // elements. func (ss myInts) Average() float64 { if l := int(len(ss)); l > 0 { return float64(ss.Sum()) / float64(l) } return 0 } // Sum is the sum of all of the elements. func (ss myInts) Sum() (sum int) { for _, s := range...
package main import ( "bufio" "bytes" "fmt" "math" "os" "strconv" "strings" ) func main() { s := bufio.NewScanner(os.Stdin) buff := new(bytes.Buffer) max := int(math.Pow(10, 7)) buff.Grow(max) s.Buffer(buff.Bytes(), max) s.Scan() temp := strings.Split(s.Text(), " ") //fmt.Println("\n\nParsed", temp) /...
package main import ( "context" "flag" "fmt" "os" "os/signal" "github.com/berquerant/gogrep" ) const usage = `Usage of gogrep cat file | gogrep [flags] REGEX gogrep [flags] REGEX files... Note: The matched lines are not guaranteed to be in order in which they appear in the input. Flags:` func printUsage(...
package db // SpotDetails is the database structure that holds the information about a spot // We do not want to expose the database format to the world, so we redefine it. type SpotDetails struct { Name string `bson:"name,omitempty"` Routes []Route `bson:"routes,omitempty"` Met...
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type AlterTSConfigurationStmt struct { Kind AlterTSConfigType Cfgname *ast.List Tokentype *ast.List Dicts *ast.List Override bool Replace bool MissingOk bool } func (n *AlterTSConfigurationStmt) Pos() int { return 0 }
package main import ( "fmt" helpers "../helpers" ) func main() { puzzleInputFile := helpers.GetFile("./input.txt") puzzleInputs := []int{} fmt.Println(puzzleInputs) }
package context import ( "context" "fmt" "math/rand" "time" ) // Exec sets two random timers and prints // a different context value for whichever // fires first func Exec() { // a base context ctx := context.Background() ctx = Setup(ctx) rand.Seed(time.Now().UnixNano()) timeoutCtx, cancel := context.WithT...
package main func bubble(arr []int) []int { len := len(arr) if (len < 2) { return arr } for i:=0; i<len; i++ { for j:=0; j<len-i-1; j++ { if (arr[j] > arr[j+1]) { tmp := arr[j] arr[j] = arr[j+1] arr[j+1] = tmp } ...
package assembler import ( "testing" ) func sscale(a float32, X []float32) { for i := range X { X[i] *= a } } func TestSscale(t *testing.T) { scalarVector2VectorTest(Sscale, sscale, t) } func BenchmarkSscale(b *testing.B) { scalarVector2VectorBench(sscale, b) } func BenchmarkOptimizedSscale(b *testing.B) { ...
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 // Package peering provides an overlay network for communicating // between nodes in a peer-to-peer style with low overhead // encoding and persistent connections. The network provides only // the asynchronous communication. // // It is intended to...
package committer_test import ( "fmt" "github.com/TangoEnSkai/committer-go/committer" "testing" ) func TestPatternMatch(t *testing.T) { const ( pattern = `^(BREAKING CHANGE|build|chore|ci|docs|feat|fix|perf|refactor|style|test)(\([a-z \-]+\))?: [\w \-]+$` validPattern = "perf: optimise pattern matching" inv...
package rss import ( "fmt" "net/http" "reunion/announcement" "reunion/configuration" ) func GetFile(writer http.ResponseWriter, request *http.Request) { writer.Write([]byte(GetRss())) writer.Header().Set("Content-Type", "application/xml") } func GetRss() string { announcements, _ := announcement.GetAnnounceme...
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
package oiio import ( "fmt" "os" "testing" ) func TestNewImageBuf(t *testing.T) { buf := NewImageBuf() if buf.Initialized() { t.Fatal("ImageBuf should not be considered initialized") } } func TestNewImageBufInitSpec(t *testing.T) { buf := NewImageBuf() if buf.Initialized() { t.Fatal("Expected ImageBuf no...
package main import ( "strings" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/route53" "github.com/aws/aws-sdk-go/service/kms" "github.com/aws/aws-sdk-go/service/iam" "github.com/aws/aws-sdk-go/service/efs" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sts" ) ...
package main import ( "Golang-Echo-MVC-Pattern/constant" "Golang-Echo-MVC-Pattern/routes" "fmt" "github.com/joho/godotenv" "os" ) // Starting server func main() { echo := routes.Routing.GetRoutes(routes.Routing{}) err := godotenv.Load() if err != nil { println(constant.MessageEnvironment) } env := os.Ge...
package validator import ( "fmt" ) // CheckRule is used for constuct error messages slice func CheckRule(errorArray *[]string, c bool, errMsg string, args ...interface{}) { if !c { if args != nil { *errorArray = append(*errorArray, fmt.Sprintf(errMsg, args...)) } else { *errorArray = append(*errorArray, f...
package main import "fmt" func main() { fmt.Println("countingSort") fmt.Println(countingSort([]int{3, 1, 0, 8, 5, 2, 4, 9, 7, 6, 1, 3}, 9)) } func countingSort(array []int, max int) []int { fmt.Println("starting array", array) res := make([]int, len(array)) counter := make([]int, max+1) for _, val := range arr...
package main /* * @lc app=leetcode id=143 lang=golang * * [143] Reorder List */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func reorderList(head *ListNode) { if head == nil || head.Next == nil { return } // Step 1: find m...
package main import ( "bufio" "fmt" "os" "strconv" ) // https://www.hackerrank.com/challenges/quicksort2 func main() { next := func() func() int { scan := bufio.NewScanner(os.Stdin) scan.Split(bufio.ScanWords) return func() int { scan.Scan() i, _ := strconv.Atoi(scan.Text()) return i } }() n...
package fram import "net/http" // Client - type Client struct { HostURL string HTTPClient *http.Client Token string } // AuthResponse - type AuthResponse struct { TokenId string `json:"tokenId"` SuccessUrl string `json:"successUrl"` Realm string `json:"realm"` } type BaseURLSource struct { Co...
package partitions import ( m "github.com/pedromss/kafli/model" "log" ) // IsEmpty will return true if all partitions have their latest offsets at 0 func IsEmpty(store *m.PartitionStore) bool { for _, v := range *store { if !PartitionIsEmpty(v.Lo, v.Hi) { return false } } return true } func TotalCount(s...
package aws type SqsClient struct { } func (c *SqsClient) GetList(qname string) map[string]interface{} { return nil }
package sns import "github.com/aws/aws-sdk-go/service/sns/snsiface" func NewTestSNSSink(snsapi snsiface.SNSAPI, topic string) *messageSink { return &messageSink{ client: snsapi, topic: topic, } }
package main import ( "fmt" ) func main() { s := "Hey 🤚!" // String literal stored in an UTF-8 file fmt.Printf("len=%d\n", len(s)) // Print characters for i := 0; i < len(s); i++ { fmt.Printf("%c ", s[i]) } fmt.Println("") // Print bytes for i := 0; i < len(s); i++ { fmt.Printf("%v ", s[i]) } }
package toolkit import ( "strings" ) // 生成指定范围内的有序整型切片 func GenerateSectionIntSliceOfOrderly(min, max int, step int) []int { result := make([]int, 0, max) for i := min; i <= max; i += step { result = append(result, i) } return result } // 生成指定范围内的无序整型切片 func GenerateSectionIntSliceOfDisorderly(min, max int) [...
package mem // A Step represents a strictly monotonically increasing step value. It is // stored as an int64, but must be non-negative. type Step int64 // StepIndexed describes values that are uniquely indexed by "step", a // non-negative integer that increases with time (potentially // non-consecutively). type StepI...
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //648. Replace Words //In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call th...
package main /* 给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值, 否则不为 NULL 的节点将直接作为新二叉树的节点。 */ func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode { return mergeTreesExec(t1, t2) } func mergeTreesExec(t1 *TreeNode, t2 *TreeNode) *TreeNode { if t1 == nil && t2 == ...
/*-------------------------------------------------------------- * package: 更新配置相关的服务 * time: 2018/05/10 *-------------------------------------------------------------*/ package api import ( "net/http" "github.com/gin-gonic/gin" "github.com/golang/glog" "sub_account_service/blockchain_server/config" "sub_acc...
// Copyright 2019 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 fetcher import ( "strings" "testing" "golang.org/x/net/html" ) type tokenTest struct { // The HTML to parse. html string // The string representations of the expected tokens, joined by '$'. expected string } var tokenTests = []tokenTest{ { `<a href="http://www.w3schools.com/html/">Visit our HTML t...
package segment import ( "encoding/json" "fmt" "net/http" "github.com/pkg/errors" ) // ListSources returns all sources for a workspace func (c *Client) ListSources() (Sources, error) { var s Sources data, err := c.doRequest(http.MethodGet, fmt.Sprintf("%s/%s/%s", WorkspacesEndpoint, c.workspace, SourceEndpoi...
package component // ////no-use // //import ( // "filemanager/mock" // "filemanager/model" // "github.com/rivo/tview" // "testing" // "time" //) // //var app *tview.Application //var filePreview *FilePreview //var eventChannel model.EventChannel //var fileRowDirectory *model.FileRow //var fileRowBigFile *model.FileRow...
package main import( "fmt" "math" "time" // "runtime" ) func main(){ fmt.Println("11") fmt.Println(pow(3,2,10)) fmt.Println(math.Pow(2,3)) fmt.Println(time.Now().Hour()) a := 12 p := &a fmt.Println(p) fmt.Println(Vertex{2,4}.x) m := []int{1,3,4,2,7} fmt.Println(m[1:2]) b := make([]int,5) fmt.Println(b) var c []in...
package cmd import ( "crypto/tls" "fmt" "io/ioutil" "os" "github.com/dkorittki/loago/internal/pkg/instructor/client" "github.com/dkorittki/loago/pkg/instructor/config" "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" ) var instructor *client.Client // instructCmd represen...
package api_server import ( "github.com/emicklei/go-restful" "github.com/kumahq/kuma/pkg/version" ) func versionsWs() *restful.WebService { ws := new(restful.WebService).Path("/versions") ws.Route(ws.GET("").To(func(req *restful.Request, resp *restful.Response) { resp.AddHeader("content-type", "application/js...
package dao import ( "go.mongodb.org/mongo-driver/bson" "time" ) // UpdateUser 修改用户数据 func (m *UserDao) UpdateUser(filter, data interface{}) (int64, error) { result, err :=m.dao.UpdateOne(m.ctx, filter, bson.M{"$set": data}) if err != nil { return 0, err } return result.ModifiedCount, nil } // Login 登录 func ...
package main import ( "fmt" ) func main() { s := "hello" s = "c" + s[1:] // 字符串虽不能更改,但可进行切片操作 fmt.Printf("%s\n", s) }
package db import ( "sort" "sync" "github.com/messagedb/messagedb/db/internal" "github.com/gogo/protobuf/proto" ) //go:generate protoc --gogo_out=. internal/meta.proto const ( maxStringLength = 64 * 1024 ) // Conversation represent unique series messages in a database type Conversation struct { mu s...
package api import ( "WAF/middlewares" "WAF/models" "WAF/utils" "strconv" "github.com/gin-gonic/gin" ) // @Tags User // @Summary 用户信息 // accept json // produce json // @Success 200 {string} string "ok" // @Router /user/ [get] func User(c *gin.Context) { claims, _ := c.Get("claims") waitUse := claims.(*middle...
package main import ( "testing" ) func TestClimbStairs(t *testing.T) { }