text stringlengths 11 4.05M |
|---|
package model
import (
"log"
"os"
)
type Processor struct {
dataDir string
databases map[string]Database
done chan bool
RequestCh chan Request
ResultCh chan Result
}
func loadDatabases(dataDir string) map[string]Database {
databases := make(map[string]Database)
dir, err := os.Open(dataDir)
if err ... |
package primary
import "github.com/renne444/go-example/init-order-example/secondary"
var (
F = secondary.Invoke()
)
|
package imdb
import (
"os"
"testing"
"github.com/DexterLB/mvm/testutils"
)
func TestMain(m *testing.M) {
os.Exit(testutils.RecordHTTP(m, "fixtures/imdb"))
}
|
package main
import (
"log"
"net/http"
route "github.com/rapidclock/align-bot-stats-cache/routehandlers"
"github.com/rapidclock/align-bot-stats-cache/cache"
)
func init() {
cache.InitializeWithStats()
}
func main() {
log.Fatal(http.ListenAndServe(":15000", route.NewRedisAppHandler()))
}
|
package format
import (
"github.com/plandem/xlsx/internal/ml"
"github.com/stretchr/testify/require"
"testing"
)
func TestNumberFormat(t *testing.T) {
style := NewStyles(
NumberFormatID(8),
)
require.IsType(t, &StyleFormat{}, style)
require.Equal(t, createStylesAndFill(func(f *StyleFormat) {
f.styleInfo.Nu... |
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
package controller
import (
"container/list"
"fmt"
"log"
"time"
"github.com/swinslow/peridot-core/internal/jobcontroller"
pba "github.com/swinslow/peridot-core/pkg/agent"
pbs "github.com/swinslow/peridot-core/pkg/status"
)
// createNewJobSets walks t... |
package keypair
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/types"
)
func TestBuild(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Package: github.com/textileio/go-textile/keypair")
}
var (
address = "... |
package domain
import "github.com/bearname/videohost/internal/common/db"
type CommentDto struct {
UserId string
VideoId string
Message string
ParentId int
}
type CommentService interface {
Create(commentDto CommentDto) (int64, error)
FindRootLevel(videoId string, page *db.Page) (VideoComments, error)
Find... |
// Copyright © 2020. All rights reserved.
// Author: Ilya Stroy.
// Contacts: qioalice@gmail.com, https://github.com/qioalice
// License: https://opensource.org/licenses/MIT
package privet
import (
"github.com/qioalice/ekago/v2/ekastr"
)
/*
isValidLocaleName reports whether passed s is a valid locale name
that is i... |
package main
import (
"bufio"
"compress/bzip2"
"compress/gzip"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"./lib"
"github.com/cheggaaa/pb"
"github.com/ulikunitz/xz"
)
type opts struct {
src string
ds... |
package main
import (
"fmt"
"os"
)
const (
EnvDebug = "LI_DEBUG"
)
func main() {
cli := &CLI{outStream: os.Stdout, errStream: os.Stderr}
os.Exit(cli.Run(os.Args))
}
func Debugf(format string, args ...interface{}) {
if os.Getenv(EnvDebug) != "" {
fmt.Fprintf(os.Stdout, "[DEBUG] "+format+"\n", args...)
}
}
|
/*
* Copyright © 2018-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
// Package reverse helps to revert things like strings or runes
package reverse
import (
"fmt"
"unicode/utf8"
)
// RevertString reverts UTF8 string by
// converting it to runes and returns
// a new string
func RevertString(line string) string {
runes := []rune(line)
RevertRunes(runes)
return string(runes)
}
// ... |
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"github.com/eduardomello/rest-api/models"
"github.com/gorilla/mux"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type TodoController struct {
C *mgo.Collection
}
func NewTodoController(s *mgo.Session) *TodoController {
tc := TodoController{s.DB("re... |
package main
import (
"fmt"
)
type Currency int
const (
USD Currency = iota // $
EUR
GBP
RMB
)
func main() {
symbol := [...]string{USD: "$", EUR: "E", GBP: "L", RMB: "Y"}
fmt.Println(RMB, symbol[RMB])
}
|
package strategy
import (
"github.com/rodrigo-brito/ninjabot/pkg/exchange"
"github.com/rodrigo-brito/ninjabot/pkg/model"
"github.com/rodrigo-brito/ninjabot/pkg/series"
)
type Controller struct {
strategy Strategy
dataframe *model.Dataframe
broker exchange.Broker
started bool
}
func NewStrategyController... |
package common
import (
hcov1beta1 "github.com/kubevirt/hyperconverged-cluster-operator/pkg/apis/hco/v1beta1"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
conditionsv1 "github.com/openshift/custom-resource-status/conditions/v1"
corev1 "k8s.io/api/core/v1"
)
var _ = Describe("HCO Conditions Tests", func(... |
package storage
import (
"database/sql"
"github.com/0studio/databasetemplate"
"github.com/wgyuuu/storage_key"
)
type MysqlEncoding interface {
GetKey(obj interface{}) storage_key.Key
Get(key storage_key.Key) string
Add(obj interface{}) string
Set(obj interface{}) string
// return "" -> transfer Get
Multi... |
package main
import (
"errors"
"strings"
)
func Pathinfo(file string) (map[string]string, error) {
if len(file) == 0 {
return nil, errors.New("file path is empty!")
}
var result map[string]string = make(map[string]string)
info := strings.Split(file, "/")
info_len := len(info)
if info_len == 1 {
result["ba... |
package dbaccess
import (
"log"
"sync"
"time"
)
const foodsOfACatSql = `
SELECT f.id, f.name, f.name_fa, f.description, f.description_fa, f.price,
i.url thumbnail
FROM foods f, images i
WHERE f.image_id = i.id
AND f.food_category_id = $1
`
type (
// Food stores basic data about foods
Food struct {
... |
// Package util contains useful functions for client.
package util
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/textproto"
"net/url"
"os"
"strings"
"github.com/BurntSushi/toml"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
"github.com/xakep66... |
package artifacts
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
type resources struct {
kubeClient kubernetes.Interface
namespace string
}
func (r resources) GetSecret(name, key string) (string, error) {
secret, err := r.kubeClient.CoreV1().Secrets(r.namespace).Get(name... |
package accountentity
const(
Common = "common"
Table = "table"
)
type Column struct{
Name string
Name_en string
Column string //database column name
Type string
Maxsize int
}
|
package main
import (
"flag"
"fmt"
"github.com/get-go/shamebot/parse"
"github.com/get-go/shamebot/poll"
git "github.com/libgit2/git2go"
"os"
"time"
)
var repoName = flag.String("repo", "", "Path to git repository")
func main() {
flag.Parse()
if flag.NFlag() < 1 {
fmt.Fprintf(os.Stderr, "Usage:\n")
flag... |
package utils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestChunkSlice(t *testing.T) {
assert.ElementsMatch(t, ChunkSlice(
[]interface{}{10, 2, 3, 4, 5, 34, 34, 12}, 4),
[][]interface{}{
[]interface{}{10, 2, 3, 4},
[]interface{}{5, 34, 34, 12},
})
assert.ElementsMatch(t, ChunkSl... |
package kucoin
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/sirupsen/logrus"
)
// A Request represents a HTTP request.
type Request struct {
fullURL string
requestURI string
BaseURI ... |
package solcast
// LatLng location on the Earth, expected projection 4326
type LatLng struct {
Latitude float64
Longitude float64
}
// Expanded LatLng location on the Earth, expected projection 4326 with a Capacity property
type PowerLatLng struct {
LatLng
Capacity int
}
|
//
package main
type Vector [3]float64
type Matrix4x4 [16]float64
/*
#cmethod Multiply
#csafe_method FastMultiply
*/
type MultiplyVectors struct {
Mat Matrix4x4
Vectors []Vector
}
|
package struct2elasticMapping
import (
"encoding/json"
)
func MappingAsJson(name string, m *Mapping) ([]byte, error) {
v := make(map[string]Mapping)
v[name] = *m
return json.MarshalIndent(v, "", "\t")
}
|
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/linkedlocked/webapp/database"
"github.com/linkedlocked/webapp/models"
"github.com/linkedlocked/webapp/utils"
)
/*
Router User Code
*/
func GetUserObject(c *gin.Context) models.User {
userID := getUserID(c)
userObj, contextUserExists := c.Get... |
package pgsql
import (
"testing"
)
func TestBitArray(t *testing.T) {
testlist2{{
valuer: BitArrayFromBoolSlice,
scanner: BitArrayToBoolSlice,
data: []testdata{
{input: []bool(nil), output: []bool(nil)},
{input: []bool{}, output: []bool{}},
{input: []bool{true}, output: []bool{true}},
{input: []bo... |
// 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... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-30 09:15
# @File : lt_64_Minimum_Path_Sum.go
# @Description :
# @Attention :
*/
package array
import (
"fmt"
"testing"
)
func Test_minPathSum(t *testing.T) {
fmt.Println(minPathSum([][]int{
[]int{1, 3, 1},
[]int{1, 5, 1},
[]int{4, 2, 1},
}))
}
|
package trigger
import (
"errors"
"fmt"
"os"
"reflect"
"sync"
)
// 事件默认最大监听数量
const defaultMaxListeners = 16
// 错误
var ErrNotFunction = errors.New("传入参数不是函数类型")
var ErrExceedMaxListeners = errors.New("此事件超过最大监听数量")
// 错误处理函数
type RecoveryFunc func(interface{}, interface{}, error)
// 默认错误处理函数
var defaultRecove... |
package persistence
import "gopkg.in/mgo.v2/bson"
type DatabaseHandler interface {
AddEvent(Event) ([]byte, error)
FindEvent([]byte) (Event, error)
FindEventByName(string) (Event, error)
FindAllAvailableEvents() ([]Event, error)
}
type Event struct {
ID bson.ObjectId `bson:"_id"`
Name string
Duration int
Sta... |
package strmap
import (
"sync"
"sync/atomic"
)
type (
// CopyOnWriteMap is a synchronous copy on write map. Reads are cheap. Writes are expensive.
CopyOnWriteMap struct {
data atomic.Value
mutex sync.Mutex // used only by writers
}
)
// NewCopyOnWriteMap initializes a new empty map.
// Use of nil to empty ... |
package main
import "strings"
type command map[string]string
type commandHandler func(*client, command)
func (a *app) cmdEcho(c *client, cmd command) {
c.send(response{
"command": "echo",
"id": c.id,
"payload": cmd["payload"],
})
}
func (a *app) cmdName(c *client, cmd command) {
name, ok := cmd["name... |
package ast
// Select represents a SQL SELECT statement.
type Select struct {
Fields []*Field
Table *Table
JoinTables []Join
Conditions []*EqualsCondition
Limit string
Offset string
}
func NewSelect() *Select {
return &Select{}
}
func (ss *Select) AddField(field *Field) {
ss.Fields = append... |
package bitbucket_v2
type Page struct {
PageLen int `json:"pagelen"`
Page int `json:"page"`
Size int `json:"size"`
Next string `json:"next"`
previous string `json:"previous"`
}
|
package hfm
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
"github.com/asaskevich/govalidator"
)
type Record struct {
Hosts []string
IP string
Line int
Raw string
}
type Records []Record
type Hosts struct {
records Records
path string
}
// Return new `Hosts` inst... |
package main
import (
"github.com/tecbot/gorocksdb"
)
// dummyMergeOperator actually doesn't do any useful work
type dummyMergeOperator struct{}
var _ gorocksdb.MergeOperator = (*dummyMergeOperator)(nil)
func (mo *dummyMergeOperator) FullMerge(_, _ []byte, _ [][]byte) ([]byte, bool) {
return []byte{}, true
}
fun... |
package bootstrap
import (
"bytes"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net"
"os"
"path"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/containers/image/pkg/sysregistriesv2"
ignutil "github.com/coreos/ignition/v2/config/util"
igntypes "github.com/coreos/ignition/v2/co... |
// 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 "fmt"
type money int64 //
type rupee money
type paisa rupee
func main() {
var r = 1
var dollar money = 100
var rupee money = money(r)
fmt.Println(dollar, rupee)
}
|
package controllers
import (
"github.com/gorilla/mux"
"net/http"
"server/src/dto"
"server/src/services/interfaces"
"strconv"
"time"
)
type AchievementController struct {
achievementService interfaces.AchievementServiceProvider
}
func NewAchievementController(achievementService interfaces.AchievementServicePro... |
package main
import "fmt"
var size int
var dx []int
var dy []int
// 初始化参数
func initParameter() {
dx = []int{0, 0, 1, -1}
dy = []int{1, -1, 0, 0}
size = 3
}
// 判断该点是否可以走
func judge(newGrid [][]int, x, y int) bool {
if len(newGrid) == 0 {
return false
}
m, n := len(newGrid), len(newGrid[0])
if x < 0 || y < 0 ... |
package main
import "fmt"
const ( // iota is reset to 0
c0 = iota // c0 == 0
c1 = iota // c1 == 1
c2 = iota // c2 == 2
)
const (
a = 1 << iota // a == 1 (iota has been reset)
b = 1 << iota // b == 2
c = 1 << iota // c == 4
)
const (
u = iota * 42 // u == 0 (untyped integer constant)
v float64 = ... |
package operation
import (
"io/ioutil"
"log"
"security_lib/aes_lib/aes_lib"
)
func GenerateKey(path string) {
log.Println("[*] Generating key")
key := aes_lib.GenerateKey()
log.Println("[*] Saving key to ", path)
err := ioutil.WriteFile(path, key, 0644)
if err != nil {
log.Println("[=] Error saving the key... |
package graphql
import (
"fmt"
"reflect"
"sort"
"github.com/graphql-go/graphql/language/ast"
"github.com/graphql-go/graphql/language/printer"
)
const (
TypeKindScalar = "SCALAR"
TypeKindObject = "OBJECT"
TypeKindInterface = "INTERFACE"
TypeKindUnion = "UNION"
TypeKindEnum = "ENUM"
... |
package shipping
import (
"net/http"
"github.com/Haski007/shipping-apis/api"
)
type Shipping struct {
Client http.Client
Resources []api.Resource
//FirstAPI api.Resource
//FirstAPI api.Resource
}
func NewShipping() *Shipping {
return &Shipping{
Client: http.Client{},
Resources: []api.Resource{
api.N... |
package helloworld
import "golang.org/x/sys/unix"
// GetFHelloWorld will get the hello world string
func GetHelloWorld() string {
return "Hello, World!"
}
// GetUserID gets the ID of the current user
func GetUserID() int {
return unix.Getuid()
}
func GetAbsValue(i int) int {
if i > 0 {
return i
}
return -1 *... |
1) struct 的内存分布原理
原理
关于Golang同一struct中field的书写顺序不同内存分配大小也会不同。主要原因如下:struct内field内存分配是以4B为基础,超过4B时必须独占。
type A1 struct {
a bool
b uint32
c bool
d uint32
e uint8
f uint32
g uint8
}
计算一下A1所需要占用的内存:
首先第1个4B中放入a,a是bool型,占用1B,剩余3B
这时看b是uint32,占用4B,剩余3B放不下,所以offset到下一个4B空间,这时我们会发现3B没有放东西,被浪费了
依次... |
package errno
// 应用级错误
const (
// 个人信息相关
NICK_EXIST Errno = 2020
strNickExist = "昵称已存在"
NICK_INVALID Errno = 2021
strNickInvalid = "昵称内容不合法"
NICK_LENGTH_INVALID Errno = 2022
strNickLengthInvalid = "昵称长度不合法"
GENDER_ERROR Errno = 2025
strGenderError ... |
package main
import (
"fmt"
"net/http"
"time"
)
// func handler(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintln(w, "Hello World!", r.URL.Path)
// }
// func helloHandler(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintln(w, "Hello!", r.URL.Path)
// }
// func main() {
// http.HandleFunc("/", ha... |
package tasks_test
import (
"testing"
"github.com/ghodss/yaml"
"github.com/stretchr/testify/assert"
"go.ua-ecm.com/chaki/tasks"
)
func TestOptionalStringArrayUnmarshal(t *testing.T) {
assert := assert.New(t)
type complexType struct {
SQL tasks.OptionalStringArray `json:"sql"`
}
cases := []struct {
dat... |
package main
import "fmt"
func main() {
var n int
fmt.Scanf("%d", &n)
for i := 0; i < n; i++ {
joao := 0
for i := 0; i < 3; i++ {
var x, d int
fmt.Scanf("%d %d", &x, &d)
joao += x * d
}
maria := 0
for i := 0; i < 3; i++ {
var x, d int
fmt.Scanf("%d %d", &x, &d)
maria += x * d
}
i... |
package types
import (
"testing"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func TestPoolEqual(t *testing.T) {
p1 := InitialPool()
p2 := InitialPool()
require.True(t, p1.Equal(p2))
p2.BondedTokens = sdk.NewDec(3)
require.False(t, p1.Equal(p2))
}
func TestAddBondedToken... |
package main
import "fmt"
func main() {
nums := []int{2, 7, 11, 15}
target := 9
fmt.Printf("nums: %v\ntarget: %d\n", nums, target)
fmt.Printf("result: %v\n", twoSum(nums, target))
}
// 两数之和 使用map结构来做算法复杂度是O(n),利用空间来换
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i := 0; i < len(nums); ... |
/////////////////////////////////////////////////////////////////////
// arataca89@gmail.com
// 20210417
//
// func Repeat(s string, count int) string
//
// Retorna uma nova string com s repetida count vezes.
//
// Se count é negativo ou se len(s) * count provoca um overflow
// Repeat() entra em pânico (panic)... |
// Copyright © 2017 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 main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
type jsn2 struct {
Company string
Subjects [4]string
IsOk bool
Price int
}
func main() {
jsnStr := `{"Company":"itcast","Subjects":["Go","C++","Python","前端"],"IsOk":true,"Price":666}`
var jsn = &jsn2{}
bytSli := bytes.NewBufferString(jsn... |
package main
import "testing"
func Test_matchWhitespace(t *testing.T) {
type args struct {
text string
source string
}
tests := []struct {
name string
args args
want string
}{
{
name: "Leading whitespace",
args: args{
text: "a",
source: " b",
},
want: " a",
},
{
name: ... |
package main
import (
"fmt"
"math"
"sync"
"time"
"github.com/gordonklaus/portaudio"
"github.com/mjibson/go-dsp/spectral"
)
const (
SAMPLE_RATE = 20000
FRAMES_PER_BUFFER = 512
NUM_CHANNELS = 1
DEBUG = false
)
type SAMPLE float32
type SoundSingnal struct {
sync.Mutex
*portaudio.Str... |
package mill
import (
"encoding/json"
"io/ioutil"
"os"
"testing"
"github.com/textileio/go-textile/mill/testdata"
)
func TestImageExif_Mill(t *testing.T) {
m := &ImageExif{}
for _, i := range testdata.Images {
file, err := os.Open(i.Path)
if err != nil {
t.Fatal(err)
}
input, err := ioutil.ReadAll... |
package anagrams
import (
"fmt"
"testing"
)
var mapChar = map[rune]int64{
'a' : 89,
'b' : 3,
'c' : 5,
'd' : 7,
'e' : 11,
'f' : 13,
'g' : 17,
'h' : 23,
'i' : 29,
'j': 107,
'k' : 31,
'l' : 37,
'm' : 41,
'n' : 47,
'o' : 2,
'p' : 53,
'q' : 59,
'r' : 61,
's' : 67,
't' : 71,
'v' : 73,
'u' : 97,
'z'... |
package hot100
// 关键:
// 一大堆边界条件判断,dp的时候的长度都是len+1,返回值都是返回len
// 状态转移方程:
// f(i)=f(i-1) + f(i-2)
// 当选择一个数的时候,f(i)+=f(i-1)
// 当选择2个数的时候,f(i)=f(i-1)+f(i-2)
// 解码的时候,可以由1个数解码,也可以是2个数合在一起解码
func numDecodings(s string) int {
dp := make([]int, len(s)+1)
dp[0] = 1
for i := 1; i <= len(s); i++ {
if s[i-1] != '0' {
dp... |
package deps
import (
"bufio"
"io"
"os"
"strings"
)
type Module struct {
Name string
// Deps is a map of dependency to its version
Deps map[string]string
}
func ParseModule(moduleFile string) (mod Module, err error) {
f, err := os.Open(moduleFile)
if err != nil {
return mod, err
}
defer f.Close()
r :=... |
package types
type Genre struct {
ID int `json:"id"`
Name string `json:"name"`
AddedAt string `json:"added_at"`
} |
package game
type MaterialType string
const (
Wood MaterialType = "Wood"
Stone MaterialType = "Stone"
Iron MaterialType = "Iron"
Steel MaterialType = "Steel"
Leather MaterialType = "Leather"
Chainmail MaterialType = "Chainmail"
Cloth MaterialType = "Cloth"
Plate MaterialType = "Pla... |
/*
* Copyright © 2020-2022 Software AG, Darmstadt, Germany and/or its licensors
*
* SPDX-License-Identifier: Apache-2.0
*
* 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://... |
package main
var (
TableSQL = "SELECT " +
"table_name name " +
"FROM " +
"information_schema.tables " +
"WHERE " +
"table_schema=?"
FieldSQL = "SELECT " +
"COLUMN_NAME name, COLUMN_KEY col_key, COLUMN_COMMENT comment, DATA_TYPE data_type " +
"FROM " +
"information_schema.columns " +
"WHERE " +
"t... |
package main
import (
"bytes"
"fmt"
"github.com/go-redis/redis"
"io/ioutil"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
)
const (
redisLuaIncrScript = `local v=redis.call("incrby",KEYS[1],1) if v==1 then redis.call("expire",KEYS[1],KEYS[2]) end return v`
rateLimitErrorMsg = "rate limi... |
package main
import (
"bufio"
"crypto/x509"
"encoding/base64"
"encoding/json"
"flag"
"github.com/adamdecaf/zlint/zlint"
log "github.com/Sirupsen/logrus"
"os"
"runtime"
"sync"
)
var ( //flags
inPath string
outPath string
numCertThreads int
prettyPrint bool
numProcs int
... |
package gallery
import (
"testing"
. "github.com/bborbe/assert"
)
func TestCreateEntry(t *testing.T) {
var err error
entryId := "entryId123"
imageId := "imageId123"
previewImageId := "previewImageId123"
entryPrio := 23
entry := CreateEntry(entryId, imageId, previewImageId, entryPrio)
err = AssertThat(entry,... |
package fake
import (
"github.com/yydzero/mnt/parser"
"golang.org/x/net/context"
"github.com/yydzero/mnt/executor"
)
type FakeExecutor struct {
}
func (e *FakeExecutor) Prepare(ctx context.Context, query string, args parser.MapArgs) (
[]executor.ResultColumn, parser.MapArgs, error) {
cols := makeFakeColumns()
... |
package queue
import (
"fmt"
"time"
"github.com/appootb/substratum/logger"
)
type Message struct {
svc *Debug
queue string
topic string
content []byte
retry int
timestamp time.Time
delay time.Duration
}
// Queue name of this message.
func (m *Message) Queue() string {
return m.que... |
package 待分类
import (
"bytes"
"fmt"
)
func main() {
var b bytes.Buffer
b.Write([]byte("hello"))
b.Write([]byte("world"))
fmt.Printf("%+v\n", b)
s1 := b.Bytes()
fmt.Printf("%v\n", string(s1))
fmt.Println(b.String())
/*fmt.Fprintf(&b," %v", "world")
io.Copy(os.Stdout, &b)*/
}
/*
1.接口作用: 用于定义行为 ~ 声明方法
... |
// Copyright 2021 The OpenSDS 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 agre... |
package main
import "github.com/esbobkov/banners-rotation/internal/bandit"
func main() {
_ = bandit.New()
}
|
package props
import (
"log"
"github.com/spf13/viper"
)
var P viper.Viper
// MustRead reads properties and panics in case of error
func MustRead(filename string) {
P.SetConfigName(filename)
P.AddConfigPath(".")
err := P.ReadInConfig()
if err != nil {
log.Panic("Unable to read config")
}
}
|
//Copyright (c) 2017 Phil
package apollo
import (
"testing"
"github.com/stretchr/testify/suite"
)
type NotificationTestSuite struct {
suite.Suite
}
func (s *NotificationTestSuite) TestNotification() {
repo := new(notificationRepo)
repo.setNotificationID("namespace", 1)
id, ok := repo.getNotificationID("name... |
/*
Copyright 2022 The KubeVela 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 agreed to in writing, softw... |
package guard
import (
"net/http"
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/form"
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
)
type UpdateParam struct {
Panel table.Table
Prefix string
Value form.Values
}
func (g *Guard) Update(ct... |
package model
import (
"strconv"
"github.com/SDkie/metric_collector/db"
"github.com/SDkie/metric_collector/logger"
"github.com/garyburd/redigo/redis"
)
type MetricRedis struct {
MetricStruct
}
func InitRedis() {
db.InitRedis()
}
func (m *MetricRedis) Insert() error {
// distinct_name:YYYY:MM:DD
dailyBucket... |
package main
import (
"fmt"
)
// 78. 子集
// 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
// 说明:解集不能包含重复的子集。
// https://leetcode-cn.com/problems/subsets/
func main() {
fmt.Println(subsets([]int{1, 2, 3}))
fmt.Println(subsets2([]int{1, 2, 3}))
fmt.Println(subsets3([]int{1, 2, 3}))
}
// 法一:回溯,每个元素不断与它之后的元素组合,形成子集
func sub... |
package main
import (
"fmt"
"unsafe"
)
// 定义非空结构体
type S struct {
a uint16
b uint32
}
// 空结构体
var Exists = struct{}{}
// Set is the main interface
type Set struct {
// struct为结构体类型的变量
m map[interface{}]struct{}
}
func test1() {
var s S
fmt.Println(unsafe.Sizeof(s)) // prints 8, not 6
var s2 struct{}
fmt... |
package receivers
import (
"encoding/json"
"fmt"
cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger"
)
// SampleReceiver configuration: receiver type, listen address, port
type SampleReceiverConfig struct {
Type string `json:"type"`
Addr string `json:"address"`
Port string `json:"port"`
}
type ... |
package classic
import (
"testing"
)
func TestEqual(t *testing.T) {
tcs := []struct {
a, b []int
expect bool
}{
{
a: []int{1, 2, 3},
b: []int{1, 2, 3},
expect: true,
},
{
a: []int{1, 2, 3},
b: []int{1, 3, 3},
expect: false,
},
{
a: []int{1, 2, 3},
b:... |
package main
import (
"github.com/therecipe/qt/core"
"github.com/therecipe/qt/network"
)
//the custom QNetworkReply is partially modeled after
//https://code.qt.io/cgit/qt/qtbase.git/tree/src/network/access/qnetworkreplyfileimpl.cpp?h=5.7
//and
//https://blogs.kde.org/2010/08/28/implementing-reusable-cust... |
// Package crawler - пакет сканирует ресурсы с использование сканнера и возвращает структуры
// реализующие контракт document.Documenter
package crawler
import (
"regexp"
"sort"
"strings"
)
type Scanner interface {
Scan(url string, depth int) (map[string]string, error)
}
type Service struct {
Scanner Scanner
}
... |
package gosolar
import "fmt"
// RemoveNCMNodes deletes nodes from NCM handling in SolarWinds.
func (c *Client) RemoveNCMNodes(guids []string) error {
endpoint := "Invoke/Cirrus.Nodes/RemoveNodes"
req := [][]string{guids}
_, err := c.post(endpoint, req)
if err != nil {
return fmt.Errorf("failed to remove the N... |
package criteria
import (
"github.com/open-policy-agent/opa/ast"
"github.com/pomerium/pomerium/pkg/policy/parser"
)
type httpMethodCriterion struct {
g *Generator
}
func (httpMethodCriterion) DataType() CriterionDataType {
return CriterionDataTypeStringMatcher
}
func (httpMethodCriterion) Name() string {
retu... |
package database_Celica
import (
"database/sql"
)
type CelicaSql struct {
db *sql.DB
}
type RecordOpe struct {
keyName string
keyValue string
tableName string
Field string
NowData string
}
func NewRecordOpe(tableName string, keyName string, keyValue string) *RecordOpe {
tableName = "`" + tableName ... |
package main
//Simple always returns 1
func Simple() int {
return 1
}
|
// Copyright 2016 The G3N 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 gls implements a loader of OpenGL functions for the platform
// and a Go binding for selected OpenGL functions. The binding maintains
// some ... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
)
// Patch represents a sql script and associated Go functions to
// go from one schema version to another
type Patch struct {
Prefix string
From int
To int
Description string
SqlFilename string
PreFunct... |
package store
import (
"database/sql"
_ "github.com/mattn/go-sqlite3" // for database/sql driver
"log"
)
type Users struct {
User string
Pass string
About string
Pic string
}
// SqliteDB is a wrapper for the Sqlite3 database store
type SqliteDB struct{ *sql.DB }
// Init opens the database and sets up the... |
package golayout
import (
"bytes"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/gobuffalo/packr/v2"
log "github.com/sirupsen/logrus"
)
var (
projOverall ProjectOverall
tpl *template.Template
)
const (
AppNamePlaceholder = "appname"
)
type ProjectOverall struct {
ProjName string
Mod... |
package main
import "fmt"
func main() {
var a [3]int
a[1] = 10
fmt.Println(a[0])
fmt.Println(a[1])
fmt.Println(a[len(a)-1])
}
|
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2016 Intel Corporation
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.