text stringlengths 11 4.05M |
|---|
package main
import "fmt"
func main() {
//iota 一般应用在枚举中
//iota自增
//在自增出现常量,后面的值会和常量相等
const (
one,two=iota+1,iota+2
three,four
fie,six
)
fmt.Println(one,two,three,four,fie,six)
}
|
package main
import "testing"
func TestSet(t *testing.T) {
env := make(Env)
key, value := "TEST", "VALUE"
env.Set(key, value)
actualValue, ok := env[key]
if !ok {
t.Fatalf("expected to have %s in env", key)
}
if value != actualValue {
t.Fatalf("expected the value to be %s, but got %s", value, actualValue)... |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
/*
println("hello,world")
fmt.Println("hello,world")
n := 100 + 200
m := n + 100
msg := "hoge" + "fuga"
//if
if n == 300 {
fmt.Println(n)
} else if n == 100 {
fmt.Print(m)
} else {
fmt.Println(msg)
}
//sw... |
package leetcode
import (
"reflect"
"testing"
)
func TestFloodFill(t *testing.T) {
if !reflect.DeepEqual(floodFill([][]int{
[]int{1, 1, 1},
[]int{1, 1, 0},
[]int{1, 0, 1},
}, 1, 1, 2), [][]int{
[]int{2, 2, 2},
[]int{2, 2, 0},
[]int{2, 0, 1},
}) {
t.Fatal()
}
}
|
package bslib
import (
"errors"
"testing"
)
const cTestItemName01 = "hjb cwec78hduycbwj dbwne w"
const cTestItemIcon01 = "fas fa-ambulance"
const cTestItemName02 = "98jmwhj2ndycwbcjdwlmdk"
const cTestItemIcon02 = "fab fa-linkedin"
func testHelperCreateItem() (itemId int64, err error) {
bsInstance := GetInstance(... |
package sqlbatch
import (
"database/sql"
"github.com/lib/pq"
"time"
"unsafe"
)
//--------------------------------------------------------------------------
func makeNullBoolPtrGetter(offset uintptr) func(structPtr unsafe.Pointer, ifacePtr *interface{}) {
return func(structPtr unsafe.Pointer, ifacePtr *interface... |
package symmetric
import (
"encoding/base64"
"fmt"
"testing"
)
func TestAesCrypt_Encrypt(t *testing.T) {
key := "kLieko0EWllskjeWkLieko0EWllskjeW"
value := "hello world"
aesCipher := AesCrypt{
Encrypter: Encrypter{
Format: "base64",
DecodeFunc: base64.StdEncoding.DecodeString,
EncodeFunc: base64.... |
package main
import (
"alro/config"
"alro/server"
"fmt"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"google.golang.org/grpc"
"net"
"os"
)
var log *logrus.Logger
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
log = logrus.StandardLogger()
alro := config.Alro
g, err := server.NewGRPCSe... |
package db
import (
mydb"FILE_STORE/db/mysql"
"database/sql"
"fmt"
)
// 存储文件到数据库中
func OnFileUploadedFinished(filehash string, filename string, filesize int64, fileaddr string ) bool {
stmt, err := mydb.DBConn().Prepare("insert ignore into tbl_file (`file_sha1`, `file_name`, `file_size`, `file_addr`, `status`) v... |
// This file is subject to a 1-clause BSD license.
// Its contents can be found in the enclosed LICENSE file.
package evdev
// Synchronization event values are undefined.
// Their usage is defined only by when they are
// sent in the evdev event stream.
//
// SynReport is used to synchronize and separate
// events in... |
package shipping_details_test
import (
shippingDetails "Pinjem/businesses/shipping_details"
"Pinjem/businesses/shipping_details/mocks"
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
var shippingDetailRepository mocks.DomainRepository
var shippingDetailSer... |
/*
Copyright 2017 The Kubernetes 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, ... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//89. Gray Code
//The gray code is a binary numeral system where two successive values differ in only one bit.
//Given a non-negative integer n represe... |
package bmredis
import (
"github.com/alfredyang1986/blackmirror/bmerror"
"github.com/go-redis/redis"
"os"
"strconv"
"sync"
)
var onceConfig sync.Once
var redisClient *redis.Client
func GetRedisClient() *redis.Client {
onceConfig.Do(func() {
host := os.Getenv("BM_REDIS_HOST")
port := os.Getenv("BM_REDIS_PO... |
package main
import "fmt"
import "strings"
import "sort"
import "reflect"
func _Sort(str string) []string {
str = strings.Trim(str, " ")
str = strings.Replace(str, " ", "", -1)
strs := strings.Split(str, "")
sort.Strings(strs)
return strs
}
func IsAnagram(str1 string, str2 string) bool {
strs1 := _Sort(str... |
package storage
import (
"io"
"time"
)
type StorageEntry struct {
Title string
Path string
IsDir bool
Updated time.Time
MimeType string
}
type Storage interface {
List(path string) ([]StorageEntry, error)
IsDownloadable(path string) (bool, error)
Download(w io.Writer, path string) error
}
|
package ticker
import (
"testing"
"time"
. "github.com/smartystreets/goconvey/convey"
"strconv"
)
func TestTicker(t *testing.T) {
ticker := NewManager()
Convey("TestTickerManager", t, func() {
var result int
key := "test1"
Convey("AddTicker", func() {
// 测试没有ticker 去判断是否存在
So(ticker.HasTicker(key), ... |
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"tptsreporter/grafana"
"tptsreporter/report"
"github.com/form3tech-oss/jwt-go"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/pborm... |
package gotten
import (
"github.com/Hexilee/gotten/headers"
"github.com/stretchr/testify/assert"
"net/http"
"testing"
)
var (
TestResponse = &http.Response{
StatusCode: http.StatusOK,
Header: map[string][]string{
headers.HeaderContentType: {"text/html"},
},
}
)
func TestCheckerFactory_Create(t *testin... |
package rpc_http_service
func init() {
go saveToDbLoggs_go()
}
|
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
)
func main() {
// new instance of NewMyType
m := NewMyType()
fmt.Fprintf(&m, "Hello from %s", "MyNewType")
// write examples
writeWithWrite()
writeWithFmt()
// read examples
readWithRead()
readWithBufioReader(m)
readAllBytes(m)
//... |
package cmd
import (
"reflect"
"testing"
)
func TestMakeParseLabels(t *testing.T) {
successCases := []struct {
name string
labels string
expected map[string]string
}{
{
name: "test1",
labels: "foo=false",
expected: map[string]string{
"foo": "false",
},
},
{
name: "test2",
... |
// Copyright 2021 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
//
// 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... |
package main
import (
"encoding/json"
"os"
)
// Config for client
type Config struct {
LocalAddr string `json:"localaddr"`
RemoteAddr string `json:"remoteaddr"`
Key string `json:"key"`
Crypt string `json:"crypt"`
Mode string `json:"mode"`
Conn int `json:"conn"`
AutoExp... |
package sese
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document03500106 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:sese.035.001.06 Document"`
Message *SecuritiesFinancingConfirmationV06 `xml:"SctiesFincgConf"`
}
func (d ... |
package main
//slice使用
//初始化后len==cap
//slice 在len<=cap时,增加数据slice后,len与cap的关系是,在小于1024时 cap按照2倍的形式增长,大于2014按照1/4形式增长
func main() {
}
|
// This file was generated by counterfeiter
package modelsfakes
import (
"gcp-service-broker/brokerapi/brokers/models"
"sync"
)
type FakeServiceBrokerHelper struct {
ProvisionStub func(instanceId string, details models.ProvisionDetails, plan models.PlanDetails) (models.ServiceInstanceDetails, error)
provis... |
package main
import (
"fmt"
"flag"
"strings"
"github.com/zettazete/sms"
)
func main() {
var number string
var message string
flag.Parse()
if flag.NArg() < 2 {
fmt.Println("Usage: gotext {number} {message}")
return
}
number = flag.Arg(0)
message = strings.Join(flag.Args()[1:], " ")
resp, err := sms.Tex... |
package main
import (
"fmt"
"github.com/bearname/videohost/cmd/videoserver/config"
"github.com/bearname/videohost/internal/common/infrarstructure/mysql"
"github.com/bearname/videohost/internal/common/infrarstructure/server"
"github.com/bearname/videohost/internal/videoserver/infrastructure/transport/router"
_ "g... |
/*
* Copyright (c) 2020 - present Kurtosis Technologies LLC.
* All Rights Reserved.
*/
package fixed_size_example_network
import (
"fmt"
"github.com/gmarchetti/elasticsearch-indexer-testing-v1/elasticsearch_indexer/services"
"github.com/kurtosis-tech/kurtosis-go/lib/networks"
"github.com/kurtosis-tech/kurtosis... |
package c35_mitm_diffie_hellman
import (
"bytes"
"testing"
)
func TestEchoStream(t *testing.T) {
uA := NewUser("A")
uB := NewUser("B")
msg := []byte("secret text")
EchoStream(uA, uB, msg)
if !bytes.Equal(uB.lastReceivedMessage, msg) || !bytes.Equal(uA.lastReceivedMessage, uB.lastReceivedMessage) {
t.Errorf("... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package kubernetes
import v1 "k8s.io/api/core/v1"
// IsNodeReady returns true if the NodeReady condition of node is set to true.
//
// Copy of https://github.com/kubernetes/kubernetes/blob/886e04f1fffbb04faf8a9f9ee141143b... |
// Package auth contains authentication for the MQTT Server
package auth
// Interface for authentication
type Interface interface {
Username() string
CanConnect() bool
CanPublishTo(topic string) bool
CanSubscribeTo(topic string) bool
}
// Plugin for authentication
type Plugin func(clientIdentifier string, usernam... |
package api_test
import (
"errors"
"net/http"
"net/http/httptest"
"encoding/json"
"github.com/gorilla/mux"
. "github.com/hirondelle-app/api/api"
. "github.com/hirondelle-app/api/common/test"
"github.com/hirondelle-app/api/tweets"
. "github.com/hirondelle-app/api/tweets/test"
. "github.com/onsi/ginkgo"
. "g... |
package authorization
import (
"testing"
"github.com/danielsomerfield/authful/server/handlers"
"fmt"
"net/url"
"github.com/danielsomerfield/authful/server/service/oauth"
"github.com/danielsomerfield/authful/common/util"
util2 "github.com/danielsomerfield/authful/common/util"
oauth2 "github.com/danielsomerfield... |
package midtrans
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
type HttpClient interface {
Call(method string, url string, apiKey *string, options *ConfigOptions, body io.Reader, result interface{}) *Error
}
// HttpClientImplementation : this is for midtrans HttpCli... |
package util
import (
"fmt"
"os"
"time"
"gopkg.in/yaml.v2"
)
// Config contain direktiv configuration.
type Config struct {
FunctionsService string `yaml:"functions-service"`
// FunctionsTimeout : Action timeout in milliseconds
FunctionsTimeout int64 `yaml:"functions-timeout"`
FlowService string `yaml:"flo... |
package main
import (
"GoFileWatcher/cli"
"fmt"
FolderWatcher "github.com/mikerapa/FolderWatcher"
"log"
"os"
"sync"
)
func main() {
wg := sync.WaitGroup{}
commandLineSettings, err := cli.GetCommandLineSettings(os.Args[1:])
if err != nil {
log.Fatal(err)
return
}
watcher := FolderWatcher.New()
paused ... |
//Package main calls examples of firstclass functions tutorial
package main
import (
"firstclassfunc/mapfunc"
"firstclassfunc/students"
"firstclassfunc/usertypefunc"
"firstclassfunc/anonfunc"
)
func main() {
anonfunc.AssignFuncToVariable()
anonfunc.CallAnonFunc()
anonfunc.PassArgToAnonFunc()
usertypefunc.Def... |
package modifier
import (
"github.com/hashicorp/go-plugin"
"github.com/jonmorehouse/gatekeeper/gatekeeper"
"github.com/jonmorehouse/gatekeeper/internal"
)
// Plugin is the interface which a plugin will implement and pass to `RunPlugin`
type Plugin interface {
// internal.Plugin exposes the following methods, per:... |
package s3
import (
"encoding/json"
"fmt"
"github.com/minio/minio-go/v7/pkg/encrypt"
"github.com/root-gg/plik/server/common"
)
// Build Server Side Encryption configuration
func (b *Backend) getServerSideEncryption(file *common.File) (sse encrypt.ServerSide, err error) {
switch encrypt.Type(b.config.SSE) {
ca... |
// time: o(n), space: o(n)
func partitionDisjoint(A []int) int {
mins := make([]int, len(A))
m := 1000001
for i, _ := range A {
idx := len(A) - 1 - i
if m > A[idx] {
m = A[idx]
}
mins[idx] = m
}
m = 0
for i := 0; i < len(A) - 1; i++ {
if m < A[... |
package domain
import (
"encoding/json"
"fmt"
"log"
"sort"
"time"
)
type Logs []*Log
func (l Logs) Less(i, j int) bool {
return time.Time(l[i].Start).Before(time.Time(l[j].Start))
}
func (l Logs) Swap(i, j int) {
l[i], l[j] = l[j], l[i]
}
func (l Logs) Len() int {
return len(l)
}
type JSONTime time.Time
... |
package action
import (
"fmt"
"github.com/fatih/color"
"github.com/urfave/cli"
)
// Git runs git commands inside the store or mounts
func (s *Action) Git(c *cli.Context) error {
store := c.String("store")
return s.Store.Git(store, c.Args()...)
}
// GitInit initializes a git repo
func (s *Action) GitInit(c *cli... |
package decodeways
import (
"bufio"
"encoding/json"
"io"
"os"
"testing"
)
type Test struct {
Input string `json:"input"`
Output int `json:"output"`
}
func TestDecodeWays(test *testing.T) {
f, err := os.Open("./tests.json")
if err != nil {
test.Error(err)
}
defer f.Close()
reader := bufio.NewRead... |
package command
import (
"github.com/payfazz/fazz-swagger/internal/compile"
"github.com/spf13/cobra"
)
type compileCommand struct{}
// NewCompile create compile as sub command
func NewCompileCommand() *cobra.Command {
c := compileCommand{}
cmd := &cobra.Command{
Use: "compile [directory]",
Short: "Compile ... |
// Code for parsing XML coverage output (eg. Java or Python).
package test
import "encoding/xml"
import "strings"
import "core"
func parseXMLCoverageResults(target *core.BuildTarget, coverage *core.TestCoverage, data []byte) error {
xcoverage := xmlCoverage{}
if err := xml.Unmarshal(data, &xcoverage); err != nil ... |
package day7
import (
"testing"
"github.com/achakravarty/30-days-of-go/assert"
)
type testCase struct {
arr []int
expected []int
}
var testCases = []testCase{
testCase{arr: []int{1, 2, 3}, expected: []int{3, 2, 1}},
}
func TestArrays(t *testing.T) {
for _, testInput := range testCases {
actual := Reve... |
package main
import (
"errors"
"log"
"syscall"
"unsafe"
)
var ()
type FlutterEmbedderGLFW struct {
flutter_embedder syscall.Handle
procCreateFlutterWindowInSnapshotMode uintptr
procFlutterWindowLoop uintptr
procFlutterTerminate uintptr
pr... |
package main
import (
"fmt"
"github.com/saylorsolutions/passlock"
)
const gcmNonceLen = 12
const scryptSaltLen = 32
const authenticationTagLen = 16
func main() {
secretData := []byte("secret sauce")
password := []byte("Pa$$w0rd")
cipherText, err := passlock.EncryptBytes(password, secretData)
if err != nil {
... |
package main
import (
"fmt"
"os"
"github.com/Cloud-Foundations/Dominator/fleetmanager/topology"
"github.com/Cloud-Foundations/Dominator/lib/errors"
"github.com/Cloud-Foundations/Dominator/lib/json"
"github.com/Cloud-Foundations/Dominator/lib/log"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
fm_proto "git... |
package dev
// ComMode ...
type ComMode int
const (
// UartMode ...
UartMode ComMode = iota
// TTLMode ...
TTLMode
)
// DistMeter ...
type DistMeter interface {
Dist() float64
Close()
}
// US100Config ...
type US100Config struct {
Mode ComMode
Trig int8
Echo int8
Dev string
Baud int
Retry int
}
|
package cis
import (
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/antonioalfa22/egida/pkg/ansible"
"github.com/antonioalfa22/go-utils/collections"
)
func ShowPointsMenu(connection string) {
var points []string
prompt := &survey.MultiSelect{
Message: "Select CIS Points:",
Options: []string{
"... |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package armhelpers
import (
"context"
"testing"
)
func TestResourceSkusInterface(t *testing.T) {
mc, err := NewHTTPMockClient()
if err != nil {
t.Fatalf("failed to create HttpMockClient - %s", err)
}
mc.RegisterLo... |
package cmd
import (
// System
"fmt"
"os"
"strconv"
"strings"
// 3rd Party
log "github.com/sirupsen/logrus"
)
// Get future release
func GetFutureRelease(o *ReleaseOptions, t string) {
release := map[string]int{
"major": 0,
"minor": 1,
"patch": 2,
}
currentRelease := o.FutureRelease
intRelease, re... |
package dushengchen
/*
Submission:
https://leetcode.com/submissions/detail/357219769/
*/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeKListsV2(lists []*ListNode) *ListNode {
if len(lists) == 0 {
return nil
}
cur := ... |
package reverseproxy
import (
"net/http/httputil"
)
func NewReverseProxy(director Director, responseModifier ResponseModifier, transporter Transporter) *httputil.ReverseProxy {
return &httputil.ReverseProxy{
Director: director.Get(),
ModifyResponse: responseModifier.Get(),
Transport: transporter.Ge... |
package fib
func isNonNegative(n int) bool {
if 0 <= n {
return true
}
return false
}
// Fib1 returns of the fibonacci of input
func Fib1(n int) int {
if !isNonNegative(n) {
panic("fibonacci input must be non-negative")
}
if n < 2 {
return n
}
return Fib1(n-2) + Fib1(n-1)
}
|
package projector
import (
"context"
"fmt"
"net"
"strings"
"time"
)
//type Devices map[string]Device
type Device struct {
Address string
Name string
context.Context
context.CancelFunc
commands chan Command
State State
EventCallbacks map[string]chan interface{}
}
type Callback func(string, interface{}... |
package recovery
import (
"context"
"testing"
)
func TestOnce(t *testing.T) {
defer func() {
if recover() != nil {
t.Error("fail")
}
}()
next := func(ctx context.Context, req interface{}) (interface{}, error) {
panic("panic reason")
}
_, e := Recovery()(next)(context.Background(), "panic")
t.Logf("s... |
package main
import (
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestEnvSetting(t *testing.T) {
env := os.Getenv("GO_ENV")
assert.Equal(t, "development", env)
neoURL := os.Getenv("NEO4J_URL")
assert.Equal(t, "bolt://neo4j:neo4jadmin@localhost:7687", neoURL)
}
|
package jwt
import (
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/rodzy/flash/models"
)
//Spawn it's the generator for our JWt
func Spawn(u models.User) (string, error) {
pass := []byte("YoooHelloGolang_")
payload := jwt.MapClaims{
"email": u.Email,
"name": u.Name,
"lastname": u.LastName... |
package service
import (
"log"
"github.com/rudeigerc/broker-gateway/mapper"
"github.com/rudeigerc/broker-gateway/model"
)
type Firm struct {
}
func (f Firm) Firms() []model.Firm {
m := mapper.NewMapper()
var firms []model.Firm
err := m.Find(&firms)
if err != nil {
log.Printf("[service.firm.Firms] [ERROR] %... |
package config
import (
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v2"
"io"
"io/ioutil"
)
// Client keeps all client configuration settings
var Client ClientConfig = ClientConfig{}
// Basically, our config is inside the "config" section. So we load the whole file and only store the Cfg section
type wrapped... |
package backend
import (
"strconv"
"time"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Sessions", func() {
It("should create a Session without crashing", func() {
createSession := func() {
NewSession("Test", 1)
}
Expect(createSession).ShouldNot(Panic())
})
It("should add... |
// 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 netlib
import (
"errors"
"net"
"github.com/elitah/utils/atomic"
)
var (
EClosed = errors.New("channel closed")
)
type ListenerWithInput interface {
net.Listener
Input(net.Conn) error
}
type chanListener struct {
flag atomic.AInt32
addr net.Addr
ch chan net.Conn
}
func NewChanListener(addr net.... |
package main
import (
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
/*
reportUrls := {
"/api/v0/diagnostic_report",
"/api/v0/diagnostic_report.json",
}
*/
// OpsManClient is the client for the ops manager.
type OpsManClient struct {
address string
token st... |
package middleware
import (
"database/sql"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func Storage(cfg string) gin.HandlerFunc {
db, err := sql.Open("mysql", cfg)
if err != nil {
panic("Failed to connect to database.")
}
return func(c *gin.Context) {
c.Set("db", db)
... |
package manager
import (
"net"
"github.com/Cloud-Foundations/Dominator/lib/net/vsock"
)
func (m *Manager) checkVsockets() error {
if cid, err := vsock.GetContextID(); err != nil {
return nil
} else if cid != 2 {
m.Logger.Printf("detected VSOCK CID=%d, not enabling\n", cid)
} else {
m.vsocketsEnabled = tru... |
package models
//Member : For /api/projects/:pid/members
type Member struct {
UserName string `json:"username"`
Roles []int `json:"roles"`
}
|
package alipay
import (
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"github.com/imkos/alipay/encoding"
"github.com/tidwall/gjson"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strings"
"time"
)
var (
RSA = &RSA_sign{sign_type: K_SIGN_TYPE_RSA, hash: crypto.SHA1}
RSA2 = &RSA_sign{sign_type: K_SIGN_TY... |
package main
import (
"bytes"
"io/ioutil"
"log"
"syscall"
)
func getHostname() []byte {
hostname, err := ioutil.ReadFile("/etc/hostname")
if err != nil {
log.Println("error while reading hostname:", err)
return []byte("akina")
}
return bytes.TrimSpace(hostname)
}
func initHostname() {
hostname := getHos... |
package global
import (
"errors"
"fmt"
"io"
"strings"
"time"
multiple "ucp/multiple"
)
type GlobalConfig struct {
Endpoints map[string]*UserConfig `json:"endpoints"`
// Servers map[string]*UserConfig `json:"servers"`
Mtu int `json:"mtu"`
}
func (c *GlobalConfig) Start() error {
var errs []string
for _, h ... |
package main
func main() {
data := PayloadCollection{}
// 1
payloadHandler(data)
// 2
payloadHandler2(data)
// 3
dispatcher := NewDispatcher(MaxWorker)
dispatcher.Run()
payloadHandler3(data)
}
|
package model
type SendMessageRequest struct {
message []byte
protocol int
src VirtualIp
dest VirtualIp
}
func MakeSendMessageRequest(message []byte, protocol int, dest VirtualIp) SendMessageRequest {
return SendMessageRequest{message, protocol, EMPTY_VIRTUAL_IP, dest}
}
func MakeSendMessageRequestWit... |
package main
import (
"flag"
"github.com/lfxnxf/protobuf_to_sdk/general"
)
var g *general.General
func init() {
//解析参数
//protobuf文件
in := flag.String("in", "", "protobuf file")
//输出模型文件名称
outModelName := flag.String("om", "model", "out model file")
//输出sdk文件名称
outSdkName := flag.String("os", "sdk", "out sd... |
package caaa
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00700101 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.007.001.01 Document"`
Message *AcceptorCancellationAdviceV01 `xml:"AccptrCxlAdvc"`
}
func (d *Document007... |
package handler
import (
"context"
"time"
server "github.com/micro/go-micro/v2/server"
"github.com/micro/go-micro/v2/util/log"
client "github.com/lecex/core/client"
"github.com/lecex/device-api/config"
cashierPB "github.com/lecex/device-api/proto/cashier"
devicePB "github.com/lecex/device-api/proto/device"
... |
package main
import (
"net/http"
"log"
"os/exec"
"strings"
)
// 入口函数
// 入口函数
func main() {
http.HandleFunc("/exec", func(w http.ResponseWriter,r *http.Request) {
defer func(){log.Printf("finished %v\n", r.URL)}()
out,err := genCmd(r).CombinedOutput()
if err!=nil {
w.WriteHeader(500)
w.... |
/*
Copyright 2017 The Kubernetes Authors.
SPDX-License-Identifier: Apache-2.0
*/
package oimcsidriver
import (
"context"
"github.com/container-storage-interface/spec/lib/go/csi"
)
func (od *oimDriver) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
return ... |
package models
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"net/http"
"strconv"
)
var Db *gorm.DB
// https://www.artacode.com/posts/sql/gorm-err/
func init() {
var err error
//"root:@/healthy?charset=utf8&parseTime=true"
Db, err = gorm.Open("mysql","root:@/healthy?charset=utf8&parseT... |
package models
import (
"time"
)
// Application represents the config file up will monitor
type Application struct {
ID int `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"-"`
Name string `yaml:"name" json:"name"... |
/*
* Copyright (C) 2019 Rohith Jayawardene <gambol99@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-09-30 09:15
# @File : lt_64_Minimum_Path_Sum.go
# @Description :
# @Attention :
*/
package array
/*
最小路径和
依旧为动态规划题
*/
func minPathSum(grid [][]int) int {
if len(grid) == 0 || len(grid[0]) == 0 {
return 0
}
for i := 0; i < len(grid); i++ {
for j... |
package nio
import (
"net"
)
/*
type Channel struct {
fd uintptr
interests int
ready int
}
TCPListener
TCPConn
UnixListener
UnixConn
UDPConn
*/
// TODO: SelectionKey 改成Channel,实现net.Listener和net.Conn
// Read:读需要全部读完
// Write:自动维护状态,自动缓存未写完数据
// 上层只需监听读,写由库维护
type SelectionKey struct {
channel interface{} // n... |
/*
Copyright The Helm 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, software
di... |
package models
import "time"
type Client struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DiscordID string `json:"discord_id" gorm:"unique_index:idx_client_discord_id_guild_id"`
UUID string `... |
// Package spec specifies valid audio formats
package spec
|
package 性质判定
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// ------------------ 独立写的代码 ------------------
func isSubStructure(A *TreeNode, B *TreeNode) bool {
if B == nil {
return false
}
return getIsSubStructure(A, B)
}
... |
package cutout
func executeFallbacks(fbf []func() (*Response, error)) (*Response, error) {
fResp := &Response{}
var err error
for _, fb := range fbf { //as cutout supports multi-level fallbacks
fResp, err = fb()
if err != nil {
continue // if one fails, try the next one
}
break
}
return fResp, err... |
package main
import (
"fmt"
"net/http"
)
type MyMux struct {
}
func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
sayhelloName(w, r)
return
}
//open http://localhost:9090/alex
//it will run openALex function
if r.URL.Path =="/alex"{
openAlex(w,r)
return
}
http... |
package main
import (
"fmt"
"image"
"gopkg.in/karalabe/cookiejar.v1/collections/deque"
)
type linkedmap map[image.Point]map[image.Point]bool
func buildlinkedmap(input string) linkedmap {
start := image.Point{0, 0}
s := deque.New()
s.PushRight(start)
linked := linkedmap{}
cur := image.Point{0, 0}
dmap := ma... |
package repository
import (
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
"github.com/dghubble/sling"
"github.com/ghodss/yaml"
"github.com/jinzhu/copier"
"github.com/mojo-zd/helm-api/pkg/typed/charts"
"github.com/rs/zerolog/log"
helmrepo "helm.sh/helm/v3/pkg/repo"
)
var indexYAML = "index.yaml"
type ... |
package main
import (
"fmt"
)
type Node struct {
Value int
Left *Node
Right *Node
}
type Tree struct {
Root *Node
}
func (t *Tree) Insert(value int) {
// First insert, set root.
if t.Root == nil {
t.Root = &Node{Value: value}
} else {
t.Root.Insert(value)
}
}
func (t *Tree) Print() {
t.R... |
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use... |
package main
import "fmt"
type money float64
func (m money) Currency(dollar money) {
m = dollar
fmt.Println(m)
}
func main() {
var dollar money = 70.4
var m1 money
m1.Currency(dollar)
}
|
package synctest
import "sync"
// NotifyingLocker is an implementation of sync.Locker that notifies callers when
// locks and unlocks happen. otherwise, it behaves identically as a sync.Mutex.
//
// Example usage:
// nl := NewNotifyingLocker()
// lch := nl.NotifyLock()
// uch := nl.NotifyUnlock()
// go func() {
/... |
package main
import (
"flag"
"fmt"
"strconv"
"strings"
"github.com/dah8ra/ch4/xkcdcom"
)
var word = flag.String("w", "default", "Search word")
const preurl = "https://xkcd.com/"
const sufurl = "/info.0.json"
var x xkcdcom.Xkcd
func main() {
m := make(map[string]string)
for i := 570; i < 572; i++ {
url :=... |
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package sample
import (
"net/http"
"google.golang.org/appengine/log"
)
// [START communication_between_modules_1]
import "google.golang.org/appengine"
func... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.