text
stringlengths
11
4.05M
/* * Copyright 2018 Haines Chan * * This program is free software; you can redistribute and/or modify it * under the terms of the standard MIT license. See LICENSE for more details */ package anchor import ( "fmt" "github.com/containernetworking/cni/pkg/types" "github.com/containernetworking/cni/pkg/types/cur...
/* You will be given a collection of five cards (representing a player's hand in poker). If your hand contains at least one pair, return an array of two elements: true and the card number of the highest pair (trivial if there only exists a single pair). Else, return false. Examples highestPair(["A", "A", "Q", "Q", "...
package server import ( "testing" //"fmt" "time" ) //import "fmt" func TestStart(t *testing.T) { var a = 1 proc := QProc{} proc.Start() a++ time.Sleep(10 * time.Second) //fmt.Println("before push") proc.Push() time.Sleep(10 * time.Second) } // func TestPush(){ // } // func TestPop(){ // }
package unionfind // Quick Find:查找快;union操作O(n) // 元素 0 1 2 3 4 5 6 7 8 9 // ------------------- // id 0 1 0 1 0 1 0 1 0 1 // 每个连在一起的组有相同的id type UnionFind1 struct { id []int // id相同连接 count int // 元素个数 } func NewUnionFind1(n int) *UnionFind1 { uf := new(UnionFind1) uf.count = n uf.id = make([]int, ...
package driver import ( "database/sql" "embed" "encoding/base64" "fmt" "io/fs" "strconv" "strings" "github.com/friendsofgo/errors" "github.com/go-sql-driver/mysql" "github.com/volatiletech/strmangle" "github.com/volatiletech/sqlboiler/v4/drivers" "github.com/volatiletech/sqlboiler/v4/importers" ) //go:e...
package models import ( "github.com/astaxie/beego/orm" "time" ) //提币配置表 type TokenskyTibiConfigQueryParam struct { BaseQueryParam StartTime string `json:"startTime"` //开始时间 EndTime string `json:"endTime"` //截止时间 } func (a *TokenskyTibiConfig) TableName() string { return TokenskyTibiConfigTBName() } //提币...
package processor import ( "encoding/json" "fmt" "net" ) type DnsInfo struct { Upstream_dns []string Upstream_dns_file string Bootstrap_dns []string Protection_enabled bool Ratelimit int Blocking_mode string Blocking_ipv4 string Blocking_ipv6 string Edns_cs_enabled b...
// 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 tmp const HubTmp = `package hub{{$module := .ModuleName}} import ( "fmt" "net/http" {{if gt (len .DBS) 0}} {{printf "\"%v/core/database\"" $module}}{{end}} {{range $i,$k := .Handlers}} {{printf "\"%v/handlers/%v_handler\"" $module $i}} {{printf "\"%v/handlers/%v_handler/%v_helper\"" $module $i $i}}{{end}...
package models import ( "fmt" ) // PostRepository handles the CRUD for post. type PostRepository interface { Create(*Post) error Get(*Query) (*Post, error) GetAll(*Query) (*[]Post, error) Update(*Post) error } // DBPostRepository ... type DBPostRepository struct { DB *DB } // NewDBPostRepository ... func NewD...
/* A "guess-that-number" game is exactly what it sounds like: a number is guessed at random by the computer, and you must guess that number to win! The only thing the computer tells you is if your guess is below or above the number. Your goal is to write a program that, upon initialization, guesses a number between 1...
package main import ( "github.com/atymkiv/echo_frame_learning/blog/cmd/subscribers/service" "github.com/atymkiv/echo_frame_learning/blog/pkg/utl/config" "github.com/atymkiv/echo_frame_learning/blog/pkg/utl/nats" "sync" ) func main() { cfg, err := config.Load("./cmd/subscribers/config.json") checkErr(err) nats...
package main /* @Time : 2020-03-12 09:28 @Author : audiRStony @File : 06_scan.go @Software: GoLand */ import ( "fmt" ) func main() { var ( name string age int gender string ) fmt.Println(name,age,gender) //fmt.Scan(&name,&age,&gender) //Scan 扫描,默认以空白为分隔(空格,tab,回车) ...
package main import ( "fmt" "sync" "time" ) /** golang中的 waitGroup,其实就是类似java中的CountDownLatch */ type Counters struct { mu sync.Mutex count uint64 } // 给 Count类添加 Incr方法 func (c *Counters) Incr() { c.mu.Lock() c.count++ c.mu.Unlock() } func (c *Counters) Count() uint64 { c.mu.Lock() defer c.mu.Unlock()...
// Package cache provides real connection to the cache. package cache
package service import ( "fmt" "github.com/asdine/storm/v3" "github.com/jschweizer78/fusion-ng/pkg/service/model" "github.com/mitchellh/mapstructure" ) // SrvUsers is a service for users type SrvUsers struct { DB storm.Node metaData *model.UserQuestion } // NewSrvUsers for user CRUD func NewSrvUsers(db ...
package main import ( "fmt" "runtime" "sync" ) func main() { var np sync.WaitGroup fmt.Println("1st GR:", runtime.NumGoroutine()) increment := 0 ps := 100 np.Add(ps) for i := 0; i < ps; i++ { go func() { v := increment runtime.Gosched() v++ increment = v fmt.Println(increment) np.Done() ...
package main //给定一个二叉树,找出其最大深度。 // //二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 // //说明: 叶子节点是指没有子节点的节点。 // //示例: //给定二叉树 [3,9,20,null,null,15,7], // //3 /// \ //9 20 /// \ //15 7 //返回它的最大深度 3 。 type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func main() { maxDepth(&TreeNode{}) } // 递归 func maxDepth(ro...
package parse import ( "bytes" "encoding/base32" "io" "io/ioutil" "time" "github.com/slotix/dataflowkit/scrape" "github.com/spf13/viper" "github.com/slotix/dataflowkit/storage" ) //storageMiddleware caches Parsed results in storage. type storageMiddleware struct { //storage instance puts fetching results t...
package routers import ( "lasti/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/index", &controllers.MainController{}) beego.Router("/login", &controllers.LoginController{}) beego.Router("/register", &controllers.RegController{}) beego.Router("/home", &controllers.HomeController{}) beego.R...
package handlers_test import ( "crypto/ecdsa" "crypto/elliptic" "encoding/base64" "encoding/json" "math/rand" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/pomerium/pomerium/internal/deterministicecdsa" "github.com/pomerium...
package uniseg import ( "testing" ) type testCase = struct { original string expected [][]rune } // The test cases for the simple test function. var testCases = []testCase{ {original: "", expected: [][]rune{}}, {original: "x", expected: [][]rune{{0x78}}}, {original: "basic", expected: [][]rune{{0x62}, {0x61}, ...
package cookie import ( "crypto/rand" "errors" "fmt" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/stretchr/testify/require" "github.com/pomerium/pomerium/internal/encoding" "github.com/pomerium/pomerium/intern...
package parser import ( "fmt" llp "github.com/romshark/llparser" ) // Parser represents a boolean expression parser type Parser struct { prs *llp.Parser } // NewParser creates a new parser instance func NewParser() (*Parser, error) { parser, err := llp.NewParser(newGrammar(), nil) if err != nil { return nil,...
package manage import ( "log" ) type Manage interface { Error() } func New() { log.Print("ss") }
package ehttp import "testing" func TestParameter_ToSwaggerParameters(t *testing.T) { Parameters := map[string]Parameter{ "id": Parameter{ InPath: &ValueInfo{Type: "string"}, InHeader: &ValueInfo{Type: "string"}, InQuery: &ValueInfo{Type: "string"}, InFormData: &ValueInfo{Type: "string"}, },...
// +build !linux package mount type Mounter struct { } func (m *Mounter) Umount(target string) error { return nil } func (m *Mounter) IsLikelyNotMountPoint(file string) (bool, error) { return true, nil }
/* * Copyright 2018, CS Systemes d'Information, http://www.c-s.fr * * 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 requir...
package aws import ( "os" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/stretchr/testify/assert" ) var ( route53Secret string route53Key string route53Region string domain string ip string liveTest bool ) func init() { route53Key ...
package spec import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai" . "test_formats" ) func TestPositionAbs(t *testing.T) { f, err := os.Open("../../src/position_abs.bin") if err != nil { t.Fatal(err) } s := kaitai.NewStream(f) var h Position...
package worker import ( "encoding/json" "io/ioutil" "time" ) // json: 序列化之后的别名 type Config struct { EtcdEndpoints []string `json:"etcdEndpoints"` EtcdDialTimeout int `json:"etcdDialTimeout"` ScheduleSleepTime time.Duration `json:"scheduleSleepTime"` WorkerSleepTime time.Duration `json:"w...
package vaultengine import ( "fmt" ) // SecretWrite is used for writing data to a Vault instance func (client *Client) SecretWrite(path string, data map[string]interface{}) { infix := "/data/" if client.engineType == "kv1" { infix = "/" } finalPath := client.engine + infix + path finalData := make(map[stri...
package queue import "errors" type Elem int type Node struct { data Elem next *Node } type QueueLink struct { front *Node // 对头 tail *Node // 队尾 length int } func (q *QueueLink) InitQueue() { q.front = new(Node) q.tail = q.front q.length = 0 } func (q *QueueLink) EnQueue(e Elem) { node := new(Node) no...
package chat import ( //"fmt" "github.com/liangdas/mqant/module" "github.com/liangdas/mqant/module/base" "github.com/liangdas/mqant/conf" "github.com/liangdas/mqant/gate" ) //创建模块 var Module = func() module.Module { chat := new(Chat) return chat } //模块定义 type Chat struct{ basemodule.BaseModule } func (m *...
package request import ( "sort" ) // RequestSlice attaches the methods of sort.Interface to []Request, sorting in increasing order. type RequestSlice []Request func (p RequestSlice) Len() int { return len(p) } func (p RequestSlice) Less(i, j int) bool { for k := 0; k < len(p[i]); k++ { if p[i][k] == p[j][k] { ...
package ruby import ( "fmt" "text/template" "strings" "bytes" "log" "unicode" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/protoc-gen-go/plugin" ) var ClientTemplate = `require_relative "./protos/{{.BaseName}}" class {{.ClassName}}C...
package event import ( "log" "github.com/streadway/amqp" ) // queueName is the queue that the consumer listens to. const queueName = "test_queue" // RunEventlistenter consumes and logs events on the queue. func RunEventlistener() { conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") failOnError(err, "F...
package main import ( "fmt" "github.com/user/stringutil" ) func main() { fmt.Printf("Hello, Go.\n") fmt.Printf(stringutil.Reverse("Hello Go reveresed")) }
package boltdb import ( "github.com/boltdb/bolt" ) func NewCache(dbFile string) *bolt.DB { db, err := bolt.Open(dbFile, 0600, nil) if err != nil { panic(err) } return db }
package test import ( "fmt" "math/rand" "testing" ) func TestMerge(t *testing.T) { arr := rand.Perm(10) t.Log(arr) arr = mergeSort(arr) t.Log(arr) } func mergeSort(arr []int) []int { if len(arr) < 2 { return arr } mid := len(arr) / 2 left := arr[:mid] right := arr[mid:] return merge(mergeSort(left),...
package iarnrod import ( "encoding/xml" "errors" "math" "net/http" "github.com/marcinwyszynski/geopoint" ) const ( API_ENDPOINT = "http://api.irishrail.ie/realtime/realtime.asmx/" STATIONS_ENDPOINT = API_ENDPOINT + "getAllStationsXML" ) var ( allStations *StationArray ) // StationArray struct represen...
// Copyright 2020 Winfried Klum // // 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 agree...
package retoil import ( "time" ) type internalDelayedLimitedStrategy struct{ retoilCount uint maxRetoils uint delay time.Duration } // DelayedLimitedStrategy returns an initialized retoil.Strategizer which will only // cause a retoil on a panic() (and not on a return) at most 'maxRetoils' times with //...
package cmd import ( "bytes" "context" "fmt" "io" "log" "net/http" "os" "path" "strings" "github.com/spf13/cobra" "github.com/spf13/viper" ) const ToolName = "direktivctl" var maxSize int64 = 1073741824 func ProjectFolder() (string, error) { projectFile := viper.GetString("projectFile") if projectFile...
package library type Controller struct { BaseUrl string ActionName string ControllerName string methodMapping map[string]func() Body string } func (c Controller) setBashUrl(url string){ c.BaseUrl = url } func (c Controller) setActionName(actionName string){ c.ActionName = actionName } func (c Controller) se...
package leetcode func abs(v int) int { if v < 0 { return -v } return v } func max(a, b int) int { if a > b { return a } return b } func minTimeToVisitAllPoints(points [][]int) int { var prev *[]int ans := 0 for _, p := range points { if prev != nil { ans += max(abs((*prev)[0]-p[0]), abs((*prev)[1]-...
package blog import ( "github.com/jinzhu/gorm" ) type ( User struct { gorm.Model Email string `json:"email" gorm:"type:varchar(100);unique_index"` Password string `json:"password,omitempty"` Token string `json:"token,omitempty"` } ) // AuthUser represents data stored in JWT token for user type AuthU...
package prediction import ( "fmt" "math/big" "github.com/streamingfast/sparkle/entity" pbcodec "github.com/streamingfast/sparkle/pb/dfuse/ethereum/codec/v1" ) func (s *Subgraph) HandlePredictionLockRoundEvent(trace *pbcodec.TransactionTrace, ev *PredictionLockRoundEvent) error { if s.StepBelow(2) { return nil...
package main import ( "net/http" "os" _ "github.com/joho/godotenv/autoload" log "github.com/sirupsen/logrus" "github.com/gorilla/handlers" h "github.com/roger-king/go-ecommerce/pkg/handlers" "github.com/roger-king/go-ecommerce/pkg/models" ) func init() { // Log as JSON instead of the default ASCII formatter...
package crypt import ( "golang.org/x/crypto/bcrypt" ) func Check(hashed string, pass string) bool { err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(pass)) if err == nil { return true } else { return false } } func Hash(pass string) string { password := []byte(pass) // Hashing the password wit...
package main import ( "testing" ) func TestMain(t *testing.T) { inputCommand := []string{"create_parking_lot 6", "park KA-01-HH-1234 White", "park KA-01-HH-9999 White", "park KA-01-BB-0001 Black", "park KA-01-HH-7777 Red", "park KA-01-HH-2701 Blue", "park KA-01-HH-3141 Black", "leave 4", "status", "...
package token const ( // ILLEGAL token ILLEGAL = "ILLEGAL" // EOF end of file EOF = "EOF" // IDENT indenfier IDENT = "IDENT" // INT integer INT = "INT" // ASSIGN operator ASSIGN = "=" // PLUS operator PLUS = "+" // MINUS operator MINUS = "-" // BANG operator BANG = "!" // ASTERISK operator ASTERISK...
package main import "fmt" func main() { var board [3][3]int turn := 0 stop := false // while the game has not ended for stop == false { fmt.Println("Turn", turn) displayBoard(board[:]) fmt.Printf("Player %d, please enter move, or -1 -1 to quit: ", getPlayer(turn)) row, col := 0, 0 fmt.Scanf("%d %d", &...
package main import "fmt" func main() { helloWorld() //1 } func helloWorld() { //#1 fmt.Println("Hello World") //Penulisan Hello World }
// Copyright (C) 2021 Cisco Systems 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 agr...
// Copyright (C) 2017 Google 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 t...
// 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() { fmt.Println(singleNumber([]int{1, 1, 6, 1})) } func singleNumber(nums []int) int { var ans int for i := 0; i < 32; i++ { x := 0 for j, v := range nums { if v != 0 { x += v & 1 nums[j] = v >> 1 } } ans += (x % 3) << i } return ans }
package foreman import ( "testing" "github.com/stretchr/testify/assert" "github.com/quilt/quilt/db" "github.com/quilt/quilt/minion/pb" ) type clients struct { clients map[string]*fakeClient newCalls int } func TestBoot(t *testing.T) { conn, clients := startTest() RunOnce(conn) assert.Zero(t, clients.new...
package geo import ( "math" ) // EarthRadius is the radius of the Earth in meter, UTM, WGS84 const EarthRadius = 6378137 const ( // MiddleSide ... MiddleSide OnSide = 0 // LeftSide ... LeftSide OnSide = 1 // RightSide ... RightSide OnSide = -1 ) // OnSide ... type OnSide int // Rad ... func Rad(degree float...
package internal_service import ( pbUser "Open_IM/pkg/proto/user" "Open_IM/pkg/common/config" "Open_IM/pkg/grpc-etcdv3/getcdv3" "context" "strings" ) func GetUserInfoClient(req *pbUser.GetUserInfoReq) (*pbUser.GetUserInfoResp, error) { etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(conf...
package main import ( "testing" ) func TestMultiplyVectors_Multiply(t *testing.T) { err := load_if("glmcpp.dll") if err != nil { t.Fatal(err) return } mv := MultiplyVectors{} mv.Mat[0], mv.Mat[5], mv.Mat[10], mv.Mat[15] = 1, 1, 1, 1 mv.Mat[12] = 100 mv.Mat[13] = 50 mv.Vectors = append(mv.Vectors, Vector{...
package urlgen_test import ( "math/rand" "testing" "time" "github.com/stretchr/testify/assert" "github.com/go-sink/sink/internal/pkg/urlgen" ) const wantedLength = 6 func TestFunction(t *testing.T) { t.Run("it generates a random string of fixed length", func(t *testing.T) { random := rand.New(rand.NewSourc...
package Problem0395 import ( "strings" ) func longestSubstring(s string, k int) int { if len(s) < k { return 0 } // count 中,记录了每个字母出现的次数 count := make(map[byte]int, len(s)) // maxCount 出现最多字母的出现次数 maxCount := 0 for i := range s { count[s[i]]++ maxCount = max(maxCount, count[s[i]]) } if maxCount < k {...
package nameshake import ( "fmt" sdk "github.com/cosmos/cosmos-sdk/types" abci "github.com/tendermint/tendermint/abci/types" ) // ValidateGenesis validates the provided module genesis state to ensure the // expected invariants holds. (i.e. params in correct bounds, no duplicate validators) func ValidateGenesis(dat...
package data // DoorPosition describes a door position an a maze type DoorPosition struct { side Direction offset int } // NewDoorPosition creates new structure func NewDoorPosition(side Direction, offset int) *DoorPosition { return &DoorPosition{side, offset} } // Side returns a side func (p *DoorPosition) Sid...
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the Lice...
package nominetuk type Domain struct { conn *Conn } // Get domain info func (domain *Domain) Info(domainName string) (DomainInfoResponse, error) { var domainInfoResponse DomainInfoResponse err := domain.encodeDomainInfo(domainName) if err != nil { return domainInfoResponse, err } return domain.processDomainIn...
package todocounter import ( "sync" ) // Counter records things remaining to process. It is needed for complicated // cases where multiple goroutines are spawned to process items, and they may // generate more items to process. For example, say a query over a set of nodes // may yield either a result value, or more ...
package arangodb import ( "fmt" "encoding/json" "github.com/apex/log" "github.com/thedanielforum/arangodb/types" ) type credentials struct { Username string `json:"username"` Password string `json:"password"` } type jwtCredentials struct { jwt string `json:"jwt"` mustChangePass bool `json:"must_...
// Package evdev is a pure Go implementation of the Linux evdev API. package evdev import ( "context" "fmt" "os" "sync" "unsafe" ) const ( // DefaultPollSize is the default number of events to poll. DefaultPollSize = 64 ) // Evdev represents an evdev device. type Evdev struct { fd *os.File pollSize in...
//////////////////////////////////////////////////////////////////////////////// // // // Copyright 2019 Broadcom. The term Broadcom refers to Broadcom Inc. and/or // // its subsidiaries. ...
package dto type ArticleSaved struct { Id int `json:"id" db:"Id"` ArticleId int `json:"article_id" db:"ArticleId"` UserId int `json:"user_id" db:"UserId"` SaveDate *TimeJson `json:"save_date" db:"SaveDate"` }
package rolling import ( "sync" "time" ) const WINDOWSIZE=5 type Number struct { Buckets map[int64]*bucket Mu *sync.RWMutex } type bucket struct { Value int64 } func NewNumber() *Number { rn := &Number{ Buckets: make(map[int64]*bucket), Mu: &sync.RWMutex{}, } return rn } func (rn *Number) g...
package direktivapps import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "net/http" "os" "os/signal" "strings" "syscall" "time" ) const ( DirektivActionIDHeader = "Direktiv-ActionID" DirektivInstanceIDHeader = "Direktiv-InstanceID" DirektivExchangeKeyHeader = "Direktiv-ExchangeKey" Direkti...
package main import ( "bufio" aesext "cm_liveme_im/libs/crypto/aes" rsaext "cm_liveme_im/libs/crypto/rsa" "cm_liveme_im/libs/define" "cm_liveme_im/libs/proto" "crypto/rsa" "encoding/json" "fmt" "net" "time" pb "github.com/golang/protobuf/proto" log "github.com/thinkboy/log4go" ) func initMsgTCP() { sta...
// Triangle package prvoides a function for determining whether 3 sides form a triangle and if so what kind package triangle import "math" type Kind int const ( NaT = iota // not a triangle Equ // equilateral Iso // isosceles Sca // scalene ) // KindFromSides takes 3 sides and determines th...
package main import ( "fmt" "log" "net" "strings" "time" ) type simpleServer struct { listener userlist *userlist msgsChan chan message // channel of messages inbound from clients commands map[string]commandHandler startTime time.Time roomlist []int } func (s simpleServer) roomExists(id int) bool { f...
package main import ( "fmt" "sync/atomic" "time" ) var totalOperations int32 = 0 func increment() { atomic.AddInt32(&totalOperations, 1) } func main() { for i := 0; i < 1000; i++{ go increment() } time.Sleep(2 * time.Millisecond) //expecting totalOperations = 1000, but in fact... fmt.Println("totalOperat...
package main import tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api" func SendKeyboard(u *User, text string) { message := tgbotapi.NewMessage(u.ChatID, text) switch u.State { case InitState: btnStart := tgbotapi.NewKeyboardButton("Start") btnAbout := tgbotapi.NewKeyboardButton("About") btnRow1 :...
package seeders import ( "github.com/jinzhu/gorm" uuid "github.com/satori/go.uuid" "github.com/tespo/satya/v2/types" ) var reminders = types.Reminders{ { ID: uuid.FromStringOrNil("0b703c2b-72c6-43ef-a089-4ce85e06519a"), UserID: uuid.FromStringOrNil("8c8aa229-3959-4a40-bbe6-67c2eeace5cb"), RegimenI...
package requestargs import ( "bytes" "fmt" "github.com/iotaledger/wasp/packages/dbprovider" "github.com/iotaledger/wasp/packages/hashing" "github.com/iotaledger/wasp/packages/kv" "github.com/iotaledger/wasp/packages/kv/kvdecoder" "github.com/iotaledger/wasp/packages/registry" "github.com/iotaledger/wasp/packag...
package router import ( "net/http" "github.com/gorilla/mux" ) type Route struct { Pattern string Method string HandlerFunc http.HandlerFunc } type Routes []Route func NewRouter(routes Routes) *mux.Router { router := mux.NewRouter().StrictSlash(true) for _, route := range routes { handler := Logg...
package main import ( "context" "fmt" "os" "os/signal" . "web-layout/utils/gin/gate" ) func main() { g := NewGate(8080) g.POST("/test", test) g.AddGroup("/group1") g.GET("/test1", test1, "/group1") g.GET("/test2", test2, "/group1") g.AddGroup("/group2") g.GET("/test1", test3, "/group2") g.GET("/test2"...
/* 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 */ /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode *...
package metadata import ( "fmt" "testing" "github.com/stretchr/testify/require" "github.com/root-gg/plik/server/common" ) func TestBackend_GetUploadStatistics(t *testing.T) { b := newTestMetadataBackend() defer shutdownTestMetadataBackend(b) for i := 1; i <= 100; i++ { upload := &common.Upload{Comments: f...
/* Copyright 2011 Google 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 di...
package main import ( "database/sql" "fmt" "html/template" "io" "log" "net/http" "os" "time" "golang.org/x/crypto/bcrypt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/sessions" ) var ( db *sql.DB store = sessions.NewCookieStore([]byte("something-very-secret")) ) func main() { _db, err :=...
package middleware import ( "net/http" "regexp" "strings" "docktor/server/storage" "docktor/server/types" jwt "github.com/dgrijalva/jwt-go" typesDocker "github.com/docker/docker/api/types" "github.com/labstack/echo/v4" log "github.com/sirupsen/logrus" ) // WithUser check if user is auth func WithUser(next ...
/* A company conducted a coding test to hire candidates. N candidates appeared for the test, and each of them faced M problems. Each problem was either unsolved by a candidate (denoted by 'U'), solved partially (denoted by 'P'), or solved completely (denoted by 'F'). To pass the test, each candidate needs to either s...
package rpn import ( "unicode" ) func splitExpression(expression string) (result []string) { var token string for _, char := range expression { if _, ok := operations[char]; ok || !unicode.IsNumber(char) { if len(token) > 0 { result = append(result, token) } if !unicode.IsSpace(char) { ...
package board type Player struct { TotalMoney int Hands Hands }
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //139. Word Break //Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a s...
package main import ( "gopkg.in/mgo.v2" "fmt" "gopkg.in/mgo.v2/bson" "strings" "encoding/json" ) var jobs chan NewUserRecord var done chan bool var counter int64 var activeCounter int64 var inactiveCounter int64 var c1 *mgo.Collection var c *mgo.Collection func main(){ jobs = make(chan NewUserRecord, 10000) ...
package conn import "database/sql" import "fmt" import "time" import _ "github.com/bmizerany/pq" type PgSql struct { db *sql.DB result *sql.Result rows *sql.Rows } func GetPgSql() *PgSql { var pg *PgSql if pg == nil { globalDB, err := sql.Open("postgres", "") if err != nil { fmt.Println(err.Error()...
package _268_Missing_Number func missingNumber(nums []int) int { // return missingNumberWithAdd(nums) return missingNumberWithXor(nums) } func missingNumberWithAdd(nums []int) int { var ( rightSum int realSum int ) rightSum = len(nums) * (len(nums) + 1) / 2 for _, n := range nums { realSum += n } retur...
package logic 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 GetOtherConfigLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext...
/* Input A list of nonnegative integers. Output The largest nonnegative integer h such that at least h of the numbers in the list are greater than or equal to h. Test Cases [0,0,0,0] -> 0 [12,312,33,12] -> 4 [1,2,3,4,5,6,7] -> 4 [22,33,1,2,4] -> 3 [1000,2,2,2] -> 2 [23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,3...
package notifier import ( "fmt" multierror "github.com/hashicorp/go-multierror" "github.com/nlopes/slack" ) // SlackAPIClient describes the methods we use on slack.Client type SlackAPIClient interface { PostMessage(channel, text string, params slack.PostMessageParameters) (string, string, error) } // SlackBacke...
package core import ( "sync" "time" ) func InStrList(value string, list []string) bool { for _, item := range list { if value == item { return true } } return false } func Retry(retries uint, f func() error) error { err := f() if err == nil { return nil } if retries == 0 { return err } return...