text stringlengths 11 4.05M |
|---|
package main
import "math"
/**
x 的平方根
实现 `int sqrt(int x)` 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
```
输入: 4
输出: 2
```
示例 2:
```
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
```
*/
/**
就今天这题,没点数学功底的还真做不出来,不由的流下了基础太差的眼泪
二分查找法本来还想到来着,有点笨了,居然没试试,但是有个很明显的缺陷,没办法精确小数位
*/
f... |
// Package main has a command that generates butler static files based on
// content in input directories.
package main
import (
"flag"
"log"
"os"
"github.com/jwowillo/butler/page"
"github.com/jwowillo/butler/recipe"
"github.com/jwowillo/gen"
)
// main builds the butler static files from input directories and ... |
package kinetic
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
// TestKineticCreation tests to make sure that the Kinetic creation doesn't return early or return a nil.
func TestKineticCreation(t *testing.T) {
kinesisKinetic, err := new(kinesis).init("fake", "ShardId-00000001", "TRIM_HORIZON", ... |
package blake2b
import (
"bytes"
"github.com/perlin-network/noise/crypto"
"math/big"
"testing"
)
func TestHash(t *testing.T) {
hp := New()
r := crypto.Hash(hp, big.NewInt(123))
n := new(big.Int)
n, ok := n.SetString("89391711502145780362310349925943903708999319576398061903082165979787487688967", 10)
if ok ... |
package main
import (
"net/http"
"fmt"
"math/rand"
)
func main() {
newMux := http.NewServeMux()
newMux.HandleFunc("/randomFloat", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Random Float: %f\n", rand.Float64())
})
newMux.HandleFunc("/randomInt", func(w http.ResponseWriter, r *http.Request)... |
package log
import (
"bytes"
"errors"
"net/http"
"testing"
"goji.io"
"goji.io/pat"
"github.com/sirupsen/logrus"
serr "github.com/stellar/go/support/errors"
"github.com/stellar/go/support/http/httptest"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
func TestSet(t *testing.T) {
assert.... |
// Copyright 2016 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 objects
import (
"fmt"
"regexp"
)
const idRegexString = "[a-f0-9]{40}"
func init() {
var err error
regex, err = regexp.Compile(idRegexString)
if err != nil {
panic("couldn't compile id regex")
}
}
type ID string
var regex *regexp.Regexp
func IdFromSum(sum [20]byte) ID {
return ID(fmt.Sprintf("%x"... |
// Copyright 2020 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package canvas
import "fmt"
// Event is an interface implemented by all event subtypes. Events can be
// received from the channel returned by Context.Events. ... |
package sgs
import "er"
const (
_E_SGS_RUNNER = 0x1000
_E_LOAD_CONF_FAIL = _E_SGS_RUNNER | er.IMPT_RECOVERABLE | er.ET_SERVICE | 0x1
)
const (
_E_SGS_SSVR = 0x2000
//E_JOIN_SESSION_INVALID_CLIENT send join session request without valid client
_E_JOIN_SESSION_INVALID_CLIENT = _E_SGS_SSVR | er.IMPT_REMARKABLE |... |
package base
type Room struct{
name string
}
|
// Copyright (c) 2020 HigKer
// Open Source: MIT License
// Author: SDing <deen.job@qq.com>
// Date: 2020/8/24 - 2:15 下午 - UTC/GMT+08:00
package session
import (
"encoding/json"
)
// Serialize object to serialize byte
// Serialize 只限于 interface{} 类型 转换 []byte使用
// 严禁把 string 类型 传入 obj 当做转换对象使用
// 大坑 大坑 大坑!!!!debug你... |
package problem0504
import "testing"
func TestBase(t *testing.T) {
t.Log(convertToBase7(1))
t.Log(convertToBase7(100))
t.Log(convertToBase7(-100))
}
|
package simple
import (
"strings"
stdsort "sort"
"github.com/etf1/kafka-message-scheduler-admin/server/db"
"github.com/etf1/kafka-message-scheduler-admin/server/sort"
"github.com/etf1/kafka-message-scheduler-admin/server/store"
"github.com/etf1/kafka-message-scheduler/schedule"
)
const (
DefaultMax = 300
Ch... |
package capture
import (
"Neo/codes/jsonstruct"
"github.com/tebeka/selenium"
)
var err error
//Gettextcontent retorna o texto do elemento
func Gettextcontent(d selenium.WebDriver, csspath string) (string, error) {
r := ""
if csspath != "none" {
var el, err = d.FindElement(selenium.ByCSSSelector, csspath)
if... |
package admin
import (
"net/http"
"html/template"
"fmt"
conn "project_reservasi/src/config"
m "project_reservasi/src/model"
)
func AdminHandler(w http.ResponseWriter,r *http.Request){
http.FileServer(http.Dir("assets/admin"))
var data = map[string]interface{}{
"title": "Learning Golang Web",
"name": "K... |
package tool
// 获取灵签json
import (
"encoding/json"
"fmt"
"github.com/gocolly/colly"
"os"
"strconv"
"strings"
"sync"
)
type Lucky struct {
Key string `json:"key"`
Number string `json:"number"`
Content []string `json:"content"`
}
type LinQian struct {
Type string `json:"type"`
Url string... |
package orm
import (
"database/sql"
"github.com/iGoogle-ink/gotil/xtime"
"github.com/jinzhu/gorm"
)
var (
ErrNoRow = sql.ErrNoRows
ErrRecordNotFound = gorm.ErrRecordNotFound
ErrCantStartTransaction = gorm.ErrCantStartTransaction
ErrInvalidSQL = gorm.ErrInvalidSQL
ErrInvalidTran... |
package main
import "encoding/xml"
type Rss struct {
XMLName xml.Name `xml:"rss"`
Text string `xml:",chardata"`
Version string `xml:"version,attr"`
ITunes string `xml:"itunes,attr"`
Atom string `xml:"atom,attr"`
GooglePlay string `xml:"googleplay,attr"`
Channel Channel `xml:... |
// Copyright 2012 Xing Xing <mikespook@gmail.com>.
// All rights reserved.
// Use of this source code is governed by a commercial
// license that can be found in the LICENSE file.
package log
import (
"flag"
"strings"
)
var (
LogFile, LogLevel string
)
func StrToLevel(str string) int {
level := LogNone
levels ... |
package db
import (
"fmt"
"github.com/sharmarajdaksh/basic-auth-microservice/config"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// DB is the global database connection object
var DB *gorm.DB
// InitializeDB initializes the global DB object and make automigrations
func InitializeDB() error {
dsn := fmt.Sprintf(... |
package siv_test
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io"
siv "github.com/secure-io/siv-go"
)
func ExampleNewCMAC_encrypt() {
// Load your secret key from a safe place and reuse it across multiple
// Seal/Open calls. (Obviously don't use this example key for anything
// real.) If you want to convert ... |
// 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 base
import "oneday-infrastructure/internal/pkg/tenant/domain"
func ToTenant(do *TenantDO) domain.Tenant {
return domain.Tenant{
TenantCode: do.TenantCode,
TenantName: do.TenantName,
}
}
func ToTenantDO(tenant *domain.Tenant) *TenantDO {
return &TenantDO{
TenantCode: tenant.TenantCode,
TenantName:... |
package tree
import (
"bytes"
"fmt"
"io"
"reflect"
)
type EdgeType string
type Value interface{}
var (
EdgeTypeLink EdgeType = "│"
EdgeTypeMid EdgeType = "├──"
EdgeTypeEnd EdgeType = "└──"
)
type Tree interface {
AddNode(v Value) Tree
AddBranch(v Value) Tree
Branch() Tree
FindByValue(value Value) Tree
... |
package index
import (
"testing"
)
func TestDocId(t *testing.T) {
testCases := map[*Position]int{
&Position{123, 456}: 123,
&Position{123, 789}: 123,
}
for param, expected := range testCases {
actual := DocId(param)
if actual != expected {
t.Errorf("\n got: %v\n want: %v", actual, expected)
}
}
}
... |
//
// Copyright 2019 Chef Software, Inc.
// Author: Salim Afiune <afiune@chef.io>
//
// 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
//
/... |
/**
* Definition for TreeNode.
* type TreeNode struct {
* Val int
* Left *ListNode
* Right *ListNode
* }
*/
package main
//初始化_ans以防未找到空指针
var _ans *TreeNode =&TreeNode{}
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
RecursionAns(root,p,q)
return _ans
}
//递归
//由于是二叉树,只有一个节点的子... |
package mdfmt
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
)
const (
testCasesPath string = "./test_cases/"
)
func TestFmt(t *testing.T) {
files, err := ioutil.ReadDir(testCasesPath)
if err != nil {
t.Fatal(err)
}
ins := make([]os.FileInfo, 0, len(files)/2)
outs := make([]os.FileInfo, ... |
//Package employee store employee data
package employee
import "fmt"
//employee struct
type employee struct {
firstName string
lastName string
totalLeaves int
leavesTaken int
}
//Employee is exported private struct employee
//type Employee employee
//errorString custom type to store errors for error interf... |
package graphparser_test
import (
"os"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "./" // graphparser
)
func fopen(filePath string) (map[string]*Graph, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
g, err := New(file)
if err != nil {
return nil... |
package main
import (
"flag"
"fmt"
"github.com/dinshaw/metrocard/card"
money "github.com/dinshaw/metrocard/money"
)
var existing money.Money
func init() {
flag.Var(&existing, "existing", "How much is currently on your Metrocard")
}
func main() {
flag.Parse()
c := metrocard.ExistingCard(existing)
value_to_ad... |
/*
* 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 encoding
import (
"github.com/funkygao/fae/servant/gen-go/fun/rpc"
"github.com/funkygao/thrift/lib/go/thrift"
"testing"
)
func BenchmarkThriftSerialize(b *testing.B) {
b.ReportAllocs()
transport := thrift.NewTMemoryBuffer()
protocol := thrift.NewTBinaryProtocolFactoryDefault()
//iprot := protocol.GetP... |
package main
func searchRange(nums []int, target int) []int {
var l, r int
// 1. 寻找第一个>= target的值
left, right := 0, len(nums)
for left < right {
mid := (left + right) >> 1
if nums[mid] >= target {
right = mid
} else {
left = mid + 1
}
}
l = left
// 2. 寻找最后一个<= target的值
left, right = -1, len(nums... |
package day19
import (
"fmt"
"strconv"
"strings"
)
func Run(lines []string) error {
rulesParsed := false
rules := map[int]Rule{}
inputs := []string{}
for _, line := range lines {
if rulesParsed {
inputs = append(inputs, line)
} else if len(line) == 0 {
rulesParsed = true
} else {
rule, err := Pa... |
package main
import (
"github.com/go-redis/redis"
"fmt"
)
func main() {
client := redis.NewClient(
&redis.Options{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
},
)
defer client.Close()
//pong, err := client.Ping().Result()
//fmt.Printl... |
// Package main -
package main
import (
"fmt"
"log"
"os"
"github.com/shanehowearth/concurrency_in_go/errorhandling/intermediate"
)
func handleError(key int, err error, message string) {
log.SetPrefix(fmt.Sprintf("[logID: %v]:", key))
log.Printf("%#v", err)
fmt.Printf("[%v] %v", key, message)
}
func main() {
... |
package main
import (
"log"
"os"
"path/filepath"
"strings"
)
var CHECKS = []struct {
checkname string
checker Accumulator
}{
{
"Двойные номера сертификатов",
&DoubleNCertif{make([]DoubleNCertifErr, 0)},
},
{
"Двойные СНИЛСы",
&DoubleSnils{make([]DoubleSnilsErr, 0)},
},
{
"Разные ФИО, ДР",
&FI... |
package env
const (
DebugModeEnv = "DEBUG_MODE"
NoahApiNodeEnv = "NOAH_API_NODE"
AdelegApiHostEnv = "ADELEG_API_HOST"
AdelegApiPortEnv = "ADELEG_API_PORT"
NoahGateApi = "NOAH_GATE_API"
)
|
// Package txmatch provides a flexible method of filtering transactions to check for ones matching a particular abi method
package txmatch
|
package encode
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"math"
"strconv"
)
// BinaryReadParctice binary data read
func BinaryReadParctice() {
//参数列表:
// 1)r 可以读出字节流的数据源
// 2)order 特殊字节序,包中提供大端字节序和小端字节序
// 3)data 需要解码成的数据
// 返回值:error 返回错误
// 功能说明:Read从r中读出字节数据并反序列化成结构数据。data必须是固定长的数据值或固定长数据的slic... |
package models
import (
"context"
"database/sql"
"fmt"
"strconv"
"strings"
"github.com/jmoiron/sqlx"
)
// LoadCollectionConfig provides the DatabaseConfig for the collection table.
func LoadCollectionConfig(dialect *SQLDialect) *DatabaseModel {
conf := ModelConfig{
Create: `CREATE TABLE IF NOT EXISTS collec... |
package main
import (
"fmt"
"strings"
)
func collisions(board [][]rune, r, c int) bool {
n := len(board)
qs := 0
// check row
for col := 0; col < n; col++ {
if board[r][col] == 'Q' {
qs++
}
}
if qs > 1 {
return true
}
qs = 0
// check column
for row := 0; row < n; row++ {
if board[row][c] ==... |
package memory
import (
"fmt"
"sort"
)
type AddressSpace interface {
Memory
Map()
AddMapping(offset Ptr, length PtrDist, mode MMapMode, mappedMemory Memory, translator AddressTranslator)
}
type AddressTranslator func(addr Ptr) Ptr
type MMapMode uint
const (
MMAP_MODE_READ = 1 << iota
MMAP_MODE_WRITE
MMAP_M... |
/*
# -*- coding: utf-8 -*-
# @Author : joker
# @Time : 2020-08-20 09:44
# @File : base.go
# @Description :
# @Attention :
*/
package main
import (
"fmt"
"strconv"
"strings"
)
type ListNode struct {
Val int
Next *ListNode
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func preOrderTr... |
package orm
import (
"reflect"
"testing"
)
func TestSqlSequence(t *testing.T) {
type User struct {
Id int `db:"id"`
Name string `db:"name"`
Age int
Phone string `db:"phone"`
}
tag, _ := NewTag(reflect.TypeOf(User{}))
_, got := tag.SqlSequence(nil)
want := "columns can't be nil"
if got != ni... |
package rpcsrv
import (
"gosearch/pkg/crawler"
"gosearch/pkg/engine"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
type RPCsrv struct {
engine *engine.Service
}
type Query struct {
Data string
}
func (r *RPCsrv) Search(query Query, result *[]crawler.Document) error {
res, err := r.engine.Search(query.Data)
i... |
package cmd
import (
"github.com/spf13/cobra"
"github.com/daticahealth/datikube/kubectl"
)
var refresh = func() *cobra.Command {
cmd := &cobra.Command{
Use: "refresh",
Short: "Acquire a new session token and persist it to local kubeconfig",
Long: "Acquire a new session token and persist it to local kubecon... |
// Galang - Golang common utilities
// Copyright (c) 2020-present, gakkiiyomi@gamil.com
//
// gakkiyomi is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
//... |
// +build unit
package nft
import (
"context"
"math/big"
"testing"
"github.com/centrifuge/go-centrifuge/config"
"github.com/centrifuge/go-centrifuge/config/configstore"
"github.com/centrifuge/go-centrifuge/errors"
"github.com/centrifuge/go-centrifuge/protobufs/gen/go/nft"
"github.com/centrifuge/go-centrifuge... |
package main
import (
"flag"
"log"
"path/filepath"
manager "./rules"
)
func main() {
var sourcepath string
var reportpath string
flag.StringVar(&sourcepath, "p", "", "Path donde se encuentran los fuentes a evaluar")
flag.StringVar(&reportpath, "r", "", "Path donde se generara el reporte HTML.... |
package release
// Keep this one empty here to make go test happy that there are non-test files in this folder
// This test suite is meant to be run just before release to validate if the codebase is properly adjusted to the release.
|
package main
import (
//"bufio"
"database/sql"
"crypto/tls"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"net/http"
"github.com/goware/urlx"
//"github.com/aybabtme/rgbterm"
"github.com/mailgun/holster"
_ "github.com/go-sql-driver/mysql"
)
type Mo... |
package secret
import (
"context"
"fmt"
"github.com/teejays/clog"
"github.com/teejays/n-factor-vault/backend/library/id"
"github.com/teejays/n-factor-vault/backend/library/orm"
"github.com/teejays/n-factor-vault/backend/src/vault"
)
var gServiceName = "Secret Service" //LOL
/* * * * * * * * * * * * * * * * ... |
package seeders
import (
"github.com/jinzhu/gorm"
uuid "github.com/satori/go.uuid"
"github.com/tespo/satya/v2/types"
)
var users = types.Users{
{
ID: uuid.FromStringOrNil("ef837bfd-aae4-4495-8aec-5d70f3aa0ed3"),
AccountID: uuid.FromStringOrNil("22b5123d-9cee-4701-b15b-8c9078142666"),
CognitoID: uu... |
package cloud
import (
"flag"
"testing"
)
var (
uid, pass string
)
func init() {
flag.StringVar(&uid, "tpLinkUser", "", "User ID to test TPLink functionality")
flag.StringVar(&pass, "tpLinkPass", "", "Password for the TPLink User")
flag.Parse()
}
func TestGetCloudToken(t *testing.T) {
if uid == "" || pass ==... |
package strings
import (
"testing"
"fmt"
)
func TestLengthOfNonRepeatingSubStr(t *testing.T) {
s := "中国helloworld中国"
num:=lengthOfNonRepeatingSubStr(s)
fmt.Printf("max length is %d ",num)
}
|
package golang
import (
"encoding/json"
"reflect"
"testing"
"github.com/CsYakamoz/leetcode/lib/golang/utils"
)
var tests = []struct {
arr string
output int
}{
{
arr: "[2,3,1,3,1,null,1]",
output: 2,
},
{
arr: "[2,1,1,1,3,null,null,null,null,null,1]",
output: 1,
},
{
arr: "[9]",
out... |
package main
import (
f "fmt"
"runtime"
"sync"
)
func main() {
f.Println("wait group")
runtime.GOMAXPROCS(runtime.NumCPU())
Wait()
f.Println("------------------------")
DeferCall()
}
func Wait() {
wait := new(sync.WaitGroup)
for i := 0; i < 10; i++ {
wait.Add(1)
go func(n int) {
f.Println(n)
... |
package adutils
import (
"testing"
"log"
)
func Test_ContentParse(t *testing.T) {
page,err := ContentParse()
if err != nil {
panic(err)
return
}
log.Println(page)
log.Println(page.Display[0].Name)
log.Println(len(page.Display))
}
func Test_ServerPa... |
// This file was generated for SObject CallCenter, API Version v43.0 at 2018-07-30 03:47:20.731256643 -0400 EDT m=+7.074128523
package sobjects
import (
"fmt"
"strings"
)
type CallCenter struct {
BaseSObject
AdapterUrl string `force:",omitempty"`
CreatedById string `force:",omitempty"`
CreatedDate... |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/rs/cors"
"gopkg.in/mgo.v2"
)
type voteStruct struct {
Vote string
CreatedAt time.Time
}
var votes *mgo.Collection
func responseError(w http.ResponseWriter, message string, code... |
package main
import (
"fmt"
"testing"
"strings"
)
func TestInitial(t *testing.T) {
texts, err := ConvertFile("testData/xen.anab_gk.xml")
if err != nil {
fmt.Println(err.Error())
t.Fail()
}
for _, ss := range texts {
fmt... |
package models
import (
"errors"
"mall/utils"
"strconv"
"github.com/astaxie/beego/orm"
)
// PmsProductAttributeCategory 结构体
type PmsProductAttributeCategory struct {
Id int `json:"id"`
Name string `orm:"size(64)" json:"name"`
AttributeCount int `description:"属性数量" json:"attribute_c... |
package pie
import (
"github.com/elliotchance/testify-stats/assert"
"sort"
"testing"
)
func TestCurrencies_Keys(t *testing.T) {
assert.Equal(t, []string(nil), currencies(nil).Keys())
assert.Equal(t, []string(nil), currencies{}.Keys())
keys := isoCurrencies.Keys()
sort.Strings(keys)
assert.Equal(t, []string{... |
package lib
import (
"errors"
"fmt"
"os"
"time"
)
type uniqueName struct {
now time.Time
}
// generate will create and return unique file names for new messages
func generate() (string, error) {
uni := &uniqueName{now: time.Now()}
hostname, err := uni.right()
if err != nil {
return "", errors.New("Failed t... |
package main
// Relay represents a single switch on controlled module.
type Relay struct {
ID string `json:"id"`
Pin int `json:"pin"`
State bool `json:"state"`
}
// module stores state of relays with their IDs as keys.
var module = make(map[string]*Relay)
|
package main
type Vertex struct {
val int64
edges []int64
}
func New(val int64)*Vertex{
return &Vertex{
val: val,
}
}
type Stack struct {
items []int64
}
func(s *Stack) Top()int64{
return s.items[0]
}
func(s *Stack) Empty()bool{
return len(s.items) == 0
}
func(s *Stack) Push(item int64)*Stack{
s.items... |
package calculator
func fact(n int) int {
if n == 0 {
return 1
}
return n * fact(n-1)
}
func pow(x float64, p int) float64 {
if p == 0 {
return 1
}
return x * pow(x, p-1)
}
func normTrig(x float64) float64 {
for x > Pi {
x -= 2 * Pi
}
for x < -Pi {
x += 2 * Pi
}
return x
}
|
package main
import (
"github.com/urfave/cli"
"log"
"os"
)
const version = "0.0.1"
func main() {
app := cli.NewApp()
app.Usage = "The Genomic Data Commons Command Line Client"
app.Version = version
app.Commands = []cli.Command{
{
Name: "download",
Usage: "download data from the GDC",
Flags: []cli.... |
package main
var templateProject = map[string]string{
"simple": "https://github.com/golamb/golamb-simple-template.git",
"api-gateway": "https://github.com/golamb/golamb-api-gateway-template.git",
"gin": "https://github.com/golamb/golamb-gin-template.git",
"dynamodb": "https://github.com/golamb/gola... |
package roulette
import (
"testing"
"time"
)
func TestExpSpin(t *testing.T) {
t.Skip()
w := NewZWheel()
tm := time.Now()
c := w.Spin(2)
v := <-c
t.Error(time.Since(tm), v.Color, v.Number)
}
func TestSpin(t *testing.T) {
w := NewZWheel()
p := w.spin(12345678)
if p.Number != 15 && p.Color != "black" {
t.... |
package ch8
import (
"fmt"
"os"
"time"
)
// 模拟火箭倒计时
func Down() {
fmt.Println("Commencing countdown. Press return to abort.")
// 读取打断的信号
abort := make(chan struct{})
go func() {
os.Stdin.Read(make([]byte, 1)) // read a single byte
abort <- struct{}{}
}()
// time.Tick()无法关闭,除非整个程序的生命周期都要用
//tick := ti... |
package models
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"os"
"time"
)
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
var sessionHash = os.Getenv("session_hash")
func ClaimsCreate(username string) (string, time.Time, Claims) {
expireToken := time.Now().Add(time.Hour * 8760).Un... |
package db
import (
"fmt"
bolt "go.etcd.io/bbolt"
)
var defaultBucket = []byte("default")
// Database is an open bolt DB
type Database struct {
db *bolt.DB
}
// NewDatabase returns an instance of DB that we can work with
func NewDatabase(dbPath string) (db *Database, closeFunc func() error, err error) {
boltDb... |
package ch01
import (
"testing"
)
func TestEx10(t *testing.T) {
for _, c := range []struct {
in []int
want []int
}{
{in: []int{1}, want: []int{1}},
{in: []int{2, 2, 1}, want: []int{1, 2, 2}},
{in: []int{2, 2, 1}, want: []int{1, 2, 2}},
{in: []int{2, 2, 1, 3}, want: []int{3, 1, 2, 2}},
} {
got := R... |
package main
import (
"fmt"
)
func minimumSwaps(arr []int32) int32 {
var c int32 = 0
for i := 0; i < len(arr); i++ {
for ;arr[i] != int32(i+1); {
arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1]
c++
}
}
return c
}
func main() {
s := []int32{4, 3, 1, 2}
fmt.Println(minimumSwap... |
package db
import (
"log"
"strconv"
)
func (r *GameDetail) InsertToDB() {
db, err := dbConnection()
if err != nil {
log.Fatal(err)
}
defer db.Close()
tmp := r.toDB()
b := db.Table(DetailTempTable).NewRecord(tmp)
if !b {
db.Table(DetailTempTable).Save(tmp)
} else {
db.Table(DetailTempTable).Create(tmp)... |
package schemadance
import (
"context"
"fmt"
"io/fs"
)
type Migrator struct {
Database Db
Patches PatchSets
Partial bool
Status chan Status
}
func (m Migrator) Version(ctx context.Context, set string) (ver int, rerr error) {
tx, err := m.Database.Begin(ctx)
if err != nil {
return 0, err
}
defer func... |
package instapi
import (
"context"
"net/http"
"net/url"
"github.com/instapi/client-go/record"
"github.com/instapi/client-go/schema"
"github.com/instapi/client-go/types"
)
// DetectSheetSchemas attempts to detect the schema for the given Google Sheets sheet.
func (c *Client) DetectSheetSchemas(ctx context.Conte... |
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
const testo = `cominciò èèèèèèèèèèèèèèèèèèèa gridar la fiera bocca,
E ’l duca mio ver lui: «Anima sciocca,
quand’ira o altra passion ti tocca!
Raphél maì amèche zabì almi,
cui non si convenia più dolci salmi.
tienti col corno, e con quel ti d... |
package mem
import (
"encoding/binary"
"fmt"
"io"
"reflect"
"unsafe"
"github.com/lioneagle/goutil/src/buffer"
)
const ARENA_ALLOCATOR_PREFIX_LEN = 8
func RoundToAlign(x, align uint32) uint32 {
return (x + align - 1) & ^(align - 1)
}
/* ArenaAllocator is a memory allocator for text/binary protocol processing... |
package runner
import (
"net/http"
"os"
"time"
"github.com/etf1/kafka-message-scheduler-admin/server/config"
"github.com/etf1/kafka-message-scheduler-admin/server/db"
"github.com/etf1/kafka-message-scheduler-admin/server/resolver/schedulers"
"github.com/etf1/kafka-message-scheduler-admin/server/restapi"
"gith... |
package imdb
import (
"encoding/json"
"fmt"
"strings"
)
func ExampleItem_ID() {
movie := New(403358)
defer movie.Free()
fmt.Printf("id: %d\n", movie.ID())
// Output:
// id: 403358
}
func ExampleItem_Title() {
movie := New(403358) // Nochnoy Dozor (2004)
defer movie.Free()
title, err := movie.Title()
i... |
package main
import "fmt"
import "time"
// Channels to sync execution across go routines.
func worker(done chan bool) {
fmt.Println("working...")
time.Sleep(time.Second)
fmt.Println("done")
done <- true // send notify we are done
}
func main() {
done := make(chan bool, 1) // start worker go routine, giving it... |
package model
import (
"time"
"errors"
)
var (
ErrInvalidApiKey = errors.New("invalid api key")
ErrInvalidUserId = errors.New("invalid user id")
ErrInvalidTimestamp = errors.New("invalid timestamp")
)
type UserEvent struct {
ApiKey string `json:"apiKey,omitempty"`
UserId int64 `json:"userId... |
package cloudforms
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"text/template"
"errors"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/servi... |
package protoutils_test
import (
"bytes"
envoy_config_route_v3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
envoy_extensions_filters_http_buffer_v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/buffer/v3"
"github.com/gogo/protobuf/types"
"github.com/golang/protobuf/jsonp... |
// DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//472. Concatenated Words
//Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of... |
package main
import (
"fmt"
"log"
"os"
)
func main() {
_, err := os.Open("no-file.txt")
if err != nil {
fmt.Println("fmt.Println Err happened", err)
log.Println("log.Println Err happened", err)
fmt.Println("Panicln")
log.Panicln(err)
panic(err)
// fmt.Println("Fatalln")
//log.Fatalln(err)
}
}
|
package main
import (
"log"
)
type MoveFunc func(x, y int, d int, p int) (int, int, int)
func MoveNorth(x, y int, d int, p int) (int, int, int) {
return d, x, y - p
}
func MoveEast(x, y int, d int, p int) (int, int, int) {
return d, x + p, y
}
func MoveSouth(x, y int, d int, p int) (int, int, int) {
return d, ... |
package merchant
import (
"context"
"errors"
"tpay_backend/adminapi/internal/common"
"tpay_backend/model"
"tpay_backend/adminapi/internal/svc"
"tpay_backend/adminapi/internal/types"
"github.com/tal-tech/go-zero/core/logx"
)
type UpdateMerchantIpWhitelistLogic struct {
logx.Logger
ctx context.Context
sv... |
package models
import (
"os/exec"
"path"
"io/ioutil"
"strings"
"strconv"
"errors"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/JacksonGariety/cetch/app/utils"
)
type Entry struct {
gorm.Model
Language string
Code string
ExecTime float64
User... |
package saml
// AttributesMap is a type that provides methods for working with SAML
// attributes.
type AttributesMap map[string][]string
// NewAttributesMap creates an attribute map given a third party assertion.
func NewAttributesMap(assertion *Assertion) *AttributesMap {
props := make(AttributesMap)
if assertion... |
package controller
import (
"github.com/gin-gonic/gin"
"net/http"
"github.com/jinzhu/gorm"
"myzone/model"
"myzone/db"
"myzone/utils"
)
//登陆
func Login(c *gin.Context){
userName := c.DefaultPostForm("userName","")
password := c.DefaultPostForm("password","")
user,_ := CheckUser(userName, password)
if user !=... |
package util
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"runtime"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type httpWriter struct {
Endpoint string
ShowConsole bool
}
func (h *httpWriter) Write(p []byte) (n int, err error) {
if h.ShowConsole {
fmt.Println(p)
}
request, err := ... |
package transport
import (
"github.com/zaynjarvis/fyp/dc/api"
)
type PullModel struct {
}
func (p PullModel) Start() {
panic("implement me")
}
func (p PullModel) Stop() {
panic("implement me")
}
func (p PullModel) SendNotification(event api.CollectionEvent) {
panic("implement me")
}
func (p PullModel) Receiv... |
// 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 reversewords
import "strings"
// https://www.careercup.com/question?id=5697358784364544
func reverseWordsInSentence(sentence string) string {
words := strings.Split(sentence, " ")
for i, word := range words {
words[i] = reverseString(word)
}
return strings.Join(words, " ")
}
func reverseString(s strin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.