text stringlengths 11 4.05M |
|---|
package logging
import (
"go.uber.org/zap"
"time"
)
func LogZap() {
logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("failed to fetch URL",
zap.Int("attempt", 3),
zap.Duration("backoff", time.Second),
zap.Error(GetError()),
)
}
|
package client
import (
"sync"
"time"
"github.com/MagalixCorp/magalix-agent/v3/proto"
"github.com/MagalixTechnologies/core/logger"
)
// PipeSender interface for sender
type PipeSender interface {
Send(kind proto.PacketKind, in interface{}, out interface{}) error
}
// Pipe pipe
type Pipe struct {
cond *sync.Co... |
package template
type Aircon struct {
Operation *Action `json:"operation"`
Modes map[string]*AirconMode `json:"modes"`
}
type AirconMode struct {
Temp *Action `json:"temp,omitempty"`
Humid *Action `json:"humid,omitempty"`
Fan *Action `json:"fan,omitempty"`
Horizo... |
package main
import (
"fmt"
"myProject/videoWater/deal/config"
"myProject/videoWater/deal/factory"
)
func main() {
Run()
}
func Run() {
con := config.ReadConfig()
fmt.Println(con)
factory.DoFactory(con)
} |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
im_type "github.com/kyf/6ryim/6ryim_http/im_type"
)
func init() {
handlers["/sendmsg"] = func(w http.ResponseWriter, r *http.Request, params url.Values, logger *log.Logger) {
msg := params.Get("msg")
var result string
if... |
/*
* @lc app=leetcode.cn id=1576 lang=golang
*
* [1576] 替换所有的问号
*/
// @lc code=start
package main
func modifyString(s string) string {
b := []byte(s)
chars := "abcdefghijklmnopqrstuvwxyz"
for i := 0; i < len(b); i++ {
if b[i] == '?' {
for j := 0; j < len(chars); j++ {
if (i == 0 || b[i-1] != chars[j])... |
package collection
import (
"errors"
)
/*
ArrayDeque是一个双端队列实现,
内部使用数组进行元素存储,不允许存储null值,
可以高效的进行元素查找和尾部插入取出,
是用作队列、双端队列、栈的绝佳选择,性能比LinkedList还要好。
*/
const (
// 初始化最小容量
MinInitialCapacity int = 8
)
type ArrayDeque struct {
elements []interface{}
head int
tail int
}
// 返回队列的大小
func (a *ArrayDeque) Si... |
package main
import "fmt"
func main() {
a := new(int)
fmt.Println(*a)
mm := make(map[string]int)
mm["abc"] = 10
fmt.Println(mm["abc"])
}
|
package v1
import (
rapiv1 "github.com/peteabre/ocp-client-go/pkg/route/api/v1"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
)
type OcpV1Interface interface {
RoutesGetter
}
type OcpV1Client struct {
restClient rest.Interface
}
func (c *OcpV1Client)... |
package base
import (
"io"
"time"
"encoding/hex"
"crypto/rand"
"encoding/base64"
"crypto/sha256"
)
func Hash(s string) string {
h := sha256.New()
h.Write([]byte(s))
io.WriteString(h, time.Now().String())
return hex.EncodeToString(h.Sum(nil))
}
func RandomString() string {
b := make([]byte, 64)
if _, err ... |
package main
import (
"fmt"
"log"
"math/rand"
"sort"
"github.com/hodgesds/perf-utils"
"golang.org/x/sys/unix"
)
func randInt64s(n int) []int64 {
ints := make([]int64, n)
for i := 0; i < n; i++ {
ints[i] = rand.Int63()
}
return ints
}
func randInt64Ps(n int) []*int64 {
ints := make([]*int64, n)
for i :... |
package tester
import (
"github.com/zeuxisoo/go-zenwords/pkg/keywords"
)
// CreateRPC will prepare all related data for RPC testing
func CreateRPC() {
keywords.NewKeywords("../../words.txt")
}
|
package main
import (
"flag"
"fmt"
"github.com/gerald1248/timeline"
"os"
"path/filepath"
"sync"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: ./%s [<JSON file> [<JSON file>]]\n", filepath.Base(os.Args[0]))
flag.PrintDefaults()
os.Exit(0)
}
certificate := flag.String("c", "cert.pe... |
package coin
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"incognito-chain/common"
"incognito-chain/common/base58"
"incognito-chain/key/wallet"
"incognito-chain/privacy/key"
"incognito-chain/privacy/operation"
)
const (
MaxSizeInfoCoin = 255
JsonMarshalFlag = 34
CoinVersion1 = 1
CoinVe... |
package service
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func NewKubernetesClientset() *kubernetes.Clientset {
//!!!!!!! dev !!!!!!!!!!
//kubeconfig := flag.String("kubeconfig", "./config", "absolute path to the kubeconfig file")
//flag.Parse()
//config, err := clientcmd.BuildConfigFromF... |
package httpserver
import (
"github.com/labstack/echo"
"strconv"
"net/http"
"Barracks/rank"
//"github.com/labstack/echo/middleware"
)
func StartServer(rankInfo *rank.RankInfo, rankInfoFreeze *rank.RankInfo, port uint) {
e := echo.New()
//e.Use(middleware.Logger())
e.GET("/api/:contestName/ranking", ... |
package notion
import "time"
type IngredientReport struct {
IngredientID string `json:"ingredient_id,omitempty"`
Value float64 `json:"value"`
Date time.Time `json:"date"`
}
type BatchIngredientReport struct {
IngredientID string `json:"ingredient_id"`
Reports []IngredientRep... |
package listen
import (
"golib/comm"
"net"
"regexp"
"strings"
"time"
"github.com/astaxie/beego/logs"
)
var cmdHanderAdapters = make(map[string]CmdHander)
//Listen ...
//监听端口
func Listen(port string) {
//监听2040端口
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
logs.Error("Start TCP listener f... |
package server
import (
"context"
"encoding/binary"
"log"
"math"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
spb "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/summary_go_proto"
tpb "github.com/tensorflow/tensorflow/tensorflow/go/core/framework/tensor_go_proto"
dtpb "githu... |
package mysql
import (
"bufio"
"context"
"database/sql"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"sync"
"github.com/fperf/fperf"
// use the mysql driver
_ "github.com/go-sql-driver/mysql"
)
const seqPlaceHolder = "__seq_int__"
const randPlaceHolder = "__rand_int__"
const randRangePlaceHolder = "__rand_... |
package main
import (
"fmt"
"reflect"
"testing"
"github.com/shopspring/decimal"
)
func testDouble(t *testing.T) {
values := []string{"23.5", "45.7", "67.9", "98.1", "23.5", "12.00", "13.000332"}
for _, num := range values {
val := double(num)
if reflect.TypeOf(val).String() != "float64" {
t.Error("Inval... |
/**
* (C) Copyright IBM Corp. 2021.
*
* 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 handlers_test
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/egamorim/star-wars-planets/cmd/api/response"
"github.com/egamorim/star-wars-planets/cmd/api/handlers"
"github.com/egamorim/star-wars-planets/cmd/api/routers"
"github.com/egamorim/star-wars-planets/pkg... |
package main
import (
"encoding/json"
"errors"
"github.com/aws/aws-lambda-go/events"
"net/url"
"strings"
)
type SoaplessRequest struct {
Service string `json:"service"` // The endpoint for the desired SOAP service
RequestBody string `json:"request... |
// Go files need a package at the top
// and files with the main method need to have package main at the top
package main
// Example import syntax for
import "fmt"
func main() {
fmt.Println("Hello")
}
|
package main
import (
"database/sql"
"fmt"
"io/ioutil"
_ "github.com/lib/pq"
)
func connectDB() *sql.DB{
fmt.Println("[*] Get password of the db")
b, err := ioutil.ReadFile("/usr/local/horizon/conf/db.pwd")
if err != nil {
fmt.Print(err)
}
password := string(b)
fmt.Println(... |
package main
import (
"context"
_ "expvar"
"fmt"
"math/rand"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/atlassian/gostatsd/pkg/util"
"github.com/atlassian/gostatsd"
"github.com/atlassian/gostatsd/pkg/backends"
"github.com/atlassian/gostatsd/pkg/statsd"
"gith... |
package rpcRouter
import (
"bytes"
"context"
"github.com/go-xe2/x/os/xlog"
"github.com/go-xe2/xthrift/pdl"
)
// 发送错误消息
func makeErrorData(pktId int64, msg string, code int32) ([]byte, error) {
buf := bytes.NewBuffer([]byte{})
proto := NewRouterBinaryProto(buf)
if err := proto.WritePacketBegin(ERR_RES_PACKET, p... |
/*
* Copyright 1999-2018 Alibaba Group.
*
* 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 a... |
package handler
import (
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"sort"
"github.com/ryotarai/kube-daemonset-proxy/pkg/k8s"
"github.com/gin-gonic/gin"
"github.com/rakyll/statik/fs"
_ "github.com/ryotarai/kube-daemonset-proxy/statik"
corev1 "k8s.io/api/core/v1"
)
func New(o... |
package leetcode
func nextPermutation(nums []int) {
i := len(nums) - 2
for i >= 0 && nums[i] >= nums[i+1] {
i--
}
if i >= 0 {
j := len(nums) - 1
for j >= 0 && nums[i] >= nums[j] {
j--
}
if j >= 0 {
nums[i], nums[j] = nums[j], nums[i]
}
}
reverse(nums[i+1:])
}
func reverse(nums []int) {
l, r :... |
package inmem
import (
"github.com/smilga/analyzer/api"
)
type FilterStore struct {
filters []*api.Filter
}
func (s *FilterStore) Save(target *api.Filter) error {
if target.ID == 0 {
var last int64
for _, n := range s.filters {
if int64(n.ID) > last {
last = int64(n.ID)
}
}
target.ID = api.Filte... |
package realm
import (
"encoding/json"
"errors"
"fmt"
"golang.org/x/mod/semver"
)
// Override is a Toggle value to be consumed by and restricted to a semantic version range
type Override struct {
*Toggle
MinimumVersion string `json:"minimumVersion"`
MaximumVersion string `json:"maximumVersion"`
}
// Unmarsha... |
package spec
import (
"strconv"
"strings"
"github.com/pkg/errors"
)
type Size int
func (size *Size) Parse(s string) error {
i := strings.IndexFunc(s, func(r rune) bool {
return r < '0' || r > '9'
})
if i < 0 {
v, err := strconv.Atoi(s)
*size = Size(v)
return err
}
switch v, _ := strconv.Atoi(s[0:i]... |
package main
import (
"fmt"
// "flag"
"testing"
"time"
)
func TestFunc(t *testing.T) {
}
func TestFunc1(t *testing.T) {
t.Log("hello")
re, err := testing.CompileRegexp("mybench")
if err != "" {
t.Error("regexp compile failed")
}
if !re.MatchString("mybench") {
t.Error("mybench regexp d... |
package cluster
type Bootstrap struct {
}
func NewBootstrap() *Bootstrap {
return &Bootstrap{}
}
|
package httpservice
import (
"crypto-performance-compare/crypto"
"crypto-performance-compare/utils"
"fmt"
"html/template"
"net/http"
"strings"
)
func (h *HTTPHandler) ServeStats(w http.ResponseWriter, r *http.Request) {
data := make(map[string]interface{})
tmpl, err := template.ParseFiles("./httpservice/temp... |
package rsapi_test
import (
"encoding/json"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/rightscale/rsc/cm15"
"github.com/rightscale/rsc/rsapi"
"github.com/rightscale/rsc/ss/ssm"
)
var _ = Describe("normalize", func() {
var payload rsapi.APIParams
var name string
var value interface{}
... |
// Package ctx contains setters and getters for request context.
//
//
package ctx
import (
"context"
"net/http"
)
// generic context setter
func set(key interface{}, value interface{}, r *http.Request) *http.Request {
ctx := r.Context()
ctx = context.WithValue(ctx, key, value)
return r.WithContext(ctx)
}
// st... |
package main
import "fmt"
func main() {
defer func() {
if e := recover(); e != nil {
fmt.Println(e)
}
}()
var a [2]int
n := 2
println(a[n])
}
|
package HashTable
import (
"github.com/Amertz08/EECS560-go/Lab01/LinkedList"
"fmt"
)
type HashTable struct {
list []LinkedList.LinkedList
mod int
}
func NewHashTable(mod int) HashTable {
table := HashTable{mod:mod}
for i := 0; i < mod; i++ {
table.list = append(table.list, LinkedList.NewLinkedList())
}
re... |
package opa_auditor
import (
"fmt"
"time"
"github.com/MagalixCorp/magalix-agent/v3/agent"
"github.com/MagalixCorp/magalix-agent/v3/entities"
"github.com/MagalixCorp/magalix-agent/v3/kuber"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
opa "github.com/MagalixTechnologies/opa-core... |
package config
import (
"testing"
"fmt"
)
type SysParameters struct {
//parameters for websocket
Port int // Open Port of the service.
WriteWait int // Milliseconds until write times out.
PongWait int // Timeout for waiting on pong.
PingPeriod int // Milliseconds b... |
package tickets
import (
"encoding/json"
"net/http"
"os"
// CORS
"github.com/rs/cors"
// JWT
"github.com/dgrijalva/jwt-go"
// JSON Web Tokens middleware Auth0
"github.com/auth0/go-jwt-middleware"
// Mongodb
"gopkg.in/mgo.v2"
// Gorilla Mux
"github.com/gorilla/mux"
// Negroni framework
"github.com/urfav... |
package main
import "fmt"
func main() {
fmt.Println("Product of Array Except Self")
fmt.Println("Result= ", productExceptSelf([]int{1, 2, 3, 4}))
fmt.Println("Result= ", productExceptSelf([]int{1, 1}))
fmt.Println("Result= ", productExceptSelf([]int{1, -1}))
fmt.Println("Result= ", productExceptSelf([]int{0, 0}... |
package main
import (
"flag"
"fmt"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
var sess = session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
var clo... |
package cli
import (
"bytes"
"errors"
"io"
"strings"
"testing"
"github.com/pjbgf/go-test/should"
)
func TestNewConsole(t *testing.T) {
assertThat := func(assumption string, stdOut, stdErr *bytes.Buffer, shouldError bool) {
should := should.New(t)
hasErrored := false
defer func() {
if r := recover();... |
// Copyright 2009 The Go 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 apng
const PngHeader = "\x89PNG\r\n\x1a\n"
// Filter type, as per the PNG spec.
const (
ftNone = 0
ftSub = 1
ftUp = 2
ftAverage = 3
f... |
package link
import (
"testing"
"github.com/cilium/ebpf/internal/testutils"
)
func TestHaveProgAttach(t *testing.T) {
testutils.CheckFeatureTest(t, haveProgAttach)
}
func TestHaveProgAttachReplace(t *testing.T) {
testutils.CheckFeatureTest(t, haveProgAttachReplace)
}
func TestHaveBPFLink(t *testing.T) {
testu... |
package server
import (
"context"
"net/http"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
func TestRequestID(t *testing.T) {
t.Run("returns empty id if no id exists", func(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, "example.com", nil)
require.Nil(t, err)
re... |
package fakerp
import (
"context"
"strings"
azdns "github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-10-01/dns"
"github.com/Azure/go-autorest/autorest/to"
"github.com/sirupsen/logrus"
"github.com/openshift/openshift-azure/pkg/api"
"github.com/openshift/openshift-azure/pkg/util/azureclient"
"github.com... |
//
// Copyright 2020 The AVFS 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 applicable law or ag... |
package main
import (
//"fmt"
"math"
)
type Color struct {
H uint16 /*0..360*/
S, V float64 /*0..1*/
R, G, B uint8 /*0..255*/
}
func (a *Color) RGB() (r, g, b uint8) {
return a.R, a.G, a.B
}
func (a *Color) RGBfromHSV() (r, g, b uint8) {
// Direct implementation of the graph in this image:
// ht... |
package server
import (
"flag"
"fmt"
"net"
log "../log"
)
const (
MaxRead = 1024 * 1024 //1MB
)
var Opts *Options
type Options struct {
TcpAddr string
Port string
LogTo string
LogLevel string
DBPath string
DBType string
Rcl bool
}
func parseArgs() *Options {
tcpAddr := flag.String("a... |
package k8sml
type Cloud interface {
GetID() string
GetVariableValue(variable string) interface{}
GetCloudProvider() CloudProvider
GetIPv4Cidr() []*IPv4Cidr
GetInternetGateway() *InternetGateway
GetKubernetes() *Kubernetes
AddRuntimeVariable(key, value string)
GetRuntimeVariables() map[string]string
ExportMod... |
package testlogger_test
import (
"testing"
"github.com/rwool/ex/log"
"github.com/rwool/ex/test/helpers/testlogger"
"github.com/stretchr/testify/assert"
)
func TestNewTestLogger(t *testing.T) {
// Creating a new testing object to prevent unnecessary output.
t2 := &testing.T{}
l, buf := testlogger.NewTestLogger... |
package main
import (
"fmt"
"time"
"net/http"
"github.com/julienschmidt/httprouter"
"encoding/json"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/cloudwatch"
)
type AWSResponse struct {
Datapoints [... |
// 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 or agreed to in writing... |
package main
import (
"fmt"
"bufio"
"github.com/dspinhirne/netaddr-go"
"github.com/libp2p/go-reuseport"
)
const (
REMOTE = "%s:9090"
LOCAL = "127.0.0.1:9091"
)
func connect(conn int, laddr, raddr string, next chan bool) {
c, err := reuseport.Dial("tcp4", laddr, raddr)
if err != nil {
panic(fmt.Sprintf("%T:... |
package DMST
import (
"errors"
"fmt"
"log"
"strconv"
"sync"
"time"
"os"
"path"
)
const Infinite = (1<<31) - 1
// Node possible states
const SleepingState = "Sleeping"
const FindState = "Find"
const FoundState = "Found"
// Edge possible states
const RejectedState = "Rejected"
const BranchState = "Branch"
con... |
package colorize
import "testing"
func TestNew(t *testing.T) {
c := NewColorize()
if r := c.Paint("test"); r != "\033[0;39;49mtest\033[0m" {
t.Errorf("Incorrect format - " + r)
}
}
func TestSkip(t *testing.T) {
c := NewColorize()
c.Fg(Red)
SkipFormatting(true)
if r := c.Paint("test"); r != "test" {
t.Erro... |
package cmd
import (
"context"
"fmt"
"net/http"
"sort"
"strings"
"time"
"github.com/google/go-github/v30/github"
"github.com/integr8ly/delorean/pkg/quay"
"github.com/integr8ly/delorean/pkg/services"
"github.com/integr8ly/delorean/pkg/utils"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/util/wait"
)
c... |
package main
var ans []string
func letterCasePermutation(S string) []string {
ans = make([]string,0)
letterCasePermutationExec([]byte(S),[]byte{})
return ans
}
func letterCasePermutationExec(bytes []byte,seq []byte) {
if len(bytes)==0{
ans = append(ans,string(seq))
return
}
if bytes[0]>='a' && bytes[0]<='z... |
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main(){
r:=gin.Default()
r.GET("/test", func(c *gin.Context) {
time.Sleep(8*time.Second)
c.String(200, "hello test\n")
})
srv:=&http.Server{
Addr:":8085",
Handler: r,
}
go ... |
package goSolution
import "sort"
type BuildingDiff struct {
Diff, Index int
}
type BuildingDiffs []BuildingDiff
func (a BuildingDiffs) Len() int {return len(a)}
func (a BuildingDiffs) Less(i, j int) bool {return a[i].Diff > a[j].Diff || (a[i].Diff == a[j].Diff && a[i].Index < a[j].Index)}
func (a BuildingDiffs) Sw... |
package main
import "defrag"
import "fmt"
func main() {
fmt.Println("Part1 - How Many 1's in the Grid?")
seed := "ffayrhll"
grid := defrag.SeedToGrid(seed)
population := defrag.CountOccupiedBits(grid)
fmt.Println("\t",population)
}
|
package main
import "testing"
func TestFetchRepoRoot(t *testing.T) {
for _, tc := range []struct {
imp string
exp string
}{
{"gopkg.in/alecthomas/kingpin.v2", "https://github.com/alecthomas/kingpin"},
{"k8s.io/api/v1", "https://github.com/kubernetes/api"},
{"k8s.io/kubernetes/pkg/apis/core/vali... |
package main
import (
"fmt"
"math/rand"
"time"
)
func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
func main() {
var hiddenNum int = random(1, 10)
var guessNum int
var amt int = 1
fmt.Println("Please enter a number 1-10... ")
fmt.Scan(&guessNum)
for ; guessNum ... |
package matchserver
import (
"context"
"io"
"log"
"time"
"github.com/ekotlikoff/gochess/internal/model"
pb "github.com/ekotlikoff/gochess/api"
"google.golang.org/grpc"
)
func (matchingServer *MatchingServer) createEngineClient(
engineAddr string, engineConnTimeout time.Duration) {
var opts []grpc.DialOptio... |
package cosmos
import "testing"
func TestLineString(t *testing.T) {
coords := Coordinates{{5.0, 10.0}, {10.0, 11.0}, {5.0, 10.0}}
ls := NewLineString()
for _, p := range coords {
ls.AddPoint(p[0], p[1])
}
if len(ls.Coordinates) != 3 {
t.Fatalf("expected %d coords, got: %d", 3, len(ls.Coordinates))
}
for ... |
// Copyright (c) 2017 jelmersnoeck
// Copyright (c) 2018 Aiven, Helsinki, Finland. https://aiven.io/
package aiven
import (
"fmt"
"github.com/aiven/terraform-provider-aiven/pkg/cache"
"log"
"net/url"
"strings"
"time"
"github.com/aiven/aiven-go-client"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
... |
package web
import (
"os"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/session/v2"
"github.com/gofiber/template/html"
"github.com/iamtraining/forum/apiserver"
"github.com/iamtraining/forum/store"
)
type Handler struct {
store store.Store
App *fiber.... |
package server
import (
"net/http"
"github.com/asaskevich/govalidator"
"github.com/go-chi/render"
log "github.com/sirupsen/logrus"
)
type response struct {
Data interface{} `json:"data"`
Errors []apiError `json:"errors"`
Status int `json:"status"`
}
func (response *response) Render(w http.Response... |
package api
import (
"context"
"testing"
"github.com/brigadecore/brigade/v2/apiserver/internal/meta"
metaTesting "github.com/brigadecore/brigade/v2/apiserver/internal/meta/testing" // nolint: lll
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
)
func TestUserMarshalJSON(t *testing.T) {
metaTesti... |
package throttle_limiter
type funnel interface {
// 漏斗限流
// @param key: 行为
// @param capacity: 漏斗的初始容量
// @param opsPerSecond: 每秒生成的令牌数量
// @param quota: 每个行为占用的令牌数
Throttle(key string, capacity int, opsPerSecond int, quota int)
}
|
package main
import (
"flag"
"sync"
"github.com/k8guard/k8guard-discover/caching"
"github.com/k8guard/k8guard-discover/discover"
"github.com/k8guard/k8guard-discover/messaging"
"github.com/k8guard/k8guard-discover/metrics"
lib "github.com/k8guard/k8guardlibs"
)
var (
Version string
Build string
)
var err... |
package util
import (
"bufio"
"context"
"fmt"
"github.com/yahoo/vssh"
"io"
"log"
"os"
"strings"
"time"
)
type SSHObject struct {
Host string
Port string
Username string
Password string
}
func (ssh SSHObject) ExecuteOriginCmd(cmd string, timeout time.Duration) (msg string, exitCode int) {
var ou... |
package arrays
func findPairs(nums []int, k int) int {
if nums == nil || len(nums) == 0 || k < 0 {
return 0
}
h := map[int]int{}
count := 0
for _, v := range nums {
h[v]++
}
if k == 0 {
for _, v := range h {
if v > 1 {
count++
}
}
return count
}
hh := map[int]bool{}
for v := range h {
i... |
/*
* Minio Client (C) 2015 Minio, 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... |
package main
import (
"compress/gzip"
f "fmt"
"io/ioutil"
"os"
)
func main() {
file, err := os.Open("hello.txt.gz")
if err != err {
f.Println(err)
return
}
defer file.Close()
r, err := gzip.NewReader(file)
if err != nil {
f.Println(err)
return
}
defer r.Close()
b, err := ioutil.ReadAll(r)
if ... |
package main
import (
"fmt"
"strconv"
)
func Parse() {
// 接受1、0、t、f、T、F、true、false、True、False、TRUE、FALSE;否则返回错误
v := "true"
if s, err := strconv.ParseBool(v); err == nil {
fmt.Printf("%T, %v\n", s, s) // bool, true
}
// ------ ParseInt 返回字符串表示的整数值,接受正负号 ------
// base 指定进制(2到36),如果 base 为0,则会从字符串前置判断,”0x”是... |
/**
* Copyright (C) 2019, Xiongfa Li.
* All right reserved.
* @author xiongfa.li
* @version V1.0
* Description:
*/
package util
import "strings"
func AddParam(url string, param map[string]string) string {
if strings.LastIndex(url, "?") == -1 {
url += "?"
}
size := len(param)
for k, v ... |
package main
import "fmt"
func changeVal(str *string){
*str = "change new"
}
//func changeVal2(str string){
// str = "change new"
//}
func main() {
// & => stand for get the address/map pointer of memory
// * => stand for pointer based/derefrences
toChange := "coba"
fmt.Println(toChange)
changeVal(&toChange)
... |
package rstreams
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/batchcorp/plumber-schemas/build/go/protos/args"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber/validate"
"github.com/batchcorp/plumber/types"
)
var _ = Describe("Redis Streams... |
package backends
type GolangConfig interface {
ConfigCommon
PackageName() string
SetPackageName(val string)
}
type GolangConfigImpl struct {
packageName string
}
func (this *GolangConfigImpl) Init() {
this.packageName = "abnf"
}
func (this *GolangConfigImpl) PackageName() string {
return this.packageName
}
... |
package myapp
import (
"time"
)
//Payment represents Model Payment
type Payment struct {
PaymentID int `sql:"AUTO_INCREMENT" gorm:"primary_key"`
SubscriptionID uint
Amount float64
DatePaid time.Time `sql:"DEFAULT:current_timestamp"`
}
|
/*
Copyright 2019 Dmitry Kolesnikov, 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 trees
import (
"fmt"
"strings"
"github.com/Nv7-Github/Nv7Haven/eod/types"
)
// Tree calculator
type Tree struct {
text *strings.Builder
rawTxt *strings.Builder
calced map[string]types.Empty
num int
dat types.ServerData
}
func (t *Tree) AddElem(elem string) (bool, string) {
_, exists := t.calc... |
package report
import (
"strings"
"fmt"
"time"
)
type CLIReporter struct {
}
func NewCLIReporter() *CLIReporter {
return &CLIReporter{}
}
func (r *CLIReporter) AddReport(options ReporterOptions) error {
// Heading printing
fmt.Printf("====== %s ======\n", strings.ToUpper(options.Name))
fmt.Printf(" %d requ... |
package heap
import (
"testing"
)
func TestCreateHeap(t *testing.T) {
//var data []int
//for i := 0; i < 10; i++ {
// data = append(data, randomdata.Number(1, 100))
//}
data := []int{18,66,50,49,96,44,25,72,17,54}
t.Log("origin: ", data)
heap := CreateHeap(data)
t.Log(heap)
t.Log(heap.Pop())
t.Log(heap)
}
|
package simple_goroutine_pool
import (
"fmt"
"sync"
"time"
)
type GoroutinePool struct {
mu sync.Mutex //mu 线程锁,用于处理并发
coreSize int32 //coreSize 核心工作协程数量
maxSize int32 //maxSize 最大工作协程数量
queue chan Task //queue 任务队列
duration time.Duration //duration 最大协程等待时... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
// DData data structure for import
type DData map[string][]string
//Dict struct maps DData map to mongodb struct
type Dict struct {
Word string `json:"word"`
Explain []string `json:"explai... |
// 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 main
//Create your own type “person” which will have an underlying type of “struct” so that it can store the following data:
//first name
//last name
//favorite ice cream flavors
//Create two VALUES of TYPE person. Print out the values, ranging over the elements in the slice which stores the favorite flavors.
... |
package main
import (
"errors"
"log"
"os"
"strings"
"github.com/evan-buss/openbooks/cli"
"github.com/spf13/cobra"
)
var config cli.Config
func init() {
rootCmd.AddCommand(cliCmd)
cliCmd.AddCommand(downloadCmd)
cliCmd.AddCommand(searchCmd)
cwd, err := os.Getwd()
if err != nil {
log.Fatalln("Could not g... |
package gov
import (
"encoding/json"
"fmt"
"strings"
"time"
sdk "github.com/irisnet/irishub/types"
"github.com/pkg/errors"
)
//-----------------------------------------------------------
// Proposal interface
type Proposal interface {
GetProposalID() uint64
SetProposalID(uint64)
GetTitle() string
SetTitle... |
package postgres
import (
"database/sql"
"reflect"
"regexp"
"testing"
"time"
sqlmock "github.com/DATA-DOG/go-sqlmock"
"github.com/kylegrantlucas/platform-exercise/models"
_ "github.com/lib/pq"
)
func TestCreateDatabase(t *testing.T) {
type args struct {
host string
port string
user string
... |
package common
var Config struct {
Auth0Secret string `short:"s" long:"auth-secret" description:"The secret from Auth0" required:"true"`
ServerPort int `short:"p" long:"server-port" description:"The server port" default:"8000" required:"true"`
Database struct {
Address string `long:"db-address" descriptio... |
package core
const (
LOW = iota
HIGH
)
const (
INPUT = iota
OUTPUT
PULL_OFF
PULL_DOWN
PULL_UP
PWM_OUTPUT
GPIO_CLOCK
SOFT_PWM_OUTPUT
SOFT_TONE_OUTPUT
PWM_TONE_OUTPUT
)
const (
LSBFIRST = iota
MSBFIRST
)
const (
_ = iota
CHANGE
FALLING
RISING
)
const (
MMAP_BLOCK_SIZE = 4096
DEV_GPIO_MEM = "/d... |
// 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.