text stringlengths 11 4.05M |
|---|
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
// +build wasm
package wasmclient
import "github.com/iotaledger/wasp/packages/vm/wasmlib"
//go:wasm-module wasplib
//export hostGetBytes
func hostGetBytes(objId int32, keyId int32, typeId int32, value *byte, size int32) int32
//go:wasm-module w... |
package main
import (
"fmt"
)
type Celsius float64
type Huashi float64
func main() {
var a Celsius = 37.5
fmt.Printf("%vC=%vF\n", a, CToF(a))
var b Huashi = CToF(a)
fmt.Printf("%vF=%vC\n", b, FToC(b))
fmt.Printf("Normal Body Temperature is %v", a)
}
func CToF(c Celsius) Huashi {
return Huashi(c*9/5 + 32)
}... |
package service
import (
"github.com/feng/future/go-kit/agfun/agfun-server/dao"
"github.com/feng/future/go-kit/agfun/agfun-server/entity"
// "github.com/sirupsen/logrus"
"common-utilities/encrypt"
"common-utilities/utilities"
"github.com/feng/future/go-kit/agfun/agfun-server/protocol"
"github.com/feng/future/... |
package utils
import (
"net/url"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestURLPathFullClean(t *testing.T) {
testCases := []struct {
name string
have string
expected string
}{
{"ShouldReturnFullPathSingleSlash", "https://example.com/", "/"},
... |
package name
import (
"regexp"
"strings"
)
// reference: https://gist.github.com/stoewer/fbe273b711e6a06315d19552dd4d33e6
// in above gist, matchFirstCap use regexp `(.)([A-Z][a-z]+)`, where `.` would match any character,
// witch make separators such as `.` `,` also be matched
// so use `[A-Za-z0-9]` instead, to ... |
package main
import (
"fmt"
"io/ioutil"
"math"
"strconv"
"strings"
)
func main() {
data, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
w1 := wire(lines[0])
w2 := wire(lines[1])
ins := intersect(w1, w2)
part1(w1, w2, ins... |
package produce
import (
"sub_account_service/number_server/routers/produce/api"
"github.com/gin-gonic/gin"
)
func InitRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
gin.SetMode(gin.ReleaseMode)
r.POST("/addOrder", api.AddOrder)
return r
}
|
package core
import (
"fmt"
"strings"
"testing"
"time"
icid "github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p-core/peerstore"
"github.com/segmentio/ksuid"
"github.com/textileio/go-textile/ipfs"
"github.com/textileio/go-textile/pb"
"github.com/textileio/go-textile/schema/textile"
)
var cafeVars = struct... |
// Copyright 2020 The Amadeus 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 rd_test
import (
"testing"
"time"
"github.com/nenad/rd"
"github.com/stretchr/testify/assert"
)
func TestToken_ExpiredAuthorization(t *testing.T) {
token := rd.Token{
AccessToken: "ACCESS",
RefreshToken: "REFRESH",
ObtainedAt: time.Now().Add(-3600 * time.Second),
}
assert.False(t, token.IsVal... |
package apis
import (
"net/http"
"gopkg.in/gin-gonic/gin.v1"
."taskweb/models"
"taskweb/core"
)
func GetTbPerformancesApi(c *gin.Context){
var tbPerformances = make([]TbPerformance, 0)
tbPerformances, err :=GetTbPerformances()
if err != nil {
core.Logger.Fatalln(err)
}
c.JSON(http.StatusOK, gin.H{
... |
package main
import (
"fmt"
"sync"
"github.com/satori/go.uuid"
)
type PGM struct{
Vertices map[uuid.UUID]*Vertex
Edges map[uuid.UUID]*Edge
storageMutex sync.Mutex
TotalEntityCount float64
TotalVertexCount float64
TotalEdgeCount float64
UniqueVertexNameMap map[string]uuid.UUID
UniqueEdgeNameMap map[string... |
// Copyright 2016 IBM 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 by applicable law or... |
/*
Copyright 2018 Pressinfra SRL.
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... |
package main
import (
"fmt"
"testing"
)
func TestKthSmallest(t *testing.T) {
fmt.Println(1 / 2)
}
|
package abnf
import (
"github.com/lioneagle/goutil/src/mem"
)
type Context struct {
allocator *mem.ArenaAllocator
parseSrc []byte
parsePos Pos
srcLen Pos
}
func NewContext(allocator *mem.ArenaAllocator, src []byte) *Context {
return &Context{allocator: allocator, parseSrc: src, srcLen: Pos(len(src))}
}
f... |
// Copyright 2021 The image-cloner 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 o... |
package main
import (
"cm_liveme_im/libs/bytes"
"cm_liveme_im/libs/debug"
"cm_liveme_im/libs/define"
"cm_liveme_im/libs/proto"
itime "cm_liveme_im/libs/time"
"cm_liveme_im/libs/tokenbucket"
"sync"
"time"
log "github.com/thinkboy/log4go"
)
const (
roomMapCup = 100
)
var roomBucket *RoomBucket
var RoomRouti... |
package runner
// This file contains the implementation for the storage sub system that will
// be used by the runner to retrieve storage from cloud providers or localized storage
import (
"fmt"
"io"
"net/url"
"path/filepath"
"strings"
"time"
"github.com/go-stack/stack"
"github.com/karlmutch/errors"
)
type ... |
package pilot
import (
"github.com/julienschmidt/httprouter"
)
type apiServer struct {
/*
db *database
*/
router *httprouter.Router
}
func setup() {
r := httprouter.New()
r.GET("/payments", nil)
}
|
package consumer
import (
"encoding/json"
"fmt"
"github.com/Shopify/sarama"
"github.com/radyatamaa/loyalti-go-echo/src/api/host/Config"
"github.com/radyatamaa/loyalti-go-echo/src/domain/model"
"github.com/radyatamaa/loyalti-go-echo/src/domain/repository"
"os"
"os/signal"
"strings"
//"time"
)
func consumeOut... |
package simplettl
import (
"sync"
"time"
)
// entry - typical element of cache
type entry struct {
value interface{}
expiry *time.Time
}
// Cache - simple implementation of cache
// More information: https://en.wikipedia.org/wiki/Time_to_live
type Cache struct {
timeTTL time.Duration
cache map[string]*entry... |
// Benchmark for memcache servers.
//
// Supports simultaneous benchmarking of multiple servers.
package main
import (
"flag"
"fmt"
memcache_org "github.com/bradfitz/gomemcache/memcache"
memcache_new "github.com/valyala/ybc/libs/go/memcache"
"github.com/vharitonsky/iniflags"
"log"
"math/rand"
"runtime"
"strin... |
package daily_notifications
import (
"testing"
"time"
)
func TestParsingStringTime(t *testing.T) {
assertParsedTimeError(t, "00")
assertParsedTimeError(t, "")
assertParsedTime(t, "00:00", 0)
assertParsedTime(t, "00:01", 60)
assertParsedTime(t, "01:00", 3600)
assertParsedTime(t, "23:59", 23*60*60+59*60)
}
fun... |
package models
import (
"api/utils"
"fmt"
)
func Fetchsingers() (artists []Artist, err error) {
var artist Artist
db, err := utils.Connecttodb()
if err != nil {
fmt.Println("unable to connect todb")
return
}
query := "select * from artist"
rows, err := db.Query(query)
if err != nil {
fmt.Println("unabl... |
package main
import (
"iv-code-challenge/api/db"
"iv-code-challenge/api/services"
"iv-code-challenge/api/server"
"log"
)
func main() {
var err error
session, err := db.NewSession()
if err != nil {
log.Fatalln("unable to connect to mongodb")
}
ss := services.NewSubmissionService(session.Copy(), "submissi... |
package bid
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gookit/gcli/v3"
dcli "github.com/ovrclk/akash/x/deployment/client/cli"
"github.com/ovrclk/akash/x/market/client/cli"
"github.com/ovrclk/akash/x/market/types"
"github.com/ovrclk/akcmd/client"
"github.com/ovrclk/akcmd/flags"
)
func TxCmd()... |
package scraper
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/gocolly/colly"
"github.com/yevhenshymotiuk/ekatalog-scraper/items"
)
func removeSpaces(s string) string {
return strings.ReplaceAll(s, "\u00a0", "")
}
func trimCapacitySuffix(s string) string {
return s... |
package main
import (
"fmt"
"github.com/mmcdole/gofeed"
"time"
"os"
"github.com/anaskhan96/soup"
)
func getItems(url string, after time.Time) (items []gofeed.Item, err error) {
fp := gofeed.NewParser()
feed, err := fp.ParseURL(url)
if err != nil {
return items, err
}
for _, item := range feed.Items {
... |
package network
import (
"fmt"
"net"
linuxproc "github.com/c9s/goprocinfo/linux"
)
type Address struct {
IP string
Mask string
}
type Iface struct {
Name string
Mac string
Addrv4 []*Address
Addrv6 []*Address
MTU int
Stat *linuxproc.NetworkStat
}
const procNetDevPath = "/proc/net/dev"
func N... |
package proxy
import (
"context"
"net/http"
"github.com/rs/xid"
log "github.com/sirupsen/logrus"
)
// Middleware is a function that accepts allows to add additional behavior to the request processing cycle
// Middleware should return new http.Handler, that calls the http.Handler that was passed to it as `next` p... |
package main
import (
"fmt"
"sort"
)
func main() {
numEls, number, q1, q2, q3 := 0, 0, 0, 0, 0
count := make(map[int]int)
var nums []int
var numbers []int
fmt.Scanf("%d", &numEls)
for i := 0; i < numEls; i++ {
fmt.Scanf("%d", &number)
nums = append(nums, number)
}
for i := 0; i < numEls; i++ {
fmt.Sca... |
package sound
import (
"errors"
"fmt"
"github.com/rmcsoft/hasp/events"
)
type SoundCapturedEventData struct {
AudioData *AudioData
}
const (
SoundCapturedEventName = "SoundCaptured"
)
// NewSoundCapturedEvent creates HotWordDetectedEvent
func NewSoundCapturedEvent(audioData *AudioData) *events.Event {
return... |
package service
import (
"sixedu/model"
// "fmt"
)
type AuthService struct {}
func (a *AuthService) Register(username,password string,age int, sex string) bool {
user := model.NewUser()
user.SetUsername(username)
user.SetPassword(password)
user.SetAge(age)
user.SetSex(sex)
user.Save()... |
/*
Copyright 2021 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 graphql
import (
"encoding"
"fmt"
"reflect"
"strings"
)
const TAG = "json"
// can't take recursive slice type
// e.g
// type Person struct{
// Friends []Person
// }
// it will throw panic stack-overflow
func BindFields(obj interface{}) Fields {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
fields... |
package server
import (
"errors"
"net/http"
"github.com/Tanibox/tania-core/src/tasks/domain"
"github.com/Tanibox/tania-core/src/tasks/storage"
"github.com/gofrs/uuid"
"github.com/labstack/echo/v4"
)
func (s *TaskServer) SaveToTaskReadModel(event interface{}) error {
taskRead := &storage.TaskRead{}
switch e ... |
package main
import (
"encoding/json"
"strings"
"testing"
)
func TestCorrectMarshaling(t *testing.T) {
testJSONString := `
{
"ImageUUID": "yolo",
"userUUID": "user",
"url": "url",
"imageScale" : "ORIGINAL"
}
`
var imageUpdate ImageUpdate
err := json.Unmarshal([]byte(testJSONString), &imageUpd... |
package trident
import (
"errors"
pf "trident.li/pitchfork/lib"
)
type TriUser interface {
pf.PfUser
IsNominator(ctx pf.PfCtx, nom_name string) (ok bool)
BestNominator(ctx pf.PfCtx) (nom_name string, err error)
}
type TriUserS struct {
pf.PfUser `pfset:"self" pfget:"self"`
}
func NewTriUser() pf.PfUser {
re... |
package virtual_security
import (
"reflect"
"testing"
"time"
)
type testClock struct {
iClock
now1 time.Time
getStockSession1 Session
getStockSessionHistory []time.Time
getSession1 Session
getBusinessDay1 time.Time
}
func (t *testClock) now() time.Time { return t.no... |
package heap
import (
"fmt"
)
// Heap holds a heap array
type Heap struct {
arr []int
}
// New creates a new instance of heap
func New() *Heap {
return &Heap{
arr: make([]int, 0),
}
}
// Insert adds a new element to heap
func (h *Heap) Insert(data int) {
h.arr = append(h.arr, data)
size := len(h.arr)
i :... |
package main
import (
"fmt"
"github.com/containers/libpod/cmd/podman/cliconfig"
"github.com/containers/libpod/pkg/adapter"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var (
treeCommand cliconfig.TreeValues
treeDescription = "Prints layer hierarchy of an image in a tree format"
_treeCommand = &cobr... |
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string)
c2 := make(chan string)
go speed1(c1)
go speed2(c2)
fmt.Println("The first to arrive is:")
// select 在没有default分支情况时,会阻塞 直到有一分支满足条件
select {
case s1 := <-c1:
fmt.Println(s1)
case s2 := <-c2:
fmt.Println(s2)
//default:
// f... |
package gogit
import (
"encoding/json"
"fmt"
"github.com/NavenduDuari/goinfo/gogit/utils"
)
func getCodeFrequency(userName string) []utils.CodeFreqStruct {
repos := getRepos(userName)
fmt.Println("Repos => ", len(repos))
var codeFreqs []utils.CodeFreqStruct
go func() {
for _, repo := range repos {
codeFr... |
package kubemq_queue
import (
"fmt"
"time"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/printer"
)
func (k *KubeMQ) DisplayMessage(cliOpts *opts.CLIOptions, msg *records.ReadReco... |
package main
import db "test/database"
func main() {
defer db.SqlDB.Close()
router := initRouter()
router.Run(":8000")
}
|
package command
import (
"TskSch/msgQ"
"github.com/garyburd/redigo/redis"
"net/http"
"fmt"
"io/ioutil"
"runtime/debug"
"TskSch/mailer"
)
//SEARCHING FOR COMMAND BASED ON THE ID POPED FROM MSG QUEUE
func Search(c redis.Conn, cmd_id string,managerPath string, host string,name string) string {
... |
package _34_Find_First_and_Last_Position_of_Element_in_Sorted_Array
import (
"fmt"
"testing"
)
func TestSearchRange(t *testing.T) {
nums := []int{5, 7, 7, 8, 8, 10}
target := 8
fmt.Println(searchRange(nums, target))
}
func TestFindFirst(t *testing.T) {
nums := []int{5, 7, 7, 8, 8, 10}
target := 8
fmt.Println... |
package tgo
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
//获取配置文件优先级 mount_configs > configs
func configGet(name string, data interface{}, defaultData interface{}) (err error) {
absPath := getConfigPath(name)
var file *os.File
file, err = os.Open(absPath)
if err != nil {
UtilLogError(fmt.Sprintf("o... |
package main
import (
"bytes"
"go/format"
"regexp"
"strings"
"testing"
)
func TestGenerator_ReadFile(t *testing.T) {
g := newGenerator()
g.ReadFile("test/file1.go")
p := g.Package
if p.Name != "main" || p.Dir != "test" || p.File != "file1.go" || len(p.Structs) != 1 {
t.Errorf("invalid package: %v", p)
} e... |
package main
import (
"log"
"context"
"bufio"
"fmt"
"os"
"strings"
pb "../proto"
"google.golang.org/grpc"
)
func conectarNodo(ip string, port string) *grpc.ClientConn {
var conn *grpc.ClientConn
log.Printf("Intentando iniciar conexión con " + ip + ":" + port)
host := ip + ":" + port
conn, err := grpc.D... |
// Copyright 2015-2016 Sevki <s@sevki.org>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cc
import (
"fmt"
"strings"
"bldy.build/build/executor"
"bldy.build/build/racy"
"path/filepath"
)
type CLib struct {
Name ... |
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
var badPairs = []string{"ab", "cd", "pq", "xy"}
var vowels = []string{"a", "e", "i", "o", "u"}
func main() {
file, err := os.Open("../input")
if err != nil {
log.Fatalln("Cannot read file", err)
}
defer file.Close()
scanner := bufio.NewScanner(f... |
package task
import (
"bankBigData/BankServerJournal/db/query"
"bankBigData/BankServerJournal/entity"
"bankBigData/BankServerJournal/excel"
"bankBigData/_public/util"
"gitee.com/johng/gf/g"
"gitee.com/johng/gf/g/util/gconv"
"github.com/360EntSecGroup-Skylar/excelize"
)
var iStartPage = 2
const infoSheetName =... |
package main
import (
"encoding/json"
"fmt"
)
type response1 struct {
Page int
Fruits []string
}
type resposne2 struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
func main() {
res1D := &response1{
Page: 1,
Fruits: []string{"apple", "peach", "pear"},
}
res1B, _ := json.Marshal... |
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
//好像需要go build操作
//文件写操作 os.OpenFile
//func OpenFile(name string,flg int,perm FileMode)(*File,error){ perm FileMode是文件权限
//}
//os.O_CREATE表示没有该文件会创建该文件,os.O_APPEND表示直接在以前的基础上面添加新内容 0644表示八进制的权限
//os.O_TRUNC 表示每次写都清理之前的文件
func writedem1(){
fileobj,err:=... |
package trylock_test
import (
"testing"
"github.com/chappjc/trylock"
)
func TestExample(t *testing.T) {
var mu trylock.Mutex
t.Log(mu.TryLock())
t.Log(mu.TryLock())
mu.Unlock()
t.Log(mu.TryLock())
// Output:
// true
// false
// true
}
|
/*
Package coinbase_api is a Go interface to the CoinBase.com
API. It may be used to design automated Bitcoin trading
systems.
Currently implemented endpoints:
* get account balance
* get receive address
* get exchange rate
* purchase bitcoins
* sell bitcoins
The... |
package main //nolint:testpackage
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const staticTestPath = "headlamp_testdata/static_files/"
// Is supposed to return the index.html if there is no static file.
func TestSpaHandlerMissing(t *testing.T) {
req, err := http.NewRequest("GET", "/headlampxxx... |
package cron
import (
"github.com/spf13/cobra"
)
func NewCronWorkflowCommand() *cobra.Command {
var command = &cobra.Command{
Use: "cron",
Short: "manage cron workflows",
Run: func(cmd *cobra.Command, args []string) {
cmd.HelpFunc()(cmd, args)
},
}
command.AddCommand(NewGetCommand())
command.AddCom... |
package models
import (
"github.com/astaxie/beego/orm"
)
type CameraOnlineStat struct {
Id int `orm:"column(id);auto;pk"`
BeforeTime string `orm:"column(beforetime);size(32)"`
AfterTime string `orm:"column(aftertime);size(32)"`
OnlineNum int `orm:"column(onlinenumber)"`
Offline... |
package schema
import (
"github.com/facebook/ent/dialect"
"github.com/facebook/ent"
"github.com/facebook/ent/schema/field"
)
// UserAccount holds the schema definition for the UserAccount entity.
type UserAccount struct {
ent.Schema
}
// Mixin of the UserAccount.
func (UserAccount) Mixin() []ent.Mixin {
return... |
package main
import "fmt"
func main() {
var avg, grade int
fmt.Scanf("%d", &grade)
fmt.Scanf("%d", &avg)
fmt.Println(avg*2 - grade)
}
|
package mid
import (
"net/http"
"github.com/Yangshuting/golang_model/lib"
"github.com/Yangshuting/golang_model/model"
"github.com/Yangshuting/golang_model/storage"
"github.com/labstack/echo"
"gopkg.in/mgo.v2/bson"
)
func AuthMid(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
... |
package environment
import "github.com/go-playground/validator/v10"
type Sqlite struct {
DatabaseName string `envconfig:"SQLITE_DATABASE" validate:"required"`
}
func (s Sqlite) IsValid() bool {
return validator.New().Struct(s) == nil
}
|
package cli
import (
"flag"
"fmt"
"os"
"github.com/neil-berg/blockchain/blockchain"
)
// CLI is the command line interface shape
type CLI struct {
Chain *blockchain.Blockchain
}
func (cli *CLI) printUsage() {
fmt.Println("Error parsing CLI commands. \nCLI usage:")
fmt.Println("\taddblock --data <some data>")... |
package main
import (
"context"
"database/sql"
"log"
"time"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:root@tcp(db:3306)/testDB")
if err != nil {
log.Fatal("error in connecting to DB:", err)
}
//db.SetConnMaxLifetime()
db.SetMaxOpenConns(100)
defer db.Close()
... |
package logger
/**
* Created by Zf_D on 2015-02-28
*/
import (
"fmt"
"log"
"os"
"runtime"
"strings"
"strconv"
"time"
"sync"
"io"
)
const (
_ = iota //日志等级
Lv_Debug //1
Lv_Info //2
Lv_Warn //3
Lv_Error //4
)
const (
_ = int64(1) << (iota * 10) //大小
KB ... |
package public
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/shopspring/decimal"
"github.com/tealeg/xlsx"
"strings"
"tpay_backend/merchantapi/internal/common"
"tpay_backend/model"
"tpay_backend/utils"
"tpay_backend/merchantapi/internal/svc"
"tpay_backend/merchantapi/internal/types"
"gith... |
package todolist
type Store interface {
Initialize()
LoadPending() ([]*Todo, error)
LoadArchived() ([]*Todo, error)
LoadBacklog(filepath string) ([]*Todo, error)
GetBacklogFilepath() string
AppendBacklog(filepath string, todos []*Todo)
DeleteBacklog(filepath string)
Save(todos []*Todo)
Import(filepath string)... |
package render
import (
"net/http"
)
// html渲染器
type HtmlRender struct {
}
// 渲染
func (htmlRender HtmlRender) Render(write http.ResponseWriter, result Result) {
write.Header().Set("Content-Type", "text/html")
write.WriteHeader(result.code)
write.Write([]byte(result.data.(string)))
}
|
package p2p
import (
"sync"
"testing"
)
func TestDispatcher(t *testing.T) {
dp := NewDispatcher()
sb := NewSubscriber("", make(chan *Message, 128), false, "test")
types := sb.MessageType()
dp.Register(sb)
mt, _ := dp.subscribersMap.Load(types)
if mt == nil {
t.Fatal("register fail")
}
dp.Deregister(sb)
m... |
package Observer
import (
"sync"
"testing"
"time"
)
func TestFib(t *testing.T) {
//for x:= range Fib(10){
// fmt.Println(x)
//}
n := eventSubject{Observers:sync.Map{}} //如关注的微博主更新微博
obs1 := eventObserver{ID:1,Time:time.Now()}
obs2 := eventObserver{ID:2,Time:time.Now()}
n.AddListener(obs1)
n.AddListener(... |
package scanner
import (
"bytes"
"fmt"
"path/filepath"
"strconv"
"strings"
"unicode/utf8"
"go/token"
"h12.io/gombi/scan"
)
const (
ScanComments Mode = 1 << iota // return comments as COMMENT tokens
dontInsertSemis // do not automatically insert semicolons - for testing only
)
var newl... |
package postgres
import (
"github.com/google/uuid"
"github.com/neuronlabs/neuron-core/config"
"github.com/neuronlabs/neuron-core/repository"
"github.com/neuronlabs/neuron-postgres/internal"
"github.com/neuronlabs/neuron-postgres/log"
)
var _ repository.Factory = &Factory{}
// Factory is the pq.Postgres factor... |
package sc
import (
"context"
"fmt"
"net"
"time"
)
type Container struct {
Name string
Hostname string
Active bool
IPChange bool
Addresses []net.IP
LastAddresses []net.IP
Verbose bool
}
func New(name, hostname string, verbose bool) Container {
res := Container{
name,... |
package master
import (
"github.com/OHopiak/fractal-load-balancer/core"
"github.com/labstack/echo/v4"
"net/http"
)
func (m *Master) RegisterWorker(request *core.RegisterWorkerRequest, ip string) *core.RegisterWorkerResponse {
worker, err := m.AddWorker(core.Host{
IP: ip,
Port: request.Port,
})
if err != ... |
// defer,panic,recover使用
package main
import "fmt"
func main() {
// a
// c
// d
// panic: 55
// goroutine 1 [running]:
// main.f()
// /donnol/Project/Golang/src/jdscript.com/day_test/2017_02_23/main.go:40 +0xd1
// main.panicDefer()
// /donnol/Project/Golang/src/jdscript.com/day_test/2017_02_23/main.go:24 ... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//6. ZigZag Conversion
//The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this ... |
// Copyright (c) 2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"io/ioutil"
"log"
"math/rand"
"os"
"os/exec"
"path/filepath"
"runtime"
"sync"
"time"
rpc "github.com/conformal/btcrpcclient"
"github.com/con... |
package command
import (
"context"
"time"
constant "github.com/angryronald/guestlist/internal/guest"
"github.com/angryronald/guestlist/internal/guest/domain/service/guest"
"github.com/angryronald/guestlist/internal/guest/public"
)
// GuestArrivedCommand encapsulate process for guest arrives in Command
type Gues... |
//author xinbing
//time 2018/9/4 15:42
package utilities
import (
"fmt"
"testing"
)
func TestGetRandomNumStr(t *testing.T) {
fmt.Println(GetRandomStr(32))
fmt.Println(GetRandomNumStr(32))
}
|
package melee
import (
"encoding/csv"
"github.com/realm/realm-server/items"
"github.com/realm/realm-server/items/weapons"
)
// resolveGrip resolves a given string to an EGrip.
func resolveGrip(str string) EGrip {
return grips[str]
}
// ParseCSV parses a csv file into an array of melee items.
func ParseCSV(reade... |
package tunnel
import (
"bytes"
"crypto/sha1"
"encoding/binary"
"fmt"
"io"
"net"
)
func sendMessage(conn net.Conn, flag Flag, data []byte) (err error) {
buf := bytes.NewBuffer(nil)
buf.WriteByte(1)
buf.WriteByte(byte(flag))
dl := uint32(len(data))
if dl > 0 {
len := make([]byte, 4)
binary.LittleEndian... |
package server
import (
"log"
"net"
"orm/ormpb"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
type Server struct {
s *grpc.Server
}
type UserBoilerOrm struct {
ormpb.UserServiceServer
}
func New(useReflection bool) *Server {
s := grpc.NewServer()
ormpb.RegisterUserServiceServer(s, &UserB... |
package web
import (
"fmt"
"github.com/dgrijalva/jwt-go"
fiber "github.com/gofiber/fiber/v2"
jwtware "github.com/gofiber/jwt/v2"
"github.com/google/uuid"
"github.com/iamtraining/forum/entity"
)
type SessionData struct {
Form interface{}
User entity.User
LoggedIn bool
}
func (h *Handler) Extract(c *... |
package main
import (
"fmt"
"github.com/Wan-Mi/RPCDemos/thriftDemo/hello"
"net"
"os"
"git.apache.org/thrift.git/lib/go/thrift"
)
func main() {
transportFactory := thrift.NewTBufferedTransportFactory(8192)
protocolFactory := thrift.NewTCompactProtocolFactory()
transport, err := thrift.NewTSocket(net.JoinH... |
package factoryreset
import (
"errors"
"os"
"github.com/rancher-sandbox/rancher-desktop/src/go/privileged-service/pkg/manage"
"github.com/sirupsen/logrus"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc"
)
const svcName = "RancherDesktopPrivilegedService"
// stopPrivilegedService will stop the Ranche... |
// Copyright © 2021 Attestant Limited.
// 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 ... |
// uji coba ambil data dari newsapi org kategori bisnis
package main
import (
"io/ioutil"
//"log"
"net/http"
"NewsAPISPE/consume/models"
"encoding/json"
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main(){
response, err := http.Get("https://newsapi.org/v2/top-headlines?apikey=6bc3cbc8dcf3... |
package tls
import (
"crypto/x509"
"crypto/x509/pkix"
"net"
"github.com/pkg/errors"
"github.com/openshift/installer/pkg/asset"
"github.com/openshift/installer/pkg/asset/installconfig"
)
// KubeAPIServerToKubeletSignerCertKey is a key/cert pair that signs the kube-apiserver to kubelet client certs.
type KubeAP... |
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/joho/godotenv"
"github.com/syndtr/goleveldb/leveldb"
tgbotapi "gopkg.in/telegram-bot-api.v1"
)
// Bot create bot with few useful methods
type Bot struct {
API *tgbotapi.BotAPI
Subscriptions []*Subscription
DB *leve... |
// Copyright 2023 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 saucecloud
import (
"fmt"
"strings"
"github.com/saucelabs/saucectl/internal/job"
"github.com/saucelabs/saucectl/internal/testcafe"
)
// TestcafeRunner represents the SauceLabs cloud implementation
type TestcafeRunner struct {
CloudRunner
Project testcafe.Project
}
// RunProject runs the defined tests ... |
package dbft
const (
TABLE_POS_VOTE = "pos_vote"
TABLE_POS_ASSET = "pos_asset"
TABLE_EPOCH_INFO = "epoch_info"
POS_VOTE_VOTE_ID = "vote_id"
POS_VOTE_TXID = "txid"
POS_VOTE_ACCOUNT_ID = "account_id"
POS_VOTE_PEERID = "peerid"
POS_VOTING_POWER = "voting_power"
POS_VOTE_EPOCH = "vote_epo... |
package planet
import (
"upper.io/db"
)
// Get Feed Service
func GetFeedService(db db.Database) Service {
return &BasicService{
Db: db,
name: "feed",
idName: "id",
}
}
// Get Feed Item Service
func GetFeedItemService(db db.Database) Service {
return &BasicService{
Db: db,
name: "item",
i... |
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"github.com/awalterschulze/gographviz"
address "github.com/hashicorp/go-terraform-address"
tfjson "github.com/hashicorp/terraform-json"
)
func newPlan(planInput io.Reader) (*tfjson.Plan, error) {
parsed := &tfjson.Plan{}
dec := json.NewDecoder... |
package auth
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
"github.com/gofor-little/xerror"
)
// ForgotPassword will initiate a forgot password request.
//
// - Use auth.ChangePassword and auth.ChangePasswordConfirm to update a user's passwor... |
package main
import "github.com/slawek87/GOstorageClient/example"
func main() {
example.Example()
}
|
package hquery
import (
"errors"
"strings"
"github.com/kirillrdy/nadeshiko/html"
"github.com/sparkymat/webdsl/css"
)
type Selection struct {
rootNode html.Node
selector css.Selector
}
func Select(node html.Node, selector css.Selector) Selection {
return Selection{rootNode: node, selector: selector}
}
func (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.