text stringlengths 11 4.05M |
|---|
package database
import (
sugar "../sugar"
"github.com/jinzhu/gorm"
"github.com/spf13/viper"
_ "github.com/jinzhu/gorm/dialects/mysql" // sd
)
// MySQLDB golbal instance
var MySQLDB *gorm.DB
// Start open db
func Start() {
host := viper.GetString("mysql.host")
port := viper.GetString("mysql.port")
username :... |
// 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... |
package kafka
import (
"context"
"github.com/Mario-Jimenez/pricescraper/subscriber"
"github.com/juju/errors"
"github.com/segmentio/kafka-go"
)
// Consumer receives messages from the broker
type Consumer struct {
consumer *kafka.Reader
}
// NewConsumer creates a consumer that receives messages from kafka
func N... |
package rest
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/tx"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/irisnet/irismod/modules/nft/types"
)
func registerTxRoutes(cliCtx cli... |
package main
import (
"fmt"
)
// 46. 全排列
// 给定一个 没有重复 数字的序列,返回其所有可能的全排列。
// https://leetcode-cn.com/problems/permutations/
func main() {
nums := []int{4, 5, 2, 6}
fmt.Println(permute(nums))
}
func permute(nums []int) (result [][]int) {
n := len(nums)
used := make([]bool, n)
cur := make([]int, n)
permuteHelper... |
package utils
const(
ID_NO_FOUND = "未找到id"
ID_ERROR = "id异常"
PARSE_USERNAME_PASSWORD_ERROR = "解析用户名密码失败"
USER_NOT_LOGIN = "用户未登录"
USER_NOT_EXIST = "用户不存在"
USER_EXISTS = "用户已存在"
TWO_PASSWORD_NOT_MATCH = "两次密码不一致"
USERNAME_PASSWORD_ERROR = "用户名密码不正确"
REGISTER_FAILED = "注册失败"
PARSE_BLOG_DATA_ERROR = "解析博文数据失败"
... |
package main
import (
"github.com/gin-gonic/gin"
"bcdb/api"
"bcdb/config"
"bcdb/db"
"sync"
)
func preInit() {
config.LoadConfig()
}
func apiServer(db *db.Db) {
r := gin.New()
r.Use(gin.Recovery())
r.Use(func(c *gin.Context) {
c.Set("db", db)
c.Next()
})
r.GET("/" , func(c *gin.Context) {
c.String... |
package model
import (
"github.com/jinzhu/gorm"
)
// DB 是gorm这个包里一个连接数据库的指针,我们可以通过这个指针来对数据库进行操作
var DB *gorm.DB
// Init 初始化admin:123456
func Init(connString string) error {
// connString是一个字符串,他保存着连接数据所需要的信息
db, err := gorm.Open("mysql", connString)
// db 就是这个函数返回的一个连接mysql的一个实例
if err != nil {
panic(err)
}
... |
package solver
import (
"context"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/containerd/console"
"github.com/docker/buildx/util/progress"
"github.com/moby/buildkit/client"
"github.com/moby/buildkit/identity"
digest "github.com/opencontainers/go-digest"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
... |
package encoding
import (
"encoding/base64"
"encoding/json"
"strings"
)
// DecodeBase64OrJSON decodes a JSON string that can optionally be base64 encoded.
func DecodeBase64OrJSON(in string, out interface{}) error {
in = strings.TrimSpace(in)
// the data can be base64 encoded
if !json.Valid([]byte(in)) {
bs, ... |
// Copyright 2020 MongoDB 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 in... |
package master
import (
"fmt"
"testing"
)
func assertEquals(t *testing.T, got, want string) {
if got != want {
t.Error("Got '" + got + "', want '" + want + "'")
}
}
func assertTrue(t *testing.T, got bool, message string) {
if !got {
t.Error(message)
}
}
func assertFalse(t *testing.T, got bool, m... |
//The debug package is great for testing and debugging of parser.Interface implementations.
package debug
|
// Copyright 2021-present Open Networking Foundation.
//
// 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 applica... |
//方法的接收者,如下两个Print方法,他的接收者分别是type A和B,属于type的方法
package main
import "fmt"
func main() {
a := new(A)
a.Print()
fmt.Println(a.Name)
b := new(B)
b.Print()
fmt.Println(b.Name)
var a1 A
a1.Print()
fmt.Println(a1.Name)
var b1 B
b1.Print()
fmt.Println(b1.Name)
}
type A struct {
Name string
}
type B struct ... |
package controllers
import (
"181103/models"
"github.com/astaxie/beego/orm"
)
type ArticleTypeController struct {
BaseController
}
func (this *ArticleTypeController) ShowAddType() {
var types []models.ArticleType
o:=orm.NewOrm()
o.QueryTable("ArticleType").All(&types)
this.Data["types"]=types
this.ShowLayou... |
/*
Copyright 2020 The Kubernetes 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 ldap
import (
"testing"
)
func TestSplitDC(t *testing.T) {
base := "dc=example,dc=org"
dc1 := splitDC(base)
if dc1 != "example" {
t.Errorf("mismatch %q and %q", dc1, "example")
}
}
|
package xdominion
import (
"fmt"
)
var fieldintegertypes = map[string]string{
DB_Postgres: "integer",
DB_MySQL: "integer",
/*
DB_Base::MSSQL => array(
DB_Field::INTEGER => "int"
),
DB_Base::ORACLE => array(
DB_Field::INTEGER => "number(16)"
)
*/
}
type XFieldInteger struct {
Name... |
package main
import "fmt"
type rect struct {
width, height int
}
// Area method has a receiver type of *rect (pointer shown below)
func (r *rect) area() int {
return r.width * r.height
}
// Methods can be defined for either pointer or value receiver types (value shown below)
func (r rect) perim() int {
return 2 ... |
package pgsql
import (
"testing"
)
func TestNumericArray(t *testing.T) {
testlist2{{
valuer: NumericArrayFromIntSlice,
scanner: NumericArrayToIntSlice,
data: []testdata{
{
input: []int{-9223372036854775808, 9223372036854775807},
output: []int{-9223372036854775808, 9223372036854775807}},
},
}, ... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2021/10/11 8:59 上午
# @File : lt_128_最长连续子序列.go
# @Description :
# @Attention :
*/
package offer
// 解题关键: 用一个hashSet来处理,
func longestConsecutive(nums []int) int {
set := make(map[int]bool)
for _, v := range nums {
set[v] = true
}
ret := 0
for k := range set ... |
package mymgo
import (
"fmt"
"strings"
"dudu/config"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Field struct {
Id string
Collection string
}
type MdbSession struct {
session *mgo.Session
db string
}
func (mdb *MdbSession) Session() *mgo.Session {
return mdb.session.New()
}
var (
Auto... |
package main
import (
"fmt"
"github.com/skorobogatov/input"
)
func vis_mealy(d [][]int, f [][]rune, n int, m int, q1 int) {
fmt.Println("digraph {")
fmt.Println("rankdir = LR")
fmt.Println("dummy [label = \"\", shape = none]")
for i := 0; i < len(d); i++ {
fmt.Printf("%d [shape = circle]\n", i)
}
fmt.Print... |
// This file contains tests for platforms that have no escape
// mechanism for including commas in mount options.
//
// +build darwin
package fuse_test
import (
"runtime"
"testing"
"gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse"
"gx/ipfs/QmSJBsmLP1XMjv8hxYg2rUMdPDB7YUpyBo9idjrJ6Cmq6F/fuse/fs/fstest... |
package parser
import (
"go/ast"
"go/parser"
"go/token"
"testing"
"github.com/stretchr/testify/require"
)
func getASTFromSrc(src string) *ast.File {
fs := token.NewFileSet()
srcAST, _ := parser.ParseFile(fs, "", src, parser.ParseComments)
return srcAST
}
func Test_parseEndpointsFrom(t *testing.T) {
src := ... |
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package config
import (
"path/filepath"
"time"
"github.com/pkg/errors"
)
const (
DefaultDaemonMode string = "multiple"
DaemonModeMultiple string = "multiple"
DaemonModeShared string = "shared"
DaemonMod... |
package main
import (
"fmt"
"strconv"
"strings"
)
type node struct {
children []node
metadata []int
}
func processNode(data []int, index int) (result node, after int) {
result = node{[]node{}, []int{}}
childCount := data[index]
metaCount := data[index+1]
index += 2
for child := 0; child < childCount; child... |
package pdns_api
import (
"fmt"
"net/http"
"net/url"
"testing"
"github.com/labstack/echo/v4"
"github.com/pir5/pdns-api/model"
)
type domainModelStub struct {
}
func init() {
globalConfig = Config{
Auth: auth{
AuthType: AuthTypeHTTP,
},
}
}
func (d *domainModelStub) FindBy(params map[string]interface... |
package main
import (
"fmt"
)
// Complete the countApplesAndOranges function below.
func countApplesAndOranges(s int32, t int32, a int32, b int32, apples []int32, oranges []int32) {
applesCoord := getFruitCoord(apples, a)
orrangesCoord := getFruitCoord(oranges, a)
fmt.Println(calcFruits(applesCoord, s, t))
fmt.P... |
package handlers
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/urbn/ordernumbergenerator/app"
"github.com/urbn/ordernumbergenerator/app/fixtures"
"github.com/urbn/ordernumbergenerator/app/mocks"
)
var (
url = "/v0/fp-us/sterling-order-number"
relativePath = "/v0/:siteId/sterling-order-nu... |
package resource
import (
"os"
"github.com/chronojam/aws-pricing-api/types/schema"
"github.com/olekukonko/tablewriter"
)
func GetCloudWatch() {
cloudwatch := &schema.AmazonCloudWatch{}
err := cloudwatch.Refresh()
if err != nil {
panic(err)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]str... |
package fs
// Version of rclone
var Version = "v1.42-DEV"
|
package transport
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
cache "github.com/patrickmn/go-cache"
cells_sdk "github.com/pydio/cells-sdk-go"
)
type TokenStore struct {
internalCache *cache.Cache
}
func NewTokenStore() *TokenStore {... |
package middleware
import (
"encoding/json"
"net/http"
"strconv"
"github.com/root-gg/plik/server/common"
"github.com/root-gg/plik/server/context"
)
// Paginate parse pagination requests
func Paginate(ctx *context.Context, next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, ... |
// Copyright 2019 Kuei-chun Chen. All rights reserved.
package atlas
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"testing"
)
func TestGetClusters(t *testing.T) {
var err error
var data []byte
var doc map[string]interface{}
publicKey := os.Getenv("ATLAS_USER_PS")
privateKey := os.Getenv("ATLAS_KEY_PS")... |
package cmd
import "github.com/spf13/cobra"
var sortFlag *string
var listCmd = &cobra.Command{
Use: "list",
Short: "list all tasks",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
if cmd.Flags().Changed("sort") {
todoController.List(sortFlag)
} else {
todoController.List(nil)
}... |
package main
import (
"fmt"
"math/rand"
"time"
)
// Operation based heartbeat
func GenerateNumbers(done <-chan struct{}, numbers ...int) (<-chan struct{}, <-chan interface{}) {
heartbeat := make(chan struct{}, 1)
stream := make(chan interface{})
go func() {
defer close(heartbeat)
defer close(stream)
for... |
// 自动生成模板TitTopic
package model
import (
"github.com/jinzhu/gorm"
)
type TitTopic struct {
gorm.Model
Title string `json:"title" form:"title" `
TopicType int `json:"topicType" form:"topicType" `
BusinessType int `json:"businessType" form:"busi... |
// Copyright (c) 2013 - Max Persson <max@looplab.se>
//
// 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 applicab... |
package g2util
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"strings"
)
// ItfExec ...
type ItfExec interface {
Start() error
Run() error
Output() ([]byte, error)
CombinedOutput() ([]byte, error)
}
// StdExec ...
func StdExec(s string) ItfExec { return NewExecInner(s, os.Stdout) }
// NewExecInner ...
func N... |
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
const apiURL = "https://api.kamergotchi.nl/game"
// GameAPI does the network communcation to the kamergotchi API
type GameAPI struct {
playerToken string
}
// GetGameInfo gets the current state of the game
func (api *GameAPI) GetGameInfo() ... |
package backend
import (
"google.golang.org/appengine/datastore"
"time"
)
type dbModel struct {
key *datastore.Key `json:"-" datastore:"-"`
parentKey *datastore.Key `json:"-" datastore:"-"`
created time.Time
}
func (m *dbModel) Key() *datastore.Key {
return m.key
}
type sessionModel struct {
dbModel
... |
package main
import (
"bufio"
"container/list"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/RyanCarrier/dijkstra"
)
type cell struct {
underlying cellType
erosionLevel int
}
type cellType byte
func (c cellType) String() string {
return fmt.Sprintf("%s", string(c))
}
type toolType byte
const (
W... |
package enums
const (
BasePath = "/api/yellow/v1"
SignIn = "/signin"
SignUp = "/signup"
GetUsers = "/users"
GetUserById = "/users/:id"
UpdateUserById = "/users/:id"
DeleteUserById = "/users/:id"
GetTweets = "/tweets"
CreateTweets = "/tweets"
GetTweetById = "/tweets/:id"
UpdateTweetBy... |
package proxy
type SchemaType string
const (
SchemaHTTP SchemaType = "http://"
SchemaHTTPS SchemaType = "https://"
HTTP_METHOD_GET = "GET"
HTTP_METHOD_POST = "POST"
CONTENT_TYPE_JSON = "application/json"
CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"
CONTENT_TYPE_XML = "application/xml"
HEADER_... |
package material
import (
"github.com/mikee385/GolangRayTracer/color"
)
type Material struct {
Color color.ColorRGB
Diffuse float32
Specular float32
Shininess int
Reflection float32
Refraction float32
RefractiveIndex float32
}
func NewMaterial(color color.ColorRGB) Ma... |
package ssh
import (
"testing"
)
func TestRun(t *testing.T) {
output, error, err := Run("localhost:22", "canux", "canux", "who")
if err != nil {
t.Error("failed")
} else {
t.Log(output)
t.Log(error)
}
}
|
package validator
import (
"fmt"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/authelia/authelia/v4/internal/configuration/schema"
)
const unexistingFilePath = "/tmp/unexisting_file"
func TestShouldSetDefaultServerValues(t *testing.T) {
validat... |
package classic
import (
"encoding/json"
"errors"
"testing"
)
var tasks = []struct {
listRaw []byte
}{
{
listRaw: []byte(`{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}`),
},
{
listRaw: []byte(`{}`),
},
}
func makeLinkedListByJSON(raw []byte) (*List... |
package main
import (
"log"
"strings"
irc "github.com/thoj/go-ircevent"
)
func ircOnCommand(e *irc.Event) {
parts := strings.SplitN(e.Message(), " ", 2)
switch parts[0] {
case "!quit":
if len(parts) > 1 {
app.irc.QuitMessage = strings.TrimPrefix(e.Message(), parts[1])
}
app.irc.Quit()
case "!join":... |
package reports
import (
"net/url"
"strconv"
)
const (
// ReportExportSBOMEndpoint is the endpoint for generating SBOMs
ReportExportSBOMEndpoint = "v1/report/getSBOM"
)
// Standard is a string enum of supported SBOM standards
type Standard string
// Encoding is a string enum of supported file/data encoding stan... |
package stats
import (
mapset "github.com/deckarep/golang-set"
"github.com/idena-network/idena-go/blockchain"
"github.com/idena-network/idena-go/blockchain/types"
"github.com/idena-network/idena-go/common"
"github.com/idena-network/idena-go/common/math"
"github.com/idena-network/idena-go/core/appstate"
"github.... |
package main
import (
"flag"
"log"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/rbxb/signedcookie"
)
var port string
func init() {
flag.StringVar(&port, "port", ":8080", "The port to listen at.")
}
func main() {
flag.Parse()
rand.Seed(time.Now().Unix())
http.HandleFunc("/", serve)
log.Fatal(http... |
package model
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
// GetSVC get DynamoDB SVC
func GetSVC() (*dynamodb.DynamoDB, error) {
session, err := session.NewSession(
&aws.Config{Region: aws.String("ap-northeast-1")},
)
if err ... |
/**
* User: Baoxu
* Date: 13-5-16
* Time: 下午4:07
*/
package main
import (
"net/http"
"log"
"html/template"
"fmt"
)
/**
* 自定义类型,路由控制器
* 根据URI中不同的地址,执行不同的函数
*/
type Router struct {
}
/**
* 路由控制器指定路由之后的处理函数
* 如果是请求根目录,执行此函数
*/
func serverDefault(w http.ResponseWriter, r *http.Request) {
fmt.Println("meth... |
package auth
import (
"net/url"
"reflect"
"testing"
)
func testParse(t *testing.T, header string, fixture Challenge) {
challenge, err := ParseChallenge(header)
if err != nil {
return
}
if expected, actual := fixture.realm.String(), challenge.realm.String(); expected != actual {
t.Fatalf("realm failed to ... |
package persistencetests
import (
"go.temporal.io/server/common/persistence/sql/sqlplugin/mysql"
"go.temporal.io/server/common/persistence/sql/sqlplugin/postgresql"
"go.temporal.io/server/common/service/config"
"go.temporal.io/server/environment"
)
const (
testMySQLUser = "temporal"
testMySQLPassword = "t... |
package xflag
import (
"flag"
"go/build"
"os"
"reflect"
"testing"
"github.com/goaltools/xflag/cflag"
)
var (
f1 = flag.String("key1", "value1_def", "flag from default section, file 1")
f2 = flag.String("section:key1", "value2_def", "flag from `section`, file 2")
f3 = flag.String("arg", "value_def", "flag fr... |
package handlers
import (
"fmt"
"net/url"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/authorization"
"github.com/authelia/authelia/v4/internal/middlewares"
)
func handleAuthzGetObjectAuthRequest(ctx *middlewares.AutheliaCtx) (object authorization.Object, err error) {
var (
target... |
package stuff
type Vitalstats struct {
Name string // freetext
Link string // full url
Power string // more or less freetext
BatteryRem string // ["yes"|"no"|"unk"] (normalized by scraper making best guess)
ReleaseDate string
Type string // so far, ["phone"|"tablet"|"phablet"]
CMSupp... |
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/config"
"github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/logconfig"
"github.com/andywow/golang-lessons/lesson-calendar/internal/calendar/msgsystem/rabbitmq"... |
package line_segment
import (
"math"
"github.com/go-gl/gl/v4.1-core/gl"
"../basic"
)
type bead struct {
prev *basic.Point
current *basic.Point
}
const VertexCount = 32
func NewBead(prev, current *basic.Point) *bead {
b := &bead{
prev: prev,
current: current,
}
return b
}
func (b *bead) color() (floa... |
package humanity
import (
"fmt"
"strconv"
)
type Pilot struct {
*Human
}
func (h *Human) String() string {
return fmt.Sprintf("%v, %v years old from %v", h.Name, strconv.Itoa(h.Age), h.Country)
}
|
package preparer
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"runtime"
"testing"
. "github.com/anthonybishopric/gotcha"
"github.com/gofrs/uuid"
"github.com/square/p2/pkg/artifact"
"github.com/square/p2/pkg/auth"
"github.com/square/p2/pkg/cgroups"
"github.com/square/p2/pkg/launch"
"gi... |
package config
import (
"bytes"
"flag"
"fmt"
"strings"
)
// Config contains values to configure runs.
type Config struct {
// Username is a Github username.
Username string
// Repos contains repository names to run against.
// Multiple values should be separated by comma.
Repos string
// RepoNames contains ... |
/*
Copyright 2020 The SuperEdge 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 silverfish
import (
"errors"
"time"
entity "silverfish/silverfish/entity"
"gopkg.in/mgo.v2/bson"
)
// Auth export
type Auth struct {
hashSalt *string
sessionSalt *string
userInf *entity.MongoInf
sessions map[string]*entity.Session
}
// NewAuth export
func NewAuth(hashSalt *string, userInf... |
package main
import (
"github.com/feng/future/goc/util"
)
func main() {
util.GoSum(4, 5)
}
|
/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... |
package postgres
import (
"github.com/morscino/wallet-engine/utility/config"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func DbConnect(database config.PsqlDatabaseConfig) *gorm.DB {
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: "user=" + database.User + " password=" + database.Passwor... |
// Set client options
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// You will be using this Trainer type later in the program
type Trainer struct {
Name stri... |
package models
import (
"context"
"github.com/misgorod/co-dev/errors"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/gridfs"
"io"
)
type File struct {
ID primitive.ObjectID `json:"id"`
}
func DownloadFile(ctx context.Context, client *mongo.C... |
// 15 april 2015
package pgidl
import (
"fmt"
"io"
)
//go:generate go tool yacc pgidl.y
func Parse(r io.Reader, filename string) (idl IDL, errs []string) {
yyErrorVerbose = true
l := newLexer(r, filename)
yyParse(l)
for _, e := range l.errs {
errs = append(errs, fmt.Sprintf("%s %s", e.pos, e.msg))
}
if len... |
package bootstrap
import (
"k8s.io/apimachinery/pkg/util/sets"
"github.com/openshift/installer/pkg/types"
)
// MergedMirrorSets consolidates a list of ImageDigestSources so that each
// source appears only once.
func MergedMirrorSets(sources []types.ImageDigestSource) []types.ImageDigestSource {
sourceSet := make... |
package pg
import (
"github.com/kyleconroy/sqlc/internal/sql/ast"
)
type CreatePublicationStmt struct {
Pubname *string
Options *ast.List
Tables *ast.List
ForAllTables bool
}
func (n *CreatePublicationStmt) Pos() int {
return 0
}
|
package bclient
import (
"math/big"
)
// EthDaiPrice returns the price of ETH in terms of DAI
func (bc *BClient) EthDaiPrice() (*big.Int, error) {
reserves, err := bc.uc.GetReserves(WETHTokenAddress, DAITokenAddress)
if err != nil {
return nil, err
}
return new(big.Int).Div(reserves.Reserve1, reserves.Reserve0... |
package models
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"gopkg.in/redis.v4"
"log"
"strconv"
)
var Db *gorm.DB
var Redis *redis.Client
func init() {
parseFlag()
var err error
viper.AddConfigPath("config")
err = vip... |
package main
import "fmt"
type animal interface {
move()
speak()
}
type dog struct {
name string
color string
}
type cat struct {
name string
color string
}
func (d dog) move() {
fmt.Printf("%s color is %s,run adn run\n", d.name, d.color)
}
func (d dog) speak() {
fmt.Printf("%s 汪汪汪\n", d.name)
}
func (... |
package main
import (
"fmt"
"net/http"
)
type myHandler struct{}
func main() {
// http.HandleFunc("/", myHandler{})
if err := http.ListenAndServe(":8088", &myHandler{}); err != nil {
fmt.Println(err)
} else {
fmt.Println("serve is start in port:8088..")
}
}
func (this *myHandler) ServeHTTP(rw http.Respo... |
package modules
import (
builderDomain "../../domain/builder"
"../../infrastructure/ssh/builder"
)
type BuilderModule interface {
LoadBuilders() *builderDomain.ISshCommandBuilder
}
func LoadBuilders() builderDomain.ISshCommandBuilder {
sshBuilder := builder.InitSshCommandBuilder()
return sshBuilder
}
|
package main
import (
"fmt"
)
func main() {
f := func(s string) {
fmt.Println("I Assign String value to this func", s)
}
f("Strange")
}
|
package rpcservice
import (
"fmt"
"github.com/goodsign/gosmsc"
. "github.com/goodsign/gosmsc/contract"
"net/http"
)
//Service Definition
type SMSService struct {
senderChecker *gosmsc.SenderCheckerImpl
}
func NewSMSService(senderChecker *gosmsc.SenderCheckerImpl) (*SMSService, error) {
if senderChecker == nil ... |
package group
type insertRequest struct {
BaseGroupId int `json:"baseGroupId"`
Code string `json:"code" validate:"required"`
Description string `json:"description" validate:"required"`
}
func insertRequestConvert(r *insertRequest) *Group {
return &Group{
Code: r.Code,
Description: r.Descripti... |
// Copyright (c) 2017, 0qdk4o. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
package main
import (
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"os"
"github.com/abegin/systemd"
)
func HelloServer(w http.ResponseWrite... |
// struct areform to/as grouping data together
// struct are typed collection of fields
// macam2 koleksi lapangan terdeklarasi{eksplisit}
// struct dari person akan berisi tentang tinggi,usia
// struct dari identitas akan berisi tentang alamat, nama
package main
type person struct {
name string
age int
}
// met... |
package saml
import (
"encoding/base64"
"encoding/pem"
"encoding/xml"
"io/ioutil"
"net/http"
"os"
"sync/atomic"
"github.com/pkg/errors"
)
// ServiceProvider represents a service provider.
type ServiceProvider struct {
MetadataURL string
// Identifier of the SP entity (must be a URI)
EntityID string
//... |
package main
import (
"fmt"
"net/http"
"encoding/json"
)
func VerifySchnorr(w http.ResponseWriter, r *http.Request) {
encoder := json.NewEncoder(w)
var schnorrSignature SchnorrSignature
err := ReadContentsIntoStruct(r, &schnorrSignature)
if err != nil {
encoder.Encode(Response{Err: &Error{Msg: err.E... |
package model
import (
"fmt"
"../compotent"
"../middlerware"
)
type DoraModel struct {
compotent.CurdHandler //数据库连接实例
tn string //数据库名
}
var DoraHandler DoraModel
func init() {
db, err := middlerware.Cont.Get("db")
if err != nil {
panic(fmt.Sprintf("内部错误, error:`%v`", err))
}
... |
/*
* @lc app=leetcode.cn id=50 lang=golang
*
* [50] Pow(x, n)
*/
// @lc code=start
package main
import "fmt"
func main() {
}
func myPow(x float64, n int) float64 {
switch {
case n == 0 || x == 1:
return 1
case n == 1:
return x
case x == 0:
return 0
case
}
if x > 1 && n > 1 {
sum := float64(1) ... |
package main
func callhome() {
}
|
// +build darwin linux
package main
import (
//"math/rand"
//"time"
//"golang.org/x/mobile/app"
//"golang.org/x/mobile/event/key"
//"golang.org/x/mobile/event/lifecycle"
//"golang.org/x/mobile/event/paint"
//"golang.org/x/mobile/event/size"
//"golang.org/x/mobile/event/touch"
//"golang.org/x/mobile/exp/gl/g... |
package main
import (
"log"
"os"
"crypto/x509"
"fmt"
"github.com/olegsmetanin/golang-grpc/api/cert"
api "github.com/olegsmetanin/golang-grpc/api/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
)
const (
port = 10000
d... |
package handler
import (
"context"
"github.com/micro/go-log"
file "bussinessenv/srv/file/proto/file"
)
type File struct {
}
func (f *File) UploadFile(ctx context.Context, req *file.UploadFileRequest, resp *file.Response) error {
log.Log(req.Name)
log.Log(req.File)
return nil
}
func (f *File) DeleteFile(ctx ... |
package model
import (
"time"
)
type Recognize struct {
RecognizeId int `json:"recognize_id"`
RecognizeRestaurantId int `json:"title"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt time.Time `json:"deleted_at"`
}
|
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"regexp"
"strings"
)
type Wiki struct {
/*
JSON構造体定義
書式は:変数名[tab]型名[tab]`json:"キー名"`
# JSON構造体の深さが可変のものは別途定義する必要あり。
*/
Text string `json:"text"`
Title string `json:"title"`
}
func main() {
wiki := []Wiki{}
var check string
re := re... |
package main
import (
"github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter12/kafkaflow"
sarama "github.com/Shopify/sarama"
flow "github.com/trustmaster/goflow"
)
func main() {
consumer, err := sarama.NewConsumer([]string{"localhost:9092"}, nil)
if err != nil {
panic(err)
}
defer consume... |
/*
On Pomax's Primer on Bézier Curves this "fairly funky image" appears:
https://pomax.github.io/bezierinfo/#canonical
This is related to the fact that every cubic Bézier curve can be put in a "canonical form" by an affine transformation that maps its first three control points to (0,0), (0,1) and (1,1) respectively... |
package set
import (
"reflect"
"testing"
)
func TestT(t *testing.T) {
set1, set2 := NewT(reflect.TypeOf(0)), NewT(reflect.TypeOf(0))
set1.Add(1, 2, 3, 4, 5)
set2.Add(3, 4, 5, 6, 7)
t.Run("union", func(t *testing.T) {
list := TUnion(set1, set2).List().([]int)
requireEqualAfterSort(t, []int{1, 2, 3, 4, 5, 6... |
package main
import (
"fmt"
"net/http"
"testing"
"github.com/max0ne/twitter_thing/back/middleware"
"github.com/stretchr/testify/suite"
)
type GetNewUserTestSuite struct {
RouteTestSuite
}
func TestGetNewUserTest(t *testing.T) {
suite.Run(t, new(GetNewUserTestSuite))
}
func signUpForAnotherBunchOfUsers(uname... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.