text
stringlengths
11
4.05M
package stmt import ( "go/ast" "fmt" "github.com/sky0621/go-testcode-autogen/inspect/result" ) type GoStmtInspector struct{} func (i *GoStmtInspector) IsTarget(node ast.Node) bool { switch node.(type) { case *ast.GoStmt: return true } return false } func (i *GoStmtInspector) Inspect(node ast.Node, aggreg...
package main import "fmt" func main() { state := 0 wait := make(chan struct{}) go func() { total := 0 for i := 0; i < 12; i++ { total = 2*i + total } state = 1 close(wait) }() if state == 1 { fmt.Println(state) } <-wait }
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
package slacknotifier import "github.com/odpf/siren/domain" type SlackMessage struct { ReceiverName string `json:"receiver_name"` ReceiverType string `json:"receiver_type"` Entity string `json:"entity"` Message string `json:"message"` } func (message *SlackMessage) fromDomain(m *domain.SlackMessage) *...
package main import ( "flag" "fmt" "github.com/bouncepaw/mycomarkup/v2" "github.com/bouncepaw/mycomarkup/v2/mycocontext" "io/ioutil" "github.com/bouncepaw/mycomarkup/v2/globals" ) func main() { hyphaName, filename := parseFlags() contents, err := ioutil.ReadFile(filename) if err != nil { _ = fmt.Errorf("%...
package io import ( "os" "strconv" "testing" ) func cleanup() { // Cleaning up TestRmdirEmptyAll _ = os.Remove("testdata/file") _ = os.RemoveAll("testdata/a") _ = os.RemoveAll("testdata/dirempty") } func TestMain(m *testing.M) { cleanup() sdebug := os.Getenv("DEBUG") if len(sdebug) > 0 { _debug, _ = str...
package main import ( "encoding/json" "fmt" msamodule "github.com/MySocialApp/mysocialapp-event-handler/modules" "gopkg.in/yaml.v2" "log" "net/http" "reflect" ) type Config struct { Http struct { Bind string `yaml:"bind"` } `yaml:"http-bind"` Language struct { Default string `yaml:"default"` } `yaml:"l...
package main import ( "fmt" "math" ) func main(){ var c float32 = math.Pi //将常量保存为float32类型 fmt.Println(c) fmt.Println(int(c)) //转换为int类型,浮点发生精度丢失 fmt.Println(math.Pi) //注:布尔型值不能强制转换 }
package types // Task is a task type Task struct { ID int Title string Done bool }
package main import ( "fmt" ) func main() { done := make(chan struct{}) fmt.Printf("%s\n", "Starting program") go NewFileWatcher() <-done }
package leetcode import "testing" func TestSearch(t *testing.T) { if search([]int{-1, 0, 3, 5, 9, 12}, 9) != 4 { t.Fatal() } if search([]int{-1, 0, 3, 5, 9, 12}, 2) != -1 { t.Fatal() } }
package repl import "fmt" const T string = "\r" type history struct { store []string pos int } func(h *history) goUp() { if h.pos+1 >= len(h.store) { return } h.pos++ fmt.Printf("%v%v", T, h.store[h.pos]) } func(h *history) save(in *input) { h.store = append(h.store, in.in) } func newHistory() *history ...
package main import ( "fmt" "io/ioutil" "os" "strconv" "sync" "time" ) const ( gb = 1024 * 1024 * 1024 ) func genFileData(fileSize int) []byte { file := make([]byte, fileSize) for i := 0; i < fileSize; i++ { file[i] = byte(i % 256) } return file } // FileData describes a file data type FileData struct ...
package main import ( "github.com/hashicorp/terraform/plugin" "github.com/kradalby/terraform-provider-opnsense/opnsense" ) func main() { plugin.Serve(&plugin.ServeOpts{ ProviderFunc: opnsense.Provider}) }
package kv_query_util import ( "bufio" "io" "log" "os" "sync" "github.com/transactional-cloud-serving-benchmark/tcsb/serialization_util" ) type IPCDriver struct { stdin io.WriteCloser stdout io.ReadCloser stderr *bufio.Reader } func NewIPCDriver(stdin io.WriteCloser, stdout, stderr io.ReadCloser) IPCDrive...
package main import ( "log" "strconv" "time" ) // ClaimLoop recusively keeps claiming rewards func ClaimLoop(game Game, api *GameAPI) { resetTime, err := time.Parse(time.RFC3339, game.ClaimReset) if err != nil { handleClaimError(api, err) return } duration := calcClaimWaitDuration(resetTime) if duration...
package main import ( "encoding/json" "fmt" ) type Message struct { Name string `json:"name" valid:"required"` Body string `json:"body" valid:"required"` Time int64 `json:"-" valid:"required"` } func main() { m := Message{"Alice", "Hello", 1294706395881547000} out, _ := json.Marshal...
package msgHandler import ( "bytes" "encoding/json" "fmt" "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr" appComm "github.com/HNB-ECO/HNB-Blockchain/HNB/appMgr/common" cmn "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/common" "github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/types" "github.c...
package lexer import ( "github.com/kzbandai/playground/go/src/interpreter/token" "testing" ) func TestNextToken(t *testing.T) { input := `let five = 5; let ten = 10; let add = fn(x, y) { x + y; }; let result = add(five, ten); !-/*5; 5 < 10 > 5; if (5 < 10) { return true; } else { return false; } 10 == 10; 1...
package main import ( "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "github.com/spf13/viper" "github.com/spf13/cobra" ) // ./Integration-with-Viper.exe get -u foo -p bar https://httpbin.org/basic-auth/foo/bar // ./Integration-with-Viper.exe get https://httpbin.org/basic-auth/Jamal/gizli // ./Integration-w...
package models // import ( // "github.com/messagedb/messagedb/meta/schema" // "github.com/messagedb/messagedb/meta/utils" // log "github.com/Sirupsen/logrus" // "gopkg.in/mgo.v2" // "gopkg.in/mgo.v2/bson" // ) // var Team *TeamModel // type TeamModel struct { // *storage.Model // } // func (m *TeamModel) New...
package booking import ( "fmt" "time" ) // Schedule returns a time.Time from a string containing a date func Schedule(date string) time.Time { mTime, _ := time.Parse("1/02/2006 15:04:05", date) return mTime } // HasPassed returns whether a date has passed func HasPassed(date string) bool { mTime, _ := time.Par...
package main import ( "fmt" ) func max(a, b int) int { if a > b { return a } return b } func canJump(nums []int) bool { maxJumpableIndex := 0 if len(nums) == 0 || len(nums) == 1 { return true } for i, jmpLen := range nums { if i > maxJumpableIndex { return false } maxJumpableIndex = max(maxJ...
package order import ( "context" "tpay_backend/adminapi/internal/common" "tpay_backend/model" "tpay_backend/adminapi/internal/svc" "tpay_backend/adminapi/internal/types" "github.com/tal-tech/go-zero/core/logx" ) type GetMerchantWithdrawOrderListLogic struct { logx.Logger ctx context.Context svcCtx *svc....
/* Copyright © 2020 Denis Rendler <connect@rendler.me> 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...
/* Write a function that pairs the first number in an array with the last, the second number with the second to last, etc. Examples pairs([1, 2, 3, 4, 5, 6, 7]) ➞ [[1, 7], [2, 6], [3, 5], [4, 4]] pairs([1, 2, 3, 4, 5, 6]) ➞ [[1, 6], [2, 5], [3, 4]] pairs([5, 9, 8, 1, 2]) ➞ [[5, 2], [9, 1], [8, 8]] pairs([]) ➞ [] ...
package main import ( "fmt" ) //If all workers die, exit func WorkerOverseer() { for workerDeadCounter < *maxWorkers { deadId := <-exitChan if *verbose { fmt.Printf("Worker %x ended (Sent %d requests) \n", deadId, workers[deadId].RequestCounter) } workerDeadCounter += 1 } fmt.Printf("All (%d) workers d...
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 deployment_install_client.go InstallStrategyDeploymentInterface package wrappers import ( "context" "github.com/pkg/errors" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/err...
package main import ( "log" "net" "github.com/xtaci/gaio" ) func main() { ln, err := net.Listen("tcp", "localhost:0") if err != nil { log.Fatal(err) } log.Println("echo server listening on", ln.Addr()) w, err := gaio.CreateWatcher(4096) if err != nil { log.Fatal(err) } chRx := make(chan gaio.OpResu...
package queries import ( "database/sql" "log" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/configuration" "gitlab.com/semestr-6/projekt-grupowy/backend/obsluga-formularzy/energy_resources/models" ) const EDIT_ENERGY_RESOURCE_ATTRIBUTE_SQL = ` UPDATE energy_resources."EnergyResourcesAttributes...
package main import ( "fmt" kyu6 "github.com/imskojs/learn_go_lang/00-Toy_problems/codewars/6kyu" ) func main() { var answer interface{} answer = kyu6.Parse("iiisdoso") fmt.Println(answer) }
package main import ( "encoding/json" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/dachanh/daita-serverless/user_api/model" "github.com/dachanh/daita-serverless/user_api/storage" "github.com/google/uuid" "net/http" ) func main() { lambda.Start(Handler) } func...
package random import ( crand "crypto/rand" "fmt" "math/big" "math/rand" "sync" "time" ) // NewMathematical runs rand.Seed with the current time and returns a random.Provider, specifically *random.Mathematical. func NewMathematical() *Mathematical { return &Mathematical{ rand: rand.New(rand.NewSource(time.No...
package main import ( "encoding/json" "fmt" "io/ioutil" "os" "text/tabwriter" "time" ) func main() { raw, errRead := ioutil.ReadFile("message_1.json") if errRead != nil { panic(errRead) } var fbExport FacebookExport if errUm := json.Unmarshal(raw, &fbExport); errUm != nil { panic(errUm) } fmt.Prin...
package stringutils import ( "strconv" "strings" "github.com/axgle/mahonia" ) //分行 func SplitLine(str string) []string { return strings.FieldsFunc(str, func(s rune) bool { if s == '\n' || s == '\r' { return true } return false }) } // parse memory string as value in unit K like: 6M, 7G etc func ParseM...
/* Copyright AppsCode Inc. and Contributors 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 shamirutil import ( "math/rand" "github.com/renproject/secp256k1" "github.com/renproject/shamir" ) // RandomCommitment constructs and returns a random commitment with the given // number of curve points. func RandomCommitment(k int) shamir.Commitment { c := make(shamir.Commitment, k) for i := range c { ...
package products import ( "errors" "net/http" "time" "cinemo.com/shoping-cart/internal/errorcode" ) // Product representation in app type Product struct { ID int64 `json:"id,omitempty"` Name string `json:"name,omitempty"` Details string `json:"details,omitempty"` Amount int64 `...
package main import ( "fmt" "time" "github.com/yanzay/tbot" ) func (app *application) createPet(f tbot.UpdateHandler) tbot.UpdateHandler { return func(u *tbot.Update) { if u.Message == nil { f(u) return } m := u.Message pet := app.petStore.Get(m.Chat.ID) if !pet.Alive { app.petStore.Set(m.Chat...
package knowledge import "github.com/clems4ever/go-graphkb/internal/query" // QueryWhereVisitor a visitor for the where clauses type QueryWhereVisitor struct { ExpressionVisitorBase Variables []string queryGraph *QueryGraph } // NewQueryWhereVisitor create an instance of query where visitor. func NewQueryWhereV...
package main import ( "fmt" ) func main() { Mustf(3) } // Must前缀表示调用者不能接收不合法输入 func Mustf(x int) { fmt.Printf("f(%d) \n", x+0/x) // panics if x == 0 defer fmt.Printf("defer %d\n", x) Mustf(x - 1) }
package matchmaker import ( "encoding/json" "log" "net/http" "github.com/garyburd/redigo/redis" "github.com/gorilla/mux" "github.com/pkg/errors" predis "github.com/ryank90/matchmaker-sample/pkg/redis" ) const version string = "alpha-0.0.1" // Server is the http server instance. type Server struct { srv ...
package assert type TestInterface interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) }
package main import ( "crypto/rsa" "crypto/rand" "crypto/md5" "fmt" "encoding/base64" ) func crypt() { //创建私钥 priv, _ := rsa.GenerateKey(rand.Reader, 1024) //创建公钥 pub := priv.PublicKey org := []byte("hello jason") cipherTxt, _ := rsa.EncryptOAEP(md5.New(), rand.Reader, &pub, org, nil) fmt.Println("密文为:...
package spa import ( "path" "strings" "github.com/labstack/echo/v4" echomiddleware "github.com/labstack/echo/v4/middleware" ) // DefaultIndexFilename the filename used as the default index const DefaultIndexFilename = "index.html" // IndexConfig defines the config for the middleware which determines the path to...
package bean import ( "github.com/astaxie/beego/orm" "fmt" "time" ) type AchievementAttr struct { AchieveName string `orm:"pk;column(achieveName)"` // 成就属性名称 + 角色编号 AchieveValue int32 `orm:"column(achieveValue)"` // 成就属性值 } type AchievementUnLock struct { AchieveName string `o...
package docs_test import ( "path/filepath" "runtime" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/werf/werf/integration/pkg/utils" ) var _ = Describe("docs", func() { BeforeEach(func() { if runtime.GOOS == "windows" { Skip("skip on windows") } resolvedExpectationPath, err := fil...
/* 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 ircserver import "gopkg.in/sorcix/irc.v2" func init() { Commands["server_KICK"] = &ircCommand{ Func: (*IRCServer).cmdServerKick, MinParams: 2, } } func (i *IRCServer) cmdServerKick(s *Session, reply *Replyctx, msg *irc.Message) { // e.g. “:ChanServ KICK #noname-ev blArgh_ :get out” channelname :...
/* Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. */ package main import ( "fmt" "strings" ) func not_string(s string) string { if ! strings.HasPrefix(s, "not") { return "not " + s } return s } func ...
package cli import ( "testing" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" "github.com/cosmos/cosmos-sdk/testutil/testdata" "github.com/stretchr/testify/assert" "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" ) func Test_splitAndCall_NoMessages(t *testing.T) { clientC...
// Package engine provides the all-encompassing interface to the Orbit // background operations. This includes replicated state management, gossip // control, and ensuring that the state is maintained for the respective nodes. package engine import ( "log" "os" "path/filepath" ) // Engine is the primary all-encomp...
/* Copyright (c) 2017 GigaSpaces Technologies Ltd. All rights reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...
package mongomodel import ( "time" ) type ShutdownModel struct { View *DailyShutDownView Typemap map[int]int } func NewShutdownModel(date time.Time) *ShutdownModel { model := ShutdownModel{ View: newDailyShutDownView(date), Typemap: make(map[int]int), } model.Typemap[0] = 0 model.Typemap[10] = 1 m...
package structs import "time" type BaseStruct struct { Id int64 `xorm:"pk autoincr"` CreateTime time.Time `xorm:"created"` CreateUser int64 UpdateTime time.Time `xorm:"updated"` UpdateUser int64 DeletedTime time.Time `xorm:"deleted"` Status int64 `xorm:"default 1"` }
package btree type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func zigzagLevelOrder(root *TreeNode) [][]int { var levelOrder [][]int if root == nil { return levelOrder } var queue []*TreeNode queue = append(queue, root) count := 0 for len(queue) > 0 { count++ var level []int size ...
// Copyright 2020 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" "os" "runtime" "sync" "gSSHToInnobackupex/gotossh" "github.com/WangJiemin/gocomm" ) var ( sshUser, sshPass, sshHost, sshPort string xtrabackupUser, xtrabackupPass, xtrabackupHost, xtrabackupPort string xtrabackupConfig, x...
package jwt import ( "time" "github.com/dgrijalva/jwt-go" ) const ( IDKey = "id" // 用户唯一标识 ExpireKey = "expire" // 过期时间 SignTSKey = "sign_ts" // token签发时间 ) // JwtSigner 签名结构 type JwtSigner struct { // signing algorithm - possible values are HS256, HS384, HS512 // Optional, default is HS256. SignA...
package operatorlister import ( "fmt" "sync" "k8s.io/apimachinery/pkg/labels" v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" aregv1 "k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1" ) // UnionAPIServiceLister is a custom implementation of an APIService lister that allows a new // Lister to...
package main import ( "encoding/json" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" "github.com/aws/aws-sdk-go/service/kms" "github.com/aws/aws-sdk-go/service/kms/kmsiface" "gi...
package main import ( "fmt" "llvvlv00.org/zinx/ziface" "llvvlv00.org/zinx/znet" ) // 基于zinx框架开发的服务器端应用程序 // ping test 自定义路由 type PingRouter struct { znet.BaseRouter } type HelloZinxRouter struct { znet.BaseRouter } // Test Handle func (this *PingRouter)Handle(request ziface.IRequest) { fmt.Println("Call Route...
package cidranger import ( "net" "testing" "github.com/stretchr/testify/assert" ) func TestInsert(t *testing.T) { ranger := newBruteRanger().(*bruteRanger) _, networkIPv4, _ := net.ParseCIDR("0.0.1.0/24") _, networkIPv6, _ := net.ParseCIDR("8000::/96") ranger.Insert(*networkIPv4) ranger.Insert(*networkIPv6)...
package qprob // classifyAnal.go import ( "encoding/json" "fmt" iou "io/ioutil" "qutil" "sort" ) const AnalNoClassSpecified = TClassId(-9999) // Structures to report on results // and make them easy to analyze // Some of these are also used // by the optimizer. Not to be confused // with ResultForRow which c...
// 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 main import "math" import "fmt" type Shape interface { area() float64 } type Circle struct { x,y,radius float64 } type Rectangle struct { width,height float64 } func ( circle Circle) area() float64{ return math.Pi *circle.radius *circle.radius } func(rect Rectangle) area() float64{ return rect.width *re...
package main import ( "flag" "fmt" "strings" "github.com/antchfx/htmlquery" "golang.org/x/net/html" "zliu.org/goutil" ) var ( url = flag.String("url", "http://www.qq.com/", "url to fetch and parse") ) func main() { doc, err := htmlquery.LoadURL(*url) if err != nil { panic(err) } var links []string htm...
package basic import ( "fmt" "sync" ) // chan<- //只写 func producer(out chan<- int) { defer close(out) // 在最后一个写通道动作后,close通道 for i := 0; i < 5; i++ { fmt.Println("produce: ", i) out <- i //如果对方不读 会阻塞 } } // <-chan //只读 func consumer(in <-chan int) { for num := range in { // range无缓存通道, 要求必须在最后一个写通道...
package main import ( "context" "fmt" "github.com/mailgun/mailgun-go/v3" ) //verify email after signup func (e *SendEmailInfo) VerifyEmail(email string, veriToken string) error { url := fmt.Sprintf("%s://%s/api/confirm-email/%s", e.Scheme, e.ServerDomain, veriToken) mg := mailgun.NewMailgun(e.EmailDomain, e.Ema...
package main import "fmt" func double(number int) { number *= 2 } func main() { amount := 6 double(amount) fmt.Print(amount) }
//Description - This program is used to add the stock details to the list //dynamically or to delete the stock dynamiclly. package main import "fmt" //stock - Declaring a structure of stock datatype. type stock struct { Name string `json:"Name"` Number_of_shares int `json:"Number_of_shares"` Share...
// Package core contains the core Bazelisk logic, as well as abstractions for Bazel repositories. package core // TODO: split this file into multiple smaller ones in dedicated packages (e.g. execution, incompatible, ...). import ( "bufio" "crypto/rand" "crypto/sha256" "encoding/json" "fmt" "io" "io/ioutil" "l...
package main import ( "encoding/json" "fmt" "io/ioutil" "os" "sync" ) type Trees struct { Trees []Tree `json:"trees"` } type Tree struct { Type string `json:"type"` Age int `json:"age"` Height float64 `json:"height_m"` Result int } var wg = sync.WaitGroup{} var FilterValue int = 9294100 var ThreadsCount in...
package main import ( "fmt" "github.com/gorilla/mux" "github.com/namsral/flag" "log" "net/http" ) func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found", http.StatusNotFound) return } if r.Method != "GET" { http.Error(w, "Method not allowed", http.Stat...
package models import ( "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/lib/pq" ) func init() { orm.RegisterDriver("postgres", orm.DRPostgres) //orm.RegisterDataBase("default", "postgres", "ccadmin:c1oudc0w@tcp(192.168.1.178:5524)/ccdb?charset=utf8") ccdbname := beego.Ap...
package handlers import ( "MovieDatabase/entities" "MovieDatabase/repo" "encoding/json" "fmt" "github.com/gorilla/mux" "net/http" ) type Service interface { AddMovie(m entities.Movie) error ViewAll() (repo.DataBase, error) FindById(id string) (*entities.Movie, error) DeleteMovie(id string) error UpdateMovi...
// Copyright (c) 2018 Benjamin Borbe All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package version_test import ( "context" "errors" mocksmocks "github.com/Shopify/sarama/mocks" "github.com/bborbe/kafka-dockerhub-version-collector/avro...
package push_translator import "ms/sun/shared/x" var m = 1 func ChatPushToPbChat(pc *x.PushChat) x.PB_Push { pb := x.PB_Push{ LastPushId: int64(m), LastChatPushId: int64(pc.ToUserId), } m++ return pb }
// +build integration /* Copyright 2016 The Kubernetes Authors 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 ...
// Package main implements a client for rate-limiter service. package main import ( "context" "log" "time" pb "github.com/sam09/rate-limiter/token-bucket" "google.golang.org/grpc" ) const ( address = "localhost:50051" bucketName = "test-bucket" maxAmount = 1000 refillTime = 60 * 60 refillAmount...
package common import ( "errors" ) const ( Lasercfg = "config/laser.cfg" ) var ( NotImplementedException = errors.New("this function not implemented.") )
package er import ( "encoding/json" "fmt" "hlf" "runtime" "strconv" ) //Err error data type Err struct { code int32 callStack []string stackDepth int info string next *Err } func (me *Err) Error() string { if me == nil { return "No Error" } return fmt.Sprintf("Error Code: 0x%x, Err...
// 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 general import "context" type BaseService struct { } func (s *BaseService) HealthCheck(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) { return &HealthCheckResponse{}, nil } func (s *BaseService) Version(ctx context.Context, req *VersionRequest) (*VersionResponse, error) { return &Vers...
/* Given two int values, return their sum. Unless the two values are the same, then return double their sum. */ package main import ( "fmt" ) func sum_double(x int, y int) int { // this is a comment var n int = x + y if x == y { return 2 * n } return n } func main(){ var status int = 0 if sum_double(1, 2)...
package main import ( "testing" "lib" "bytes" "time" ) func TestCountDown(t *testing.T) { t.Run("write countdown and sleep 4 times", func(t *testing.T) { buffer := &bytes.Buffer{} spySleeper := &SpySleeper{} CountDown(buffer, spySleeper) want := `3 2 1 Go!` lib.AssertEqual(t, buffer.String(), want) l...
package domain import ( "context" ) type Merchant struct { ID int64 `json:"id"` Name string `json:"name"` } type MerchantGroup struct { ParentMerchantID int64 `json:"parentMerchantId"` ChildMerchantID int64 `json:"childMerchantId"` } type MerchantUsecase inte...
package pomodoro import ( "strings" "testing" "time" ) const ( layout string = "Jan 01 2006 at 15:04:01" ) func TestNewPomodoro(t *testing.T) { n := NewPomodoro() if n.Active != true { t.Fail() } t.Log("\n", n.Active) } func TestGetCurrentTime(t *testing.T) { ti := GetCurrentTime().Format(layout) t.Log(...
package nnw import ( "math" "math/rand" ) func Gauss() float64 { x := float64(rand.Int()) w := math.Pow(math.E, - x * x) return w } func Random() float64 { w := rand.Float64() return w } func Sigmoid(x float64) float64 { y := 1 / (1+math.Pow(math.E, -x)) return y } func LeRU(x float64) float64 { y := mat...
package main import ( "github.com/stretchr/testify/assert" "strings" "testing" ) func TestParse_Help(t *testing.T) { stdout := strings.Builder{} _, _, _ = Parse("bagel --help", &stdout, nil) assert.NotEmpty(t, stdout.String()) t.Log("\n" + stdout.String()) stdout = strings.Builder{} _, _, _ = Parse("bagel t...
package handler import ( "fmt" "net/http" "github.com/teejays/clog" "github.com/teejays/n-factor-vault/backend/library/go-api" "github.com/teejays/n-factor-vault/backend/library/id" "github.com/teejays/n-factor-vault/backend/src/auth" "github.com/teejays/n-factor-vault/backend/src/vault" ) func init() { } ...
package pki import ( "crypto/x509" "crypto/x509/pkix" ) func GenerateCSR(domains []string) *x509.CertificateRequest { template := x509.CertificateRequest{ Subject: pkix.Name{ CommonName: domains[0], }, DNSNames: domains, } return &template }
package lbctrl import ( "context" "fmt" "github.com/zdnscloud/elb-controller/driver" "github.com/zdnscloud/gok8s/client" corev1 "k8s.io/api/core/v1" ) const ( ZcloudLBVIPAnnotationKey = "lb.zcloud.cn/vip" ZcloudLBMethodAnnotationKey = "lb.zcloud.cn/method" ) func genLBConfig(svc *corev1.Service, ep *core...
/* * This file is part of the KubeVirt project * * 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 c15_pkcs7_validation import ( "bytes" "testing" ) func TestValidInput(t *testing.T) { inp := []byte("ICE ICE BABY\x04\x04\x04\x04") exp := []byte("ICE ICE BABY") res, err := Validation(inp) if err != nil || !bytes.Equal(res, exp) { t.Errorf("Incorrect result. Expected: (%s, nil), got: (%s, %s)\n", exp...
/* 交易市场订单参数 返回所有系统支持的交易市场的参数信息,包括交易费,最小下单量,价格精度等。 http://data.gate.io/api2/1/marketinfo */ package main import ( "github.com/buger/jsonparser" "errors" "strconv" ) type ApiMarketInfo struct { Api Result bool `json:"result,string"` Pairs []ApiMarketInfoPair `json:"pairs"` } type ApiMarketInfoPair struct...
package main import ( "./ant" ) func main() { ant.BenchAll() }
package main import ( "bufio" "os" "strconv" "github.com/muesli/termenv" ) /** * ReadInts * * @desc: read in lines from stdin and convert to ints * * @return: array of ints * * this functions expects actual ints coming in * as is a typical puzzle input in AoC * * @usage: ./exe < input-file **/ func Re...
package version import "fmt" // OLMVersion indicates what version of OLM the binary belongs to var OLMVersion string // GitCommit indicates which git commit the binary was built from var GitCommit string // String returns a pretty string concatenation of OLMVersion and GitCommit func String() string { return fmt.S...
package main import ( "log" "./gui" "./util" "./constants" "github.com/andlabs/ui" _ "github.com/andlabs/ui/winmanifest" ) func main() { log.Printf("Starting %s %s", constants.APP_NAME, constants.APP_VERSION) log.Println("Making app dir.") util.CreateDirIfNotExist(constants.APP_DIR) log.Println("Making A...