text stringlengths 11 4.05M |
|---|
package server
import (
"crypto/sha256"
"fmt"
"net/http"
"time"
"github.com/jetuuuu/hl_homework/mysql"
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/v4"
)
type Server struct {
Store *mysql.DB
}
func (s Server) Login(eCtx echo.Context) error {
ctx := eCtx.Request().Context()
params := struct {
... |
package problems
import (
"fmt"
"reflect"
"testing"
)
func Test_isSymmetric(t *testing.T) {
tests := []struct {
nums numSlice
want bool
}{
{
nums: numSlice{{1}, {2}, {2}, {3}, {4}, {4}, {3}},
want: true,
},
{
nums: numSlice{{1}, {2}, {2}, nil, {3}, nil, {3}},
want: false,
},
{
nums: ... |
package main
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func spawn(opts spawnOptions) error {
args := []string{"--distribution", opts.distro, "--exec", opts.nerdctl, "--address", opts.containerdSocket}
args = append(args, opts.args.args...)
cmd := exec.Command("wsl.exe", args...)
cmd.St... |
package ziface
type IMsgHandle interface {
DoMsgHandler(request IRequest)
AddRouter(msgId uint32, router IRouter)
// worker pool
StartWorkerPool()
SendMsgToTaskQueue(request IRequest)
}
|
package handlers
import (
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/hiraisin/go-postgre/config"
"github.com/hiraisin/go-postgre/models"
"github.com/labstack/echo"
)
func FormLogin(c echo.Context) error {
data := config.M{
"title": "Form Login",
}
return c.Render(http.StatusOK, "login.htm... |
// googlenewsInfo
package DaeseongLib
import (
"flag"
"fmt"
_ "html"
_ "io"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
)
func getSrc(sInput string) string {
sParam := "src="
if strings.Contains(sInput, sParam) {
Pos1 := strings.Index(sInput, sParam) + len(sParam)
sValue := sInput[Pos1+1:]... |
package mysqldb
import (
"context"
"time"
)
// UserSubscriptionSharing 订阅拥有或者被分享
type UserSubscriptionSharing struct {
SubscriptionID int32 `gorm:"primary_key"` // 订阅ID
UserID int32 `gorm:"column:user_id"` // 使用者
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt... |
package modules
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"text/template"
"github.com/wx13/genesis"
)
type Template struct {
Dest string
Src string
Vars interface{}
}
func (tmpl Template) src() string {
match, _ := regexp.MatchString("^[.]?/", tmpl.Src)
if match {
re... |
package config
import (
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
)
//服务端配置
type AppConfig struct {
AppName string `json:"app_name"`
AppScope string `json:"app_scope"`
TenantId string `json:"tenant_id"`
Port string `json:"port"`
StaticPath string `json:"static_path"`
... |
package rtrserver
import (
"bytes"
"encoding/binary"
"errors"
"net"
"strconv"
"time"
"github.com/cpusoft/goutil/belogs"
"github.com/cpusoft/goutil/conf"
"github.com/cpusoft/goutil/convert"
"github.com/cpusoft/goutil/jsonutil"
)
// rtrPduModel:
func ParseToRtrPduModel(buf *bytes.Reader) (rtrPduModel RtrPduM... |
package main
import (
"fmt"
"reflect"
)
func test() {
//普通slice,像没有长度的数组
s1 := []int{}
//make,可以指定len,cap,没有cap,则cap=len
//make创建了一个只属于s2的底层数组,s2只引用了前len个元素
s2 := make([]int, 10, 20)
a := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
//判断类型
fmt.Println(reflect.TypeOf(s1))
fmt.Println(reflect.TypeOf(s2), len(s2), ... |
// 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 spdx
type Package struct {
Name ValueStr // one
Version ValueStr // zero or one
DownloadLocation ValueStr // one; NOASSERTION or NONE valid
HomePage ValueStr // zero or one; NOASSERTION or NONE valid
FileName Valu... |
package load_balance
import (
"fmt"
"testing"
"time"
)
func TestSmoothWeightedRoundRobin(t *testing.T) {
lb := NewSmoothWeightedRoundRobin([]*SmoothWServer{
{"10.11.0.1", 3, 0}, {"10.11.0.5", 1, 0}, {"10.11.0.3", 1, 0},
})
for i := 0; i < 5; i++ {
// go func() {
s := l... |
package main
import (
pb "github.com/youtangai/HelloServerStreaming/proto"
"golang.org/x/net/context"
"time"
"log"
"io"
"fmt"
"google.golang.org/grpc"
)
func runGreet(client pb.HelloServerStreamingServiceClient) {
req := &pb.HelloRequest{Message: "hello"}
ctx, cancel := context.WithTimeout(context.Background... |
package config
import (
"fmt"
"os"
)
type Config struct {
ConnectionString string
}
func getConfigValue(envName string, defaultValue string) string {
if val, ok := os.LookupEnv(envName); ok {
return val
}
return defaultValue
}
func getConnectionString() (connectionString string) {
postgresHost := os.Getenv... |
// Copyright 2018 Diego Bernardes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package http
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
"github.com/go-kit/kit/log"
"github.com/pkg/errors... |
package common
import (
"encoding/json"
"fmt"
"os"
)
type message struct {
Confirmed string `json:"confirmed"`
Regfin string `json:"regfin"`
Required string `json:"required"`
EmailNotFound string `json:"email_not_found"`
IncorrectPassword string `json:"incorrect_password"`
Wel... |
package xorm1
//
//import (
// "fmt"
// _ "github.com/go-sql-driver/mysql"
// "github.com/xormplus/core"
// "github.com/xormplus/xorm"
// "os"
// "time"
//)
//
//var engine *xorm.Engine
//
//func xorm2() {
// var _ error
// engine, _ = xorm.NewEngine("mysql",
// "root:root@/test?charset=utf8")
//
// f, err := os.Creat... |
// 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 commands
import (
"context"
"time"
"github.com/projecteru2/phistage/apiserver/grpc/proto"
"github.com/urfave/cli/v2"
"google.golang.org/grpc"
"google.golang.org/grpc/keepalive"
)
func newClient(c *cli.Context) (proto.PhistageClient, error) {
connection, err := dial(c.Context, c.String("host"))
if err... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
ptp "github.com/subutai-io/p2p/lib"
)
type request struct {
IP string `json:"ip"`
Mac string `json:"mac"`
Dev string `json:"dev"`
Hash string `json:"hash"`
Dht string `json:"dht"`
Keyfile ... |
package car
var Lada, Mazda *car
type car struct {
Brand string
Year int
BodyVolume int
IsRunning bool
WindowIsOpen bool
BootVolume int
}
func init(){
Lada = &car{
Brand: "LADA",
Year: 2000,
BodyVolume: 400,
IsRunning: false,
WindowIsOpen: true,
BootVolume... |
package hamming
import "errors"
func Distance(a, b string) (int, error) {
if len(a) != len(b) {
return -1, errors.New("Lengths of DNA strands don't match")
}
count := 0
for index := 0; index < len(a); index++ {
if a[index] != b[index] {
count++
}
}
return count, nil
}
|
package main
import (
"flag"
"fmt"
"os"
)
var (
default_source_dir = "/home/thens/Dropbox/linux/dotfiles"
default_target_dir = "/home/thens"
// just for testing purposes
// default_source_dir = "/home/thens/gocode/src/github.com/thensgens/godotfiler/test_files/source"
// default_target_dir = "/home/thens/goc... |
package coinbase
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"net/http"
"strconv"
"time"
"github.com/fabioberger/coinbase-go/config"
)
// ApiKeyAuthentication Struct implements the Authentication interface and takes
// care of authenticating RPC requests for clients with a Key & Secret pair
type api... |
package analytics
import (
zap "go.uber.org/zap"
"gopkg.in/mgo.v2"
"time"
)
const ACTION_CHAN_BUFF = 1
const RUN_CHAN_BUFF = 1
type ActionCustom struct {
RunId uint32
UserId string
Action *string
Param *string
Time time.Time
}
type ActionRun struct {
CharType *string
UserId string
RunId uint32
... |
package services
import (
"net/http"
"./welcome"
"github.com/gorilla/mux"
)
// NewRouter creates a router for URL-to-service mapping
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
apiV1 := router.PathPrefix("/v1").Subrouter()
apiV1.HandleFunc("/hello-world", welcome.GetWelcomeHand... |
package acl
import (
"encoding/json"
"fmt"
api "github.com/uhppoted/uhppoted-lib/acl"
"github.com/uhppoted/uhppoted-lib/uhppoted"
"github.com/uhppoted/uhppoted-mqtt/common"
)
func (a *ACL) Revoke(impl uhppoted.IUHPPOTED, request []byte) (interface{}, error) {
body := struct {
CardNumber *uint32 `json:"card-... |
package main
import (
"math/rand"
"time"
)
func randomSeconds(n int) time.Duration {
rand.Seed(time.Now().UnixNano())
return time.Duration(rand.Intn(n)) * time.Second
}
|
package main
import "fmt"
func main() {
var test string
fmt.Println(test)
var a string = "hello world"
fmt.Printf("a=%v\n", a)
fmt.Println(a)
//反引号
var b string = `hello world fmt.Println(a)\n`
fmt.Println(b)
//拼接
var c string = "1111"
c += "22222"
fmt.Println(c)
}
|
/*
Package dev ...
LedDisplay let you display text on an led digital module which bases on the 74HC595 dirver.
Please note that I only test it on a 4-bit led digital module.
Andy Only following chars were supported. The any char which didn't be spported will be displayed as '-'.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
0 1 ... |
package go_crawl
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"unicode/utf8"
"golang.org/x/net/html"
)
var version = "1.0"
var projectName string
var crawled []string
var links []string
func checkError(err error) {
if err != nil {
fmt.Println(err.Error()... |
// Copyright 2018 Diego Bernardes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package wildcard
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestValid(t *testing.T) {
Convey("Feature: Validate wildcards", t... |
package main
import "fmt"
func getSum(n1 int, n2 int) int {
return n1 + n2
}
//---------------------
//函数类型的parfun 作参数. 即函数作为形参
func myFun(parfun func(int, int) int, num1 int, num2 int) int {
return parfun(num1, num2)
}
func main() {
//将getSum()函数 赋值给变量a, a即函数类型
//a 的值即getSum()返回值
a := getSum
//等价于 res := get... |
package handler
import (
"context"
"fmt"
"strings"
"github.com/jinmukeji/jiujiantang-services/service/mysqldb"
)
// macWithColon 返回由冒号分隔的 MAC 地址
func macWithColon(mac string) string {
length := len(mac) / 2
sa := make([]string, length)
for i := 0; i < length; i++ {
sa[i] = mac[2*i : 2*i+2]
}
return stri... |
package system
import (
"dappapi/models"
"dappapi/tools"
"dappapi/tools/app"
"fmt"
"time"
"github.com/gin-gonic/gin"
)
func Dlist(c *gin.Context) {
var err error
var gs models.GameStats
var cs models.CoinStats
stime, etime := tools.RequestTime(c)
stimeStru, _ := time.Parse("2006-01-02", stime)
nstime :... |
// Licensed to SolID under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. SolID licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compli... |
package main
import "fmt"
func sumfunction(first int, second int, channel chan int) {
channel <- first + second
}
func main() {
channel := make(chan int)
go sumfunction(10, 3, channel)
sum := <-channel
fmt.Println(sum)
}
|
package controllers
import (
"github.com/gorilla/mux"
"net/http"
"server/src/services/interfaces"
"strconv"
)
type ArticleController struct {
articleService interfaces.ArticleServiceProvider
}
func NewArticleController(articleService interfaces.ArticleServiceProvider) *ArticleController {
return &ArticleContro... |
package service
import (
"github.com/GoGroup/Movie-and-events/model"
"github.com/GoGroup/Movie-and-events/user"
)
type RoleService struct {
roleRepo user.RoleRepository
}
func NewRoleService(RoleRepo user.RoleRepository) user.RoleService {
return &RoleService{roleRepo: RoleRepo}
}
func (rs *RoleService) Roles()... |
package smg
import (
"strings"
)
func split2(s, sep string) (string, string, bool) {
spl := strings.SplitN(s, sep, 2)
if len(spl) < 2 {
return spl[0], "", true
}
return spl[0], spl[1], true
}
|
package api
import (
"context"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"net/http"
"shop-web/user-api/forms"
"shop-web/user-api/global"
"shop-web/user-api/global/reponse"
"... |
package app
import (
"github.com/PinkFairyArmadillos/go-endpoints/endpoints"
)
func init() {
registerApi()
endpoints.HandleHttp()
}
|
package filter
import (
"fmt"
"strings"
)
func FromQuery(vals map[string][]string) Config {
if len(vals) == 0 {
return Config{}
}
metricWhitelist := vals[MetricWhitelist]
metricBlacklist := vals[MetricBlacklist]
metricTagWhitelist := parseFilters(vals[MetricTagWhitelist])
metricTagBlacklist := parseFilters... |
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/docker/buildx/commands"
"github.com/docker/cli/cli/command"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const descriptionSourcePath = "docs/reference/"
func generateDocs(opts *options)... |
package domain
import (
"log"
"os"
"time"
mgo "gopkg.in/mgo.v2"
)
//GetMongoDBDatabase provide a MongoDB session
func GetMongoDBDatabase(db string) (*mgo.Database, error) {
mongoDBDialInfo := getConnectionInfo()
log.Println("Mongo dial info: ", mongoDBDialInfo)
session, err := mgo.DialWithInfo(m... |
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"time"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
tpl, err := template.New("").ParseFiles("templates/index.html", "templates/layout.html")
err = tpl.ExecuteTemplate(w, "layout", nil)
if err != nil {
log.Fatalln("Error serving in... |
//
//go:generate dllcall dbif.go ../docdbcpp/dbif.h
package main
import "log"
func main() {
err := load_dbif("docdbdll.dll")
if err != nil {
log.Fatal(err)
}
d := &dbIf{dbName: "test.db"}
err = d.Open()
if err != nil {
log.Fatal(err)
}
/// ... Do something with db
err = d.Close()
if err != nil {
log.... |
// +build !local
package bslib
const localTestFile = "" // create your own local db file for testing purposes
const useLocalTestFile = false
|
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"syscall"
"time"
"golang.org/x/crypto/acme/autocert"
"github.com/gentlemanautomaton/signaler"
"github.com/scjalliance/redirection"
)
func main() {
shutdown := signaler.New().Capture(os.Interrupt, sys... |
package user
import (
"log"
"strconv"
"time"
"github.com/pulsar-go/example/models"
"github.com/pulsar-go/pulsar/db"
"github.com/pulsar-go/pulsar/queue"
"github.com/pulsar-go/pulsar/request"
"github.com/pulsar-go/pulsar/response"
)
// Data ...
type Data struct {
Users []models.User
}
// Index function
func ... |
package index
import (
"strconv"
"testing"
)
func TestBinarySearch(t *testing.T) {
testDocs := []Document{}
for i := 0; i < 10; i++ {
testDocs = append(testDocs, Document{
uint64(i), "Title" + strconv.Itoa(i), "URL" + strconv.Itoa(i),
})
}
want := uint64(6)
got, err := BinarySearch(want, testDocs)
if ... |
package responses
type WalletChangeSeedResponse struct {
Success string `json:"success" mapstructure:"success"`
LastRestoredAccount string `json:"last_restored_account" mapstructure:"last_restored_account"`
RestoredCount int `json:"restored_count" mapstructure:"restored_count"`
}
|
// Copyright 2019 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... |
// Tests for development build only
// +build debug
package ybc
import (
"fmt"
"testing"
)
/*******************************************************************************
* Config
******************************************************************************/
func TestConfig_DoubleDataFileOpen(t *testing.T) {... |
package friend
import "spapp/src/models/apimodels"
type SubscribeUserInput struct {
Requestor string `json:"requestor"`
Target string `json:"target"`
}
type SubscribeUserOutput struct {
apimodels.ApiResult
} |
package main
import (
"fmt"
)
func MaxRequestEnforcer() {
if *maxRequests < 0 {
//Listen forever
for {
<-requestChan
requestCounter++
}
} else {
//Listen until max requests reached
for requestCounter < *maxRequests {
<-requestChan
requestCounter++
}
}
//Reached max requests
fmt.Printf("... |
package leetcode
// https://leetcode-cn.com/problems/container-with-most-water/
/*
题目:
给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,
垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以
容纳最多的水。
示例:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
思路:
通过指针碰撞,首尾 2 个指针,每次移动以后都判断长宽的乘积是否最大
*/
fu... |
// Copyright (c) 2023 Target Brands, Inc. All rights reserved.
//
// Use of this source code is governed by the LICENSE file in this repository.
package vela
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/go-vela/types/constants"
"github.com/go-vela/types/library"
)
type AuthenticationType int
cons... |
package main
import (
"fmt"
"reflect"
)
type X int
type Y int
func main() {
//var a, b X = 100, 200
//var c Y = 300
//
//ta, tb, tc := reflect.TypeOf(a), reflect.TypeOf(b), reflect.TypeOf(c)
//
//fmt.Println(ta == tb, ta == tc)
//fmt.Println(ta.Kind() == tc.Kind())
type t rune
var t2 t
t1 := reflect.Ty... |
package controllers
import (
"github.com/robfig/revel"
"myapp/app/models"
"myapp/app/utils"
"strconv"
"encoding/base64"
"encoding/json"
)
type Cate struct {
*revel.Controller
}
func (c Cate) checkUser() revel.Result {
userInfo := c.Session["UserInfo"]
if userInfo == "" {
c.Flash.Error("... |
package ZFic
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"strconv"
"time"
"net/http"
"errors"
"github.com/russross/blackfriday"
)
func GetMD(input []byte) []byte {
return blackfriday.MarkdownCommon(input)
}
func HandlePage(icfg string) []byte {
CFGDATA,... |
package v1
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// RemoveRequested is invoked when the invoker requests to remove an activity.
func (h Handle) RemoveRequested(
_ context.Context,
_ string,
_ string,
) (e error) {
e = status.Error(codes.Unimplemented, "Out of scop... |
/* For license and copyright information please see LEGAL file in repository */
package approuter
// ReqSetSettings : Don't send this request between active stream due may streams data will lost!
type ReqSetSettings struct {
PacketPayloadSize uint16 // Defaults: 1200 byte. It can't be under 1200 byte. Exclude networ... |
package podprocess
import (
"io/ioutil"
"os"
"path/filepath"
"testing"
"time"
"github.com/hashicorp/consul/api"
"github.com/square/p2/pkg/logging"
"github.com/square/p2/pkg/store/consul"
"github.com/square/p2/pkg/store/consul/consulutil"
"github.com/square/p2/pkg/store/consul/statusstore"
"github.com/squa... |
package main
import (
"fmt"
"github.com/achakravarty/30-days-of-go/day2"
)
func main() {
var mealCost float32
var tipPercent, taxPercent int
fmt.Scanf("%f\n%d\n%d", &mealCost, &tipPercent, &taxPercent)
fmt.Printf("The total meal cost is %d dollars.", day2.GetTotalCost(mealCost, tipPercent, taxPercent))
}
|
package ed25519
import (
"crypto/ed25519"
"golang.org/x/xerrors"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/Secured-Finance/dione/sigs"
"github.com/Secured-Finance/dione/types"
)
type ed25519Signer struct{}
func (ed25519Signer) GenPrivate() ([]byte, error) {
_, privKey, err := ed25519.GenerateKey(n... |
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"encoding/json"
"net/http"
)
var db, err = sql.Open("mysql", "root:112@/test?charset=utf8")
type Node struct {
Id int
Label string
Lft int
Rgt int
}
type Nodeslice struct {
Nodes []Node
}
func main() {
http.HandleFunc("/getAl... |
package auth
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestAuth(t *testing.T) {
Convey(`When calling NoAuth`, t, func() {
auth, err := NoAuth("id", "user", []byte("foo"))
Convey(`Then There should be no error`, func() { So(err, ShouldBeNil) })
Convey(`Then it should return the u... |
package middleware
import (
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// GinLogger 接收gin框架默认的日志
func GinLogger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
cost := time.Since(start)
status := c.W... |
package main
import "fmt"
//结构体模拟实现其他语言的继承
type animal struct {
name string
}
//给animal实现一个移动的方法
func (a animal) move() {
fmt.Printf("%s会动\n", a.name)
}
//狗类
type dog struct {
feet uint8
animal
}
//给dog实现一个汪汪汪方法
func (d dog) wang() {
fmt.Printf("%s在叫汪汪汪~\n", d.name)
}
func main() {
d1 := dog{
animal: anim... |
/*
指针
*/
package basicgrammar
import "fmt"
//函数是一个变量
var p = f()
func f() *int {
v := 1
fmt.Println(&v)
return &v
}
func incr(p *int) int {
//非常重要:只是增加p指向的变量的值,并不改变p指针!!!
*p++
//上面的等价于 *p = *p + 1
return *p
}
func TestPoint() {
a := incr(p)
fmt.Println(a)
}
|
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string, 1)
c2 := make(chan string, 1)
timeout := make(chan bool, 1)
c2 <- "hello"
c1 <- "world"
go makeTimeout(timeout, 2)
select {
case msg := <-c1:
fmt.Println("c1 receive: ", msg)
case msg := <-c2:
fmt.Println("c2 receive: ", msg)
c... |
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"github.com/juangm/go-exercises/go-quiz/quiz"
)
func main() {
csvFilename := flag.String("csv", "problem.csv", "a csv file in teh format of 'question,answer'")
timeLimit := flag.Int("limit", 30, "The time limit for the quiz in seconds")
flag.Parse()
fi... |
package rsvc
import (
"bytes"
"fmt"
"log"
"strings"
"github.com/isbm/inid/rtutils"
"github.com/isbm/processman"
)
type RunService struct {
serialCommands []*RunServiceCommand
concurrentCommands []*RunServiceCommand
procman *processman.Processman
BaseService
}
func NewRunService() *RunServic... |
package main
import (
"bufio"
"flag"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
)
func die(msg string, err error) {
dieSlow(msg, "", err)
}
func dieSlow(msg, longMsg string, err error) {
fmt.Fprint... |
package utils
import (
"testing"
"fmt"
)
func TestContains (t *testing.T) {
strArray := StringArray{"slack", "bot", "webhook", "rabbit", "sur5an"}
inputExpectedOutput := []struct {
input string
expectedOutput bool
}{
{"bot", true},
{"test", false},
... |
package migration
import (
"github.com/jinzhu/gorm"
"github.com/tppgit/we_service/entity/order"
"github.com/tppgit/we_service/entity/service"
"gopkg.in/gormigrate.v1"
)
//Service
func CreateServiceTable() []*gormigrate.Migration {
migrations := []*gormigrate.Migration{
{
ID: "create-service-table",
Migr... |
package rpc
import (
"context"
"fmt"
"strconv"
sdkclient "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec/legacy"
"github.com/gookit/gcli/v3"
"github.com/ovrclk/akcmd/client"
"github.com/ovrclk/akcmd/flags"
)
// BlockCommand returns the verified block data for a given heights
func Bl... |
package models
// NewCollectionParams creates a new instance of CollectionParams.
func NewCollectionParams(cursor string, limit uint8) (params *CollectionParams) {
if limit == 0 {
limit = 25
}
return &CollectionParams{
Cursor: cursor,
Limit: limit,
}
}
// CollectionParams represents various parameters th... |
package catalog
import (
"fmt"
"reflect"
"testing"
mapset "github.com/deckarep/golang-set"
"github.com/golang/mock/gomock"
access "github.com/servicemeshinterface/smi-sdk-go/pkg/apis/access/v1alpha3"
spec "github.com/servicemeshinterface/smi-sdk-go/pkg/apis/specs/v1alpha4"
specs "github.com/servicemeshinterfa... |
/*
* EVE Swagger Interface
*
* An OpenAPI for EVE Online
*
* OpenAPI spec version: 0.4.1.dev1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package swagger
// 200 ok object
type GetCharactersCharacterIdBookmarksFolders200Ok struct {
// folder_id integer
FolderId int32 `json:"fol... |
package binance
import (
"context"
"strings"
bin "github.com/adshao/go-binance"
"github.com/mhereman/cryptotrader/logger"
"github.com/mhereman/cryptotrader/types"
)
// GetOrderTrades executes the get order trades request
func (b Binance) GetOrderTrades(ctx context.Context, orderInfo types.OrderInfo) (trades []t... |
package pattern
import (
"fmt"
"regexp"
"strings"
)
// Type describes a type of pattern.
type Type int
// Pattern types.
const (
Text Type = iota
Regexp
)
// Pattern type prefixes.
const (
PrefixRegexp = "re"
)
// Pattern matches string patterns by performing an exact text match or a
// regular expression ma... |
package lecimg
import (
"bytes"
"errors"
"image"
"image/color"
"image/gif"
"image/jpeg"
"image/png"
"io"
"os"
"path/filepath"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
"lec/lecio"
"golang.org/x/image/font/inconsolata"
)
type Changeable interface {
Set(x, y int, c color.Color)
}
func... |
package main
import (
"fmt"
"github.com/boltdb/bolt"
"log"
"os"
"os/signal"
"syscall"
)
// TODO:
// - DNS expiration go routine
// - Callback handling
// - DKIM
// - DRY up WorkerPool/Queue implementation (See processor.go and worker.go)
var Database *bolt.DB
var dispatcher *Dispatcher
var processorPool *Proce... |
package res
type Video struct {
ToUserName string `json:"to_user_name"`
FromUserName string `json:"from_user_name"`
CreateTime string `json:"create_time"`
MsgType string `json:"msg_type"`
MediaId string `json:"media_id"`
Title string `json:"title"`
Description string `json:"description"`
}... |
// package main
/*
if else语句
*/
// import (
// "fmt"
// )
// func main() {
// num := 99
// if num >= 9 && num <= 50 {
// fmt.Println("ok")
// // fmt.Println("number is greater than 50")
// } else if num >= 51 && num <= 100 {
// fmt.Println("here")
// // fmt.Println("number is greater than 50 2")
/... |
package main
import (
"testing"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/aws"
"github.com/stretchr/testify/assert"
"time"
)
type mockedReceiveMsgs struct {
sqsiface.SQSAPI
Resp sqs.ReceiveMessageOutput
}
func (m mockedReceiveMsgs) Rec... |
// Copyright (c) 2020 Xiaozhe Yao & AICAMP.CO.,LTD
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
package entities
import (
"strconv"
"time"
"github.com/BurntSushi/toml"
"github.com/autoai-org/aid/components/cmd/pkg/storage"
"github.com/autoai-org/aid/components/cm... |
/*
Copyright 2020 The Qmgo 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, sof... |
package main
import (
"flag"
"fmt"
"os"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
)
func newKubeClient() (*client.Client, error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.ExplicitPath = clientcmd.RecommendedHomeFi... |
package sort
import (
"reflect"
"strings"
"testing"
)
func TestShellSort(t *testing.T) {
input := strings.Split("shellsortexample", "")
actual := ShellSort(input)
expected := strings.Split("aeeehlllmoprsstx", "")
if reflect.DeepEqual(expected, actual) != true {
t.Errorf("Expected %v, was %v", expected, actua... |
// Copyright The 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 writ... |
package 读写指针
/*
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
*/
func removeElement(nums []int, val int) int {
reader, writer := 0, 0
for reader < len(nums) {
if nums[reader] != val {
nums[writer] = nums[reader]
writer+... |
package main
import (
"google.golang.org/appengine"
_ "github.com/shihanng/gaegoasample/svc/servicea/cmd/servicea_svc"
)
func main() {
appengine.Main()
}
|
// See https://go-review.googlesource.com/c/go/+/37639/1/src/encoding/base64/base64_test.go#18
package base64
import (
"encoding/base64"
"testing"
)
type testpair struct {
decoded, encoded string
}
var pairs = []testpair{
// RFC 3548 examples
{"\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l+"},
{"\x14\xfb\x9c\x03\xd9", ... |
package user
import (
"fmt"
"strconv"
"net/http"
"encoding/json"
"portal/util"
"portal/model"
"portal/config"
"portal/service"
"portal/middleware"
"github.com/gin-gonic/gin"
)
// 账户登录
func Signin(c *gin.Context) {
var loginInfo model.LoginForm
if err := c.BindJSON(&loginInfo); err != nil {
util.Respo... |
package content
import (
"encoding/json"
"golang.org/x/net/context"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/memcache"
// "io/ioutil"
// "log"
)
// Use Key List method instead of this one.
func Get(ctx context.Context, page string) (Contents, error) {
// filename := title + ".html"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.