text
stringlengths
11
4.05M
/* * @lc app=leetcode.cn id=239 lang=golang * * [239] 滑动窗口最大值 */ package main import "fmt" // @lc code=start func maxSlidingWindow(nums []int, k int) []int { numsLen := len(nums) if numsLen < 2 { return nums } // 存数字下标 queue := make([]int, 0, k) ans := make([]int, 0, numsLen-k+1) for i, v := range nums {...
/* Copyright 2021 The Nuclio 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, soft...
package main import ( "github.com/jorgenpo/stayfit-server/config" "log" "os" "github.com/jorgenpo/stayfit-server/database" "github.com/jorgenpo/stayfit-server/server" ) func main() { serverConfig, err := config.GetConfig() if err != nil { log.Fatalf("Failed to load config file: %e", err) os.Exit(1) } se...
package goecharts import ( "encoding/json" "fmt" "reflect" gf "github.com/wanglovesyang/gframe" ) type BarSettings struct { Title string `json:"title"` TruncPrecision int32 `json:"trunc_precision"` HideMarkPoint bool `json:"hide_markpoint"` HideMarkLine bool `json:"hide_markline"` } func pa...
package tpl // 指定package是tpl,我们写自定义的模板的时候,也需要指定为tpl const ltgtTpl = `{{ $f := .Field }}{{ $r := .Rules }} // 使用模板的时候,会传入相应的RulesContext,Filed和Rules是其的字段,定义变量f,r,f是域,r是规则 {{ if $r.Lt }} // 看r的Lt是否有,如果有看是否有Gt {{ if $r.Gt }} // 判断r是否设置了Gt这个规则 {{ if gt $r.GetLt $r.GetGt }} // 如果小于的数字大于大于的数字,那ok // 通过accessor . ...
package ircserver import ( "fmt" "strings" "gopkg.in/sorcix/irc.v2" ) func init() { Commands["server_KILL"] = &ircCommand{ Func: (*IRCServer).cmdServerKill, MinParams: 1, } } func (i *IRCServer) cmdServerKill(s *Session, reply *Replyctx, msg *irc.Message) { if len(msg.Params) < 2 { i.sendServices(r...
package fsnotify // no-op on Windows
package train import ( "github.com/y4v8/errors" ) type ParamsRoute struct { From string `url:"routes[0][from]"` To string `url:"routes[0][to]"` Date string `url:"routes[0][date]"` Train string `url:"routes[0][train]"` } type DataRoute struct { Tpl string `json:"tpl"` Routes []TrainRoute `json:"r...
package resources import ( "errors" "fmt" ) var resourceTypes []Resource func InitResourcesForPersonage(personageId int64) error { checkConnection() columns := []string{"resource_id", "personage_id", "amount"} data := make([][]interface{}, len(resourceTypes)) for i := 0; i < len(data); i++ { data[i] = make([...
package models import ( "fmt" "github.com/jinzhu/gorm" "time" ) type Cate struct { ID int `gorm:"primary_key" json:"id"` Name string `json:"name"` State int `json:"state"` CreatedOn int `json:"created_on"` ModifiedOn int `json:"modified_on"` } // 获取所有栏目 func GetCates(name stri...
package server import ( "errors" "net/http" "golang.org/x/net/context" "github.com/Sirupsen/logrus" "github.com/bryanl/dolb/dao" "github.com/bryanl/dolb/do" "github.com/bryanl/dolb/dolbutil" "github.com/bryanl/dolb/kvs" "github.com/bryanl/dolb/pkg/app" "github.com/bryanl/dolb/service" "github.com/gorilla/...
package httpserver import ( "context" "encoding/json" "io/ioutil" "log" "net/http" "strconv" "github.com/ekotlikoff/gochess/internal/model" matchserver "github.com/ekotlikoff/gochess/internal/server/backend/match" gateway "github.com/ekotlikoff/gochess/internal/server/frontend" ) // HTTPBackend handles http...
package responses import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) func TestDecodeAccountsPendingResponse(t *testing.T) { encoded := "{\n \"blocks\" : {\n \"nano_1111111111111111111111111111111111111111111111111117353trpda\": [\"142A538F36833D1CC78B94E11C766F75818F8B940771335C6C1B8AB...
package main import "fmt" import "math" import "strconv" import "strings" import "regexp" func main() { fmt.Println(ControlCode( "7904006306693", "876814", "1665979", "20080519", "35959", "zZ7Z]xssKqkEf_6K9uH(EcV+%x+u[Cca9T%+_$kiLjT8(zr3T9b5Fx2xG-D+_EBS", )) //output: 7B-F3-48-A8 } func verhoeff(num st...
package context import ( "log" "github.com/jinzhu/gorm" "github.com/kivutar/chainz/model" // Side effect import of postgres _ "github.com/jinzhu/gorm/dialects/postgres" ) // OpenDB creates the connection to the database func OpenDB(config *Config) (*gorm.DB, error) { log.Println("Database is connecting... ") ...
package register import "github.com/MintegralTech/juno/operation" var FieldMap map[string]operation.Operation type Register struct { } func NewRegister() *Register { FieldMap = make(map[string]operation.Operation, 16) return &Register{} } func (r *Register) Register(fieldName string, e operation.Operation) { Fi...
package main import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "os/exec" "strings" "time" "github.com/docker/docker/client" "github.com/gorilla/mux" ) var PORT string func init() { PORT = os.Getenv("PORT") if len(PORT) == 0 { PORT = "8080" } } func main() { // Create Server and Route ...
package handlers import ( "time" cors "github.com/rs/cors/wrapper/gin" "api-gaming/internal/config" "github.com/gin-gonic/gin" "context" "github.com/shaj13/go-guardian/auth" "github.com/shaj13/go-guardian/auth/strategies/bearer" "github.com/shaj13/go-guardian/store" ) var router = gin.Default() var authentica...
package caaa import ( "encoding/xml" "github.com/thought-machine/finance-messaging/iso20022" ) type Document00400104 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.004.001.04 Document"` Message *AcceptorCompletionAdviceResponseV04 `xml:"AccptrCmpltnAdvcRspn"` } f...
package common // Skips duplicate messages (based on .ID) func Dedup(messageChan chan LogMessage) chan LogMessage { resultChan := make(chan LogMessage) idCache := make(map[string]bool) go func() { for message := range messageChan { if !idCache[message.ID] { resultChan <- message idCache[message.ID] = t...
func fac(x int,y int) int { if x < 1 { return 1 } else { y:=fac(x-1); z := a * b; return x * y } } { x := fac(1,false); y := fac() }
package util import "encoding/binary" func HostTo2Net(n uint16) []byte { b := make([]byte, 2) binary.BigEndian.PutUint16(b, n) return b } //主机序网络序互转 func HostTo4Net(n uint32) []byte { b := make([]byte, 4) binary.BigEndian.PutUint32(b, n) return b } //主机序网络序互转 func HostTo8Net(n uint64) []byte { b := make([]by...
package repository; // UserRepository handles user manipulations in the database type UserRepository struct { } // ProvideUserRepository is the provider for UserRepository func ProvideUserRepository() (*UserRepository, error) { return &UserRepository{}, nil }
/* * Work on parallel processing * * */ package main import ( "bufio" "fmt" "os" "strings" "strconv" ) func main() { // Printing to the command line // fmt.Println(buildCorrectedGFF("incorrectFormat.gff")) // Call buildCorrectedGFF buildCorrectedGFF("inccorectlyFormated.gff") } /* * This function will at...
package frida_go import ( "github.com/a97077088/frida-go/cfrida" "unsafe" ) const ( RELAY_KIND_TURN_UDP = iota RELAY_KIND_TURN_TCP RELAY_KIND_TURN_TLS ) type RelayKind int type Relay struct { CObj } func (r *Relay) Free() { cfrida.G_object_unref(r.instance) } // NewRelay // 新建一个对象来自已经存在的对象实例指针。 // // Create ...
package main import "log" import "net/http" func checkLinks( urls []string) { c := make(chan string) for _, url := range urls { go checkLink(url, c) } reportFails := 0 for i:= 0; i < len(urls); i++ { if ("success" != <-c) { reportFails += 1 } } if reportFails > 0 { log.Printf("Encountered %d failure...
package main import ( "fmt" "net" "io" "flag" ) func handleConn(conn *net.TCPConn, raddr *net.TCPAddr) { remote, err := net.DialTCP("tcp", nil, raddr) if err != nil { fmt.Println("dial remote fail. err:", err) conn.Close() return } finish := make(chan bool,...
package rest import ( "io/ioutil" "net/http" "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/utils" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/keyerror" "github.com/cosmos/cosmos-sdk/x/auth" authtxb "github.com/cosmos/cosmos-sdk/x/auth/cli...
//宣告程式屬於哪個package package main //引入套件 import ( "fmt" ) //常數宣告 const ip string = "127.0.0.1" var ip2 string = "" //主程式 func main(){ //使用:= 簡化變數宣告 var word string = "Hello World!!" word := "Hello World!!" //使用fmt 套件印出字串word fmt.Println(word) fmt.Println("MyIp:"+ip) //change my ip const can't ...
// Package syncutil contains methods for working with sync code. package syncutil import ( "sync" ) // A OnceMap is a collection sync.Onces accessible by a key. The zero value is usable. type OnceMap[T comparable] struct { mu sync.Mutex m map[T]*sync.Once } // Do runs f once. func (o *OnceMap[T]) Do(key T, f fun...
package main import ( "database/sql" "fmt" "os" _ "github.com/lib/pq" "net/http" "encoding/json" ) func main() { http.HandleFunc("/", getAll) PORT := getenv("PORT", "9100") http.ListenAndServe(":" + PORT, nil) } func getenv(key, fallback string) string { if value, ok := os.LookupEnv(key); ok { ...
package components import ( "html/template" "github.com/GoAdminGroup/go-admin/plugins/admin/modules" "github.com/GoAdminGroup/go-admin/template/types" ) type ImgAttribute struct { Name string Width string Height string Uuid string HasModal bool Src template.URL types.Attribute } func (co...
package rateutil import ( "math" "sync" "sync/atomic" "time" ) //Rate ... type Rate struct { requestsCount []int64 responseTimeSum []int64 } var rate *Rate var once sync.Once //GetRateCounter ... func GetRateCounter() *Rate { once.Do(func() { rate = &Rate{ requestsCount: make([]int64, 2), respons...
package main import "fmt" func main() { arrays := []int{1,2,232,454,2323,354,5656,434354} maximum := arrays[0] for _,num := range arrays { if num > maximum { maximum = num } } fmt.Println(maximum) }
package admin import ( "github.com/apache/thrift/lib/go/thrift" "github.com/go-xe2/x/type/t" "github.com/go-xe2/xthrift/pdl" ) type RegSvcUpdateResultArgs struct { *pdl.TDynamicStructBase RegId int32 `thrift:"reg_id,1,required" json:"reg_id"` ParId int32 `thrift:"par_id,2,required" json:"par_...
package types import ( "bytes" "encoding/json" "errors" "time" "github.com/shopspring/decimal" ) const ( DateFormat = "2006-01-02" DatetimeFormat = "2006-01-02 15:04:05" ) type Date struct { time.Time Empty bool } func (t *Date) UnmarshalJSON(data []byte) error { if string(data) == "null" { return ...
// Copyright 2018 The go-bindata Authors. All rights reserved. // Use of this source code is governed by a CC0 1.0 Universal (CC0 1.0) // Public Domain Dedication license that can be found in the LICENSE file. package bindata import ( "os" "path/filepath" "unicode" ) // asset holds information about a single asse...
package repository import ( "database/sql" "fmt" "github.com/jinzhu/gorm" "github.com/radyatamaa/loyalti-go-echo/src/database" "github.com/radyatamaa/loyalti-go-echo/src/domain/model" "github.com/sirupsen/logrus" ) type SpecialProgramRepository interface { CreateSpecial(special *model.SpecialProgram) error U...
package main import ( "fmt" "io/ioutil" "net/http" ) func main(){ res,err:=http.Get("https://www.baidu.com") if err!=nil{ fmt.Println("http.Get err",err) return } buf,err:=ioutil.ReadAll(res.Body) if err!=nil{ fmt.Println("ioutil.ReadAll err",err) return } fmt.Println(string(buf[:])) }
package pg import ( "github.com/kyleconroy/sqlc/internal/sql/ast" ) type RangeSubselect struct { Lateral bool Subquery ast.Node Alias *Alias } func (n *RangeSubselect) Pos() int { return 0 }
package main // START OMIT func (cp *connectionPool) GetWithTimeout(d time.Duration) (rv *memcached.Client, err error) { // short-circuit available connetions select { case rv, isopen := <-cp.connections: if !isopen { return nil, errClosedPool } return rv, nil default: } // END OMIT // START P2 OMIT ...
package common const ( GreetingFormat = "hello,%s!\n" Math = "math" English = "english" Chinese = "chinese" )
package mppuma import ( "flag" mp "github.com/mackerelio/go-mackerel-plugin" ) // PumaPlugin mackerel plugin for Puma type PumaPlugin struct { Prefix string Host string Port string Sock string Token string Single bool WithGC bool } func merge(m1, m2 map[string]float64) map[string]float64 { ans := m...
package main import ( "crypto/x509" "fmt" ) func main() { pubB := []byte{48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45, 3, 66, 0, 4, 233, 114, 166, 49, 76, 93, 192, 127, 172, 110, 4, 122, 99, 20, 48, 45, 11, 46, 233, 77, 11, 54, 86, 19, 235, 137, 78, 117, 34, 23, 193, 45...
package coinmarketcap_go import ( "context" "encoding/json" "errors" "fmt" "github.com/drankou/coinmarketcap-go/types" "github.com/google/go-querystring/query" log "github.com/sirupsen/logrus" "golang.org/x/time/rate" "io/ioutil" "net/http" "os" ) const ( API_URL = "https://pro-api.coinmarketcap.com" ...
package Proxy import ( "fmt" "strconv" ) type ITask interface { RentHouse(desc string,price int) } type Task struct { } func (t *Task) RentHouse(desc string,price int) { fmt.Println(fmt.Sprintf("租房地址%s,价格%s",desc,strconv.Itoa(price))) } //代理 type AgentTask struct { task *Task } func NewAgentTask() *AgentTa...
package frac // Div divides two fractions. func Div(frac1 Frac, frac2 Frac) Frac { // Adjust fractions to common denominator. num := frac1.Num * frac2.Den den := frac1.Den * frac2.Num // Yield result. return Frac{num, den} }
package eglm import ( "bytes" "fmt" "github.com/GameWith/gwlog/formatter" "net/http" "net/http/httptest" "strings" "testing" "github.com/GameWith/gwlog" "github.com/labstack/echo/v4" ) func TestMiddleware(t *testing.T) { e := echo.New() buf := new(bytes.Buffer) logger := gwlog.GetLogger() logger.SetOutp...
package first import ( "fmt" "go/ast" "reflect" ) type DumpVisitor struct { } func (visitor DumpVisitor) Visit(node ast.Node) ast.Visitor { fmt.Println(reflect.TypeOf(node)) return visitor }
package service import ( "github.com/roberthafner/bpmn-engine/domain/model" "github.com/roberthafner/bpmn-engine/domain/model/command" ) type DeploymentService interface { CreateDeployment(d model.DeploymentEntity) model.DeploymentEntity } func NewDeploymentService(ce command.CommandExecutor) DeploymentService { ...
package main import ( "github.com/Shopify/sarama" "log" ) var config = sarama.NewConfig() var localKafka = []string{"127.0.0.1:9093"} func init() { config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Partitioner = sarama.NewRandomPartitioner config.Producer.Return.Successes = true } func main() {...
package main import ( "fmt" ) func captured() (i int) { i = 1 defer func(j int) { fmt.Println("captured defer:", j) }(i) i++ return } func pointer() (i int) { i = 1 defer func(j *int) { fmt.Println("pointer defer:", *j) }(&i) i++ return } func latest() (i int) { i = 1 defer func() { fmt.Pr...
package arima import ( "math" "github.com/DoOR-Team/goutils/log" mtx "github.com/DoOR-Team/timeseries_forecasting/arima/matrix" "github.com/DoOR-Team/timeseries_forecasting/arima/utils" ) const maxIterationForHannanRissanen = 5 type Solver struct { } func newSolver() *Solver { return &Solver{} } func forecas...
// Copyright 2016 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 handlers import ( "crypto/md5" "encoding/hex" "encoding/json" "net/http" "github.com/sirupsen/logrus" "github.com/vitorfhc/heimdall/auth" "github.com/vitorfhc/heimdall/gql" ) type loginJSON struct { Username string Password string } func AuthHandler(w http.ResponseWriter, req *http.Request) { logr...
package main import ( "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" // "log" "fmt" "net/http" //"time" ) func mwAdmin() gin.HandlerFunc { return func(c *gin.Context) { c.Next() } } func mwIsUser() gin.HandlerFunc { return func(c *gin.Context) { session := sessions.Default(c) v := sessio...
// Copyright 2020 MongoDB 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...
package BLC import "fmt" // 查询余额 先用它去 查询 余额 func (cli *Cli) getBalance(address string) { fmt.Println("") blockchain := BlockChainObject() defer blockchain.DB.Close() amount := blockchain.GetBalance(address) fmt.Println(amount) }
package creator import ( "context" "regexp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/argoproj/argo/server/auth" "github.com/argoproj/argo/util/labels" "github.com/argoproj/argo/workflow/common" ) func Label(ctx context.Context, obj metav1.Object) { claims := auth.GetClaimSet(ctx) if claims ...
package main import ( "fmt" "io/ioutil" "itops/hpmsa_exporter/collector" "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prometheus/common/log" "github.com/prometheus/common/version" kingpin "gopkg.in/alecthomas/kingpin.v2" ya...
/* * @lc app=leetcode.cn id=1030 lang=golang * * [1030] 距离顺序排列矩阵单元格 */ package solution // @lc code=start // BFS func allCellsDistOrder(R int, C int, r0 int, c0 int) (ans [][]int) { dirs := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} // up, down, left, right q := [][]int{} q = append(q, []int{r0, c0}) visited :...
package cli import ( "bytes" "fmt" "os" "os/exec" "testing" "github.com/scaleway/scaleway-cli/pkg/commands" . "github.com/smartystreets/goconvey/convey" ) func testHelpOutput(out string, err string) { // headers & footers So(out, ShouldContainSubstring, "Usage: scw [OPTIONS] COMMAND [arg...]") So(out, Shou...
package main import ( "flag" "fmt" "os" ) func usage() { pf := func(format string, a ...interface{}) { fmt.Fprintf(flag.CommandLine.Output(), format, a) } pln := func(s string) { fmt.Fprintln(flag.CommandLine.Output(), s) } pf("Usage of %s [options] <filename>\n\n", os.Args[0]) pln("Options:\n") flag.P...
package concurrent import ( "container/list" "sync" ) /* 安全的链表队列 */ type LinkedQueue struct { store *list.List mutex *sync.Mutex } /* 创建队列 */ func NewLinkedQueue() *LinkedQueue { return &LinkedQueue{store: list.New()} } /* 压入队列 */ func (q *LinkedQueue) Push(e interface{}) error { q.mutex.Lock() defer q.mut...
package Problem0483 import ( "math" "strconv" ) func smallestGoodBase(n string) string { num, _ := strconv.ParseUint(n, 10, 64) // num = k^m + k^(m-1) + ... + k + 1 // 想要找到最小的 k // 可知 k 变小的时候,m 会变大 // k 最小可以是 2,即是 二进制 // k == 2 时,m == mMax mMax := int(math.Log2(float64(num))) // 从 mMax 开始往下检查,对应的 k 能否满足题意 ...
package uikit import ( "github.com/maxence-charriere/go-app/v7/pkg/app" ) // UIAccordionItem is a component type UIAccordionItem interface { app.UI // Class adds a CSS class to the section. Class(c string) UIAccordionItem // Title defines and styles the toggle for accordion item Title(v string) UIAccordionIte...
package bytemap type valuesIF interface { get(idx int) interface{} } type interfaceValues []interface{} func (iv interfaceValues) get(idx int) interface{} { return iv[idx] } type floatValues []float64 func (fv floatValues) get(idx int) interface{} { return fv[idx] }
package kvraft import ( "../labgob" "../labrpc" "log" "../raft" "sync" "sync/atomic" "bytes" "time" ) const Debug = 0 func DPrintf(format string, a ...interface{}) (n int, err error) { if Debug > 0 { log.Printf(format, a...) } return } const ( GET = "Get" PUT = "Put" APPEND = "Append" ) // 具体操作内...
package log import ( "bytes" "io" "strings" "testing" "go.uber.org/zap" "go.uber.org/zap/zapcore" "go.uber.org/zap/zaptest/observer" ) func TestLog(t *testing.T) { f := &bytes.Buffer{} SetLogJSON(false) SetOutput(f) Printf("hello %v", "everyone") if !strings.HasSuffix(f.String(), "hello everyone\n") { ...
package streamdal import ( "encoding/json" "fmt" "github.com/pkg/errors" ) // DestinationOutput is used for displaying destinations as a table type DestinationOutput struct { Name string `json:"name" header:"Name"` ID string `json:"id" header:"Destination ID"` Type string `json:"type" header:"Typ...
package main import ( "fmt" "io/ioutil" "log" "os" "time" "github.com/pandada8/logd/lib/common" "github.com/pandada8/logd/lib/dumper" "github.com/DataDog/zstd" "github.com/go-redis/redis" "github.com/spf13/viper" ) type DumperBridge struct { redis *redis.Client redisCluster *redis.ClusterClient ...
package isogen import ( "context" "fmt" "os" "path/filepath" "strings" "opendev.org/airship/airshipctl/pkg/bootstrap/cloudinit" "opendev.org/airship/airshipctl/pkg/container" "opendev.org/airship/airshipctl/pkg/document" "opendev.org/airship/airshipctl/pkg/errors" "opendev.org/airship/airshipctl/pkg/log" "...
package internal var ( // PostgresVersionKey is the query's store key used to set the postgres server version. PostgresVersionKey = pgversion{} // IncrementorKey is the scope's context key used to save current incrementor value. IncrementorKey = incrementorKey{} ) type pgversion struct{} type incrementorKey struc...
package main import ( "fmt" "os" "bufio" "strconv" ) func main() { f, _ := os.Open("input.txt") defer f.Close() scanner := bufio.NewScanner(f) freqChanges := make([]int, 0) freqMap := make(map[int]int) for scanner.Scan() { change, _ := strconv.Atoi(scanner.Text()) ...
package database import ( "database/sql" "fmt" "log" ) func Connect(databasename string) *sql.DB { db, err := sql.Open("mysql", "root:pass@(localhost:3306)/"+databasename) if err != nil { log.Fatal(err) } fmt.Println("connected") return db }
package main import ( "log" "net" "os" "os/signal" "sync" "syscall" "time" ) // support for reloading configuration without restarting Redwood var configRequests = make(chan chan *config) // getConfig returns the current configuration. func getConfig() *config { ch := make(chan *config) configRequests <- c...
package main import "fmt" func main1001() { //append() //copy() var s []int = []int{1,2,3,4,5} //s1 := make([]int,5) s1 := []int{6,7,8,9} copy(s,s1) fmt.Println(s1) //使用copy进行拷贝 在内存中存储两个独立的切片内容 如果任意一个发生修改 不会影响到另一个 fmt.Printf("%p\n",s) fmt.Printf("%p\n",s1) s1[2] = 123 fmt.Println(s) fmt.Println(s1) ...
package common import "errors" var ( // Database Related Error ErrNoConnectionProvider = errors.New(ErrorMessageNoConnectionProvider) ErrNoTransactionFunction = errors.New(ErrorMessageNoTransactionFunction) ErrNotExist = errors.New(ErrorMessageNotExist) ErrAlreadyExist = errors.New(ErrorMessa...
package ratelimiters import ( "sync" "time" "github.com/corverroos/ratelimit" ) // Coffee rate limiter is a WIP. func NewCoffee(period time.Duration, limit int) *Coffee{ return &Coffee{ period: period, limit: limit, nowFunc: time.Now, mm: newMapMutex(), counts: map[string]burst{}, } } type burst s...
// Package bootstrap provides a cluster-destroyer for Bootstrap node package bootstrap
package main import ( "log" "net/http" "os" "text/template" "github.com/gorilla/sessions" _ "github.com/lib/pq" ) var tmpl *template.Template var ( port = ":80" certFilePath = "" keyFilePath = "" appDir = "" logFile = os.File{} key = []byte("087736079f8d9e4c7fc7b642bb4c7afa") st...
package main import ( "github.com/gin-gonic/gin" "flag" "os" "net/http" "os/exec" "time" "fmt" ) func main() { port := flag.String("port","","默认监听端口8080, 设置监听端口示例:\r\n\t./monitor -port 9999\r\n") flag.String("启动监控","","参数n:name 生成报告的文件名\r\n\t参数t:time 监控时长,单位分钟\r\n\tget示例:http://192.168.x.x:8080/start?n=test&t=...
package app import ( "log" "regexp" ) var pattern *regexp.Regexp func init() { var err error pattern, err = regexp.Compile("[^a-zA-z0-9]+") if err != nil { log.Fatal(err) } } func StripURL(url string, result chan string) { result <- pattern.ReplaceAllString(url, "") }
package main import ( "fmt" "testing" ) func TestIsLongPressedName(t *testing.T) { ans := IsLongPressedName("alex", "aaleex") fmt.Println(ans) }
package users import ( "github.com/jakewitcher/pos-server/graph/model" "strconv" ) type UserEntity struct { Id int64 `json:"id"` EmployeeId int64 `json:"employee_id"` Username string `json:"username"` Password string `json:"password"` } func (u *UserEntity) ToDTO() *model.User { return &model.Us...
package remote import ( "fmt" "reflect" "regexp" ) func Format(str string, data interface{}) string { var par = map[string]string{} var val = reflect.ValueOf(data) val = reflect.Indirect(val) switch val.Kind() { case reflect.Map: for _, k := range val.MapKeys() { var v = val.MapIndex(k) par[fmt.Sprint...
package ciolite // Api functions that support: users/email_accounts/folders/messages import ( "bytes" "encoding/json" "fmt" "net/url" ) // GetUserEmailAccountsFolderMessageParams query values data struct. // Optional: Delimiter, IncludeBody, BodyType, IncludeHeaders, IncludeFlags, // and (for GetUserEmailAccount...
package store import ( "fmt" "github.com/go-redis/redis" ) type Redis struct { conf *Config } func (s *Redis) Get() *redis.Client { redisOnce.Do(func() { redisClient = redis.NewClient(&redis.Options{ Addr: fmt.Sprintf("%s:%d", s.conf.Get().Redis.Host, s.conf.Get().Redis.Port), Password: s.conf.Get()....
package domain import ( "time" "github.com/gofrs/uuid" ) type FarmCreated struct { UID uuid.UUID Name string Type string Latitude string Longitude string Country string City string IsActive bool CreatedDate time.Time } type FarmNameChanged struct { FarmUID uuid.U...
// Copyright 2020 The Kubernetes Authors. // SPDX-License-Identifier: Apache-2.0 package v1alpha1 import ( "k8s.io/apimachinery/pkg/runtime" "regexp" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "kmodules.xyz/client-go/apiextensions" "x-helm.dev/apimachinery/apis/shared" "x-helm.dev/apimachinery/cr...
package client import ( "encoding/json" "fmt" "io" "net/http" "net/url" "path" "strings" ) type ApiClient struct { Http *http.Client config *Config } func New(config *Config) (*ApiClient, error) { h := &http.Client{} if err := validateConfig(config); err != nil { return nil, err } a := &ApiClient{Ht...
package cmds import ( "flag" "fmt" "io/ioutil" "os" "strings" "github.com/appscode/go/log" stringz "github.com/appscode/go/strings" "github.com/appscode/kutil/tools/analytics" pcm "github.com/coreos/prometheus-operator/pkg/client/monitoring/v1" cs "github.com/kubedb/apimachinery/client/clientset/versioned/t...
package config import ( "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/session" "github.com/gofiber/storage/dynamodb" "github.com/gofiber/storage/memcache" "github.com/gofiber/storage/memory" "github.com/gofiber/storage/mongodb" "github.com/gofiber/storage/mysql" "github.com/gofiber/stor...
package hello_service type HelloService struct { } // Hello 方法的输入参数和 输出参数均改用 protobuf 定义的String类型表示 func (p *HelloService) Hello(request *String ,reply *String)error { reply.Value="Hello:-->"+request.Value return nil }
package server import ( "context" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "errors" "fmt" "io" "math/big" "net" "testing" "time" "github.com/dkorittki/loago/pkg/api/v1" "github.com/grpc-ecosystem/go-grpc-middleware/util/metautils" "github.com/stretchr/testify/assert" "...
// 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" func main() { inputArray := []int{1, 2, 3, 4, 5, 6, 7, 8} count := 1 for len(inputArray) != 1 { if count%2 == 0 { var temp []int for i := 0; i < len(inputArray)-1; i += 2 { temp = append(temp, inputArray[i]*inputArray[i+1]) } inputArray = make([]int, len(temp)) copy(...
package main import "fmt" /* Adding comments */ func main() { fmt.Println("Hi There!") }
package main import ( "bufio" "fmt" "io" "log" "os" "strings" ) func main() { if len(os.Args) < 2 { fmt.Printf("Usage: %s <file>\n", os.Args[0]) return } in, err := os.Open(os.Args[1]) if err != nil { log.Fatal(err) } defer in.Close() br := bufio.NewReader(in) for { line, c := br.ReadString('\n'...
package flatten func Flatten(list interface{}) []interface{} { if list == nil { return []interface{}{} } else if _, ok := list.([]interface{}); !ok { return []interface{}{list} } collection := make([]interface{}, 0) for _, element := range list.([]interface{}) { collection = append(collection, Flatten(ele...