text stringlengths 11 4.05M |
|---|
// 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... |
package common
import (
"encoding/hex"
"encoding/json"
"fmt"
"testing"
)
func TestNewTransaction(t *testing.T) {
tx := new(Transaction)
tx.Txid = "hgs"
data, _ := json.Marshal(tx)
fmt.Println(hex.EncodeToString(data))
}
|
/*
A trivial application to illustrate how the blockartlib library can be
used from an application in project 1 for UBC CS 416 2017W2.
Usage:
go run art-app.go
*/
package main
// Expects blockartlib.go to be in the ./blockartlib/ dir, relative to
// this art-app.go file
import "./blockartlib"
import (
"crypto/x50... |
package main
import (
"context"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/husseinhammoud/cdktesting-backend/lib/models/API_Responses"
"github.com/husseinhammoud/cdktesting-backend/lib/models/Address"
)
type Event struc... |
package main
import (
"math/rand"
tl "github.com/JoelOtter/termloop"
)
func newStageTwo() *Stage {
const textGap = 100
var textCandidates = []string{
"Transformation",
"InfrastructureAsCode",
"ContinuousIntegration",
"ContinuousDeployment",
"Waterfall",
"Blockchain",
"Microservices",
"MachineLea... |
package mongomodel
import (
"time"
)
type DockModel struct {
View *DailyDockView
Typemap map[int]int
}
func NewDockModel(date time.Time) *DockModel {
errormodel := DockModel{
View: newDailyDockView(date),
Typemap: make(map[int]int),
}
errormodel.Typemap[0] = 0
errormodel.Typemap[10] = 1
errormodel... |
package bolt
import (
"log"
"encoding/json"
"webapp/entities"
)
// This type/struct stores no state, it’s just a collection of methods
type LanguageDAOBolt struct {
bucketName string
}
func NewLanguageDAOBolt() LanguageDAOBolt {
// Creates a DAO using the "language" bucket
return LanguageDAOBolt{"language"}... |
package slices
import (
"fmt"
"math/rand"
"sort"
"strings"
"time"
"github.com/life4/genesis/constraints"
)
// Choice chooses a random element from the slice.
// If seed is zero, UNIX timestamp will be used.
func Choice[S ~[]T, T any](items S, seed int64) (T, error) {
if len(items) == 0 {
var tmp T
return ... |
package sstable
import (
"bytes"
)
type bytesReaderCloser struct {
*bytes.Reader
}
func (bytesReaderCloser) Close() error {
return nil
}
func equalBytes(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func equa... |
package ToDoApi
import (
"goRestData/ToDoService"
"net/http"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
ToDoService.Index,
},
Route{
"List",
"GET",
"/List",
... |
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"github.com/AdityaVallabh/swagger_meqa/meqa/mqutil"
"github.com/AdityaVallabh/swagger_meqa/meqa/mqswag"
"github.com/AdityaVallabh/swagger_meqa/meqa/mqplan"
)
const (
meqaDataDir = "meqa_data"
algoSimple = "simple"
algoObject = "object"
algoPath ... |
package main
import (
"crypto/rand"
"fmt"
"gm/sm2"
"io/ioutil"
)
func main(){
testSM2()
}
func testSM2(){
data, err := ioutil.ReadFile("test.txt")
//data := []byte{1, 2, 3, 4, 5, 6, 7}
fmt.Println("read:",string(data))
priv, pub, err := sm2.GenerateKey(rand.Reader)
if(err != nil){
fmt.Println(err)
ret... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"crypto/md5"
)
// Digest structure summarizing a CSV/TXT file for identification
type Digest struct {
preview []string // preview rows (excluding non-blank non-comment lines)
erows int // estimated total file rows
comment string // inferre... |
package topology // import "github.com/nathanaelle/wireguard-topology"
import (
"fmt"
"io"
"io/ioutil"
"path/filepath"
"text/template"
)
type (
Template interface {
Execute(template string, dest io.Writer, data interface{}) (err error)
}
tmpls struct {
templates map[string]*template.Template
}
NetClus... |
package pxmgo
import (
"errors"
"io"
"github.com/jjeffcaii/mongo-proxy/protocol"
)
type Context interface {
io.Closer
Use(middlewares ...Middleware) Context
Send(bs []byte) error
SendMessage(msg protocol.Message) error
Next() <-chan protocol.Message
}
// Endpoint communicate endpoint for routing messages.
t... |
package models
//1. 思った通りにならなかったとき、しばらく考え込む 01
//2. 自分のいい面、得意なことを聞かれたら10個言える 10
//3. トラブルが起きた時、まず人に頼る 01
//4. 人と比較することが多い 01
//5. 昔から「マイペースだよね」とよく言われる 10
//6. 過去を振り返ったときに、結果を出してき... |
package config
import _ "github.com/joho/godotenv/autoload"
|
package stats
import (
"context"
"strings"
"time"
)
// Tags should use a key:value format
type Collector interface {
// FYI entry
Inform(string, string, ...string)
// Error resulting in a notification
Error(error, ...string)
// Measure rate of events over dT, an Inc = Count(1), Dec = Count(-1)
Count(strin... |
package main
import (
"encoding/json"
"fmt"
"runtime"
"sort"
"sync"
)
var globalIndex int
var mutex sync.Mutex
func main() {
p := Parser{}
QBs, RBs, WRs, TEs, DSTs := p.Parse()
for _, q := range QBs {
q.ScoreQB()
}
for _, r := range RBs {
r.ScoreRB()
}
for _, w := range WRs {
w.ScoreWR()
}
f... |
package subscription
import (
"context"
"github.com/syncromatics/kafmesh/internal/graph/resolvers"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
//go:generate mockgen -source=./subscribers.go -destination=./subscribers_mock_test.go -package=subscription_test
// PodLister gets the ... |
package handler
import (
"errors"
"net/http"
"strconv"
"github.com/mafewo/meliexercise/database/mongo"
"github.com/mafewo/meliexercise/models"
"github.com/mafewo/meliexercise/msj"
mgo "gopkg.in/mgo.v2"
)
// GetWeatherByDay get weather by day
func GetWeatherByDay(w http.ResponseWriter, r *http.Request) {
quer... |
// Copyright 2021 Praetorian Security, 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 o... |
// Copyright Amazon.com Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file ... |
package finduser
import (
"errors"
pagerduty "github.com/PagerDuty/go-pagerduty"
)
var UserNotFoundError = errors.New("Could not find specified user.")
type Client struct {
pagerduty.Client
}
func (c *Client) FindAndValidate(in string) (*pagerduty.User, error) {
u, e := c.GetUser(in, pagerduty.GetUserOptions{}... |
/**
Create a for loop using this syntax
for {}
Have it print out the years you have been alive
*/
package main
import (
"fmt"
"time"
)
func main() {
birthYear := 1995
for {
if birthYear > time.Now().Year() {
break
}
fmt.Println(birthYear)
birthYear++
}
} |
package main
import (
"log"
sarama "github.com/Shopify/sarama"
)
func main() {
consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)
if err != nil {
panic(err)
}
defer consumer.Close()
partitionConsumer, err := consumer.ConsumePartition("example", 0, sarama.OffsetNewest)
if err != nil {
p... |
package chains
import (
"fmt"
"sync"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/hive.go/daemon"
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/hive.go/node"
"github.com/iotaledger/wasp/packages/... |
package factories
import (
"database/sql"
"github.com/barrydev/api-3h-shop/src/common/connect"
"github.com/barrydev/api-3h-shop/src/connections"
"github.com/barrydev/api-3h-shop/src/model"
)
func StatisticOrder(query *connect.QueryMySQL) (*model.StatisticOrder, error) {
connection := connections.Mysql.GetConnec... |
package main
import "fmt"
func main() {
words := [3][2]string{
{"a", "b"},
{"c", "d"},
{"e", "f"},
}
for _, v1 := range words {
for _, v2 := range v1 {
fmt.Printf("%v ", v2)
}
fmt.Printf("\n")
}
}
|
package main
import (
"context"
"crypto/rand"
"errors"
"flag"
"fmt"
"log"
mathRand "math/rand"
"net"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"sync/atomic"
"time"
"github.com/pion/stun"
)
var (
workers = flag.Int("w", runtime.GOMAXPROCS(0), "concurrent workers") // nolint:gochecknoglob... |
//go:build ignore
// +build ignore
package main
import (
"context"
"fmt"
"github.com/looplab/fsm"
)
func main() {
var afterFinishCalled bool
fsm := fsm.NewFSM(
"start",
fsm.Events{
{Name: "run", Src: []string{"start"}, Dst: "end"},
{Name: "finish", Src: []string{"end"}, Dst: "finished"},
{Name: "r... |
package models
import "encoding/xml"
type SoapResponse struct {
XMLName xml.Name `xml:"Envelope"`
Text string `xml:",chardata"`
Soap string `xml:"soap,attr"`
Xsd string `xml:"xsd,attr"`
Xsi string `xml:"xsi,attr"`
Header struct {
Text string `xml:",chardata"`
SOAPENV string `xml:"S... |
package xlsx
import (
"errors"
"fmt"
"github.com/plandem/xlsx/format"
"github.com/plandem/xlsx/internal"
"github.com/plandem/xlsx/internal/ml"
"github.com/plandem/xlsx/internal/number_format"
"github.com/plandem/xlsx/internal/number_format/convert"
"github.com/plandem/xlsx/types"
"math"
"strconv"
"time"
)
... |
package user
import "github.com/piapip/Learning-Go/Gomock/doer"
//User duper useless
type User struct {
Doer doer.Doer
}
//Use same goes with this
func (u *User) Use() error {
return u.Doer.DoSomething(123, "Hello GoMock")
}
func (u *User) take(x, y int) int {
return u.Doer.DoThisToo(x, y)
}
|
package main
import (
"flag"
"fmt"
"github.com/vincentcreusot/finance-limits/fileutils"
"github.com/vincentcreusot/finance-limits/logic"
"log"
"os"
)
func main() {
inputFileName := ""
outputFileName := ""
validateUsage(&inputFileName, &outputFileName)
lineToParseChannel := make(chan string)
go fileutils.Re... |
package main
import "github.com/ahhoefel/cdf/scene"
import "github.com/ahhoefel/cdf"
const (
width = 800
height = 800
depth = 3
numPoints = 300
)
func main() {
ptsA := cdf.RandomPointsNorm(numPoints, 60, 300)
ptsB := cdf.RandomPointsNorm(numPoints, 60, 400)
q := cdf.NewBoxQuad(depth, append(ptsA, p... |
package static
import (
"os"
"path"
"strings"
"github.com/spiral/errors"
)
// Config describes file location and controls access to them.
type Config struct {
Static *struct {
// Dir contains name of directory to control access to.
Dir string
// Forbid specifies list of file extensions which are forbidde... |
package router
import (
"github.com/gin-gonic/gin"
"github.com/tzr2020/gin_demo/controller"
)
func SetupRouters() (r *gin.Engine) {
// 使用Gin默认路由器
r = gin.Default()
// 静态资源处理器
r.Static("/static", "static")
// 加载模板文件
r.LoadHTMLFiles("template/index.html")
// 渲染模板
r.GET("/", controller.IndexHandler)
// api... |
package gpg_test
import (
"testing"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/invidian/terraform-provider-gpg/gpg"
)
func TestProvider(t *testing.T) {
if err := gpg.Provider().(*schema.Provider).InternalValidate(); err != nil {
t.Fatalf("validating provider internally: %v", err)
}... |
package main
import "fmt"
func main() {
a := 2
fmt.Println(generateMatrix(a))
}
func generateMatrix(n int) [][]int {
res := [][]int{}
for i := 0; i < n; i++ {
temp := make([]int, n)
res = append(res, temp)
}
fmt.Println(res)
rowBegin := 0
rowEnd := n - 1
colBegin := 0
colEnd := n - 1
for num := 1; num... |
package models
import (
"errors"
"strings"
"time"
)
// User represents the user model/table
type User struct {
ID uint64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Nick string `json:"nick,omitempty"`
Email string `json:"email,omitempty"`
Password string `jso... |
package transport
import (
"github.com/atymkiv/echo_frame_learning/blog/cmd/api/user"
"github.com/atymkiv/echo_frame_learning/blog/model"
"github.com/labstack/echo"
"net/http"
)
type HTTP struct {
svc user.Service
}
// NewHTTP creates new user http service
func NewHTTP(svc user.Service, e *echo.Echo) {
h := HT... |
// Copyright (c) 2020 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package starlark
import (
"os"
"strings"
"testing"
"github.com/vmware-tanzu/crash-diagnostics/ssh"
"go.starlark.net/starlarkstruct"
)
func testCrashdConfigNew(t *testing.T) {
e := New()
if e.thread == nil {
t.Err... |
package gallery
import (
"testing"
. "github.com/bborbe/assert"
)
func TestCreateImage(t *testing.T) {
var err error
imageId := "imageId123"
imageContent := "imageContent123"
image := CreateImage(imageId, imageContent)
err = AssertThat(image, NotNilValue())
if err != nil {
t.Fatal(err)
}
err = AssertThat... |
package user
import (
"errors"
"github.com/google/uuid"
)
type Id struct {
/*
- Id型の構造体を作ることで、技術的な詳細(ここではUUIDを使ってIdを生成していること)を隠蔽する
- ビジネス的にシステム一意のユーザオブジェクトを作成したいという要件があったとき、Idをどう生成するかはメインの問題ではない
- このUUIDライブラリに万が一致命的なバグがあって違うライブラリに差し替えるときも変更箇所はここだけになる
- もし異なる方法でIdを生成する(例えばDBに生成させたり)ケースであっても、Id型を作って... |
// Copyright (c) 2020 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package starlark
import (
"fmt"
"strings"
"testing"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
)
func TestKubeGet(t *testing.T) {
tests := []struct {
name string
kwargs func(t *testing.T) []st... |
package nests
import "fmt"
func (a *Ant) trainSoluce(ns *Nests, nb int) {
a.trained = true
//a.Life = 100000000
ins := []int{0, 1, 2, 3}
if a.AntType == 1 {
ins = []int{0, 3}
}
for _, in := range ins {
direct := 0
for ii := 0; ii < nb; ii++ {
a.setEntriesSoluce(in, direct)
a.setOutsSoluce(in, direct... |
package main
import (
"fmt"
"sort"
)
// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
func main() {
// Test cases
nums := []int{-1, 0, 1, 2, -1, -4}
fmt.Println("[[-1 0 1] [-1 -1 2]] =", threeSum(n... |
package MessageChannels
import (
"bytes"
"encoding/json"
"main/Structs"
"net/http"
"os"
)
type slackMessage struct {
Text string `json:"text"`
}
type SlackChannel struct {
L Structs.LinkStruct
}
func (sc *SlackChannel) SendMessage() bool {
if os.Getenv("SLACK_HOOK_URL") == "" {
return false
}
message ... |
package main
import "fmt"
func main() {
Fizzes := []int{3}
Buzzes := []int{5}
for i := 1; i <= 100; i++ {
output := ""
decider(&Fizzes, &i, &output, "Fizz")
decider(&Buzzes, &i, &output, "Buzz")
if output == "" {
output = fmt.Sprintf("%d", i)
}
fmt.Println(output)
}
}
func decider(list *[]int, i *... |
package backends
import (
"encoding/json"
"fmt"
"github.com/schachmat/wego/iface"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
"time"
)
type smhiConfig struct {
}
type smhiDataPoint struct {
Level int `json:"level"`
LevelType string `json:"levelType"`
Name string `json... |
package main
import "fmt"
func main(){
//copying a slice
var patientZero = []int{101100, 111001, 100100} //has len = 3, cap = 3
//THE WRONG WAY
buf := make([]int, 0)
fmt.Println(len(buf), cap(buf))
copied := copy(buf, patientZero) //only copies the smallest slice
fmt.Println(copied) //is actually empty
//T... |
package port
import (
"github.com/mirzaakhena/danarisan/domain/repository"
"github.com/mirzaakhena/danarisan/domain/service"
)
// UndangPesertaOutport ...
type UndangPesertaOutport interface {
repository.FindOneArisanRepo
repository.FindOneArisanByAdminIDRepo
repository.SavePesertaRepo
repository.SaveListOfPese... |
package main
import "fmt"
func is_prime(n int64) bool {
if n <= 1 {
return false
} else if n <= 3 {
return true
} else if n%2 == 0 || n%3 == 0 {
return false
}
i := int64(5)
for i*i <= n {
if n%i == 0 || n%(i+2) == 0 {
return false
}
i += 6
}
return true
}
// 10001st prime
func main() {
n := ... |
package main
import (
"bufio"
"io"
"io/ioutil"
"os"
"testing"
)
func ScanLines(r io.Reader) []string {
s := bufio.NewScanner(r)
var lines []string
for s.Scan() {
lines = append(lines, s.Text())
}
return lines
}
func setupTests(prefix string) (*os.File, func(), error) {
createdFile, err := ioutil.TempFi... |
package mhfpacket
import (
"errors"
"github.com/Andoryuuta/Erupe/network"
"github.com/Andoryuuta/Erupe/network/clientctx"
"github.com/Andoryuuta/byteframe"
)
type OperateGuildMemberAction uint8
const (
_ = iota
OPERATE_GUILD_MEMBER_ACTION_ACCEPT
OPERATE_GUILD_MEMBER_ACTION_REJECT
OPERATE_GUILD_MEMBER_ACTION... |
package main
import "fmt"
func factorial(num int) int {
var i, j int
for i = 1; i < num; i++ {
j = j * i
}
return j
}
func main() {
num := 2
j := factorial(num)
fmt.Printf("The factorial of %d is %d\n", num, j)
}
|
package inet_test
import (
"fmt"
"math/rand"
"testing"
"github.com/gaissmai/go-inet/inet"
"github.com/gaissmai/go-inet/internal"
)
func BenchmarkSortIP(b *testing.B) {
bench := []int{10000, 100000, 1000000}
for _, n := range bench {
ips := internal.GenMixed(n)
rand.Shuffle(len(ips), func(i, j int) { ips[... |
package main
import "fmt"
type student struct{
rollNo int
name string
}
func main(){
fmt.Println(student{1,"sushil"})
obj := student{2,"arati"}
fmt.Println(obj)
fmt.Println(obj.name)
fmt.Println(obj.rollNo)
fmt.Println(&obj)
fmt.Println(&obj.rollNo)
fmt.Println(&obj.name)
obj1 := student{rollNo: 3, n... |
package main
import (
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/gabriel-vasile/mimetype"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"golang.design/x/clipboard"
)
type Page struct {
ID uint64
Project *Project
UpwardPage *Page
Grid *Grid
Cards ... |
//如下对int封装为另一个类型,并提供一个Increase方法
package main
import "fmt"
type TZ int
type A struct {
}
func main() {
var a TZ
a.Increase(100)
fmt.Println(a)
}
func (tz *TZ) Increase(num int) {
*tz += TZ(num)
//+=操作的左右两端类型必须匹配,虽然TZ底层类型是int,但是和TZ是不同类型,需要将int转换为TZ。
}
|
package function
import (
"fmt"
"sort"
)
func ExampleSort() {
// case int
intS := []int{-3, 2, 0, 8, -5, 1}
sort.Ints(intS)
fmt.Println(intS)
// case float64
floatS := []float64{-3.5, 2.5, 0.5, 8.5, -5.5, 1.5}
sort.Float64s(floatS)
fmt.Println(floatS)
// case string
stringS := []string{"orange", "lemon"... |
package requests
import (
"encoding/json"
"testing"
"github.com/mitchellh/mapstructure"
"github.com/stretchr/testify/assert"
)
func TestDecodeWalletRepresentativeSetRequest(t *testing.T) {
encoded := `{"action":"wallet_representative_set","wallet":"1234","representative":"nano_2"}`
var decoded WalletRepresenta... |
package el
import (
"fmt"
"strings"
"unicode"
)
type EL struct {
alphabetLength int
runeAlphabet map[rune]int
intAlphabet map[int]rune
decodeMap map[int]string
encodeMap map[string]string
}
// Init initializes the variables for the given EL variable
func (el *EL) Init() {
el.decodeMap = map[i... |
package sgs
import (
"testing"
"time"
)
func TestScript3(t *testing.T) {
srv, _ := makeSSrv(SSrvParam{
Profile: "test",
DefaultClients: 2,
MinimalClients: 2,
OptimalWS: 30,
BaseTickMs: 10,
ABF: buildMockApp,
})
rl := makeresLogger()
p1 := makePlayer("regn", 22, rl, srv)
... |
// Copyright 2021 BoCloud
//
// 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 wri... |
package models
const (
JobOk uint8 = 0
JobFailed uint8 = 1
)
type Job struct {
Token string `json:"token"`
Url string `json:"url"`
AppID string `json:"app_id"`
}
type JobResult struct {
Job
HTML string
Status uint8
}
|
package main
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"time"
)
func main() {
//在服务器启动etcd
// nohup ./etcd --listen-client-urls 'http://0.0.0.0:2379' --advertise-client-urls 'http://0.0.0.0:2379' &
config := clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"}, //集群列表
DialTimeout: 5 *... |
package model
import (
"context"
"github.com/gorhill/cronexpr"
"time"
)
// JobLog is data carrier for the log for job
type JobLog struct {
JobName string `json:"jobName" bson:"jobName"` // job name
Command string `json:"command" bson:"command"` // job shell command
Err str... |
package main
import (
bouncer "github.com/Karagar/final_project/bouncer"
)
func main() {
service := &bouncer.Service{}
service.InitService()
}
|
package boshio
import (
"fmt"
"net"
"net/http"
"net/url"
"os"
"time"
)
func NewHTTPClient(host string, wait time.Duration) HTTPClient {
return HTTPClient{
Host: host,
Wait: wait,
Client: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeo... |
package util
import (
"time"
"gopkg.in/pg.v3"
"fmt"
)
var Db *pg.DB
func Init() {
config := InitConfig()
Db = singleConnect(config)
}
func singleConnect(config *ServerConfig) *pg.DB {
return pg.Connect(pgOptions(config.Host[0], config.Port, config.User, config.Password, config.Database))
}
var Index = 32
//v... |
package main
import (
"fmt"
"time"
)
type Sender chan<- string
type Receiver <-chan string
func main() {
ch1 := make(chan string, 3)
go func() {
fmt.Println("start send to ch1")
ch1 <- "hello"
fmt.Println("end send to ch1")
}()
time.Sleep(time.Duration(2)*time.Second)
var value string = "receive from ch1:... |
package role
// Available roles.
const (
System = "SYSTEM"
Admin = "ADMIN"
Create = "CREATE"
Write = "WRITE"
Read = "READ"
)
|
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"flag"
)
var (
size = flag.Int("bytes", 4, "How many bytes should be read. The number of characters in the output will be twice this value.")
)
func main() {
flag.Parse()
buffer := make([]byte, *size)
_, err := rand.Read(buffer)
if err != nil {
p... |
package main
import (
"encoding/json"
"fmt"
"time"
)
// OnlineInit runs infinit loop to send online users count to all clients
func onlineInit(hub *Hub) {
message := make([]interface{}, 2)
ticker := time.NewTicker(10 * time.Second)
quit := make(chan struct{})
for {
select {
case <-ticker.C:
message[0] ... |
package jsonschema
import (
extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
)
// ExtV1CRDOpenAPIV3Schema defines the schema for
func ExtV1CRDOpenAPIV3Schema() extv1.JSONSchemaProps {
properties := map[string]extv1.JSONSchemaProps{
"apiVersion": StringProp,
"kind": StringProp,
}
return e... |
package main
import (
"bufio"
"bytes"
"io"
)
// Scanner represents a lexical scanner
type Scanner struct {
r *bufio.Reader
}
// NewScanner returns a new instance of Scanner.
func NewScanner(r io.Reader) *Scanner {
return &Scanner{r: bufio.NewReader(r)}
}
// read reads the next rune from the bufferred reader.
/... |
package tag
// List is Qiita tag list(Set 100 tags in order of frequency of appearance)
var List [100]string = [100]string{"Python",
"JavaScript",
"Ruby",
"Rails",
"PHP",
"AWS",
"iOS",
"Java",
"Docker",
"Swift",
"Android",
"Linux",
"初心者",
"Node.js",
"Python3",
"Git",
"C#",
"Unity",
"Mac",
"Go",
"CS... |
package main
import (
"fmt"
student ".."
)
func main() {
student.Raid1b(5, 3)
fmt.Println()
student.Raid1e(0, 1)
fmt.Println()
student.Raid1e(0, 1)
fmt.Println()
student.Raid1e(6, 0)
fmt.Println()
student.Raid1e(0, -6)
}
|
package main
import . "leetcode"
func main() {
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isEvenOddTree(root *TreeNode) bool {
var ans []int
var travel func(root *TreeNode, level int) bool
travel = func(root *Tr... |
package modules
import (
"context"
"fmt"
"regexp"
"time"
"github.com/astaxie/beego"
beegoContext "github.com/astaxie/beego/context"
"github.com/sirupsen/logrus"
elastic "gopkg.in/olivere/elastic.v5"
elogrus "gopkg.in/sohlich/elogrus.v2"
)
const (
HTTP_LOG_NAME = "http"
)
var (
esClient *elastic.Cli... |
//go:build js
package checkbox
import (
"net/url"
"strings"
"github.com/gopherjs/gopherjs/js"
"github.com/shurcooL/go/gopherjs_http/jsutil"
"honnef.co/go/js/dom"
)
func init() {
js.Global.Set("CheckboxOnChange", jsutil.Wrap(CheckboxOnChange))
}
func CheckboxOnChange(event dom.Event, object dom.HTMLElement, d... |
package main
import (
"fmt"
"sort"
"github.com/jnewmano/advent2020/input"
"github.com/jnewmano/advent2020/output"
)
func main() {
answer := partb()
fmt.Println(answer)
}
func partb() interface{} {
// input.SetRaw((raw2))
var things = input.LoadSliceInt("")
things = append(things, 0) // add the starting no... |
package diffiehellman
import (
"math/big"
"math/rand"
"time"
)
const testVersion = 1
func PrivateKey(p *big.Int) *big.Int {
source := rand.New(rand.NewSource(time.Now().UnixNano()))
return new(big.Int).Add(big.NewInt(2), new(big.Int).Rand(source, new(big.Int).Sub(p, big.NewInt(2))))
}
func PublicKey(private, p ... |
/*
Tencent is pleased to support the open source community by making Basic Service Configuration Platform available.
Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain... |
type RecentCounter struct {
queue []int
}
func Constructor() RecentCounter {
return RecentCounter{}
}
func (this *RecentCounter) Ping(t int) int {
temp := *this
temp.queue = append(temp.queue, t)
for temp.queue[0] < t - 3000 {
temp.queue = temp.queue[1:]
}
*this = temp
... |
package condiments
type Whip struct {
description string
cost int
}
func NewWhip() Whip {
return Whip{
description: "Whip",
cost: 30,
}
}
func (wp Whip)GetDescription(beverageDescription func() string) func() string {
return func() string {
return beverageDescription() +" "+ wp.description
... |
package utils
import "encoding/xml"
// 通过xml解析的结构体,des必须是引用
func Copy(src, des interface{})bool{
bs,err:=xml.Marshal(src)
if err!=nil {
return false
}
err = xml.Unmarshal(bs,des)
if err!=nil {
return false
}
return true
} |
package tasks
import (
"reflect"
"testing"
)
func TestNewTask(t *testing.T) {
task_name := "TestTask"
tsk := NewTask(task_name)
if reflect.TypeOf(tsk).String() != "tasks.Task" {
t.Fatalf(`NewTask("%s") did not return a "Task" type.`, task_name)
}
if tsk.Name != task_name {
... |
package main
import (
"encoding/csv"
"log"
"os"
"strconv"
"io"
//"fmt"
)
func saveToFile(locOfCities map[string]Location) {
f, _ := os.Create("geodb")
w := csv.NewWriter(f)
for key, value := range locOfCities {
csvRecord := []string{key, strconv.FormatFloat(value.Lat, 'f', -1, 64), strconv.FormatFloat(... |
package scsprotov1
func (c *scsv1) GetRunningProcesses() int {
return c.concurrentRoutinesPool.AvailablePermits()
}
|
package repositories_test
import (
"context"
"testing"
"github.com/syncromatics/kafmesh/internal/graph/model"
"gotest.tools/assert"
)
func Test_Component_Services(t *testing.T) {
repo := repos.Component()
r, err := repo.ServicesByComponents(context.Background(), []int{1, 2, 3, 4})
assert.NilError(t, err)
a... |
package main
import (
"fmt"
)
// Go includes the built-in error interface defined as
/*
type error interface {
Error () string
}
So, any value that satisfies this interface can be used wherever errors are used.
*/
//
type GreetingError struct {
Who string
}
func (ge *GreetingError) Error() string ... |
package parser
import (
"fmt"
"strings"
"github.com/emptyland/akino/sql/ast"
"github.com/emptyland/akino/sql/token"
)
func ParseCommand(cmd string) (ast.Command, error) {
var p Parser
return p.Init(cmd).NextStatement()
}
func ParseExpression(expr string) (ast.Expr, error) {
var p Parser
return p.Init(expr).... |
package test
// 定义一个结构体,首字母小写,则只能同包级别访问
type student struct {
id int
name string
}
// 定义一个结构体,首字母大写,则其它包级别可以访问
type Student struct {
// 定义的成员变量,首字母小写,则只能同包级别访问
id int
// 定义的成员变量,首字母大写,则其它包级别可以访问
Name string
}
|
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
"github.com/kataras/iris"
)
const (
adapterMetadata = "http://adapter-metadata.default.svc.cluster.local"
adapterExtension = "http://adapter-extension.default.svc.cluster.local"
)
// Timeseries : Timeseries... |
package leetcode
/*You're given strings J representing the types of stones that are jewels,
and S representing the stones you have. Each character in S is a type of stone you have.
You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J an... |
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/li... |
package posthttpport
import (
"encoding/json"
"net/http"
"strings"
"github.com/alejogs4/blog/src/post/application"
"github.com/alejogs4/blog/src/post/domain/post"
"github.com/alejogs4/blog/src/post/infraestructure/posthttpadapter"
"github.com/alejogs4/blog/src/shared/infraestructure/httputils"
"github.com/ale... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.