text stringlengths 11 4.05M |
|---|
package main
/*
@Time : 2020-04-01 21:29
@Author : audiRStony
@File : 02_反射.go
@Software: GoLand
*/
import (
"fmt"
"reflect"
)
/*在Go语言的反射机制中,任何接口值都是由一个具体类型和具体类型的值两部分组成的
在Go语言中反射的相关功能由内置的reflect包提供,任意接口值在反射中都可以理解为
由reflect.Type和reflect.Value两部分组成,并且reflect包提供了reflect.TypeOf和reflect.ValueOf
两个函数来获取任意对象的Type和Va... |
package main
import (
"fmt"
"log"
"github.com/piotrpersona/saga/events"
"github.com/piotrpersona/saga/config"
"github.com/piotrpersona/saga/store"
)
func main() {
config := config.RedisConfig{
Channel: "order.reserve",
URI: "localhost:6379",
Password: "topsecret",
}
client, err := store.NewRedis... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//216. Combination Sum III
//Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and... |
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
const DEFAULT_PORT int = 80
const ROOT = "./static/"
const FLAG_PORT_HELP string = "the port to listen for requests"
const CANNOT_OPEN_PORT_MSG string = `cannot connect to specified por... |
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadAll(r.Body)
serviceName := r.Header.Get("sparrow-service")
methodName := r.Header.Get("sparrow-service-method")
filterIvk := &filterInvoker{
Invoker: &httpInvoker{},
fil... |
package apis
import (
"fmt"
"pkg/mod/github.com/golang/protobuf/proto"
"zinx/src/mmo_game_zinx/core"
"zinx/src/mmo_game_zinx/pb/pb"
"zinx/src/zinx/ziface"
"zinx/src/zinx/znet"
)
// 玩家移动路由 API
type MoveApi struct {
znet.BaseRouter
}
func (pM *MoveApi)Handle(request ziface.IRequest) {
// 解析客户端传递进来的proto 协议
... |
package commands
import (
"context"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/yunify/qscamel/model"
"github.com/yunify/qscamel/utils"
)
// DeleteCmd will provide delete command for qscamel.
var DeleteCmd = &cobra.Command{
Use: "delete [task name]",
Short: "Delete a task",
Args: co... |
// Copyright alphaair 2016
// “幸运星座”游戏模拟推演示
package amusing
import (
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"time"
)
// newNum生成一个指定范围内的随机数
func newNum(min int, max int) int {
src := rand.NewSource(time.Now().UnixNano() / 1000 / 1000)
r := rand.New(src)
n := r.Intn(max + 1)
f... |
package module
import (
"math"
"buddin.us/eolian/dsp"
)
func init() {
Register("Shape", func(Config) (Patcher, error) { return newShape() })
}
type shape struct {
multiOutIO
gate, trigger, rise, fall, cycle, ratio *In
state *shapeState
stateFunc shapeStateFunc
main, endCycle dsp.Frame
}
func... |
package main
import (
"fmt"
"sort"
)
func main() {
x := []string{"Ali", "Sancho", "Messi", "Bale", "Ronaldo"}
y := []string{"Ali", "Sancho", "Messi", "Bale", "Ronaldo"}
// 1. here we are converting "[]slice" into type "StringSlice" and then using StringSlice's "Sort" method
sort.StringSlice(x).Sort()
// 2. ... |
package main
import (
"fmt"
)
func main() {
y := []string{"sun", "moon", "star", "rocket", "foot", "face"}
fmt.Println(y)
fmt.Println(cap(y))
fmt.Println(len(y))
for i, v := range y {
fmt.Println(i, v)
}
fmt.Println("Let's check the alternative method")
//alternative method
for i := 0; i <= 5; i++ {
fmt... |
package validator
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestJSON(t *testing.T) {
type User struct {
Username string `json:"username" validate:"alphanum"`
Email string `json:"email" validate:"email"`
}
u := &User{
Username: "big_kahuna",
Email: "savage_surfer@alabama...... |
package atomicraceprotect
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
// This demonstrates the use of teh atomic package functions Store and Load for safe acces
// to numeric types
var (
//shutdown is a flac to alert goroutines to shutdown
shutdown int64
//wg waits for a program to fininsh
//this is declare... |
package mira
const (
// RedditBase is the basic reddit base URL, authed is the base URL for use once authenticated
RedditBase = "https://www.reddit.com/"
// RedditOauth is the oauth url to pass the tokens to
RedditOauth = "https://oauth.reddit.com"
// JsonAPI sets the api type to json
JsonAPI = "json"
// Sort... |
/*
* Delete a given cross-datacenter firewall policy.
*/
package main
import (
"flag"
"fmt"
"os"
"path"
"strings"
"github.com/grrtrr/clcv2/clcv2cli"
"github.com/grrtrr/exit"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [options] <Location> <PolicyID>\n", path.Base(os.Args[0]))... |
package main
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSystemEnv(t *testing.T) {
setRunAppEnv("KEY1=val1 KEY2=val2")
assert.Equal(t, os.Getenv("KEY1"), "val1")
assert.Equal(t, os.Getenv("KEY2"), "val2")
}
func TestSetEnv(t *testing.T) {
envs = &Envs{
Mode: "add",
Name: "",
... |
package custom
import (
"io"
"path/filepath"
"strings"
"github.com/bmatcuk/doublestar"
"github.com/devspace-cloud/devspace/pkg/devspace/config/generated"
"github.com/devspace-cloud/devspace/pkg/devspace/config/versions/latest"
"github.com/devspace-cloud/devspace/pkg/util/command"
"github.com/devspace-cloud/de... |
package util
import (
"github.com/leonelquinteros/gotext"
)
func TR(str string, vars ...interface{}) string {
return gotext.Get(str, vars...)
}
func LoadTranslation(lib, lang, dom string) {
gotext.Configure(lib, lang, dom)
}
|
/*
Objective
Design a modulator/demodulator pair to accurately transmit data as quickly as possible over simulated plain old telephone service (POTS).
Steps
Generate some random (/dev/random or the like) data that will take 3-4 seconds to transmit
Modulate the data with your modulator to produce an audio file
Pass th... |
package fleetrome
import (
"github.com/zond/godip/state"
"github.com/zond/godip/variants/classical"
"github.com/zond/godip/variants/classical/orders"
"github.com/zond/godip/variants/classical/start"
"github.com/zond/godip/variants/common"
cla "github.com/zond/godip/variants/classical/common"
dip "github.com/zo... |
package http
import (
"context"
"fmt"
"net/http"
"github.com/pkg/errors"
"github.com/pyspa/voice-notify/log"
"github.com/pyspa/voice-notify/service"
"github.com/pyspa/voice-notify/tts"
"github.com/spf13/viper"
)
type HttpService struct {
}
func (s *HttpService) Start() {
http.HandleFunc("/", handler)
addr... |
package nameshake
import (
"github.com/cosmos/cosmos-sdk/codec"
)
var ModuleCdc = codec.New()
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgSetName{}, "nameshake/SetName", nil)
cdc.RegisterConcrete(MsgBuyName{}, "nameshake/BuyName", nil)
}
|
// Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package registry
import (
"github.com/iotaledger/hive.go/logger"
"github.com/iotaledger/wasp/packages/dbprovider"
"github.com/iotaledger/wasp/packages/tcrypto"
"github.com/iotaledger/wasp/plugins/database"
)
// Impl is just a placeholder to i... |
package main
import (
"os/exec"
"strings"
)
func getMergedBranches() ([]string, error) {
var branches []string
out, err := exec.Command("git", "branch", "--merged").Output()
if err != nil {
return nil, err
}
for _, branch := range strings.Split(string(out), "\n") {
branch = strings.TrimSpace(branch)
if ... |
package Controllers
import (
"errors"
Config "github.com/renancrc99/1sti.challenge.backend/config"
"github.com/renancrc99/1sti.challenge.backend/graph/model"
Models "github.com/renancrc99/1sti.challenge.backend/models"
)
func CriarUsuario(input *model.UsuarioInput) error {
usuario := new(Models.Usuario)
if in... |
/**
* day 08 2020
* https://adventofcode.com/2020/day/8
*
* compile: go build main.go
* run: ./main < input
* compile & run: go run main.go < input
**/
package main
import (
"bufio"
"os"
"fmt"
"strings"
)
type bootcode struct {
instruction string
value int
alreadyRun bool
}
var gameboy []bo... |
package oasis_test
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/go-oasis/oasis"
)
func TestResponseCache(t *testing.T) {
var rspr oasis.Responder = &oasis.ResponseCache{
Code: http.StatusInternalServerError,
HeaderCache: http.Header{
"X-Hello-World": {"silly hello"}... |
package main
import (
"fmt"
"time"
"github.com/golang-jwt/jwt"
)
const (
mySigningKey = "WOW,MuchShibe,ToDogge"
)
func main() {
createdToken, err := exampleNew([]byte(mySigningKey))
if err != nil {
fmt.Println("Creating token failed")
}
exampleParse(createdToken, mySigningKey)
}
func exampleNew(mySigning... |
package core
import (
"encoding/json"
"time"
)
type Snippet struct {
Title string
Body string
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
func MarshalSnippetForStorage(s Snippet) ([]byte, []byte, error) {
name := []byte(s.Title)
snippetBlob, err := json.Marshal(s)
if err ... |
package main
import "github.com/Mario-Jimenez/pricescraper/service"
func main() {
service.Run("pricescraper-srv", "0.0.1")
}
|
package main
import (
"log"
"sync"
"time"
)
var cache = make(map[string]string)
func main() {
var wg sync.WaitGroup
var mu sync.Mutex
wg.Add(1)
go func() {
mu.Lock()
defer wg.Done()
for len(cache) == 0 {
mu.Unlock()
log.Printf("[go-routine] waiting for Elements from cache : %v\n", cache)
time... |
package day11
func countOccupiedSightLines(row int, col int, seating [][]rune) (adjacent int) {
cardinalMap := make(map[string]rune)
//Expand outward in all cardinals, stop on
for i := 1; i < len(seating); i++ {
back := i * -1
forward := i
//south
if row+forward < len(seating) && cardinalMap["S"] == 0 {
... |
package test
import (
"MainApplication/internal/Letter/LetterDelivery"
"MainApplication/internal/Letter/LetterModel"
"MainApplication/internal/Letter/LetterRepository"
"MainApplication/internal/User/UserDelivery"
"MainApplication/internal/User/UserModel"
"MainApplication/internal/User/UserRepository"
"MainAppli... |
package initialization
import (
"encoding/json"
"errors"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"os"
)
var (
ConfCenterService = &ConfCenter{}
log = &confCenterLog{}
)
type (
ConfCenter struct {
Addr string
}
confCenterLog struct {
path string
level string
}... |
package service_test
import (
"context"
"database/sql"
"fmt"
"testing"
"boiler/pkg/entity"
"boiler/pkg/errors"
"boiler/pkg/service"
"boiler/pkg/store"
"boiler/pkg/store/config"
"boiler/pkg/store/mock"
"github.com/DATA-DOG/go-sqlmock"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
)... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//46. Permutations
//Given a collection of distinct integers, return all possible permutations.
//Example:
//Input: [1,2,3]
//Output:
//[
// [1,2,3],
... |
package model
type RedisConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
}
type PostgresConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password... |
package viewmodel
// Home struct
type Home struct {
Title string
Active string
Alert string
AlertMessage string
AlertDanger string
AlertSuccess string
}
// NewHome function
func NewHome() Home {
result := Home{
Active: "home",
Title: "Lemonade Stand Supply",
Alert: "invisible",
}
... |
package coordinator
import (
"errors"
"net/rpc"
"os"
"path/filepath"
"sync"
"time"
"github.com/golang/protobuf/proto"
"github.com/hashicorp/raft"
"github.com/raft-kv-store/common"
"github.com/raft-kv-store/config"
"github.com/raft-kv-store/raftpb"
log "github.com/sirupsen/logrus"
)
const (
// Transactio... |
package httpd
import (
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"github.com/messagedb/messagedb/cluster"
"github.com/messagedb/messagedb/db"
"github.com/messagedb/messagedb/meta"
"github.com/messagedb/messagedb/services/httpd/controllers"
"github.com/messagedb/messagedb/services/httpd/middleware"
"git... |
package main
import (
"os/exec"
"fmt"
"time"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
const path = "/var/lib/postgresql/"
func fullPath(filename string) string {
return fmt.Sprintf("%s/%s", path, filename)
}
func uploadTo... |
package utils
import (
"encoding/json"
"gopkg.in/gomail.v2"
"io/ioutil"
)
type Mailclient struct {
mc *gomail.Dialer //mc Mail Dialer Client
}
type MailInfo struct {
User string `json:"user"` //发件人邮箱
Pass string `json:"pass"` //发件人邮箱密码
Host string `json:"host"` //发件邮箱
Port string `json:"port"` //邮箱端口
}
fun... |
package p07
func toLowerCase(str string) string {
s := make([]byte, len(str))
for i := 0; i < len(str); i++ {
v := str[i]
if v <= 'Z' && v >= 'A' {
v = v + 'a' - 'A'
}
s[i] = v
}
return string(s)
}
|
package main
/*
import (
"bytes"
"encoding/binary"
"time"
)
func csLogin(csId, maxConn string) {
csIdLen := make([]byte, 4)
binary.BigEndian.PutUint32(csIdLen, uint32(len(csId)))
maxConnLen := make([]byte, 4)
binary.BigEndian.PutUint32(maxConnLen, uint32(len(maxConn)))
data := new(bytes.Buffer)
data.Write(cs... |
package main
import "fmt"
func main() {
//普通for循环
var arr = [...]int{1, 2, 3, 4, 5}
slice := arr[1:4]
for i := 0; i < len(slice); i++ {
fmt.Printf("slice[%v]=%v\n", i, slice[i])
}
//增强for循环
for i, val := range slice {
fmt.Printf("slice[%v]=%v\n", i, val)
}
//==============================================... |
package database
import (
"BackendGo/models"
"fmt"
"github.com/google/uuid"
"gorm.io/gorm"
"os"
)
const (
DbDriverEnvVar = "DB_DRIVER"
DriverPostgres = "postgres"
DriverSqlite = "sqlite"
)
type Database struct {
*gorm.DB
Config map[string]string
}
const (
User1UUID = "4d365568-d3ac-4880-8403-8d4e2638e0... |
package bigsum
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
scan := bufio.NewScanner(os.Stdin)
scan.Split(bufio.ScanWords)
scan.Scan()
cnt, _ := strconv.Atoi(scan.Text())
var sum int64
for i := 0; i < cnt; i++ {
scan.Scan()
j, _ := strconv.ParseInt(scan.Text(), 10, 64)
sum += j
}
fmt.Printl... |
package 动态规划
func numWays(n int) int {
const givenMaxStep = 100
const givenMod = 1000000007
jumpWays := getJumpWays(givenMod, givenMaxStep)
return jumpWays[n]
}
func getJumpWays(mod int, maxStep int) []int {
jumpWays := make([]int, maxStep+1)
initialJumpWays(jumpWays)
formJumpWays(jumpWays, mod)
return jumpWa... |
package util
import (
"bufio"
"bytes"
"io"
"math/rand"
"os"
"path/filepath"
"strings"
)
var (
fileBuffer = 32 * 1024
filesMode = os.FileMode(0666)
filesEndLineDelimiter = byte('\n')
defaultApplicationFolder = ".curlson"
)
// Counts the number of lines in a given file.
// In... |
package main
import (
"log"
"os"
"github.com/urfave/cli"
)
const (
defaultEthernetConfig = "ethernet@%s.json"
defaultWifiClientConfig = "wifi-client@%s.json"
defaultAccessPointConfig = "access-point@%s.json"
defaultFougGConfig = "4g-ndis@%s.json"
defaultThreeGGConfig = "3g-ras@%s.json"
default... |
package chart
import (
"github.com/jchavannes/jgo/jerr"
"time"
)
type ChartItem struct {
Name string
ChartDataPoints []*ChartDataPoint
}
func (i *ChartItem) GetDataPoint(timestamp time.Time) (*ChartDataPoint, error) {
for _, chartDataPoint := range i.ChartDataPoints {
if chartDataPoint.Timestamp ==... |
package cmd
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
var (
cfgFile string
logLevel string
prefix = "pbnj"
)
// rootCmd represents the base command when called without any subcommands.
var rootCmd = &cobra.Command{
Use: "pbnj",
Short:... |
// Copyright 2020. Akamai Technologies, 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 t... |
/*
* Copyright 2017 StreamSets 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... |
package main
import "strings"
func main() {
}
func mergeAlternately(word1 string, word2 string) string {
if word1 == "" {
return word2
}
if word2 == "" {
return word1
}
var ans strings.Builder
ans.WriteByte(word1[0])
ans.WriteByte(word2[0])
ans.WriteString(mergeAlternately(word1[1:], word2[1:]))
retur... |
package main
import "fmt"
func max2(a, b int) int {
if a > b {
return a
}
return b
}
func longestConsecutive(nums []int) int {
if len(nums) == 0 {
return 0
}
numIndices := make(map[int]int)
for i, n := range nums {
numIndices[n] = i
}
distinctNums := make([]int, 0, len(nums))
for k, _ := range n... |
package main
import (
"flag"
"fmt"
"io"
"net"
"os"
"github.com/nwehr/chatterbox"
)
func main() {
var domain, address, port string
{
flag.StringVar(&address, "b", "0.0.0.0", "Bind address, default 0.0.0.0")
flag.StringVar(&port, "p", "6847", "Listen port, default 6847")
flag.StringVar(&domain, "d", "ho... |
package remark
import (
"fmt"
"os"
"testing"
"time"
"github.com/go-jar/mysql"
"blog/conf"
"blog/entity"
"blog/errno"
"blog/resource"
"blog/resource/log"
)
func prepare() {
if err := conf.Init("/usr/local/lighthouse/softwares/aping-blog/blog-back/"); err != nil {
fmt.Println(err)
}
err := log.InitLog... |
package item
type Item struct {
Name string
Exp int
MadeWithItems []*ItemUsed
}
func (s *Item) IsCollectable() bool {
return len(s.MadeWithItems) == 0
}
type ItemUsed struct {
Item
Quantity int
}
func (s *Item) CalcItemsReport(quantity int) map[string]*ItemUsed {
currentItemMap := make(map... |
// Copyright 2019 CUE 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 ... |
package v2
import (
"strconv"
"strings"
"github.com/davyxu/tabtoy/v2/i18n"
"github.com/davyxu/tabtoy/v2/model"
)
type typeCell struct {
value string
col int
}
// 类型表的数据, 数据读取与使用分开使用, 让类型互相没有依赖
type typeModel struct {
colData map[string]*typeCell
done bool
row int
fd *model.FieldDescriptor
rawFieldT... |
package list
/*
import (
"io/ioutil"
"os"
"reflect"
"testing"
"github.com/devspace-cloud/devspace/cmd/flags"
cloudconfig "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config"
cloudlatest "github.com/devspace-cloud/devspace/pkg/devspace/cloud/config/versions/latest"
"github.com/devspace-cloud/devspace... |
package main
import (
"fmt"
"io"
"net"
"os"
)
// 传输文件的客户端
func main() {
fmt.Println("请输入文件路径:")
var path string
fmt.Scan(&path)
// 获取文件相关信息
info, err1 := os.Stat(path)
if err1 != nil {
fmt.Println("os.Stat err1 = ", err1)
return
}
fileName := info.Name()
fmt.Println("fileName:", fileName)
// 连接服务... |
package cbor
import (
"testing"
"github.com/polydawn/refmt/tok/fixtures"
)
func testTags(t *testing.T) {
t.Run("tagged object", func(t *testing.T) {
seq := fixtures.SequenceMap["tagged object"]
canon := bcat(b(0xc0+(0x20-8)), b(50), b(0xa0+1), b(0x60+1), []byte(`k`), b(0x60+1), []byte(`v`))
t.Run("encode ca... |
package ghosts
type Wraith struct {
}
func (w Wraith) Name() string {
return "Wraith"
}
func (w Wraith) Evidence() [3]string {
return [3]string{"Freezing", "Spirit Box", "Fingerprints"}
}
|
package ch01
// Find the maximum element in a sorted and rotated list. Complexity O(log(n))
// Hint: user binary search algorithm
// Comments: Must be rotated at some unknown point, otherwise this problem doesn't make much sense
// (Largest value is the first element...)
// If duplicates are allowed then bina... |
package main
import (
"os"
"io/ioutil"
"container/list"
"strings"
)
type Entries []*Entry
func EntriesFromPath(path string) (entries Entries, err error) {
files, err := ioutil.ReadDir(cwd)
if err != nil {
return
}
return EntriesFromFiles(files), nil
}
func matches(file os.FileInfo) bool {
startsWith, end... |
package views
import (
"bytes"
"errors"
"html/template"
"io"
"log"
"net/http"
"path/filepath"
"time"
"github.com/gorilla/csrf"
"lenslocked.com/context"
)
var (
LayoutDir string = "views/layouts/"
TemplateDir string = "views/"
TemplateExtension string = ".gohtml"
)
func NewFiles(layout str... |
//
// Example how to handle custom errors
//
package main
import (
"fmt"
"log"
"github.com/rogozhka/ytrwrap"
)
func main() {
tr := ytrwrap.NewYandexTranslate("<your-api-key")
src := "the pony eat grass"
out, err := tr.Translate(src, ytrwrap.FR, nil)
if err != nil {
switch err.Code() {
case ytrwrap.KE... |
package functions
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
"github.com/fatih/color"
"golang.org/x/crypto/bcrypt"
)
var users []User
// User type which is a struct with two field
// User.Name string
// User.Password string
type User struct {
Name string `json:"name"`
Password string `json:"passwo... |
package main
import (
"testing"
)
func Test(t *testing.T) {
a := [][]int{[]int{1}}
ret := minPathSum(a)
if ret != 1 {
t.Error("Expected 1 got ", ret)
}
a = [][]int{[]int{1, 2}}
ret = minPathSum(a)
if ret != 3 {
t.Fatalf("Expacted 3 got %d", ret)
}
a = [][]int{[]int{1}, []int{2}}
ret = minPathSum(a)
if... |
package main
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
)
func makeCmd(args []string) (*exec.Cmd, error) {
var cmd *exec.Cmd
switch len(args) {
case 0:
return nil, errors.New("empty command")
case 1:
cmd = exec.Command(args[0])
default:
cmd = exec.Co... |
package obox
import (
"testing"
)
func TestKcDb(t *testing.T) {
db, err := OpenKcDb("foo")
if err != nil { t.Fatal("open fail", err) }
testDb(t, db)
}
func BenchmarkKcDbIter(b *testing.B) {
db, err := OpenKcDb("bar")
if err != nil { b.Fatal("open fail", err) }
benchmarkDb(b, db)
}
|
package devto
import "testing"
func TestRetrieveVideoArticles(t *testing.T) {
pageNum := 1
perPageNum := 2
client := NewClient("")
opt := &RetrieveVideoArticlesOption{
Page: pageNum,
PerPage: perPageNum,
}
articles, err := client.RetrieveVideoArticles(opt)
if err != nil {
t.Fatal(err)
}
if len(arti... |
package azure
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
operatorv1 "github.com/openshift/api/operator/v1"
)
// ClusterCSIDriverConfig is the Azure config for the cluster CSI driver.
type ClusterCSIDriverConfig struct {
SubscriptionID string
ResourceGroupName string
Di... |
package alerts
import (
"github.com/dennor/go-paddle/events/types"
"github.com/dennor/phpserialize"
"github.com/shopspring/decimal"
)
const TransferCreatedAlertName = "transfer_created"
// TransferCreated refer to https://paddle.com/docs/reference-using-webhooks/#transfer_created
type TransferCreated struct {
Al... |
// Package sudoku comtains functions for reading, writing, and solving sudoku puzzles
package sudoku
import (
"fmt"
"github.com/lukpank/go-glpk/glpk"
)
type Sudoku [][]uint8
func (puzzle Sudoku) Print() {
fmt.Println("╔═══╤═══╤═══╦═══╤═══╤═══╦═══╤═══╤═══╗")
for i, row := range puzzle {
fmt.Print("║ ")
for... |
package config
import (
"math/big"
"github.com/shopspring/decimal"
)
// ToWei converts decimals to wei this is copied from the
// utils package to prevent import cycles
func ToWei(iamount interface{}, decimals int) *big.Int {
amount := decimal.NewFromFloat(0)
switch v := iamount.(type) {
case string:
amount, ... |
package main
import (
"fmt"
"net"
"runtime"
"github.com/mndrix/tap-go"
"github.com/opencontainers/runtime-tools/cgroups"
"github.com/opencontainers/runtime-tools/validation/util"
)
func testNetworkCgroups() error {
t := tap.New()
t.Header(0)
defer t.AutoPlan()
loIfName := ""
ethIfName := ""
// we try t... |
package ansi
import "image"
// Point represents an ANSI screen point, relative to a 1,1 column,row origin.
//
// This naturally aligns with the requirements of parsing and building ANSI
// control sequences (e.g. for cursor positioning and mouse events), while
// allowing the 1,1-origin semantic to be type checked.
t... |
package css
import (
"fmt"
"testing"
"github.com/sparkymat/webdsl/css/color"
"github.com/sparkymat/webdsl/css/size"
)
func TestLetterSpacing(t *testing.T) {
css := Stylesheet(
For(Class("text")).Set(
LetterSpacingNormal(),
LetterSpacingInherit(),
LetterSpacingInitial(),
LetterSpacing(size.Px(12)),... |
package main
import (
"fmt"
"math/rand"
"time"
)
const formatDate = "2006-01-02 15:04:05"
func main001() {
t, _ := time.ParseInLocation(formatDate, "2020-02-26 09:14:00", time.Local)
fmt.Println(time.Local)
fmt.Println(t.Location())
fmt.Println(time.Now().Sub(t).Hours())
// 输出正点的时间
t,_ = time.ParseInLocati... |
// utility
package main
import (
"fmt"
"github.com/captaingit/datfile"
"github.com/captaingit/dynhtml"
"net/http"
"sort"
"strconv"
"strings"
"time"
)
func utility(w http.ResponseWriter, r *http.Request) {
bm := dynhtml.NewPlate(w, r)
bm.Log("utility")
a := bm.GetElement()
// check if logged in
ok, user ... |
package inter
import (
"bytes"
"encoding/gob"
. "server/data/datatype"
"server/libs/log"
)
type Watcher interface {
AddObject(id ObjectID, typ int) bool
RemoveObject(id ObjectID, typ int) bool
SetRange(r int)
GetRange() int
ClearAll()
}
type AOI struct {
watchers map[int]map[int32]ObjectID
Range int
}
... |
package model
import "github.com/guregu/null"
type Goods struct {
GoodsAlias null.String `gorm:"column:goods_alias" json:"goods_alias"`
GoodsName null.String `gorm:"column:goods_name" json:"goods_name"`
GroupName null.String `gorm:"column:group_name" json:"group_name"`
ID int64 `gorm:"column:id" j... |
package pkg
import (
"context"
"encoding/json"
"fmt"
"github.com/calvinmclean/automated-garden/garden-app/pkg/influxdb"
"github.com/calvinmclean/automated-garden/garden-app/pkg/mqtt"
"github.com/rs/xid"
)
// AggregateAction collects all the possible actions into a single struct/request so one
// or more action... |
package index
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gorilla/mux"
"go.mongodb.org/mongo-driver/bson"
)
func GetQuizByOwner(response http.ResponseWriter, request *http.Request) {
response.Header().Add("content-type", "application/json")
var quizzes []Quizzes
json.NewDecoder... |
package main
import (
"math"
)
var toRoman = map[int]string{1: "I", 2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI", 7: "VII", 8: "VIII", 9: "IX", 10: "X",
50: "L", 100: "C", 500: "D", 1000: "M"}
var toNumeric = map[string]int{"I": 1, "II": 2, "III": 3, "IV": 4, "V": 5, "VI": 6, "VII": 7, "VIII": 8, "IX": 9, "X": 10,
... |
package validator
import (
"fmt"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/utils"
)
// ValidatePasswordPolicy validates and updates the Password Policy configuration.
func ValidatePasswordPolicy(config *schema.PasswordPolicy, validator *schema.Struct... |
package builtins
import "fmt"
type method struct {
name string
body func(...Value) (Value, error)
valueStub
}
type Method interface {
Name() string
Value
Execute(args ...Value) (Value, error)
}
func NewMethod(name string, body func(...Value) (Value, error)) Method {
m := &method{name: name, body: body}
m.in... |
package dynamic_programming
import "math"
func maxProfit(prices []int) int {
maxCur, maxAll := 0, 0
for i := 1; i < len(prices); i++ {
maxCur += prices[i] - prices[i-1]
maxCur = max(0, maxCur)
maxAll = max(maxCur, maxAll)
}
return maxAll
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
fun... |
package util
import (
"errors"
)
// 获取分页编号序列, 序列中非负整数表示页码, -1 表示省略, 如 [0,1,-1,8,9,10,11,12,-1,15,16] 表示 0,1,...8,9,10,11,12,...15,16
// pageNum: 页面数量, 大于 0 的整数
// pageIndex: 当前页码, 从 0 开始编码
func Paginator0(pageNum, pageIndex int) ([]int, error) {
const (
// 0,1...4,5,[6],7,8...10,11
paginatorBeginNum = 2 /... |
func search(nums []int, target int) int {
left, right := 0, len(nums) - 1
for left <= right {
md := (left + right) / 2
mdv := nums[md]
if mdv == target{
return md
}
if mdv > nums[right]{
if target < mdv && nums[left] <= target{
righ... |
package venom
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
"plugin"
"sort"
"strings"
"github.com/confluentinc/bincover"
"github.com/fatih/color"
"github.com/ovh/cds/sdk/interpolate"
"github.com/pkg/errors"
"github.com/rockbears/yaml"
"github.com/spf13/cast"
)
var... |
package foundationdb
import (
"github.com/apple/foundationdb/bindings/go/src/fdb"
"github.com/blevesearch/bleve/index/store"
"github.com/blevesearch/bleve/registry"
)
const (
// Name is the name of this KVStore
Name = "foundationdb"
)
// Store is a FoundationDB implementation of the KVStore interface
type Store... |
// Copyright 2020 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 openflow
import (
"errors"
"testing"
"github.com/quilt/quilt/minion/ovsdb"
"github.com/quilt/quilt/minion/ovsdb/mocks"
"github.com/stretchr/testify/assert"
)
func TestAddReplaceFlows(t *testing.T) {
anErr := errors.New("err")
ovsdb.Open = func() (ovsdb.Client, error) { return nil, anErr }
assert.Equa... |
package main
import (
"net/http"
"strings"
"testing"
)
func TestRememberBodyLazy(t *testing.T) {
resp := Response{
http: &http.Response{
Header: map[string][]string{"Content-Type": {"application/json"}},
},
body: []byte(`# invalid body so it fails if parsed`),
}
err := rememberBody(&resp, map[string]s... |
package listen
import (
"database/sql"
"fmt"
"github.com/lib/pq"
_ "github.com/lib/pq"
)
type Listen interface {
Listener(event Event) (*pq.Listener, error)
}
func connect(connParams DBConnParams) *sql.DB {
connInfo := connInfo(connParams)
db, err := sql.Open("postgres", connInfo)
if err != nil {
panic(er... |
/* Copyright (c) 2017 Jason Ish
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.