text stringlengths 11 4.05M |
|---|
package infrastructure
import (
"cleanarchitecture/adapter/controller"
"cleanarchitecture/adapter/interfaces"
"github.com/jinzhu/gorm"
"github.com/labstack/echo"
"github.com/spf13/viper"
)
type CustomContext struct {
echo.Context
}
func Router(dbConn *gorm.DB) {
e := echo.New()
logger := &Logger{}
e.Use( ... |
package gotest
import (
"testing"
)
//单元测试,debug 的时候注意打好断点,F11
func Test_Division(t *testing.T) {
if i, e := Division(6, 2); i != 3 || e != nil {
t.Error("Division除法测试不通过!")
} else {
// 记录一些日志
t.Log("Dvicesion 测试通过!")
t.Log("i:", i)
}
}
//性能测试
func Benchmark_Division(b *testing.B) {
for i := 0; i < b.N... |
package handlers
import (
"fmt"
"net/http"
"net/http/httputil"
)
type Headers struct {
}
func (p *Headers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
dump, err := httputil.DumpRequest(r, true)
if err != nil {
w.Write([]byte(err.Error()))
}
fmt.Fprintf(w, "%q", dump)
// w.Write(dump)
}
|
package main
import "fmt"
func main() {
a:="store in a"
//b:="store in b" 没引用会一直报错
fmt.Println(a)
}
|
package main
import (
"fmt"
"log"
"net"
"os"
"path/filepath"
"runtime/debug"
"syscall"
"time"
"golang.org/x/sys/unix"
)
var (
ReconfigureDomainSocket = "listener.sock"
TransferListenDomainSocket = "listener.sock"
TransferConnDomainSocket = "conn.sock"
)
func init() {
absPath, _ := filepath.Abs(os.Ar... |
// Copyright 2018 xgfone
//
// 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 writi... |
package gohub_test
import (
"http"
"url"
. "launchpad.net/gocheck"
"fmt"
"os"
"testing"
"time"
)
func Test(t *testing.T) {
TestingT(t)
}
type HTTPSuite struct {}
var testServer = NewTestHTTPServer("http://localhost:4444", 5e9)
func (s *HTTPSuite) SetUpSuite(c *C) {
testServer.Start()
}
func (s *HTTPSuite... |
package cryptpass
import (
"bufio"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"errors"
"os"
)
const (
ikey = "WueIirKvsQpSc6x3ZSHd5g=="
iiv = "1PNr7RSgUy2ITtD/iEJGOg=="
)
var (
PassPath = "/etc/cryptpass.key"
ErrLengthNotMatch = errors.New("length not match")
)
var (
masterKey []byte
ma... |
package model
import (
"encoding/json"
"github.com/caos/logging"
es_models "github.com/caos/zitadel/internal/eventstore/models"
"github.com/caos/zitadel/internal/project/model"
)
type Application struct {
es_models.ObjectRoot
AppID string `json:"appId"`
State int32 `json:"-"`
Name s... |
package eventchannel
import (
"bytes"
"compress/gzip"
"sync"
"time"
"github.com/benbjohnson/clock"
"github.com/golang/glog"
)
type Metrics struct {
bufferSize int64
eventCount int64
}
type Limit struct {
maxByteSize int64
maxEventCount int64
maxTime time.Duration
}
type EventChannel struct {
gz... |
package main
import (
"fmt"
"sort"
)
func main() {
var n, k int
fmt.Scan(&n, &k)
var major []int
var minor []int
for i := 0; i < n; i++ {
var luck, importance int
fmt.Scan(&luck, &importance)
if importance == 1 {
major = append(major, luck)
} else {
minor = append(minor, luck)
}
}
sort.Int... |
package builder
import (
"strings"
"github.com/chenwj93/utils"
)
type Where struct {
where string
sqlRet string
paramWhere []interface{}
paramIn []interface{}
}
func (t *Where) GetWhere() *Where {
if strings.TrimSpace(t.where) != utils.EMPTY_STRING {
t.sqlRet += " where " + t.where[4:]
}
retu... |
package goz
import (
"reflect"
"testing"
)
func TestNewRoute(t *testing.T) {
expectedID := "/hello"
expectedTypeOfChildren := "map[string]*goz.Route"
expectedTypeOfHandlers := "map[string]goz.GoAppHandlerFunc"
expectedTypeOfVariableMap := "map[string]map[string]string"
route := NewRoute(expectedID)
if expec... |
// Copyright 2020 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package iw
import (
"context"
"sync"
"time"
"chromiumos/tast/dut"
"chromiumos/tast/errors"
"chromiumos/tast/testing"
)
// EventLogger captures events on a WiFi inter... |
// This file demonstrate how to sort values in Go.
package tips
import (
"sort"
"testing"
)
type person struct {
name string
age int
}
type byAge []person
func (a byAge) Len() int { return len(a) }
func (a byAge) Less(i, j int) bool { return a[i].age < a[j].age }
func (a byAge) Swap(i, j int) {... |
package main
/*
type cal struct{}
func (cal) hello() {
fmt.Println("Hello word")
}
*/
func main() {
server := NewServer(":3000")
server.Handle("POST", "/login", CheckAut)
server.Handle("POST", "/valida", ValidaToken)
server.Handle("POST", "/valida", server.AddMiddleware(prueba, CheckAuth()))
server.Handle("G... |
package desync
import "fmt"
type Store interface {
GetChunk(id ChunkID) ([]byte, error)
fmt.Stringer
}
|
package shoppingCartController
import (
"github.com/gin-gonic/gin"
"hd-mall-ed/packages/client/models/shoppingCartModel"
"hd-mall-ed/packages/common/pkg/app"
"hd-mall-ed/packages/common/pkg/e"
"strconv"
)
// 参数 type
func GetList(c *gin.Context) {
api := app.ApiFunction{C: c}
// 必须要 type 参数
model := &shopping... |
package word_test
import (
"testing"
"github.com/edipermadi/arabic/pkg/word"
"github.com/edipermadi/unicode"
"github.com/stretchr/testify/require"
)
func TestWord_Parse(t *testing.T) {
src := word.New("كَتَبَ")
dst := src.Cleanup()
require.Equal(t, []rune{unicode.ArabicLetterKaf, unicode.ArabicLetterTeh, unic... |
package wechat_brain
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"os/exec"
"strconv"
"time"
"github.com/coreos/goproxy"
)
var (
_spider = newSpider()
Mode int
AutoMatic int
)
type spider struct {
proxy *goproxy.ProxyHttpServer
}
func Run(port string, mode, automatic int) {
Mode = mode
AutoMa... |
// Copyright 2022 The gVisor 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 agree... |
package c78
//给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
//
// 说明:解集不能包含重复的子集。
//
// 示例:
//
// 输入: nums = [1,2,3]
//输出:
//[
// [3],
// [1],
// [2],
// [1,2,3],
// [1,3],
// [2,3],
// [1,2],
// []
//]
// Related Topics 位运算 数组 回溯算法
//leetcode submit region begin(Prohibit modification and deletion)
/*
思路1:遍历插入子集
... |
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package transactionrecord_test
import (
"crypto/rand"
"os"
"testing"
"golang.org/x/crypto/ed25519"
"github.com/bitmark-inc/bitmarkd/account"... |
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"os"
"vrcdb/httpServer"
)
type JsonConfig struct {
HttpPort uint16 `json:"http_port"`
MongoDB struct {
Host string `json:"host"`
Username string `json:"username"`
Password string `json:"password"`
} `json:"mongodb"`
}
func ReadConfi... |
package db
import (
"context"
"log"
"time"
"NokiaAssesmentGo/utils"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var client *mongo.Client
// CreatePersonEndpoint will insert data into DB
func CreatePersonEndpoint(person utils.Person) *m... |
/*
Copyright 2021 The KodeRover 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, s... |
// Package matcher provides matching positioning messages to a set of filtering rules
// and pereating messages to a topic in case of they are matched.
package matcher
import (
"encoding/json"
"errors"
"github.com/lvl484/positioning-filter/position"
"github.com/lvl484/positioning-filter/repository"
)
const (
Er... |
package array_memory
import (
"testing"
"math/big"
)
func TestSetGet(t *testing.T) {
mySummer := NewMemArray()
myArray := [][2]*big.Int{ { big.NewInt(1), big.NewInt(1)}, {big.NewInt(1) , big.NewInt(2)}, {big.NewInt(3), big.NewInt(4)} }
result := mySummer.SumArray(myArray)
res1 := result[0].Uint64()
if 5 !... |
package plex
import (
"net/http"
)
// BasicAuthTransport is an http.RoundTripper that authenticates all requests
// using HTTP Basic Authentication with the provided username and password.
type PlexAuthTransport struct {
XPlexToken string // X-Plex-Token
// Transport is the underlying HTTP transport to use when m... |
package crawler
import "log"
import "os"
import "strings"
import "net/url"
import "net/http"
import "github.com/ernesto-jimenez/emit_urls/url_extractor"
func Crawl(initial_url string, channel chan FoundURL, logfile string) {
parsedUrl, _ := url.Parse(initial_url)
var output *os.File
switch logfile {
case "/de... |
// Copyright 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package group
import (
"context"
"sync"
"github.com/upfluence/pkg/multierror"
)
type waitGroup struct {
ctx context.Context
fn context.CancelFunc
mu sync.Mutex
errs []error
wg sync.WaitGroup
}
func WaitGroup(ctx context.Context) Group {
var cctx, fn = context.WithCancel(ctx)
return &waitGroup{ctx: c... |
package logif
import (
"errors"
"strings"
)
// Logging level constants
const (
LevelDebug = iota
LevelInfo
LevelWarning
LevelError
)
// ErrNoSuchLogLevel is thrown when a parse
var ErrNoSuchLogLevel = errors.New("no such log level")
// LogLevelString returns the name representation of a given log level int
fu... |
package printers
import (
"fmt"
"html/template"
"io"
"log"
"sort"
"strconv"
"strings"
"time"
containers "github.com/ernoaapa/eliot/pkg/api/services/containers/v1"
node "github.com/ernoaapa/eliot/pkg/api/services/node/v1"
pods "github.com/ernoaapa/eliot/pkg/api/services/pods/v1"
"github.com/ernoaapa/eliot/... |
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"runtime"
"github.com/golang/glog"
"github.com/spf13/pflag"
"github.com/urfave/negroni"
"kolihub.io/koli/pkg/git/conf"
gitserver "kolihub.io/koli/pkg/git/server"
gitutil "kolihub.io/koli/pkg/git/util"
"kolihub.io/koli/pkg/version"
... |
package ha
var HtmlPage = `
<h2>High Availability</h2>
<table class="responsive-table highlight">
<thead>
<tr>
<th>Namespace</th>
<th>Name</th>
<th>Type</th>
<th>Replicas</th>
<th>Rollout Strategy</th>
... |
//go:generate mockgen -destination mock/enable_service.go . EnableServiceHandler
package handlers
import (
"context"
"github.com/raba-jp/primus/pkg/cli/ui"
"github.com/raba-jp/primus/pkg/exec"
"golang.org/x/xerrors"
)
type EnableServiceHandler interface {
EnableService(ctx context.Context, dryrun bool, name st... |
package main
import (
"bufio"
"fmt"
"io"
"os"
"sort"
"strconv"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
f, err := os.Open("day10/input.txt")
check(err)
r:= bufio.NewReader(f)
nums,_ := ReadInts(r)
nums=append(nums, 0)
sort.Ints(nums)
lastItem := nums[len(nums)-1]
nums=append(n... |
/*
1) Create a new type: vehicle. The underlying type is a struct.
The fields: doors, color. Create two new types: truck & sedan.
The underlying type of each of these new types is a struct.
Embed the “vehicle” type in both truck & sedan.
Give truck the field “fourWheel” which will be set to bool.
Give sedan the field “... |
package adapter
import (
"fmt"
"regexp"
"strconv"
"github.com/ikmski/git-lfs3/usecase"
)
type transferController struct {
transferService usecase.TransferService
}
// TransferController is ...
type TransferController interface {
Download(ctx Context)
Upload(ctx Context)
}
// NewTransferController is ...
fun... |
package orb
// MultiLineString is a set of polylines.
type MultiLineString []LineString
// GeoJSONType returns the GeoJSON type for the object.
func (mls MultiLineString) GeoJSONType() string {
return "MultiLineString"
}
// Dimensions returns 1 because a MultiLineString is a 2d object.
func (mls MultiLineString) Di... |
package bus
import (
"context"
"fmt"
"sync"
"time"
)
// TxOptions 事务配置
type TxOptions struct {
Context context.Context
// Timeout 事务处理时长
// 启用事务的消息不会立即发布给消费者
// 当本地事务回调执行返回true才会正式发布
// 详见事务流程图 ./tx_flow.png
Timeout time.Duration
// EnsureFunc 事务完成确认
// 请一定要注意布尔返回值的代表含义
// 若返回值为true则表示事务已处理, 发布消息
// 若返... |
package webx
import (
"io"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/golang/glog"
"github.com/shestakovda/errx"
)
var ErrMsgMustBeAbs = "Базовый URL должен быть абсолютным"
var defClient = &http.Client{
Timeout: time.Minute,
}
func newRequestV1(base string, args []Option) (req ... |
package core
import (
"fmt"
"log"
"path/filepath"
homedir "github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"github.com/skatsuta/athenai/exec"
"gopkg.in/ini.v1"
)
const (
defaultDir = ".athenai"
defaultConfigFile = "config"
)
// Config is a configuration information.
type Config struct {
De... |
package main
var PodInfoTemplate string = `
Podname: {{.Name}}
========================
Master: {{.MasterIP}}:{{.MasterPort}}
Quorum: {{.Quorum}}
Auth Token: {{.Authpass}}
Known Sentinels: {{ range .KnownSentinels }}
{{.}}
{{ end }}
Known Slaves: {{ range .KnownSlaves }}
{{.}}
{{ end }}
Settings: {{ range $k,$v := .... |
package mr
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"sort"
"sync"
)
import "log"
import "net/rpc"
import "hash/fnv"
//
// Map functions return a slice of KeyValue.
//
type KeyValue struct {
Key string
Value string
}
//
// use ihash(key) % NReduce to choose the reduce
// task number for each KeyValue... |
// 07 CGroup
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"syscall"
)
func main() {
switch os.Args[1] {
case "run":
run()
case "child":
child()
default:
panic(fmt.Sprintf("Unknow command %s", os.Args[1]))
}
}
func run() {
cmd := exec.Command("/proc/self/exe", ap... |
package main
import (
"fmt"
"log"
"os"
"text/template"
)
type artifactClass struct {
Id string
Name string
Effect string
LevelNames []string
}
var _artifacts = []artifactClass{
{
Id: "puzzle_cube",
Name: "Puzzle cube",
Effect: "Lowers research costs",
LevelNames: ... |
package helpers
import (
"encoding/binary"
"math/big"
"math/rand"
"sync"
"time"
"github.com/dbogatov/fabric-amcl/amcl"
)
// RandomBytes ...
func RandomBytes(prg *amcl.RAND, n int) (bytes []byte) {
bytes = make([]byte, n)
for i := 0; i < n; i++ {
bytes[i] = prg.GetByte()
}
return
}
// PeerByHash ...
fu... |
package fitbuddy
import (
"fittgbot/internal/configuration"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"log"
)
type BotInstance struct {
BotAPI *tgbotapi.BotAPI
Configuration configuration.Configuration
UpdateConfig tgbotapi.UpdateConfig
}
func NewBot(conf configuration.Configuration, u... |
package cmd
import (
"context"
"fmt"
"io"
"net/http"
"os"
"github.com/calvinfeng/sling/handler"
//"github.com/calvinfeng/sling/stream"
"github.com/calvinfeng/sling/stream/broker"
//"github.com/calvinfeng/sling/stream/broker"
"github.com/gorilla/websocket"
"github.com/jinzhu/gorm"
"github.com/labstack/echo... |
// Copyright 2019 - 2022 The Samply Community
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... |
package file
import (
"os"
"syscall"
)
type Flock struct {
path string
file *os.File
}
func NewFlock(path string) *Flock {
return &Flock{path: path}
}
func (f *Flock) File() *os.File {
return f.file
}
func (f *Flock) Lock() error {
if f.file == nil {
if err := f.createOrOpenFile(); err != nil {
return ... |
package repositories
import (
"errors"
"strconv"
"github.com/auenc/simple-rest/models"
)
type InMemoryJobRepository struct {
Jobs []models.Job
}
func NewInMemoryJobRepository() *InMemoryJobRepository {
jobs := make([]models.Job, 0)
return &InMemoryJobRepository{
Jobs: jobs,
}
}
func (r *InMemoryJobReposit... |
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
/*
Copyright 2018 The Ceph-CSI 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, so... |
package api
import (
"contetto"
"html"
"log"
"net/http"
"service/app/middleware/auth"
"service/app/models"
"service/app/models/capability"
"service/app/models/role"
"service/app/services"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"gopkg.in/mgo.v2/bson"
)
const (
UserApiEndpoint = "/users"
)
... |
// Copyright (C) 2017 Google 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 t... |
package monitor
import (
"time"
"yunion.io/x/onecloud/pkg/apis"
)
type MonitorResourceJointListInput struct {
MonitorResourceId string `json:"monitor_resource_id"`
AlertId string `json:"alert_id"`
JointId []int64 `json:"joint_id"`
}
type MonitorResourceJointCreateInput struct {
apis.Meta... |
package database
import (
"macaddress_io_grabber/models"
"time"
)
type ApplicationRange struct {
ID uint64 `gorm:"primary_key"`
LeftBorder string `gorm:"column:l_border;type:varchar(100);not null;index:l_border_idx"`
RightBorder string `gorm:"column:r_border;type:varchar(100);not null;index:r_border_id... |
package main
//807. 保持城市天际线
//在二维数组grid中,grid[i][j]代表位于某处的建筑物的高度。 我们被允许增加任何数量(不同建筑物的数量可能不同)的建筑物的高度。 高度 0 也被认为是建筑物。
//
//最后,从新数组的所有四个方向(即顶部,底部,左侧和右侧)观看的“天际线”必须与原始数组的天际线相同。 城市的天际线是从远处观看时,由所有建筑物形成的矩形的外部轮廓。 请看下面的例子。
//
//建筑物高度可以增加的最大总和是多少?
//
//例子:
//输入: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
//输出: 35
//解释:
//Th... |
package mysql
import (
"github.com/jinzhu/gorm"
"github.com/void616/gm.mint.sender/internal/watcher/db/mysql/model"
gormigrate "gopkg.in/gormigrate.v1"
)
var migrations = []*gormigrate.Migration{
// initial
{
ID: "2019-09-27T10:08:24.153Z",
Migrate: func(tx *gorm.DB) error {
return tx.
... |
package adapter
import (
"fmt"
"regexp"
"strings"
"github.com/newrelic/infrastructure-agent/pkg/log"
metricpb "go.opentelemetry.io/proto/otlp/metrics/v1"
tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
resourcepb "go.opentelemetry.io/proto/otlp/resource/... |
package requests
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/atomicjolt/canvasapi"
"github.com/atomicjolt/canvasapi/models"
)
// ListAvatarOptions A paginated list of the possible user avatar options that can be set with the user update endpoint. The response will be... |
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package method
import (
"context"
"gm/manager"
"gm/param"
"shared/protobuf/pb"
"shared/utility/errors"
)
func (p *HttpPostHandler) MaintainSwitch(ctx context.Context, m *param.MaintainSwitch) error {
err := manager.Global.SetMaintainSwitch(ctx, m.Switch)
if err != nil {
return errors.WrapTrace(err)
}
_, e... |
package core
import (
"context"
"errors"
"time"
"github.com/bots-house/share-file-bot/pkg/secretid"
"github.com/volatiletech/null/v8"
)
// DocumentID it's alias for share id.
type DocumentID int
// Document represents shared document.
type Document struct {
// Unique ID of Document.
ID DocumentID
// Telegr... |
package p_00101_00200
// 119. Pascal's Triangle II, https://leetcode.com/problems/pascals-triangle-ii/
func getRow(rowIndex int) []int {
memo := make([][]int, rowIndex+1)
for i := range memo {
memo[i] = make([]int, i+1)
}
for j := 0; j < rowIndex+1; j++ {
memo[rowIndex][j] = getValue(rowIndex, j, memo)
}
re... |
package helmet
import (
"fmt"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// NoSniff applies header to protect your server from MimeType Sniffing
func NoSniff() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("X-Content-Type-Options", "nosniff")
}
}
// DNSPrefetchControl sets Pref... |
package ravendb
import (
"crypto/tls"
"crypto/x509"
"strings"
"sync"
"time"
)
// Note: Java's IDocumentStore is DocumentStore
// Note: Java's DocumentStoreBase is folded into DocumentStore
// DocumentStore represents a database
type DocumentStore struct {
// from DocumentStoreBase
onBeforeStore []func(*B... |
// Copyright 2020 Paul Greenberg greenpau@outlook.com
//
// 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 applic... |
package main
import (
"fmt"
"io/ioutil"
"regexp"
"strconv"
"strings"
)
func main() {
file, e := ioutil.ReadFile("day18/input.txt")
if e != nil {
panic(e)
}
fileString := string(file)
fileString = strings.Replace(fileString, " ", "", -1)
fileArray := strings.Split(fileString, "\n")
fmt.Println(run2(fileA... |
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/brotherlogic/goserver/utils"
"google.golang.org/grpc"
pbrc "github.com/brotherlogic/recordcollection/proto"
//Needed to pull in gzip encoding init
_ "google.golang.org/grpc/encoding/gzip"
)
func main() {
dServer, dPor... |
package main
// Person holds person information
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
var ExamplePerson Person
|
package main
import (
"fmt"
"sync"
)
func main() {
wg := &sync.WaitGroup{}
isFollow := true
ch := make(chan []int, 10)
for i := 0; i < 10; i++ {
wg.Add(1)
go func(i int, wg *sync.WaitGroup) {
ret := make([]int, 0)
if isFollow {
fmt.Println("isFollow:", isFollow)
}
ret = append(ret, i)
re... |
// Copyright 2014 Dirk Jablonowski. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lcd20x4
import (
"fmt"
"github.com/dirkjabl/bricker"
"github.com/dirkjabl/bricker/device"
"github.com/dirkjabl/bricker/net/packet"
misc "github.... |
package utils
import (
"syscall/js"
)
func Keys(obj js.Value) []string {
if !obj.Truthy() {
return nil
}
var (
keys = js.Global().Get("Object").Call("keys", obj)
slice = make([]string, keys.Length())
)
for i := 0; i < keys.Length(); i++ {
slice[i] = keys.Index(i).String()
}
return slice
}
|
package def
import (
"github.com/talesmud/talesmud/pkg/service"
)
// GameCtrl def
// interface for commands package to communicate back to game instance
type GameCtrl interface {
// Used to pass messages as events inside the mud server, e.g. translate a command into other user messages etc.
OnMessageReceived() ch... |
package util
import "testing"
func TestIsValidPortAsInt(t *testing.T) {
type args struct {
port int32
}
tests := []struct {
name string
args args
want bool
}{
{
name: "Returns false if port negative",
args: args{port: -1},
want: false,
},
{
name: "Returns false if port more than 49151",
... |
package mysql
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/spf13/viper"
)
var db *sqlx.DB
// Init 初始化MySQL连接
func Init() (err error) {
// "user:password@tcp(host:port)/dbname"
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&loc=Local",
viper.GetString("mysql... |
package main
import (
"fmt"
"time"
)
func Run6() {
//6. Trong golang mặc định thì thời gian dạng số được sử dụng với các loại mốc đơn vị nào?
fmt.Println("\n 6.")
t := time.Now()
fmt.Println("Năm, tháng, ngày, giờ, phút, giây, múi giờ")
fmt.Println(t)
}
|
package base
import (
"appdemo/errcode"
"crypto/md5"
"encoding/hex"
"encoding/json"
"strconv"
"strings"
"sync"
)
// RespHead shopapi返回结果头
type RespHead struct {
Code int `json:"code"`
Info string `json:"info"`
Desc string `json:"desc"`
Ext interface{} `json:"ext,omitempty"`
}
// Resp 返回... |
package network
import (
"testing"
)
func newDateComponent() Params {
params := Params{
Symbol: "goog",
StartDate: DateComponents{
Day: 1,
Month: 1,
Year: 2016,
},
EndDate: DateComponents{
Month: 1,
Day: 15,
Year: 2016,
},
}
return params
}
func TestDateComponents(t *testing.T) ... |
package structs
type Host struct {
ID int64
Host string
}
func (h Host) TableName() string {
return "adscoop_hosts"
}
type Hosts []Host
func (h *Hosts) FindAll() error {
return AdscoopsDB.Table("adscoop_hosts").Find(&h).Error
}
|
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package http
import (
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/candraalim/be_tsel_candra/config"
"github.com/candraalim/be_tsel_candra/internal/usecase/inquiry"
"github.com/candraalim/be_tsel_candra/internal/usecase/referral"
)
func setupRouter(serv... |
package main
import (
"fmt"
_ "unsafe"
"strconv"
)
func main() {
basic2string_1()
basic2string_2()
basic2string_3()
}
// 方法1:基本数据类型转字符串
func basic2string_1() {
var num1 int = 90
var num2 float64 = 23.456
var b bool = true
// var mychar byte = 'h'
var str string
str = fmt.Sprintf("%d", num1)
fmt.Printf(... |
/*
Copyright 2014 Huawei Technologies Co., Ltd. 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 la... |
package models
import "time"
type Video struct {
CreatedTime time.Time
Title string
Description string
SoftTags []string
Src string
Domain string
SHA256 string
Format string
} |
package ekatime
import "bytes"
var (
// _WeekdayStr is just English names of days of week.
_WeekdayStr = [...]string {
"Unknown",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
"Monday",
"Tuesday",
}
_WeekdayBytes = [len(_WeekdayStr)][]byte{}
)
// asPartOfDate returns current Weekday b... |
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
package netxmocks
import (
"context"
"crypto/tls"
"errors"
"net"
"reflect"
"testing"
)
func TestTLSHandshakerHandshake(t *testing.T) {
expected := errors.New("mocked error")
conn := &Conn{}
ctx := context.Background()
config := &tls.Config{}
th := &TLSHandshaker{
MockHandshake: func(ctx context.Context, ... |
package controllers
import (
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
"../models"
)
type UsersController struct {
model models.UserModel
}
func NewUsersController(app *mvc.Application) {
app.Handle(&UsersController{
model: models.UserModel{},
})
}
func (uc *UsersController) Get() mvc.Result ... |
package main
import (
"fmt"
)
func main() {
messages := make(chan string, 3)
go func() {
messages <- "100"
messages <- "200"
messages <- "300"
}()
fmt.Println(<-messages)
fmt.Println(<-messages)
fmt.Println(<-messages)
//fmt.Println(<-messages) //goroutines are asleep - deadlock
}
|
package missprop
import (
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "missprop",
Doc: Doc,
Run: run,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
},
}
const D... |
// Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package main
import (
"fmt"
"log"
"github.com/mvdan/fdroidcl"
"github.com/mvdan/fdroidcl/adb"
)
var cmdInstall = &Command{
UsageLine: "install <appid...>",
Short: "Install an app",
}
func init() {
cmdInstall.Ru... |
package logger
import (
"github.com/sirupsen/logrus"
"github.com/honeycombio/samproxy/config"
)
// LogrusLogger is a Logger implementation that sends all logs to stdout using
// the Logrus package to get nice formatting
type LogrusLogger struct {
Config config.Config `inject:""`
logger *logrus.Logger
level *l... |
// consolidate a LaTeX top-level source file into a single file in preparation
// for running through pandoc to generate an ePub.
package main
/*
Copyright (c) 2012 Kyle Isom <kyle@tyrfingr.is>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted... |
package service
import (
"context"
"strings"
"github.com/movsb/taoblog/modules/utils"
"github.com/movsb/taoblog/service/models"
"github.com/movsb/taorm/taorm"
)
func (s *Service) tags() *taorm.Stmt {
return s.tdb.Model(models.Tag{})
}
// GetTagByName gets a tag by Name.
func (s *Service) GetTagByName(name str... |
package common
import (
"bytes"
"crypto/rand"
"testing"
"github.com/ontio/ontology/common/serialization"
)
func BenchmarkZeroCopySource(b *testing.B) {
const N = 12000
buf := make([]byte, N)
rand.Read(buf)
for i := 0; i < b.N; i++ {
source := NewZeroCopySource(buf)
for j := 0; j < N/100; j++ {
source... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.