text stringlengths 11 4.05M |
|---|
package pgsql
import (
"testing"
)
func TestText(t *testing.T) {
testlist2{{
data: []testdata{
{input: string("foo bar"), output: string("foo bar")},
},
}, {
data: []testdata{
{input: []byte("foo bar"), output: []byte("foo bar")},
},
}}.execute(t, "text")
}
|
package 链表
// --------------------- 迭代版 ---------------------
func mergeTwoLists(listA *ListNode, listB *ListNode) *ListNode {
dummyMergedListHead := &ListNode{-1, nil}
mergedListHead := dummyMergedListHead
for listA != nil && listB != nil {
if listA.Val > listB.Val {
mergedListHead.Next = listB
listB = lis... |
package handlers
import (
"bytes"
"log"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/gorilla/mux"
"github.com/saurabmish/Coffee-Shop/data"
"github.com/stretchr/testify/assert"
)
func MiddlewareRouter() *mux.Router {
l := log.New(os.Stdout, "[TEST] Coffee shop API service ", log.LstdFlags)
v :... |
package pgtune
import (
"fmt"
"strconv"
"strings"
"github.com/timescale/timescaledb-tune/internal/parse"
)
const (
errUnrecognizedBoolValue = "unrecognized bool value: %s"
)
type FloatParser interface {
ParseFloat(string, string) (float64, error)
}
type bytesFloatParser struct{}
func (v *bytesFloatParser) P... |
package main
import (
"encoding/json"
"time"
)
type Task struct {
ID int `json:"id"`
Progress float64 `json:"progress"`
ResourceLocation string `json:"resource_location"`
CreatedOn time.Time `json:"created_on"`
ExpiresOn time.Time `json:"expires_on"`
... |
package ionic
import (
"github.com/franela/goblin"
. "github.com/onsi/gomega"
"testing"
)
func TestAppliedRulesets(t *testing.T) {
g := goblin.Goblin(t)
RegisterFailHandler(func(m string, _ ...int) { g.Fail(m) })
g.Describe("Applied Ruleset Summary", func() {
g.It("should return low risk and passed if the ev... |
package main
import (
"log"
"strings"
)
type Profile struct {
Id int
Name string
Reporter map[string]bool
}
func solution(id_list []string, report []string, k int) []int {
points := make([]int, len(id_list))
// init id map
idMap := make(map[string]*Profile, len(id_list))
for idx, name := range id_... |
package pgsql
import (
"database/sql"
"database/sql/driver"
"strconv"
)
// PointFromFloat64Array2 returns a driver.Valuer that produces a PostgreSQL point from the given Go [2]float64.
func PointFromFloat64Array2(val [2]float64) driver.Valuer {
return pointFromFloat64Array2{val: val}
}
// PointToFloat64Array2 re... |
package test
import (
// "net/http"
"testing"
)
//____________________________ INSERT ________________________________________//
func TestUserEntityInsertWRONGBODY(t *testing.T) {
resp := sendPost("http://localhost:8080/SignUp", APPJASON_UTF_8, UserEntityInsertWRONGBODY)
response := responseToString(resp)
compar... |
package main
import (
"fmt"
"github.com/devfeel/dotweb"
//"net/http"
"db"
)
type S map[string][]string
func main() {
c := make(chan int, 2)//修改 2 为 1 就报错,修改 2 为 3 可以正常运行
c <- 1
c <- 2
fmt.Println(<-c)
fmt.Println(<-c)
//初始化app
dotapp := dotweb.New()
dotapp.SetLogPath("/Users/liangsijun/go/log")
Init... |
package main
// 方法1: 2次循环
func isMonotonic(A []int) bool {
flag1, flag2 := true, true
// 判断数组是否单调递增
for i := 1; i < len(A); i++ {
if A[i-1] > A[i] {
flag1 = false
}
}
// 判断数组是否单调递减
for i := 1; i < len(A); i++ {
if A[i-1] < A[i] {
flag2 = false
}
}
return flag1 || flag2
}
// 方法2: 1次循环 (先判断单调性)
fu... |
package cmd
import (
"github.com/emi1997/con-app/client"
"github.com/spf13/cobra"
)
//calls on rootCmd from root.go with AddDocument function and passes it newly created command as argument
func init() {
rootCmd.AddCommand(addIndex)
}
//Defining new command
var addIndex = &cobra.Command{
Use: "newind",
Short:... |
package config
import (
"encoding/json"
)
// Cache stores values indexed by a cache name and a cache key.
type Cache interface {
Flush()
Put(cacheName, key, value string)
Get(cacheName, key string) string
}
// MapCache is a Cache that stores all values in a map.
type MapCache struct {
data map[string]map[string... |
package atlas
import (
"errors"
"fmt"
"image"
"math"
"os"
)
// Includes parameters that can be passed to the Generate function
type GenerateParams struct {
Name string
Descriptor DescriptorFormat
Packer Packer
Sorter Sorter
MaxWidth, MaxHeight int
MaxAtlase... |
/*
An electric circuit uses exclusively identical capacitors of the same value C.
The capacitors can be connected in series or in parallel to form sub-units, which can then be connected in series or in parallel with other capacitors or other sub-units to form larger sub-units, and so on up to a final circuit.
Using t... |
package main
import (
"learn6/map"
)
func main() {
demo.Test()
}
|
package main
import (
"errors"
"image"
"image/png"
"io"
"os"
"strconv"
)
/*
Maps a FieldObject to a RGBA color.
*/
var PIXEL_WALL_SOLID = newPixel(0, 0, 0, 255)
var PIXEL_WALL_WEAK = newPixel(66, 65, 66, 255)
var PIXEL_ITEM_BOOST = newPixel(0, 230, 255, 255)
var PIXEL_ITEM_SLOW = newPixel(255, 115, 0, 255)
var ... |
package stages
import (
"fmt"
mortarpb "github.com/SoftwareDefinedBuildings/mortar/proto"
"github.com/pkg/errors"
"time"
)
func validateFetchRequest(req *mortarpb.FetchRequest) error {
// check the list of sites is non-empty
if len(req.Sites) == 0 {
return errors.New("Need to include non-empty request.Sites")... |
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
/*
gin实现restful
*/
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
var users = []User{
{ID: 1, Name: "111"},
{ID: 2, Name: "222"},
{ID: 3, Name: "333"},
}
func main() {
r := gin.Default()
//r.GET("/users",listUser)
//r.G... |
// 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 isaac
import (
"time"
)
const (
actionLogsBasePath = "/api/v1/logs/scenariosLog"
)
type ActionLogsService interface {
Add(NewActionLog) (ActionLog, error)
Get(ID) (ActionLog, error)
List() ([]ActionLog, error)
}
type ActionLogsServiceOp struct {
client *Client
}
type NewActionLog struct {
Origin str... |
package kucoin
import (
"net/http"
)
// A WithdrawalModel represents a withdrawal.
type WithdrawalModel struct {
Chain string `json:"chain"`
Id string `json:"id"`
Address string `json:"address"`
Memo string `json:"memo"`
Currency string `json:"currency"`
Amount string `json:"amount"... |
// Package unions illustrates how to implement tagged unions in Go
// Let's start with simple enums that you're probably familiar with.
package enums
import (
"fmt"
)
// The simplest form of enums using consts and `iota`
// Here, we encode the cardinal directions as ints
const (
// North as in the North Star
North... |
package paths
import (
"errors"
"fmt"
"os"
"path/filepath"
)
func GetPaths(getResourcesPathFuncs ...func() (string, error)) (Paths, error) {
var getResourcesPathFunc func() (string, error)
switch len(getResourcesPathFuncs) {
case 0:
getResourcesPathFunc = getResourcesPath
case 1:
getResourcesPathFunc = ge... |
package node
import (
"github.com/wcong/ants-go/ants/crawler"
"github.com/wcong/ants-go/ants/http"
"github.com/wcong/ants-go/ants/util"
)
type NodeInfo struct {
Name string
Ip string
Port int
Settings *util.Settings
}
type Node interface {
GetNodeInfo() *NodeInfo
StartSpider(spiderName string)... |
// Package mock provides a mock implementation of session store and loader.
package mock
import (
"net/http"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/sessions"
)
var (
_ sessions.SessionStore = &Store{}
_ sessi... |
package gh
import (
"context"
"github.com/google/go-github/github"
)
var publicReposFilter = github.RepositoryListByOrgOptions{Type: "public"}
var openIssuesFilter = github.IssueListByRepoOptions{State: "open"}
type Client struct {
GithubClient *github.Client
}
func NewClient(githubClient *github.Client) *Clien... |
package main
// emulates some C functions
import (
"fmt"
"os"
"unicode"
)
const UINT_MAX = 4294967295
type pseudoStdin struct {
buf []byte
i int
}
var stdin *pseudoStdin
func initStdin() {
stdin = newStdin()
}
func newStdin() *pseudoStdin {
s := &pseudoStdin{}
s.buf = make([]byte, 1024*1024)
os.Stdin.... |
package handler
import (
"context"
"fmt"
"math"
"time"
"github.com/jinmukeji/jiujiantang-services/service/auth"
"github.com/golang/protobuf/ptypes"
"github.com/jinmukeji/go-pkg/v2/age"
corepb "github.com/jinmukeji/proto/v3/gen/micro/idl/partner/xima/core/v1"
subscriptionpb "github.com/jinmukeji/proto/v3/ge... |
package c34_mitm_diffie_hellman
import (
"math/big"
)
type Point interface {
SetReceiver(p Point)
SendPGK()
ReceivePGK(p, g, pKA *big.Int)
SendK()
ReceiveK(pKB *big.Int)
SendMessage([]byte)
ReceiveMessage([]byte)
ReturnMessage()
}
func EchoStream(uA, uB Point, msg []byte) {
uA.SetReceiver(uB)
uB.SetReceiv... |
package main
import (
"../core"
)
func main() {
w := core.NewWorld(25, 50)
w.Run()
}
|
package main
func main() {
largestRectangleArea([]int{1, 3, 4, 56, 6, 2})
}
func largestRectangleArea(heights []int) int {
max := 0
stack := []int{0}
heights = append([]int{-1}, heights...)
heights = append(heights, 0)
for i := 1; i < len(heights); i++ {
if heights[i] >= heights[stack[len(stack)-1]] {
stac... |
package player
// NotePlayer is an interface for playing notes. This allows for swapping out different types of players.
// Return an interface to allow for unit testing output.
type NotePlayer interface {
PlayNotes(noteNames []string) interface{}
}
|
package etcdraft
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/golang/mock/gomock"
crypto2 "github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/meshplus/bitxhub-kit/crypto"
"github.com/meshplus/bitxhub-kit/crypto/... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
client := &http.Client{}
reqest, _ := http.NewRequest("GET", "http://127.0.0.1:554/modules/admin/server/qtssSvrModuleObjects/QTSSRelayModule/qtssModPrefs/relay_prefs_file?command=set+value=\"/etc/streaming/relayconfig.xml\"", nil)
reqest.Header.... |
package znet
import (
"errors"
"log"
"net"
"sync"
"zinxWebsocket/utils"
"zinxWebsocket/ziface"
"github.com/gorilla/websocket"
)
//连接管理
type Connection struct {
//当前属于那个server
WsServer ziface.IServer
//当前连接的ws
Conn *websocket.Conn
//连接id
ConnID uint32
//当前连接状态
isClosed bool
//告知当前连接已经退出/停止,由reder退... |
package std
import (
"fmt"
"github.com/gopherjs/gopherjs/js"
"github.com/iansmith/tropical"
)
//This implementation assumes that the browser is doing double buffering so there
//no need to do that ourselves.
//http://stackoverflow.com/questions/2795269/does-html5-canvas-support-double-buffering
type canvasImpl s... |
// Copyright 2019-2023 The sakuracloud_exporter Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... |
package sms
import (
"MI/pkg/cache"
"context"
"time"
)
//将手机号跟验证码存入redis
func SmsSet(key,value string)error{
return cache.Set(context.Background(),key,value,60*time.Second)
}
func SmsGet(key string)(string,error) {
return cache.Get(context.Background(),key)
} |
package handlers
import (
"crypto/sha256"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"github.com/Neffats/final-scenes/models"
"github.com/Neffats/final-scenes/stores"
)
type HTTP struct {
Films *stores.FilmStore
Logger *log.Logger
}
func (h *HTTP) HandleGuess(w http.ResponseWriter,... |
package rws
import (
"testing"
"io/ioutil"
)
func TestGet(t *testing.T) {
resp,err := Get()
if err != nil {
t.Error("Connection error: %s",err)
}
if resp.StatusCode != 200 {
t.Error()
content,err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
t.Error(string(content[:]))
if err != n... |
package main
// http://go101.org/article/unsafe.html
func main() {
// Fact 1: Unsafe Pointers Are Pointers And Uintptr Values Are Intergers
// Fact 2: Unused Values May Be Collected At Any Time
// Fact 3: We Can Use A runtime.KeepAlive Function Call To Mark A Value As Still In Using (Reachable) Currently
// Fact... |
package main
import "math"
import "fmt"
func isPrime(nb int) bool {
i := 1
limit := int(math.Sqrt(float64(nb))) // the square of the number (int : can't % on float...)
for i < limit {
i++
if nb%i == 0 {
return false
}
}
return true
}
func main() {
var rank int
fmt.Print("The rank of the prime number... |
package persistence
import (
"fmt"
"gopetstore/src/domain"
"testing"
)
func TestInsertAccount(t *testing.T) {
err := InsertAccount(&domain.Account{
UserName: "1234",
Password: "1234",
Email: "1234",
FirstName: "1234",
LastName: "1234",
Status: ... |
package main
import "fmt"
//func sayHelloWithFilter(name string, filter func(string) string) {
// nameFiltered := filter(name)
// fmt.Println("Hello", nameFiltered)
//}
// example if using function as parameter with type declaration
type Filter func(string) string
func sayHelloWithFilter(name string, filter Filter... |
// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package dht
import (
"time"
"net/http"
// "net/http/httptest"
"testing"
// "github.com/julienschmidt/httprouter"
"fmt"
"log"
//"io/ioutil"
"bytes"
"strconv"
)
type handlerStruct struct {
handeled *bool
}
func Test_1(t *testing.T)() {
node0 := makeDHTNode(generateNodeId(), "127.0.0.1", "4242")
go... |
package chance_test
import (
"regexp"
"testing"
. "github.com/smartystreets/goconvey/convey"
"github.com/victorquinn/chancego"
)
func TestChar(t *testing.T) {
Convey("Existence", t, func() {
c := chance.Char()
So(c, ShouldNotBeNil)
})
Convey("Generates random character", t, func() {
charRegex := regexp... |
// Copyright © 2018 NAME HERE <EMAIL ADDRESS>
//
// 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 utils
import (
"errors"
"github.com/kataras/iris/v12/sessions/sessiondb/redis"
"strings"
)
func CheckLoginStatus(redis *redis.Database, authSid string, userId string, token string) (isLogin bool, err error) {
value := redis.Get(authSid, userId)
if value == nil {
return false, errors.New("authError:didn... |
package ptp
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io/ioutil"
"strconv"
"time"
"gopkg.in/yaml.v2"
)
// CryptoKey represents a key and it's expiration date
type CryptoKey struct {
TTLConfig string `yaml:"ttl"`
KeyConfig string `yaml:"key"`
Until time.Time
Key []byte
}
// C... |
package tasks
import (
"github.com/emicklei/go-restful"
api "github.com/emicklei/go-restful-openapi"
"data-importer/dbcentral/etcd"
"data-importer/dbcentral/pg"
"data-importer/types"
"grm-service/mq"
. "grm-service/util"
)
type TasksSvc struct {
SysDB *pg.SystemDB
MetaDB *pg.MetaDB
DynamicDB *etcd.... |
package ast
// HasFields is an AST nodes with Field children.
type HasFields interface {
// AddField adds a Field to the node.
AddField(*Field)
}
|
package socialmedia
import (
"time"
)
//go:generate stringer -type=MoodState
type MoodState int
// Here we define all the possible mood states using an
// iota enumerator.
const (
MoodStateNeutral MoodState = iota
MoodStateHappy
MoodStateSad
MoodStateAngry
MoodStateHopeful
MoodStateThrilled
MoodStateBored
M... |
package swarm_test
import (
"context"
"fmt"
"sync"
"testing"
"time"
. "gx/ipfs/QmTJCJaS8Cpjc2MkoS32iwr4zMZtbLkaF9GJsUgH1uwtN9/go-libp2p-swarm"
peer "gx/ipfs/QmPJxxDsX2UbchSHobbYuvz7qnyJTFKvaKMzE2rZWJ4x5B/go-libp2p-peer"
)
func getMockDialFunc() (DialFunc, func(), context.Context, <-chan struct{}) {
dfcalls ... |
package decodeways
import (
"fmt"
"strconv"
)
func toKey(arr []byte) (key string) {
for _, byt := range arr {
key = fmt.Sprintf("%s%c", key, byt+'a')
}
return
}
func decoder(s []byte, memo map[string]int) int {
fmt.Printf("s %v\n", s)
key := toKey(s)
if _, saw := memo[key]; saw {
return 0
}
var co... |
package context
import (
"testing"
)
func init() {
SetContext(NewMemoryContext())
}
type firstIndependentStruct struct {
val string
}
type secondIndependentStruct struct {
val string
}
type dependentStruct struct {
firstDep *firstIndependentStruct
secondDep *secondIndependentStruct
}
func TestMemoryContext_D... |
package broker
import (
"fmt"
)
type Err struct {
code int
msg string
}
func (e Err) Error() string {
return fmt.Sprintf("%d %s", e.code, e.msg)
}
|
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package models
type Todo struct {
ID string
Title string
Done bool
}
|
package cmd
func x() {
return
}
|
package main
import (
"errors"
"github.com/shiningacg/apicore"
)
func init() {
apicore.AddHandler(apicore.NewMatcher("/login"), func() apicore.Handler {
return &Login{}
})
}
type Login struct {
UserName string `json:"user_name"`
UserPWD string `json:"user_pwd"`
}
func (l *Login) Handle(ctx apicore.Conn) {
... |
package pipenv
import (
"os"
"path"
"sort"
"strings"
"testing"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/kylelemons/godebug/pretty"
)
func TestParse(t *testing.T) {
vectors := []struct {
file string // Test input file
libraries []types.Library
}{
{
file: "testdata/Pipf... |
package main
import (
"fmt"
"strconv"
)
func restoreIpAddresses(s string) []string {
n := len(s)
if n < 4 || n > 12 {
return []string{}
}
pos := [4]int{}
var res []string
var search func(idx, cnt int)
search = func(idx, cnt int) {
if idx == n && cnt == 4 {
item := make([]byte, n+3)
for i, j := 0, ... |
package main
import (
"github.com/gopherchina/website/controllers"
"github.com/gopherchina/website/models"
"github.com/astaxie/beego"
"github.com/beego/i18n"
)
func main() {
beego.Router("/", &controllers.MainController{})
beego.Router("/:name", &controllers.MainController{})
beego.Router("/:name/:id", &cont... |
package kademlia
import (
"testing"
)
func TestStorage(t *testing.T) {
storage := NewStorage("TEST")
storage.Store("test.txt", []byte("bonjour"), false)
storage.Store("test.txt", []byte("bonjour"), false)
out := storage.Read("test.txt")
if string(out) != "bonjour" {
t.Error("Invalid content")
}
storage.d... |
package payment
type NotFoundAccountError struct {
err error
}
func (e *NotFoundAccountError) Error() string {
return e.err.Error()
}
type SameEmailAccountAlreadyExistError struct {
err error
}
func (e *SameEmailAccountAlreadyExistError) Error() string {
return e.err.Error()
}
type NotFoundAccountRepositoryErr... |
package main
import (
"fmt"
"regexp"
)
func main() {
regex := regexp.MustCompile("N([\\w])l")
fmt.Println(regex.MatchString("NAl"))
}
|
package route
import (
"fmt"
"RelationshipMatch/model"
"RelationshipMatch/repository"
"github.com/gin-gonic/gin"
)
// CreateUserRelationship
//
// PUT /users/:user_id/relationships/:other_user_id
//
// Request body
// {
// "user_id": "21341231231",
// "state": "liked" ,
// "type": "relationship"
// }
type Crea... |
package routerHandler
import (
"encoding/json"
"fmt"
"net"
"cmpeax.tech/lower-machine/lib/DataParser"
"cmpeax.tech/lower-machine/lib/routerDI"
"cmpeax.tech/lower-machine/struct/ACS"
)
func WSServiceExport() routerDI.MapOfWSCallbackJSONFunc {
return routerDI.MapOfWSCallbackJSONFunc{
"0x03": func(jsonData rou... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//456. 132 Pattern
//Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. De... |
// Copyright 2020 beego
//
// 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, s... |
package rest
import (
"flag"
"fmt"
"metabnb/lib/configuration"
"net/http"
"github.com/julienschmidt/httprouter"
"metabnb/controllers"
"metabnb/lib/persistence/mongolayer"
)
func Server() error {
confPath := flag.String("conf", `.\configuration\config.json`, "flag to set the path to the configuration json fil... |
package informer
import "context"
// Interface is used to access remote resources.
// may implmented by HTTP API or MySQL, etc.
type Interface[ObjectContent any] interface {
Create(ctx context.Context, object Object[ObjectContent]) (Object[ObjectContent], error)
// List return all objects
List(ctx context.Context... |
package sort
/*
Notes:
分组进行的插入排序。
分组增量序列的选取影响算法效率。
Hibbard 增量序列:1,3,7,...,2n-1 被证明可广泛应用,时间复杂度 O(N^1.5)
希尔排序复杂度范围大约 O(N^1.3) ~ O(N^2)。
不稳定排序。
*/
func shellSort(nums []int) {
for step := len(nums) / 2; step >= 1; step /= 2 {
// insert sort
for i := step; i < len(nums); i += step {
for j := i - step; j >= 0; j -... |
package main
import (
"fmt"
"net/http"
"os"
"github.com/czerwonk/ping_exporter/config"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/log"
"gopkg.in/alecthomas/kingpin.v2"
)
const version string = "0.5.0"
var (
showV... |
package main
func twoSum(numbers []int, target int) []int {
var res []int
if len(numbers) == 0 {
return res
}
left := 0
right := len(numbers) - 1
for left < right {
sum := numbers[left] + numbers[right]
if sum < target {
left++
} else if sum > target {
right--
} else {
res = append(res, left+1... |
require 'json'
require 'aws-sdk'
def lambda_handler(event:, context:)
# TODO implement
name=event["queryStringParameters"]["name"]
#タグごとそれぞれの総時間を格納するためのハッシュ
hash=Hash.new
10.times{|i|hash[i.to_s]=0}
dynamoDB = Aws::DynamoDB::Resource.new(region: 'ap-northeast-1')
table = dynamoDB.table('D... |
package tars
import (
"bytes"
"context"
"fmt"
"strings"
"time"
githubql "github.com/shurcooL/githubv4"
"github.com/sirupsen/logrus"
"k8s.io/test-infra/prow/config"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/pluginhelp/externalplugins"
"k8s.io/test-infra/pro... |
package main
import (
"fmt"
)
func main() {
s := foo()
fmt.Printf("Type of value returned by foo() :: %T\n", s)
fmt.Println("String returned by foo() ::", s)
f := bar()
fmt.Printf("Type of value returned by bar() :: %T\n", f)
x := f()
fmt.Println("Value returned by the function returne... |
// Basic Layout Example
// http://qt-project.org/doc/qt-5.1/qtquickcontrols/basiclayouts.html
package main
import (
"fmt"
"github.com/niemeyer/qml"
"os"
)
func main() {
qml.Init(nil)
engine := qml.NewEngine()
engine.On("quit", func() {
fmt.Println("quit")
os.Exit(0)
})
component, err := engine.LoadF... |
package db
import (
"runtime"
"sync"
"sync/atomic"
)
type RWLocker interface {
sync.Locker
RLock()
RUnlock()
}
type brokenLocker struct{}
func newBrokenLocker() brokenLocker { return brokenLocker{} }
func (brokenLocker) Lock() {}
func (brokenLocker) Unlock() {}
func (brokenLocker) RLock() {}
func (brokenL... |
package cmd
import (
"flag"
"fmt"
"os"
"strings"
"github.com/mmbros/quote/internal/quote"
"github.com/mmbros/quote/pkg/simpleflag"
)
const (
defaultConfigType = "yaml"
defaultMode = "1"
)
type appArgs struct {
config simpleflag.String
configType simpleflag.String
database simpleflag.String
d... |
package main
import (
"bytes"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/plugins/cors"
"time"
)
var Bc BlockChain
var Sleeptime time.Duration =60
var Id uint64 = 0
func main() {
Bc=*CreateBlockChain()
go MakeRecordBlock(&Bc)
defer Bc.db.Close()
beego.InsertFilter("*", beego.BeforeRouter, cor... |
package main
import (
"bytes"
"testing"
)
func TestPKCS7Pad(t *testing.T) {
cases := []struct {
buf []byte
blockSize int
want []byte
}{
{
[]byte{0},
3,
[]byte{0, 2, 2},
},
{
[]byte{0, 0},
3,
[]byte{0, 0, 1},
},
{
[]byte{0, 0, 0},
3,
[]byte{0, 0, 0, 3, 3, 3},
... |
package service
type queue struct {
Writer QueueWriter
}
type Queue interface {
Write(event Event) error
}
type QueueWriter interface {
Publish(event Event) error
}
func NewQueue(writer QueueWriter) Queue {
return &queue{
Writer: writer,
}
}
func (qs *queue) Write(event Event) error {
return qs.Writer.Publ... |
package trace
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestTrace(t *testing.T) {
assert.Equal(t, "message=[test string] call=[github.com/atsttk84/goutils/trace.TestTrace] parameters=[string]", Trace("test string", "string"))
assert.Equal(t, "message=[test int] call=[github.com/atsttk84/gouti... |
package ansi
// Mode is an ANSI terminal mode constant.
type Mode uint64
// Mode bit fields
const (
ModePrivate Mode = 1 << 63
)
// Set returns a control sequence for enabling the mode.
func (mode Mode) Set() Seq {
if mode&ModePrivate == 0 {
return SM.WithInts(int(mode))
}
return SMprivate.WithInts(int(mode & ... |
package main
import (
"encoding/json"
"flag"
"math/rand"
"net/http"
"time"
"github.com/fblanco/talks/rtb/bid"
)
var port = flag.String("port", "9090", "http server port")
func main() {
rand.Seed(time.Now().UnixNano())
flag.Parse()
http.HandleFunc("/bid", bidder)
http.ListenAndServe(":"+*port, nil)
}
func... |
package proxy
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/config"
hpke_handlers "github.com/pomerium/pomerium/pkg/hpke/handlers"
)
func testOptions(t *testing.T) *config.Options {
t.Helper()
opts := conf... |
package accounts
import (
"testing"
uuid "github.com/satori/go.uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewAccount(t *testing.T) {
acc := NewAccount("123", "GB", []string{"Samantha Holder"}, &AccountAttributes{BankID: "xxx"})
_, err := uuid.FromString(acc.Dat... |
package fileWatcher
type Folder struct {
Path string
Recursive bool
}
|
package main
import (
"strings"
"testing"
)
func TestDetectCircularDependencySimple(t *testing.T) {
a := NewNode(Job{}, "a")
b := NewNode(Job{}, "b")
a.Dependents[b] = struct{}{}
b.Dependents[a] = struct{}{}
root := NewNode(Job{}, "root")
root.Dependents[a] = struct{}{}
expectedCycle := "a->b->a"
err := de... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package export
import (
"testing"
"github.com/pingcap/tidb/util/promutil"
)
func TestMetricsRegistration(t *testing.T) {
m := newMetrics(promutil.NewDefaultFactory(), nil)
registry := promutil.NewDefaultRegistry()
m.registerTo(registry)
m.unregisterFr... |
package solution
import "testing"
func TestRomanToInt(t *testing.T) {
var tests = []struct {
s string
want int
}{
{"III", 3},
{"IV", 4},
{"IX", 9},
{"LVIII", 58},
{"MCMXCIV", 1994},
}
for _, c := range tests {
got := romanToInt(c.s)
if got != c.want {
t.Errorf("romanToInt(%s) == %d, want ... |
package schema
// PaginationMetadata represents the meta data of a paginated response
type PaginationMetadata struct {
TotalElements int `json:"total_elements"`
DisplayedElements int `json:"displayed_elements"`
}
|
package main
import (
"log"
"net"
)
const nLEDs = 92
func main() {
// Open the serial port
conn, err := net.Dial("tcp", "localhost:9996")
if err != nil {
log.Fatalln("Couldn't open localhost: ", err)
}
defer conn.Close()
buf := make([]byte, (nLEDs*3 + 1))
for j := 0; j < 15; j++ {
buf[0] = 0x84
for i... |
package mempool
import (
"testing"
"github.com/meshplus/bitxhub-model/pb"
"github.com/stretchr/testify/assert"
)
func TestForward(t *testing.T) {
ast := assert.New(t)
mpi, _ := mockMempoolImpl()
defer cleanTestData()
txList := make([]*pb.Transaction, 0)
privKey1 := genPrivKey()
account1, _ := privKey1.Pub... |
package factory
import (
"fmt"
)
const (
ItalianType = 1
)
const (
FerrariModel = 1
CarWithFiveWheelModel = 2
)
type Vehicle interface {
NumOfWheels() int
GetModelName() string
}
type VehicleFactory interface {
Build(v int) (Vehicle, error)
}
type ItalianFactory struct{}
type CarWithFiveWheelType... |
package model
import (
"Seaman/utils"
"time"
)
type TplExportHistoryT struct {
Id int `xorm:"not null pk autoincr INT(11)"`
TypeId int `xorm:"not null comment('导出类型ID') INT(11)"`
Status int `xorm:"not null comment('状态') TINYINT(3)"`
Params string ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.