text
stringlengths
11
4.05M
package main import ( "fmt" "io" "os" ) type ( Logger interface { Println(msg string) Printf(format string, args ...interface{}) } Service struct { logger Logger repository interface{ Save(string) bool } service int } simpleLogger struct { w io.Writer } ) func main() { f, _ := os.Creat...
package main import ( "fmt" "log" "net" ) func main() { listener, e := net.Listen("tcp", "192.168.20.23:8888") if e != nil { log.Fatal(e) } defer listener.Close() for { conn, e := listener.Accept() if e != nil { log.Fatal(e) } fmt.Printf("访问客户端信息: con=%v 客户端ip=%v\n", conn, conn.RemoteAddr().Strin...
package operation import ( "testing" ) func TestSquareMatrix(t *testing.T) { t.Run("return error if number of cols are greater than rows", func(t *testing.T) { matrix := [][]string{ {"1","2","3"}, {"4","5","6"}, } err := squareMatrix(matrix) assertError(t, err, errInvalidMatrix) }) t.Run("return err...
package hashicups import ( "strconv" hc "github.com/hashicorp-demoapp/hashicups-client-go" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) func dataSourceOrder() *schema.Resource { return &schema.Resource{ Read: dataSourceOrderRead, Schema: map[string]*schema.Schema{ "id": &schema.Schema{ ...
package queue type SimpleQueue struct { linkedList.List }
// Package storage provide generic interface to interact with storage backend. package storage import ( "context" "errors" "strings" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/anypb" "github....
package sort type Interface interface { Len() int Less(i, j int) bool // x, j are indices of sequence elements Swap(i, j int) } /* 其他数据类型使用sort.Sort(pama)时, 只需要定义里面的三个函数, 如stringsort.go所示 */
package cron // Cron instance var CronInst Cron func init() { CronInst = NewCron() CronInst.Start() }
package con import ( "github.com/GanymedeNil/shorturl/config" "github.com/garyburd/redigo/redis" "log" ) var redisConn *redis.Conn func Redis() redis.Conn { if redisConn != nil { return *redisConn } address := config.Get("redis.default") c, err := redis.Dial("tcp", address.(string)) if err != nil { log....
package main var lastSum int func convertBST(root *TreeNode) *TreeNode { lastSum = 0 convertBSTExec(root) return root } func convertBSTExec(root *TreeNode) { if root == nil { return } convertBSTExec(root.Right) root.Val += lastSum lastSum = root.Val convertBSTExec(root.Left) } /* 题目链接: https://leetcod...
package models import "time" type Thread struct { Slug *string `json:"slug,omitempty"` Author *string `json:"author"` Author_id *int `json:"author_id,omitempty"` Created *time.Time `json:"created,omitempty"` Forum *string `json:"forum"` Forum_id *int `json:"forum_id,omitempty"` Id *...
package app import ( "fmt" "net/http" ) type StreamService struct { } func NewStreamService() StreamService { return *new(StreamService) } func (s *StreamService) ServeHlsM3u8(w http.ResponseWriter, r *http.Request, videoId string, m3u8Name string) { mediaBase := s.getMediaBase(videoId) mediaFile := fmt.Sprin...
package main import ( "fmt" "time" "math/rand" ) func UnThreadedMergeSorted(left []int, right []int) []int{ var result []int for (len(left) > 0) && (len(right) > 0){ if(left[0] > right[0]){ result = append(result, right[0]) right = right[1:len(right)] }else{ result = append(result,left[0]) left =...
package install import ( "fmt" "reflect" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/a...
package ratelimit import ( "log" "github.com/prometheus/client_golang/prometheus" "go.bmvs.io/ynab" ) var ( rateLimitUsed = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "rate_limit_used", Help: "Rate limit used of YNAB API", }) rateLimitTotal = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "rate_lim...
package main import ( "fmt" intcode "github.com/seizethedave/advent2019/advent02" ) const ( target = 19690720 ) func main() { memory := []intcode.Word{1, 0, 0, 3, 1, 1, 2, 3, 1, 3, 4, 3, 1, 5, 0, 3, 2, 13, 1, 19, 1, 19, 10, 23, 1, 23, 13, 27, 1, 6, 27, 31, 1, 9, 31, 35, 2, 10, 35, 39, 1, 39, 6, 43, 1, 6, 43...
// Copyright (c) 2019 Aiven, Helsinki, Finland. https://aiven.io/ package aiven import ( "fmt" "github.com/aiven/aiven-go-client" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) func datasourceServiceIntegrationEndpoint() *schema.Resource { return &schema.Resource{ Read: datasourceServiceIntegrat...
package main import "fmt" func main() { fmt.Println("------事先声明cap的情况------") var numbers = make([]int, 3, 5) fmt.Printf("len = %d, cap = %d, slice = %v\n", len(numbers), cap(numbers), numbers) // 向切片追加一个元素1 numbers = append(numbers, 1) fmt.Printf("len = %d, cap = %d, slice = %v\n", len(numbers), cap(numbers)...
// TODO exec this main function by another main package main import ( "testing" // ref: https://github.com/golang/go/blob/bb998747d6c5213e3a366936c482e149dce62720/src/cmd/go/internal/load/test.go#L616 // Todo import path //{{if .ImportTest}} //{{if .NeedTest}}_test{{else}}_{{end}} {{.Package.ImportPath | printf "...
package models type INFOTEMP struct { TASKID string `gorm:"type:varchar(128);"` COUNT int //COLLECTED_COUNT int //INSERT_COUNT int //PAGE_COUNT int //COUNT_NULL int } type INFO struct { //ID int `gorm:"cloumn:id"` //URL string `gorm:"cloumn:url"` //TITLE ...
package tpl import ( "crypto/rand" "encoding/hex" "fmt" "os" ) // CheckIfError should be used to naively panics if an error is not nil. func CheckIfError(err error) { if err == nil { return } fmt.Printf("\x1b[31;1m%s\x1b[0m\n", fmt.Sprintf("error: %s", err)) os.Exit(1) } func randomHex(n int) (string, err...
package controllers import ( "encoding/json" "github.com/kataras/iris/context" "gocherry-api-gateway/components/common_enum" "gocherry-api-gateway/components/etcd_client" "gocherry-api-gateway/components/utils" ) type ClusterSaveReq struct { ClusterName string `json:"cluster_name"` Title string `json:"ti...
package main import "math" func Max(a int, b int) int { if a > b { return a } else { return b } } func Min(a int, b int) int { if a < b { return a } else { return b } } // return the index of max element instead of its value func MaxElement(list []int) int { idx := 0 max := math.MinInt32 for i, e :...
package products const ( SparkPastaName = "SparkPastaName" SparkPastaValue = 35 ) var ( SparkPasta = &Product{ Name: SparkPastaName, Value: SparkPastaValue, } ) type Product struct { Name string Value int } type Repository interface { Add(*Product) error List() map[string][]*Product Check(*Product) ...
package mqops import ( "encoding/json" "github.com/matscus/Hamster/Guns/busM5/errors" ) func init() { GetDepositList() } type getDepositListJSON struct { Data struct { Hid string `json:"hid"` } `json:"data"` } //GetDepositList - init script struct func GetDepositList() { getDepositList := New() getDeposi...
package query import ( "time" "github.com/gofrs/uuid" ) type AreaReadQuery interface { FindByID(areaUID uuid.UUID) <-chan QueryResult } type CropQuery interface { FindByBatchID(batchID string) <-chan QueryResult FindAllCropsByFarm(farmUID uuid.UUID) <-chan QueryResult FindAllCropsByArea(areaUID uuid.UUID) <-c...
package main import ( "fmt" "log" "net/http" ) /** * author: will fan * created: 2019/9/1 14:33 * description: */ type messageHandler struct { message string } func (m *messageHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, m.message) } func main() { mux := http.NewServeMux() ...
// Copyright 2022 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...
// +build ignore package statequery import ( "encoding/json" "fmt" "time" "github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address" "github.com/iotaledger/wasp/packages/coretypes" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/kv" "github.com/iotaledger/wasp/...
package main import ( "fmt" ) func main() { nums := []int{2, 1, 2, 4} fmt.Println(rob(nums)) } func rob(nums []int) int { if len(nums) == 0 { return 0 } if len(nums) == 1 { return nums[0] } first := nums[0] second := max(nums[0], nums[1]) for i := 2; i < len(nums); i++ { tmp := second second =...
package main import "fmt" func printSlice(x []int) { fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x) } func main() { /* 创建切片 */ numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8} printSlice(numbers) /* 打印原始切片 */ fmt.Println("numbers ==", numbers) /* 打印子切片从索引1(包含) 到索引4(不包含)*/ fmt.Println("numbers[1:4] =...
// Package types contains generic data types for use with SQL package types
package cloud import ( "bytes" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/devinmcgloin/sail/pkg/slog" ) const ( bucketName = "sail-content" ) // Upload stores the given sketch in DO Spaces func Upload(sketch *bytes.Buffer, path st...
// 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 main // ----------------------- 方法1: 双栈实现 ----------------------- const INF = 1000000000000 type MinStack struct { dataStack *MyStack minValueStack *MyStack } func Constructor() MinStack { return MinStack{ dataStack: NewMyStack(), minValueStack: NewMyStack(), } } func (ms *MinStack) Push(x i...
package oss_test import "testing" func TestClient_PutObjectFromFile(t *testing.T) { client, err := getClient() if err != nil { t.Error(err) return } if err := client.PutObjectFromFile("file.go", "file.go"); err != nil { t.Error(err) return } } func TestClient_GetObjectToFile(t *testing.T) { client, er...
package opp import ( "bytes" "math/rand" "strconv" ) // CPUProFile show cpu info func CPUProFile()error{ max := 100000000 var buf bytes.Buffer for j := 0;j<max;j++{ num := rand.Int63n((int64(max))) str := strconv.FormatInt(num,10) buf.WriteString(str) } _ = buf.String() return nil }
package main import "fmt" func main() { studentsAge := map[string]int{ "john": 32, "bob": 31, } fmt.Println(studentsAge) }
package asciitransport import ( "io" "sync" "time" ) type AsciiTransportClient interface { OutputEvent() <-chan *OutputEvent Input([]byte) InputFrom(io.Reader) error Resize(uint, uint) Done() <-chan struct{} Close() error } func Client(conn io.ReadWriteCloser, opts ...Opt) AsciiTransportClient { at := &Asc...
// mEmIFy is a meme library. Its practically useless. If you're using this, it's your fault. package mEmIFy import ( "errors" "math/rand" "regexp" "strings" "time" ) // SpongebobCaseSeed taKes ThE OriGiNaL stRiNg anD ReTuRns It LiKE the SpOnGeBob MocK mEMe. It TaKeS A SEed FoR Y'All CoNTrOl FrEAks. func Spongebo...
package cmd import ( "github.com/gusandrioli/small-aes/aes" "github.com/spf13/cobra" ) // pdfEncryptCmd represents the pdfEncrypt command var pdfEncryptCmd = &cobra.Command{ Use: "pdfEncrypt", Short: "Encrypts pdf with AES and a 127 byte key", Long: `A longer description that spans multiple lines and likely co...
package main import ( //"math" "fmt" //"io/ioutil" ) func main() { var n int var s string var d, sum int var f bool fmt.Scan(&n) for i:=0; i<n; i++ { fmt.Scan(&d, &s) if s[0] != 'S' && sum == 0 { f = true break } if s[0] != 'N...
package database import ( "database/sql" "github.com/darkliquid/leader1/config" _ "github.com/go-sql-driver/mysql" "log" "os" ) var db *sql.DB var logger *log.Logger var cfg *config.DbSettings func init() { logger = log.New(os.Stdout, "[database] ", log.LstdFlags) } func Config(dbCfg *config.DbSettings) { cf...
package acronym import ( "regexp" "strings" ) // Abbreviate - Returns the acronyms of 's' func Abbreviate(s string) string { wordsPattern := regexp.MustCompile("\\w+") words := wordsPattern.FindAllString(s, -1) return BuildAcro(words, "") } // BuildAcro - recursively builds an acronym from the the words in 'wor...
/* Copyright 2015 Crunchy Data Solutions, 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 merchant import ( "context" "tpay_backend/adminapi/internal/common" "tpay_backend/model" "tpay_backend/utils" "github.com/go-redis/redis/v8" "tpay_backend/adminapi/internal/svc" "tpay_backend/adminapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type EnableMerchantLogic struct { logx....
package main import ( "fmt" "os" ldap "gopkg.in/ldap.v3" ) type loginLDAPerror struct { message string } func newLoginLDAPerror(message string) *loginLDAPerror { return &loginLDAPerror{ message: message, } } func (e *loginLDAPerror) Error() string { return e.message } const ldapServer = "ads.mc.asu.ru:32...
package cache import ( "crypto/tls" "fmt" "github.com/go-redis/redis/v7" "strings" "sync" "time" ) var ( onceCacheCluster sync.Once cacheClusterClientSvc Service ) func InitCacheClusterClientSvc(cacheHost string, cachePort string, cachePassword string) { onceCacheCluster.Do(func() { cacheSvc, err := NewC...
package main import ( "fmt" "os" "github.com/Cloud-Foundations/Dominator/imagepublishers/amipublisher" libjson "github.com/Cloud-Foundations/Dominator/lib/json" "github.com/Cloud-Foundations/Dominator/lib/log" ) func listUnpackersSubcommand(args []string, logger log.DebugLogger) error { if err := listUnpackers...
package server import ( "fmt" "go-be-book/server/handler" "net/http" "sync" "github.com/gorilla/mux" ) func Run(wg *sync.WaitGroup) { book_handler := handler.BookHandler{} router := mux.NewRouter() defer wg.Done() router.HandleFunc("/", book_handler.ListBook).Methods("GET") ...
package main_test import ( "log" "net" "os/exec" "strconv" "strings" "time" "xip/testhelper" "xip/xip" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" . "github.com/onsi/gomega/gexec" ) var err error var serverCmd *exec.Cmd var serverSession *Session var port = ...
package data import ( "github.com/bububa/oppo-omni/enum" "github.com/bububa/oppo-omni/model" ) type QTodayTopRequest struct { model.BaseRequest Demision *enum.DataDemision `json:"demision,omitempty"` } type QTodayTopResponse struct { model.BaseResponse Data *QTodayTopResult `json:"data,omitempty"` } type QTod...
package billyfs import ( "os" "time" ) type dirFileInfo struct { name string mode os.FileMode } func (dirFileInfo) IsDir() bool { return true } func (dirFileInfo) ModTime() time.Time { return time.Now() } func (d dirFileInfo) Mode() os.FileMode { return d.mode } func (d dirFileInfo) Name() string { return d....
// Copyright (c) 2013, Sean Treadway, SoundCloud Ltd. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Source code and contact info at http://github.com/streadway/zk // GENERATED - DO NOT EDIT package proto import "fmt" type Id struct { Scheme string Id ...
package leetcode /*Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ //import "sort" func sortedSquares(A [...
package main import () //总日志结构 type LogInfo struct { ServerId uint64 //服务器ID TODO 前三个字段不能动,应用模块已经使用 OpId uint32 //运营商ID UserId uint64 //玩家ID EventId uint64 //流水ID MainType uint32 //日志主类型 ChildType uint32 //日志子类型 RealServerId uint64 //真实服务器ID(合服后主服务器ID) OpgameId uint32 //混服组ID AdId st...
package message type MessageService struct { msgManager *messageManager } func (ms *MessageService) Init() { } func (ms *MessageService) Tick() { for { msg := ms.msgManager.Consume() msg.Handle() } } func (ms *MessageService) Destroy() { }
package opusutil import ( "errors" "time" ) // Header represents the opus packet's TOC plus extra information depending on config type Header struct { Config *Config NumFrames int Stereo bool } // FullDuration returns the full duration of the opus packet (frameduration * number of frames) func (h *Header)...
package metadata import ( "time" "github.com/go-gormigrate/gormigrate/v2" "gorm.io/gorm" ) func (b *Backend) getMigrations() []*gormigrate.Migration { migrations := []*gormigrate.Migration{ { ID: "0001-initial", Migrate: func(tx *gorm.DB) error { type File struct { ID string `json:"id"` ...
package main import ( _ "github.com/go-sql-driver/mysql" //加载mysql "github.com/jinzhu/gorm" ) var DB *gorm.DB var err error func DbInit() (db *gorm.DB) { DB, err = gorm.Open("mysql", "root:.aA1451418@tcp(123.207.88.76:3306)/updateflow?charset=utf8&parseTime=True&loc=Local") if err != nil { panic(err.Error()) ...
package game_map import ( "github.com/steelx/go-rpg-cgm/combat" "github.com/steelx/go-rpg-cgm/utilz" "github.com/steelx/go-rpg-cgm/world" ) type CombatSelectorFunc struct { RandomAlivePlayer, WeakestEnemy, SideEnemy, SelectAll func(state *CombatState) []*combat.Actor } var CombatSelectorMap = map[string]func(...
package mainWindow import ( "errors" "github.com/myProj/scaner/new/include/unarchive" "github.com/therecipe/qt/widgets" ) func newErrorTable()*widgets.QTableWidget{ table := widgets.NewQTableWidget(nil) //установить readOnly table.SetEditTriggers(widgets.QAbstractItemView__NoEditTriggers) table.SetColumnCount(...
package qywxapi import ( "github.com/thelark/request" "fmt" "reflect" ) type cgiBin struct { CorpID string Secret string AccessToken string } func (t *cgiBin) set(k, v string) { _value := reflect.ValueOf(t).Elem() _type := reflect.TypeOf(t).Elem() if _, ok := _type.FieldByName(k); ok { _field :=...
/* There is a game in which you try not to repeat a word while your opponent tries to see if you have repeated one. "THE RAIN IN SPAIN" has no repeats. "IN THE RAIN AND THE SNOW" repeats THE. "THE RAIN IN SPAIN IN THE PLAIN" repeats THE and IN. Write a program to test a phrase. Input Input is a line containing wo...
package query import ( "encoding/json" "fmt" "github.com/juju/errgo" "github.com/mezis/klask/index" ) type Query interface { // `records` is a ZSET key, containing subset of records IDs. // The key returned should contain a subset of `sourceKey`. // Pass `nil` as a context to the top-level query. Run(records ...
package handler import ( "net/http" "testing" "github.com/golang/protobuf/ptypes" analysispb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/analysis/v1" ptypesv2 "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2" "github.com/micro/go-micro/v2/metadata" "github.com/stretchr/testify/assert" "git...
package main func countPrimeSetBits(L int, R int) int { isPrime := [40]bool{} prime := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 31} for i := 0; i < len(prime); i++ { isPrime[prime[i]] = true } ans := 0 for i := L; i <= R; i++ { if isPrime[countOne(i)] { ans++ } } return ans } func countOne(a int) int {...
package main import ( "context" "errors" "fmt" "os" "strings" "github.com/kudrykv/latex-yearly-planner/app" ) var code int func main() { ctx := context.Background() defer func() { os.Exit(code) }() shouldExit("", app.New().RunContext(ctx, os.Args)) } func shouldExit(msg string, err error) bool { if err ...
package socketman import ( "crypto/tls" "io" "net" ) //Client is a socket client type Client struct { //Config is a configuration for new incoming connections Config } //Connect opens a tcp connection on server behind addr and calls handler. // //connection will be closed after the handler returns // //The synt...
package rpc import ( "context" "fmt" "github.com/benka-me/users/go-pkg/hash" "github.com/benka-me/users/go-pkg/users" "go.mongodb.org/mongo-driver/bson" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) func (app *App) insertRegisterProcess() { for { r := <-app.RegisterChan fmt.Println("Re...
// Copyright 2020, Jeff Alder // // 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 a...
package imagekit import ( "context" "errors" ) // // REQUESTS // type AddTagsRequest struct { // FileIDs is the list of unique ID of the uploaded files. FileIDs []string `json:"fileIds"` // Tags is an array of tags to add on these files. Tags []string `json:"tags"` } // // METHODS // // AddTags to multiple f...
package main import "fmt" func main(){ cardsList := newDeck() //fmt.Println(cardsList) // //handCards, remainCards := deal(cardsList,5) // //fmt.Println("Cards in hand are : ",show(handCards)) //fmt.Println("Cards remain are : ",show(remainCards)) fmt.Print(cardsList.toString()) }
package core // windows环境下启动服务 func RunWindowsServer() { runServer() }
package lookup import ( "fmt" "github.com/docker/libcompose/config" ) type MapEnvLookup struct { Env map[string]interface{} } func (m *MapEnvLookup) Lookup(key string, config *config.ServiceConfig) []string { if v, ok := m.Env[key]; ok { return []string{fmt.Sprintf("%s=%v", key, v)} } return []string{} }
package main import ( "context" "encoding/json" "flag" "fmt" "os" "time" "github.com/amenzhinsky/iothub/cmd/internal" "github.com/amenzhinsky/iothub/eventhub" "github.com/amenzhinsky/iothub/iotservice" ) // globally accessible by command handlers, is it a good idea? var ( // common debugFlag bool comp...
package main //Accesslog tipo per transaction type Accesslog struct { Hash string Type string Time string TTS int SEIp string Clientip string Request string Bytes int Method string URL string Urlschema string Urlhost string Urlpath string Urlquery string Mi...
package content import ( dbUtils "github.com/sundogrd/content-api/utils/db" "sync" ) var _contentRepository *ContentRepository var _contentRepositoryOnce sync.Once func ContentRepositoryInstance() *ContentRepository { _contentRepositoryOnce.Do(func() { db := dbUtils.Client hasContentTable := db.HasTable(&PFCo...
package config import ( "path/filepath" "runtime" "gopkg.in/ini.v1" ) type ConfigManager interface { Load(section string, tpl interface{}) error } type configManagerImpl struct { config *ini.File } // returns api/config.ConfigManager func NewConfigManager() (ConfigManager, error) { _, filename, _, ok := runt...
package main import ( "fmt" "github.com/lxc/lxd/client" "github.com/lxc/lxd/shared/api" ) //Connect to Unixsocket func connect() (container lxd.ContainerServer) { container, err := lxd.ConnectLXDUnix("", nil) if err != nil { fmt.Println(err) } return } //Create container func create(container lxd.Contain...
package metadata import ( "fmt" "gorm.io/gorm" "github.com/root-gg/plik/server/common" ) // CreateFile persist a new file to the database func (b *Backend) CreateFile(file *common.File) (err error) { return b.db.Create(file).Error } // GetFile return a file from the database ( nil and no error if not found ) f...
package methods import ( "net/http" ) func contains(needle string, haystack []string) bool { for _, item := range haystack { if needle == item { return true } } return false } func makeMiddleware(predicate func(string, []string) bool) func(...string) func(http.Handler) http.Handler { return func(methods ...
package cmd import ( "github.com/stretchr/testify/assert" "testing" ) func Test_Root(t *testing.T) { // Arrange ass := assert.New(t) appPrinter = newMockPrn() // Act err := Execute() // Assert ass.Nil(err) } func Test_RootUnknownCommand(t *testing.T) { // Arrange ass := assert.New(t) appPrinter = new...
package errors import ( "fmt" ) type TceCloudSDKError struct { Code string Message string RequestId string } func (e *TceCloudSDKError) Error() string { return fmt.Sprintf("[TceCloudSDKError] Code=%s, Message=%s, RequestId=%s", e.Code, e.Message, e.RequestId) } func NewTceCloudSDKError(code, message, re...
package main import "fmt" func main() { fmt.Println(removeStars("leet**cod*e")) } func removeStars(s string) string { bs := make([]byte, 0) for i := 0; i < len(s); i++ { if s[i] == '*' { bs = bs[:len(bs)-1] // 删除左侧的一个字符 } else { bs = append(bs, s[i]) // 直接插入 } } return string(bs) }
package fslm import ( "bytes" "encoding/gob" "errors" "os" "reflect" "unsafe" "github.com/kho/byteblock" "github.com/kho/word" ) // Hashed is a finite-state representation of a n-gram language model // using hash tables. A Hashed model is usually loaded from file or // constructed with a Builder. type Hashed...
package main import "fmt" func fibonacci(n uint) uint { if n == 0 { return 0 } if n == 1 { return 1 } return fibonacci(n-1) + fibonacci(n-2) } func main() { prevRes := make(map[uint]uint) var n uint nEnter: fmt.Print("Input positive number: ") fmt.Scanln(&n) res := prevRes[n] if res == 0 && n != 0 {...
// Copyright 2019 Leandro Akira Omiya Takagi. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package unio import ( "reflect" ) // Search if a value contains inside array func (u *Util) ArrayContains(ss interface{}, e interface{}) bool { ...
package handlers import ( "aws-lambda-api/pkg/ngo" "net/http" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" ) func GetNgo(req events.APIGatewayProxyRequest, tableName string, dynaClient dynamodbiface.DynamoDBAPI) ( *events.APIGa...
package rlcli import ( "context" "fmt" "github.com/gin-gonic/gin" "github.com/sanguohot/rlcli/pkg/common/log" "github.com/ulule/limiter/v3" mgin "github.com/ulule/limiter/v3/drivers/middleware/gin" "github.com/ulule/limiter/v3/drivers/store/memory" "net/http" "os" "os/signal" "time" ) type Rlcli struct { ...
package createplayerusecase import "backend/internal/domain" type UseCase interface { Execute(name string) (Result, error) } func New( playerIdGenerator domain.PlayerIdGenerator, playerRepository domain.PlayerRepository, ) UseCase { return &createPlayerUseCase{ playerIdGenerator: playerIdGenerator, playerRep...
package sshmux import ( "errors" "fmt" "io" "strconv" ) // DefaultInteractive is the default server selection prompt for users during // session forward. func DefaultInteractive(comm io.ReadWriter, session *Session) (string, error) { remotes := session.Remotes fmt.Fprintf(comm, "Welcome to sshmux, %s\r\n", ses...
package main import "fmt" func main() { s := []int{2, 3, 5, 7, 11} s = s[1:4] fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) s = s[:2] fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) s = s[:3] fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) s = s[1:] fmt.Printf("len=%d cap=%d %v\n", len(s),...
package utils import ( "encoding/json" "io" "io/ioutil" "log" ) type ApiData struct { body io.ReadCloser } func (ap ApiData) ToString() string { defer ap.body.Close() bs, _ := ioutil.ReadAll(ap.body) return string(bs) } func (ap ApiData) ToJson() JsonObject { defer ap.body.Close() jsonMap := make(map[s...
// Licensed to SolID under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. SolID licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compli...
// Copyright 2021 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 http import ( "bytes" "context" "fmt" "math" "net/http" "net/url" "strconv" "strings" "sync" "time" "github.com/drand/drand/chain" "github.com/drand/drand/log" "github.com/drand/drand/metrics" "github.com/drand/drand/protobuf/drand" "github.com/prometheus/client_golang/prometheus/promhttp" js...
/* Copyright 2023 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, so...
package main import ( "fmt" ) func main() { ss := [][]string{ { "miu", "milton", "encher o saco", }, { "mimi", "martha", "pedir comida", }, { "meus alunos queridos", "que estudam bastante", "fazer os exercícios ninja", }, } for _, v := range ss { fmt.Println(v) } fmt.P...
package pomogo import ( "bytes" "log" "os/exec" ) // StopTask ... func StopTask(taskUUID string) ([]byte, error) { log.Println("StopTask") cmd := exec.Command("task", taskUUID, "stop") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() return out.Bytes(), err } // StartTask ... func StartTask(taskUUID ...