text stringlengths 11 4.05M |
|---|
package server
type Storage interface {
NewRoutes()
StartAPI()
} |
package discover
import (
"encoding/json"
"io/ioutil"
"strings"
"github.com/k8guard/k8guard-discover/messaging"
"github.com/k8guard/k8guard-discover/metrics"
"github.com/k8guard/k8guard-discover/rules"
lib "github.com/k8guard/k8guardlibs"
"github.com/k8guard/k8guardlibs/messaging/types"
"github.com/k8guard/k... |
// Copyright (c) 2018 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wallet
import (
"os"
"testing"
"time"
"github.com/btcsuite/btcd/chaincfg"
_ "github.com/btcsuite/btcwallet/walletdb/bdb"
)
// TestCreateWatchingOnly checks th... |
package ehttp
import (
"github.com/enjoy-web/ehttp/swagger"
)
// Response of the api
// Fields
// Description -- Description of the response model
// Model -- The Response Model (nil, struct, or []string )
// Headers -- The Response info in the HTTP header
type Response struct {
Description string
Mode... |
package ctree
import (
"bytes"
"fmt"
"reflect"
"testing"
)
func TestSize(t *testing.T) {
r := &mys{"root"}
e := &mys{"="}
p := &mys{"+"}
o := &mys{"1"}
two := &mys{"2"}
tests := []struct {
name string
input Tree
expected int
}{
{"simple", BuildTree("", r).Add(e).Down().Add(p).Add(o).Add(two)... |
package gorasp
import (
"fmt"
)
func printAThing(v RankSelect) {
val := v.RankOfIndex(2)
fmt.Println(val)
}
func main() {
fmt.Println("Hello, rasp!")
val := NewRankSelectSimple([]int{0, 0, 1, 0, 1, 1, 0})
printAThing(val)
fmt.Println(val)
fmt.Println(val.RankOfIndex(1))
}
|
package main
import (
"fmt"
"github.com/bndr/gopencils"
)
type Repo struct {
*Project
Name string
Resource *gopencils.Resource
}
func (repo *Repo) GetPullRequest(id int64) PullRequest {
return PullRequest{
Repo: repo,
Id: id,
Resource: repo.Resource.Res("pull-requests").Id(fmt.Sprint(id)),... |
package main
import "sort"
func merge(intervals [][]int) [][]int {
if len(intervals) == 0 {
return [][]int{}
}
// 进行排序,让区间开端小的排在前面,如果相等,则让尾端小的排在前面
sort.Slice(intervals, func(i, j int) bool {
if intervals[i][0] == intervals[j][0] {
return intervals[i][1] < intervals[j][1]
}
return intervals[i][0] < inte... |
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/Zenika/marcel/version"
)
func init() {
Marcel.AddCommand(&cobra.Command{
Use: "version",
Short: "Displays version information",
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, _ []string) {
fmt.Printf("%s rev: %s\n", version.Version(... |
package client
import (
"encoding/json"
"errors"
"net/http"
"strings"
log "github.com/sirupsen/logrus"
)
const checkoutsSuffix = "/v1/checkouts"
//CreateCheckout creates a new checkout on Satispay Platform
func (client *Client) CreateCheckout(checkoutRequest *CheckoutRequest, idempotencyKey string) (checkout C... |
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
var Db *sql.DB
type User struct {
Id int `db:"id"`
Name sql.NullString `db:"name"`
}
func queryRowTest() {
sql := "select id, name from test_data where id=?"
row := Db.QueryRow(sql, 1)
var user User
err := row.Sca... |
package service
import (
"tesou.io/platform/brush-parent/brush-api/common/base"
"tesou.io/platform/brush-parent/brush-api/module/match/pojo"
"tesou.io/platform/brush-parent/brush-core/common/base/service/mysql"
)
type MatchHisService struct {
mysql.BaseService
}
func (this *MatchHisService) Exist(v *pojo.MatchH... |
package apiclient
import (
"context"
"google.golang.org/grpc"
workflowtemplatepkg "github.com/argoproj/argo/pkg/apiclient/workflowtemplate"
"github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
grpcutil "github.com/argoproj/argo/util/grpc"
)
type errorTranslatingWorkflowTemplateServiceClient struct {
delegate... |
package handlers
import (
"net/http"
"github.com/esrever001/toyserver/db"
"github.com/julienschmidt/httprouter"
)
type HttpMethod int
const (
GET HttpMethod = 1 + iota
POST
)
type BaseHandler interface {
Path() string
Method() HttpMethod
Handle(w http.ResponseWriter, r *http.Request, _ httprouter.Params)
}... |
package kvstore
import (
"path/filepath"
"github.com/Sirupsen/logrus"
"github.com/pkg/errors"
"github.com/rancher/longhorn-manager/types"
)
type Backend interface {
Set(key string, obj interface{}) error
Get(key string, obj interface{}) error
Delete(key string) error
Keys(prefix string) ([]string, error)
I... |
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
)
func rootHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
createTodoHandler(w, r)
case "GET":
getAllTodosHandler(w, r)
case "DELETE":
deleteAllTodosHandler()
default:
http.NotFoundH... |
package internal
import "github.com/m3hm3t/customerapi3/internal/model"
type RepositoryPort interface {
RetrieveByID(uint) (*model.Customer, error)
RetrieveByEmail(string) (*model.Customer, error)
RetrieveByUsername(string) (*model.Customer, error)
Create(*model.Customer) error
Update(*model.Customer) error
Del... |
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type books struct {
ID string `json:"id"`
ISBN string `json:"isbn"`
Title string `json:"title"`
Author string `json:"author"`
}
var Books = []books{
{ID: "1", ISBN: "978-0988262591", Title: "The Phoenix Project", Author: "Gene Kim, Kevin Be... |
package store
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/odpf/optimus/models"
)
var (
ErrResourceNotFound = errors.New("resource not found")
)
// ProjectJobSpecRepository represents a storage interface for Job specifications at a project level
type ProjectJobSpecRepository interf... |
package virtual_security
import (
"sort"
"sync"
)
var (
marginPositionStoreSingleton iMarginPositionStore
marginPositionStoreSingletonMutex sync.Mutex
)
func getMarginPositionStore() iMarginPositionStore {
marginPositionStoreSingletonMutex.Lock()
defer marginPositionStoreSingletonMutex.Unlock()
if margi... |
package main
import (
"bytes"
"time"
"fmt"
"strings"
)
//字符串连接的3中方式
func main() {
//1 最快
var buffer bytes.Buffer
s := time.Now()
for i := 0; i < 10000; i++ {
buffer.WriteString("test is here\n")
}
buffer.String()
e := time.Now()
fmt.Println("1 time is ", e.Sub(s).Seconds())
//2
s = time.Now(... |
package bot
import (
"encoding/binary"
"io"
"log"
"os"
)
func openFile(path string) ([][]byte, error) {
buffer := make([][]byte, 0)
file, err := os.Open(path)
if err != nil {
return buffer, err
}
var opuslen int16
for {
// Read opus frame length from dca file.
err = binary.Read(file, binary.LittleEndi... |
package main
import (
"log"
"net/http"
"time"
"github.com/gin-contrib/timeout"
"github.com/gin-gonic/gin"
)
func testResponse(c *gin.Context) {
c.String(http.StatusRequestTimeout, "timeout")
}
func timeoutMiddleware() gin.HandlerFunc {
return timeout.New(
timeout.WithTimeout(500*time.Millisecond),
timeou... |
package main
import (
"fmt"
"sync"
"time"
)
func Start() <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 0; i < 10; i++ {
out <- i
}
}()
return out
}
func Worker(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := range in {
out <... |
package main
import (
"fmt"
tensorflow "github.com/tensorflow/tensorflow/tensorflow/go"
tf "github.com/tensorflow/tensorflow/tensorflow/go"
)
func makeTensor(data [][]float32) (*tf.Tensor, error) {
return tf.NewTensor(data)
}
func getResult(prediction [][]float32) bool {
if prediction[0][0] > prediction[0][1] ... |
package calendar
import (
"encoding/json"
"github.com/pkg/errors"
"github.com/andywow/golang-lessons/lesson-calendar/pkg/eventapi"
)
// CheckEventData check event data
func CheckEventData(e *eventapi.Event) error {
if e.StartTime == nil || e.Duration <= 0 || e.Header == "" || e.Description == "" || e.Username =... |
package main
import (
"crypto/md5"
"fmt"
"log"
)
//easyjson:json
type S struct {
I int
StringToFilter OrderedMapStringToFilter
}
//easyjson:json
type Filter struct {
Name string
Value int
StringToInt OrderedMapStringToInt
}
func main() {
s := S{
I: 1,
StringToFilter: OrderedMa... |
package routers
import (
"qixijie/controllers"
"github.com/astaxie/beego"
)
func init() {
//正式路由器
//登陆
beego.Router("/seven_night/redirecturl", &controllers.MainController{}, "*:Redirecturl")
beego.Router("/seven_night/index", &controllers.MainController{}, "*:Index")
//分享接口
beego.Router("/seven_night/upimag... |
package redcode
import (
"errors"
"regexp"
"strings"
)
//go:generate ragel -Z -G2 -o lex.go redcode.rl
//go:generate goyacc redcode.y
// Directives map Redcode directive names to values
//
// e.g. ";name Imp"
type Directives map[string]string
var scanDirective *regexp.Regexp
func init() {
var err error
scanDi... |
/*
Given an infix expression, determine whether all constants are of the same type.
Operators will consist only of these dyadic operators: +-/*
Your program or function should take a valid expression string as input, and output a truthy value if the constants in the expression are of the same time, and a falsey valu... |
package stringconcat_test
import (
"testing"
"github.com/nandarimansyah/gobasicbenchmark/stringconcat"
)
const (
TEST_STRING = "test"
TEST_SIZE = 2
)
func benchmarkConcat(size int, SelfConcat func(string, int) string, b *testing.B) {
for n := 0; n < b.N; n++ {
SelfConcat(TEST_STRING, size)
}
}
func Bench... |
// Copyright 2020 Thomas.Hoehenleitner [at] seerose.net
// Use of this source code is governed by a license that can be found in the LICENSE file.
package id_test
import "testing"
func TestUpdateZeroId(t *testing.T) {
sOri := []string{`
TRICE0 (Id(0), "---------------------------------------\n" );
TRICE0 (Id(0),... |
// +build it
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"testing"
"github.com/TempleEight/spec-golang/auth/comm"
"github.com/TempleEight/spec-golang/auth/dao"
"github.com/TempleEight/spec-golang/auth/util"
"github.com/dgrijalva/jwt-go"
"github.com/google/uuid"
)
var environment env
func ... |
package clouddatastore
import (
"cloud.google.com/go/datastore"
w "go.mercari.io/datastore"
)
func toOriginalKey(key w.Key) *datastore.Key {
if key == nil {
return nil
}
return &datastore.Key{
Kind: key.Kind(),
ID: key.ID(),
Name: key.Name(),
Parent: toOriginalKey(key.ParentKey()),... |
package Problem0140
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// tcs is testcase slice
var tcs = []struct {
s string
wordDict []string
ans []string
}{
{
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... |
package main
import (
"fmt"
"io"
"os"
"github.com/urfave/cli"
"github.com/polydawn/refmt/cbor"
"github.com/polydawn/refmt/json"
"github.com/polydawn/refmt/pretty"
"github.com/polydawn/refmt/shared"
)
func main() {
os.Exit(Main(os.Args, os.Stdin, os.Stdout, os.Stderr))
}
func Main(args []string, stdin io.R... |
package client
import (
"errors"
"fmt"
"strings"
"github.com/wish/ctl/pkg/client/types"
)
// Helpers for finding a specific pod
func (c *Client) findPod(contexts []string, namespace, name string, options ListOptions) (*types.PodDiscovery, error) {
list, err := c.ListPodsOverContexts(contexts, namespace, options... |
package main
import (
"fmt"
"os/exec"
"github.com/mattn/go-tty"
)
func runTinyGo(dockerImage, currentDir, targetPath string, args []string, verbose, cmdMode bool) error {
cmd := exec.Command(
`docker`, `run`, `-it`, `--rm`,
`-v`, fmt.Sprintf(`%s:/go/%s`, currentDir, targetPath),
`-w`, fmt.Sprintf(`/go/%s`,... |
package p2pNetwork
import (
"errors"
"fmt"
"github.com/HNB-ECO/HNB-Blockchain/HNB/config"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/common"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/bean"
"github.com/HNB-ECO/HNB-Blockchain/HNB/p2pNetwork/message/reqMsg"
"github.com/HNB-ECO/HNB-Blockchain... |
package data
type IpInfo struct {
Ip string `json:"ip"`
}
type WeatherInfo struct {
Temp float32 `json:"temp"`
Pressure float32 `json:"pressure"`
Day bool `json:"day"`
Humidity float32 `json:"humid"`
Lux float32 `json:"lux"`
LastPressure float32 `json:"lastPressure"`
Date ... |
package main_test
import (
. "thesaurus_similarity"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Document", func() {
It("should return random elements that do no repeat", func() {
doc := []Pair{
Pair{
Word: "firstWord",
WordDescription: WordDescription{},
... |
package database
type TbEdRX2 struct {
ID uint
EdID uint
DCC int `gorm:"column:dCC"`
DFC int `gorm:"column:dFC"`
SF int `gorm:"column:SF"`
}
func (TbEdRX2) TableName() string {
return "tb_ed_rx2"
}
|
package carfinder
import (
"github.com/iLLeniumStudios/FiveMCarsMerger/pkg/flags"
sliceutils "github.com/iLLeniumStudios/FiveMCarsMerger/pkg/utils/slice"
log "github.com/sirupsen/logrus"
"io/ioutil"
"os"
"regexp"
"strings"
)
type CarFinder interface {
FindValidCars(dataFileCars []string, streamFileCars []stri... |
package main
import (
"github.com/micro/go-micro"
"log"
"moriaty.com/cia/cia-publisher/service"
)
/**
* @author 16计算机 Moriaty
* @version 1.0
* @copyright :Moriaty 版权所有 © 2020
* @date 2020/4/19 18:40
* @Description TODO
* CIA-Publisher
*/
/**
1、拉取 apk
1. 获取拉取配置
2. 根据配置拉取 apk
2、整合 zip
1. 根据配置将 apk 整合成 z... |
package validator
import (
"fmt"
"strconv"
"strings"
)
//ValidateCpf from https://github.com/miguelpragier/handy/blob/master/handybra.go
func ValidateCpf(cpf string) bool {
// Se o comprimento da string estiver diferente de 11, falhar
if len(cpf) != 11 {
return false
}
// Testa seqüências de 11 dígitos igua... |
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License ... |
package server
import (
"bufio"
"os"
"server/libs/log"
"server/libs/rpc"
"text/template"
)
var (
remotes = make(map[string]interface{})
handlers = make(map[string]interface{})
)
func GetRemote(name string) interface{} {
if k, ok := remotes[name]; ok {
return k
}
return nil
}
func GetHandler(name strin... |
package hutoma
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const HUTOMA_BASE_URL = "https://api.hutoma.ai"
type HutomaClient struct {
BotID string
DevKey string
ClientKey string
ChatID string
}
func (c *HutomaClient) Chat(query string) (hutomaChatResponse, error) {... |
/* Use the “defer” keyword to show that a deferred func runs after the func containing it exits. */
package main
import "fmt"
func createDbConnection() {
fmt.Println("Openning db connection ...")
}
func closeDbConnection() {
fmt.Println("DB Connection closed!!!")
}
func saveData() {
fmt.Println("Writing some da... |
package elements
import (
"fmt"
"strings"
"github.com/Nv7-Github/Nv7Haven/eod/base"
"github.com/Nv7-Github/Nv7Haven/eod/types"
"github.com/Nv7-Github/Nv7Haven/eod/util"
)
var invalidNames = []string{
"+",
"@everyone",
"@here",
"<@",
"İ",
"\n",
}
var charReplace = map[rune]rune{
'’': '\'',
'‘': '\'',
'... |
package main
import (
"flag"
"fmt"
"github.com/jccroft1/KeychronChecker/keychron"
"github.com/jccroft1/KeychronChecker/telegram"
)
var (
token = flag.String("token", "", "the bot token")
channel = flag.String("channel", "", "the target channel for the stock alert")
)
func main() {
flag.Parse()
telegram.T... |
package main
import (
"fmt"
)
func plusTwo() func(int) int {
f := func(x int) int {
return x + 2
}
return f
}
func plusX(x int) func(int) int {
f := func(y int) int {
return x + y
}
return f
}
func main() {
p := plusTwo()
fmt.Printf("%v\n", p(2))
q := plusX(2)
fmt.Printf("%v\n", q(7))... |
/*
Copyright 2021 CodeNotary, 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 or agreed to i... |
package binance_websocket
import (
. "exchange_websocket/common"
"strings"
)
// Binance symbols
type BinanceSymbol struct {
BinanceUsdtSymbol []string
BinanceBtcSymbol []string
BinanceEthSymbol []string
BinanceSymbols []string
}
func NewBinanceSymbol() *BinanceSymbol {
ba := new(BinanceSymbol)
return ba... |
package collectors
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
cclog "github.com/ClusterCockpit/cc-metric-collector/pkg/ccLogger"
lp "github.com/ClusterCockpit/cc-metric-collector/pkg/ccMetric"
)
const MEMSTATFILE = "/proc/meminfo"
const NUMA_M... |
package rtrserver
import (
"bytes"
"encoding/binary"
"errors"
"github.com/cpusoft/goutil/belogs"
"github.com/cpusoft/goutil/jsonutil"
)
func ParseToCacheResponse(buf *bytes.Reader, protocolVersion uint8) (rtrPduModel RtrPduModel, err error) {
var sessionId uint16
var length uint32
// get sessionId
err = bi... |
package glog
import (
"log"
"github.com/dalixu/glogger"
)
//GLoggerFactory 实现gloggerFactory
type GLoggerFactory struct {
manager Manager
}
//GetLogger implement GLogger
func (gf *GLoggerFactory) GetLogger(name string) glogger.GLogger {
return gf.manager.GetLogger(name)
}
//NewGLoggerFactory 返回1个glogger.Factory... |
package main
import "fmt"
func search(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
rotateIndex := findRotateIndex(nums, 0, len(nums)-1)
fmt.Println(rotateIndex)
if rotateIndex == 0 {
return binarySearch(nums, 0, len(nums)-1, target)
}
if nums[rotateIndex] == target {
return rotateIndex
... |
// Copyright 2020 PingCAP, Inc. Licensed under Apache-2.0.
package backup
import (
"github.com/prometheus/client_golang/prometheus"
)
var (
backupRegionCounters = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "br",
Subsystem: "raw",
Name: "backup_region",
Help: "Backup region... |
package utils
import (
"encoding/json"
"strconv"
"time"
)
func StringToInt(e string) (int, error) {
return strconv.Atoi(e)
}
func GetCurrentTimeStr() string {
return time.Now().Format("2006-01-02 15:04:05")
}
// 时间戳转时间
func UnixToTime(e string) (datatime time.Time, err error) {
data, err := strconv.ParseInt(e... |
package straw
import (
"fmt"
"os"
"sort"
)
var _ StreamStore = &OsStreamStore{}
type OsStreamStore struct {
}
func (_ *OsStreamStore) Lstat(filename string) (os.FileInfo, error) {
return os.Lstat(filename)
}
func (_ *OsStreamStore) Stat(filename string) (os.FileInfo, error) {
return os.Stat(filename)
}
func ... |
package loghelper
import (
"os"
log "github.com/sirupsen/logrus"
)
var logFields = log.Fields{"Client": "Publisher"}
// Init - to make one time initial setup for logrus
func Init() {
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(log.InfoLevel)
}
// LogInfo logs a message at leve... |
package noise
import (
"crypto/rand"
"testing"
"github.com/katzenpost/noise"
"github.com/stretchr/testify/require"
)
func TestNoiseXX(t *testing.T) {
clientStaticKeypair, err := noise.DH25519.GenerateKeypair(rand.Reader)
require.NoError(t, err)
serverStaticKeypair, err := noise.DH25519.GenerateKeypair(rand.... |
package gbinterface
type IRequest interface {
GetConnection() IConnection
GetData() []byte
GetMessageID() uint32
GetMessageLen() uint32
}
|
package config
import (
"log"
"github.com/jinzhu/gorm"
"github.com/spf13/viper"
)
type Config struct {
Version string
Port int
DebugMode bool
LogFilePath string
DBConnection *gorm.DB
}
func Load(environment string) *Config {
cfg := new(Config)
var configFile *viper.Viper = viper.New()
c... |
package main
//we need main package and fmt or format import to print anything basically.
//GO isn't object oriented , does not have classes and shit, so like make functions.
import "fmt"
func main() {
fmt.Println("Hello, go")
}
|
package common
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
)
type Config struct {
// Log config
Logdir string
Loglevel string
Logname string
// RabbitMQ config
Rabbithost string
Rabbitport int
Rabbituser string
Rabbitpw string
// queue information
Udrqueue string
Reqreciever string
// redi... |
package core
import (
"net/http"
"github.com/gin-gonic/gin"
peer "github.com/libp2p/go-libp2p-core/peer"
)
// ping godoc
// @Summary Ping a network peer
// @Description Pings another peer on the network, returning online|offline.
// @Tags utils
// @Produce text/plain
// @Param X-Textile-Args header string true "p... |
// tgbot-go -
// https://github.com/modern-dev/tgbot-go
// Copyright (c) 2020 Bohdan Shtepan
// Licensed under the MIT license.
package tgbot
type InputFile struct {
FileId string
FileURL string
FilePath string
}
func InputFileFromURL(url string) InputFile {
return InputFile{FileURL:url}
}
func InputFileFromDis... |
package osbuild2
type MkfsFATStageOptions struct {
VolID string `json:"volid"`
Label string `json:"label,omitempty"`
FATSize *int `json:"fat-size,omitempty"`
}
func (MkfsFATStageOptions) isStageOptions() {}
type MkfsFATStageDevices struct {
Device Device `json:"device"`
}
func (MkfsFATStageDevices) isStag... |
package shamir_test
import (
"fmt"
"reflect"
"github.com/renproject/surge/surgeutil"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/renproject/shamir"
)
var _ = Describe("Surge marshalling", func() {
trials := 100
types := []reflect.Type{
reflect.TypeOf(Share{}),
reflect.TypeOf(Shar... |
package server
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"path/filepath"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/filemonitor"
"github.com/operator-framework/operator-lifecycle-manager/pkg/lib/profile"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirup... |
package http
const (
// Info Logger信息
Info = iota
// Error 错误信息
Error
// Warn 警告信息
Warn
)
// SendLog 日志处理
func (server *Server) SendLog(status int, format string, a ...interface{}) {
if !server.Logger {
return
}
switch status {
case Info:
server.logger.Printf("[I] "+format, a...)
break
case Error:
... |
package day04
import (
"fmt"
"reflect"
)
func CallMethod() {
man := Man{"male", Human{"杨一帆", 22}}
rValue := reflect.ValueOf(man)
rType := reflect.TypeOf(man)
for i := 0; i < rType.NumMethod(); i++ {
m := rType.Method(i)
fmt.Printf("%s\t %v\n", m.Name, m.Type)
}
rValue.Method(0).Call([]reflect.Value{reflec... |
package db
import (
"context"
"fmt"
"github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/errors"
"github.com/yandex-cloud/examples/serverless/alice-shareable-todolist/app/log"
"github.com/yandex-cloud/ydb-go-sdk/table"
"go.uber.org/zap"
)
type TxManager interface {
InTx(ctx context.Contex... |
package gocacher
import (
"bytes"
"crypto/md5"
"encoding/gob"
"encoding/hex"
"errors"
"time"
)
type cacher interface {
Init(config map[string]interface{}) cacher
Clone(config map[string]interface{}) cacher
Set(key string, value interface{}) error
SetExpire(key string, value interface{}, exp time.Duration) e... |
package dao
import (
log "github.com/sirupsen/logrus"
"zhiyuan/scaffold/internal/model"
"zhiyuan/zyutil_v1.5"
)
func (d *Dao) AddCamera(data model.Camera)(Camera_obj model.Camera,err error){
if err := d.crmdb.Create(&data);err.Error!=nil{
log.WithFields(log.Fields{
"Camera": "insert",
}).Error("camera ins... |
package main
import (
"fmt"
"github.com/astaxie/beego/toolbox"
_ "tokensky_bg_admin/manage_tick/sysinit"
"tokensky_bg_admin/manage_tick/tick"
)
//定时任务
/*
符号 含义 示例
* 表示任何时刻
, 表示分割 如第三段里:2,4,表示 2 点和 4 点执行
- 表示一个段 如第三端里: 1-5,就表示 1 到 5 点
/n 表示每个n的单位执行一次 如第三段里,1, 就表示每隔 1 个小时执行一次命令。也可以写成1-23/1
示例 详细含义
0/... |
package webdav
import (
"encoding/xml"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/julienschmidt/httprouter"
"github.com/sanato/sanato-lib/storage"
"net/http"
"time"
)
func (api *API) propfind(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
authRes, err := api.basicAuth(r)
if err != nil {
... |
package gosqrl
import (
"bytes"
"encoding/base64"
)
var (
twoEqBytes = []byte("==")
)
// B64TruncatedEncode base64 URL encodes a string, and removes the trailing '='
// bytes.
func B64TruncatedEncode(data []byte) []byte {
b64 := make([]byte, base64.URLEncoding.EncodedLen(len(data)))
base64.URLEncoding.Encode(b6... |
package main
import (
"github.com/funkygao/gobench/util"
"testing"
)
func main() {
b := testing.Benchmark(benchmarkRecover)
util.ShowBenchResult("recover", b)
}
func benchmarkRecover(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
recover()
}
}
|
package nsp
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"sync"
"time"
"github.com/golang/protobuf/ptypes/empty"
nspAPI "github.com/nordix/meridio/api/nsp"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
type NetworkServicePlateformService struct {
Listener net.Listener
Server ... |
package cmd
import (
"fmt"
"strings"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func newXFlagsCmd() (cmd *cobra.Command) {
cmd = &cobra.Command{
Use: "xflags",
Short: cmdXFlagsShort,
Long: cmdXFlagsLong,
Example: cmdXFlagsExample,
Args: cobra.NoArgs,
Run: cmdXFlagsRu... |
package bridge
import (
"bytes"
"github.com/sujit-baniya/smpp/pdu"
"github.com/sujit-baniya/smpp/sms"
)
func ToDeliverSM(deliver *sms.Deliver) (sm *pdu.DeliverSM, err error) {
var message pdu.ShortMessage
if deliver.Flags.UDHIndicator {
message.UDHeader = pdu.UserDataHeader{}
}
_, err = message.ReadFrom(byte... |
package graphql
import (
"context"
"errors"
"github.com/nomkhonwaan/myblog/pkg/auth"
"github.com/samsarahq/thunder/graphql"
"net/http"
)
// AuthorizedID is a context.Context key where an authorized ID value stored
const AuthorizedID = "authID"
var (
protectedResources = map[string]bool{
"myPosts": ... |
package utils
import (
"app-auth/db"
"context"
"fmt"
"log"
"github.com/mongodb/mongo-go-driver/bson"
)
var AndEmptyString = ""
var AndTrue = true
var AndFalse = false
//when you have a slice of string
// you want to remove a specific value from an index
func RemoveIndex(s []string, index int) []string {
retur... |
package middlewares
import (
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
func SetLogger(e *echo.Echo) {
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: `[${time_rfc3339}][remote_ip:${remote_ip}][status: ${status}][method: ${method}][url: ${host}${path}]` + "\n",
}))
}
|
package shamir
import (
"math/rand"
"reflect"
"github.com/renproject/secp256k1"
"github.com/renproject/surge"
)
// VShareSize is the size of a verifiable share in bytes.
const VShareSize = ShareSize + secp256k1.FnSizeMarshalled
// VerifiableShares is a alias for a slice of VerifiableShare(s).
type VerifiableSha... |
package controllers
import "lenslocked.com/views"
// NewStatic creates a struct with the static pages
func NewStatic() *Static {
return &Static{
HomeView: views.NewFiles("bootstrap", "static/home"),
ContactView: views.NewFiles("bootstrap", "static/contact"),
FAQView: views.NewFiles("bootstrap", "stat... |
package api
import (
"net/http"
"reflect"
"strings"
"github.com/labstack/echo"
)
func OKRequest(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{
"stat": "OK",
})
}
func OKRequestWith(c echo.Context, o interface{}) error {
m := map[string]interface{}{
"stat": "OK",
}
on := reflect... |
package main
import (
"fmt"
"strings"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/yanyiwu/gojieba"
)
var db *gorm.DB
func 到資料庫撈全部資料() (
店家資料 []StoreModel, err error,
) {
店家資料 = []StoreModel{}
// 開始找資料庫
err = db.New().Find(&店家資料).Error
if err != nil {
return
}
return
}
fu... |
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package main
import (
"log"
"os"
"text/template"
)
var tpl *template.Template
type sages struct {
Name string
Motto string
}
type car struct {
Manufacturer string
Model string
Doors int
}
// type items struct {
// Wisdom []sages
// Transport []car
// }
func init() {
tpl = template.Mus... |
package main
import (
"strings"
)
func (g *Guild) CalcElemStats(elem string) {
elem = strings.ToLower(elem)
_, exists := g.Finished[elem]
if exists {
return
}
el, exists := g.Elements[elem]
if !exists {
g.Finished[elem] = empty{}
return
}
if len(el.Parents) == 0 {
g.Finished[elem] = empty{}
retu... |
package main
import (
"fmt"
)
func main() {
c := make(chan int, 2)
c <- 55
c <- 66
fmt.Println(<-c)
fmt.Println(<-c)
fmt.Printf("%T\t", c)
}
|
package windows
type tagPOINT struct {
X int32
Y int32
}
type tagMSG struct {
Hwnd HWND
Message UINT
WParam WPARAM
LParam LPARAM
Time DWORD
Pt POINT
LPrivate DWORD
}
type tagCWPSTRUCT struct {
LParam LPARAM
WParam WPARAM
Message UINT
Hwnd HWND
}
type tagK... |
package tsing
import (
"errors"
"net/http"
"path/filepath"
"runtime"
"strconv"
"strings"
)
// 事件
type Event struct {
Status int // HTTP状态码
Message error // 消息(error)
Source *_Source // 来源
Trace []string // 跟踪
ResponseWriter http.ResponseWriter
Request *http.R... |
package util
const (
SUCCESS_CODE = "00"
SUCCESS_MESSAGE = "success"
SERVER_ERROR_CODE = "-91"
)
|
package main
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"time"
)
func main() {
fmt.Println(Sha2256Days())
}
func Sha2256(data []byte) [32]byte {
return sha256.Sum256(data)
}
func Sha2256Days() string {
temp := Sha2256([]byte(TodayString(3)))
//fmt.Printf("%x\n", temp)
return Base64E(temp[:])
}
func ... |
package registry
// Blob describes a
type Blob struct {
// MediaType describe the type of the content. All text based formats are
// encoded as utf-8.
MediaType string
// Size in bytes of content.
Size int64
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.