text
stringlengths
11
4.05M
package sse import ( "encoding/json" "fmt" "net/http" sse "github.com/alexandrevicenzi/go-sse" "github.com/delgus/def-parser/internal/app" ) // Notifier реализует интерфейс для оповещения пользователя type Notifier struct { server *sse.Server route string } // NewNotifier вернет *Notifier func NewNotifier(r...
package decider // Decider is Decider Interface. type Decider interface { Allowed() bool NewDecider(options *[]interface{}) (Decider, error) }
package controllers import ( "strconv" "time" "github.com/canghai908/zbxtable/models" "github.com/canghai908/zbxtable/utils" ) // AlarmController 历史告警消息接口 type AlarmController struct { BaseController } // AlarmRes used var AlarmRes models.AlarmList // AnalysisRes mod var AnalysisRes models.AnalysisList // UR...
package router import ( "gin-vue-admin/api/v1" "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitTitTrainingInfoRouter(Router *gin.RouterGroup) { TitTrainingInfoRouter := Router.Group("trainingInfo").Use(middleware.JWTAuth()).Use(middleware.CasbinHandler()) { TitTrainingInfoRouter.POST("createTi...
package repo import ( "context" "fmt" "github.com/jackc/pgx" "time" ) type postgres struct { pool *pgx.ConnPool timeout time.Duration } func (p *postgres) SetLink(ctx context.Context, url, code string, isCustom bool) error { ctx, cancel := context.WithTimeout(ctx, p.timeout) defer cancel() if _, err := p.p...
package bottom import ( "io" "github.com/bborbe/server/renderer" "github.com/bborbe/server/renderer/content" ) const CONTENT string = `<div id="footer"> <ul class="navi"> <li> <a href="/photo/links/">Links</a> </li> <li> <a href="/photo/contact/">Contact</a> </li> </ul> <div id="copyright"> <a href="/photo/contac...
package helm import ( "context" "fmt" "github.com/spf13/cobra" "github.com/werf/logboek" "github.com/werf/logboek/pkg/level" "github.com/werf/werf/cmd/werf/common" "github.com/werf/werf/pkg/build" "github.com/werf/werf/pkg/deploy/helm/chart_extender/helpers" "github.com/werf/werf/pkg/git_repo" "github.com...
package main import ( "bytes" "io/ioutil" "net/http" "os" "reflect" "testing" ) // RoundTripFunc . type RoundTripFunc func(req *http.Request) *http.Response // RoundTrip . func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req), nil } //NewTestClient returns *http.Client w...
/* * @lc app=leetcode id=99 lang=golang * * [99] Recover Binary Search Tree * * https://leetcode.com/problems/recover-binary-search-tree/description/ * * algorithms * Hard (35.40%) * Likes: 876 * Dislikes: 48 * Total Accepted: 125.1K * Total Submissions: 353.5K * Testcase Example: '[1,3,null,null,2]...
package apis import ( "log" "net/http" "github.com/gin-gonic/gin" "github.com/go-gnss/data/cmd/database/daos" "github.com/google/uuid" ) func GetObservation(c *gin.Context) { id, _ := uuid.Parse(c.Param("id")) if obs, err := daos.GetObservation(id); err != nil { c.AbortWithStatus(http.StatusNotFound) log....
package main import ( "context" "fmt" "log" divpb "github.com/golang-grpc-snippet/drill_exercise_1/division/protobuf" "google.golang.org/grpc" ) func main() { conn, err := grpc.Dial("0.0.0.0:50051", grpc.WithInsecure()) if err != nil { log.Fatalf("Error : %v", err) } c := divpb.NewDivClient(conn) doUnar...
package main // https://hyperledger-fabric.readthedocs.io/en/latest/chaincode4ade.html import ( "github.com/hyperledger/fabric-contract-api-go/contractapi" ) func main() { cc, err := contractapi.NewChaincode(&ResourceTypesContract{}) if err != nil { panic(err.Error()) } if err := cc.Start(); err != nil { p...
package httputil import ( "errors" "net/http" "strconv" "strings" ) // ErrCookieTooLarge indicates that a cookie is too large. var ErrCookieTooLarge = errors.New("cookie too large") const ( defaultCookieChunkerChunkSize = 3800 defaultCookieChunkerMaxChunks = 16 ) type cookieChunkerConfig struct { chunkSize i...
package main import ( "fmt" "os" "os/exec" "regexp" "strings" ) type Conf struct { code string arg string } func main() { var args []string for _, envVar := range os.Environ() { if (len(envVar) > 13 && string(envVar[0:13]) == "PLUGIN_SONAR.") { args = append(args, "-D" + toCamelCase(envVar[7:le...
// 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 ( "net/http" "time" "fmt" "log" "os" ) func main() { myMux := http.NewServeMux() myMux.HandleFunc("/", someFunc) server := http.Server{ Addr: ":8080", ReadTimeout: time.Duration(10) * time.Second, WriteTimeout: time.Duration(5) * time.Second, Handler: myMux, } ...
package models import ( "context" "github.com/tsingsun/go-oauth2" ) type Client struct { oauth2.Entity oauth2.ClientEntity } type ClientRepository struct { oauth2.ClientRepositoryInterface Db string } func (c *ClientRepository) GetClientEntity(ctx context.Context,clientIdentifier string, grantType oauth2.Gran...
package contracts import ( "github.com/pedromss/kafli/model" ) // Consumable represents something that can be consumed and for that only these // two operations were deemed necessary as we need to know if we can consume and // how many elements there are. SHOULD find a better name for this type Consumable interface ...
package repository import ( "github.com/TodoApp2021/gorestreact/pkg/models" "github.com/jackc/pgx/v4/pgxpool" ) type Authorization interface { CreateUser(user models.User) (int, error) GetUser(username, password string) (models.User, error) } type TodoList interface { Create(userId int, list models.TodoList) (i...
package main import ( "encoding/json" "net/http" "strconv" ) const ( errorUnauthorized = "unauthorized" errorBadMethod = "bad method" errorUnknownMethod = "unknown method" ) func ResponseWrite(w http.ResponseWriter, responseCode int, errorMessage string, actionResult interface{}) { result := make(map[str...
package student import ( "fmt" ) var AllStudents []*Student type Student struct { Username string Sex int Grade int Score float32 } func NewStudent(username string, sex, grade int, score float32) (stu *Student) { stu = &Student{ Username: username, Sex: sex, Grade: grade, Score: ...
package core import ( "sync" "github.com/jonmorehouse/gatekeeper/gatekeeper" ) type Subscriber interface { starter stopper AddUpstreamEventHook(gatekeeper.Event, func(*UpstreamEvent)) error } func NewSubscriber(broadcaster Broadcaster) Subscriber { return &subscriber{ hooks: make(map[gatekeeper.Event...
package main import ( "flag" "net/http" "github.com/CardInfoLink/bubble-gum/channelMock" "fmt" ) func main() { startMock() } func startMock() { flag.IntVar(&channelMock.MbpSleep, "mbpSleep", 0, "Sleep [mbpSleep] ms before mybank responds") flag.Parse() http.HandleFunc("/mock/alp", channelMo...
package main import ( "net/http" "github.com/labstack/echo" "github.com/labstack/echo/engine/standard" "os" "fmt" "io/ioutil" "net/url" "github.com/labstack/echo/middleware" "time" ) const SEPERATOR string = "_" var GEOCODE_KEY string var WEATHER_KEY string var dynCache map[string]string var staticCache ma...
package lang import ( "fmt" "testing" ) func TestAdder(t *testing.T) { pos, neg := adder(), adder() for i := 0; i < 10; i++ { fmt.Println( pos(i), neg(-2*i), ) } }
package invoice import ( "fmt" "github.com/imrenagi/go-payment" "github.com/imrenagi/go-payment/util/validator" ) var ( emailValidator = validator.EmailValidator{} phoneValidator = validator.PhoneNumberValidator{} ) // NewBillingAddress ... func NewBillingAddress(fullName, email, phoneNumber string) (*BillingA...
package controller import ( "encoding/json" "github.com/bearname/videohost/internal/common/caching" "github.com/bearname/videohost/internal/common/infrarstructure/transport/controller" "github.com/bearname/videohost/internal/videoserver/domain" "github.com/bearname/videohost/internal/videoserver/domain/dto" "net...
package main import ( "fmt" "math" ) type ErrNegativeSqrt float64 func (e ErrNegativeSqrt) Error() string { return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e)) } func Sqrt(x float64) (float64, error) { if x < 0 { return 0, ErrNegativeSqrt(x) } z, epsilon := x, 1e-5 for i := 0; i < 10; i++ { ...
package websockets import ( "encoding/json" "errors" "math/rand" "net/http" "strings" "github.com/go-chi/chi" "github.com/gorilla/websocket" "github.com/steam-authority/steam-authority/logging" ) const ( PageChanges = "changes" PageChat = "chat" PageNews = "news" PagePrices = "prices" PageProfile...
package wallet import ( "pmdgo/conf" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/shopspring/decimal" "context" "pmdgo/services/wallet/tokens" "pmdgo/services/wallet/connector/go_ethereum_conn" "pmdgo/services/wallet/connector/ethrpc" "github.com/gar...
package user import ( "net/http" "github.com/gomeetups/gomeetups/models" "github.com/pressly/chi" "github.com/pressly/chi/render" ) func handleSearch(services *models.Services) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var params = models.ValidUserSearchParams{ DisplayName: ...
// This file is subject to a 1-clause BSD license. // Its contents can be found in the enclosed LICENSE file. package main import ( "flag" "fmt" "github.com/jteeuwen/evdev" "os" "os/signal" "strings" ) func main() { node := parseArgs() // Create and open our device. dev, err := evdev.Open(node) if err != ...
package main import ( "errors" "fmt" "sync" "time" ) var stopErrCh = make(chan struct{}) var stopOkCh = make(chan struct{}) var errCountCh = make(chan int) // handler run goroutines with values received from channel. func handler(in chan func() error) { var wg sync.WaitGroup var i int for fn := range in { w...
package app import ( "errors" "fmt" "reflect" "sync" "sync/atomic" ) const ( _DefaultMethodNameForDependencyInjection = "DependOn" ) // ApplicationContainer support simple object container // If object provide 'DependOn' method with several parameters as dependencies, // then DI will be effective and dependenc...
package models import ( "time" ) // Task represents task table type Task struct { ID int64 `json:"id"` Title string `json:"title"` Description string `json:"description" validate:"required"` CreatedBy *User `json:"user" validate:"required"` IsComplete bool `json:"isComplete"...
package watchgod import ( "fmt" ) func ExecuteArgument(arguments []string, configuration Configuration, usage func()) { nbArgs := len(arguments) switch nbArgs { case 0: usage() case 1: switch arguments[0] { case "boot": Boot(IpcServerUrl(configuration.IPCServerURL), configuration) case "list": cli...
/* Copyright 2019 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 writing, software dis...
package main import ( "strconv" "github.com/tddhit/tools/log" "github.com/tddhit/bindex" ) func main() { b, err := bindex.New("../bindex.idx", false) if err != nil { panic(err) } for i := 1; i <= 10000000; i++ { log.Info(string(b.Get([]byte("hello" + strconv.Itoa(i))))) } //for i := 1; i <= 10000000; i...
/* Challenge Imagine a necklace with lettered beads that can slide along the string. Here's an example image. In this example, you could take the N off NICOLE and slide it around to the other end to make ICOLEN. Do it again to get COLENI, and so on. For the purpose of today's challenge, we'll say that the strings "ni...
package bloom import ( "hash" "log" "math" "github.com/mateuszdyminski/bloom-filter/bitset" "github.com/spaolacci/murmur3" ) // A BloomFilter is a representation of a set of _n_ items, where the main // requirement is to make membership queries; _i.e._, whether an item is a // member of a set. type BloomFilter ...
package account import ( "github.com/bitmaelum/bitmaelum-suite/pkg/address" "github.com/bitmaelum/bitmaelum-suite/pkg/bmcrypto" "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" "os" ) // Create a new account for this address func (r *fileRepo) Create(addr address.HashAddress, pubKey bmcrypto.PubKey) err...
package builder import ( "fmt" "text/template" "github.com/sirupsen/logrus" "github.com/gogap/config" ) type Builder struct { options *Options projects map[string]*Project projectsKeys []string } type Option func(*Options) type Options struct { Config config.Configuration UpdateRepo bool Te...
package magicbytes var CheckMetaData = checkMetaData var WalkDir = walkDir var FindMatch = findMatch var FindMatchWorker = findMatchWorker
// Copyright 2018 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 abstractfactory // FamilyCar TODO type FamilyCar struct{} // NumDoors TODO func (f *FamilyCar) NumDoors() int { return 5 } // NumWheels TODO func (f *FamilyCar) NumWheels() int { return 4 } // NumSeats TODO func (f *FamilyCar) NumSeats() int { return 4 }
package flow import ( "context" "database/sql" "errors" "fmt" "log" "os" "os/signal" "runtime" "strings" "sync" "syscall" "time" "github.com/direktiv/direktiv/pkg/cluster" "github.com/direktiv/direktiv/pkg/dlog" "github.com/direktiv/direktiv/pkg/flow/database" "github.com/direktiv/direktiv/pkg/flow/da...
package gogo import ( "log" "path" "github.com/dolab/logger" ) // AppLogger implements Logger interface type AppLogger struct { *logger.Logger requestId string } func NewAppLogger(output, filename string) *AppLogger { switch output { case "stdout", "stderr", "null", "nil": // skip default: if output[0...
package virtual_security import ( "errors" "reflect" "testing" "time" ) func Test_virtualSecurity_StockOrders(t *testing.T) { t.Parallel() tests := []struct { name string security virtualSecurity service *testStockService want1 ...
package game // WitchOperation kill people func WitchOperation(players []Player) Player { votes := CollectVote(players, players) result := GetVoteResult(votes) return result.target[0] }
package main import ( "fmt" "time" ) func main() { delay := 100*time.Millisecond go spinner(delay) const n = 41 fibN := fib(n) fmt.Printf("\rFibonacci(%d) = %d", n, fibN) } func spinner(delay time.Duration) { for { for _, v := range `-\|/`{ fmt.Printf("\r%c", v) time.Sleep(delay) } } } func fib...
package g import ( "math/rand" "strings" "time" "encoding/binary" "encoding/json" "fmt" "io/ioutil" "log" "net" "os" "sync" "unsafe" "github.com/open-falcon/falcon-plus/common/model" ) func SendZabbixMetrics(metrics []*model.MetricValue) { rand.Seed(time.Now().UnixNano()) wg := sync.WaitGroup{} for...
// ˅ package main // ˄ type ListLink struct { // ˅ // ˄ Link // ˅ // ˄ } func NewListLink(name string, url string) *ListLink { // ˅ listLink := &ListLink{} listLink.Link = *NewLink(name, url) return listLink // ˄ } func (self *ListLink) ToHTML() string { // ˅ return " <li><a href=\"" + self.url + "...
package snapshots import gophercloud "github.com/zhuqinghua/gophercloud" func listURL(c *gophercloud.ServiceClient) string { return c.ServiceURL("snapshots") }
package p_test import ( "runtime" "sync" "testing" "github.com/Kretech/xgo/p" "github.com/Kretech/xgo/test" ) func TestG(t *testing.T) { cas := test.TR(t) cas.Add(func(t *test.Assert) { wg := sync.WaitGroup{} for i := 0; i < 10; i++ { wg.Add(1) go func() { id1 := p.GoID() runtime.Gosched() ...
package sqlbuilder import ( "fmt" . "github.com/smartystreets/goconvey/convey" "testing" ) // Run INSERT using a struct. The `db` tags designate alternate column names; otherwise the verbatim struct property will be used. In this case "Age" is the interpreted column name because that property has no `db` tag. Note...
package longestcommonprefix_test import ( lcp "leetcode/longestcommonprefix" "testing" ) func TestLongestCommonPrefix(t *testing.T) { testCases := []struct { name string strs []string expectedResult string }{ { name: "has common prefix", strs: []string{"flowe...
package apicontrollers import ( "encoding/xml" "io/ioutil" "log" "net/http" "os" "time" "github.com/gin-gonic/gin" "github.com/hsynakin/GORM/dbconnect" "github.com/hsynakin/GORM/models" ) var xmlUsers models.Users func TaxNoResults(c *gin.Context) { var TaxNo = c.Params.ByName("id") ...
package variable_demo import "fmt" /* 定义变量 var关键字表示定义变量,参数名,参数类型 可以出现在包或函数级别 Java定义变量 int a = 4 */ var a int = 4 func VarDefinition() { var b string b = "hi" fmt.Println(a, b) }
package Problem0498 import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) // tcs is testcase slice var tcs = []struct { matrix [][]int ans []int }{ { [][]int{}, []int{}, }, { [][]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, }, []int{1, 2, 4, 7, 5, 3, 6, 8, 9}, }, // 可以有多个 testca...
/* * Copyright 2010-2018 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "lice...
package mongomodel import ( "time" "util" ) type RemoteModel struct { View *DailyRemoteView Typemap map[int]int Interpolate_duration *util.Interpolate } func NewRemoteModel(date time.Time) *RemoteModel { model := RemoteModel{ View: newDailyRemoteView(date), Typemap: make(map...
package server import ( "context" "crypto/tls" "net" "net/http" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tsaikd/KDGoLib/errutil" "github.com/tsaikd/go-grpc-echo/client" "golang.org/x/sync/errgroup" ) func getAddr() (addr string) { lis, err :=...
package http import types "github.com/queueup-dev/qup-types" type Response struct { headers Headers contentType string body types.PayloadReader errors []error httpErrors []HttpError statusCode int } func (r Response) Errors() []error { var combinedErrors []error for _, err := range r.httpE...
package restmachinery import ( "bytes" "errors" "io/ioutil" "net/http" "net/http/httptest" "testing" "github.com/brigadecore/brigade/v2/apiserver/internal/meta" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/xeipuuv/gojsonschema" ) var testSchema = gojsonschema.NewBy...
package main import ( "database/sql" "flag" "fmt" "go/build" "log" "net/http" "path/filepath" "github.com/gorilla/websocket" _ "github.com/mattn/go-sqlite3" //no name needed as it implements the database/sql interface "github.com/ugorji/go/codec" ) type Context struct { db *sql.DB mh codec.Handle } func...
package main import ( "context" "flag" "io" "log" "pancakebasspanda/grpc-message-service/client" "pancakebasspanda/grpc-message-service/protos" ) var ( connectionID string ) func init() { flag.StringVar(&connectionID, "connectionID", "", "unique identifier for the connection") } func main() { ctx := conte...
package main import "fmt" // main send iterator to channel func main() { c := make(chan int) q := make(chan bool) go print_it(c, q) for i := 0; i < 10; i++ { c <- i } q <- true } // print_it print values from channel c func print_it(c chan int, q chan bool) { for { select { case i := <-c: fmt.Printf(...
package dns_test import ( "fmt" "os" "runtime" "github.com/miekg/dns" . "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo/extensions/table" . "github.com/onsi/gomega" . "github.com/kumahq/kuma/pkg/dns" "github.com/kumahq/kuma/pkg/dns/resolver" "github.com/kumahq/kuma/pkg/dns/vips" core_metrics "github.co...
package middleware import ( "testing" "github.com/stretchr/testify/require" ) func TestConfig_ValidateConfig(t *testing.T) { t.Run("OK", func(t *testing.T) { cfg := Config{ Database: DatabaseConfig{ Host: "t.bk.ru", Port: "1234", User: "test", Password: "test", Name: "db"}...
/* Copyright (c) 2022 Red Hat, 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 writing, software...
package csv_conv import ( "io" "reflect" "strings" "testing" ) func TestConverter_ChangeColumnName(t *testing.T) { type fields struct { original [][]string } type args struct { newNames map[string]string } tests := []struct { name string fields fields args args want [][]string wantErr...
// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file ...
package main import ( "fmt" "time" "encoding/json" "github.com/op/go-logging" "github.com/orenb133/twingo" ) func main() { ch1 := make(chan *twingo.MarketBar, 1) logging.SetFormatter(logging.GlogFormatter) logging.SetLevel(logging.INFO, "") listener := twingo.NewMarketDataListener(...
// problem 14.4 package chapter14 func search(root *TreeNode, k int, found_k bool) (*TreeNode, bool) { if root == nil { return nil, found_k } var succ *TreeNode if !found_k { if k == root.Value { return search(root.Right, k, true) } else if k < root.Value { succ, found_k = search(root.Left, k, found...
package databroker import ( "context" "fmt" "net" "strings" "testing" "time" "github.com/stretchr/testify/assert" "google.golang.org/grpc" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/structpb" "github.com/pomerium/pomerium/pkg/protoutil" ) func TestApplyOffsetAndLimit(t *te...
package astar import ( "math" ) const ( maxDefaultMapCapacity = 131072 defaultListCapacity = 4096 ) type nodeInfo struct { node Node parent Node // the node from which we came to get here index int // index of the node in the heap cost float32 // current cost from sta...
package parameters type ( GetMeRequest struct { RootRequest } LoginMeRequest struct { RootRequest Name string `json:"name" mapstructure:"name"` AvatarURL string `json:"avatar_url" mapstructure:"avatar_url"` Location string `json:"location" mapstructure:"location"` } ) func NewGetMeRequest() GetMe...
package lccc_model // 用于描述某一服务的基本信息,如服务名称,服务介绍等 type ServiceBaseInfo struct { ServiceKey string `json:"service_key"` // 服务的唯一标识 ServiceName string `json:"service_name"` // 服务名称 ServiceIntroduce string `json:"service_introduce"` // 服务的介绍 } // 用于描述某一服务的可执行应用的信息,如应用程序版本号等 type ServiceApplication...
package server import ( "context" "fmt" "net/http" "net/url" "os" "os/signal" "strings" "syscall" "time" "github.com/prometheus/client_golang/prometheus" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus" grpctags "git...
package bring import ( "errors" "image" "strconv" "github.com/deluan/bring/protocol" ) // ErrInvalidKeyCode is returned by SendKey if an invalid code is passed var ErrInvalidKeyCode = errors.New("invalid key code") // OnSyncFunc is the signature for OnSync event handlers. It will receive the current screen imag...
package web3 import ( "errors" "github.com/gopherjs/gopherjs/js" ) // Version of the various protocols and apis type Version struct { API string // The ethereum JS api version. js *js.Object } // GetNode takes a callback with node version and error as a params // Returns the client/node version. func (v *Versi...
package main import ( "bytes" "github.com/golang/protobuf/proto" "io" "os" // "database/sql" _ "github.com/alexbrainman/odbc" "log" "net" // "os" // "encoding/json" "fmt" //"github.com/rs/cors" "net/http" "github.com/julienschmidt/httprouter" "text/template" ) //var db *sql.DB var r = httprouter.New()...
package vm import ( ) type ClassLoader struct { loadedClasses map[string]ClassFile } func NewClassLoader() ClassLoader { cl := ClassLoader{} cl.loadedClasses = make(map[string]ClassFile) return cl } func (cl ClassLoader) FindClass(className string, vm *VirtualMachine) ClassFile { loaded, ok := cl.loadedCl...
package util import ( "math/rand" "strings" "time" ) const alphabet = "abcdefghijklmnopqrstuvwxyz" func init() { rand.Seed(time.Now().UnixNano()) } func RandomInt(min, max int64) int64 { return min + rand.Int63n(max-min+1) } func RandomString(n int) string { var sb strings.Builder k := len(alphabet) for i ...
package model import ( "encoding/json" "io/ioutil" "log" "os" "sort" "time" ) var ( UnreadMails = UnreadEmails{} AppConfig *Config NewEmails = make([]string, 0) CheckTime = 0 Ticker <-chan time.Time ) // UnreadEmails struct for work with unread emails type UnreadEmails struct { EmailMap map[st...
package main import ( "fmt" "github.com/sigmonsays/haproxyctl" ) /* "show env", "show errors *iid", "show backend", "show info", "show info typed", "show map *map", "show acl *acl", "show pools", "show servers state *backend", "show sess", "show sess *sess_id", "show stat *iid *type *sid typed", "show...
/* 命題 「パタトクカシーー」という文字列の1,3,5,7文字目を取り出して連結した文字列を得よ。 */ package main import ( "strings" "fmt" ) func main(){ str := "パタトクカシーー" slice := strings.Split(str, "") var oddStr string for i := range slice { if (i + 1) % 2 == 0 { continue } oddStr += slice[i] } fmt.Println(oddStr) // => パトカー }
package main import "fmt" type ByteSize float64 const ( KB ByteSize = 1000 MB = KB * KB GB = MB * KB TB = GB * KB PB = TB * KB EB = PB * KB ZB = EB * KB YB = ZB * KB ) func main() { fmt.Printf("%g\n", KB) fmt.Printf("%g\n", MB) fmt.Printf("%g...
package eventbus import ( "reflect" "github.com/panjf2000/ants/v2" ) // EventBus event bus type EventBus interface { EventPublisher EventSubscriber Release() } // EventPublisher event publisher type EventPublisher interface { Publish(events ...Event) error } // EventSubscriber event subscriber type EventSubs...
package baremetal // Metadata contains baremetal metadata (e.g. for uninstalling the cluster). type Metadata struct { LibvirtURI string `json:"libvirtURI"` BootstrapProvisioningIP string `json:"bootstrapProvisioningIP"` ClusterProvisioningIP string `json:"provisioningHostIP"` }
package server import ( "go-binar/product/repository" "go-binar/product/repository/sqlite" "go-binar/response" "net/http" "github.com/jmoiron/sqlx" "github.com/labstack/echo" ) type ServerV2 struct { ProductRepo repository.ProductRepository } func NewServerV2(db *sqlx.DB) (*ServerV2, error) { s := ServerV2{...
package human import ( "fmt" "math" "math/rand" //"time" "github.com/siggy/bbox/bbox/color" "github.com/siggy/bbox/bbox/leds" "github.com/siggy/bbox/beatboxer/render/web" "github.com/siggy/rpi_ws281x/golang/ws2811" //log "github.com/sirupsen/logrus" ) const ( // 1x heart, 1x human STRAND_COUNT1 = 8 STRA...
package envreader import ( "os" "strconv" ) // ReadEnvAsInt reads env variable and converts it to string, if not found or failed returns default value func ReadEnvAsInt(envName string, defaultValue int) int { envValue, exists := os.LookupEnv(envName) if !exists { return defaultValue } integerEnvValue, err :=...
package types type Auth struct { Jwt string `json:"jwt"` MustChangePassword bool `json:"must_change_password"` }
package main import ( "github.com/merisho/snakegame/game" "github.com/merisho/snakegame/presenter" "github.com/merisho/snakegame/snake" "github.com/merisho/snakegame/view" "github.com/zetamatta/go-getch" "time" ) const ( up = 119 right = 100 down = 115 left = 97 exit ...
/* # -*- coding: utf-8 -*- # @Author : joker # @Time : 2020-08-13 09:28 # @File : lt_201_Bitwise_AND_of_Numbers_Range.go # @Description : 计算 [n,m]范围内的所有数字的按位与的和 # @Attention : 思路呢,因为是按位与,所以一旦某个位置有0,必然为0 因此只需要找到公共前缀即可 */ package byte func rangeBitwiseAnd(m int, n int) int { count := 0 for m != n { m >>= 1 n >>...
// Copyright 2021 BoCloud // // 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 wri...
package handler import ( "os" "strings" "golang.org/x/crypto/bcrypt" ) const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func RandomString(n int) string { // b := make([]byte, n) // for i := range b { // b[i] = letterBytes[rand.Intn(len(letterBytes))] // } // return string(b) has...
package router import ( "net/http" "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/mongo" "github.com/damocles217/server/database" "github.com/damocles217/server/middlewares" "github.com/damocles217/server/router/user" ) type App struct { Router *mux.Router Collection *mongo.Collection } func (a ...
package model // Price is the model for Bitex's response type Price struct { Last float32 `json:"last"` PriceBeforeLast float32 `json:"price_before_last"` Open float32 `json:"open"` High float32 `json:"high"` Low float32 `json:"low"` Vwap float32 `json:"vwa...