text stringlengths 11 4.05M |
|---|
package token
import (
"testing"
"net/http"
"fmt"
"encoding/json"
"reflect"
"time"
"errors"
"github.com/danielsomerfield/authful/server/service/oauth"
"net/http/httptest"
"github.com/danielsomerfield/authful/server/handlers"
)
var validClientId = "valid-client-id"
var validClientSecret = "valid-client-secre... |
package websockets
import (
"github.com/bakape/meguca/util"
"sync"
"time"
)
// Subs is the only instance of SubscriptionMap in this running instance, that
// constains and manages all active subscriptions
var Subs = SubscriptionMap{
subs: make(map[uint64]*Subscription),
}
// SubscriptionMap contains all active S... |
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
)
type (
Response struct {
TotalResults int `json:"total_results"`
Page int `json:"page"`
PerPage int `json:"per_page"`
Photos []Phot... |
package main
import "fmt"
func main() {
b := true
if ninja := "Shikamaru"; b {
fmt.Println(ninja)
}
}
// Shikamaru
|
package gofinancial
import (
"fmt"
"math"
"testing"
"github.com/smartystreets/assertions"
"github.com/razorpay/go-financial/enums/paymentperiod"
)
func Test_Pmt(t *testing.T) {
type args struct {
rate float64
nper int64
pv float64
fv float64
when paymentperiod.Type
}
tests := []struct {
name... |
package wiki
type WikiService interface {
}
type wikiService struct {
}
func NewWikiService() *wikiService {
s := new(wikiService)
return s
}
|
package question
// DropDown a type of question
type DropDown struct {
*Base
Options []*SelectOptions `json:"options"`
}
// SelectOptions to provide options for a drop down
type SelectOptions struct {
Key string
Value string
}
// MultiSelect a type of question
type MultiSelect struct {
*DropDown
Multiple boo... |
package resolver
import (
"github.com/taktakty/netlabi/testdata"
"github.com/stretchr/testify/require"
"strings"
"testing"
)
func TestHostOSQueries(t *testing.T) {
testData := hostosTestData
t.Run("GetSingle", func(t *testing.T) {
p := string(testData[0].ID)
q := strings.Join([]string{`query {getHostOS(inp... |
package node
import (
"context"
"encoding/json"
"fmt"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
"sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage.k8s.io/v1alpha1"
... |
package countgoodtriplets
import (
"math"
)
func countGoodTriplets(arr []int, a int, b int, c int) int {
n := len(arr)
res := 0
for i := 0; i < n-2; i++ {
for j := 0; j < n-1; j++ {
for k := 0; k < n; k++ {
va, vb, vc := arr[i], arr[j], arr[k]
if int(math.Abs(float64(va-vb))) <= a && int(math.Abs(flo... |
package cfg
import (
"os"
"testing"
)
type optionsDefaultExample struct {
Str string `default:"127.0.0.1"`
Int int `default:"4080"`
Uint uint16 `default:"16"`
}
func TestDefaultsOpt(t *testing.T) {
opt := &optionsDefaultExample{}
err := Parse(emptyGetter, opt)
if err != nil {
t.Fatalf("Parse failed wi... |
package ratecounter
import (
"fmt"
"io/ioutil"
"testing"
"time"
)
func TestRateCounter(t *testing.T) {
interval := 50 * time.Millisecond
r := NewRateCounter(interval)
check := func(expected int64) {
val := r.Rate()
if val != expected {
t.Error("Expected ", val, " to equal ", expected)
}
}
check(0)... |
package henchman
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"strings"
)
type PlanProxy struct {
Name string `yaml:"name"`
Sudo bool `yaml:"sudo"`
TaskProxies []*TaskProxy `yaml:"tasks"`
VarsProxy *VarsProxy `yaml:"vars"`
InventoryGroups []string `yaml:"h... |
package testFunctions
import (
"encoding/csv"
"fmt"
"io"
"os"
)
var path_list string = "D:/workspace/stock/stock_data_cleaner/tehran_watch_list.json"
var path_src_dir string = "D:/workspace/stock/tseclient/normal/"
var path_dst_dir string = "D:/workspace/stock/tseclient/tmp/"
func csvExport(data [][]string, out ... |
package apicore
import (
"errors"
"net/http"
)
func Run(host string) error {
return http.ListenAndServe(host, &server{})
}
type server struct{}
func (s *server) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
ctx := NewConn(request, writer)
// 寻找路径,匹配处理方法
for matcher, generator := range handleM... |
package readers
import (
"os"
"net"
"net/http"
"log"
"io"
)
func GetHttpReader(uri string) io.Reader{
get, err := http.Get(uri); if err != nil{
log.Fatal(err)
}
return get.Body
}
func GetFilesystemReader(uri string) io.Reader{
log.Println(uri)
f, err := os.Open(uri); ... |
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"main/robot"
)
func main() {
done := make(chan bool)
robots, err := getRobots()
if err != nil {
fmt.Println(err)
}
var rb robotInfo
for _, rb = range robots {
robot.Run(rb.Username, rb.Password, rb.Secret)
}
<-done
}
type robotInfo s... |
package utils
import (
"KServer/library/kiface/iwebsocket"
"gopkg.in/yaml.v3"
"io/ioutil"
"os"
)
/*
存储一切有关Zinx框架的全局参数,供其他模块使用
一些参数也可以通过 用户根据 zinx.json来配置
*/
type GlobalObj struct {
/*
Server
*/
TcpServer iwebsocket.IServer //当前Zinx的全局Server对象
Host string `yaml:"Host"` //当前服务器主机IP
TcpP... |
package Map
import (
"testing"
)
func TestLinkedListMap(t *testing.T) {
m := new(LinkedListMap)
sample := [][2]interface{}{
{"a", "A"},
{"b", "B"},
{"c", "C"},
{"d", "D"},
{1, 1},
}
for _, v := range sample {
m.Set(v[0], v[1])
}
if m.Get("a") != "A" {
t.Error("a!=A")
}
if m.Get("b") != "B" ... |
package main
import "fmt"
//map
func main() {
var m = map[string]int{"A": 100, "B": 300}
fmt.Println(m)
m2 := map[string]int{"N": 879, "K": 723982}
fmt.Println(m2)
//改行する場合は巻末にコロンをつける
m3 := map[int]string{
1: "A",
2: "I",
}
fmt.Println(m3)
m4 := make(map[int]string)
m4[0] = "JAPAN"
m4[2] = "USA"
... |
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
"github.com/miekg/dns"
)
const defaultTarget = "myip.opendns.com"
const defaultServer = "resolver1.opendns.com"
const defaultC... |
package draw
import (
"os"
"path/filepath"
)
var SystemInstace *System
const (
LANGUAGE_CHINESE_ENGLISH = 0x0409
LANGUAGE_CHINESE_SIMPLE = 0x0804
LANGUAGE_CHINESE_TW = 0x0404
LANGUAGE_CHINESE_HK = 0x0C04
LANGUAGE_CHINESE_SGP = 0x1004
)
type System struct {
languaeId int
rootPath string
}
f... |
package main
import (
"context"
"log"
"os"
"github.com/dapr/go-sdk/client"
"github.com/dapr/go-sdk/service/common"
"github.com/dapr/go-sdk/service/http"
"github.com/ohler55/ojg/oj"
"github.com/rs/xid"
)
func main() {
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)
s ... |
package main
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
g "github.com/eonpatapon/contrail-gremlin/gremlin"
"github.com/eonpatapon/contrail-gremlin/utils"
"github.com/eonpatapon/gremlin"
"github.com/jawher/mow.cli"
logging "github.com/op/go-logging"
"github.com/... |
// +build OMIT
package sample
import "encoding/json"
//START OMIT
func LoadStruct(data []byte) (output JSONData) {
json.Unmarshal(data, &output)
return output
}
//END OMIT
|
package schema
// How to find details about a table
// Get the columns from a schema table
// Get the path of where the table is stored from table name
// Each table is a new file
import (
// "fmt"
"github.com/chaitya62/noobdb/buffer"
"github.com/chaitya62/noobdb/storage/disk"
"github.com/chaitya62/noobdb/storage... |
package app
import (
"fmt"
"strings"
)
func ValidateShortURL(baseURL, url string, resultChan chan error) {
if !strings.Contains(url, baseURL) {
resultChan <- fmt.Errorf("URL is not valid for this service")
return
}
resultChan <- nil
}
|
package module
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/garyburd/redigo/redis"
"github.com/zieckey/simgo"
)
type IdGenerator struct {
RedisPool *redis.Pool
}
func New() *IdGenerator {
m := &IdGenerator{}
return m
}
func (m *IdGenerator) Initialize() error {
fw := s... |
package seed
import (
"log"
"git.roosoft.com/bitcoin/hd-wallets/lib"
"github.com/tyler-smith/go-bip32"
)
var km *lib.KeyManager
var masterKey *bip32.Key
func init() {
var err error
km, err = lib.NewKeyManagerFromMnemonic(lib.Mnemonic, lib.Passphrase)
if err != nil {
log.Fatal(err)
}
masterKey, err = km.... |
package database
import "github.com/jinzhu/gorm"
type DataBase struct {
DB *gorm.DB
}
var DataBaseObject DataBase
|
// Package imdb provides easy access to publicly available data on IMDB.
// Items are accessed by their IMDB ID, and all getter methods called
// on them are lazy (an http request will be made only when data is needed,
// and this will happen only once). There is also a convenience AllData()
// method, which fetches al... |
package util
import (
"io/ioutil"
"net/http"
)
//获取目标url的内容
func GetContent(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
io, err := ioutil.ReadAll(resp.Body)
return io, err
}
|
package api
import (
"fmt"
"net/http"
"time"
"tynmarket/coffeehub-go/model"
"tynmarket/coffeehub-go/serializer"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
"github.com/jinzhu/gorm"
"github.com/k0kubun/pp"
)
// Coffee bind params
type cffeeBind stru... |
//usr/bin/env go run $0 ;exit
// chmod +x script.go and run this file as a script:
// ./script.go
package main
func main() {
println("Hello from script!")
}
|
package usecase
import (
md "bareksa-test/model"
st "bareksa-test/struck"
"context"
)
type TagsUsecase struct {
tagsRepository md.TagsUsecase
}
func InitiateTagsUsecase(tagsRepository md.TagsRepository) md.TagsUsecase {
return &TagsUsecase{
tagsRepository: tagsRepository,
}
}
func (u *TagsUsecase) Add(ctx c... |
package config_test
import (
"os"
"testing"
"tagallery.com/api/config"
)
func TestLoad(t *testing.T) {
configuration := config.Load()
if configuration.Database != "tagallery" {
t.Error("Load() should set the default settings.")
}
if configuration != config.Get() {
t.Error("Get() should return the same c... |
// Package error implements generic tooling for tracking RFC 2119
// violations and linking back to the appropriate specification section.
package error
import (
"fmt"
"strings"
)
// Level represents the RFC 2119 compliance levels
type Level int
const (
// MAY-level
// May represents 'MAY' in RFC 2119.
May Lev... |
package heartbeat
import "testing"
func TestDoWork_GeneratesAllNumbers(t *testing.T) {
done := make(chan interface{})
defer close(done)
intSlice := []int{0, 1, 2, 3, 5}
heartbeat, results := DoWorkDelay(done, intSlice...)
<-heartbeat
i := 0
for r := range results {
if expected := intSlice[i]; r != expected ... |
package template
const (
//数据库连接模版
cfgDbconn = `#数据库连接
mode = debug
#调试模式段
[debug]
jdcore = jiudeng:jiudeng2016@tcp(10.0.0.13:3306)/jdcore?charset=utf8mb4&loc=Asia%2fShanghai
jdapp = jiudeng:jiudeng2016@tcp(10.0.0.13:3306)/jdapp?charset=utf8mb4&loc=Asia%2fShanghai
jdweb = jiudeng:jiudeng2016@tcp(10.0.0.13:3306)/jdwe... |
package impl
import (
. "vericomp/hash/SWIFFT"
)
func TranslateToBase256(input []int, output []byte) int {
pairs := make([]int, EIGHTH_N / 2);
for i := 0; i < EIGHTH_N; i += 2 {
// input[i] + 257 * input[i + 1]
pairs[i >> 1] = input[i] + input[i + 1] + (input[i + 1] << 8);
}
for i := (EIGHTH_N / 2) - 1; ... |
package nacos
import (
"errors"
"github.com/nacos-group/nacos-sdk-go/vo"
"github.com/spf13/cast"
"github.com/sunmi-OS/gocore/viper"
"io/ioutil"
"sync"
"time"
)
type ViperToml struct {
dataIdorGroupList []dataIdorGroup
viperBase string
callbackList map[string]func(namespace, group, dataId, data ... |
package main
import (
"time"
"gopkg.in/mgo.v2/bson"
)
// RepositoryStats is the layout for how an entry is stored in MongoDB.
// TODO: add YAML note to marshall for REST
type RepositoryStats struct {
ID bson.ObjectId `bson:"_id,omitempty"`
RepositoryName string `json:"repositoryname,string"`
... |
package main
import "fmt"
//指针,学过C的都知道
//指针的使用会是程序更灵活,但也令变量的作用域变相扩大,且不易追踪。
//自由与安全永远是一对矛盾体
func main() {
i := 1
fmt.Println("initial:", i)
zeroval(i)
fmt.Println("zeroval:", i)
//通过 &i 语法来取得 i 的内存地址,例如一个变量i 的指针。
zeroptr(&i)
fmt.Println("zeroptr:", i)
//指针也是可以被打印的。
fmt.Println("pointer:", &i)
}
//zeroval 有一个... |
package processors
import (
"context"
sdk "github.com/identityOrg/oidcsdk"
"github.com/identityOrg/oidcsdk/impl/sdkerror"
)
type DefaultBearerUserAuthProcessor struct {
TokenStore sdk.ITokenStore
UserStore sdk.IUserStore
AccessTokenStrategy sdk.IAccessTokenStrategy
}
func NewDefaultBearerUse... |
package operatorclient
import (
"context"
"fmt"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog"
)
// CreateService creates the Service.
func (c *Client) CreateService(ig *v1.Service) (*v1.Service, error) {
return c.CoreV1().Services(ig.GetNam... |
// basic-middleware.go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"html/template"
"github.com/rs/cors"
"github.com/gorilla/sessions"
)
var (
key = []byte("super-secret-key")
store = sessions.NewCookieStore(key)
)
type User struct {
Firstname string `json... |
package lib
import (
"context"
"goimpulse/conf"
"time"
"github.com/coreos/etcd/client"
"github.com/labstack/gommon/log"
)
const MasterNode = "/goimpulse/master"
var Running chan bool = make(chan bool, 1)
func RegisterSelf() {
ec := GetEtcd()
kapi := client.NewKeysAPI(ec)
opts := &client.SetOptions{TTL: 2 ... |
// Copyright 2023 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applica... |
package main
import (
"flag"
"os"
"github.com/subosito/gotenv"
"github.com/tespo/satya/v2/migrations"
"github.com/tespo/satya/v2/seeders"
)
func init() {
env := os.Getenv("GO_ENV")
if env == "" {
env = "local"
}
gotenv.Load("./config/" + env + ".env")
}
func main() {
t := flag.String("type", "migration"... |
package service
import "fmt"
// AlreadyExist sucede cuando se esta agregando un servicio que ya existe
type AlreadyExist struct {
Name string
}
func (err AlreadyExist) Error() string {
return fmt.Sprintf("El servicio ya existe: %s", err.Name)
}
// ManagerAlreadyExist sucede cuando se esta agregando un manager de ... |
package main //必须有一个main包
import "fmt" //导入包含,必须使用
func main() {
//变量,程序运行期间,可以改变的量
//1.声明格式 var 变量名 类型,变量声明了,必须要使用
//2.只是声明没有初始化的变量,默认值为0
//3.同一个{}里,声明的变量名是唯一的
var a int //默认值为0
fmt.Println(a)
a = 10
//4.可以同时声明多个变量
var b, c int
fmt.Println(b, c)
//3.自动推导类型,必须初始化,通过初始化的值确定类型
d := "nihao"
fmt.Println(d)... |
package relay
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
"google.golang.org/grpc"
"github.com/batchcorp/collector-schemas/build/go/protos/records"
"github.com/batchcorp/collector-schemas/build/go/protos/services"
"github.com/batchcorp/plumber/backends/cdcpostgres/types"
)
// handleCdcPostgres se... |
package common
import (
"net"
"github.com/containers/libpod/pkg/domain/entities"
"github.com/containers/libpod/pkg/rootless"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
func getDefaultNetwork() string {
if rootless.IsRootless() {
return "slirp4netns"
}
return "bridge"
}
func GetNetFlags() *pflag.F... |
package 一维子串问题
const inf = 100000000000 // 要定义的足够大,一般要大于int32
func maxSubArray(nums []int) int {
/* 1. 搞清楚定义后,初始化dp数组 */
dp := make([]int, len(nums)) // 定义dp[i]为: 以nums[i]为结尾的最大子串和
for i := 0; i < len(nums); i++ {
if i == 0 {
/* 2. dp[i]基础情况处理 (指: nums[i]前面没有元素时) */
dp[i] = nums[i]
continue
}
/* 3.... |
package utils
/**
*网络辅助
*/
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
)
const (
QWS_WX_ROOT_URL = "http://wxmsg.360qws.cn"
)
/**Http post 提交请求
*@author Andy.wang
*@param url 请求地址
*@param url 参数
*/
func HttpPost(url, s string) (string, error) {
var result string
resp, err := http.Post(url... |
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package testutil
import (
"fmt"
"github.com/iotaledger/goshimmer/dapps/valuetransfers/packages/address"
"github.com/iotaledger/wasp/packages/tcrypto"
)
// DkgRegistryProvider stands for a mock for dkg.RegistryProvider.
type DkgRegistryProvide... |
package stash
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
const response string = `
{
"link" : {
"rel" : "self",
"url" : "/projects/PROJ/repos/trunk/browse"
},
"project" : {
"link" : {
"rel" : "self",
"url" : "/projects/PROJ"
},
"na... |
/*
You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).
The valid times are those inclusively between 00:00 and 23:59.
Return the latest valid time you can get from time by replacing the hidden digits.
Example 1:
Input: time = "2?:?0"
Output: "23:... |
package handlers
import (
"errors"
"net/http"
"regexp"
"github.com/pivotal-cf-experimental/envoy/domain"
)
type deprovisioner interface {
Deprovision(domain.DeprovisionRequest) error
}
type DeprovisionHandler struct {
deprovisioner
}
func NewDeprovisionHandler(deprovisioner deprovisioner) DeprovisionHandler ... |
package filter
import (
"github.com/dgrijalva/jwt-go"
"gocherry-api-gateway/proxy/enum"
)
type JwtFilter struct {
Filter
}
func (f *JwtFilter) Init(proxyContext *ProxyContext) {
}
func (f *JwtFilter) Name(proxyContext *ProxyContext) string {
return Jwt
}
func (f *JwtFilter) Pre(proxyContext *ProxyContext) (sta... |
package main
import (
"database/sql"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"os"
"regexp"
"time"
_ "github.com/lib/pq"
)
// BaseURL is the Url of the website
const BaseURL = "gorl.herokuapp.com/"
var (
repeat int
db *sql.DB
)
// Page is a Home page template
type Page struct {
Info ... |
package main
import (
"fmt"
"github.com/bonjourmalware/melody/internal/fileutils"
"github.com/bonjourmalware/melody/internal/meloctl/prompt"
"io/ioutil"
"os"
"gopkg.in/yaml.v3"
"github.com/spf13/cobra"
)
// MeloctlConfig represents the meloctl config file
type MeloctlConfig struct {
MelodyHomeDir string `ya... |
// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
// This file was generated by swaggo/swag at
// 2017-06-25 01:25:37.872454531 +0800 CST
package docs
import (
"github.com/swaggo/swag"
)
var doc = `{
"swagger": "2.0",
"info": {
"description": "Library API ",
"version": "1.0.0",
"title": "Libr... |
package di
import (
"fmt"
"reflect"
"github.com/goava/di/internal/reflection"
)
type invocationType int
const (
invocationUnknown invocationType = iota
invokerStd // func (deps) {}
invokerError // func (deps) error {}
)
func determineInvokerType(fn reflection.Func) (... |
package player
import (
"os"
"time"
"github.com/faiface/beep"
"github.com/faiface/beep/speaker"
"github.com/faiface/beep/wav"
)
// WavNotePlayer defines a struct for playing notes using a wav player.
type WavNotePlayer struct {
FileMap map[string]string
}
// NewWavNotePlayer initializes a WavNotePlayer.
func ... |
package gcalbot
import (
"errors"
"fmt"
"strconv"
"time"
"github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1"
"google.golang.org/api/calendar/v3"
)
const AllDayDateFormat = "2006-01-02"
func ParseTime(startDateTime, endDateTime *calendar.EventDateTime) (start, end time.Time, isAllDay bool, err... |
package swag
import (
"bytes"
"go/ast"
goparser "go/parser"
"go/token"
"io/ioutil"
"path"
"strings"
"text/template"
"github.com/pkg/errors"
)
const (
generalTemplateD = `
// @title {{.Title}}
//// API的版本号
// @version v1.0
// @desc 此处可写一些 API 的相关说明
//// 调试接口时的本地地址,可以写多个,逗号分隔
// @hos... |
package sort
import (
"fmt"
heap2 "github.com/DestinyWang/go-widget/data_structs/heap"
)
// 冒泡排序会把正确的序列排到末尾, 因此断尾不断头, 内层遍历需要从 0 开始
func BubbleSort(arr []int) {
if len(arr) <= 0 {
return
}
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr)-i-1; j++ {
if arr[j] <= arr[j+1] {
t := arr[j]
arr[j]... |
package yna
import (
"github.com/gin-gonic/gin"
)
// ApplyRoutes applies router to the gin Engine
func ApplyRoutes(r *gin.RouterGroup) {
posts := r.Group("/yna")
{
posts.POST("/yna_by_adunit", PostYNAReport)
}
}
|
package presenters
import (
"fmt"
"net/url"
"github.com/messagedb/messagedb/meta/schema"
)
// User represents a API user.
type User struct {
ID string `json:"id"`
Username string `json:"username"`
FullName string `json:"full_name,omitempty"`
PrimaryEmail string `json:"primary_email,omitempty... |
package controllers
import (
"database/sql"
"net/http"
"github.com/evilfactorylabs/gow/api/models"
)
type notFound struct {
Data []string
}
// GetHitsStatsBySlug — TODO: Create middleware of this
func GetHitsStatsBySlug(db *sql.DB, w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
slug := para... |
package memrepo
import (
"github.com/scjalliance/drivestream/collection"
"github.com/scjalliance/drivestream/resource"
)
var _ collection.StateReference = (*CollectionState)(nil)
// CollectionState is a reference to a collection state.
type CollectionState struct {
repo *Repository
drive resource.ID
... |
// Package disgord provides Go bindings for the documented Discord API, and allows for a stateful Client using the Session interface, with the option of a configurable caching system or bypass the built-in caching logic all together.
//
// Getting started
//
// Create a Disgord session to get access to the REST API and... |
package fasthttpmiddleware
import (
"github.com/valyala/fasthttp"
)
// AuthFunc is your custom auth function type
type AuthFunc func(ctx *fasthttp.RequestCtx) bool
// NewAuthMiddleware accepts a customer auth function and then returns a middleware which only accepts auth passed request.
// If auth function returns ... |
package main
func hammingWeight(num uint32) int {
var pc [256]byte
for i := range pc {
pc[i] = pc[i/2] + byte(i&1)
}
return int(
pc[byte(num>>0)] +
pc[byte(num>>8)] +
pc[byte(num>>16)] +
pc[byte(num>>24)] +
pc[byte(num>>32)] +
pc[byte(num>>40)] +
pc[byte(num>>48)] +
pc[byte(num>>56)])
}
|
package haproxyctl
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
)
type Backend struct {
name string
servers []*Server
}
func NewBackend(name string) *Backend {
b := &Backend{
name: name,
servers: make([]*Server, 0),
}
return b
}
func (b *Backend) Name() string {
return b.name
}
// returns a l... |
// Copyright 2018 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 main
import (
f "fmt"
"time"
)
func main() {
ticker := time.NewTicker(time.Millisecond * 500)
go func() {
for t := range ticker.C {
f.Println("Tick at ", t)
}
}()
time.Sleep(time.Millisecond * 1600)
ticker.Stop()
f.Println("Ticker stopped")
}
|
package main
import (
"search"
"fmt"
)
func demoAvlTree() {
tree := search.NewAvlTree()
fmt.Printf("root-val:%v, height:%v\n", tree.Root().E, tree.Height())
tree.AddInt(1)
fmt.Printf("root-val:%v, height:%v\n", tree.Root().E, tree.Height())
tree.AddInt(2)
tree.AddInt(3)
tree.AddInt(4)
fmt.Printf("root-val:%... |
package commands
import (
"fmt"
"github.com/qubitz/lawyer/commands/manuals"
"github.com/qubitz/lawyer/constants"
)
type helpCommand struct {
subject string
}
func (help helpCommand) Execute() (err error) {
if help.subject == "" {
printSummary()
} else {
err = printManual(help.subject)
}
return err
}
f... |
package main
import (
"fmt"
"reflect"
"shuxiang/common/reflecter"
)
type RouteMethod interface {
Insert()
Add()
}
type Router struct {
}
func (v *Router) Insert() {
}
func (v *Router) Add() {
}
func change(r interface{}) {
vft := reflect.TypeOf(r)
// vf := reflect.ValueOf(&r)
// vft := vf.Type()
//读取方法... |
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
... |
package controller
import (
"gin-app/model"
"gin-app/service"
"net/http"
"github.com/gin-gonic/gin"
)
func TodoList(c *gin.Context) {
todoService := service.TodoService{}
TodoLists := todoService.GetTodoList()
c.JSON(http.StatusOK, gin.H{
"message": "ok",
"data": TodoLists,
})
}
func TodoAdd(c *gin.Cont... |
package cli
import (
"fmt"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/dreamer-epitech/dreamer-storage/x/nameservice/types"
"github.com/spf13/cobra"
)
func GetQueryCmd(storeKey string, cdc *codec.Codec) *cobra.Command {
n... |
package main
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/ghttp"
"testing"
)
func TestRSSSHExample(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "RSSSH Example Suite")
}
var _ = Describe("RSSSH Exampl... |
package main
import (
"fmt"
)
func main() {
fmt.Println("Diameter of Binary Tree")
root := &TreeNode{
Val: 1,
Left: &TreeNode{
Val: 2,
Left: &TreeNode{Val: 3, Left: &TreeNode{Val: 5}},
Right: &TreeNode{Val: 4, Left: &TreeNode{Val: 6, Left: &TreeNode{Val: 7}, Right: &TreeNode{Val: 8}}},
},
Right... |
package main // import "sevki.org/q9p/q9pfs"
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"flag"
"log"
"math/big"
quic "github.com/lucas-clemente/quic-go"
"sevki.org/q9p/filesystem"
"sevki.org/q9p/protocol"
)
const addr = "localhost:4242"
func main() {
flag.Parse()
lis... |
package main
import (
"test_server/server"
"test_server/server/handlers"
"test_server/storage/memstorage"
)
func main(){
ms := memstorage.NewMemStorage()
h := handlers.NewTaskHandlers(ms)
srv := server.NewServer(":8080", h)
srv.ConfigureAndRun()
}
|
package responses
import "time"
type KeyEvent struct {
ID uint
CreatedAt time.Time
UpdatedAt time.Time
Name string
Description string
EventDate time.Time
}
|
package main
import (
"os"
"github.com/yogihardi/guestbook/cli/run"
"github.com/yogihardi/guestbook/version"
"github.com/inconshreveable/log15"
"github.com/urfave/cli"
)
var logHandler log15.Handler
func main() {
app := cli.NewApp()
app.Name = "guestbook"
app.Usage = "Guset Book API"
app.Version = version... |
package main
import (
"fmt"
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
"math/rand"
"time"
)
//红包列表
var packageList map[uint32][]uint = make(map[uint32][]uint)
type lotteryController struct {
Ctx iris.Context
}
func newApp() *iris.Application{
app := iris.New()
mvc.New(app.Party("/")).Handle(&l... |
package provider
// IMPORTANT: requires : export GO111MODULE=on
import (
"fmt"
"context"
"strings"
// https://godoc.org/github.com/Azure/azure-sdk-for-go/services/privatedns/mgmt/2018-09-01/privatedns
"github.com/Azure/azure-sdk-for-go/services/privatedns/mgmt/2018-09-01/privatedns"
"github.com/Azure/go-autor... |
package funcrunner
import (
"fmt"
)
// Run concurrent tasks
func Run(tasks []func() error, N int, M int) error {
// start task pool
taskChannel := make(chan int, len(tasks))
// error pool
errorChannel := make(chan error, len(tasks))
// routine count
routineNum := N
if len(tasks) < N {
routineNum = len(task... |
package pluginutil_test
import (
"fmt"
"code.cloudfoundry.org/cli/plugin"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/pivotal-cf/spring-cloud-services-cli-plugin/pluginutil"
)
var _ = Describe("ParsePluginVersion", func() {
var (
pluginVersion string
fail func(format string,... |
package 模拟
func isValid(S string) bool {
stack := NewMyStack()
for i := 0; i < len(S); i++ {
switch {
case S[i] == 'a':
stack.Push(S[i])
case S[i] == 'b':
if stack.IsEmpty() || stack.GetTop() != 'a' {
return false
}
stack.Push(S[i])
case S[i] == 'c':
if stack.IsEmpty() || stack.GetTop() !=... |
// Copyright 2021 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 mcache
import (
"encoding/json"
)
// Timestamp is a Unix milliseconds offset
type Timestamp = int64
// Document is a resource that can be accessed by users
type Document struct {
ID string `json:"id"`
UpdatedAt Timestamp `json:"updatedAt"`
Body []byte `json:"body"`
Deleted bool ... |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
type Integer int
func (i Integer) isEven() bool {
if i%2 == 0 {
return true
}
return false
}
func (i Integer) isWeird() string {
switch {
case !i.isEven():
return "Weird"
case i.isEven() && 2 <= i && i <= 5:
return "Not Weird"
case i.isEven() &... |
package leetcodego
import (
"fmt"
"testing"
)
func Test_longestCommonPrefix(t *testing.T) {
strs := []string{"flower", "flow", "flight"}
res := longestCommonPrefix(strs)
fmt.Println(res)
}
|
package validators
import (
"gopkg.in/go-playground/validator.v9"
)
var validate = validator.New()
func Init() {}
// Struct valid the structure
func Struct(s interface{}) error {
return validate.Struct(s)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.