text stringlengths 11 4.05M |
|---|
package pgeo
import (
"database/sql/driver"
)
// NullLseg allows line segment to be null
type NullLseg struct {
Lseg
Valid bool `json:"valid"`
}
// Value for database
func (l NullLseg) Value() (driver.Value, error) {
if !l.Valid {
return nil, nil
}
return valueLseg(l.Lseg)
}
// Scan from sql query
func (l ... |
package main
import (
"encoding/json"
"fmt"
"log"
)
type Envelope struct {
Type string `json:"type"`
}
type Sound struct {
Description string `json:"description"`
Authority string `json:"authority"`
}
type Cowbell struct {
More bool `json:"more"`
}
func main() {
input := `
{
"type": "sound",
"des... |
package manager
import (
"github.com/ChowRobin/fantim/model/bo"
"github.com/ChowRobin/fantim/model/vo"
"github.com/gorilla/websocket"
)
// 单机先采用本地缓存链接关系,分布式采用redis
var (
UserConnRouter map[int64]*bo.LConnectionGroup
)
func init() {
UserConnRouter = make(map[int64]*bo.LConnectionGroup)
}
// 注册长连接
func RegisterU... |
package raft
import (
"errors"
zmq "github.com/pebbe/zmq4"
"github.com/syndtr/goleveldb/leveldb"
"net"
"sync"
"time"
)
type ErrRedirect int // See Log.Append. Implements Error interface.
var MsgAckMap map[Lsn]int
//Map to maintain log-entry to client conn mapping, used while sending back response to client
... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type RuleInputs struct {
firstName string
lastName string
abn string
}
// RuleResults returns the success fail of each rule, and an aggregated message string.
type RuleResults struct {
validFirstName ... |
//Package cutout implements the circuit breaker design pattern(see: https://martinfowler.com/bliki/CircuitBreaker.html)
//for calling third party api services.
//
// Cutout comes with features like:
//
// 1. Multilevel fallback functions(in case even the fallback fails)
//
// 2. Custom BackOff function on the request l... |
package provider
import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/mrparkers/terraform-provider-keycloak/keycloak"
)
func resourceKeycloakOpenidClientAuthorizationClientPolicy() *schema.Resource {
return &schema.Resou... |
package resolvers
import (
"context"
"github.com/Keijun-KUMAGAI/graphql-server/gqlgen"
"github.com/Keijun-KUMAGAI/graphql-server/prisma-client"
)
// -------------------- Mutation --------------------
func (r *mutationResolver) TodoCreate(ctx context.Context, params gqlgen.TodoCreateInput) (*prisma.Todo, error) {... |
package config
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
"github.com/schicho/mensa/canteen"
)
const FilenameConfig = "mensa_conf.json"
const FilenameCache = "mensa_data.csv"
var defaultConfig = Config{canteen.Canteens2Abbrev["UNI_PASSAU_CANTEEN"], time.Time{}, PriceStudent_t}
var FilepathConfig ... |
package queries
import (
"fmt"
"github.com/graphql-go/graphql"
"go_graphql/blog/db"
"go_graphql/blog/types"
)
// GetUserQuery returns the queries available against user type.
func GetUserQuery() *graphql.Field {
return &graphql.Field{
Type: graphql.NewList(types.UserType),
Resolve: func(params graphql.Resolv... |
// Copyright 2019-present 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 agr... |
// DO NOT EDIT. This file was generated by "github.com/frk/gosql".
package testdata
import (
"github.com/frk/gosql"
"github.com/frk/gosql/pgsql"
)
func (q *insertarrayquery) Exec(c gosql.Conn) error {
const queryString = `INSERT INTO "pgsql_test" (
"col_bitarr"
, "col_boolarr"
, "col_boxarr"
, "col_bpchar... |
package valexa
import (
"os"
"testing"
// "fmt"
"bufio"
"bytes"
"net/http"
)
func init(){
os.Chdir("./test/data")
}
//注意
//下面这requestBody是签名的,不能改动他,生成日期是 2017-12-01T09:00:10Z
//在此项目里设置测试有效时间是在 testValidTime 变量里
//如果你测试这个项目发生报错,应该是testValidTime过期了
//1,你可以增加 testValidTime 数值,不能超出 int 类型允许大小的限制。
//2,你可以自己生成一个reque... |
// Copyright 2014 Gyepi Sam. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package redux
// Dependent is the inverse of Prerequisite
type Dependent struct {
Path string
}
func (d Dependent) File(dir string) (*File, error) {
f, err := Ne... |
/*
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,... |
package main
import "fmt"
import "math"
func main() {
found := 0
for i := 2; ; i++ {
isPrime := true
for d := 2; d <= int(math.Sqrt(float64(i))); d++ {
if i%d == 0 {
isPrime = false
}
}
if isPrime {
found++
if found == 10001 {
fmt.Printf("%v\n", i)
break
}
}
}
}
|
//go:build integration
package test
import (
"bytes"
"context"
"flag"
"io"
"io/ioutil"
"testing"
"time"
krakendlambda "github.com/devopsfaith/krakend-lambda/v2"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/proxy"
)
var endpoint = flag.String("aws_endpoint", "http://192.168.99.10... |
package leveldb
import (
"bytes"
"sync"
"testing"
)
var testDB *LevelDBEngine
var onlyOnce sync.Once
func createDB(name string) *LevelDBEngine {
f := func() {
var err error
testDB, err = Open(name)
if err != nil {
println(err.Error())
panic(err)
}
}
onlyOnce.Do(f)
return testDB
}
func TestSim... |
package msgHandler
import (
"bytes"
"github.com/HNB-ECO/HNB-Blockchain/HNB/consensus/algorand/types"
"github.com/HNB-ECO/HNB-Blockchain/HNB/util"
)
type BftGroup struct {
BgID uint64
// VRF
VRFValue []byte
VRFProof []byte
Validators []*types.Validator
}
func (bg BftGroup) Exist(digestAddr util.HexBytes) boo... |
package sql
import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
// Statement represents a single command in MessageQL.
type Statement interface {
Node
stmt()
RequiredPrivileges() ExecutionPrivileges
}
// Statements represents a list of statements.
type Statements []Statement
// String returns a st... |
package graphql_test
import (
"reflect"
"testing"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/gqlerrors"
"github.com/graphql-go/graphql/language/location"
"github.com/graphql-go/graphql/testutil"
)
func checkList(t *testing.T, testType graphql.Type, testData interface{}, expected *graphql.Re... |
package controllers
import (
"businessense/models"
u "businessense/utils"
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
//CreateProject HandlerFunc
var CreateProject = func(w http.ResponseWriter, r *http.Request) {
project := &models.Project{}
err := json.NewDecoder(r.Body).Decode(p... |
package mesh
import (
"fmt"
"net"
"strconv"
"github.com/asaskevich/govalidator"
mesh_proto "github.com/kumahq/kuma/api/mesh/v1alpha1"
"github.com/kumahq/kuma/pkg/core/validators"
)
func (es *ExternalServiceResource) Validate() error {
var err validators.ValidationError
err.Add(validateExternalServiceNetwork... |
package practice
import (
"github.com/sko00o/leetcode-adventure/queue-stack/queue"
)
// Queue defines a queue for interface{} type.
type Queue struct {
queue.SliceQueue
}
func openLock(deadends []string, target string) int {
if len(target) != 4 {
return -1
}
var queue Queue
var step int
visited := make(map... |
package flow
// Message represents a single FBP protocol message
type Message struct {
// Protocol is NoFlo protocol identifier:
// "runtime", "component", "graph" or "network"
Protocol string
// Command is a command to be executed within the protocol
Command string
// Payload is JSON-encoded body of the message... |
package TryMe
import (
"testing"
)
func BenchmarkFibGenerator(b *testing.B) {
//b.ResetTimer()
for i := 0; i < b.N; i++ {
<-FibGenerator(10)
/*
go func(i int) {
log.Printf("result %v for %v \n", <-FibGenerator(i), i)
}(i)
*/
}
}
|
package main
import (
"log"
"time"
)
func main() {
ticker := time.NewTicker(500 * time.Millisecond)
done := make(chan int)
go runTickerUntilDone(ticker, done)
log.Printf("go routine created")
time.Sleep(2 * time.Second)
log.Printf("change to 100 ms")
ticker.Reset(100*time.Millisecond)
time.Sleep(2 * time.... |
package main
import "fmt"
func main(){
numbers := []int{1,2,3,4,5}
sum := 0
for _,number := range numbers{
sum += number
}
fmt.Println("sum", sum)
for index := range numbers{
fmt.Println("index", index)
}
maps := map[int]string{4:"sushil",1:"sanjay",2:"bharati",3:"suuhas",5:"arati"}
for i,val := ran... |
package model
import (
"github.com/jinlicode/jinli-panel/global"
"github.com/jinlicode/jinli-panel/model/request"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var db *gorm.DB
func InitDbConnt() {
//open a db connection
var err error
db, err = gorm.Open(sqlite.Open(global.BASEPATH+"config.db"), &gorm.Config{})
if... |
package controllers
import (
"coludRenderDiscovery/discovery"
"coludRenderDiscovery/models"
"encoding/base64"
"errors"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"github.com/golibs/uuid"
"github.com/gorilla/websocket"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strin... |
// Copyright 2019-present 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 agr... |
package main
import "time"
func main() {
NewThing()
select {}
}
type Thing struct{}
func NewThing() *Thing {
t := &Thing{}
go t.loop()
return t
}
func (t *Thing) loop() {
for range time.Tick(time.Second) {
println("blep")
}
}
|
package model
import "time"
type Event struct {
Metadata []byte `json:"metadata"`
Type string `json:"type"`
Timestamp time.Time `json:"timestamp"`
}
|
package generator
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"github.com/pkg/errors"
)
func generateMocks(fullOutputDir string) error {
directories, err := ioutil.ReadDir(fullOutputDir)
if err != nil {
return errors.Wrap(err, "failed to get output directories")
}
for _, d := ra... |
package linkedlist
import "testing"
func TestAddTwoNumbers(t *testing.T) {
l1 := newListNodes([]int{1, 2, 3, 4, 5, 6, 7}, false)
l2 := newListNodes([]int{1, 2, 3, 4, 5, 6, 7, 9}, false)
l3 := addTwoNumbers(l1, l2)
l4 := newListNodes([]int{2, 4, 6, 8, 0, 3, 5, 0, 1}, false)
if !equalTwoList(l3, l4) {
t.Fail()
... |
//
// 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 controller
import (
"database/sql"
"encoding/json"
"net/http"
"sms-aiforesee-be/database"
"sms-aiforesee-be/models"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
func Register(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var us models.User
err := d... |
package model
type RainlabBlogPosts struct {
Id int
Title string
ContentHtml string
}
|
package bean
import (
"log"
"sync"
"time"
"github.com/astaxie/beego/orm"
. "webapi/common"
)
const (
DefaultChannelID = "default"
)
type Announcement struct {
ID int64 `orm:"column(id);auto;pk"` // 主键
Channel string `orm:"column(channel);size(8)"` // 渠道编号
Illustration s... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
var mealCost, tipPercent, taxPercent float64
var texts []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
text := scanner.Text()
texts = append(texts, text)
if len(texts) >= 3 {
break
}
}
mealCost, _ = strconv.P... |
/*
GoLang code created by Jirawat Harnsiriwatanakit https://github.com/kazekim
*/
package tbccert
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"time"
)
const (
x509CertificateCommonName = "ThaiBankClientGo"
x509CertificateOrganization ... |
// Package server defines internal behaviour.
package server
import (
"encoding/json"
"net/http"
)
// Error explains what went wrong.
func Error(w http.ResponseWriter, code int, message string) {
JSON(w, code, map[string]string{"error": message})
}
// JSON marshals a JSON payload and writes it out to the response... |
package cotacao
import (
"fmt"
"github.com/fabioxgn/go-bot"
. "github.com/smartystreets/goconvey/convey"
"net/http"
"net/http/httptest"
"testing"
)
const (
expectedJSON = `{
"bovespa":{
"cotacao":"60800",
"variacao":"-1.68"
},
"dolar":{
"cotacao":"2.2430",
"var... |
package core
import "github.com/zhenghaoz/gorse/base"
// ModelInterface is the interface for all models. Any model in this
// package should implement it.
type ModelInterface interface {
// Set parameters.
SetParams(params base.Params)
// Get parameters.
GetParams() base.Params
// Predict the rating given by a u... |
// Copyright 2016 Tim O'Brien. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package jnigi
/*
#include <jni.h>
#include <Windows.h>
typedef jint (*type_JNI_GetDefaultJavaVMInitArgs)(void*);
type_JNI_GetDefaultJavaVMIni... |
package gominin
import (
"testing"
)
type intList []int
func (list intList) Len() int {
return len(list)
}
func TestBinarySearchSingleValue(t *testing.T) {
target := 0
list := intList{target}
x := BinarySearch(list, func(index int) int { return list[index] - target })
if x != 0 {
t.Error("Error. BinarySearc... |
package main
import (
"fmt"
"strconv"
"strings"
"github.com/jnewmano/advent2020/input"
"github.com/jnewmano/advent2020/output"
)
func main() {
sum := parta()
fmt.Println(sum)
}
func parta() interface{} {
// input.SetRaw(raw2)
// var things = input.Load()
// var things = input.LoadSliceSliceString("")
va... |
package demo
import (
"fmt"
"math/rand"
)
type Job struct {
Id int
Number int
}
type Result struct {
job *Job
sum int
}
func cals(job *Job, resultChan chan *Result) {
sum := 0
number := job.Number
for number > 0 {
temp := number % 10
sum += temp
number = number / 10
}
resulet := &Result{
job:... |
package qiwi
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestCardRequest(t *testing.T) {
// Expected reply from QIWI
// HTTP/1.1 200 OK
// Content-Type: application/json
reply := `
{
"siteId": "test-01",
"billId": "gg",
"amount": {
... |
package remotego
import (
"errors"
"github.com/dash-app/remote-go/aircon"
"github.com/dash-app/remote-go/aircon/daikin/daikin01"
"github.com/dash-app/remote-go/aircon/daikin/daikin02"
"github.com/dash-app/remote-go/aircon/daikin/daikin03"
"github.com/dash-app/remote-go/aircon/daikin/daikin04"
"github.com/dash-... |
package glog
import (
"fmt"
"testing"
"github.com/onsi/gomega"
)
func TestNewLogLevel(t *testing.T) {
g := gomega.NewGomegaWithT(t)
cases := []struct {
input string
expected LogLevel
ok bool
}{
{"debug", Debug, true},
{"info", Info, true},
{"notice", Notice, true},
{"warning", Warning,... |
package db
import (
"sync"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/golang/glog"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"sub_account_service/finance/models"
)
//DbClient 客户端
var DbClient *Db
//AutoMigrate 自动迁移
var AutoMigrate = false
//Db 数据库
type Db struct {
addr ... |
package collection
import (
"runtime"
"github.com/tidwall/btree"
"github.com/tidwall/geojson"
"github.com/tidwall/geojson/geometry"
"github.com/tidwall/rtree"
"github.com/tidwall/tile38/internal/deadline"
"github.com/tidwall/tile38/internal/field"
"github.com/tidwall/tile38/internal/object"
)
// yieldStep fo... |
package domain
import "errors"
type Recipes struct {
recipes map[Beverage]*Recipe
}
func CreateRecipes(recipes map[Beverage]*Recipe) *Recipes {
return &Recipes{recipes: recipes}
}
func (r *Recipes) get(beverage Beverage) (*Recipe, error) {
recipe := r.recipes[beverage]
if recipe == nil {
return nil, errors.Ne... |
package gchalk
//go:generate stringer -type=ColorLevel
// ColorLevel represents the ANSI color level supported by the terminal.
type ColorLevel int
const (
// LevelNone represents a terminal that does not support color at all.
LevelNone ColorLevel = 0
// LevelBasic represents a terminal with basic 16 color suppor... |
package binance
import (
"context"
"net/http"
)
// AssetDividendService fetches the saving purchases
type AssetDividendService struct {
c *Client
asset *string
startTime *int64
endTime *int64
limit *int
}
// Asset sets the asset parameter.
func (s *AssetDividendService) Asset(asset string) *... |
/*
hub.go
*/
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gorilla/websocket"
"github.com/tidwall/gjson"
)
type Hub struct {
clients []*Client
register chan*Client
unregister chan*Client
}
// Constructor
func newHub() *Hub {
return &Hub {
cli... |
package main
import (
"math"
"math/rand"
)
func distanceBetweenPoints(p1, p2 *City) float64 {
return math.Sqrt(math.Pow(p1.x-p2.x, 2) + math.Pow(p1.y - p2.y, 2))
}
func calculateDistance(cities []City) float64 {
total := 0.0
for i := 0; i < len(cities) - 1; i++ {
total += distanceBetweenPoints(&cities[i], &c... |
package camt
import (
"encoding/xml"
"github.com/thought-machine/finance-messaging/iso20022"
)
type Document00700201 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:camt.007.002.01 Document"`
Message *RequestToModifyPayment `xml:"camt.007.002.01"`
}
func (d *Document00700201) AddMe... |
package routes
import (
"fmt"
"github.com/gin-gonic/gin"
E "github.com/gowyu/yuw/exceptions"
M "github.com/gowyu/yuw/modules"
"html/template"
"strings"
)
type (
Routes interface {
Tag() string
Put(r *gin.Engine, toFunc map[string][]gin.HandlerFunc)
ToFunc() template.FuncMap
}
Rcfg []Routes
Rtpl []int... |
/**
* (c) 2014, Caoimhe Chaos <caoimhechaos@protonmail.com>,
* Ancient Solutions. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain ... |
package user
import (
"fmt"
"octlink/mirage/src/modules/account"
"octlink/mirage/src/modules/session"
"octlink/mirage/src/utils/config"
"octlink/mirage/src/utils/merrors"
"octlink/mirage/src/utils/octlog"
"octlink/mirage/src/utils/octmysql"
"time"
)
var logger *octlog.LogConfig
func InitLog(level int) {
log... |
package main
import (
"encoding/hex"
"fmt"
"io/ioutil"
"os"
shellcode "github.com/brimstone/go-shellcode"
)
// This program runs the shellcode from: https://www.exploit-db.com/exploits/40245/
//
// As the shellcode is 32 bit, this must also be compiled as a 32 bit go application
// via "set GOARCH=386"
func ma... |
package testing
import (
"fmt"
"github.com/gorilla/mux"
qupHttp "github.com/queueup-dev/qup-io/v2/http"
types "github.com/queueup-dev/qup-types"
"io/ioutil"
"log"
"net/http"
"sync"
"testing"
"time"
)
const (
inputTypeRequestBody = "REQUEST_BODY"
inputTypeRequestHeader = "REQUEST_HEADER"
)
type Logger i... |
package main
import (
"bytes"
"net"
"time"
"fmt"
"github.com/nkbai/goice/ice"
"github.com/nkbai/log"
)
const (
typHost = 1
typStun = 2
typTurn = 3
)
type icecb struct {
data chan []byte
iceresult chan error
name string
}
func newicecb(name string) *icecb {
return &icecb{
name: name,
... |
package main
import (
"fmt"
"github.com/Cloud-Foundations/Dominator/lib/log"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
"github.com/Cloud-Foundations/Dominator/proto/sub"
"github.com/Cloud-Foundations/Dominator/sub/client"
)
func deleteSubcommand(args []string, logger log.DebugLogger) error {
srpcClient... |
package remark
import (
"time"
"github.com/go-jar/goerror"
"github.com/go-jar/gohttp/query"
"blog/entity"
"blog/errno"
)
func (rc *RemarkController) CreateAction(context *RemarkContext) {
remarkEntity, e := rc.parseCreateActionParams(context)
if e != nil {
context.ApiData.Err = e
return
}
ids, err := ... |
// Copyright (C) 2021 Cisco Systems 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 agr... |
package user_test
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/golovers/gotest/user"
gomock "github.com/golang/mock/gomock"
)
func TestHandleRegister(t *testing.T) {
srv := NewMockservice(gomock.NewController(t))
handler := user.NewHandler(srv)
... |
package frontend
//go:generate esc -o static.go -pkg frontend -ignore=(.go|.swp) -modtime 0 .
|
/*
Copyright 2014 GoPivotal (UK) 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 agre... |
package main
import (
_ "hello_api/routers"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"fmt"
_ "github.com/go-sql-driver/mysql"
"hello_api/kafka"
)
func init(){
beego.SetLogger("file", `{"filename":"logs/test.log"}`)
logLevel, err:= beego.AppConfig.Int("logLevel")
if nil != err{
logLevel = ... |
package main
import (
help "hello/Helper"
"hello/ProdService"
"github.com/gin-gonic/gin"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/web"
"github.com/micro/go-plugins/registry/consul"
)
func main() {
//consul服务注册
consulreg := consul.NewRegistry(
registry.Addrs("192.168.238.131:8500"), /... |
package header
import (
"strconv"
"strings"
"time"
"github.com/kudrykv/latex-yearly-planner/app/components/calendar"
"github.com/kudrykv/latex-yearly-planner/app/components/hyper"
)
type Header struct {
Left Items
Right Items
}
type Items []Item
type Item interface {
Display() string
}
func (i Items) ColS... |
package ksqlparser
import "strings"
type caseWhenExpression struct {
When []*Condition
Then Expression
Else Expression
}
func (b *caseWhenExpression) String() string {
sb := []string{ReservedCaseWhen}
for _, w := range b.When {
sb = append(sb, w.String())
}
sb = append(sb, ReservedThen, b.Then.String())
if... |
package main
#Importing required modules
import (
"os"
"github.com/shomali11/slacker"
)
#Request writer
func handle(request *slacker.Request, response slacker.ResponseWriter) {
response.Reply("Hey!")
}
#Connecting to slack and providing a response
func main() {
bot := slacker.NewClient(os.Getenv("API_TOKEN"))
... |
package main
import (
"fmt"
"log"
"net/http"
"path"
"strings"
)
type server struct {
kvs KVS
hasher Hasher
servStats *serverStats
}
// newServer creates a new server, with the specified hasher and key-value store.
func newServer(kvs KVS, hasher Hasher) *server {
return &server{
kvs: kvs,
hasher: ... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package micropay
import (
"github.com/iotaledger/wasp/contracts"
"github.com/iotaledger/wasp/packages/coretypes/coreutil"
"github.com/iotaledger/wasp/packages/hashing"
"time"
)
const (
Name = "micropay"
description = "Micro payment P... |
/*
Copyright (c) 2019 VMware, Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package plugin
import (
"os"
"path/filepath"
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_AvailablePlugins(t *testing.T) {
tests := []str... |
// 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 server
import (
"bufio"
"fmt"
"net"
"strings"
"testing"
"github.com/danhale-git/craft/internal/mock"
)
func TestServer_Command(t *testing.T) {
mockClient := &mock.DockerContainerClient{}
s := &Server{ContainerAPIClient: mockClient}
conn, reader := net.Pipe()
mockClient.Conn = conn
mockClient.Reade... |
// Package memcache provides a client for the memcached cache server.
package memcache
import (
"bufio"
"bytes"
"errors"
"fmt"
"hash/crc32"
"net"
"strconv"
"sync"
"time"
)
const (
// DefaultTimeout is the default socket read/write timeout.
DefaultTimeout = 100 * time.Millisecond
// Defau... |
// Package econtext provides Echo integration with golang.org/x/net/context.
package econtext
import (
"github.com/labstack/echo"
"golang.org/x/net/context"
)
type ctx struct {
c *echo.Context
context.Context
}
func (c ctx) Value(key interface{}) interface{} {
if key == ckey {
return c.c
}
if v := c.c.Get(k... |
package timbler
import (
"log"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
)
func TestServer(t *testing.T) {
// start server
serve := gin.Default()
ws := &RealtimeWS{}
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
ws.InitWS(serve, dir)
serve.Run(":8... |
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
expr := `a == 1 && b == 2`
fset := token.NewFileSet()
exprAst, err := parser.ParseExpr(expr)
if err != nil {
fmt.Println(err)
return
}
ast.Print(fset, exprAst)
}
|
package base
type BaseModel struct {
Id uint `gorm:"primary_key"json:"id"`
CreateTime LocalTime `json:"createTime"`
UpdateTime LocalTime `json:"updateTime"`
}
|
/*
获取黄金的行情,从新浪财经
黄金地址 : http://gu.sina.cn/m/?vt=1&cid=76613#/futures/foreign
纽约黄金 : <li data-symbol="hf_GC"
聚合数据的黄金数据接口API : http://web.juhe.cn:8080/finance/gold/shgold?key=您申请的APPKEY
每两分钟更新一次,这个接口可能也是爬取别的站的,但是调用比直接爬取新浪财经快,
作为备用方案
*/
package main
func goldMain(){
// 黄金行情的获取入口
for {
}
}
|
package deck
import (
"testing"
"math/rand"
)
func TestExampleCard(t *testing.T) {
AceHeart := Card{Rank: Ace, Suit: Heart}.String()
if AceHeart != "Ace of Hearts" {
t.Errorf("Failed")
}
TwoSpade := Card{Rank: Two, Suit: Spade}.String()
if TwoSpade != "Two of Spades" {
t.Errorf("Fa... |
package template
import (
"path/filepath"
"scaffold/core/input"
)
// Scaffold bootstraps a project
func Scaffold(ans *input.UserAnswers, templatePaths map[string]string) error {
// TODO: platform independent implementation
// TODO: replace project name in files
// TODO: bootstrap.sh script
dst, err := filepath... |
//complete reference from: https://github.com/gorilla/websocket/tree/master/examples/chat
package main
import (
"flag"
"log"
"net/http"
)
var addr = flag.String("addr", ":12345", "http server port address")
func homeHandler(w http.ResponseWriter, r *http.Request) {
log.Println("home:", r.URL)
if r.URL.Path != ... |
package main
import (
"sync"
"testing"
"time"
)
// 1 tx
func TestPattern1(t *testing.T) {
db := NewTestDB()
tx := NewTx(db)
if err := tx.Insert("key1", "value1"); err != nil {
t.Fatalf("failed to insert: %v\n", err)
}
if value, err := tx.Read("key1"); err != nil || value != "value1" {
t.Fatalf("failed to ... |
package response
import (
"net/http"
"github.com/jinzhu/gorm"
"github.com/labstack/echo"
)
// ModelError for decorating responses
type ModelError struct {
Message string `json:"message"`
}
// APIResponse - returns a decorated json response
func APIResponse(err error, c echo.Context, model interface{}) error {
... |
package main
import "fmt"
//func 函数名(参数)(返回值){
// 函数体
//}
func f1(x int, y int) int {
return x + y
}
// 简写
func intSum(x, y int) int {
return x + y
}
func intSum2(x ...int) int {
fmt.Println(x) //x是一个切片
sum := 0
for _, v := range x {
sum = sum + v
}
return sum
}
func intSum3(x int, y ...int) int {
fmt.Prin... |
package main
import (
_ "visitor/config"
_ "visitor/logger"
"fmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"math/rand"
"time"
"visitor/app/server"
)
func main() {
// 设置随机数因子
rand.Seed(time.Now().Unix())
// 启动服务
port := viper.GetString("server.port")
log.Info("Server listening on ", p... |
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// time: O(n), space: O(n)
func levelOrder(root *TreeNode) [][]int {
var res [][]int
if root == nil {
return res
}
q := []*TreeNode{root}
for len(q) > 0 {
... |
package api
import (
"context"
pb_api "github.com/inari111/layered-architecture-example-2020/rpc/api"
)
type taskService struct {
}
func NewTaskService() pb_api.TaskService {
return &taskService{}
}
func (t *taskService) Create(ctx context.Context, request *pb_api.TaskCreateRequest) (*pb_api.TaskCreateResponse,... |
package types
import (
"bytes"
"context"
"fmt"
"time"
"github.com/golang/protobuf/jsonpb"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/backends"
... |
// Copyright 2021, Pulumi Corporation. All rights reserved.
// +build tools
// Place any runtime dependencies as imports in this file.
// Go modules will be forced to download and install them.
package tools
|
package golog_test
import (
"testing"
"time"
"github.com/bingoohuang/golog"
"github.com/sirupsen/logrus"
)
func TestSetupLogrus(t *testing.T) {
golog.SetupLogrus(nil, "level=debug,rotate=.yyyy-mm-dd-HH-mm-ss,maxAge=5s,gzipAge=3s", "")
for i := 0; i < 10; i++ {
logrus.Warnf("这是警告信息 %d", i)
logrus.Infof("这是... |
func climbStairs(n int) int {
if n == 1{
return 1
} else if n == 2{
return 2
}
steps := make([]int, n)
steps[0], steps[1] = 1, 2
for idx := 2; idx < n; idx++ {
steps[idx] = steps[idx-1] + steps[idx-2]
}
return steps[n-1]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.