text stringlengths 11 4.05M |
|---|
package metalgo
import (
sw "github.com/metal-stack/metal-go/api/client/switch_operations"
"github.com/metal-stack/metal-go/api/models"
)
// SwitchListResponse is the response of a SwitchList action
type SwitchListResponse struct {
Switch []*models.V1SwitchResponse
}
// SwitchGetResponse is the response of a Swit... |
package server
import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"sync"
"time"
"github.com/tidwall/resp"
)
// Client is an remote connection into to Tile38
type Client struct {
id int // unique id
replPort int // the known replication port for follower connections
replAd... |
// go_04
package main
import (
"fmt"
)
func main() {
/*if condition {
}else{
}
switch 判断变量 {
case 变量值1:xx1
case 变量值2,变量值3,变量值4:xx2
...
default:xxn+m
}
switch {
case 变量==变量值1:xx1
case 变量==变量值2:xx2
...
def... |
package search
import (
"testing"
"github.com/takatori/mini-search/index"
)
func TestNextPhrase(t *testing.T) {
idx := index.NewIndex(map[string]index.PostingsList{
"first": []*index.Posting{
index.NewPosting(1, []int{2205, 2268, 745406, 745466, 745501, 1271487}),
index.NewPosting(22, []int{265, 235, 360}... |
package gflag
import (
"strings"
"github.com/gookit/gcli/v3/helper"
"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/comdef"
"github.com/gookit/goutil/strutil"
)
func sepStr(seps []string) string {
if len(seps) > 0 {
return seps[0]
}
return comdef.DefaultSep
}
func getRequiredMark(must bool) s... |
package systemdeps
import (
"testing"
google_protobuf "test/system_deps/source_context"
)
func TestSourceContextProto(t *testing.T) {
sc := google_protobuf.SourceContext{}
// These assertions are a bit pointless, essentially compiling this test is
// sufficient to ensure things are working OK. Just want to ensu... |
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/s... |
package main
import (
"context"
"fmt"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"log"
"math/big"
"os"
"os/exec"
"time"
)... |
package fileutil_test
import (
"github.com/APTrust/exchange/util/fileutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"io"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestNewFileSystemIterator(t *testing.T) {
_, filename, _, _ := runtime.Caller(0)
testD... |
package main
import (
"fmt"
"math/rand"
"time"
)
type numbers []string
func main(){
n :=initNumbers()
fmt.Println("Numbers initial sequence :")
n.print()
n.shuffle()
fmt.Println("Numbers after shuffle :")
n.print()
}
func (n numbers) print(){
fmt.Println(n)
}
func initNumbers() numbers{
return []string{"... |
package main
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/protos/msp"
pb "github.com/hyperledger/fabric/protos/peer"
)
type response struct {
OK bool `json:"ok"`
Message string `... |
/*
Copyright 2018 Intel Corporation.
SPDX-License-Identifier: Apache-2.0
*/
// Package testlog provides a logger that outputs
// via testing.T.Log. There are two ways to use it
// inside a test function:
// - `defer testlog.SetGlobal(t)()` will install
// a test logger as global logger and restore
// the previous... |
package stk
import (
"log"
"net/url"
"strconv"
"time"
statuscake "github.com/andrewn3wman7/statuscake"
)
// StkOptions StatusCake CLI Options
type StkOptions struct {
Client statuscake.Client
Tags string
}
// StkAPI handle the basic API config and last data.
type StkAPI struct {
client *statuscak... |
package cli
import (
"errors"
"github.com/koinos/koinos-proto-golang/koinos/protocol"
)
var (
// ErrNoSession no session is in progress
ErrNoSession = errors.New("no session in progress")
// ErrSesionInProgress session is in progress
ErrSesionInProgress = errors.New("session in progress")
)
// PendingOperati... |
package core
import (
"math"
"math/rand"
)
type RefractiveMaterial struct {
RefractiveIndex float64
}
func (mat *RefractiveMaterial) Scatter(rayIn *Ray, hitRecord *HitRecord, attenuation *Col3, scatteredRay *Ray) bool {
ri := mat.RefractiveIndex
if hitRecord.FrontFacing {
ri = 1.0 / ri
}
normalizedInputVec... |
package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/gtfierro/xboswave/ingester/types"
xbospb "github.com/gtfierro/xboswave/proto"
"github.com/immesys/wavemq/mqpb"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus/promhttp"
logrus "githu... |
package constant
const (
StatusError = "Error"
MessageErrorEmptyField = "Data Input Tidak Boleh Kosong"
MessageExpiredJWT = "Token Anda Telah Expired"
MessageFailedJWT = "Unauthorized"
MessageFailedServer = "Gagal Menghubungkan Server"
)
// LOAD ENV
const (
MessageEnvironment = "Gagal L... |
package main
import (
"fmt"
)
/**
* created: 2019/5/13 8:50
* By Will Fan
*/
func main() {
data := []*struct{num int} {{1}, {2}, {3}}
for _, v := range data {
v.num *= 10
}
fmt.Println("data", data[0],data[1], data[2])
}
|
package micro
import "testing"
func TestFormatName(t *testing.T) {
t.Log(FormatName("ByAccountId-Chain"))
}
|
package model
// User is a user account.
type User struct {
Name string
Email string
Hash string
Roles []Role
}
|
package auth
import (
"fmt"
"net/http"
"os"
"strings"
log "github.com/sirupsen/logrus"
"github.com/dgrijalva/jwt-go"
"github.com/walln/flurry2/flurry/global"
)
func AuthenticateWithFirebase(w http.ResponseWriter, r *http.Request) bool {
logger := log.WithFields(log.Fields{
"Proxy Route": r.URL.Request... |
// Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
package gallery
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/bborbe/http/client"
"github.com/bborbe/http/requestbuilder"
"github.com/bborbe/log"
"github.com/bborbe/www/config"
)
const (
GROUP_TOP_NAVI = "naviTop"
GROUP_BOTTOM_NAVI = "naviBottom"
COLLECTION_TOP_BEAUT... |
package sqlstore
import (
"database/sql"
"github.com/igogorek/http-rest-api-go/internal/app/store"
_ "github.com/lib/pq"
)
type Store struct {
db *sql.DB
userRepository *UserRepository
}
func New(db *sql.DB) store.Store {
return &Store{
db: db,
}
}
func (st *Store) User() store.UserRepository {... |
package pusher
type Message struct {
Event string `json:"event"`
Channel string `json:"channel"`
Data interface{} `json:"data"`
}
func NewSubscribeMessage(channel string) *Message {
return &Message{"pusher:subscribe", "", map[string]string{"channel": channel}}
}
func NewPongMessage() *Message {
r... |
package piscine
func StrLen(str string) int {
z := 0
for range str {
z++
}
return z
}
|
package Sync
const (
maxRetriesServer = 16 // How many retries are allowed to create the SSH server's connection?
)
|
package main
import (
"log"
"math"
c "arkanoid/components"
e "arkanoid/ecs"
m "arkanoid/math"
"arkanoid/systems/sprite"
"github.com/hajimehoshi/ebiten"
"github.com/hajimehoshi/ebiten/ebitenutil"
)
const (
windowWidth = 720
windowHeight = 600
)
type game struct {
ecs e.Ecs
}
func (g game) Layout(outsid... |
package elasticsearch
import (
"context"
"github.com/elastic/go-elasticsearch/v8"
)
type ClientChecker struct {
client *elasticsearch.Client
}
func (c *ClientChecker) Check(ctx context.Context) error {
_, err := c.client.Ping(c.client.Ping.WithPretty())
return err
}
func NewClientChecker(client *elasticsearch... |
package main
import (
"flag"
"fmt"
"os"
"github.com/xuqingfeng/devops"
)
const (
VERSION = "0.3.0"
)
func main() {
version := flag.Bool("v", false, "version")
flag.Parse()
if *version {
fmt.Printf("%s\n", VERSION)
os.Exit(0)
}
if len(flag.Args()) != 1 {
fmt.Printf("E! %v\n", devops.ErrParamNum)
... |
package main
// Transaction encapsulates one transaction data
type Transaction struct {
Amount int `json:"amount"`
Currency string `json:"currency"`
StatusCode int `json:"statusCode"`
OrderReference string `json:"orderReference"`
TransactionID string `json:"transactionId"`
}
// Params to... |
package hranking
import (
"fmt"
"strconv"
"testing"
"time"
)
func TestRanking(t *testing.T) {
count := 100 * 10000
r := NewRanking()
nums := createNums(count)
startTime := time.Now()
for k, v := range nums {
r.Set(Key(k), Value(v)) // 乱序插入
}
fmt.Printf("write useTime:%.2fs\n", time.Now().Sub(startTime).S... |
package routing_table
import "sync"
type RoutingTableInterface interface {
Sync(routes RoutesByProcessGuid, containers ContainersByProcessGuid) MessagesToEmit
MessagesToEmit() MessagesToEmit
SetRoutes(processGuid string, routes ...string) MessagesToEmit
RemoveRoutes(processGuid string) MessagesToEmit
AddOrUpdat... |
package eval
import (
"bufio"
"fmt"
"os"
)
func EvalLoopDriver(input string) {
env := initEnv()
sentences := CodeSplit(input)
var rel interface{}
for _, exp := range sentences {
sentence := buildSentence(exp)
switch expType(sentence) {
case ANNOTATION:
continue
case CALL:
rel = executeCall(senten... |
package google
import (
"strings"
"time"
"universe/data"
"universe/db"
"github.com/andy-zhangtao/golog"
)
// Save 保存检索到底数据
func (g Google) Save(key string, result []*data.Result) error {
for _, item := range result {
link := &data.DLink{
Name: key,
Title: item.Title,
Link: item.Link,
Sn... |
package main
import "testing"
func TestConcept(t *testing.T) {
result := abidesByPolicyPuzzle2()
}
|
/*
*ssdb asynchronous API : Copyright to qudreams(2014)
*All rights reserved.
*Note:
*It depend on ssdb synchronous client.
*You can find more detailed documention about SSDB protocol at
* http://www.ideawu.com/ssdb
*/
package ssdb
import (
"bytes"
"errors"
"fmt"
"sync"
)
type CntlCode byte
const (
_ Cn... |
package main
import "fmt"
func main() {
mc := &monteCarlo{actions: 3, learn: true, eps: 0.00}
mc.init()
p := &perfect{}
// MonteCarlo vs. Perfect -> MC learns to beat perfect in 50% of all games :)
fmt.Println("\nMonte Carlo vs Perfect")
players := []Agents{mc, p}
playN(players, 1000, false)
// freeze learn... |
package backspaceCompare
// Helper function for backspaceCompare to retrieve a character according
// to the input index.
func getChar(str string, curr_index int) (char byte, next_index int) {
if curr_index < 0 {
char = ' '
next_index = -1
return
}
char = str[curr_index]
next_index = curr_index
if char ==... |
package router
import (
"portal/controller"
"portal/controller/captcha"
"portal/controller/user"
"portal/controller/role"
"portal/controller/app"
"portal/controller/menu"
"portal/controller/inter"
"portal/controller/permission"
"portal/controller/resource"
"portal/controller/openAuth"
"portal/middleware"
... |
package main
import (
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/blang/semver"
"github.com/rhysd/go-github-selfupdate/selfupdate"
"github.com/go-task/task/v2"
"github.com/go-task/task/v2/internal/args"
"github.com/spf13/pflag"
)
var (
version = "master"
repo = "go-task/task"
)
const usa... |
package dynamodb
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
// GetTypesAttrDefs returns the definitions
func GetTypesAttrDefs() []*dynamodb.AttributeDefinition {
return []*dynamodb.AttributeDefinition{{
AttributeName: aws.String("Type"),
AttributeType: aws.String("S... |
package users
import (
"github.com/gin-gonic/gin"
)
func UsersRoute(publicApi *gin.RouterGroup) {
usersGroup := publicApi.Group("/users")
{
usersGroup.GET("/list", GetUserList)
}
} |
package user
import "time"
type User struct {
Id int
Name string
RegisterDate time.Time
Status bool
}
func (this *User) UserRegistry(id int, name string, registerDate time.Time, status bool) {
this.Id = id
this.Name = name
this.RegisterDate = registerDate
this.Status = status
}
|
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/labstack/echo"
)
type config struct {
Port int
ConfigLocation string
}
var realConfig config
func main() {
argsWithoutProg := os.Args[1:]
if len(argsWithoutProg) == 0 {
log.Fatal("Please provide config... |
package main
import (
"sample/gen-go/Sample"
"sample/gen-go/timerpc"
"sample/internal/service"
"sample/rpc"
)
func main() {
startTriftServer()
}
func startTriftServer() {
handlers := make([]rpc.ThriftHandlers, 0, 2)
handlers = append(handlers, rpc.ThriftHandlers{ServiceName: "greeterService", Pro... |
package main
import (
"testing"
)
// go test -bench=.
// PASS
// BenchmarkTemplateRender1-4 500000 3209 ns/op
// BenchmarkTemplateRender10-4 100000 23998 ns/op
// BenchmarkTemplateRender100-4 10000 230203 ns/op
// BenchmarkTemplateRender1000-4 1000 2299531 ns/op... |
package main
import (
"bufio"
"fmt"
"strings"
"os"
"strconv"
)
type point struct {
x int
y int
}
func (c *point) dist() (int) {
return abs(c.x) + abs(c.y)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
func ReadLines(filePath string) (f [2][]string) {
fileHandle,_ := os.Open(filePath)
d... |
package main
import (
"fmt"
"sort"
)
func main() {
test := []int{2, 3, 5, 1, 6}
k := 2
count := 0
count2 := 0
//var ansArray []int
total := 0
maxvar := 0
if k == 1 {
sort.Ints(test)
fmt.Println(test[len(test)-1])
return
}
for i := 0; i < len(test); i++ {
count++
if count == k {
count2++
... |
package main
import (
"fmt"
"log"
"os"
)
//basic registration system
func main() {
f, err := os.Create("dados.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
for i := 1; i > 0; i++ {
var (
nome string
idade string
)
fmt.Println("Seu nome:")
fmt.Scanln(&nome... |
package gatewaySDK
import (
"bytes"
"encoding/json"
"net/http"
"os"
)
var API_GATEWAY = os.Getenv("API_GATEWAY")
func SetGatewayURI(s string) {
API_GATEWAY = s
}
type Service struct {
NAME string `json:"service_name"`
URL string `json:"url"`
}
func RegisterService(s Service) (bool, error) {
body, _ := jso... |
package logger
type NilLogger struct{}
func NewNilLogger() *NilLogger {
return &NilLogger{}
}
func (this *NilLogger) Log(message string) error {
return nil
}
|
package cmd
import (
"errors"
"io/ioutil"
"os"
"regexp"
"testing"
"github.com/spf13/cobra"
)
func TestDoCmd(t *testing.T) {
dotestSuit := []struct {
args []string
expected string
}{
{args: []string{"1", "2", "3", "4"}, expected: `1. do testing2. do development3. do deployment4. do release`},
{arg... |
// Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package al implements the Go bindings of a subset of the functions of the OpenAL C library.
// The OpenAL documentation can be accessed at https://open... |
package realm
import (
"encoding/json"
"fmt"
"net/http"
"github.com/10gen/realm-cli/internal/utils/api"
)
const (
draftsPathPattern = appPathPattern + "/drafts"
draftPathPattern = draftsPathPattern + "/%s"
draftDeployPathPattern = draftPathPattern + "/deployment"
draftDiffPathPattern = draftPath... |
package errors
import (
"errors"
"fmt"
"runtime"
"strings"
)
// Error represents the error struct that should be returned in all functions
// Error implements the Go's error interface
type Error struct {
Severity Severity
Err error
Code Code
Op Op
KVs []KeyValue
}
func (e Error) Error() ... |
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"github.com/miekg/dns"
)
func main() {
srv := &dns.Server{Addr: ":53", Net: "udp"}
go srv.ListenAndServe()
dns.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative = true
w.WriteMsg(m)
fmt.... |
package db
import (
"testing"
"fmt"
)
func TestDbConnect(t *testing.T) {
Connect(TEST_DB_CONNECT)
defer SafeClose()
_, err := MySQL.Exec(`INSERT INTO person (name, phone) VALUES ("golang", 123456), ("golang2", 123456)`)
if err != nil {
fmt.Println(err.Error())
}
rows, err := MySQL.Query("SELECT * FROM per... |
package ch05
import "errors"
// Given a list of n elements, write an algorithm to find three elements in a list whose sum is a given value.
// Hist: Try to do this problem using a brute fore approach. Then try to apply the sorting approach along with brute force approach.
// The time complexity will be O(n2)
var err... |
package repository
import (
"database/sql"
_ "github.com/lib/pq"
"kz.nitec.digidocs.pcr/pkg/logger"
)
type ServiceRepository struct {
db *sql.DB
}
func NewServiceRepository(db *sql.DB) *ServiceRepository {
return &ServiceRepository{db: db}
}
func (repo *ServiceRepository) GetServiceIdByCode(code string) (strin... |
package mgr
import (
"errors"
"fmt"
"sync/atomic"
"time"
"github.com/qiniu/log"
"github.com/qiniu/logkit/metric"
"github.com/qiniu/logkit/sender"
"github.com/qiniu/logkit/utils"
)
const (
KeyMetricType = "type"
)
const (
defaultCollectInterval = "3s"
)
type MetricRunner struct {
RunnerName string `json:... |
// Copyright (c) 2015-2017 Marcus Rohrmoser, http://purl.mro.name/recorder
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights t... |
package updater
import (
"bytes"
"io/ioutil"
"os"
"path"
)
// Remote directory
type RemotePath struct {
Username string // Sent via HTTP BASIC authorization
Password string // Sent via HTTP BASIC authorization
Path string // Typically a URL (eg https://deploy.imqs.co.za/files/stable)
}
// A directory that... |
package kmap
import (
"database/sql"
"fmt"
"strconv"
"strings"
"time"
)
type Map map[string]interface{}
func Make() Map {
return make(Map)
}
// Returns the map value as a string.
func (m Map) String(name string) string {
if m[name] == nil {
return ""
}
switch t := m[name].(type) {
case []by... |
package main
import (
"bytes"
"strconv"
"strings"
"testing"
)
func ExpectEqual(t *testing.T, expect, actual string) {
if expect != actual {
t.Errorf("Got %s, want %s", actual, expect)
}
}
func TestClientHandlerStart(t *testing.T) {
r := strings.NewReader("GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n")
w ... |
package cutout
import (
"net/http"
"time"
)
// CircuitBreaker is the circuit breaker!!!
type CircuitBreaker struct {
FailThreshold int
HealthCheckPeriod time.Duration
events chan string
state string
lastFailed *time.Time
failCount int
analytics *Analytics
}
... |
package waveform
import "errors"
// Wav struct
type Wav struct {
WaveFormat WaveFormat
NumChannels uint16
SampleRate uint32
BitsPerSample uint16
DataChuckSize uint32
Data []byte
}
// GetData get wav audio data
func (w *Wav) GetData() (interface{}, error) {
bytePerSample := int(w.BitsPerSample / 8)
s... |
package service
import (
"errors"
"fmt"
"sort"
"time"
"sync"
"github.com/TianqiuHuang/grpc-fight-app/pkg/module"
gc "github.com/patrickmn/go-cache"
)
// ErrorNotFound ...
var ErrorNotFound = errors.New("session not found")
type sessions struct {
cache *gc.Cache
signal chan struct{}
lock sync.Mutex
}
... |
package chat
import(
"GoAPI/model"
)
type SendMessageRequest struct {
Username string `json:"username"`
Aim string `json:"aim"`
MessageType uint32 `json:"messagetype"`
Content string `json:"content"`
PushTime uint64 `json:"pushtime"`
}
type SendMessageResponse struct {
Username string `json:"username"`
}
typ... |
package main
import "fmt"
func main() {
fmt.Println("quicksort")
fmt.Println(quicksort([]int{1, 0, 8, 5, 2, 4, 9, 7, 6, 3}))
}
func quicksort(array []int) []int {
fmt.Println("input", array)
sorter(array, 0, len(array)-1)
return array
}
func sorter(array []int, start, finish int) {
if start < finish {
pivo... |
package runnertest
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/etf1/kafka-message-scheduler-admin/server/config"
log "github.com/sirupsen/logrus"
)
func getSchedulers(timeout time.Duration) (resp *http.Response, err error) {
return get("/schedulers", timeout)
}
func getSchedules(schedul... |
package global
import "github.com/garyburd/redigo/redis"
/**
* @Author: super
* @Date: 2021-03-18 19:59
* @Description:
**/
var (
RedisEngine *redis.Pool
)
func GetConn() redis.Conn {
return RedisEngine.Get()
}
|
package tools
//NotEmptyAll is not empty for all
func NotEmptyAll(str ...string) bool {
if len(str) == 0 {
return false
}
for i := 0; i < len(str); i++ {
if str[i] == "" {
return false
}
}
return true
}
//MapToString is used for k8s select string from map convert
func MapToString(labels map[string]strin... |
package sshtarget
import (
"context"
errors2 "errors"
"io"
"sync"
"github.com/pkg/errors"
"github.com/rwool/ex/ex/internal/recorder"
"github.com/rwool/ex/ex/internal/signal"
"github.com/rwool/ex/log"
)
// ErrCancelledByTarget indicates command was cancelled indirectly by the
// target.
var ErrCancelledByTarg... |
/*
This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines.
The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output.
The aim, as with most ... |
// Copyright 2014 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.
// Package xmpp provides functionality from the Extensible Messaging and
// Presence Protocol, sometimes known as "Jabber".
//
// It is subdivided into several packag... |
package main
import (
"context"
"errors"
"log"
"net"
"github.com/lab5e/lmqtt/pkg/entities"
"github.com/lab5e/lmqtt/pkg/lmqtt"
"github.com/lab5e/lmqtt/pkg/packets"
)
// This is stub handlers for the simple server.
func onAccept(ctx context.Context, conn net.Conn) bool {
log.Printf("onAccept: %s", conn.Remote... |
package main
import (
"fmt"
_ "fmt"
"os"
)
/**
1. package main
2. func main()
3. main() 不能有返回值 os.Exit(int code)
4. 无法通过过 main() 传递参数
*/
func main() {
if len(os.Args) > 1 {
fmt.Print("Hello World", os.Args[1])
}
os.Exit(1)
}
|
package main
// Simple drawing application.
func main() {
NewAppMain()
}
|
package main
import "fmt"
// 自定义错误接口
type MyError struct {
Msg string
Err error
}
func (me *MyError) Error() string {
return me.Msg
}
type Geter interface {
Get() string
}
type User struct {
Name string
Age int
}
func (u User) Get() string {
return u.Name
}
func main() {
user := &User{
Name: "test",
... |
package main
import "fmt"
import "io/ioutil"
import "strings"
import "strconv"
var idealFrequencyAZ = []float64{
0.081, // A
0.014, // B
0.027, // C
0.043, // D
0.127, // E
0.022, // F
0.020, // G
0.061, // H
0.070, // I
0.002, // J
0.008, // K
0.040, // L
0.024, //... |
package senders
import (
"context"
"fmt"
"github.com/Laisky/go-fluentd/libs"
"github.com/Laisky/go-utils"
"github.com/Laisky/zap"
)
// NullSenderCfg configuration of NullSender
type NullSenderCfg struct {
Name, LogLevel string
Tags []string
NFork, InChanSize ... |
package loadbalancer
import (
"net/rpc"
"github.com/hashicorp/go-plugin"
"github.com/jonmorehouse/gatekeeper/gatekeeper"
"github.com/jonmorehouse/gatekeeper/internal"
)
type AddBackendArgs struct {
Backend *gatekeeper.Backend
Upstream gatekeeper.UpstreamID
}
type AddBackendResp struct {
Err *gatekeeper.Error... |
package routers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/context/param"
)
func init() {
beego.GlobalControllerRouter["ecnu_code/backend/controllers:ActivityController"] = append(beego.GlobalControllerRouter["ecnu_code/backend/controllers:ActivityController"],
beego.ControllerCommen... |
package model
import (
"os"
"io/ioutil"
"encoding/json"
"log"
"bytes"
"time"
"github.com/ystyle/phoneix/utils"
"errors"
)
type JenkinsServer struct {
Id string `json:"id"`
Name string `json:"name"`
Url string `json:"url"`
User string `json:"user"`
Passwd string `json:"passw... |
package http_server
import (
"github.com/gorilla/mux"
"github.com/jsagl/go-from-scratch/usecase"
"go.uber.org/zap"
"net/http"
)
func NewHTTPServer(logger *zap.SugaredLogger, usecase usecase.RecipeUseCaseInterface) {
logger.Infow("Setting up router...")
router := mux.NewRouter()
recipeHandler := NewRecipeHandl... |
package leetcode
import "testing"
func TestFib(t *testing.T) {
if fib(0) != 0 {
t.Fatal()
}
if fib(2) != 1 {
t.Fatal()
}
if fib(3) != 2 {
t.Fatal()
}
if fib(4) != 3 {
t.Fatal()
}
}
|
package usecase
import (
"fmt"
"strings"
"time"
entity "silverfish/silverfish/entity"
"github.com/PuerkitoBio/goquery"
"github.com/axgle/mahonia"
"github.com/sirupsen/logrus"
)
// Fetcher77xsw export
type Fetcher77xsw struct {
Fetcher
charset string
decoder mahonia.Decoder
}
// NewFetcher77xsw export
fun... |
package scsprotov1
import (
"encoding/binary"
"errors"
"math"
)
func Float32bytes(float float32) []byte {
bits := math.Float32bits(float)
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, bits)
return bytes
}
func readBinString(message []byte) (string, uint, error) {
if len(message) == 0 {
retu... |
package asshat
import (
"regexp"
"testing"
"github.com/stretchr/testify/require"
"go.coder.com/hat"
)
// BodyEqual checks if the response body equals expects.
// Use BodyStringEqual instead of casting `expects` from a string so
// the error message shows the textual difference.
func BodyEqual(expects []byte) ha... |
package routes
import (
"net/http"
"strconv"
"github.com/labstack/echo"
"github.com/vsabreu/go-echo-tests/models"
)
var (
users map[int]*models.User
usersSeq int
)
func init() {
users = make(map[int]*models.User)
}
// GetUsers retrieves all users
func GetUsers(c echo.Context) error {
u := []*models.User... |
package h3zone
import "github.com/uber/h3-go"
const (
MinLevel = 0
MaxLevel = 15
)
var edgeLengthKm = []float64{
1107.712591, 418.6760055, 158.2446558, 59.81085794,
22.6063794, 8.544408276, 3.229482772, 1.220629759,
0.461354684, 0.174375668, 0.065907807, 0.024910561,
0.009415526, 0.003559893, 0.001348575, 0.00... |
package dock
import (
"os/exec"
"log"
"strings"
)
var shellFunc func(nodeName string, args ...string) (out string)
func SetShell(shell func(nodeName string, args ...string) (out string)) {
shellFunc = shell
}
func defaultShell(nodeName string, args ...string) string {
var sshHost, sshPort string
{
a := stri... |
package main
import (
"testing"
"github.com/hashicorp/packer/packer"
)
func TestPostProcessor_ImplementsPostProcessor(t *testing.T) {
var _ packer.PostProcessor = new(CaryatidPostProcessor)
}
|
package graphql
type CodexCategory struct {
ID string `json:"id"`
Name string `json:"name"`
}
type Course struct {
ID string `json:"id"`
Name string `json:"name"`
CodexCategories []CodexCategory `json:"codexCategories"`
}
type CourseEdge struct {
Course Course `json:... |
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"path"
"sort"
"strconv"
"github.com/flynn/flynn/blobstore/backend"
"github.com/flynn/flynn/blobstore/data"
"github.com/flynn/flynn/discoverd/client"
"github.com/flynn/flynn/pkg/httphelper"
"github.com/flynn/flynn/pkg/postgres"
"github.com/flynn/... |
package cache
import (
"encoding/csv"
"fmt"
"os"
"sync"
"github.com/pilillo/igovium/utils"
)
var csvFormatterOnce sync.Once
var csvFormatterInstance *csvFormatter
type csvFormatter struct{}
// NewCSVFormatter ... constructor of FormatManager of csv type
func NewCSVFormatter() FormatManager {
return &csvForma... |
package initDB
import (
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
func DbInit() *gorm.DB {
db := NewConn()
db.DB().SetMaxOpenConns(10)
db.DB().SetMaxIdleConns(10)
db.LogMode(true)
// 自动迁移模式
//db.AutoMigrate(&model.UserModel{})
return db
}
func NewConn() *gorm.DB {
db, err := gorm.Op... |
/*
Copyright [2015] Alex Davies-Moore
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, soft... |
package main
import (
"crypto/rand"
"flag"
"log"
"net"
"time"
)
var (
listenAddr string
delayTime time.Duration
nBytes int
)
func init() {
flag.StringVar(&listenAddr, "l", "0.0.0.0:5678", "listen address")
flag.DurationVar(&delayTime, "t", 100*time.Millisecond, "delay time")
flag.IntVar(&nBytes, "n",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.