text stringlengths 11 4.05M |
|---|
package register
import "fmt"
// DataType ...
type DataType byte
// DTNumeric datatype is numeric
func DTNumeric(t DataType) bool {
return t == Int8Type ||
t == Int16Type ||
t == Int32Type ||
t == Int64Type ||
t == UInt8Type ||
t == UInt16Type ||
t == UInt32Type ||
t == UInt64Type ||
t == Float32Typ... |
package registry
import ()
/*func TestCreatePullSecret(t *testing.T) {
namespace := "myns"
//Setting up kubeClient
kubeClient := &kubectl.Client{
Client: fake.NewSimpleClientset(),
}
_, err := kubeClient.Client.CoreV1().Namespaces().Create(&k8sv1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
... |
// Copyright 2018 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... |
/*
Create a function (named fifth) that takes some arguments and returns the type of the fifth argument.
In case the arguments were less than 5, return "Not enough arguments".
Examples
fifth(1, 2, 3, 4, 5) ➞ int
fifth("a", 2, 3, [1, 2, 3], "five") ➞ str
fifth() ➞ "Not enough arguments"
Notes
Don't get confus... |
package handler
import (
"context"
"encoding/json"
"fmt"
"geofinder/es"
"geofinder/model"
"reflect"
gj "github.com/kpawlik/geojson"
"github.com/valyala/fasthttp"
elastic "gopkg.in/olivere/elastic.v5"
)
type CircleQueryRequest struct {
Radius string `json:"radius"`
Coordinates gj.Coordinate `js... |
package alertmanager
import (
"testing"
"time"
"github.com/prometheus/alertmanager/types"
"github.com/stretchr/testify/assert"
)
func TestResolved(t *testing.T) {
s := &types.Silence{}
assert.False(t, Resolved(s))
s.EndsAt = time.Now().Add(time.Minute)
assert.False(t, Resolved(s))
s.EndsAt = time.Now().Ad... |
package autoscaler
import (
"encoding/json"
"fmt"
"strconv"
"time"
"gopkg.in/redis.v4"
)
type StatusStoreIface interface {
StoreCooldownEndsAt(t time.Time) error
FetchCooldownEndsAt() (time.Time, error)
ListSchedules() ([]*Schedule, error)
AddSchedules(sch *Schedule) error
RemoveSchedule(key string) error
... |
// +build !race
package rc
import (
"context"
"encoding/json"
"fmt"
"sync"
"testing"
"time"
"github.com/square/p2/pkg/alerting/alertingtest"
"github.com/square/p2/pkg/artifact"
"github.com/square/p2/pkg/audit"
"github.com/square/p2/pkg/health"
fake_checker "github.com/square/p2/pkg/health/checker/test"
"... |
package bundler
import (
"database/sql"
"errors"
"fmt"
"log"
"os"
"strings"
// Loads the PostgreSQL driver for database/sql.
_ "github.com/lib/pq"
)
const filesTable = "files"
// OpenDB returns a configured connection to the postgres database.
func OpenDB() *sql.DB {
url := fmt.Sprintf("postgres://%s:%s@%s... |
// 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 prod
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
)
type metadata struct {
ClientCertificates []struct {
Thumbprint string `json:"thumbprint,omitempty"`
NotBefore time.Time `json:"notBefore,omitempty"`
NotAfter time.Time `json:... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//209. Minimum Size Subarray Sum
//Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of ... |
package main
import (
"fmt"
)
func addition(a int, b int) int {
return a + b
}
func aVoidFunc() {
fmt.Println("a void function")
}
// multiple return function
func aFuncMultipleRet() (int, int) {
return 4, 6
}
// variadic function
func sums(nums ...int) int {
total := 0
for _, num := range nums {
total += ... |
package inputProcessors
import (
"bufio"
"io"
"github.com/dpordomingo/learning-exercises/ant/geo"
"github.com/dpordomingo/learning-exercises/ant/literals"
)
//Process returns a Map, origin and destiny from STDin
func Process(f io.Reader) (*geo.Map, *geo.Point, *geo.Point, error) {
var mapTarget *geo.Point
var... |
package jsonio
type JSONReadWriter interface {
JSONReader
JSONWriter
}
|
package main
import (
"encoding/json"
"flag"
"io/ioutil"
"os"
"strconv"
)
type JSONConfig struct {
path string
PidFile string
Master string
LogFile string
Port string
NumShards string
Shard string
Cluster map[string]string
}
type MomConfig struct {
jsonConf *JSONConfig
Se... |
package mockqueue
import (
"context"
"errors"
"github.com/utilitywarehouse/go-pubsub"
)
var _ pubsub.MessageSink = (*MockQueue)(nil)
var _ pubsub.MessageSource = (*MockQueue)(nil)
// MockQueue is intended for testing purposes.
// It provides a simple in-memory sink and source
type MockQueue struct {
q chan... |
package api
import "sync"
type API struct {
currentFilepath string
currentFilename string
sync.Mutex
}
|
package logic
import (
"context"
"tpay_backend/payapi/internal/svc"
"tpay_backend/payapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type GetUnionpayLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetUnionpayLogic(ctx context.Context, svcCtx *svc.ServiceC... |
package visitor_test
import (
"io/ioutil"
"reflect"
"testing"
"fmt"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/language/ast"
"github.com/graphql-go/graphql/language/kinds"
"github.com/graphql-go/graphql/language/parser"
"github.com/graphql-go/graphql/language/printer"
"github.com/graphq... |
package main
import (
"bytes"
"testing"
)
func TestCompress(t *testing.T) {
bts, err := Compress("hello world")
if err != nil {
t.Fail()
}
//0b11010001
//0b10010111
//0b01100110
//0b11001101
//0b11101000
//0b00111011
//0b11101111
//0b11100101
//0b10110011
//0b00100000
expectedBytes := []byte{
0xd... |
package models
import (
"context"
)
type Dao interface {
CreateUser(ctx context.Context, user User) error
GetUserByEmployeeId(ctx context.Context, employeeId int64) (User, error)
GetUserByCredentials(ctx context.Context, email string, password string) (User, error)
UpdateUserProfile(ctx context.Context, user Use... |
package main
import "fmt"
func main() {
//var colors map[string]string
//colors := make(map[string]string)
//colors["black"] = "#000"
//delete(colors, "black")
//fmt.Println(colors)
colors := map[string]string{
"red" : "#ff0000",
"black": "#000000",
"white": "#ffffff",
}
printColors(colors)
}
func p... |
package common
import (
"fmt"
"strings"
)
// FeatureDisabled feature is always off
const FeatureDisabled = "disabled"
// FeatureEnabled feature is opt-in
const FeatureEnabled = "enabled"
// FeatureDefault feature is opt-out
const FeatureDefault = "default"
// FeatureForced feature is always on
const FeatureForce... |
// Copyright 2021 PingCAP, Inc. Licensed under Apache-2.0.
package utils
import (
"context"
"database/sql"
"strconv"
"strings"
"github.com/docker/go-units"
"github.com/pingcap/errors"
"github.com/pingcap/log"
"github.com/pingcap/tidb/br/pkg/logutil"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/ses... |
//+build test
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package azure
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"strconv"
"time"
"github.com/Azure/aks-engine/test/e2e/engine"
"github.com/Azure/aks-engine/test/e2e/kubernetes/util"
"g... |
package abstract_factory
type Car interface {
GetDoors() int
}
|
// Copyright 2021 PingCAP, Inc. Licensed under Apache-2.0.
package streamhelper
import (
"context"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/br/pkg/redact"
"github.com/pingcap/tidb/kv"
kvutil "github.com/tikv/client-go/v2/kv"
clientv3 "go.etcd.io/etcd/client/v3"
)
// etcdSource is the adapter for et... |
package main
type dbCreator struct {
}
func (d *dbCreator) DBExists(dbName string) bool {
return true
}
func (d *dbCreator) CreateDB(dbName string) error {
return nil
}
func (d *dbCreator) RemoveOldDB(dbName string) error {
return nil
}
func (d *dbCreator) Init() {
loader.GetBufferedReader()
}
func (d *dbCrea... |
package main
import (
"fmt"
"gm/util"
)
func main() {
msg := []byte("abcd")
key := []byte("123456789abcdefg")
enMsg, err := util.SM4Encrypt(key, msg)
if err != nil {
fmt.Println(err)
}
fmt.Println("-----------------SM4加密后密文-----------------")
fmt.Println(enMsg)
fmt.Println(string(enMsg))
deMsg, _ := ut... |
// Copyright 2018 The Hugo Authors. All rights reserved.
// Simplified copy of Hugo's scratch.go file
package scratch
import (
_os "os"
"sync"
)
// Scratch is a writable context used for stateful operations in Page/Node rendering.
type Scratch struct {
values map[string]interface{}
mu sync.RWMutex
}
// Set... |
package main
import (
"context"
"log"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/storage/inmem"
)
func main() {
ctx := context.Background()
query := ast.MustParseBody(`data.example.allow = x`)
... |
package main
import (
"context"
"github.com/pkg/errors"
"github.com/brigadecore/brigade/sdk/v3"
"github.com/brigadecore/brigade/sdk/v3/restmachinery"
)
func getClient(testConn bool) (sdk.APIClient, error) {
cfg, err := getConfig()
if err != nil {
return nil, errors.Wrapf(
err,
"error getting brigade c... |
package indicator
import (
"time"
"fmt"
)
type Stat interface {
Calculate(tp time.Duration) (float64, error)
}
type Generator struct {
Stats []Stat
}
func (g *Generator) Start(duration time.Duration, interval time.Duration) (chan struct{}){
ticker := time.NewTicker(interval)
quit := make(chan struct{})
go fu... |
// Copyright 2015 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... |
//
// 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 bigflake
import (
"encoding/hex"
"errors"
"fmt"
"math/big"
"regexp"
"github.com/mattheath/base62"
)
// NewId creates a BigflakeId from a big.Int
func NewId(id *big.Int) *BigflakeId {
return &BigflakeId{id}
}
// BigflakeId represents a globally unique ID
type BigflakeId struct {
id *big.Int
}
// Str... |
package model
import (
"encoding/json"
"fmt"
"github.com/magiconair/properties/assert"
"testing"
)
func TestCreateCard(t *testing.T) {
card := &Card{
Type: 0,
Title: "Card Title",
Content: "This is card",
}
id, err := CreateCard(card)
assert.Equal(t, err, nil)
assert.Equal(t, true, id > 0)
}
fun... |
package lyrics
import (
"fmt"
"strings"
"github.com/sirupsen/logrus"
)
type Handler struct {
backends []backend
}
type TrackInfo struct {
Artist string
Title string
SongArtURL string
}
func (p *Handler) cleanName(s string) string {
badChars := []rune{'-', '(', '[', ')', ']'}
res := s
for i, c :=... |
package ufile
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
model "github.com/cloudreve/Cloudreve/v3/models"
"github.com/cloudreve/Cloudreve/v3/pkg/filesystem/fsctx"
"github.com/cloudreve/Cloudreve/v3/pkg/filesystem/response"
"github.com/cloudreve/Cloudreve/v3/pkg/request"
"github.com/c... |
package main
import (
"fmt"
"os"
"os/exec"
"runtime"
"github.com/mjthomp95/minesweeper/pkg/board"
)
func main() {
fmt.Println("Welcome to Minesweeper!")
run := true
for run {
fmt.Print("Start (Type s), Help (Type h), Quit (type q): ")
var choice string
if _, err := fmt.Scan(&choice); err != nil {
fm... |
package typeutils
func BoolPtr(b bool) *bool {
return &b
}
func BoolYNString(b bool) string {
if b {
return "Y"
}
return "N"
}
func BoolYesNoString(b bool) string {
if b {
return "Yes"
}
return "No"
}
|
package sdk
import (
"testing"
"github.com/stretchr/testify/require"
)
const (
testAPIAddress = "localhost:8080"
testAPIToken = "11235813213455"
)
func TestNewAPIClient(t *testing.T) {
client, ok := NewAPIClient(testAPIAddress, testAPIToken, nil).(*apiClient)
require.True(t, ok)
require.NotNil(t, client.au... |
package polochon
import (
"github.com/odwrtw/errors"
"github.com/sirupsen/logrus"
)
// Detailer is the interface to get details on a video or a show
type Detailer interface {
Module
GetDetails(i interface{}, log *logrus.Entry) error
}
// Detailable represents a ressource which can be detailed
type Detailable int... |
package 获取
var minLabelsInLay []int
var maxLabelsInLay []int
var maxLayOfOwningLabel int
func widthOfBinaryTree(root *TreeNode) int {
minLabelsInLay = make([]int, 0)
maxLabelsInLay = make([]int, 0)
maxLayOfOwningLabel = -1
formLabels(root, 0, 0)
return getMaxWidth()
}
func formLabels(root *TreeNode, nowLay int,... |
package baidupcs
import (
"errors"
"github.com/iikira/BaiduPCS-Go/baidupcs/pcserror"
"github.com/iikira/BaiduPCS-Go/pcsutil/escaper"
"mime"
"net/url"
"path"
"strings"
)
const (
// ShellPatternCharacters 通配符字符串
ShellPatternCharacters = "*?[]"
)
var (
// ErrFixMD5Isdir 目录不需要修复md5
ErrFixMD5Isdir = errors.New... |
package html
type bodyNode struct {
Node
}
func Body(children ...*Node) bodyNode {
return bodyNode{Node{Name: "body", Children: children}}
}
|
package module
import (
"accountBook/models/beans"
"accountBook/models/beans/customer"
"accountBook/models/beans/dbBeans"
"accountBook/models/endpoints"
"accountBook/models/endpoints/web"
"accountBook/models/service"
"github.com/kinwyb/go/err1"
)
var ReceiptType web.IReceiptTypeEndpoint = &receiptTypeEp{}
ty... |
/*
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, ... |
package mypkg1
import "testing"
import "github.com/stretchr/testify/assert"
func TestPkg1GetString(t *testing.T) {
str := GetPkg1String()
expectedStr := "inside the package 1 code"
assert.Equal(t, expectedStr, str, "The two words should be the same.")
}
|
package main
import (
"bufio"
"os"
)
func main() {
file, _ := os.Open("input/day03.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
rows := make([]string, 0)
for scanner.Scan() {
rows = append(rows, scanner.Text())
}
result := countPerSlope(rows, 1, 1) *
countPerSlope(rows, 1, 3) *
countPer... |
package ginhandler
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/line/line-bot-sdk-go/linebot"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var testRequestBody =... |
package controllers
import (
"app-auth/auth"
"app-auth/db"
"app-auth/types"
"app-auth/utils"
"fmt"
"os"
"time"
"log"
"net/http"
"github.com/labstack/echo/v4"
"github.com/mongodb/mongo-go-driver/bson"
)
func ConfirmMemberInvite(ctx echo.Context) error {
mailId := ctx.Param("confirmationId")
// we get t... |
package net
import (
"math"
"github.com/therecipe/qt/core"
"github.com/ivanterekh/qt-go-examples/internal/geometry"
)
type Net struct {
net [][][]geometry.Point
cw, ch int
}
func New(points []geometry.Point, w, h int) *Net {
n := len(points)
k := int(math.Ceil(math.Pow(float64(n), 0.33)))
net := make([... |
package lua
import (
"testing"
assert "gopkg.in/go-playground/assert.v1"
)
func TestPitchTransposition(t *testing.T) {
vm := newVM(t)
defer vm.Close()
err := vm.DoString(`
local theory = require('eolian.theory')
local tonic = theory.pitch('C4')
assert(tonic:transpose(theory.octave(1)):name() == 'C5', 'oct... |
package main
import "fmt"
func main() {
greet("Jane") // arguments
greet("John") // arguments
}
func greet(name string) { // parameter
fmt.Println(name)
}
// greet is declared with a parameter
// when calling greet, pass in an argument
|
package main
import (
"net"
"fmt"
)
func main() {
listen, err := net.Listen("tcp","0.0.0.0:50002")
if err != nil {
fmt.Println("listen tcp error:", err)
return
}
for {
connect, err := listen.Accept()
if err != nil{
fmt.Println("accept error:", err)
continue
}
go handleConnect(connect)
}
}
... |
package bridge
import (
"bytes"
"github.com/sujit-baniya/smpp/pdu"
"github.com/sujit-baniya/smpp/sms"
)
func ToSubmit(sm *pdu.SubmitSM) (submit *sms.Submit, err error) {
var userData bytes.Buffer
_, _ = sm.Message.UDHeader.WriteTo(&userData)
userData.Write(sm.Message.Message)
submit = &sms.Submit{
Flags: sms... |
// Copyright 2013 Albert P. Tobey. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lnxns
import (
"fmt"
"log"
)
func assertNil(err error, message string) {
if err != nil {
log.Fatal(fmt.Sprintf("%s: %s\n", message, err))
}
}
... |
package subscription
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilclock "k8s.io/utils/clock/testing"
"github.com/operator-frame... |
package main
import "fmt"
func main() {
var weight = 210.0 * 0.3783
var age = 38 * 365 / 687
fmt.Printf("My weight on the surface of Mars is %v lbs,", weight)
fmt.Printf(" and I would be %v years old.\n", age)
fmt.Printf("weight %v, age %v\n", weight, age)
fmt.Printf("$%4v\n", 94)
fmt.Printf("$%4v\n", 100)
... |
package main
import "fmt"
func pop(list *[]int, c chan int, done chan bool) {
for len(*list) != 0 {
result := (*list)[0]
*list = (*list)[1:]
fmt.Println("about to send ", result)
c <- result
}
close(c)
done <- true
}
func receiver(c chan int) {
for result := range c {
fmt.Println("received ", result)
... |
package main
import (
consul "github.com/hashicorp/consul/api"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"time"
)
type ConsulClient interface {
RegisterService(name string, ttl time.Duration) error
}
type consulClient struct {
client *consul.Client
aclGetter func() string
}
func NewConsulCl... |
package restapi
import (
"testing"
)
func TestRegister(t *testing.T) {
cases := []struct {id, password, name, email string} {
{"helloljho", "root1234", "lee jungho", "helloljho@igloosec.om"},
{"puslip41", "root1234", "kim pilseop", "puslip41@igloosec.om"},
}
s := MemoryStorage{}
for i, tc := range cases ... |
命令行传入的参数在os.Args变量中保存。
func 函数名(参数列表)(返回值列表) {
// 函数体
}
GOPATH和PATH环境变量一样,也可以接受多个路径,并且路径和路径之间用冒号分割。
编译方式1{
直接生产可执行文件
cd bin
go build main(注意如果GOPATH有多个路径的话,只会编译第一个路径的包)
会把可执行文件生成到当前目录下
只会生成可执行文件
}
编译方式2{
直接go install main (注意如果GOPATH有多个路径的话,只会编译第一个路径的包)
会生成所以依赖的包,并把可可执行文件放到bin目录里
}
设置了GOPATH,所以可以在任意目录下执行以下... |
// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
package main
import (
"fmt"
)
type People interface {
Show()
}
type Student struct{}
func (stu *Student) Show() {
if stu == nil {
fmt.Println("stu is nil.")
}
}
func live() People {
var stu *Student
return stu
}
func main() {
si := live()
if si == nil {
fmt.Println("AAAAAAA")
} else {
fmt.Println("... |
package api
import (
"encoding/json"
"errors"
"fmt"
"github.com/dkpeakbil/taskserver/domain"
"github.com/dkpeakbil/taskserver/usecase"
"net/http"
)
type Api struct {
addr string
ucase usecase.UseCase
}
func NewApi(addr string, ucase usecase.UseCase) (*Api, error) {
return &Api{
addr: addr,
ucase: ucas... |
/*
Copyright 2020 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, ... |
package network
import (
"bytes"
"encoding/gob"
"encoding/hex"
"fmt"
"golang-blockchain/blockchain"
"gopkg.in/vrecan/death.v3"
"io"
"io/ioutil"
"log"
"net"
"os"
"runtime"
"syscall"
)
/*
Algorithm:
- Create blockchain with central node
- Wallet node connects and downloads blockchain from central node
- Mi... |
package ptracer
import (
"syscall"
unix "golang.org/x/sys/unix"
)
// SyscallNo get current syscall no
func (c *Context) SyscallNo() uint {
return uint(c.regs.Orig_rax)
}
// Arg0 gets the arg0 for the current syscall
func (c *Context) Arg0() uint {
return uint(c.regs.Rdi)
}
// Arg1 gets the arg1 for the current... |
package db
import (
"time"
"github.com/dgrijalva/jwt-go"
profile_repo "github.com/oojob/protorepo-profile-go"
"github.com/oojob/service-profile/src/model"
uuid "github.com/satori/go.uuid"
"github.com/spf13/viper"
)
var (
accessSecret = []byte(viper.GetString("accesssecret"))
refreshSecret = []byte(viper.Get... |
package main
import (
"KServer/library/kiface/iwebsocket"
"KServer/library/websocket"
"fmt"
)
func main() {
s := websocket.NewWebsocket()
s.SetOnConnStart(action)
s.SetOnConnStop(stop)
s.AddHandle(100, Newhand())
s.Serve()
select {}
}
func action(conn iwebsocket.IConnection) {
fmt.Println(conn.GetConnI... |
package validation_test
import (
"github.com/APTrust/exchange/constants"
"github.com/APTrust/exchange/models"
"github.com/APTrust/exchange/testhelper"
"github.com/APTrust/exchange/util"
"github.com/APTrust/exchange/util/fileutil"
"github.com/APTrust/exchange/util/storage"
"github.com/APTrust/exchange/validation... |
// This file was generated for SObject UserFeed, API Version v43.0 at 2018-07-30 03:47:44.507814336 -0400 EDT m=+30.851578407
package sobjects
import (
"fmt"
"strings"
)
type UserFeed struct {
BaseSObject
Body string `force:",omitempty"`
CommentCount int `force:",omitempty"`
CreatedById ... |
package pain
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00100102 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:pain.001.001.02 Document"`
Message *CustomerCreditTransferInitiationV02 `xml:"pain.001.001.02"`
}
func (... |
package main
import (
"fmt"
"go/ast"
"sync"
)
//检查chan是否 关闭
type T int
type i=int
func IsClosed(ch <-chan T) bool {
select {
case <-ch:
return true
default:
}
return false
}
func SafeClose(ch chan T) (justClosed bool) {
defer func() {
if recover() != nil {
justClosed = false
}
}()
close(ch)... |
package model
type UnifiedResponse struct {
Success bool `json:"success"`
Msg string `json:"msg"`
ErrorCode int `json:"errorCode"`
Data interface{} `json:"data"`
}
func NewUnifiedResponse(success bool, data interface{}) UnifiedResponse {
return UnifiedResponse{
Success: success... |
package routes
import (
"github.com/labstack/echo"
"net/http"
// HOFSTADTER_START import
// HOFSTADTER_END import
)
// HOFSTADTER_START start
// HOFSTADTER_END start
var (
ReadyStatus = false
ReadyState = "NotReady"
ReadyInfo = map[string]string{
"reason": "unknown",
"message": "unchanged since st... |
package leetcode
import "testing"
func TestStack(t *testing.T) {
tests := []rune{'a', 'b', 'c', 'd', '1'}
s := make(stack, 0, 10)
for _, r := range tests {
s.Push(r)
}
for i := len(tests) - 1; i >= 0; i-- {
c, ok := s.Pop()
if !ok {
t.Fatalf("stack[%d] pop failed", i)
}
if got, want := c, tests[i];... |
package main
import (
"fmt"
"sort"
)
// User ...
type User struct {
First string
Last string
Age int
Sayings []string
}
// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []User
// Len ...
func (a ByAge) Len() int {
return len(a)
}
// Swap ...
func (a ByAge) Swap(... |
package main
import (
"github.com/Secured-Finance/dione/node"
)
func main() {
node.Start()
}
|
package main
import "testing"
func TestNewDeck(t *testing.T) {
deck := NewDeck()
if len(deck.cards) != 52 {
t.Fatalf("Expected new deck to contain 52 cards, but contained %d", len(deck.cards))
}
}
func TestDeckShuffle(t *testing.T) {
deck := NewDeck()
oldLen := len(deck.cards)
deck.Shuffle()
if len(deck.car... |
// +build darwin freebsd netbsd openbsd
package logs
import (
"syscall"
)
const ioctlReadTermios = syscall.TIOCGETA
|
package config
import (
"fmt"
"time"
"github.com/kelseyhightower/envconfig"
log "github.com/sirupsen/logrus"
)
var EnvPrefix = ""
var RedisAddr = ":6379"
type (
Config struct {
*Server
}
Server struct {
IP string `envconfig:"SERVER_IP" default:"127.0.0.1"`
Port string `envcon... |
package blc
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"log"
"sync/atomic"
"time"
)
type Block struct{
Timestamp int64
Hash []byte
PreBlockHash []byte
Height int64
Txs []*Transaction //交易数据
Nonce int64 //碰撞次数,也可以是随机数
}
func NewBlock(preBlockHash []byte, height int64,txs []*Transaction) *Block{
... |
package gopg
import (
"fmt"
"github.com/go-pg/pg/v9"
)
type GoPgConection struct {
*pg.DB
}
type ConnectionWithTransacion interface {
RunInTransaction(func(Connection) error) error
Connection
}
type Connection interface {
Insert(...interface{}) error
}
type PGRecord interface {
GetId() int64
}
func (c GoPg... |
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
const listeningAddress = ":7070"
func main() {
fmt.Printf("Listening on %s ...\n", listeningAddress)
http.HandleFunc("/get", handleGet)
http.ListenAndServe(listeningAddress, nil)
}
func handleGet(w http.ResponseWriter, r *http.Request) {
... |
package web
import (
"encoding/json"
"net/http"
"github.com/husobee/vestigo"
"github.com/juju/errors"
r "gopkg.in/dancannon/gorethink.v2"
"github.com/ernestoalejo/tfg-fn/pkg/context"
"github.com/ernestoalejo/tfg-fn/pkg/models"
)
func Register(r *vestigo.Router, db *r.Session) {
r.Get("/", middleware(db, hom... |
package main
import "os"
import "strings"
import "errors"
import "github.com/BurntSushi/toml"
var ErrMissingConfig = errors.New("ServerURL configuration missing. Create a .petrify configuration file containing: ServerURL = \"http://url-to-dev-server\"")
var ErrMissingDeploy = errors.New("Missing deployment configurat... |
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB //是一个连接池对象
func initDb() (err error) {
//数据库信息
dsn := "root:root@tcp(127.0.0.1:3306)/goday10"
//连接数据库
//db 全局的db
db, err = sql.Open("mysql", dsn) //不会校验用户名和密码是否正确
if err != nil {
return
}
err = db.Ping()
if e... |
package lexer
import (
"regexp"
"token"
)
type Pattern struct {
expr *regexp.Regexp
kind token.TokenType
}
type Error struct {
RowIndex int
ColumnIndex int
Value string
}
type Lexer struct {
patterns []Pattern
whiteSpacesReg *regexp.Regexp
absorbErrorReg *regexp.Regexp
rowIndex int
columtIndex int
to... |
/*
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 mysql
import (
"database/sql"
"strings"
"time"
. "../../base"
"github.com/golang/glog"
)
func (p *Mysql) createTickTable(table string) {
sql := "CREATE TABLE IF NOT EXISTS `" + table + "` (" +
"`time` DATETIME(3) NOT NULL," +
"`price` INT(11) NOT NULL DEFAULT 0," +
"`change` INT(11) NOT NULL DEF... |
package mail
import (
"crypto/tls"
"fmt"
"net/smtp"
"strings"
)
type SMTP struct {
FromMail string
FromName string
Identity string
Username string
Password string
Host string
Port int
MaxMailContentLength int
SSL ... |
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package auth
import (
"context"
"net/http"
"github.com/Zenika/marcel/api/commons"
)
type authContextKeyType string
const authContextKey = authContextKeyType("MARCEL/AUT_BACKEND/AUTH")
func Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ... |
package deplog
const (
FlagDebug uint64 = 1 << iota
FlagDebuga
FlagDebugf
FlagInfo
FlagInfoa
FlagInfof
FlagWarning
FlagWarninga
FlagWarningf
FlagWarn
FlagWarna
FlagWarnf
FlagError
FlagErrora
FlagErrorf
FlagCritical
FlagCriticala
FlagCriticalf
FlagCritic
FlagCritica
FlagCriticf
FlagCrit
FlagCrita... |
package main
import (
"bytes"
"encoding/binary"
"errors"
"io"
"unicode/utf16"
)
func readUtf16(r io.Reader) (string, error) {
var buf bytes.Buffer
n, err := io.Copy(&buf, r)
if err != nil {
return "", err
}
if n%2 != 0 {
return "", errors.New("Read odd number of bytes, while expecting UTF-16LE")
}
... |
// 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.