text stringlengths 11 4.05M |
|---|
// Package ratedreader provides an implementation of a rate limited io.Reader.
//
// A token bucket algorithm (https://godoc.org/golang.org/x/time/rate) performs
// the rate limiting / scheduling.
package ratedreader
import (
"context"
"io"
"golang.org/x/time/rate"
)
// DefaultBurstSize is the default size of bur... |
package wrapper
import (
"io"
"time"
)
type Rows interface {
Columns() []string
Next() ([]interface{}, error)
Close() error
}
type File interface {
io.Writer
io.Reader
Abort()
io.Closer
ID() string
Size() int64
MD5() string
CreatedAt() time.Time
SetContentType(string)
ContentType() string
Metadata()... |
// +build !disgord_parallelism
package constant
// LockedMethods signifies if the methods of discord objects should handle locking.
// I don't enjoy introducing this, but at the same time, I don't want to completely remove a
// easy way to activate locking for people that require parallel handling of objects.
//
// Y... |
package shared
import (
"time"
)
type LocalUser struct {
Username string `json:"username"`
FullName string `json:"fullName"`
IsEnabled bool `json:"isEnabled"`
IsLocked bool ... |
package repository
import (
"RelationshipMatch/model"
log "github.com/Sirupsen/logrus"
"github.com/go-pg/pg"
)
const (
GetRelationshipSQL = `select status from relationship where user_id=? and other_id=?`
InsertRelationshipSQL = `insert into relationship (user_id, other_id, status, type) values (?,?,?,?)`
U... |
package engine
import (
"errors"
"io"
)
type SelectOptions struct {
StartPage int
EndPage int
EndFlag byte
FlagLimit int
}
// utils
func SelectPages(in io.Reader, out io.Writer, opts *SelectOptions) error {
// process input stream
pageIter, flagIter, writedFlag := 1, 0, false
// deal page with flag '\f... |
package dependencyinjection
import (
"fmt"
"io"
)
func OtherGreet(writer io.Writer, name string) {
_, err := fmt.Fprintf(writer, "Hello, %s", name)
if err != nil {
return
}
}
// func main() {
// OtherGreet(os.Stdout, "Vijay")
// }
|
package aoc2016
import (
"crypto/md5"
"strconv"
"sync"
)
// checkHash checks the first n nibbles (half-octets) of the MD5 of Augend+string(Addend)
// and returns true and the entire hash if the first n nibbles are all zero.
// Otherwise it will return false and the hash.
func checkHash(n int, augend string, addend... |
package main
// https://swtch.com/~rsc/regexp/regexp1.html
// https://swtch.com/~rsc/regexp/nfa.c.txt
import "fmt"
// 将正则表达式的中缀形式转换为后缀形式
func Re2Post(re string) string {
type pframe struct {
nalt int
natom int
}
var paren []pframe
var buf []byte
var (
nalt int // | 分支计数器
natom int // | 操作数计数器
)
for... |
package add_two_numbers
import (
"github.com/stretchr/testify/assert"
"testing"
)
func Test_AddTwoNumbers(t *testing.T) {
var a *ListNode
var b *ListNode
var ab *ListNode
a = NewList([]int{1, 2, 3})
b = NewList([]int{1, 2, 3})
ab = NewList([]int{2, 4, 6})
assert.Equal(t, addTwoNumbers(a, b), ab)
a = NewLi... |
package lib
type BaseResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type UserResponse struct {
ID int `db:"id" json:"id"`
Name string `db:"name" json:"name"`
}
type RegistResponse struct {
UserResponse
}
|
package main
import (
"bytes"
"fmt"
"os"
)
func main() {
fieldstest()
fmt.Println("---------------")
indexRuneTest()
fmt.Println("---------------")
titleTest()
fmt.Println("---------------")
ToTitleTest()
fmt.Println("---------------")
BufferWrite()
fmt.Println("---------------")
}
//fields方法根据空格分割成多个sl... |
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1) //Adds one 'buffer' to the wait group
go doSomething(i, &wg)
}
wg.Wait() //stays active until counter is equals to zero
}
func doSomething(i int, wg *sync.WaitGroup) {
defer wg.Done() //D... |
package main
import (
"errors"
"fmt"
"net"
"os"
"os/signal"
)
func getIPAddr(host string) (net.IP, error) {
ips, err := net.LookupIP(host)
if err != nil {
return nil, err
}
for _, ip := range ips {
if ip.To4() != nil {
return ip.To4(), nil
}
}
return nil, errors.New("IP address not found")
}
ty... |
package _func
import (
"github.com/tal-tech/go-zero/core/logx"
"net/http"
"strconv"
"tpay_backend/merchantapi/internal/common"
)
func GetLoginedUserIdRequestHeader(r *http.Request) (int64, error) {
userIdStr := r.Header.Get(common.RequestHeaderLoginedUserId)
// 验证是否是int64
userId, err := strconv.ParseInt(userI... |
package command
import (
"fmt"
"sort"
"strings"
"sync"
)
// Callback is a function that can be attached to a command
type Callback func(data *Data)
// Command represents a fireable command
type Command interface {
AdminRequired() int
Fire(data *Data)
Help() string
Name() string
fmt.Stringer
}
// SingleComm... |
/*
https://developer.github.com/v3/issues
*/
package githubLib
import (
"encoding/json"
)
type Label struct {
Url string
Name string
Color string
}
func (label *Label) Marshal() string {
content, _ := json.MarshalIndent(label, "", " ")
return string(content)
}
func LabelFrom(value string) (label Label, va... |
package idonia_share
import (
"bitbucket.org/inehealth/idonia-pacs/service/idonia/idonia"
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
type PostTransferFile_FileIDReq struct {
Email string `json:"email"`
Phone string `json:"phone"`
}
type PostTransferFile_FileIDRes s... |
package main
import (
"bytes"
"fmt"
"github.com/seizethedave/advent2019/advent04"
)
func hasRepeat(digits []byte) bool {
for i := 0; i < len(digits)-1; i++ {
if digits[i] == digits[i+1] {
return true
}
}
return false
}
func main() {
// given was 124075, 124444 was next proper value.
digits := []byte{... |
package server
import (
"context"
"fmt"
uuid "github.com/satori/go.uuid"
"github.com/batchcorp/plumber-schemas/build/go/protos"
"github.com/batchcorp/plumber-schemas/build/go/protos/common"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
)
func (s *Server) GetAllTunnels(_ context.Context, req *pro... |
package main
import (
"bytes"
"flag"
"fmt"
"log"
"strconv"
"strings"
"sync"
parser "github.com/marcsantiago/app-review-parser"
)
var headersOnce sync.Once
func printHeadersOnce(e parser.Entry) {
headersOnce.Do(func() {
fmt.Println(strings.Join(e.QuickHeaders(), "\t"))
})
}
// example run
// go run main... |
package main
import (
"fmt"
"runtime"
"os"
"math/rand"
"time"
)
const c = 1 //常量
var v int = 5 //变量
type T struct {
value float64
}
func init() {
fmt.Println("init func")
}
func main() {
//a1,b1 := 10,0
//c := a1 / b1 //panic: runtime error: integer divide by zero
//print(c)
fmt.Println("hello world ... |
package dp
func knapsack(weight []int, w int) int {
n := len(weight)
dp := make([][]bool, n)
// 默认值false
for i := 0; i < n; i++ {
dp[i] = make([]bool, w+1)
}
// 第一行的数据要特殊处理,可以利用哨兵优化
dp[0][0] = true
if weight[0] < w {
dp[0][weight[0]] = true
}
// 动态规划
for i := 1; i < n; i++ { // 动态规划状态转移
for j := 0; j... |
package router
import (
v1 "gin-vue-admin/api/v1"
"gin-vue-admin/middleware"
"github.com/gin-gonic/gin"
)
func InitCertHolderRouter(Router *gin.RouterGroup) {
CertHolderRouter := Router.Group("cert").Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
CertHolderRouter.POST("getCertHolderList", v1.GetCertHo... |
package telnet
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xackery/log"
"github.com/xackery/talkeq/config"
)
func TestConvertLinks(t *testing.T) {
assert := assert.New(t)
//[\x1200046F000000000000000000000000000000000000000Mask of Tinkering\x12]
//latest looks like this
//\... |
package task
import (
"logicdata/entity"
"server"
"server/data/datatype"
"time"
)
type PlayerTask struct {
server.Callee
}
func (pl *PlayerTask) OnReady(self datatype.Entity, first bool) int {
if first {
Module.GetCore().Kernel().AddHeartbeat(self, "CheckTask", time.Minute, -1, nil)
Module.TaskSystem.Check... |
package cmd
import (
"os"
"path/filepath"
"github.com/spf13/cobra"
)
var encodingKey string
var rootCmd = &cobra.Command{
Use: "secret",
Short: "secret is secrets manager CLI Application",
}
// Execute it will adds all child commands to the root command.
//It only needs to happen once to the rootCmd.
func Ex... |
package main
import (
"flag"
"fmt"
"log"
"math"
"os"
"os/signal"
"sort"
"time"
"github.com/nuttapp/pinghist/dal"
"github.com/nuttapp/pinghist/ping"
"github.com/olekukonko/tablewriter"
)
var (
d *dal.DAL
host string
showExamples bool
start string
end ... |
package mqtt
import (
"testing"
"time"
"mqtt-adapter/src/config"
"mqtt-adapter/src/logger"
"github.com/sirupsen/logrus"
)
func TestNewClient(t *testing.T) {
svr := getMockServer()
defer svr.Close()
go svr.ListenAndServe(mockURL)
<-time.After(time.Millisecond * 100)
testCases := []struct {
name strin... |
package day15
import (
"testing"
"github.com/kdeberk/advent-of-code/2019/internal/utils"
)
const part1Answer = 304
const part2Answer = 310
func TestPart1(t *testing.T) {
program, err := utils.ReadProgram("./../../input/15.txt")
if err != nil {
t.Fatal(err)
}
remote := newRemoteControl(program)
answer := ... |
package tcp
import (
"bufio"
"context"
"godis/src/lib/logger"
"godis/src/lib/sync/atomic"
"godis/src/lib/sync/wait"
"io"
"net"
"sync"
"time"
)
type Client struct {
// tcp 连接
Conn net.Conn
// 当服务端开始发送数据时进入 waiting 状态, 阻止其他 goroutine 关闭连接
Waiting wait.Wait
}
func (c *Client) Close() error {
c.Waiting.Wai... |
/*
Your local bank has decided to upgrade its ATM machines by incorporating motion sensor technology. The machines now interpret a series of consecutive dance moves in place of a PIN number.
Create a program that converts a customer's PIN number to its dance equivalent. There is one dance move per digit in the PIN nu... |
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"regex/solve"
"regexp"
_ "strconv"
"strings"
"unicode"
)
var expr string
var set=make(map[string]interface{})
var arr []string
var match [][]string
var count int=0
func home(c *gin.Context){
for k:= range set{
delete(set,k)
}
c.HTML(http.... |
package run_actions
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"github.com/cloudfoundry-incubator/executor/api"
"github.com/cloudfoundry-incubator/executor/registry"
"github.com/cloudfoundry-incubator/executor/sequence"
"github.com/cloudfoundry-incubator/executor/transformer"
"github.c... |
package metrics
import (
"go.uber.org/atomic"
"time"
)
type TimedMetrics struct {
SpawnCount,
DieCount,
DropCount,
RemoteDropCount,
UnhandledCount,
ReceiveTotalCount,
ReceiveRemoteCount,
SendLocalCount,
SendRemoteCount int32
}
type TimedRecorderHook interface {
Record(metrics TimedMetrics)
}
func NewTim... |
package rest
import (
"fmt"
"time"
"github.com/jinmukeji/jiujiantang-services/pkg/rest"
corepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
generalpb "github.com/jinmukeji/proto/v3/gen/micro/idl/ptypes/v2"
"github.com/kataras/iris/v12"
)
// Schedule 推送时间表
type Schedule struct {
EventHapp... |
package users
import (
"io"
"io/ioutil"
"log"
"github.com/pkg/errors"
. "2019_2_IBAT/pkg/pkg/models"
)
func (h *UserService) CreateRespond(body io.ReadCloser, record AuthStorageValue) error { //should do this part by one r with if?
if record.Role != SeekerStr {
// log.Printf("Invalid action: %s", err)
ret... |
package pleasanter
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
)
const (
getPath = "%v/api/items/%v/get"
)
type ItemRequest struct {
requestBase
Offset int64 `json:"Offset,omitempty"`
View *View `json:"View,omitempty"`
}
type ItemResult struct {
StatusCode int `json:"Statu... |
package common
const (
ConsumerGoSDK = "sdkat_consumer_gosdk"
ConsumerMesher = "sdkat_consumer_mesher"
ProviderGoSDK = "sdkat_provider_gosdk"
ProviderMesher = "sdkat_provider_mesher"
)
const (
EnvPlatform = "PLATFORM"
EnvServiceName = "SERVICE_NAME"
EnvVersion = "VERSION"
EnvAppId = "AP... |
package controllers
import (
"net/http"
"github.com/dmdinh22/go-blog/api/responses"
)
// Home godoc
// @Summary Main route to check API is running
// @Produce json
// @Tags home
// @Success 200
// @Router /api [get]
func (server *Server) Home(w http.ResponseWriter, r *http.Request) {
responses.JSON(w, http.Status... |
package server
import (
"bytes"
"encoding/base64"
"fmt"
"path/filepath"
"github.com/go-yaml/yaml"
"k8s.io/kubernetes/pkg/apis/abac"
"k8s.io/kubernetes/pkg/apis/abac/v1beta1"
"k8s.io/kubernetes/pkg/runtime/serializer/json"
"github.com/coreos/tectonic-installer/installer/server/asset"
)
type secret struct {
... |
package runit
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
. "github.com/anthonybishopric/gotcha"
)
func TestRunitServicesCanBeStarted(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "runit_service")
os.MkdirAll(filepath.Join(tmpdir, "supervise"), 0644)
Assert(t).IsNil(err, "test set... |
/*
图片化浏览某个目录
如果浏览目录dir1,则需要目录${dir1}支持或提供以下特性:
- ${dir1}/thumb.jpg # 用于封面图 可以是.jpg,.png,.gif
- ${dir1}/thumbs/ # 用于存放原图对应的缩略图
- 目录名称当前图集显示名称
// done: cache, paysapi, static fs, page
// todo: multi domain, login/register, pay and access, advertise, shopping mall, bitpay, ethereum pay,
, fake order, friendly ... |
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
... |
package Problem0375
func getMoneyAmount(n int) int {
// dp[i][j] 保证能猜出 i<=x<=j 中 x 的具体值的最小金额
// dp[1][n] 是答案
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, n+1)
}
for j := 2; j <= n; j++ {
for i := j - 1; 0 < i; i-- {
// 为了确保可以猜出 i<=x<=j 中的 x
// 第一次,我们可以猜 x 为,i,i+1,...,j-1
// 所有这些... |
// 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 (
"github.com/gin-gonic/gin"
"gogin/router"
)
func main() {
e := gin.Default()
router.Router(e)
e.Run(":3000")
}
|
package stack
import (
"github.com/cheekybits/genny/generic"
"sync"
)
type Item generic.Type
type ItemStack struct {
items []Item
lock sync.RWMutex
}
// 创建栈
func (s *ItemStack) New() *ItemStack {
s.items = []Item{}
return s
}
// 入栈
func (s *ItemStack) Push(t Item) {
s.lock.Lock()
s.items = append(s.items,... |
package graph
import (
"context"
"database/sql"
"fmt"
"net/http"
"time"
"github.com/99designs/gqlgen/graphql/handler/extension"
"github.com/syncromatics/kafmesh/internal/graph/generated"
"github.com/syncromatics/kafmesh/internal/graph/loaders"
"github.com/syncromatics/kafmesh/internal/graph/resolvers"
"git... |
package main
import (
"log"
"net/http"
"os"
"bufio"
"strings"
"io/ioutil"
)
func isNodeInStaticList(enode string, datadir string) (bool, error) {
file, err := os.Open(datadir + "/static-nodes.json")
if err != nil {
return false, err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scan... |
package main
import (
"encoding/binary"
. "scommon"
)
const (
PACKET_ID_DEV_ECHO_REQ = 192
PACKET_ID_DEV_ECHO_RES = 193
)
type Header struct {
TotalSize int16
ID int16
PacketType int8 // 비트 필드로 데이터 설정. 0 이면 Normal, 1번 비트 On(압축), 2번 비트 On(암호화)
}
// Header의 PacketID만 읽는다
func peekPacketID(rawData []by... |
package main
import "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter4/global"
func main() {
if err := global.UseLog(); err != nil {
panic(err)
}
}
|
// package pipeline implements a system for running data pipelines on top of the filesystem
package pipeline
import (
"bufio"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path"
"strings"
"sync"
"time"
"github.com/fsouza/go-dockerclient"
"github.com/pachyderm/pachyderm/src/btrfs"
"github.com/pac... |
package main
import (
"fmt"
"github.com/unixpickle/learn-quantum/quantum"
)
const maxCircuitCache = 5000000
func AllGates(numBits int, includeCCNot bool) []quantum.Gate {
var result []quantum.Gate
for i := 0; i < numBits; i++ {
result = append(result, &quantum.HGate{Bit: i})
result = append(result, &quantum... |
// Package frames process dc6 frame data
package frames
|
package svc
import (
"github.com/tal-tech/go-zero/core/stores/sqlx"
"shorturl/rpc/expand/internal/config"
"shorturl/rpc/model"
)
type ServiceContext struct {
c config.Config
Model *model.ShorturlModel
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
c: c,
Model: model... |
package users
import (
"math/rand"
"testing"
)
import "github.com/dchest/uniuri"
func TestPasswordHashing(t *testing.T) {
stdlen := 0
hash := ""
passwordValid := false
var err error
for i := 0; i < 20; i++ {
// generate a random password
stdlen = int(rand.Intn(10) + 5)
password := uniuri.NewLen(stdlen)
... |
package utils
import "sort"
func BubbleSort(elements []int) {
for i := 0; i < len(elements); i++ {
for j := i + 1; j < len(elements); j++ {
if elements[i] > elements[j] {
elements[i], elements[j] = elements[j], elements[i]
}
}
}
}
func Sort(elements []int) {
if len(elements) < 1000 {
BubbleSort(el... |
// Copyright 2013 hanguofeng. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package gocaptcha
import (
"time"
)
// CaptchaInfo is the entity of a captcha
// text:the content text,for the image display and user to recognize
// createTime:... |
/*
Create a function takes in two arrays and returns an intersection array and a union array.
Intersection Array: Elements shared by both.
Union Array: Elements that exist in first or second array, or both (not exclusive OR).
While the input arrays may have duplicate numbers, the returned intersection and un... |
package main
import (
"log"
"regexp"
"strings"
"github.com/fiam/gounidecode/unidecode"
)
func urlize(s string) string {
reg, err := regexp.Compile("[^A-Za-z0-9]+")
if err != nil {
log.Println(err)
}
url := reg.ReplaceAllString(unidecode.Unidecode(s), "-")
url = strings.ToLower(strings.Trim(url, "-"))
... |
package main
import (
"flag"
"time"
"github.com/segmentio/ksuid"
)
type Cmd struct {
bind string
remote string
healthTick time.Duration
healthExpiry time.Duration
instanceID string
clusterConnect string
clusterBind string
remoteUser string
remotePassword string
}
func ... |
// Copyright 2015 Google Inc. 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 law... |
package main
import (
"fmt"
)
// array com tamanho 5
var x [5]int
// array com valores iniciais
// [1, 2, 3, 0, 0]
var y [5]int = [5]int{1, 2, 3}
func main() {
x[0] = 1
x[1] = 10
// x[7] = 20 // error
fmt.Println(x[0], x[1])
fmt.Println(x)
fmt.Printf("%T\n", x)
fmt.Println(len(x))
fmt.Println(y)
}
|
package dp
import "testing"
func TestMaxSubArray(t *testing.T) {
// 4, -1, 2, 1
array := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
println(maxSubArray1(array))
println(maxSubArray2(array))
}
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package controlclient
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"strings"
"time"
"github.com/tailscale/wireguard-go/w... |
package main
import (
"2021/shared"
"fmt"
"strings"
"sort"
"strconv"
)
func main() {
// input := shared.ReadInput("day8/input")
input := shared.ReadInput("day8/example")
part1 := part1(input)
part2 := part2(input)
fmt.Printf("\nPart 1 answer: %d\n\n", part1)
fmt.Printf("\nPart 2 answer: %d\n\n", part2)
... |
package dbrepository
import (
"database/sql"
"fmt"
// driver package
_ "github.com/mattn/go-sqlite3"
)
var db *sql.DB
var initDB = sql.Open
// InitDatabase function used to initialized the sqlite3 db
func InitDatabase(dbPath string) error {
var err error
db, err = initDB("sqlite3", dbPath)
if err != nil {
... |
package gof
import (
"sync"
"github.com/atcharles/gof/v2/g2cache"
"github.com/atcharles/gof/v2/g2cmd"
"github.com/atcharles/gof/v2/g2db"
"github.com/atcharles/gof/v2/g2emq"
"github.com/atcharles/gof/v2/g2gin"
"github.com/atcharles/gof/v2/g2util"
"github.com/atcharles/gof/v2/j2rpc"
)
// App ...
var App = new(... |
package event
//群聊事件
import (
"fmt"
"github.com/Mrs4s/MiraiGo/client"
"github.com/balrogsxt/xtbot-go/util/msg"
)
//收到群成员发送消息事件
func OnGroupMessageEvent(event *msg.GroupHandle) {
//m := handle.BuildMsg()
//m.Add(handle.MsgBuild.LocalImage("./test/1.jpg")) //发送本地图片
//m.Add(handle.MsgB... |
// Package googlegeocode is used to make queries to the Google Geocode API.
//
// Initilizing the package will create one file called .geocoder-data on your machine that stores your api key and information necessary to ensure that api limits arean't exceed. It will prompt you to enter your google geocode api key for la... |
package connect
import (
"context"
"fmt"
"github.com/go-redis/redis"
"github.com/lifenglin/micro-library/helper"
"github.com/sirupsen/logrus"
"path/filepath"
"sync"
"time"
)
var rds *Rds
type Rds struct {
sync.RWMutex
Map map[string]*redis.ClusterClient
MapRedis map[string]*redis.Client
}
type Redis... |
package repository
import "github.com/jmoiron/sqlx"
type Authorization interface {
}
type TodoList interface {
}
type TodoItem interface {
}
type Repository struct {
Authorization
TodoItem
TodoList
}
func NewRepository(db *sqlx.DB) *Repository {
return &Repository{
Authorization: nil,
TodoItem: nil,
... |
/*
Given two 1d vectors, implement an iterator to return their elements alternately.
Example:
Input:
v1 = [1,2]
v2 = [3,4,5,6]
Output: [1,3,2,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next
should be: [1,3,2,4,5,6].
Follow up: What if you are gi... |
package mysql
import (
"fmt"
"github.com/jmoiron/sqlx"
"github.com/vincentserpoul/playwithsql/status/islatest"
)
// InsertOne will insert a Entityone into db
func (link *Link) InsertOne(exec sqlx.Ext) (id int64, err error) {
res, err := exec.Exec(`INSERT INTO entityone VALUES()`)
if err != nil {
return id, f... |
package users
import (
"database/sql"
"fmt"
"github.com/AyokunlePaul/book_users-api/datasources/mysql/users_db"
"github.com/AyokunlePaul/book_users-api/domain/response"
"github.com/AyokunlePaul/book_users-api/logger"
"github.com/AyokunlePaul/book_users-api/utils/errors"
"github.com/VividCortex/mysqlerr"
"githu... |
/**
* Copyright (C) 2019, Xiongfa Li.
* All right reserved.
* @author xiongfa.li
* @version V1.0
* Description:
*/
package oauth2
import (
"github.com/emicklei/go-restful"
"net/http"
"github.com/xfali/oauth2/defines"
)
func ProcessRevokeToken(auth *OAuth2, request *restful.Request, response *restf... |
package main
type Permalink struct {
Url string `json:"url"`
Vertical string `json:"vertical"`
City string `json:"city"`
Town string `json:"town"`
}
type Photos struct {
Thumb string `json:"thumb"`
ThumbRetina string `json:"thumb_retina"`
Small string `json:"small"`
SmallRetina string `json:"small_r... |
package main
import "fmt"
func main(){
}
//闭包 闭包指的是一个函数和与其相关的引用环境组合而成的实体。简单来说,闭包=函数+引用环境。
func closureAdder() func(int) int {
var x int
return func(y int) int {
x += y
return x
}
}
func closure(){
var f = closureAdder()
fmt.Println(f(10)) //10
fmt.Println(f(20)) //30
fmt.Println(f(30)) //60
f1 := clos... |
package main
import (
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/thedevsaddam/govalidator"
)
// Respond Function Is To Handel Http Returns With A Json.
func Respond(c echo.Context, payload map[string]interface{}, status int, success bool) error {
return c.JSON(statu... |
// Copyright 2020. Akamai Technologies, 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... |
package storage
import (
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/boltdb/bolt"
"github.com/empirefox/ic-client-one/ipcam"
)
const jsonContent = `{
"DbPath": "%s",
"RecDir": "/tmp/ic-client-one-rec-dir",
"WsUrl": "ws://127.0.0.1:9998",
"PingSecond": 50,
"Stuns": [
"stun3.l.google.com:19302",
... |
package dal
import (
"math"
"time"
)
// PingGroup is used to summarize the output of the pings_by_minute bucket
type PingGroup struct {
Start time.Time
End time.Time
Received int // # of ping packets received
Timedout int // # packets timed out
TotalTime float64 // sum of resTime of all rec... |
package models
import (
benchmarkagent "github.com/hyperpilotio/container-benchmarks/benchmark-agent/apis"
deployer "github.com/hyperpilotio/deployer/apis"
)
// ServiceConfig a struct that describes the address of the corresponding service
type ServiceConfig struct {
Name string `bson:"name" json:... |
package main
import (
"testing"
)
func TestGreet(t *testing.T) {
expected := "Hello, visitor number 42!"
actual := greet(42)
if actual != expected {
t.Errorf("Expected '%s', got '%s'", expected, actual)
}
}
|
package logging
import (
"context"
"fmt"
"reflect"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/pkg/errors"
"github.com/rancher/norman/controller"
"github.com/rancher/types/apis/apps/v1beta2"
"github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/apis/management.cattle.io/v3"
rbac... |
package main
import (
l4g "base/log4go"
"net/http"
)
var g_HttpCommandM = NewHttpCommandM()
type HttpCommand interface {
Execute(*http.Request, *HttpHandlerPool) bool
}
type HttpCommandM struct {
cmdm map[string]HttpCommand
}
func NewHttpCommandM() *HttpCommandM {
return &HttpCommandM{
cmdm: make(map[string... |
/*
Related: What's my telephone number? which asks to calculate the terms of A000085, the number of possible ordinal transforms of length n.
Background
Ordinal transform is a transformation on an integer sequence. For a sequence a=(a0,a1,a2,⋯), the n-th term of the ordinal transform ord(a)n is defined as the occurre... |
package restful
import (
// "github.com/gin-contrib/gzip"
"github.com/freelifer/gohelper/pkg/log"
"github.com/freelifer/gohelper/transport/restful/v1"
"github.com/gin-gonic/gin"
"net/http"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "github.com/freelifer/gohelper/docs" // d... |
package nn
import (
"testing"
)
func TestNewNet(test *testing.T) {
var tests = []struct {
inputNeurons int
hiddenNeurons int
totalLayers int
outputNeurons int
in []float64
}{
{
inputNeurons: 2,
hiddenNeurons: 3,
totalLayers: 4,
outputNeurons: 1,
in: []float64... |
package balancetests
import (
"github.com/jamiealquiza/vaporch"
)
var vch *vaporch.Ring
func vaporchInit() {
vch, _ = vaporch.New(&vaporch.Config{
Nodes: nodeList,
})
methods = append(methods, method{
name: "vaporCH", f: vchGet})
}
func vchGet(k string) string {
return vch.Get(k)
}
|
package admin
import (
"github.com/kataras/iris"
"strconv"
"github.com/go-ozzo/ozzo-validation"
"os"
"fmt"
"bufio"
"encoding/base64"
"../../model"
"../../db"
"regexp"
)
var (
SortByRegex = regexp.MustCompile("^(id|name|country|birthday)$")
StageFilterRegex = regexp.MustCompile("^(all|unconfirmed|confirme... |
package mlserver
import (
"fmt"
"log"
"net"
"net/http"
"path/filepath"
"time"
"github.com/freignat91/mlearning/nests"
"github.com/freignat91/mlearning/network"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
var (
config = mlConfig{}
ctx = ... |
package blocks
import (
bolt "go.etcd.io/bbolt"
"log"
)
/*
In blocks, the key -> value pairs are:
'b' + 32-byte block hash -> block index record
'f' + 4-byte file number -> file information record
'l' -> 4-byte file number: the last block file number used
'R' -> 1-byte boolean: whether we're in the process of rein... |
package ratecounter
import (
"strconv"
"sync"
"sync/atomic"
"time"
)
// A RateCounter is a thread-safe counter which returns the number of times
// 'Incr' has been called in the last interval
type RateCounter struct {
counter Counter
interval time.Duration
resolution int
partials []Counter
current ... |
package app
import (
"github.com/ebar-go/ego/component/log"
"github.com/ebar-go/ego/component/mns"
"github.com/ebar-go/ego/config"
"github.com/ebar-go/ws"
"github.com/ebar-go/event"
"github.com/go-redis/redis"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"go.uber.org/dig"
)
var (
Conta... |
package sol
import "testing"
func TestBasic(t *testing.T) {
testcases := []struct {
input []int
want int
}{
{
input: []int{},
want: -1,
},
{
input: []int{1, 2, 3},
want: 1,
},
{
input: []int{2, 1},
want: 1,
},
{
input: []int{100},
want: 100,
},
{
input: []int{3,... |
package model
import (
"fmt"
"github.com/zhenghaoz/gorse/base"
"github.com/zhenghaoz/gorse/core"
"github.com/zhenghaoz/gorse/floats"
"gonum.org/v1/gonum/mat"
"log"
"math"
"sync"
)
/* SVD */
// SVD algorithm, as popularized by Simon Funk during the
// Netflix Prize. The prediction \hat{r}_{ui} is set as:
//
/... |
// Copyright 2016 Google Inc. 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 main
import (
"embed"
"fmt"
"io/fs"
"os"
"text/template"
)
//go:embed templates
var templateFS embed.FS
var tmpl = template.Must(template.New("t").ParseFS(templateFS, "templates/*"))
func main() {
files, _ := fs.ReadDir(templateFS, "templates")
fmt.Println("Templates:")
for _, file := range files {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.